Linux Kernel Labs
Linux Kernel Labs
Linux Kernel Labs
Practical Labs
https://bootlin.com
Training setup
Download files and directories used in practical labs
Lab data are now available in an linux-kernel-labs directory in your home directory. For each
lab there is a directory containing various data. This directory will also be used as working
space for each lab, so that the files that you produce during each lab are kept separate.
You are now ready to start the real practical labs!
More guidelines
Can be useful throughout any of the labs
• Read instructions and tips carefully. Lots of people make mistakes or waste time because
they missed an explanation or a guideline.
• Always read error messages carefully, in particular the first one which is issued. Some
people stumble on very simple errors just because they specified a wrong file path and
didn’t pay enough attention to the corresponding error message.
• Never stay stuck with a strange problem more than 5 minutes. Show your problem to
your colleagues or to the instructor.
• You should only use the root user for operations that require super-user privileges, such
as: mounting a file system, loading a kernel module, changing file ownership, configuring
the network. Most regular tasks (such as downloading, extracting sources, compiling...)
can be done as a regular user.
• If you ran commands from a root shell by mistake, your regular user may no longer be
able to handle the corresponding generated files. In this case, use the chown -R command
to give the new files back to your regular user.
Example: chown -R myuser.myuser linux/
• If you are using Gnome Terminal (the default terminal emulator in the current version of
Ubuntu), you can use tabs to have multiple terminals in the same window. There’s no more
menu option to create a new tab, but you can get one by pressing the [Ctrl] [Shift] [t]
keys.
Setup
Create the $HOME/linux-kernel-labs/src directory.
Git configuration
After installing git on a new machine, the first thing to do is to let git know about your name
and e-mail address:
git config --global user.name ’My Name’
git config --global user.email [email protected]
Such information will be stored in commits. It is important to configure it properly when the
time comes to generate and send patches, in particular.
or if the network port for git is blocked by the corporate firewall, you can use the http protocol
as a less efficient fallback:
git clone http://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
If Internet access is not fast enough and if multiple people have to share it, your instructor will
give you a USB flash drive with a tar.gz archive of a recently cloned Linux source tree.
You will just have to extract this archive in the current directory, and then pull the most recent
changes over the network:
tar xf linux-git.tar.gz
cd linux
As this still represents many git objects to download (243 MiB when 4.16 was the latest version),
if you are using an already downloaded git tree, your instructor will probably have fetched the
stable branch ahead of time for you too. You can check by running:
git branch -a
We will choose a particular stable version in the next labs.
Now, let’s continue the lectures. This will leave time for the commands that you typed to
complete their execution (if needed).
Board setup
Objective: setup communication with the board and configure the
bootloader.
• Configure the U-boot bootloader and a tftp server on your workstation to download files
through tftp.
The first document to download is the BeagleBone Black System Reference Manual found at
https://github.com/CircuitCo/BeagleBone-Black/blob/master/BBB_SRM.pdf?raw=true.
Even if you have the BeagleBoneBlack Wireless board, this is the ultimate reference about the
board, in particular for the pinout and possible configurations of the P8 and P9 headers, and
more generally for most devices which are the same in both boards. You don’t have to start
reading this document now but you will need it during the practical labs.
The second document to download is the datasheet for the TI AM335x SoCs, available on
http://www.ti.com/lit/ds/symlink/am3359.pdf. This document will give us details about pin
assignments.
Last but not least, download the Technical Reference Manual (TRM) for the TI AM3359 SoC,
available on http://www.ti.com/product/am3359, in the User guides section in the Technical
documents tab. This document is more than 5100 pages big! You will need it too during the
practical labs.
(blue) to the pin closest to the power supply connector (let’s call it pin 1), and the TX (red) and
RX (green) wires to the pins 4 (board RX) and 5 (board TX)2 .
You always should make sure that you connect the TX pin of the cable to the RX pin of the board,
and vice versa, whatever the board and cables that you use.
Once the USB to Serial connector is plugged in, a new serial port should appear: /dev/ttyUSB0.
You can also see this device appear by looking at the output of dmesg.
To communicate with the board through the serial port, install a serial communication program,
such as picocom:
sudo apt install picocom
If you run ls -l /dev/ttyUSB0, you can also see that only root and users belonging to the
dialout group have read and write access to this file. Therefore, you need to add your user to
the dialout group:
sudo adduser $USER dialout
You need to completely log out of your session and log in again for the group change
to be effective.
Now, you can run picocom -b 115200 /dev/ttyUSB0, to start serial communication on /dev/
ttyUSB0, with a baudrate of 115200. If you wish to exit picocom, press [Ctrl][a] followed by
[Ctrl][x].
There should be nothing on the serial line so far, as the board is not powered up yet.
It is now time to power up your board by plugging in the mini-USB (BeagleBone Black case) or
micro-USB (BeagleBone Black Wireless case) cable supplied by your instructor (with your PC
or a USB power supply at the other end of the cable).
See what messages you get on the serial line. You should see U-boot start on the serial line.
Bootloader interaction
Reset your board. Press the space bar in the picocom terminal to stop the U-boot countdown.
You should then see the U-Boot prompt.
For the version we use in the BeagleBone Black, it’s:
2 See https://www.olimex.com/Products/Components/Cables/USB-Serial-Cable/USB-Serial-Cable-F/ for details
U-Boot>
And for the BeagleBone Black Wireless, it’s:
=>
You can now use U-Boot. Run the help command to see the available commands.
Type the help saveenv command to make sure that the saveenv command exists. We use it
in these labs to save your U-Boot environment settings to the boards’ eMMC storage. Some
earlier versions do not support this.
If you don’t have this command, it’s probably because you are doing these labs on your own
(i.e. without participating to a Bootlin course), we ask you to install the U-Boot binary that we
compiled and tested. See instructions in https://git.bootlin.com/training-materials/tree/
lab-data/common/bootloader/beaglebone-black/README.txt or in https://git.bootlin.com/
training-materials/tree/lab-data/common/bootloader/beaglebone-black-wireless/README.
txt for a simple way to do this.
To avoid trouble because of settings applied in previous practical labs, we advise you to clear
the U-Boot environment variables:
env default -f -a
saveenv
3 The U-boot environment settings are stored in some free space between the master boot record (512 bytes,
containing the partition tables and other stuff), and the beginning of the first partition (often at 32256). This is
why you won’t find any related file in the first partition of the eMMC storage.
• Boot this kernel on an NFS root filesystem, which is somewhere on your development
workstation4 .
Lab implementation
While developing a kernel module, the developer wants to change the source code, compile and
test the new kernel module very frequently. While writing and compiling the kernel module is
done on the development workstation, the test of the kernel module usually has to be done on
the target, since it might interact with hardware specific to the target.
However, flashing the root filesystem on the target for every test is time-consuming and would
use the flash chip needlessly.
Fortunately, it is possible to set up networking between the development workstation and the
target. Then, workstation files can be accessed through the network by the target, using NFS.
Setup
Go to the $HOME/linux-kernel-labs/src/linux directory.
Install packages needed for configuring, compiling and booting the kernel for your board:
4 NFS root filesystems are particularly useful to compile modules on your host, and make them directly visible
on the target. You no longer have to update the root filesystem by hand and transfer it to the target (requiring
a shutdown and reboot).
Kernel configuration
Configure your kernel sources with the ready-made configuration for boards in the OMAP2 and
later family which the AM335x found in the BeagleBone belongs to. Don’t forget to set the
ARCH and CROSS_COMPILE definitions for the arm platform and to use your cross-compiler.
For the BeagleBone Black Wireless board, add the below options:
• CONFIG_USB_GADGET=y
• CONFIG_USB_MUSB_HDRC Driver for the USB OTG controller
• CONFIG_USB_MUSB_GADGET Use the USB OTG controller in device (gadget) mode
• CONFIG_MUSB_DSPS=y
• Check the dependencies of CONFIG_AM335X_PHY_USB and find the way to set CONFIG_AM335X_
PHY_USB=y
• Find the ”USB Gadget precomposed configurations” menu and set it to static instead of
module so that CONFIG_USB_ETH=y
Make sure that this configuration has CONFIG_ROOT_NFS=y (support booting on an NFS exported
root directory).
Kernel compiling
Compile your kernel and generate the Device Tree Binaries (DTBs) (running 4 compile jobs in
parallel):
make -j 4
Now, copy the zImage and am335x-boneblack.dtb or am335x-boneblack-wireless.dtb files to
the TFTP server home directory (/var/lib/tftpboot).
Make sure that the path and the options are on the same line. Also make sure that there is no
space between the IP address and the NFS options, otherwise default options will be used for
this IP address, causing your root filesystem to be read-only.
Writing modules
Objective: create a simple kernel module
• Compile and test standalone kernel modules, which code is outside of the main Linux
sources.
Setup
Go to the ~/linux-kernel-labs/modules/nfsroot/root/hello directory. Boot your board if
needed.
Writing a module
Look at the contents of the current directory. All the files you generate there will also be visible
from the target. That’s great to load modules!
Add C code to the hello_version.c file, to implement a module which displays this kind of
message when loaded:
Suggestion: you can look for files in kernel sources which contain version in their name, and
see what they do.
You may just start with a module that displays a hello message, and add version information
later.
Caution: you must use a kernel variable or function to get version information, and not just the
value of a C macro. Otherwise, you will only get the version of the kernel you used to build the
module.
Run one of the kernel configuration interfaces and check that it shows your new driver lets you
configure it as a module.
Run the make command and make sure that the code of your new driver is getting compiled.
Then, commit your changes in the current branch (try to choose an appropriate commit mes-
sage):
cd ~/linux-kernel-labs/src/linux
git add <files>
git commit -as
• git add adds files to the next commit. It is mandatory to use for new files that should be
added under version control.
• git commit -a creates a commit with all modified files that already under version control
• git commit -s adds a Signed-off-by: line to the commit message. All contributions to
the Linux kernel must have such a line.
Throughout the upcoming labs, we will implement a driver for an I2C device, which offers the
functionality of an I2C nunchuk.
After this lab, you will be able to:
• Add an I2C device to a device tree.
• Implement basic probe() and remove() driver functions and make sure that they are called
when there is a device/driver match.
• Find your driver and device in /sys.
Setup
Go to the ~/linux-kernel-labs/src/linux directory. Check out the 4.16.y branch.
Now create a new nunchuk branch starting from the 4.16.y branch, for your upcoming work on
the nunchuk driver.
GND SDA
Open the System Reference Manual that you downloaded earlier, and look for ”connector P9”
in the table of contents, and then follow the link to the corresponding section. Look at the table
listing the pinout of the P9 connector.
Now connect the nunchuk pins:
• The GND pin to P9 pins 1 or 2 (GND)
• The PWR pin to P9 pins 3 or 4 (DC_3.3V)
• The SCL pin to P9 pin 17 (I2C1_SCL)
• The SDA pin to P9 pin 18 (I2C1_SDA)
Serial
Wii Nunchuk
GND
PWR
SDA
SCL
We are first going to enable and configure the second I2C bus (i2c1).
As a child node to the i2c1 bus, now declare the nunchuk device, choosing nintendo,nunchuk
for its compatible property. You will find the I2C slave address of the nunchuk on the nunckuk
document that we have used earlier6 .
Now, just compile your DTB by asking the kernel Makefile to recompile only DTBs:
make dtbs
Now, copy the new DTB to the tftp server home directory, change the DTB file name in the
U-Boot configuration7 , and boot the board.
Through the /sys/firmware/devicetree directory, it is possible to check the Device Tree set-
tings that your system has loaded. That’s useful when you are not sure exactly which settings
were actually loaded.
For example, you can check the presence of a new nunchuk node in your device tree:
# find /sys/firmware/devicetree -name "*nunchuk*"
/sys/firmware/devicetree/base/ocp/i2c@4802a000/nunchuk@52
Using the Device Tree Compiler (dtc, which we put in the root filesystem), you can also check
the whole Device Tree structure. That’s better than checking the source files and includes in
the source directory!
# dtc -I fs /sys/firmware/devicetree/base/
Look for i2c1 and nunchuk in the output of this command, and see where the nodes are instan-
tiated. Don’t hesitate to ask your instructor for questions!
Relying on explanations given during the lectures, fill the nunchuk.c file to implement:
• probe() and remove() functions that will be called when a nunchuk is found. For the
moment, just put a call to pr_info() inside to confirm that these function are called.
• Initialize an i2c_driver structure, and register the i2c driver using it. Make sure that you
use a compatible property that matches the one in the Device Tree.
You can now compile your module and reboot your board, to boot with the updated DTB.
Driver tests
You can now load the /root/nunchuk/nunchuk.ko file. You need to check that the probe()
function gets called then, and that the remove() function gets called too when you remove the
module.
Once your new Device Tree and module work as expected, commit your DT changes in your
Linux tree:
git commit -sa
Exploring /sys
Take a little time to explore /sys:
• Find the representation of your driver. That’s a way of finding the matching devices.
• Find the representation of your device, containing its name. You will find a link to the
driver too.
Setup
Stay in the ~/linux-kernel-labs/src/linux directory for kernel and DTB compiling (stay in
the nunchuk branch), and in ~/linux-kernel-labs/modules/nfsroot/root/nunchuk for module
compiling (use two different terminals).
you need to configure muxing mode number 2. You can also see that both pins support pull-up
and pull-down modes9 (see the PULLUP /DOWN TYPE column).
The next thing to do is to open the big TRM document and look for the address of the registers
that control pin muxing. First, look for L4_WKUP Peripheral Memory Map with your PDF
reader search utility. You will find a table containing a Control Module Registers entry with
its address: 0x44E1_0000.
Last but not least, look for the SPI0_CS0 and SPI0_D1 pin names, and you will find the offsets
for the registers controlling muxing for these pins in the CONTROL_MODULE REGISTERS
table: respectively 0x95c and 0x958.
We now know which registers we can write to to enable i2c1 signals.
Device initialization
The next step is to read the state of the nunchuk registers, to find out whether buttons are
pressed or not, for example.
Before being able to read nunchuk registers, the first thing to do is to send initialization com-
mands to it. That’s also a nice way of making sure i2c communication works as expected.
In the probe routine (run every time a matching device is found):
1. Using the I2C raw API (i2c_master_send() and i2c_master_recv()), send two bytes to
the device: 0xf0 and 0x5510 . Make sure you check the return value of the function you’re
using. This could reveal communication issues. Using Elixir, find examples of how to
handle failures properly using the same function.
2. Let the CPU wait for 1 ms by using the msleep() routine. You may need to use Elixir
again to find the right C headers to include.
10 The I2C messages to communicate with a wiimote extension are in the form: <i2c_address> <register>
for reading and <i2c_address> <register> <value> for writing. The address, 0x52 is sent by the i2c framework
so you only have to write the other bytes, the register address and if needed, the value you want to write. There
are two ways to set up the communication. The first known way was with data encryption by writing 0x00 to
register 0x40 of the nunchuk. With this way, you have to decrypt each byte you read from the nunchuk (not so
hard but something you have to do). Unfortunately, such encryption doesn’t work on third party nunchuks so
you have to set up unencrypted communication by writing 0x55 to 0xf0 instead. This works across all brands of
nunchuks (including Nintendo ones).
3. In the same way, send the 0xfb and 0x00 bytes now. This completes the nunchuk initial-
ization.
Recompile and load the driver, and make sure you have no communication errors.
Testing
Compile your module, and reload it. No button presses should be detected. Remove your
module.
Now hold the Z button and reload and remove your module again:
insmod /root/nunchuk/nunchuk.ko; rmmod nunchuk
11 msleep() is nicer than mdelay() because it is not making an active wait, and instead lets the CPU run other
You should now see the message confirming that the driver found out that the Z button was
held.
Do the same over and over again with various button states.
At this stage, we just made sure that we could read the state of the device registers through
the I2C bus. Of course, loading and removing the module every time is not an acceptable way
of accessing such data. We will give the driver a proper input interface in the next slides.
Input interface
Objective: make the I2C device available to user space using the
input subsystem.
• In our case, we only allocated resources with devm_ functions. Thanks to this, in case of
failure, all the corresponding allocations are automatically released before destroying the
device structure for each device. This greatly simplifies our error management code!
set_bit(EV_KEY, input->evbit);
set_bit(BTN_C, input->keybit);
set_bit(BTN_Z, input->keybit);
(Source code link: https://git.bootlin.com/training-materials/plain/labs/kernel-i2c-input-interface/
input-device-attributes.c)
Recompile and reload your driver. You should now see in the kernel log that the Unspecified
device type is replaced by Wii Nunchuk and that the physical path of the device is reported too.
versely, when we have an event on the logical side (such as running the polling function), we
can find out which i2c slave this corresponds to, to communicate with the hardware.
This need is typically implemented by creating a private data structure to manage our device
and implement such pointers between the physical and logical worlds.
Add the below global definition to your code:
struct nunchuk_dev {
struct i2c_client *i2c_client;
};
Now, in your probe() routine, declare an instance of this structure:
struct nunchuk_dev *nunchuk;
Then allocate one such instead for each new device:
nunchuk = devm_kzalloc(&client->dev, sizeof(struct nunchuk_dev), GFP_KERNEL);
if (!nunchuk) {
dev_err(&client->dev, "Failed to allocate memory\n");
return -ENOMEM;
}
(Source code link: https://git.bootlin.com/training-materials/plain/labs/kernel-i2c-input-interface/
private-data-alloc.c)
Note that we haven’t seen kernel memory allocator routines and flags yet.
We haven’t explained the dev_* logging routines yet either (they are basically used to tell which
device a given log message is associated to). For the moment, just use the above code. You will
get all the details later.
Now implement the pointers that we need:
nunchuk->i2c_client = client;
polled_input->private = nunchuk;
(Source code link: https://git.bootlin.com/training-materials/plain/labs/kernel-i2c-input-interface/
device-pointers.c)
Make sure you add this code before registering the input device. You don’t want to enable
a device with incomplete information or when it is not completely yet (there could be race
conditions).
First, add lines retrieving the I2C physical device from the input_polled_dev structure. That’s
where you will need your private nunchuk structure.
Now that you have a handle on the I2C physical device, you can move the code reading the
nunchuk registers to this function. You can remove the double reading of the device state, as
the polling function will make periodic reads anyway13 .
At the end of the polling routine, the last thing to do is post the events and notify the input
core. Assuming that polled_input is the name of the input_polled_dev parameter of your
polling routine:
input_event(polled_input->input,
EV_KEY, BTN_Z, zpressed);
13 During the move, you will have to handle communication errors in a slightly different way, as the nunchuk_
poll() routine has a void type. When the function reading registers fails, you can use a return; statement
instead of return value;
input_event(polled_input->input,
EV_KEY, BTN_C, cpressed);
input_sync(polled_input->input);
(Source code link: https://git.bootlin.com/training-materials/plain/labs/kernel-i2c-input-interface/
input-notification.c)
Now, back to the probe() function, the last thing to do is to declare the new polling function
(see the slides if you forgot about the details) and specify a polling interval of 50 ms.
At this stage, also remove the debugging messages about the state of the buttons. You will get
that information from the input interface.
You can now make sure that your code compiles and loads successfully.
Going further
If you complete your lab before the others, you can add support for the nunchuk joystick
coordinates.
Another thing you can do then is add support for the nunchuk accelerometer coordinates.
Throughout the upcoming labs, we will implement a character driver allowing to write data to
additional CPU serial ports available on the BeagleBone, and to read data from them.
After this lab, you will be able to:
• Add UART devices to the board device tree.
• Access I/O registers to control the device and send first characters to it.
Setup
Go to your kernel source directory.
Create a new branch for this new series of labs. Since this new stuff is independent from the
nunchuk changes, it’s best to create a separate branch!
git checkout 4.16.y
git checkout -b uart
uart4_pins: uart4_pins {
pinctrl-single,pins = <
AM33XX_IOPAD(0x870, PIN_INPUT_PULLUP | MUX_MODE6) /* gpmc_wait0.uart4_rx */
AM33XX_IOPAD(0x874, PIN_OUTPUT_PULLDOWN | MUX_MODE6) /* gpmc_wpn.uart4_tx */
>;
};
&uart4 {
compatible = "bootlin,serial";
status = "okay";
pinctrl-names = "default";
pinctrl-0 = <&uart4_pins>;
};
(Source code link: https://git.bootlin.com/training-materials/plain/labs/kernel-serial-iomem/
uarts.dts)
This is a good example of how we can override definitions in the Device Tree. uart2 and uart4
are already defined in arch/arm/boot/dts/am33xx.dtsi. In the above code, we just override a
few properties and add missing ones: duplicate the valid ones:
• compatible: use our driver instead of using the default one (omap3-uart).
• status: enable the device (was set to disabled in the original definition.
• pinctrl-names, pinctrl-0: add pinmux settings (none were defined so far).
Compile and update your DTB.
devices. Even if we only connect a serial-to-USB dongle to one of them, both of them are ready to be used!
Such information is precisely available in the Device Tree. You can extract it with the below
code:
Add such code to your probe() routine, with proper error handling when res == NULL, and
print the start address (res->start) to make sure that the address values that you get match
the ones in the device tree.
You can remove the printing instruction as soon as the collected addresses are correct.
In the same way as in the nunchuk lab, we now need to create a structure that will hold device
specific information and help keeping pointers between logical and physical devices.
As the first thing to store will be the base virtual address for each device (obtained through
ioremap()), let’s declare this structure as follows:
struct serial_dev {
void __iomem *regs;
};
The first thing to do is allocate such a structure at the beginning of the probe() routine. Let’s
do it with the devm_kzalloc function again as in the previous lab. Again, resource deallocation
is automatically taken care of when we use the devm_ functions.
You can now get a virtual address for your device’s base physical address, by calling:
What’s nice is that you won’t ever have to release this resource, neither in the remove() routine,
nor if there are failures in subsequent steps of the probe() routine.
Make sure that your updated driver compiles, loads and unloads well.
Device initialization
Now that we have a virtual address to access registers, we are ready to configure a few registers
which will allow us to enable the UART devices. Of course, this will be done in the probe()
routine.
As we will have multiple registers to read, create a reg_read() routine, returning an unsigned
int value, and taking a dev pointer to an serial_dev structure and an offset integer offset.
In this function, read from a 32 bits register at the base virtual address for the device plus the
offset multiplied by 4.
All the UART register offsets have standardized values, shared between several types of serial
drivers (see include/uapi/linux/serial_reg.h). This explains why they are not completely
ready to use and we have to multiply them by 4 for OMAP SoCs.
Create a similar reg_write() routine, writing an unsigned integer value at a given integer offset
(don’t forget to multiply it by 4) from the device base virtual address. The following code
samples are using the writel() convention of passing the value first, then the offset. Your
prototype should look like:
static void reg_write(struct serial_dev *dev, int val, int off);
In the next sections, we will tell you what register offsets to use to drive the hardware.
After these lines, let’s add code to initialize the line and configure the baud rate. This shows
how to get a special property from the device tree, in this case clock-frequency:
/* Configure the baud rate to 115200 */
of_property_read_u32(pdev->dev.of_node, "clock-frequency",
&uartclk);
baud_divisor = uartclk / 16 / 115200;
reg_write(dev, 0x07, UART_OMAP_MDR1);
reg_write(dev, 0x00, UART_LCR);
reg_write(dev, UART_LCR_DLAB, UART_LCR);
reg_write(dev, baud_divisor & 0xff, UART_DLL);
reg_write(dev, (baud_divisor >> 8) & 0xff, UART_DLM);
reg_write(dev, UART_LCR_WLEN8, UART_LCR);
Soft reset
• To specify a name for the device file in devtmpfs. We propose to use devm_kasprintf(&pdev->dev,
GFP_KERNEL, "serial-%x", res->start). devm_kasprintf() allocates a buffer and runs
ksprintf() to fill its contents.
• To pass the file operations structure that you defined.
See the lectures for details if needed!
The last things to do (at least to have a misc driver, even if its file operations are not ready
yet), are to add the registration and deregistration routines. That’s typically the time when you
will need to access the serial_dev structure for each device from the pdev structure passed to
the remove() routine.
Make sure that your driver compiles and loads well, and that you now see two new device files
in /dev.
At this stage, make sure you can load and unload the driver multiple times. This should reveal
registration and deregistration issues if there are any.
Setup
This lab is a continuation of the Output-only misc driver lab. Use the same kernel, environment
and paths!
Compile and load your module. Send a character on the serial link (just type something in
the corresponding picocom terminal, and look at the kernel logs: they are full of our message
indicating that interrupts are occurring, even if we only sent one character! It shows you that
interrupt handlers should do a little bit more when an interrupt occurs.
struct serial_dev {
void __iomem *regs;
struct miscdevice miscdev;
int irq;
char serial_buf[SERIAL_BUFSIZE];
int serial_buf_rd;
int serial_buf_wr;
};
In the interrupt handler, store the received character at location serial_buf_wr in the circular
buffer, and increment the value of serial_buf_wr. If this value reaches SERIAL_BUFSIZE, reset
it to zero.
In the read() operation, if the serial_buf_rd value is different from the serial_buf_wr value,
it means that one character can be read from the circular buffer. So, read this character, store
it in the user space buffer, update the serial_buf_rd variable, and return to user space (we will
only read one character at a time, even if the user space application requested more than one).
Now, what happens in our read() function if no character is available for reading (i.e, if serial_
buf_wr is equal to serial_buf_rd)? We should put the process to sleep!
To do so, add a wait queue to our serial_dev structure, named for example serial_wait. In
the read() function, keep things simple by directly using wait_event_interruptible() right
from the start, to wait until serial_buf_wr is different from serial_buf_rd15 .
Last but not least, in the interrupt handler, after storing the received characters in the circular
buffer, use wake_up() to wake up all processes waiting on the wait queue.
Compile and load your driver. Run cat /dev/serial-48024000 on the target, and then in
picocom on the development workstation side, type some characters. They should appear on
the remote side if everything works correctly!
Don’t be surprised if the keys you type in Picocom don’t appear on the screen. This happens
because they are not echoed back by the target.
15 A single test in the wait_event_interruptible() function is sufficient. If the condition is met, you don’t go
to sleep and read one character right away. Otherwise, when you wake up, you can proceed to the reading part.
Locking
Objective: practice with basic locking primitives
Setup
Continue to work with the serial driver.
You need to have completed the previous two labs to perform this one.
In this lab, we will continue to work on the code of our serial driver.
Check what happens with your module. Do you see the debugging messages that you added?
Your kernel probably does not have CONFIG_DYNAMIC_DEBUG set and your driver is not compiled
with DEBUG defined., so you shouldn’t see any message.
Now, recompile your kernel with CONFIG_DYNAMIC_DEBUG and reboot. The dynamic debug feature
can be configured using debugfs, so you’ll have to mount the debugfs filesystem first. Then,
after reading the dynamic debug documentation in the kernel sources, do the following things:
• Enable all debugging messages of your serial module, and check that you indeed see these
messages.
• Enable just one single debug message in your serial module, and check that you see just
this message and not the other debug messages of your module.
Now, you have a good mechanism to keep many debug messages in your drivers and be able to
selectively enable only some of them.
debugfs
Since you have enabled debugfs to control the dynamic debug feature, we will also use it to add
a new debugfs entry. Modify your driver to add:
• And file called counter inside the serial directory of the debugfs filesystem. This file
should allow to see the contents of the counter variable of your module.
Recompile and reload your driver, and check that in /sys/kernel/debug/serial/counter you
can see the amount of characters that have been transmitted by your driver.
16 gdb-multiarch is a new package supporting multiple architectures at once. If you have a cross toolchain
Setup
Go to your kernel source tree in ~/linux-kernel-labs/src/linux
• Device tree sources: simplify them by replacing nodes that are instantiated again in the
.dts files (with their location in the tree) by a phandle to a definition in the .dtsi file
(simpler because you don’t have to repeat the location in the tree). Make sure that the
new DT is equivalent by decompiling and comparing the old DTB and the new DTB
(dtc -I dtb).
• Run apt install coccinelle and make coccicheck and try to propose fixes for the re-
ported bugs (coccinelle can propose patches too, but they need to be reviewed by humans
before submission.
Before making changes, create a new branch and move into it.
Now, implement your changes, and commit them, following instructions in the slides for con-
tributing to the Linux kernel.
A git fetch will fetch the data for this tree. Of course, Git will optimize the storage, and
will not store everything that’s common between the two trees. This is the big advantage of
having a single local repository to track multiple remote trees, instead of having multiple local
repositories.
We can then switch to the master branch of the realtime tree:
git checkout realtime/master
Or look at the difference between the scheduler code in the official tree and in the realtime tree:
git diff master..realtime/master kernel/sched/