Ubuntu compile linux kernel

HOW-TO: Сборка ядра Linux

Содержание

В данном пошаговом руководстве вы узнаете, как правильно собрать и установить ядро ветвей >2.6 в семействе ОС Ubuntu.

Шаг 1. Получение исходного кода ядра

Исходники ядра Ubuntu можно получить двумя способами:

150 Мб в текущую папку. Чтобы получить исходники ядра, версия которого установлена на компьютере выполните команду:

Или вместо `uname -r` можно указать конкретную версию из имеющихся в репозитории.

Не забудьте включить общий доступ к исходникам в репозитории ( Параметры системы → Программы и обновления → Программное обеспечение Ubuntu → Исходный код ). Из консоли это сделать можно раскомментировав строки начинающиеся с deb-src в файле /etc/apt/sources.list, а затем выполнить обновление командой: «sudo apt-get update».

Где — имя релиза, например:

Другие ядра

Также существуют ядра, работоспособность которых в Ubuntu не гарантируется. Например, известна проблема с рядом популярных системных приложений (в частности драйвера NVidia, VirtualBox), которые при своей установке компилируются под установленное ядро. Поэтому для их установки на ядро, нестандартное для данной версии Ubuntu (например, Ubuntu 16.04 идёт с ядром 4.4.0), может потребоваться их отдельная компиляция вручную или специальные патчи, а последние версии ядер с kernel.org приложение может вообще не поддерживать.

Распакуйте полученный архив, используя команды:

Или в случае с linux-source:

Шаг 2. Получение необходимых для сборки пакетов

Выполните следующие команды для установки основных пакетов:

Далее всё зависит от того, каким способом вы хотите произвести конфигурацию ядра. Это можно сделать несколькими способами.

В случае, если вы хотите использовать config, oldconfig, defconfig, localmodconfig или localyesconfig, вам больше не нужны никакие дополнительные пакеты. В случае же с оставшимися тремя вариантами необходимо установить также дополнительные пакеты.

Для установки пакетов, необходимых для использования menuconfig выполните следующую команду:

Для установки пакетов, необходимых для использования gconfig выполните следующую команду:

Для установки пакетов, необходимых для использования xconfig выполните следующую команду:

Шаг 3. Применение патчей

Официальные патчи уже наложены на исходники, если ядро получалось описанной выше командой:

Если вы никогда до этого не применяли патчей к исходному коду, то выполните следующую команду:

Эта команда установит программу patch, необходимую для, как можно догадаться, применения патчей. Теперь скачайте файл патча в папку, куда вы распаковали ядро. Это может быть либо архивный файл (напр. Bzip2 или Gzip), либо несжатый patch-файл.

На данный момент подразумевается, что вы уже сохранили файл в ту папку, куда ранее распаковали ядро, и установили программу patch.
Если скачанный вами файл был в формате Gzip (*.gz), тогда выполните следующую команду для распаковки содержимого архива:

Если скачанный вами файл был в формате Bzip2 (*.bz2), тогда выполните следующую команду для распаковки содержимого архива:

где 2.6.x.y — версия патча ядра. Соответствующие команды распакуют файл патча в папку с исходным кодом ядра. Прежде чем применить патч, необходимо удостовериться, что он заработает без ошибкок. Для этого выполните команду:

где 2.6.x.y — версия патча ядра. Эта команда сымитирует применение патча, не изменяя сами файлы.

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

где 2.6.x.y — версия патча ядра. Если не было никаких ошибок, значит к исходному коду был успешно применён патч.

где 2.6.x.y — версия патча и ваших исходников

Шаг 4. Конфигурация будущей сборки ядра

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

где 2.6.x.y — версия загруженного вами ядра.

На данный момент вы уже должны были определиться с методом конфигурации ядра (если нет, то ознакомьтесь с ними в разделе «Получение необходимых для сборки пакетов». В зависимости от этого, выполните следующую команду для запуска выбранного вами способа конфигурации:

После вызова соответствующая программа конфигурации будет запущена. Произведите необходимые настройки в соответствии с вашими потребностями, сохраните файл конфигурации и переходите к следующему шагу.

Шаг 5. Сборка ядра

Итак, приготовления завершены. Теперь можно запустить процесс сборки ядра. Чтобы это сделать, выполните команду:

Шаг 6. Установка образов и заголовков ядра

Когда сборка ядра подошла к концу, в вашей домашней папке появятся два deb-пакета. Их и необходимо установить. Для этого выполните команды:

где 2.6.x.y — версия собранного ядра, arc — архитектура процессора (i386 — 32-бит, amd64 — 64-бит).
Если вы не знаете точного названия пакета, выведите список файлов в домашнем каталоге командой

и найдите эти самые два пакета.

Шаг 7. Генерация начального RAM-диска

Для корректной работы Ubuntu требует наличия образа начального RAM-диска. Чтобы его создать, выполните команду:

где 2.6.x.y — версия собранного ядра.

Шаг 8. Обновление конфигурации загрузчика GRUB

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

Файл menu.lst (для GRUB версии 1) или grub.cfg (для GRUB версии 2) обновится в соответствии с наличием установленных операционных систем и образов ядер.

Шаг 9. Проверка ядра

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

Она выведет на экран используемую версию ядра.

Если всё сделано правильно, то вы можете удалить архивы с исходным кодом и весь каталог linux-2.6.x.y в вашей домашней папке. Это освободит около 5 ГБ на вашем жёстком диске (размер освобождаемого пространства зависит от параметров сборки).

На этом процесс сборки и установки завершён, поздравляю!

Источник

Ubuntu Wiki

BuildYourOwnKernel

This page describes how to build the kernel.

The majority of users that are interested in building their own kernel are doing so because they have installed Ubuntu on their system and they wish to make a small change to the kernel for that system. In many cases the user just wants to make a kernel configuration change.

Читайте также:  Windows 10 как установить принтер по умолчанию

The purpose of this page is to give that user a minimum amount of information for them to meet the goal of making a simple change to the kernel, building it and installing their kernel. It is not intended to be the definitive guide to doing Ubuntu kernel development.

Build Environment

If you have not built a kernel on your system before, there are some packages needed before you can successfully build. You can get these installed with:

Unfortunately, the above does not install all of the necessary dependencies. The current Disco Dingo release requires the following additional packages.

If you are going to be using git, install it via:

The above command requires your system to have the correct deb-src lines in /etc/apt/sources.list. For example, on Disco Dingo you should have:

Obtaining the source for an Ubuntu release

There are a number of different ways of getting the kernel sources. The two main ways will be documented here.

If you have installed a version of Ubuntu and you want to make changes to the kernel that is installed on your system, use the apt-get method (described below) to obtain the sources.

However, if you wish to get the most up to date sources for the Ubuntu release you are running and make changes to that, use the git method (described below) to obtain the sources.

apt-get

The source code which generated a specific binary package may be obtained using the apt-get source

command. For example to obtain the source for the currently running kernel you can use the command:

All of the Ubuntu Kernel source is maintained under git. The source for each release is maintained in its own git repository on kernel.ubuntu.com. To obtain a local copy you can simply git clone the repository for the release you are interested in as shown below.

For example to obtain the Disco Dingo tree:

Modifying the configuration

This step can be skipped if no configuration changes are wanted. The build process will use a configuration that is put together from various sub-config files. The simplest way to modify anything here is to run:

This takes the current configuration for each architecture/flavour supported and calls menuconfig to edit its config file. The chmod is needed because the way the source package is created, it loses the executable bits on the scripts.

In order to make your kernel "newer" than the stock Ubuntu kernel from which you are based you should add a local version modifier. Add something like "+test1" to the end of the first version number in the debian.master/changelog file, before building. This will help identify your kernel when running as it also appears in uname -a. Note that when a new Ubuntu kernel is released that will be newer than your kernel (which needs regenerating), so care is needed when upgrading. NOTE: do not attempt to use CONFIG_LOCALVERSION as this _will_ break the build.

Building the kernel

Building the kernel is quite easy. Change your working directory to the root of the kernel source tree and then type the following commands:

If the build is successful, a set of three .deb binary package files will be produced in the directory above the build root directory. For example after building a kernel with version "4.8.0-17.19" on an amd64 system, these three (or four) .deb packages would be produced:

on later releases you will also find a linux-extra- package which you should also install if present.

Testing the new kernel

Install the three-package set (on your build system, or on a different target system) with dpkg -i and then reboot:

Debug Symbols

Sometimes it is useful to have debug symbols built as well. Two additional steps are needed. First pkg-config-dbgsym needs to be installed. Second when executing the binary-* targets you need to add 'skipdbg=false'.

See also

The above instructions provide a very simple recipe for obtaining the sources and then building them. If you are going to be doing more kernel development than simple configuration changes you may want to look at:

More information about using git to pull down the kernel sources.

For more info about ARM and cross compilation.

Kernel/BuildYourOwnKernel (последним исправлял пользователь rs2009 2021-02-03 17:41:47)

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

Источник

Ubuntu Documentation

Content Cleanup Required
This article should be cleaned-up to follow the content standards in the Wiki Guide. More info.

Needs Updating
This article needs updating to include the latest versions of Ubuntu. More info.

Disclaimer

Building and using a custom kernel will make it very difficult to get support for your system.

While it is a learning experience to compile your own kernel, you will not be allowed to file bugs on the custom-built kernel (if you do, they will be Rejected without further explanation).

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.

This page does NOT describe how to build upstream kernels from kernel.org. This is how to rebuild the actual Ubuntu kernel starting from source.

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

Use git - This is for users who always want to stay in sync with the latest Ubuntu kernel source. For your information, detailed instructions on it can be found in the Kernel Git Guide

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

Option B) Download the source archive

Download the source archive - This is for users who want to rebuild the standard Ubuntu packages with additional patches. Note that this will almost always be out of date compared to the latest development source, so you should use git (option A) if you need the latest patches.

Use a follow command to install the build dependencies and extract the source (to the current directory):

Ubuntu Hardy (8.04)

  • 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.

Ubuntu Karmic Koala (9.10) and newer releases

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.

Raring (13.04):

Option C) Download the source package

Download the source package (detailed instructions are further down this page under Alternate Build Method (B): The Old-Fashioned Debian Way) - This is for users who simply want to modify, or play around with, the Ubuntu-patched kernel source. Again, this will not be the most up-to-date (use Option A/git if you need the latest source). Please be aware this is NOT the same as Option B/Download the source archive.

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.

The stock Ubuntu configs are located in debian/config/ARCH/ where ARCH is the architecture you are building for (Starting with Jaunty this is debian.master/config/ARCH/). In this directory there are several files. The config file is the base for all targets in that architecture. Then there are several config.FLAVOUR files that contain options specific to that target. For example, here are the files for 2.6.20, i386:

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.

Note: Though these outside instructions include making a separate and unique branch of the kernel, unlike here, they include thorough explanations of all necessary steps from start to finish.

These instructions are specific to the git-tree and for the source downloaded via apt-get source, not when downloading the linux-source package from kernel.org

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.
/*
(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.)

Читайте также:  Explay fresh драйвера для windows

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" 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.

Источник

Оцените статью