Mainline linux что это

Обновлено: 04.07.2024

We want to get as many devices working with one shared kernel package (based on upstream). Making a device boot with the upstream kernel is commonly referred to as mainlining.

Why bother?

Carrying around forks of the kernel is not sustainable as it becomes impossible to provide security patches after a short time. The only way to truly fix this for a device is mainlining it.

Mainlining guide

Kernel packaging

That package is linux-postmarketos-stable . For devices, which are in the kernel's mainline release, but not yet in stable (see kernel releases), we also have linux-postmarketos-mainline . It is even allowed to carry temporary patches around on top of these kernels, as long as work is being done to get them upstreamed properly. The kernel packages based on the official one are in aports/main/linux-postmarketos-* , while the device-specific forks are in aports/device/linux-* .

To make the kernel work with multiple devices, it no longer appends the dtb file to the kernel image. Instead, it puts all dtb files for the current architecture in /usr/share/dtb . The postmarketos-mkinitfs package appends the dtb file defined in the deviceinfo to the linux image in the boot partition.

Device tree source (ARM architecture)

To make your device boot, you will need a device tree source ( dts ) file (which will get compiled to a dtb mentioned above). Check the arch/arm/boot/dts (replace arm with your architecture) folder in the kernel source code for relevant files (browse online) with your device's codename. The general file naming is $chipset_vendor-$chipset-$vendor-$codename.dts .

  • qcom-msm8974-lge-nexus5-hammerhead.dts
  • qcom-msm8974-sony-xperia-honami.dts
  • qcom-apq8064-sony-xperia-yuga.dts
  • qcom-apq8064-asus-nexus7-flo.dts

When you don't have a result, try to find a dts file with the same chipset as your device (e.g. msm8974 ). Try to create a new one for your device based on that by creating a patch for linux-postmarketos-stable . If there is not even a dts file for the same chipset, you need to create one from scratch (no idea how to do that, good luck and please extend the wiki).

Enable the mainline kernel for a new device

Before proceeding, make sure that you know that your device is supported by the mainline kernel. Otherwise use the source code of a vendor's fork of the kernel, which is known to work as described in the porting guide.

  1. run pmbootstrap kconfig edit postmarketos-qcom and adjust the kernel config to add the drivers for the device if they are not enabled yet. Set as many drivers to build as external module as possible so the main vmlinuz filesize doesn't increase too much. Replace qcom with the kernel config you want to modify (see ls aports/main/linux-postmarketos-* ).
  2. Set the kernel dependency to linux-postmarketos in the APKBUILD for the device package if you want to make it the default kernel (more information).
  3. Add the name of the generated dtb file (without path or extension) to the deviceinfo_dtb file in the deviceinfo file.

A good example of a device using a mainline kernel is the device-nokia-n900 package.

Note: This page would need significant cleaning. You may want to refer to Kernel/BuildYourOwnKernel page in Ubuntu wiki instead which is a cleaner and more up-to-date guide to (simple) kernel building

If you have a commercial support contract with Ubuntu/Canonical, this will void such support.

Also note that this page describes how to do things for the Edgy (2.6.17) kernel and newer! Until this kernel source, we did not have any mechanisms in place that would allow people to build their own kernels easily. This was intentional.

Reasons for compiling a custom kernel

  • You are a kernel developer.
  • You need the kernel compiled in a special way, that the official kernel is not compiled in (for example, with some experimental feature enabled).
  • You are attempting to debug a problem in the stock Ubuntu kernel for which you have filed or will file a bug report.
  • You have hardware the stock Ubuntu kernel does not support.
  • You love computers and are curious and interested in hacking on your own GNU/Linux system to learn more about how it works (with the understanding that you'll need to fix anything you break).

Reasons for NOT compiling a custom kernel

  • You merely need to compile a special driver. For this, you only need to install the linux-headers packages.
  • You have no idea what you are doing, and if you break something, you'll need help fixing it. Depending on what you do wrong, you might end up having to reinstall your system from scratch.
  • You got to this page by mistake, and checked it out because it looked interesting, but you don't really want to learn a lot about kernels.

If you want to install a new kernel without compilation, you can use Synaptic, search for linux-image and select the kernel version you want to install.

An easier way is to click on System > Administration > Update Manager, then click on the Check button, and finally click on Apply all updates including the kernel.

Tools you'll need

To start, you will need to install a few packages. Use a following command line to install precisely the packages needed for the release you are using:

Hardy (8.04):

Note: The package makedumpfile is not available in Hardy.

Lucid (10.04):

Raring (13.04):

Get the kernel source

There are a few ways to obtain the Ubuntu kernel source:

Option A) Use git


The git repository does not include necessary control files, so you must build them by:

Option B) Download the source archive

  • Ubuntu modules source may also be needed if you plan to enable PAE and 64 GiB support in the kernel for 32-bit Hardy (8.04). The Ubuntu supplied modules may not be compatible with a PAE enabled kernel.

    The source will be downloaded to a subdirectory inside the current directory.

The source will be downloaded to the current directory as a trio of files (for Lucid, at least) (.orig.tar.gz, .diff.gz, and .dsc) and a sub-directory. For instance, if uname -r returns 2.6.32-25-generic, you'll obtain linux_2.6.32.orig.tar.gz, linux_2.6.32-25.44.diff.gz, linux_2.6.32-25.44.dsc and the sub-directory linux-2.6.32.

Option C) Download the source package

Modify the source for your needs

  • For most people, simply modifying the configs is enough. If you need to install a patch, read the instructions from the patch provider to learn how to apply it.

If you do not find the config files under debian/config, you may find them in your /boot directory (for instance, /boot/config-2.6.22-14-generic) otherwise you should check to see if an alternate location has been specified within debian/debian.env of your kernel source directory.

If you need to change a config option, simply modify the file that contains the option. If you modify just the config file, it will affect all targets for this architecture. If you modify one of the target files, it only affects that target.

After applying a patch, or adjusting the configs, it is always best to regenerate the config files to ensure they are consistent. There is a helper command for this. To regenerate all architectures run:

If you just want to update one architecture, run:

Note: If you don't have the debian/ directory after using apt-get source, use dpkg-source -x *dsc to extract the sources properly.

For these two commands to work, you need to give the scripts in the debian/scripts/misc and debian/scripts directories execute permission with the following command:

Build the Kernel(s)

There are two listed ways to build the Ubuntu kernel:

Build Method A: Build the kernel (when source is from git repository, or from apt-get source)

  • To build the kernel(s) is very simple. Depending on your needs, you may want to build all the kernel targets, or just one specific to your system. However, you also want to make sure that you do not clash with the stock kernels.

Use this command to build all targets for the architecture you are building on:

debian/rules clean creates debian/control, debian/changelog, and so on from debian.<branchname>/* (e.g. debian.master). It is necessary in git trees following git commit 3ebd3729ce35b784056239131408b9a72b0288ef "UBUNTU: [Config] Abstract the debian directory".

The AUTOBUILD environment variable triggers special features in the kernel build. First, it skips normal ABI checks (ABI is the binary compatibility). It can do this because it also creates a unique ABI ID. If you used a git repo, this unique ID is generated from the git HEAD SHA. If not, it is generated from the uuidgen program (which means every time you execute the debian/rules build, the UUID will be different!). Your packages will be named using this ID. (Note that in Intrepid and newer, you will need skipabi=true to skip ABI checks.)

To build a specific target, use this command:

Where FLAVOUR is one of the main flavours of the kernel (e.g. generic)

To build one of the custom flavours (found in debian/binary-custom.d/), use:

As of this documentation, custom flavours include xen and rt.

If you have a more than one processor or more than one core, you can speed things up by running concurrent compile commands. Prepend CONCURRENCY_LEVEL=2 for two processors or two cores; replace '2' with whatever number suits your hardware setup (for Gutsy and later, you can alternatively use DEB_BUILD_OPTIONS=parallel=2).

If you get ABI errors, you can avoid the ABI check with skipabi=true. For example,

To trigger a rebuild, remove the appropriate stamp file from debian/stamps (e.g. stamp-build-server for the server flavour, etc.).

The debs are placed in your the parent directory of the kernel source directory.

If needed, the Ubuntu modules source for Hardy (8.04) can be built in a similar way.

Alternatively, if you need to specify a different kernel than the running one, use

If you get an error, try running this in the kerneldir: (example for the generic flavour)

Alternate Build Method (B): The Old-Fashioned Debian Way

The new Ubuntu build system is great for developers, for people who need the absolute latest bleeding-edge kernel, and people who need to build a diverse set of kernels (several "flavours"). However it can be a little complex for ordinary users. If you don't need the latest development sources, there is a simpler way to compile your kernel from the linux-source package. As suggested above, all you need for this is:

The last command in the sequence brings you into the top directory of a kernel source tree.

Before building the kernel, you must configure it. If you wish to re-use the configuration of your currently-running kernel, start with

Before you run make menuconfig or make xconfig (which is what the next step tells you to do), make sure you have the necessary packages:

If you would like to see what is different between your original kernel config and the new one (and decide whether you want any of the new features), you can run:

Since the 2.6.32 kernel, a new feature allows you to update the configuration to only compile modules that are actually used in your system:

Then, regardless of whether you're re-using an existing configuration or starting from scratch:


What about this. ? (which is from the Kernel/BuildYourOwnKernel Page in the section "Modifying the configuration")


If you re-used the existing configuration, note that Ubuntu kernels build with debugging information on, which makes the resulting kernel modules (*.ko files) much larger than they would otherwise be. To turn this off, go into the config's "Kernel hacking"<!-- ; then, under "Kernel debugging", --> and turn OFF "Compile the kernel with debug info".

Now you can compile the kernel and create the packages:

You can enable parallel make use make -j). Try 1+number of processor cores, e.g. 3 if you have a dual core processor:

On a newer kernel, if you only need binary packages and want several builds (while editing the source) to not cause everything to be rebuilt, use:

The *.deb packages will be created in the parent directory of your Linux source directory (in this example, they would be placed in

/src because our Linux source directory is

Install the new kernel

If you want to see the Ubuntu splash screen (or use text mode) before you get to X instead of just a black screen, you'll want to make sure the framebuffer driver loads:

Now that you've told initramfs-tools which modules it should include, and once the build is complete, you can install the generated debs using dpkg:

Similarly, if you have built the Ubuntu module for Hardy (8.04) earlier, install them as follows:

If you use modules from linux-restricted-modules, you will need to recompile this against your new linux-headers package.

Note: In response to the various comments in the remainder of this section: On Ubuntu Precise (12.04) it appears that postinst DOES take care of the initramfs stuff. After installing the package my new kernel booted just fine without following any of the methods below. Someone please correct me if I'm mistaken.

Since Ubuntu Lucid (10.04) the image postinst no longer runs the initramfs creation commands. Instead, there are example scripts provided that will perform the task. These scripts will work for official kernel images as well. For example:

Note: I couldn't get the above scripts to help in generating an initrd for the kernel - and so the built kernel couldn't boot; the only thing that worked for me was the recommendation in http://www.debian-administration.org/article/How_Do_I_Make_an_initrd_image, "use initramfs command. It is real solution."; what I used (after the custom-built kernel's *.deb's were installed), was:

Note (Michael): that is because you need to include the right package scripts to build the initrd at package install time. The make-kpkg option is --overlay-dir. By default, make-kpkg uses /usr/share/kernel-package as an overlay directory, which contains the default, uncustomised scripts for a Debian distribution, and not the ones needed for building a Ubuntu kernel.

First copy the default overlay directory to your home directory:

Then install the source of the kernel you are using currently, using the exact package name, e.g.

which will unpack the sources to $HOME/linux-2.6.32. Now copy the control scripts into your new overlay:

And now you can execute make-kpkg with the additional command line option --overlay-dir=$HOME/kernel-package.

Rebuilding ''linux-restricted-modules''

The linux-restricted-modules (l-r-m) package contains a number of non-DFSG-free drivers (as well as some firmware and the ipw3945 wireless networking daemon) which, in a perfect world, wouldn't have to be packaged separately, but which unfortunately are not available under a GPL-compatible license. If you use any of the hardware supported by the l-r-m package, you will likely find that your system does not work as well after switching to a custom kernel. In this case you should try to compile the l-r-m package.

See CustomRestrictedModules on how to rebuild l-r-m (if you use nVidia or ATI binary drivers, you do).

Note: you will need around 8 hours of compilation time and around 10 Gb of hard drive space to compile all kernel flavours and restricted modules.

Further note: There are no l-r-m or linux-restricted-modules packages in Lucid.

All Ubuntu Desktop 20.04 LTS will ship with an updated kernel by default. Also Ubuntu Desktop certified hardware may use OEM kernel flavour, where required. Server installations will default to the GA kernel and provide the enablement kernel as optional.

The 20.04 LTS HWE Stacks continue to follow Rolling Update Model, as has been in use since 16.04 LTS.

Desktop

It is advised to keep Ubuntu Desktop 20.04 LTS with the kernel flavour picked during installation. It can be either HWE or OEM flavour. Changing to track GA kernel may result in regressions of performance, hardware support, and certified features.

To check if you are on a certified hardware platform execute:

If any meta packages are listed, please refrain from manually changing the kernel flavours.

To downgrade from HWE/OEM to GA kernel:

sudo apt install --install-recommends linux-generic

If NVIDIA drivers are required check appropriate level and install them:

And then install appropriate NNN version of the drivers:

sudo apt install --install-recommends linux-modules-nvidia-NNN-generic

Reboot, interrupt grub, in advanced options elect to boot 5.4 based kernel, complete boot. Check that everything works as expected.

If everything is good, you may remove the other kernel flavours:

sudo apt remove --purge linux-generic-hwe-20.04 linux-oem-20.04 linux-hwe-* linux-oem-* linux-modules-5.1* linux-modules-5.8.0-* linux-modules-5.6.0-*

Server

Installing the HWE stack is simple:

sudo apt install --install-recommends linux-generic-hwe-20.04

Ubuntu 18.04 LTS - Bionic Beaver

The 18.04.2 and newer point releases will ship with an updated kernel and X stack by default for the desktop. Server installations will default to the GA kernel and provide the enablement kernel as optional.

The 18.04 HWE Stacks continue to follow Rolling Update Model, as has been in use since 16.04 LTS.

Installing the HWE stack is simple:

Desktop

sudo apt-get install --install-recommends linux-generic-hwe-18.04 xserver-xorg-hwe-18.04

Server

sudo apt-get install --install-recommends linux-generic-hwe-18.04

Ubuntu 16.04 LTS - Xenial Xerus

The 16.04.2 and newer point releases will ship with an updated kernel and X stack by default for the desktop. Server installations will default to the GA kernel and provide the enablement kernel as optional.

The 16.04 HWE Stacks will follow a new Rolling Update Model.

It is highly recommended to read the above documentation before executing the following commands, as the HWE model has changed in 16.04.

Installing the HWE stack is simple:

Desktop

sudo apt-get install --install-recommends linux-generic-hwe-16.04 xserver-xorg-hwe-16.04

Server

sudo apt-get install --install-recommends linux-generic-hwe-16.04

Ubuntu 14.04 LTS - Trusty Tahr

The 14.04.2 and newer point releases will ship with an updated kernel and X stack by default. If you have installed with older media you can use the following to install the newer HWE kernel derived from 16.04 (Xenial):

Desktop

sudo apt-get install --install-recommends linux-generic-lts-xenial xserver-xorg-core-lts-xenial xserver-xorg-lts-xenial xserver-xorg-video-all-lts-xenial xserver-xorg-input-all-lts-xenial libwayland-egl1-mesa-lts-xenial

Multiarch Desktop

If you run a multiarch desktop (for example, i386 and amd64 on amd64, for gaming or Wine), you may find you need a slightly more involved command, like this:

sudo apt-get install --install-recommends linux-generic-lts-xenial xserver-xorg-core-lts-xenial xserver-xorg-lts-xenial xserver-xorg-video-all-lts-xenial xserver-xorg-input-all-lts-xenial libwayland-egl1-mesa-lts-xenial libgl1-mesa-glx-lts-xenial libgl1-mesa-glx-lts-xenial:i386 libglapi-mesa-lts-xenial:i386

Server

Install the HWE kernel derived from 16.04 (xenial):

sudo apt-get install --install-recommends linux-generic-lts-xenial

Ubuntu 12.04 LTS - Precise Pangolin

The 12.04.2 and newer point releases will ship with an updated kernel and X stack by default. The current and supported hardware enablement stack is comprised of the newer kernel and X stacks from 14.04 (Trusty).

Anyone wishing to opt into the hardware enablement stack for Precise may do so running the following commands:

Desktop

sudo apt-get install --install-recommends linux-generic-lts-trusty xserver-xorg-lts-trusty libgl1-mesa-glx-lts-trusty

Server

sudo apt-get install --install-recommends linux-generic-lts-trusty

Check your support status

Ubuntu 12.04 LTS Extended Security Maintenance

Following the end-of-life of Ubuntu 12.04 LTS, Canonical is offering Ubuntu 12.04 ESM (Extended Security Maintenance), which provides important security fixes for the kernel and the most essential user space packages in Ubuntu 12.04. All Ubuntu 12.04 LTS users are encouraged to upgrade to Ubuntu 14.04 LTS or Ubuntu 16.04 LTS. But for those who cannot upgrade immediately, Ubuntu 12.04 ESM updates will help ensure the on-going security and integrity of Ubuntu 12.04 systems.

Ubuntu 12.04 LTS initially released with kernel based on version 3.2. The final hardware enablement kernel, when Ubuntu 12.04 LTS reached end of life, was based on kernel version 3.13. Both kernels are included as part of Ubuntu 12.04 ESM.

The following is a generic view of the Ubuntu release schedule, the kernels delivered, and the support time frames. 14.04, 16.04, and 18.04 will each deliver point release updates respectively (ie. 14.04.x, 16.04.x, 18.04.x) and eventually introduce newer hardware enablement kernels. Please refer to the 14.04.x, 16.04.x, and 18.04.x Ubuntu Kernel Support diagrams in the corresponding sections below for more details.

This is a distilled view of our 14.04.x Ubuntu Kernel Support Schedule.

This is a distilled view of our 16.04.x Ubuntu Kernel Support Schedule.

This is a distilled view of our 18.04.x Ubuntu Kernel Support Schedule.

This is a combined view of the diagrams from above (ie the Ubuntu Kernel Release Schedule combined with the Distilled 14.04.x, 16.04.x, and 18.04.x Ubuntu Kernel Support diagrams)

A more detailed view of our LTS Kernel Support Schedule. This includes views for 12.04.x, 14.04.x, 16.04.x as well as upstream stable commitments.

Kernel/LTSEnablementStack (последним исправлял пользователь nmavrogiannopoulos 2021-11-11 14:23:22)

The material on this wiki is available under a free license, see Copyright / License for details.

Последние версии ядра Linux имеют драйверы для новых устройств и другие нововведения. К сожалению, многие популярные дистрибутивы Linux не спешат обновить ядро. Данная инструкция покажет, как легко, без компиляции, установить любую версию ядра Linux в Ubuntu и Linux Mint. Вы можете выбрать для установки как более новое ядро, так и более старое, чем предлагает репозиторий вашего дистрибутива.

При желании, вы без проблем можете удалить установленные ядра Linux и вернуться к ядру из репозитория.

Поскольку Linux Mint основана на Ubuntu, то данная инструкция в полной мере применима и к дистрибутивам Linux Mint, кроме LMDE. Для LMDE (Linux Mint Debian Edition) смотрите статью «Как установить последние версии ядра Linux в Debian и основанные на Debian дистрибутивы».

Предупреждение перед обновлением ядра

Необходимо помнить, что из-за несовместимости ядра с программами (в первую очередь, с проприетарными видео драйверами), вы можете столкнуться с проблемами, в том числе с чёрным экраном во время загрузки.

В большинстве случаев, возникшие проблемы можно решить без переустановки дистрибутива. Начните с того, что в меню загрузки перейдите в дополнительные параметры и загрузитесь с предыдущей версией ядра. Выполнив загрузку, удалите проблемное ядро.

Проблемы могут вызвать проприетарные драйверы для видеокарт, поскольку старые версии могут быть не совместимы с последними версиями ядра без патча. Если у вас установлены проприетарные видео драйверы, то серьёзной подумайте, прежде чем следовать инструкциям ниже. Также подготовьтесь, поищите инструкции, как решить проблему при загрузки дистрибутива в чёрный экран.

Следует быть особенно осторожным владельцам старых дистрибутивов — настоятельно рекомендуется обновлять ядро только на последних версиях ОС.

Ещё одна вполне вероятная проблема, с которой вы можете столкнуться если установите ядро самой последней версии — проблема с неразрешёнными зависимостями и как следствие невозможность использования менеджера пакетов apt для обновления и установки программ. Если вы столкнулись с ситуацией, когда после успешной установки нового ядра не получается обновить пакеты с помощью apt, то попробуйте устанавливать более ранние версии ядра, которые вам подходят, а версии, вызывающие проблемы с зависимостями, удаляйте. Помните, что невозможно удалить ядро с которым вы загрузились — перед удалением загрузите компьютер с любой другой версией ядра.

mainline — репозиторий ядер Ubuntu

Для Ubuntu имеется репозиторий скомпилированных ядер mainline всех версий, в том числе самых последних, поэтому установка не вызывает особых сложностей — компилировать ядро Linux не нужно. Более того, имеются инструменты, в том числе с графическим интерфейсом для установки любых ядер.

На самом деле, если ядра уже скомпилированы, то достаточно скачать из одной папки с сервера файлы следующего вида:

  • linux-headers-*-generic_*_amd64.deb
  • linux-headers-*_all.deb
  • linux-image-unsigned-*-generic_*_amd64.deb
  • linux-modules-*-generic_*_amd64.deb

И установить их командой:

Но процесс можно упростить ещё больше, используя утилиты для работы с ядрами.

mainline (продолжение бесплатной версии ukuu) — программа с графическим и консольным интерфейсом для обновления ядра

Если вы предпочитаете графический интерфейс, то используйте Mainline.

Чтобы установить программу выполните следующие команды:

Для запуска графического интерфейса выполните:

Для запуска консольной версии выполните:

Использование графической версии не должно вызвать затруднений. При запуске будет получена информация о доступных ядрах, вы можете выбрать любое ядро и установить его, просто нажав на кнопку «Установка». Дополнительно доступны такие действия как удаление ядер и просмотр списков изменений для каждой версии ядра.


Использование консольной версии следующее:

Справка по опциям и командам:

(1) Строка версии должна браться из вывода --list

(2) Одна или более строк версий (разделённые запятыми) берутся из вывода --list

Перезагрузите компьютер, чтобы использовать новое ядро.

По умолчанию ваша система будет загружена с последним ядром, если вы хотите это изменить, то перейдите в дополнительные параметры загрузки


и выберите желаемую версию из установленных ядер.


Утилита ubuntu-mainline-kernel.sh

Последнюю версию ядра на Ubuntu и Linux Mint также можно установить с помощью утилиты командной строки ubuntu-mainline-kernel.sh.

Загружаем и устанавливаем скрипт ubuntu-mainline-kernel.sh:

Справка по ubuntu-mainline-kernel.sh

Пример установки последней версии ядра

Проверяем текущую версию ядра:


Ядро имеет версию 5.11.

Проверяем, какая версия ядра является последней:


Чтобы вывести список доступных для установки версий ядер выполните команду:

Например, мы хотим установить ядро версии v5.12.11, тогда команда следующая (префикс «v» указывать не надо):

Если вы хотите установить последнюю на данный момент версию, то запустите следующую команду:


Вам будет задан вопрос, хотите ли вы продолжить, введите «y»:

Программа завершила работу — чтобы изменения вступили в силу, требуется перезагрузка.


Опять проверяем версию ядра:


Как восстановить Linux после установки ядра

Если ваш компьютер загружается с чёрным экраном, зависает или что-то не работает после обновления ядра, перезагрузитесь и выберите Дополнительные параметры для вашего дистрибутива в меню GRUB:


Затем выберите предыдущую версию ядра и нажмите Enter:


Независимо от причины, вам необходимо загрузиться с предыдущей версией ядра, если вы хотите удалить последнее ядро. Это потому, что вы не можете удалить ядро, которое в настоящее время используется.

Если вы не видите меню GRUB2, нажмите и удерживайте клавишу Shift или несколько раз нажмите клавишу Esc (это может варьироваться в зависимости от загрузки BIOS или UEFI и от используемой вами версии Ubuntu/Linux Mint) при загрузке GRUB. Должно появиться меню Grub, позволяющее выбрать предыдущую версию ядра.

Читайте также: