Ubuntu linux kernel git

Ubuntu Wiki

SourceCode

The kernel source for the Ubuntu kernel is based very closely on the upstream mainline kernel tree maintained by Linus. The Ubuntu-ness of this kernel is maintained as a git branch against the Linus tree.

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.

Obtaining the kernel sources for an Ubuntu release using apt-get

The literal 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 below:

or failing that:

Obtaining the kernel sources for an Ubuntu release using git

The source for each release is maintained in its own git repository on Launchpad.

The git repository is listed in the Vcs-Git: header in the source package and is of the following form:

For example, the standard Cosmic kernel is available at:

There is a tree for each of the currently supported releases as well as any open development and upcoming releases:

ubuntu-kernel/ubuntu/+source/linux/+git/groovy

ubuntu-kernel/ubuntu/+source/linux/+git/focal

ubuntu-kernel/ubuntu/+source/linux/+git/bionic

Replace your intended OS series in the above, and pull the source for the kernels you need.

The distro kernel is always on the master branch in these repositories. Each release also has a master-next branch containing the commits that will go onto the master branch and become the next release for that release.

A number of releases also have other source packages which represent other related but divergent kernels for other purposes. For example, there is a specialized AWS kernel available in the linux-aws source package. (Previously these sorts of things were done in Topic Branches and some older kernels and projects still use them.)

If you cannot use the git protocol (perhaps because of a firewall), you can use the slower http protocol. For example:

Obtaining a copy

To obtain a local copy you can simply git clone the repository for the release you are interested. The git command is part of the git package.

For example to obtain the Bionic tree:

This will download several hundred megabytes of data. If you plan on working on more than one kernel release you can save space and time by downloading the upstream kernel tree. Note that once these two trees are tied together you cannot remove the virgin Linus tree without damage to the Ubuntu tree:

Читайте также:  Как полностью отформатировать жесткий диск через windows

In each case you will end up with a new directory ubuntu- containing the source and the full history which can be manipulated using the git command from within each directory.

By default you will have the latest version of the kernel tree, the master tree. You can switch to any previously released kernel version using the release tags. To obtain a full list of the tagged versions in the release as below:

To look at the Ubuntu-5.4.0-52.57 version you can simply checkout a new branch pointing to that version:

You may then manipulate the release — for example, by adding new commits.

Kernel/SourceCode (последним исправлял пользователь apw 2010-06-21 08:20:10)

Источник

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.

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.

Читайте также:  Linux нет команды open

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.

Источник

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, вам больше не нужны никакие дополнительные пакеты. В случае же с оставшимися тремя вариантами необходимо установить также дополнительные пакеты.

Читайте также:  Windows thread memory usage

Для установки пакетов, необходимых для использования 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 ГБ на вашем жёстком диске (размер освобождаемого пространства зависит от параметров сборки).

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

Источник

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