How do I get the kernel source code?

I am planning to write some device drivers and I need to get the Linux kernel source. My Linux kernel version is 3.2.0-23-generic-pae and I downloaded the image from this. In many of the articles I have read, it tells me that I need to have the entire kernel tree to start inserting new modules.

Is it enough if I download this image and paste it into the usr/src/ folder or do I have to do something else?


Solution 1:

This will get the source of the stock kernel:

apt-get source linux-source
  • https://help.ubuntu.com/community/Kernel/Compile/

You can check what version of the kernel is running like this:

uname -r

Which will print something like:

3.13.0-46-generic

You can find a list of current source package versions available on your system via:

apt-cache search linux-source

To get the upstream version of the kernel:

git clone git://kernel.ubuntu.com/ubuntu/ubuntu-trusty.git
  • https://wiki.ubuntu.com/KernelTeam/GitKernelBuild

In the above link, 'trusty' is the codename for the version of Ubuntu. You can find out the codename for the version of Ubuntu you have installed via:

cat /etc/lsb-release

Solution 2:

apt-get source linux

is the easiest way. It will download the source from your repository - and it'll be the same as the version you're running (assuming you haven't already customised it).

But if you want to find where the source is maintained you can run:

apt-cache showsrc linux

Look for the 'Vcs-' attribute (Version control system). It'll usually be a git (Vcs-Git) or mercurial repository.

Note - these commands work with any package. Just substitute 'linux' with the package you're interested in. And also note that 'apt-get source' doesn't need sudo access and will dump the source in your current directory.

Solution 3:

Download source directly from Launchpad

Strangely enough everyone recommends apt-get source which doesn't work most of the time if you're looking for a specific kernel version:

Say you need kernel source for 3.19.0-58 :
apt-get source linux-image-3.19.0-58-generic will get the source for the latest kernel in the series: 3.19.0-80 in this case, which is not what you asked for.

So you have two options:

1) Give up, install kernel 3.19.0-80 and use apt-get source

2) Get source directly from launchpad:

  • Google site:launchpad.net "linux-image-3.19.0-58-generic"

  • That should give you the Launchpad Package Page for that version.

  • Scroll down, click the "Source:" link, you're on the Package Source Page now.

  • Scroll down and download .tar.gz, .diff.gz, .dsc files:

links

  • Put them in a new directory, unpack with dpkg-source -x *.dsc

Notes:

  • There must be a better way.
  • You can get the version you want from git, but you're in for a big download. See "Obtaining the kernel sources for an Ubuntu release using git" in Ubuntu Wiki Kernel Source Code.