архитектура процесса разработки и каталог патч-проектовthe architecture of the development process and a catalog of patch projects

kernel.org: как патч становится частью ядраkernel.org: how a patch becomes part of the kernel

kernel.org — не просто сайт со ссылками на архивы, а витрина целого процесса: как код проходит путь от подсистемного дерева через интеграционное тестирование до релиза, кто отвечает за каждую ветку, и какие именные проекты (реального времени, безопасности) годами живут поверх мейнлайна, прежде чем влиться в него — или не влиться никогда.kernel.org isn't just a site with download links — it's the storefront of an entire process: how code travels from a subsystem tree through integration testing to release, who's responsible for each branch, and which named projects (real-time, security) live on top of mainline for years before merging in — or never merging at all.

Что этоWhat it is

kernel.org — не одно дерево исходников, а семейство деревьев с разными ролями в жизненном цикле кода. Новая фича сначала попадает в подсистемное дерево конкретного мейнтейнера, оттуда — в интеграционное дерево linux-next для раннего тестирования, затем в mainline (дерево Торвальдса) во время двухнедельного merge window, а после релиза уходит в отдельные ветки stable и longterm, где живёт годами, получая только исправления. Параллельно существуют именные проекты (PREEMPT_RT, KSPP) — код, который годами дорабатывается вне основной последовательности веток и вливается в мейнлайн частями или целиком, когда готов.kernel.org isn't one source tree — it's a family of trees with different roles in the code's lifecycle. A new feature first lands in a specific maintainer's subsystem tree, then moves to the linux-next integration tree for early testing, then to mainline (Torvalds's tree) during a two-week merge window, and after release it lives on in separate stable and longterm branches for years, receiving only fixes. Alongside this, named projects (PREEMPT_RT, KSPP) exist — code developed for years outside the main branch sequence, merging into mainline in pieces or all at once once it's ready.

История: как это былоHistory: how it happened

01

Начало: сайт как побочный продукт переезда ТорвальдсаThe beginning: a site born as a side effect of Torvalds's move

Инфраструктура, ставшая kernel.org, возникла, когда Торвальдс переехал в Калифорнию и начал работать в Transmeta — понадобилось место для публикации исходников ядра, доступное сообществу разработчиков по всему миру. Долгое время это была чисто волонтёрская история без выделенного персонала: в 2002 году сайт оформился как отдельная некоммерческая организация, но полноценного штатного администратора не было вплоть до 2008 года, когда Linux Foundation наняла на эту роль Джона Хоули.The infrastructure that became kernel.org emerged when Torvalds moved to California and started working at Transmeta — a place was needed to publish kernel sources, accessible to developers worldwide. For a long time it was a purely volunteer effort with no dedicated staff: in 2002 the site was spun off as a standalone nonprofit, but there was no full-time administrator until 2008, when the Linux Foundation hired John Hawley for the role.

02

Август 2011: взлом, обнаруженный спустя 17 днейAugust 2011: a breach discovered 17 days late

28 августа 2011 разработчик ядра Х. Питер Анвин (H. Peter Anvin) обнаружил троян на своей личной машине — и, копнув глубже, выяснил, что серверы kernel.org (известные под именами Hera и Odin1) тоже скомпрометированы. Заражение произошло не позднее 12 августа, то есть обнаружение отставало на 17 дней. Атака оказалась частью более широкой сети кражи учётных данных, действовавшей годами. Сайт был полностью офлайн больше месяца — с конца августа до начала октября 2011 — пока затронутые серверы перестраивали с нуля. Подозреваемый в атаке был арестован лишь спустя пять лет после инцидента. Прямое следствие взлома — то, что инфраструктура kernel.org и процесс подписи коммитов стали заметно строже: разработчики верхнего уровня подписывают теги релизов собственными GPG-ключами, а не полагаются только на защиту периметра сервера.On August 28, 2011, kernel developer H. Peter Anvin found a trojan on his personal machine — and, digging deeper, discovered kernel.org's servers (known as Hera and Odin1) were compromised too. The infection had happened no later than August 12, so detection lagged by 17 days. The attack turned out to be part of a wider credential-theft network that had been operating for years. The site was fully offline for over a month — from late August to early October 2011 — while the affected servers were rebuilt from scratch. A suspect in the attack was only arrested five years after the incident. A direct consequence of the breach: kernel.org's infrastructure and commit-signing practices became noticeably stricter — top-level developers sign release tags with their own GPG keys rather than relying solely on server perimeter defense.

03

2008: staging tree как ответ на проблему «драйверу негде дозревать»2008: the staging tree as an answer to "there's nowhere for a driver to mature"

10 июня 2008 Грег Кроа-Хартман анонсировал дерево linux-staging — вырос он из Linux Driver Project и жалоб на то, что отдельным драйверам буквально негде было находиться, пока они дозревали до качества, приемлемого для мейнлайна. Идея: собрать такой код в одном месте — это повышает его видимость сообществу, привлекая больше разработчиков к доработке, тестированию и рецензированию. Уже в октябре 2008 дерево staging влилось непосредственно в мейнлайн. С тех пор Кроа-Хартман (тот же человек, что сопровождает и stable-ветки) продолжает поддерживать эту область кодовой базы.On June 10, 2008, Greg Kroah-Hartman announced the linux-staging tree — it grew out of the Linux Driver Project and complaints that individual drivers had literally nowhere to sit while they matured to mainline-acceptable quality. The idea: collecting such code in one place raises its visibility to the community, drawing in more developers to help fix, test, and review it. By October 2008 the staging tree had merged directly into mainline. Since then, Kroah-Hartman (the same person who maintains the stable branches) has continued maintaining this part of the codebase.

04

Ноябрь 2015: KSPP — не изобретать защиту заново, а протащить существующую в апстримNovember 2015: KSPP — not reinventing protections, but getting existing ones upstream

Кис Кук (Kees Cook, тогда сотрудник Google) анонсировал Kernel Self Protection Project в ноябре 2015 при поддержке Core Infrastructure Initiative Linux Foundation. Отправная точка проекта была не «придумать новую защиту», а признать, что значительная часть нужных технологий (защита от переполнения буфера/целых чисел, утечек указателей ядра, ROP-атак) годами существовала вне мейнлайна — в первую очередь в проектах grsecurity и PaX — но по совокупности социальных, культурных и технических причин не попадала в апстрим. Цель KSPP была не конкурировать с grsecurity, а систематически протаскивать уже проверенные идеи защиты в основное дерево ядра, делая защищённым сам код ядра, а не только пространство пользователя, которое ядро охраняет.Kees Cook (then at Google) announced the Kernel Self Protection Project in November 2015, backed by the Linux Foundation's Core Infrastructure Initiative. The project's starting point wasn't "invent new protections" but acknowledging that much of the needed technology (buffer/integer overflow protection, kernel pointer leak prevention, ROP-attack mitigation) had existed outside mainline for years — chiefly in the grsecurity and PaX projects — but for a mix of social, cultural, and technical reasons hadn't made it upstream. KSPP's goal wasn't to compete with grsecurity but to systematically get already-proven protection ideas into the main kernel tree, hardening the kernel's own code, not just the userspace the kernel guards.

Как это устроено сегодняHow it's organized today

дерево / проектtree / projectрольroleкто сопровождаетmaintained by
mainlineдерево Торвальдса — куда сливается всё новое во время merge window; жизненный цикл релиза: 2-недельное окно слияния → еженедельные rc1–rc7/8 (стабилизационные тэги, только багфиксы) → финальный релизTorvalds's tree — where everything new merges during the merge window; a release's lifecycle: a 2-week merge window → weekly rc1–rc7/8 stabilization tags (bugfixes only) → the final releaseЛинус ТорвальдсLinus Torvalds
stableфорк каждого мейнлайн-релиза — багфиксы и security-патчи, уже принятые в mainline, бэкпортируются сюда еженедельно; живёт до выхода следующей версииa fork of every mainline release — bugfixes and security patches already accepted into mainline are backported here weekly; lives until the next version shipsGreg Kroah-Hartman, Sasha Levin
longterm (LTS)одна версия в год выбирается для поддержки на годы вперёд (обычно от двух до шести лет) — то, что реально используют дистрибутивы, Android-устройства и embedded-проекты вместо гонки за mainlineone version per year is chosen for years of support (typically two to six years) — what distros, Android devices, and embedded projects actually rely on instead of chasing mainlineGreg Kroah-Hartman, Sasha Levin
linux-nextинтеграционное дерево — снимок того, как предположительно будет выглядеть mainline после закрытия следующего merge window; десятки подсистемных деревьев сливаются сюда ежедневно для раннего обнаружения конфликтов и поломок сборкиthe integration tree — a snapshot of what mainline is expected to look like after the next merge window closes; dozens of subsystem trees merge here daily for early conflict and build-breakage detectionStephen Rothwell
staging treeдрайверы и код, ещё не готовые к мейнлайн-качеству, но уже в дереве ради видимости сообществу; для каждого — своя папка в drivers/staging/ и файл TODO с перечнем недоделок и списком людей для CC на патчиdrivers and code not yet at mainline quality, but already in the tree for community visibility; each gets its own drivers/staging/ subdirectory and a TODO file listing what's left to do and who to CC on patchesGreg Kroah-Hartman
PREEMPT_RTпатчсет реального времени, разрабатывавшийся отдельно от мейнлайна с 2004–2005 годов — двадцать лет параллельного существования закончились полным мержем в 6.12 (ноябрь 2024)the real-time patchset, developed separately from mainline since 2004–2005 — twenty years of parallel existence ended with a full merge in 6.12 (November 2024)исторически Thomas Gleixner, Ingo Molnar и др.; с 2015 — Real-Time Linux Collaborative Projecthistorically Thomas Gleixner, Ingo Molnar, and others; from 2015 the Real-Time Linux Collaborative Project
KSPPпроект по системному ужесточению ядра против эксплуатации уязвимостей — не разработка новой защиты с нуля, а протаскивание уже существующих (в grsecurity/PaX) идей в апстримa project for systematically hardening the kernel against exploitation — not building new protections from scratch, but getting ideas that already existed (in grsecurity/PaX) upstreamKees Cook

Порядок движения кода: подсистемный мейнтейнер собирает патчи в своё дерево → дерево появляется в linux-next для интеграционного тестирования (сборка, конфликты между разными подсистемами, иногда — загрузка и прогон) → во время двухнедельного merge window Торвальдс стягивает подготовленные деревья в mainline → следующие 7–8 недель — только стабилизация через еженедельные rc-тэги → финальный релиз → релиз тут же форкается в отдельную stable-ветку, получающую бэкпорченные фиксы, пока не выйдет следующая версия. Раз в год одна из версий получает статус longterm и живёт годами. Именные проекты вроде PREEMPT_RT и KSPP существуют вне этой последовательности: они либо вливаются кусками через обычные merge windows, либо годами копятся отдельно, прежде чем мейнтейнеры сочтут код готовым для разового полного слияния.The code's path: a subsystem maintainer collects patches into their own tree → the tree shows up in linux-next for integration testing (build, cross-subsystem conflicts, sometimes boot/run testing) → during the two-week merge window, Torvalds pulls the prepared trees into mainline → the following 7–8 weeks are stabilization-only via weekly rc tags → the final release ships → the release is immediately forked into its own stable branch, receiving backported fixes until the next version ships. Once a year, one version gets longterm status and lives for years. Named projects like PREEMPT_RT and KSPP exist outside this sequence: they either merge in pieces through regular merge windows, or accumulate separately for years before maintainers consider the code ready for a single full merge.

Грабли и мифыGotchas & myths

«linux-next — это просто бета-версия следующего релиза» — нет, это инструмент для мейнтейнеров, не для пользователей"linux-next is just a beta of the next release" — no, it's a maintainer tool, not a user product

linux-next пересобирается заново каждый день из десятков подсистемных деревьев и по определению может не собираться или не загружаться — это рабочий снимок для раннего обнаружения конфликтов между подсистемами, а не кандидат на установку для обычных пользователей. Стабильность появляется только после того, как код пройдёт через linux-next и осядет в mainline.linux-next is rebuilt fresh every day from dozens of subsystem trees and, by definition, may fail to build or boot — it's a working snapshot for catching cross-subsystem conflicts early, not an installation candidate for ordinary users. Stability only appears once code has passed through linux-next and settled into mainline.

KSPP не «конкурент» grsecurity — общая цель, разный путь до апстримаKSPP isn't a grsecurity "rival" — the same goal, a different road to upstream

Формулировки вроде «KSPP против grsecurity» упрощают ситуацию до конфликта, хотя суть в другом: grsecurity/PaX годами были источником рабочих идей защиты ядра, но существовали как набор патчей поверх исходников, а не как часть официального дерева. KSPP не изобретал альтернативу, а систематически переносил уже проверенные подходы в мейнлайн, чтобы ими могли пользоваться все дистрибутивы без необходимости накладывать сторонний патчсет.Phrasing like "KSPP vs. grsecurity" oversimplifies things into a conflict, when the real story is different: grsecurity/PaX had for years been a source of working kernel-hardening ideas, but existed as a set of patches on top of the source tree, not as part of the official tree. KSPP didn't invent an alternative — it systematically moved already-proven approaches into mainline so every distro could use them without applying a third-party patchset.

stable и longterm — не «более надёжная версия», а разная длина обязательствstable and longterm aren't "a more reliable version" — they're different lengths of commitment

Обе ветки получают одни и те же типы патчей — багфиксы и security-исправления, уже принятые в mainline — разница исключительно в том, сколько времени конкретная версия будет их получать: обычная stable-ветка живёт до следующего релиза (пара месяцев), longterm — годами. Выбор longterm-версии для продакшена не означает, что она технически «стабильнее» соседних — просто её дольше поддерживают.Both branches receive the same kinds of patches — bugfixes and security fixes already accepted into mainline — the only difference is how long a given version keeps getting them: a regular stable branch lives until the next release (a couple of months), longterm lives for years. Choosing a longterm version for production doesn't mean it's technically "more stable" than its neighbors — it just gets supported longer.

ТерминыTerms

merge windowmerge window
двухнедельный период в начале каждого релизного цикла, когда Торвальдс принимает крупные новые функции из подсистемных деревьев в mainline. После его закрытия (тег rc1) новые фичи больше не принимаются до следующего цикла — остаются только исправления.the two-week period at the start of every release cycle when Torvalds pulls major new features from subsystem trees into mainline. Once it closes (the rc1 tag), no new features are accepted until the next cycle — only fixes are.
rc (release candidate)
еженедельный тэг-стабилизации после закрытия merge window (rc1, rc2 … обычно до rc7 или rc8) — в это время в дерево принимаются только багфиксы, устранение регрессий и правки документации, никаких новых функций. Финальный релиз выходит, когда поток входящих исправлений замедляется до приемлемого уровня.a weekly stabilization tag after the merge window closes (rc1, rc2 … usually up to rc7 or rc8) — during this time only bugfixes, regression fixes, and documentation edits are accepted into the tree, no new features. The final release ships once the flow of incoming fixes slows to an acceptable level.
подсистемное деревоsubsystem tree
отдельный git-репозиторий, которым управляет мейнтейнер конкретной части ядра (например, сетевого стека или файловой системы) — сюда стекаются патчи именно этой подсистемы, прежде чем попасть дальше по цепочке в linux-next и mainline.a separate git repository managed by the maintainer of one specific kernel area (say, the network stack or a filesystem) — patches for that subsystem accumulate here before moving further down the chain into linux-next and mainline.
интеграционное тестированиеintegration testing
проверка того, что десятки независимо разрабатываемых подсистемных деревьев вообще собираются и работают вместе, а не только каждое по отдельности — именно эту роль выполняет linux-next, ежедневно объединяя все деревья и выявляя конфликты между ними до того, как код попадёт в mainline.checking that dozens of independently developed subsystem trees actually build and work together, not just each on its own — this is exactly what linux-next does, merging all the trees daily and surfacing conflicts between them before the code reaches mainline.
GPG-подписьsigning
криптографическая подпись релизных тэгов и коммитов личным ключом разработчика, подтверждающая, что код действительно пришёл от заявленного автора и не был подменён по пути — практика, заметно ужесточённая после взлома kernel.org в 2011 году.a cryptographic signature on release tags and commits using a developer's personal key, confirming the code genuinely came from the claimed author and wasn't tampered with along the way — a practice noticeably tightened after kernel.org's 2011 breach.
ROP (return-oriented programming)
техника эксплуатации уязвимостей, при которой атакующий не внедряет собственный исполняемый код, а собирает вредоносное поведение из уже существующих в программе маленьких фрагментов кода (обычно заканчивающихся инструкцией return), связывая их в цепочку через манипуляцию стеком вызовов — одна из угроз, против которых KSPP системно ужесточает ядро.an exploitation technique where the attacker doesn't inject their own executable code, but assembles malicious behavior out of small code fragments already present in the program (usually ending in a return instruction), chaining them together by manipulating the call stack — one of the threats KSPP systematically hardens the kernel against.