<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="ro">
	<id>http://wiki.dcae.pub.ro/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Vserbu</id>
	<title>WikiLabs - Contribuții utilizator [ro]</title>
	<link rel="self" type="application/atom+xml" href="http://wiki.dcae.pub.ro/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Vserbu"/>
	<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php/Special:Contribu%C8%9Bii/Vserbu"/>
	<updated>2026-12-06T03:39:25Z</updated>
	<subtitle>Contribuții utilizator</subtitle>
	<generator>MediaWiki 1.35.14</generator>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=OS_Lab_9_-_USB_drivers._USB_transfers&amp;diff=8466</id>
		<title>OS Lab 9 - USB drivers. USB transfers</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=OS_Lab_9_-_USB_drivers._USB_transfers&amp;diff=8466"/>
		<updated>2026-12-04T14:23:12Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In [[OS_Lab_8_-_Kernel_modules._Character_devices|the last lab]], we wrote a kernel module with a character device, whose &amp;lt;code&amp;gt;read()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;write()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ioctl()&amp;lt;/code&amp;gt; ran our functions. The device was a virtual one: it only kept data in memory. In this lab, the device behind the file is a real USB device, your project board, and the driver&amp;#039;s functions talk to it.&lt;br /&gt;
&lt;br /&gt;
The rule for the whole lab is simple: &amp;#039;&amp;#039;&amp;#039;each file operation does its own USB transfers, waits for them, and returns&amp;#039;&amp;#039;&amp;#039;. The driver never does anything in the background. Real drivers are often more complicated (see [[#How real drivers do it|How real drivers do it]]), but for our boards, this is all that is needed, and it keeps the driver close to the character device of the last lab.&lt;br /&gt;
&lt;br /&gt;
== Learning objectives ==&lt;br /&gt;
&lt;br /&gt;
By the end of this lab you should be able to:&lt;br /&gt;
&lt;br /&gt;
# read the descriptors of a USB device, and find its interfaces and endpoints;&lt;br /&gt;
# write a USB driver which binds to a device, checks it in &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt;, and cleans up in &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt;;&lt;br /&gt;
# give each board its own file in &amp;lt;code&amp;gt;/dev&amp;lt;/code&amp;gt;;&lt;br /&gt;
# send control requests, and read and write interrupt and bulk endpoints, with blocking calls;&lt;br /&gt;
# make a blocking call that can be interrupted with Ctrl+C, and that respects &amp;lt;code&amp;gt;O_NONBLOCK&amp;lt;/code&amp;gt;;&lt;br /&gt;
# convert between the byte order of the device and of the machine;&lt;br /&gt;
# handle a device which is unplugged while a program uses it.&lt;br /&gt;
&lt;br /&gt;
== The project ==&lt;br /&gt;
&lt;br /&gt;
There is no new template: you build your USB driver in the project of the last lab, which already has the three parts (the driver, a library which wraps it, and a program which uses the library) and the kernel tree in &amp;lt;code&amp;gt;kbuild/&amp;lt;/code&amp;gt;. Work in a copy of it. &amp;lt;code&amp;gt;kbuild/&amp;lt;/code&amp;gt; is large, so move it rather than copy it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
rsync -a --exclude kbuild lab08/ lab09/&lt;br /&gt;
mv lab08/kbuild lab09/&lt;br /&gt;
cd lab09&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then turn the &amp;lt;code&amp;gt;klog&amp;lt;/code&amp;gt; driver of the template into yours. The examples in this lab are from &amp;lt;code&amp;gt;arhboard&amp;lt;/code&amp;gt;, a driver which works on every project board, because it only uses the requests and events which all of them have. For your own driver, use the name of your project instead:&lt;br /&gt;
&lt;br /&gt;
# rename &amp;lt;code&amp;gt;driver/klog.c&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;driver/arhboard.c&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;driver/uapi/klog_ioctl.h&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;driver/uapi/arhboard_ioctl.h&amp;lt;/code&amp;gt;;&lt;br /&gt;
# in &amp;lt;code&amp;gt;driver/Kbuild&amp;lt;/code&amp;gt;, change the line &amp;lt;code&amp;gt;obj-m&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;obj-m := arhboard.o&amp;lt;/code&amp;gt;;&lt;br /&gt;
# in &amp;lt;code&amp;gt;driver/Makefile&amp;lt;/code&amp;gt;, change &amp;lt;code&amp;gt;MODULE := klog&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;MODULE := arhboard&amp;lt;/code&amp;gt;;&lt;br /&gt;
# rename the files in &amp;lt;code&amp;gt;lib/&amp;lt;/code&amp;gt; as well, when you write the library. CMake builds every &amp;lt;code&amp;gt;.c&amp;lt;/code&amp;gt; file in &amp;lt;code&amp;gt;lib/&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;app/&amp;lt;/code&amp;gt;, whatever its name. Until then, the library and the program of the template no longer build, because they include &amp;lt;code&amp;gt;klog_ioctl.h&amp;lt;/code&amp;gt;: build the driver alone, with &amp;lt;code&amp;gt;make -C driver&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
A USB driver has one file in &amp;lt;code&amp;gt;/dev&amp;lt;/code&amp;gt; for each board, &amp;lt;code&amp;gt;/dev/arhboard0&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;/dev/arhboard1&amp;lt;/code&amp;gt;, ..., and they only appear when a board is plugged in (see [[#One file per board|One file per board]]). The rule &amp;lt;code&amp;gt;load&amp;lt;/code&amp;gt; of the template already handles this: after &amp;lt;code&amp;gt;insmod&amp;lt;/code&amp;gt;, it makes the file of every device of the module that it finds in &amp;lt;code&amp;gt;/sys/class&amp;lt;/code&amp;gt;, which was &amp;lt;code&amp;gt;/dev/klog&amp;lt;/code&amp;gt; in the last lab, and is one file per board now. &amp;lt;code&amp;gt;make unload&amp;lt;/code&amp;gt; removes them again. On OrbStack, which does not make the files itself, run &amp;lt;code&amp;gt;make -C driver nodes&amp;lt;/code&amp;gt; for a board you plug in after loading the driver.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; If the build of the driver stops with &amp;lt;code&amp;gt;ERROR: modpost: &amp;quot;usb_register_driver&amp;quot; [...] undefined!&amp;lt;/code&amp;gt;, your &amp;lt;code&amp;gt;kbuild/&amp;lt;/code&amp;gt; was made without USB support, by an older &amp;lt;code&amp;gt;make_kbuild.sh&amp;lt;/code&amp;gt;. Download the template of the last lab again, take its &amp;lt;code&amp;gt;make_kbuild.sh&amp;lt;/code&amp;gt;, delete &amp;lt;code&amp;gt;kbuild/&amp;lt;/code&amp;gt;, and run the script again. Take its &amp;lt;code&amp;gt;driver/Makefile&amp;lt;/code&amp;gt; too (and set &amp;lt;code&amp;gt;MODULE&amp;lt;/code&amp;gt; in it again): an older one has no &amp;lt;code&amp;gt;nodes&amp;lt;/code&amp;gt; rule, and only makes &amp;lt;code&amp;gt;/dev/klog&amp;lt;/code&amp;gt;.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== The board ===&lt;br /&gt;
&lt;br /&gt;
The board you will be working with is a Raspberry Pi Pico 2 (or Pico 2 W) which runs the firmware assigned to you for your project. It should be running the firmware as soon as you plug it in. You do not need to program the board yourself.&lt;br /&gt;
&lt;br /&gt;
On a PC which runs Linux directly, there is nothing else to do: plug the board in. In a virtual machine, the board is plugged into the host (macOS or Windows), and you must give it to the Linux machine first.&lt;br /&gt;
&lt;br /&gt;
==== OrbStack ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;orb usb list&amp;lt;/code&amp;gt; shows the USB devices of the Mac, with an ID for each:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ orb usb list&lt;br /&gt;
...&lt;br /&gt;
00114000  cafe:4301  ARH ARH CC-1&lt;br /&gt;
$ orb usb attach 00114000&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
From then on, Linux sees the board as if it were plugged into it, and macOS does not see it anymore. &amp;lt;code&amp;gt;orb usb detach 00114000&amp;lt;/code&amp;gt; gives it back to the Mac, which, for Linux, is the same as unplugging it. This is useful later, to test what your driver does when the board goes away.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; When you unplug the board and plug it back in, it goes back to the Mac: attach it again. The ID belongs to the USB port, not to the board, so it stays the same as long as you use the same port. Run &amp;lt;code&amp;gt;orb usb list&amp;lt;/code&amp;gt; again if you change ports.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== WSL ====&lt;br /&gt;
&lt;br /&gt;
WSL gets USB devices from Windows through [https://github.com/dorssel/usbipd-win usbipd-win], which you install in Windows. In a PowerShell window opened as administrator, &amp;lt;code&amp;gt;usbipd list&amp;lt;/code&amp;gt; shows the USB devices of the PC, with a bus ID for each. Share the board once with &amp;lt;code&amp;gt;bind&amp;lt;/code&amp;gt;, and then give it to WSL with &amp;lt;code&amp;gt;attach&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;powershell&amp;quot;&amp;gt;&lt;br /&gt;
&amp;gt; usbipd list&lt;br /&gt;
BUSID  VID:PID    DEVICE                    STATE&lt;br /&gt;
2-3    cafe:4301  ARH CC-1                  Not shared&lt;br /&gt;
&amp;gt; usbipd bind --busid 2-3&lt;br /&gt;
&amp;gt; usbipd attach --wsl --busid 2-3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
From then on, &amp;lt;code&amp;gt;lsusb&amp;lt;/code&amp;gt; in WSL shows the board. &amp;lt;code&amp;gt;usbipd detach --busid 2-3&amp;lt;/code&amp;gt; gives it back to Windows, which, for Linux, is the same as unplugging it. After you unplug the board and plug it back in, run &amp;lt;code&amp;gt;usbipd attach&amp;lt;/code&amp;gt; again.&lt;br /&gt;
&lt;br /&gt;
== USB in brief ==&lt;br /&gt;
&lt;br /&gt;
USB connects one &amp;#039;&amp;#039;&amp;#039;host&amp;#039;&amp;#039;&amp;#039; (the computer) to many &amp;#039;&amp;#039;&amp;#039;devices&amp;#039;&amp;#039;&amp;#039;. The most important rule is that &amp;#039;&amp;#039;&amp;#039;the host always starts communication&amp;#039;&amp;#039;&amp;#039;. A device never sends anything on its own: it only answers when the host asks. When the host asks a device for data, the device answers in one of three ways:&lt;br /&gt;
&lt;br /&gt;
* with the data;&lt;br /&gt;
* with a &amp;#039;&amp;#039;&amp;#039;NAK&amp;#039;&amp;#039;&amp;#039;: nothing now, ask again later. This is normal, and the host should keep asking;&lt;br /&gt;
* with a &amp;#039;&amp;#039;&amp;#039;STALL&amp;#039;&amp;#039;&amp;#039;: no, the device refuses the request, or this part of the device is stopped.&lt;br /&gt;
&lt;br /&gt;
=== Devices, interfaces and endpoints ===&lt;br /&gt;
&lt;br /&gt;
A device describes itself to the host with &amp;#039;&amp;#039;&amp;#039;descriptors&amp;#039;&amp;#039;&amp;#039;, when it is plugged in. They form a tree:&lt;br /&gt;
&lt;br /&gt;
* the &amp;#039;&amp;#039;&amp;#039;device&amp;#039;&amp;#039;&amp;#039;: its vendor and product IDs (VID and PID), its name, its serial number;&lt;br /&gt;
** a &amp;#039;&amp;#039;&amp;#039;configuration&amp;#039;&amp;#039;&amp;#039;: almost every device has exactly one;&lt;br /&gt;
*** one or more &amp;#039;&amp;#039;&amp;#039;interfaces&amp;#039;&amp;#039;&amp;#039;: one function of the device. A webcam with a microphone has one interface for the video, and one for the sound. Each interface has a &amp;#039;&amp;#039;&amp;#039;class&amp;#039;&amp;#039;&amp;#039; (audio, keyboard, storage, ...). A class of 0xFF means that the interface is &amp;#039;&amp;#039;&amp;#039;vendor-specific&amp;#039;&amp;#039;&amp;#039;: its protocol is known only to its own driver;&lt;br /&gt;
**** the &amp;#039;&amp;#039;&amp;#039;endpoints&amp;#039;&amp;#039;&amp;#039; of the interface: the places where data goes in or out of the device.&lt;br /&gt;
&lt;br /&gt;
A driver in Linux binds to an interface, not to a whole device. Our boards have exactly one interface, with three endpoints: a bulk endpoint in each direction for data, and an interrupt endpoint for events. So the driver of a board binds to that interface, and has the whole board to itself.&lt;br /&gt;
&lt;br /&gt;
An &amp;#039;&amp;#039;&amp;#039;endpoint&amp;#039;&amp;#039;&amp;#039; has a number, from 1 to 15, and a &amp;#039;&amp;#039;&amp;#039;direction&amp;#039;&amp;#039;&amp;#039;, which is always seen from the host: &amp;#039;&amp;#039;&amp;#039;IN&amp;#039;&amp;#039;&amp;#039; means from the device to the host, &amp;#039;&amp;#039;&amp;#039;OUT&amp;#039;&amp;#039;&amp;#039; from the host to the device. The direction is the top bit of the endpoint &amp;#039;&amp;#039;&amp;#039;address&amp;#039;&amp;#039;&amp;#039;: 0x81 is endpoint 1 IN, 0x01 is endpoint 1 OUT. Every device also has &amp;#039;&amp;#039;&amp;#039;endpoint 0&amp;#039;&amp;#039;&amp;#039;, which works both ways, and is used for &amp;#039;&amp;#039;&amp;#039;control&amp;#039;&amp;#039;&amp;#039; requests: commands and settings. Each endpoint also has a &amp;#039;&amp;#039;&amp;#039;maximum packet size&amp;#039;&amp;#039;&amp;#039; (&amp;lt;code&amp;gt;wMaxPacketSize&amp;lt;/code&amp;gt;), the most bytes that one packet on it can carry: on our boards, 64 bytes for endpoint 0 and the bulk endpoints, and 8 bytes for the event endpoint, which is exactly one event.&lt;br /&gt;
&lt;br /&gt;
Each endpoint has a &amp;#039;&amp;#039;&amp;#039;transfer type&amp;#039;&amp;#039;&amp;#039;, which says how the host uses it:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Type !! Used for !! On our boards&lt;br /&gt;
|-&lt;br /&gt;
| Control || Commands, settings, small replies. Only on endpoint 0 || Every request in the protocol of the board: &amp;lt;code&amp;gt;GET_INFO&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IDENTIFY&amp;lt;/code&amp;gt;, ...&lt;br /&gt;
|-&lt;br /&gt;
| Bulk || Large amounts of data, as fast as the bus allows, with no promise about time || The data of a project: what a CC-1 hashes or encrypts, for example&lt;br /&gt;
|-&lt;br /&gt;
| Interrupt || Small, infrequent messages, which must arrive within a known time || Events: the button was pressed, an operation has finished&lt;br /&gt;
|-&lt;br /&gt;
| Isochronous || Sound and video: a fixed rate, and late data is dropped || Not used&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
The name of interrupt endpoints is misleading: the device still cannot speak first. The host asks the endpoint again and again, every few milliseconds (the &amp;#039;&amp;#039;&amp;#039;interval&amp;#039;&amp;#039;&amp;#039;, set in the descriptor), and the device answers with NAK until it has something to say. Nothing reaches the host while nobody asks.&lt;br /&gt;
&lt;br /&gt;
Our boards run at &amp;#039;&amp;#039;&amp;#039;full speed&amp;#039;&amp;#039;&amp;#039; (12 Mbit/s), where a bulk or interrupt &amp;#039;&amp;#039;&amp;#039;packet&amp;#039;&amp;#039;&amp;#039; carries at most 64 bytes. A larger transfer is cut into several packets.&lt;br /&gt;
&lt;br /&gt;
=== Your board&amp;#039;s descriptors ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;lsusb&amp;lt;/code&amp;gt; lists the devices, and &amp;lt;code&amp;gt;lsusb -v&amp;lt;/code&amp;gt; prints all their descriptors. All our boards have the vendor ID &amp;lt;code&amp;gt;0xcafe&amp;lt;/code&amp;gt;, and a product ID for each project:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ lsusb -d cafe:&lt;br /&gt;
Bus 001 Device 004: ID cafe:4301 ARH ARH CC-1&lt;br /&gt;
$ lsusb -v -d cafe:&lt;br /&gt;
...&lt;br /&gt;
  idVendor           0xcafe&lt;br /&gt;
  idProduct          0x4301&lt;br /&gt;
  bcdDevice            1.00&lt;br /&gt;
  iManufacturer           1 ARH&lt;br /&gt;
  iProduct                2 ARH CC-1&lt;br /&gt;
  iSerial                 3 E6614103E7452D2F&lt;br /&gt;
  ...&lt;br /&gt;
    Interface Descriptor:&lt;br /&gt;
      bInterfaceNumber        0&lt;br /&gt;
      bNumEndpoints           3&lt;br /&gt;
      bInterfaceClass       255 Vendor Specific Class&lt;br /&gt;
      bInterfaceSubClass      0&lt;br /&gt;
      bInterfaceProtocol      0&lt;br /&gt;
      Endpoint Descriptor:&lt;br /&gt;
        bEndpointAddress     0x01  EP 1 OUT&lt;br /&gt;
        bmAttributes            2&lt;br /&gt;
          Transfer Type            Bulk&lt;br /&gt;
        wMaxPacketSize     0x0040  1x 64 bytes&lt;br /&gt;
      Endpoint Descriptor:&lt;br /&gt;
        bEndpointAddress     0x81  EP 1 IN&lt;br /&gt;
        bmAttributes            2&lt;br /&gt;
          Transfer Type            Bulk&lt;br /&gt;
        wMaxPacketSize     0x0040  1x 64 bytes&lt;br /&gt;
      Endpoint Descriptor:&lt;br /&gt;
        bEndpointAddress     0x82  EP 2 IN&lt;br /&gt;
        bmAttributes            3&lt;br /&gt;
          Transfer Type            Interrupt&lt;br /&gt;
        wMaxPacketSize     0x0008  1x 8 bytes&lt;br /&gt;
        bInterval              10&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This CC-1 has one vendor-specific interface, with a bulk endpoint in each direction for its data, and an interrupt IN endpoint of 8 bytes for its events, which the host asks every 10 ms. Look at the descriptors of your own board: it has the same three endpoints, and what travels on the two bulk endpoints depends on your project.&lt;br /&gt;
&lt;br /&gt;
=== What every board answers ===&lt;br /&gt;
&lt;br /&gt;
Every board for our lab, for all projects, answers a small common set of control requests, and sends events in the same format. They are described in full in section 4 of the specification of your project. The example driver of this lab uses only these:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Request !! Number !! Direction !! wValue !! Data&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;GET_INFO&amp;lt;/code&amp;gt; || 0x00 || IN || 0 || 16 bytes: what the board is (below)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;IDENTIFY&amp;lt;/code&amp;gt; || 0xE0 || OUT || How many times to flash the LED, 1 to 10 || None&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;GET_BOARD_STATUS&amp;lt;/code&amp;gt; || 0xE1 || IN || 0 || 8 bytes: uptime, event counters, the button&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SET_LABEL&amp;lt;/code&amp;gt; || 0xE2 || OUT || 0 || 16 bytes: a name for the board, padded with zero bytes&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;GET_LABEL&amp;lt;/code&amp;gt; || 0xE3 || IN || 0 || 16 bytes: the name set before&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;GET_INFO&amp;lt;/code&amp;gt; starts with a &amp;#039;&amp;#039;&amp;#039;magic&amp;#039;&amp;#039;&amp;#039; number: the characters &amp;lt;code&amp;gt;&amp;quot;ARH&amp;quot;&amp;lt;/code&amp;gt;, which are the same on every board, followed by one character which names the project (&amp;lt;code&amp;gt;&amp;quot;ARH1&amp;quot;&amp;lt;/code&amp;gt; for the CC-1). Then come the version of the project&amp;#039;s protocol, the version of the firmware, and a few fields which the project defines.&lt;br /&gt;
&lt;br /&gt;
Each &amp;#039;&amp;#039;&amp;#039;event&amp;#039;&amp;#039;&amp;#039; is one 8-byte packet on the first interrupt IN endpoint: a type, an argument, a sequence number, and the time in milliseconds since the board was powered up. Type 0x01 is a short press of the button which the board has no other use for. The other types belong to the project.&lt;br /&gt;
&lt;br /&gt;
== A USB driver ==&lt;br /&gt;
&lt;br /&gt;
A USB driver is a &amp;lt;code&amp;gt;struct usb_driver&amp;lt;/code&amp;gt;, with a table of the devices which it can handle, and two functions which the USB core calls:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/usb.h&amp;gt;&lt;br /&gt;
struct usb_driver {&lt;br /&gt;
	const char *name;&lt;br /&gt;
	int (*probe)(struct usb_interface *intf, const struct usb_device_id *id);&lt;br /&gt;
	void (*disconnect)(struct usb_interface *intf);&lt;br /&gt;
	const struct usb_device_id *id_table;&lt;br /&gt;
	...&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
int usb_register(struct usb_driver *driver);&lt;br /&gt;
void usb_deregister(struct usb_driver *driver);&lt;br /&gt;
module_usb_driver(driver);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;module_usb_driver()&amp;lt;/code&amp;gt; writes the module&amp;#039;s init and exit functions for you: init registers the driver, exit deregisters it. A USB driver&amp;#039;s module usually has nothing else to do when it is loaded. All the work happens per device, in &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Which devices: the ID table ===&lt;br /&gt;
&lt;br /&gt;
When a device is plugged in, the USB core compares each of its interfaces with the ID table of every USB driver, and calls the &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; of the first driver which matches:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
/* The seven lab boards: vendor 0xcafe, one product ID per project */&lt;br /&gt;
static const struct usb_device_id arhboard_ids[] = {&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4301) },	/* CC-1 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4302) },	/* EL-2 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4303) },	/* FV-3 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4304) },	/* MB-4 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4305) },	/* TW-5 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4306) },	/* WP-6 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4307) },	/* BP-7 */&lt;br /&gt;
	{}&lt;br /&gt;
};&lt;br /&gt;
MODULE_DEVICE_TABLE(usb, arhboard_ids);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The table ends with an empty entry. A few macros fill in an entry:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Macro !! Matches&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;USB_DEVICE(vid, pid)&amp;lt;/code&amp;gt; || One product. The example lists the seven boards this way; the driver of your project has a single entry, with the PID of your board&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;USB_VENDOR_AND_INTERFACE_INFO(vid, class, subclass, protocol)&amp;lt;/code&amp;gt; || Every interface of that class, on every product of that vendor&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;USB_INTERFACE_INFO(class, subclass, protocol)&amp;lt;/code&amp;gt; || Every interface of that class, from any vendor: how the drivers of standard classes (keyboards, storage, ...) bind&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;MODULE_DEVICE_TABLE()&amp;lt;/code&amp;gt; copies the table into the module file. The system uses it to load the right module by itself when a device is plugged in. &amp;lt;code&amp;gt;modinfo&amp;lt;/code&amp;gt; shows it, as &amp;lt;code&amp;gt;alias&amp;lt;/code&amp;gt; lines.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Only one driver can own an interface. While &amp;lt;code&amp;gt;arhboard&amp;lt;/code&amp;gt; is loaded, it takes your board, and the driver of your project never gets a &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt;. Unload it first, with &amp;lt;code&amp;gt;sudo rmmod arhboard&amp;lt;/code&amp;gt;, and the other way around.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== probe() and disconnect() ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; is called once for each matching interface, when the device is plugged in, or when the driver is loaded with the device already there. It decides whether the driver takes the interface: it returns 0 to take it, or an error, usually &amp;lt;code&amp;gt;-ENODEV&amp;lt;/code&amp;gt;, to leave it. If it takes it, it should:&lt;br /&gt;
&lt;br /&gt;
# check that the interface has the endpoints which the driver expects;&lt;br /&gt;
# allocate a structure for this device, which keeps everything the driver knows about it. There may be several boards at once, so nothing about a board goes in a global variable;&lt;br /&gt;
# check that the device is really what the driver expects;&lt;br /&gt;
# attach its structure to the interface, with &amp;lt;code&amp;gt;usb_set_intfdata()&amp;lt;/code&amp;gt;, so that &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt; finds it again with &amp;lt;code&amp;gt;usb_get_intfdata()&amp;lt;/code&amp;gt;;&lt;br /&gt;
# make the device available to programs: here, a file in &amp;lt;code&amp;gt;/dev&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt; is called when the device is unplugged, or when the driver is unloaded. It cannot fail, and cannot stop the unplugging: when it is called, the device may already be gone. It undoes what &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; did. See [[#Unplugging|Unplugging]] for what happens to programs which still have the file open.&lt;br /&gt;
&lt;br /&gt;
Print with &amp;lt;code&amp;gt;dev_info()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;dev_err()&amp;lt;/code&amp;gt; and so on, with &amp;lt;code&amp;gt;&amp;amp;intf-&amp;gt;dev&amp;lt;/code&amp;gt;. The messages then start with the name of the driver and the place of the device on the bus, so that two boards can be told apart in the log:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
arhboard 1-1:1.0: project &amp;#039;1&amp;#039;, protocol 1.0, firmware 1.0, /dev/arhboard0&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Checking the endpoints ===&lt;br /&gt;
&lt;br /&gt;
The endpoints of our boards are fixed: every board has the three endpoints which &amp;lt;code&amp;gt;lsusb -v&amp;lt;/code&amp;gt; showed above, at the same addresses. So the driver does not search for them. It has their addresses as constants:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
/* The endpoints of every board: the addresses which lsusb -v shows */&lt;br /&gt;
#define EP_DATA_OUT 0x01 /* bulk OUT */&lt;br /&gt;
#define EP_DATA_IN 0x81  /* bulk IN */&lt;br /&gt;
#define EP_EVENT 0x82    /* interrupt IN: one event of 8 bytes */&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A device with the right VID and PID may still be something else, for example a board which runs other firmware, with other endpoints. Transfers to an endpoint which the device does not have would only fail later, in the middle of a file operation. So &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; first checks that the interface really has these endpoints, and refuses the device if it doesn&amp;#039;t. Two functions do the check:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/usb.h&amp;gt;&lt;br /&gt;
bool usb_check_bulk_endpoints(const struct usb_interface *intf, const u8 *ep_addrs);&lt;br /&gt;
bool usb_check_int_endpoints(const struct usb_interface *intf, const u8 *ep_addrs);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;ep_addrs&amp;lt;/code&amp;gt; is an array of endpoint addresses, which ends with 0. They return &amp;lt;code&amp;gt;true&amp;lt;/code&amp;gt; if the interface has an endpoint at every address in the array, and each of them is a bulk endpoint (or an interrupt endpoint, for the second function). The direction is part of the address, so it is checked too. The example checks its three endpoints at the start of &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt;, before it allocates anything:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
/* For usb_check_*_endpoints(): lists of addresses, which end with 0 */&lt;br /&gt;
static const u8 arhboard_bulk_eps[] = { EP_DATA_OUT, EP_DATA_IN, 0 };&lt;br /&gt;
static const u8 arhboard_int_eps[] = { EP_EVENT, 0 };&lt;br /&gt;
&lt;br /&gt;
static int arhboard_probe(struct usb_interface *intf,&lt;br /&gt;
			  const struct usb_device_id *id)&lt;br /&gt;
{&lt;br /&gt;
	...&lt;br /&gt;
	/* Does the interface have the endpoints which we expect? */&lt;br /&gt;
	if (!usb_check_bulk_endpoints(intf, arhboard_bulk_eps) ||&lt;br /&gt;
	    !usb_check_int_endpoints(intf, arhboard_int_eps)) {&lt;br /&gt;
		dev_err(&amp;amp;intf-&amp;gt;dev, &amp;quot;unexpected endpoints\n&amp;quot;);&lt;br /&gt;
		return -ENODEV;&lt;br /&gt;
	}&lt;br /&gt;
	...&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The example does not use the bulk endpoints, but every board has them, so it checks them as well. The driver of your project starts with the same check.&lt;br /&gt;
&lt;br /&gt;
=== One file per board ===&lt;br /&gt;
&lt;br /&gt;
In the last lab, we got a device number, a &amp;lt;code&amp;gt;struct cdev&amp;lt;/code&amp;gt; and a class in three steps. A USB driver does all three with one call:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/usb.h&amp;gt;&lt;br /&gt;
struct usb_class_driver {&lt;br /&gt;
	char *name;          /* &amp;quot;arhboard%d&amp;quot;: %d becomes 0, 1, ... */&lt;br /&gt;
	char *(*devnode)(const struct device *dev, umode_t *mode);&lt;br /&gt;
	const struct file_operations *fops;&lt;br /&gt;
	int minor_base;&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
int usb_register_dev(struct usb_interface *intf, struct usb_class_driver *class_driver);&lt;br /&gt;
void usb_deregister_dev(struct usb_interface *intf, struct usb_class_driver *class_driver);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;usb_register_dev()&amp;lt;/code&amp;gt; takes the next free minor number from &amp;lt;code&amp;gt;minor_base&amp;lt;/code&amp;gt; on, of major number 180, which the kernel keeps for USB devices. It sets &amp;lt;code&amp;gt;intf-&amp;gt;minor&amp;lt;/code&amp;gt;, and makes the device &amp;lt;code&amp;gt;arhboard0&amp;lt;/code&amp;gt; in the class &amp;lt;code&amp;gt;usbmisc&amp;lt;/code&amp;gt;, so that the file &amp;lt;code&amp;gt;/dev/arhboard0&amp;lt;/code&amp;gt; appears. A second board gets &amp;lt;code&amp;gt;/dev/arhboard1&amp;lt;/code&amp;gt;, and so on. The example uses minors from 192, and the driver of your project uses minors from 208, so that both can be loaded at once.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Major 180 is on OrbStack&amp;#039;s list of allowed numbers (see the last lab), so these files can be opened there too. OrbStack does not create them by itself, though: &amp;lt;code&amp;gt;make -C driver load&amp;lt;/code&amp;gt; creates them with &amp;lt;code&amp;gt;mknod&amp;lt;/code&amp;gt;, from &amp;lt;code&amp;gt;/sys/class/usbmisc/arhboardN/dev&amp;lt;/code&amp;gt;. For a board which you attach after loading the driver, run &amp;lt;code&amp;gt;make -C driver nodes&amp;lt;/code&amp;gt;.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;open()&amp;lt;/code&amp;gt; gets only the inode, and must find the board from its minor number. &amp;lt;code&amp;gt;usb_find_interface()&amp;lt;/code&amp;gt; returns the interface of this driver which has that minor:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
static int arhboard_open(struct inode *inode, struct file *file)&lt;br /&gt;
{&lt;br /&gt;
	struct usb_interface *intf;&lt;br /&gt;
	struct arhboard *dev;&lt;br /&gt;
&lt;br /&gt;
	intf = usb_find_interface(&amp;amp;arhboard_driver, iminor(inode));&lt;br /&gt;
	if (!intf)&lt;br /&gt;
		return -ENODEV;&lt;br /&gt;
	dev = usb_get_intfdata(intf);&lt;br /&gt;
	if (!dev)&lt;br /&gt;
		return -ENODEV;&lt;br /&gt;
&lt;br /&gt;
	kref_get(&amp;amp;dev-&amp;gt;kref);&lt;br /&gt;
	file-&amp;gt;private_data = dev;&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
From then on, every file operation finds the board in &amp;lt;code&amp;gt;file-&amp;gt;private_data&amp;lt;/code&amp;gt;, as in the last lab. &amp;lt;code&amp;gt;kref_get()&amp;lt;/code&amp;gt; is explained in [[#Unplugging|Unplugging]].&lt;br /&gt;
&lt;br /&gt;
A device which is a &amp;#039;&amp;#039;&amp;#039;stream&amp;#039;&amp;#039;&amp;#039;, with no position to seek to (most project boards), should say so in its &amp;lt;code&amp;gt;open()&amp;lt;/code&amp;gt;, by ending it with &amp;lt;code&amp;gt;stream_open()&amp;lt;/code&amp;gt; (from &amp;lt;code&amp;gt;&amp;amp;lt;linux/fs.h&amp;amp;gt;&amp;lt;/code&amp;gt;) instead of &amp;lt;code&amp;gt;return 0&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
	file-&amp;gt;private_data = dev;&lt;br /&gt;
	return stream_open(inode, file);   /* always returns 0 */&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;lseek()&amp;lt;/code&amp;gt; on the file then fails with &amp;lt;code&amp;gt;ESPIPE&amp;lt;/code&amp;gt;, and so do &amp;lt;code&amp;gt;pread()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;pwrite()&amp;lt;/code&amp;gt;, which take a position. Your device is a stream unless its data has positions which a program can jump to. (The example has no &amp;lt;code&amp;gt;llseek&amp;lt;/code&amp;gt; function, so &amp;lt;code&amp;gt;lseek()&amp;lt;/code&amp;gt; already fails on it; it leaves &amp;lt;code&amp;gt;stream_open()&amp;lt;/code&amp;gt; out to stay short.)&lt;br /&gt;
&lt;br /&gt;
== Talking to the device ==&lt;br /&gt;
&lt;br /&gt;
=== Buffers ===&lt;br /&gt;
&lt;br /&gt;
The USB controller moves the data of a transfer to and from memory by itself, with &amp;#039;&amp;#039;&amp;#039;DMA&amp;#039;&amp;#039;&amp;#039;, without the processor. It can only do that with memory from &amp;lt;code&amp;gt;kmalloc()&amp;lt;/code&amp;gt;. &amp;#039;&amp;#039;&amp;#039;A transfer buffer must never be on the stack, or a global variable&amp;#039;&amp;#039;&amp;#039;: the transfer may fail, or corrupt memory next to the buffer, and on some machines it seems to work, until it doesn&amp;#039;t.&lt;br /&gt;
&lt;br /&gt;
The example allocates its buffers once, in &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt;, and keeps them in its structure:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
	dev-&amp;gt;ctrl_buf = kmalloc(CTRL_BUF_LEN, GFP_KERNEL);&lt;br /&gt;
	dev-&amp;gt;ev_buf = kmalloc(sizeof(struct wire_event), GFP_KERNEL);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A buffer which is used by one transfer at a time, like these, needs a lock: see [[#Locking|Locking]].&lt;br /&gt;
&lt;br /&gt;
=== Byte order ===&lt;br /&gt;
&lt;br /&gt;
All the numbers which our boards send and receive are &amp;#039;&amp;#039;&amp;#039;little-endian&amp;#039;&amp;#039;&amp;#039;: the lowest byte comes first. Most processors which run Linux are little-endian too, but not all of them, and a driver must work on any machine. The kernel has types which say the byte order of a value, and functions which convert it to and from the byte order of the machine:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;asm/byteorder.h&amp;gt;, which most kernel headers include&lt;br /&gt;
u16 le16_to_cpu(__le16 x);    __le16 cpu_to_le16(u16 x);&lt;br /&gt;
u32 le32_to_cpu(__le32 x);    __le32 cpu_to_le32(u32 x);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
On a little-endian machine, they do nothing, and cost nothing. Describe what the device sends with a structure of these types, and convert each field when you use it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
/* What the board sends, exactly as it is on the wire: little-endian */&lt;br /&gt;
struct wire_event {&lt;br /&gt;
	u8 type;&lt;br /&gt;
	u8 arg;&lt;br /&gt;
	__le16 seq;&lt;br /&gt;
	__le32 time_ms;&lt;br /&gt;
};&lt;br /&gt;
static_assert(sizeof(struct wire_event) == 8);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The structure must be exactly the 8 bytes that the board sends. If the compiler added padding between the fields, it would not be, and &amp;lt;code&amp;gt;static_assert()&amp;lt;/code&amp;gt; catches that when you build. &amp;lt;code&amp;gt;__le16&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;__le32&amp;lt;/code&amp;gt; mark the fields which are in the board&amp;#039;s byte order: read them with &amp;lt;code&amp;gt;le16_to_cpu()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;le32_to_cpu()&amp;lt;/code&amp;gt;, never directly.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Keep the structures of the wire and the structures of the shared header apart. The wire structures are what the device sends, in its byte order. The structures in &amp;lt;code&amp;gt;uapi/&amp;lt;/code&amp;gt; are what the driver gives to programs, in the byte order of the machine, with the &amp;lt;code&amp;gt;__u8&amp;lt;/code&amp;gt; ... &amp;lt;code&amp;gt;__u32&amp;lt;/code&amp;gt; types of the last lab. The driver converts one into the other, field by field. Never copy the bytes from the device straight to user space.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Blocking calls ===&lt;br /&gt;
&lt;br /&gt;
The kernel has one function for each transfer type, which sends the transfer, waits until it ends, and returns:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/usb.h&amp;gt;&lt;br /&gt;
int usb_control_msg(struct usb_device *dev, unsigned int pipe,&lt;br /&gt;
	__u8 request, __u8 requesttype, __u16 value, __u16 index,&lt;br /&gt;
	void *data, __u16 size, int timeout);&lt;br /&gt;
int usb_interrupt_msg(struct usb_device *dev, unsigned int pipe,&lt;br /&gt;
	void *data, int len, int *actual_length, int timeout);&lt;br /&gt;
int usb_bulk_msg(struct usb_device *dev, unsigned int pipe,&lt;br /&gt;
	void *data, int len, int *actual_length, int timeout);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;dev&amp;lt;/code&amp;gt; is the &amp;lt;code&amp;gt;struct usb_device&amp;lt;/code&amp;gt; of the whole device, which &amp;lt;code&amp;gt;interface_to_usbdev(intf)&amp;lt;/code&amp;gt; returns. The example keeps it in its structure, as &amp;lt;code&amp;gt;dev-&amp;gt;udev&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;pipe&amp;lt;/code&amp;gt; says where the transfer goes. It is not the address of the endpoint alone, but a number which combines the device, the endpoint, its direction and its type. A macro for each kind of endpoint makes it, and we write it directly in the call:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Endpoint !! IN !! OUT&lt;br /&gt;
|-&lt;br /&gt;
| Control (endpoint 0) || &amp;lt;code&amp;gt;usb_rcvctrlpipe(udev, 0)&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;usb_sndctrlpipe(udev, 0)&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| Bulk || &amp;lt;code&amp;gt;usb_rcvbulkpipe(udev, EP_DATA_IN)&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;usb_sndbulkpipe(udev, EP_DATA_OUT)&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| Interrupt || &amp;lt;code&amp;gt;usb_rcvintpipe(udev, EP_EVENT)&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;usb_sndintpipe(udev, addr)&amp;lt;/code&amp;gt;: our boards have none&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;timeout&amp;lt;/code&amp;gt; is in milliseconds. They sleep, so they can only be called where sleeping is allowed: in file operations, in &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; and in &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt;, but not while holding a spinlock. They return a negative error if the transfer failed, and &amp;lt;code&amp;gt;-ETIMEDOUT&amp;lt;/code&amp;gt; in particular if the device did not respond in time. &amp;lt;code&amp;gt;usb_control_msg()&amp;lt;/code&amp;gt; returns the number of bytes moved. The other two return 0, and store the number of bytes moved in &amp;lt;code&amp;gt;*actual_length&amp;lt;/code&amp;gt;. &amp;#039;&amp;#039;&amp;#039;It can be less than you asked for&amp;#039;&amp;#039;&amp;#039;, and a driver should always check it. They store it when they fail, too: see [[#A slice which times out may have moved data|A slice which times out may have moved data]].&lt;br /&gt;
&lt;br /&gt;
The errors which you will meet most often:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Error !! Meaning !! What to do&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-EPIPE&amp;lt;/code&amp;gt; || The device answered with STALL: it refused the request, or the endpoint is halted || For a control request, return it to the program: the request was refused. For a bulk endpoint, see [[#Halted endpoints|Halted endpoints]]&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-ETIMEDOUT&amp;lt;/code&amp;gt; || The device did not finish in time: for an IN endpoint, it had nothing to send || Wait again, or give up: see below&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-EOVERFLOW&amp;lt;/code&amp;gt; || The device sent more than the buffer can hold || Use a buffer of whole packets: see [[#Bulk transfers|Bulk transfers]]&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-EPROTO&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;-EILSEQ&amp;lt;/code&amp;gt; || The packet was damaged on the cable || Return an error. It is rare, unless the cable is bad&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-ENODEV&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;-ESHUTDOWN&amp;lt;/code&amp;gt; || The device is gone || Return &amp;lt;code&amp;gt;-ENODEV&amp;lt;/code&amp;gt; to userspace&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=== Waiting for a long time ===&lt;br /&gt;
&lt;br /&gt;
Some calls must wait for as long as it takes: a program which reads an event waits until somebody presses the button, maybe forever. A transfer with a very long timeout would do that, but then nothing could stop it. The blocking calls cannot be interrupted: they return only when the transfer ends or its timeout runs out, and a signal does not wake them. So Ctrl+C would do nothing, the process could not even be killed while it waits, and every other call which needs the same lock would wait behind it.&lt;br /&gt;
&lt;br /&gt;
So &amp;#039;&amp;#039;&amp;#039;a long wait is a loop of short waits&amp;#039;&amp;#039;&amp;#039;. Each transfer has a short timeout, 100 ms in the example. When it times out, the loop checks what may have happened meanwhile, and starts another one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
	for (;;) {&lt;br /&gt;
		if (mutex_lock_interruptible(&amp;amp;dev-&amp;gt;ev_lock))&lt;br /&gt;
			return -ERESTARTSYS;&lt;br /&gt;
		if (dev-&amp;gt;gone)&lt;br /&gt;
			ret = -ENODEV;&lt;br /&gt;
		else&lt;br /&gt;
			ret = usb_interrupt_msg(dev-&amp;gt;udev,&lt;br /&gt;
						usb_rcvintpipe(dev-&amp;gt;udev, EP_EVENT),&lt;br /&gt;
						dev-&amp;gt;ev_buf, sizeof(struct wire_event),&lt;br /&gt;
						&amp;amp;actual, SLICE_MS);&lt;br /&gt;
		/* ... use the data while we still hold the lock ... */&lt;br /&gt;
		mutex_unlock(&amp;amp;dev-&amp;gt;ev_lock);&lt;br /&gt;
&lt;br /&gt;
		if (ret != -ETIMEDOUT)&lt;br /&gt;
			break;          /* the data, or a real error */&lt;br /&gt;
		/* No event in this slice */&lt;br /&gt;
		if (file-&amp;gt;f_flags &amp;amp; O_NONBLOCK)&lt;br /&gt;
			return -EAGAIN;&lt;br /&gt;
		if (signal_pending(current))&lt;br /&gt;
			return -ERESTARTSYS;&lt;br /&gt;
	}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Between two slices:&lt;br /&gt;
&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Signals.&amp;#039;&amp;#039;&amp;#039; &amp;lt;code&amp;gt;signal_pending(current)&amp;lt;/code&amp;gt; is true when the process has a signal waiting, for example after Ctrl+C. Returning &amp;lt;code&amp;gt;-ERESTARTSYS&amp;lt;/code&amp;gt; lets the kernel deliver it. The program sees &amp;lt;code&amp;gt;EINTR&amp;lt;/code&amp;gt;, or, if it is stopped and continued, the call starts again by itself. &amp;lt;code&amp;gt;mutex_lock_interruptible()&amp;lt;/code&amp;gt; does the same while it waits for the lock.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;&amp;lt;code&amp;gt;O_NONBLOCK&amp;lt;/code&amp;gt;.&amp;#039;&amp;#039;&amp;#039; A program which opened the file with &amp;lt;code&amp;gt;O_NONBLOCK&amp;lt;/code&amp;gt; does not want to wait. It gets one slice, and then &amp;lt;code&amp;gt;EAGAIN&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;The lock is free&amp;#039;&amp;#039;&amp;#039;, so another call, or &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt;, can take it. Never wait for longer than one slice while holding a lock.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Unplugging.&amp;#039;&amp;#039;&amp;#039; &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt; sets &amp;lt;code&amp;gt;gone&amp;lt;/code&amp;gt;, and the loop notices it at the next slice.&lt;br /&gt;
&lt;br /&gt;
None of this needs anything new in the kernel: only a loop, and the mutex of the last lab. Every call of your driver which may wait for long should use this pattern.&lt;br /&gt;
&lt;br /&gt;
== Control transfers ==&lt;br /&gt;
&lt;br /&gt;
A control request starts with an 8-byte &amp;#039;&amp;#039;&amp;#039;setup packet&amp;#039;&amp;#039;&amp;#039;, which the host sends to endpoint 0. Its fields are the arguments of &amp;lt;code&amp;gt;usb_control_msg()&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Field !! Argument !! Meaning&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;bmRequestType&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;requesttype&amp;lt;/code&amp;gt; || The direction of the data, who defined the request, and who it is for: see below&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;bRequest&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;request&amp;lt;/code&amp;gt; || The number of the request&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;wValue&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;value&amp;lt;/code&amp;gt; || A 16-bit argument, defined by the request&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;wIndex&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;index&amp;lt;/code&amp;gt; || Another 16-bit argument. For a request to an interface, the number of the interface&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;wLength&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;size&amp;lt;/code&amp;gt; || The number of bytes in the data stage. May be 0&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
After the setup packet comes the &amp;#039;&amp;#039;&amp;#039;data stage&amp;#039;&amp;#039;&amp;#039;, &amp;lt;code&amp;gt;wLength&amp;lt;/code&amp;gt; bytes in the direction which &amp;lt;code&amp;gt;bmRequestType&amp;lt;/code&amp;gt; gives, and then the device confirms that it has finished. If it refuses the request, it answers with STALL instead, and &amp;lt;code&amp;gt;usb_control_msg()&amp;lt;/code&amp;gt; returns &amp;lt;code&amp;gt;-EPIPE&amp;lt;/code&amp;gt;. This is not a problem with the device: it is its way of saying no.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;bmRequestType&amp;lt;/code&amp;gt; is made of three parts, with a macro for each:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Part !! Our boards !! Other values&lt;br /&gt;
|-&lt;br /&gt;
| Direction || &amp;lt;code&amp;gt;USB_DIR_IN&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;USB_DIR_OUT&amp;lt;/code&amp;gt; ||&lt;br /&gt;
|-&lt;br /&gt;
| Type || &amp;lt;code&amp;gt;USB_TYPE_VENDOR&amp;lt;/code&amp;gt;: a request which the maker of the device defined || &amp;lt;code&amp;gt;USB_TYPE_STANDARD&amp;lt;/code&amp;gt;, which every device answers, and &amp;lt;code&amp;gt;USB_TYPE_CLASS&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| Recipient || &amp;lt;code&amp;gt;USB_RECIP_INTERFACE&amp;lt;/code&amp;gt;: for interface 0 || &amp;lt;code&amp;gt;USB_RECIP_DEVICE&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;USB_RECIP_ENDPOINT&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
For the requests of our boards, &amp;lt;code&amp;gt;bmRequestType&amp;lt;/code&amp;gt; is 0xC1 for IN, and 0x41 for OUT. The example wraps &amp;lt;code&amp;gt;usb_control_msg()&amp;lt;/code&amp;gt; in two functions, one for each direction. The data is always in &amp;lt;code&amp;gt;dev-&amp;gt;ctrl_buf&amp;lt;/code&amp;gt;, which comes from &amp;lt;code&amp;gt;kmalloc()&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
#define REQTYPE_IN (USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_INTERFACE)   /* 0xC1 */&lt;br /&gt;
#define REQTYPE_OUT (USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE) /* 0x41 */&lt;br /&gt;
&lt;br /&gt;
static int arhboard_ctrl_in(struct arhboard *dev, u8 request, u16 len)&lt;br /&gt;
{&lt;br /&gt;
	int ret = usb_control_msg(dev-&amp;gt;udev, usb_rcvctrlpipe(dev-&amp;gt;udev, 0),&lt;br /&gt;
				  request, REQTYPE_IN, 0, 0, dev-&amp;gt;ctrl_buf, len,&lt;br /&gt;
				  CTRL_TIMEOUT_MS);&lt;br /&gt;
	if (ret &amp;lt; 0)&lt;br /&gt;
		return ret; /* -EPIPE: the board refused (STALL) */&lt;br /&gt;
	if (ret != len)&lt;br /&gt;
		return -EPROTO; /* a short answer is an error too */&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static int arhboard_ctrl_out(struct arhboard *dev, u8 request, u16 value,&lt;br /&gt;
			     u16 len)&lt;br /&gt;
{&lt;br /&gt;
	int ret = usb_control_msg(dev-&amp;gt;udev, usb_sndctrlpipe(dev-&amp;gt;udev, 0),&lt;br /&gt;
				  request, REQTYPE_OUT, value, 0,&lt;br /&gt;
				  len ? dev-&amp;gt;ctrl_buf : NULL, len,&lt;br /&gt;
				  CTRL_TIMEOUT_MS);&lt;br /&gt;
	if (ret &amp;lt; 0)&lt;br /&gt;
		return ret;&lt;br /&gt;
	if (ret != len)&lt;br /&gt;
		return -EPROTO;&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A control request is short, so it doesn&amp;#039;t need the loop of the last section: one transfer with a timeout of a second is enough.&lt;br /&gt;
&lt;br /&gt;
=== Checking the device in probe() ===&lt;br /&gt;
&lt;br /&gt;
The vendor ID &amp;lt;code&amp;gt;0xcafe&amp;lt;/code&amp;gt; is not registered, so another device could use it too, even with the same product ID. Before it takes the interface, &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; asks the board what it is, with &amp;lt;code&amp;gt;GET_INFO&amp;lt;/code&amp;gt;, and refuses it if the magic does not start with &amp;lt;code&amp;gt;&amp;quot;ARH&amp;quot;&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
	ret = arhboard_ctrl_in(dev, REQ_GET_INFO, sizeof(struct wire_info));&lt;br /&gt;
	if (ret) {&lt;br /&gt;
		dev_err(&amp;amp;intf-&amp;gt;dev, &amp;quot;GET_INFO failed: %pe\n&amp;quot;, ERR_PTR(ret));&lt;br /&gt;
		goto err;&lt;br /&gt;
	}&lt;br /&gt;
	info_from_wire(&amp;amp;info, (struct wire_info *)dev-&amp;gt;ctrl_buf);&lt;br /&gt;
	if ((info.magic &amp;amp; 0x00ffffff) != MAGIC_ARH) {&lt;br /&gt;
		dev_err(&amp;amp;intf-&amp;gt;dev, &amp;quot;not a lab board (magic 0x%08x)\n&amp;quot;,&lt;br /&gt;
			info.magic);&lt;br /&gt;
		ret = -ENODEV;&lt;br /&gt;
		goto err;&lt;br /&gt;
	}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The driver of your project should check the whole magic, and the major version of its protocol, and refuse a board which runs other firmware.&lt;br /&gt;
&lt;br /&gt;
=== Control requests as ioctls ===&lt;br /&gt;
&lt;br /&gt;
A request which returns a structure, or takes a number, fits an &amp;lt;code&amp;gt;ioctl()&amp;lt;/code&amp;gt;. The example has one for each common request, in its shared header:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
#define ARHBOARD_IOC_MAGIC 0xB8&lt;br /&gt;
#define ARHBOARD_IOC_GET_INFO   _IOR(ARHBOARD_IOC_MAGIC, 1, struct arhboard_info)&lt;br /&gt;
#define ARHBOARD_IOC_GET_STATUS _IOR(ARHBOARD_IOC_MAGIC, 2, struct arhboard_status)&lt;br /&gt;
#define ARHBOARD_IOC_GET_LABEL  _IOR(ARHBOARD_IOC_MAGIC, 3, struct arhboard_label)&lt;br /&gt;
/* Flash the LED: 1 to 10 times. Anything else is refused by the board (EPIPE). */&lt;br /&gt;
#define ARHBOARD_IOC_IDENTIFY   _IOW(ARHBOARD_IOC_MAGIC, 4, __u32)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
They show the three kinds of control request:&lt;br /&gt;
&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;IN, with data&amp;#039;&amp;#039;&amp;#039;: &amp;lt;code&amp;gt;GET_INFO&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;GET_BOARD_STATUS&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;GET_LABEL&amp;lt;/code&amp;gt;. The driver reads the reply into &amp;lt;code&amp;gt;ctrl_buf&amp;lt;/code&amp;gt;, converts it into the structure of the shared header, and copies that to the program;&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;OUT, with no data&amp;#039;&amp;#039;&amp;#039;: &amp;lt;code&amp;gt;IDENTIFY&amp;lt;/code&amp;gt;. The number of flashes travels in &amp;lt;code&amp;gt;wValue&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;wLength&amp;lt;/code&amp;gt; is 0;&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;OUT, with data&amp;#039;&amp;#039;&amp;#039;: &amp;lt;code&amp;gt;SET_LABEL&amp;lt;/code&amp;gt;, which the example does in &amp;lt;code&amp;gt;write()&amp;lt;/code&amp;gt;: &amp;lt;code&amp;gt;echo bench-3 &amp;gt; /dev/arhboard0&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
	case ARHBOARD_IOC_GET_STATUS: {&lt;br /&gt;
		struct wire_status *w = (struct wire_status *)dev-&amp;gt;ctrl_buf;&lt;br /&gt;
&lt;br /&gt;
		ret = arhboard_ctrl_in(dev, REQ_GET_BOARD_STATUS, sizeof(*w));&lt;br /&gt;
		if (ret)&lt;br /&gt;
			break;&lt;br /&gt;
		out.status.uptime_ms = le32_to_cpu(w-&amp;gt;uptime_ms);&lt;br /&gt;
		out.status.events_dropped = le16_to_cpu(w-&amp;gt;events_dropped);&lt;br /&gt;
		out.status.events_queued = w-&amp;gt;events_queued;&lt;br /&gt;
		out.status.button_down = w-&amp;gt;button_down;&lt;br /&gt;
		out_len = sizeof(out.status);&lt;br /&gt;
		break;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	case ARHBOARD_IOC_IDENTIFY:&lt;br /&gt;
		/* No data stage: the number travels in wValue */&lt;br /&gt;
		ret = arhboard_ctrl_out(dev, REQ_IDENTIFY, flashes, 0);&lt;br /&gt;
		break;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The driver does not check the number of flashes: the board does, and refuses 0 or more than 10 with a STALL. The program then gets &amp;lt;code&amp;gt;EPIPE&amp;lt;/code&amp;gt;. Try it: this is what a refused request looks like, and the requests of your project will be refused in the same way.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; With two boards, &amp;lt;code&amp;gt;IDENTIFY&amp;lt;/code&amp;gt; tells you which file is which board: the LED of the board behind &amp;lt;code&amp;gt;/dev/arhboard1&amp;lt;/code&amp;gt; flashes when you send it to &amp;lt;code&amp;gt;/dev/arhboard1&amp;lt;/code&amp;gt;.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Interrupt transfers: events ==&lt;br /&gt;
&lt;br /&gt;
=== The board keeps the events ===&lt;br /&gt;
&lt;br /&gt;
The host gets an event only when it reads the interrupt endpoint. What happens to the events which come while nobody reads? Our boards keep them: each board has a queue of &amp;lt;code&amp;gt;event_queue_len&amp;lt;/code&amp;gt; events (a field of &amp;lt;code&amp;gt;GET_INFO&amp;lt;/code&amp;gt;), and sends the oldest one each time the host reads. So &amp;#039;&amp;#039;&amp;#039;the driver only needs to read the endpoint when a program asks for an event&amp;#039;&amp;#039;&amp;#039;, and nothing is lost meanwhile.&lt;br /&gt;
&lt;br /&gt;
If nobody reads for a long time, the queue fills up. The board then drops an old event to make room (the oldest one which is not already on its way to the host), and counts it in &amp;lt;code&amp;gt;events_dropped&amp;lt;/code&amp;gt; (in &amp;lt;code&amp;gt;GET_BOARD_STATUS&amp;lt;/code&amp;gt;). Each event has a sequence number, which goes up by one for every event the board makes, so a program sees a gap where events were lost.&lt;br /&gt;
&lt;br /&gt;
=== read() waits for the next event ===&lt;br /&gt;
&lt;br /&gt;
In the example, &amp;lt;code&amp;gt;read()&amp;lt;/code&amp;gt; waits for the next event, with the loop of [[#Waiting for a long time|Waiting for a long time]], and returns it as one line of text. Any program which reads lines can then show the events:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ cat /dev/arhboard0&lt;br /&gt;
seq=0 time=48213 type=0x01 arg=0&lt;br /&gt;
seq=1 time=51007 type=0x01 arg=0&lt;br /&gt;
^C&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Each line is one short press of the button, and Ctrl+C stops &amp;lt;code&amp;gt;cat&amp;lt;/code&amp;gt; at once, because the driver checks for signals between its slices. The line is made with &amp;lt;code&amp;gt;scnprintf()&amp;lt;/code&amp;gt;, which works like &amp;lt;code&amp;gt;snprintf()&amp;lt;/code&amp;gt;, but returns the number of characters it actually wrote. The fields are converted from little-endian first:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
			if (ret == 0 &amp;amp;&amp;amp; actual != sizeof(*wev))&lt;br /&gt;
				ret = -EPROTO;&lt;br /&gt;
			if (ret == 0)&lt;br /&gt;
				len = scnprintf(line, sizeof(line),&lt;br /&gt;
						&amp;quot;seq=%u time=%u type=0x%02x arg=%u\n&amp;quot;,&lt;br /&gt;
						le16_to_cpu(wev-&amp;gt;seq),&lt;br /&gt;
						le32_to_cpu(wev-&amp;gt;time_ms),&lt;br /&gt;
						wev-&amp;gt;type, wev-&amp;gt;arg);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A real program would rather have the event as a structure, from an &amp;lt;code&amp;gt;ioctl()&amp;lt;/code&amp;gt;: text is used here only so that &amp;lt;code&amp;gt;cat&amp;lt;/code&amp;gt; works. The events of your project, and what their type and argument mean, are in the specification of your project. The example prints them as raw numbers: on a CC-1, a long press shows type 0x05.&lt;br /&gt;
&lt;br /&gt;
A short press is type 0x01 only on a board which has no other use for the button: a CC-1, an EL-2 which is not logging, or an FV-3. On the other boards, the press does its job, and you see that event instead: a lap (type 0x05) on a TW-5; a scan which starts (0x02) and, a few seconds later, ends (0x03) on a WP-6 or a BP-7; and on an MB-4, a quick tap is keyed as the letter E (type 0x03, arg 69), followed 3 s later by the space which ends the word (type 0x03, arg 32).&lt;br /&gt;
&lt;br /&gt;
== Bulk transfers ==&lt;br /&gt;
&lt;br /&gt;
The common requests do not use the bulk endpoints, so neither does the example. The data of your project goes through its bulk endpoints, with &amp;lt;code&amp;gt;usb_bulk_msg()&amp;lt;/code&amp;gt;, in the loop of [[#Waiting for a long time|Waiting for a long time]] whenever the device may take long to answer. A few rules come from the way bulk data travels.&lt;br /&gt;
&lt;br /&gt;
=== Packets, short packets and ZLPs ===&lt;br /&gt;
&lt;br /&gt;
A bulk transfer is cut into packets of at most 64 bytes. The receiver knows that a transfer has ended when a packet is &amp;#039;&amp;#039;&amp;#039;short&amp;#039;&amp;#039;&amp;#039;: less than 64 bytes. A transfer of 150 bytes is sent as 64 + 64 + 22 bytes, and the 22-byte packet ends it.&lt;br /&gt;
&lt;br /&gt;
A transfer whose size is an exact multiple of 64 has no short packet at its end. Then the sender adds a &amp;#039;&amp;#039;&amp;#039;zero-length packet&amp;#039;&amp;#039;&amp;#039; (&amp;#039;&amp;#039;&amp;#039;ZLP&amp;#039;&amp;#039;&amp;#039;), which carries no data, only to say that the transfer is over. A &amp;lt;code&amp;gt;usb_bulk_msg()&amp;lt;/code&amp;gt; on an IN endpoint which receives a ZLP returns 0 with &amp;lt;code&amp;gt;*actual_length&amp;lt;/code&amp;gt; 0. Whether your device sends ZLPs, and when, is in the specification of your project. A driver usually skips them.&lt;br /&gt;
&lt;br /&gt;
An IN transfer also ends when the buffer is full. So &amp;#039;&amp;#039;&amp;#039;one &amp;lt;code&amp;gt;usb_bulk_msg()&amp;lt;/code&amp;gt; may return less than the device has to send&amp;#039;&amp;#039;&amp;#039;, and the rest comes with the next call.&lt;br /&gt;
&lt;br /&gt;
=== Read whole packets ===&lt;br /&gt;
&lt;br /&gt;
The host cannot ask the device for 10 bytes: it asks for a packet, and the device sends up to 64. If it sends more than the buffer can hold, the transfer fails with &amp;lt;code&amp;gt;-EOVERFLOW&amp;lt;/code&amp;gt;, and the data is lost. So the buffer of an IN transfer should always hold whole packets: a multiple of 64 bytes, the maximum packet size of our bulk endpoints.&lt;br /&gt;
&lt;br /&gt;
A &amp;lt;code&amp;gt;read()&amp;lt;/code&amp;gt; of any size then needs a buffer of its own in the driver: read whole packets into it, give the program what it asked for, and keep the rest for the next &amp;lt;code&amp;gt;read()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
	/* in_buf: kmalloc()ed, a multiple of 64 bytes */&lt;br /&gt;
	ret = usb_bulk_msg(dev-&amp;gt;udev, usb_rcvbulkpipe(dev-&amp;gt;udev, EP_DATA_IN),&lt;br /&gt;
			   dev-&amp;gt;in_buf, IN_BUF_LEN, &amp;amp;actual, SLICE_MS);&lt;br /&gt;
	if (ret == 0 || ret == -ETIMEDOUT) {&lt;br /&gt;
		/* actual bytes in in_buf: 0 for a ZLP, or less than the device has */&lt;br /&gt;
	}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== A slice which times out may have moved data ===&lt;br /&gt;
&lt;br /&gt;
A transfer of several packets can stop halfway: the device sends or takes a few packets, then answers NAK until the slice runs out. &amp;lt;code&amp;gt;usb_bulk_msg()&amp;lt;/code&amp;gt; then returns &amp;lt;code&amp;gt;-ETIMEDOUT&amp;lt;/code&amp;gt;, but &amp;lt;code&amp;gt;*actual_length&amp;lt;/code&amp;gt; still says how many bytes were moved, and those bytes are done: the device will not send them again, and it has already taken the ones you wrote. So after a timeout:&lt;br /&gt;
&lt;br /&gt;
* on an IN endpoint, keep the &amp;lt;code&amp;gt;actual&amp;lt;/code&amp;gt; bytes which arrived;&lt;br /&gt;
* on an OUT endpoint, go on from &amp;lt;code&amp;gt;buf + actual&amp;lt;/code&amp;gt; in the next slice, and never send the same bytes twice.&lt;br /&gt;
&lt;br /&gt;
A driver which treats &amp;lt;code&amp;gt;-ETIMEDOUT&amp;lt;/code&amp;gt; as &amp;quot;nothing happened&amp;quot; loses or repeats data. The simplest way to avoid the question is to move one packet (at most 64 bytes) in each transfer: a single packet either goes through, or does not.&lt;br /&gt;
&lt;br /&gt;
=== Halted endpoints ===&lt;br /&gt;
&lt;br /&gt;
A device can &amp;#039;&amp;#039;&amp;#039;halt&amp;#039;&amp;#039;&amp;#039; a bulk endpoint, for example after an error in the data. Every transfer on it then fails with &amp;lt;code&amp;gt;-EPIPE&amp;lt;/code&amp;gt;, until the host clears the halt:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/usb.h&amp;gt;&lt;br /&gt;
int usb_clear_halt(struct usb_device *dev, int pipe);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;pipe&amp;lt;/code&amp;gt; is made as for a transfer: &amp;lt;code&amp;gt;usb_clear_halt(dev-&amp;gt;udev, usb_rcvbulkpipe(dev-&amp;gt;udev, EP_DATA_IN))&amp;lt;/code&amp;gt;. The example driver does not use the bulk endpoints, so it never needs this, but most project boards refuse bulk data in some states, with a STALL. When to clear the halt, and what else the device expects before it works again, is in the specification of your project.&lt;br /&gt;
&lt;br /&gt;
== Locking ==&lt;br /&gt;
&lt;br /&gt;
Several programs, or several threads, can use the same board at once, and each file operation uses the device and its buffers. As in the last lab, a mutex protects them. A transfer can take long, though, and while one file operation waits on an endpoint, the others should not wait behind it if they don&amp;#039;t need that endpoint. So &amp;#039;&amp;#039;&amp;#039;take one mutex for each thing which can be used on its own&amp;#039;&amp;#039;&amp;#039;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
struct arhboard {&lt;br /&gt;
	struct usb_device *udev;&lt;br /&gt;
	struct usb_interface *intf;&lt;br /&gt;
	struct kref kref; /* probe() holds one reference, each open file one */&lt;br /&gt;
&lt;br /&gt;
	struct mutex ctrl_lock; /* control transfers, ctrl_buf */&lt;br /&gt;
	u8 *ctrl_buf;           /* kmalloc()ed: the controller reads it by DMA */&lt;br /&gt;
&lt;br /&gt;
	struct mutex ev_lock; /* the event endpoint, ev_buf */&lt;br /&gt;
	u8 *ev_buf;&lt;br /&gt;
&lt;br /&gt;
	bool gone; /* unplugged: written under both locks */&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
While &amp;lt;code&amp;gt;cat&amp;lt;/code&amp;gt; waits for an event, holding &amp;lt;code&amp;gt;ev_lock&amp;lt;/code&amp;gt; for one slice at a time, an &amp;lt;code&amp;gt;ioctl()&amp;lt;/code&amp;gt; takes &amp;lt;code&amp;gt;ctrl_lock&amp;lt;/code&amp;gt;, and its control request goes through at once. A driver with bulk endpoints usually adds one mutex for each direction. Two calls which both read events take turns, one slice each, and each event goes to only one of them.&lt;br /&gt;
&lt;br /&gt;
== Unplugging ==&lt;br /&gt;
&lt;br /&gt;
A board can be unplugged at any moment: while a program has its file open, or even while a call waits on one of its endpoints. &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt; is then called, and must not wait for the programs to close their files, which may never happen. But the structure of the board cannot be freed while open files still point to it.&lt;br /&gt;
&lt;br /&gt;
The solution has two parts.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;The structure is reference counted&amp;#039;&amp;#039;&amp;#039;, with a &amp;lt;code&amp;gt;struct kref&amp;lt;/code&amp;gt;: a counter of how many users the structure has, kept as a member of the structure itself, like the &amp;lt;code&amp;gt;struct list_head&amp;lt;/code&amp;gt; of the last lab.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/kref.h&amp;gt;&lt;br /&gt;
void kref_init(struct kref *kref);    // The count starts at 1&lt;br /&gt;
void kref_get(struct kref *kref);     // One more user&lt;br /&gt;
int kref_put(struct kref *kref, void (*release)(struct kref *kref)); // One user less&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;kref_put()&amp;lt;/code&amp;gt; calls &amp;lt;code&amp;gt;release&amp;lt;/code&amp;gt; when the count reaches 0. &amp;lt;code&amp;gt;release&amp;lt;/code&amp;gt; gets a pointer to the &amp;lt;code&amp;gt;struct kref&amp;lt;/code&amp;gt;, goes back to the structure around it with &amp;lt;code&amp;gt;container_of()&amp;lt;/code&amp;gt;, and frees it.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; holds one reference, from &amp;lt;code&amp;gt;kref_init()&amp;lt;/code&amp;gt;, and each open file holds one: &amp;lt;code&amp;gt;open()&amp;lt;/code&amp;gt; takes it with &amp;lt;code&amp;gt;kref_get()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;release()&amp;lt;/code&amp;gt; drops it with &amp;lt;code&amp;gt;kref_put()&amp;lt;/code&amp;gt;. Whoever drops the last reference frees the structure:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
static void arhboard_delete(struct kref *kref)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard *dev = container_of(kref, struct arhboard, kref);&lt;br /&gt;
&lt;br /&gt;
	kfree(dev-&amp;gt;ev_buf);&lt;br /&gt;
	kfree(dev-&amp;gt;ctrl_buf);&lt;br /&gt;
	usb_put_intf(dev-&amp;gt;intf);&lt;br /&gt;
	usb_put_dev(dev-&amp;gt;udev);&lt;br /&gt;
	kfree(dev);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static int arhboard_release(struct inode *inode, struct file *file)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard *dev = file-&amp;gt;private_data;&lt;br /&gt;
&lt;br /&gt;
	kref_put(&amp;amp;dev-&amp;gt;kref, arhboard_delete);&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; also takes a reference to the &amp;lt;code&amp;gt;struct usb_device&amp;lt;/code&amp;gt; and to the interface, with &amp;lt;code&amp;gt;usb_get_dev()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;usb_get_intf()&amp;lt;/code&amp;gt;, so that they stay valid for as long as the structure of the driver does.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;&amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt; marks the board as gone&amp;#039;&amp;#039;&amp;#039;, under both locks, and drops the reference of &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
static void arhboard_disconnect(struct usb_interface *intf)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard *dev = usb_get_intfdata(intf);&lt;br /&gt;
&lt;br /&gt;
	/* No new open() from now on */&lt;br /&gt;
	usb_deregister_dev(intf, &amp;amp;arhboard_class);&lt;br /&gt;
	usb_set_intfdata(intf, NULL);&lt;br /&gt;
&lt;br /&gt;
	/*&lt;br /&gt;
	 * Calls already running notice within one slice. Taking each lock&lt;br /&gt;
	 * waits for the transfer which holds it, if any.&lt;br /&gt;
	 */&lt;br /&gt;
	mutex_lock(&amp;amp;dev-&amp;gt;ctrl_lock);&lt;br /&gt;
	mutex_lock(&amp;amp;dev-&amp;gt;ev_lock);&lt;br /&gt;
	dev-&amp;gt;gone = true;&lt;br /&gt;
	mutex_unlock(&amp;amp;dev-&amp;gt;ev_lock);&lt;br /&gt;
	mutex_unlock(&amp;amp;dev-&amp;gt;ctrl_lock);&lt;br /&gt;
&lt;br /&gt;
	dev_info(&amp;amp;intf-&amp;gt;dev, &amp;quot;unplugged\n&amp;quot;);&lt;br /&gt;
	/* Freed now, or at the last close() */&lt;br /&gt;
	kref_put(&amp;amp;dev-&amp;gt;kref, arhboard_delete);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Every file operation checks &amp;lt;code&amp;gt;gone&amp;lt;/code&amp;gt;, under its lock, before it touches the device, and returns &amp;lt;code&amp;gt;-ENODEV&amp;lt;/code&amp;gt;. A call which is waiting notices it at its next slice. The program then gets &amp;lt;code&amp;gt;ENODEV&amp;lt;/code&amp;gt; from every call, until it closes the file, and the last &amp;lt;code&amp;gt;close()&amp;lt;/code&amp;gt; frees the structure.&lt;br /&gt;
&lt;br /&gt;
Try it: start &amp;lt;code&amp;gt;cat /dev/arhboard0&amp;lt;/code&amp;gt;, and unplug the board, or run &amp;lt;code&amp;gt;orb usb detach&amp;lt;/code&amp;gt;. &amp;lt;code&amp;gt;cat&amp;lt;/code&amp;gt; stops with &amp;lt;code&amp;gt;No such device&amp;lt;/code&amp;gt;, and the kernel log shows &amp;lt;code&amp;gt;unplugged&amp;lt;/code&amp;gt;, and nothing else.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; This is why the slices must be short. &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt; takes each lock, so it waits for the transfer which holds it: at most one slice for the events, and one control request. A call which held a lock for a long wait would make &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt; wait for just as long.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== The library and the program ==&lt;br /&gt;
&lt;br /&gt;
The library and the program follow the shape of the last lab: the library has one function for each operation of the driver, hides the ioctl numbers and structures, and turns errors into messages. The program should not need to include the shared header.&lt;br /&gt;
&lt;br /&gt;
A program often has to do two things at once: wait for the commands of the user, and print the events of the board as they come. Both are blocking calls. The simplest way is &amp;#039;&amp;#039;&amp;#039;two threads&amp;#039;&amp;#039;&amp;#039;:&lt;br /&gt;
&lt;br /&gt;
* one thread waits for events, in a loop, and prints each one as it comes;&lt;br /&gt;
* the main thread reads the commands of the user, with &amp;lt;code&amp;gt;readline()&amp;lt;/code&amp;gt;, and runs them.&lt;br /&gt;
&lt;br /&gt;
The two threads can use the same open file: the driver has a separate lock for the events, so a command does not wait for the event thread. To stop the event thread, let it wait with a short timeout, for example 200 ms, and check a flag between two waits. When the user quits, the main thread sets the flag, waits for the event thread with &amp;lt;code&amp;gt;pthread_join()&amp;lt;/code&amp;gt;, and only then closes the file. Never close a file which another thread is still using.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Two threads printing at once can mix up the output, and an event printed in the middle of a line which the user types breaks the prompt. Protect the printing with a mutex, and redraw the prompt after an event with &amp;lt;code&amp;gt;rl_forced_update_display()&amp;lt;/code&amp;gt;.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== How real drivers do it ==&lt;br /&gt;
&lt;br /&gt;
The drivers in the kernel rarely use the blocking calls of this lab. They send &amp;#039;&amp;#039;&amp;#039;URBs&amp;#039;&amp;#039;&amp;#039; (USB Request Blocks): a transfer which is started, and finishes later, while the driver does something else. When it finishes, the USB core calls a &amp;#039;&amp;#039;&amp;#039;completion handler&amp;#039;&amp;#039;&amp;#039; of the driver. A driver of a device with events keeps one URB always waiting on the interrupt endpoint, from &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt;: its completion handler puts each event in a queue in the driver, wakes up the processes which wait for one, and sends the URB again. The driver then implements &amp;lt;code&amp;gt;poll()&amp;lt;/code&amp;gt;, so that a program can wait for events on several files at once, in one thread.&lt;br /&gt;
&lt;br /&gt;
This is needed when a device does not keep its events, or when it must be read without a pause, like a keyboard or a sound card. It also comes with new rules: a completion handler runs in &amp;#039;&amp;#039;&amp;#039;interrupt context&amp;#039;&amp;#039;&amp;#039;, where it cannot sleep, and so cannot take a mutex or call &amp;lt;code&amp;gt;kmalloc()&amp;lt;/code&amp;gt; with &amp;lt;code&amp;gt;GFP_KERNEL&amp;lt;/code&amp;gt;; it needs a spinlock instead. &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt; must also stop every URB before it frees what they use. Our boards keep their events, so the blocking calls are enough, and none of this is needed.&lt;br /&gt;
&lt;br /&gt;
== Debugging ==&lt;br /&gt;
&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;The kernel log.&amp;#039;&amp;#039;&amp;#039; Print what the driver does with &amp;lt;code&amp;gt;dev_dbg()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;dev_info()&amp;lt;/code&amp;gt;, and every error with &amp;lt;code&amp;gt;dev_err()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;%pe&amp;lt;/code&amp;gt;: &amp;lt;code&amp;gt;usb_control_msg failed: -EPIPE&amp;lt;/code&amp;gt; is much more useful than a program which gets &amp;lt;code&amp;gt;EPIPE&amp;lt;/code&amp;gt; and says nothing.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;&amp;lt;code&amp;gt;lsusb -v&amp;lt;/code&amp;gt;&amp;#039;&amp;#039;&amp;#039;, to check the descriptors, and &amp;lt;code&amp;gt;lsusb -t&amp;lt;/code&amp;gt;, to see which driver owns which interface.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;The board on its own.&amp;#039;&amp;#039;&amp;#039; The &amp;lt;code&amp;gt;arhboard&amp;lt;/code&amp;gt; driver of this lab works on every board. If &amp;lt;code&amp;gt;arhboard&amp;lt;/code&amp;gt; works and your driver doesn&amp;#039;t, the problem is in your driver. Only one of them can own the board: unload your driver first.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;&amp;lt;code&amp;gt;usbmon&amp;lt;/code&amp;gt;&amp;#039;&amp;#039;&amp;#039;, on a Linux machine which has it (not on OrbStack), shows every packet on the bus, with Wireshark: every request, every STALL, every ZLP.&lt;br /&gt;
&lt;br /&gt;
== A complete example: arhboard ==&lt;br /&gt;
&lt;br /&gt;
The whole driver of this lab. It only uses the common part of the protocol, so it works on every project board. The driver of your project has the same shape, with the requests, endpoints and events of your project.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
// SPDX-License-Identifier: GPL-2.0&lt;br /&gt;
/*&lt;br /&gt;
 * arhboard: a driver for any lab board, which uses only the requests&lt;br /&gt;
 * and events that every board has (section 4 of every board&amp;#039;s spec).&lt;br /&gt;
 *&lt;br /&gt;
 *   /dev/arhboardN&lt;br /&gt;
 *   read()   waits for the next event, and returns it as one line of text&lt;br /&gt;
 *   write()  sets the label of the board&lt;br /&gt;
 *   ioctl()  GET_INFO, GET_STATUS, GET_LABEL, IDENTIFY&lt;br /&gt;
 *&lt;br /&gt;
 * Every transfer is synchronous: each file operation does its own USB&lt;br /&gt;
 * transfers, and returns. The driver does nothing in the background.&lt;br /&gt;
 */&lt;br /&gt;
&lt;br /&gt;
#include &amp;lt;linux/kref.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/module.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/mutex.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/slab.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/uaccess.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/usb.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#include &amp;quot;arhboard_ioctl.h&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#define ARHBOARD_MINOR_BASE 192&lt;br /&gt;
&lt;br /&gt;
/* The endpoints of every board: the addresses which lsusb -v shows */&lt;br /&gt;
#define EP_DATA_OUT 0x01 /* bulk OUT */&lt;br /&gt;
#define EP_DATA_IN 0x81  /* bulk IN */&lt;br /&gt;
#define EP_EVENT 0x82    /* interrupt IN: one event of 8 bytes */&lt;br /&gt;
&lt;br /&gt;
/* For usb_check_*_endpoints(): lists of addresses, which end with 0 */&lt;br /&gt;
static const u8 arhboard_bulk_eps[] = { EP_DATA_OUT, EP_DATA_IN, 0 };&lt;br /&gt;
static const u8 arhboard_int_eps[] = { EP_EVENT, 0 };&lt;br /&gt;
&lt;br /&gt;
/* Vendor requests, all to interface 0 */&lt;br /&gt;
#define REQ_GET_INFO 0x00&lt;br /&gt;
#define REQ_IDENTIFY 0xE0&lt;br /&gt;
#define REQ_GET_BOARD_STATUS 0xE1&lt;br /&gt;
#define REQ_SET_LABEL 0xE2&lt;br /&gt;
#define REQ_GET_LABEL 0xE3&lt;br /&gt;
&lt;br /&gt;
#define REQTYPE_IN (USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_INTERFACE)   /* 0xC1 */&lt;br /&gt;
#define REQTYPE_OUT (USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE) /* 0x41 */&lt;br /&gt;
&lt;br /&gt;
#define CTRL_TIMEOUT_MS 1000&lt;br /&gt;
/* A long wait is a loop of waits this long: see arhboard_read(). */&lt;br /&gt;
#define SLICE_MS 100&lt;br /&gt;
&lt;br /&gt;
/* What the board sends, exactly as it is on the wire: little-endian */&lt;br /&gt;
struct wire_info {&lt;br /&gt;
	__le32 magic;&lt;br /&gt;
	__le16 protocol_version;&lt;br /&gt;
	__le16 firmware_version;&lt;br /&gt;
	__le32 capabilities;&lt;br /&gt;
	u8 device_specific[3];&lt;br /&gt;
	u8 event_queue_len;&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
struct wire_status {&lt;br /&gt;
	__le32 uptime_ms;&lt;br /&gt;
	__le16 events_dropped;&lt;br /&gt;
	u8 events_queued;&lt;br /&gt;
	u8 button_down;&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
struct wire_event {&lt;br /&gt;
	u8 type;&lt;br /&gt;
	u8 arg;&lt;br /&gt;
	__le16 seq;&lt;br /&gt;
	__le32 time_ms;&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
static_assert(sizeof(struct wire_info) == 16);&lt;br /&gt;
static_assert(sizeof(struct wire_status) == 8);&lt;br /&gt;
static_assert(sizeof(struct wire_event) == 8);&lt;br /&gt;
&lt;br /&gt;
#define MAGIC_ARH 0x00485241 /* &amp;quot;ARH&amp;quot; in the low three bytes */&lt;br /&gt;
#define CTRL_BUF_LEN 16&lt;br /&gt;
&lt;br /&gt;
/* Everything the driver knows about one board */&lt;br /&gt;
struct arhboard {&lt;br /&gt;
	struct usb_device *udev;&lt;br /&gt;
	struct usb_interface *intf;&lt;br /&gt;
	struct kref kref; /* probe() holds one reference, each open file one */&lt;br /&gt;
&lt;br /&gt;
	struct mutex ctrl_lock; /* control transfers, ctrl_buf */&lt;br /&gt;
	u8 *ctrl_buf;           /* kmalloc()ed: the controller reads it by DMA */&lt;br /&gt;
&lt;br /&gt;
	struct mutex ev_lock; /* the event endpoint, ev_buf */&lt;br /&gt;
	u8 *ev_buf;&lt;br /&gt;
&lt;br /&gt;
	bool gone; /* unplugged: written under both locks */&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
static struct usb_driver arhboard_driver;&lt;br /&gt;
&lt;br /&gt;
static void arhboard_delete(struct kref *kref)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard *dev = container_of(kref, struct arhboard, kref);&lt;br /&gt;
&lt;br /&gt;
	kfree(dev-&amp;gt;ev_buf);&lt;br /&gt;
	kfree(dev-&amp;gt;ctrl_buf);&lt;br /&gt;
	usb_put_intf(dev-&amp;gt;intf);&lt;br /&gt;
	usb_put_dev(dev-&amp;gt;udev);&lt;br /&gt;
	kfree(dev);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
/*&lt;br /&gt;
 * Control transfers. The caller holds ctrl_lock (or is probe(), before the&lt;br /&gt;
 * device can be opened). The data is in dev-&amp;gt;ctrl_buf.&lt;br /&gt;
 */&lt;br /&gt;
static int arhboard_ctrl_in(struct arhboard *dev, u8 request, u16 len)&lt;br /&gt;
{&lt;br /&gt;
	int ret = usb_control_msg(dev-&amp;gt;udev, usb_rcvctrlpipe(dev-&amp;gt;udev, 0),&lt;br /&gt;
				  request, REQTYPE_IN, 0, 0, dev-&amp;gt;ctrl_buf, len,&lt;br /&gt;
				  CTRL_TIMEOUT_MS);&lt;br /&gt;
	if (ret &amp;lt; 0)&lt;br /&gt;
		return ret; /* -EPIPE: the board refused (STALL) */&lt;br /&gt;
	if (ret != len)&lt;br /&gt;
		return -EPROTO; /* a short answer is an error too */&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static int arhboard_ctrl_out(struct arhboard *dev, u8 request, u16 value,&lt;br /&gt;
			     u16 len)&lt;br /&gt;
{&lt;br /&gt;
	int ret = usb_control_msg(dev-&amp;gt;udev, usb_sndctrlpipe(dev-&amp;gt;udev, 0),&lt;br /&gt;
				  request, REQTYPE_OUT, value, 0,&lt;br /&gt;
				  len ? dev-&amp;gt;ctrl_buf : NULL, len,&lt;br /&gt;
				  CTRL_TIMEOUT_MS);&lt;br /&gt;
	if (ret &amp;lt; 0)&lt;br /&gt;
		return ret;&lt;br /&gt;
	if (ret != len)&lt;br /&gt;
		return -EPROTO;&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static void info_from_wire(struct arhboard_info *info,&lt;br /&gt;
			   const struct wire_info *w)&lt;br /&gt;
{&lt;br /&gt;
	info-&amp;gt;magic = le32_to_cpu(w-&amp;gt;magic);&lt;br /&gt;
	info-&amp;gt;protocol_version = le16_to_cpu(w-&amp;gt;protocol_version);&lt;br /&gt;
	info-&amp;gt;firmware_version = le16_to_cpu(w-&amp;gt;firmware_version);&lt;br /&gt;
	info-&amp;gt;capabilities = le32_to_cpu(w-&amp;gt;capabilities);&lt;br /&gt;
	memcpy(info-&amp;gt;device_specific, w-&amp;gt;device_specific,&lt;br /&gt;
	       sizeof(info-&amp;gt;device_specific));&lt;br /&gt;
	info-&amp;gt;event_queue_len = w-&amp;gt;event_queue_len;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static int arhboard_open(struct inode *inode, struct file *file)&lt;br /&gt;
{&lt;br /&gt;
	struct usb_interface *intf;&lt;br /&gt;
	struct arhboard *dev;&lt;br /&gt;
&lt;br /&gt;
	intf = usb_find_interface(&amp;amp;arhboard_driver, iminor(inode));&lt;br /&gt;
	if (!intf)&lt;br /&gt;
		return -ENODEV;&lt;br /&gt;
	dev = usb_get_intfdata(intf);&lt;br /&gt;
	if (!dev)&lt;br /&gt;
		return -ENODEV;&lt;br /&gt;
&lt;br /&gt;
	kref_get(&amp;amp;dev-&amp;gt;kref);&lt;br /&gt;
	file-&amp;gt;private_data = dev;&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static int arhboard_release(struct inode *inode, struct file *file)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard *dev = file-&amp;gt;private_data;&lt;br /&gt;
&lt;br /&gt;
	kref_put(&amp;amp;dev-&amp;gt;kref, arhboard_delete);&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
/*&lt;br /&gt;
 * Wait for the next event, and return it as one line of text. The board keeps&lt;br /&gt;
 * the events until we read them, so nothing is lost while nobody reads.&lt;br /&gt;
 *&lt;br /&gt;
 * The wait is a loop of short transfers: between two of them, the lock is&lt;br /&gt;
 * free (disconnect() can take it), and we look for Ctrl+C and O_NONBLOCK.&lt;br /&gt;
 */&lt;br /&gt;
static ssize_t arhboard_read(struct file *file, char __user *ubuf,&lt;br /&gt;
			     size_t count, loff_t *ppos)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard *dev = file-&amp;gt;private_data;&lt;br /&gt;
	struct wire_event *wev = (struct wire_event *)dev-&amp;gt;ev_buf;&lt;br /&gt;
	char line[64];&lt;br /&gt;
	int len = 0;&lt;br /&gt;
	int actual;&lt;br /&gt;
	int ret;&lt;br /&gt;
&lt;br /&gt;
	for (;;) {&lt;br /&gt;
		if (mutex_lock_interruptible(&amp;amp;dev-&amp;gt;ev_lock))&lt;br /&gt;
			return -ERESTARTSYS;&lt;br /&gt;
		if (dev-&amp;gt;gone) {&lt;br /&gt;
			ret = -ENODEV;&lt;br /&gt;
		} else {&lt;br /&gt;
			ret = usb_interrupt_msg(dev-&amp;gt;udev,&lt;br /&gt;
						usb_rcvintpipe(dev-&amp;gt;udev, EP_EVENT),&lt;br /&gt;
						dev-&amp;gt;ev_buf, sizeof(*wev),&lt;br /&gt;
						&amp;amp;actual, SLICE_MS);&lt;br /&gt;
			if (ret == 0 &amp;amp;&amp;amp; actual != sizeof(*wev))&lt;br /&gt;
				ret = -EPROTO;&lt;br /&gt;
			if (ret == 0)&lt;br /&gt;
				len = scnprintf(line, sizeof(line),&lt;br /&gt;
						&amp;quot;seq=%u time=%u type=0x%02x arg=%u\n&amp;quot;,&lt;br /&gt;
						le16_to_cpu(wev-&amp;gt;seq),&lt;br /&gt;
						le32_to_cpu(wev-&amp;gt;time_ms),&lt;br /&gt;
						wev-&amp;gt;type, wev-&amp;gt;arg);&lt;br /&gt;
		}&lt;br /&gt;
		mutex_unlock(&amp;amp;dev-&amp;gt;ev_lock);&lt;br /&gt;
&lt;br /&gt;
		if (ret != -ETIMEDOUT)&lt;br /&gt;
			break;&lt;br /&gt;
		/* No event in this slice */&lt;br /&gt;
		if (file-&amp;gt;f_flags &amp;amp; O_NONBLOCK)&lt;br /&gt;
			return -EAGAIN;&lt;br /&gt;
		if (signal_pending(current))&lt;br /&gt;
			return -ERESTARTSYS;&lt;br /&gt;
	}&lt;br /&gt;
	if (ret)&lt;br /&gt;
		return ret;&lt;br /&gt;
&lt;br /&gt;
	if (count &amp;lt; len)&lt;br /&gt;
		return -EINVAL; /* one event per read(), and it must fit */&lt;br /&gt;
	if (copy_to_user(ubuf, line, len))&lt;br /&gt;
		return -EFAULT;&lt;br /&gt;
	return len;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
/* Set the label: up to 16 bytes, a final &amp;#039;\n&amp;#039; is dropped */&lt;br /&gt;
static ssize_t arhboard_write(struct file *file, const char __user *ubuf,&lt;br /&gt;
			      size_t count, loff_t *ppos)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard *dev = file-&amp;gt;private_data;&lt;br /&gt;
	char label[ARHBOARD_LABEL_LEN + 1] = {};&lt;br /&gt;
	size_t len = count;&lt;br /&gt;
	int ret;&lt;br /&gt;
&lt;br /&gt;
	if (len &amp;gt; ARHBOARD_LABEL_LEN + 1)&lt;br /&gt;
		return -EINVAL;&lt;br /&gt;
	if (copy_from_user(label, ubuf, len))&lt;br /&gt;
		return -EFAULT;&lt;br /&gt;
	if (len &amp;gt; 0 &amp;amp;&amp;amp; label[len - 1] == &amp;#039;\n&amp;#039;)&lt;br /&gt;
		len--;&lt;br /&gt;
	if (len &amp;gt; ARHBOARD_LABEL_LEN)&lt;br /&gt;
		return -EINVAL;&lt;br /&gt;
&lt;br /&gt;
	mutex_lock(&amp;amp;dev-&amp;gt;ctrl_lock);&lt;br /&gt;
	if (dev-&amp;gt;gone) {&lt;br /&gt;
		ret = -ENODEV;&lt;br /&gt;
	} else {&lt;br /&gt;
		memset(dev-&amp;gt;ctrl_buf, 0, ARHBOARD_LABEL_LEN); /* padded with &amp;#039;\0&amp;#039; */&lt;br /&gt;
		memcpy(dev-&amp;gt;ctrl_buf, label, len);&lt;br /&gt;
		ret = arhboard_ctrl_out(dev, REQ_SET_LABEL, 0, ARHBOARD_LABEL_LEN);&lt;br /&gt;
	}&lt;br /&gt;
	mutex_unlock(&amp;amp;dev-&amp;gt;ctrl_lock);&lt;br /&gt;
&lt;br /&gt;
	return ret ? ret : count;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static long arhboard_ioctl(struct file *file, unsigned int cmd,&lt;br /&gt;
			   unsigned long arg)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard *dev = file-&amp;gt;private_data;&lt;br /&gt;
	void __user *uarg = (void __user *)arg;&lt;br /&gt;
	union {&lt;br /&gt;
		struct arhboard_info info;&lt;br /&gt;
		struct arhboard_status status;&lt;br /&gt;
		struct arhboard_label label;&lt;br /&gt;
	} out = {}; /* zeroed: no kernel memory leaks to user space */&lt;br /&gt;
	size_t out_len = 0;&lt;br /&gt;
	u32 flashes;&lt;br /&gt;
	int ret;&lt;br /&gt;
&lt;br /&gt;
	/* Read the argument before taking the lock */&lt;br /&gt;
	if (cmd == ARHBOARD_IOC_IDENTIFY) {&lt;br /&gt;
		if (copy_from_user(&amp;amp;flashes, uarg, sizeof(flashes)))&lt;br /&gt;
			return -EFAULT;&lt;br /&gt;
		if (flashes &amp;gt; U16_MAX) /* it travels in wValue, 16 bits */&lt;br /&gt;
			return -EINVAL;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	mutex_lock(&amp;amp;dev-&amp;gt;ctrl_lock);&lt;br /&gt;
	if (dev-&amp;gt;gone) {&lt;br /&gt;
		ret = -ENODEV;&lt;br /&gt;
		goto out_unlock;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	switch (cmd) {&lt;br /&gt;
	case ARHBOARD_IOC_GET_INFO:&lt;br /&gt;
		ret = arhboard_ctrl_in(dev, REQ_GET_INFO, sizeof(struct wire_info));&lt;br /&gt;
		if (ret)&lt;br /&gt;
			break;&lt;br /&gt;
		info_from_wire(&amp;amp;out.info, (struct wire_info *)dev-&amp;gt;ctrl_buf);&lt;br /&gt;
		out_len = sizeof(out.info);&lt;br /&gt;
		break;&lt;br /&gt;
&lt;br /&gt;
	case ARHBOARD_IOC_GET_STATUS: {&lt;br /&gt;
		struct wire_status *w = (struct wire_status *)dev-&amp;gt;ctrl_buf;&lt;br /&gt;
&lt;br /&gt;
		ret = arhboard_ctrl_in(dev, REQ_GET_BOARD_STATUS, sizeof(*w));&lt;br /&gt;
		if (ret)&lt;br /&gt;
			break;&lt;br /&gt;
		out.status.uptime_ms = le32_to_cpu(w-&amp;gt;uptime_ms);&lt;br /&gt;
		out.status.events_dropped = le16_to_cpu(w-&amp;gt;events_dropped);&lt;br /&gt;
		out.status.events_queued = w-&amp;gt;events_queued;&lt;br /&gt;
		out.status.button_down = w-&amp;gt;button_down;&lt;br /&gt;
		out_len = sizeof(out.status);&lt;br /&gt;
		break;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	case ARHBOARD_IOC_GET_LABEL:&lt;br /&gt;
		ret = arhboard_ctrl_in(dev, REQ_GET_LABEL, ARHBOARD_LABEL_LEN);&lt;br /&gt;
		if (ret)&lt;br /&gt;
			break;&lt;br /&gt;
		/* out.label.label[16] stays &amp;#039;\0&amp;#039; */&lt;br /&gt;
		memcpy(out.label.label, dev-&amp;gt;ctrl_buf, ARHBOARD_LABEL_LEN);&lt;br /&gt;
		out_len = sizeof(out.label);&lt;br /&gt;
		break;&lt;br /&gt;
&lt;br /&gt;
	case ARHBOARD_IOC_IDENTIFY:&lt;br /&gt;
		/* No data stage: the number travels in wValue */&lt;br /&gt;
		ret = arhboard_ctrl_out(dev, REQ_IDENTIFY, flashes, 0);&lt;br /&gt;
		break;&lt;br /&gt;
&lt;br /&gt;
	default:&lt;br /&gt;
		ret = -ENOTTY;&lt;br /&gt;
		break;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
out_unlock:&lt;br /&gt;
	mutex_unlock(&amp;amp;dev-&amp;gt;ctrl_lock);&lt;br /&gt;
&lt;br /&gt;
	if (ret == 0 &amp;amp;&amp;amp; out_len &amp;amp;&amp;amp; copy_to_user(uarg, &amp;amp;out, out_len))&lt;br /&gt;
		ret = -EFAULT;&lt;br /&gt;
	return ret;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static const struct file_operations arhboard_fops = {&lt;br /&gt;
	.owner = THIS_MODULE,&lt;br /&gt;
	.open = arhboard_open,&lt;br /&gt;
	.release = arhboard_release,&lt;br /&gt;
	.read = arhboard_read,&lt;br /&gt;
	.write = arhboard_write,&lt;br /&gt;
	.unlocked_ioctl = arhboard_ioctl,&lt;br /&gt;
	.compat_ioctl = compat_ptr_ioctl,&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
static char *arhboard_devnode(const struct device *dev, umode_t *mode)&lt;br /&gt;
{&lt;br /&gt;
	if (mode)&lt;br /&gt;
		*mode = 0666;&lt;br /&gt;
	return NULL;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
/* /dev/arhboard0, /dev/arhboard1, ...: major 180, minors from 192 */&lt;br /&gt;
static struct usb_class_driver arhboard_class = {&lt;br /&gt;
	.name = &amp;quot;arhboard%d&amp;quot;,&lt;br /&gt;
	.devnode = arhboard_devnode,&lt;br /&gt;
	.fops = &amp;amp;arhboard_fops,&lt;br /&gt;
	.minor_base = ARHBOARD_MINOR_BASE,&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
static int arhboard_probe(struct usb_interface *intf,&lt;br /&gt;
			  const struct usb_device_id *id)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard_info info;&lt;br /&gt;
	struct arhboard *dev;&lt;br /&gt;
	int ret;&lt;br /&gt;
&lt;br /&gt;
	/* Does the interface have the endpoints which we expect? */&lt;br /&gt;
	if (!usb_check_bulk_endpoints(intf, arhboard_bulk_eps) ||&lt;br /&gt;
	    !usb_check_int_endpoints(intf, arhboard_int_eps)) {&lt;br /&gt;
		dev_err(&amp;amp;intf-&amp;gt;dev, &amp;quot;unexpected endpoints\n&amp;quot;);&lt;br /&gt;
		return -ENODEV;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	dev = kzalloc(sizeof(*dev), GFP_KERNEL);&lt;br /&gt;
	if (!dev)&lt;br /&gt;
		return -ENOMEM;&lt;br /&gt;
	kref_init(&amp;amp;dev-&amp;gt;kref);&lt;br /&gt;
	mutex_init(&amp;amp;dev-&amp;gt;ctrl_lock);&lt;br /&gt;
	mutex_init(&amp;amp;dev-&amp;gt;ev_lock);&lt;br /&gt;
	dev-&amp;gt;udev = usb_get_dev(interface_to_usbdev(intf));&lt;br /&gt;
	dev-&amp;gt;intf = usb_get_intf(intf);&lt;br /&gt;
&lt;br /&gt;
	dev-&amp;gt;ctrl_buf = kmalloc(CTRL_BUF_LEN, GFP_KERNEL);&lt;br /&gt;
	dev-&amp;gt;ev_buf = kmalloc(sizeof(struct wire_event), GFP_KERNEL);&lt;br /&gt;
	if (!dev-&amp;gt;ctrl_buf || !dev-&amp;gt;ev_buf) {&lt;br /&gt;
		ret = -ENOMEM;&lt;br /&gt;
		goto err;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	/* Is it really a lab board? */&lt;br /&gt;
	ret = arhboard_ctrl_in(dev, REQ_GET_INFO, sizeof(struct wire_info));&lt;br /&gt;
	if (ret) {&lt;br /&gt;
		dev_err(&amp;amp;intf-&amp;gt;dev, &amp;quot;GET_INFO failed: %pe\n&amp;quot;, ERR_PTR(ret));&lt;br /&gt;
		goto err;&lt;br /&gt;
	}&lt;br /&gt;
	info_from_wire(&amp;amp;info, (struct wire_info *)dev-&amp;gt;ctrl_buf);&lt;br /&gt;
	if ((info.magic &amp;amp; 0x00ffffff) != MAGIC_ARH) {&lt;br /&gt;
		dev_err(&amp;amp;intf-&amp;gt;dev, &amp;quot;not a lab board (magic 0x%08x)\n&amp;quot;,&lt;br /&gt;
			info.magic);&lt;br /&gt;
		ret = -ENODEV;&lt;br /&gt;
		goto err;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	usb_set_intfdata(intf, dev);&lt;br /&gt;
	ret = usb_register_dev(intf, &amp;amp;arhboard_class);&lt;br /&gt;
	if (ret) {&lt;br /&gt;
		dev_err(&amp;amp;intf-&amp;gt;dev, &amp;quot;no minor number: %pe\n&amp;quot;, ERR_PTR(ret));&lt;br /&gt;
		usb_set_intfdata(intf, NULL);&lt;br /&gt;
		goto err;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	dev_info(&amp;amp;intf-&amp;gt;dev,&lt;br /&gt;
		 &amp;quot;project &amp;#039;%c&amp;#039;, protocol %u.%u, firmware %u.%u, /dev/arhboard%d\n&amp;quot;,&lt;br /&gt;
		 (char)(info.magic &amp;gt;&amp;gt; 24), info.protocol_version &amp;gt;&amp;gt; 8,&lt;br /&gt;
		 info.protocol_version &amp;amp; 0xff, info.firmware_version &amp;gt;&amp;gt; 8,&lt;br /&gt;
		 info.firmware_version &amp;amp; 0xff, intf-&amp;gt;minor - ARHBOARD_MINOR_BASE);&lt;br /&gt;
	return 0;&lt;br /&gt;
&lt;br /&gt;
err:&lt;br /&gt;
	kref_put(&amp;amp;dev-&amp;gt;kref, arhboard_delete);&lt;br /&gt;
	return ret;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static void arhboard_disconnect(struct usb_interface *intf)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard *dev = usb_get_intfdata(intf);&lt;br /&gt;
&lt;br /&gt;
	/* No new open() from now on */&lt;br /&gt;
	usb_deregister_dev(intf, &amp;amp;arhboard_class);&lt;br /&gt;
	usb_set_intfdata(intf, NULL);&lt;br /&gt;
&lt;br /&gt;
	/*&lt;br /&gt;
	 * Calls already running notice within one slice. Taking each lock&lt;br /&gt;
	 * waits for the transfer which holds it, if any.&lt;br /&gt;
	 */&lt;br /&gt;
	mutex_lock(&amp;amp;dev-&amp;gt;ctrl_lock);&lt;br /&gt;
	mutex_lock(&amp;amp;dev-&amp;gt;ev_lock);&lt;br /&gt;
	dev-&amp;gt;gone = true;&lt;br /&gt;
	mutex_unlock(&amp;amp;dev-&amp;gt;ev_lock);&lt;br /&gt;
	mutex_unlock(&amp;amp;dev-&amp;gt;ctrl_lock);&lt;br /&gt;
&lt;br /&gt;
	dev_info(&amp;amp;intf-&amp;gt;dev, &amp;quot;unplugged\n&amp;quot;);&lt;br /&gt;
	/* Freed now, or at the last close() */&lt;br /&gt;
	kref_put(&amp;amp;dev-&amp;gt;kref, arhboard_delete);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
/* The seven lab boards: vendor 0xcafe, one product ID per project */&lt;br /&gt;
static const struct usb_device_id arhboard_ids[] = {&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4301) },	/* CC-1 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4302) },	/* EL-2 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4303) },	/* FV-3 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4304) },	/* MB-4 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4305) },	/* TW-5 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4306) },	/* WP-6 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4307) },	/* BP-7 */&lt;br /&gt;
	{}&lt;br /&gt;
};&lt;br /&gt;
MODULE_DEVICE_TABLE(usb, arhboard_ids);&lt;br /&gt;
&lt;br /&gt;
static struct usb_driver arhboard_driver = {&lt;br /&gt;
	.name = &amp;quot;arhboard&amp;quot;,&lt;br /&gt;
	.probe = arhboard_probe,&lt;br /&gt;
	.disconnect = arhboard_disconnect,&lt;br /&gt;
	.id_table = arhboard_ids,&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
module_usb_driver(arhboard_driver);&lt;br /&gt;
&lt;br /&gt;
MODULE_LICENSE(&amp;quot;GPL&amp;quot;);&lt;br /&gt;
MODULE_AUTHOR(&amp;quot;OS Lab&amp;quot;);&lt;br /&gt;
MODULE_DESCRIPTION(&amp;quot;Example USB driver for any lab board&amp;quot;);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And its shared header, &amp;lt;code&amp;gt;uapi/arhboard_ioctl.h&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */&lt;br /&gt;
/*&lt;br /&gt;
 * The interface between the arhboard driver and user space: ioctl numbers&lt;br /&gt;
 * and their structures. Shared by the driver and by programs, so it only&lt;br /&gt;
 * uses the __u8 ... __u32 types.&lt;br /&gt;
 *&lt;br /&gt;
 * The values here are in the byte order of the machine: the driver converts&lt;br /&gt;
 * them from the device&amp;#039;s little-endian structures.&lt;br /&gt;
 */&lt;br /&gt;
#ifndef ARHBOARD_IOCTL_H&lt;br /&gt;
#define ARHBOARD_IOCTL_H&lt;br /&gt;
&lt;br /&gt;
#include &amp;lt;linux/ioctl.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/types.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define ARHBOARD_LABEL_LEN 16&lt;br /&gt;
&lt;br /&gt;
/* GET_INFO: what the board says about itself */&lt;br /&gt;
struct arhboard_info {&lt;br /&gt;
	__u32 magic;            /* &amp;quot;ARH&amp;quot; + one character per project */&lt;br /&gt;
	__u16 protocol_version; /* major in the high byte, minor in the low byte */&lt;br /&gt;
	__u16 firmware_version;&lt;br /&gt;
	__u32 capabilities;     /* bits defined by the project */&lt;br /&gt;
	__u8 device_specific[3];&lt;br /&gt;
	__u8 event_queue_len;   /* unread events the board keeps */&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
/* GET_BOARD_STATUS */&lt;br /&gt;
struct arhboard_status {&lt;br /&gt;
	__u32 uptime_ms;      /* since power-up */&lt;br /&gt;
	__u16 events_dropped; /* lost because the board&amp;#039;s queue was full */&lt;br /&gt;
	__u8 events_queued;   /* waiting to be read, now */&lt;br /&gt;
	__u8 button_down;     /* 1 while the button is held */&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
/* GET_LABEL: always ends with &amp;#039;\0&amp;#039; */&lt;br /&gt;
struct arhboard_label {&lt;br /&gt;
	char label[ARHBOARD_LABEL_LEN + 1];&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
#define ARHBOARD_IOC_MAGIC 0xB8&lt;br /&gt;
#define ARHBOARD_IOC_GET_INFO   _IOR(ARHBOARD_IOC_MAGIC, 1, struct arhboard_info)&lt;br /&gt;
#define ARHBOARD_IOC_GET_STATUS _IOR(ARHBOARD_IOC_MAGIC, 2, struct arhboard_status)&lt;br /&gt;
#define ARHBOARD_IOC_GET_LABEL  _IOR(ARHBOARD_IOC_MAGIC, 3, struct arhboard_label)&lt;br /&gt;
/* Flash the LED: 1 to 10 times. Anything else is refused by the board (EPIPE). */&lt;br /&gt;
#define ARHBOARD_IOC_IDENTIFY   _IOW(ARHBOARD_IOC_MAGIC, 4, __u32)&lt;br /&gt;
&lt;br /&gt;
#endif&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Try it on your board:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ make -C driver load&lt;br /&gt;
$ sudo dmesg | tail -1&lt;br /&gt;
[ 9120.551021] arhboard 1-1:1.0: project &amp;#039;1&amp;#039;, protocol 1.0, firmware 1.0, /dev/arhboard0&lt;br /&gt;
$ echo bench-3 &amp;gt; /dev/arhboard0      # SET_LABEL&lt;br /&gt;
$ cat /dev/arhboard0                 # press the button; Ctrl+C to stop&lt;br /&gt;
seq=0 time=48213 type=0x01 arg=0&lt;br /&gt;
^C&lt;br /&gt;
$ make -C driver unload&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=OS_Lab_9_-_USB_drivers._USB_transfers&amp;diff=8463</id>
		<title>OS Lab 9 - USB drivers. USB transfers</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=OS_Lab_9_-_USB_drivers._USB_transfers&amp;diff=8463"/>
		<updated>2026-11-27T15:14:42Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: Pagină nouă: In the last lab, we wrote a kernel module with a character device, whose &amp;lt;code&amp;gt;read()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;write()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ioctl(...&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In [[OS_Lab_8_-_Kernel_modules._Character_devices|the last lab]], we wrote a kernel module with a character device, whose &amp;lt;code&amp;gt;read()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;write()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ioctl()&amp;lt;/code&amp;gt; ran our functions. The device was a virtual one: it only kept data in memory. In this lab, the device behind the file is a real USB device, your project board, and the driver&amp;#039;s functions talk to it.&lt;br /&gt;
&lt;br /&gt;
The rule for the whole lab is simple: &amp;#039;&amp;#039;&amp;#039;each file operation does its own USB transfers, waits for them, and returns&amp;#039;&amp;#039;&amp;#039;. The driver never does anything in the background. Real drivers are often more complicated (see [[#How real drivers do it|How real drivers do it]]), but for our boards, this is all that is needed, and it keeps the driver close to the character device of the last lab.&lt;br /&gt;
&lt;br /&gt;
== Learning objectives ==&lt;br /&gt;
&lt;br /&gt;
By the end of this lab you should be able to:&lt;br /&gt;
&lt;br /&gt;
# read the descriptors of a USB device, and find its interfaces and endpoints;&lt;br /&gt;
# write a USB driver which binds to a device, checks it in &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt;, and cleans up in &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt;;&lt;br /&gt;
# give each board its own file in &amp;lt;code&amp;gt;/dev&amp;lt;/code&amp;gt;;&lt;br /&gt;
# send control requests, and read and write interrupt and bulk endpoints, with blocking calls;&lt;br /&gt;
# make a blocking call that can be interrupted with Ctrl+C, and that respects &amp;lt;code&amp;gt;O_NONBLOCK&amp;lt;/code&amp;gt;;&lt;br /&gt;
# convert between the byte order of the device and of the machine;&lt;br /&gt;
# handle a device which is unplugged while a program uses it.&lt;br /&gt;
&lt;br /&gt;
== The project ==&lt;br /&gt;
&lt;br /&gt;
There is no new template: you build your USB driver in the project of the last lab, which already has the three parts (the driver, a library which wraps it, and a program which uses the library) and the kernel tree in &amp;lt;code&amp;gt;kbuild/&amp;lt;/code&amp;gt;. Work in a copy of it. &amp;lt;code&amp;gt;kbuild/&amp;lt;/code&amp;gt; is large, so move it rather than copy it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
rsync -a --exclude kbuild lab08/ lab09/&lt;br /&gt;
mv lab08/kbuild lab09/&lt;br /&gt;
cd lab09&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then turn the &amp;lt;code&amp;gt;klog&amp;lt;/code&amp;gt; driver of the template into yours. The examples in this lab are from &amp;lt;code&amp;gt;arhboard&amp;lt;/code&amp;gt;, a driver which works on every project board, because it only uses the requests and events which all of them have. For your own driver, use the name of your project instead:&lt;br /&gt;
&lt;br /&gt;
# rename &amp;lt;code&amp;gt;driver/klog.c&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;driver/arhboard.c&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;driver/uapi/klog_ioctl.h&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;driver/uapi/arhboard_ioctl.h&amp;lt;/code&amp;gt;;&lt;br /&gt;
# in &amp;lt;code&amp;gt;driver/Kbuild&amp;lt;/code&amp;gt;, change the line &amp;lt;code&amp;gt;obj-m&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;obj-m := arhboard.o&amp;lt;/code&amp;gt;;&lt;br /&gt;
# in &amp;lt;code&amp;gt;driver/Makefile&amp;lt;/code&amp;gt;, change &amp;lt;code&amp;gt;MODULE := klog&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;MODULE := arhboard&amp;lt;/code&amp;gt;;&lt;br /&gt;
# rename the files in &amp;lt;code&amp;gt;lib/&amp;lt;/code&amp;gt; as well, when you write the library. CMake builds every &amp;lt;code&amp;gt;.c&amp;lt;/code&amp;gt; file in &amp;lt;code&amp;gt;lib/&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;app/&amp;lt;/code&amp;gt;, whatever its name. Until then, the library and the program of the template no longer build, because they include &amp;lt;code&amp;gt;klog_ioctl.h&amp;lt;/code&amp;gt;: build the driver alone, with &amp;lt;code&amp;gt;make -C driver&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
A USB driver has one file in &amp;lt;code&amp;gt;/dev&amp;lt;/code&amp;gt; for each board, &amp;lt;code&amp;gt;/dev/arhboard0&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;/dev/arhboard1&amp;lt;/code&amp;gt;, ..., and they only appear when a board is plugged in (see [[#One file per board|One file per board]]). The rule &amp;lt;code&amp;gt;load&amp;lt;/code&amp;gt; of the template already handles this: after &amp;lt;code&amp;gt;insmod&amp;lt;/code&amp;gt;, it makes the file of every device of the module that it finds in &amp;lt;code&amp;gt;/sys/class&amp;lt;/code&amp;gt;, which was &amp;lt;code&amp;gt;/dev/klog&amp;lt;/code&amp;gt; in the last lab, and is one file per board now. &amp;lt;code&amp;gt;make unload&amp;lt;/code&amp;gt; removes them again. On OrbStack, which does not make the files itself, run &amp;lt;code&amp;gt;make -C driver nodes&amp;lt;/code&amp;gt; for a board you plug in after loading the driver.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; If the build of the driver stops with &amp;lt;code&amp;gt;ERROR: modpost: &amp;quot;usb_register_driver&amp;quot; [...] undefined!&amp;lt;/code&amp;gt;, your &amp;lt;code&amp;gt;kbuild/&amp;lt;/code&amp;gt; was made without USB support, by an older &amp;lt;code&amp;gt;make_kbuild.sh&amp;lt;/code&amp;gt;. Download the template of the last lab again, take its &amp;lt;code&amp;gt;make_kbuild.sh&amp;lt;/code&amp;gt;, delete &amp;lt;code&amp;gt;kbuild/&amp;lt;/code&amp;gt;, and run the script again. Take its &amp;lt;code&amp;gt;driver/Makefile&amp;lt;/code&amp;gt; too (and set &amp;lt;code&amp;gt;MODULE&amp;lt;/code&amp;gt; in it again): an older one has no &amp;lt;code&amp;gt;nodes&amp;lt;/code&amp;gt; rule, and only makes &amp;lt;code&amp;gt;/dev/klog&amp;lt;/code&amp;gt;.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== The board ===&lt;br /&gt;
&lt;br /&gt;
The board you will be working with is a Raspberry Pi Pico 2 (or Pico 2 W) which runs the firmware assigned to you for your project. It should be running the firmware as soon as you plug it in. You do not need to program the board yourself.&lt;br /&gt;
&lt;br /&gt;
On a PC which runs Linux directly, there is nothing else to do: plug the board in. In a virtual machine, the board is plugged into the host (macOS or Windows), and you must give it to the Linux machine first.&lt;br /&gt;
&lt;br /&gt;
==== OrbStack ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;orb usb list&amp;lt;/code&amp;gt; shows the USB devices of the Mac, with an ID for each:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ orb usb list&lt;br /&gt;
...&lt;br /&gt;
00114000  cafe:4301  ARH ARH CC-1&lt;br /&gt;
$ orb usb attach 00114000&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
From then on, Linux sees the board as if it were plugged into it, and macOS does not see it anymore. &amp;lt;code&amp;gt;orb usb detach 00114000&amp;lt;/code&amp;gt; gives it back to the Mac, which, for Linux, is the same as unplugging it. This is useful later, to test what your driver does when the board goes away.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; When you unplug the board and plug it back in, it goes back to the Mac: attach it again. The ID belongs to the USB port, not to the board, so it stays the same as long as you use the same port. Run &amp;lt;code&amp;gt;orb usb list&amp;lt;/code&amp;gt; again if you change ports.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== WSL ====&lt;br /&gt;
&lt;br /&gt;
WSL gets USB devices from Windows through [https://github.com/dorssel/usbipd-win usbipd-win], which you install in Windows. In a PowerShell window opened as administrator, &amp;lt;code&amp;gt;usbipd list&amp;lt;/code&amp;gt; shows the USB devices of the PC, with a bus ID for each. Share the board once with &amp;lt;code&amp;gt;bind&amp;lt;/code&amp;gt;, and then give it to WSL with &amp;lt;code&amp;gt;attach&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;powershell&amp;quot;&amp;gt;&lt;br /&gt;
&amp;gt; usbipd list&lt;br /&gt;
BUSID  VID:PID    DEVICE                    STATE&lt;br /&gt;
2-3    cafe:4301  ARH CC-1                  Not shared&lt;br /&gt;
&amp;gt; usbipd bind --busid 2-3&lt;br /&gt;
&amp;gt; usbipd attach --wsl --busid 2-3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
From then on, &amp;lt;code&amp;gt;lsusb&amp;lt;/code&amp;gt; in WSL shows the board. &amp;lt;code&amp;gt;usbipd detach --busid 2-3&amp;lt;/code&amp;gt; gives it back to Windows, which, for Linux, is the same as unplugging it. After you unplug the board and plug it back in, run &amp;lt;code&amp;gt;usbipd attach&amp;lt;/code&amp;gt; again.&lt;br /&gt;
&lt;br /&gt;
== USB in brief ==&lt;br /&gt;
&lt;br /&gt;
USB connects one &amp;#039;&amp;#039;&amp;#039;host&amp;#039;&amp;#039;&amp;#039; (the computer) to many &amp;#039;&amp;#039;&amp;#039;devices&amp;#039;&amp;#039;&amp;#039;. The most important rule is that &amp;#039;&amp;#039;&amp;#039;the host always starts communication&amp;#039;&amp;#039;&amp;#039;. A device never sends anything on its own: it only answers when the host asks. When the host asks a device for data, the device answers in one of three ways:&lt;br /&gt;
&lt;br /&gt;
* with the data;&lt;br /&gt;
* with a &amp;#039;&amp;#039;&amp;#039;NAK&amp;#039;&amp;#039;&amp;#039;: nothing now, ask again later. This is normal, and the host should keep asking;&lt;br /&gt;
* with a &amp;#039;&amp;#039;&amp;#039;STALL&amp;#039;&amp;#039;&amp;#039;: no, the device refuses the request, or this part of the device is stopped.&lt;br /&gt;
&lt;br /&gt;
=== Devices, interfaces and endpoints ===&lt;br /&gt;
&lt;br /&gt;
A device describes itself to the host with &amp;#039;&amp;#039;&amp;#039;descriptors&amp;#039;&amp;#039;&amp;#039;, when it is plugged in. They form a tree:&lt;br /&gt;
&lt;br /&gt;
* the &amp;#039;&amp;#039;&amp;#039;device&amp;#039;&amp;#039;&amp;#039;: its vendor and product IDs (VID and PID), its name, its serial number;&lt;br /&gt;
** a &amp;#039;&amp;#039;&amp;#039;configuration&amp;#039;&amp;#039;&amp;#039;: almost every device has exactly one;&lt;br /&gt;
*** one or more &amp;#039;&amp;#039;&amp;#039;interfaces&amp;#039;&amp;#039;&amp;#039;: one function of the device. A webcam with a microphone has one interface for the video, and one for the sound. Each interface has a &amp;#039;&amp;#039;&amp;#039;class&amp;#039;&amp;#039;&amp;#039; (audio, keyboard, storage, ...). A class of 0xFF means that the interface is &amp;#039;&amp;#039;&amp;#039;vendor-specific&amp;#039;&amp;#039;&amp;#039;: its protocol is known only to its own driver;&lt;br /&gt;
**** the &amp;#039;&amp;#039;&amp;#039;endpoints&amp;#039;&amp;#039;&amp;#039; of the interface: the places where data goes in or out of the device.&lt;br /&gt;
&lt;br /&gt;
A driver in Linux binds to an interface, not to a whole device. Our boards have exactly one interface, with three endpoints: a bulk endpoint in each direction for data, and an interrupt endpoint for events. So the driver of a board binds to that interface, and has the whole board to itself.&lt;br /&gt;
&lt;br /&gt;
An &amp;#039;&amp;#039;&amp;#039;endpoint&amp;#039;&amp;#039;&amp;#039; has a number, from 1 to 15, and a &amp;#039;&amp;#039;&amp;#039;direction&amp;#039;&amp;#039;&amp;#039;, which is always seen from the host: &amp;#039;&amp;#039;&amp;#039;IN&amp;#039;&amp;#039;&amp;#039; means from the device to the host, &amp;#039;&amp;#039;&amp;#039;OUT&amp;#039;&amp;#039;&amp;#039; from the host to the device. The direction is the top bit of the endpoint &amp;#039;&amp;#039;&amp;#039;address&amp;#039;&amp;#039;&amp;#039;: 0x81 is endpoint 1 IN, 0x01 is endpoint 1 OUT. Every device also has &amp;#039;&amp;#039;&amp;#039;endpoint 0&amp;#039;&amp;#039;&amp;#039;, which works both ways, and is used for &amp;#039;&amp;#039;&amp;#039;control&amp;#039;&amp;#039;&amp;#039; requests: commands and settings. Each endpoint also has a &amp;#039;&amp;#039;&amp;#039;maximum packet size&amp;#039;&amp;#039;&amp;#039; (&amp;lt;code&amp;gt;wMaxPacketSize&amp;lt;/code&amp;gt;), the most bytes that one packet on it can carry: on our boards, 64 bytes for endpoint 0 and the bulk endpoints, and 8 bytes for the event endpoint, which is exactly one event.&lt;br /&gt;
&lt;br /&gt;
Each endpoint has a &amp;#039;&amp;#039;&amp;#039;transfer type&amp;#039;&amp;#039;&amp;#039;, which says how the host uses it:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Type !! Used for !! On our boards&lt;br /&gt;
|-&lt;br /&gt;
| Control || Commands, settings, small replies. Only on endpoint 0 || Every request in the protocol of the board: &amp;lt;code&amp;gt;GET_INFO&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;IDENTIFY&amp;lt;/code&amp;gt;, ...&lt;br /&gt;
|-&lt;br /&gt;
| Bulk || Large amounts of data, as fast as the bus allows, with no promise about time || The data of a project: what a CC-1 hashes or encrypts, for example&lt;br /&gt;
|-&lt;br /&gt;
| Interrupt || Small, infrequent messages, which must arrive within a known time || Events: the button was pressed, an operation has finished&lt;br /&gt;
|-&lt;br /&gt;
| Isochronous || Sound and video: a fixed rate, and late data is dropped || Not used&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
The name of interrupt endpoints is misleading: the device still cannot speak first. The host asks the endpoint again and again, every few milliseconds (the &amp;#039;&amp;#039;&amp;#039;interval&amp;#039;&amp;#039;&amp;#039;, set in the descriptor), and the device answers with NAK until it has something to say. Nothing reaches the host while nobody asks.&lt;br /&gt;
&lt;br /&gt;
Our boards run at &amp;#039;&amp;#039;&amp;#039;full speed&amp;#039;&amp;#039;&amp;#039; (12 Mbit/s), where a bulk or interrupt &amp;#039;&amp;#039;&amp;#039;packet&amp;#039;&amp;#039;&amp;#039; carries at most 64 bytes. A larger transfer is cut into several packets.&lt;br /&gt;
&lt;br /&gt;
=== Your board&amp;#039;s descriptors ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;lsusb&amp;lt;/code&amp;gt; lists the devices, and &amp;lt;code&amp;gt;lsusb -v&amp;lt;/code&amp;gt; prints all their descriptors. All our boards have the vendor ID &amp;lt;code&amp;gt;0xcafe&amp;lt;/code&amp;gt;, and a product ID for each project:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ lsusb -d cafe:&lt;br /&gt;
Bus 001 Device 004: ID cafe:4301 ARH ARH CC-1&lt;br /&gt;
$ lsusb -v -d cafe:&lt;br /&gt;
...&lt;br /&gt;
  idVendor           0xcafe&lt;br /&gt;
  idProduct          0x4301&lt;br /&gt;
  bcdDevice            1.00&lt;br /&gt;
  iManufacturer           1 ARH&lt;br /&gt;
  iProduct                2 ARH CC-1&lt;br /&gt;
  iSerial                 3 E6614103E7452D2F&lt;br /&gt;
  ...&lt;br /&gt;
    Interface Descriptor:&lt;br /&gt;
      bInterfaceNumber        0&lt;br /&gt;
      bNumEndpoints           3&lt;br /&gt;
      bInterfaceClass       255 Vendor Specific Class&lt;br /&gt;
      bInterfaceSubClass      0&lt;br /&gt;
      bInterfaceProtocol      0&lt;br /&gt;
      Endpoint Descriptor:&lt;br /&gt;
        bEndpointAddress     0x01  EP 1 OUT&lt;br /&gt;
        bmAttributes            2&lt;br /&gt;
          Transfer Type            Bulk&lt;br /&gt;
        wMaxPacketSize     0x0040  1x 64 bytes&lt;br /&gt;
      Endpoint Descriptor:&lt;br /&gt;
        bEndpointAddress     0x81  EP 1 IN&lt;br /&gt;
        bmAttributes            2&lt;br /&gt;
          Transfer Type            Bulk&lt;br /&gt;
        wMaxPacketSize     0x0040  1x 64 bytes&lt;br /&gt;
      Endpoint Descriptor:&lt;br /&gt;
        bEndpointAddress     0x82  EP 2 IN&lt;br /&gt;
        bmAttributes            3&lt;br /&gt;
          Transfer Type            Interrupt&lt;br /&gt;
        wMaxPacketSize     0x0008  1x 8 bytes&lt;br /&gt;
        bInterval              10&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This CC-1 has one vendor-specific interface, with a bulk endpoint in each direction for its data, and an interrupt IN endpoint of 8 bytes for its events, which the host asks every 10 ms. Look at the descriptors of your own board: it has the same three endpoints, and what travels on the two bulk endpoints depends on your project.&lt;br /&gt;
&lt;br /&gt;
=== What every board answers ===&lt;br /&gt;
&lt;br /&gt;
Every board for our lab, for all projects, answers a small common set of control requests, and sends events in the same format. They are described in full in section 4 of the specification of your project. The example driver of this lab uses only these:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Request !! Number !! Direction !! wValue !! Data&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;GET_INFO&amp;lt;/code&amp;gt; || 0x00 || IN || 0 || 16 bytes: what the board is (below)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;IDENTIFY&amp;lt;/code&amp;gt; || 0xE0 || OUT || How many times to flash the LED, 1 to 10 || None&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;GET_BOARD_STATUS&amp;lt;/code&amp;gt; || 0xE1 || IN || 0 || 8 bytes: uptime, event counters, the button&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SET_LABEL&amp;lt;/code&amp;gt; || 0xE2 || OUT || 0 || 16 bytes: a name for the board, padded with zero bytes&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;GET_LABEL&amp;lt;/code&amp;gt; || 0xE3 || IN || 0 || 16 bytes: the name set before&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;GET_INFO&amp;lt;/code&amp;gt; starts with a &amp;#039;&amp;#039;&amp;#039;magic&amp;#039;&amp;#039;&amp;#039; number: the characters &amp;lt;code&amp;gt;&amp;quot;ARH&amp;quot;&amp;lt;/code&amp;gt;, which are the same on every board, followed by one character which names the project (&amp;lt;code&amp;gt;&amp;quot;ARH1&amp;quot;&amp;lt;/code&amp;gt; for the CC-1). Then come the version of the project&amp;#039;s protocol, the version of the firmware, and a few fields which the project defines.&lt;br /&gt;
&lt;br /&gt;
Each &amp;#039;&amp;#039;&amp;#039;event&amp;#039;&amp;#039;&amp;#039; is one 8-byte packet on the first interrupt IN endpoint: a type, an argument, a sequence number, and the time in milliseconds since the board was powered up. Type 0x01 is a short press of the button which the board has no other use for. The other types belong to the project.&lt;br /&gt;
&lt;br /&gt;
== A USB driver ==&lt;br /&gt;
&lt;br /&gt;
A USB driver is a &amp;lt;code&amp;gt;struct usb_driver&amp;lt;/code&amp;gt;, with a table of the devices which it can handle, and two functions which the USB core calls:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/usb.h&amp;gt;&lt;br /&gt;
struct usb_driver {&lt;br /&gt;
	const char *name;&lt;br /&gt;
	int (*probe)(struct usb_interface *intf, const struct usb_device_id *id);&lt;br /&gt;
	void (*disconnect)(struct usb_interface *intf);&lt;br /&gt;
	const struct usb_device_id *id_table;&lt;br /&gt;
	...&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
int usb_register(struct usb_driver *driver);&lt;br /&gt;
void usb_deregister(struct usb_driver *driver);&lt;br /&gt;
module_usb_driver(driver);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;module_usb_driver()&amp;lt;/code&amp;gt; writes the module&amp;#039;s init and exit functions for you: init registers the driver, exit deregisters it. A USB driver&amp;#039;s module usually has nothing else to do when it is loaded. All the work happens per device, in &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== Which devices: the ID table ===&lt;br /&gt;
&lt;br /&gt;
When a device is plugged in, the USB core compares each of its interfaces with the ID table of every USB driver, and calls the &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; of the first driver which matches:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
/* The seven lab boards: vendor 0xcafe, one product ID per project */&lt;br /&gt;
static const struct usb_device_id arhboard_ids[] = {&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4301) },	/* CC-1 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4302) },	/* EL-2 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4303) },	/* FV-3 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4304) },	/* MB-4 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4305) },	/* TW-5 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4306) },	/* WP-6 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4307) },	/* BP-7 */&lt;br /&gt;
	{}&lt;br /&gt;
};&lt;br /&gt;
MODULE_DEVICE_TABLE(usb, arhboard_ids);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The table ends with an empty entry. A few macros fill in an entry:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Macro !! Matches&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;USB_DEVICE(vid, pid)&amp;lt;/code&amp;gt; || One product. The example lists the seven boards this way; the driver of your project has a single entry, with the PID of your board&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;USB_VENDOR_AND_INTERFACE_INFO(vid, class, subclass, protocol)&amp;lt;/code&amp;gt; || Every interface of that class, on every product of that vendor&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;USB_INTERFACE_INFO(class, subclass, protocol)&amp;lt;/code&amp;gt; || Every interface of that class, from any vendor: how the drivers of standard classes (keyboards, storage, ...) bind&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;MODULE_DEVICE_TABLE()&amp;lt;/code&amp;gt; copies the table into the module file. The system uses it to load the right module by itself when a device is plugged in. &amp;lt;code&amp;gt;modinfo&amp;lt;/code&amp;gt; shows it, as &amp;lt;code&amp;gt;alias&amp;lt;/code&amp;gt; lines.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Only one driver can own an interface. While &amp;lt;code&amp;gt;arhboard&amp;lt;/code&amp;gt; is loaded, it takes your board, and the driver of your project never gets a &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt;. Unload it first, with &amp;lt;code&amp;gt;sudo rmmod arhboard&amp;lt;/code&amp;gt;, and the other way around.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== probe() and disconnect() ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; is called once for each matching interface, when the device is plugged in, or when the driver is loaded with the device already there. It decides whether the driver takes the interface: it returns 0 to take it, or an error, usually &amp;lt;code&amp;gt;-ENODEV&amp;lt;/code&amp;gt;, to leave it. If it takes it, it should:&lt;br /&gt;
&lt;br /&gt;
# allocate a structure for this device, which keeps everything the driver knows about it. There may be several boards at once, so nothing about a board goes in a global variable;&lt;br /&gt;
# find the endpoints which it needs;&lt;br /&gt;
# check that the device is really what the driver expects;&lt;br /&gt;
# attach its structure to the interface, with &amp;lt;code&amp;gt;usb_set_intfdata()&amp;lt;/code&amp;gt;, so that &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt; finds it again with &amp;lt;code&amp;gt;usb_get_intfdata()&amp;lt;/code&amp;gt;;&lt;br /&gt;
# make the device available to programs: here, a file in &amp;lt;code&amp;gt;/dev&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt; is called when the device is unplugged, or when the driver is unloaded. It cannot fail, and cannot stop the unplugging: when it is called, the device may already be gone. It undoes what &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; did. See [[#Unplugging|Unplugging]] for what happens to programs which still have the file open.&lt;br /&gt;
&lt;br /&gt;
Print with &amp;lt;code&amp;gt;dev_info()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;dev_err()&amp;lt;/code&amp;gt; and so on, with &amp;lt;code&amp;gt;&amp;amp;intf-&amp;gt;dev&amp;lt;/code&amp;gt;. The messages then start with the name of the driver and the place of the device on the bus, so that two boards can be told apart in the log:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
arhboard 1-1:1.0: project &amp;#039;1&amp;#039;, protocol 1.0, firmware 1.0, /dev/arhboard0&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Finding the endpoints ===&lt;br /&gt;
&lt;br /&gt;
A driver should not assume the addresses of its endpoints: &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; finds them in the descriptors of the interface, in three steps.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Step 1: find the descriptor of the endpoint.&amp;#039;&amp;#039;&amp;#039; The current descriptors of the interface are in &amp;lt;code&amp;gt;intf-&amp;gt;cur_altsetting&amp;lt;/code&amp;gt;. &amp;lt;code&amp;gt;usb_find_common_endpoints()&amp;lt;/code&amp;gt; searches them, and returns the first endpoint of each kind. A few shorter functions return only one kind:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/usb.h&amp;gt;&lt;br /&gt;
int usb_find_common_endpoints(struct usb_host_interface *alt,&lt;br /&gt;
		struct usb_endpoint_descriptor **bulk_in,&lt;br /&gt;
		struct usb_endpoint_descriptor **bulk_out,&lt;br /&gt;
		struct usb_endpoint_descriptor **int_in,&lt;br /&gt;
		struct usb_endpoint_descriptor **int_out);&lt;br /&gt;
int usb_find_bulk_in_endpoint(struct usb_host_interface *alt, struct usb_endpoint_descriptor **bulk_in);&lt;br /&gt;
int usb_find_bulk_out_endpoint(struct usb_host_interface *alt, struct usb_endpoint_descriptor **bulk_out);&lt;br /&gt;
int usb_find_int_in_endpoint(struct usb_host_interface *alt, struct usb_endpoint_descriptor **int_in);&lt;br /&gt;
&lt;br /&gt;
int usb_endpoint_maxp(const struct usb_endpoint_descriptor *epd);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;alt&amp;lt;/code&amp;gt; is &amp;lt;code&amp;gt;intf-&amp;gt;cur_altsetting&amp;lt;/code&amp;gt;. Pass &amp;lt;code&amp;gt;NULL&amp;lt;/code&amp;gt; for the kinds you don&amp;#039;t need. They return 0, or &amp;lt;code&amp;gt;-ENXIO&amp;lt;/code&amp;gt; if one of the endpoints you asked for is missing.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Step 2: check it.&amp;#039;&amp;#039;&amp;#039; In an endpoint descriptor, &amp;lt;code&amp;gt;bEndpointAddress&amp;lt;/code&amp;gt; is the address of the endpoint, and &amp;lt;code&amp;gt;usb_endpoint_maxp()&amp;lt;/code&amp;gt; returns its largest packet. Refuse a device whose endpoint is not what the driver expects.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Step 3: make a pipe.&amp;#039;&amp;#039;&amp;#039; A transfer does not take the address of an endpoint directly, but a &amp;#039;&amp;#039;&amp;#039;pipe&amp;#039;&amp;#039;&amp;#039;, a number which combines the device, the endpoint, its direction and its type. Make it once, and keep it in the structure of the device:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Endpoint !! IN !! OUT&lt;br /&gt;
|-&lt;br /&gt;
| Control (endpoint 0) || &amp;lt;code&amp;gt;usb_rcvctrlpipe(udev, 0)&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;usb_sndctrlpipe(udev, 0)&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| Bulk || &amp;lt;code&amp;gt;usb_rcvbulkpipe(udev, addr)&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;usb_sndbulkpipe(udev, addr)&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| Interrupt || &amp;lt;code&amp;gt;usb_rcvintpipe(udev, addr)&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;usb_sndintpipe(udev, addr)&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;udev&amp;lt;/code&amp;gt; is the &amp;lt;code&amp;gt;struct usb_device&amp;lt;/code&amp;gt; of the whole device, which &amp;lt;code&amp;gt;interface_to_usbdev(intf)&amp;lt;/code&amp;gt; returns. The example does the three steps for its event endpoint:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
	/* The event endpoint: the first interrupt IN endpoint */&lt;br /&gt;
	ret = usb_find_int_in_endpoint(intf-&amp;gt;cur_altsetting, &amp;amp;ev_ep);&lt;br /&gt;
	if (ret) {&lt;br /&gt;
		dev_err(&amp;amp;intf-&amp;gt;dev, &amp;quot;no interrupt IN endpoint\n&amp;quot;);&lt;br /&gt;
		goto err;&lt;br /&gt;
	}&lt;br /&gt;
	if (usb_endpoint_maxp(ev_ep) != sizeof(struct wire_event)) {&lt;br /&gt;
		dev_err(&amp;amp;intf-&amp;gt;dev, &amp;quot;event endpoint is not 8 bytes\n&amp;quot;);&lt;br /&gt;
		ret = -ENODEV;&lt;br /&gt;
		goto err;&lt;br /&gt;
	}&lt;br /&gt;
	dev-&amp;gt;ev_pipe = usb_rcvintpipe(dev-&amp;gt;udev, ev_ep-&amp;gt;bEndpointAddress);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== One file per board ===&lt;br /&gt;
&lt;br /&gt;
In the last lab, we got a device number, a &amp;lt;code&amp;gt;struct cdev&amp;lt;/code&amp;gt; and a class in three steps. A USB driver does all three with one call:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/usb.h&amp;gt;&lt;br /&gt;
struct usb_class_driver {&lt;br /&gt;
	char *name;          /* &amp;quot;arhboard%d&amp;quot;: %d becomes 0, 1, ... */&lt;br /&gt;
	char *(*devnode)(const struct device *dev, umode_t *mode);&lt;br /&gt;
	const struct file_operations *fops;&lt;br /&gt;
	int minor_base;&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
int usb_register_dev(struct usb_interface *intf, struct usb_class_driver *class_driver);&lt;br /&gt;
void usb_deregister_dev(struct usb_interface *intf, struct usb_class_driver *class_driver);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;usb_register_dev()&amp;lt;/code&amp;gt; takes the next free minor number from &amp;lt;code&amp;gt;minor_base&amp;lt;/code&amp;gt; on, of major number 180, which the kernel keeps for USB devices. It sets &amp;lt;code&amp;gt;intf-&amp;gt;minor&amp;lt;/code&amp;gt;, and makes the device &amp;lt;code&amp;gt;arhboard0&amp;lt;/code&amp;gt; in the class &amp;lt;code&amp;gt;usbmisc&amp;lt;/code&amp;gt;, so that the file &amp;lt;code&amp;gt;/dev/arhboard0&amp;lt;/code&amp;gt; appears. A second board gets &amp;lt;code&amp;gt;/dev/arhboard1&amp;lt;/code&amp;gt;, and so on. The example uses minors from 192, and the driver of your project uses minors from 208, so that both can be loaded at once.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Major 180 is on OrbStack&amp;#039;s list of allowed numbers (see the last lab), so these files can be opened there too. OrbStack does not create them by itself, though: &amp;lt;code&amp;gt;make -C driver load&amp;lt;/code&amp;gt; creates them with &amp;lt;code&amp;gt;mknod&amp;lt;/code&amp;gt;, from &amp;lt;code&amp;gt;/sys/class/usbmisc/arhboardN/dev&amp;lt;/code&amp;gt;. For a board which you attach after loading the driver, run &amp;lt;code&amp;gt;make -C driver nodes&amp;lt;/code&amp;gt;.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;open()&amp;lt;/code&amp;gt; gets only the inode, and must find the board from its minor number. &amp;lt;code&amp;gt;usb_find_interface()&amp;lt;/code&amp;gt; returns the interface of this driver which has that minor:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
static int arhboard_open(struct inode *inode, struct file *file)&lt;br /&gt;
{&lt;br /&gt;
	struct usb_interface *intf;&lt;br /&gt;
	struct arhboard *dev;&lt;br /&gt;
&lt;br /&gt;
	intf = usb_find_interface(&amp;amp;arhboard_driver, iminor(inode));&lt;br /&gt;
	if (!intf)&lt;br /&gt;
		return -ENODEV;&lt;br /&gt;
	dev = usb_get_intfdata(intf);&lt;br /&gt;
	if (!dev)&lt;br /&gt;
		return -ENODEV;&lt;br /&gt;
&lt;br /&gt;
	kref_get(&amp;amp;dev-&amp;gt;kref);&lt;br /&gt;
	file-&amp;gt;private_data = dev;&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
From then on, every file operation finds the board in &amp;lt;code&amp;gt;file-&amp;gt;private_data&amp;lt;/code&amp;gt;, as in the last lab. &amp;lt;code&amp;gt;kref_get()&amp;lt;/code&amp;gt; is explained in [[#Unplugging|Unplugging]].&lt;br /&gt;
&lt;br /&gt;
A device which is a &amp;#039;&amp;#039;&amp;#039;stream&amp;#039;&amp;#039;&amp;#039;, with no position to seek to (most project boards), should say so in its &amp;lt;code&amp;gt;open()&amp;lt;/code&amp;gt;, by ending it with &amp;lt;code&amp;gt;stream_open()&amp;lt;/code&amp;gt; (from &amp;lt;code&amp;gt;&amp;amp;lt;linux/fs.h&amp;amp;gt;&amp;lt;/code&amp;gt;) instead of &amp;lt;code&amp;gt;return 0&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
	file-&amp;gt;private_data = dev;&lt;br /&gt;
	return stream_open(inode, file);   /* always returns 0 */&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;lseek()&amp;lt;/code&amp;gt; on the file then fails with &amp;lt;code&amp;gt;ESPIPE&amp;lt;/code&amp;gt;, and so do &amp;lt;code&amp;gt;pread()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;pwrite()&amp;lt;/code&amp;gt;, which take a position. Your device is a stream unless its data has positions which a program can jump to. (The example has no &amp;lt;code&amp;gt;llseek&amp;lt;/code&amp;gt; function, so &amp;lt;code&amp;gt;lseek()&amp;lt;/code&amp;gt; already fails on it; it leaves &amp;lt;code&amp;gt;stream_open()&amp;lt;/code&amp;gt; out to stay short.)&lt;br /&gt;
&lt;br /&gt;
== Talking to the device ==&lt;br /&gt;
&lt;br /&gt;
=== Buffers ===&lt;br /&gt;
&lt;br /&gt;
The USB controller moves the data of a transfer to and from memory by itself, with &amp;#039;&amp;#039;&amp;#039;DMA&amp;#039;&amp;#039;&amp;#039;, without the processor. It can only do that with memory from &amp;lt;code&amp;gt;kmalloc()&amp;lt;/code&amp;gt;. &amp;#039;&amp;#039;&amp;#039;A transfer buffer must never be on the stack, or a global variable&amp;#039;&amp;#039;&amp;#039;: the transfer may fail, or corrupt memory next to the buffer, and on some machines it seems to work, until it doesn&amp;#039;t.&lt;br /&gt;
&lt;br /&gt;
The example allocates its buffers once, in &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt;, and keeps them in its structure:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
	dev-&amp;gt;ctrl_buf = kmalloc(CTRL_BUF_LEN, GFP_KERNEL);&lt;br /&gt;
	dev-&amp;gt;ev_buf = kmalloc(sizeof(struct wire_event), GFP_KERNEL);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A buffer which is used by one transfer at a time, like these, needs a lock: see [[#Locking|Locking]].&lt;br /&gt;
&lt;br /&gt;
=== Byte order ===&lt;br /&gt;
&lt;br /&gt;
All the numbers which our boards send and receive are &amp;#039;&amp;#039;&amp;#039;little-endian&amp;#039;&amp;#039;&amp;#039;: the lowest byte comes first. Most processors which run Linux are little-endian too, but not all of them, and a driver must work on any machine. The kernel has types which say the byte order of a value, and functions which convert it to and from the byte order of the machine:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;asm/byteorder.h&amp;gt;, which most kernel headers include&lt;br /&gt;
u16 le16_to_cpu(__le16 x);    __le16 cpu_to_le16(u16 x);&lt;br /&gt;
u32 le32_to_cpu(__le32 x);    __le32 cpu_to_le32(u32 x);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
On a little-endian machine, they do nothing, and cost nothing. Describe what the device sends with a structure of these types, and convert each field when you use it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
/* What the board sends, exactly as it is on the wire: little-endian */&lt;br /&gt;
struct wire_event {&lt;br /&gt;
	u8 type;&lt;br /&gt;
	u8 arg;&lt;br /&gt;
	__le16 seq;&lt;br /&gt;
	__le32 time_ms;&lt;br /&gt;
};&lt;br /&gt;
static_assert(sizeof(struct wire_event) == 8);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The structure must be exactly the 8 bytes that the board sends. If the compiler added padding between the fields, it would not be, and &amp;lt;code&amp;gt;static_assert()&amp;lt;/code&amp;gt; catches that when you build. &amp;lt;code&amp;gt;__le16&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;__le32&amp;lt;/code&amp;gt; mark the fields which are in the board&amp;#039;s byte order: read them with &amp;lt;code&amp;gt;le16_to_cpu()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;le32_to_cpu()&amp;lt;/code&amp;gt;, never directly.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Keep the structures of the wire and the structures of the shared header apart. The wire structures are what the device sends, in its byte order. The structures in &amp;lt;code&amp;gt;uapi/&amp;lt;/code&amp;gt; are what the driver gives to programs, in the byte order of the machine, with the &amp;lt;code&amp;gt;__u8&amp;lt;/code&amp;gt; ... &amp;lt;code&amp;gt;__u32&amp;lt;/code&amp;gt; types of the last lab. The driver converts one into the other, field by field. Never copy the bytes from the device straight to user space.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Blocking calls ===&lt;br /&gt;
&lt;br /&gt;
The kernel has one function for each transfer type, which sends the transfer, waits until it ends, and returns:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/usb.h&amp;gt;&lt;br /&gt;
int usb_control_msg(struct usb_device *dev, unsigned int pipe,&lt;br /&gt;
	__u8 request, __u8 requesttype, __u16 value, __u16 index,&lt;br /&gt;
	void *data, __u16 size, int timeout);&lt;br /&gt;
int usb_interrupt_msg(struct usb_device *dev, unsigned int pipe,&lt;br /&gt;
	void *data, int len, int *actual_length, int timeout);&lt;br /&gt;
int usb_bulk_msg(struct usb_device *dev, unsigned int pipe,&lt;br /&gt;
	void *data, int len, int *actual_length, int timeout);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;timeout&amp;lt;/code&amp;gt; is in milliseconds. They sleep, so they can only be called where sleeping is allowed: in file operations, in &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; and in &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt;, but not while holding a spinlock. They return a negative error if the transfer failed, and &amp;lt;code&amp;gt;-ETIMEDOUT&amp;lt;/code&amp;gt; in particular if the device did not respond in time. &amp;lt;code&amp;gt;usb_control_msg()&amp;lt;/code&amp;gt; returns the number of bytes moved. The other two return 0, and store the number of bytes moved in &amp;lt;code&amp;gt;*actual_length&amp;lt;/code&amp;gt;. &amp;#039;&amp;#039;&amp;#039;It can be less than you asked for&amp;#039;&amp;#039;&amp;#039;, and a driver should always check it. They store it when they fail, too: see [[#A slice which times out may have moved data|A slice which times out may have moved data]].&lt;br /&gt;
&lt;br /&gt;
The errors which you will meet most often:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Error !! Meaning !! What to do&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-EPIPE&amp;lt;/code&amp;gt; || The device answered with STALL: it refused the request, or the endpoint is halted || For a control request, return it to the program: the request was refused. For a bulk endpoint, see [[#Halted endpoints|Halted endpoints]]&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-ETIMEDOUT&amp;lt;/code&amp;gt; || The device did not finish in time: for an IN endpoint, it had nothing to send || Wait again, or give up: see below&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-EOVERFLOW&amp;lt;/code&amp;gt; || The device sent more than the buffer can hold || Use a buffer of whole packets: see [[#Bulk transfers|Bulk transfers]]&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-EPROTO&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;-EILSEQ&amp;lt;/code&amp;gt; || The packet was damaged on the cable || Return an error. It is rare, unless the cable is bad&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-ENODEV&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;-ESHUTDOWN&amp;lt;/code&amp;gt; || The device is gone || Return &amp;lt;code&amp;gt;-ENODEV&amp;lt;/code&amp;gt; to userspace&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=== Waiting for a long time ===&lt;br /&gt;
&lt;br /&gt;
Some calls must wait for as long as it takes: a program which reads an event waits until somebody presses the button, maybe forever. A transfer with a very long timeout would do that, but then nothing could stop it. The blocking calls cannot be interrupted: they return only when the transfer ends or its timeout runs out, and a signal does not wake them. So Ctrl+C would do nothing, the process could not even be killed while it waits, and every other call which needs the same lock would wait behind it.&lt;br /&gt;
&lt;br /&gt;
So &amp;#039;&amp;#039;&amp;#039;a long wait is a loop of short waits&amp;#039;&amp;#039;&amp;#039;. Each transfer has a short timeout, 100 ms in the example. When it times out, the loop checks what may have happened meanwhile, and starts another one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
	for (;;) {&lt;br /&gt;
		if (mutex_lock_interruptible(&amp;amp;dev-&amp;gt;ev_lock))&lt;br /&gt;
			return -ERESTARTSYS;&lt;br /&gt;
		if (dev-&amp;gt;gone)&lt;br /&gt;
			ret = -ENODEV;&lt;br /&gt;
		else&lt;br /&gt;
			ret = usb_interrupt_msg(dev-&amp;gt;udev, dev-&amp;gt;ev_pipe, dev-&amp;gt;ev_buf,&lt;br /&gt;
						sizeof(struct wire_event), &amp;amp;actual, SLICE_MS);&lt;br /&gt;
		/* ... use the data while we still hold the lock ... */&lt;br /&gt;
		mutex_unlock(&amp;amp;dev-&amp;gt;ev_lock);&lt;br /&gt;
&lt;br /&gt;
		if (ret != -ETIMEDOUT)&lt;br /&gt;
			break;          /* the data, or a real error */&lt;br /&gt;
		/* No event in this slice */&lt;br /&gt;
		if (file-&amp;gt;f_flags &amp;amp; O_NONBLOCK)&lt;br /&gt;
			return -EAGAIN;&lt;br /&gt;
		if (signal_pending(current))&lt;br /&gt;
			return -ERESTARTSYS;&lt;br /&gt;
	}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Between two slices:&lt;br /&gt;
&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Signals.&amp;#039;&amp;#039;&amp;#039; &amp;lt;code&amp;gt;signal_pending(current)&amp;lt;/code&amp;gt; is true when the process has a signal waiting, for example after Ctrl+C. Returning &amp;lt;code&amp;gt;-ERESTARTSYS&amp;lt;/code&amp;gt; lets the kernel deliver it. The program sees &amp;lt;code&amp;gt;EINTR&amp;lt;/code&amp;gt;, or, if it is stopped and continued, the call starts again by itself. &amp;lt;code&amp;gt;mutex_lock_interruptible()&amp;lt;/code&amp;gt; does the same while it waits for the lock.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;&amp;lt;code&amp;gt;O_NONBLOCK&amp;lt;/code&amp;gt;.&amp;#039;&amp;#039;&amp;#039; A program which opened the file with &amp;lt;code&amp;gt;O_NONBLOCK&amp;lt;/code&amp;gt; does not want to wait. It gets one slice, and then &amp;lt;code&amp;gt;EAGAIN&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;The lock is free&amp;#039;&amp;#039;&amp;#039;, so another call, or &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt;, can take it. Never wait for longer than one slice while holding a lock.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Unplugging.&amp;#039;&amp;#039;&amp;#039; &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt; sets &amp;lt;code&amp;gt;gone&amp;lt;/code&amp;gt;, and the loop notices it at the next slice.&lt;br /&gt;
&lt;br /&gt;
None of this needs anything new in the kernel: only a loop, and the mutex of the last lab. Every call of your driver which may wait for long should use this pattern.&lt;br /&gt;
&lt;br /&gt;
== Control transfers ==&lt;br /&gt;
&lt;br /&gt;
A control request starts with an 8-byte &amp;#039;&amp;#039;&amp;#039;setup packet&amp;#039;&amp;#039;&amp;#039;, which the host sends to endpoint 0. Its fields are the arguments of &amp;lt;code&amp;gt;usb_control_msg()&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Field !! Argument !! Meaning&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;bmRequestType&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;requesttype&amp;lt;/code&amp;gt; || The direction of the data, who defined the request, and who it is for: see below&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;bRequest&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;request&amp;lt;/code&amp;gt; || The number of the request&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;wValue&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;value&amp;lt;/code&amp;gt; || A 16-bit argument, defined by the request&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;wIndex&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;index&amp;lt;/code&amp;gt; || Another 16-bit argument. For a request to an interface, the number of the interface&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;wLength&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;size&amp;lt;/code&amp;gt; || The number of bytes in the data stage. May be 0&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
After the setup packet comes the &amp;#039;&amp;#039;&amp;#039;data stage&amp;#039;&amp;#039;&amp;#039;, &amp;lt;code&amp;gt;wLength&amp;lt;/code&amp;gt; bytes in the direction which &amp;lt;code&amp;gt;bmRequestType&amp;lt;/code&amp;gt; gives, and then the device confirms that it has finished. If it refuses the request, it answers with STALL instead, and &amp;lt;code&amp;gt;usb_control_msg()&amp;lt;/code&amp;gt; returns &amp;lt;code&amp;gt;-EPIPE&amp;lt;/code&amp;gt;. This is not a problem with the device: it is its way of saying no.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;bmRequestType&amp;lt;/code&amp;gt; is made of three parts, with a macro for each:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Part !! Our boards !! Other values&lt;br /&gt;
|-&lt;br /&gt;
| Direction || &amp;lt;code&amp;gt;USB_DIR_IN&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;USB_DIR_OUT&amp;lt;/code&amp;gt; ||&lt;br /&gt;
|-&lt;br /&gt;
| Type || &amp;lt;code&amp;gt;USB_TYPE_VENDOR&amp;lt;/code&amp;gt;: a request which the maker of the device defined || &amp;lt;code&amp;gt;USB_TYPE_STANDARD&amp;lt;/code&amp;gt;, which every device answers, and &amp;lt;code&amp;gt;USB_TYPE_CLASS&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| Recipient || &amp;lt;code&amp;gt;USB_RECIP_INTERFACE&amp;lt;/code&amp;gt;: for interface 0 || &amp;lt;code&amp;gt;USB_RECIP_DEVICE&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;USB_RECIP_ENDPOINT&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
For the requests of our boards, &amp;lt;code&amp;gt;bmRequestType&amp;lt;/code&amp;gt; is 0xC1 for IN, and 0x41 for OUT. The example wraps &amp;lt;code&amp;gt;usb_control_msg()&amp;lt;/code&amp;gt; in two functions, one for each direction. The data is always in &amp;lt;code&amp;gt;dev-&amp;gt;ctrl_buf&amp;lt;/code&amp;gt;, which comes from &amp;lt;code&amp;gt;kmalloc()&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
#define REQTYPE_IN (USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_INTERFACE)   /* 0xC1 */&lt;br /&gt;
#define REQTYPE_OUT (USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE) /* 0x41 */&lt;br /&gt;
&lt;br /&gt;
static int arhboard_ctrl_in(struct arhboard *dev, u8 request, u16 len)&lt;br /&gt;
{&lt;br /&gt;
	int ret = usb_control_msg(dev-&amp;gt;udev, usb_rcvctrlpipe(dev-&amp;gt;udev, 0),&lt;br /&gt;
				  request, REQTYPE_IN, 0, 0, dev-&amp;gt;ctrl_buf, len,&lt;br /&gt;
				  CTRL_TIMEOUT_MS);&lt;br /&gt;
	if (ret &amp;lt; 0)&lt;br /&gt;
		return ret; /* -EPIPE: the board refused (STALL) */&lt;br /&gt;
	if (ret != len)&lt;br /&gt;
		return -EPROTO; /* a short answer is an error too */&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static int arhboard_ctrl_out(struct arhboard *dev, u8 request, u16 value,&lt;br /&gt;
			     u16 len)&lt;br /&gt;
{&lt;br /&gt;
	int ret = usb_control_msg(dev-&amp;gt;udev, usb_sndctrlpipe(dev-&amp;gt;udev, 0),&lt;br /&gt;
				  request, REQTYPE_OUT, value, 0,&lt;br /&gt;
				  len ? dev-&amp;gt;ctrl_buf : NULL, len,&lt;br /&gt;
				  CTRL_TIMEOUT_MS);&lt;br /&gt;
	if (ret &amp;lt; 0)&lt;br /&gt;
		return ret;&lt;br /&gt;
	if (ret != len)&lt;br /&gt;
		return -EPROTO;&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A control request is short, so it doesn&amp;#039;t need the loop of the last section: one transfer with a timeout of a second is enough.&lt;br /&gt;
&lt;br /&gt;
=== Checking the device in probe() ===&lt;br /&gt;
&lt;br /&gt;
The vendor ID &amp;lt;code&amp;gt;0xcafe&amp;lt;/code&amp;gt; is not registered, so another device could use it too, even with the same product ID. Before it takes the interface, &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; asks the board what it is, with &amp;lt;code&amp;gt;GET_INFO&amp;lt;/code&amp;gt;, and refuses it if the magic does not start with &amp;lt;code&amp;gt;&amp;quot;ARH&amp;quot;&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
	ret = arhboard_ctrl_in(dev, REQ_GET_INFO, sizeof(struct wire_info));&lt;br /&gt;
	if (ret) {&lt;br /&gt;
		dev_err(&amp;amp;intf-&amp;gt;dev, &amp;quot;GET_INFO failed: %pe\n&amp;quot;, ERR_PTR(ret));&lt;br /&gt;
		goto err;&lt;br /&gt;
	}&lt;br /&gt;
	info_from_wire(&amp;amp;info, (struct wire_info *)dev-&amp;gt;ctrl_buf);&lt;br /&gt;
	if ((info.magic &amp;amp; 0x00ffffff) != MAGIC_ARH) {&lt;br /&gt;
		dev_err(&amp;amp;intf-&amp;gt;dev, &amp;quot;not a lab board (magic 0x%08x)\n&amp;quot;,&lt;br /&gt;
			info.magic);&lt;br /&gt;
		ret = -ENODEV;&lt;br /&gt;
		goto err;&lt;br /&gt;
	}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The driver of your project should check the whole magic, and the major version of its protocol, and refuse a board which runs other firmware.&lt;br /&gt;
&lt;br /&gt;
=== Control requests as ioctls ===&lt;br /&gt;
&lt;br /&gt;
A request which returns a structure, or takes a number, fits an &amp;lt;code&amp;gt;ioctl()&amp;lt;/code&amp;gt;. The example has one for each common request, in its shared header:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
#define ARHBOARD_IOC_MAGIC 0xB8&lt;br /&gt;
#define ARHBOARD_IOC_GET_INFO   _IOR(ARHBOARD_IOC_MAGIC, 1, struct arhboard_info)&lt;br /&gt;
#define ARHBOARD_IOC_GET_STATUS _IOR(ARHBOARD_IOC_MAGIC, 2, struct arhboard_status)&lt;br /&gt;
#define ARHBOARD_IOC_GET_LABEL  _IOR(ARHBOARD_IOC_MAGIC, 3, struct arhboard_label)&lt;br /&gt;
/* Flash the LED: 1 to 10 times. Anything else is refused by the board (EPIPE). */&lt;br /&gt;
#define ARHBOARD_IOC_IDENTIFY   _IOW(ARHBOARD_IOC_MAGIC, 4, __u32)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
They show the three kinds of control request:&lt;br /&gt;
&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;IN, with data&amp;#039;&amp;#039;&amp;#039;: &amp;lt;code&amp;gt;GET_INFO&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;GET_BOARD_STATUS&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;GET_LABEL&amp;lt;/code&amp;gt;. The driver reads the reply into &amp;lt;code&amp;gt;ctrl_buf&amp;lt;/code&amp;gt;, converts it into the structure of the shared header, and copies that to the program;&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;OUT, with no data&amp;#039;&amp;#039;&amp;#039;: &amp;lt;code&amp;gt;IDENTIFY&amp;lt;/code&amp;gt;. The number of flashes travels in &amp;lt;code&amp;gt;wValue&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;wLength&amp;lt;/code&amp;gt; is 0;&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;OUT, with data&amp;#039;&amp;#039;&amp;#039;: &amp;lt;code&amp;gt;SET_LABEL&amp;lt;/code&amp;gt;, which the example does in &amp;lt;code&amp;gt;write()&amp;lt;/code&amp;gt;: &amp;lt;code&amp;gt;echo bench-3 &amp;gt; /dev/arhboard0&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
	case ARHBOARD_IOC_GET_STATUS: {&lt;br /&gt;
		struct wire_status *w = (struct wire_status *)dev-&amp;gt;ctrl_buf;&lt;br /&gt;
&lt;br /&gt;
		ret = arhboard_ctrl_in(dev, REQ_GET_BOARD_STATUS, sizeof(*w));&lt;br /&gt;
		if (ret)&lt;br /&gt;
			break;&lt;br /&gt;
		out.status.uptime_ms = le32_to_cpu(w-&amp;gt;uptime_ms);&lt;br /&gt;
		out.status.events_dropped = le16_to_cpu(w-&amp;gt;events_dropped);&lt;br /&gt;
		out.status.events_queued = w-&amp;gt;events_queued;&lt;br /&gt;
		out.status.button_down = w-&amp;gt;button_down;&lt;br /&gt;
		out_len = sizeof(out.status);&lt;br /&gt;
		break;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	case ARHBOARD_IOC_IDENTIFY:&lt;br /&gt;
		/* No data stage: the number travels in wValue */&lt;br /&gt;
		ret = arhboard_ctrl_out(dev, REQ_IDENTIFY, flashes, 0);&lt;br /&gt;
		break;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The driver does not check the number of flashes: the board does, and refuses 0 or more than 10 with a STALL. The program then gets &amp;lt;code&amp;gt;EPIPE&amp;lt;/code&amp;gt;. Try it: this is what a refused request looks like, and the requests of your project will be refused in the same way.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; With two boards, &amp;lt;code&amp;gt;IDENTIFY&amp;lt;/code&amp;gt; tells you which file is which board: the LED of the board behind &amp;lt;code&amp;gt;/dev/arhboard1&amp;lt;/code&amp;gt; flashes when you send it to &amp;lt;code&amp;gt;/dev/arhboard1&amp;lt;/code&amp;gt;.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Interrupt transfers: events ==&lt;br /&gt;
&lt;br /&gt;
=== The board keeps the events ===&lt;br /&gt;
&lt;br /&gt;
The host gets an event only when it reads the interrupt endpoint. What happens to the events which come while nobody reads? Our boards keep them: each board has a queue of &amp;lt;code&amp;gt;event_queue_len&amp;lt;/code&amp;gt; events (a field of &amp;lt;code&amp;gt;GET_INFO&amp;lt;/code&amp;gt;), and sends the oldest one each time the host reads. So &amp;#039;&amp;#039;&amp;#039;the driver only needs to read the endpoint when a program asks for an event&amp;#039;&amp;#039;&amp;#039;, and nothing is lost meanwhile.&lt;br /&gt;
&lt;br /&gt;
If nobody reads for a long time, the queue fills up. The board then drops an old event to make room (the oldest one which is not already on its way to the host), and counts it in &amp;lt;code&amp;gt;events_dropped&amp;lt;/code&amp;gt; (in &amp;lt;code&amp;gt;GET_BOARD_STATUS&amp;lt;/code&amp;gt;). Each event has a sequence number, which goes up by one for every event the board makes, so a program sees a gap where events were lost.&lt;br /&gt;
&lt;br /&gt;
=== read() waits for the next event ===&lt;br /&gt;
&lt;br /&gt;
In the example, &amp;lt;code&amp;gt;read()&amp;lt;/code&amp;gt; waits for the next event, with the loop of [[#Waiting for a long time|Waiting for a long time]], and returns it as one line of text. Any program which reads lines can then show the events:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ cat /dev/arhboard0&lt;br /&gt;
seq=0 time=48213 type=0x01 arg=0&lt;br /&gt;
seq=1 time=51007 type=0x01 arg=0&lt;br /&gt;
^C&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Each line is one short press of the button, and Ctrl+C stops &amp;lt;code&amp;gt;cat&amp;lt;/code&amp;gt; at once, because the driver checks for signals between its slices. The line is made with &amp;lt;code&amp;gt;scnprintf()&amp;lt;/code&amp;gt;, which works like &amp;lt;code&amp;gt;snprintf()&amp;lt;/code&amp;gt;, but returns the number of characters it actually wrote. The fields are converted from little-endian first:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
			if (ret == 0 &amp;amp;&amp;amp; actual != sizeof(*wev))&lt;br /&gt;
				ret = -EPROTO;&lt;br /&gt;
			if (ret == 0)&lt;br /&gt;
				len = scnprintf(line, sizeof(line),&lt;br /&gt;
						&amp;quot;seq=%u time=%u type=0x%02x arg=%u\n&amp;quot;,&lt;br /&gt;
						le16_to_cpu(wev-&amp;gt;seq),&lt;br /&gt;
						le32_to_cpu(wev-&amp;gt;time_ms),&lt;br /&gt;
						wev-&amp;gt;type, wev-&amp;gt;arg);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A real program would rather have the event as a structure, from an &amp;lt;code&amp;gt;ioctl()&amp;lt;/code&amp;gt;: text is used here only so that &amp;lt;code&amp;gt;cat&amp;lt;/code&amp;gt; works. The events of your project, and what their type and argument mean, are in the specification of your project. The example prints them as raw numbers: on a CC-1, a long press shows type 0x05.&lt;br /&gt;
&lt;br /&gt;
A short press is type 0x01 only on a board which has no other use for the button: a CC-1, an EL-2 which is not logging, or an FV-3. On the other boards, the press does its job, and you see that event instead: a lap (type 0x05) on a TW-5; a scan which starts (0x02) and, a few seconds later, ends (0x03) on a WP-6 or a BP-7; and on an MB-4, a quick tap is keyed as the letter E (type 0x03, arg 69), followed 3 s later by the space which ends the word (type 0x03, arg 32).&lt;br /&gt;
&lt;br /&gt;
== Bulk transfers ==&lt;br /&gt;
&lt;br /&gt;
The common requests have no bulk endpoint, so the example does not use one. The data of your project goes through its bulk endpoints, with &amp;lt;code&amp;gt;usb_bulk_msg()&amp;lt;/code&amp;gt;, in the loop of [[#Waiting for a long time|Waiting for a long time]] whenever the device may take long to answer. A few rules come from the way bulk data travels.&lt;br /&gt;
&lt;br /&gt;
=== Packets, short packets and ZLPs ===&lt;br /&gt;
&lt;br /&gt;
A bulk transfer is cut into packets of at most 64 bytes. The receiver knows that a transfer has ended when a packet is &amp;#039;&amp;#039;&amp;#039;short&amp;#039;&amp;#039;&amp;#039;: less than 64 bytes. A transfer of 150 bytes is sent as 64 + 64 + 22 bytes, and the 22-byte packet ends it.&lt;br /&gt;
&lt;br /&gt;
A transfer whose size is an exact multiple of 64 has no short packet at its end. Then the sender adds a &amp;#039;&amp;#039;&amp;#039;zero-length packet&amp;#039;&amp;#039;&amp;#039; (&amp;#039;&amp;#039;&amp;#039;ZLP&amp;#039;&amp;#039;&amp;#039;), which carries no data, only to say that the transfer is over. A &amp;lt;code&amp;gt;usb_bulk_msg()&amp;lt;/code&amp;gt; on an IN endpoint which receives a ZLP returns 0 with &amp;lt;code&amp;gt;*actual_length&amp;lt;/code&amp;gt; 0. Whether your device sends ZLPs, and when, is in the specification of your project. A driver usually skips them.&lt;br /&gt;
&lt;br /&gt;
An IN transfer also ends when the buffer is full. So &amp;#039;&amp;#039;&amp;#039;one &amp;lt;code&amp;gt;usb_bulk_msg()&amp;lt;/code&amp;gt; may return less than the device has to send&amp;#039;&amp;#039;&amp;#039;, and the rest comes with the next call.&lt;br /&gt;
&lt;br /&gt;
=== Read whole packets ===&lt;br /&gt;
&lt;br /&gt;
The host cannot ask the device for 10 bytes: it asks for a packet, and the device sends up to 64. If it sends more than the buffer can hold, the transfer fails with &amp;lt;code&amp;gt;-EOVERFLOW&amp;lt;/code&amp;gt;, and the data is lost. So the buffer of an IN transfer should always hold whole packets: a multiple of &amp;lt;code&amp;gt;usb_endpoint_maxp()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
A &amp;lt;code&amp;gt;read()&amp;lt;/code&amp;gt; of any size then needs a buffer of its own in the driver: read whole packets into it, give the program what it asked for, and keep the rest for the next &amp;lt;code&amp;gt;read()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
	/* in_buf: kmalloc()ed, a multiple of 64 bytes */&lt;br /&gt;
	ret = usb_bulk_msg(dev-&amp;gt;udev, dev-&amp;gt;in_pipe, dev-&amp;gt;in_buf, IN_BUF_LEN,&lt;br /&gt;
			   &amp;amp;actual, SLICE_MS);&lt;br /&gt;
	if (ret == 0 || ret == -ETIMEDOUT) {&lt;br /&gt;
		/* actual bytes in in_buf: 0 for a ZLP, or less than the device has */&lt;br /&gt;
	}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== A slice which times out may have moved data ===&lt;br /&gt;
&lt;br /&gt;
A transfer of several packets can stop halfway: the device sends or takes a few packets, then answers NAK until the slice runs out. &amp;lt;code&amp;gt;usb_bulk_msg()&amp;lt;/code&amp;gt; then returns &amp;lt;code&amp;gt;-ETIMEDOUT&amp;lt;/code&amp;gt;, but &amp;lt;code&amp;gt;*actual_length&amp;lt;/code&amp;gt; still says how many bytes were moved, and those bytes are done: the device will not send them again, and it has already taken the ones you wrote. So after a timeout:&lt;br /&gt;
&lt;br /&gt;
* on an IN endpoint, keep the &amp;lt;code&amp;gt;actual&amp;lt;/code&amp;gt; bytes which arrived;&lt;br /&gt;
* on an OUT endpoint, go on from &amp;lt;code&amp;gt;buf + actual&amp;lt;/code&amp;gt; in the next slice, and never send the same bytes twice.&lt;br /&gt;
&lt;br /&gt;
A driver which treats &amp;lt;code&amp;gt;-ETIMEDOUT&amp;lt;/code&amp;gt; as &amp;quot;nothing happened&amp;quot; loses or repeats data. The simplest way to avoid the question is to move one packet (at most 64 bytes) in each transfer: a single packet either goes through, or does not.&lt;br /&gt;
&lt;br /&gt;
=== Halted endpoints ===&lt;br /&gt;
&lt;br /&gt;
A device can &amp;#039;&amp;#039;&amp;#039;halt&amp;#039;&amp;#039;&amp;#039; a bulk endpoint, for example after an error in the data. Every transfer on it then fails with &amp;lt;code&amp;gt;-EPIPE&amp;lt;/code&amp;gt;, until the host clears the halt:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/usb.h&amp;gt;&lt;br /&gt;
int usb_clear_halt(struct usb_device *dev, int pipe);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The example driver has no bulk endpoints, so it never needs this, but most project boards refuse bulk data in some states, with a STALL. When to clear the halt, and what else the device expects before it works again, is in the specification of your project.&lt;br /&gt;
&lt;br /&gt;
== Locking ==&lt;br /&gt;
&lt;br /&gt;
Several programs, or several threads, can use the same board at once, and each file operation uses the device and its buffers. As in the last lab, a mutex protects them. A transfer can take long, though, and while one file operation waits on an endpoint, the others should not wait behind it if they don&amp;#039;t need that endpoint. So &amp;#039;&amp;#039;&amp;#039;take one mutex for each thing which can be used on its own&amp;#039;&amp;#039;&amp;#039;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
struct arhboard {&lt;br /&gt;
	struct usb_device *udev;&lt;br /&gt;
	struct usb_interface *intf;&lt;br /&gt;
	struct kref kref; /* probe() holds one reference, each open file one */&lt;br /&gt;
&lt;br /&gt;
	struct mutex ctrl_lock; /* control transfers, ctrl_buf */&lt;br /&gt;
	u8 *ctrl_buf;           /* kmalloc()ed: the controller reads it by DMA */&lt;br /&gt;
&lt;br /&gt;
	struct mutex ev_lock; /* the event endpoint, ev_buf */&lt;br /&gt;
	u8 *ev_buf;&lt;br /&gt;
	unsigned int ev_pipe;&lt;br /&gt;
&lt;br /&gt;
	bool gone; /* unplugged: written under both locks */&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
While &amp;lt;code&amp;gt;cat&amp;lt;/code&amp;gt; waits for an event, holding &amp;lt;code&amp;gt;ev_lock&amp;lt;/code&amp;gt; for one slice at a time, an &amp;lt;code&amp;gt;ioctl()&amp;lt;/code&amp;gt; takes &amp;lt;code&amp;gt;ctrl_lock&amp;lt;/code&amp;gt;, and its control request goes through at once. A driver with bulk endpoints usually adds one mutex for each direction. Two calls which both read events take turns, one slice each, and each event goes to only one of them.&lt;br /&gt;
&lt;br /&gt;
== Unplugging ==&lt;br /&gt;
&lt;br /&gt;
A board can be unplugged at any moment: while a program has its file open, or even while a call waits on one of its endpoints. &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt; is then called, and must not wait for the programs to close their files, which may never happen. But the structure of the board cannot be freed while open files still point to it.&lt;br /&gt;
&lt;br /&gt;
The solution has two parts.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;The structure is reference counted&amp;#039;&amp;#039;&amp;#039;, with a &amp;lt;code&amp;gt;struct kref&amp;lt;/code&amp;gt;: a counter of how many users the structure has, kept as a member of the structure itself, like the &amp;lt;code&amp;gt;struct list_head&amp;lt;/code&amp;gt; of the last lab.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/kref.h&amp;gt;&lt;br /&gt;
void kref_init(struct kref *kref);    // The count starts at 1&lt;br /&gt;
void kref_get(struct kref *kref);     // One more user&lt;br /&gt;
int kref_put(struct kref *kref, void (*release)(struct kref *kref)); // One user less&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;kref_put()&amp;lt;/code&amp;gt; calls &amp;lt;code&amp;gt;release&amp;lt;/code&amp;gt; when the count reaches 0. &amp;lt;code&amp;gt;release&amp;lt;/code&amp;gt; gets a pointer to the &amp;lt;code&amp;gt;struct kref&amp;lt;/code&amp;gt;, goes back to the structure around it with &amp;lt;code&amp;gt;container_of()&amp;lt;/code&amp;gt;, and frees it.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; holds one reference, from &amp;lt;code&amp;gt;kref_init()&amp;lt;/code&amp;gt;, and each open file holds one: &amp;lt;code&amp;gt;open()&amp;lt;/code&amp;gt; takes it with &amp;lt;code&amp;gt;kref_get()&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;release()&amp;lt;/code&amp;gt; drops it with &amp;lt;code&amp;gt;kref_put()&amp;lt;/code&amp;gt;. Whoever drops the last reference frees the structure:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
static void arhboard_delete(struct kref *kref)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard *dev = container_of(kref, struct arhboard, kref);&lt;br /&gt;
&lt;br /&gt;
	kfree(dev-&amp;gt;ev_buf);&lt;br /&gt;
	kfree(dev-&amp;gt;ctrl_buf);&lt;br /&gt;
	usb_put_intf(dev-&amp;gt;intf);&lt;br /&gt;
	usb_put_dev(dev-&amp;gt;udev);&lt;br /&gt;
	kfree(dev);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static int arhboard_release(struct inode *inode, struct file *file)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard *dev = file-&amp;gt;private_data;&lt;br /&gt;
&lt;br /&gt;
	kref_put(&amp;amp;dev-&amp;gt;kref, arhboard_delete);&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; also takes a reference to the &amp;lt;code&amp;gt;struct usb_device&amp;lt;/code&amp;gt; and to the interface, with &amp;lt;code&amp;gt;usb_get_dev()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;usb_get_intf()&amp;lt;/code&amp;gt;, so that they stay valid for as long as the structure of the driver does.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;&amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt; marks the board as gone&amp;#039;&amp;#039;&amp;#039;, under both locks, and drops the reference of &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
static void arhboard_disconnect(struct usb_interface *intf)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard *dev = usb_get_intfdata(intf);&lt;br /&gt;
&lt;br /&gt;
	/* No new open() from now on */&lt;br /&gt;
	usb_deregister_dev(intf, &amp;amp;arhboard_class);&lt;br /&gt;
	usb_set_intfdata(intf, NULL);&lt;br /&gt;
&lt;br /&gt;
	/*&lt;br /&gt;
	 * Calls already running notice within one slice. Taking each lock&lt;br /&gt;
	 * waits for the transfer which holds it, if any.&lt;br /&gt;
	 */&lt;br /&gt;
	mutex_lock(&amp;amp;dev-&amp;gt;ctrl_lock);&lt;br /&gt;
	mutex_lock(&amp;amp;dev-&amp;gt;ev_lock);&lt;br /&gt;
	dev-&amp;gt;gone = true;&lt;br /&gt;
	mutex_unlock(&amp;amp;dev-&amp;gt;ev_lock);&lt;br /&gt;
	mutex_unlock(&amp;amp;dev-&amp;gt;ctrl_lock);&lt;br /&gt;
&lt;br /&gt;
	dev_info(&amp;amp;intf-&amp;gt;dev, &amp;quot;unplugged\n&amp;quot;);&lt;br /&gt;
	/* Freed now, or at the last close() */&lt;br /&gt;
	kref_put(&amp;amp;dev-&amp;gt;kref, arhboard_delete);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Every file operation checks &amp;lt;code&amp;gt;gone&amp;lt;/code&amp;gt;, under its lock, before it touches the device, and returns &amp;lt;code&amp;gt;-ENODEV&amp;lt;/code&amp;gt;. A call which is waiting notices it at its next slice. The program then gets &amp;lt;code&amp;gt;ENODEV&amp;lt;/code&amp;gt; from every call, until it closes the file, and the last &amp;lt;code&amp;gt;close()&amp;lt;/code&amp;gt; frees the structure.&lt;br /&gt;
&lt;br /&gt;
Try it: start &amp;lt;code&amp;gt;cat /dev/arhboard0&amp;lt;/code&amp;gt;, and unplug the board, or run &amp;lt;code&amp;gt;orb usb detach&amp;lt;/code&amp;gt;. &amp;lt;code&amp;gt;cat&amp;lt;/code&amp;gt; stops with &amp;lt;code&amp;gt;No such device&amp;lt;/code&amp;gt;, and the kernel log shows &amp;lt;code&amp;gt;unplugged&amp;lt;/code&amp;gt;, and nothing else.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; This is why the slices must be short. &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt; takes each lock, so it waits for the transfer which holds it: at most one slice for the events, and one control request. A call which held a lock for a long wait would make &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt; wait for just as long.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== The library and the program ==&lt;br /&gt;
&lt;br /&gt;
The library and the program follow the shape of the last lab: the library has one function for each operation of the driver, hides the ioctl numbers and structures, and turns errors into messages. The program should not need to include the shared header.&lt;br /&gt;
&lt;br /&gt;
A program often has to do two things at once: wait for the commands of the user, and print the events of the board as they come. Both are blocking calls. The simplest way is &amp;#039;&amp;#039;&amp;#039;two threads&amp;#039;&amp;#039;&amp;#039;:&lt;br /&gt;
&lt;br /&gt;
* one thread waits for events, in a loop, and prints each one as it comes;&lt;br /&gt;
* the main thread reads the commands of the user, with &amp;lt;code&amp;gt;readline()&amp;lt;/code&amp;gt;, and runs them.&lt;br /&gt;
&lt;br /&gt;
The two threads can use the same open file: the driver has a separate lock for the events, so a command does not wait for the event thread. To stop the event thread, let it wait with a short timeout, for example 200 ms, and check a flag between two waits. When the user quits, the main thread sets the flag, waits for the event thread with &amp;lt;code&amp;gt;pthread_join()&amp;lt;/code&amp;gt;, and only then closes the file. Never close a file which another thread is still using.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Two threads printing at once can mix up the output, and an event printed in the middle of a line which the user types breaks the prompt. Protect the printing with a mutex, and redraw the prompt after an event with &amp;lt;code&amp;gt;rl_forced_update_display()&amp;lt;/code&amp;gt;.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== How real drivers do it ==&lt;br /&gt;
&lt;br /&gt;
The drivers in the kernel rarely use the blocking calls of this lab. They send &amp;#039;&amp;#039;&amp;#039;URBs&amp;#039;&amp;#039;&amp;#039; (USB Request Blocks): a transfer which is started, and finishes later, while the driver does something else. When it finishes, the USB core calls a &amp;#039;&amp;#039;&amp;#039;completion handler&amp;#039;&amp;#039;&amp;#039; of the driver. A driver of a device with events keeps one URB always waiting on the interrupt endpoint, from &amp;lt;code&amp;gt;probe()&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt;: its completion handler puts each event in a queue in the driver, wakes up the processes which wait for one, and sends the URB again. The driver then implements &amp;lt;code&amp;gt;poll()&amp;lt;/code&amp;gt;, so that a program can wait for events on several files at once, in one thread.&lt;br /&gt;
&lt;br /&gt;
This is needed when a device does not keep its events, or when it must be read without a pause, like a keyboard or a sound card. It also comes with new rules: a completion handler runs in &amp;#039;&amp;#039;&amp;#039;interrupt context&amp;#039;&amp;#039;&amp;#039;, where it cannot sleep, and so cannot take a mutex or call &amp;lt;code&amp;gt;kmalloc()&amp;lt;/code&amp;gt; with &amp;lt;code&amp;gt;GFP_KERNEL&amp;lt;/code&amp;gt;; it needs a spinlock instead. &amp;lt;code&amp;gt;disconnect()&amp;lt;/code&amp;gt; must also stop every URB before it frees what they use. Our boards keep their events, so the blocking calls are enough, and none of this is needed.&lt;br /&gt;
&lt;br /&gt;
== Debugging ==&lt;br /&gt;
&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;The kernel log.&amp;#039;&amp;#039;&amp;#039; Print what the driver does with &amp;lt;code&amp;gt;dev_dbg()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;dev_info()&amp;lt;/code&amp;gt;, and every error with &amp;lt;code&amp;gt;dev_err()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;%pe&amp;lt;/code&amp;gt;: &amp;lt;code&amp;gt;usb_control_msg failed: -EPIPE&amp;lt;/code&amp;gt; is much more useful than a program which gets &amp;lt;code&amp;gt;EPIPE&amp;lt;/code&amp;gt; and says nothing.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;&amp;lt;code&amp;gt;lsusb -v&amp;lt;/code&amp;gt;&amp;#039;&amp;#039;&amp;#039;, to check the descriptors, and &amp;lt;code&amp;gt;lsusb -t&amp;lt;/code&amp;gt;, to see which driver owns which interface.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;The board on its own.&amp;#039;&amp;#039;&amp;#039; The &amp;lt;code&amp;gt;arhboard&amp;lt;/code&amp;gt; driver of this lab works on every board. If &amp;lt;code&amp;gt;arhboard&amp;lt;/code&amp;gt; works and your driver doesn&amp;#039;t, the problem is in your driver. Only one of them can own the board: unload your driver first.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;&amp;lt;code&amp;gt;usbmon&amp;lt;/code&amp;gt;&amp;#039;&amp;#039;&amp;#039;, on a Linux machine which has it (not on OrbStack), shows every packet on the bus, with Wireshark: every request, every STALL, every ZLP.&lt;br /&gt;
&lt;br /&gt;
== A complete example: arhboard ==&lt;br /&gt;
&lt;br /&gt;
The whole driver of this lab. It only uses the common part of the protocol, so it works on every project board. The driver of your project has the same shape, with the requests, endpoints and events of your project.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
// SPDX-License-Identifier: GPL-2.0&lt;br /&gt;
/*&lt;br /&gt;
 * arhboard: a driver for any lab board, which uses only the requests&lt;br /&gt;
 * and events that every board has (section 4 of every board&amp;#039;s spec).&lt;br /&gt;
 *&lt;br /&gt;
 *   /dev/arhboardN&lt;br /&gt;
 *   read()   waits for the next event, and returns it as one line of text&lt;br /&gt;
 *   write()  sets the label of the board&lt;br /&gt;
 *   ioctl()  GET_INFO, GET_STATUS, GET_LABEL, IDENTIFY&lt;br /&gt;
 *&lt;br /&gt;
 * Every transfer is synchronous: each file operation does its own USB&lt;br /&gt;
 * transfers, and returns. The driver does nothing in the background.&lt;br /&gt;
 */&lt;br /&gt;
&lt;br /&gt;
#include &amp;lt;linux/kref.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/module.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/mutex.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/slab.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/uaccess.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/usb.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#include &amp;quot;arhboard_ioctl.h&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#define ARHBOARD_MINOR_BASE 192&lt;br /&gt;
&lt;br /&gt;
/* Vendor requests, all to interface 0 */&lt;br /&gt;
#define REQ_GET_INFO 0x00&lt;br /&gt;
#define REQ_IDENTIFY 0xE0&lt;br /&gt;
#define REQ_GET_BOARD_STATUS 0xE1&lt;br /&gt;
#define REQ_SET_LABEL 0xE2&lt;br /&gt;
#define REQ_GET_LABEL 0xE3&lt;br /&gt;
&lt;br /&gt;
#define REQTYPE_IN (USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_INTERFACE)   /* 0xC1 */&lt;br /&gt;
#define REQTYPE_OUT (USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE) /* 0x41 */&lt;br /&gt;
&lt;br /&gt;
#define CTRL_TIMEOUT_MS 1000&lt;br /&gt;
/* A long wait is a loop of waits this long: see arhboard_read(). */&lt;br /&gt;
#define SLICE_MS 100&lt;br /&gt;
&lt;br /&gt;
/* What the board sends, exactly as it is on the wire: little-endian */&lt;br /&gt;
struct wire_info {&lt;br /&gt;
	__le32 magic;&lt;br /&gt;
	__le16 protocol_version;&lt;br /&gt;
	__le16 firmware_version;&lt;br /&gt;
	__le32 capabilities;&lt;br /&gt;
	u8 device_specific[3];&lt;br /&gt;
	u8 event_queue_len;&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
struct wire_status {&lt;br /&gt;
	__le32 uptime_ms;&lt;br /&gt;
	__le16 events_dropped;&lt;br /&gt;
	u8 events_queued;&lt;br /&gt;
	u8 button_down;&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
struct wire_event {&lt;br /&gt;
	u8 type;&lt;br /&gt;
	u8 arg;&lt;br /&gt;
	__le16 seq;&lt;br /&gt;
	__le32 time_ms;&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
static_assert(sizeof(struct wire_info) == 16);&lt;br /&gt;
static_assert(sizeof(struct wire_status) == 8);&lt;br /&gt;
static_assert(sizeof(struct wire_event) == 8);&lt;br /&gt;
&lt;br /&gt;
#define MAGIC_ARH 0x00485241 /* &amp;quot;ARH&amp;quot; in the low three bytes */&lt;br /&gt;
#define CTRL_BUF_LEN 16&lt;br /&gt;
&lt;br /&gt;
/* Everything the driver knows about one board */&lt;br /&gt;
struct arhboard {&lt;br /&gt;
	struct usb_device *udev;&lt;br /&gt;
	struct usb_interface *intf;&lt;br /&gt;
	struct kref kref; /* probe() holds one reference, each open file one */&lt;br /&gt;
&lt;br /&gt;
	struct mutex ctrl_lock; /* control transfers, ctrl_buf */&lt;br /&gt;
	u8 *ctrl_buf;           /* kmalloc()ed: the controller reads it by DMA */&lt;br /&gt;
&lt;br /&gt;
	struct mutex ev_lock; /* the event endpoint, ev_buf */&lt;br /&gt;
	u8 *ev_buf;&lt;br /&gt;
	unsigned int ev_pipe;&lt;br /&gt;
&lt;br /&gt;
	bool gone; /* unplugged: written under both locks */&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
static struct usb_driver arhboard_driver;&lt;br /&gt;
&lt;br /&gt;
static void arhboard_delete(struct kref *kref)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard *dev = container_of(kref, struct arhboard, kref);&lt;br /&gt;
&lt;br /&gt;
	kfree(dev-&amp;gt;ev_buf);&lt;br /&gt;
	kfree(dev-&amp;gt;ctrl_buf);&lt;br /&gt;
	usb_put_intf(dev-&amp;gt;intf);&lt;br /&gt;
	usb_put_dev(dev-&amp;gt;udev);&lt;br /&gt;
	kfree(dev);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
/*&lt;br /&gt;
 * Control transfers. The caller holds ctrl_lock (or is probe(), before the&lt;br /&gt;
 * device can be opened). The data is in dev-&amp;gt;ctrl_buf.&lt;br /&gt;
 */&lt;br /&gt;
static int arhboard_ctrl_in(struct arhboard *dev, u8 request, u16 len)&lt;br /&gt;
{&lt;br /&gt;
	int ret = usb_control_msg(dev-&amp;gt;udev, usb_rcvctrlpipe(dev-&amp;gt;udev, 0),&lt;br /&gt;
				  request, REQTYPE_IN, 0, 0, dev-&amp;gt;ctrl_buf, len,&lt;br /&gt;
				  CTRL_TIMEOUT_MS);&lt;br /&gt;
	if (ret &amp;lt; 0)&lt;br /&gt;
		return ret; /* -EPIPE: the board refused (STALL) */&lt;br /&gt;
	if (ret != len)&lt;br /&gt;
		return -EPROTO; /* a short answer is an error too */&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static int arhboard_ctrl_out(struct arhboard *dev, u8 request, u16 value,&lt;br /&gt;
			     u16 len)&lt;br /&gt;
{&lt;br /&gt;
	int ret = usb_control_msg(dev-&amp;gt;udev, usb_sndctrlpipe(dev-&amp;gt;udev, 0),&lt;br /&gt;
				  request, REQTYPE_OUT, value, 0,&lt;br /&gt;
				  len ? dev-&amp;gt;ctrl_buf : NULL, len,&lt;br /&gt;
				  CTRL_TIMEOUT_MS);&lt;br /&gt;
	if (ret &amp;lt; 0)&lt;br /&gt;
		return ret;&lt;br /&gt;
	if (ret != len)&lt;br /&gt;
		return -EPROTO;&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static void info_from_wire(struct arhboard_info *info,&lt;br /&gt;
			   const struct wire_info *w)&lt;br /&gt;
{&lt;br /&gt;
	info-&amp;gt;magic = le32_to_cpu(w-&amp;gt;magic);&lt;br /&gt;
	info-&amp;gt;protocol_version = le16_to_cpu(w-&amp;gt;protocol_version);&lt;br /&gt;
	info-&amp;gt;firmware_version = le16_to_cpu(w-&amp;gt;firmware_version);&lt;br /&gt;
	info-&amp;gt;capabilities = le32_to_cpu(w-&amp;gt;capabilities);&lt;br /&gt;
	memcpy(info-&amp;gt;device_specific, w-&amp;gt;device_specific,&lt;br /&gt;
	       sizeof(info-&amp;gt;device_specific));&lt;br /&gt;
	info-&amp;gt;event_queue_len = w-&amp;gt;event_queue_len;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static int arhboard_open(struct inode *inode, struct file *file)&lt;br /&gt;
{&lt;br /&gt;
	struct usb_interface *intf;&lt;br /&gt;
	struct arhboard *dev;&lt;br /&gt;
&lt;br /&gt;
	intf = usb_find_interface(&amp;amp;arhboard_driver, iminor(inode));&lt;br /&gt;
	if (!intf)&lt;br /&gt;
		return -ENODEV;&lt;br /&gt;
	dev = usb_get_intfdata(intf);&lt;br /&gt;
	if (!dev)&lt;br /&gt;
		return -ENODEV;&lt;br /&gt;
&lt;br /&gt;
	kref_get(&amp;amp;dev-&amp;gt;kref);&lt;br /&gt;
	file-&amp;gt;private_data = dev;&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static int arhboard_release(struct inode *inode, struct file *file)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard *dev = file-&amp;gt;private_data;&lt;br /&gt;
&lt;br /&gt;
	kref_put(&amp;amp;dev-&amp;gt;kref, arhboard_delete);&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
/*&lt;br /&gt;
 * Wait for the next event, and return it as one line of text. The board keeps&lt;br /&gt;
 * the events until we read them, so nothing is lost while nobody reads.&lt;br /&gt;
 *&lt;br /&gt;
 * The wait is a loop of short transfers: between two of them, the lock is&lt;br /&gt;
 * free (disconnect() can take it), and we look for Ctrl+C and O_NONBLOCK.&lt;br /&gt;
 */&lt;br /&gt;
static ssize_t arhboard_read(struct file *file, char __user *ubuf,&lt;br /&gt;
			     size_t count, loff_t *ppos)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard *dev = file-&amp;gt;private_data;&lt;br /&gt;
	struct wire_event *wev = (struct wire_event *)dev-&amp;gt;ev_buf;&lt;br /&gt;
	char line[64];&lt;br /&gt;
	int len = 0;&lt;br /&gt;
	int actual;&lt;br /&gt;
	int ret;&lt;br /&gt;
&lt;br /&gt;
	for (;;) {&lt;br /&gt;
		if (mutex_lock_interruptible(&amp;amp;dev-&amp;gt;ev_lock))&lt;br /&gt;
			return -ERESTARTSYS;&lt;br /&gt;
		if (dev-&amp;gt;gone) {&lt;br /&gt;
			ret = -ENODEV;&lt;br /&gt;
		} else {&lt;br /&gt;
			ret = usb_interrupt_msg(dev-&amp;gt;udev, dev-&amp;gt;ev_pipe,&lt;br /&gt;
						dev-&amp;gt;ev_buf, sizeof(*wev),&lt;br /&gt;
						&amp;amp;actual, SLICE_MS);&lt;br /&gt;
			if (ret == 0 &amp;amp;&amp;amp; actual != sizeof(*wev))&lt;br /&gt;
				ret = -EPROTO;&lt;br /&gt;
			if (ret == 0)&lt;br /&gt;
				len = scnprintf(line, sizeof(line),&lt;br /&gt;
						&amp;quot;seq=%u time=%u type=0x%02x arg=%u\n&amp;quot;,&lt;br /&gt;
						le16_to_cpu(wev-&amp;gt;seq),&lt;br /&gt;
						le32_to_cpu(wev-&amp;gt;time_ms),&lt;br /&gt;
						wev-&amp;gt;type, wev-&amp;gt;arg);&lt;br /&gt;
		}&lt;br /&gt;
		mutex_unlock(&amp;amp;dev-&amp;gt;ev_lock);&lt;br /&gt;
&lt;br /&gt;
		if (ret != -ETIMEDOUT)&lt;br /&gt;
			break;&lt;br /&gt;
		/* No event in this slice */&lt;br /&gt;
		if (file-&amp;gt;f_flags &amp;amp; O_NONBLOCK)&lt;br /&gt;
			return -EAGAIN;&lt;br /&gt;
		if (signal_pending(current))&lt;br /&gt;
			return -ERESTARTSYS;&lt;br /&gt;
	}&lt;br /&gt;
	if (ret)&lt;br /&gt;
		return ret;&lt;br /&gt;
&lt;br /&gt;
	if (count &amp;lt; len)&lt;br /&gt;
		return -EINVAL; /* one event per read(), and it must fit */&lt;br /&gt;
	if (copy_to_user(ubuf, line, len))&lt;br /&gt;
		return -EFAULT;&lt;br /&gt;
	return len;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
/* Set the label: up to 16 bytes, a final &amp;#039;\n&amp;#039; is dropped */&lt;br /&gt;
static ssize_t arhboard_write(struct file *file, const char __user *ubuf,&lt;br /&gt;
			      size_t count, loff_t *ppos)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard *dev = file-&amp;gt;private_data;&lt;br /&gt;
	char label[ARHBOARD_LABEL_LEN + 1] = {};&lt;br /&gt;
	size_t len = count;&lt;br /&gt;
	int ret;&lt;br /&gt;
&lt;br /&gt;
	if (len &amp;gt; ARHBOARD_LABEL_LEN + 1)&lt;br /&gt;
		return -EINVAL;&lt;br /&gt;
	if (copy_from_user(label, ubuf, len))&lt;br /&gt;
		return -EFAULT;&lt;br /&gt;
	if (len &amp;gt; 0 &amp;amp;&amp;amp; label[len - 1] == &amp;#039;\n&amp;#039;)&lt;br /&gt;
		len--;&lt;br /&gt;
	if (len &amp;gt; ARHBOARD_LABEL_LEN)&lt;br /&gt;
		return -EINVAL;&lt;br /&gt;
&lt;br /&gt;
	mutex_lock(&amp;amp;dev-&amp;gt;ctrl_lock);&lt;br /&gt;
	if (dev-&amp;gt;gone) {&lt;br /&gt;
		ret = -ENODEV;&lt;br /&gt;
	} else {&lt;br /&gt;
		memset(dev-&amp;gt;ctrl_buf, 0, ARHBOARD_LABEL_LEN); /* padded with &amp;#039;\0&amp;#039; */&lt;br /&gt;
		memcpy(dev-&amp;gt;ctrl_buf, label, len);&lt;br /&gt;
		ret = arhboard_ctrl_out(dev, REQ_SET_LABEL, 0, ARHBOARD_LABEL_LEN);&lt;br /&gt;
	}&lt;br /&gt;
	mutex_unlock(&amp;amp;dev-&amp;gt;ctrl_lock);&lt;br /&gt;
&lt;br /&gt;
	return ret ? ret : count;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static long arhboard_ioctl(struct file *file, unsigned int cmd,&lt;br /&gt;
			   unsigned long arg)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard *dev = file-&amp;gt;private_data;&lt;br /&gt;
	void __user *uarg = (void __user *)arg;&lt;br /&gt;
	union {&lt;br /&gt;
		struct arhboard_info info;&lt;br /&gt;
		struct arhboard_status status;&lt;br /&gt;
		struct arhboard_label label;&lt;br /&gt;
	} out = {}; /* zeroed: no kernel memory leaks to user space */&lt;br /&gt;
	size_t out_len = 0;&lt;br /&gt;
	u32 flashes;&lt;br /&gt;
	int ret;&lt;br /&gt;
&lt;br /&gt;
	/* Read the argument before taking the lock */&lt;br /&gt;
	if (cmd == ARHBOARD_IOC_IDENTIFY) {&lt;br /&gt;
		if (copy_from_user(&amp;amp;flashes, uarg, sizeof(flashes)))&lt;br /&gt;
			return -EFAULT;&lt;br /&gt;
		if (flashes &amp;gt; U16_MAX) /* it travels in wValue, 16 bits */&lt;br /&gt;
			return -EINVAL;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	mutex_lock(&amp;amp;dev-&amp;gt;ctrl_lock);&lt;br /&gt;
	if (dev-&amp;gt;gone) {&lt;br /&gt;
		ret = -ENODEV;&lt;br /&gt;
		goto out_unlock;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	switch (cmd) {&lt;br /&gt;
	case ARHBOARD_IOC_GET_INFO:&lt;br /&gt;
		ret = arhboard_ctrl_in(dev, REQ_GET_INFO, sizeof(struct wire_info));&lt;br /&gt;
		if (ret)&lt;br /&gt;
			break;&lt;br /&gt;
		info_from_wire(&amp;amp;out.info, (struct wire_info *)dev-&amp;gt;ctrl_buf);&lt;br /&gt;
		out_len = sizeof(out.info);&lt;br /&gt;
		break;&lt;br /&gt;
&lt;br /&gt;
	case ARHBOARD_IOC_GET_STATUS: {&lt;br /&gt;
		struct wire_status *w = (struct wire_status *)dev-&amp;gt;ctrl_buf;&lt;br /&gt;
&lt;br /&gt;
		ret = arhboard_ctrl_in(dev, REQ_GET_BOARD_STATUS, sizeof(*w));&lt;br /&gt;
		if (ret)&lt;br /&gt;
			break;&lt;br /&gt;
		out.status.uptime_ms = le32_to_cpu(w-&amp;gt;uptime_ms);&lt;br /&gt;
		out.status.events_dropped = le16_to_cpu(w-&amp;gt;events_dropped);&lt;br /&gt;
		out.status.events_queued = w-&amp;gt;events_queued;&lt;br /&gt;
		out.status.button_down = w-&amp;gt;button_down;&lt;br /&gt;
		out_len = sizeof(out.status);&lt;br /&gt;
		break;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	case ARHBOARD_IOC_GET_LABEL:&lt;br /&gt;
		ret = arhboard_ctrl_in(dev, REQ_GET_LABEL, ARHBOARD_LABEL_LEN);&lt;br /&gt;
		if (ret)&lt;br /&gt;
			break;&lt;br /&gt;
		/* out.label.label[16] stays &amp;#039;\0&amp;#039; */&lt;br /&gt;
		memcpy(out.label.label, dev-&amp;gt;ctrl_buf, ARHBOARD_LABEL_LEN);&lt;br /&gt;
		out_len = sizeof(out.label);&lt;br /&gt;
		break;&lt;br /&gt;
&lt;br /&gt;
	case ARHBOARD_IOC_IDENTIFY:&lt;br /&gt;
		/* No data stage: the number travels in wValue */&lt;br /&gt;
		ret = arhboard_ctrl_out(dev, REQ_IDENTIFY, flashes, 0);&lt;br /&gt;
		break;&lt;br /&gt;
&lt;br /&gt;
	default:&lt;br /&gt;
		ret = -ENOTTY;&lt;br /&gt;
		break;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
out_unlock:&lt;br /&gt;
	mutex_unlock(&amp;amp;dev-&amp;gt;ctrl_lock);&lt;br /&gt;
&lt;br /&gt;
	if (ret == 0 &amp;amp;&amp;amp; out_len &amp;amp;&amp;amp; copy_to_user(uarg, &amp;amp;out, out_len))&lt;br /&gt;
		ret = -EFAULT;&lt;br /&gt;
	return ret;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static const struct file_operations arhboard_fops = {&lt;br /&gt;
	.owner = THIS_MODULE,&lt;br /&gt;
	.open = arhboard_open,&lt;br /&gt;
	.release = arhboard_release,&lt;br /&gt;
	.read = arhboard_read,&lt;br /&gt;
	.write = arhboard_write,&lt;br /&gt;
	.unlocked_ioctl = arhboard_ioctl,&lt;br /&gt;
	.compat_ioctl = compat_ptr_ioctl,&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
static char *arhboard_devnode(const struct device *dev, umode_t *mode)&lt;br /&gt;
{&lt;br /&gt;
	if (mode)&lt;br /&gt;
		*mode = 0666;&lt;br /&gt;
	return NULL;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
/* /dev/arhboard0, /dev/arhboard1, ...: major 180, minors from 192 */&lt;br /&gt;
static struct usb_class_driver arhboard_class = {&lt;br /&gt;
	.name = &amp;quot;arhboard%d&amp;quot;,&lt;br /&gt;
	.devnode = arhboard_devnode,&lt;br /&gt;
	.fops = &amp;amp;arhboard_fops,&lt;br /&gt;
	.minor_base = ARHBOARD_MINOR_BASE,&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
static int arhboard_probe(struct usb_interface *intf,&lt;br /&gt;
			  const struct usb_device_id *id)&lt;br /&gt;
{&lt;br /&gt;
	struct usb_endpoint_descriptor *ev_ep;&lt;br /&gt;
	struct arhboard_info info;&lt;br /&gt;
	struct arhboard *dev;&lt;br /&gt;
	int ret;&lt;br /&gt;
&lt;br /&gt;
	dev = kzalloc(sizeof(*dev), GFP_KERNEL);&lt;br /&gt;
	if (!dev)&lt;br /&gt;
		return -ENOMEM;&lt;br /&gt;
	kref_init(&amp;amp;dev-&amp;gt;kref);&lt;br /&gt;
	mutex_init(&amp;amp;dev-&amp;gt;ctrl_lock);&lt;br /&gt;
	mutex_init(&amp;amp;dev-&amp;gt;ev_lock);&lt;br /&gt;
	dev-&amp;gt;udev = usb_get_dev(interface_to_usbdev(intf));&lt;br /&gt;
	dev-&amp;gt;intf = usb_get_intf(intf);&lt;br /&gt;
&lt;br /&gt;
	dev-&amp;gt;ctrl_buf = kmalloc(CTRL_BUF_LEN, GFP_KERNEL);&lt;br /&gt;
	dev-&amp;gt;ev_buf = kmalloc(sizeof(struct wire_event), GFP_KERNEL);&lt;br /&gt;
	if (!dev-&amp;gt;ctrl_buf || !dev-&amp;gt;ev_buf) {&lt;br /&gt;
		ret = -ENOMEM;&lt;br /&gt;
		goto err;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	/* The event endpoint: the first interrupt IN endpoint */&lt;br /&gt;
	ret = usb_find_int_in_endpoint(intf-&amp;gt;cur_altsetting, &amp;amp;ev_ep);&lt;br /&gt;
	if (ret) {&lt;br /&gt;
		dev_err(&amp;amp;intf-&amp;gt;dev, &amp;quot;no interrupt IN endpoint\n&amp;quot;);&lt;br /&gt;
		goto err;&lt;br /&gt;
	}&lt;br /&gt;
	if (usb_endpoint_maxp(ev_ep) != sizeof(struct wire_event)) {&lt;br /&gt;
		dev_err(&amp;amp;intf-&amp;gt;dev, &amp;quot;event endpoint is not 8 bytes\n&amp;quot;);&lt;br /&gt;
		ret = -ENODEV;&lt;br /&gt;
		goto err;&lt;br /&gt;
	}&lt;br /&gt;
	dev-&amp;gt;ev_pipe = usb_rcvintpipe(dev-&amp;gt;udev, ev_ep-&amp;gt;bEndpointAddress);&lt;br /&gt;
&lt;br /&gt;
	/* Is it really a lab board? */&lt;br /&gt;
	ret = arhboard_ctrl_in(dev, REQ_GET_INFO, sizeof(struct wire_info));&lt;br /&gt;
	if (ret) {&lt;br /&gt;
		dev_err(&amp;amp;intf-&amp;gt;dev, &amp;quot;GET_INFO failed: %pe\n&amp;quot;, ERR_PTR(ret));&lt;br /&gt;
		goto err;&lt;br /&gt;
	}&lt;br /&gt;
	info_from_wire(&amp;amp;info, (struct wire_info *)dev-&amp;gt;ctrl_buf);&lt;br /&gt;
	if ((info.magic &amp;amp; 0x00ffffff) != MAGIC_ARH) {&lt;br /&gt;
		dev_err(&amp;amp;intf-&amp;gt;dev, &amp;quot;not a lab board (magic 0x%08x)\n&amp;quot;,&lt;br /&gt;
			info.magic);&lt;br /&gt;
		ret = -ENODEV;&lt;br /&gt;
		goto err;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	usb_set_intfdata(intf, dev);&lt;br /&gt;
	ret = usb_register_dev(intf, &amp;amp;arhboard_class);&lt;br /&gt;
	if (ret) {&lt;br /&gt;
		dev_err(&amp;amp;intf-&amp;gt;dev, &amp;quot;no minor number: %pe\n&amp;quot;, ERR_PTR(ret));&lt;br /&gt;
		usb_set_intfdata(intf, NULL);&lt;br /&gt;
		goto err;&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	dev_info(&amp;amp;intf-&amp;gt;dev,&lt;br /&gt;
		 &amp;quot;project &amp;#039;%c&amp;#039;, protocol %u.%u, firmware %u.%u, /dev/arhboard%d\n&amp;quot;,&lt;br /&gt;
		 (char)(info.magic &amp;gt;&amp;gt; 24), info.protocol_version &amp;gt;&amp;gt; 8,&lt;br /&gt;
		 info.protocol_version &amp;amp; 0xff, info.firmware_version &amp;gt;&amp;gt; 8,&lt;br /&gt;
		 info.firmware_version &amp;amp; 0xff, intf-&amp;gt;minor - ARHBOARD_MINOR_BASE);&lt;br /&gt;
	return 0;&lt;br /&gt;
&lt;br /&gt;
err:&lt;br /&gt;
	kref_put(&amp;amp;dev-&amp;gt;kref, arhboard_delete);&lt;br /&gt;
	return ret;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static void arhboard_disconnect(struct usb_interface *intf)&lt;br /&gt;
{&lt;br /&gt;
	struct arhboard *dev = usb_get_intfdata(intf);&lt;br /&gt;
&lt;br /&gt;
	/* No new open() from now on */&lt;br /&gt;
	usb_deregister_dev(intf, &amp;amp;arhboard_class);&lt;br /&gt;
	usb_set_intfdata(intf, NULL);&lt;br /&gt;
&lt;br /&gt;
	/*&lt;br /&gt;
	 * Calls already running notice within one slice. Taking each lock&lt;br /&gt;
	 * waits for the transfer which holds it, if any.&lt;br /&gt;
	 */&lt;br /&gt;
	mutex_lock(&amp;amp;dev-&amp;gt;ctrl_lock);&lt;br /&gt;
	mutex_lock(&amp;amp;dev-&amp;gt;ev_lock);&lt;br /&gt;
	dev-&amp;gt;gone = true;&lt;br /&gt;
	mutex_unlock(&amp;amp;dev-&amp;gt;ev_lock);&lt;br /&gt;
	mutex_unlock(&amp;amp;dev-&amp;gt;ctrl_lock);&lt;br /&gt;
&lt;br /&gt;
	dev_info(&amp;amp;intf-&amp;gt;dev, &amp;quot;unplugged\n&amp;quot;);&lt;br /&gt;
	/* Freed now, or at the last close() */&lt;br /&gt;
	kref_put(&amp;amp;dev-&amp;gt;kref, arhboard_delete);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
/* The seven lab boards: vendor 0xcafe, one product ID per project */&lt;br /&gt;
static const struct usb_device_id arhboard_ids[] = {&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4301) },	/* CC-1 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4302) },	/* EL-2 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4303) },	/* FV-3 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4304) },	/* MB-4 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4305) },	/* TW-5 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4306) },	/* WP-6 */&lt;br /&gt;
	{ USB_DEVICE(0xcafe, 0x4307) },	/* BP-7 */&lt;br /&gt;
	{}&lt;br /&gt;
};&lt;br /&gt;
MODULE_DEVICE_TABLE(usb, arhboard_ids);&lt;br /&gt;
&lt;br /&gt;
static struct usb_driver arhboard_driver = {&lt;br /&gt;
	.name = &amp;quot;arhboard&amp;quot;,&lt;br /&gt;
	.probe = arhboard_probe,&lt;br /&gt;
	.disconnect = arhboard_disconnect,&lt;br /&gt;
	.id_table = arhboard_ids,&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
module_usb_driver(arhboard_driver);&lt;br /&gt;
&lt;br /&gt;
MODULE_LICENSE(&amp;quot;GPL&amp;quot;);&lt;br /&gt;
MODULE_AUTHOR(&amp;quot;OS Lab&amp;quot;);&lt;br /&gt;
MODULE_DESCRIPTION(&amp;quot;Example USB driver for any lab board&amp;quot;);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And its shared header, &amp;lt;code&amp;gt;uapi/arhboard_ioctl.h&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */&lt;br /&gt;
/*&lt;br /&gt;
 * The interface between the arhboard driver and user space: ioctl numbers&lt;br /&gt;
 * and their structures. Shared by the driver and by programs, so it only&lt;br /&gt;
 * uses the __u8 ... __u32 types.&lt;br /&gt;
 *&lt;br /&gt;
 * The values here are in the byte order of the machine: the driver converts&lt;br /&gt;
 * them from the device&amp;#039;s little-endian structures.&lt;br /&gt;
 */&lt;br /&gt;
#ifndef ARHBOARD_IOCTL_H&lt;br /&gt;
#define ARHBOARD_IOCTL_H&lt;br /&gt;
&lt;br /&gt;
#include &amp;lt;linux/ioctl.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/types.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define ARHBOARD_LABEL_LEN 16&lt;br /&gt;
&lt;br /&gt;
/* GET_INFO: what the board says about itself */&lt;br /&gt;
struct arhboard_info {&lt;br /&gt;
	__u32 magic;            /* &amp;quot;ARH&amp;quot; + one character per project */&lt;br /&gt;
	__u16 protocol_version; /* major in the high byte, minor in the low byte */&lt;br /&gt;
	__u16 firmware_version;&lt;br /&gt;
	__u32 capabilities;     /* bits defined by the project */&lt;br /&gt;
	__u8 device_specific[3];&lt;br /&gt;
	__u8 event_queue_len;   /* unread events the board keeps */&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
/* GET_BOARD_STATUS */&lt;br /&gt;
struct arhboard_status {&lt;br /&gt;
	__u32 uptime_ms;      /* since power-up */&lt;br /&gt;
	__u16 events_dropped; /* lost because the board&amp;#039;s queue was full */&lt;br /&gt;
	__u8 events_queued;   /* waiting to be read, now */&lt;br /&gt;
	__u8 button_down;     /* 1 while the button is held */&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
/* GET_LABEL: always ends with &amp;#039;\0&amp;#039; */&lt;br /&gt;
struct arhboard_label {&lt;br /&gt;
	char label[ARHBOARD_LABEL_LEN + 1];&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
#define ARHBOARD_IOC_MAGIC 0xB8&lt;br /&gt;
#define ARHBOARD_IOC_GET_INFO   _IOR(ARHBOARD_IOC_MAGIC, 1, struct arhboard_info)&lt;br /&gt;
#define ARHBOARD_IOC_GET_STATUS _IOR(ARHBOARD_IOC_MAGIC, 2, struct arhboard_status)&lt;br /&gt;
#define ARHBOARD_IOC_GET_LABEL  _IOR(ARHBOARD_IOC_MAGIC, 3, struct arhboard_label)&lt;br /&gt;
/* Flash the LED: 1 to 10 times. Anything else is refused by the board (EPIPE). */&lt;br /&gt;
#define ARHBOARD_IOC_IDENTIFY   _IOW(ARHBOARD_IOC_MAGIC, 4, __u32)&lt;br /&gt;
&lt;br /&gt;
#endif&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Try it on your board:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ make -C driver load&lt;br /&gt;
$ sudo dmesg | tail -1&lt;br /&gt;
[ 9120.551021] arhboard 1-1:1.0: project &amp;#039;1&amp;#039;, protocol 1.0, firmware 1.0, /dev/arhboard0&lt;br /&gt;
$ echo bench-3 &amp;gt; /dev/arhboard0      # SET_LABEL&lt;br /&gt;
$ cat /dev/arhboard0                 # press the button; Ctrl+C to stop&lt;br /&gt;
seq=0 time=48213 type=0x01 arg=0&lt;br /&gt;
^C&lt;br /&gt;
$ make -C driver unload&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Operating_Systems&amp;diff=8462</id>
		<title>Operating Systems</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Operating_Systems&amp;diff=8462"/>
		<updated>2026-11-27T15:14:05Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: /* Lab Sessions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Lab Sessions ==&lt;br /&gt;
&lt;br /&gt;
* Lab 1 - [[OS Lab 1 - Linux setup. Bash primer. C primer]]&lt;br /&gt;
* Lab 2 - [[OS Lab 2 - System calls. The initial stack]]&lt;br /&gt;
* Lab 3 - [[OS Lab 3 - Files. Memory mapping]]&lt;br /&gt;
* Lab 4 - [[OS Lab 4 - Processes. Signals]]&lt;br /&gt;
* Lab 5 - [[OS Lab 5 - Threads. Mutexes]]&lt;br /&gt;
* Lab 6 - [[OS Lab 6 - Users. Permissions]]&lt;br /&gt;
* Lab 7 - [[OS Lab 7 - Sockets. Datagrams]]&lt;br /&gt;
* Lab 8 - [[OS Lab 8 - Kernel modules. Character devices]]&lt;br /&gt;
* Lab 9 - [[OS Lab 9 - USB drivers. USB transfers ]]&lt;br /&gt;
&lt;br /&gt;
=== Old Lab Sessions (2025) ===&lt;br /&gt;
&lt;br /&gt;
* Lab 1 - [[OS Lab 1 - Installing Linux]]&lt;br /&gt;
* Lab 2 - [[OS Lab 2 - Linux Filesystems]]&lt;br /&gt;
* Lab 3 - [[OS Lab 3 - Processes and Jobs]]&lt;br /&gt;
* Lab 4 - [[OS Lab 4 - Users, Groups and Permissions]]&lt;br /&gt;
* Lab 5 - [[OS Lab 5 - Bash Scripting]]&lt;br /&gt;
* Lab 6 - [[OS Lab 6 - Inter Process Communication]]&lt;br /&gt;
* Lab 7 - [[OS Lab 7 - The Network Subsystem]]&lt;br /&gt;
* Lab 8 - [[OS Lab 8 - Transport and Security]]&lt;br /&gt;
* Lab 9 - [[OS Lab 9 - Application Protocols: DNS, SSH, HTTP(S)]]&lt;br /&gt;
* Lab 10 - [[OS Lab 10 - Containers and Docker]]&lt;br /&gt;
* Lab 11 - [[OS Lab 11 - Linux Kernel Modules]]&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Operating_Systems&amp;diff=8461</id>
		<title>Operating Systems</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Operating_Systems&amp;diff=8461"/>
		<updated>2026-11-27T15:03:54Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: /* Lab Sessions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Lab Sessions ==&lt;br /&gt;
&lt;br /&gt;
* Lab 1 - [[OS Lab 1 - Linux setup. Bash primer. C primer]]&lt;br /&gt;
* Lab 2 - [[OS Lab 2 - System calls. The initial stack]]&lt;br /&gt;
* Lab 3 - [[OS Lab 3 - Files. Memory mapping]]&lt;br /&gt;
* Lab 4 - [[OS Lab 4 - Processes. Signals]]&lt;br /&gt;
* Lab 5 - [[OS Lab 5 - Threads. Mutexes]]&lt;br /&gt;
* Lab 6 - [[OS Lab 6 - Users. Permissions]]&lt;br /&gt;
* Lab 7 - [[OS Lab 7 - Sockets. Datagrams]]&lt;br /&gt;
* Lab 8 - [[OS Lab 8 - Kernel modules. Character devices]]&lt;br /&gt;
* Lab 9 - [[OS Lab 9 - The USB ]]&lt;br /&gt;
&lt;br /&gt;
=== Old Lab Sessions (2025) ===&lt;br /&gt;
&lt;br /&gt;
* Lab 1 - [[OS Lab 1 - Installing Linux]]&lt;br /&gt;
* Lab 2 - [[OS Lab 2 - Linux Filesystems]]&lt;br /&gt;
* Lab 3 - [[OS Lab 3 - Processes and Jobs]]&lt;br /&gt;
* Lab 4 - [[OS Lab 4 - Users, Groups and Permissions]]&lt;br /&gt;
* Lab 5 - [[OS Lab 5 - Bash Scripting]]&lt;br /&gt;
* Lab 6 - [[OS Lab 6 - Inter Process Communication]]&lt;br /&gt;
* Lab 7 - [[OS Lab 7 - The Network Subsystem]]&lt;br /&gt;
* Lab 8 - [[OS Lab 8 - Transport and Security]]&lt;br /&gt;
* Lab 9 - [[OS Lab 9 - Application Protocols: DNS, SSH, HTTP(S)]]&lt;br /&gt;
* Lab 10 - [[OS Lab 10 - Containers and Docker]]&lt;br /&gt;
* Lab 11 - [[OS Lab 11 - Linux Kernel Modules]]&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_8_-_container_of.png&amp;diff=8460</id>
		<title>Fișier:OS Lab 8 - container of.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_8_-_container_of.png&amp;diff=8460"/>
		<updated>2026-11-27T15:01:26Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_8_-_list.png&amp;diff=8459</id>
		<title>Fișier:OS Lab 8 - list.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_8_-_list.png&amp;diff=8459"/>
		<updated>2026-11-27T15:00:50Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=OS_Lab_8_-_Kernel_modules._Character_devices&amp;diff=8458</id>
		<title>OS Lab 8 - Kernel modules. Character devices</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=OS_Lab_8_-_Kernel_modules._Character_devices&amp;diff=8458"/>
		<updated>2026-11-27T14:59:53Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: Pagină nouă: In the last lab, processes talked to each other through sockets, and the kernel carried the data between them. Until now, all our code ran in user...&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In [[OS_Lab_7_-_Sockets._Datagrams|the last lab]], processes talked to each other through sockets, and the kernel carried the data between them. Until now, all our code ran in user space, and asked the kernel for everything through system calls. In this lab, we will write code which runs inside the kernel, as a &amp;#039;&amp;#039;&amp;#039;kernel module&amp;#039;&amp;#039;&amp;#039;. We will see the rules of kernel code, a few of the data structures which the kernel uses everywhere, and how a module makes a &amp;#039;&amp;#039;&amp;#039;character device&amp;#039;&amp;#039;&amp;#039;: a file in &amp;lt;code&amp;gt;/dev&amp;lt;/code&amp;gt; whose &amp;lt;code&amp;gt;read()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;write()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ioctl()&amp;lt;/code&amp;gt; calls run our functions. In the next lab, the device behind such a file will be a real USB device.&lt;br /&gt;
&lt;br /&gt;
== Learning objectives ==&lt;br /&gt;
&lt;br /&gt;
By the end of this lab you should be able to:&lt;br /&gt;
&lt;br /&gt;
# build a kernel module, load it, and unload it;&lt;br /&gt;
# print to the kernel log, and read the log;&lt;br /&gt;
# choose the right type for a value in kernel code, in user code, and in a header which both share;&lt;br /&gt;
# report errors and clean up after them in the way of the kernel;&lt;br /&gt;
# keep objects in a kernel list, and get from a list element back to its object with &amp;lt;code&amp;gt;container_of()&amp;lt;/code&amp;gt;;&lt;br /&gt;
# create a character device, and implement its &amp;lt;code&amp;gt;open()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;read()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;write()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;ioctl()&amp;lt;/code&amp;gt;;&lt;br /&gt;
# move data between user space and the kernel safely;&lt;br /&gt;
# protect shared data with a mutex.&lt;br /&gt;
&lt;br /&gt;
== The project ==&lt;br /&gt;
&lt;br /&gt;
A module is built against the kernel it will be loaded into, with the kernel&amp;#039;s own build system, &amp;#039;&amp;#039;&amp;#039;kbuild&amp;#039;&amp;#039;&amp;#039;. The driver project template has three parts: the module, a library which wraps it, and a program which uses the library. Download it and unpack it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
curl -OL https://wiki.dcae.pub.ro/images/3/33/Skeleton_driver.zip&lt;br /&gt;
unzip -d lab08 Skeleton_driver.zip&lt;br /&gt;
cd lab08&lt;br /&gt;
./make_kbuild.sh&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;make_kbuild.sh&amp;lt;/code&amp;gt; makes &amp;lt;code&amp;gt;kbuild/&amp;lt;/code&amp;gt;, the build tree of the kernel which you are running. Run it in the folder of the project, &amp;#039;&amp;#039;&amp;#039;before&amp;#039;&amp;#039;&amp;#039; you open the folder in VS Code:&lt;br /&gt;
&lt;br /&gt;
* on OrbStack, it downloads the source of your kernel version and builds the whole kernel, which takes about half an hour;&lt;br /&gt;
* on WSL, it downloads the source of Microsoft&amp;#039;s kernel and builds it, which takes just as long;&lt;br /&gt;
* on any other Linux, it installs the kernel headers package of your distribution, and &amp;lt;code&amp;gt;kbuild&amp;lt;/code&amp;gt; links to it.&lt;br /&gt;
&lt;br /&gt;
When you open the folder, VS Code configures the project and builds the driver once. After that, the editor knows every function and type you use (it suggests names as you type, shows errors before you build, and jumps to a definition with F12) in all three parts: for the kernel&amp;#039;s functions in &amp;lt;code&amp;gt;driver/&amp;lt;/code&amp;gt;, and for the C library in &amp;lt;code&amp;gt;lib/&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;app/&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Folder !! What&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;driver/&amp;lt;/code&amp;gt; || The module. &amp;lt;code&amp;gt;Kbuild&amp;lt;/code&amp;gt; lists its files, &amp;lt;code&amp;gt;Makefile&amp;lt;/code&amp;gt; builds, loads and unloads it&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;driver/uapi/&amp;lt;/code&amp;gt; || The headers which the driver shares with user space&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;lib/&amp;lt;/code&amp;gt; || A library which wraps the driver for programs&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;app/&amp;lt;/code&amp;gt; || The program, linked with the library&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;kbuild/&amp;lt;/code&amp;gt; || The kernel&amp;#039;s build tree, made by &amp;lt;code&amp;gt;make_kbuild.sh&amp;lt;/code&amp;gt;. Do not change it&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! What !! In VS Code !! From a terminal&lt;br /&gt;
|-&lt;br /&gt;
| Build everything || &amp;#039;&amp;#039;&amp;#039;Build&amp;#039;&amp;#039;&amp;#039; button, or &amp;lt;code&amp;gt;Ctrl/Cmd+Shift+B&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;cmake --build --preset debug&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| Build only the driver || || &amp;lt;code&amp;gt;make -C driver&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| Load the driver || task &amp;#039;&amp;#039;load driver&amp;#039;&amp;#039; || &amp;lt;code&amp;gt;make -C driver load&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| Unload the driver || task &amp;#039;&amp;#039;unload driver&amp;#039;&amp;#039; || &amp;lt;code&amp;gt;make -C driver unload&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| Watch the kernel log || task &amp;#039;&amp;#039;kernel log&amp;#039;&amp;#039; || &amp;lt;code&amp;gt;sudo dmesg -w&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Tasks are in &amp;#039;&amp;#039;&amp;#039;Terminal → Run Task...&amp;#039;&amp;#039;&amp;#039;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; If a module is already loaded, you must unload it before you can load a new version.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; If you update the kernel, &amp;lt;code&amp;gt;kbuild/&amp;lt;/code&amp;gt; no longer matches it, and &amp;lt;code&amp;gt;insmod&amp;lt;/code&amp;gt; fails with &amp;lt;code&amp;gt;Invalid module format&amp;lt;/code&amp;gt;. Delete &amp;lt;code&amp;gt;kbuild&amp;lt;/code&amp;gt;, and run &amp;lt;code&amp;gt;./make_kbuild.sh&amp;lt;/code&amp;gt; again.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note: Secure Boot&amp;#039;&amp;#039;&amp;#039; (only for Linux installed directly on a PC, not OrbStack or WSL). With Secure Boot on, most distributions refuse unsigned modules, so &amp;lt;code&amp;gt;insmod&amp;lt;/code&amp;gt; fails with &amp;lt;code&amp;gt;Key was rejected by service&amp;lt;/code&amp;gt;. To check whether it is on, run &amp;lt;code&amp;gt;mokutil --sb-state&amp;lt;/code&amp;gt;. You can fix this in one of two ways:&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Turn Secure Boot off&amp;#039;&amp;#039;&amp;#039; in the firmware settings (open them with F2, F10, F12 or Del at start-up). We recommend this for the lab. You can turn it back on when you&amp;#039;re done.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Sign your modules&amp;#039;&amp;#039;&amp;#039; with your own key. The steps to do this are described in [https://wiki.debian.org/SecureBoot#MOK_-_Machine_Owner_Key the Debian wiki]. Then sign each module after you build it: &amp;lt;code&amp;gt;kbuild/scripts/sign-file sha256 MOK.priv MOK.der driver/klog.ko&amp;lt;/code&amp;gt;.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== When the kernel crashes ===&lt;br /&gt;
&lt;br /&gt;
A bug in a module is a bug in the kernel. There is no process around it to kill. A bad pointer in user space ends the program with &amp;lt;code&amp;gt;SIGSEGV&amp;lt;/code&amp;gt;. In a module, it is an &amp;#039;&amp;#039;&amp;#039;oops&amp;#039;&amp;#039;&amp;#039;: the kernel prints a report to its log, with the name of the function and the call stack, and kills the process which was running the module&amp;#039;s code. Whatever the module held at that moment stays held: a lock stays locked, and the module often cannot be unloaded anymore (&amp;lt;code&amp;gt;rmmod&amp;lt;/code&amp;gt; says that it is in use). The only way out is to restart the machine.&lt;br /&gt;
&lt;br /&gt;
Some systems go further. On OrbStack, &amp;lt;code&amp;gt;sysctl kernel.panic_on_oops&amp;lt;/code&amp;gt; is 1: the first oops stops the whole VM, with all its machines. Restart it from the OrbStack menu, or with &amp;lt;code&amp;gt;orb stop&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;orb start&amp;lt;/code&amp;gt;. On WSL, run &amp;lt;code&amp;gt;wsl --shutdown&amp;lt;/code&amp;gt; in Windows, and open the terminal again.&lt;br /&gt;
&lt;br /&gt;
The first time you load a module of your own, the kernel prints &amp;lt;code&amp;gt;loading out-of-tree module taints kernel&amp;lt;/code&amp;gt;. A &amp;#039;&amp;#039;&amp;#039;tainted&amp;#039;&amp;#039;&amp;#039; kernel runs code which did not come with it. The kernel remembers this in &amp;lt;code&amp;gt;/proc/sys/kernel/tainted&amp;lt;/code&amp;gt; (4096 means an out-of-tree module), and prints it at the top of every oops report.&lt;br /&gt;
&lt;br /&gt;
== A first module ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#define pr_fmt(fmt) KBUILD_MODNAME &amp;quot;: &amp;quot; fmt&lt;br /&gt;
&lt;br /&gt;
#include &amp;lt;linux/module.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/printk.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static char *name = &amp;quot;world&amp;quot;;&lt;br /&gt;
module_param(name, charp, 0444);&lt;br /&gt;
MODULE_PARM_DESC(name, &amp;quot;Who to greet&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
static int __init hello_init(void)&lt;br /&gt;
{&lt;br /&gt;
	pr_info(&amp;quot;hello, %s\n&amp;quot;, name);&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static void __exit hello_exit(void)&lt;br /&gt;
{&lt;br /&gt;
	pr_info(&amp;quot;goodbye, %s\n&amp;quot;, name);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
module_init(hello_init);&lt;br /&gt;
module_exit(hello_exit);&lt;br /&gt;
&lt;br /&gt;
MODULE_LICENSE(&amp;quot;GPL&amp;quot;);&lt;br /&gt;
MODULE_AUTHOR(&amp;quot;OS Lab&amp;quot;);&lt;br /&gt;
MODULE_DESCRIPTION(&amp;quot;Says hello when loaded, and goodbye when unloaded&amp;quot;);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A module has no &amp;lt;code&amp;gt;main()&amp;lt;/code&amp;gt;. It has two functions, which the kernel calls:&lt;br /&gt;
&lt;br /&gt;
* the &amp;#039;&amp;#039;&amp;#039;init&amp;#039;&amp;#039;&amp;#039; function, named by &amp;lt;code&amp;gt;module_init()&amp;lt;/code&amp;gt;, runs when the module is loaded. It should set up whatever the module provides, and should return 0 on success. If it returns an error (a negative number, see below), the module is not considered loaded;&lt;br /&gt;
* the &amp;#039;&amp;#039;&amp;#039;exit&amp;#039;&amp;#039;&amp;#039; function, named by &amp;lt;code&amp;gt;module_exit()&amp;lt;/code&amp;gt;, runs when the module is unloaded. It should undo everything that init did.&lt;br /&gt;
&lt;br /&gt;
Aside from those two moments, the module&amp;#039;s code runs only when somebody calls it: a process which uses its device, or a piece of hardware which needs attention.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;__init&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;__exit&amp;lt;/code&amp;gt; mark the two functions, so that the kernel can save the memory they use when they are not needed:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Marker !! Put on !! Built as a module !! Built into the kernel&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;__init&amp;lt;/code&amp;gt; || The init function || Freed once the module is loaded || Freed once the kernel has booted&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;__exit&amp;lt;/code&amp;gt; || The exit function || Kept, and run by &amp;lt;code&amp;gt;rmmod&amp;lt;/code&amp;gt; || Left out, since it could never be unloaded&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Init runs only once, so nothing may call an &amp;lt;code&amp;gt;__init&amp;lt;/code&amp;gt; function after loading.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;MODULE_*&amp;lt;/code&amp;gt; macros store information in the module file:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Macro !! Meaning&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;MODULE_LICENSE()&amp;lt;/code&amp;gt; || Required. Without it, the build fails with &amp;lt;code&amp;gt;ERROR: modpost: missing MODULE_LICENSE()&amp;lt;/code&amp;gt;. Many kernel functions may only be used by modules whose license is &amp;lt;code&amp;gt;&amp;quot;GPL&amp;quot;&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;MODULE_DESCRIPTION()&amp;lt;/code&amp;gt; || One line description of the module&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;MODULE_AUTHOR()&amp;lt;/code&amp;gt; || Author of the module&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;module_param(name, type, perm)&amp;lt;/code&amp;gt; || Makes the variable &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; a &amp;#039;&amp;#039;&amp;#039;parameter&amp;#039;&amp;#039;&amp;#039;, which can be set when the module is loaded. &amp;lt;code&amp;gt;type&amp;lt;/code&amp;gt; is &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;uint&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;charp&amp;lt;/code&amp;gt; (a string), ...&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;MODULE_PARM_DESC()&amp;lt;/code&amp;gt; || One line description of a parameter&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=== Trying it out ===&lt;br /&gt;
&lt;br /&gt;
Save the module as &amp;lt;code&amp;gt;driver/hello.c&amp;lt;/code&amp;gt;, and add it to the line &amp;lt;code&amp;gt;obj-m&amp;lt;/code&amp;gt; in &amp;lt;code&amp;gt;driver/Kbuild&amp;lt;/code&amp;gt;. Each name in &amp;lt;code&amp;gt;obj-m&amp;lt;/code&amp;gt; is one module:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;make&amp;quot;&amp;gt;&lt;br /&gt;
obj-m := klog.o hello.o&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then build it, and look at what the macros stored:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ make -C driver&lt;br /&gt;
$ modinfo driver/hello.ko&lt;br /&gt;
filename:       /home/john/lab08/driver/hello.ko&lt;br /&gt;
license:        GPL&lt;br /&gt;
author:         OS Lab&lt;br /&gt;
description:    Says hello when loaded, and goodbye when unloaded&lt;br /&gt;
name:           hello&lt;br /&gt;
depends:&lt;br /&gt;
vermagic:       7.2.12-orbstack-00394-gbecdd6130068 SMP preempt mod_unload aarch64&lt;br /&gt;
parm:           name:Who to greet (charp)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;vermagic&amp;lt;/code&amp;gt; is the kernel which the module was built for. The kernel refuses a module whose vermagic does not match its own.&lt;br /&gt;
&lt;br /&gt;
Load it with &amp;lt;code&amp;gt;insmod&amp;lt;/code&amp;gt;, see it in &amp;lt;code&amp;gt;lsmod&amp;lt;/code&amp;gt;, and unload it with &amp;lt;code&amp;gt;rmmod&amp;lt;/code&amp;gt;. The messages go to the kernel log, which &amp;lt;code&amp;gt;dmesg&amp;lt;/code&amp;gt; prints:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sudo insmod driver/hello.ko&lt;br /&gt;
$ lsmod | grep hello&lt;br /&gt;
hello                  12288  0&lt;br /&gt;
$ cat /sys/module/hello/parameters/name&lt;br /&gt;
world&lt;br /&gt;
$ sudo rmmod hello&lt;br /&gt;
$ sudo insmod driver/hello.ko name=students&lt;br /&gt;
$ sudo rmmod hello&lt;br /&gt;
$ sudo dmesg | tail -4&lt;br /&gt;
[446617.235506] hello: hello, world&lt;br /&gt;
[446617.249769] hello: goodbye, world&lt;br /&gt;
[446617.259058] hello: hello, students&lt;br /&gt;
[446617.262071] hello: goodbye, students&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The last column of &amp;lt;code&amp;gt;lsmod&amp;lt;/code&amp;gt; counts the users of the module: while it is not 0, &amp;lt;code&amp;gt;rmmod&amp;lt;/code&amp;gt; refuses to unload it.&lt;br /&gt;
&lt;br /&gt;
=== The kernel log ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/printk.h&amp;gt;&lt;br /&gt;
pr_emerg(fmt, ...)   pr_alert(fmt, ...)   pr_crit(fmt, ...)   pr_err(fmt, ...)&lt;br /&gt;
pr_warn(fmt, ...)    pr_notice(fmt, ...)  pr_info(fmt, ...)   pr_debug(fmt, ...)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;pr_*&amp;lt;/code&amp;gt; macros write a message to the kernel log, a buffer in memory. Every message has a &amp;#039;&amp;#039;&amp;#039;level&amp;#039;&amp;#039;&amp;#039;, from 0 (the system is unusable) to 7 (debugging), and each macro writes at its own level. Modules mostly use these four:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Macro !! Level !! When&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;pr_err()&amp;lt;/code&amp;gt; || 3 || Something failed&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;pr_warn()&amp;lt;/code&amp;gt; || 4 || Something is wrong, but the module goes on&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;pr_info()&amp;lt;/code&amp;gt; || 6 || Information: the module was loaded, a device was found, ...&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;pr_debug()&amp;lt;/code&amp;gt; || 7 || Details which only help while debugging&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;pr_emerg()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;pr_alert()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;pr_crit()&amp;lt;/code&amp;gt; are for when the whole system is in trouble, and &amp;lt;code&amp;gt;pr_notice()&amp;lt;/code&amp;gt; sits between a warning and information. They are mostly used by core kernel code.&lt;br /&gt;
&lt;br /&gt;
The format is that of &amp;lt;code&amp;gt;printf()&amp;lt;/code&amp;gt;, with a few additions. &amp;lt;code&amp;gt;%pe&amp;lt;/code&amp;gt; prints an error by name (&amp;lt;code&amp;gt;-ENOMEM&amp;lt;/code&amp;gt; instead of -12). It takes a pointer, not an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;: wrap the error code in &amp;lt;code&amp;gt;ERR_PTR()&amp;lt;/code&amp;gt;, as in &amp;lt;code&amp;gt;pr_err(&amp;quot;...: %pe\n&amp;quot;, ERR_PTR(ret))&amp;lt;/code&amp;gt;, or pass a pointer which already holds an error (see [[#Returning errors|Returning errors]]). &amp;lt;code&amp;gt;%*ph&amp;lt;/code&amp;gt; prints a buffer in hex, and takes its length, then the pointer. Every message should end with &amp;lt;code&amp;gt;\n&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
The line &amp;lt;code&amp;gt;#define pr_fmt(fmt) ...&amp;lt;/code&amp;gt; at the top of the file sets a prefix for every &amp;lt;code&amp;gt;pr_*&amp;lt;/code&amp;gt; message in it: each &amp;lt;code&amp;gt;pr_*&amp;lt;/code&amp;gt; macro passes its format through &amp;lt;code&amp;gt;pr_fmt()&amp;lt;/code&amp;gt;, and two string constants next to each other are joined into one. &amp;lt;code&amp;gt;KBUILD_MODNAME&amp;lt;/code&amp;gt; is the name of the module, which kbuild defines when it compiles the file, so &amp;lt;code&amp;gt;KBUILD_MODNAME &amp;quot;: &amp;quot; fmt&amp;lt;/code&amp;gt; becomes &amp;lt;code&amp;gt;&amp;quot;hello: &amp;quot; fmt&amp;lt;/code&amp;gt;, and every message of the example starts with &amp;lt;code&amp;gt;hello:&amp;lt;/code&amp;gt;. The line must come before the first &amp;lt;code&amp;gt;#include&amp;lt;/code&amp;gt;, because &amp;lt;code&amp;gt;&amp;amp;lt;linux/printk.h&amp;amp;gt;&amp;lt;/code&amp;gt; defines a &amp;lt;code&amp;gt;pr_fmt()&amp;lt;/code&amp;gt; of its own (with no prefix) when it sees none.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;pr_debug()&amp;lt;/code&amp;gt; prints nothing, unless &amp;lt;code&amp;gt;DEBUG&amp;lt;/code&amp;gt; is defined when the file is compiled and the running kernel is configured to print debugging information. The template defines it in &amp;lt;code&amp;gt;driver/Kbuild&amp;lt;/code&amp;gt;, with &amp;lt;code&amp;gt;ccflags-y += -DDEBUG&amp;lt;/code&amp;gt;. If &amp;lt;code&amp;gt;pr_debug()&amp;lt;/code&amp;gt; doesn&amp;#039;t print anything on your machine, use &amp;lt;code&amp;gt;pr_info()&amp;lt;/code&amp;gt; instead.&lt;br /&gt;
&lt;br /&gt;
For example, this &amp;lt;code&amp;gt;hello_init()&amp;lt;/code&amp;gt; prints a message at each level:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
static int __init hello_init(void)&lt;br /&gt;
{&lt;br /&gt;
	u8 id[4] = { 0x12, 0x34, 0xab, 0xcd };&lt;br /&gt;
&lt;br /&gt;
	pr_info(&amp;quot;hello, %s\n&amp;quot;, name);&lt;br /&gt;
	pr_info(&amp;quot;device id: %*ph\n&amp;quot;, (int)sizeof(id), id);&lt;br /&gt;
	pr_warn(&amp;quot;only %d of %d buffers\n&amp;quot;, 3, 4);&lt;br /&gt;
	pr_err(&amp;quot;cannot allocate: %pe\n&amp;quot;, ERR_PTR(-ENOMEM));&lt;br /&gt;
	pr_debug(&amp;quot;init done\n&amp;quot;);&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To read the log, use &amp;lt;code&amp;gt;sudo dmesg&amp;lt;/code&amp;gt;. &amp;lt;code&amp;gt;-x&amp;lt;/code&amp;gt; adds the level of each message, &amp;lt;code&amp;gt;-l&amp;lt;/code&amp;gt; shows only some levels:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sudo insmod driver/hello.ko&lt;br /&gt;
$ sudo dmesg -x | tail -5&lt;br /&gt;
kern  :info  : [454231.944115] hello: hello, world&lt;br /&gt;
kern  :info  : [454231.944130] hello: device id: 12 34 ab cd&lt;br /&gt;
kern  :warn  : [454231.944131] hello: only 3 of 4 buffers&lt;br /&gt;
kern  :err   : [454231.944131] hello: cannot allocate: -ENOMEM&lt;br /&gt;
kern  :debug : [454231.944156] hello: init done&lt;br /&gt;
$ sudo dmesg -l err,warn | tail -2&lt;br /&gt;
[454231.944131] hello: only 3 of 4 buffers&lt;br /&gt;
[454231.944131] hello: cannot allocate: -ENOMEM&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Once a module has a &amp;lt;code&amp;gt;struct device&amp;lt;/code&amp;gt;, it should print with &amp;lt;code&amp;gt;dev_err(dev, ...)&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;dev_info(dev, ...)&amp;lt;/code&amp;gt;, and so on, instead. They associate the message with a particular device, but are otherwise the same as &amp;lt;code&amp;gt;pr_*&amp;lt;/code&amp;gt;.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Rules of kernel code ==&lt;br /&gt;
&lt;br /&gt;
The kernel is one large program, and a module becomes part of it. A few rules follow from that:&lt;br /&gt;
&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Make everything &amp;lt;code&amp;gt;static&amp;lt;/code&amp;gt;&amp;#039;&amp;#039;&amp;#039; that can be: every function and every variable which is not shared with another file. A name which is not static is visible to the whole kernel when the code is built in, and can clash with another name.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Start every name with the name of the module&amp;#039;&amp;#039;&amp;#039; (&amp;lt;code&amp;gt;membuf_read&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;struct membuf&amp;lt;/code&amp;gt;).&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Keep the state of a device in a structure&amp;#039;&amp;#039;&amp;#039;, not in global variables. There may be multiple instances of the same device.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;There is no C library.&amp;#039;&amp;#039;&amp;#039; No &amp;lt;code&amp;gt;printf()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;malloc()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;errno&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;&amp;amp;lt;stdio.h&amp;amp;gt;&amp;lt;/code&amp;gt;. The kernel has its own versions, in &amp;lt;code&amp;gt;&amp;amp;lt;linux/...&amp;amp;gt;&amp;lt;/code&amp;gt; headers:&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! C library !! Kernel&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;printf()&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;pr_info()&amp;lt;/code&amp;gt;, ...&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;malloc()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;free()&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;kmalloc()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;kfree()&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;strcpy()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;strncpy()&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;strscpy()&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;strtol()&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;kstrtol()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;kstrtouint()&amp;lt;/code&amp;gt;, ...&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;sleep()&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;msleep()&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;errno&amp;lt;/code&amp;gt; || A negative return value&lt;br /&gt;
|}&lt;br /&gt;
: &amp;lt;code&amp;gt;memcpy()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;memset()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;strlen()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;strcmp()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;snprintf()&amp;lt;/code&amp;gt; exist, with the same names.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Avoid (large) arrays on the stack and recursive functions&amp;#039;&amp;#039;&amp;#039;: The stack is small. 16 KiB on x86-64 and arm64. Large arrays go on the heap (&amp;lt;code&amp;gt;kmalloc()&amp;lt;/code&amp;gt;) or in a global.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;No floating point.&amp;#039;&amp;#039;&amp;#039; The kernel does not save the registers of the floating-point unit when it is entered, so it cannot use them. Trying to use them will make the module build fail, or the module not load: &amp;lt;code&amp;gt;Unknown symbol __floatsidf&amp;lt;/code&amp;gt;. Use integers, for example millimetres instead of metres, nanoseconds instead of seconds.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Follow the kernel coding style.&amp;#039;&amp;#039;&amp;#039; The kernel coding style is explained in [https://www.kernel.org/doc/html/latest/process/coding-style.html Linux kernel coding style]. Because the kernel is one large program, it is important to follow it.&lt;br /&gt;
&lt;br /&gt;
== Data types ==&lt;br /&gt;
&lt;br /&gt;
Only a subset of primitive data types usable in C are common in kernel code.&lt;br /&gt;
&lt;br /&gt;
Kernel code uses its own names for integers of a fixed size, from &amp;lt;code&amp;gt;&amp;amp;lt;linux/types.h&amp;amp;gt;&amp;lt;/code&amp;gt;. When code needs to be shared between kernel and user code, an even smaller subset is used:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Value !! Kernel code !! User code !! Shared header&lt;br /&gt;
|-&lt;br /&gt;
| 8 bits, unsigned || &amp;lt;code&amp;gt;u8&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;uint8_t&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;__u8&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| 8 bits, signed || &amp;lt;code&amp;gt;s8&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;int8_t&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;__s8&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| 16 bits, unsigned || &amp;lt;code&amp;gt;u16&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;uint16_t&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;__u16&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| 16 bits, signed || &amp;lt;code&amp;gt;s16&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;int16_t&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;__s16&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| 32 bits, unsigned || &amp;lt;code&amp;gt;u32&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;uint32_t&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;__u32&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| 32 bits, signed || &amp;lt;code&amp;gt;s32&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;int32_t&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;__s32&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| 64 bits, unsigned || &amp;lt;code&amp;gt;u64&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;uint64_t&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;__u64&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| 64 bits, signed || &amp;lt;code&amp;gt;s64&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;int64_t&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;__s64&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| A character of text || &amp;lt;code&amp;gt;char&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;char&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;char&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| True or false || &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;__u8&amp;lt;/code&amp;gt; (0 or 1)&lt;br /&gt;
|-&lt;br /&gt;
| A size in bytes || &amp;lt;code&amp;gt;size_t&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;size_t&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;__u32&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;__u64&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| An address, or a value as wide as a register || &amp;lt;code&amp;gt;long&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;unsigned long&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;intptr_t&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;uintptr_t&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;__u64&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Types used in the kernel:&lt;br /&gt;
&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;An exact size&amp;#039;&amp;#039;&amp;#039;, for registers, protocol fields, counters: &amp;lt;code&amp;gt;u8&amp;lt;/code&amp;gt; ... &amp;lt;code&amp;gt;u64&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;s8&amp;lt;/code&amp;gt; ... &amp;lt;code&amp;gt;s64&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Text&amp;#039;&amp;#039;&amp;#039;: &amp;lt;code&amp;gt;char&amp;lt;/code&amp;gt;, and only for text. For bytes which are not text, use &amp;lt;code&amp;gt;u8&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;&amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;&amp;#039;&amp;#039;&amp;#039; for the values which are &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; by convention: file descriptors, error codes, the return value of most functions.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;&amp;lt;code&amp;gt;long&amp;lt;/code&amp;gt;&amp;#039;&amp;#039;&amp;#039; and &amp;lt;code&amp;gt;unsigned long&amp;lt;/code&amp;gt; for values as wide as a register: the arguments of a system call, the argument of &amp;lt;code&amp;gt;ioctl()&amp;lt;/code&amp;gt;, addresses.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;&amp;lt;code&amp;gt;size_t&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;ssize_t&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;loff_t&amp;lt;/code&amp;gt;&amp;#039;&amp;#039;&amp;#039; where they are used conventionally: sizes, the results of &amp;lt;code&amp;gt;read()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;write()&amp;lt;/code&amp;gt;, file positions.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;&amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt;&amp;#039;&amp;#039;&amp;#039; for true or false.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Nothing else&amp;#039;&amp;#039;&amp;#039;: no &amp;lt;code&amp;gt;short&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;long long&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;unsigned&amp;lt;/code&amp;gt; on its own, and no &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; at all.&lt;br /&gt;
&lt;br /&gt;
In a shared header, only use &amp;lt;code&amp;gt;__u8&amp;lt;/code&amp;gt; ... &amp;lt;code&amp;gt;__s64&amp;lt;/code&amp;gt;. The size of &amp;lt;code&amp;gt;long&amp;lt;/code&amp;gt; and of a pointer differs between 32-bit and 64-bit programs, and a 32-bit program can run on a 64-bit kernel. The size of &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt; and of an &amp;lt;code&amp;gt;enum&amp;lt;/code&amp;gt; is up to the compiler, and the kernel compiler and the userspace compiler may disagree.&lt;br /&gt;
&lt;br /&gt;
== Errors and memory ==&lt;br /&gt;
&lt;br /&gt;
=== Returning errors ===&lt;br /&gt;
&lt;br /&gt;
There is no &amp;lt;code&amp;gt;errno&amp;lt;/code&amp;gt; in the kernel. A function which can fail returns 0, or a positive result, on success, and a negative error code on failure: &amp;lt;code&amp;gt;return -ENOMEM;&amp;lt;/code&amp;gt;. When a system call returns a negative value to user space, the C library stores it in &amp;lt;code&amp;gt;errno&amp;lt;/code&amp;gt;, without the minus, and returns -1 to the program.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Error !! Meaning&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-EINVAL&amp;lt;/code&amp;gt; || An argument is invalid&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-EFAULT&amp;lt;/code&amp;gt; || A pointer from user space does not point to memory which the process may use&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-ENOMEM&amp;lt;/code&amp;gt; || Out of memory&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-ENOTTY&amp;lt;/code&amp;gt; || The device does not know this &amp;lt;code&amp;gt;ioctl()&amp;lt;/code&amp;gt; command&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-EBUSY&amp;lt;/code&amp;gt; || Resource requested is in use&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-EAGAIN&amp;lt;/code&amp;gt; || Not now: the call would block, and the file was opened with &amp;lt;code&amp;gt;O_NONBLOCK&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-ENOSPC&amp;lt;/code&amp;gt; || No room left on device&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-ENODEV&amp;lt;/code&amp;gt; || The device doesn&amp;#039;t exist (anymore)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;-ERESTARTSYS&amp;lt;/code&amp;gt; || A signal interrupted a wait. User space never sees it: the kernel runs the signal handler, and restarts the system call or makes it fail with &amp;lt;code&amp;gt;EINTR&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Functions which return a pointer cannot return a negative number, so they hide the error in the pointer:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/err.h&amp;gt;&lt;br /&gt;
void *ERR_PTR(long error); // An error as a pointer&lt;br /&gt;
bool IS_ERR(const void *ptr); // Is the pointer an error?&lt;br /&gt;
long PTR_ERR(const void *ptr); // The error in the pointer&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
dev = device_create(&amp;amp;membuf_class, NULL, MEMBUF_DEVT, NULL, &amp;quot;membuf&amp;quot;);&lt;br /&gt;
if (IS_ERR(dev)) {&lt;br /&gt;
	ret = PTR_ERR(dev);&lt;br /&gt;
	goto err_class;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Read the documentation of each function: some return &amp;lt;code&amp;gt;NULL&amp;lt;/code&amp;gt; on failure, others an error pointer.&lt;br /&gt;
&lt;br /&gt;
=== Cleaning up with goto ===&lt;br /&gt;
&lt;br /&gt;
C does not have automatic destructors, so care must be taken when errors occur so that partially initialized structures are deallocated before references to them are lost.&lt;br /&gt;
&lt;br /&gt;
The kernel convention is to use a series of &amp;lt;code&amp;gt;goto&amp;lt;/code&amp;gt; labels to clean up initializations in reverse order when we need to return with a failure.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
	ret = register_chrdev_region(MEMBUF_DEVT, 1, &amp;quot;membuf&amp;quot;);&lt;br /&gt;
	if (ret)&lt;br /&gt;
		return ret;&lt;br /&gt;
&lt;br /&gt;
	cdev_init(&amp;amp;membuf.cdev, &amp;amp;membuf_fops);&lt;br /&gt;
	membuf.cdev.owner = THIS_MODULE;&lt;br /&gt;
	ret = cdev_add(&amp;amp;membuf.cdev, MEMBUF_DEVT, 1);&lt;br /&gt;
	if (ret)&lt;br /&gt;
		goto err_region;&lt;br /&gt;
&lt;br /&gt;
	ret = class_register(&amp;amp;membuf_class);&lt;br /&gt;
	if (ret)&lt;br /&gt;
		goto err_cdev;&lt;br /&gt;
&lt;br /&gt;
	dev = device_create(&amp;amp;membuf_class, NULL, MEMBUF_DEVT, NULL, &amp;quot;membuf&amp;quot;);&lt;br /&gt;
	if (IS_ERR(dev)) {&lt;br /&gt;
		ret = PTR_ERR(dev);&lt;br /&gt;
		goto err_class;&lt;br /&gt;
	}&lt;br /&gt;
	return 0;&lt;br /&gt;
&lt;br /&gt;
err_class:&lt;br /&gt;
	class_unregister(&amp;amp;membuf_class);&lt;br /&gt;
err_cdev:&lt;br /&gt;
	cdev_del(&amp;amp;membuf.cdev);&lt;br /&gt;
err_region:&lt;br /&gt;
	unregister_chrdev_region(MEMBUF_DEVT, 1);&lt;br /&gt;
	pr_err(&amp;quot;cannot load: %pe\n&amp;quot;, ERR_PTR(ret));&lt;br /&gt;
	return ret;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== kmalloc() and kfree() ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/slab.h&amp;gt;&lt;br /&gt;
void *kmalloc(size_t size, gfp_t flags);&lt;br /&gt;
void *kzalloc(size_t size, gfp_t flags); // Like kmalloc(), and zeroes the memory&lt;br /&gt;
void kfree(const void *ptr);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
They return &amp;lt;code&amp;gt;NULL&amp;lt;/code&amp;gt; when there is no memory, which must be checked.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;flags&amp;lt;/code&amp;gt; says what the allocation may do to find memory:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Flag !! Meaning&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;GFP_KERNEL&amp;lt;/code&amp;gt; || It may sleep, while the kernel frees memory. Used in most kernel code&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;GFP_ATOMIC&amp;lt;/code&amp;gt; || It never sleeps, and fails instead if it cannot find memory quickly. It should be used only where sleeping is not allowed: while holding a spinlock, or in an interrupt handler&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Nothing is freed for you. When a process ends, the kernel frees all its memory, but when a module is unloaded, what it allocated and did not free is lost until the machine restarts.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Kernel data structures ==&lt;br /&gt;
&lt;br /&gt;
In user space, the usual way to keep many objects is a dynamic array: a block of memory which is replaced by a larger one, and copied, whenever it fills up (a &amp;lt;code&amp;gt;vector&amp;lt;/code&amp;gt; in C++ and Rust, a &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; in Python). It is simple and fast to walk, but the kernel mostly uses linked lists instead for the following reasons:&lt;br /&gt;
&lt;br /&gt;
* growing an array needs a new, larger block of contiguous memory, which may not be available, so adding an object can fail at any time;&lt;br /&gt;
* growing an array moves the objects, and the kernel keeps pointers to its objects everywhere: in open files, in other lists, in the hardware&amp;#039;s own queues. A pointer to an object in a list stays valid as long as the object exists;&lt;br /&gt;
* objects in the kernel come and go in any order (devices are plugged and unplugged, files are opened and closed), and removing one from the middle of an array means moving all the ones after it.&lt;br /&gt;
&lt;br /&gt;
=== Intrusive structures and container_of() ===&lt;br /&gt;
&lt;br /&gt;
A list in user space usually has nodes which point to the data. The kernel&amp;#039;s lists do it the other way around: the node, a &amp;lt;code&amp;gt;struct list_head&amp;lt;/code&amp;gt;, is a member of the data. The list links these members, and knows nothing about the structures around them. Such a structure is called &amp;#039;&amp;#039;&amp;#039;intrusive&amp;#039;&amp;#039;&amp;#039;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/list.h&amp;gt;&lt;br /&gt;
struct list_head {&lt;br /&gt;
	struct list_head *next, *prev;&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
struct student {&lt;br /&gt;
	char name[16];&lt;br /&gt;
	u8 grade;&lt;br /&gt;
	struct list_head node; /* links this student into the list */&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_8_-_list.png|center|thumb|600px|A list of three students. The head and the &amp;lt;code&amp;gt;node&amp;lt;/code&amp;gt; member of each student form a circle. &amp;lt;code&amp;gt;container_of()&amp;lt;/code&amp;gt; goes from a &amp;lt;code&amp;gt;node&amp;lt;/code&amp;gt; back to the start of its student.]]&lt;br /&gt;
&lt;br /&gt;
Walking the list gives pointers to &amp;lt;code&amp;gt;node&amp;lt;/code&amp;gt; members. &amp;lt;code&amp;gt;container_of()&amp;lt;/code&amp;gt; turns such a pointer into a pointer to the structure around it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/container_of.h&amp;gt;&lt;br /&gt;
container_of(ptr, type, member)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It subtracts the offset of &amp;lt;code&amp;gt;member&amp;lt;/code&amp;gt; in &amp;lt;code&amp;gt;type&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;ptr&amp;lt;/code&amp;gt;. It is used everywhere in the kernel: the kernel hands a module a pointer to a member which it knows about (a &amp;lt;code&amp;gt;struct list_head&amp;lt;/code&amp;gt;, a &amp;lt;code&amp;gt;struct cdev&amp;lt;/code&amp;gt;, a &amp;lt;code&amp;gt;struct kref&amp;lt;/code&amp;gt;), and the module gets back to its own structure.&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_8_-_container_of.png|center|thumb|700px|The list gives a pointer to &amp;lt;code&amp;gt;node&amp;lt;/code&amp;gt;. &amp;lt;code&amp;gt;container_of()&amp;lt;/code&amp;gt; goes back by the offset of &amp;lt;code&amp;gt;node&amp;lt;/code&amp;gt;, 24 bytes, to the start of the student.]]&lt;br /&gt;
&lt;br /&gt;
==== Several members of the same type ====&lt;br /&gt;
&lt;br /&gt;
A structure may have several members of the same type, for example to be in two lists at once. The name of the member tells &amp;lt;code&amp;gt;container_of()&amp;lt;/code&amp;gt; which offset to subtract, so it must be the member which the pointer really points to:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
struct course_student {&lt;br /&gt;
	char name[16];&lt;br /&gt;
	struct list_head by_name;  /* offset 16: in the list sorted by name */&lt;br /&gt;
	struct list_head by_grade; /* offset 32: in the list sorted by grade */&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
/* p came from the list sorted by grade, so it points to a by_grade member */&lt;br /&gt;
struct course_student *cs = container_of(p, struct course_student, by_grade);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
With &amp;lt;code&amp;gt;by_name&amp;lt;/code&amp;gt; instead, the code still builds, since both members are &amp;lt;code&amp;gt;struct list_head&amp;lt;/code&amp;gt;, but &amp;lt;code&amp;gt;cs&amp;lt;/code&amp;gt; is 16 bytes past the real structure, and every field read through it is wrong. The same happens with a pointer which is not inside a &amp;lt;code&amp;gt;struct course_student&amp;lt;/code&amp;gt; at all. &amp;lt;code&amp;gt;container_of()&amp;lt;/code&amp;gt; cannot check this: the programmer must know where the pointer came from.&lt;br /&gt;
&lt;br /&gt;
==== In real code ====&lt;br /&gt;
&lt;br /&gt;
The kernel calls a module with a pointer to a member which the kernel knows about, and the module uses &amp;lt;code&amp;gt;container_of()&amp;lt;/code&amp;gt; to get back to its own structure. Two cases appear in this lab:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
/* open(): the inode of a device file points to the struct cdev which was&lt;br /&gt;
 * registered for its number, and the cdev is a member of our structure. */&lt;br /&gt;
static int membuf_open(struct inode *inode, struct file *file)&lt;br /&gt;
{&lt;br /&gt;
	struct membuf *mb = container_of(inode-&amp;gt;i_cdev, struct membuf, cdev);&lt;br /&gt;
	...&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
/* Walking a list by hand: each next pointer is a node member. */&lt;br /&gt;
struct list_head *first = students.next;&lt;br /&gt;
struct student *s = container_of(first, struct student, node);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;list_*_entry()&amp;lt;/code&amp;gt; macros below, such as &amp;lt;code&amp;gt;list_for_each_entry()&amp;lt;/code&amp;gt;, call &amp;lt;code&amp;gt;container_of()&amp;lt;/code&amp;gt; for you: that is what their &amp;lt;code&amp;gt;member&amp;lt;/code&amp;gt; argument is for.&lt;br /&gt;
&lt;br /&gt;
=== Lists ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The kernel uses its doubly linked list for almost every collection, with a few properties:&lt;br /&gt;
&lt;br /&gt;
* the links are inside the object, so adding an object to a list allocates nothing, and cannot fail;&lt;br /&gt;
* given an object, it can be removed from its list in constant time, without searching;&lt;br /&gt;
* an object can be in several lists at once, with one &amp;lt;code&amp;gt;struct list_head&amp;lt;/code&amp;gt; for each;&lt;br /&gt;
* one implementation, in &amp;lt;code&amp;gt;&amp;amp;lt;linux/list.h&amp;amp;gt;&amp;lt;/code&amp;gt;, works for every type.&lt;br /&gt;
&lt;br /&gt;
A list starts at a &amp;#039;&amp;#039;&amp;#039;head&amp;#039;&amp;#039;&amp;#039;, a &amp;lt;code&amp;gt;struct list_head&amp;lt;/code&amp;gt; which is not part of any object. An empty list is a head which points to itself.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Macro !! What it does&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;LIST_HEAD(name)&amp;lt;/code&amp;gt; || Defines an empty list called &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;INIT_LIST_HEAD(&amp;amp;head)&amp;lt;/code&amp;gt; || Makes &amp;lt;code&amp;gt;head&amp;lt;/code&amp;gt; an empty list, for a head inside a structure&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;list_add(&amp;amp;obj-&amp;gt;node, &amp;amp;head)&amp;lt;/code&amp;gt; || Adds at the start&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;list_add_tail(&amp;amp;obj-&amp;gt;node, &amp;amp;head)&amp;lt;/code&amp;gt; || Adds at the end&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;list_del(&amp;amp;obj-&amp;gt;node)&amp;lt;/code&amp;gt; || Removes the object from its list&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;list_move_tail(&amp;amp;obj-&amp;gt;node, &amp;amp;head)&amp;lt;/code&amp;gt; || Moves the object to the end of a list&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;list_empty(&amp;amp;head)&amp;lt;/code&amp;gt; || True if the list is empty&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;list_first_entry_or_null(&amp;amp;head, type, member)&amp;lt;/code&amp;gt; || The first object, or &amp;lt;code&amp;gt;NULL&amp;lt;/code&amp;gt; if the list is empty&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;list_for_each_entry(pos, &amp;amp;head, member)&amp;lt;/code&amp;gt; || A loop over every object: &amp;lt;code&amp;gt;pos&amp;lt;/code&amp;gt; points to each one, in turn&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;list_for_each_entry_safe(pos, tmp, &amp;amp;head, member)&amp;lt;/code&amp;gt; || The same, but &amp;lt;code&amp;gt;pos&amp;lt;/code&amp;gt; may be removed and freed inside the loop&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;member&amp;lt;/code&amp;gt; is the name of the &amp;lt;code&amp;gt;struct list_head&amp;lt;/code&amp;gt; in the type, &amp;lt;code&amp;gt;node&amp;lt;/code&amp;gt; in our case. The following module keeps a list of students:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
// SPDX-License-Identifier: GPL-2.0&lt;br /&gt;
#define pr_fmt(fmt) KBUILD_MODNAME &amp;quot;: &amp;quot; fmt&lt;br /&gt;
&lt;br /&gt;
#include &amp;lt;linux/list.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/module.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/slab.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/string.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
struct student {&lt;br /&gt;
	char name[16];&lt;br /&gt;
	u8 grade;&lt;br /&gt;
	struct list_head node; /* links this student into the list */&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
static LIST_HEAD(students); /* an empty list: the head points to itself */&lt;br /&gt;
&lt;br /&gt;
static int student_add(const char *name, u8 grade)&lt;br /&gt;
{&lt;br /&gt;
	struct student *s = kzalloc(sizeof(*s), GFP_KERNEL);&lt;br /&gt;
&lt;br /&gt;
	if (!s)&lt;br /&gt;
		return -ENOMEM;&lt;br /&gt;
	strscpy(s-&amp;gt;name, name, sizeof(s-&amp;gt;name));&lt;br /&gt;
	s-&amp;gt;grade = grade;&lt;br /&gt;
	list_add_tail(&amp;amp;s-&amp;gt;node, &amp;amp;students);&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static void students_print(const char *title)&lt;br /&gt;
{&lt;br /&gt;
	struct student *s;&lt;br /&gt;
&lt;br /&gt;
	pr_info(&amp;quot;%s:\n&amp;quot;, title);&lt;br /&gt;
	list_for_each_entry(s, &amp;amp;students, node)&lt;br /&gt;
		pr_info(&amp;quot;  %s %u\n&amp;quot;, s-&amp;gt;name, s-&amp;gt;grade);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static void students_free(void)&lt;br /&gt;
{&lt;br /&gt;
	struct student *s, *tmp;&lt;br /&gt;
&lt;br /&gt;
	list_for_each_entry_safe(s, tmp, &amp;amp;students, node) {&lt;br /&gt;
		list_del(&amp;amp;s-&amp;gt;node);&lt;br /&gt;
		kfree(s);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static int __init lists_init(void)&lt;br /&gt;
{&lt;br /&gt;
	static const struct {&lt;br /&gt;
		const char *name;&lt;br /&gt;
		u8 grade;&lt;br /&gt;
	} start[] = { { &amp;quot;ana&amp;quot;, 9 }, { &amp;quot;bob&amp;quot;, 4 }, { &amp;quot;eve&amp;quot;, 10 }, { &amp;quot;dan&amp;quot;, 3 } };&lt;br /&gt;
	struct student *s, *tmp;&lt;br /&gt;
	struct list_head *first;&lt;br /&gt;
&lt;br /&gt;
	for (size_t i = 0; i &amp;lt; ARRAY_SIZE(start); i++) {&lt;br /&gt;
		if (student_add(start[i].name, start[i].grade)) {&lt;br /&gt;
			students_free();&lt;br /&gt;
			return -ENOMEM;&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
	students_print(&amp;quot;all&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
	/*&lt;br /&gt;
	 * The list only links the list_head members. Get back to the student&lt;br /&gt;
	 * around one of them with container_of().&lt;br /&gt;
	 */&lt;br /&gt;
	first = students.next;&lt;br /&gt;
	s = container_of(first, struct student, node);&lt;br /&gt;
	pr_info(&amp;quot;first: %s\n&amp;quot;, s-&amp;gt;name);&lt;br /&gt;
&lt;br /&gt;
	/*&lt;br /&gt;
	 * Remove while walking the list: the _safe version keeps the next&lt;br /&gt;
	 * element in tmp, before s is freed.&lt;br /&gt;
	 */&lt;br /&gt;
	list_for_each_entry_safe(s, tmp, &amp;amp;students, node) {&lt;br /&gt;
		if (s-&amp;gt;grade &amp;lt; 5) {&lt;br /&gt;
			list_del(&amp;amp;s-&amp;gt;node);&lt;br /&gt;
			kfree(s);&lt;br /&gt;
		}&lt;br /&gt;
	}&lt;br /&gt;
	students_print(&amp;quot;passed&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
	/* Move the first student to the end. */&lt;br /&gt;
	s = list_first_entry_or_null(&amp;amp;students, struct student, node);&lt;br /&gt;
	if (s)&lt;br /&gt;
		list_move_tail(&amp;amp;s-&amp;gt;node, &amp;amp;students);&lt;br /&gt;
	students_print(&amp;quot;rotated&amp;quot;);&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static void __exit lists_exit(void)&lt;br /&gt;
{&lt;br /&gt;
	students_free();&lt;br /&gt;
	pr_info(&amp;quot;list empty: %d\n&amp;quot;, list_empty(&amp;amp;students));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
module_init(lists_init);&lt;br /&gt;
module_exit(lists_exit);&lt;br /&gt;
&lt;br /&gt;
MODULE_LICENSE(&amp;quot;GPL&amp;quot;);&lt;br /&gt;
MODULE_DESCRIPTION(&amp;quot;Kernel lists: add, walk, remove, container_of&amp;quot;);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sudo insmod driver/lists.ko&lt;br /&gt;
$ sudo rmmod lists&lt;br /&gt;
$ sudo dmesg | tail -13&lt;br /&gt;
[446617.269675] lists: all:&lt;br /&gt;
[446617.269680] lists:   ana 9&lt;br /&gt;
[446617.269681] lists:   bob 4&lt;br /&gt;
[446617.269681] lists:   eve 10&lt;br /&gt;
[446617.269681] lists:   dan 3&lt;br /&gt;
[446617.269682] lists: first: ana&lt;br /&gt;
[446617.269682] lists: passed:&lt;br /&gt;
[446617.269682] lists:   ana 9&lt;br /&gt;
[446617.269682] lists:   eve 10&lt;br /&gt;
[446617.269683] lists: rotated:&lt;br /&gt;
[446617.269683] lists:   eve 10&lt;br /&gt;
[446617.269683] lists:   ana 9&lt;br /&gt;
[446617.272695] lists: list empty: 1&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; A list does no locking of its own. If two processes can change it at the same time, you must protect it with a lock (see below).&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The kernel has other intrusive structures, built in the same way: &amp;lt;code&amp;gt;hlist&amp;lt;/code&amp;gt; for hash tables, &amp;lt;code&amp;gt;rbtree&amp;lt;/code&amp;gt; for sorted data, &amp;lt;code&amp;gt;xarray&amp;lt;/code&amp;gt; for arrays indexed by number, &amp;lt;code&amp;gt;kfifo&amp;lt;/code&amp;gt; for queues of bytes and &amp;lt;code&amp;gt;kref&amp;lt;/code&amp;gt; for reference counting.&lt;br /&gt;
&lt;br /&gt;
== Declaring a device ==&lt;br /&gt;
&lt;br /&gt;
=== Device numbers ===&lt;br /&gt;
&lt;br /&gt;
A device file in &amp;lt;code&amp;gt;/dev&amp;lt;/code&amp;gt; holds no data. It holds a pair of numbers, &amp;#039;&amp;#039;&amp;#039;major:minor&amp;#039;&amp;#039;&amp;#039;, which names one device. The device belongs to whichever driver registered that pair. &amp;lt;code&amp;gt;ls -l&amp;lt;/code&amp;gt; shows the numbers where the size would be:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ls -l /dev/null /dev/zero&lt;br /&gt;
crw-rw-rw- 1 root root 1, 3 Nov 12 14:59 /dev/null&lt;br /&gt;
crw-rw-rw- 1 root root 1, 5 Nov 12 14:59 /dev/zero&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt; means a &amp;#039;&amp;#039;&amp;#039;character device&amp;#039;&amp;#039;&amp;#039;: one which is read and written as a stream of bytes. When a process opens such a file, the kernel looks up the driver which registered the numbers, and from then on, every system call on the file descriptor calls a function of that driver.&lt;br /&gt;
&lt;br /&gt;
Often a driver has a whole major number, and its devices are the minors (&amp;lt;code&amp;gt;/dev/null&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;/dev/zero&amp;lt;/code&amp;gt; are two devices of the driver of major 1), but that is only a habit: a driver registers a range of numbers, and several drivers can share a major. All misc devices have major 10, and on OrbStack, USB devices and this lab&amp;#039;s drivers share major 180 (see [[#Device numbers on OrbStack|below]]).&lt;br /&gt;
&lt;br /&gt;
The kernel keeps both numbers in an integer &amp;lt;code&amp;gt;dev_t&amp;lt;/code&amp;gt; type:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/kdev_t.h&amp;gt;&lt;br /&gt;
dev_t MKDEV(unsigned int major, unsigned int minor);&lt;br /&gt;
unsigned int MAJOR(dev_t dev);&lt;br /&gt;
unsigned int MINOR(dev_t dev);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Registering a character device ===&lt;br /&gt;
&lt;br /&gt;
It takes three steps: get a number, connect it to the driver&amp;#039;s functions, and tell user space that the device exists.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/fs.h&amp;gt;&lt;br /&gt;
int alloc_chrdev_region(dev_t *dev, unsigned int firstminor, unsigned int count, const char *name);&lt;br /&gt;
int register_chrdev_region(dev_t first, unsigned int count, const char *name);&lt;br /&gt;
void unregister_chrdev_region(dev_t first, unsigned int count);&lt;br /&gt;
&lt;br /&gt;
// In: &amp;lt;linux/cdev.h&amp;gt;&lt;br /&gt;
void cdev_init(struct cdev *cdev, const struct file_operations *fops);&lt;br /&gt;
int cdev_add(struct cdev *cdev, dev_t dev, unsigned int count);&lt;br /&gt;
void cdev_del(struct cdev *cdev);&lt;br /&gt;
&lt;br /&gt;
// In: &amp;lt;linux/device.h&amp;gt;&lt;br /&gt;
int class_register(const struct class *class);&lt;br /&gt;
void class_unregister(const struct class *class);&lt;br /&gt;
struct device *device_create(const struct class *class, struct device *parent, dev_t devt,&lt;br /&gt;
                             void *drvdata, const char *fmt, ...);&lt;br /&gt;
void device_destroy(const struct class *class, dev_t devt);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The init function does the three steps in this order, and the exit function undoes them in the reverse order:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Step !! Init calls !! Exit calls !! After this step&lt;br /&gt;
|-&lt;br /&gt;
| 1. Reserve a number || &amp;lt;code&amp;gt;register_chrdev_region()&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;alloc_chrdev_region()&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;unregister_chrdev_region()&amp;lt;/code&amp;gt; || No other driver can take the number. Nothing happens yet when it is opened&lt;br /&gt;
|-&lt;br /&gt;
| 2. Connect the number to the functions || &amp;lt;code&amp;gt;cdev_init()&amp;lt;/code&amp;gt;, then &amp;lt;code&amp;gt;cdev_add()&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;cdev_del()&amp;lt;/code&amp;gt; || Opening a file with this number calls the driver. There is no such file yet&lt;br /&gt;
|-&lt;br /&gt;
| 3. Make the file in &amp;lt;code&amp;gt;/dev&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;class_register()&amp;lt;/code&amp;gt;, then &amp;lt;code&amp;gt;device_create()&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;device_destroy()&amp;lt;/code&amp;gt;, then &amp;lt;code&amp;gt;class_unregister()&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;/dev/&amp;amp;lt;name&amp;amp;gt;&amp;lt;/code&amp;gt; exists, and programs can open it&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Step 1.&amp;#039;&amp;#039;&amp;#039; &amp;lt;code&amp;gt;register_chrdev_region()&amp;lt;/code&amp;gt; takes &amp;lt;code&amp;gt;count&amp;lt;/code&amp;gt; numbers starting at &amp;lt;code&amp;gt;first&amp;lt;/code&amp;gt;, chosen by the driver, and fails with &amp;lt;code&amp;gt;-EBUSY&amp;lt;/code&amp;gt; if another driver has them. &amp;lt;code&amp;gt;alloc_chrdev_region()&amp;lt;/code&amp;gt; lets the kernel choose: it finds &amp;lt;code&amp;gt;count&amp;lt;/code&amp;gt; free numbers, and stores the first one in &amp;lt;code&amp;gt;*dev&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Step 2.&amp;#039;&amp;#039;&amp;#039; A &amp;lt;code&amp;gt;struct cdev&amp;lt;/code&amp;gt; is the kernel&amp;#039;s record of a character device: which numbers it has, and its &amp;lt;code&amp;gt;struct file_operations&amp;lt;/code&amp;gt;, the table of the driver&amp;#039;s functions (see [[#File operations|File operations]]). It is usually a member of the driver&amp;#039;s own structure, which is how &amp;lt;code&amp;gt;open()&amp;lt;/code&amp;gt; finds that structure again with &amp;lt;code&amp;gt;container_of()&amp;lt;/code&amp;gt;. &amp;lt;code&amp;gt;cdev_init()&amp;lt;/code&amp;gt; fills it in, and &amp;lt;code&amp;gt;cdev_add()&amp;lt;/code&amp;gt; makes it live. From that moment, the driver&amp;#039;s functions can be called, so everything they use must be ready before &amp;lt;code&amp;gt;cdev_add()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Step 3.&amp;#039;&amp;#039;&amp;#039; After steps 1 and 2, the number works, but there is still no file in &amp;lt;code&amp;gt;/dev&amp;lt;/code&amp;gt;: reserving a number and adding a &amp;lt;code&amp;gt;struct cdev&amp;lt;/code&amp;gt; does not create one. The file is created only when the driver adds a &amp;#039;&amp;#039;&amp;#039;device&amp;#039;&amp;#039;&amp;#039; with that number. &amp;lt;code&amp;gt;class_register()&amp;lt;/code&amp;gt; registers a &amp;#039;&amp;#039;&amp;#039;class&amp;#039;&amp;#039;&amp;#039;, a group of devices of one kind, and &amp;lt;code&amp;gt;device_create()&amp;lt;/code&amp;gt; adds a device to it. The device appears in &amp;lt;code&amp;gt;/sys/class/&amp;amp;lt;class&amp;amp;gt;/&amp;amp;lt;name&amp;amp;gt;/&amp;lt;/code&amp;gt;, where the file &amp;lt;code&amp;gt;dev&amp;lt;/code&amp;gt; holds its numbers. On most systems, &amp;lt;code&amp;gt;/dev&amp;lt;/code&amp;gt; is a &amp;#039;&amp;#039;&amp;#039;devtmpfs&amp;#039;&amp;#039;&amp;#039;, a file system kept by the kernel itself, and the kernel adds &amp;lt;code&amp;gt;/dev/&amp;amp;lt;name&amp;amp;gt;&amp;lt;/code&amp;gt; to it at the same moment. A program called &amp;#039;&amp;#039;&amp;#039;udev&amp;#039;&amp;#039;&amp;#039; then sees the new device, and can change the owner and mode of the file, or add links to it, following its rules.&lt;br /&gt;
&lt;br /&gt;
If a step fails, init must undo the steps before it, in the reverse order, and return the error: this is what the labels of [[#Cleaning up with goto|Cleaning up with goto]] are for. The template&amp;#039;s &amp;lt;code&amp;gt;klog_init()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;klog_exit()&amp;lt;/code&amp;gt; show all three steps and their cleanup.&lt;br /&gt;
&lt;br /&gt;
The kernel gives the new file the mode 0600, unless the class says otherwise. Its &amp;lt;code&amp;gt;devnode&amp;lt;/code&amp;gt; function can change it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
static char *membuf_devnode(const struct device *dev, umode_t *mode)&lt;br /&gt;
{&lt;br /&gt;
	if (mode)&lt;br /&gt;
		*mode = 0666;&lt;br /&gt;
	return NULL;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static const struct class membuf_class = {&lt;br /&gt;
	.name = &amp;quot;membuf&amp;quot;,&lt;br /&gt;
	.devnode = membuf_devnode,&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; A driver with a single device can do all three steps with one call. &amp;lt;code&amp;gt;misc_register()&amp;lt;/code&amp;gt;, from &amp;lt;code&amp;gt;&amp;amp;lt;linux/miscdevice.h&amp;amp;gt;&amp;lt;/code&amp;gt;, takes a &amp;lt;code&amp;gt;struct miscdevice&amp;lt;/code&amp;gt; with a name, the &amp;lt;code&amp;gt;struct file_operations&amp;lt;/code&amp;gt; and the mode, and makes a &amp;#039;&amp;#039;&amp;#039;misc device&amp;#039;&amp;#039;&amp;#039;: major number 10, a free minor number, the &amp;lt;code&amp;gt;struct cdev&amp;lt;/code&amp;gt;, and the device in the class &amp;lt;code&amp;gt;misc&amp;lt;/code&amp;gt;. &amp;lt;code&amp;gt;misc_deregister()&amp;lt;/code&amp;gt; removes it. Misc devices do not work on OrbStack (see below).&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Device numbers on OrbStack ===&lt;br /&gt;
&lt;br /&gt;
OrbStack (the macOS virtual machine we recommend) lets its machines open only the device numbers on a fixed list. Opening any other device file fails with &amp;lt;code&amp;gt;EPERM&amp;lt;/code&amp;gt;, even for root. The number which &amp;lt;code&amp;gt;alloc_chrdev_region()&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;misc_register()&amp;lt;/code&amp;gt; picks is not on that list, so the device registers, and nobody can open it.&lt;br /&gt;
&lt;br /&gt;
The whole of major number 180 is on the list, for USB devices. The kernel&amp;#039;s USB code uses only its minor numbers 0 to 255, so the examples in this lab, and the template, take a fixed number above them with &amp;lt;code&amp;gt;register_chrdev_region()&amp;lt;/code&amp;gt;: 180:256 for the template, 180:257 for &amp;lt;code&amp;gt;membuf&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
/* OrbStack only allows device numbers on its list: see the lab. */&lt;br /&gt;
#define MEMBUF_DEVT MKDEV(180, 257)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
OrbStack&amp;#039;s &amp;lt;code&amp;gt;/dev&amp;lt;/code&amp;gt; is also not a devtmpfs, but an ordinary tmpfs, into which OrbStack mounts a few chosen device files, and udev does not create files itself, so nothing creates the file in &amp;lt;code&amp;gt;/dev&amp;lt;/code&amp;gt;. &amp;lt;code&amp;gt;make load&amp;lt;/code&amp;gt; in the template creates it with &amp;lt;code&amp;gt;mknod&amp;lt;/code&amp;gt;, from the numbers in &amp;lt;code&amp;gt;/sys/class/&amp;amp;lt;class&amp;amp;gt;/&amp;amp;lt;name&amp;amp;gt;/dev&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; A serious driver does not pick its number by hand, to avoid clashing with other drivers. On a real production project, use &amp;lt;code&amp;gt;alloc_chrdev_region()&amp;lt;/code&amp;gt; or a misc device.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== File operations ==&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;struct file_operations&amp;lt;/code&amp;gt; of a driver says which function runs for each system call on its files. It is a structure of function pointers, one for each operation. These are the members which character devices typically use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/fs.h&amp;gt;&lt;br /&gt;
struct file_operations {&lt;br /&gt;
	struct module *owner;&lt;br /&gt;
	loff_t (*llseek) (struct file *, loff_t, int);&lt;br /&gt;
	ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);&lt;br /&gt;
	ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);&lt;br /&gt;
	__poll_t (*poll) (struct file *, struct poll_table_struct *);&lt;br /&gt;
	long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);&lt;br /&gt;
	long (*compat_ioctl) (struct file *, unsigned int, unsigned long);&lt;br /&gt;
	int (*mmap) (struct file *, struct vm_area_struct *);&lt;br /&gt;
	int (*open) (struct inode *, struct file *);&lt;br /&gt;
	int (*release) (struct inode *, struct file *);&lt;br /&gt;
	// ... and about 25 more, mostly for regular files&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A driver fills in only the members it needs, with designated initializers. Members which are not set get a default behaviour, usually an error to userspace if the associated system call is called.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
static const struct file_operations membuf_fops = {&lt;br /&gt;
	.owner = THIS_MODULE,&lt;br /&gt;
	.open = membuf_open,&lt;br /&gt;
	.read = membuf_read,&lt;br /&gt;
	.write = membuf_write,&lt;br /&gt;
	.unlocked_ioctl = membuf_ioctl,&lt;br /&gt;
	.compat_ioctl = compat_ptr_ioctl,&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Member !! System call !! If it is not set&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;open&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;open()&amp;lt;/code&amp;gt; || The open succeeds&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;release&amp;lt;/code&amp;gt; || The last &amp;lt;code&amp;gt;close()&amp;lt;/code&amp;gt; of the file || Nothing happens&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;read&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;read()&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;EINVAL&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;write&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;write()&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;EINVAL&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;unlocked_ioctl&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;ioctl()&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;ENOTTY&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;compat_ioctl&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;ioctl()&amp;lt;/code&amp;gt; from a 32-bit program on a 64-bit kernel || &amp;lt;code&amp;gt;ENOTTY&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;llseek&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;lseek()&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;ESPIPE&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;.owner = THIS_MODULE&amp;lt;/code&amp;gt; keeps the module loaded while one of its files is open: &amp;lt;code&amp;gt;rmmod&amp;lt;/code&amp;gt; fails.&lt;br /&gt;
&lt;br /&gt;
Every function gets the &amp;lt;code&amp;gt;struct file&amp;lt;/code&amp;gt; of the open file. It holds the flags of &amp;lt;code&amp;gt;open()&amp;lt;/code&amp;gt; in &amp;lt;code&amp;gt;f_flags&amp;lt;/code&amp;gt;, and a generic pointer which belongs to and is interpreted by the driver, &amp;lt;code&amp;gt;private_data&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== open() and release() ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
int (*open)(struct inode *inode, struct file *file);&lt;br /&gt;
int (*release)(struct inode *inode, struct file *file);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;open()&amp;lt;/code&amp;gt; usually finds the device which the file is for, and sets a pointer to it in &amp;lt;code&amp;gt;file-&amp;gt;private_data&amp;lt;/code&amp;gt;, where the other functions called later will find it. The &amp;lt;code&amp;gt;struct inode&amp;lt;/code&amp;gt; of a device file points to the &amp;lt;code&amp;gt;struct cdev&amp;lt;/code&amp;gt; of the device, which is a member of the driver&amp;#039;s structure:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
static int membuf_open(struct inode *inode, struct file *file)&lt;br /&gt;
{&lt;br /&gt;
	struct membuf *mb = container_of(inode-&amp;gt;i_cdev, struct membuf, cdev);&lt;br /&gt;
&lt;br /&gt;
	file-&amp;gt;private_data = mb;&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;open()&amp;lt;/code&amp;gt; may also refuse to open the file, by returning an error: &amp;lt;code&amp;gt;-EBUSY&amp;lt;/code&amp;gt; if only one process may use the device at a time, for example. &amp;lt;code&amp;gt;release()&amp;lt;/code&amp;gt; undoes what &amp;lt;code&amp;gt;open()&amp;lt;/code&amp;gt; did, if anything. It runs when the last file descriptor which refers to the open file is closed.&lt;br /&gt;
&lt;br /&gt;
=== read() and write() ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
ssize_t (*read)(struct file *file, char __user *buf, size_t count, loff_t *ppos);&lt;br /&gt;
ssize_t (*write)(struct file *file, const char __user *buf, size_t count, loff_t *ppos);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Parameter !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;buf&amp;lt;/code&amp;gt; || The buffer of the process, in user space (see below)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;count&amp;lt;/code&amp;gt; || How many bytes the process asked for&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;ppos&amp;lt;/code&amp;gt; || The position in the file. The driver decides what it means, and is responsible for moving it forward&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
They return how many bytes they read or wrote, or an error. This is what the process gets from &amp;lt;code&amp;gt;read()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;write()&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
* fewer bytes than &amp;lt;code&amp;gt;count&amp;lt;/code&amp;gt; is not an error. Programs are responsible for calling &amp;lt;code&amp;gt;read()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;write()&amp;lt;/code&amp;gt; again;&lt;br /&gt;
* &amp;lt;code&amp;gt;read()&amp;lt;/code&amp;gt; returning 0 means the end of the file;&lt;br /&gt;
* &amp;lt;code&amp;gt;write()&amp;lt;/code&amp;gt; returning 0 is generally malformed and programs may try again forever or may treat it as an opaque error. When there is no more room to write additional data, return an error, such as &amp;lt;code&amp;gt;-ENOSPC&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== ioctl() ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
long (*unlocked_ioctl)(struct file *file, unsigned int cmd, unsigned long arg);&lt;br /&gt;
long (*compat_ioctl) (struct file *file, unsigned int cmd, unsigned long arg);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;ioctl()&amp;lt;/code&amp;gt; (&amp;lt;code&amp;gt;unlocked_ioctl&amp;lt;/code&amp;gt;) is for everything which is not reading or writing data: settings, status, commands. &amp;lt;code&amp;gt;cmd&amp;lt;/code&amp;gt; says what to do. &amp;lt;code&amp;gt;arg&amp;lt;/code&amp;gt; is usually a pointer to a structure in user space.&lt;br /&gt;
&lt;br /&gt;
Each command is a number made with a macro, in the header which the driver shares with user space:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/ioctl.h&amp;gt;&lt;br /&gt;
_IO(type, nr)               // No argument&lt;br /&gt;
_IOR(type, nr, argtype)     // The driver writes an argtype to arg: user space reads it&lt;br /&gt;
_IOW(type, nr, argtype)     // User space writes an argtype for the driver to read&lt;br /&gt;
_IOWR(type, nr, argtype)    // Both&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;type&amp;lt;/code&amp;gt; is one byte, the same for all the commands of a driver, so that a command for one driver is not mistaken for a command of another. &amp;lt;code&amp;gt;nr&amp;lt;/code&amp;gt; numbers the commands. The macros also put the size of &amp;lt;code&amp;gt;argtype&amp;lt;/code&amp;gt; and the direction into the number.&lt;br /&gt;
&lt;br /&gt;
An unknown command should return &amp;lt;code&amp;gt;-ENOTTY&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;compat_ioctl&amp;lt;/code&amp;gt; is called when a 32-bit program calls &amp;lt;code&amp;gt;ioctl&amp;lt;/code&amp;gt; on a 64-bit system. The kernel provides a wrapper: &amp;lt;code&amp;gt;.compat_ioctl = compat_ptr_ioctl&amp;lt;/code&amp;gt;, which calls &amp;lt;code&amp;gt;unlocked_ioctl&amp;lt;/code&amp;gt;, and works for drivers whose &amp;lt;code&amp;gt;arg&amp;lt;/code&amp;gt; is always a pointer (or unused).&lt;br /&gt;
&lt;br /&gt;
== Working with user data ==&lt;br /&gt;
&lt;br /&gt;
=== User pointers ===&lt;br /&gt;
&lt;br /&gt;
Pointers which come from user space are marked &amp;lt;code&amp;gt;__user&amp;lt;/code&amp;gt;, as &amp;lt;code&amp;gt;buf&amp;lt;/code&amp;gt; above. Never dereference them in the kernel:&lt;br /&gt;
&lt;br /&gt;
* the process may have passed any number, by mistake or on purpose: an address in the kernel, or nothing at all;&lt;br /&gt;
* the memory may be in swap, and may need to be read from disk;&lt;br /&gt;
* recent x86-64 and arm64 processors make the kernel fault on any access to user memory which does not go through the functions below.&lt;br /&gt;
&lt;br /&gt;
The functions below check the address, and handle a missing page. They may sleep while the data is read from disk, in case of swapped out or not-yet-allocated memory (see: mmap lazy allocation).&lt;br /&gt;
&lt;br /&gt;
=== copy_from_user() and copy_to_user() ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/uaccess.h&amp;gt;&lt;br /&gt;
unsigned long copy_from_user(void *to, const void __user *from, unsigned long n);&lt;br /&gt;
unsigned long copy_to_user(void __user *to, const void *from, unsigned long n);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;copy_from_user()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;copy_to_user()&amp;lt;/code&amp;gt; return how many bytes they could &amp;#039;&amp;#039;&amp;#039;not&amp;#039;&amp;#039;&amp;#039; copy: 0 means success. A driver should turn anything else into &amp;lt;code&amp;gt;-EFAULT&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
	if (copy_to_user(ubuf, mb-&amp;gt;data + *ppos, count)) {&lt;br /&gt;
		ret = -EFAULT;&lt;br /&gt;
		goto out;&lt;br /&gt;
	}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; When creating a structure which will be copied to user space, always zero it at the beginning, for example with &amp;lt;code&amp;gt;struct membuf_info info = {};&amp;lt;/code&amp;gt;. The compiler may leave gaps between members, and whatever was on the kernel stack in those gaps would go to the process, which would be a security issue.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== The shared header ===&lt;br /&gt;
&lt;br /&gt;
The driver and the programs which use it must agree exactly on a few definitions: the ioctl numbers, the structures which the ioctls carry, and constants such as sizes. Rather than describe them in a document, and write them twice, the kernel keeps them in C headers which both sides include, called &amp;#039;&amp;#039;&amp;#039;uapi headers&amp;#039;&amp;#039;&amp;#039; (for user-space API). The C definitions are then the only description, and the two sides cannot drift apart. A uapi header must compile both in the kernel and in a program, which limits what it may use (see below).&lt;br /&gt;
&lt;br /&gt;
For our project, we store these in &amp;lt;code&amp;gt;driver/uapi/&amp;lt;/code&amp;gt;, which the driver and the library both include.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */&lt;br /&gt;
#ifndef MEMBUF_H&lt;br /&gt;
#define MEMBUF_H&lt;br /&gt;
&lt;br /&gt;
#include &amp;lt;linux/ioctl.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/types.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define MEMBUF_SIZE 4096&lt;br /&gt;
&lt;br /&gt;
struct membuf_info {&lt;br /&gt;
	__u32 size; /* MEMBUF_SIZE */&lt;br /&gt;
	__u32 used; /* bytes in the buffer */&lt;br /&gt;
	__u64 writes; /* write() calls since it was loaded */&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
#define MEMBUF_IOC_MAGIC 0xB8&lt;br /&gt;
#define MEMBUF_IOC_GET_INFO _IOR(MEMBUF_IOC_MAGIC, 1, struct membuf_info)&lt;br /&gt;
#define MEMBUF_IOC_CLEAR _IO(MEMBUF_IOC_MAGIC, 2)&lt;br /&gt;
&lt;br /&gt;
#endif /* MEMBUF_H */&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The structure must have the same layout in the kernel, in 64-bit programs, and in 32-bit ones:&lt;br /&gt;
&lt;br /&gt;
* only &amp;lt;code&amp;gt;__u8&amp;lt;/code&amp;gt; ... &amp;lt;code&amp;gt;__s64&amp;lt;/code&amp;gt;, never &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;long&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;u8&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;s64&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;bool&amp;lt;/code&amp;gt;, an &amp;lt;code&amp;gt;enum&amp;lt;/code&amp;gt; or a pointer;&lt;br /&gt;
* the larger members first, or explicit padding members (&amp;lt;code&amp;gt;__u32 pad;&amp;lt;/code&amp;gt;), so that the compiler adds no gaps.&lt;br /&gt;
* a pointer to more user memory travels as a &amp;lt;code&amp;gt;__u64&amp;lt;/code&amp;gt;. The driver can turn it back into a pointer with &amp;lt;code&amp;gt;u64_to_user_ptr()&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
In user space, the program includes the same header, and passes a pointer to the structure:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;fcntl.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;sys/ioctl.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#include &amp;quot;membuf.h&amp;quot;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(int argc, char *argv[])&lt;br /&gt;
{&lt;br /&gt;
    int fd = open(&amp;quot;/dev/membuf&amp;quot;, O_RDONLY);&lt;br /&gt;
    if (fd == -1) {&lt;br /&gt;
        print_error(&amp;quot;open /dev/membuf&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
    if (argc == 2 &amp;amp;&amp;amp; strcmp(argv[1], &amp;quot;clear&amp;quot;) == 0) {&lt;br /&gt;
        if (ioctl(fd, MEMBUF_IOC_CLEAR) == -1) {&lt;br /&gt;
            print_error(&amp;quot;MEMBUF_IOC_CLEAR&amp;quot;);&lt;br /&gt;
            return EXIT_FAILURE;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    struct membuf_info info;&lt;br /&gt;
    if (ioctl(fd, MEMBUF_IOC_GET_INFO, &amp;amp;info) == -1) {&lt;br /&gt;
        print_error(&amp;quot;MEMBUF_IOC_GET_INFO&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
    char line[128];&lt;br /&gt;
    int len = snprintf(line, sizeof line, &amp;quot;%u of %u bytes used, %llu writes\n&amp;quot;,&lt;br /&gt;
                       info.used, info.size, (unsigned long long)info.writes);&lt;br /&gt;
    write(STDOUT_FILENO, line, len);&lt;br /&gt;
    close(fd);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Locking ==&lt;br /&gt;
&lt;br /&gt;
Two processes may use the same device at the same moment, on two processors. Two threads may even use the same file descriptor. The driver&amp;#039;s functions then run at the same time, on the same data. If one &amp;lt;code&amp;gt;write()&amp;lt;/code&amp;gt; reads &amp;lt;code&amp;gt;used&amp;lt;/code&amp;gt;, and another one changes it before the first one stores the new value, one of the writes is lost.&lt;br /&gt;
&lt;br /&gt;
A &amp;#039;&amp;#039;&amp;#039;mutex&amp;#039;&amp;#039;&amp;#039; lets only one task at a time run the code between &amp;lt;code&amp;gt;mutex_lock()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;mutex_unlock()&amp;lt;/code&amp;gt;. The others wait, asleep:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/mutex.h&amp;gt;&lt;br /&gt;
DEFINE_MUTEX(name); // A mutex outside a structure&lt;br /&gt;
void mutex_init(struct mutex *lock); // A mutex inside a structure&lt;br /&gt;
void mutex_lock(struct mutex *lock);&lt;br /&gt;
int mutex_lock_interruptible(struct mutex *lock); // A signal ends the wait: returns -EINTR&lt;br /&gt;
void mutex_unlock(struct mutex *lock);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Put the mutex in the structure which it protects, and say in a comment what it protects.&lt;br /&gt;
* Where a process waits for the lock on behalf of a system call, prefer &amp;lt;code&amp;gt;mutex_lock_interruptible()&amp;lt;/code&amp;gt;, so that Ctrl+C still works, and return &amp;lt;code&amp;gt;-ERESTARTSYS&amp;lt;/code&amp;gt; if it fails.&lt;br /&gt;
* Never return with the lock held. The &amp;lt;code&amp;gt;goto out&amp;lt;/code&amp;gt; at the end of a function makes sure of it.&lt;br /&gt;
* A task holding a mutex may sleep, so &amp;lt;code&amp;gt;copy_to_user()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;kmalloc(..., GFP_KERNEL)&amp;lt;/code&amp;gt; are fine under it.&lt;br /&gt;
&lt;br /&gt;
The kernel also has &amp;#039;&amp;#039;&amp;#039;spinlocks&amp;#039;&amp;#039;&amp;#039; (&amp;lt;code&amp;gt;spinlock_t&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;spin_lock()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;spin_unlock()&amp;lt;/code&amp;gt;), whose waiters spin on the processor instead of sleeping. Code which holds a spinlock must not sleep in the critical section: no &amp;lt;code&amp;gt;copy_to_user()&amp;lt;/code&amp;gt;, no &amp;lt;code&amp;gt;GFP_KERNEL&amp;lt;/code&amp;gt;. They are needed where sleeping is not allowed at all, such as in interrupt handlers, as well as being generally faster than mutexes when the critical section is very short (a few microseconds).&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== A complete example: membuf ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;membuf&amp;lt;/code&amp;gt; is a buffer of 4 KiB in the kernel, behind &amp;lt;code&amp;gt;/dev/membuf&amp;lt;/code&amp;gt;. The module allocates it with &amp;lt;code&amp;gt;kzalloc()&amp;lt;/code&amp;gt; when it loads, and frees it when it unloads:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;code&amp;gt;write()&amp;lt;/code&amp;gt; adds to the end of the buffer, and fails with &amp;lt;code&amp;gt;ENOSPC&amp;lt;/code&amp;gt; when it is full;&lt;br /&gt;
* &amp;lt;code&amp;gt;read()&amp;lt;/code&amp;gt; reads the buffer from the start, up to the bytes written so far. An empty buffer reads as the end of the file;&lt;br /&gt;
* &amp;lt;code&amp;gt;MEMBUF_IOC_GET_INFO&amp;lt;/code&amp;gt; returns the size, the bytes used and the number of writes, and &amp;lt;code&amp;gt;MEMBUF_IOC_CLEAR&amp;lt;/code&amp;gt; empties the buffer.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
// SPDX-License-Identifier: GPL-2.0&lt;br /&gt;
/*&lt;br /&gt;
 * membuf: a 4 KiB buffer in the kernel, /dev/membuf.&lt;br /&gt;
 *&lt;br /&gt;
 *   write()  adds to the end of the buffer&lt;br /&gt;
 *   read()   reads it from the start&lt;br /&gt;
 *   ioctl()  MEMBUF_IOC_GET_INFO, MEMBUF_IOC_CLEAR&lt;br /&gt;
 */&lt;br /&gt;
#define pr_fmt(fmt) KBUILD_MODNAME &amp;quot;: &amp;quot; fmt&lt;br /&gt;
&lt;br /&gt;
#include &amp;lt;linux/cdev.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/device.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/fs.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/module.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/mutex.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/slab.h&amp;gt;&lt;br /&gt;
#include &amp;lt;linux/uaccess.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#include &amp;quot;membuf.h&amp;quot;&lt;br /&gt;
&lt;br /&gt;
/* OrbStack only allows device numbers on its list: see the lab. */&lt;br /&gt;
#define MEMBUF_DEVT MKDEV(180, 257)&lt;br /&gt;
&lt;br /&gt;
struct membuf {&lt;br /&gt;
	struct cdev cdev;&lt;br /&gt;
	struct mutex lock; /* protects everything below */&lt;br /&gt;
	char *data; /* MEMBUF_SIZE bytes, from kzalloc() */&lt;br /&gt;
	size_t used;&lt;br /&gt;
	u64 writes;&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
static struct membuf membuf;&lt;br /&gt;
&lt;br /&gt;
static int membuf_open(struct inode *inode, struct file *file)&lt;br /&gt;
{&lt;br /&gt;
	struct membuf *mb = container_of(inode-&amp;gt;i_cdev, struct membuf, cdev);&lt;br /&gt;
&lt;br /&gt;
	file-&amp;gt;private_data = mb;&lt;br /&gt;
	return 0;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static ssize_t membuf_read(struct file *file, char __user *ubuf, size_t count,&lt;br /&gt;
			   loff_t *ppos)&lt;br /&gt;
{&lt;br /&gt;
	struct membuf *mb = file-&amp;gt;private_data;&lt;br /&gt;
	ssize_t ret;&lt;br /&gt;
&lt;br /&gt;
	if (mutex_lock_interruptible(&amp;amp;mb-&amp;gt;lock))&lt;br /&gt;
		return -ERESTARTSYS;&lt;br /&gt;
&lt;br /&gt;
	if (*ppos &amp;gt;= mb-&amp;gt;used) {&lt;br /&gt;
		ret = 0; /* end of file */&lt;br /&gt;
		goto out;&lt;br /&gt;
	}&lt;br /&gt;
	count = min_t(size_t, count, mb-&amp;gt;used - *ppos);&lt;br /&gt;
	if (copy_to_user(ubuf, mb-&amp;gt;data + *ppos, count)) {&lt;br /&gt;
		ret = -EFAULT;&lt;br /&gt;
		goto out;&lt;br /&gt;
	}&lt;br /&gt;
	*ppos += count;&lt;br /&gt;
	ret = count;&lt;br /&gt;
out:&lt;br /&gt;
	mutex_unlock(&amp;amp;mb-&amp;gt;lock);&lt;br /&gt;
	return ret;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static ssize_t membuf_write(struct file *file, const char __user *ubuf,&lt;br /&gt;
			    size_t count, loff_t *ppos)&lt;br /&gt;
{&lt;br /&gt;
	struct membuf *mb = file-&amp;gt;private_data;&lt;br /&gt;
	ssize_t ret;&lt;br /&gt;
&lt;br /&gt;
	if (mutex_lock_interruptible(&amp;amp;mb-&amp;gt;lock))&lt;br /&gt;
		return -ERESTARTSYS;&lt;br /&gt;
&lt;br /&gt;
	if (mb-&amp;gt;used == MEMBUF_SIZE) {&lt;br /&gt;
		ret = -ENOSPC;&lt;br /&gt;
		goto out;&lt;br /&gt;
	}&lt;br /&gt;
	count = min_t(size_t, count, MEMBUF_SIZE - mb-&amp;gt;used);&lt;br /&gt;
	if (copy_from_user(mb-&amp;gt;data + mb-&amp;gt;used, ubuf, count)) {&lt;br /&gt;
		ret = -EFAULT;&lt;br /&gt;
		goto out;&lt;br /&gt;
	}&lt;br /&gt;
	mb-&amp;gt;used += count;&lt;br /&gt;
	mb-&amp;gt;writes++;&lt;br /&gt;
	ret = count;&lt;br /&gt;
out:&lt;br /&gt;
	mutex_unlock(&amp;amp;mb-&amp;gt;lock);&lt;br /&gt;
	return ret;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static long membuf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)&lt;br /&gt;
{&lt;br /&gt;
	struct membuf *mb = file-&amp;gt;private_data;&lt;br /&gt;
	struct membuf_info info = {}; /* zeroed, padding included */&lt;br /&gt;
&lt;br /&gt;
	switch (cmd) {&lt;br /&gt;
	case MEMBUF_IOC_GET_INFO:&lt;br /&gt;
		mutex_lock(&amp;amp;mb-&amp;gt;lock);&lt;br /&gt;
		info.size = MEMBUF_SIZE;&lt;br /&gt;
		info.used = mb-&amp;gt;used;&lt;br /&gt;
		info.writes = mb-&amp;gt;writes;&lt;br /&gt;
		mutex_unlock(&amp;amp;mb-&amp;gt;lock);&lt;br /&gt;
		if (copy_to_user((void __user *)arg, &amp;amp;info, sizeof(info)))&lt;br /&gt;
			return -EFAULT;&lt;br /&gt;
		return 0;&lt;br /&gt;
	case MEMBUF_IOC_CLEAR:&lt;br /&gt;
		mutex_lock(&amp;amp;mb-&amp;gt;lock);&lt;br /&gt;
		mb-&amp;gt;used = 0;&lt;br /&gt;
		mutex_unlock(&amp;amp;mb-&amp;gt;lock);&lt;br /&gt;
		return 0;&lt;br /&gt;
	default:&lt;br /&gt;
		return -ENOTTY;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static const struct file_operations membuf_fops = {&lt;br /&gt;
	.owner = THIS_MODULE,&lt;br /&gt;
	.open = membuf_open,&lt;br /&gt;
	.read = membuf_read,&lt;br /&gt;
	.write = membuf_write,&lt;br /&gt;
	.unlocked_ioctl = membuf_ioctl,&lt;br /&gt;
	.compat_ioctl = compat_ptr_ioctl,&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
static char *membuf_devnode(const struct device *dev, umode_t *mode)&lt;br /&gt;
{&lt;br /&gt;
	if (mode)&lt;br /&gt;
		*mode = 0666;&lt;br /&gt;
	return NULL;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static const struct class membuf_class = {&lt;br /&gt;
	.name = &amp;quot;membuf&amp;quot;,&lt;br /&gt;
	.devnode = membuf_devnode,&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
static int __init membuf_init(void)&lt;br /&gt;
{&lt;br /&gt;
	struct device *dev;&lt;br /&gt;
	int ret;&lt;br /&gt;
&lt;br /&gt;
	mutex_init(&amp;amp;membuf.lock);&lt;br /&gt;
	membuf.data = kzalloc(MEMBUF_SIZE, GFP_KERNEL);&lt;br /&gt;
	if (!membuf.data)&lt;br /&gt;
		return -ENOMEM;&lt;br /&gt;
&lt;br /&gt;
	ret = register_chrdev_region(MEMBUF_DEVT, 1, &amp;quot;membuf&amp;quot;);&lt;br /&gt;
	if (ret)&lt;br /&gt;
		goto err_free;&lt;br /&gt;
&lt;br /&gt;
	cdev_init(&amp;amp;membuf.cdev, &amp;amp;membuf_fops);&lt;br /&gt;
	membuf.cdev.owner = THIS_MODULE;&lt;br /&gt;
	ret = cdev_add(&amp;amp;membuf.cdev, MEMBUF_DEVT, 1);&lt;br /&gt;
	if (ret)&lt;br /&gt;
		goto err_region;&lt;br /&gt;
&lt;br /&gt;
	ret = class_register(&amp;amp;membuf_class);&lt;br /&gt;
	if (ret)&lt;br /&gt;
		goto err_cdev;&lt;br /&gt;
&lt;br /&gt;
	dev = device_create(&amp;amp;membuf_class, NULL, MEMBUF_DEVT, NULL, &amp;quot;membuf&amp;quot;);&lt;br /&gt;
	if (IS_ERR(dev)) {&lt;br /&gt;
		ret = PTR_ERR(dev);&lt;br /&gt;
		goto err_class;&lt;br /&gt;
	}&lt;br /&gt;
	return 0;&lt;br /&gt;
&lt;br /&gt;
err_class:&lt;br /&gt;
	class_unregister(&amp;amp;membuf_class);&lt;br /&gt;
err_cdev:&lt;br /&gt;
	cdev_del(&amp;amp;membuf.cdev);&lt;br /&gt;
err_region:&lt;br /&gt;
	unregister_chrdev_region(MEMBUF_DEVT, 1);&lt;br /&gt;
err_free:&lt;br /&gt;
	kfree(membuf.data);&lt;br /&gt;
	pr_err(&amp;quot;cannot load: %pe\n&amp;quot;, ERR_PTR(ret));&lt;br /&gt;
	return ret;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static void __exit membuf_exit(void)&lt;br /&gt;
{&lt;br /&gt;
	device_destroy(&amp;amp;membuf_class, MEMBUF_DEVT);&lt;br /&gt;
	class_unregister(&amp;amp;membuf_class);&lt;br /&gt;
	cdev_del(&amp;amp;membuf.cdev);&lt;br /&gt;
	unregister_chrdev_region(MEMBUF_DEVT, 1);&lt;br /&gt;
	kfree(membuf.data);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
module_init(membuf_init);&lt;br /&gt;
module_exit(membuf_exit);&lt;br /&gt;
&lt;br /&gt;
MODULE_LICENSE(&amp;quot;GPL&amp;quot;);&lt;br /&gt;
MODULE_DESCRIPTION(&amp;quot;A 4 KiB buffer in the kernel&amp;quot;);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To build the example, write &amp;lt;code&amp;gt;membuf.c&amp;lt;/code&amp;gt; in &amp;lt;code&amp;gt;driver/&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;membuf.h&amp;lt;/code&amp;gt; in &amp;lt;code&amp;gt;driver/uapi/&amp;lt;/code&amp;gt;, and the program in &amp;lt;code&amp;gt;app/main.c&amp;lt;/code&amp;gt;. Add &amp;lt;code&amp;gt;membuf.o&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;obj-m&amp;lt;/code&amp;gt; in &amp;lt;code&amp;gt;driver/Kbuild&amp;lt;/code&amp;gt;. Build everything, and load the module. &amp;lt;code&amp;gt;MODULE=membuf&amp;lt;/code&amp;gt; tells the Makefile which module to load:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ cmake --build --preset debug&lt;br /&gt;
$ make -C driver load MODULE=membuf&lt;br /&gt;
$ ls -l /dev/membuf&lt;br /&gt;
crw-rw-rw- 1 root root 180, 257 Nov 18 12:47 /dev/membuf&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Write to it, and read it back. &amp;lt;code&amp;gt;cat&amp;lt;/code&amp;gt; stops at the end of the data:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ echo hello &amp;gt; /dev/membuf&lt;br /&gt;
$ echo kernel &amp;gt;&amp;gt; /dev/membuf&lt;br /&gt;
$ cat /dev/membuf&lt;br /&gt;
hello&lt;br /&gt;
kernel&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
13 of 4096 bytes used, 2 writes&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Fill it up, and empty it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ head -c 5000 /dev/zero &amp;gt; /dev/membuf&lt;br /&gt;
head: error writing &amp;#039;standard output&amp;#039;: No space left on device&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
4096 of 4096 bytes used, 3 writes&lt;br /&gt;
$ ./build/debug/app clear&lt;br /&gt;
0 of 4096 bytes used, 3 writes&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;head&amp;lt;/code&amp;gt; wrote 5000 bytes. The driver took the 4083 which fit, and refused the rest with &amp;lt;code&amp;gt;ENOSPC&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Some things to try:&lt;br /&gt;
&lt;br /&gt;
* Read the empty buffer with &amp;lt;code&amp;gt;cat /dev/membuf&amp;lt;/code&amp;gt;. Which line of &amp;lt;code&amp;gt;membuf_read()&amp;lt;/code&amp;gt; returns, and with what?&lt;br /&gt;
* Keep the file open with &amp;lt;code&amp;gt;exec 3&amp;lt;/dev/membuf&amp;lt;/code&amp;gt;, and run &amp;lt;code&amp;gt;sudo rmmod membuf&amp;lt;/code&amp;gt;. Why does it fail? Close the file with &amp;lt;code&amp;gt;exec 3&amp;lt;&amp;amp;-&amp;lt;/code&amp;gt;, and try again.&lt;br /&gt;
* Read the buffer with &amp;lt;code&amp;gt;dd if=/dev/membuf bs=3&amp;lt;/code&amp;gt;. How many times is &amp;lt;code&amp;gt;membuf_read()&amp;lt;/code&amp;gt; called, and what does &amp;lt;code&amp;gt;*ppos&amp;lt;/code&amp;gt; hold each time?&lt;br /&gt;
* Remove the zeroing of &amp;lt;code&amp;gt;info&amp;lt;/code&amp;gt; in &amp;lt;code&amp;gt;membuf_ioctl()&amp;lt;/code&amp;gt;. Does the program see any difference? Would it, if the structure had a gap?&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Operating_Systems&amp;diff=8457</id>
		<title>Operating Systems</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Operating_Systems&amp;diff=8457"/>
		<updated>2026-11-27T14:59:38Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: /* Lab Sessions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Lab Sessions ==&lt;br /&gt;
&lt;br /&gt;
* Lab 1 - [[OS Lab 1 - Linux setup. Bash primer. C primer]]&lt;br /&gt;
* Lab 2 - [[OS Lab 2 - System calls. The initial stack]]&lt;br /&gt;
* Lab 3 - [[OS Lab 3 - Files. Memory mapping]]&lt;br /&gt;
* Lab 4 - [[OS Lab 4 - Processes. Signals]]&lt;br /&gt;
* Lab 5 - [[OS Lab 5 - Threads. Mutexes]]&lt;br /&gt;
* Lab 6 - [[OS Lab 6 - Users. Permissions]]&lt;br /&gt;
* Lab 7 - [[OS Lab 7 - Sockets. Datagrams]]&lt;br /&gt;
* Lab 8 - [[OS Lab 8 - Kernel modules. Character devices]]&lt;br /&gt;
&lt;br /&gt;
=== Old Lab Sessions (2025) ===&lt;br /&gt;
&lt;br /&gt;
* Lab 1 - [[OS Lab 1 - Installing Linux]]&lt;br /&gt;
* Lab 2 - [[OS Lab 2 - Linux Filesystems]]&lt;br /&gt;
* Lab 3 - [[OS Lab 3 - Processes and Jobs]]&lt;br /&gt;
* Lab 4 - [[OS Lab 4 - Users, Groups and Permissions]]&lt;br /&gt;
* Lab 5 - [[OS Lab 5 - Bash Scripting]]&lt;br /&gt;
* Lab 6 - [[OS Lab 6 - Inter Process Communication]]&lt;br /&gt;
* Lab 7 - [[OS Lab 7 - The Network Subsystem]]&lt;br /&gt;
* Lab 8 - [[OS Lab 8 - Transport and Security]]&lt;br /&gt;
* Lab 9 - [[OS Lab 9 - Application Protocols: DNS, SSH, HTTP(S)]]&lt;br /&gt;
* Lab 10 - [[OS Lab 10 - Containers and Docker]]&lt;br /&gt;
* Lab 11 - [[OS Lab 11 - Linux Kernel Modules]]&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:Skeleton_driver.zip&amp;diff=8456</id>
		<title>Fișier:Skeleton driver.zip</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:Skeleton_driver.zip&amp;diff=8456"/>
		<updated>2026-11-27T14:49:49Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_7_-_mychat.png&amp;diff=8454</id>
		<title>Fișier:OS Lab 7 - mychat.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_7_-_mychat.png&amp;diff=8454"/>
		<updated>2026-11-20T12:38:51Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_7_-_dgram.png&amp;diff=8453</id>
		<title>Fișier:OS Lab 7 - dgram.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_7_-_dgram.png&amp;diff=8453"/>
		<updated>2026-11-20T12:38:08Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=OS_Lab_7_-_Sockets._Datagrams&amp;diff=8452</id>
		<title>OS Lab 7 - Sockets. Datagrams</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=OS_Lab_7_-_Sockets._Datagrams&amp;diff=8452"/>
		<updated>2026-11-20T12:20:01Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: Pagină nouă: In the last lab, we looked at how the kernel decides what a task may do with a file. In this lab, processes will talk to each other through &amp;#039;&amp;#039;&amp;#039;soc...&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In [[OS_Lab_6_-_Users._Permissions|the last lab]], we looked at how the kernel decides what a task may do with a file. In this lab, processes will talk to each other through &amp;#039;&amp;#039;&amp;#039;sockets&amp;#039;&amp;#039;&amp;#039;. We will use local datagram sockets, which carry whole messages, each with the address of its sender. With them, a server needs a single socket and a single thread to serve many clients at once. We will also see how a program can wait for the keyboard and for a socket at the same time, still with one thread. As an application, we will write MyChat, a small chat server and client, in the style of IRC (ancestor of WhatsApp, Discord, etc.).&lt;br /&gt;
&lt;br /&gt;
== Learning objectives ==&lt;br /&gt;
&lt;br /&gt;
By the end of this lab you should be able to:&lt;br /&gt;
&lt;br /&gt;
# create a local socket and give it an address;&lt;br /&gt;
# send packets to an address with [https://man7.org/linux/man-pages/man2/sendto.2.html &amp;lt;code&amp;gt;sendto(2)&amp;lt;/code&amp;gt;], and receive them, with the address of their sender, with [https://man7.org/linux/man-pages/man2/recvfrom.2.html &amp;lt;code&amp;gt;recvfrom(2)&amp;lt;/code&amp;gt;];&lt;br /&gt;
# say what the flag &amp;lt;code&amp;gt;MSG_DONTWAIT&amp;lt;/code&amp;gt; changes;&lt;br /&gt;
# serve many clients from a single socket;&lt;br /&gt;
# receive packets while [https://man7.org/linux/man-pages/man3/readline.3.html &amp;lt;code&amp;gt;readline(3)&amp;lt;/code&amp;gt;] waits for the user.&lt;br /&gt;
&lt;br /&gt;
== Sockets ==&lt;br /&gt;
&lt;br /&gt;
A socket is one end of a communication. The process sees it as a file descriptor. Every socket has a &amp;#039;&amp;#039;&amp;#039;family&amp;#039;&amp;#039;&amp;#039;, which says where the other end is, and a &amp;#039;&amp;#039;&amp;#039;type&amp;#039;&amp;#039;&amp;#039;, which says how the data moves. In this lab we use a single combination:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;code&amp;gt;AF_UNIX&amp;lt;/code&amp;gt;: both ends are on the same machine. The address is a path, and the kernel copies the data from one process to the other, without touching the disk.&lt;br /&gt;
* &amp;lt;code&amp;gt;SOCK_DGRAM&amp;lt;/code&amp;gt;: the data travels in &amp;#039;&amp;#039;&amp;#039;datagrams&amp;#039;&amp;#039;&amp;#039;, or packets, which keep their boundaries. One [https://man7.org/linux/man-pages/man2/sendto.2.html &amp;lt;code&amp;gt;sendto(2)&amp;lt;/code&amp;gt;] makes one packet, and one [https://man7.org/linux/man-pages/man2/recvfrom.2.html &amp;lt;code&amp;gt;recvfrom(2)&amp;lt;/code&amp;gt;] takes one whole packet. There is no connection: every packet is sent to an address, and the receiver learns the address of the sender, so it can reply.&lt;br /&gt;
&lt;br /&gt;
Every socket which receives packets has a queue in the kernel. Packets from all senders wait there, in the order in which they arrived, until the owner of the socket takes them. With &amp;lt;code&amp;gt;AF_UNIX&amp;lt;/code&amp;gt;, no packet is lost.&lt;br /&gt;
&lt;br /&gt;
One side, the &amp;#039;&amp;#039;&amp;#039;server&amp;#039;&amp;#039;&amp;#039;, has an address which everybody knows. The others, the &amp;#039;&amp;#039;&amp;#039;clients&amp;#039;&amp;#039;&amp;#039;, send packets to that address. Both sides make the same calls:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Server !! Client&lt;br /&gt;
|-&lt;br /&gt;
| [https://man7.org/linux/man-pages/man2/socket.2.html &amp;lt;code&amp;gt;socket(2)&amp;lt;/code&amp;gt;]: a new socket || [https://man7.org/linux/man-pages/man2/socket.2.html &amp;lt;code&amp;gt;socket(2)&amp;lt;/code&amp;gt;]&lt;br /&gt;
|-&lt;br /&gt;
| [https://man7.org/linux/man-pages/man2/bind.2.html &amp;lt;code&amp;gt;bind(2)&amp;lt;/code&amp;gt;]: give it a known address || [https://man7.org/linux/man-pages/man2/bind.2.html &amp;lt;code&amp;gt;bind(2)&amp;lt;/code&amp;gt;]: give it any free address, so that the server can reply&lt;br /&gt;
|-&lt;br /&gt;
| [https://man7.org/linux/man-pages/man2/recvfrom.2.html &amp;lt;code&amp;gt;recvfrom(2)&amp;lt;/code&amp;gt;]: a packet, and who sent it || [https://man7.org/linux/man-pages/man2/sendto.2.html &amp;lt;code&amp;gt;sendto(2)&amp;lt;/code&amp;gt;]: a packet, to the address of the server&lt;br /&gt;
|-&lt;br /&gt;
| [https://man7.org/linux/man-pages/man2/sendto.2.html &amp;lt;code&amp;gt;sendto(2)&amp;lt;/code&amp;gt;]: the reply, to that sender || [https://man7.org/linux/man-pages/man2/recv.2.html &amp;lt;code&amp;gt;recv(2)&amp;lt;/code&amp;gt;]: the reply&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=== Creating a socket ===&lt;br /&gt;
&lt;br /&gt;
Both sides start in the same way: they create a socket, and fill in an address.&lt;br /&gt;
&lt;br /&gt;
==== socket(2) ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;sys/socket.h&amp;gt;&lt;br /&gt;
int socket(int domain, int type, int protocol);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Parameter !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;domain&amp;lt;/code&amp;gt; || The family: &amp;lt;code&amp;gt;AF_UNIX&amp;lt;/code&amp;gt; in this lab&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;type&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;SOCK_DGRAM&amp;lt;/code&amp;gt; in this lab. Others are &amp;lt;code&amp;gt;SOCK_STREAM&amp;lt;/code&amp;gt; (a connection which carries a stream of bytes, like a pipe) and &amp;lt;code&amp;gt;SOCK_SEQPACKET&amp;lt;/code&amp;gt; (a connection which carries packets)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;protocol&amp;lt;/code&amp;gt; || 0: the usual protocol for the family and type&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
It returns a new file descriptor, or -1 on error. The new socket has no address yet.&lt;br /&gt;
&lt;br /&gt;
==== Addresses ====&lt;br /&gt;
&lt;br /&gt;
An &amp;lt;code&amp;gt;AF_UNIX&amp;lt;/code&amp;gt; address is a path, kept in a &amp;lt;code&amp;gt;struct sockaddr_un&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;sys/un.h&amp;gt;&lt;br /&gt;
struct sockaddr_un {&lt;br /&gt;
    sa_family_t sun_family; // AF_UNIX&lt;br /&gt;
    char sun_path[108];     // The path of the socket file&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Every family has its own structure, but the socket functions take any of them, as a &amp;lt;code&amp;gt;struct sockaddr *&amp;lt;/code&amp;gt; and a size. We fill in our structure, and cast its address:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
struct sockaddr_un addr = { .sun_family = AF_UNIX, .sun_path = &amp;quot;upper.sock&amp;quot; };&lt;br /&gt;
bind(s, (struct sockaddr *)&amp;amp;addr, sizeof addr);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A relative path, like the one above, is relative to the current directory of the process.&lt;br /&gt;
&lt;br /&gt;
=== bind(2) ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;sys/socket.h&amp;gt;&lt;br /&gt;
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man2/bind.2.html &amp;lt;code&amp;gt;bind(2)&amp;lt;/code&amp;gt;] gives the socket an address, so that others can send packets to it.&lt;br /&gt;
&lt;br /&gt;
On the server, the address is a path. [https://man7.org/linux/man-pages/man2/bind.2.html &amp;lt;code&amp;gt;bind(2)&amp;lt;/code&amp;gt;] creates a &amp;#039;&amp;#039;&amp;#039;socket file&amp;#039;&amp;#039;&amp;#039; at that path, whose type &amp;lt;code&amp;gt;ls -l&amp;lt;/code&amp;gt; shows as &amp;lt;code&amp;gt;s&amp;lt;/code&amp;gt;. The file is only a name: no data is ever written to it. To send to the socket, a process needs write permission on this file.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; The socket file stays after the server ends, and [https://man7.org/linux/man-pages/man2/bind.2.html &amp;lt;code&amp;gt;bind(2)&amp;lt;/code&amp;gt;] fails with &amp;lt;code&amp;gt;EADDRINUSE&amp;lt;/code&amp;gt; if the path exists. That is why servers usually call [https://man7.org/linux/man-pages/man2/unlink.2.html &amp;lt;code&amp;gt;unlink(2)&amp;lt;/code&amp;gt;] on the path first.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A client does not care about its own address, but it needs one: without it, the server could not reply. If &amp;lt;code&amp;gt;addrlen&amp;lt;/code&amp;gt; covers only &amp;lt;code&amp;gt;sun_family&amp;lt;/code&amp;gt;, the kernel picks a free name, such as &amp;lt;code&amp;gt;@a50a0&amp;lt;/code&amp;gt;. This name is not a file, and it goes away when the socket is closed:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
struct sockaddr_un me = { .sun_family = AF_UNIX };&lt;br /&gt;
bind(s, (struct sockaddr *)&amp;amp;me, sizeof(sa_family_t)); // Any free name&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== sendto(2) and recvfrom(2) ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;sys/socket.h&amp;gt;&lt;br /&gt;
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,&lt;br /&gt;
               const struct sockaddr *dest_addr, socklen_t addrlen);&lt;br /&gt;
ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags,&lt;br /&gt;
                 struct sockaddr *src_addr, socklen_t *addrlen);&lt;br /&gt;
ssize_t recv(int sockfd, void *buf, size_t len, int flags);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* [https://man7.org/linux/man-pages/man2/sendto.2.html &amp;lt;code&amp;gt;sendto(2)&amp;lt;/code&amp;gt;] sends &amp;lt;code&amp;gt;len&amp;lt;/code&amp;gt; bytes as one packet, to the socket at &amp;lt;code&amp;gt;dest_addr&amp;lt;/code&amp;gt;.&lt;br /&gt;
* [https://man7.org/linux/man-pages/man2/recvfrom.2.html &amp;lt;code&amp;gt;recvfrom(2)&amp;lt;/code&amp;gt;] takes one packet from the queue, and returns its size. It blocks while the queue is empty. If the packet is larger than &amp;lt;code&amp;gt;len&amp;lt;/code&amp;gt;, the rest of it is lost.&lt;br /&gt;
* [https://man7.org/linux/man-pages/man2/recvfrom.2.html &amp;lt;code&amp;gt;recvfrom(2)&amp;lt;/code&amp;gt;] also tells us who sent the packet. Before the call, we set &amp;lt;code&amp;gt;*addrlen&amp;lt;/code&amp;gt; to the size allocated for the structure at &amp;lt;code&amp;gt;src_addr&amp;lt;/code&amp;gt;. The call writes the address of the sender into that structure, and sets &amp;lt;code&amp;gt;*addrlen&amp;lt;/code&amp;gt; to the real length of the address. To reply, we give the recieved address and length to [https://man7.org/linux/man-pages/man2/sendto.2.html &amp;lt;code&amp;gt;sendto(2)&amp;lt;/code&amp;gt;], as &amp;lt;code&amp;gt;dest_addr&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;addrlen&amp;lt;/code&amp;gt;.&lt;br /&gt;
* [https://man7.org/linux/man-pages/man2/recv.2.html &amp;lt;code&amp;gt;recv(2)&amp;lt;/code&amp;gt;] is [https://man7.org/linux/man-pages/man2/recvfrom.2.html &amp;lt;code&amp;gt;recvfrom(2)&amp;lt;/code&amp;gt;] without the address, for when we do not care who sent the packet.&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man2/sendto.2.html &amp;lt;code&amp;gt;sendto(2)&amp;lt;/code&amp;gt;] fails if nobody can receive at &amp;lt;code&amp;gt;dest_addr&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Error !! Meaning&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;ENOENT&amp;lt;/code&amp;gt; || There is no such socket file&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;ECONNREFUSED&amp;lt;/code&amp;gt; || The address exists, but no socket has it anymore: for example, the server has ended, and its socket file stayed&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;EACCES&amp;lt;/code&amp;gt; || We have no write permission on the socket file&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;flags&amp;lt;/code&amp;gt; adds additional options to a single call. We will need one flag:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Flag !! Meaning&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;MSG_DONTWAIT&amp;lt;/code&amp;gt; || Do not block. If there is no packet to receive, or no room to send one, fail at once with &amp;lt;code&amp;gt;EAGAIN&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; The queue of a socket is limited. If the receiver does not take its packets, its queue fills up, and [https://man7.org/linux/man-pages/man2/sendto.2.html &amp;lt;code&amp;gt;sendto(2)&amp;lt;/code&amp;gt;] blocks until there is room again. A server must not stop because one client does not read, so it sends with &amp;lt;code&amp;gt;MSG_DONTWAIT&amp;lt;/code&amp;gt;.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The following program is a server which sends back every packet in upper case, and a client which connects to it and sends it its command line arguments:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;ctype.h&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;sys/socket.h&amp;gt;&lt;br /&gt;
#include &amp;lt;sys/un.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define PATH &amp;quot;upper.sock&amp;quot;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static int server(void)&lt;br /&gt;
{&lt;br /&gt;
    int s = socket(AF_UNIX, SOCK_DGRAM, 0);&lt;br /&gt;
    if (s == -1) {&lt;br /&gt;
        print_error(&amp;quot;socket&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
    struct sockaddr_un addr = { .sun_family = AF_UNIX, .sun_path = PATH };&lt;br /&gt;
    unlink(PATH); // remove it in case it existed before&lt;br /&gt;
    if (bind(s, (struct sockaddr *)&amp;amp;addr, sizeof addr) == -1) {&lt;br /&gt;
        print_error(&amp;quot;bind&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
    for (;;) {&lt;br /&gt;
        char buf[256];&lt;br /&gt;
        struct sockaddr_un from;&lt;br /&gt;
        socklen_t len = sizeof from;&lt;br /&gt;
        ssize_t n = recvfrom(s, buf, sizeof buf, 0, (struct sockaddr *)&amp;amp;from, &amp;amp;len);&lt;br /&gt;
        if (n == -1) {&lt;br /&gt;
            print_error(&amp;quot;recvfrom&amp;quot;);&lt;br /&gt;
            continue;&lt;br /&gt;
        }&lt;br /&gt;
        for (ssize_t i = 0; i &amp;lt; n; i++) {&lt;br /&gt;
            buf[i] = toupper(buf[i]);&lt;br /&gt;
        }&lt;br /&gt;
        sendto(s, buf, n, 0, (struct sockaddr *)&amp;amp;from, len); // back to the sender&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static int client(int count, char *words[])&lt;br /&gt;
{&lt;br /&gt;
    int s = socket(AF_UNIX, SOCK_DGRAM, 0);&lt;br /&gt;
    if (s == -1) {&lt;br /&gt;
        print_error(&amp;quot;socket&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
    struct sockaddr_un me = { .sun_family = AF_UNIX };&lt;br /&gt;
    if (bind(s, (struct sockaddr *)&amp;amp;me, sizeof(sa_family_t)) == -1) { // any free name&lt;br /&gt;
        print_error(&amp;quot;bind&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
    struct sockaddr_un server = { .sun_family = AF_UNIX, .sun_path = PATH };&lt;br /&gt;
    for (int i = 0; i &amp;lt; count; i++) {&lt;br /&gt;
        if (sendto(s, words[i], strlen(words[i]), 0, (struct sockaddr *)&amp;amp;server, sizeof server) == -1) {&lt;br /&gt;
            print_error(&amp;quot;sendto&amp;quot;);&lt;br /&gt;
            return EXIT_FAILURE;&lt;br /&gt;
        }&lt;br /&gt;
        char buf[256];&lt;br /&gt;
        ssize_t n = recv(s, buf, sizeof buf, 0);&lt;br /&gt;
        if (n == -1) {&lt;br /&gt;
            print_error(&amp;quot;recv&amp;quot;);&lt;br /&gt;
            return EXIT_FAILURE;&lt;br /&gt;
        }&lt;br /&gt;
        char line[300];&lt;br /&gt;
        int len = snprintf(line, sizeof line, &amp;quot;%.*s\n&amp;quot;, (int)n, buf);&lt;br /&gt;
        write(STDOUT_FILENO, line, len);&lt;br /&gt;
        sleep(1);&lt;br /&gt;
    }&lt;br /&gt;
    close(s);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(int argc, char *argv[])&lt;br /&gt;
{&lt;br /&gt;
    if (argc == 2 &amp;amp;&amp;amp; strcmp(argv[1], &amp;quot;server&amp;quot;) == 0) {&lt;br /&gt;
        return server();&lt;br /&gt;
    }&lt;br /&gt;
    if (argc &amp;gt;= 2 &amp;amp;&amp;amp; strcmp(argv[1], &amp;quot;client&amp;quot;) == 0) {&lt;br /&gt;
        return client(argc - 2, argv + 2);&lt;br /&gt;
    }&lt;br /&gt;
    const char *usage = &amp;quot;usage: app server | client &amp;lt;word&amp;gt;...\n&amp;quot;;&lt;br /&gt;
    write(STDERR_FILENO, usage, strlen(usage));&lt;br /&gt;
    return EXIT_FAILURE;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Start the server in the background with &amp;lt;code&amp;gt;&amp;amp;&amp;lt;/code&amp;gt;, and run the client:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app server &amp;amp;&lt;br /&gt;
$ ls -l upper.sock&lt;br /&gt;
srwxr-xr-x 1 john john 0 Nov 17 12:03 upper.sock&lt;br /&gt;
$ ./build/debug/app client hello socket world&lt;br /&gt;
HELLO&lt;br /&gt;
SOCKET&lt;br /&gt;
WORLD&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now start two clients at the same time:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app client one two three &amp;amp; ./build/debug/app client four five six&lt;br /&gt;
ONE&lt;br /&gt;
FOUR&lt;br /&gt;
FIVE&lt;br /&gt;
TWO&lt;br /&gt;
THREE&lt;br /&gt;
SIX&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Both clients are served at the same time, by a single thread. The server has one socket for all its clients, and takes the packets in the order in which they arrive, whoever sent them. The order of the lines may differ from one run to the next.&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_7_-_dgram.png|center|thumb|500px|Two clients sent a packet to &amp;lt;code&amp;gt;upper.sock&amp;lt;/code&amp;gt;. [https://man7.org/linux/man-pages/man2/recvfrom.2.html &amp;lt;code&amp;gt;recvfrom(2)&amp;lt;/code&amp;gt;] returns the first one, with the address of its sender, and the server replies to that address.]]&lt;br /&gt;
&lt;br /&gt;
Stop the server with &amp;lt;code&amp;gt;kill %1&amp;lt;/code&amp;gt;, and run a client again. Its [https://man7.org/linux/man-pages/man2/sendto.2.html &amp;lt;code&amp;gt;sendto(2)&amp;lt;/code&amp;gt;] fails with &amp;lt;code&amp;gt;ECONNREFUSED&amp;lt;/code&amp;gt;: the socket file is still there, but no process has a socket with that address anymore.&lt;br /&gt;
&lt;br /&gt;
== Waiting in readline ==&lt;br /&gt;
&lt;br /&gt;
As part of this lab we will build a chat client.&lt;br /&gt;
&lt;br /&gt;
A chat client must wait for two things at once: the user typing a line, and packets from the server. But [https://man7.org/linux/man-pages/man3/readline.3.html &amp;lt;code&amp;gt;readline(3)&amp;lt;/code&amp;gt;] only returns when the user presses Enter. For this, readline can call a function of ours while it waits:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;readline/readline.h&amp;gt;&lt;br /&gt;
extern int (*rl_event_hook)(void); // Called while readline waits for a key&lt;br /&gt;
extern int rl_done;                // Set it to 1, and readline() returns&lt;br /&gt;
&lt;br /&gt;
int rl_on_new_line(void); // Tells readline that the cursor is on a new, empty line&lt;br /&gt;
void rl_redisplay(void);  // Draws the prompt and the line typed so far&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
While no key is pressed, [https://man7.org/linux/man-pages/man3/readline.3.html &amp;lt;code&amp;gt;readline(3)&amp;lt;/code&amp;gt;] calls &amp;lt;code&amp;gt;rl_event_hook&amp;lt;/code&amp;gt; about 10 times a second. The function must return quickly, so it must not block: it can receive with &amp;lt;code&amp;gt;MSG_DONTWAIT&amp;lt;/code&amp;gt;, and stop when [https://man7.org/linux/man-pages/man2/recv.2.html &amp;lt;code&amp;gt;recv(2)&amp;lt;/code&amp;gt;] fails with &amp;lt;code&amp;gt;EAGAIN&amp;lt;/code&amp;gt;. Its return value is not used.&lt;br /&gt;
&lt;br /&gt;
When the hook prints something, the cursor is after the prompt and the half-typed line. To print above them:&lt;br /&gt;
&lt;br /&gt;
# write &amp;lt;code&amp;gt;&amp;quot;\r&amp;quot;&amp;lt;/code&amp;gt;, which moves the cursor to the start of the line, and &amp;lt;code&amp;gt;&amp;quot;\033[K&amp;quot;&amp;lt;/code&amp;gt;, an escape sequence which asks the terminal to clear the rest of the line;&lt;br /&gt;
# write our text, ending with &amp;lt;code&amp;gt;&amp;quot;\n&amp;quot;&amp;lt;/code&amp;gt;;&lt;br /&gt;
# call &amp;lt;code&amp;gt;rl_on_new_line()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;rl_redisplay()&amp;lt;/code&amp;gt;, so that readline draws the prompt and the typed text again, on the next line.&lt;br /&gt;
&lt;br /&gt;
The following program prints the time every 3 seconds, while the user types:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;time.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#include &amp;lt;readline/history.h&amp;gt;&lt;br /&gt;
#include &amp;lt;readline/readline.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static time_t last;&lt;br /&gt;
&lt;br /&gt;
static void print(const char *msg)&lt;br /&gt;
{&lt;br /&gt;
    write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// Prints a line above the prompt, and draws the prompt again below it.&lt;br /&gt;
static void print_above(const char *msg)&lt;br /&gt;
{&lt;br /&gt;
    print(&amp;quot;\r\033[K&amp;quot;); // Back to the start of the line, and clear it&lt;br /&gt;
    print(msg);&lt;br /&gt;
    rl_on_new_line();&lt;br /&gt;
    rl_redisplay();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// readline() calls this about 10 times a second, while it waits for a key.&lt;br /&gt;
static int on_idle(void)&lt;br /&gt;
{&lt;br /&gt;
    time_t now = time(nullptr);&lt;br /&gt;
    if (now - last &amp;gt;= 3) {&lt;br /&gt;
        last = now;&lt;br /&gt;
        struct tm tm;&lt;br /&gt;
        localtime_r(&amp;amp;now, &amp;amp;tm);&lt;br /&gt;
        char msg[64];&lt;br /&gt;
        strftime(msg, sizeof msg, &amp;quot;* %H:%M:%S\n&amp;quot;, &amp;amp;tm);&lt;br /&gt;
        print_above(msg);&lt;br /&gt;
    }&lt;br /&gt;
    return 0;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    last = time(nullptr);&lt;br /&gt;
    rl_event_hook = on_idle;&lt;br /&gt;
&lt;br /&gt;
    char *line;&lt;br /&gt;
    while ((line = readline(&amp;quot;&amp;gt; &amp;quot;)) != nullptr) {&lt;br /&gt;
        char msg[512];&lt;br /&gt;
        snprintf(msg, sizeof msg, &amp;quot;you typed: %s\n&amp;quot;, line);&lt;br /&gt;
        print(msg);&lt;br /&gt;
        free(line);&lt;br /&gt;
    }&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
* 12:33:21&lt;br /&gt;
&amp;gt; hello wor&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Start typing, and wait: the time is printed above the prompt, and what you typed is drawn again below it, so you can go on typing.&lt;br /&gt;
&lt;br /&gt;
== Exercises ==&lt;br /&gt;
&lt;br /&gt;
Write the program in a new copy of the project template. As a reminder from [[OS_Lab_1_-_Linux_setup._Bash_primer._C_primer#getting-the-template|the first lab]]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
mkdir -p ~/oslab &amp;amp;&amp;amp; cd ~/oslab&lt;br /&gt;
curl -OL https://wiki.dcae.pub.ro/images/9/93/Os_lab_skeleton.zip&lt;br /&gt;
unzip -d lab07 Os_lab_skeleton.zip&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For this lab:&lt;br /&gt;
&lt;br /&gt;
* As in the last labs, do not use the standard I/O library for output: build the text with [https://man7.org/linux/man-pages/man3/snprintf.3.html &amp;lt;code&amp;gt;snprintf(3)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;] it. Use [https://man7.org/linux/man-pages/man3/readline.3.html &amp;lt;code&amp;gt;readline(3)&amp;lt;/code&amp;gt;] for input.&lt;br /&gt;
* Both the server and the client have a single thread: no [https://man7.org/linux/man-pages/man3/pthread_create.3.html &amp;lt;code&amp;gt;pthread_create(3)&amp;lt;/code&amp;gt;], no [https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;].&lt;br /&gt;
* The server has a single socket, and the only call in which it waits is [https://man7.org/linux/man-pages/man2/recvfrom.2.html &amp;lt;code&amp;gt;recvfrom(2)&amp;lt;/code&amp;gt;].&lt;br /&gt;
&lt;br /&gt;
=== MyChat ===&lt;br /&gt;
&lt;br /&gt;
In this exercise you will write MyChat, a chat room for the users of one machine. A single program is both the server and the client, depending on its argument. To try it, start the server in one terminal, and each client in a terminal of its own, all in the folder of the project:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
./build/debug/app --server&lt;br /&gt;
./build/debug/app --client&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The client reads lines from the user. A client which has just started is not in the chat yet: the user must first pick a name with &amp;lt;code&amp;gt;/join&amp;lt;/code&amp;gt;. The client should understand the following:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! The user types !! What the client should do&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;/join NAME&amp;lt;/code&amp;gt; || Join the chat as &amp;lt;code&amp;gt;NAME&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;/leave&amp;lt;/code&amp;gt; || Leave the chat. The client keeps running, and can &amp;lt;code&amp;gt;/join&amp;lt;/code&amp;gt; again&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;/dm NAME TEXT&amp;lt;/code&amp;gt; || Send &amp;lt;code&amp;gt;TEXT&amp;lt;/code&amp;gt; only to &amp;lt;code&amp;gt;NAME&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| Any other line || Send it to everyone in the chat&lt;br /&gt;
|-&lt;br /&gt;
| Ctrl+D || Leave the chat, if it joined, and end&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
To understand each other, the server and the clients must agree on what a packet contains: they need a &amp;#039;&amp;#039;&amp;#039;protocol&amp;#039;&amp;#039;&amp;#039;. A real chat protocol, such as IRC, has to work between different programs on different machines, and takes many pages to describe.&lt;br /&gt;
&lt;br /&gt;
The protocol we propose for this lab is a simple example: every packet is one &amp;lt;code&amp;gt;struct myc_packet&amp;lt;/code&amp;gt;, sent as it is in memory. The structure is defined as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// The socket file, in the current directory.&lt;br /&gt;
#define MYC_PATH &amp;quot;mychat.sock&amp;quot;&lt;br /&gt;
&lt;br /&gt;
#define MYC_NAME_MAX 32  // Including the final &amp;#039;\0&amp;#039;&lt;br /&gt;
#define MYC_TEXT_MAX 256 // Including the final &amp;#039;\0&amp;#039;&lt;br /&gt;
&lt;br /&gt;
enum myc_type {&lt;br /&gt;
    // Sent by the user&lt;br /&gt;
    MYC_U_JOIN = 1, // name: the nickname&lt;br /&gt;
    MYC_U_LEAVE,    // -&lt;br /&gt;
    MYC_U_MSG,      // text&lt;br /&gt;
    MYC_U_DM,       // name: to whom&lt;br /&gt;
                    // text&lt;br /&gt;
&lt;br /&gt;
    // Sent by the server&lt;br /&gt;
    MYC_S_JOIN,  // name: who joined&lt;br /&gt;
    MYC_S_LEAVE, // name: who left&lt;br /&gt;
                 // clean: true if they sent MYC_U_LEAVE, false if they errored out&lt;br /&gt;
    MYC_S_MSG,   // name: from whom&lt;br /&gt;
                 // dm: if it was sent only to us&lt;br /&gt;
                 // text&lt;br /&gt;
    MYC_S_ERR,   // text: what went wrong&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
// Every packet has the same size, whatever its type.&lt;br /&gt;
struct myc_packet {&lt;br /&gt;
    int type;&lt;br /&gt;
    bool clean;&lt;br /&gt;
    bool dm;&lt;br /&gt;
    char name[MYC_NAME_MAX];&lt;br /&gt;
    char text[MYC_TEXT_MAX];&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this protocol, every packet has space for all the fields, but each type uses only some of them:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Type !! Sent by !! Fields !! Meaning&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;MYC_U_JOIN&amp;lt;/code&amp;gt; || client || &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; || I want to join with this name&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;MYC_U_LEAVE&amp;lt;/code&amp;gt; || client || || I am leaving the chat&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;MYC_U_MSG&amp;lt;/code&amp;gt; || client || &amp;lt;code&amp;gt;text&amp;lt;/code&amp;gt; || Send this to everyone&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;MYC_U_DM&amp;lt;/code&amp;gt; || client || &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;text&amp;lt;/code&amp;gt; || Send this only to &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;MYC_S_JOIN&amp;lt;/code&amp;gt; || server || &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; joined. Sent to everyone in the chat, including the new user&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;MYC_S_LEAVE&amp;lt;/code&amp;gt; || server || &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;clean&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; left. &amp;lt;code&amp;gt;clean&amp;lt;/code&amp;gt; is true if they sent &amp;lt;code&amp;gt;MYC_U_LEAVE&amp;lt;/code&amp;gt;, and false if their client ended without it&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;MYC_S_MSG&amp;lt;/code&amp;gt; || server || &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;dm&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;text&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;name&amp;lt;/code&amp;gt; wrote &amp;lt;code&amp;gt;text&amp;lt;/code&amp;gt;. &amp;lt;code&amp;gt;dm&amp;lt;/code&amp;gt; is true if it was sent only to us. A message is not sent back to its author&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;MYC_S_ERR&amp;lt;/code&amp;gt; || server || &amp;lt;code&amp;gt;text&amp;lt;/code&amp;gt; || The last request failed, and why&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_7_-_mychat.png|center|thumb|500px|ana writes to everyone, and the server sends the message to everyone else in the chat. bob writes only to eve.]]&lt;br /&gt;
&lt;br /&gt;
With this protocol, a session with a server and two clients, in three terminals, could look like this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app --server&lt;br /&gt;
serving on mychat.sock&lt;br /&gt;
ana joined&lt;br /&gt;
john joined&lt;br /&gt;
ana left&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app --client&lt;br /&gt;
&amp;gt; hello?&lt;br /&gt;
! join first: /join &amp;lt;name&amp;gt;&lt;br /&gt;
&amp;gt; /join ana&lt;br /&gt;
* ana joined&lt;br /&gt;
* john joined&lt;br /&gt;
&amp;gt; hi john&lt;br /&gt;
&amp;lt;john&amp;gt; hey ana&lt;br /&gt;
[dm] &amp;lt;john&amp;gt; a secret&lt;br /&gt;
&amp;gt; /dm nobody hi&lt;br /&gt;
! no such user: nobody&lt;br /&gt;
&amp;gt; /leave&lt;br /&gt;
* ana left&lt;br /&gt;
&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app --client&lt;br /&gt;
&amp;gt; /join ana&lt;br /&gt;
! this name is taken&lt;br /&gt;
&amp;gt; /join john&lt;br /&gt;
* john joined&lt;br /&gt;
&amp;lt;ana&amp;gt; hi john&lt;br /&gt;
&amp;gt; hey ana&lt;br /&gt;
&amp;gt; /dm ana a secret&lt;br /&gt;
* ana left&lt;br /&gt;
&amp;gt; ^C&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
ana left with &amp;lt;code&amp;gt;/leave&amp;lt;/code&amp;gt; and then Ctrl+D, and john with Ctrl+C. The server does not know yet that john is gone: no packet told it. The server prints whatever you find useful.&lt;br /&gt;
&lt;br /&gt;
Build it in these steps:&lt;br /&gt;
&lt;br /&gt;
# &amp;#039;&amp;#039;&amp;#039;Talking.&amp;#039;&amp;#039;&amp;#039; In &amp;lt;code&amp;gt;main()&amp;lt;/code&amp;gt;, pick the server or the client from the argument. The server creates the socket, removes an old &amp;lt;code&amp;gt;mychat.sock&amp;lt;/code&amp;gt;, binds, and receives packets with [https://man7.org/linux/man-pages/man2/recvfrom.2.html &amp;lt;code&amp;gt;recvfrom(2)&amp;lt;/code&amp;gt;], in a loop. For each one, it prints its size. The client creates its socket, binds it to any free name, reads lines with [https://man7.org/linux/man-pages/man3/readline.3.html &amp;lt;code&amp;gt;readline(3)&amp;lt;/code&amp;gt;] until Ctrl+D, and sends each one to the server as a &amp;lt;code&amp;gt;MYC_U_MSG&amp;lt;/code&amp;gt;. Start a server and a few clients, and type some lines.&lt;br /&gt;
# &amp;#039;&amp;#039;&amp;#039;Joining.&amp;#039;&amp;#039;&amp;#039; The server keeps a table of users, for example an array of 64 elements, each with a name and an address. An empty name marks a free element. It answers &amp;lt;code&amp;gt;MYC_U_JOIN&amp;lt;/code&amp;gt; with &amp;lt;code&amp;gt;MYC_S_JOIN&amp;lt;/code&amp;gt; to everyone in the chat, or with &amp;lt;code&amp;gt;MYC_S_ERR&amp;lt;/code&amp;gt; if this address has already joined, if the name is empty, contains a space, or is taken, or if the table is full. It passes &amp;lt;code&amp;gt;MYC_U_MSG&amp;lt;/code&amp;gt; on as &amp;lt;code&amp;gt;MYC_S_MSG&amp;lt;/code&amp;gt;. Anything else from an address which has not joined gets a &amp;lt;code&amp;gt;MYC_S_ERR&amp;lt;/code&amp;gt;. The client sends &amp;lt;code&amp;gt;/join&amp;lt;/code&amp;gt; and plain lines, and sets &amp;lt;code&amp;gt;rl_event_hook&amp;lt;/code&amp;gt; to a function which receives every waiting packet and prints it, as in the session above.&lt;br /&gt;
# &amp;#039;&amp;#039;&amp;#039;Leaving.&amp;#039;&amp;#039;&amp;#039; Handle &amp;lt;code&amp;gt;/leave&amp;lt;/code&amp;gt;, and send &amp;lt;code&amp;gt;MYC_S_LEAVE&amp;lt;/code&amp;gt; with &amp;lt;code&amp;gt;clean&amp;lt;/code&amp;gt; set to everyone in the chat, including the user who left. On Ctrl+D, a client which is in the chat sends &amp;lt;code&amp;gt;MYC_U_LEAVE&amp;lt;/code&amp;gt; before it ends. To know whether it is in the chat, it can remember the name of its last &amp;lt;code&amp;gt;/join&amp;lt;/code&amp;gt;, and look for &amp;lt;code&amp;gt;MYC_S_JOIN&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;MYC_S_LEAVE&amp;lt;/code&amp;gt; packets with that name. A client which ends without leaving, for example with Ctrl+C, sends nothing. The server finds out the next time it sends that user a packet: [https://man7.org/linux/man-pages/man2/sendto.2.html &amp;lt;code&amp;gt;sendto(2)&amp;lt;/code&amp;gt;] fails with &amp;lt;code&amp;gt;ECONNREFUSED&amp;lt;/code&amp;gt;. Then it removes the user, and sends &amp;lt;code&amp;gt;MYC_S_LEAVE&amp;lt;/code&amp;gt; with &amp;lt;code&amp;gt;clean&amp;lt;/code&amp;gt; false to the others. In the same way, when the client&amp;#039;s [https://man7.org/linux/man-pages/man2/sendto.2.html &amp;lt;code&amp;gt;sendto(2)&amp;lt;/code&amp;gt;] fails with &amp;lt;code&amp;gt;ECONNREFUSED&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;ENOENT&amp;lt;/code&amp;gt;, the server is gone: print it, and end.&lt;br /&gt;
# &amp;#039;&amp;#039;&amp;#039;Direct messages.&amp;#039;&amp;#039;&amp;#039; Handle &amp;lt;code&amp;gt;/dm NAME TEXT&amp;lt;/code&amp;gt;. The server sends &amp;lt;code&amp;gt;MYC_S_MSG&amp;lt;/code&amp;gt;, with &amp;lt;code&amp;gt;dm&amp;lt;/code&amp;gt; set, only to &amp;lt;code&amp;gt;NAME&amp;lt;/code&amp;gt;, or &amp;lt;code&amp;gt;MYC_S_ERR&amp;lt;/code&amp;gt; if there is no such user.&lt;br /&gt;
&lt;br /&gt;
Some rules and hints:&lt;br /&gt;
&lt;br /&gt;
* The server sends with &amp;lt;code&amp;gt;MSG_DONTWAIT&amp;lt;/code&amp;gt;. A client which does not read must not stop the server. If a send fails with &amp;lt;code&amp;gt;EAGAIN&amp;lt;/code&amp;gt;, that client loses the packet.&lt;br /&gt;
* The client sends without flags, and receives, in the hook, with &amp;lt;code&amp;gt;MSG_DONTWAIT&amp;lt;/code&amp;gt;.&lt;br /&gt;
* Two addresses are the same if they have the same length, and [https://man7.org/linux/man-pages/man3/memcmp.3.html &amp;lt;code&amp;gt;memcmp(3)&amp;lt;/code&amp;gt;] finds the same bytes in that length. Keep the length which [https://man7.org/linux/man-pages/man2/recvfrom.2.html &amp;lt;code&amp;gt;recvfrom(2)&amp;lt;/code&amp;gt;] gave you next to each address.&lt;br /&gt;
* While the server sends a packet to everyone, one send can fail with &amp;lt;code&amp;gt;ECONNREFUSED&amp;lt;/code&amp;gt;. Removing that user sends &amp;lt;code&amp;gt;MYC_S_LEAVE&amp;lt;/code&amp;gt; to everyone, in the middle of the first loop. This only works if you take a user out of the table before you send &amp;lt;code&amp;gt;MYC_S_LEAVE&amp;lt;/code&amp;gt; about them.&lt;br /&gt;
* &amp;lt;code&amp;gt;struct myc_packet p = { .type = MYC_S_JOIN };&amp;lt;/code&amp;gt; sets every field which is not named to 0.&lt;br /&gt;
* &amp;lt;code&amp;gt;snprintf(p.name, sizeof p.name, &amp;quot;%s&amp;quot;, name)&amp;lt;/code&amp;gt; copies a string without overflowing. It returns the length of the whole string, so a result of &amp;lt;code&amp;gt;sizeof p.name&amp;lt;/code&amp;gt; or more means that the name did not fit.&lt;br /&gt;
* To split the line of &amp;lt;code&amp;gt;/dm&amp;lt;/code&amp;gt;, take the command and the name with [https://man7.org/linux/man-pages/man3/strtok_r.3.html &amp;lt;code&amp;gt;strtok_r(3)&amp;lt;/code&amp;gt;], and then the rest of the line with &amp;lt;code&amp;gt;strtok_r(nullptr, &amp;quot;&amp;quot;, &amp;amp;save)&amp;lt;/code&amp;gt;.&lt;br /&gt;
* Lines which do not come from the hook, such as an error for an unknown command, are printed with a plain [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;]: readline is not waiting at that moment.&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Operating_Systems&amp;diff=8451</id>
		<title>Operating Systems</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Operating_Systems&amp;diff=8451"/>
		<updated>2026-11-20T12:19:35Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: /* Lab Sessions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Lab Sessions ==&lt;br /&gt;
&lt;br /&gt;
* Lab 1 - [[OS Lab 1 - Linux setup. Bash primer. C primer]]&lt;br /&gt;
* Lab 2 - [[OS Lab 2 - System calls. The initial stack]]&lt;br /&gt;
* Lab 3 - [[OS Lab 3 - Files. Memory mapping]]&lt;br /&gt;
* Lab 4 - [[OS Lab 4 - Processes. Signals]]&lt;br /&gt;
* Lab 5 - [[OS Lab 5 - Threads. Mutexes]]&lt;br /&gt;
* Lab 6 - [[OS Lab 6 - Users. Permissions]]&lt;br /&gt;
* Lab 7 - [[OS Lab 7 - Sockets. Datagrams]]&lt;br /&gt;
&lt;br /&gt;
=== Old Lab Sessions (2025) ===&lt;br /&gt;
&lt;br /&gt;
* Lab 1 - [[OS Lab 1 - Installing Linux]]&lt;br /&gt;
* Lab 2 - [[OS Lab 2 - Linux Filesystems]]&lt;br /&gt;
* Lab 3 - [[OS Lab 3 - Processes and Jobs]]&lt;br /&gt;
* Lab 4 - [[OS Lab 4 - Users, Groups and Permissions]]&lt;br /&gt;
* Lab 5 - [[OS Lab 5 - Bash Scripting]]&lt;br /&gt;
* Lab 6 - [[OS Lab 6 - Inter Process Communication]]&lt;br /&gt;
* Lab 7 - [[OS Lab 7 - The Network Subsystem]]&lt;br /&gt;
* Lab 8 - [[OS Lab 8 - Transport and Security]]&lt;br /&gt;
* Lab 9 - [[OS Lab 9 - Application Protocols: DNS, SSH, HTTP(S)]]&lt;br /&gt;
* Lab 10 - [[OS Lab 10 - Containers and Docker]]&lt;br /&gt;
* Lab 11 - [[OS Lab 11 - Linux Kernel Modules]]&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_6_-_open_check.png&amp;diff=8450</id>
		<title>Fișier:OS Lab 6 - open check.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_6_-_open_check.png&amp;diff=8450"/>
		<updated>2026-11-13T14:15:58Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_6_-_mode_bits.png&amp;diff=8449</id>
		<title>Fișier:OS Lab 6 - mode bits.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_6_-_mode_bits.png&amp;diff=8449"/>
		<updated>2026-11-13T14:15:45Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=OS_Lab_6_-_Users._Permissions&amp;diff=8448</id>
		<title>OS Lab 6 - Users. Permissions</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=OS_Lab_6_-_Users._Permissions&amp;diff=8448"/>
		<updated>2026-11-13T14:14:22Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: Pagină nouă: In the last lab, we gave one process several threads. In this lab, we will look at how the kernel decides what a task is allowed to do. It compares...&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In [[OS_Lab_5_-_Threads._Mutexes|the last lab]], we gave one process several threads. In this lab, we will look at how the kernel decides what a task is allowed to do. It compares the numbers of the task, its &amp;#039;&amp;#039;&amp;#039;credentials&amp;#039;&amp;#039;&amp;#039;, with the owner, group and mode of the file. We will read these numbers, turn them into names, and change the permissions of our own files. As an application, we will write our own &amp;lt;code&amp;gt;ls -l&amp;lt;/code&amp;gt;, and a tool which finds and repairs dangerous permissions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Everything in this lab works as a normal user, and you will not need &amp;lt;code&amp;gt;sudo&amp;lt;/code&amp;gt;. Some of the commands below fail with a permission error on purpose.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Learning objectives ==&lt;br /&gt;
&lt;br /&gt;
By the end of this lab you should be able to:&lt;br /&gt;
&lt;br /&gt;
# read the user and group IDs of a task, and turn them into names;&lt;br /&gt;
# read the owner, group and mode of a file with [https://man7.org/linux/man-pages/man2/statx.2.html &amp;lt;code&amp;gt;statx(2)&amp;lt;/code&amp;gt;], and change the mode with [https://man7.org/linux/man-pages/man2/chmod.2.html &amp;lt;code&amp;gt;chmod(2)&amp;lt;/code&amp;gt;];&lt;br /&gt;
# say which class of permission bits applies when a task uses a file;&lt;br /&gt;
# explain what read, write and execute mean for files and for directories;&lt;br /&gt;
# recognize the set-user-ID, set-group-ID and sticky bits.&lt;br /&gt;
&lt;br /&gt;
== The credentials of a task ==&lt;br /&gt;
&lt;br /&gt;
Every task has a set of numbers, which the kernel uses for every permission check. First, it has three user IDs:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! ID !! Meaning&lt;br /&gt;
|-&lt;br /&gt;
| Real UID || Who started the task&lt;br /&gt;
|-&lt;br /&gt;
| Effective UID || Whose rights the task uses&lt;br /&gt;
|-&lt;br /&gt;
| Saved set-user-ID || One more value the task can go back to&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
It also has a real GID, an effective GID and a saved set-group-ID, which work in the same way, and a list of &amp;#039;&amp;#039;&amp;#039;supplementary groups&amp;#039;&amp;#039;&amp;#039;. All of them are copied to the child by [https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;], and kept across &amp;lt;code&amp;gt;exec&amp;lt;/code&amp;gt;, so everything started from a shell normally has the same credentials as the shell.&lt;br /&gt;
&lt;br /&gt;
=== getresuid(2) and getresgid(2) ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);&lt;br /&gt;
int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);&lt;br /&gt;
&lt;br /&gt;
uid_t getuid(void);  // The real UID&lt;br /&gt;
uid_t geteuid(void); // The effective UID&lt;br /&gt;
gid_t getgid(void);  // The real GID&lt;br /&gt;
gid_t getegid(void); // The effective GID&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man2/getresuid.2.html &amp;lt;code&amp;gt;getresuid(2)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/getresgid.2.html &amp;lt;code&amp;gt;getresgid(2)&amp;lt;/code&amp;gt;] store the three IDs at the given addresses. The four shorter functions return a single ID, and cannot fail.&lt;br /&gt;
&lt;br /&gt;
=== getgroups(2) ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
int getgroups(int size, gid_t list[]);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Parameter !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;size&amp;lt;/code&amp;gt; || How many elements &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; can hold&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; || Where to store the supplementary groups&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
It returns the number of groups, or -1 on error. If &amp;lt;code&amp;gt;size&amp;lt;/code&amp;gt; is 0, &amp;lt;code&amp;gt;list&amp;lt;/code&amp;gt; is not touched, and the call only returns the number of groups. This lets us first ask how many groups there are, and then declare an array of exactly that size: a &amp;#039;&amp;#039;&amp;#039;variable-length array&amp;#039;&amp;#039;&amp;#039; (VLA), whose size is only known at run time.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; A VLA must have at least one element. A task may have no supplementary groups at all, so the programs below make room for one more group than needed.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The following program prints all the credentials of the task running it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    uid_t ruid, euid, suid;&lt;br /&gt;
    gid_t rgid, egid, sgid;&lt;br /&gt;
&lt;br /&gt;
    getresuid(&amp;amp;ruid, &amp;amp;euid, &amp;amp;suid);&lt;br /&gt;
    getresgid(&amp;amp;rgid, &amp;amp;egid, &amp;amp;sgid);&lt;br /&gt;
&lt;br /&gt;
    int n = getgroups(0, nullptr);&lt;br /&gt;
    if (n == -1) {&lt;br /&gt;
        print_error(&amp;quot;getgroups&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
    gid_t groups[n + 1]; // + 1: a VLA cannot be empty&lt;br /&gt;
    n = getgroups(n, groups);&lt;br /&gt;
    if (n == -1) {&lt;br /&gt;
        print_error(&amp;quot;getgroups&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;UID: real %u, effective %u, saved %u\n&amp;quot;, ruid, euid, suid);&lt;br /&gt;
    write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;GID: real %u, effective %u, saved %u\n&amp;quot;, rgid, egid, sgid);&lt;br /&gt;
    write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
&lt;br /&gt;
    write(STDOUT_FILENO, &amp;quot;Groups:&amp;quot;, 7);&lt;br /&gt;
    for (int i = 0; i &amp;lt; n; i++) {&lt;br /&gt;
        snprintf(msg, sizeof msg, &amp;quot; %u&amp;quot;, groups[i]);&lt;br /&gt;
        write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
    }&lt;br /&gt;
    write(STDOUT_FILENO, &amp;quot;\n&amp;quot;, 1);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
UID: real 1000, effective 1000, saved 1000&lt;br /&gt;
GID: real 1000, effective 1000, saved 1000&lt;br /&gt;
Groups: 1000&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your numbers may be different. The three IDs are the same for almost every task, and only differ while special programs run, as we will see below.&lt;br /&gt;
&lt;br /&gt;
== From numbers to names ==&lt;br /&gt;
&lt;br /&gt;
The kernel does not know what users are called. Names are looked up in user space, by the C library:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;pwd.h&amp;gt;&lt;br /&gt;
struct passwd *getpwuid(uid_t uid);&lt;br /&gt;
&lt;br /&gt;
// In: &amp;lt;grp.h&amp;gt;&lt;br /&gt;
struct group *getgrgid(gid_t gid);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
They return a structure describing the user or group, or &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt; if nothing is known about that number. For example, a file can still belong to a user who has been deleted. A program must be ready to print the number instead.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;pwd.h&amp;gt; (simplified)&lt;br /&gt;
struct passwd {&lt;br /&gt;
    char *pw_name;  // The name of the user&lt;br /&gt;
    uid_t pw_uid;   // Its UID&lt;br /&gt;
    gid_t pw_gid;   // Its primary group&lt;br /&gt;
    char *pw_dir;   // Its home directory&lt;br /&gt;
    char *pw_shell; // Its shell&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
// In: &amp;lt;grp.h&amp;gt; (simplified)&lt;br /&gt;
struct group {&lt;br /&gt;
    char *gr_name; // The name of the group&lt;br /&gt;
    gid_t gr_gid;  // Its GID&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; The returned structure is kept in a static buffer, which the next call to the same function overwrites. If you need a name after another lookup, copy it first.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The following program prints the same line as the &amp;lt;code&amp;gt;id&amp;lt;/code&amp;gt; command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;grp.h&amp;gt;&lt;br /&gt;
#include &amp;lt;pwd.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static void print_group(gid_t gid)&lt;br /&gt;
{&lt;br /&gt;
    const struct group *gr = getgrgid(gid);&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%u(%s)&amp;quot;, gid, gr != nullptr ? gr-&amp;gt;gr_name : &amp;quot;?&amp;quot;);&lt;br /&gt;
    write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    int n = getgroups(0, nullptr);&lt;br /&gt;
    if (n == -1) {&lt;br /&gt;
        print_error(&amp;quot;getgroups&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
    gid_t groups[n + 1]; // + 1: a VLA cannot be empty&lt;br /&gt;
    n = getgroups(n, groups);&lt;br /&gt;
    if (n == -1) {&lt;br /&gt;
        print_error(&amp;quot;getgroups&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    uid_t uid = getuid();&lt;br /&gt;
    const struct passwd *pw = getpwuid(uid);&lt;br /&gt;
&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;uid=%u(%s) gid=&amp;quot;, uid, pw != nullptr ? pw-&amp;gt;pw_name : &amp;quot;?&amp;quot;);&lt;br /&gt;
    write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
    print_group(getgid());&lt;br /&gt;
&lt;br /&gt;
    write(STDOUT_FILENO, &amp;quot; groups=&amp;quot;, 8);&lt;br /&gt;
    for (int i = 0; i &amp;lt; n; i++) {&lt;br /&gt;
        if (i &amp;gt; 0) {&lt;br /&gt;
            write(STDOUT_FILENO, &amp;quot;,&amp;quot;, 1);&lt;br /&gt;
        }&lt;br /&gt;
        print_group(groups[i]);&lt;br /&gt;
    }&lt;br /&gt;
    write(STDOUT_FILENO, &amp;quot;\n&amp;quot;, 1);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
uid=1000(john) gid=1000(john) groups=1000(john)&lt;br /&gt;
$ id&lt;br /&gt;
uid=1000(john) gid=1000(john) groups=1000(john)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== The permissions of a file ==&lt;br /&gt;
&lt;br /&gt;
Every file has an &amp;#039;&amp;#039;&amp;#039;owner&amp;#039;&amp;#039;&amp;#039; (a UID), a &amp;#039;&amp;#039;&amp;#039;group&amp;#039;&amp;#039;&amp;#039; (a GID) and a &amp;#039;&amp;#039;&amp;#039;mode&amp;#039;&amp;#039;&amp;#039; of 16 bits. The mode holds the type of the file, 3 special bits, and 9 permission bits: read, write and execute, for each of the three classes.&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_6_-_mode_bits.png|center|thumb|500px|The owner, group and mode of a file. The mode is usually written in octal: each digit is one group of 3 bits. The file here is &amp;lt;code&amp;gt;rwxr-x---&amp;lt;/code&amp;gt;, or 0750.]]&lt;br /&gt;
&lt;br /&gt;
When a task uses a file, the kernel picks &amp;#039;&amp;#039;&amp;#039;exactly one&amp;#039;&amp;#039;&amp;#039; class, and only checks that one:&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_6_-_open_check.png|center|thumb|500px|The first match decides. An owner with &amp;lt;code&amp;gt;---&amp;lt;/code&amp;gt; cannot read the file, even if the others can.]]&lt;br /&gt;
&lt;br /&gt;
The checks use the effective IDs. A task with effective UID 0, the superuser, skips them. In addition, every directory on the path needs the execute permission.&lt;br /&gt;
&lt;br /&gt;
The mode bits have names, defined in &amp;lt;code&amp;gt;&amp;amp;lt;sys/stat.h&amp;amp;gt;&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Class !! Read !! Write !! Execute&lt;br /&gt;
|-&lt;br /&gt;
| Owner || &amp;lt;code&amp;gt;S_IRUSR&amp;lt;/code&amp;gt; (0400) || &amp;lt;code&amp;gt;S_IWUSR&amp;lt;/code&amp;gt; (0200) || &amp;lt;code&amp;gt;S_IXUSR&amp;lt;/code&amp;gt; (0100)&lt;br /&gt;
|-&lt;br /&gt;
| Group || &amp;lt;code&amp;gt;S_IRGRP&amp;lt;/code&amp;gt; (0040) || &amp;lt;code&amp;gt;S_IWGRP&amp;lt;/code&amp;gt; (0020) || &amp;lt;code&amp;gt;S_IXGRP&amp;lt;/code&amp;gt; (0010)&lt;br /&gt;
|-&lt;br /&gt;
| Others || &amp;lt;code&amp;gt;S_IROTH&amp;lt;/code&amp;gt; (0004) || &amp;lt;code&amp;gt;S_IWOTH&amp;lt;/code&amp;gt; (0002) || &amp;lt;code&amp;gt;S_IXOTH&amp;lt;/code&amp;gt; (0001)&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
The three special bits are:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Bit !! Value !! Shown as !! Meaning&lt;br /&gt;
|-&lt;br /&gt;
| Set-user-ID, &amp;lt;code&amp;gt;S_ISUID&amp;lt;/code&amp;gt; || 04000 || &amp;lt;code&amp;gt;s&amp;lt;/code&amp;gt; instead of the owner&amp;#039;s &amp;lt;code&amp;gt;x&amp;lt;/code&amp;gt; || The program runs with the effective UID of the owner of the file&lt;br /&gt;
|-&lt;br /&gt;
| Set-group-ID, &amp;lt;code&amp;gt;S_ISGID&amp;lt;/code&amp;gt; || 02000 || &amp;lt;code&amp;gt;s&amp;lt;/code&amp;gt; instead of the group&amp;#039;s &amp;lt;code&amp;gt;x&amp;lt;/code&amp;gt; || The program runs with the effective GID of the group of the file. On a directory: new files get the group of the directory&lt;br /&gt;
|-&lt;br /&gt;
| Sticky, &amp;lt;code&amp;gt;S_ISVTX&amp;lt;/code&amp;gt; || 01000 || &amp;lt;code&amp;gt;t&amp;lt;/code&amp;gt; instead of the others&amp;#039; &amp;lt;code&amp;gt;x&amp;lt;/code&amp;gt; || On a directory: an entry can only be deleted or renamed by its owner, the owner of the directory, or root&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
If the &amp;lt;code&amp;gt;x&amp;lt;/code&amp;gt; underneath is not set, the letter is uppercase: &amp;lt;code&amp;gt;S&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;T&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== statx(2) ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;fcntl.h&amp;gt; and &amp;lt;sys/stat.h&amp;gt;&lt;br /&gt;
int statx(int dirfd, const char *pathname, int flags, unsigned int mask, struct statx *statxbuf);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Parameter !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;dirfd&amp;lt;/code&amp;gt; || A directory to which a relative &amp;lt;code&amp;gt;pathname&amp;lt;/code&amp;gt; is relative, or &amp;lt;code&amp;gt;AT_FDCWD&amp;lt;/code&amp;gt; for the current directory&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;pathname&amp;lt;/code&amp;gt; || The file&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;flags&amp;lt;/code&amp;gt; || 0 to follow a symbolic link and describe its target, or &amp;lt;code&amp;gt;AT_SYMLINK_NOFOLLOW&amp;lt;/code&amp;gt; to describe the link itself&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;mask&amp;lt;/code&amp;gt; || Which fields we want. &amp;lt;code&amp;gt;STATX_BASIC_STATS&amp;lt;/code&amp;gt; asks for the usual ones&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;statxbuf&amp;lt;/code&amp;gt; || Where to store the result&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;sys/stat.h&amp;gt; (simplified)&lt;br /&gt;
struct statx {&lt;br /&gt;
    uint16_t stx_mode;  // The type, special bits and permission bits&lt;br /&gt;
    uint32_t stx_uid;   // The owner&lt;br /&gt;
    uint32_t stx_gid;   // The group&lt;br /&gt;
    uint32_t stx_nlink; // The number of hard links&lt;br /&gt;
    uint64_t stx_size;  // The size in bytes&lt;br /&gt;
    struct statx_timestamp stx_atime; // Last access&lt;br /&gt;
    struct statx_timestamp stx_mtime; // Last modification&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
struct statx_timestamp {&lt;br /&gt;
   int64_t tv_sec;    /* Seconds since the Epoch (00:00 1st Jan 1970 UTC) */&lt;br /&gt;
   uint32_t tv_nsec;  /* Nanoseconds since tv_sec */&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The type is tested with macros: &amp;lt;code&amp;gt;S_ISREG(mode)&amp;lt;/code&amp;gt; (regular file), &amp;lt;code&amp;gt;S_ISDIR&amp;lt;/code&amp;gt; (directory), &amp;lt;code&amp;gt;S_ISLNK&amp;lt;/code&amp;gt; (symbolic link), &amp;lt;code&amp;gt;S_ISCHR&amp;lt;/code&amp;gt; (character device), &amp;lt;code&amp;gt;S_ISBLK&amp;lt;/code&amp;gt; (block device), &amp;lt;code&amp;gt;S_ISFIFO&amp;lt;/code&amp;gt; (pipe) and &amp;lt;code&amp;gt;S_ISSOCK&amp;lt;/code&amp;gt; (socket).&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man2/statx.2.html &amp;lt;code&amp;gt;statx(2)&amp;lt;/code&amp;gt;] only needs the execute permission on the directories of the path, and no permission on the file itself. The following program describes any file we can reach:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;fcntl.h&amp;gt;&lt;br /&gt;
#include &amp;lt;grp.h&amp;gt;&lt;br /&gt;
#include &amp;lt;pwd.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;sys/stat.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(int argc, char *argv[])&lt;br /&gt;
{&lt;br /&gt;
    if (argc != 2) {&lt;br /&gt;
        const char *usage = &amp;quot;usage: app &amp;lt;path&amp;gt;\n&amp;quot;;&lt;br /&gt;
        write(STDERR_FILENO, usage, strlen(usage));&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    struct statx st;&lt;br /&gt;
    if (statx(AT_FDCWD, argv[1], 0, STATX_BASIC_STATS, &amp;amp;st) == -1) {&lt;br /&gt;
        print_error(argv[1]);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    const char *type = &amp;quot;other&amp;quot;;&lt;br /&gt;
    if (S_ISREG(st.stx_mode)) {&lt;br /&gt;
        type = &amp;quot;regular file&amp;quot;;&lt;br /&gt;
    } else if (S_ISDIR(st.stx_mode)) {&lt;br /&gt;
        type = &amp;quot;directory&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    const struct passwd *pw = getpwuid(st.stx_uid);&lt;br /&gt;
    const struct group *gr = getgrgid(st.stx_gid);&lt;br /&gt;
&lt;br /&gt;
    char msg[512];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s, owner %u (%s), group %u (%s), mode %04o\n&amp;quot;, type,&lt;br /&gt;
             st.stx_uid, pw != nullptr ? pw-&amp;gt;pw_name : &amp;quot;?&amp;quot;,&lt;br /&gt;
             st.stx_gid, gr != nullptr ? gr-&amp;gt;gr_name : &amp;quot;?&amp;quot;,&lt;br /&gt;
             st.stx_mode &amp;amp; 07777);&lt;br /&gt;
    write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app /etc/shadow&lt;br /&gt;
regular file, owner 0 (root), group 42 (shadow), mode 0640&lt;br /&gt;
$ ./build/debug/app /tmp&lt;br /&gt;
directory, owner 0 (root), group 0 (root), mode 1777&lt;br /&gt;
$ ./build/debug/app /usr/bin/passwd&lt;br /&gt;
regular file, owner 0 (root), group 0 (root), mode 4755&lt;br /&gt;
$ ./build/debug/app /nope&lt;br /&gt;
/nope: No such file or directory&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;stx_mode&amp;lt;/code&amp;gt; also holds the type of the file, and &amp;lt;code&amp;gt;&amp;amp; 07777&amp;lt;/code&amp;gt; keeps only the special and permission bits. In the examples above:&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;code&amp;gt;/etc/shadow&amp;lt;/code&amp;gt; holds the password hashes, and the others class has no permissions at all.&lt;br /&gt;
* &amp;lt;code&amp;gt;/tmp&amp;lt;/code&amp;gt; can be written by anyone, but the sticky bit (the leading 1) stops users from deleting each other&amp;#039;s files.&lt;br /&gt;
* &amp;lt;code&amp;gt;/usr/bin/passwd&amp;lt;/code&amp;gt; is set-user-ID (the leading 4) and belongs to root. This is how a normal user can change their own password: the program runs with effective UID 0, and it knows who started it from the real UID.&lt;br /&gt;
&lt;br /&gt;
=== chmod(2) ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;sys/stat.h&amp;gt;&lt;br /&gt;
int chmod(const char *pathname, mode_t mode);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man2/chmod.2.html &amp;lt;code&amp;gt;chmod(2)&amp;lt;/code&amp;gt;] replaces the permission and special bits of a file. Only the owner of the file, or root, may call it. The permission bits themselves do not matter: an owner with &amp;lt;code&amp;gt;---&amp;lt;/code&amp;gt; can still give itself &amp;lt;code&amp;gt;rw-&amp;lt;/code&amp;gt;. Since it replaces all the bits, changing just some of them means starting from the old mode, which [https://man7.org/linux/man-pages/man2/statx.2.html &amp;lt;code&amp;gt;statx(2)&amp;lt;/code&amp;gt;] gives us. For example, to remove the write permission of the group and of the others:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
mode_t new_mode = (st.stx_mode &amp;amp; 07777) &amp;amp; ~(S_IWGRP | S_IWOTH);&lt;br /&gt;
chmod(path, new_mode);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; [https://man7.org/linux/man-pages/man2/chmod.2.html &amp;lt;code&amp;gt;chmod(2)&amp;lt;/code&amp;gt;] follows symbolic links: called on a link, it changes the file the link points to.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Trying it out ===&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;chmod&amp;lt;/code&amp;gt; command takes the same octal numbers. Try the following on your own files:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ echo hello &amp;gt; notes.txt&lt;br /&gt;
$ chmod 044 notes.txt&lt;br /&gt;
$ cat notes.txt&lt;br /&gt;
cat: notes.txt: Permission denied&lt;br /&gt;
$ chmod 644 notes.txt&lt;br /&gt;
$ cat notes.txt&lt;br /&gt;
hello&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
With mode 044, everybody else can read the file, but its owner cannot: only the owner class is checked. On a directory, the three permissions mean something else:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Permission !! For a directory&lt;br /&gt;
|-&lt;br /&gt;
| Read || List the names&lt;br /&gt;
|-&lt;br /&gt;
| Write || Create, delete and rename entries&lt;br /&gt;
|-&lt;br /&gt;
| Execute || Go through it, to use the names inside&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ mkdir box&lt;br /&gt;
$ echo hi &amp;gt; box/a.txt&lt;br /&gt;
$ chmod 600 box&lt;br /&gt;
$ ls box&lt;br /&gt;
a.txt&lt;br /&gt;
$ cat box/a.txt&lt;br /&gt;
cat: box/a.txt: Permission denied&lt;br /&gt;
$ chmod 300 box&lt;br /&gt;
$ ls box&lt;br /&gt;
ls: cannot open directory &amp;#039;box&amp;#039;: Permission denied&lt;br /&gt;
$ cat box/a.txt&lt;br /&gt;
hi&lt;br /&gt;
$ chmod 500 box&lt;br /&gt;
$ touch box/b.txt&lt;br /&gt;
touch: cannot touch &amp;#039;box/b.txt&amp;#039;: Permission denied&lt;br /&gt;
$ rm box/a.txt&lt;br /&gt;
rm: cannot remove &amp;#039;box/a.txt&amp;#039;: Permission denied&lt;br /&gt;
$ chmod 700 box&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Without execute, we can see the names, but we cannot use them. Without read, we can use a name, if we already know it. Deleting a file needs write permission on its &amp;#039;&amp;#039;&amp;#039;directory&amp;#039;&amp;#039;&amp;#039;. The permissions of the file itself are not checked. Depending on its version, &amp;lt;code&amp;gt;ls box&amp;lt;/code&amp;gt; may also complain about each name in the first case.&lt;br /&gt;
&lt;br /&gt;
== Exercises ==&lt;br /&gt;
&lt;br /&gt;
Write each program in its own copy of the project template. As a reminder from [[OS_Lab_1_-_Linux_setup._Bash_primer._C_primer#getting-the-template|the first lab]]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
mkdir -p ~/oslab/lab06 &amp;amp;&amp;amp; cd ~/oslab/lab06&lt;br /&gt;
curl -OL https://wiki.dcae.pub.ro/images/9/93/Os_lab_skeleton.zip&lt;br /&gt;
unzip -d ls Os_lab_skeleton.zip&lt;br /&gt;
unzip -d doctor Os_lab_skeleton.zip&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For this lab:&lt;br /&gt;
&lt;br /&gt;
* As in the last labs, do not use the standard I/O library for output: build the text with [https://man7.org/linux/man-pages/man3/snprintf.3.html &amp;lt;code&amp;gt;snprintf(3)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;] it.&lt;br /&gt;
* Do not run other programs: make the system calls yourself.&lt;br /&gt;
* If a file cannot be reached, print the error on standard error, and continue with the next one.&lt;br /&gt;
&lt;br /&gt;
=== A. Your own ls -l ===&lt;br /&gt;
&lt;br /&gt;
Write a command which lists a directory like &amp;lt;code&amp;gt;ls -la&amp;lt;/code&amp;gt;. It takes the directory as an optional parameter, and uses the current directory if there is none. Build it in these steps:&lt;br /&gt;
&lt;br /&gt;
# &amp;#039;&amp;#039;&amp;#039;Names and sizes.&amp;#039;&amp;#039;&amp;#039; Read the directory with [https://man7.org/linux/man-pages/man3/readdir.3.html &amp;lt;code&amp;gt;readdir(3)&amp;lt;/code&amp;gt;], as in [[OS_Lab_3_-_Files._Memory_mapping#readdir()|Lab 3]], and call [https://man7.org/linux/man-pages/man2/statx.2.html &amp;lt;code&amp;gt;statx(2)&amp;lt;/code&amp;gt;] for each entry. Print the size and the name.&lt;br /&gt;
# &amp;#039;&amp;#039;&amp;#039;The mode.&amp;#039;&amp;#039;&amp;#039; Print the mode as 10 characters: the type (&amp;lt;code&amp;gt;-&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;d&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;l&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;c&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;b&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;p&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;s&amp;lt;/code&amp;gt;), then the 9 permission bits. Write a function which fills in a string.&lt;br /&gt;
# &amp;#039;&amp;#039;&amp;#039;The other columns.&amp;#039;&amp;#039;&amp;#039; Add the number of hard links, the owner, the group and the date. If a number has no name, print the number. For a symbolic link, also print &amp;lt;code&amp;gt;-&amp;gt; target&amp;lt;/code&amp;gt;.&lt;br /&gt;
# &amp;#039;&amp;#039;&amp;#039;The special bits.&amp;#039;&amp;#039;&amp;#039; Show &amp;lt;code&amp;gt;s&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;S&amp;lt;/code&amp;gt; for the set-user-ID and set-group-ID bits, as described [[#The permissions of a file|above]]. You can ignore the sticky bit.&lt;br /&gt;
# &amp;#039;&amp;#039;&amp;#039;What can I do?&amp;#039;&amp;#039;&amp;#039; Add a first column with your own rights over the file, such as &amp;lt;code&amp;gt;r-x&amp;lt;/code&amp;gt;, by picking the class as the kernel does: compare with your effective UID, then with your effective GID and supplementary groups, or else use the others class.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
rwx drwxr-xr-x   1 john     john           44 2026-11-09 15:54 .&lt;br /&gt;
rwx drwxr-xr-x   1 john     john           50 2026-11-09 15:54 ..&lt;br /&gt;
rw- -rw-r-S---   1 john     john            6 2026-11-09 15:54 notes.txt&lt;br /&gt;
rwx lrwxrwxrwx   1 john     john            9 2026-11-09 15:54 link -&amp;gt; notes.txt&lt;br /&gt;
rwx drwxr-x--x   1 john     john            0 2026-11-09 15:54 sub&lt;br /&gt;
rwx -rwsr-xr-x   1 john     john        68064 2026-11-09 15:54 tool&lt;br /&gt;
$ ./build/debug/app /etc | grep shadow&lt;br /&gt;
--- -rw-r-----   1 root     shadow        840 2026-11-09 15:54 shadow&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The names do not have to be sorted. The widths of the columns are up to you.&lt;br /&gt;
&lt;br /&gt;
* You do not need to build a path for each entry: give [https://man7.org/linux/man-pages/man2/statx.2.html &amp;lt;code&amp;gt;statx(2)&amp;lt;/code&amp;gt;] the directory through &amp;lt;code&amp;gt;dirfd(dir)&amp;lt;/code&amp;gt;, which returns the file descriptor of an open &amp;lt;code&amp;gt;DIR&amp;lt;/code&amp;gt;, and the name of the entry as &amp;lt;code&amp;gt;pathname&amp;lt;/code&amp;gt;.&lt;br /&gt;
* Use &amp;lt;code&amp;gt;AT_SYMLINK_NOFOLLOW&amp;lt;/code&amp;gt;, so that links are listed as links.&lt;br /&gt;
* &amp;lt;code&amp;gt;readlinkat(dirfd(dir), name, buffer, size)&amp;lt;/code&amp;gt; reads the target of a link. It returns the length, and does not add a &amp;lt;code&amp;gt;&amp;#039;\0&amp;#039;&amp;lt;/code&amp;gt;.&lt;br /&gt;
* For the date: &amp;lt;code&amp;gt;time_t when = st.stx_mtime.tv_sec;&amp;lt;/code&amp;gt;, then &amp;lt;code&amp;gt;localtime_r(&amp;amp;when, &amp;amp;tm)&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;strftime(date, sizeof date, &amp;quot;%Y-%m-%d %H:%M&amp;quot;, &amp;amp;tm)&amp;lt;/code&amp;gt;, from &amp;lt;code&amp;gt;&amp;amp;lt;time.h&amp;amp;gt;&amp;lt;/code&amp;gt;.&lt;br /&gt;
* [https://man7.org/linux/man-pages/man3/getpwuid.3.html &amp;lt;code&amp;gt;getpwuid(3)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man3/getgrgid.3.html &amp;lt;code&amp;gt;getgrgid(3)&amp;lt;/code&amp;gt;] use different buffers, but copy the names anyway if you want to look up anything else before printing them.&lt;br /&gt;
&lt;br /&gt;
After step 4, compare your output with the real &amp;lt;code&amp;gt;ls&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== B. Permission doctor ===&lt;br /&gt;
&lt;br /&gt;
Write a command which walks a directory and everything below it, and reports dangerous permissions. With &amp;lt;code&amp;gt;--fix&amp;lt;/code&amp;gt;, it also repairs them.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
./build/debug/app [--fix] &amp;lt;directory&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It checks only regular files and directories, including the starting directory, against three rules:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Applies to !! Problem !! Repair&lt;br /&gt;
|-&lt;br /&gt;
| Regular files and directories || Writable by others, except for directories with the sticky bit || Remove the write permission of the others&lt;br /&gt;
|-&lt;br /&gt;
| Regular files whose name ends in &amp;lt;code&amp;gt;.key&amp;lt;/code&amp;gt; || Any permission for the group or the others || Remove all of them&lt;br /&gt;
|-&lt;br /&gt;
| Regular files || Set-user-ID or set-group-ID || Remove those bits&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Create a test directory inside the project:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
mkdir -p demo/sub demo/locked&lt;br /&gt;
echo hello &amp;gt; demo/notes.txt&lt;br /&gt;
echo hello &amp;gt; demo/shared.txt &amp;amp;&amp;amp; chmod 666 demo/shared.txt&lt;br /&gt;
echo secret &amp;gt; demo/sub/server.key &amp;amp;&amp;amp; chmod 644 demo/sub/server.key&lt;br /&gt;
cp /bin/true demo/sub/tool &amp;amp;&amp;amp; chmod 4755 demo/sub/tool&lt;br /&gt;
chmod 777 demo/sub&lt;br /&gt;
ln -s /etc/shadow demo/link&lt;br /&gt;
chmod 000 demo/locked&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app demo&lt;br /&gt;
demo/sub: writable by others (0777)&lt;br /&gt;
demo/sub/server.key: private key open to group or others (0644)&lt;br /&gt;
demo/sub/tool: runs with the rights of its owner or group (4755)&lt;br /&gt;
demo/locked: Permission denied&lt;br /&gt;
demo/shared.txt: writable by others (0666)&lt;br /&gt;
problems found: 4, fixed: 0&lt;br /&gt;
$ ./build/debug/app --fix demo&lt;br /&gt;
demo/sub: writable by others (0777)&lt;br /&gt;
  fixed: 0777 -&amp;gt; 0775&lt;br /&gt;
demo/sub/server.key: private key open to group or others (0644)&lt;br /&gt;
  fixed: 0644 -&amp;gt; 0600&lt;br /&gt;
demo/sub/tool: runs with the rights of its owner or group (4755)&lt;br /&gt;
  fixed: 4755 -&amp;gt; 0755&lt;br /&gt;
demo/locked: Permission denied&lt;br /&gt;
demo/shared.txt: writable by others (0666)&lt;br /&gt;
  fixed: 0666 -&amp;gt; 0664&lt;br /&gt;
problems found: 4, fixed: 4&lt;br /&gt;
$ ./build/debug/app demo&lt;br /&gt;
demo/locked: Permission denied&lt;br /&gt;
problems found: 0, fixed: 0&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The lines may come in a different order. The exit status is 0 if every problem found was fixed, and 1 otherwise.&lt;br /&gt;
&lt;br /&gt;
* Write a recursive function which takes the path of a directory. Build the path of each entry with [https://man7.org/linux/man-pages/man3/snprintf.3.html &amp;lt;code&amp;gt;snprintf(3)&amp;lt;/code&amp;gt;], into a buffer of &amp;lt;code&amp;gt;PATH_MAX&amp;lt;/code&amp;gt; bytes (from &amp;lt;code&amp;gt;&amp;amp;lt;limits.h&amp;amp;gt;&amp;lt;/code&amp;gt;).&lt;br /&gt;
* Skip &amp;lt;code&amp;gt;.&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;..&amp;lt;/code&amp;gt;, or the walk will never end.&lt;br /&gt;
* Use &amp;lt;code&amp;gt;AT_SYMLINK_NOFOLLOW&amp;lt;/code&amp;gt;, and leave symbolic links alone.&lt;br /&gt;
* Set &amp;lt;code&amp;gt;errno&amp;lt;/code&amp;gt; to 0 before &amp;#039;&amp;#039;&amp;#039;each&amp;#039;&amp;#039;&amp;#039; call to [https://man7.org/linux/man-pages/man3/readdir.3.html &amp;lt;code&amp;gt;readdir(3)&amp;lt;/code&amp;gt;]. The recursive calls change it.&lt;br /&gt;
* A file can break several rules. Work out the new mode from all of them, and call [https://man7.org/linux/man-pages/man2/chmod.2.html &amp;lt;code&amp;gt;chmod(2)&amp;lt;/code&amp;gt;] once.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; The set-user-ID bit on &amp;lt;code&amp;gt;demo/sub/tool&amp;lt;/code&amp;gt; is harmless here, because that program is a copy of &amp;lt;code&amp;gt;true&amp;lt;/code&amp;gt;. Never set it on a shell or on anything which runs commands: whoever starts the program would get your rights.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to look at:&lt;br /&gt;
&lt;br /&gt;
* Run &amp;lt;code&amp;gt;./build/debug/app --fix /usr/bin&amp;lt;/code&amp;gt;. Why does it fail for every file?&lt;br /&gt;
* Why is &amp;lt;code&amp;gt;/tmp&amp;lt;/code&amp;gt; not reported, even though everybody can write to it?&lt;br /&gt;
* &amp;lt;code&amp;gt;demo/link&amp;lt;/code&amp;gt; has mode 0777. What would &amp;lt;code&amp;gt;--fix&amp;lt;/code&amp;gt; try to do if the program treated it like a regular file? Why would that fail here, and what would happen if the link pointed to a file of yours?&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Operating_Systems&amp;diff=8447</id>
		<title>Operating Systems</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Operating_Systems&amp;diff=8447"/>
		<updated>2026-11-13T14:13:54Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: /* Lab Sessions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Lab Sessions ==&lt;br /&gt;
&lt;br /&gt;
* Lab 1 - [[OS Lab 1 - Linux setup. Bash primer. C primer]]&lt;br /&gt;
* Lab 2 - [[OS Lab 2 - System calls. The initial stack]]&lt;br /&gt;
* Lab 3 - [[OS Lab 3 - Files. Memory mapping]]&lt;br /&gt;
* Lab 4 - [[OS Lab 4 - Processes. Signals]]&lt;br /&gt;
* Lab 5 - [[OS Lab 5 - Threads. Mutexes]]&lt;br /&gt;
* Lab 6 - [[OS Lab 6 - Users. Permissions]]&lt;br /&gt;
&lt;br /&gt;
=== Old Lab Sessions (2025) ===&lt;br /&gt;
&lt;br /&gt;
* Lab 1 - [[OS Lab 1 - Installing Linux]]&lt;br /&gt;
* Lab 2 - [[OS Lab 2 - Linux Filesystems]]&lt;br /&gt;
* Lab 3 - [[OS Lab 3 - Processes and Jobs]]&lt;br /&gt;
* Lab 4 - [[OS Lab 4 - Users, Groups and Permissions]]&lt;br /&gt;
* Lab 5 - [[OS Lab 5 - Bash Scripting]]&lt;br /&gt;
* Lab 6 - [[OS Lab 6 - Inter Process Communication]]&lt;br /&gt;
* Lab 7 - [[OS Lab 7 - The Network Subsystem]]&lt;br /&gt;
* Lab 8 - [[OS Lab 8 - Transport and Security]]&lt;br /&gt;
* Lab 9 - [[OS Lab 9 - Application Protocols: DNS, SSH, HTTP(S)]]&lt;br /&gt;
* Lab 10 - [[OS Lab 10 - Containers and Docker]]&lt;br /&gt;
* Lab 11 - [[OS Lab 11 - Linux Kernel Modules]]&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_5_-_deadlock.png&amp;diff=8441</id>
		<title>Fișier:OS Lab 5 - deadlock.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_5_-_deadlock.png&amp;diff=8441"/>
		<updated>2026-11-06T14:15:12Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_5_-_futex.png&amp;diff=8440</id>
		<title>Fișier:OS Lab 5 - futex.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_5_-_futex.png&amp;diff=8440"/>
		<updated>2026-11-06T14:14:29Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_5_-_lost_update.png&amp;diff=8439</id>
		<title>Fișier:OS Lab 5 - lost update.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_5_-_lost_update.png&amp;diff=8439"/>
		<updated>2026-11-06T14:13:58Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_5_-_threads.png&amp;diff=8438</id>
		<title>Fișier:OS Lab 5 - threads.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_5_-_threads.png&amp;diff=8438"/>
		<updated>2026-11-06T14:07:56Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=OS_Lab_5_-_Threads._Mutexes&amp;diff=8437</id>
		<title>OS Lab 5 - Threads. Mutexes</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=OS_Lab_5_-_Threads._Mutexes&amp;diff=8437"/>
		<updated>2026-11-06T14:04:59Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: Pagină nouă: In the last lab, we created new processes with [https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;], and each of them had a si...&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In [[OS_Lab_4_-_Processes._Signals|the last lab]], we created new processes with [https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;], and each of them had a single task. In this lab, we will give one process several tasks, its &amp;#039;&amp;#039;&amp;#039;threads&amp;#039;&amp;#039;&amp;#039;, which share its memory. We will create them with [https://man7.org/linux/man-pages/man3/pthread_create.3.html &amp;lt;code&amp;gt;pthread_create(3)&amp;lt;/code&amp;gt;], wait for them with [https://man7.org/linux/man-pages/man3/pthread_join.3.html &amp;lt;code&amp;gt;pthread_join(3)&amp;lt;/code&amp;gt;], and protect the data they share with &amp;#039;&amp;#039;&amp;#039;mutexes&amp;#039;&amp;#039;&amp;#039;. We will also see what these functions ask of the kernel: [https://man7.org/linux/man-pages/man2/clone.2.html &amp;lt;code&amp;gt;clone(2)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/futex.2.html &amp;lt;code&amp;gt;futex(2)&amp;lt;/code&amp;gt;]. As an application, we will simulate a small bank.&lt;br /&gt;
&lt;br /&gt;
== Learning objectives ==&lt;br /&gt;
&lt;br /&gt;
By the end of this lab you should be able to:&lt;br /&gt;
&lt;br /&gt;
# create threads with [https://man7.org/linux/man-pages/man3/pthread_create.3.html &amp;lt;code&amp;gt;pthread_create(3)&amp;lt;/code&amp;gt;], and wait for them with [https://man7.org/linux/man-pages/man3/pthread_join.3.html &amp;lt;code&amp;gt;pthread_join(3)&amp;lt;/code&amp;gt;];&lt;br /&gt;
# explain which [https://man7.org/linux/man-pages/man2/clone.2.html &amp;lt;code&amp;gt;clone(2)&amp;lt;/code&amp;gt;] flags make a new task a thread of the same process;&lt;br /&gt;
# recognize a &amp;#039;&amp;#039;&amp;#039;race&amp;#039;&amp;#039;&amp;#039; on shared data, and fix it with a mutex;&lt;br /&gt;
# explain how a mutex uses [https://man7.org/linux/man-pages/man2/futex.2.html &amp;lt;code&amp;gt;futex(2)&amp;lt;/code&amp;gt;], and why an uncontended lock needs no system call;&lt;br /&gt;
# recognize a &amp;#039;&amp;#039;&amp;#039;deadlock&amp;#039;&amp;#039;&amp;#039;, and avoid it by always locking in the same order.&lt;br /&gt;
&lt;br /&gt;
== Threads ==&lt;br /&gt;
&lt;br /&gt;
A &amp;#039;&amp;#039;&amp;#039;thread&amp;#039;&amp;#039;&amp;#039; is a task which shares memory with other tasks in a task group (process). All the threads of a process run the same program and see the same global variables and heap, but each has its own registers and its own stack, so each can be at a different point of the program, in a different function.&lt;br /&gt;
&lt;br /&gt;
On Linux, threads are created and managed with the &amp;#039;&amp;#039;POSIX threads&amp;#039;&amp;#039; (&amp;#039;&amp;#039;pthreads&amp;#039;&amp;#039;) functions, which are part of &amp;#039;&amp;#039;glibc&amp;#039;&amp;#039;.&lt;br /&gt;
&lt;br /&gt;
=== pthread_create(3) ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;pthread.h&amp;gt;&lt;br /&gt;
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,&lt;br /&gt;
                   void *(*start_routine)(void *), void *arg);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Parameter !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;thread&amp;lt;/code&amp;gt; || Where to store the ID of the new thread, used later to wait for it&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;attr&amp;lt;/code&amp;gt; || Options, such as the size of the stack, or &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt; for the defaults&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;start_routine&amp;lt;/code&amp;gt; || The function the new thread runs. When it returns, the thread ends&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;arg&amp;lt;/code&amp;gt; || The argument passed to &amp;lt;code&amp;gt;start_routine&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
The new thread starts running &amp;lt;code&amp;gt;start_routine(arg)&amp;lt;/code&amp;gt;, while the thread that created it continues after [https://man7.org/linux/man-pages/man3/pthread_create.3.html &amp;lt;code&amp;gt;pthread_create(3)&amp;lt;/code&amp;gt;]. Both &amp;lt;code&amp;gt;arg&amp;lt;/code&amp;gt; and the return value of &amp;lt;code&amp;gt;start_routine&amp;lt;/code&amp;gt; are &amp;lt;code&amp;gt;void *&amp;lt;/code&amp;gt;, so a thread can be given, and can give back, a pointer to anything.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; The pthreads functions do &amp;#039;&amp;#039;&amp;#039;not&amp;#039;&amp;#039;&amp;#039; set &amp;lt;code&amp;gt;errno&amp;lt;/code&amp;gt;. They return 0 on success, or the error number itself (for example, &amp;lt;code&amp;gt;EAGAIN&amp;lt;/code&amp;gt;) on error. The examples below use a &amp;lt;code&amp;gt;print_error()&amp;lt;/code&amp;gt; which takes that number as a parameter.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The following program starts three threads, gives each one its own number, and each of them prints its PID and its &amp;#039;&amp;#039;&amp;#039;TID&amp;#039;&amp;#039;&amp;#039; (&amp;#039;&amp;#039;thread ID&amp;#039;&amp;#039;), the ID of the task:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;pthread.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define N_THREADS 3&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what, int err)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(err));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
static void *worker(void *arg)&lt;br /&gt;
{&lt;br /&gt;
    int id = *(int *) arg;&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;thread %d: PID %d, TID %d\n&amp;quot;, id, getpid(), gettid());&lt;br /&gt;
    write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
    return nullptr;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    pthread_t threads[N_THREADS];&lt;br /&gt;
    int ids[N_THREADS];&lt;br /&gt;
&lt;br /&gt;
    for (int i = 0; i &amp;lt; N_THREADS; i++) {&lt;br /&gt;
        ids[i] = i;&lt;br /&gt;
        int err = pthread_create(&amp;amp;threads[i], nullptr, worker, &amp;amp;ids[i]);&lt;br /&gt;
        if (err != 0) {&lt;br /&gt;
            print_error(&amp;quot;pthread_create&amp;quot;, err);&lt;br /&gt;
            return EXIT_FAILURE;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    for (int i = 0; i &amp;lt; N_THREADS; i++) {&lt;br /&gt;
        pthread_join(threads[i], nullptr);&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;main:     PID %d, TID %d\n&amp;quot;, getpid(), gettid());&lt;br /&gt;
    write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
thread 0: PID 4307, TID 4308&lt;br /&gt;
thread 1: PID 4307, TID 4309&lt;br /&gt;
thread 2: PID 4307, TID 4310&lt;br /&gt;
main:     PID 4307, TID 4307&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
All the threads have the same PID: they are one process. Each has its own TID, and the first thread of the process, the one which runs &amp;lt;code&amp;gt;main()&amp;lt;/code&amp;gt;, has a TID equal to the PID. The three lines may come in any order: the threads run independently.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Each thread is given a pointer to its own element of &amp;lt;code&amp;gt;ids&amp;lt;/code&amp;gt;. Passing &amp;lt;code&amp;gt;&amp;amp;i&amp;lt;/code&amp;gt; instead would be a bug: all the threads would get a pointer to the same variable, which the loop keeps changing, leading to a race condition on access.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== pthread_join(3) ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;pthread.h&amp;gt;&lt;br /&gt;
int pthread_join(pthread_t thread, void **retval);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man3/pthread_join.3.html &amp;lt;code&amp;gt;pthread_join(3)&amp;lt;/code&amp;gt;] waits for a thread to end, the way [https://man7.org/linux/man-pages/man2/waitpid.2.html &amp;lt;code&amp;gt;waitpid(2)&amp;lt;/code&amp;gt;] waits for a child process. If &amp;lt;code&amp;gt;retval&amp;lt;/code&amp;gt; is not &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt;, it stores there the value returned by the thread&amp;#039;s function.&lt;br /&gt;
&lt;br /&gt;
A simpler way to get results back is to give each thread a structure, with both its input and a place for its output. The following program adds up the numbers from 0 to 99,999,999 with four threads, each adding a quarter of them:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;pthread.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define N_THREADS 4&lt;br /&gt;
#define N 100000000&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what, int err)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(err));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// What one thread works on: its input, and a place for its result.&lt;br /&gt;
struct part {&lt;br /&gt;
    long from, to; // Add the numbers in [from, to)&lt;br /&gt;
    long sum;&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
static void *add_range(void *arg)&lt;br /&gt;
{&lt;br /&gt;
    struct part *p = arg;&lt;br /&gt;
    p-&amp;gt;sum = 0;&lt;br /&gt;
    for (long i = p-&amp;gt;from; i &amp;lt; p-&amp;gt;to; i++) {&lt;br /&gt;
        p-&amp;gt;sum += i;&lt;br /&gt;
    }&lt;br /&gt;
    return nullptr;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    pthread_t threads[N_THREADS];&lt;br /&gt;
    struct part parts[N_THREADS];&lt;br /&gt;
&lt;br /&gt;
    for (int i = 0; i &amp;lt; N_THREADS; i++) {&lt;br /&gt;
        parts[i].from = (long) N / N_THREADS * i;&lt;br /&gt;
        parts[i].to = (long) N / N_THREADS * (i + 1);&lt;br /&gt;
        int err = pthread_create(&amp;amp;threads[i], nullptr, add_range, &amp;amp;parts[i]);&lt;br /&gt;
        if (err != 0) {&lt;br /&gt;
            print_error(&amp;quot;pthread_create&amp;quot;, err);&lt;br /&gt;
            return EXIT_FAILURE;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    long sum = 0;&lt;br /&gt;
    for (int i = 0; i &amp;lt; N_THREADS; i++) {&lt;br /&gt;
        pthread_join(threads[i], nullptr);&lt;br /&gt;
        sum += parts[i].sum;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;sum of 0..%d: %ld\n&amp;quot;, N - 1, sum);&lt;br /&gt;
    write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
sum of 0..99999999: 4999999950000000&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Each thread writes only to its own &amp;lt;code&amp;gt;struct part&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;main()&amp;lt;/code&amp;gt; reads it only after [https://man7.org/linux/man-pages/man3/pthread_join.3.html &amp;lt;code&amp;gt;pthread_join(3)&amp;lt;/code&amp;gt;], when the thread has ended. The threads never touch the same data at the same time, so nothing more is needed in this case.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Returning from &amp;lt;code&amp;gt;main()&amp;lt;/code&amp;gt;, or calling [https://man7.org/linux/man-pages/man3/exit.3.html &amp;lt;code&amp;gt;exit(3)&amp;lt;/code&amp;gt;] from any thread, ends the &amp;#039;&amp;#039;&amp;#039;whole process&amp;#039;&amp;#039;&amp;#039;, with all its threads (it uses the &amp;lt;code&amp;gt;exit_group&amp;lt;/code&amp;gt; system call). To end only the calling thread, return from its function, or call [https://man7.org/linux/man-pages/man3/pthread_exit.3.html &amp;lt;code&amp;gt;pthread_exit(3)&amp;lt;/code&amp;gt;]. This is why &amp;lt;code&amp;gt;main()&amp;lt;/code&amp;gt; must join the threads before it returns.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Under the hood: clone(2) ===&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man3/pthread_create.3.html &amp;lt;code&amp;gt;pthread_create(3)&amp;lt;/code&amp;gt;] creates the new task with the [https://man7.org/linux/man-pages/man2/clone.2.html &amp;lt;code&amp;gt;clone(2)&amp;lt;/code&amp;gt;] system call, the same one [https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;] uses. The difference is in the flags, which say what the new task shares with the one that created it:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Flag !! The new task shares&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;CLONE_VM&amp;lt;/code&amp;gt; || The memory: the code, the global variables, the heap, and the stacks of the other threads&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;CLONE_FILES&amp;lt;/code&amp;gt; || The file descriptor table: a file opened by one thread can be used by all of them&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;CLONE_SIGHAND&amp;lt;/code&amp;gt; || The signal handlers&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;CLONE_THREAD&amp;lt;/code&amp;gt; || The process: the new task gets a new TID, but the same PID, and is not a child to be waited for with [https://man7.org/linux/man-pages/man2/waitpid.2.html &amp;lt;code&amp;gt;waitpid(2)&amp;lt;/code&amp;gt;]&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;] calls [https://man7.org/linux/man-pages/man2/clone.2.html &amp;lt;code&amp;gt;clone(2)&amp;lt;/code&amp;gt;] with none of these, so the child gets a copy of everything instead. Since the memory is shared, the new thread cannot use the stack of the thread which created it. Before calling [https://man7.org/linux/man-pages/man2/clone.2.html &amp;lt;code&amp;gt;clone(2)&amp;lt;/code&amp;gt;], glibc allocates a new stack (8 MiB by default) with [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;], and gives its address to [https://man7.org/linux/man-pages/man2/clone.2.html &amp;lt;code&amp;gt;clone(2)&amp;lt;/code&amp;gt;].&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_5_-_threads.png|center|thumb|500px|One process with three threads. They share all the memory of the process, but each one has its own registers, and its own stack, which glibc maps with [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] before calling [https://man7.org/linux/man-pages/man2/clone.2.html &amp;lt;code&amp;gt;clone(2)&amp;lt;/code&amp;gt;].]]&lt;br /&gt;
&lt;br /&gt;
== Races ==&lt;br /&gt;
&lt;br /&gt;
Since threads share their memory, two threads can change the same variable at the same time. The following program starts two threads, and each of them increments a global counter one million times:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;pthread.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define N 1000000&lt;br /&gt;
&lt;br /&gt;
static long counter = 0;&lt;br /&gt;
&lt;br /&gt;
static void *increment(void *arg)&lt;br /&gt;
{&lt;br /&gt;
    (void) arg;&lt;br /&gt;
    for (int i = 0; i &amp;lt; N; i++) {&lt;br /&gt;
        counter++;&lt;br /&gt;
    }&lt;br /&gt;
    return nullptr;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    pthread_t a, b;&lt;br /&gt;
    pthread_create(&amp;amp;a, nullptr, increment, nullptr);&lt;br /&gt;
    pthread_create(&amp;amp;b, nullptr, increment, nullptr);&lt;br /&gt;
    pthread_join(a, nullptr);&lt;br /&gt;
    pthread_join(b, nullptr);&lt;br /&gt;
&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;counter = %ld (expected %d)\n&amp;quot;, counter, 2 * N);&lt;br /&gt;
    write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
counter = 1018661 (expected 2000000)&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
counter = 1008721 (expected 2000000)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The result is wrong, and different every time. &amp;lt;code&amp;gt;counter++&amp;lt;/code&amp;gt; looks like a single operation, but the processor does it in three steps: &amp;#039;&amp;#039;&amp;#039;load&amp;#039;&amp;#039;&amp;#039; the value from memory into a register, &amp;#039;&amp;#039;&amp;#039;add&amp;#039;&amp;#039;&amp;#039; 1 to the register, and &amp;#039;&amp;#039;&amp;#039;store&amp;#039;&amp;#039;&amp;#039; the register back to memory. When two threads do these steps at the same time, they can both load the same value, and one of the increments is lost.&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_5_-_lost_update.png|center|thumb|600px|&amp;lt;code&amp;gt;counter++&amp;lt;/code&amp;gt; is three steps. If two threads interleave them, both load 5 and both store 6: one of the two increments is lost.]]&lt;br /&gt;
&lt;br /&gt;
This is a &amp;#039;&amp;#039;&amp;#039;race&amp;#039;&amp;#039;&amp;#039;: the result depends on how the steps of the threads happen to interleave. A part of the program which uses shared data, and must not be run by two threads at the same time, is called a &amp;#039;&amp;#039;&amp;#039;critical section&amp;#039;&amp;#039;&amp;#039;.&lt;br /&gt;
&lt;br /&gt;
== Mutexes ==&lt;br /&gt;
&lt;br /&gt;
A &amp;#039;&amp;#039;&amp;#039;mutex&amp;#039;&amp;#039;&amp;#039; (&amp;#039;&amp;#039;mutual exclusion&amp;#039;&amp;#039;) is a lock which only one thread can hold at a time. A thread &amp;#039;&amp;#039;&amp;#039;locks&amp;#039;&amp;#039;&amp;#039; the mutex before the critical section, and &amp;#039;&amp;#039;&amp;#039;unlocks&amp;#039;&amp;#039;&amp;#039; it after. If another thread already holds it, [https://man7.org/linux/man-pages/man3/pthread_mutex_lock.3.html &amp;lt;code&amp;gt;pthread_mutex_lock(3)&amp;lt;/code&amp;gt;] waits until it is unlocked.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;pthread.h&amp;gt;&lt;br /&gt;
int pthread_mutex_init(pthread_mutex_t *m, const pthread_mutexattr_t *attr);&lt;br /&gt;
int pthread_mutex_lock(pthread_mutex_t *m);&lt;br /&gt;
int pthread_mutex_unlock(pthread_mutex_t *m);&lt;br /&gt;
int pthread_mutex_destroy(pthread_mutex_t *m);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A mutex must be set up with [https://man7.org/linux/man-pages/man3/pthread_mutex_init.3.html &amp;lt;code&amp;gt;pthread_mutex_init(3)&amp;lt;/code&amp;gt;] before it is used, usually before the threads which use it are created. &amp;lt;code&amp;gt;attr&amp;lt;/code&amp;gt; can choose other kinds of mutexes, or be &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt; for a normal one, which starts unlocked. When the mutex is no longer needed, [https://man7.org/linux/man-pages/man3/pthread_mutex_destroy.3.html &amp;lt;code&amp;gt;pthread_mutex_destroy(3)&amp;lt;/code&amp;gt;] frees anything the mutex may hold.&lt;br /&gt;
&lt;br /&gt;
To fix the counter, we add a mutex, and lock it around the increment:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;pthread.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#define N 1000000&lt;br /&gt;
&lt;br /&gt;
static long counter = 0;&lt;br /&gt;
static pthread_mutex_t lock;&lt;br /&gt;
&lt;br /&gt;
static void *increment(void *arg)&lt;br /&gt;
{&lt;br /&gt;
    (void) arg;&lt;br /&gt;
    for (int i = 0; i &amp;lt; N; i++) {&lt;br /&gt;
        pthread_mutex_lock(&amp;amp;lock);&lt;br /&gt;
        counter++;&lt;br /&gt;
        pthread_mutex_unlock(&amp;amp;lock);&lt;br /&gt;
    }&lt;br /&gt;
    return nullptr;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    pthread_mutex_init(&amp;amp;lock, nullptr);&lt;br /&gt;
&lt;br /&gt;
    pthread_t a, b;&lt;br /&gt;
    pthread_create(&amp;amp;a, nullptr, increment, nullptr);&lt;br /&gt;
    pthread_create(&amp;amp;b, nullptr, increment, nullptr);&lt;br /&gt;
    pthread_join(a, nullptr);&lt;br /&gt;
    pthread_join(b, nullptr);&lt;br /&gt;
&lt;br /&gt;
    pthread_mutex_destroy(&amp;amp;lock);&lt;br /&gt;
&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;counter = %ld (expected %d)\n&amp;quot;, counter, 2 * N);&lt;br /&gt;
    write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
counter = 2000000 (expected 2000000)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The result is now correct, but locking has a cost: on our machine, the program became as much as 100 times slower. Every increment now also locks and unlocks the mutex, and while one thread holds it, the other has to wait. Critical sections should be kept as short as possible.&lt;br /&gt;
&lt;br /&gt;
=== Under the hood: futex(2) ===&lt;br /&gt;
&lt;br /&gt;
A &amp;lt;code&amp;gt;pthread_mutex_t&amp;lt;/code&amp;gt; is, at its core, just an integer in the memory of the process. glibc uses three values:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Value !! Meaning&lt;br /&gt;
|-&lt;br /&gt;
| 0 || Unlocked&lt;br /&gt;
|-&lt;br /&gt;
| 1 || Locked, and no other thread is waiting&lt;br /&gt;
|-&lt;br /&gt;
| 2 || Locked, and other threads may be waiting&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
The processor has &amp;#039;&amp;#039;&amp;#039;atomic&amp;#039;&amp;#039;&amp;#039; instructions, which read and change a value in memory in a single step, so that no other thread can come in between. C provides them in &amp;lt;code&amp;gt;&amp;amp;lt;stdatomic.h&amp;amp;gt;&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;stdatomic.h&amp;gt;. A is an atomic type, such as _Atomic uint32_t, and C the plain one, uint32_t.&lt;br /&gt;
// If *obj == *expected, sets *obj to desired and returns true.&lt;br /&gt;
// Otherwise, copies *obj into *expected and returns false.&lt;br /&gt;
bool atomic_compare_exchange_strong(volatile A *obj, C *expected, C desired);&lt;br /&gt;
// Sets *obj to desired, and returns its old value.&lt;br /&gt;
C atomic_exchange(volatile A *obj, C desired);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Locking a free mutex is a single atomic instruction, which changes it from 0 to 1. This is the &amp;#039;&amp;#039;&amp;#039;fast path&amp;#039;&amp;#039;&amp;#039;, and it needs &amp;#039;&amp;#039;&amp;#039;no system call&amp;#039;&amp;#039;&amp;#039;. The kernel is only needed when a thread has to wait, since only the kernel can put a thread to sleep and wake it up. For this, Linux provides the [https://man7.org/linux/man-pages/man2/futex.2.html &amp;lt;code&amp;gt;futex(2)&amp;lt;/code&amp;gt;] (&amp;#039;&amp;#039;fast user-space mutex&amp;#039;&amp;#039;) system call:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;linux/futex.h&amp;gt; and &amp;lt;sys/syscall.h&amp;gt;. glibc has no wrapper for it.&lt;br /&gt;
long syscall(SYS_futex, uint32_t *addr, int op, uint32_t val, ...);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! &amp;lt;code&amp;gt;op&amp;lt;/code&amp;gt; !! What the kernel does&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;FUTEX_WAIT&amp;lt;/code&amp;gt; || If &amp;lt;code&amp;gt;*addr&amp;lt;/code&amp;gt; is still equal to &amp;lt;code&amp;gt;val&amp;lt;/code&amp;gt;, puts the thread to sleep, until another thread wakes it. Otherwise, returns right away&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;FUTEX_WAKE&amp;lt;/code&amp;gt; || Wakes up to &amp;lt;code&amp;gt;val&amp;lt;/code&amp;gt; threads sleeping on &amp;lt;code&amp;gt;addr&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
For the threads of a single process, the &amp;lt;code&amp;gt;FUTEX_WAIT_PRIVATE&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;FUTEX_WAKE_PRIVATE&amp;lt;/code&amp;gt; versions are a little faster. The kernel does not know anything about mutexes: it only keeps a list of sleeping threads for each address. Using the three values above:&lt;br /&gt;
&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;lock&amp;#039;&amp;#039;&amp;#039;: try to change the mutex from 0 to 1. If that worked, we hold it. Otherwise, set it to 2, to say that someone is waiting, and call &amp;lt;code&amp;gt;FUTEX_WAIT&amp;lt;/code&amp;gt; with 2. When woken, try again.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;unlock&amp;#039;&amp;#039;&amp;#039;: set the mutex to 0. If it was 2, someone may be waiting, so call &amp;lt;code&amp;gt;FUTEX_WAKE&amp;lt;/code&amp;gt; to wake one of them.&lt;br /&gt;
&lt;br /&gt;
The check done by &amp;lt;code&amp;gt;FUTEX_WAIT&amp;lt;/code&amp;gt; is what makes this work: if the mutex was unlocked between our failed attempt and the system call, the value is no longer 2, and the thread does not go to sleep waiting for a wake-up which already happened.&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_5_-_futex.png|center|thumb|750px|Thread A locks a free mutex in user space, with no system call. Thread B finds it taken, marks it with 2 and sleeps in the kernel. When A unlocks it, it sees the 2, and asks the kernel to wake B, which then takes the mutex.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; [https://man7.org/linux/man-pages/man3/pthread_join.3.html &amp;lt;code&amp;gt;pthread_join(3)&amp;lt;/code&amp;gt;] also uses [https://man7.org/linux/man-pages/man2/futex.2.html &amp;lt;code&amp;gt;futex(2)&amp;lt;/code&amp;gt;]. When [https://man7.org/linux/man-pages/man3/pthread_create.3.html &amp;lt;code&amp;gt;pthread_create(3)&amp;lt;/code&amp;gt;] calls [https://man7.org/linux/man-pages/man2/clone.2.html &amp;lt;code&amp;gt;clone(2)&amp;lt;/code&amp;gt;], it asks the kernel (with &amp;lt;code&amp;gt;CLONE_CHILD_CLEARTID&amp;lt;/code&amp;gt;) to set a variable holding the TID of the thread to 0 when the thread ends, and to do a &amp;lt;code&amp;gt;FUTEX_WAKE&amp;lt;/code&amp;gt; on it. [https://man7.org/linux/man-pages/man3/pthread_join.3.html &amp;lt;code&amp;gt;pthread_join(3)&amp;lt;/code&amp;gt;] waits on that variable with &amp;lt;code&amp;gt;FUTEX_WAIT&amp;lt;/code&amp;gt;.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Deadlock ===&lt;br /&gt;
&lt;br /&gt;
A program may need to hold several mutexes at once. If thread A locks mutex 5 and then waits for mutex 7, while thread B has locked mutex 7 and waits for mutex 5, neither of them can ever continue. This is a &amp;#039;&amp;#039;&amp;#039;deadlock&amp;#039;&amp;#039;&amp;#039;. The program does not crash, it just stops, using no CPU time at all.&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_5_-_deadlock.png|center|thumb|550px|Thread A holds one lock and waits for the other, while thread B holds the other and waits for the first. Each waits for the other, forever.]]&lt;br /&gt;
&lt;br /&gt;
The simplest way to avoid it is to always take the mutexes &amp;#039;&amp;#039;&amp;#039;in the same order&amp;#039;&amp;#039;&amp;#039;, for example in increasing order of their number. Then no thread can hold a mutex while waiting for one that comes before it, so the threads can never wait for each other in a circle.&lt;br /&gt;
&lt;br /&gt;
== Exercises ==&lt;br /&gt;
&lt;br /&gt;
Write the program in a new copy of the project template. As a reminder from [[OS_Lab_1_-_Linux_setup._Bash_primer._C_primer#getting-the-template|the first lab]]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
mkdir -p ~/oslab &amp;amp;&amp;amp; cd ~/oslab&lt;br /&gt;
curl -OL https://wiki.dcae.pub.ro/images/9/93/Os_lab_skeleton.zip&lt;br /&gt;
unzip -d lab05 Os_lab_skeleton.zip&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For this lab:&lt;br /&gt;
&lt;br /&gt;
* As in the last labs, do not use the standard I/O library for output: build the text with [https://man7.org/linux/man-pages/man3/snprintf.3.html &amp;lt;code&amp;gt;snprintf(3)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;] it.&lt;br /&gt;
* Check the value returned by [https://man7.org/linux/man-pages/man3/pthread_create.3.html &amp;lt;code&amp;gt;pthread_create(3)&amp;lt;/code&amp;gt;], and remember that it is an error number, not -1.&lt;br /&gt;
* Use &amp;lt;code&amp;gt;time ./build/debug/app&amp;lt;/code&amp;gt; to measure how long the program runs.&lt;br /&gt;
&lt;br /&gt;
=== Bank transfers ===&lt;br /&gt;
&lt;br /&gt;
A bank has 100 accounts, each starting with 1000. 8 threads, the &amp;#039;&amp;#039;&amp;#039;tellers&amp;#039;&amp;#039;&amp;#039;, each make 1,000,000 random transfers between the accounts. Money only moves from one account to another, so at the end, the total must still be 100,000.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
#define N_ACCOUNTS 100&lt;br /&gt;
#define N_THREADS 8&lt;br /&gt;
#define N_TRANSFERS 1000000&lt;br /&gt;
#define INITIAL_BALANCE 1000&lt;br /&gt;
&lt;br /&gt;
struct account {&lt;br /&gt;
    pthread_mutex_t lock; // Not used until step 3&lt;br /&gt;
    int balance;&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
static struct account accounts[N_ACCOUNTS];&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Each transfer picks two &amp;#039;&amp;#039;&amp;#039;different&amp;#039;&amp;#039;&amp;#039; accounts, &amp;lt;code&amp;gt;from&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;to&amp;lt;/code&amp;gt;, and an amount between 1 and 100. If &amp;lt;code&amp;gt;from&amp;lt;/code&amp;gt; has enough money, the amount moves from &amp;lt;code&amp;gt;from&amp;lt;/code&amp;gt; to &amp;lt;code&amp;gt;to&amp;lt;/code&amp;gt;. Otherwise, nothing happens. Use [https://man7.org/linux/man-pages/man3/rand_r.3.html &amp;lt;code&amp;gt;rand_r(3)&amp;lt;/code&amp;gt;] for the random numbers, with a different seed for each thread: [https://man7.org/linux/man-pages/man3/rand.3.html &amp;lt;code&amp;gt;rand(3)&amp;lt;/code&amp;gt;] keeps its state in a global variable, shared by all the threads.&lt;br /&gt;
&lt;br /&gt;
# &amp;#039;&amp;#039;&amp;#039;No locks.&amp;#039;&amp;#039;&amp;#039; Write the tellers, and print the total after joining them. Run the program a few times: what happens to the total?&lt;br /&gt;
# &amp;#039;&amp;#039;&amp;#039;One mutex for the whole bank.&amp;#039;&amp;#039;&amp;#039; Lock a single global mutex around each transfer. The total is now correct. How long does the program take? Why is the &amp;lt;code&amp;gt;sys&amp;lt;/code&amp;gt; time so large?&lt;br /&gt;
# &amp;#039;&amp;#039;&amp;#039;One mutex per account.&amp;#039;&amp;#039;&amp;#039; Instead of the global mutex, lock &amp;lt;code&amp;gt;accounts[from].lock&amp;lt;/code&amp;gt;, then &amp;lt;code&amp;gt;accounts[to].lock&amp;lt;/code&amp;gt;, do the transfer, and unlock them. Run the program: it will probably never end (Ctrl+C stops it). Explain why, in a comment.&lt;br /&gt;
# &amp;#039;&amp;#039;&amp;#039;Lock ordering.&amp;#039;&amp;#039;&amp;#039; Fix step 3 by always locking the account with the lower number first. The total must be correct, and the program should now be faster than in step 2. Why?&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
total: 766978 (expected 100000)&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
total: 751625 (expected 100000)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ time ./build/debug/app&lt;br /&gt;
total: 100000 (expected 100000)&lt;br /&gt;
&lt;br /&gt;
real	0m0.304s&lt;br /&gt;
user	0m0.427s&lt;br /&gt;
sys	0m0.081s&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The first output is from step 1, and the second from step 4. The times depend on the machine, but step 4 should be clearly faster than step 2.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Bonus:&amp;#039;&amp;#039;&amp;#039; Write your own mutex, on top of [https://man7.org/linux/man-pages/man2/futex.2.html &amp;lt;code&amp;gt;futex(2)&amp;lt;/code&amp;gt;], as described in [[#Under the hood: futex(2)|the futex section]]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
typedef _Atomic uint32_t mutex_t; // 0, 1 or 2, as above&lt;br /&gt;
&lt;br /&gt;
void mutex_lock(mutex_t *m);&lt;br /&gt;
void mutex_unlock(mutex_t *m);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use it instead of &amp;lt;code&amp;gt;pthread_mutex_t&amp;lt;/code&amp;gt; in step 4. The total must still be correct, and the time should be close to that of step 4.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Extra:&amp;#039;&amp;#039;&amp;#039; Add an &amp;#039;&amp;#039;&amp;#039;auditor&amp;#039;&amp;#039;&amp;#039; thread, which checks the bank while the tellers work. Every 50 ms ([https://man7.org/linux/man-pages/man2/nanosleep.2.html &amp;lt;code&amp;gt;nanosleep(2)&amp;lt;/code&amp;gt;]), it locks all the accounts, adds up their balances, unlocks them, and prints the total, which must always be 100,000. When the tellers are done, &amp;lt;code&amp;gt;main()&amp;lt;/code&amp;gt; tells the auditor to stop through a global &amp;lt;code&amp;gt;atomic_bool&amp;lt;/code&amp;gt; (from &amp;lt;code&amp;gt;&amp;amp;lt;stdatomic.h&amp;amp;gt;&amp;lt;/code&amp;gt;): a variable which one thread writes while another reads it must be atomic.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
audit: 100000&lt;br /&gt;
audit: 100000&lt;br /&gt;
audit: 100000&lt;br /&gt;
audit: 100000&lt;br /&gt;
audit: 100000&lt;br /&gt;
audit: 100000&lt;br /&gt;
total: 100000 (expected 100000)&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* In which order must the auditor lock the accounts?&lt;br /&gt;
* Why must it hold all the locks at once? Try locking, reading and unlocking one account at a time instead: what totals do you get, and why?&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Operating_Systems&amp;diff=8436</id>
		<title>Operating Systems</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Operating_Systems&amp;diff=8436"/>
		<updated>2026-11-06T14:04:44Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: /* Lab Sessions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Lab Sessions ==&lt;br /&gt;
&lt;br /&gt;
* Lab 1 - [[OS Lab 1 - Linux setup. Bash primer. C primer]]&lt;br /&gt;
* Lab 2 - [[OS Lab 2 - System calls. The initial stack]]&lt;br /&gt;
* Lab 3 - [[OS Lab 3 - Files. Memory mapping]]&lt;br /&gt;
* Lab 4 - [[OS Lab 4 - Processes. Signals]]&lt;br /&gt;
* Lab 5 - [[OS Lab 5 - Threads. Mutexes]]&lt;br /&gt;
&lt;br /&gt;
=== Old Lab Sessions (2025) ===&lt;br /&gt;
&lt;br /&gt;
* Lab 1 - [[OS Lab 1 - Installing Linux]]&lt;br /&gt;
* Lab 2 - [[OS Lab 2 - Linux Filesystems]]&lt;br /&gt;
* Lab 3 - [[OS Lab 3 - Processes and Jobs]]&lt;br /&gt;
* Lab 4 - [[OS Lab 4 - Users, Groups and Permissions]]&lt;br /&gt;
* Lab 5 - [[OS Lab 5 - Bash Scripting]]&lt;br /&gt;
* Lab 6 - [[OS Lab 6 - Inter Process Communication]]&lt;br /&gt;
* Lab 7 - [[OS Lab 7 - The Network Subsystem]]&lt;br /&gt;
* Lab 8 - [[OS Lab 8 - Transport and Security]]&lt;br /&gt;
* Lab 9 - [[OS Lab 9 - Application Protocols: DNS, SSH, HTTP(S)]]&lt;br /&gt;
* Lab 10 - [[OS Lab 10 - Containers and Docker]]&lt;br /&gt;
* Lab 11 - [[OS Lab 11 - Linux Kernel Modules]]&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=OS_Lab_4_-_Processes._Signals&amp;diff=8435</id>
		<title>OS Lab 4 - Processes. Signals</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=OS_Lab_4_-_Processes._Signals&amp;diff=8435"/>
		<updated>2026-10-29T09:57:30Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: Pagină nouă: In the last lab, we used system calls to work with files. So far, each of our programs has been a single process. In this lab, we will create n...&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In [[OS_Lab_3_-_Files._Memory_mapping|the last lab]], we used system calls to work with files. So far, each of our programs has been a single process. In this lab, we will create new processes with [https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;], run other programs in them with &amp;lt;code&amp;gt;exec&amp;lt;/code&amp;gt;, wait for them to end with [https://man7.org/linux/man-pages/man2/waitpid.2.html &amp;lt;code&amp;gt;waitpid(2)&amp;lt;/code&amp;gt;], and send and handle &amp;#039;&amp;#039;&amp;#039;signals&amp;#039;&amp;#039;&amp;#039;. As an application, we will write a small &amp;#039;&amp;#039;&amp;#039;shell&amp;#039;&amp;#039;&amp;#039;.&lt;br /&gt;
&lt;br /&gt;
== Learning objectives ==&lt;br /&gt;
&lt;br /&gt;
By the end of this lab you should be able to:&lt;br /&gt;
&lt;br /&gt;
# create a new process with [https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;], and tell the parent from the child by the value it returns;&lt;br /&gt;
# wait for a child with [https://man7.org/linux/man-pages/man2/waitpid.2.html &amp;lt;code&amp;gt;waitpid(2)&amp;lt;/code&amp;gt;], and read its exit status;&lt;br /&gt;
# run another program with the &amp;lt;code&amp;gt;exec&amp;lt;/code&amp;gt; family of functions, and explain what the process keeps and what it loses;&lt;br /&gt;
# send signals with [https://man7.org/linux/man-pages/man2/kill.2.html &amp;lt;code&amp;gt;kill(2)&amp;lt;/code&amp;gt;], and handle them with [https://man7.org/linux/man-pages/man2/sigaction.2.html &amp;lt;code&amp;gt;sigaction(2)&amp;lt;/code&amp;gt;];&lt;br /&gt;
# put all of these together into a simple shell.&lt;br /&gt;
&lt;br /&gt;
== Processes ==&lt;br /&gt;
&lt;br /&gt;
The kernel runs &amp;#039;&amp;#039;&amp;#039;tasks&amp;#039;&amp;#039;&amp;#039;, and a &amp;#039;&amp;#039;&amp;#039;process&amp;#039;&amp;#039;&amp;#039; is a group of tasks which share their memory, and usually their open files and more. In this lab, each process will have a single task, so we will only use the word process from now on.&lt;br /&gt;
&lt;br /&gt;
Every process is identified by a number, its &amp;#039;&amp;#039;&amp;#039;PID&amp;#039;&amp;#039;&amp;#039; (&amp;#039;&amp;#039;process ID&amp;#039;&amp;#039;), and has a &amp;#039;&amp;#039;&amp;#039;parent&amp;#039;&amp;#039;&amp;#039;: the process that created it. A process can find its own PID using [https://man7.org/linux/man-pages/man2/getpid.2.html &amp;lt;code&amp;gt;getpid(2)&amp;lt;/code&amp;gt;], and the PID of its parent using [https://man7.org/linux/man-pages/man2/getppid.2.html &amp;lt;code&amp;gt;getppid(2)&amp;lt;/code&amp;gt;].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
pid_t getpid(void);  // The PID of the process itself&lt;br /&gt;
pid_t getppid(void); // The PID of its parent&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== fork(2) ===&lt;br /&gt;
&lt;br /&gt;
A new process is created with:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
pid_t fork(void);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;] creates a copy of the calling process, the &amp;#039;&amp;#039;&amp;#039;child&amp;#039;&amp;#039;&amp;#039;. Both processes continue from the same point, the return from [https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;], so [https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;] &amp;#039;&amp;#039;&amp;#039;returns twice&amp;#039;&amp;#039;&amp;#039;, once in each process:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! In the !! [https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;] returns&lt;br /&gt;
|-&lt;br /&gt;
| Parent || The PID of the child&lt;br /&gt;
|-&lt;br /&gt;
| Child || 0&lt;br /&gt;
|-&lt;br /&gt;
| Parent, on error (no child was created) || -1, and sets &amp;lt;code&amp;gt;errno&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_4_-_fork.png|center|thumb|650px|[https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;] returns twice: the PID of the child in the parent, and 0 in the child. From there on, the two processes run independently, each with its own copy of the memory.]]&lt;br /&gt;
&lt;br /&gt;
The child gets a copy of everything the parent has:&lt;br /&gt;
&lt;br /&gt;
* its memory: the code, the global variables, the heap and the stack. The copy is made with &amp;#039;&amp;#039;copy-on-write&amp;#039;&amp;#039; (see the course), so it is fast, but after [https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;] a change made by one process is not seen by the other;&lt;br /&gt;
* its file descriptor table: the same numbers point to the same open files, so the two processes share the file offsets;&lt;br /&gt;
* its current working directory, its signal handlers (see below) and more.&lt;br /&gt;
&lt;br /&gt;
The following program creates a child, and both processes print their PIDs and a variable:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;sys/wait.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    int x = 1;&lt;br /&gt;
&lt;br /&gt;
    pid_t pid = fork();&lt;br /&gt;
    if (pid == -1) {&lt;br /&gt;
        print_error(&amp;quot;fork&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    if (pid == 0) {&lt;br /&gt;
        // The child: its own copy of x.&lt;br /&gt;
        x = 2;&lt;br /&gt;
        snprintf(msg, sizeof msg, &amp;quot;child:  PID %d, parent %d, x = %d\n&amp;quot;, getpid(), getppid(), x);&lt;br /&gt;
        write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
        return EXIT_SUCCESS;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    // The parent: pid is the PID of the child.&lt;br /&gt;
    waitpid(pid, nullptr, 0);&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;parent: PID %d, child %d, x = %d\n&amp;quot;, getpid(), pid, x);&lt;br /&gt;
    write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
child:  PID 2741, parent 2740, x = 2&lt;br /&gt;
parent: PID 2740, child 2741, x = 1&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The parent calls [https://man7.org/linux/man-pages/man2/waitpid.2.html &amp;lt;code&amp;gt;waitpid(2)&amp;lt;/code&amp;gt;], which we will look at next, to wait for the child to end before printing, so the child&amp;#039;s line always comes first. Without it, the two lines could come in either order: after [https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;], the kernel runs the two processes independently.&lt;br /&gt;
&lt;br /&gt;
=== waitpid(2) ===&lt;br /&gt;
&lt;br /&gt;
A parent waits for a child to end with:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;sys/wait.h&amp;gt;&lt;br /&gt;
pid_t waitpid(pid_t pid, int *wstatus, int options);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Parameter !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;pid&amp;lt;/code&amp;gt; || The PID of the child to wait for, or &amp;lt;code&amp;gt;-1&amp;lt;/code&amp;gt; for any child&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;wstatus&amp;lt;/code&amp;gt; || Where to store the status of the child, or &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt; if we do not need it&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;options&amp;lt;/code&amp;gt; || 0 to block until the child ends. &amp;lt;code&amp;gt;WNOHANG&amp;lt;/code&amp;gt;: do not block, return 0 if the child has not ended yet&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man2/waitpid.2.html &amp;lt;code&amp;gt;waitpid(2)&amp;lt;/code&amp;gt;] returns the PID of the child that ended, or &amp;lt;code&amp;gt;-1&amp;lt;/code&amp;gt; on error (for example, &amp;lt;code&amp;gt;ECHILD&amp;lt;/code&amp;gt; if there is no such child). The status is an &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt; which packs several pieces of information. It is read with the following macros:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Macro !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;WIFEXITED(status)&amp;lt;/code&amp;gt; || True if the child ended normally, by returning from &amp;lt;code&amp;gt;main()&amp;lt;/code&amp;gt; or calling [https://man7.org/linux/man-pages/man3/exit.3.html &amp;lt;code&amp;gt;exit(3)&amp;lt;/code&amp;gt;]&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;WEXITSTATUS(status)&amp;lt;/code&amp;gt; || The exit status, from 0 to 255. Only valid if &amp;lt;code&amp;gt;WIFEXITED(status)&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;WIFSIGNALED(status)&amp;lt;/code&amp;gt; || True if the child was killed by a signal&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;WTERMSIG(status)&amp;lt;/code&amp;gt; || The number of the signal. Only valid if &amp;lt;code&amp;gt;WIFSIGNALED(status)&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;sys/wait.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    pid_t pid = fork();&lt;br /&gt;
    if (pid == -1) {&lt;br /&gt;
        print_error(&amp;quot;fork&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
    if (pid == 0) {&lt;br /&gt;
        exit(3);&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    int status;&lt;br /&gt;
    if (waitpid(pid, &amp;amp;status, 0) == -1) {&lt;br /&gt;
        print_error(&amp;quot;waitpid&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    if (WIFEXITED(status)) {&lt;br /&gt;
        snprintf(msg, sizeof msg, &amp;quot;child %d exited with status %d\n&amp;quot;, pid, WEXITSTATUS(status));&lt;br /&gt;
    } else if (WIFSIGNALED(status)) {&lt;br /&gt;
        snprintf(msg, sizeof msg, &amp;quot;child %d was killed by signal %d\n&amp;quot;, pid, WTERMSIG(status));&lt;br /&gt;
    }&lt;br /&gt;
    write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
child 2803 exited with status 3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; A child that has ended, but has not been waited for yet, is a &amp;#039;&amp;#039;&amp;#039;zombie&amp;#039;&amp;#039;&amp;#039;: the kernel has freed its memory and files, and keeps only its PID and its status, for when the parent waits for it. &amp;lt;code&amp;gt;ps&amp;lt;/code&amp;gt; shows it as &amp;lt;code&amp;gt;&amp;amp;lt;defunct&amp;amp;gt;&amp;lt;/code&amp;gt;. A parent should always wait for its children: leaving zombies around for a long time is bad practice. If the parent ends first, the child is adopted by process 1, which waits for it.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== exec ===&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;] can only make copies of the running program. To run a &amp;#039;&amp;#039;&amp;#039;different&amp;#039;&amp;#039;&amp;#039; program, a process calls [https://man7.org/linux/man-pages/man2/execve.2.html &amp;lt;code&amp;gt;execve(2)&amp;lt;/code&amp;gt;]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
int execve(const char *path, char *const argv[], char *const envp[]);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The kernel loads the executable file at &amp;lt;code&amp;gt;path&amp;lt;/code&amp;gt; into the process, in place of the program that is running, and starts it with the given arguments and environment. Both &amp;lt;code&amp;gt;argv&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;envp&amp;lt;/code&amp;gt; are arrays of strings ending with &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
On success, [https://man7.org/linux/man-pages/man2/execve.2.html &amp;lt;code&amp;gt;execve(2)&amp;lt;/code&amp;gt;] &amp;#039;&amp;#039;&amp;#039;does not return&amp;#039;&amp;#039;&amp;#039;: the program that called it is gone. If it returns, it failed, and it returns &amp;lt;code&amp;gt;-1&amp;lt;/code&amp;gt; and sets &amp;lt;code&amp;gt;errno&amp;lt;/code&amp;gt; (for example, &amp;lt;code&amp;gt;ENOENT&amp;lt;/code&amp;gt; if there is no such file).&lt;br /&gt;
&lt;br /&gt;
The process is the same: it keeps its PID, its parent, its open file descriptors and its current working directory. Only its memory, and the program in it, are replaced.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;glibc&amp;#039;&amp;#039; provides several functions on top of [https://man7.org/linux/man-pages/man2/execve.2.html &amp;lt;code&amp;gt;execve(2)&amp;lt;/code&amp;gt;], which differ in how they take the arguments and how they find the program:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Function !! Arguments !! The program is !! Environment&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;execl(path, arg0, arg1, ..., nullptr)&amp;lt;/code&amp;gt; || A list || &amp;lt;code&amp;gt;path&amp;lt;/code&amp;gt; || Inherited&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;execlp(file, arg0, arg1, ..., nullptr)&amp;lt;/code&amp;gt; || A list || Searched for in &amp;lt;code&amp;gt;PATH&amp;lt;/code&amp;gt; || Inherited&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;execv(path, argv)&amp;lt;/code&amp;gt; || An array || &amp;lt;code&amp;gt;path&amp;lt;/code&amp;gt; || Inherited&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;execvp(file, argv)&amp;lt;/code&amp;gt; || An array || Searched for in &amp;lt;code&amp;gt;PATH&amp;lt;/code&amp;gt; || Inherited&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;execve(path, argv, envp)&amp;lt;/code&amp;gt; || An array || &amp;lt;code&amp;gt;path&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;envp&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
A common pattern when launching new programs is calling &amp;lt;code&amp;gt;exec&amp;lt;/code&amp;gt; in the child, right after [https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;]. The following program runs &amp;lt;code&amp;gt;ls -l /&amp;lt;/code&amp;gt; and waits for it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;sys/wait.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    pid_t pid = fork();&lt;br /&gt;
    if (pid == -1) {&lt;br /&gt;
        print_error(&amp;quot;fork&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    if (pid == 0) {&lt;br /&gt;
        char *argv[] = {&amp;quot;ls&amp;quot;, &amp;quot;-l&amp;quot;, &amp;quot;/&amp;quot;, nullptr};&lt;br /&gt;
        execvp(argv[0], argv);&lt;br /&gt;
        // execvp() only returns if it failed.&lt;br /&gt;
        print_error(argv[0]);&lt;br /&gt;
        _exit(127);&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    int status;&lt;br /&gt;
    waitpid(pid, &amp;amp;status, 0);&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;ls exited with status %d\n&amp;quot;, WEXITSTATUS(status));&lt;br /&gt;
    write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
total 64&lt;br /&gt;
lrwxrwxrwx   1 root root     7 Apr 22  2024 bin -&amp;gt; usr/bin&lt;br /&gt;
drwxr-xr-x   4 root root  4096 Sep  3 15:07 boot&lt;br /&gt;
...&lt;br /&gt;
drwxr-xr-x  12 root root  4096 Sep  3 21:06 var&lt;br /&gt;
ls exited with status 0&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_4_-_fork_exec_wait.png|center|thumb|700px|How a shell runs a command: it forks a copy of itself, the copy prepares itself and calls &amp;lt;code&amp;gt;exec&amp;lt;/code&amp;gt; to become the command, and the shell waits for it to end.]]&lt;br /&gt;
&lt;br /&gt;
== Signals ==&lt;br /&gt;
&lt;br /&gt;
A &amp;#039;&amp;#039;&amp;#039;signal&amp;#039;&amp;#039;&amp;#039; is a small number that the kernel sends to a process, to tell it that something happened, right away, whatever the process is doing. Signals come from the kernel itself (an invalid memory access, a child that ended), from the terminal (Ctrl+C), or from other processes. Each signal has a name, a number and a &amp;#039;&amp;#039;&amp;#039;default action&amp;#039;&amp;#039;&amp;#039;, which is what happens to a process that does nothing about it:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Signal !! Number !! Default action !! Sent when&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SIGINT&amp;lt;/code&amp;gt; || 2 || End the process || Ctrl+C is pressed in the terminal&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SIGKILL&amp;lt;/code&amp;gt; || 9 || End the process. &amp;#039;&amp;#039;&amp;#039;Cannot be caught or ignored&amp;#039;&amp;#039;&amp;#039; || &amp;lt;code&amp;gt;kill -KILL&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;kill -9&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SIGSEGV&amp;lt;/code&amp;gt; || 11 || End the process || An invalid memory access&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SIGPIPE&amp;lt;/code&amp;gt; || 13 || End the process || Writing to a pipe that nobody reads&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SIGTERM&amp;lt;/code&amp;gt; || 15 || End the process || &amp;lt;code&amp;gt;kill&amp;lt;/code&amp;gt;: a polite request to end&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SIGCHLD&amp;lt;/code&amp;gt; || 17 || Ignore || A child ended or stopped&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SIGCONT&amp;lt;/code&amp;gt; || 18 || Continue a stopped process || &amp;lt;code&amp;gt;kill -CONT&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SIGSTOP&amp;lt;/code&amp;gt; || 19 || Stop (pause) the process. &amp;#039;&amp;#039;&amp;#039;Cannot be caught or ignored&amp;#039;&amp;#039;&amp;#039; || &amp;lt;code&amp;gt;kill -STOP&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SIGTSTP&amp;lt;/code&amp;gt; || 20 || Stop the process || Ctrl+Z is pressed in the terminal&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;kill -l&amp;lt;/code&amp;gt; lists all of them.&lt;br /&gt;
&lt;br /&gt;
=== Sending signals: kill(2) ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;signal.h&amp;gt;&lt;br /&gt;
int kill(pid_t pid, int sig);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Despite its name, [https://man7.org/linux/man-pages/man2/kill.2.html &amp;lt;code&amp;gt;kill(2)&amp;lt;/code&amp;gt;] sends any signal, not only those which end the process. A process may only send signals to processes of the same user, unless it runs as the superuser (&amp;lt;code&amp;gt;root&amp;lt;/code&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
The following program starts a child which waits forever, and ends it with &amp;lt;code&amp;gt;SIGTERM&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;signal.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;sys/wait.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    pid_t pid = fork();&lt;br /&gt;
    if (pid == -1) {&lt;br /&gt;
        print_error(&amp;quot;fork&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
    if (pid == 0) {&lt;br /&gt;
        pause(); // Wait forever, or until a signal ends the process.&lt;br /&gt;
        _exit(0);&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    sleep(1);&lt;br /&gt;
    if (kill(pid, SIGTERM) == -1) {&lt;br /&gt;
        print_error(&amp;quot;kill&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    int status;&lt;br /&gt;
    waitpid(pid, &amp;amp;status, 0);&lt;br /&gt;
    if (WIFSIGNALED(status)) {&lt;br /&gt;
        char msg[256];&lt;br /&gt;
        snprintf(msg, sizeof msg, &amp;quot;child %d: %s\n&amp;quot;, pid, strsignal(WTERMSIG(status)));&lt;br /&gt;
        write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
    }&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
child 2911: Terminated&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man3/strsignal.3.html &amp;lt;code&amp;gt;strsignal(3)&amp;lt;/code&amp;gt;] (from &amp;lt;code&amp;gt;&amp;amp;lt;string.h&amp;amp;gt;&amp;lt;/code&amp;gt;) returns the description of a signal, the way [https://man7.org/linux/man-pages/man3/strerror.3.html &amp;lt;code&amp;gt;strerror(3)&amp;lt;/code&amp;gt;] does for &amp;lt;code&amp;gt;errno&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Ctrl+C sends &amp;lt;code&amp;gt;SIGINT&amp;lt;/code&amp;gt; to all the processes running in the foreground of the terminal: a program, and the children it creates, all receive it.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Handling signals: sigaction(2) ===&lt;br /&gt;
&lt;br /&gt;
A process can choose what happens when it receives a signal, with:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;signal.h&amp;gt; (simplified)&lt;br /&gt;
struct sigaction {&lt;br /&gt;
    void (*sa_handler)(int); // A function, SIG_DFL or SIG_IGN&lt;br /&gt;
    sigset_t sa_mask;        // Signals to block while the handler runs&lt;br /&gt;
    int sa_flags;            // SA_RESTART, ...&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! &amp;lt;code&amp;gt;sa_handler&amp;lt;/code&amp;gt; !! When the signal arrives&lt;br /&gt;
|-&lt;br /&gt;
| A function &amp;lt;code&amp;gt;void handler(int sig)&amp;lt;/code&amp;gt; || The kernel interrupts the program and calls the function, the &amp;#039;&amp;#039;&amp;#039;signal handler&amp;#039;&amp;#039;&amp;#039;, with the number of the signal. When the handler returns, the program continues where it was&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SIG_IGN&amp;lt;/code&amp;gt; || The signal is ignored&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SIG_DFL&amp;lt;/code&amp;gt; || The default action (see the table above)&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_4_-_signal_handler.png|center|thumb|700px|A signal handler is the reverse of a system call: the kernel calls into the program. After the handler, [https://man7.org/linux/man-pages/man2/sigreturn.2.html &amp;lt;code&amp;gt;sigreturn(2)&amp;lt;/code&amp;gt;] takes the program back to where it was interrupted.]]&lt;br /&gt;
&lt;br /&gt;
The following program counts Ctrl+C presses, and ends after the third one:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;signal.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static volatile sig_atomic_t count = 0;&lt;br /&gt;
&lt;br /&gt;
static void on_sigint(int sig)&lt;br /&gt;
{&lt;br /&gt;
    (void) sig;&lt;br /&gt;
    count++;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    struct sigaction sa = {.sa_handler = on_sigint};&lt;br /&gt;
    sigemptyset(&amp;amp;sa.sa_mask);&lt;br /&gt;
    if (sigaction(SIGINT, &amp;amp;sa, nullptr) == -1) {&lt;br /&gt;
        char msg[256];&lt;br /&gt;
        snprintf(msg, sizeof msg, &amp;quot;sigaction: %s\n&amp;quot;, strerror(errno));&lt;br /&gt;
        write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    while (count &amp;lt; 3) {&lt;br /&gt;
        pause(); // Sleep until a signal arrives.&lt;br /&gt;
        const char msg[] = &amp;quot; Caught SIGINT\n&amp;quot;;&lt;br /&gt;
        write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
    }&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
^C Caught SIGINT&lt;br /&gt;
^C Caught SIGINT&lt;br /&gt;
^C Caught SIGINT&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A signal handler can run between any two instructions of the program, so it must be careful:&lt;br /&gt;
&lt;br /&gt;
* It should only change global variables of type &amp;lt;code&amp;gt;volatile sig_atomic_t&amp;lt;/code&amp;gt;, which the program reads after it returns, like &amp;lt;code&amp;gt;count&amp;lt;/code&amp;gt; above.&lt;br /&gt;
* It should only call &amp;#039;&amp;#039;&amp;#039;async-signal-safe&amp;#039;&amp;#039;&amp;#039; functions, such as [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man2/kill.2.html &amp;lt;code&amp;gt;kill(2)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/_exit.2.html &amp;lt;code&amp;gt;_exit(2)&amp;lt;/code&amp;gt;]. [https://man7.org/linux/man-pages/man3/printf.3.html &amp;lt;code&amp;gt;printf(3)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man3/malloc.3.html &amp;lt;code&amp;gt;malloc(3)&amp;lt;/code&amp;gt;] are &amp;#039;&amp;#039;&amp;#039;not&amp;#039;&amp;#039;&amp;#039; safe: the handler may have interrupted the program in the middle of one of them.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; If a signal arrives while the process is blocked in a system call, such as [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] or [https://man7.org/linux/man-pages/man2/waitpid.2.html &amp;lt;code&amp;gt;waitpid(2)&amp;lt;/code&amp;gt;], the system call is interrupted: after the handler returns, it fails with &amp;lt;code&amp;gt;errno&amp;lt;/code&amp;gt; set to &amp;lt;code&amp;gt;EINTR&amp;lt;/code&amp;gt;. With &amp;lt;code&amp;gt;SA_RESTART&amp;lt;/code&amp;gt; in &amp;lt;code&amp;gt;sa_flags&amp;lt;/code&amp;gt;, most system calls are restarted instead, as if nothing happened.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Blocking signals: sigprocmask(2) ===&lt;br /&gt;
&lt;br /&gt;
A process can also &amp;#039;&amp;#039;&amp;#039;block&amp;#039;&amp;#039;&amp;#039; signals for a while, for example during a part of the program that should not be interrupted. A blocked signal is not lost: it stays &amp;#039;&amp;#039;&amp;#039;pending&amp;#039;&amp;#039;&amp;#039;, and is delivered as soon as it is unblocked.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;signal.h&amp;gt;&lt;br /&gt;
int sigprocmask(int how, const sigset_t *set, sigset_t *oldset);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
sigset_t set;&lt;br /&gt;
sigemptyset(&amp;amp;set);&lt;br /&gt;
sigaddset(&amp;amp;set, SIGINT);&lt;br /&gt;
sigprocmask(SIG_BLOCK, &amp;amp;set, nullptr);   // Ctrl+C waits from here...&lt;br /&gt;
// ...&lt;br /&gt;
sigprocmask(SIG_UNBLOCK, &amp;amp;set, nullptr); // ...until here&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Signals, fork(2) and exec ===&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! !! After [https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;], in the child !! After &amp;lt;code&amp;gt;exec&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| Signals with a handler || Same handler || Back to the default action: the handler was part of the old program&lt;br /&gt;
|-&lt;br /&gt;
| Ignored signals (&amp;lt;code&amp;gt;SIG_IGN&amp;lt;/code&amp;gt;) || Still ignored || Still ignored&lt;br /&gt;
|-&lt;br /&gt;
| Blocked signals || Still blocked || Still blocked&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
== Reading lines: readline ==&lt;br /&gt;
&lt;br /&gt;
The project template already uses the GNU &amp;#039;&amp;#039;readline&amp;#039;&amp;#039; library, which reads a line from the terminal and lets the user edit it and recall earlier lines with the arrow keys:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;readline/readline.h&amp;gt; and &amp;lt;readline/history.h&amp;gt;&lt;br /&gt;
char *readline(const char *prompt);&lt;br /&gt;
void add_history(const char *line);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man3/readline.3.html &amp;lt;code&amp;gt;readline(3)&amp;lt;/code&amp;gt;] prints the prompt and returns the line, without the newline, in memory allocated with [https://man7.org/linux/man-pages/man3/malloc.3.html &amp;lt;code&amp;gt;malloc(3)&amp;lt;/code&amp;gt;], which the program must [https://man7.org/linux/man-pages/man3/free.3.html &amp;lt;code&amp;gt;free(3)&amp;lt;/code&amp;gt;]. At the end of the input (Ctrl+D on an empty line), it returns &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt;. &amp;lt;code&amp;gt;add_history()&amp;lt;/code&amp;gt; saves a line for the arrow keys.&lt;br /&gt;
&lt;br /&gt;
By default, [https://man7.org/linux/man-pages/man3/readline.3.html &amp;lt;code&amp;gt;readline(3)&amp;lt;/code&amp;gt;] installs signal handlers of its own while it waits for a line, to put the terminal back in order before the program is interrupted. A program which handles signals itself turns this off, before anything else, with:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
rl_catch_signals = 0;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Exercises ==&lt;br /&gt;
&lt;br /&gt;
Write the program in a new copy of the project template. As a reminder from [[OS_Lab_1_-_Linux_setup._Bash_primer._C_primer#getting-the-template|the first lab]]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
mkdir -p ~/oslab &amp;amp;&amp;amp; cd ~/oslab&lt;br /&gt;
curl -OL https://wiki.dcae.pub.ro/images/9/93/Os_lab_skeleton.zip&lt;br /&gt;
unzip -d lab04 Os_lab_skeleton.zip&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For this lab:&lt;br /&gt;
&lt;br /&gt;
* Use the &amp;#039;&amp;#039;glibc&amp;#039;&amp;#039; wrappers for the system calls ([https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man3/execvp.3.html &amp;lt;code&amp;gt;execvp(3)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man2/waitpid.2.html &amp;lt;code&amp;gt;waitpid(2)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man2/kill.2.html &amp;lt;code&amp;gt;kill(2)&amp;lt;/code&amp;gt;], ...).&lt;br /&gt;
* As in the last lab, do not use the standard I/O library for output: build the text with [https://man7.org/linux/man-pages/man3/snprintf.3.html &amp;lt;code&amp;gt;snprintf(3)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;] it. Use [https://man7.org/linux/man-pages/man3/readline.3.html &amp;lt;code&amp;gt;readline(3)&amp;lt;/code&amp;gt;] for input.&lt;br /&gt;
&lt;br /&gt;
=== A simple shell ===&lt;br /&gt;
&lt;br /&gt;
Write a shell: a program which reads commands with [https://man7.org/linux/man-pages/man3/readline.3.html &amp;lt;code&amp;gt;readline(3)&amp;lt;/code&amp;gt;], runs them, and waits for them to end, until the user types &amp;lt;code&amp;gt;exit&amp;lt;/code&amp;gt; or presses Ctrl+D.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
$ echo hello world&lt;br /&gt;
hello world&lt;br /&gt;
$ ls /nonexistent&lt;br /&gt;
ls: cannot access &amp;#039;/nonexistent&amp;#039;: No such file or directory&lt;br /&gt;
[exit status 2]&lt;br /&gt;
$ nosuchcmd&lt;br /&gt;
nosuchcmd: command not found&lt;br /&gt;
[exit status 127]&lt;br /&gt;
$ cd /usr&lt;br /&gt;
$ pwd&lt;br /&gt;
/usr&lt;br /&gt;
$ exit&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
# Read a line, and split it into words, at spaces and tabs, into an array of strings ending with &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt;. [https://man7.org/linux/man-pages/man3/strtok_r.3.html &amp;lt;code&amp;gt;strtok_r(3)&amp;lt;/code&amp;gt;] can be used.&lt;br /&gt;
# Run the command: [https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;], call [https://man7.org/linux/man-pages/man3/execvp.3.html &amp;lt;code&amp;gt;execvp(3)&amp;lt;/code&amp;gt;] in the child, and [https://man7.org/linux/man-pages/man2/waitpid.2.html &amp;lt;code&amp;gt;waitpid(2)&amp;lt;/code&amp;gt;] for it in the parent. If [https://man7.org/linux/man-pages/man3/execvp.3.html &amp;lt;code&amp;gt;execvp(3)&amp;lt;/code&amp;gt;] fails, print &amp;lt;code&amp;gt;NAME: command not found&amp;lt;/code&amp;gt; on standard error, and end the child with status 127.&lt;br /&gt;
# After the command ends, print its exit status on standard error if it is not 0, as &amp;lt;code&amp;gt;[exit status N]&amp;lt;/code&amp;gt;, or the signal that killed it, as &amp;lt;code&amp;gt;[killed by signal N: NAME]&amp;lt;/code&amp;gt;.&lt;br /&gt;
# Add two &amp;#039;&amp;#039;&amp;#039;built-in&amp;#039;&amp;#039;&amp;#039; commands, which the shell runs itself, without [https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;]: &amp;lt;code&amp;gt;exit&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;cd DIR&amp;lt;/code&amp;gt;, which changes the current working directory with [https://man7.org/linux/man-pages/man2/chdir.2.html &amp;lt;code&amp;gt;chdir(2)&amp;lt;/code&amp;gt;], or to &amp;lt;code&amp;gt;$HOME&amp;lt;/code&amp;gt; (&amp;lt;code&amp;gt;getenv(&amp;quot;HOME&amp;quot;)&amp;lt;/code&amp;gt;) if there is no &amp;lt;code&amp;gt;DIR&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Bonus:&amp;#039;&amp;#039;&amp;#039; Set &amp;lt;code&amp;gt;rl_catch_signals = 0&amp;lt;/code&amp;gt; as the first thing in &amp;lt;code&amp;gt;main()&amp;lt;/code&amp;gt;, and install a handler for &amp;lt;code&amp;gt;SIGINT&amp;lt;/code&amp;gt; which passes the signal on to the running command, with [https://man7.org/linux/man-pages/man2/kill.2.html &amp;lt;code&amp;gt;kill(2)&amp;lt;/code&amp;gt;].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ sleep 10&lt;br /&gt;
^C[killed by signal 2: Interrupt]&lt;br /&gt;
$ echo still here&lt;br /&gt;
still here&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* Keep the PID of the running command in a &amp;lt;code&amp;gt;volatile sig_atomic_t&amp;lt;/code&amp;gt; global variable, and set it back to 0 when the command ends. At the prompt, there is no command to pass the signal to.&lt;br /&gt;
* Use &amp;lt;code&amp;gt;SA_RESTART&amp;lt;/code&amp;gt;, or check for &amp;lt;code&amp;gt;EINTR&amp;lt;/code&amp;gt; around [https://man7.org/linux/man-pages/man2/waitpid.2.html &amp;lt;code&amp;gt;waitpid(2)&amp;lt;/code&amp;gt;].&lt;br /&gt;
* The handler is installed before [https://man7.org/linux/man-pages/man2/fork.2.html &amp;lt;code&amp;gt;fork(2)&amp;lt;/code&amp;gt;]. What happens to it in the child, after &amp;lt;code&amp;gt;exec&amp;lt;/code&amp;gt;? Why would &amp;lt;code&amp;gt;SIG_IGN&amp;lt;/code&amp;gt; not work instead of a handler?&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Extra:&amp;#039;&amp;#039;&amp;#039; Support output redirection: &amp;lt;code&amp;gt;ls -l / &amp;gt; listing.txt&amp;lt;/code&amp;gt;. In the child, before [https://man7.org/linux/man-pages/man3/execvp.3.html &amp;lt;code&amp;gt;execvp(3)&amp;lt;/code&amp;gt;], open the file, and make the standard output point to it with [https://man7.org/linux/man-pages/man2/dup2.2.html &amp;lt;code&amp;gt;dup2(2)&amp;lt;/code&amp;gt;]: &amp;lt;code&amp;gt;dup2(fd, STDOUT_FILENO)&amp;lt;/code&amp;gt; makes file descriptor 1 point to the same open file as &amp;lt;code&amp;gt;fd&amp;lt;/code&amp;gt;, which can then be closed. Remove &amp;lt;code&amp;gt;&amp;amp;gt;&amp;lt;/code&amp;gt; and the file name from the arguments.&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Operating_Systems&amp;diff=8434</id>
		<title>Operating Systems</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Operating_Systems&amp;diff=8434"/>
		<updated>2026-10-29T09:57:08Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: /* Lab Sessions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Lab Sessions ==&lt;br /&gt;
&lt;br /&gt;
* Lab 1 - [[OS Lab 1 - Linux setup. Bash primer. C primer]]&lt;br /&gt;
* Lab 2 - [[OS Lab 2 - System calls. The initial stack]]&lt;br /&gt;
* Lab 3 - [[OS Lab 3 - Files. Memory mapping]]&lt;br /&gt;
* Lab 3 - [[OS Lab 4 - Processes. Signals]]&lt;br /&gt;
&lt;br /&gt;
=== Old Lab Sessions (2025) ===&lt;br /&gt;
&lt;br /&gt;
* Lab 1 - [[OS Lab 1 - Installing Linux]]&lt;br /&gt;
* Lab 2 - [[OS Lab 2 - Linux Filesystems]]&lt;br /&gt;
* Lab 3 - [[OS Lab 3 - Processes and Jobs]]&lt;br /&gt;
* Lab 4 - [[OS Lab 4 - Users, Groups and Permissions]]&lt;br /&gt;
* Lab 5 - [[OS Lab 5 - Bash Scripting]]&lt;br /&gt;
* Lab 6 - [[OS Lab 6 - Inter Process Communication]]&lt;br /&gt;
* Lab 7 - [[OS Lab 7 - The Network Subsystem]]&lt;br /&gt;
* Lab 8 - [[OS Lab 8 - Transport and Security]]&lt;br /&gt;
* Lab 9 - [[OS Lab 9 - Application Protocols: DNS, SSH, HTTP(S)]]&lt;br /&gt;
* Lab 10 - [[OS Lab 10 - Containers and Docker]]&lt;br /&gt;
* Lab 11 - [[OS Lab 11 - Linux Kernel Modules]]&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_4_-_signal_handler.png&amp;diff=8433</id>
		<title>Fișier:OS Lab 4 - signal handler.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_4_-_signal_handler.png&amp;diff=8433"/>
		<updated>2026-10-29T09:56:15Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_4_-_fork.png&amp;diff=8432</id>
		<title>Fișier:OS Lab 4 - fork.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_4_-_fork.png&amp;diff=8432"/>
		<updated>2026-10-29T09:56:04Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_4_-_fork_exec_wait.png&amp;diff=8431</id>
		<title>Fișier:OS Lab 4 - fork exec wait.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_4_-_fork_exec_wait.png&amp;diff=8431"/>
		<updated>2026-10-29T09:55:50Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=OS_Lab_3_-_Files._Memory_mapping&amp;diff=8427</id>
		<title>OS Lab 3 - Files. Memory mapping</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=OS_Lab_3_-_Files._Memory_mapping&amp;diff=8427"/>
		<updated>2026-10-23T15:00:40Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: /* The ELF file */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In [[OS_Lab_2_-_System_calls._The_initial_stack|the last lab]], we saw how a user-space program asks the kernel for services through &amp;#039;&amp;#039;&amp;#039;system calls&amp;#039;&amp;#039;&amp;#039;, and what the kernel places on the stack before &amp;lt;code&amp;gt;main()&amp;lt;/code&amp;gt; runs. In this lab, we will use system calls to work with &amp;#039;&amp;#039;&amp;#039;files&amp;#039;&amp;#039;&amp;#039;: open them, map them into memory, read and write them, and list the contents of directories. As an application, we will look inside the executable file of our own program.&lt;br /&gt;
&lt;br /&gt;
== Learning objectives ==&lt;br /&gt;
&lt;br /&gt;
By the end of this lab you should be able to:&lt;br /&gt;
&lt;br /&gt;
# explain what a file descriptor is, and open and close files with [https://man7.org/linux/man-pages/man2/open.2.html &amp;lt;code&amp;gt;open(2)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/close.2.html &amp;lt;code&amp;gt;close(2)&amp;lt;/code&amp;gt;];&lt;br /&gt;
# map a file into memory with [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;], and allocate memory with anonymous mappings;&lt;br /&gt;
# read and write files with [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;], and move the file offset with [https://man7.org/linux/man-pages/man2/lseek.2.html &amp;lt;code&amp;gt;lseek(2)&amp;lt;/code&amp;gt;];&lt;br /&gt;
# list the entries of a directory with [https://man7.org/linux/man-pages/man3/readdir.3.html &amp;lt;code&amp;gt;readdir(3)&amp;lt;/code&amp;gt;] and relate them to inode numbers;&lt;br /&gt;
# describe the layout of an ELF executable and find a program header, such as &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt;, in it.&lt;br /&gt;
&lt;br /&gt;
== System call wrappers ==&lt;br /&gt;
&lt;br /&gt;
In the last lab, we called every system call through the generic [https://man7.org/linux/man-pages/man2/syscall.2.html &amp;lt;code&amp;gt;syscall(2)&amp;lt;/code&amp;gt;] function, to see the system call numbers at work. In practice, this is very rarely done: for each system call, the GNU C library (&amp;#039;&amp;#039;glibc&amp;#039;&amp;#039;) provides a small C function with the same name and the same arguments, which only calls the syscall function with the appropriate number.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! System call !! glibc wrapper&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;syscall(SYS_write, fd, buf, count)&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;write(fd, buf, count)&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;syscall(SYS_read, fd, buf, count)&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;read(fd, buf, count)&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;syscall(SYS_close, fd)&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;close(fd)&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;syscall(SYS_mmap, addr, length, prot, flags, fd, offset)&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;mmap(addr, length, prot, flags, fd, offset)&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
The wrappers handle errors in the same way as [https://man7.org/linux/man-pages/man2/syscall.2.html &amp;lt;code&amp;gt;syscall(2)&amp;lt;/code&amp;gt;]: on failure they return &amp;lt;code&amp;gt;-1&amp;lt;/code&amp;gt; (or another special value, as we will see for [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;]) and set &amp;lt;code&amp;gt;errno&amp;lt;/code&amp;gt;. From now on, we will use the wrappers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Not every function in glibc is a thin wrapper. [https://man7.org/linux/man-pages/man3/printf.3.html &amp;lt;code&amp;gt;printf(3)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man3/puts.3.html &amp;lt;code&amp;gt;puts(3)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man3/fopen.3.html &amp;lt;code&amp;gt;fopen(3)&amp;lt;/code&amp;gt;] belong to the C standard I/O library (&amp;#039;&amp;#039;stdio&amp;#039;&amp;#039;), which keeps its own buffers in user space and calls [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] only from time to time. In the labs, we will aim to talk to the kernel directly, and will use only the thin wrappers.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Files ==&lt;br /&gt;
&lt;br /&gt;
A &amp;#039;&amp;#039;&amp;#039;file&amp;#039;&amp;#039;&amp;#039; is an array of bytes, identified by an &amp;#039;&amp;#039;&amp;#039;inode&amp;#039;&amp;#039;&amp;#039;, and found by a name in a &amp;#039;&amp;#039;&amp;#039;directory&amp;#039;&amp;#039;&amp;#039;. The same system calls are used for regular files, for devices (such as the terminal) and for other kinds of files, which we will meet in future lessons.&lt;br /&gt;
&lt;br /&gt;
=== open(2) and close(2) ===&lt;br /&gt;
&lt;br /&gt;
A program cannot use a file by its name directly. It first asks the kernel to &amp;#039;&amp;#039;&amp;#039;open&amp;#039;&amp;#039;&amp;#039; it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;fcntl.h&amp;gt;&lt;br /&gt;
int open(const char *pathname, int flags, ... /* mode_t mode */);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The kernel finds the file, checks the permissions, and records the open file in a table of the process. It returns a small integer, the &amp;#039;&amp;#039;&amp;#039;file descriptor&amp;#039;&amp;#039;&amp;#039;, which identifies the open file in all the following system calls. When the program is done with it, it releases the file descriptor with:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
int close(int fd);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Every process starts with three file descriptors already open, inherited from the program that started it (usually the shell):&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! File descriptor !! Constant !! Name&lt;br /&gt;
|-&lt;br /&gt;
| 0 || &amp;lt;code&amp;gt;STDIN_FILENO&amp;lt;/code&amp;gt; || Standard input&lt;br /&gt;
|-&lt;br /&gt;
| 1 || &amp;lt;code&amp;gt;STDOUT_FILENO&amp;lt;/code&amp;gt; || Standard output&lt;br /&gt;
|-&lt;br /&gt;
| 2 || &amp;lt;code&amp;gt;STDERR_FILENO&amp;lt;/code&amp;gt; || Standard error&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_3_-_fd_table.png|center|thumb|700px|Each process has a table of file descriptors. Each entry points to an open file in the kernel, which records the current offset and the access mode, and points to the file itself.]]&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;flags&amp;lt;/code&amp;gt; argument must contain exactly one of the access modes &amp;lt;code&amp;gt;O_RDONLY&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;O_WRONLY&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;O_RDWR&amp;lt;/code&amp;gt;, optionally combined (with &amp;lt;code&amp;gt;|&amp;lt;/code&amp;gt;) with other flags:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Flag !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_RDONLY&amp;lt;/code&amp;gt; || Open for reading only&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_WRONLY&amp;lt;/code&amp;gt; || Open for writing only&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_RDWR&amp;lt;/code&amp;gt; || Open for reading and writing&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_CREAT&amp;lt;/code&amp;gt; || Create the file if it does not exist. Requires the third argument, &amp;lt;code&amp;gt;mode&amp;lt;/code&amp;gt;, with the permissions of the new file (for example &amp;lt;code&amp;gt;0644&amp;lt;/code&amp;gt;)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_EXCL&amp;lt;/code&amp;gt; || Together with &amp;lt;code&amp;gt;O_CREAT&amp;lt;/code&amp;gt;: fail with &amp;lt;code&amp;gt;EEXIST&amp;lt;/code&amp;gt; if the file already exists&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_TRUNC&amp;lt;/code&amp;gt; || If the file exists, cut its size to 0&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_APPEND&amp;lt;/code&amp;gt; || Every write goes to the end of the file&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
For example, the shell runs &amp;lt;code&amp;gt;echo hi &amp;gt; notes.txt&amp;lt;/code&amp;gt; by opening the file with &amp;lt;code&amp;gt;open(&amp;quot;notes.txt&amp;quot;, O_WRONLY | O_CREAT | O_TRUNC, 0644)&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;echo hi &amp;gt;&amp;gt; notes.txt&amp;lt;/code&amp;gt; with &amp;lt;code&amp;gt;O_APPEND&amp;lt;/code&amp;gt; instead of &amp;lt;code&amp;gt;O_TRUNC&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;fcntl.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(int argc, char **argv)&lt;br /&gt;
{&lt;br /&gt;
    if (argc != 2) {&lt;br /&gt;
        const char usage[] = &amp;quot;Usage: app FILE\n&amp;quot;;&lt;br /&gt;
        write(STDERR_FILENO, usage, strlen(usage));&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    int fd = open(argv[1], O_RDONLY);&lt;br /&gt;
    if (fd == -1) {&lt;br /&gt;
        print_error(argv[1]);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;Opened %s as file descriptor %d\n&amp;quot;, argv[1], fd);&lt;br /&gt;
    write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
&lt;br /&gt;
    close(fd);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app notes.txt&lt;br /&gt;
Opened notes.txt as file descriptor 3&lt;br /&gt;
$ ./build/debug/app nope&lt;br /&gt;
nope: No such file or directory&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== mmap(2) ===&lt;br /&gt;
&lt;br /&gt;
There are two ways for a program to get to the data in a file. The first is the &amp;#039;&amp;#039;&amp;#039;transparent&amp;#039;&amp;#039;&amp;#039; one: the kernel makes the file appear in the virtual memory of the process, and the program uses it like any other memory. This is done with [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;sys/mman.h&amp;gt;&lt;br /&gt;
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);&lt;br /&gt;
int munmap(void *addr, size_t length);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Parameter !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;addr&amp;lt;/code&amp;gt; || A hint for where to place the mapping. Use &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt;, and let the kernel choose&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; || The number of bytes to map. The kernel maps whole pages, so it is rounded up to a multiple of the page size&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;prot&amp;lt;/code&amp;gt; || What the program may do with the memory: &amp;lt;code&amp;gt;PROT_READ&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;PROT_WRITE&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;PROT_EXEC&amp;lt;/code&amp;gt;, combined with &amp;lt;code&amp;gt;|&amp;lt;/code&amp;gt;, or &amp;lt;code&amp;gt;PROT_NONE&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;flags&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;MAP_PRIVATE&amp;lt;/code&amp;gt;: writes to the memory stay in this process and never reach the file. &amp;lt;code&amp;gt;MAP_SHARED&amp;lt;/code&amp;gt;: writes go to the file, and other processes mapping it see them&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;fd&amp;lt;/code&amp;gt; || The open file to map. It must have been opened for reading&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;offset&amp;lt;/code&amp;gt; || Where in the file the mapping starts. Must be a multiple of the page size&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
On success, [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] returns the address of the first mapped byte. On failure, it returns &amp;lt;code&amp;gt;MAP_FAILED&amp;lt;/code&amp;gt; (which is &amp;lt;code&amp;gt;(void *) -1&amp;lt;/code&amp;gt;, &amp;#039;&amp;#039;&amp;#039;not&amp;#039;&amp;#039;&amp;#039; &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt;) and sets &amp;lt;code&amp;gt;errno&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_3_-_mmap_file.png|center|thumb|650px|[https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] makes the file appear in virtual memory: &amp;lt;code&amp;gt;p[i]&amp;lt;/code&amp;gt; is the byte at offset &amp;lt;code&amp;gt;i&amp;lt;/code&amp;gt; in the file. The pages are read from the disk only when the program first touches them.]]&lt;br /&gt;
&lt;br /&gt;
To map the whole file, we need to know its size. We will look at [https://man7.org/linux/man-pages/man2/lseek.2.html &amp;lt;code&amp;gt;lseek(2)&amp;lt;/code&amp;gt;] in detail below, together with [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;]. For now, it is enough to know that &amp;lt;code&amp;gt;lseek(fd, 0, SEEK_END)&amp;lt;/code&amp;gt; returns the size of the file.&lt;br /&gt;
&lt;br /&gt;
The following program prints a file, by mapping it into memory and writing the memory to the standard output:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;fcntl.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;sys/mman.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(int argc, char **argv)&lt;br /&gt;
{&lt;br /&gt;
    if (argc != 2) {&lt;br /&gt;
        const char usage[] = &amp;quot;Usage: app FILE\n&amp;quot;;&lt;br /&gt;
        write(STDERR_FILENO, usage, strlen(usage));&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    int fd = open(argv[1], O_RDONLY);&lt;br /&gt;
    if (fd == -1) {&lt;br /&gt;
        print_error(argv[1]);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    // The offset of the end of the file is its size.&lt;br /&gt;
    off_t size = lseek(fd, 0, SEEK_END);&lt;br /&gt;
    if (size == -1) {&lt;br /&gt;
        print_error(&amp;quot;lseek&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    char *p = mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0);&lt;br /&gt;
    if (p == MAP_FAILED) {&lt;br /&gt;
        print_error(&amp;quot;mmap&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    // The mapping stays valid after the file descriptor is closed.&lt;br /&gt;
    close(fd);&lt;br /&gt;
&lt;br /&gt;
    // The whole file is now an array of bytes in memory.&lt;br /&gt;
    write(STDOUT_FILENO, p, size);&lt;br /&gt;
&lt;br /&gt;
    munmap(p, size);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; A mapping cannot be empty: [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] of an empty file fails with &amp;lt;code&amp;gt;EINVAL&amp;lt;/code&amp;gt; (&amp;#039;&amp;#039;Invalid argument&amp;#039;&amp;#039;).&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; The size of a file can be changed with [https://man7.org/linux/man-pages/man2/truncate.2.html &amp;lt;code&amp;gt;truncate(2)&amp;lt;/code&amp;gt;], given its path, or [https://man7.org/linux/man-pages/man2/ftruncate.2.html &amp;lt;code&amp;gt;ftruncate(2)&amp;lt;/code&amp;gt;], given a file descriptor open for writing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
int truncate(const char *path, off_t length);&lt;br /&gt;
int ftruncate(int fd, off_t length);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Mapping a file is especially convenient for files with a binary structure: a pointer into the mapping can be cast to a pointer to a C &amp;lt;code&amp;gt;struct&amp;lt;/code&amp;gt;, and the fields read directly, as we will do with the ELF file below.&lt;br /&gt;
&lt;br /&gt;
=== Anonymous mmap(2) ===&lt;br /&gt;
&lt;br /&gt;
With the &amp;lt;code&amp;gt;MAP_ANONYMOUS&amp;lt;/code&amp;gt; flag, [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] maps no file at all. The &amp;lt;code&amp;gt;fd&amp;lt;/code&amp;gt; argument must be &amp;lt;code&amp;gt;-1&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;offset&amp;lt;/code&amp;gt; must be 0, and the kernel gives the process new memory, filled with zeros:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;sys/mman.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    size_t size = 1024 * 1024; // 1 MiB&lt;br /&gt;
&lt;br /&gt;
    char *buf = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);&lt;br /&gt;
    if (buf == MAP_FAILED) {&lt;br /&gt;
        char msg[256];&lt;br /&gt;
        snprintf(msg, sizeof msg, &amp;quot;mmap: %s\n&amp;quot;, strerror(errno));&lt;br /&gt;
        write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    // The new memory is filled with zeros.&lt;br /&gt;
    snprintf(buf, size, &amp;quot;Got %zu bytes at %p, the last one is %d\n&amp;quot;, size, (void *) buf, buf[size - 1]);&lt;br /&gt;
    write(STDOUT_FILENO, buf, strlen(buf));&lt;br /&gt;
&lt;br /&gt;
    munmap(buf, size);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
Got 1048576 bytes at 0xffff98360000, the last one is 0&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is how the program gets memory from the kernel: [https://man7.org/linux/man-pages/man3/malloc.3.html &amp;lt;code&amp;gt;malloc(3)&amp;lt;/code&amp;gt;] itself uses anonymous mappings for large allocations (by default, 128 KiB and more), and carves the smaller ones out of bigger regions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; The kernel only reserves the virtual addresses at first. A physical page is given to the process the first time it touches each page, so a mapping of 1 GiB that is never used costs almost nothing.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== read(2), write(2) and lseek(2) ===&lt;br /&gt;
&lt;br /&gt;
The second way to get to the data in a file is the &amp;#039;&amp;#039;&amp;#039;explicit&amp;#039;&amp;#039;&amp;#039; one: the program provides a buffer in its own memory, and asks the kernel to copy data from the file into it, or from it into the file.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
ssize_t read(int fd, void *buf, size_t count);&lt;br /&gt;
ssize_t write(int fd, const void *buf, size_t count);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] copies at most &amp;lt;code&amp;gt;count&amp;lt;/code&amp;gt; bytes from the file into &amp;lt;code&amp;gt;buf&amp;lt;/code&amp;gt;, and returns the number of bytes it copied:&lt;br /&gt;
&lt;br /&gt;
* a positive number, which may be &amp;#039;&amp;#039;&amp;#039;less&amp;#039;&amp;#039;&amp;#039; than &amp;lt;code&amp;gt;count&amp;lt;/code&amp;gt;: for a regular file, only near its end; for a terminal or a pipe, whenever less data is available;&lt;br /&gt;
* &amp;lt;code&amp;gt;0&amp;lt;/code&amp;gt;, at the end of the file;&lt;br /&gt;
* &amp;lt;code&amp;gt;-1&amp;lt;/code&amp;gt;, on error.&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;] works the same way in the other direction. It may also write fewer bytes than asked (for example, when the disk is full), in which case the program must call it again for the rest.&lt;br /&gt;
&lt;br /&gt;
Each open file has a &amp;#039;&amp;#039;&amp;#039;current offset&amp;#039;&amp;#039;&amp;#039;: the position in the file where the next [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] or [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;] starts. It begins at 0 when the file is opened, and every [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] or [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;] moves it forward by the number of bytes it copied. The program can also move it explicitly:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
off_t lseek(int fd, off_t offset, int whence);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! &amp;lt;code&amp;gt;whence&amp;lt;/code&amp;gt; !! The new offset is&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SEEK_SET&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;offset&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SEEK_CUR&amp;lt;/code&amp;gt; || the current offset + &amp;lt;code&amp;gt;offset&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SEEK_END&amp;lt;/code&amp;gt; || the size of the file + &amp;lt;code&amp;gt;offset&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man2/lseek.2.html &amp;lt;code&amp;gt;lseek(2)&amp;lt;/code&amp;gt;] returns the new offset. This is why &amp;lt;code&amp;gt;lseek(fd, 0, SEEK_END)&amp;lt;/code&amp;gt;, which we used in the [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] example above, returns the size of the file.&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_3_-_file_offset.png|center|thumb|525px|The current offset of an open file: [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] moves it forward by the number of bytes it read, and [https://man7.org/linux/man-pages/man2/lseek.2.html &amp;lt;code&amp;gt;lseek(2)&amp;lt;/code&amp;gt;] sets it directly.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; The offset belongs to the open file, not to the file itself (see the file descriptor table above). Two [https://man7.org/linux/man-pages/man2/open.2.html &amp;lt;code&amp;gt;open(2)&amp;lt;/code&amp;gt;] calls on the same file give two independent offsets.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The following program prints a file, like the [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] example above, this time copying it in pieces of up to 4 KiB, until [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] reports the end of the file:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;fcntl.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(int argc, char **argv)&lt;br /&gt;
{&lt;br /&gt;
    if (argc != 2) {&lt;br /&gt;
        const char usage[] = &amp;quot;Usage: app FILE\n&amp;quot;;&lt;br /&gt;
        write(STDERR_FILENO, usage, strlen(usage));&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    int fd = open(argv[1], O_RDONLY);&lt;br /&gt;
    if (fd == -1) {&lt;br /&gt;
        print_error(argv[1]);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    char buf[4096];&lt;br /&gt;
    ssize_t n;&lt;br /&gt;
    while ((n = read(fd, buf, sizeof buf)) &amp;gt; 0) {&lt;br /&gt;
        if (write(STDOUT_FILENO, buf, n) == -1) {&lt;br /&gt;
            print_error(&amp;quot;write&amp;quot;);&lt;br /&gt;
            return EXIT_FAILURE;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    if (n == -1) {&lt;br /&gt;
        print_error(&amp;quot;read&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    close(fd);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Unlike the [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] version, this one also works for an empty file. Like the [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] version, it fails on a directory: &amp;lt;code&amp;gt;read: Is a directory&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== readdir(3) ===&lt;br /&gt;
&lt;br /&gt;
As we saw in the course, a &amp;#039;&amp;#039;&amp;#039;directory&amp;#039;&amp;#039;&amp;#039; is a special file which maps names to &amp;#039;&amp;#039;&amp;#039;inode numbers&amp;#039;&amp;#039;&amp;#039;. Its entries are not read with [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;], but with the [https://man7.org/linux/man-pages/man2/getdents64.2.html &amp;lt;code&amp;gt;getdents64(2)&amp;lt;/code&amp;gt;] system call, which fills a buffer with as many entries as fit. &amp;#039;&amp;#039;glibc&amp;#039;&amp;#039; provides the following interface on top of it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;dirent.h&amp;gt;&lt;br /&gt;
DIR *opendir(const char *name);&lt;br /&gt;
struct dirent *readdir(DIR *dirp);&lt;br /&gt;
int closedir(DIR *dirp);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man3/opendir.3.html &amp;lt;code&amp;gt;opendir(3)&amp;lt;/code&amp;gt;] opens the directory and returns a &amp;lt;code&amp;gt;DIR&amp;lt;/code&amp;gt; structure, which holds the file descriptor and a buffer of entries. Each call to [https://man7.org/linux/man-pages/man3/readdir.3.html &amp;lt;code&amp;gt;readdir(3)&amp;lt;/code&amp;gt;] returns the next entry, calling [https://man7.org/linux/man-pages/man2/getdents64.2.html &amp;lt;code&amp;gt;getdents64(2)&amp;lt;/code&amp;gt;] again when the buffer runs out, and returns &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt; after the last one.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;dirent.h&amp;gt; (simplified)&lt;br /&gt;
struct dirent {&lt;br /&gt;
    ino_t d_ino;             // The inode number&lt;br /&gt;
    off_t d_off;             // Used internally&lt;br /&gt;
    unsigned short d_reclen; // Used internally&lt;br /&gt;
    unsigned char d_type;    // The type of the file&lt;br /&gt;
    char d_name[256];        // The name, &amp;#039;\0&amp;#039;-terminated&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_3_-_dirent.png|center|thumb|600px|A directory is a list of (name, inode number) entries. Each call to [https://man7.org/linux/man-pages/man3/readdir.3.html &amp;lt;code&amp;gt;readdir(3)&amp;lt;/code&amp;gt;] returns the next one, in the order the file system keeps them.]]&lt;br /&gt;
&lt;br /&gt;
The entries come in the order the file system stores them, which is not alphabetical, and include &amp;lt;code&amp;gt;.&amp;lt;/code&amp;gt; (the directory itself) and &amp;lt;code&amp;gt;..&amp;lt;/code&amp;gt; (its parent). The &amp;lt;code&amp;gt;d_type&amp;lt;/code&amp;gt; field holds one of &amp;lt;code&amp;gt;DT_REG&amp;lt;/code&amp;gt; (regular file), &amp;lt;code&amp;gt;DT_DIR&amp;lt;/code&amp;gt; (directory), &amp;lt;code&amp;gt;DT_LNK&amp;lt;/code&amp;gt; (symbolic link), &amp;lt;code&amp;gt;DT_FIFO&amp;lt;/code&amp;gt; (pipe), &amp;lt;code&amp;gt;DT_CHR&amp;lt;/code&amp;gt; (character device), &amp;lt;code&amp;gt;DT_BLK&amp;lt;/code&amp;gt; (block device), &amp;lt;code&amp;gt;DT_SOCK&amp;lt;/code&amp;gt; (socket), or &amp;lt;code&amp;gt;DT_UNKNOWN&amp;lt;/code&amp;gt; if the file system does not provide it.&lt;br /&gt;
&lt;br /&gt;
The following program prints the names in the current directory:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
#include &amp;lt;dirent.h&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    DIR *dir = opendir(&amp;quot;.&amp;quot;);&lt;br /&gt;
    if (dir == nullptr) {&lt;br /&gt;
        print_error(&amp;quot;.&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    struct dirent *entry;&lt;br /&gt;
    errno = 0;&lt;br /&gt;
    while ((entry = readdir(dir)) != nullptr) {&lt;br /&gt;
        write(STDOUT_FILENO, entry-&amp;gt;d_name, strlen(entry-&amp;gt;d_name));&lt;br /&gt;
        write(STDOUT_FILENO, &amp;quot;\n&amp;quot;, 1);&lt;br /&gt;
    }&lt;br /&gt;
    // nullptr means either &amp;quot;no more entries&amp;quot; or an error: only an error sets errno.&lt;br /&gt;
    if (errno != 0) {&lt;br /&gt;
        print_error(&amp;quot;readdir&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    closedir(dir);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; &amp;lt;code&amp;gt;ls&amp;lt;/code&amp;gt; sorts the names before printing them. &amp;lt;code&amp;gt;ls -f&amp;lt;/code&amp;gt; prints them unsorted, in the same order as the program above.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check inode numbers from the shell, use &amp;lt;code&amp;gt;ls -i&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;stat&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ls -i notes.txt&lt;br /&gt;
645260 notes.txt&lt;br /&gt;
$ stat -c &amp;#039;%i %n&amp;#039; notes.txt&lt;br /&gt;
645260 notes.txt&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== The ELF file ==&lt;br /&gt;
&lt;br /&gt;
Executable files and shared libraries on Linux use the &amp;#039;&amp;#039;&amp;#039;ELF&amp;#039;&amp;#039;&amp;#039; format (&amp;#039;&amp;#039;Executable and Linkable Format&amp;#039;&amp;#039;: [https://man7.org/linux/man-pages/man5/elf.5.html &amp;lt;code&amp;gt;elf(5)&amp;lt;/code&amp;gt;]). It is a binary format, described by the structures in &amp;lt;code&amp;gt;&amp;amp;lt;elf.h&amp;amp;gt;&amp;lt;/code&amp;gt;. We will only look at the parts the kernel needs to start a program.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ readelf -h build/debug/app    # the ELF header&lt;br /&gt;
$ readelf -l build/debug/app    # the program headers&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== The ELF header ===&lt;br /&gt;
&lt;br /&gt;
Every ELF file starts with the &amp;#039;&amp;#039;&amp;#039;ELF header&amp;#039;&amp;#039;&amp;#039;, at offset 0:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;elf.h&amp;gt; (simplified)&lt;br /&gt;
typedef struct {&lt;br /&gt;
    unsigned char e_ident[16]; // &amp;quot;\x7f&amp;quot; &amp;quot;ELF&amp;quot;, then the class, byte order, ...&lt;br /&gt;
    uint16_t e_type;           // Executable, shared library, ...&lt;br /&gt;
    uint16_t e_machine;        // The architecture: x86-64, AArch64, RISC-V, ...&lt;br /&gt;
    uint32_t e_version;&lt;br /&gt;
    uint64_t e_entry;          // The entry point (see the last lab)&lt;br /&gt;
    uint64_t e_phoff;          // File offset of the program header table&lt;br /&gt;
    uint64_t e_shoff;          // File offset of the section header table&lt;br /&gt;
    uint32_t e_flags;&lt;br /&gt;
    uint16_t e_ehsize;         // Size of this header&lt;br /&gt;
    uint16_t e_phentsize;      // Size of one program header&lt;br /&gt;
    uint16_t e_phnum;          // Number of program headers&lt;br /&gt;
    uint16_t e_shentsize;&lt;br /&gt;
    uint16_t e_shnum;&lt;br /&gt;
    uint16_t e_shstrndx;&lt;br /&gt;
} Elf64_Ehdr;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The first 4 bytes are always &amp;lt;code&amp;gt;0x7f&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;&amp;#039;E&amp;#039;&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;&amp;#039;L&amp;#039;&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;&amp;#039;F&amp;#039;&amp;lt;/code&amp;gt;. The next byte, &amp;lt;code&amp;gt;e_ident[EI_CLASS]&amp;lt;/code&amp;gt;, is &amp;lt;code&amp;gt;ELFCLASS64&amp;lt;/code&amp;gt; for 64-bit programs.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ readelf -h build/debug/app&lt;br /&gt;
ELF Header:&lt;br /&gt;
  Magic:   7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00&lt;br /&gt;
  Class:                             ELF64&lt;br /&gt;
  ...&lt;br /&gt;
  Machine:                           AArch64&lt;br /&gt;
  ...&lt;br /&gt;
  Start of program headers:          64 (bytes into file)&lt;br /&gt;
  ...&lt;br /&gt;
  Size of program headers:           56 (bytes)&lt;br /&gt;
  Number of program headers:         10&lt;br /&gt;
  ...&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== The program headers ===&lt;br /&gt;
&lt;br /&gt;
The &amp;#039;&amp;#039;&amp;#039;program header table&amp;#039;&amp;#039;&amp;#039; is an array of &amp;lt;code&amp;gt;e_phnum&amp;lt;/code&amp;gt; entries, each &amp;lt;code&amp;gt;e_phentsize&amp;lt;/code&amp;gt; bytes long, starting at offset &amp;lt;code&amp;gt;e_phoff&amp;lt;/code&amp;gt; in the file. Each entry describes a &amp;#039;&amp;#039;&amp;#039;segment&amp;#039;&amp;#039;&amp;#039;: a range of bytes in the file and what the kernel should do with it.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;elf.h&amp;gt;&lt;br /&gt;
typedef struct {&lt;br /&gt;
    uint32_t p_type;   // The kind of segment: PT_LOAD, PT_INTERP, ...&lt;br /&gt;
    uint32_t p_flags;  // Permissions: PF_R, PF_W, PF_X&lt;br /&gt;
    uint64_t p_offset; // Where the segment starts in the file&lt;br /&gt;
    uint64_t p_vaddr;  // Where it goes in virtual memory&lt;br /&gt;
    uint64_t p_paddr;  // Unused&lt;br /&gt;
    uint64_t p_filesz; // Its size in the file&lt;br /&gt;
    uint64_t p_memsz;  // Its size in memory (larger for .bss)&lt;br /&gt;
    uint64_t p_align;&lt;br /&gt;
} Elf64_Phdr;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Common segment types:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! &amp;lt;code&amp;gt;p_type&amp;lt;/code&amp;gt; !! Value !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;PT_LOAD&amp;lt;/code&amp;gt; || 1 || A range of the file to map into memory (&amp;lt;code&amp;gt;.text&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;.rodata&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;.data&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;.bss&amp;lt;/code&amp;gt;, ...)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;PT_DYNAMIC&amp;lt;/code&amp;gt; || 2 || Information for the dynamic loader: which shared libraries to load, ...&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; || 3 || The path of the program interpreter (the dynamic loader)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;PT_NOTE&amp;lt;/code&amp;gt; || 4 || Auxiliary information (for example, a unique build ID)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;PT_PHDR&amp;lt;/code&amp;gt; || 6 || The program header table itself&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==== PT_INTERP ====&lt;br /&gt;
&lt;br /&gt;
As we saw in the [[OS_Lab_2_-_System_calls._The_initial_stack|last lab]], most programs are &amp;#039;&amp;#039;&amp;#039;dynamically linked&amp;#039;&amp;#039;&amp;#039;: the code of the libraries they use (such as &amp;#039;&amp;#039;glibc&amp;#039;&amp;#039;) is not in the executable file, and must be loaded when the program starts. When the kernel finds a &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; segment in a program, it also loads the program named there, the &amp;#039;&amp;#039;&amp;#039;dynamic loader&amp;#039;&amp;#039;&amp;#039;, and starts it instead of the program. The loader then loads the libraries and jumps to the program&amp;#039;s entry point.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; segment is a &amp;lt;code&amp;gt;&amp;#039;\0&amp;#039;&amp;lt;/code&amp;gt;-terminated string of &amp;lt;code&amp;gt;p_filesz&amp;lt;/code&amp;gt; bytes (the &amp;lt;code&amp;gt;&amp;#039;\0&amp;#039;&amp;lt;/code&amp;gt; included), at offset &amp;lt;code&amp;gt;p_offset&amp;lt;/code&amp;gt; in the file:&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_3_-_elf_interp.png|center|thumb|600px|Finding &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt;: the ELF header gives the position of the program header table, and the &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; entry gives the position of the string.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ readelf -l build/debug/app&lt;br /&gt;
...&lt;br /&gt;
Program Headers:&lt;br /&gt;
  Type           Offset             VirtAddr           PhysAddr&lt;br /&gt;
                 FileSiz            MemSiz              Flags  Align&lt;br /&gt;
  PHDR           0x0000000000000040 0x0000000000000040 0x0000000000000040&lt;br /&gt;
                 0x0000000000000230 0x0000000000000230  R      0x8&lt;br /&gt;
  INTERP         0x0000000000000294 0x0000000000000294 0x0000000000000294&lt;br /&gt;
                 0x000000000000001b 0x000000000000001b  R      0x1&lt;br /&gt;
      [Requesting program interpreter: /lib/ld-linux-aarch64.so.1]&lt;br /&gt;
...&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
On x86-64, the dynamic loader is &amp;lt;code&amp;gt;/lib64/ld-linux-x86-64.so.2&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Statically linked programs contain all the library code they need, and have no &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; segment: the kernel jumps directly to their entry point.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Exercises ==&lt;br /&gt;
&lt;br /&gt;
Write each program in its own copy of the project template. As a reminder from [[OS_Lab_1_-_Linux_setup._Bash_primer._C_primer#getting-the-template|the first lab]]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
mkdir -p ~/oslab &amp;amp;&amp;amp; cd ~/oslab&lt;br /&gt;
curl -OL https://wiki.dcae.pub.ro/images/9/93/Os_lab_skeleton.zip&lt;br /&gt;
unzip -d lab03 Os_lab_skeleton.zip&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use a new directory name instead of &amp;lt;code&amp;gt;interp_mmap&amp;lt;/code&amp;gt; for each exercise.&lt;br /&gt;
&lt;br /&gt;
For this lab:&lt;br /&gt;
&lt;br /&gt;
* Use the &amp;#039;&amp;#039;glibc&amp;#039;&amp;#039; wrappers for the system calls ([https://man7.org/linux/man-pages/man2/open.2.html &amp;lt;code&amp;gt;open(2)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man2/lseek.2.html &amp;lt;code&amp;gt;lseek(2)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;], ...), instead of [https://man7.org/linux/man-pages/man2/syscall.2.html &amp;lt;code&amp;gt;syscall(2)&amp;lt;/code&amp;gt;].&lt;br /&gt;
* Do not use the standard I/O library: no &amp;lt;code&amp;gt;FILE&amp;lt;/code&amp;gt;, [https://man7.org/linux/man-pages/man3/printf.3.html &amp;lt;code&amp;gt;printf(3)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man3/puts.3.html &amp;lt;code&amp;gt;puts(3)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man3/fopen.3.html &amp;lt;code&amp;gt;fopen(3)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man3/fread.3.html &amp;lt;code&amp;gt;fread(3)&amp;lt;/code&amp;gt;] and so on. [https://man7.org/linux/man-pages/man3/snprintf.3.html &amp;lt;code&amp;gt;snprintf(3)&amp;lt;/code&amp;gt;] is still fine, and recommended, for building a string that you then [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;].&lt;br /&gt;
* [https://man7.org/linux/man-pages/man3/opendir.3.html &amp;lt;code&amp;gt;opendir(3)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man3/readdir.3.html &amp;lt;code&amp;gt;readdir(3)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man3/closedir.3.html &amp;lt;code&amp;gt;closedir(3)&amp;lt;/code&amp;gt;] should be used for exercise C.&lt;br /&gt;
&lt;br /&gt;
=== A. PT_INTERP with mmap(2) ===&lt;br /&gt;
&lt;br /&gt;
Print the path of the dynamic loader of your own program. Open the executable file, using &amp;lt;code&amp;gt;argv[0]&amp;lt;/code&amp;gt; as its path, map the whole file into memory with [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;], then walk the program headers to find the &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; segment, and print its string.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
/lib/ld-linux-aarch64.so.1&lt;br /&gt;
$ readelf -l build/debug/app | grep interpreter&lt;br /&gt;
      [Requesting program interpreter: /lib/ld-linux-aarch64.so.1]&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your output will be different on x86-64.&lt;br /&gt;
&lt;br /&gt;
* Cast the start of the mapping to &amp;lt;code&amp;gt;const Elf64_Ehdr *&amp;lt;/code&amp;gt;. The program headers are an array of &amp;lt;code&amp;gt;Elf64_Phdr&amp;lt;/code&amp;gt; at &amp;lt;code&amp;gt;e_phoff&amp;lt;/code&amp;gt; bytes from the start.&lt;br /&gt;
* Check that the file starts with &amp;lt;code&amp;gt;[0x7f, &amp;#039;E&amp;#039;, &amp;#039;L&amp;#039;, &amp;#039;F&amp;#039;]&amp;lt;/code&amp;gt; before looking further.&lt;br /&gt;
* If there is no &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; segment, say so on standard error and exit with status 1.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Extra:&amp;#039;&amp;#039;&amp;#039; &amp;lt;code&amp;gt;argv[0]&amp;lt;/code&amp;gt; is not always trustworthy as the location of the executable. Where does the kernel offer us this information direcly?&lt;br /&gt;
&lt;br /&gt;
=== B. PT_INTERP with read(2) and lseek(2) ===&lt;br /&gt;
&lt;br /&gt;
Write the same program again, without [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;]-ing the file: read the ELF header with [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;], then use [https://man7.org/linux/man-pages/man2/lseek.2.html &amp;lt;code&amp;gt;lseek(2)&amp;lt;/code&amp;gt;] to move to the program headers and read them, and finally move to the &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; segment and read the string. The two programs must print the same thing.&lt;br /&gt;
&lt;br /&gt;
* The size of the program header table is only known at run time (&amp;lt;code&amp;gt;e_phnum * e_phentsize&amp;lt;/code&amp;gt; bytes). Allocate the buffer for it with an anonymous [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;], and [https://man7.org/linux/man-pages/man2/munmap.2.html &amp;lt;code&amp;gt;munmap(2)&amp;lt;/code&amp;gt;] it when you are done.&lt;br /&gt;
* [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] may return fewer bytes than you asked for. Check that you got everything you need: for a regular file, getting less means the file is shorter than its headers say.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Extra:&amp;#039;&amp;#039;&amp;#039; compare the system calls the two versions make, with &amp;lt;code&amp;gt;strace ./build/debug/app&amp;lt;/code&amp;gt; (install it with &amp;lt;code&amp;gt;sudo apt install strace&amp;lt;/code&amp;gt;). The ones at the start belong to the dynamic loader and to &amp;#039;&amp;#039;glibc&amp;#039;&amp;#039;; look for &amp;lt;code&amp;gt;openat&amp;lt;/code&amp;gt; and what comes after it.&lt;br /&gt;
&lt;br /&gt;
=== C. Inode numbers with readdir(3) ===&lt;br /&gt;
&lt;br /&gt;
Write a command which takes the name of a file in the current working directory and prints its inode number. Find it by reading the directory with [https://man7.org/linux/man-pages/man3/readdir.3.html &amp;lt;code&amp;gt;readdir(3)&amp;lt;/code&amp;gt;], not with [https://man7.org/linux/man-pages/man2/stat.2.html &amp;lt;code&amp;gt;stat(2)&amp;lt;/code&amp;gt;].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ echo hi &amp;gt; notes.txt&lt;br /&gt;
$ ./build/debug/app notes.txt&lt;br /&gt;
645260&lt;br /&gt;
$ ls -i notes.txt&lt;br /&gt;
645260 notes.txt&lt;br /&gt;
$ ./build/debug/app nope&lt;br /&gt;
nope: No such file or directory&lt;br /&gt;
$ echo $?&lt;br /&gt;
1&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to look at:&lt;br /&gt;
&lt;br /&gt;
* Make a hard link with &amp;lt;code&amp;gt;ln notes.txt other.txt&amp;lt;/code&amp;gt; and a symbolic link with &amp;lt;code&amp;gt;ln -s notes.txt link.txt&amp;lt;/code&amp;gt;. What inode numbers do they have, and why?&lt;br /&gt;
* What are the inode numbers of &amp;lt;code&amp;gt;.&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;..&amp;lt;/code&amp;gt;?&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Extra:&amp;#039;&amp;#039;&amp;#039; also print the type of the file, from &amp;lt;code&amp;gt;d_type&amp;lt;/code&amp;gt;: &amp;lt;code&amp;gt;regular file&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;directory&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;symbolic link&amp;lt;/code&amp;gt;, ...&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=OS_Lab_3_-_Files._Memory_mapping&amp;diff=8426</id>
		<title>OS Lab 3 - Files. Memory mapping</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=OS_Lab_3_-_Files._Memory_mapping&amp;diff=8426"/>
		<updated>2026-10-23T15:00:22Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: /* The ELF file */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In [[OS_Lab_2_-_System_calls._The_initial_stack|the last lab]], we saw how a user-space program asks the kernel for services through &amp;#039;&amp;#039;&amp;#039;system calls&amp;#039;&amp;#039;&amp;#039;, and what the kernel places on the stack before &amp;lt;code&amp;gt;main()&amp;lt;/code&amp;gt; runs. In this lab, we will use system calls to work with &amp;#039;&amp;#039;&amp;#039;files&amp;#039;&amp;#039;&amp;#039;: open them, map them into memory, read and write them, and list the contents of directories. As an application, we will look inside the executable file of our own program.&lt;br /&gt;
&lt;br /&gt;
== Learning objectives ==&lt;br /&gt;
&lt;br /&gt;
By the end of this lab you should be able to:&lt;br /&gt;
&lt;br /&gt;
# explain what a file descriptor is, and open and close files with [https://man7.org/linux/man-pages/man2/open.2.html &amp;lt;code&amp;gt;open(2)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/close.2.html &amp;lt;code&amp;gt;close(2)&amp;lt;/code&amp;gt;];&lt;br /&gt;
# map a file into memory with [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;], and allocate memory with anonymous mappings;&lt;br /&gt;
# read and write files with [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;], and move the file offset with [https://man7.org/linux/man-pages/man2/lseek.2.html &amp;lt;code&amp;gt;lseek(2)&amp;lt;/code&amp;gt;];&lt;br /&gt;
# list the entries of a directory with [https://man7.org/linux/man-pages/man3/readdir.3.html &amp;lt;code&amp;gt;readdir(3)&amp;lt;/code&amp;gt;] and relate them to inode numbers;&lt;br /&gt;
# describe the layout of an ELF executable and find a program header, such as &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt;, in it.&lt;br /&gt;
&lt;br /&gt;
== System call wrappers ==&lt;br /&gt;
&lt;br /&gt;
In the last lab, we called every system call through the generic [https://man7.org/linux/man-pages/man2/syscall.2.html &amp;lt;code&amp;gt;syscall(2)&amp;lt;/code&amp;gt;] function, to see the system call numbers at work. In practice, this is very rarely done: for each system call, the GNU C library (&amp;#039;&amp;#039;glibc&amp;#039;&amp;#039;) provides a small C function with the same name and the same arguments, which only calls the syscall function with the appropriate number.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! System call !! glibc wrapper&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;syscall(SYS_write, fd, buf, count)&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;write(fd, buf, count)&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;syscall(SYS_read, fd, buf, count)&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;read(fd, buf, count)&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;syscall(SYS_close, fd)&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;close(fd)&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;syscall(SYS_mmap, addr, length, prot, flags, fd, offset)&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;mmap(addr, length, prot, flags, fd, offset)&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
The wrappers handle errors in the same way as [https://man7.org/linux/man-pages/man2/syscall.2.html &amp;lt;code&amp;gt;syscall(2)&amp;lt;/code&amp;gt;]: on failure they return &amp;lt;code&amp;gt;-1&amp;lt;/code&amp;gt; (or another special value, as we will see for [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;]) and set &amp;lt;code&amp;gt;errno&amp;lt;/code&amp;gt;. From now on, we will use the wrappers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Not every function in glibc is a thin wrapper. [https://man7.org/linux/man-pages/man3/printf.3.html &amp;lt;code&amp;gt;printf(3)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man3/puts.3.html &amp;lt;code&amp;gt;puts(3)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man3/fopen.3.html &amp;lt;code&amp;gt;fopen(3)&amp;lt;/code&amp;gt;] belong to the C standard I/O library (&amp;#039;&amp;#039;stdio&amp;#039;&amp;#039;), which keeps its own buffers in user space and calls [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] only from time to time. In the labs, we will aim to talk to the kernel directly, and will use only the thin wrappers.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Files ==&lt;br /&gt;
&lt;br /&gt;
A &amp;#039;&amp;#039;&amp;#039;file&amp;#039;&amp;#039;&amp;#039; is an array of bytes, identified by an &amp;#039;&amp;#039;&amp;#039;inode&amp;#039;&amp;#039;&amp;#039;, and found by a name in a &amp;#039;&amp;#039;&amp;#039;directory&amp;#039;&amp;#039;&amp;#039;. The same system calls are used for regular files, for devices (such as the terminal) and for other kinds of files, which we will meet in future lessons.&lt;br /&gt;
&lt;br /&gt;
=== open(2) and close(2) ===&lt;br /&gt;
&lt;br /&gt;
A program cannot use a file by its name directly. It first asks the kernel to &amp;#039;&amp;#039;&amp;#039;open&amp;#039;&amp;#039;&amp;#039; it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;fcntl.h&amp;gt;&lt;br /&gt;
int open(const char *pathname, int flags, ... /* mode_t mode */);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The kernel finds the file, checks the permissions, and records the open file in a table of the process. It returns a small integer, the &amp;#039;&amp;#039;&amp;#039;file descriptor&amp;#039;&amp;#039;&amp;#039;, which identifies the open file in all the following system calls. When the program is done with it, it releases the file descriptor with:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
int close(int fd);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Every process starts with three file descriptors already open, inherited from the program that started it (usually the shell):&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! File descriptor !! Constant !! Name&lt;br /&gt;
|-&lt;br /&gt;
| 0 || &amp;lt;code&amp;gt;STDIN_FILENO&amp;lt;/code&amp;gt; || Standard input&lt;br /&gt;
|-&lt;br /&gt;
| 1 || &amp;lt;code&amp;gt;STDOUT_FILENO&amp;lt;/code&amp;gt; || Standard output&lt;br /&gt;
|-&lt;br /&gt;
| 2 || &amp;lt;code&amp;gt;STDERR_FILENO&amp;lt;/code&amp;gt; || Standard error&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_3_-_fd_table.png|center|thumb|700px|Each process has a table of file descriptors. Each entry points to an open file in the kernel, which records the current offset and the access mode, and points to the file itself.]]&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;flags&amp;lt;/code&amp;gt; argument must contain exactly one of the access modes &amp;lt;code&amp;gt;O_RDONLY&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;O_WRONLY&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;O_RDWR&amp;lt;/code&amp;gt;, optionally combined (with &amp;lt;code&amp;gt;|&amp;lt;/code&amp;gt;) with other flags:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Flag !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_RDONLY&amp;lt;/code&amp;gt; || Open for reading only&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_WRONLY&amp;lt;/code&amp;gt; || Open for writing only&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_RDWR&amp;lt;/code&amp;gt; || Open for reading and writing&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_CREAT&amp;lt;/code&amp;gt; || Create the file if it does not exist. Requires the third argument, &amp;lt;code&amp;gt;mode&amp;lt;/code&amp;gt;, with the permissions of the new file (for example &amp;lt;code&amp;gt;0644&amp;lt;/code&amp;gt;)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_EXCL&amp;lt;/code&amp;gt; || Together with &amp;lt;code&amp;gt;O_CREAT&amp;lt;/code&amp;gt;: fail with &amp;lt;code&amp;gt;EEXIST&amp;lt;/code&amp;gt; if the file already exists&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_TRUNC&amp;lt;/code&amp;gt; || If the file exists, cut its size to 0&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_APPEND&amp;lt;/code&amp;gt; || Every write goes to the end of the file&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
For example, the shell runs &amp;lt;code&amp;gt;echo hi &amp;gt; notes.txt&amp;lt;/code&amp;gt; by opening the file with &amp;lt;code&amp;gt;open(&amp;quot;notes.txt&amp;quot;, O_WRONLY | O_CREAT | O_TRUNC, 0644)&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;echo hi &amp;gt;&amp;gt; notes.txt&amp;lt;/code&amp;gt; with &amp;lt;code&amp;gt;O_APPEND&amp;lt;/code&amp;gt; instead of &amp;lt;code&amp;gt;O_TRUNC&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;fcntl.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(int argc, char **argv)&lt;br /&gt;
{&lt;br /&gt;
    if (argc != 2) {&lt;br /&gt;
        const char usage[] = &amp;quot;Usage: app FILE\n&amp;quot;;&lt;br /&gt;
        write(STDERR_FILENO, usage, strlen(usage));&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    int fd = open(argv[1], O_RDONLY);&lt;br /&gt;
    if (fd == -1) {&lt;br /&gt;
        print_error(argv[1]);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;Opened %s as file descriptor %d\n&amp;quot;, argv[1], fd);&lt;br /&gt;
    write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
&lt;br /&gt;
    close(fd);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app notes.txt&lt;br /&gt;
Opened notes.txt as file descriptor 3&lt;br /&gt;
$ ./build/debug/app nope&lt;br /&gt;
nope: No such file or directory&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== mmap(2) ===&lt;br /&gt;
&lt;br /&gt;
There are two ways for a program to get to the data in a file. The first is the &amp;#039;&amp;#039;&amp;#039;transparent&amp;#039;&amp;#039;&amp;#039; one: the kernel makes the file appear in the virtual memory of the process, and the program uses it like any other memory. This is done with [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;sys/mman.h&amp;gt;&lt;br /&gt;
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);&lt;br /&gt;
int munmap(void *addr, size_t length);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Parameter !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;addr&amp;lt;/code&amp;gt; || A hint for where to place the mapping. Use &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt;, and let the kernel choose&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; || The number of bytes to map. The kernel maps whole pages, so it is rounded up to a multiple of the page size&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;prot&amp;lt;/code&amp;gt; || What the program may do with the memory: &amp;lt;code&amp;gt;PROT_READ&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;PROT_WRITE&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;PROT_EXEC&amp;lt;/code&amp;gt;, combined with &amp;lt;code&amp;gt;|&amp;lt;/code&amp;gt;, or &amp;lt;code&amp;gt;PROT_NONE&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;flags&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;MAP_PRIVATE&amp;lt;/code&amp;gt;: writes to the memory stay in this process and never reach the file. &amp;lt;code&amp;gt;MAP_SHARED&amp;lt;/code&amp;gt;: writes go to the file, and other processes mapping it see them&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;fd&amp;lt;/code&amp;gt; || The open file to map. It must have been opened for reading&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;offset&amp;lt;/code&amp;gt; || Where in the file the mapping starts. Must be a multiple of the page size&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
On success, [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] returns the address of the first mapped byte. On failure, it returns &amp;lt;code&amp;gt;MAP_FAILED&amp;lt;/code&amp;gt; (which is &amp;lt;code&amp;gt;(void *) -1&amp;lt;/code&amp;gt;, &amp;#039;&amp;#039;&amp;#039;not&amp;#039;&amp;#039;&amp;#039; &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt;) and sets &amp;lt;code&amp;gt;errno&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_3_-_mmap_file.png|center|thumb|650px|[https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] makes the file appear in virtual memory: &amp;lt;code&amp;gt;p[i]&amp;lt;/code&amp;gt; is the byte at offset &amp;lt;code&amp;gt;i&amp;lt;/code&amp;gt; in the file. The pages are read from the disk only when the program first touches them.]]&lt;br /&gt;
&lt;br /&gt;
To map the whole file, we need to know its size. We will look at [https://man7.org/linux/man-pages/man2/lseek.2.html &amp;lt;code&amp;gt;lseek(2)&amp;lt;/code&amp;gt;] in detail below, together with [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;]. For now, it is enough to know that &amp;lt;code&amp;gt;lseek(fd, 0, SEEK_END)&amp;lt;/code&amp;gt; returns the size of the file.&lt;br /&gt;
&lt;br /&gt;
The following program prints a file, by mapping it into memory and writing the memory to the standard output:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;fcntl.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;sys/mman.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(int argc, char **argv)&lt;br /&gt;
{&lt;br /&gt;
    if (argc != 2) {&lt;br /&gt;
        const char usage[] = &amp;quot;Usage: app FILE\n&amp;quot;;&lt;br /&gt;
        write(STDERR_FILENO, usage, strlen(usage));&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    int fd = open(argv[1], O_RDONLY);&lt;br /&gt;
    if (fd == -1) {&lt;br /&gt;
        print_error(argv[1]);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    // The offset of the end of the file is its size.&lt;br /&gt;
    off_t size = lseek(fd, 0, SEEK_END);&lt;br /&gt;
    if (size == -1) {&lt;br /&gt;
        print_error(&amp;quot;lseek&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    char *p = mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0);&lt;br /&gt;
    if (p == MAP_FAILED) {&lt;br /&gt;
        print_error(&amp;quot;mmap&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    // The mapping stays valid after the file descriptor is closed.&lt;br /&gt;
    close(fd);&lt;br /&gt;
&lt;br /&gt;
    // The whole file is now an array of bytes in memory.&lt;br /&gt;
    write(STDOUT_FILENO, p, size);&lt;br /&gt;
&lt;br /&gt;
    munmap(p, size);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; A mapping cannot be empty: [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] of an empty file fails with &amp;lt;code&amp;gt;EINVAL&amp;lt;/code&amp;gt; (&amp;#039;&amp;#039;Invalid argument&amp;#039;&amp;#039;).&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; The size of a file can be changed with [https://man7.org/linux/man-pages/man2/truncate.2.html &amp;lt;code&amp;gt;truncate(2)&amp;lt;/code&amp;gt;], given its path, or [https://man7.org/linux/man-pages/man2/ftruncate.2.html &amp;lt;code&amp;gt;ftruncate(2)&amp;lt;/code&amp;gt;], given a file descriptor open for writing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
int truncate(const char *path, off_t length);&lt;br /&gt;
int ftruncate(int fd, off_t length);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Mapping a file is especially convenient for files with a binary structure: a pointer into the mapping can be cast to a pointer to a C &amp;lt;code&amp;gt;struct&amp;lt;/code&amp;gt;, and the fields read directly, as we will do with the ELF file below.&lt;br /&gt;
&lt;br /&gt;
=== Anonymous mmap(2) ===&lt;br /&gt;
&lt;br /&gt;
With the &amp;lt;code&amp;gt;MAP_ANONYMOUS&amp;lt;/code&amp;gt; flag, [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] maps no file at all. The &amp;lt;code&amp;gt;fd&amp;lt;/code&amp;gt; argument must be &amp;lt;code&amp;gt;-1&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;offset&amp;lt;/code&amp;gt; must be 0, and the kernel gives the process new memory, filled with zeros:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;sys/mman.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    size_t size = 1024 * 1024; // 1 MiB&lt;br /&gt;
&lt;br /&gt;
    char *buf = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);&lt;br /&gt;
    if (buf == MAP_FAILED) {&lt;br /&gt;
        char msg[256];&lt;br /&gt;
        snprintf(msg, sizeof msg, &amp;quot;mmap: %s\n&amp;quot;, strerror(errno));&lt;br /&gt;
        write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    // The new memory is filled with zeros.&lt;br /&gt;
    snprintf(buf, size, &amp;quot;Got %zu bytes at %p, the last one is %d\n&amp;quot;, size, (void *) buf, buf[size - 1]);&lt;br /&gt;
    write(STDOUT_FILENO, buf, strlen(buf));&lt;br /&gt;
&lt;br /&gt;
    munmap(buf, size);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
Got 1048576 bytes at 0xffff98360000, the last one is 0&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is how the program gets memory from the kernel: [https://man7.org/linux/man-pages/man3/malloc.3.html &amp;lt;code&amp;gt;malloc(3)&amp;lt;/code&amp;gt;] itself uses anonymous mappings for large allocations (by default, 128 KiB and more), and carves the smaller ones out of bigger regions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; The kernel only reserves the virtual addresses at first. A physical page is given to the process the first time it touches each page, so a mapping of 1 GiB that is never used costs almost nothing.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== read(2), write(2) and lseek(2) ===&lt;br /&gt;
&lt;br /&gt;
The second way to get to the data in a file is the &amp;#039;&amp;#039;&amp;#039;explicit&amp;#039;&amp;#039;&amp;#039; one: the program provides a buffer in its own memory, and asks the kernel to copy data from the file into it, or from it into the file.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
ssize_t read(int fd, void *buf, size_t count);&lt;br /&gt;
ssize_t write(int fd, const void *buf, size_t count);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] copies at most &amp;lt;code&amp;gt;count&amp;lt;/code&amp;gt; bytes from the file into &amp;lt;code&amp;gt;buf&amp;lt;/code&amp;gt;, and returns the number of bytes it copied:&lt;br /&gt;
&lt;br /&gt;
* a positive number, which may be &amp;#039;&amp;#039;&amp;#039;less&amp;#039;&amp;#039;&amp;#039; than &amp;lt;code&amp;gt;count&amp;lt;/code&amp;gt;: for a regular file, only near its end; for a terminal or a pipe, whenever less data is available;&lt;br /&gt;
* &amp;lt;code&amp;gt;0&amp;lt;/code&amp;gt;, at the end of the file;&lt;br /&gt;
* &amp;lt;code&amp;gt;-1&amp;lt;/code&amp;gt;, on error.&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;] works the same way in the other direction. It may also write fewer bytes than asked (for example, when the disk is full), in which case the program must call it again for the rest.&lt;br /&gt;
&lt;br /&gt;
Each open file has a &amp;#039;&amp;#039;&amp;#039;current offset&amp;#039;&amp;#039;&amp;#039;: the position in the file where the next [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] or [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;] starts. It begins at 0 when the file is opened, and every [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] or [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;] moves it forward by the number of bytes it copied. The program can also move it explicitly:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
off_t lseek(int fd, off_t offset, int whence);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! &amp;lt;code&amp;gt;whence&amp;lt;/code&amp;gt; !! The new offset is&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SEEK_SET&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;offset&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SEEK_CUR&amp;lt;/code&amp;gt; || the current offset + &amp;lt;code&amp;gt;offset&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SEEK_END&amp;lt;/code&amp;gt; || the size of the file + &amp;lt;code&amp;gt;offset&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man2/lseek.2.html &amp;lt;code&amp;gt;lseek(2)&amp;lt;/code&amp;gt;] returns the new offset. This is why &amp;lt;code&amp;gt;lseek(fd, 0, SEEK_END)&amp;lt;/code&amp;gt;, which we used in the [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] example above, returns the size of the file.&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_3_-_file_offset.png|center|thumb|525px|The current offset of an open file: [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] moves it forward by the number of bytes it read, and [https://man7.org/linux/man-pages/man2/lseek.2.html &amp;lt;code&amp;gt;lseek(2)&amp;lt;/code&amp;gt;] sets it directly.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; The offset belongs to the open file, not to the file itself (see the file descriptor table above). Two [https://man7.org/linux/man-pages/man2/open.2.html &amp;lt;code&amp;gt;open(2)&amp;lt;/code&amp;gt;] calls on the same file give two independent offsets.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The following program prints a file, like the [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] example above, this time copying it in pieces of up to 4 KiB, until [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] reports the end of the file:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;fcntl.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(int argc, char **argv)&lt;br /&gt;
{&lt;br /&gt;
    if (argc != 2) {&lt;br /&gt;
        const char usage[] = &amp;quot;Usage: app FILE\n&amp;quot;;&lt;br /&gt;
        write(STDERR_FILENO, usage, strlen(usage));&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    int fd = open(argv[1], O_RDONLY);&lt;br /&gt;
    if (fd == -1) {&lt;br /&gt;
        print_error(argv[1]);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    char buf[4096];&lt;br /&gt;
    ssize_t n;&lt;br /&gt;
    while ((n = read(fd, buf, sizeof buf)) &amp;gt; 0) {&lt;br /&gt;
        if (write(STDOUT_FILENO, buf, n) == -1) {&lt;br /&gt;
            print_error(&amp;quot;write&amp;quot;);&lt;br /&gt;
            return EXIT_FAILURE;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    if (n == -1) {&lt;br /&gt;
        print_error(&amp;quot;read&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    close(fd);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Unlike the [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] version, this one also works for an empty file. Like the [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] version, it fails on a directory: &amp;lt;code&amp;gt;read: Is a directory&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== readdir(3) ===&lt;br /&gt;
&lt;br /&gt;
As we saw in the course, a &amp;#039;&amp;#039;&amp;#039;directory&amp;#039;&amp;#039;&amp;#039; is a special file which maps names to &amp;#039;&amp;#039;&amp;#039;inode numbers&amp;#039;&amp;#039;&amp;#039;. Its entries are not read with [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;], but with the [https://man7.org/linux/man-pages/man2/getdents64.2.html &amp;lt;code&amp;gt;getdents64(2)&amp;lt;/code&amp;gt;] system call, which fills a buffer with as many entries as fit. &amp;#039;&amp;#039;glibc&amp;#039;&amp;#039; provides the following interface on top of it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;dirent.h&amp;gt;&lt;br /&gt;
DIR *opendir(const char *name);&lt;br /&gt;
struct dirent *readdir(DIR *dirp);&lt;br /&gt;
int closedir(DIR *dirp);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man3/opendir.3.html &amp;lt;code&amp;gt;opendir(3)&amp;lt;/code&amp;gt;] opens the directory and returns a &amp;lt;code&amp;gt;DIR&amp;lt;/code&amp;gt; structure, which holds the file descriptor and a buffer of entries. Each call to [https://man7.org/linux/man-pages/man3/readdir.3.html &amp;lt;code&amp;gt;readdir(3)&amp;lt;/code&amp;gt;] returns the next entry, calling [https://man7.org/linux/man-pages/man2/getdents64.2.html &amp;lt;code&amp;gt;getdents64(2)&amp;lt;/code&amp;gt;] again when the buffer runs out, and returns &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt; after the last one.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;dirent.h&amp;gt; (simplified)&lt;br /&gt;
struct dirent {&lt;br /&gt;
    ino_t d_ino;             // The inode number&lt;br /&gt;
    off_t d_off;             // Used internally&lt;br /&gt;
    unsigned short d_reclen; // Used internally&lt;br /&gt;
    unsigned char d_type;    // The type of the file&lt;br /&gt;
    char d_name[256];        // The name, &amp;#039;\0&amp;#039;-terminated&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_3_-_dirent.png|center|thumb|600px|A directory is a list of (name, inode number) entries. Each call to [https://man7.org/linux/man-pages/man3/readdir.3.html &amp;lt;code&amp;gt;readdir(3)&amp;lt;/code&amp;gt;] returns the next one, in the order the file system keeps them.]]&lt;br /&gt;
&lt;br /&gt;
The entries come in the order the file system stores them, which is not alphabetical, and include &amp;lt;code&amp;gt;.&amp;lt;/code&amp;gt; (the directory itself) and &amp;lt;code&amp;gt;..&amp;lt;/code&amp;gt; (its parent). The &amp;lt;code&amp;gt;d_type&amp;lt;/code&amp;gt; field holds one of &amp;lt;code&amp;gt;DT_REG&amp;lt;/code&amp;gt; (regular file), &amp;lt;code&amp;gt;DT_DIR&amp;lt;/code&amp;gt; (directory), &amp;lt;code&amp;gt;DT_LNK&amp;lt;/code&amp;gt; (symbolic link), &amp;lt;code&amp;gt;DT_FIFO&amp;lt;/code&amp;gt; (pipe), &amp;lt;code&amp;gt;DT_CHR&amp;lt;/code&amp;gt; (character device), &amp;lt;code&amp;gt;DT_BLK&amp;lt;/code&amp;gt; (block device), &amp;lt;code&amp;gt;DT_SOCK&amp;lt;/code&amp;gt; (socket), or &amp;lt;code&amp;gt;DT_UNKNOWN&amp;lt;/code&amp;gt; if the file system does not provide it.&lt;br /&gt;
&lt;br /&gt;
The following program prints the names in the current directory:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
#include &amp;lt;dirent.h&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    DIR *dir = opendir(&amp;quot;.&amp;quot;);&lt;br /&gt;
    if (dir == nullptr) {&lt;br /&gt;
        print_error(&amp;quot;.&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    struct dirent *entry;&lt;br /&gt;
    errno = 0;&lt;br /&gt;
    while ((entry = readdir(dir)) != nullptr) {&lt;br /&gt;
        write(STDOUT_FILENO, entry-&amp;gt;d_name, strlen(entry-&amp;gt;d_name));&lt;br /&gt;
        write(STDOUT_FILENO, &amp;quot;\n&amp;quot;, 1);&lt;br /&gt;
    }&lt;br /&gt;
    // nullptr means either &amp;quot;no more entries&amp;quot; or an error: only an error sets errno.&lt;br /&gt;
    if (errno != 0) {&lt;br /&gt;
        print_error(&amp;quot;readdir&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    closedir(dir);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; &amp;lt;code&amp;gt;ls&amp;lt;/code&amp;gt; sorts the names before printing them. &amp;lt;code&amp;gt;ls -f&amp;lt;/code&amp;gt; prints them unsorted, in the same order as the program above.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check inode numbers from the shell, use &amp;lt;code&amp;gt;ls -i&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;stat&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ls -i notes.txt&lt;br /&gt;
645260 notes.txt&lt;br /&gt;
$ stat -c &amp;#039;%i %n&amp;#039; notes.txt&lt;br /&gt;
645260 notes.txt&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== The ELF file ==&lt;br /&gt;
&lt;br /&gt;
Executable files and shared libraries on Linux use the &amp;#039;&amp;#039;&amp;#039;ELF&amp;#039;&amp;#039;&amp;#039; format (&amp;#039;&amp;#039;Executable and Linkable Format&amp;#039;&amp;#039;: [https://man7.org/linux/man-pages/man5/elf.5.html &amp;lt;code&amp;gt;syscall(2)&amp;lt;/code&amp;gt;]). It is a binary format, described by the structures in &amp;lt;code&amp;gt;&amp;amp;lt;elf.h&amp;amp;gt;&amp;lt;/code&amp;gt;. We will only look at the parts the kernel needs to start a program.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ readelf -h build/debug/app    # the ELF header&lt;br /&gt;
$ readelf -l build/debug/app    # the program headers&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== The ELF header ===&lt;br /&gt;
&lt;br /&gt;
Every ELF file starts with the &amp;#039;&amp;#039;&amp;#039;ELF header&amp;#039;&amp;#039;&amp;#039;, at offset 0:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;elf.h&amp;gt; (simplified)&lt;br /&gt;
typedef struct {&lt;br /&gt;
    unsigned char e_ident[16]; // &amp;quot;\x7f&amp;quot; &amp;quot;ELF&amp;quot;, then the class, byte order, ...&lt;br /&gt;
    uint16_t e_type;           // Executable, shared library, ...&lt;br /&gt;
    uint16_t e_machine;        // The architecture: x86-64, AArch64, RISC-V, ...&lt;br /&gt;
    uint32_t e_version;&lt;br /&gt;
    uint64_t e_entry;          // The entry point (see the last lab)&lt;br /&gt;
    uint64_t e_phoff;          // File offset of the program header table&lt;br /&gt;
    uint64_t e_shoff;          // File offset of the section header table&lt;br /&gt;
    uint32_t e_flags;&lt;br /&gt;
    uint16_t e_ehsize;         // Size of this header&lt;br /&gt;
    uint16_t e_phentsize;      // Size of one program header&lt;br /&gt;
    uint16_t e_phnum;          // Number of program headers&lt;br /&gt;
    uint16_t e_shentsize;&lt;br /&gt;
    uint16_t e_shnum;&lt;br /&gt;
    uint16_t e_shstrndx;&lt;br /&gt;
} Elf64_Ehdr;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The first 4 bytes are always &amp;lt;code&amp;gt;0x7f&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;&amp;#039;E&amp;#039;&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;&amp;#039;L&amp;#039;&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;&amp;#039;F&amp;#039;&amp;lt;/code&amp;gt;. The next byte, &amp;lt;code&amp;gt;e_ident[EI_CLASS]&amp;lt;/code&amp;gt;, is &amp;lt;code&amp;gt;ELFCLASS64&amp;lt;/code&amp;gt; for 64-bit programs.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ readelf -h build/debug/app&lt;br /&gt;
ELF Header:&lt;br /&gt;
  Magic:   7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00&lt;br /&gt;
  Class:                             ELF64&lt;br /&gt;
  ...&lt;br /&gt;
  Machine:                           AArch64&lt;br /&gt;
  ...&lt;br /&gt;
  Start of program headers:          64 (bytes into file)&lt;br /&gt;
  ...&lt;br /&gt;
  Size of program headers:           56 (bytes)&lt;br /&gt;
  Number of program headers:         10&lt;br /&gt;
  ...&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== The program headers ===&lt;br /&gt;
&lt;br /&gt;
The &amp;#039;&amp;#039;&amp;#039;program header table&amp;#039;&amp;#039;&amp;#039; is an array of &amp;lt;code&amp;gt;e_phnum&amp;lt;/code&amp;gt; entries, each &amp;lt;code&amp;gt;e_phentsize&amp;lt;/code&amp;gt; bytes long, starting at offset &amp;lt;code&amp;gt;e_phoff&amp;lt;/code&amp;gt; in the file. Each entry describes a &amp;#039;&amp;#039;&amp;#039;segment&amp;#039;&amp;#039;&amp;#039;: a range of bytes in the file and what the kernel should do with it.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;elf.h&amp;gt;&lt;br /&gt;
typedef struct {&lt;br /&gt;
    uint32_t p_type;   // The kind of segment: PT_LOAD, PT_INTERP, ...&lt;br /&gt;
    uint32_t p_flags;  // Permissions: PF_R, PF_W, PF_X&lt;br /&gt;
    uint64_t p_offset; // Where the segment starts in the file&lt;br /&gt;
    uint64_t p_vaddr;  // Where it goes in virtual memory&lt;br /&gt;
    uint64_t p_paddr;  // Unused&lt;br /&gt;
    uint64_t p_filesz; // Its size in the file&lt;br /&gt;
    uint64_t p_memsz;  // Its size in memory (larger for .bss)&lt;br /&gt;
    uint64_t p_align;&lt;br /&gt;
} Elf64_Phdr;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Common segment types:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! &amp;lt;code&amp;gt;p_type&amp;lt;/code&amp;gt; !! Value !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;PT_LOAD&amp;lt;/code&amp;gt; || 1 || A range of the file to map into memory (&amp;lt;code&amp;gt;.text&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;.rodata&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;.data&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;.bss&amp;lt;/code&amp;gt;, ...)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;PT_DYNAMIC&amp;lt;/code&amp;gt; || 2 || Information for the dynamic loader: which shared libraries to load, ...&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; || 3 || The path of the program interpreter (the dynamic loader)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;PT_NOTE&amp;lt;/code&amp;gt; || 4 || Auxiliary information (for example, a unique build ID)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;PT_PHDR&amp;lt;/code&amp;gt; || 6 || The program header table itself&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==== PT_INTERP ====&lt;br /&gt;
&lt;br /&gt;
As we saw in the [[OS_Lab_2_-_System_calls._The_initial_stack|last lab]], most programs are &amp;#039;&amp;#039;&amp;#039;dynamically linked&amp;#039;&amp;#039;&amp;#039;: the code of the libraries they use (such as &amp;#039;&amp;#039;glibc&amp;#039;&amp;#039;) is not in the executable file, and must be loaded when the program starts. When the kernel finds a &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; segment in a program, it also loads the program named there, the &amp;#039;&amp;#039;&amp;#039;dynamic loader&amp;#039;&amp;#039;&amp;#039;, and starts it instead of the program. The loader then loads the libraries and jumps to the program&amp;#039;s entry point.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; segment is a &amp;lt;code&amp;gt;&amp;#039;\0&amp;#039;&amp;lt;/code&amp;gt;-terminated string of &amp;lt;code&amp;gt;p_filesz&amp;lt;/code&amp;gt; bytes (the &amp;lt;code&amp;gt;&amp;#039;\0&amp;#039;&amp;lt;/code&amp;gt; included), at offset &amp;lt;code&amp;gt;p_offset&amp;lt;/code&amp;gt; in the file:&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_3_-_elf_interp.png|center|thumb|600px|Finding &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt;: the ELF header gives the position of the program header table, and the &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; entry gives the position of the string.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ readelf -l build/debug/app&lt;br /&gt;
...&lt;br /&gt;
Program Headers:&lt;br /&gt;
  Type           Offset             VirtAddr           PhysAddr&lt;br /&gt;
                 FileSiz            MemSiz              Flags  Align&lt;br /&gt;
  PHDR           0x0000000000000040 0x0000000000000040 0x0000000000000040&lt;br /&gt;
                 0x0000000000000230 0x0000000000000230  R      0x8&lt;br /&gt;
  INTERP         0x0000000000000294 0x0000000000000294 0x0000000000000294&lt;br /&gt;
                 0x000000000000001b 0x000000000000001b  R      0x1&lt;br /&gt;
      [Requesting program interpreter: /lib/ld-linux-aarch64.so.1]&lt;br /&gt;
...&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
On x86-64, the dynamic loader is &amp;lt;code&amp;gt;/lib64/ld-linux-x86-64.so.2&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Statically linked programs contain all the library code they need, and have no &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; segment: the kernel jumps directly to their entry point.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Exercises ==&lt;br /&gt;
&lt;br /&gt;
Write each program in its own copy of the project template. As a reminder from [[OS_Lab_1_-_Linux_setup._Bash_primer._C_primer#getting-the-template|the first lab]]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
mkdir -p ~/oslab &amp;amp;&amp;amp; cd ~/oslab&lt;br /&gt;
curl -OL https://wiki.dcae.pub.ro/images/9/93/Os_lab_skeleton.zip&lt;br /&gt;
unzip -d lab03 Os_lab_skeleton.zip&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use a new directory name instead of &amp;lt;code&amp;gt;interp_mmap&amp;lt;/code&amp;gt; for each exercise.&lt;br /&gt;
&lt;br /&gt;
For this lab:&lt;br /&gt;
&lt;br /&gt;
* Use the &amp;#039;&amp;#039;glibc&amp;#039;&amp;#039; wrappers for the system calls ([https://man7.org/linux/man-pages/man2/open.2.html &amp;lt;code&amp;gt;open(2)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man2/lseek.2.html &amp;lt;code&amp;gt;lseek(2)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;], ...), instead of [https://man7.org/linux/man-pages/man2/syscall.2.html &amp;lt;code&amp;gt;syscall(2)&amp;lt;/code&amp;gt;].&lt;br /&gt;
* Do not use the standard I/O library: no &amp;lt;code&amp;gt;FILE&amp;lt;/code&amp;gt;, [https://man7.org/linux/man-pages/man3/printf.3.html &amp;lt;code&amp;gt;printf(3)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man3/puts.3.html &amp;lt;code&amp;gt;puts(3)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man3/fopen.3.html &amp;lt;code&amp;gt;fopen(3)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man3/fread.3.html &amp;lt;code&amp;gt;fread(3)&amp;lt;/code&amp;gt;] and so on. [https://man7.org/linux/man-pages/man3/snprintf.3.html &amp;lt;code&amp;gt;snprintf(3)&amp;lt;/code&amp;gt;] is still fine, and recommended, for building a string that you then [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;].&lt;br /&gt;
* [https://man7.org/linux/man-pages/man3/opendir.3.html &amp;lt;code&amp;gt;opendir(3)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man3/readdir.3.html &amp;lt;code&amp;gt;readdir(3)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man3/closedir.3.html &amp;lt;code&amp;gt;closedir(3)&amp;lt;/code&amp;gt;] should be used for exercise C.&lt;br /&gt;
&lt;br /&gt;
=== A. PT_INTERP with mmap(2) ===&lt;br /&gt;
&lt;br /&gt;
Print the path of the dynamic loader of your own program. Open the executable file, using &amp;lt;code&amp;gt;argv[0]&amp;lt;/code&amp;gt; as its path, map the whole file into memory with [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;], then walk the program headers to find the &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; segment, and print its string.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
/lib/ld-linux-aarch64.so.1&lt;br /&gt;
$ readelf -l build/debug/app | grep interpreter&lt;br /&gt;
      [Requesting program interpreter: /lib/ld-linux-aarch64.so.1]&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your output will be different on x86-64.&lt;br /&gt;
&lt;br /&gt;
* Cast the start of the mapping to &amp;lt;code&amp;gt;const Elf64_Ehdr *&amp;lt;/code&amp;gt;. The program headers are an array of &amp;lt;code&amp;gt;Elf64_Phdr&amp;lt;/code&amp;gt; at &amp;lt;code&amp;gt;e_phoff&amp;lt;/code&amp;gt; bytes from the start.&lt;br /&gt;
* Check that the file starts with &amp;lt;code&amp;gt;[0x7f, &amp;#039;E&amp;#039;, &amp;#039;L&amp;#039;, &amp;#039;F&amp;#039;]&amp;lt;/code&amp;gt; before looking further.&lt;br /&gt;
* If there is no &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; segment, say so on standard error and exit with status 1.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Extra:&amp;#039;&amp;#039;&amp;#039; &amp;lt;code&amp;gt;argv[0]&amp;lt;/code&amp;gt; is not always trustworthy as the location of the executable. Where does the kernel offer us this information direcly?&lt;br /&gt;
&lt;br /&gt;
=== B. PT_INTERP with read(2) and lseek(2) ===&lt;br /&gt;
&lt;br /&gt;
Write the same program again, without [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;]-ing the file: read the ELF header with [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;], then use [https://man7.org/linux/man-pages/man2/lseek.2.html &amp;lt;code&amp;gt;lseek(2)&amp;lt;/code&amp;gt;] to move to the program headers and read them, and finally move to the &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; segment and read the string. The two programs must print the same thing.&lt;br /&gt;
&lt;br /&gt;
* The size of the program header table is only known at run time (&amp;lt;code&amp;gt;e_phnum * e_phentsize&amp;lt;/code&amp;gt; bytes). Allocate the buffer for it with an anonymous [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;], and [https://man7.org/linux/man-pages/man2/munmap.2.html &amp;lt;code&amp;gt;munmap(2)&amp;lt;/code&amp;gt;] it when you are done.&lt;br /&gt;
* [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] may return fewer bytes than you asked for. Check that you got everything you need: for a regular file, getting less means the file is shorter than its headers say.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Extra:&amp;#039;&amp;#039;&amp;#039; compare the system calls the two versions make, with &amp;lt;code&amp;gt;strace ./build/debug/app&amp;lt;/code&amp;gt; (install it with &amp;lt;code&amp;gt;sudo apt install strace&amp;lt;/code&amp;gt;). The ones at the start belong to the dynamic loader and to &amp;#039;&amp;#039;glibc&amp;#039;&amp;#039;; look for &amp;lt;code&amp;gt;openat&amp;lt;/code&amp;gt; and what comes after it.&lt;br /&gt;
&lt;br /&gt;
=== C. Inode numbers with readdir(3) ===&lt;br /&gt;
&lt;br /&gt;
Write a command which takes the name of a file in the current working directory and prints its inode number. Find it by reading the directory with [https://man7.org/linux/man-pages/man3/readdir.3.html &amp;lt;code&amp;gt;readdir(3)&amp;lt;/code&amp;gt;], not with [https://man7.org/linux/man-pages/man2/stat.2.html &amp;lt;code&amp;gt;stat(2)&amp;lt;/code&amp;gt;].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ echo hi &amp;gt; notes.txt&lt;br /&gt;
$ ./build/debug/app notes.txt&lt;br /&gt;
645260&lt;br /&gt;
$ ls -i notes.txt&lt;br /&gt;
645260 notes.txt&lt;br /&gt;
$ ./build/debug/app nope&lt;br /&gt;
nope: No such file or directory&lt;br /&gt;
$ echo $?&lt;br /&gt;
1&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to look at:&lt;br /&gt;
&lt;br /&gt;
* Make a hard link with &amp;lt;code&amp;gt;ln notes.txt other.txt&amp;lt;/code&amp;gt; and a symbolic link with &amp;lt;code&amp;gt;ln -s notes.txt link.txt&amp;lt;/code&amp;gt;. What inode numbers do they have, and why?&lt;br /&gt;
* What are the inode numbers of &amp;lt;code&amp;gt;.&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;..&amp;lt;/code&amp;gt;?&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Extra:&amp;#039;&amp;#039;&amp;#039; also print the type of the file, from &amp;lt;code&amp;gt;d_type&amp;lt;/code&amp;gt;: &amp;lt;code&amp;gt;regular file&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;directory&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;symbolic link&amp;lt;/code&amp;gt;, ...&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=OS_Lab_3_-_Files._Memory_mapping&amp;diff=8425</id>
		<title>OS Lab 3 - Files. Memory mapping</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=OS_Lab_3_-_Files._Memory_mapping&amp;diff=8425"/>
		<updated>2026-10-23T07:26:45Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: Pagină nouă: In the last lab, we saw how a user-space program asks the kernel for services through &amp;#039;&amp;#039;&amp;#039;system calls&amp;#039;&amp;#039;&amp;#039;, and what the kernel places...&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In [[OS_Lab_2_-_System_calls._The_initial_stack|the last lab]], we saw how a user-space program asks the kernel for services through &amp;#039;&amp;#039;&amp;#039;system calls&amp;#039;&amp;#039;&amp;#039;, and what the kernel places on the stack before &amp;lt;code&amp;gt;main()&amp;lt;/code&amp;gt; runs. In this lab, we will use system calls to work with &amp;#039;&amp;#039;&amp;#039;files&amp;#039;&amp;#039;&amp;#039;: open them, map them into memory, read and write them, and list the contents of directories. As an application, we will look inside the executable file of our own program.&lt;br /&gt;
&lt;br /&gt;
== Learning objectives ==&lt;br /&gt;
&lt;br /&gt;
By the end of this lab you should be able to:&lt;br /&gt;
&lt;br /&gt;
# explain what a file descriptor is, and open and close files with [https://man7.org/linux/man-pages/man2/open.2.html &amp;lt;code&amp;gt;open(2)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/close.2.html &amp;lt;code&amp;gt;close(2)&amp;lt;/code&amp;gt;];&lt;br /&gt;
# map a file into memory with [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;], and allocate memory with anonymous mappings;&lt;br /&gt;
# read and write files with [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;], and move the file offset with [https://man7.org/linux/man-pages/man2/lseek.2.html &amp;lt;code&amp;gt;lseek(2)&amp;lt;/code&amp;gt;];&lt;br /&gt;
# list the entries of a directory with [https://man7.org/linux/man-pages/man3/readdir.3.html &amp;lt;code&amp;gt;readdir(3)&amp;lt;/code&amp;gt;] and relate them to inode numbers;&lt;br /&gt;
# describe the layout of an ELF executable and find a program header, such as &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt;, in it.&lt;br /&gt;
&lt;br /&gt;
== System call wrappers ==&lt;br /&gt;
&lt;br /&gt;
In the last lab, we called every system call through the generic [https://man7.org/linux/man-pages/man2/syscall.2.html &amp;lt;code&amp;gt;syscall(2)&amp;lt;/code&amp;gt;] function, to see the system call numbers at work. In practice, this is very rarely done: for each system call, the GNU C library (&amp;#039;&amp;#039;glibc&amp;#039;&amp;#039;) provides a small C function with the same name and the same arguments, which only calls the syscall function with the appropriate number.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! System call !! glibc wrapper&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;syscall(SYS_write, fd, buf, count)&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;write(fd, buf, count)&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;syscall(SYS_read, fd, buf, count)&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;read(fd, buf, count)&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;syscall(SYS_close, fd)&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;close(fd)&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;syscall(SYS_mmap, addr, length, prot, flags, fd, offset)&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;mmap(addr, length, prot, flags, fd, offset)&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
The wrappers handle errors in the same way as [https://man7.org/linux/man-pages/man2/syscall.2.html &amp;lt;code&amp;gt;syscall(2)&amp;lt;/code&amp;gt;]: on failure they return &amp;lt;code&amp;gt;-1&amp;lt;/code&amp;gt; (or another special value, as we will see for [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;]) and set &amp;lt;code&amp;gt;errno&amp;lt;/code&amp;gt;. From now on, we will use the wrappers.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Not every function in glibc is a thin wrapper. [https://man7.org/linux/man-pages/man3/printf.3.html &amp;lt;code&amp;gt;printf(3)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man3/puts.3.html &amp;lt;code&amp;gt;puts(3)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man3/fopen.3.html &amp;lt;code&amp;gt;fopen(3)&amp;lt;/code&amp;gt;] belong to the C standard I/O library (&amp;#039;&amp;#039;stdio&amp;#039;&amp;#039;), which keeps its own buffers in user space and calls [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] only from time to time. In the labs, we will aim to talk to the kernel directly, and will use only the thin wrappers.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Files ==&lt;br /&gt;
&lt;br /&gt;
A &amp;#039;&amp;#039;&amp;#039;file&amp;#039;&amp;#039;&amp;#039; is an array of bytes, identified by an &amp;#039;&amp;#039;&amp;#039;inode&amp;#039;&amp;#039;&amp;#039;, and found by a name in a &amp;#039;&amp;#039;&amp;#039;directory&amp;#039;&amp;#039;&amp;#039;. The same system calls are used for regular files, for devices (such as the terminal) and for other kinds of files, which we will meet in future lessons.&lt;br /&gt;
&lt;br /&gt;
=== open(2) and close(2) ===&lt;br /&gt;
&lt;br /&gt;
A program cannot use a file by its name directly. It first asks the kernel to &amp;#039;&amp;#039;&amp;#039;open&amp;#039;&amp;#039;&amp;#039; it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;fcntl.h&amp;gt;&lt;br /&gt;
int open(const char *pathname, int flags, ... /* mode_t mode */);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The kernel finds the file, checks the permissions, and records the open file in a table of the process. It returns a small integer, the &amp;#039;&amp;#039;&amp;#039;file descriptor&amp;#039;&amp;#039;&amp;#039;, which identifies the open file in all the following system calls. When the program is done with it, it releases the file descriptor with:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
int close(int fd);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Every process starts with three file descriptors already open, inherited from the program that started it (usually the shell):&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! File descriptor !! Constant !! Name&lt;br /&gt;
|-&lt;br /&gt;
| 0 || &amp;lt;code&amp;gt;STDIN_FILENO&amp;lt;/code&amp;gt; || Standard input&lt;br /&gt;
|-&lt;br /&gt;
| 1 || &amp;lt;code&amp;gt;STDOUT_FILENO&amp;lt;/code&amp;gt; || Standard output&lt;br /&gt;
|-&lt;br /&gt;
| 2 || &amp;lt;code&amp;gt;STDERR_FILENO&amp;lt;/code&amp;gt; || Standard error&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_3_-_fd_table.png|center|thumb|700px|Each process has a table of file descriptors. Each entry points to an open file in the kernel, which records the current offset and the access mode, and points to the file itself.]]&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;flags&amp;lt;/code&amp;gt; argument must contain exactly one of the access modes &amp;lt;code&amp;gt;O_RDONLY&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;O_WRONLY&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;O_RDWR&amp;lt;/code&amp;gt;, optionally combined (with &amp;lt;code&amp;gt;|&amp;lt;/code&amp;gt;) with other flags:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Flag !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_RDONLY&amp;lt;/code&amp;gt; || Open for reading only&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_WRONLY&amp;lt;/code&amp;gt; || Open for writing only&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_RDWR&amp;lt;/code&amp;gt; || Open for reading and writing&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_CREAT&amp;lt;/code&amp;gt; || Create the file if it does not exist. Requires the third argument, &amp;lt;code&amp;gt;mode&amp;lt;/code&amp;gt;, with the permissions of the new file (for example &amp;lt;code&amp;gt;0644&amp;lt;/code&amp;gt;)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_EXCL&amp;lt;/code&amp;gt; || Together with &amp;lt;code&amp;gt;O_CREAT&amp;lt;/code&amp;gt;: fail with &amp;lt;code&amp;gt;EEXIST&amp;lt;/code&amp;gt; if the file already exists&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_TRUNC&amp;lt;/code&amp;gt; || If the file exists, cut its size to 0&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;O_APPEND&amp;lt;/code&amp;gt; || Every write goes to the end of the file&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
For example, the shell runs &amp;lt;code&amp;gt;echo hi &amp;gt; notes.txt&amp;lt;/code&amp;gt; by opening the file with &amp;lt;code&amp;gt;open(&amp;quot;notes.txt&amp;quot;, O_WRONLY | O_CREAT | O_TRUNC, 0644)&amp;lt;/code&amp;gt;, and &amp;lt;code&amp;gt;echo hi &amp;gt;&amp;gt; notes.txt&amp;lt;/code&amp;gt; with &amp;lt;code&amp;gt;O_APPEND&amp;lt;/code&amp;gt; instead of &amp;lt;code&amp;gt;O_TRUNC&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;fcntl.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(int argc, char **argv)&lt;br /&gt;
{&lt;br /&gt;
    if (argc != 2) {&lt;br /&gt;
        const char usage[] = &amp;quot;Usage: app FILE\n&amp;quot;;&lt;br /&gt;
        write(STDERR_FILENO, usage, strlen(usage));&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    int fd = open(argv[1], O_RDONLY);&lt;br /&gt;
    if (fd == -1) {&lt;br /&gt;
        print_error(argv[1]);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;Opened %s as file descriptor %d\n&amp;quot;, argv[1], fd);&lt;br /&gt;
    write(STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
&lt;br /&gt;
    close(fd);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app notes.txt&lt;br /&gt;
Opened notes.txt as file descriptor 3&lt;br /&gt;
$ ./build/debug/app nope&lt;br /&gt;
nope: No such file or directory&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== mmap(2) ===&lt;br /&gt;
&lt;br /&gt;
There are two ways for a program to get to the data in a file. The first is the &amp;#039;&amp;#039;&amp;#039;transparent&amp;#039;&amp;#039;&amp;#039; one: the kernel makes the file appear in the virtual memory of the process, and the program uses it like any other memory. This is done with [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;sys/mman.h&amp;gt;&lt;br /&gt;
void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);&lt;br /&gt;
int munmap(void *addr, size_t length);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Parameter !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;addr&amp;lt;/code&amp;gt; || A hint for where to place the mapping. Use &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt;, and let the kernel choose&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;length&amp;lt;/code&amp;gt; || The number of bytes to map. The kernel maps whole pages, so it is rounded up to a multiple of the page size&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;prot&amp;lt;/code&amp;gt; || What the program may do with the memory: &amp;lt;code&amp;gt;PROT_READ&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;PROT_WRITE&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;PROT_EXEC&amp;lt;/code&amp;gt;, combined with &amp;lt;code&amp;gt;|&amp;lt;/code&amp;gt;, or &amp;lt;code&amp;gt;PROT_NONE&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;flags&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;MAP_PRIVATE&amp;lt;/code&amp;gt;: writes to the memory stay in this process and never reach the file. &amp;lt;code&amp;gt;MAP_SHARED&amp;lt;/code&amp;gt;: writes go to the file, and other processes mapping it see them&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;fd&amp;lt;/code&amp;gt; || The open file to map. It must have been opened for reading&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;offset&amp;lt;/code&amp;gt; || Where in the file the mapping starts. Must be a multiple of the page size&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
On success, [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] returns the address of the first mapped byte. On failure, it returns &amp;lt;code&amp;gt;MAP_FAILED&amp;lt;/code&amp;gt; (which is &amp;lt;code&amp;gt;(void *) -1&amp;lt;/code&amp;gt;, &amp;#039;&amp;#039;&amp;#039;not&amp;#039;&amp;#039;&amp;#039; &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt;) and sets &amp;lt;code&amp;gt;errno&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_3_-_mmap_file.png|center|thumb|650px|[https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] makes the file appear in virtual memory: &amp;lt;code&amp;gt;p[i]&amp;lt;/code&amp;gt; is the byte at offset &amp;lt;code&amp;gt;i&amp;lt;/code&amp;gt; in the file. The pages are read from the disk only when the program first touches them.]]&lt;br /&gt;
&lt;br /&gt;
To map the whole file, we need to know its size. We will look at [https://man7.org/linux/man-pages/man2/lseek.2.html &amp;lt;code&amp;gt;lseek(2)&amp;lt;/code&amp;gt;] in detail below, together with [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;]. For now, it is enough to know that &amp;lt;code&amp;gt;lseek(fd, 0, SEEK_END)&amp;lt;/code&amp;gt; returns the size of the file.&lt;br /&gt;
&lt;br /&gt;
The following program prints a file, by mapping it into memory and writing the memory to the standard output:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;fcntl.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;sys/mman.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(int argc, char **argv)&lt;br /&gt;
{&lt;br /&gt;
    if (argc != 2) {&lt;br /&gt;
        const char usage[] = &amp;quot;Usage: app FILE\n&amp;quot;;&lt;br /&gt;
        write(STDERR_FILENO, usage, strlen(usage));&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    int fd = open(argv[1], O_RDONLY);&lt;br /&gt;
    if (fd == -1) {&lt;br /&gt;
        print_error(argv[1]);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    // The offset of the end of the file is its size.&lt;br /&gt;
    off_t size = lseek(fd, 0, SEEK_END);&lt;br /&gt;
    if (size == -1) {&lt;br /&gt;
        print_error(&amp;quot;lseek&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    char *p = mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0);&lt;br /&gt;
    if (p == MAP_FAILED) {&lt;br /&gt;
        print_error(&amp;quot;mmap&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    // The mapping stays valid after the file descriptor is closed.&lt;br /&gt;
    close(fd);&lt;br /&gt;
&lt;br /&gt;
    // The whole file is now an array of bytes in memory.&lt;br /&gt;
    write(STDOUT_FILENO, p, size);&lt;br /&gt;
&lt;br /&gt;
    munmap(p, size);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; A mapping cannot be empty: [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] of an empty file fails with &amp;lt;code&amp;gt;EINVAL&amp;lt;/code&amp;gt; (&amp;#039;&amp;#039;Invalid argument&amp;#039;&amp;#039;).&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; The size of a file can be changed with [https://man7.org/linux/man-pages/man2/truncate.2.html &amp;lt;code&amp;gt;truncate(2)&amp;lt;/code&amp;gt;], given its path, or [https://man7.org/linux/man-pages/man2/ftruncate.2.html &amp;lt;code&amp;gt;ftruncate(2)&amp;lt;/code&amp;gt;], given a file descriptor open for writing:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
int truncate(const char *path, off_t length);&lt;br /&gt;
int ftruncate(int fd, off_t length);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Mapping a file is especially convenient for files with a binary structure: a pointer into the mapping can be cast to a pointer to a C &amp;lt;code&amp;gt;struct&amp;lt;/code&amp;gt;, and the fields read directly, as we will do with the ELF file below.&lt;br /&gt;
&lt;br /&gt;
=== Anonymous mmap(2) ===&lt;br /&gt;
&lt;br /&gt;
With the &amp;lt;code&amp;gt;MAP_ANONYMOUS&amp;lt;/code&amp;gt; flag, [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] maps no file at all. The &amp;lt;code&amp;gt;fd&amp;lt;/code&amp;gt; argument must be &amp;lt;code&amp;gt;-1&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;offset&amp;lt;/code&amp;gt; must be 0, and the kernel gives the process new memory, filled with zeros:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;sys/mman.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    size_t size = 1024 * 1024; // 1 MiB&lt;br /&gt;
&lt;br /&gt;
    char *buf = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);&lt;br /&gt;
    if (buf == MAP_FAILED) {&lt;br /&gt;
        char msg[256];&lt;br /&gt;
        snprintf(msg, sizeof msg, &amp;quot;mmap: %s\n&amp;quot;, strerror(errno));&lt;br /&gt;
        write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    // The new memory is filled with zeros.&lt;br /&gt;
    snprintf(buf, size, &amp;quot;Got %zu bytes at %p, the last one is %d\n&amp;quot;, size, (void *) buf, buf[size - 1]);&lt;br /&gt;
    write(STDOUT_FILENO, buf, strlen(buf));&lt;br /&gt;
&lt;br /&gt;
    munmap(buf, size);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
Got 1048576 bytes at 0xffff98360000, the last one is 0&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is how the program gets memory from the kernel: [https://man7.org/linux/man-pages/man3/malloc.3.html &amp;lt;code&amp;gt;malloc(3)&amp;lt;/code&amp;gt;] itself uses anonymous mappings for large allocations (by default, 128 KiB and more), and carves the smaller ones out of bigger regions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; The kernel only reserves the virtual addresses at first. A physical page is given to the process the first time it touches each page, so a mapping of 1 GiB that is never used costs almost nothing.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== read(2), write(2) and lseek(2) ===&lt;br /&gt;
&lt;br /&gt;
The second way to get to the data in a file is the &amp;#039;&amp;#039;&amp;#039;explicit&amp;#039;&amp;#039;&amp;#039; one: the program provides a buffer in its own memory, and asks the kernel to copy data from the file into it, or from it into the file.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
ssize_t read(int fd, void *buf, size_t count);&lt;br /&gt;
ssize_t write(int fd, const void *buf, size_t count);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] copies at most &amp;lt;code&amp;gt;count&amp;lt;/code&amp;gt; bytes from the file into &amp;lt;code&amp;gt;buf&amp;lt;/code&amp;gt;, and returns the number of bytes it copied:&lt;br /&gt;
&lt;br /&gt;
* a positive number, which may be &amp;#039;&amp;#039;&amp;#039;less&amp;#039;&amp;#039;&amp;#039; than &amp;lt;code&amp;gt;count&amp;lt;/code&amp;gt;: for a regular file, only near its end; for a terminal or a pipe, whenever less data is available;&lt;br /&gt;
* &amp;lt;code&amp;gt;0&amp;lt;/code&amp;gt;, at the end of the file;&lt;br /&gt;
* &amp;lt;code&amp;gt;-1&amp;lt;/code&amp;gt;, on error.&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;] works the same way in the other direction. It may also write fewer bytes than asked (for example, when the disk is full), in which case the program must call it again for the rest.&lt;br /&gt;
&lt;br /&gt;
Each open file has a &amp;#039;&amp;#039;&amp;#039;current offset&amp;#039;&amp;#039;&amp;#039;: the position in the file where the next [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] or [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;] starts. It begins at 0 when the file is opened, and every [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] or [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;] moves it forward by the number of bytes it copied. The program can also move it explicitly:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
off_t lseek(int fd, off_t offset, int whence);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! &amp;lt;code&amp;gt;whence&amp;lt;/code&amp;gt; !! The new offset is&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SEEK_SET&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;offset&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SEEK_CUR&amp;lt;/code&amp;gt; || the current offset + &amp;lt;code&amp;gt;offset&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SEEK_END&amp;lt;/code&amp;gt; || the size of the file + &amp;lt;code&amp;gt;offset&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man2/lseek.2.html &amp;lt;code&amp;gt;lseek(2)&amp;lt;/code&amp;gt;] returns the new offset. This is why &amp;lt;code&amp;gt;lseek(fd, 0, SEEK_END)&amp;lt;/code&amp;gt;, which we used in the [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] example above, returns the size of the file.&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_3_-_file_offset.png|center|thumb|525px|The current offset of an open file: [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] moves it forward by the number of bytes it read, and [https://man7.org/linux/man-pages/man2/lseek.2.html &amp;lt;code&amp;gt;lseek(2)&amp;lt;/code&amp;gt;] sets it directly.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; The offset belongs to the open file, not to the file itself (see the file descriptor table above). Two [https://man7.org/linux/man-pages/man2/open.2.html &amp;lt;code&amp;gt;open(2)&amp;lt;/code&amp;gt;] calls on the same file give two independent offsets.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The following program prints a file, like the [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] example above, this time copying it in pieces of up to 4 KiB, until [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] reports the end of the file:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;fcntl.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(int argc, char **argv)&lt;br /&gt;
{&lt;br /&gt;
    if (argc != 2) {&lt;br /&gt;
        const char usage[] = &amp;quot;Usage: app FILE\n&amp;quot;;&lt;br /&gt;
        write(STDERR_FILENO, usage, strlen(usage));&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    int fd = open(argv[1], O_RDONLY);&lt;br /&gt;
    if (fd == -1) {&lt;br /&gt;
        print_error(argv[1]);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    char buf[4096];&lt;br /&gt;
    ssize_t n;&lt;br /&gt;
    while ((n = read(fd, buf, sizeof buf)) &amp;gt; 0) {&lt;br /&gt;
        if (write(STDOUT_FILENO, buf, n) == -1) {&lt;br /&gt;
            print_error(&amp;quot;write&amp;quot;);&lt;br /&gt;
            return EXIT_FAILURE;&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    if (n == -1) {&lt;br /&gt;
        print_error(&amp;quot;read&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    close(fd);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Unlike the [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] version, this one also works for an empty file. Like the [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;] version, it fails on a directory: &amp;lt;code&amp;gt;read: Is a directory&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=== readdir(3) ===&lt;br /&gt;
&lt;br /&gt;
As we saw in the course, a &amp;#039;&amp;#039;&amp;#039;directory&amp;#039;&amp;#039;&amp;#039; is a special file which maps names to &amp;#039;&amp;#039;&amp;#039;inode numbers&amp;#039;&amp;#039;&amp;#039;. Its entries are not read with [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;], but with the [https://man7.org/linux/man-pages/man2/getdents64.2.html &amp;lt;code&amp;gt;getdents64(2)&amp;lt;/code&amp;gt;] system call, which fills a buffer with as many entries as fit. &amp;#039;&amp;#039;glibc&amp;#039;&amp;#039; provides the following interface on top of it:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;dirent.h&amp;gt;&lt;br /&gt;
DIR *opendir(const char *name);&lt;br /&gt;
struct dirent *readdir(DIR *dirp);&lt;br /&gt;
int closedir(DIR *dirp);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[https://man7.org/linux/man-pages/man3/opendir.3.html &amp;lt;code&amp;gt;opendir(3)&amp;lt;/code&amp;gt;] opens the directory and returns a &amp;lt;code&amp;gt;DIR&amp;lt;/code&amp;gt; structure, which holds the file descriptor and a buffer of entries. Each call to [https://man7.org/linux/man-pages/man3/readdir.3.html &amp;lt;code&amp;gt;readdir(3)&amp;lt;/code&amp;gt;] returns the next entry, calling [https://man7.org/linux/man-pages/man2/getdents64.2.html &amp;lt;code&amp;gt;getdents64(2)&amp;lt;/code&amp;gt;] again when the buffer runs out, and returns &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt; after the last one.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;dirent.h&amp;gt; (simplified)&lt;br /&gt;
struct dirent {&lt;br /&gt;
    ino_t d_ino;             // The inode number&lt;br /&gt;
    off_t d_off;             // Used internally&lt;br /&gt;
    unsigned short d_reclen; // Used internally&lt;br /&gt;
    unsigned char d_type;    // The type of the file&lt;br /&gt;
    char d_name[256];        // The name, &amp;#039;\0&amp;#039;-terminated&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_3_-_dirent.png|center|thumb|600px|A directory is a list of (name, inode number) entries. Each call to [https://man7.org/linux/man-pages/man3/readdir.3.html &amp;lt;code&amp;gt;readdir(3)&amp;lt;/code&amp;gt;] returns the next one, in the order the file system keeps them.]]&lt;br /&gt;
&lt;br /&gt;
The entries come in the order the file system stores them, which is not alphabetical, and include &amp;lt;code&amp;gt;.&amp;lt;/code&amp;gt; (the directory itself) and &amp;lt;code&amp;gt;..&amp;lt;/code&amp;gt; (its parent). The &amp;lt;code&amp;gt;d_type&amp;lt;/code&amp;gt; field holds one of &amp;lt;code&amp;gt;DT_REG&amp;lt;/code&amp;gt; (regular file), &amp;lt;code&amp;gt;DT_DIR&amp;lt;/code&amp;gt; (directory), &amp;lt;code&amp;gt;DT_LNK&amp;lt;/code&amp;gt; (symbolic link), &amp;lt;code&amp;gt;DT_FIFO&amp;lt;/code&amp;gt; (pipe), &amp;lt;code&amp;gt;DT_CHR&amp;lt;/code&amp;gt; (character device), &amp;lt;code&amp;gt;DT_BLK&amp;lt;/code&amp;gt; (block device), &amp;lt;code&amp;gt;DT_SOCK&amp;lt;/code&amp;gt; (socket), or &amp;lt;code&amp;gt;DT_UNKNOWN&amp;lt;/code&amp;gt; if the file system does not provide it.&lt;br /&gt;
&lt;br /&gt;
The following program prints the names in the current directory:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
#include &amp;lt;dirent.h&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
static void print_error(const char *what)&lt;br /&gt;
{&lt;br /&gt;
    char msg[256];&lt;br /&gt;
    snprintf(msg, sizeof msg, &amp;quot;%s: %s\n&amp;quot;, what, strerror(errno));&lt;br /&gt;
    write(STDERR_FILENO, msg, strlen(msg));&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    DIR *dir = opendir(&amp;quot;.&amp;quot;);&lt;br /&gt;
    if (dir == nullptr) {&lt;br /&gt;
        print_error(&amp;quot;.&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    struct dirent *entry;&lt;br /&gt;
    errno = 0;&lt;br /&gt;
    while ((entry = readdir(dir)) != nullptr) {&lt;br /&gt;
        write(STDOUT_FILENO, entry-&amp;gt;d_name, strlen(entry-&amp;gt;d_name));&lt;br /&gt;
        write(STDOUT_FILENO, &amp;quot;\n&amp;quot;, 1);&lt;br /&gt;
    }&lt;br /&gt;
    // nullptr means either &amp;quot;no more entries&amp;quot; or an error: only an error sets errno.&lt;br /&gt;
    if (errno != 0) {&lt;br /&gt;
        print_error(&amp;quot;readdir&amp;quot;);&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    closedir(dir);&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; &amp;lt;code&amp;gt;ls&amp;lt;/code&amp;gt; sorts the names before printing them. &amp;lt;code&amp;gt;ls -f&amp;lt;/code&amp;gt; prints them unsorted, in the same order as the program above.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To check inode numbers from the shell, use &amp;lt;code&amp;gt;ls -i&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;stat&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ls -i notes.txt&lt;br /&gt;
645260 notes.txt&lt;br /&gt;
$ stat -c &amp;#039;%i %n&amp;#039; notes.txt&lt;br /&gt;
645260 notes.txt&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== The ELF file ==&lt;br /&gt;
&lt;br /&gt;
Executable files and shared libraries on Linux use the &amp;#039;&amp;#039;&amp;#039;ELF&amp;#039;&amp;#039;&amp;#039; format (&amp;#039;&amp;#039;Executable and Linkable Format&amp;#039;&amp;#039;). It is a binary format, described by the structures in &amp;lt;code&amp;gt;&amp;amp;lt;elf.h&amp;amp;gt;&amp;lt;/code&amp;gt;. We will only look at the parts the kernel needs to start a program.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ readelf -h build/debug/app    # the ELF header&lt;br /&gt;
$ readelf -l build/debug/app    # the program headers&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== The ELF header ===&lt;br /&gt;
&lt;br /&gt;
Every ELF file starts with the &amp;#039;&amp;#039;&amp;#039;ELF header&amp;#039;&amp;#039;&amp;#039;, at offset 0:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;elf.h&amp;gt; (simplified)&lt;br /&gt;
typedef struct {&lt;br /&gt;
    unsigned char e_ident[16]; // &amp;quot;\x7f&amp;quot; &amp;quot;ELF&amp;quot;, then the class, byte order, ...&lt;br /&gt;
    uint16_t e_type;           // Executable, shared library, ...&lt;br /&gt;
    uint16_t e_machine;        // The architecture: x86-64, AArch64, RISC-V, ...&lt;br /&gt;
    uint32_t e_version;&lt;br /&gt;
    uint64_t e_entry;          // The entry point (see the last lab)&lt;br /&gt;
    uint64_t e_phoff;          // File offset of the program header table&lt;br /&gt;
    uint64_t e_shoff;          // File offset of the section header table&lt;br /&gt;
    uint32_t e_flags;&lt;br /&gt;
    uint16_t e_ehsize;         // Size of this header&lt;br /&gt;
    uint16_t e_phentsize;      // Size of one program header&lt;br /&gt;
    uint16_t e_phnum;          // Number of program headers&lt;br /&gt;
    uint16_t e_shentsize;&lt;br /&gt;
    uint16_t e_shnum;&lt;br /&gt;
    uint16_t e_shstrndx;&lt;br /&gt;
} Elf64_Ehdr;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The first 4 bytes are always &amp;lt;code&amp;gt;0x7f&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;&amp;#039;E&amp;#039;&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;&amp;#039;L&amp;#039;&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;&amp;#039;F&amp;#039;&amp;lt;/code&amp;gt;. The next byte, &amp;lt;code&amp;gt;e_ident[EI_CLASS]&amp;lt;/code&amp;gt;, is &amp;lt;code&amp;gt;ELFCLASS64&amp;lt;/code&amp;gt; for 64-bit programs.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ readelf -h build/debug/app&lt;br /&gt;
ELF Header:&lt;br /&gt;
  Magic:   7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00&lt;br /&gt;
  Class:                             ELF64&lt;br /&gt;
  ...&lt;br /&gt;
  Machine:                           AArch64&lt;br /&gt;
  ...&lt;br /&gt;
  Start of program headers:          64 (bytes into file)&lt;br /&gt;
  ...&lt;br /&gt;
  Size of program headers:           56 (bytes)&lt;br /&gt;
  Number of program headers:         10&lt;br /&gt;
  ...&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== The program headers ===&lt;br /&gt;
&lt;br /&gt;
The &amp;#039;&amp;#039;&amp;#039;program header table&amp;#039;&amp;#039;&amp;#039; is an array of &amp;lt;code&amp;gt;e_phnum&amp;lt;/code&amp;gt; entries, each &amp;lt;code&amp;gt;e_phentsize&amp;lt;/code&amp;gt; bytes long, starting at offset &amp;lt;code&amp;gt;e_phoff&amp;lt;/code&amp;gt; in the file. Each entry describes a &amp;#039;&amp;#039;&amp;#039;segment&amp;#039;&amp;#039;&amp;#039;: a range of bytes in the file and what the kernel should do with it.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;elf.h&amp;gt;&lt;br /&gt;
typedef struct {&lt;br /&gt;
    uint32_t p_type;   // The kind of segment: PT_LOAD, PT_INTERP, ...&lt;br /&gt;
    uint32_t p_flags;  // Permissions: PF_R, PF_W, PF_X&lt;br /&gt;
    uint64_t p_offset; // Where the segment starts in the file&lt;br /&gt;
    uint64_t p_vaddr;  // Where it goes in virtual memory&lt;br /&gt;
    uint64_t p_paddr;  // Unused&lt;br /&gt;
    uint64_t p_filesz; // Its size in the file&lt;br /&gt;
    uint64_t p_memsz;  // Its size in memory (larger for .bss)&lt;br /&gt;
    uint64_t p_align;&lt;br /&gt;
} Elf64_Phdr;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Common segment types:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! &amp;lt;code&amp;gt;p_type&amp;lt;/code&amp;gt; !! Value !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;PT_LOAD&amp;lt;/code&amp;gt; || 1 || A range of the file to map into memory (&amp;lt;code&amp;gt;.text&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;.rodata&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;.data&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;.bss&amp;lt;/code&amp;gt;, ...)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;PT_DYNAMIC&amp;lt;/code&amp;gt; || 2 || Information for the dynamic loader: which shared libraries to load, ...&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; || 3 || The path of the program interpreter (the dynamic loader)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;PT_NOTE&amp;lt;/code&amp;gt; || 4 || Auxiliary information (for example, a unique build ID)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;PT_PHDR&amp;lt;/code&amp;gt; || 6 || The program header table itself&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
==== PT_INTERP ====&lt;br /&gt;
&lt;br /&gt;
As we saw in the [[OS_Lab_2_-_System_calls._The_initial_stack|last lab]], most programs are &amp;#039;&amp;#039;&amp;#039;dynamically linked&amp;#039;&amp;#039;&amp;#039;: the code of the libraries they use (such as &amp;#039;&amp;#039;glibc&amp;#039;&amp;#039;) is not in the executable file, and must be loaded when the program starts. When the kernel finds a &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; segment in a program, it also loads the program named there, the &amp;#039;&amp;#039;&amp;#039;dynamic loader&amp;#039;&amp;#039;&amp;#039;, and starts it instead of the program. The loader then loads the libraries and jumps to the program&amp;#039;s entry point.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; segment is a &amp;lt;code&amp;gt;&amp;#039;\0&amp;#039;&amp;lt;/code&amp;gt;-terminated string of &amp;lt;code&amp;gt;p_filesz&amp;lt;/code&amp;gt; bytes (the &amp;lt;code&amp;gt;&amp;#039;\0&amp;#039;&amp;lt;/code&amp;gt; included), at offset &amp;lt;code&amp;gt;p_offset&amp;lt;/code&amp;gt; in the file:&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_3_-_elf_interp.png|center|thumb|600px|Finding &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt;: the ELF header gives the position of the program header table, and the &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; entry gives the position of the string.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ readelf -l build/debug/app&lt;br /&gt;
...&lt;br /&gt;
Program Headers:&lt;br /&gt;
  Type           Offset             VirtAddr           PhysAddr&lt;br /&gt;
                 FileSiz            MemSiz              Flags  Align&lt;br /&gt;
  PHDR           0x0000000000000040 0x0000000000000040 0x0000000000000040&lt;br /&gt;
                 0x0000000000000230 0x0000000000000230  R      0x8&lt;br /&gt;
  INTERP         0x0000000000000294 0x0000000000000294 0x0000000000000294&lt;br /&gt;
                 0x000000000000001b 0x000000000000001b  R      0x1&lt;br /&gt;
      [Requesting program interpreter: /lib/ld-linux-aarch64.so.1]&lt;br /&gt;
...&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
On x86-64, the dynamic loader is &amp;lt;code&amp;gt;/lib64/ld-linux-x86-64.so.2&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; Statically linked programs contain all the library code they need, and have no &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; segment: the kernel jumps directly to their entry point.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Exercises ==&lt;br /&gt;
&lt;br /&gt;
Write each program in its own copy of the project template. As a reminder from [[OS_Lab_1_-_Linux_setup._Bash_primer._C_primer#getting-the-template|the first lab]]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
mkdir -p ~/oslab &amp;amp;&amp;amp; cd ~/oslab&lt;br /&gt;
curl -OL https://wiki.dcae.pub.ro/images/9/93/Os_lab_skeleton.zip&lt;br /&gt;
unzip -d lab03 Os_lab_skeleton.zip&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use a new directory name instead of &amp;lt;code&amp;gt;interp_mmap&amp;lt;/code&amp;gt; for each exercise.&lt;br /&gt;
&lt;br /&gt;
For this lab:&lt;br /&gt;
&lt;br /&gt;
* Use the &amp;#039;&amp;#039;glibc&amp;#039;&amp;#039; wrappers for the system calls ([https://man7.org/linux/man-pages/man2/open.2.html &amp;lt;code&amp;gt;open(2)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man2/lseek.2.html &amp;lt;code&amp;gt;lseek(2)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;], ...), instead of [https://man7.org/linux/man-pages/man2/syscall.2.html &amp;lt;code&amp;gt;syscall(2)&amp;lt;/code&amp;gt;].&lt;br /&gt;
* Do not use the standard I/O library: no &amp;lt;code&amp;gt;FILE&amp;lt;/code&amp;gt;, [https://man7.org/linux/man-pages/man3/printf.3.html &amp;lt;code&amp;gt;printf(3)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man3/puts.3.html &amp;lt;code&amp;gt;puts(3)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man3/fopen.3.html &amp;lt;code&amp;gt;fopen(3)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man3/fread.3.html &amp;lt;code&amp;gt;fread(3)&amp;lt;/code&amp;gt;] and so on. [https://man7.org/linux/man-pages/man3/snprintf.3.html &amp;lt;code&amp;gt;snprintf(3)&amp;lt;/code&amp;gt;] is still fine, and recommended, for building a string that you then [https://man7.org/linux/man-pages/man2/write.2.html &amp;lt;code&amp;gt;write(2)&amp;lt;/code&amp;gt;].&lt;br /&gt;
* [https://man7.org/linux/man-pages/man3/opendir.3.html &amp;lt;code&amp;gt;opendir(3)&amp;lt;/code&amp;gt;], [https://man7.org/linux/man-pages/man3/readdir.3.html &amp;lt;code&amp;gt;readdir(3)&amp;lt;/code&amp;gt;] and [https://man7.org/linux/man-pages/man3/closedir.3.html &amp;lt;code&amp;gt;closedir(3)&amp;lt;/code&amp;gt;] should be used for exercise C.&lt;br /&gt;
&lt;br /&gt;
=== A. PT_INTERP with mmap(2) ===&lt;br /&gt;
&lt;br /&gt;
Print the path of the dynamic loader of your own program. Open the executable file, using &amp;lt;code&amp;gt;argv[0]&amp;lt;/code&amp;gt; as its path, map the whole file into memory with [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;], then walk the program headers to find the &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; segment, and print its string.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
/lib/ld-linux-aarch64.so.1&lt;br /&gt;
$ readelf -l build/debug/app | grep interpreter&lt;br /&gt;
      [Requesting program interpreter: /lib/ld-linux-aarch64.so.1]&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your output will be different on x86-64.&lt;br /&gt;
&lt;br /&gt;
* Cast the start of the mapping to &amp;lt;code&amp;gt;const Elf64_Ehdr *&amp;lt;/code&amp;gt;. The program headers are an array of &amp;lt;code&amp;gt;Elf64_Phdr&amp;lt;/code&amp;gt; at &amp;lt;code&amp;gt;e_phoff&amp;lt;/code&amp;gt; bytes from the start.&lt;br /&gt;
* Check that the file starts with &amp;lt;code&amp;gt;[0x7f, &amp;#039;E&amp;#039;, &amp;#039;L&amp;#039;, &amp;#039;F&amp;#039;]&amp;lt;/code&amp;gt; before looking further.&lt;br /&gt;
* If there is no &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; segment, say so on standard error and exit with status 1.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Extra:&amp;#039;&amp;#039;&amp;#039; &amp;lt;code&amp;gt;argv[0]&amp;lt;/code&amp;gt; is not always trustworthy as the location of the executable. Where does the kernel offer us this information direcly?&lt;br /&gt;
&lt;br /&gt;
=== B. PT_INTERP with read(2) and lseek(2) ===&lt;br /&gt;
&lt;br /&gt;
Write the same program again, without [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;]-ing the file: read the ELF header with [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;], then use [https://man7.org/linux/man-pages/man2/lseek.2.html &amp;lt;code&amp;gt;lseek(2)&amp;lt;/code&amp;gt;] to move to the program headers and read them, and finally move to the &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; segment and read the string. The two programs must print the same thing.&lt;br /&gt;
&lt;br /&gt;
* The size of the program header table is only known at run time (&amp;lt;code&amp;gt;e_phnum * e_phentsize&amp;lt;/code&amp;gt; bytes). Allocate the buffer for it with an anonymous [https://man7.org/linux/man-pages/man2/mmap.2.html &amp;lt;code&amp;gt;mmap(2)&amp;lt;/code&amp;gt;], and [https://man7.org/linux/man-pages/man2/munmap.2.html &amp;lt;code&amp;gt;munmap(2)&amp;lt;/code&amp;gt;] it when you are done.&lt;br /&gt;
* [https://man7.org/linux/man-pages/man2/read.2.html &amp;lt;code&amp;gt;read(2)&amp;lt;/code&amp;gt;] may return fewer bytes than you asked for. Check that you got everything you need: for a regular file, getting less means the file is shorter than its headers say.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Extra:&amp;#039;&amp;#039;&amp;#039; compare the system calls the two versions make, with &amp;lt;code&amp;gt;strace ./build/debug/app&amp;lt;/code&amp;gt; (install it with &amp;lt;code&amp;gt;sudo apt install strace&amp;lt;/code&amp;gt;). The ones at the start belong to the dynamic loader and to &amp;#039;&amp;#039;glibc&amp;#039;&amp;#039;; look for &amp;lt;code&amp;gt;openat&amp;lt;/code&amp;gt; and what comes after it.&lt;br /&gt;
&lt;br /&gt;
=== C. Inode numbers with readdir(3) ===&lt;br /&gt;
&lt;br /&gt;
Write a command which takes the name of a file in the current working directory and prints its inode number. Find it by reading the directory with [https://man7.org/linux/man-pages/man3/readdir.3.html &amp;lt;code&amp;gt;readdir(3)&amp;lt;/code&amp;gt;], not with [https://man7.org/linux/man-pages/man2/stat.2.html &amp;lt;code&amp;gt;stat(2)&amp;lt;/code&amp;gt;].&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ echo hi &amp;gt; notes.txt&lt;br /&gt;
$ ./build/debug/app notes.txt&lt;br /&gt;
645260&lt;br /&gt;
$ ls -i notes.txt&lt;br /&gt;
645260 notes.txt&lt;br /&gt;
$ ./build/debug/app nope&lt;br /&gt;
nope: No such file or directory&lt;br /&gt;
$ echo $?&lt;br /&gt;
1&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to look at:&lt;br /&gt;
&lt;br /&gt;
* Make a hard link with &amp;lt;code&amp;gt;ln notes.txt other.txt&amp;lt;/code&amp;gt; and a symbolic link with &amp;lt;code&amp;gt;ln -s notes.txt link.txt&amp;lt;/code&amp;gt;. What inode numbers do they have, and why?&lt;br /&gt;
* What are the inode numbers of &amp;lt;code&amp;gt;.&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;..&amp;lt;/code&amp;gt;?&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Extra:&amp;#039;&amp;#039;&amp;#039; also print the type of the file, from &amp;lt;code&amp;gt;d_type&amp;lt;/code&amp;gt;: &amp;lt;code&amp;gt;regular file&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;directory&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;symbolic link&amp;lt;/code&amp;gt;, ...&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Operating_Systems&amp;diff=8424</id>
		<title>Operating Systems</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Operating_Systems&amp;diff=8424"/>
		<updated>2026-10-23T07:26:16Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: /* Lab Sessions */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Lab Sessions ==&lt;br /&gt;
&lt;br /&gt;
* Lab 1 - [[OS Lab 1 - Linux setup. Bash primer. C primer]]&lt;br /&gt;
* Lab 2 - [[OS Lab 2 - System calls. The initial stack]]&lt;br /&gt;
* Lab 3 - [[OS Lab 3 - Files. Memory mapping]]&lt;br /&gt;
&lt;br /&gt;
=== Old Lab Sessions (2025) ===&lt;br /&gt;
&lt;br /&gt;
* Lab 1 - [[OS Lab 1 - Installing Linux]]&lt;br /&gt;
* Lab 2 - [[OS Lab 2 - Linux Filesystems]]&lt;br /&gt;
* Lab 3 - [[OS Lab 3 - Processes and Jobs]]&lt;br /&gt;
* Lab 4 - [[OS Lab 4 - Users, Groups and Permissions]]&lt;br /&gt;
* Lab 5 - [[OS Lab 5 - Bash Scripting]]&lt;br /&gt;
* Lab 6 - [[OS Lab 6 - Inter Process Communication]]&lt;br /&gt;
* Lab 7 - [[OS Lab 7 - The Network Subsystem]]&lt;br /&gt;
* Lab 8 - [[OS Lab 8 - Transport and Security]]&lt;br /&gt;
* Lab 9 - [[OS Lab 9 - Application Protocols: DNS, SSH, HTTP(S)]]&lt;br /&gt;
* Lab 10 - [[OS Lab 10 - Containers and Docker]]&lt;br /&gt;
* Lab 11 - [[OS Lab 11 - Linux Kernel Modules]]&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_3_-_mmap_file.png&amp;diff=8423</id>
		<title>Fișier:OS Lab 3 - mmap file.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_3_-_mmap_file.png&amp;diff=8423"/>
		<updated>2026-10-23T07:24:57Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_3_-_file_offset.png&amp;diff=8422</id>
		<title>Fișier:OS Lab 3 - file offset.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_3_-_file_offset.png&amp;diff=8422"/>
		<updated>2026-10-23T07:24:43Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_3_-_fd_table.png&amp;diff=8421</id>
		<title>Fișier:OS Lab 3 - fd table.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_3_-_fd_table.png&amp;diff=8421"/>
		<updated>2026-10-23T07:24:31Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_3_-_elf_interp.png&amp;diff=8420</id>
		<title>Fișier:OS Lab 3 - elf interp.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_3_-_elf_interp.png&amp;diff=8420"/>
		<updated>2026-10-23T07:24:18Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_3_-_dirent.png&amp;diff=8419</id>
		<title>Fișier:OS Lab 3 - dirent.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_3_-_dirent.png&amp;diff=8419"/>
		<updated>2026-10-23T07:24:06Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=FPGA_Student_Classroom_tutorial&amp;diff=8411</id>
		<title>FPGA Student Classroom tutorial</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=FPGA_Student_Classroom_tutorial&amp;diff=8411"/>
		<updated>2026-10-22T14:17:26Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: /* Step 3 - VNC */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== FPGA Student Classroom Access Tutorial ==&lt;br /&gt;
&lt;br /&gt;
This is a guide that aims to show how to connect to the classroom resources remotely, in order to access the software and hardware resources (FPGAs) available at the university. The goal is to create a remote desktop session to one of the computers in the lab. This session can then be used to run software (e.g., Vivado) and to program hardware FPGAs.&lt;br /&gt;
&lt;br /&gt;
Before you can connect to the classroom cluster, you will need to obtain the following from a system administrator:&lt;br /&gt;
&lt;br /&gt;
* A VPN configuration file (e.g., a415-myname.conf)&lt;br /&gt;
* A username and password&lt;br /&gt;
* An assigned workstation and FPGA board (e.g., station07 &amp;amp; pynq07)&lt;br /&gt;
&lt;br /&gt;
The connection process consists of the following steps:&lt;br /&gt;
&lt;br /&gt;
# Connect via VPN to the cluster network.&lt;br /&gt;
# Connect to your workstation via SSH and create a remote desktop (VNC) instance.&lt;br /&gt;
# Connect to the remote desktop instance.&lt;br /&gt;
&lt;br /&gt;
== Step 1 - VPN ==&lt;br /&gt;
&lt;br /&gt;
To connect to the cluster network via VPN, you will need the provided VPN configuration file (e.g., a415-myname.conf) (ask your system administrator if you don&amp;#039;t have it) and a WireGuard VPN client.&lt;br /&gt;
&lt;br /&gt;
For a full guide on how to use the WireGuard VPN, check [https://wiki.dcae.pub.ro/index.php/VPN_Tutorial_-_en this page].&lt;br /&gt;
&lt;br /&gt;
== Step 2 - SSH ==&lt;br /&gt;
&lt;br /&gt;
In order to connect to your workstation via SSH to open the remote desktop instance, you will need a terminal application or a dedicated SSH client.&lt;br /&gt;
&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Windows 11&amp;#039;&amp;#039;&amp;#039; comes with Windows Terminal. Windows 10 users can download the [https://apps.microsoft.com/detail/9n0dx20hk701 Windows Terminal] from the Microsoft Store or use the older Command Prompt application.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;macOS&amp;#039;&amp;#039;&amp;#039; has a pre-installed Terminal application. [https://iterm2.com/ iTerm2] is a popular community alternative with more features.&lt;br /&gt;
&lt;br /&gt;
First, connect to the workstation using the following command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
ssh myname@station07&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this is your first time logging in, you will be prompted to change your initial password:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
(myname@station07) Password: &lt;br /&gt;
Password expired. Change your password now.&lt;br /&gt;
(myname@station07) Current Password: &lt;br /&gt;
(myname@station07) New password: &lt;br /&gt;
(myname@station07) Retype new password:&lt;br /&gt;
&lt;br /&gt;
myname@station07:~$&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Replace &amp;lt;code&amp;gt;myname&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;station07&amp;lt;/code&amp;gt; with your assigned username and workstation.&lt;br /&gt;
&lt;br /&gt;
Once connected, set up VNC settings with:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
arh-setup-vnc-config&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You only need to set VNC settings once for your account.&lt;br /&gt;
&lt;br /&gt;
Afterwards, you can launch the VNC server:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
tigervncserver -localhost no&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this is your first time starting a VNC instance, you will be prompted to set a password. You will also need to note the &amp;#039;&amp;#039;&amp;#039;VNC port&amp;#039;&amp;#039;&amp;#039; and &amp;#039;&amp;#039;&amp;#039;X display number&amp;#039;&amp;#039;&amp;#039; from the output. If you forget these numbers, you can retrieve them with:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
tigervncserver -list&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To stop the VNC session, use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
tigervncserver -kill :3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Replace &amp;lt;code&amp;gt;:3&amp;lt;/code&amp;gt; with your actual X display number.&lt;br /&gt;
&lt;br /&gt;
== Step 3 - VNC ==&lt;br /&gt;
&lt;br /&gt;
To connect to your workstation using VNC, you will need a VNC client. &amp;#039;&amp;#039;&amp;#039;TigerVNC&amp;#039;&amp;#039;&amp;#039; is a popular choice, though others like RealVNC, TightVNC, and Remmina are also available.&lt;br /&gt;
&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Windows:&amp;#039;&amp;#039;&amp;#039; Download TigerVNC from [https://sourceforge.net/projects/tigervnc/files/stable/1.15.0/ here].&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;macOS:&amp;#039;&amp;#039;&amp;#039; Download TigerVNC from [https://tigervnc.macupdate.com/ here].&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Linux:&amp;#039;&amp;#039;&amp;#039; Install TigerVNC via Flatpak:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
flatpak install flathub org.tigervnc.vncviewer&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Once installed, enter your workstation name followed by a colon and the VNC port (e.g., &amp;lt;code&amp;gt;station07:5903&amp;lt;/code&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
[[File:Tigervnc.png|Enter your workstation and port here.]]&lt;br /&gt;
&lt;br /&gt;
Click &amp;#039;&amp;#039;&amp;#039;Connect&amp;#039;&amp;#039;&amp;#039;, then enter your &amp;#039;&amp;#039;&amp;#039;VNC session password&amp;#039;&amp;#039;&amp;#039; (not your account password).&lt;br /&gt;
&lt;br /&gt;
[[File:TigerVNC_password.png|Enter your VNC password here.]]&lt;br /&gt;
&lt;br /&gt;
If successful, you will see your remote desktop.&lt;br /&gt;
&lt;br /&gt;
[[File:GNOME_desktop.png|You are now connected!]]&lt;br /&gt;
&lt;br /&gt;
You can now open a terminal and launch Vivado:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
vivado&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:Vivado_open.png|Vivado running on remote desktop.]]&lt;br /&gt;
&lt;br /&gt;
== FAQ ==&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Q: I cannot connect to my VNC session.&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
&lt;br /&gt;
A: Connect via SSH and check with `vncserver -list`. Ensure the VNC server was started with `-localhost no`.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Q: I cannot connect via SSH; my workstation appears to be powered off.&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
&lt;br /&gt;
A: Some students turn off the stations despite instructions. Contact a system administrator to power it on remotely.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Q: I can connect to VNC, but I see a login screen and an &amp;quot;Authentication error&amp;quot; message.&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
&lt;br /&gt;
A: This is a [https://askubuntu.com/questions/1224957/i-cannot-log-in-a-vnc-session-after-the-screen-locks-authentification-error known bug] in TigerVNC. While connected via VNC, open an SSH session and run&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
loginctl list-sessions&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
to see the open sessions. Identify your session and run&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
loginctl unlock-session &amp;lt;session-id&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
replacing session-id with the id of your session.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039; Q: Is there any fix for the login screen bug? &amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
&lt;br /&gt;
A: Run this command in a SSH connection (different terminal):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
gsettings set org.gnome.desktop.session idle-delay 0&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=FPGA_Student_Classroom_tutorial&amp;diff=8410</id>
		<title>FPGA Student Classroom tutorial</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=FPGA_Student_Classroom_tutorial&amp;diff=8410"/>
		<updated>2026-10-22T14:14:11Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: /* Step 2 - SSH */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== FPGA Student Classroom Access Tutorial ==&lt;br /&gt;
&lt;br /&gt;
This is a guide that aims to show how to connect to the classroom resources remotely, in order to access the software and hardware resources (FPGAs) available at the university. The goal is to create a remote desktop session to one of the computers in the lab. This session can then be used to run software (e.g., Vivado) and to program hardware FPGAs.&lt;br /&gt;
&lt;br /&gt;
Before you can connect to the classroom cluster, you will need to obtain the following from a system administrator:&lt;br /&gt;
&lt;br /&gt;
* A VPN configuration file (e.g., a415-myname.conf)&lt;br /&gt;
* A username and password&lt;br /&gt;
* An assigned workstation and FPGA board (e.g., station07 &amp;amp; pynq07)&lt;br /&gt;
&lt;br /&gt;
The connection process consists of the following steps:&lt;br /&gt;
&lt;br /&gt;
# Connect via VPN to the cluster network.&lt;br /&gt;
# Connect to your workstation via SSH and create a remote desktop (VNC) instance.&lt;br /&gt;
# Connect to the remote desktop instance.&lt;br /&gt;
&lt;br /&gt;
== Step 1 - VPN ==&lt;br /&gt;
&lt;br /&gt;
To connect to the cluster network via VPN, you will need the provided VPN configuration file (e.g., a415-myname.conf) (ask your system administrator if you don&amp;#039;t have it) and a WireGuard VPN client.&lt;br /&gt;
&lt;br /&gt;
For a full guide on how to use the WireGuard VPN, check [https://wiki.dcae.pub.ro/index.php/VPN_Tutorial_-_en this page].&lt;br /&gt;
&lt;br /&gt;
== Step 2 - SSH ==&lt;br /&gt;
&lt;br /&gt;
In order to connect to your workstation via SSH to open the remote desktop instance, you will need a terminal application or a dedicated SSH client.&lt;br /&gt;
&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;Windows 11&amp;#039;&amp;#039;&amp;#039; comes with Windows Terminal. Windows 10 users can download the [https://apps.microsoft.com/detail/9n0dx20hk701 Windows Terminal] from the Microsoft Store or use the older Command Prompt application.&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;macOS&amp;#039;&amp;#039;&amp;#039; has a pre-installed Terminal application. [https://iterm2.com/ iTerm2] is a popular community alternative with more features.&lt;br /&gt;
&lt;br /&gt;
First, connect to the workstation using the following command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
ssh myname@station07&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this is your first time logging in, you will be prompted to change your initial password:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
(myname@station07) Password: &lt;br /&gt;
Password expired. Change your password now.&lt;br /&gt;
(myname@station07) Current Password: &lt;br /&gt;
(myname@station07) New password: &lt;br /&gt;
(myname@station07) Retype new password:&lt;br /&gt;
&lt;br /&gt;
myname@station07:~$&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Replace &amp;lt;code&amp;gt;myname&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;station07&amp;lt;/code&amp;gt; with your assigned username and workstation.&lt;br /&gt;
&lt;br /&gt;
Once connected, set up VNC settings with:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
arh-setup-vnc-config&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You only need to set VNC settings once for your account.&lt;br /&gt;
&lt;br /&gt;
Afterwards, you can launch the VNC server:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
tigervncserver -localhost no&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If this is your first time starting a VNC instance, you will be prompted to set a password. You will also need to note the &amp;#039;&amp;#039;&amp;#039;VNC port&amp;#039;&amp;#039;&amp;#039; and &amp;#039;&amp;#039;&amp;#039;X display number&amp;#039;&amp;#039;&amp;#039; from the output. If you forget these numbers, you can retrieve them with:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
tigervncserver -list&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To stop the VNC session, use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
tigervncserver -kill :3&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Replace &amp;lt;code&amp;gt;:3&amp;lt;/code&amp;gt; with your actual X display number.&lt;br /&gt;
&lt;br /&gt;
== Step 3 - VNC ==&lt;br /&gt;
&lt;br /&gt;
To connect to your workstation using VNC, you will need a VNC client. **TigerVNC** is a popular choice, though others like RealVNC, TightVNC, and Remmina are also available.&lt;br /&gt;
&lt;br /&gt;
* **Windows:** Download TigerVNC from [https://sourceforge.net/projects/tigervnc/files/stable/1.15.0/ here].&lt;br /&gt;
* **macOS:** Download TigerVNC from [https://tigervnc.macupdate.com/ here].&lt;br /&gt;
* **Linux:** Install TigerVNC via Flatpak:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
flatpak install flathub org.tigervnc.vncviewer&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Once installed, enter your workstation name followed by a colon and the VNC port (e.g., `station07:5903`).&lt;br /&gt;
&lt;br /&gt;
[[File:Tigervnc.png|Enter your workstation and port here.]]&lt;br /&gt;
&lt;br /&gt;
Click **Connect**, then enter your **VNC session password** (not your account password).&lt;br /&gt;
&lt;br /&gt;
[[File:TigerVNC_password.png|Enter your VNC password here.]]&lt;br /&gt;
&lt;br /&gt;
If successful, you will see your remote desktop.&lt;br /&gt;
&lt;br /&gt;
[[File:GNOME_desktop.png|You are now connected!]]&lt;br /&gt;
&lt;br /&gt;
You can now open a terminal and launch Vivado:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
vivado&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:Vivado_open.png|Vivado running on remote desktop.]]&lt;br /&gt;
&lt;br /&gt;
== FAQ ==&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Q: I cannot connect to my VNC session.&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
&lt;br /&gt;
A: Connect via SSH and check with `vncserver -list`. Ensure the VNC server was started with `-localhost no`.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Q: I cannot connect via SSH; my workstation appears to be powered off.&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
&lt;br /&gt;
A: Some students turn off the stations despite instructions. Contact a system administrator to power it on remotely.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Q: I can connect to VNC, but I see a login screen and an &amp;quot;Authentication error&amp;quot; message.&amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
&lt;br /&gt;
A: This is a [https://askubuntu.com/questions/1224957/i-cannot-log-in-a-vnc-session-after-the-screen-locks-authentification-error known bug] in TigerVNC. While connected via VNC, open an SSH session and run&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
loginctl list-sessions&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
to see the open sessions. Identify your session and run&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
loginctl unlock-session &amp;lt;session-id&amp;gt;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
replacing session-id with the id of your session.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039; Q: Is there any fix for the login screen bug? &amp;#039;&amp;#039;&amp;#039;&lt;br /&gt;
&lt;br /&gt;
A: Run this command in a SSH connection (different terminal):&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
gsettings set org.gnome.desktop.session idle-delay 0&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Circuite_Integrate_Digitale_2&amp;diff=8409</id>
		<title>Circuite Integrate Digitale 2</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Circuite_Integrate_Digitale_2&amp;diff=8409"/>
		<updated>2026-10-22T11:37:39Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: /* Platforme laborator */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Platforme laborator ==&lt;br /&gt;
&lt;br /&gt;
* [[Media:CID2_lab_1_2.pdf|Platformă lab 1+2]]&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Circuite_Integrate_Digitale_2&amp;diff=8408</id>
		<title>Circuite Integrate Digitale 2</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Circuite_Integrate_Digitale_2&amp;diff=8408"/>
		<updated>2026-10-22T11:37:06Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: /* Platforme laborator */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Platforme laborator ==&lt;br /&gt;
&lt;br /&gt;
* [[Media:CID2_lab_1_2.pdf]]&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:CID2_lab_1_2.pdf&amp;diff=8407</id>
		<title>Fișier:CID2 lab 1 2.pdf</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:CID2_lab_1_2.pdf&amp;diff=8407"/>
		<updated>2026-10-22T11:36:43Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Circuite_Integrate_Digitale_2&amp;diff=8406</id>
		<title>Circuite Integrate Digitale 2</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Circuite_Integrate_Digitale_2&amp;diff=8406"/>
		<updated>2026-10-22T11:33:44Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: Pagină nouă: == Platforme laborator ==&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Platforme laborator ==&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Pagina_principal%C4%83&amp;diff=8405</id>
		<title>Pagina principală</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Pagina_principal%C4%83&amp;diff=8405"/>
		<updated>2026-10-22T11:32:40Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: /* Platforme de aplicatii sau laborator */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Scopul acestei pagini este de a centraliza platformele de laborator dar și toate resursele auxiliare pentru cursurile și laboratoarele ținute în cadrul departamentului de Dispozitive, Circuite și Arhitecturi Electronice. &lt;br /&gt;
&lt;br /&gt;
== Materiale de curs ==&lt;br /&gt;
* [[Programarea Calculatoarelor (curs seria C,F)|Programarea Calculatoarelor]]&lt;br /&gt;
* [[Circuite Integrate Digitale (curs)|Circuite Integrate Digitale]]&lt;br /&gt;
* [[Dispozitive Semiconductoare de Putere (curs)|Dispozitive Semiconductoare de Putere]]&lt;br /&gt;
* [[Structuri de Date și Algoritmi (curs)|Structuri de Date și Algoritmi]]&lt;br /&gt;
* [[Senzori si Circuite de Conditionare a Semnalelor (curs)|Senzori si Circuite de Conditionare a Semnalelor]]&lt;br /&gt;
&amp;lt;!--* [[Programarea Calculatoarelor (curs)|Programarea Calculatoarelor]]--&amp;gt;&lt;br /&gt;
* [[Programare Orientată Obiect (curs)|Programare Orientată Obiect]]&lt;br /&gt;
* [[Tehnici de proiectare VLSI (curs)|Tehnici de proiectare VLSI]]&lt;br /&gt;
&lt;br /&gt;
== Platforme de aplicatii sau laborator ==&lt;br /&gt;
* [[Arhitectura Sistemelor de Calcul]]&lt;br /&gt;
* [[Circuite Integrate Analogice (laborator)|Circuite Integrate Analogice]]&lt;br /&gt;
* [[Circuite Integrate Digitale | Circuite Integrate Digitale]] &amp;lt;&amp;gt; [[Digital Integrated Circuits (app) | Digital Integrated Circuits (app)]]&lt;br /&gt;
* [[Circuite Integrate Digitale 2]]&lt;br /&gt;
* [[Electronica Digitala | Electronica Digitala]]&lt;br /&gt;
* [[Dispozitive Semiconductoare de Putere (laborator)|Dispozitive Semiconductoare de Putere]]&lt;br /&gt;
* [[Dispozitive Electronice(laborator)|Dispozitive Electronice]]&lt;br /&gt;
* [[Circuite Electronice(laborator)|Circuite Electronice]]&lt;br /&gt;
* [[Programare Orientată Obiect (Java)]]&lt;br /&gt;
* [[Programare Orientată pe Obiecte (C++)]]&lt;br /&gt;
* [[Structuri de Date și Algoritmi]]&lt;br /&gt;
* [[Senzori si Circuite de Conditionare a Semnalelor (laborator)|SCCS]]&lt;br /&gt;
* [[Programarea Calculatoarelor (laborator)|Programarea Calculatoarelor]]&lt;br /&gt;
* [[Tehnici de proiectare VLSI (laborator)|Tehnici de proiectare VLSI]]&lt;br /&gt;
* [[Performance analysis and optimization]]&lt;br /&gt;
* [https://users.dcae.pub.ro/~zhascsi/courses/dsd/dsd.html Digital Systems Design Project]&lt;br /&gt;
* [[Reconfigurable Computing]]&lt;br /&gt;
* [[Operating Systems]]&lt;br /&gt;
* [[Python Project]]&lt;br /&gt;
&lt;br /&gt;
== Materiale vechi CID ==&lt;br /&gt;
* [[Circuite Integrate Digitale (2023)]]&lt;br /&gt;
* [[Circuite_Integrate_Digitale_(2021)|Circuite Integrate Digitale (2021)]]&lt;br /&gt;
* [[Circuite integrate digitale (seminar)|Circuite Integrate Digitale]] * [[Digital Integrated Circuits (seminar)|Digital Integrated Circuits]]&lt;br /&gt;
* [[Circuite Integrate Digitale (laborator)|Circuite Integrate Digitale]] * [[Digital Integrated Circuits (lab)|Digital Integrated Circuits]]&lt;br /&gt;
&lt;br /&gt;
== Materiale pentru proiecte ==&lt;br /&gt;
* [[Project SCCS - Senzori si Circuite de Conditionare a Semnalelor]]&lt;br /&gt;
* [[Proiect 1 - Dispozitive si Circuite Electronice|Dispozitive si Circuite Electronice]]&lt;br /&gt;
* [[ACES - Vivado remote run]]&lt;br /&gt;
&lt;br /&gt;
== Regulamente ==&lt;br /&gt;
* [[Regulament protectia muncii]]&lt;br /&gt;
* [[Regulamentul laboratoarelor POO și ASC]]&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=PC_Laborator_4&amp;diff=8404</id>
		<title>PC Laborator 4</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=PC_Laborator_4&amp;diff=8404"/>
		<updated>2026-10-20T09:00:11Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: /* Operator de negare be biți (BWNOT) */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Obiective ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Familiarizarea cu noțiunile de bază ale limbajului C: tipuri de date numerice, operatori aritmetici, operatori pe biți dar și folosirea corectă a acestora.&lt;br /&gt;
&lt;br /&gt;
== Tipuri de date numerice ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;&amp;lt;font color=&amp;quot;red&amp;quot;&amp;gt; Observatie:&amp;lt;/font&amp;gt;&amp;#039;&amp;#039;&amp;#039; Bit-ul reprezintă cea mai mică unitate de informaţie dintr-un calculator. Denumirea de bit provine de la „binary digit” adică număr binar. Sistemul binar este un sistem de numeraţie unde totul se reprezintă doar cu 1 şi 0. Simbolul pentru un bit este &amp;quot;b&amp;quot;,a nu se confunda cu byte &amp;quot;B&amp;quot; care reprezintă o grupare de 8 biți.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Tipuri de date întregi ===&lt;br /&gt;
&lt;br /&gt;
Tipurile de date întregi fundamentale ale limbajului C sunt &amp;lt;code&amp;gt;char&amp;lt;/code&amp;gt; și &amp;lt;code&amp;gt;int&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;&amp;lt;font color=&amp;quot;red&amp;quot;&amp;gt; Observatie:&amp;lt;/font&amp;gt;&amp;#039;&amp;#039;&amp;#039; Specificația limbajul C nu forțează tipurile de date să aibă o dimensiune fixă. Prin urmare ele pot avea diferite limite, în funcție de procesor și compilator. De aici înainte, toate dimensiunile specificate sunt pentru compilatorul GCC ce rulează pe un procesor compatibil x86, pe 64 de biți.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! colspan=&amp;quot;3&amp;quot; | Tipuri fundamentale&lt;br /&gt;
|-&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; |Tip&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; |Număr de biți&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; |Domeniu&lt;br /&gt;
|-&lt;br /&gt;
| char&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | 8&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | -128 ... +127&lt;br /&gt;
|-&lt;br /&gt;
| int&lt;br /&gt;
| style=&amp;quot;text-align: center&amp;quot; | 32&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | -2,147,483,648	... +2,147,483,647&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
 Tipurile fundamentale pot fi precedate de diferiţi modificatori. Un &amp;#039;&amp;#039;&amp;#039;modificator&amp;#039;&amp;#039;&amp;#039; se utilizează pentru a adapta cât mai convenabil tipul de bază la situație.&lt;br /&gt;
&lt;br /&gt;
==== Modificatori ====&lt;br /&gt;
&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;signed&amp;#039;&amp;#039;&amp;#039; (implicit) - tip de dată cu semn, utilizabil excusiv pentru numere întregi, face ca intervalul de definiție să fie între [-2&amp;lt;sup&amp;gt;n-1&amp;lt;/sup&amp;gt;:2&amp;lt;sup&amp;gt;n-1&amp;lt;/sup&amp;gt;-1];&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;unsigned&amp;#039;&amp;#039;&amp;#039; - tip de dată fără semn, utilizabil excusiv pentru numere întregi, face ca intervalul de definiție să fie între [0:2&amp;lt;sup&amp;gt;n&amp;lt;/sup&amp;gt;-1];&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;long&amp;#039;&amp;#039;&amp;#039; - de obicei, dublează domeniul de definiție pentru &amp;#039;&amp;#039;&amp;#039;int&amp;#039;&amp;#039;&amp;#039;; de exemplu un &amp;#039;&amp;#039;&amp;#039;long int&amp;#039;&amp;#039;&amp;#039; va avea 64 de biți în loc de 32;&lt;br /&gt;
* &amp;#039;&amp;#039;&amp;#039;short&amp;#039;&amp;#039;&amp;#039; - de obicei, înjumătățește domeniul de definiție pentru &amp;#039;&amp;#039;&amp;#039;int&amp;#039;&amp;#039;&amp;#039;, adică rezultatul este un tip de dată pe 16 biți.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! colspan=&amp;quot;3&amp;quot; | Folosirea modificatorilor&lt;br /&gt;
|-&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; |Tip&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; |Număr de biți&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; |Domeniu&lt;br /&gt;
|-&lt;br /&gt;
| unsigned char&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | 8&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | 0 ... 255&lt;br /&gt;
|-&lt;br /&gt;
| unsigned long int&lt;br /&gt;
| style=&amp;quot;text-align: center&amp;quot; | 64&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | 0 .. 18,446,744,073,709,551,615 &lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
 Diferenţa dintre întregii signed şi unsigned constă în interpretarea diferită a bitului semnificativ (adică cel mai din stânga).  &lt;br /&gt;
 Pentru un întreg signed, se va considera bitul semnificativ ca fiind bit de semn. Dacă acest bit este 0 atunci numărul este pozitiv iar dacă este 1 atunci este negativ.&lt;br /&gt;
 Modul de reprezentare a valorilor negative se face folosind convenția complement față de 2.&lt;br /&gt;
&lt;br /&gt;
=== Tipuri în virgulă mobilă ===&lt;br /&gt;
&lt;br /&gt;
Tipurile de date în virgulă mobilă ale limbajului C sunt &amp;lt;code&amp;gt;float&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;double&amp;lt;/code&amp;gt; și &amp;lt;code&amp;gt;long double&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! colspan=&amp;quot;3&amp;quot; | Tipuri fundamentale&lt;br /&gt;
|-&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; |Tip&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; |Număr de biți&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; |Domeniu&lt;br /&gt;
|-&lt;br /&gt;
| float&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | 32&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | Precizie 4 zecimale&lt;br /&gt;
|-&lt;br /&gt;
| double&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | 64&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | Precizie 8 zecimale&lt;br /&gt;
|-&lt;br /&gt;
| long double&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | 80&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | Precizie 16 zecimale&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;&amp;lt;font color=&amp;quot;red&amp;quot;&amp;gt; Observatie:&amp;lt;/font&amp;gt;&amp;#039;&amp;#039;&amp;#039; Principalul dezavantaj al reprezentării în virgulă fixă este faptul că, dacă un număr nu mai încape în spaţiul de biţi rezervat, se pierd cifrele cele mai semnificative.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Un număr este reprezentat în virgulă mobilă printr-un cuvant de n biți conținând semn, mantisă și exponent sub următoarea formă:&lt;br /&gt;
&lt;br /&gt;
[[Fișier:Mantisa.jpg]]&lt;br /&gt;
&lt;br /&gt;
Unde &amp;lt;code&amp;gt;s&amp;lt;/code&amp;gt; este bitul de semn al numărului, cu aceeași convenție ca pentru numere în virgulă fixă (s=0 număr pozitiv și s=1 număr negativ), &amp;lt;code&amp;gt;m&amp;lt;/code&amp;gt; este mantisa numărului, reprezentând cifrele semnificative, iar &amp;lt;code&amp;gt;e&amp;lt;/code&amp;gt; este exponentul (puterea la care trebuie ridicată baza).&lt;br /&gt;
&lt;br /&gt;
Valoarea numărului fracționar reprezentat în virgulă mobilă este data de expresia:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;math&amp;gt;valoare=-1^s \times m \times baza^e&amp;lt;/math&amp;gt; &lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;&amp;lt;font color=&amp;quot;red&amp;quot;&amp;gt; Observatie:&amp;lt;/font&amp;gt;&amp;#039;&amp;#039;&amp;#039; Mantisa trebuie să îndeplinească condiția: &amp;lt;math&amp;gt;1 &amp;gt; m \geqslant 1 / baza&amp;lt;/math&amp;gt; &amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Tipuri de date de dimensiune fixă în standardul C99 ==&lt;br /&gt;
&lt;br /&gt;
Deoarece există situații când numărul de biți pentru un anumit tip de dată este extrem de important, iar acest număr diferă între procesoare și compilatoare, standardul C99 a introdus următoarele tipuri de date, de dimensiune fixă, care se găsesc în header-ul &amp;lt;code style=&amp;quot;color: blue&amp;quot;&amp;gt;stdint.h&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! colspan=&amp;quot;3&amp;quot; | Tipuri de dimensiune fixă&lt;br /&gt;
|-&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; |Tip&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; |Numar de biti&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; |Domeniu&lt;br /&gt;
|-&lt;br /&gt;
| int8_t&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | 8&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | -128 .. +127&lt;br /&gt;
|-&lt;br /&gt;
| uint8_t&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | 8&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | 0 .. 255&lt;br /&gt;
|-&lt;br /&gt;
| int16_t&lt;br /&gt;
| style=&amp;quot;text-align: center&amp;quot; | 16&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | -32,768 ... +32,767&lt;br /&gt;
|-&lt;br /&gt;
| uint16_t&lt;br /&gt;
| style=&amp;quot;text-align: center&amp;quot; | 16&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | 0 ... +65,535 &lt;br /&gt;
|-&lt;br /&gt;
| int32_t&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | 32&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | -2,147,483,648 .. 2,147,483,647&lt;br /&gt;
|-&lt;br /&gt;
| uint32_t&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | 32&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | 0 .. 4,294,967,295&lt;br /&gt;
|-&lt;br /&gt;
| int64_t&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | 64&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | -9,223,372,036,854,775,808 .. 9,223,372,036,854,775,807&lt;br /&gt;
|-&lt;br /&gt;
| uint64_t&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | 64&lt;br /&gt;
| style=&amp;quot;text-align: center;&amp;quot; | 0 .. 18,446,744,073,709,551,615&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;sfat&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;&amp;lt;font color=&amp;quot;blue&amp;quot;&amp;gt;Recomandare:&amp;lt;/font&amp;gt;&amp;#039;&amp;#039;&amp;#039; Utilizați tipurile de date de dimensiune fixă pentru valorile numerice întregi, tipul de date &amp;#039;&amp;#039;&amp;#039;char&amp;#039;&amp;#039;&amp;#039; pentru a stoca un caracter și tipurile &amp;#039;&amp;#039;&amp;#039;float&amp;#039;&amp;#039;&amp;#039;, &amp;#039;&amp;#039;&amp;#039;double&amp;#039;&amp;#039;&amp;#039; și &amp;#039;&amp;#039;&amp;#039;long double&amp;#039;&amp;#039;&amp;#039; pentru valorile numerice fracționare.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Operatori ==&lt;br /&gt;
&lt;br /&gt;
=== Operatorii aritmetici ===&lt;br /&gt;
* &amp;lt;code&amp;gt;+&amp;lt;/code&amp;gt;  adunarea &lt;br /&gt;
* &amp;lt;code&amp;gt;-&amp;lt;/code&amp;gt;  scăderea &lt;br /&gt;
* &amp;lt;code&amp;gt;*&amp;lt;/code&amp;gt;  înmulţirea &lt;br /&gt;
* &amp;lt;code&amp;gt;/&amp;lt;/code&amp;gt;  împărţirea (rezultatul împărţirii pentru numere reale, câtul împărţirii pentru numere întregi)&lt;br /&gt;
* &amp;lt;code&amp;gt;%&amp;lt;/code&amp;gt;  modulo (restul împărţirii a două numere întregi)&lt;br /&gt;
* &amp;lt;code&amp;gt;++&amp;lt;/code&amp;gt; incrementarea (mărirea unei valori cu o unitate)&lt;br /&gt;
* &amp;lt;code&amp;gt;--&amp;lt;/code&amp;gt; decrementarea (micşorarea unei valori cu o unitate)&lt;br /&gt;
&lt;br /&gt;
Operatorii de incrementare/decrementare sunt folosiţi pentru creșterea/micşorarea unei valori cu o unitate.&lt;br /&gt;
 a++ / ++a - incrementare&lt;br /&gt;
 a-- / --a - decrementare&lt;br /&gt;
De asemenea se pot folosi instrucțiuni de pre sau post incrementare/decrementare.&lt;br /&gt;
  &amp;#039;&amp;#039;&amp;#039;POST-incrementare: x = a++;&amp;#039;&amp;#039;&amp;#039; &amp;lt;syntaxhighlight lang=&amp;quot;C&amp;quot;&amp;gt;&lt;br /&gt;
x = a; &lt;br /&gt;
a = a + 1;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  &amp;#039;&amp;#039;&amp;#039;PRE-incremenatare: x = ++a;&amp;#039;&amp;#039;&amp;#039; &amp;lt;syntaxhighlight lang=&amp;quot;C&amp;quot;&amp;gt;&lt;br /&gt;
a = a + 1;&lt;br /&gt;
x = a;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Operatori la nivel de bit ===&lt;br /&gt;
&lt;br /&gt;
Avem şase operatori la nivel de bit,aceștia se aplică tipurilor char,int,long signed/unsigned,iar rezultatul este un întreg.&lt;br /&gt;
Operatorii la nivel de bit sunt următorii.&lt;br /&gt;
* &amp;lt;code&amp;gt;~&amp;lt;/code&amp;gt; - negare la nivel de bit&lt;br /&gt;
* &amp;lt;code&amp;gt;&amp;amp;&amp;lt;/code&amp;gt; - AND (şi logic)&lt;br /&gt;
* &amp;lt;code&amp;gt;|&amp;lt;/code&amp;gt; - OR (sau logic)&lt;br /&gt;
* &amp;lt;code&amp;gt;^&amp;lt;/code&amp;gt; - XOR (sau exclusiv)&lt;br /&gt;
* &amp;lt;code&amp;gt;&amp;lt;&amp;lt;&amp;lt;/code&amp;gt; - deplasare la stânga&lt;br /&gt;
* &amp;lt;code&amp;gt;&amp;gt;&amp;gt;&amp;lt;/code&amp;gt; - deplasare la dreapta&lt;br /&gt;
&lt;br /&gt;
==== Operator de negare be biți (BWNOT) ====&lt;br /&gt;
Operatorul de negare realizează complementarea biților, biții de 0 se pun 1, iar biții de 1 se pun 0.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;C&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
int a = 2200;  /* 0....0 1000 1001 1000*/&lt;br /&gt;
a = ~a;        /* 1....1 0111 0110 0111*/ &lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Operatorul ȘI pe biți (BWAND) ====&lt;br /&gt;
Dorim să aflăm valoarea bitului de pe poziția 2 a numarului 20.Pentru a afla valorea acestui bit se poate realiza operația AND (&amp;amp;) între numărul dorit și un alt număr binar care are doar pe poziția dorită valoarea 1 (în cazul nostru poziția 2),astfel dacă rezultatul este diferit de 0 atunci inițial am avut bitul 1, respectiv 0 dacă bitul a fost 0.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|- bgcolor=&amp;quot;#ddeeff&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
|- bgcolor=&amp;quot;#ddeeff&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
| A || B || A AND B&lt;br /&gt;
|- bgcolor=&amp;quot;#ddffdd&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
|0 || 0 || 0&lt;br /&gt;
|- bgcolor=&amp;quot;#ddffdd&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
|0 || 1 || 0&lt;br /&gt;
|- bgcolor=&amp;quot;#ddffdd&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
|1 || 0 || 0&lt;br /&gt;
|- bgcolor=&amp;quot;#ddffdd&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
|1 || 1 || 1&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;C&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
int main() {&lt;br /&gt;
   int a = 20;  /*  0...0 1 0 1 0 0 */&lt;br /&gt;
   int b = 4;   /*  0...0 0 0 1 0 0 */&lt;br /&gt;
 &lt;br /&gt;
    if (a &amp;amp; b) {/*  0...0 0 0 1 0 0 */&lt;br /&gt;
        printf(&amp;quot;Rezultatul este diferit de 0\n&amp;quot;);&lt;br /&gt;
    } else {&lt;br /&gt;
        printf(&amp;quot;Rezultatul are valoarea 0\n&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    return 0;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Operatorul SAU pe biți (BWOR) ====&lt;br /&gt;
Dorim să setăm (în 1) valoarea bitului de pe poziția 2 a numarului 20. Pentru a seta valorea acestui bit se poate realiza operația OR (|) între numărul dorit și un alt număr binar care are doar pe poziția dorită valoarea 1 (în cazul nostru poziția 2).&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|- bgcolor=&amp;quot;#ddeeff&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
|- bgcolor=&amp;quot;#ddeeff&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
| A || B || A OR B&lt;br /&gt;
|- bgcolor=&amp;quot;#ddffdd&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
|0 || 0 || 0&lt;br /&gt;
|- bgcolor=&amp;quot;#ddffdd&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
|0 || 1 || 1&lt;br /&gt;
|- bgcolor=&amp;quot;#ddffdd&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
|1 || 0 || 1&lt;br /&gt;
|- bgcolor=&amp;quot;#ddffdd&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
|1 || 1 || 1&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;C&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
int main() {&lt;br /&gt;
   int a = 20;    /*  0...0 1 0 1 0 0 */&lt;br /&gt;
   int b = 4;     /*  0...0 0 0 1 0 0 */&lt;br /&gt;
   int c = a | b; /*  0...0 1 0 1 0 0*/&lt;br /&gt;
   return 0;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Operatorul SAU EXCLUSIV pe biți (BWXOR) ====&lt;br /&gt;
Dorim să schimbăm valoarea bitului de pe poziția 2 a numarului 20. Pentru a schimba valorea acestui bit se poate realiza operația XOR (^) între numărul dorit și un alt număr binar care are doar pe poziția dorită valoarea 1 (în cazul nostru poziția 2).&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
|- bgcolor=&amp;quot;#ddeeff&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
|- bgcolor=&amp;quot;#ddeeff&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
| A || B || A XOR B&lt;br /&gt;
|- bgcolor=&amp;quot;#ddffdd&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
|0 || 0 || 0&lt;br /&gt;
|- bgcolor=&amp;quot;#ddffdd&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
|0 || 1 || 1&lt;br /&gt;
|- bgcolor=&amp;quot;#ddffdd&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
|1 || 0 || 1&lt;br /&gt;
|- bgcolor=&amp;quot;#ddffdd&amp;quot; align=&amp;quot;center&amp;quot;&lt;br /&gt;
|1 || 1 || 0&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;C&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
int main() {&lt;br /&gt;
   int a = 20;    /*  0...0 1 0 1 0 0 */&lt;br /&gt;
   int b = 4;     /*  0...0 0 0 1 0 0 */&lt;br /&gt;
   int c = a ^ b; /*  0...0 1 0 0 0 0*/&lt;br /&gt;
   return 0;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Operatorul de deplasare la stânga ====&lt;br /&gt;
Operatorii de deplasare (&amp;lt;&amp;lt; şi &amp;gt;&amp;gt;) realizează deplasarea biţilor din operandul stâng cu atâtea poziţii câte sunt indicate de operandul drept.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;C&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
int a = 255;  /* 0...0 0000 1111 1111*/&lt;br /&gt;
a = a &amp;lt;&amp;lt; 3;   /* 0...0 0111 1111 1000*/ &lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;&amp;lt;font color=&amp;quot;red&amp;quot;&amp;gt; Observatie:&amp;lt;/font&amp;gt; &amp;#039;&amp;#039;&amp;#039;Deplasarea la stânga (&amp;lt;&amp;lt;) completează la dreapta cu 0, deci biţii din stânga se vor pierde.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Exerciții ==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt; Scrieți un program care să citească un număr în virgulă mobilă de la tastatură și să se afișeze, pe linii diferite, în hexazecimal, semnul, mantisa și exponentul. Notă: pentru a putea efectua operații pe biți, operanzii trebuie să fie de tip întreg. Astfel, pentru a interpreta un număr în virgulă mobilă ca secvență de biți, variabila trebuie sa fie de tip int, iar citirea să se facă cu template-ul &amp;quot;%f&amp;quot;.&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt; Scrieți un program care să citească de la tastatură un număr întreg fără semn pe 8 biți (în bază 10) și să-l afișeze pe ecran în baza doi, folosind operatori de shiftare și mascare.&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt; Citiți de la tastatură un număr întreg cu semn, pe 32 de biți, apoi negați-l aritmetic și afișați valoarea, fără să folosiți operatorului unar &amp;quot;-&amp;quot; (folosind regulile convenției complement față de 2).&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt; Scrieți un program care să citească un număr întreg pozitiv pe 8 biți de la tastatură, să numere și să afișeze câți biți de 1 și câți biți 0 are reprezentarea lui binară.&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt; Citiți de la tastatură un număr întreg n, calculați și afișați suma numerelor de la 0 la n.&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt; Citiți o valoare de temperatură în grade Celsius, și afișați pe ecran valoarea acelei temperaturi în Kelvin și grade Fahrenheit. &amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt; Fie o matrice de 8 linii și 10 coloane, cu elementele numerotate de la 0 (elementul din stânga sus) la 79 (elementul din dreapta jos):&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
  0  1  2  3  4  5  6  7  8  9&lt;br /&gt;
 10 11 12 13 14 15 16 17 18 19&lt;br /&gt;
 ...&lt;br /&gt;
 70 71 72 73 74 75 76 77 78 79&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
Dându-se de la tastatură un index n între 0 si 79, să se afișeze pe ce linie și pe ce coloană este indexul respectiv.&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;Dându-se un număr întreg de la tastatură, să se afișeze 0 dacă numărul este impar și 1 dacă este par.&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;Dându-se un număr întreg de la tastatură, să se afișeze restul împărțirii numărului la 16, folosind doar operații pe biți.&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;li&amp;gt;&amp;lt;code&amp;gt;dificil&amp;lt;/code&amp;gt; Folosind doar operații pe biți (fără construcții condiționale), să se calculeze modulul unui număr întreg pe 32 de biți, introdus de la tastatură.&amp;lt;/li&amp;gt;&lt;br /&gt;
&amp;lt;ol&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_2_-_auxv.png&amp;diff=8401</id>
		<title>Fișier:OS Lab 2 - auxv.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_2_-_auxv.png&amp;diff=8401"/>
		<updated>2026-10-16T13:49:36Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_2_-_environ.png&amp;diff=8400</id>
		<title>Fișier:OS Lab 2 - environ.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_2_-_environ.png&amp;diff=8400"/>
		<updated>2026-10-16T13:49:12Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_2_-_argv.png&amp;diff=8399</id>
		<title>Fișier:OS Lab 2 - argv.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_2_-_argv.png&amp;diff=8399"/>
		<updated>2026-10-16T13:47:48Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_2_-_initial_stack.png&amp;diff=8398</id>
		<title>Fișier:OS Lab 2 - initial stack.png</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=Fi%C8%99ier:OS_Lab_2_-_initial_stack.png&amp;diff=8398"/>
		<updated>2026-10-16T13:46:23Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
	<entry>
		<id>http://wiki.dcae.pub.ro/index.php?title=OS_Lab_2_-_System_calls._The_initial_stack&amp;diff=8397</id>
		<title>OS Lab 2 - System calls. The initial stack</title>
		<link rel="alternate" type="text/html" href="http://wiki.dcae.pub.ro/index.php?title=OS_Lab_2_-_System_calls._The_initial_stack&amp;diff=8397"/>
		<updated>2026-10-16T12:52:22Z</updated>

		<summary type="html">&lt;p&gt;Vserbu: /* Calling a system call */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;In [[OS_Lab_1_-_Linux_setup._Bash_primer._C_primer|the last lab]], we set up our Linux environment, learned the basics of bash and C, and saw that ordinary programs run in &amp;#039;&amp;#039;&amp;#039;user space&amp;#039;&amp;#039;&amp;#039; while the &amp;#039;&amp;#039;&amp;#039;Linux kernel&amp;#039;&amp;#039;&amp;#039; runs in &amp;#039;&amp;#039;&amp;#039;kernel space&amp;#039;&amp;#039;&amp;#039; and manages the hardware. In this lab, we will look closely at how a user-space program starts up, how it communicates with the kernel through &amp;#039;&amp;#039;&amp;#039;system calls&amp;#039;&amp;#039;&amp;#039;, and how it exits.&lt;br /&gt;
&lt;br /&gt;
== Learning objectives ==&lt;br /&gt;
&lt;br /&gt;
By the end of this lab you should be able to:&lt;br /&gt;
&lt;br /&gt;
# explain how a user-space program enters the kernel through a system call instruction and how system calls are multiplexed by number;&lt;br /&gt;
# invoke Linux system calls directly from C using &amp;lt;code&amp;gt;syscall()&amp;lt;/code&amp;gt; and handle errors via &amp;lt;code&amp;gt;errno&amp;lt;/code&amp;gt;;&lt;br /&gt;
# describe the memory regions of a loaded program (&amp;lt;code&amp;gt;.text&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;.rodata&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;.data&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;.bss&amp;lt;/code&amp;gt;, and the stack) and the steps that run before &amp;lt;code&amp;gt;main()&amp;lt;/code&amp;gt;;&lt;br /&gt;
# explain how command-line arguments (&amp;lt;code&amp;gt;argc&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;argv&amp;lt;/code&amp;gt;), environment variables (&amp;lt;code&amp;gt;environ&amp;lt;/code&amp;gt;), and the auxiliary vector (&amp;lt;code&amp;gt;auxv&amp;lt;/code&amp;gt;) are laid out on the initial stack and read them in C;&lt;br /&gt;
# explain what happens when a program terminates and the difference between the &amp;lt;code&amp;gt;exit()&amp;lt;/code&amp;gt; library function and the &amp;lt;code&amp;gt;SYS_exit&amp;lt;/code&amp;gt; system call.&lt;br /&gt;
&lt;br /&gt;
== System calls ==&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;System calls&amp;#039;&amp;#039;&amp;#039; (or &amp;#039;&amp;#039;syscalls&amp;#039;&amp;#039;) represent the fundamental programmatic interface between an unprivileged user-space process and the privileged operating system kernel. Whenever a program needs to interact with the outside world or request a resource managed by the operating system — such as reading or writing a file, allocating more memory, spawning a new process, or terminating execution — it must issue a system call.&lt;br /&gt;
&lt;br /&gt;
=== Calling a system call ===&lt;br /&gt;
&lt;br /&gt;
In Linux, each system call conceptually corresponds to a function call, for example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// CONCEPTUAL ILLUSTRATION&lt;br /&gt;
syscall_read(file, buffer_ptr, buffer_size);&lt;br /&gt;
syscall_write(file, buffer_ptr, buffer_size);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In response to receiving these requests, the kernel validates the parameters provided by user space (for instance, checking that &amp;lt;code&amp;gt;file&amp;lt;/code&amp;gt; refers to a valid open file and that &amp;lt;code&amp;gt;buffer_ptr&amp;lt;/code&amp;gt; points to readable or writable user-space memory), performs the requested operation in privileged mode, and returns the result (or an error code) back to the calling process.&lt;br /&gt;
&lt;br /&gt;
However, because there is only one syscall entry point when entering kernel space, the actual function called must be multiplexed. This is done by encoding the system call function as the first parameter. The above read and write examples become:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
syscall(SYS_read, file, buffer_ptr, buffer_size);&lt;br /&gt;
syscall(SYS_write, file, buffer_ptr, buffer_size);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above, &amp;lt;code&amp;gt;SYS_read&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;SYS_write&amp;lt;/code&amp;gt; are special numeric values, defined in a Linux header, and these numbers must be agreed upon between the userspace and the kernelspace. These numbers are different for the different architectures supported by Linux. For example, on the x86-64 architecture, the values are defined as &amp;lt;code&amp;gt;SYS_read = 0; SYS_write = 1&amp;lt;/code&amp;gt;. On AArch64 (ARM64) and RV64I (RISC-V), the values are defined as &amp;lt;code&amp;gt;SYS_read = 63; SYS_write = 64&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Other examples of common system calls include:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! System call !! x86-64 !! AArch64 / RV64I !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SYS_read&amp;lt;/code&amp;gt; || 0 || 63 || Read data from an open file into a buffer&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SYS_write&amp;lt;/code&amp;gt; || 1 || 64 || Write data from a buffer to an open file&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SYS_close&amp;lt;/code&amp;gt; || 3 || 57 || Close an open file&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SYS_mmap&amp;lt;/code&amp;gt; || 9 || 222 || Allocate a new region of memory, or map a file into memory&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SYS_brk&amp;lt;/code&amp;gt; || 12 || 214 || Resize the program&amp;#039;s data segment&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SYS_getpid&amp;lt;/code&amp;gt; || 39 || 172 || Get the current process ID&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SYS_execve&amp;lt;/code&amp;gt; || 59 || 221 || Replace the current process with a new program&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SYS_exit&amp;lt;/code&amp;gt; || 60 || 93 || Terminate the current thread&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=== Syscall instructions ===&lt;br /&gt;
&lt;br /&gt;
All modern CPU architectures provide hardware support for system calls.&lt;br /&gt;
&lt;br /&gt;
In general, there is a single instruction which transfers control from an unprivileged execution context to a privileged execution context, and simultaneously jumps to an address specified beforehand by the privileged execution context. Because of the immediate jump to a fixed address, the user-space program cannot jump to arbitrary code inside the kernel; it can only enter the kernel through this single, tightly controlled gatekeeper routine.&lt;br /&gt;
&lt;br /&gt;
The instructions for syscalls are as follows:&lt;br /&gt;
&lt;br /&gt;
* For x86-64: &amp;lt;code&amp;gt;syscall&amp;lt;/code&amp;gt;&lt;br /&gt;
* For AArch64 (ARM64): &amp;lt;code&amp;gt;svc #0&amp;lt;/code&amp;gt; (stands for &amp;#039;&amp;#039;supervisor call&amp;#039;&amp;#039;; the argument is ignored by Linux)&lt;br /&gt;
* For RV64I (RISC-V): &amp;lt;code&amp;gt;ecall&amp;lt;/code&amp;gt; (stands for &amp;#039;&amp;#039;environment call&amp;#039;&amp;#039;)&lt;br /&gt;
&lt;br /&gt;
The arguments for the syscalls are passed in registers. The register conventions are a bit different than for normal function calls, and registers must be shifted accordingly.&lt;br /&gt;
&lt;br /&gt;
Because they are almost never used directly, and different platforms have different syscall conventions, the C language does not define a standard way to generate system call instructions. For ease of use, the GNU C library (glibc) defines most syscall functions as C functions (for example &amp;lt;code&amp;gt;read()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;write()&amp;lt;/code&amp;gt;) as well as a generic &amp;lt;code&amp;gt;syscall()&amp;lt;/code&amp;gt; function.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;syscall()&amp;lt;/code&amp;gt; function is declared as:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
long syscall(long number, ...);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The function has the following pseudocode logic:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;text&amp;quot;&amp;gt;&lt;br /&gt;
syscall:&lt;br /&gt;
    set register arguments&lt;br /&gt;
    &lt;br /&gt;
    syscall instruction&lt;br /&gt;
    &lt;br /&gt;
    let r = result register&lt;br /&gt;
&lt;br /&gt;
    if r &amp;lt;= -1 &amp;amp;&amp;amp; r &amp;gt;= -4095:&lt;br /&gt;
        errno = -r&lt;br /&gt;
        return -1&lt;br /&gt;
    else:&lt;br /&gt;
        return r&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Negative return values (in the [-4095, -1] range specifically) from system calls indicate errors. The error is extracted by the GNU C library and saved in the &amp;lt;code&amp;gt;errno&amp;lt;/code&amp;gt; global, and &amp;lt;code&amp;gt;-1&amp;lt;/code&amp;gt; is returned.&lt;br /&gt;
&lt;br /&gt;
Common examples of errors:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Constant !! Value !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;EPERM&amp;lt;/code&amp;gt; || 1 || Operation not permitted&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;ENOENT&amp;lt;/code&amp;gt; || 2 || No such file or directory&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;EINTR&amp;lt;/code&amp;gt; || 4 || Interrupted system call&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;ENOMEM&amp;lt;/code&amp;gt; || 12 || Out of memory&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;EACCES&amp;lt;/code&amp;gt; || 13 || Permission denied&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;EFAULT&amp;lt;/code&amp;gt; || 14 || Bad address&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;EEXIST&amp;lt;/code&amp;gt; || 17 || File already exists&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;EINVAL&amp;lt;/code&amp;gt; || 22 || Invalid argument&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;ENOSYS&amp;lt;/code&amp;gt; || 38 || Function not implemented (invalid system call number)&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=== Hello world using system calls ===&lt;br /&gt;
&lt;br /&gt;
With the generic &amp;lt;code&amp;gt;syscall()&amp;lt;/code&amp;gt; function, we can write a complete &amp;quot;Hello World&amp;quot; program that writes directly to standard output and exits without calling standard I/O wrappers like &amp;lt;code&amp;gt;printf()&amp;lt;/code&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot; line&amp;gt;&lt;br /&gt;
#include &amp;lt;errno.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;sys/syscall.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    char msg[] = &amp;quot;Hello World\n&amp;quot;;&lt;br /&gt;
&lt;br /&gt;
    long ret = syscall(SYS_write, STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
    if (ret == -1) {&lt;br /&gt;
        char error_msg[128];&lt;br /&gt;
        snprintf(error_msg, sizeof error_msg, &amp;quot;Error: %d %s\n&amp;quot;, errno, strerror(errno));&lt;br /&gt;
&lt;br /&gt;
        syscall(SYS_write, STDERR_FILENO, error_msg, strlen(error_msg));&lt;br /&gt;
&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    } else {&lt;br /&gt;
        char success_msg[128];&lt;br /&gt;
        snprintf(success_msg, sizeof success_msg, &amp;quot;Success! Wrote %ld bytes\n&amp;quot;, ret);&lt;br /&gt;
&lt;br /&gt;
        syscall(SYS_write, STDOUT_FILENO, success_msg, strlen(success_msg));&lt;br /&gt;
&lt;br /&gt;
        return EXIT_SUCCESS;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; To see the error path of the above program, redirect its standard output to &amp;lt;code&amp;gt;/dev/full&amp;lt;/code&amp;gt;, a special file which always fails writes with &amp;lt;code&amp;gt;ENOSPC&amp;lt;/code&amp;gt; (&amp;#039;&amp;#039;No space left on device&amp;#039;&amp;#039;). The error message is still printed, because it is written to standard error, which is not redirected:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./hello &amp;gt; /dev/full&lt;br /&gt;
Error: 28 No space left on device&lt;br /&gt;
$ echo $?&lt;br /&gt;
1&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== The initial environment ==&lt;br /&gt;
&lt;br /&gt;
When a new program is loaded into memory, the kernel allocates a number of memory regions for the program. Most of these regions are copied from the executable file directly (from the &amp;#039;&amp;#039;&amp;#039;ELF&amp;#039;&amp;#039;&amp;#039; file).&lt;br /&gt;
&lt;br /&gt;
The allocated memory regions are as follows:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Region / Section !! Permissions !! Backed by ELF file? !! Contents in C&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;.text&amp;lt;/code&amp;gt; || Read, Execute || Yes || The program instructions (functions)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;.rodata&amp;lt;/code&amp;gt; || Read || Yes || Read-only data: string literals (e.g., &amp;lt;code&amp;gt;&amp;quot;Hello World\n&amp;quot;&amp;lt;/code&amp;gt;) and &amp;lt;code&amp;gt;const&amp;lt;/code&amp;gt; global/static variables&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;.data&amp;lt;/code&amp;gt; || Read, Write || Yes || Global and &amp;lt;code&amp;gt;static&amp;lt;/code&amp;gt; variables initialized to non-zero values&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;.bss&amp;lt;/code&amp;gt; || Read, Write || No (only size is specified) || Uninitialized or zero-initialized global and &amp;lt;code&amp;gt;static&amp;lt;/code&amp;gt; variables&lt;br /&gt;
|-&lt;br /&gt;
| &amp;#039;&amp;#039;&amp;#039;Stack&amp;#039;&amp;#039;&amp;#039; || Read, Write || No (allocated by kernel) || Initial startup data, function call frames, return addresses, and local variables&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; The explanation in this lab is focused on &amp;#039;&amp;#039;&amp;#039;statically linked&amp;#039;&amp;#039;&amp;#039; executables. Most modern executables, including the ones produced by the lab setup, are &amp;#039;&amp;#039;&amp;#039;dynamically linked&amp;#039;&amp;#039;&amp;#039;. For these, the dynamic loader runs first (defined by the &amp;lt;code&amp;gt;PT_INTERP&amp;lt;/code&amp;gt; ELF header entry) and the kernel hands off to it. Consult the course materials for more information.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In addition to these, as we will see in future lessons, the program can request additional regions using the &amp;lt;code&amp;gt;mmap()&amp;lt;/code&amp;gt; system call, or by growing the data region using the &amp;lt;code&amp;gt;brk()&amp;lt;/code&amp;gt; system call. These regions are what C uses to implement dynamic memory allocations, also known as &amp;#039;&amp;#039;the heap&amp;#039;&amp;#039;.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; All of these regions reside in &amp;#039;&amp;#039;&amp;#039;virtual memory&amp;#039;&amp;#039;&amp;#039;, not directly in physical RAM. Virtual pages that appear contiguous to the program are usually not contiguous in physical memory, and may not even be allocated in physical RAM until the program first accesses them or may be swapped out to disk, trapping into the kernel on access so the kernel can map the backing page transparently.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Process startup ===&lt;br /&gt;
&lt;br /&gt;
=== The stack ===&lt;br /&gt;
&lt;br /&gt;
Unlike the code and global data segments, whose initial contents come from the ELF executable, the &amp;#039;&amp;#039;&amp;#039;stack&amp;#039;&amp;#039;&amp;#039; is created fresh by the kernel when the process starts. It serves as scratch memory for function calls and starts off empty except for the initial startup information placed at its very top by the kernel.&lt;br /&gt;
&lt;br /&gt;
The stack is allocated by the kernel and is limited. On all the architectures discussed here (x86-64, AArch64, RV64I), on Linux it defaults to &amp;#039;&amp;#039;&amp;#039;8MiB&amp;#039;&amp;#039;&amp;#039;. Since any dynamic or large data is usually kept outside the stack (on the heap), the stack contains small local variables and pointers to the data structures on the heap. Because of this, the &amp;#039;&amp;#039;&amp;#039;8MiB&amp;#039;&amp;#039;&amp;#039; stack is considered large. Its main use is to support deep recursion. For example, the kernel (which does not use or strictly limits recursion) only needs a &amp;#039;&amp;#039;&amp;#039;16KiB&amp;#039;&amp;#039;&amp;#039; stack.&lt;br /&gt;
&lt;br /&gt;
Aside from the local variables each program uses, the kernel puts a set of initial information for the program.&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_2_-_initial_stack.png|center|thumb|400px|The stack at program start: &amp;lt;code&amp;gt;argc&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;argv&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;environ&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;auxv&amp;lt;/code&amp;gt;, pointing to data placed at the top of the stack.]]&lt;br /&gt;
&lt;br /&gt;
==== The arguments ====&lt;br /&gt;
&lt;br /&gt;
When a program is executed, it is launched with a set of strings representing its &amp;#039;&amp;#039;arguments&amp;#039;&amp;#039;. The argument array is called &amp;lt;code&amp;gt;argv&amp;lt;/code&amp;gt;, and it contains &amp;lt;code&amp;gt;argc&amp;lt;/code&amp;gt; strings. Additionally, &amp;lt;code&amp;gt;argv[argc]&amp;lt;/code&amp;gt; is set to &amp;lt;code&amp;gt;NULL&amp;lt;/code&amp;gt; (&amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt;) to indicate the end of the array.&lt;br /&gt;
&lt;br /&gt;
Conventionally, &amp;lt;code&amp;gt;argv[0]&amp;lt;/code&amp;gt; represents the command-line name of the program being executed (including any full or relative path used), and the rest are the given arguments.&lt;br /&gt;
&lt;br /&gt;
For example:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Command !! Variable !! Value&lt;br /&gt;
|-&lt;br /&gt;
| rowspan=&amp;quot;5&amp;quot; | &amp;lt;code&amp;gt;ls -la /usr/share&amp;lt;/code&amp;gt;&lt;br /&gt;
| &amp;lt;code&amp;gt;argc&amp;lt;/code&amp;gt; || 3&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;argv[0]&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;&amp;quot;ls&amp;quot;&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;argv[1]&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;&amp;quot;-la&amp;quot;&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;argv[2]&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;&amp;quot;/usr/share&amp;quot;&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;argv[3]&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; The command line is split into a list of strings by the shell; the kernel gets the arguments as a list in the &amp;lt;code&amp;gt;execve&amp;lt;/code&amp;gt; system call.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_2_-_argv.png|center|thumb|500px|The shell splits the command line into &amp;lt;code&amp;gt;argv&amp;lt;/code&amp;gt;: an array of pointers to &amp;lt;code&amp;gt;\0&amp;lt;/code&amp;gt;-terminated strings, ending with &amp;lt;code&amp;gt;NULL&amp;lt;/code&amp;gt;.]]&lt;br /&gt;
&lt;br /&gt;
Upon entry into the entry point (the &amp;lt;code&amp;gt;e_entry&amp;lt;/code&amp;gt; marked address in ELF) the kernel sets the stack pointer register (&amp;lt;code&amp;gt;rsp&amp;lt;/code&amp;gt; for x86-64, &amp;lt;code&amp;gt;SP&amp;lt;/code&amp;gt; for AArch64 and &amp;lt;code&amp;gt;sp&amp;lt;/code&amp;gt;/&amp;lt;code&amp;gt;x2&amp;lt;/code&amp;gt; for RV64I) to point to the &amp;lt;code&amp;gt;argc&amp;lt;/code&amp;gt; value, with the contents of &amp;lt;code&amp;gt;argv&amp;lt;/code&amp;gt; directly above it (the stack grows downwards).&lt;br /&gt;
&lt;br /&gt;
==== Using the arguments ====&lt;br /&gt;
&lt;br /&gt;
The C library initialization code (&amp;lt;code&amp;gt;_start&amp;lt;/code&amp;gt;), which runs before the main function, extracts these and sets them as parameters to the main function.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
#include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;sys/syscall.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
int main(int argc, char **argv)&lt;br /&gt;
{&lt;br /&gt;
    if (argc &amp;gt;= 1) {&lt;br /&gt;
        char msg[128];&lt;br /&gt;
        snprintf(msg, sizeof msg, &amp;quot;My name is: %s\n&amp;quot;, argv[0]);&lt;br /&gt;
&lt;br /&gt;
        syscall(SYS_write, STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
&lt;br /&gt;
        return EXIT_SUCCESS;&lt;br /&gt;
    } else {&lt;br /&gt;
        return EXIT_FAILURE;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; In C parameter declarations, an array parameter decays to a pointer to its first element. Because of this, &amp;lt;code&amp;gt;char *argv[]&amp;lt;/code&amp;gt; (an array of pointers to &amp;lt;code&amp;gt;char&amp;lt;/code&amp;gt;) and &amp;lt;code&amp;gt;char **argv&amp;lt;/code&amp;gt; (a pointer to a pointer to &amp;lt;code&amp;gt;char&amp;lt;/code&amp;gt;) are completely identical in a function signature. You will see both &amp;lt;code&amp;gt;int main(int argc, char *argv[])&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;int main(int argc, char **argv)&amp;lt;/code&amp;gt; used interchangeably in C code and documentation.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== The environment ====&lt;br /&gt;
&lt;br /&gt;
In Linux (and in general in Unix-like operating systems), programs are launched all the time to perform short-lived operations. Because of this, it was considered useful to implement a set of &amp;#039;&amp;#039;&amp;#039;environment variables&amp;#039;&amp;#039;&amp;#039;, which would get passed transparently between programs.&lt;br /&gt;
&lt;br /&gt;
These &amp;#039;&amp;#039;&amp;#039;environment variables&amp;#039;&amp;#039;&amp;#039; define configuration options which are generally shared by many different programs. However, it is not uncommon to see a program support specific environment variables as an alternative way to set configuration.&lt;br /&gt;
&lt;br /&gt;
Common environment variables are (by no means an exhaustive list):&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Environment Variable !! Example Value !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;USER&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;john&amp;lt;/code&amp;gt; || The username of the current user&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;HOME&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;/home/john&amp;lt;/code&amp;gt; || The home directory of the current user&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;LANG&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;en_US.UTF-8&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;ro_RO.UTF-8&amp;lt;/code&amp;gt; || The current locale (used for the language of messages, number formats etc.)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;TERM&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;xterm-256color&amp;lt;/code&amp;gt; || Terminal capability identifier for the open terminal&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;SHELL&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;/bin/bash&amp;lt;/code&amp;gt; || Preferred shell for the current user&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;DISPLAY&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;:0&amp;lt;/code&amp;gt; || Address and number of X11 display (for graphical apps)&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;PATH&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;/usr/bin:/usr/local/bin:/home/john/.local/bin&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;:&amp;lt;/code&amp;gt;-separated list of directories to search for executables when running commands in the shell&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Internally, &amp;lt;code&amp;gt;environ&amp;lt;/code&amp;gt; is stored as a list of strings, terminated by &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt;. It may only store strings. By convention, environment variable names are separated from their values by the first &amp;lt;code&amp;gt;=&amp;lt;/code&amp;gt; character.&lt;br /&gt;
&lt;br /&gt;
The above environment may be stored as:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Variable !! Value&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;environ[0]&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;&amp;quot;USER=john&amp;quot;&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;environ[1]&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;&amp;quot;HOME=/home/john&amp;quot;&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;environ[2]&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;&amp;quot;LANG=en_US.UTF-8&amp;quot;&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;environ[3]&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;&amp;quot;TERM=xterm-256color&amp;quot;&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;environ[4]&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;&amp;quot;SHELL=/bin/bash&amp;quot;&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;environ[5]&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;&amp;quot;DISPLAY=:0&amp;quot;&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;environ[6]&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;&amp;quot;PATH=/usr/bin:/usr/local/bin:/home/john/.local/bin&amp;quot;&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;environ[7]&amp;lt;/code&amp;gt; || &amp;lt;code&amp;gt;nullptr&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_2_-_environ.png|center|thumb|550px|The environment is inherited from the program that started us (e.g. the shell) and stored as an array of &amp;lt;code&amp;gt;&amp;quot;NAME=value&amp;quot;&amp;lt;/code&amp;gt; strings.]]&lt;br /&gt;
&lt;br /&gt;
Environment variable names may contain any characters (except &amp;lt;code&amp;gt;\0&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;=&amp;lt;/code&amp;gt;) and environment variable values may contain any characters (except &amp;lt;code&amp;gt;\0&amp;lt;/code&amp;gt;), including &amp;lt;code&amp;gt;=&amp;lt;/code&amp;gt;. The string &amp;lt;code&amp;gt;&amp;quot;foo=bar=biz&amp;quot;&amp;lt;/code&amp;gt; specifies the variable with name &amp;lt;code&amp;gt;foo&amp;lt;/code&amp;gt; and value &amp;lt;code&amp;gt;&amp;quot;bar=biz&amp;quot;&amp;lt;/code&amp;gt;. The string &amp;lt;code&amp;gt;&amp;quot;foo=&amp;quot;&amp;lt;/code&amp;gt; specifies the variable with name &amp;lt;code&amp;gt;foo&amp;lt;/code&amp;gt; and value &amp;lt;code&amp;gt;&amp;quot;&amp;quot;&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
Because, to the kernel, &amp;lt;code&amp;gt;environ&amp;lt;/code&amp;gt; is just a list of strings it needs to pass, a program may receive duplicate variables (with the same name and the same or different values), or strings without any &amp;lt;code&amp;gt;=&amp;lt;/code&amp;gt; at all.&lt;br /&gt;
&lt;br /&gt;
==== Using the environment ====&lt;br /&gt;
&lt;br /&gt;
On Linux, the GNU C library (&amp;#039;&amp;#039;glibc&amp;#039;&amp;#039;) implements the following rules:&lt;br /&gt;
&lt;br /&gt;
* If a variable is specified multiple times, only the first entry is considered.&lt;br /&gt;
* If there are strings that do not contain &amp;lt;code&amp;gt;=&amp;lt;/code&amp;gt;, they are ignored entirely.&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;code&amp;gt;environ&amp;lt;/code&amp;gt; vector is set by the kernel on the stack above &amp;lt;code&amp;gt;argc&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;argv&amp;lt;/code&amp;gt;. It is retrieved from that point by the C library, which sets a pointer to it in the &amp;lt;code&amp;gt;environ&amp;lt;/code&amp;gt; variable.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
#include &amp;lt;stddef.h&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;sys/syscall.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
extern char **environ;&lt;br /&gt;
&lt;br /&gt;
int main(int argc, char **argv)&lt;br /&gt;
{&lt;br /&gt;
    // Unused. This syntax disables unused parameter warnings.&lt;br /&gt;
    (void) argc;&lt;br /&gt;
    (void) argv;&lt;br /&gt;
&lt;br /&gt;
    const char msg[] = &amp;quot;Environment variables:\n&amp;quot;;&lt;br /&gt;
    syscall(SYS_write, STDOUT_FILENO, msg, strlen(msg));&lt;br /&gt;
&lt;br /&gt;
    for (size_t i = 0; environ[i] != nullptr; ++i) {&lt;br /&gt;
        syscall(SYS_write, STDOUT_FILENO, environ[i], strlen(environ[i]));&lt;br /&gt;
        syscall(SYS_write, STDOUT_FILENO, &amp;quot;\n&amp;quot;, 1);&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== The auxiliary vector ====&lt;br /&gt;
&lt;br /&gt;
In addition to the arguments and environment which are passed from userspace program to userspace program with the help of the kernel, the kernel provides each running program a set of auxiliary information parameters in the form of a vector called &amp;lt;code&amp;gt;auxv&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
This is generally advisory information, and a large majority of programs do not need to read it directly to work correctly.&lt;br /&gt;
&lt;br /&gt;
Auxiliary information is of the form:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
// In: &amp;lt;elf.h&amp;gt;&lt;br /&gt;
typedef struct {&lt;br /&gt;
    uint64_t a_type;&lt;br /&gt;
    union {&lt;br /&gt;
        uint64_t a_val;&lt;br /&gt;
    } a_un;&lt;br /&gt;
} Elf64_auxv_t;&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Practically, it is a vector of &amp;lt;code&amp;gt;a_type&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;a_un.a_val&amp;lt;/code&amp;gt; pairs, both 64 bits (on 64-bit architectures). Depending on the &amp;lt;code&amp;gt;a_type&amp;lt;/code&amp;gt; code, the value of &amp;lt;code&amp;gt;a_un.a_val&amp;lt;/code&amp;gt; may be an &amp;#039;&amp;#039;integer value&amp;#039;&amp;#039;, a &amp;#039;&amp;#039;set of bitflags&amp;#039;&amp;#039; or a &amp;#039;&amp;#039;pointer&amp;#039;&amp;#039; to additional data.&lt;br /&gt;
&lt;br /&gt;
[[File:OS_Lab_2_-_auxv.png|center|thumb|550px|The auxiliary vector: (type, value) pairs provided by the kernel. Some values are integers, others point to additional data.]]&lt;br /&gt;
&lt;br /&gt;
Common auxiliary data (not an exhaustive list):&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! &amp;lt;code&amp;gt;a_type&amp;lt;/code&amp;gt; !! &amp;lt;code&amp;gt;a_val&amp;lt;/code&amp;gt; type !! Description&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;AT_NULL&amp;lt;/code&amp;gt; || N/A || End of the array; the value is ignored&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;AT_PAGESZ&amp;lt;/code&amp;gt; || &amp;#039;&amp;#039;integer value&amp;#039;&amp;#039; || System page size&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;AT_UID&amp;lt;/code&amp;gt; || &amp;#039;&amp;#039;integer value&amp;#039;&amp;#039; || Real user ID&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;AT_GID&amp;lt;/code&amp;gt; || &amp;#039;&amp;#039;integer value&amp;#039;&amp;#039; || Real group ID&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;AT_PLATFORM&amp;lt;/code&amp;gt; || &amp;#039;&amp;#039;pointer&amp;#039;&amp;#039; || String identifying the hardware platform&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;AT_HWCAP&amp;lt;/code&amp;gt; || &amp;#039;&amp;#039;set of bitflags&amp;#039;&amp;#039; || Architecture-dependent CPU capability mask&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;code&amp;gt;AT_RANDOM&amp;lt;/code&amp;gt; || &amp;#039;&amp;#039;pointer&amp;#039;&amp;#039; || Address of 16 random bytes&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
The array is terminated by an auxiliary value of type &amp;lt;code&amp;gt;AT_NULL&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
===== Using the auxiliary vector =====&lt;br /&gt;
&lt;br /&gt;
Unlike the &amp;#039;&amp;#039;argument&amp;#039;&amp;#039; and &amp;#039;&amp;#039;environment&amp;#039;&amp;#039; arrays, &amp;#039;&amp;#039;glibc&amp;#039;&amp;#039; provides no means of accessing a pointer to this array. To arrive at it, the simplest method is walking the environment array.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
#include &amp;lt;elf.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
extern char **environ;&lt;br /&gt;
&lt;br /&gt;
Elf64_auxv_t *get_auxv(void)&lt;br /&gt;
{&lt;br /&gt;
    char **envp = environ;&lt;br /&gt;
&lt;br /&gt;
    while (*envp != nullptr) {&lt;br /&gt;
        ++envp;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    // Walk past the end of environ&lt;br /&gt;
    ++envp;&lt;br /&gt;
&lt;br /&gt;
    return (Elf64_auxv_t *) envp;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Convenience functions ====&lt;br /&gt;
&lt;br /&gt;
For easier access to the environment and auxiliary data, glibc provides the functions:&lt;br /&gt;
&lt;br /&gt;
* In &amp;lt;code&amp;gt;&amp;amp;lt;stdlib.h&amp;amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
** &amp;lt;code&amp;gt;getenv()&amp;lt;/code&amp;gt; -- to get the value of an environment variable&lt;br /&gt;
** &amp;lt;code&amp;gt;setenv()&amp;lt;/code&amp;gt; -- to set the value of an environment variable&lt;br /&gt;
** &amp;lt;code&amp;gt;unsetenv()&amp;lt;/code&amp;gt; -- to remove an environment variable&lt;br /&gt;
* In &amp;lt;code&amp;gt;&amp;amp;lt;sys/auxv.h&amp;amp;gt;&amp;lt;/code&amp;gt;&lt;br /&gt;
** &amp;lt;code&amp;gt;getauxval()&amp;lt;/code&amp;gt; -- to retrieve a value from the auxiliary vector&lt;br /&gt;
&lt;br /&gt;
For the argument list, most programs interpret this list using their own conventions, parsing it from the arguments passed to main. However, many programs share a convention like:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
ls --all -nt dir1 -- -dir2&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here the flags &amp;lt;code&amp;gt;all&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;n&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;t&amp;lt;/code&amp;gt; are set, and the directories to list are &amp;lt;code&amp;gt;dir1&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;-dir2&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
A single &amp;lt;code&amp;gt;-&amp;lt;/code&amp;gt; followed by characters indicates a list of short options (a single character per option), a &amp;lt;code&amp;gt;--&amp;lt;/code&amp;gt; followed by characters indicates a long option, and a bare &amp;lt;code&amp;gt;--&amp;lt;/code&amp;gt; stops argument parsing, allowing &amp;lt;code&amp;gt;-dir2&amp;lt;/code&amp;gt; to be treated literally.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;glibc&amp;#039;&amp;#039; provides the functions &amp;lt;code&amp;gt;getopt()&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;getopt_long()&amp;lt;/code&amp;gt; for parsing this convention, in &amp;lt;code&amp;gt;unistd.h&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;getopt.h&amp;lt;/code&amp;gt; respectively.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;NOTE:&amp;#039;&amp;#039;&amp;#039; for the exercises below, &amp;#039;&amp;#039;&amp;#039;DO NOT&amp;#039;&amp;#039;&amp;#039; use these functions. You can define similar functions yourself.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Program exit ===&lt;br /&gt;
&lt;br /&gt;
When a program finishes its work, it cannot simply return from its initial function because there is simply no caller in user space to return to. Instead, the program must make a system call to ask the kernel to terminate it.&lt;br /&gt;
&lt;br /&gt;
On Linux, the system call for this is &amp;lt;code&amp;gt;SYS_exit&amp;lt;/code&amp;gt;. It takes an integer &amp;#039;&amp;#039;exit status&amp;#039;&amp;#039; (&amp;lt;code&amp;gt;0&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;EXIT_SUCCESS&amp;lt;/code&amp;gt; for success, and a non-zero value such as &amp;lt;code&amp;gt;EXIT_FAILURE&amp;lt;/code&amp;gt; for failure). The kernel closes all of the program&amp;#039;s open resources, frees its memory regions, and passes the exit status back to the parent program (for example, the shell, which stores it in &amp;lt;code&amp;gt;$?&amp;lt;/code&amp;gt;).&lt;br /&gt;
&lt;br /&gt;
In C, when you &amp;lt;code&amp;gt;return&amp;lt;/code&amp;gt; from &amp;lt;code&amp;gt;main()&amp;lt;/code&amp;gt;, control returns to the &amp;#039;&amp;#039;glibc&amp;#039;&amp;#039; function &amp;lt;code&amp;gt;_start&amp;lt;/code&amp;gt;, which passes &amp;lt;code&amp;gt;main()&amp;lt;/code&amp;gt;&amp;#039;s return value to the exit system call via the &amp;lt;code&amp;gt;exit()&amp;lt;/code&amp;gt; library function.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;NOTE:&amp;#039;&amp;#039;&amp;#039; The &amp;lt;code&amp;gt;exit()&amp;lt;/code&amp;gt; library function does some additional cleanup work, such as running callbacks registered using &amp;lt;code&amp;gt;atexit()&amp;lt;/code&amp;gt;.&amp;lt;/div&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c&amp;quot;&amp;gt;&lt;br /&gt;
#include &amp;lt;stdlib.h&amp;gt;&lt;br /&gt;
#include &amp;lt;string.h&amp;gt;&lt;br /&gt;
#include &amp;lt;sys/syscall.h&amp;gt;&lt;br /&gt;
#include &amp;lt;unistd.h&amp;gt;&lt;br /&gt;
&lt;br /&gt;
int main(void)&lt;br /&gt;
{&lt;br /&gt;
    const char before[] = &amp;quot;Exiting now...\n&amp;quot;;&lt;br /&gt;
    syscall(SYS_write, STDOUT_FILENO, before, strlen(before));&lt;br /&gt;
&lt;br /&gt;
    syscall(SYS_exit, 42); // After running this program, echo $? will print 42 in the shell&lt;br /&gt;
&lt;br /&gt;
    // Never reached.&lt;br /&gt;
    const char after[] = &amp;quot;This will never be printed.\n&amp;quot;;&lt;br /&gt;
    syscall(SYS_write, STDOUT_FILENO, after, strlen(after));&lt;br /&gt;
&lt;br /&gt;
    return EXIT_SUCCESS;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Exercises ==&lt;br /&gt;
&lt;br /&gt;
Write each program in its own copy of the project template. As a reminder from [[OS_Lab_1_-_Linux_setup._Bash_primer._C_primer#getting-the-template|the last lab]]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
mkdir -p ~/oslab &amp;amp;&amp;amp; cd ~/oslab&lt;br /&gt;
curl -OL https://wiki.dcae.pub.ro/images/9/93/Os_lab_skeleton.zip&lt;br /&gt;
unzip -d echo Os_lab_skeleton.zip&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Use a new directory name instead of &amp;lt;code&amp;gt;echo&amp;lt;/code&amp;gt; for each exercise.&lt;br /&gt;
&lt;br /&gt;
For this lab:&lt;br /&gt;
&lt;br /&gt;
* Write your output with &amp;lt;code&amp;gt;syscall(SYS_write, ...)&amp;lt;/code&amp;gt;, not &amp;lt;code&amp;gt;printf()&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;puts()&amp;lt;/code&amp;gt;.&lt;br /&gt;
* Walk &amp;lt;code&amp;gt;argv&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;environ&amp;lt;/code&amp;gt; and the auxiliary vector yourself, as arrays. No &amp;lt;code&amp;gt;getenv()&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;getauxval()&amp;lt;/code&amp;gt; or &amp;lt;code&amp;gt;getopt()&amp;lt;/code&amp;gt;.&lt;br /&gt;
* &amp;lt;code&amp;gt;snprintf()&amp;lt;/code&amp;gt; is fine, and recommended, for building a string (formatting a number, for example) that you then write.&lt;br /&gt;
* You can (and it is recommended to) wrap the system calls you use in small functions of your own.&lt;br /&gt;
&lt;br /&gt;
=== A. echo ===&lt;br /&gt;
&lt;br /&gt;
Write your own &amp;lt;code&amp;gt;echo&amp;lt;/code&amp;gt;: print the arguments separated by spaces, followed by a newline. If the first argument is &amp;lt;code&amp;gt;-l&amp;lt;/code&amp;gt;, don&amp;#039;t print it, and put each of the other arguments on its own line instead.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app hello   world&lt;br /&gt;
hello world&lt;br /&gt;
$ ./build/debug/app -l one two three&lt;br /&gt;
one&lt;br /&gt;
two&lt;br /&gt;
three&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Some things to look at:&lt;br /&gt;
&lt;br /&gt;
* There were three spaces between &amp;lt;code&amp;gt;hello&amp;lt;/code&amp;gt; and &amp;lt;code&amp;gt;world&amp;lt;/code&amp;gt; on the command line, but only one in the output. Why? What changes if you put quotes around &amp;lt;code&amp;gt;&amp;quot;hello   world&amp;quot;&amp;lt;/code&amp;gt;?&lt;br /&gt;
* If a write fails, print an error to standard error and exit with status 1. You can check this with &amp;lt;code&amp;gt;/dev/full&amp;lt;/code&amp;gt;, just like the Hello World program above.&lt;br /&gt;
&lt;br /&gt;
=== B. Environment variables ===&lt;br /&gt;
&lt;br /&gt;
Write a program that prints the value of the environment variable named in &amp;lt;code&amp;gt;argv[1]&amp;lt;/code&amp;gt;. With no argument, it prints every variable, one per line.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ env -i HOME=/home/john USER=john ./build/debug/app HOME&lt;br /&gt;
/home/john&lt;br /&gt;
$ env -i HOME=/home/john USER=john ./build/debug/app&lt;br /&gt;
HOME=/home/john&lt;br /&gt;
USER=john&lt;br /&gt;
$ ./build/debug/app NOPE&lt;br /&gt;
NOPE: not set&lt;br /&gt;
$ echo $?&lt;br /&gt;
1&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* &amp;lt;code&amp;gt;env -i&amp;lt;/code&amp;gt; runs a program with only the variables you list.&lt;br /&gt;
* Be careful with the matching: asking for &amp;lt;code&amp;gt;HOME&amp;lt;/code&amp;gt; must not match &amp;lt;code&amp;gt;HOMEDIR=/somewhere&amp;lt;/code&amp;gt;.&lt;br /&gt;
* If the variable isn&amp;#039;t there, say so on standard error and exit with status 1.&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Extra:&amp;#039;&amp;#039;&amp;#039; follow the same rules as &amp;#039;&amp;#039;glibc&amp;#039;&amp;#039;: if a name appears more than once, only the first one counts, and strings without a &amp;lt;code&amp;gt;=&amp;lt;/code&amp;gt; are skipped.&lt;br /&gt;
&lt;br /&gt;
=== C. The auxiliary vector ===&lt;br /&gt;
&lt;br /&gt;
Print every entry of the auxiliary vector: its type and its value, one per line, stopping at &amp;lt;code&amp;gt;AT_NULL&amp;lt;/code&amp;gt;. Use &amp;lt;code&amp;gt;get_auxv()&amp;lt;/code&amp;gt; from above to find it.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app&lt;br /&gt;
33  0xffffa6fb3000&lt;br /&gt;
51  0x1270&lt;br /&gt;
16  0x2fb3ffff&lt;br /&gt;
 6  0x1000&lt;br /&gt;
17  0x64&lt;br /&gt;
 3  0xaaaad0b50040&lt;br /&gt;
...&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Your values will be different: this output is from an ARM64 machine.&lt;br /&gt;
&lt;br /&gt;
* The type numbers are defined in &amp;lt;code&amp;gt;/usr/include/elf.h&amp;lt;/code&amp;gt; (try &amp;lt;code&amp;gt;grep &amp;#039;define AT_&amp;#039; /usr/include/elf.h&amp;lt;/code&amp;gt;).&lt;br /&gt;
* To check your output, the dynamic loader can print the same list, with names: &amp;lt;code&amp;gt;LD_SHOW_AUXV=1 /bin/true&amp;lt;/code&amp;gt;.&lt;br /&gt;
* Run your program a few times. Some values change on every run. Which ones, and what do they have in common?&lt;br /&gt;
&lt;br /&gt;
&amp;#039;&amp;#039;&amp;#039;Extra:&amp;#039;&amp;#039;&amp;#039; print the names of the types from the table above (&amp;lt;code&amp;gt;AT_PAGESZ&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;AT_UID&amp;lt;/code&amp;gt;, ...) instead of their numbers.&lt;br /&gt;
&lt;br /&gt;
=== Bonus: CPU capabilities ===&lt;br /&gt;
&lt;br /&gt;
Write a command that says whether the CPU has a given feature, and exits with status 0 if it does and 1 if it doesn&amp;#039;t:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;bash&amp;quot;&amp;gt;&lt;br /&gt;
$ ./build/debug/app sse2&lt;br /&gt;
sse2: yes&lt;br /&gt;
$ ./build/debug/app ring3mwait&lt;br /&gt;
ring3mwait: no&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Find the &amp;lt;code&amp;gt;AT_HWCAP&amp;lt;/code&amp;gt; entry by walking the auxiliary vector, then test the bit for the feature you were asked about.&lt;br /&gt;
&lt;br /&gt;
On &amp;#039;&amp;#039;&amp;#039;x86-64&amp;#039;&amp;#039;&amp;#039;, &amp;lt;code&amp;gt;AT_HWCAP&amp;lt;/code&amp;gt; is a copy of the EDX register returned by the &amp;lt;code&amp;gt;cpuid&amp;lt;/code&amp;gt; instruction for leaf 1. A few of its bits:&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;wikitable&amp;quot;&lt;br /&gt;
! Bit !! Feature&lt;br /&gt;
|-&lt;br /&gt;
| 0 || &amp;lt;code&amp;gt;fpu&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| 4 || &amp;lt;code&amp;gt;tsc&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| 23 || &amp;lt;code&amp;gt;mmx&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| 25 || &amp;lt;code&amp;gt;sse&amp;lt;/code&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| 26 || &amp;lt;code&amp;gt;sse2&amp;lt;/code&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
The headers don&amp;#039;t name these bits, so look up the rest in a CPUID table, and compare your answers with the &amp;lt;code&amp;gt;flags&amp;lt;/code&amp;gt; line in &amp;lt;code&amp;gt;/proc/cpuinfo&amp;lt;/code&amp;gt;. Almost every bit is set on a modern CPU, so for a feature you &amp;#039;&amp;#039;don&amp;#039;t&amp;#039;&amp;#039; have, look at &amp;lt;code&amp;gt;AT_HWCAP2&amp;lt;/code&amp;gt; as well. Its two bits are named in &amp;lt;code&amp;gt;&amp;amp;lt;asm/hwcap2.h&amp;amp;gt;&amp;lt;/code&amp;gt;: &amp;lt;code&amp;gt;HWCAP2_RING3MWAIT&amp;lt;/code&amp;gt; (only set on Intel Xeon Phi CPUs) and &amp;lt;code&amp;gt;HWCAP2_FSGSBASE&amp;lt;/code&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
You don&amp;#039;t have to support every feature: a handful of names is plenty, as long as you find at least one that your machine has and one that it doesn&amp;#039;t.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;div class=&amp;quot;regula&amp;quot;&amp;gt;&amp;#039;&amp;#039;&amp;#039;Note:&amp;#039;&amp;#039;&amp;#039; The bits of &amp;lt;code&amp;gt;AT_HWCAP&amp;lt;/code&amp;gt; mean something different on every architecture:&lt;br /&gt;
* On &amp;#039;&amp;#039;&amp;#039;AArch64&amp;#039;&amp;#039;&amp;#039; (macOS with OrbStack, ARM laptops), the bits are named in &amp;lt;code&amp;gt;&amp;amp;lt;asm/hwcap.h&amp;amp;gt;&amp;lt;/code&amp;gt;, for example &amp;lt;code&amp;gt;HWCAP_AES&amp;lt;/code&amp;gt; (bit 3) and &amp;lt;code&amp;gt;HWCAP_SVE&amp;lt;/code&amp;gt; (bit 22), with more in &amp;lt;code&amp;gt;AT_HWCAP2&amp;lt;/code&amp;gt;. The &amp;lt;code&amp;gt;Features&amp;lt;/code&amp;gt; line in &amp;lt;code&amp;gt;/proc/cpuinfo&amp;lt;/code&amp;gt; lists what your CPU has.&lt;br /&gt;
* On &amp;#039;&amp;#039;&amp;#039;RV64I&amp;#039;&amp;#039;&amp;#039;, bit &amp;#039;&amp;#039;n&amp;#039;&amp;#039; is set if the CPU has the single-letter extension at position &amp;#039;&amp;#039;n&amp;#039;&amp;#039; in the alphabet: &amp;lt;code&amp;gt;A&amp;lt;/code&amp;gt; is bit 0, &amp;lt;code&amp;gt;C&amp;lt;/code&amp;gt; bit 2, &amp;lt;code&amp;gt;D&amp;lt;/code&amp;gt; bit 3, &amp;lt;code&amp;gt;F&amp;lt;/code&amp;gt; bit 5, &amp;lt;code&amp;gt;I&amp;lt;/code&amp;gt; bit 8, &amp;lt;code&amp;gt;M&amp;lt;/code&amp;gt; bit 12, &amp;lt;code&amp;gt;V&amp;lt;/code&amp;gt; bit 21. Longer extension names (&amp;lt;code&amp;gt;Zba&amp;lt;/code&amp;gt;, &amp;lt;code&amp;gt;Zbb&amp;lt;/code&amp;gt;, ...) are not in &amp;lt;code&amp;gt;AT_HWCAP&amp;lt;/code&amp;gt;; the kernel reports them through the &amp;lt;code&amp;gt;riscv_hwprobe&amp;lt;/code&amp;gt; system call instead.&lt;br /&gt;
&amp;lt;/div&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vserbu</name></author>
	</entry>
</feed>