Compare commits
154 Commits
02-KernelM
...
3097b3ae8d
| Author | SHA1 | Date | |
|---|---|---|---|
|
3097b3ae8d
|
|||
|
93c439abb8
|
|||
|
e46d3bb4b2
|
|||
|
16e60f46e8
|
|||
|
0f6502bf9b
|
|||
|
ca5dd30872
|
|||
|
5f1974da91
|
|||
|
d727a75357
|
|||
|
c120e0d663
|
|||
|
361b6eae4d
|
|||
|
6ef9b6a244
|
|||
|
08635f5080
|
|||
|
4e9064aca2
|
|||
|
341b84e29a
|
|||
|
11cb58fdfe
|
|||
|
bd86f241c2
|
|||
|
f99f8882c5
|
|||
|
56d92132b2
|
|||
|
43ee262d4d
|
|||
|
20eb84e22e
|
|||
|
a3de85fccf
|
|||
|
937b32994d
|
|||
|
7dfd644824
|
|||
|
e9977acfaf
|
|||
|
6740bd2318
|
|||
| 89eced25e0 | |||
| f3a7577fea | |||
| 760d19f2a0 | |||
| bc6ee5e94d | |||
| bc9c4aee23 | |||
| 6519371c8d | |||
| 5bde2024ee | |||
| ede642701a | |||
| 6efff669d5 | |||
| c76492ab42 | |||
| d515871987 | |||
| fa58b76bcd | |||
| 28541d3222 | |||
| 83532f3848 | |||
| ad9c9adf7f | |||
| 9bf6c9ade4 | |||
| 8c5e185b43 | |||
| 8b7afb6329 | |||
| bbe3bb9fed | |||
|
c230621c34
|
|||
|
f42d00a8f8
|
|||
|
52da239f31
|
|||
|
9f305c4626
|
|||
|
6e19040c50
|
|||
|
619dfb4720
|
|||
|
e581628178
|
|||
| 282d83894e | |||
| 943fcefc1c | |||
| df7985033a | |||
| deff0976e0 | |||
| aae80fe658 | |||
| 3162b64d71 | |||
|
6a92019cbe
|
|||
| 995f9c43c5 | |||
| c012b2dcc4 | |||
| db59e76527 | |||
| ce3b308d6d | |||
| 66dd0c5192 | |||
|
79480a37ef
|
|||
|
84cebb07a1
|
|||
|
5b1f51616a
|
|||
|
3c3f8df8c7
|
|||
|
e313e95f9f
|
|||
|
04dad90d55
|
|||
|
0abaa8414e
|
|||
|
e54856dc00
|
|||
|
5a2d352807
|
|||
|
fd4e890483
|
|||
|
e07d1d8dd0
|
|||
|
bc6bf4f69b
|
|||
|
4cca9903fb
|
|||
|
e9067f2051
|
|||
|
c0366b888e
|
|||
|
8aa79f62b7
|
|||
|
64b8cad953
|
|||
|
481a53d0f8
|
|||
|
6c5c8750b3
|
|||
|
5d8ef47e0e
|
|||
|
cb254f4d47
|
|||
|
9a09f6cba6
|
|||
|
286c73f8d5
|
|||
|
eef8b28381
|
|||
|
198265a515
|
|||
|
362730f76f
|
|||
|
4924a705be
|
|||
|
4179e73ba9
|
|||
|
820cbe6d86
|
|||
|
f554918ec4
|
|||
|
a09c855503
|
|||
|
390334d795
|
|||
|
70a07f11bb
|
|||
|
e04bf05b1a
|
|||
|
c408b57c14
|
|||
|
e717434f29
|
|||
|
b74b2e5d19
|
|||
|
e036e18057
|
|||
|
1189c3374d
|
|||
|
d1189e8fda
|
|||
|
e1cfb44e05
|
|||
|
734e23d272
|
|||
|
110ebe0d70
|
|||
|
1221757fae
|
|||
|
734e269533
|
|||
|
c94273f8bf
|
|||
|
fbb9b5e993
|
|||
|
a9a5ecd4c7
|
|||
|
6fc8edfd66
|
|||
|
fb67d8aad7
|
|||
|
5eddfb17a3
|
|||
|
00bc81465c
|
|||
|
95c86b3ea5
|
|||
|
a9c9d11521
|
|||
|
a65c061642
|
|||
|
5aa46bc864
|
|||
|
a8a1080180
|
|||
|
5a9295edfb
|
|||
|
15783a04b0
|
|||
|
b72fca7b26
|
|||
|
5978d25a1c
|
|||
|
6fb6bd811b
|
|||
|
76699b8d19
|
|||
|
6b0246b2a5
|
|||
|
aa7342123d
|
|||
|
8a610842f8
|
|||
|
8cfadd1bf9
|
|||
|
ff22715a6b
|
|||
|
263b5c203e
|
|||
|
86a5f88481
|
|||
|
c501d368d5
|
|||
|
2130c96ada
|
|||
|
e3f234c088
|
|||
|
03b6f0beda
|
|||
|
baf46b7929
|
|||
|
f26133499c
|
|||
|
83e10f098b
|
|||
|
9725e2c66b
|
|||
|
beac78bf94
|
|||
|
62e059775c
|
|||
|
183e6243eb
|
|||
|
1676b42d58
|
|||
|
a6d7b86637
|
|||
|
7f12a642e2
|
|||
|
61cb96d2d7
|
|||
|
6ba497d3e2
|
|||
|
7a376ff789
|
|||
|
906954a035
|
|||
|
59b7caf82e
|
|||
|
b1a1d6af60
|
|||
|
d477abe506
|
@@ -14,7 +14,6 @@ RUN apt-get update && \
|
||||
device-tree-compiler \
|
||||
file \
|
||||
flex \
|
||||
just \
|
||||
libfl-dev \
|
||||
libglib2.0-dev \
|
||||
libssl-dev \
|
||||
@@ -28,5 +27,7 @@ RUN apt-get update && \
|
||||
wget \
|
||||
bear
|
||||
|
||||
RUN curl --proto '=https' --tlsv1.2 -sSf https://just.systems/install.sh | bash -s -- --to /usr/local/bin
|
||||
|
||||
COPY scripts/* /usr/local/bin/
|
||||
RUN chmod +x /usr/local/bin/*
|
||||
|
||||
2
.gitattributes
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
src/05-optimization/ex03/access_log_NASA_Jul95 filter=lfs diff=lfs merge=lfs -text
|
||||
src/05-optimization/ex03/access_log_NASA_Jul95_samples filter=lfs diff=lfs merge=lfs -text
|
||||
20
.gitignore
vendored
@@ -54,3 +54,23 @@ solutions/**/build
|
||||
boot-scripts/boot.cifs
|
||||
boot-scripts/boot.net
|
||||
|
||||
doc/**/*.pdf
|
||||
|
||||
build
|
||||
src/03-led-controller/led-controller
|
||||
src/04-multiprocessing/multiprocessing
|
||||
src/04-multiprocessing/cgroups
|
||||
src/04-multiprocessing/max-cpu
|
||||
src/05-optimization/ex01/basic
|
||||
src/05-optimization/ex01/optimized
|
||||
src/05-optimization/ex02/optimized
|
||||
src/05-optimization/ex02/basic
|
||||
|
||||
src/05-optimization/ex03/ApacheAccessLogAnalyzer.d
|
||||
src/05-optimization/ex03/ApacheAccessLogAnalyzer.o
|
||||
src/05-optimization/ex03/HostCounter.d
|
||||
src/05-optimization/ex03/HostCounter.o
|
||||
src/05-optimization/ex03/main.d
|
||||
src/05-optimization/ex03/main.d
|
||||
src/05-optimization/ex03/perf.data
|
||||
src/05-optimization/ex03/read-apache-logs
|
||||
29
README.md
@@ -37,3 +37,32 @@ sync-images.sh
|
||||
```
|
||||
|
||||
You can now "burn" the Compact Flash using [BalenaEtcher](https://www.balena.io/etcher/)
|
||||
|
||||
## Changing boot env
|
||||
|
||||
### CIFS
|
||||
|
||||
In the bootloader:
|
||||
```bash
|
||||
setenv boot_scripts boot.cifs
|
||||
saveenv
|
||||
boot
|
||||
```
|
||||
|
||||
If the workspace isn't mount control if there is the line in `/etc/fstab`:
|
||||
```text
|
||||
//192.168.53.4/workspace /workspace cifs vers=1.0,username=root,password=toor,port=1445,noserverino
|
||||
```
|
||||
|
||||
If the line isn't there, add it and mount:
|
||||
```bash
|
||||
mount -a
|
||||
```
|
||||
|
||||
### NET
|
||||
In the bootloader:
|
||||
```bash
|
||||
setenv boot_scripts boot.net
|
||||
saveenv
|
||||
boot
|
||||
```
|
||||
|
||||
@@ -5,3 +5,7 @@
|
||||
/ {
|
||||
/delete-node/ leds;
|
||||
};
|
||||
|
||||
&i2c0 {
|
||||
status = "okay";
|
||||
};
|
||||
@@ -1,14 +1,10 @@
|
||||
// #import "@preview/hei-synd-report:0.1.1": *
|
||||
#import "@preview/hei-synd-thesis:0.4.0": *
|
||||
#import "/doc/metadata.typ": *
|
||||
#import "/doc/resources/glossary.typ": *
|
||||
#show:make-glossary
|
||||
#register-glossary(entry-list)
|
||||
|
||||
#import "@preview/fractusist:0.1.1":*
|
||||
|
||||
#import "@preview/grape-suite:3.1.0": exercise
|
||||
#import exercise: task, subtask
|
||||
|
||||
//-------------------------------------
|
||||
// Template config
|
||||
@@ -49,366 +45,31 @@
|
||||
//-------------------------------------
|
||||
// Content
|
||||
//
|
||||
|
||||
= Embedded Linux Environment
|
||||
|
||||
In this laboratory, we see how to setup our environnement and how to have several way to boot. That include a `boot.cifs` that allow us to load the rootfs from samba to easily share the rootfs between the host and the target. And also a `boot.tftp` that allow us to load the kernel by tftp, which is really usefull when we want to modify the kernel and test it without having to reflash the whole system.
|
||||
|
||||
We also see how to debug our system with a remote debugger. That allow us to use debug in our code editor (vscode) a programm that run on the target.
|
||||
|
||||
#figure(
|
||||
image("/doc/resources/img/dev-environment.drawio.svg"),
|
||||
caption: "Development environment schema"
|
||||
) <fig:dev-env>
|
||||
|
||||
|
||||
== Questions
|
||||
=== How to generate U-Boot?
|
||||
We use buildroot, a tool to build embedded Linux.
|
||||
It can generate the U-Boot bootloader.
|
||||
With `make menuconfig`, we can select the U-Boot package.
|
||||
U-boot can be configured with `make uboot-menuconfig`
|
||||
|
||||
And finally, when we have configured everything, we can build the whole system with `make` command.
|
||||
Or only uboot with `make uboot` command.
|
||||
|
||||
=== How to add and build a additional package in Buildroot?
|
||||
In buildroot, with `make menuconfig`, we can select the package we want in `Target packages` section. We can specifically build it with `make <package-name>` command. Otherwise, it will be built with the whole system when we run `make` command.
|
||||
|
||||
=== How to modify the Linux kernel configuration?
|
||||
Like all package, with `make <package-name>-menuconfig` command. So, for Linux kernel:
|
||||
```bash
|
||||
|> make linux-menuconfig
|
||||
```
|
||||
|
||||
=== How to generate a custom rootfs?
|
||||
First of all, select the type of filesystem you want to generate in `Filesystem images` section of `make menuconfig`. We can use an overlay to customise our rootfs.
|
||||
The overlay is a directory (inin the board folder) with the same structure as rootfs and it will merge with the generated rootfs. So, we can add files and directories in the overlay and they will be added to the final rootfs.
|
||||
|
||||
|
||||
=== How to use the eMMC card instead of the SD card?
|
||||
We need to change the boot script `(boot*.cmd)` to load from eMMC by changing the `fatload` command with the correct number. Probably 1 instead of 0.
|
||||
```
|
||||
fatload mmc 1 $kernel_addr_r Image
|
||||
```
|
||||
|
||||
|
||||
=== In cours support, we find several configurations of the development environment. What would be the optimal configuration for developing only user-space applications?
|
||||
If we develop only user space program, we don't need to load kernel by tftp. But it's really usefull to have rootfs load by samba. So the best approach is to use the `boot.cifs`.
|
||||
|
||||
|
||||
|
||||
//--------------------------------------
|
||||
#include "lab00-env/main.typ"
|
||||
#pagebreak()
|
||||
= Linux Kernel Programming
|
||||
|
||||
== Cheatsheet commands
|
||||
- `modinfo <module.ko>`: display information about a kernel module
|
||||
- `insmod <module.ko>`: install a kernel module (without checking for dependencies)
|
||||
- `rmmod <module.ko>`: uninstall a kernel module
|
||||
- `lsmod`: list the currently loaded kernel modules
|
||||
- `dmesg`: display the kernel log
|
||||
- `cat /proc/modules`: display the currently loaded kernel modules with more details
|
||||
- `modprobe <module>`: install a kernel module and its dependencies
|
||||
- `modprobe -r <module>`: uninstall a kernel module and its dependencies
|
||||
- `make`: build the kernel module
|
||||
- `make install`: install the kernel module in the root filesystem
|
||||
|
||||
|
||||
== Exercises
|
||||
|
||||
//-------------------
|
||||
// Exercise 1: Generate kernel module out of tree
|
||||
//-------------------
|
||||
#task(
|
||||
[Generate kernel module out of tree],
|
||||
[],
|
||||
)
|
||||
|
||||
//--------------
|
||||
#subtask[
|
||||
Create the skeleton of a kernel module and generate it outside the kernel sources using a Makefile. The module should display a message when it is registered and when it is uninstalled.
|
||||
]
|
||||
|
||||
We already have a skeleton in `src/02-modules/exercice01` (now `solutions/02_modules/exercice01` that we move to `src/01-skeleton`). We see on the Makefile that the module is generated outside the kernel sources with the `KDIR` variable imported from `src/kernel_settings`. This variable point to the kernel sources.
|
||||
The Makefile also use the `PWD` variable to the current directory.
|
||||
The `make` command will use these variables to generate the module in the current directory.
|
||||
|
||||
```makefile
|
||||
$(MAKE) -C $(KDIR) M=$(PWD) ARCH=$(CPU) CROSS_COMPILE=$(TOOLS) modules
|
||||
```
|
||||
|
||||
//--------------
|
||||
#subtask[
|
||||
Test on the host machine the command modinfo1 on your module skeleton and compare the information returned with that of the source code.
|
||||
]
|
||||
|
||||
```bash
|
||||
|> modinfo mymodule.ko
|
||||
filename: /workspace/src/01-skeleton/mymodule.ko
|
||||
license: GPL
|
||||
description: Module skeleton
|
||||
author: Klagarge <remi@heredero.ch>
|
||||
author: Fastium <fastium.pro@proton.me>
|
||||
depends:
|
||||
name: mymodule
|
||||
vermagic: 5.15.148 SMP preempt mod_unload aarch64
|
||||
parm: text:charp
|
||||
parm: elements:int
|
||||
```
|
||||
//--------------
|
||||
#subtask[
|
||||
Install the module (insmod) and check the kernel log (dmesg)
|
||||
]
|
||||
|
||||
```bash
|
||||
|> insmod mymodule.ko
|
||||
[ 1727.896902] mymodule: loading out-of-tree module taints kernel.
|
||||
[ 1727.903442] Linux module 01 skeleton loaded
|
||||
```
|
||||
We can see the module is indead out-of-tree and correctly loaded.
|
||||
```bash
|
||||
|> dmesg | tail -5
|
||||
[ 1381.694764] CIFS: Attempting to mount \\192.168.53.4\workspace
|
||||
[ 1727.896902] mymodule: loading out-of-tree module taints kernel.
|
||||
[ 1727.903442] Linux module 01 skeleton loaded
|
||||
[ 1727.907659] text: dummy text
|
||||
[ 1727.907659] elements: 1
|
||||
```
|
||||
|
||||
//--------------
|
||||
#subtask[
|
||||
Compare the results obtained by the lsmod command with those obtained with the cat /proc/modules command
|
||||
]
|
||||
|
||||
```bash
|
||||
|> lsmod
|
||||
Module Size Used by Tainted: G
|
||||
mymodule 16384 0
|
||||
···
|
||||
|
||||
|> cat /proc/modules
|
||||
mymodule 16384 0 - Live 0xffff8000011bf000 (O)
|
||||
···
|
||||
```
|
||||
The `/proc/modules` file give us more details about the state of the module. We see it is now live (charged in memory and running)
|
||||
|
||||
//--------------
|
||||
#subtask[
|
||||
Uninstall the module (rmmod).
|
||||
]
|
||||
|
||||
```bash
|
||||
|> rmmod mymodule.ko
|
||||
[ 2989.535793] Linux module skeleton unloaded
|
||||
```
|
||||
|
||||
//--------------
|
||||
#subtask[
|
||||
Adapt the Makefile of the module to allow the installation of the module with other kernel modules allowing the use of the modprobe command. The module should be installed in the root filesystem used in cifs by the target.
|
||||
]
|
||||
|
||||
```bash
|
||||
# On host:
|
||||
|> make install
|
||||
|
||||
# On target:
|
||||
|> modprobe mymodule
|
||||
[ 3359.811183] Linux module 01 skeleton loaded
|
||||
```
|
||||
#include "lab01-module/main.typ"
|
||||
#pagebreak()
|
||||
#include "lab02-peripheral/main.typ"
|
||||
|
||||
#pagebreak()
|
||||
//-------------------
|
||||
// Exercise 2: Adapt the kernel module to receive parameters
|
||||
//-------------------
|
||||
#task(
|
||||
[Adapt the kernel module to receive parameters],
|
||||
[
|
||||
Adapt the kernel module of the previous exercise to receive two or three parameters of your choice. These parameters will be displayed in the console when the module is loaded.
|
||||
],
|
||||
)
|
||||
|
||||
```bash
|
||||
|> modprobe mymodule
|
||||
[ 3583.616662] Linux module skeleton ex02 loaded
|
||||
|> dmesg | tail -5
|
||||
[ 3559.279143] number: 1
|
||||
[ 3581.198562] Linux module skeleton unloaded
|
||||
[ 3583.616662] Linux module skeleton ex03 loaded
|
||||
[ 3583.621085] text: The answer to the Ultimate Question of Life, The Universe, and Everything
|
||||
[ 3583.621085] number: 42
|
||||
|> modprobe -r mymodule
|
||||
[ 3588.404778] Linux module skeleton unloaded
|
||||
|
||||
```
|
||||
|
||||
//-------------------
|
||||
// Exercise 3: What does it mean the 4 values in ```/proc/sys/kernel/printk``` ?
|
||||
//-------------------
|
||||
#task(
|
||||
[What does it mean the 4 values in ```/proc/sys/kernel/printk``` ?],
|
||||
[]
|
||||
)
|
||||
|
||||
We can show what there is in:
|
||||
|
||||
```bash
|
||||
|> cat /proc/sys/kernel/printk
|
||||
7 4 1 7
|
||||
```
|
||||
The number specified the level of output in a console.
|
||||
|
||||
This file specifies the log level for: \
|
||||
current (7), default (4), minimum (1) and boot-time default (7).
|
||||
|
||||
This number matches with this table (#link("https://www.kernel.org/doc/html/latest/core-api/printk-basics.html", [printk documentation])):
|
||||
|
||||
#table(
|
||||
columns: (2fr, 1fr, 3fr),
|
||||
|
||||
[*Name*], [*String*], [*Alias function*],
|
||||
|
||||
[KERN_EMERG], ["0"], [pr_emerg()],
|
||||
[KERN_ALERT], ["1"], [pr_alert()],
|
||||
[KERN_CRIT], ["2"], [pr_crit()],
|
||||
[KERN_ERR], ["3"], [pr_err()],
|
||||
[KERN_WARNING], ["4"], [pr_warning()],
|
||||
[KERN_NOTICE], ["5"], [pr_notice()],
|
||||
[KERN_INFO], ["6"], [pr_info()],
|
||||
[KERN_DEBUG], ["7"], [pr_debug() and pr_devel() if DEBUG is defined],
|
||||
[KERN_DEFAULT], [""], [],
|
||||
[KERN_CONT], ["c"], [pr_cont()],
|
||||
)
|
||||
= #i18n("appendix-title", lang: option.lang) <sec:appendix>
|
||||
== Exercices Lab 01
|
||||
|
||||
#include "lab01-module/ex01.typ"
|
||||
#pagebreak()
|
||||
//-------------------
|
||||
// Exercise 4: Create module with dynamic allocation and a chained list
|
||||
//-------------------
|
||||
|
||||
#task(
|
||||
[
|
||||
Create module with dynamic allocation and a chained list
|
||||
],
|
||||
[
|
||||
Create dynamically elements in the kernel. Adapt a kernel module to specify at the installation the number of element to create a initial text.
|
||||
Each element will contain a unique number. The elements are create at the installation of the module adn chained in a list.
|
||||
These elements will be destruct during the uninstallation of the module.
|
||||
Some information messages are emits to allow debugging.
|
||||
]
|
||||
)
|
||||
|
||||
To allocate memory in the kernel, we can use the `kcalloc` function. It allows to allocate directly the memory for all element. It's also possible to use `kzalloc` in a loop to allocate memory for each element. We prefer allocate all the memory at once to avoid fragmentation and to be sure all the memory can be allocated.
|
||||
|
||||
```bash
|
||||
struct element* element_ptr = kcalloc(elements, sizeof(struct element), GFP_KERNEL);
|
||||
|
||||
for (int i = 0; i < elements; i++) {
|
||||
struct element* e = element_ptr + i;
|
||||
if (e != 0) {
|
||||
strncpy(e->text, text, TEXT_LENGTH_MAX - 1);
|
||||
e->unique_number = i;
|
||||
list_add_tail(&e->node, &list_unique_elements);
|
||||
pr_info ("add element %d: %s\n", e->unique_number, e->text);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#include "lab01-module/ex02.typ"
|
||||
#include "lab01-module/ex03.typ"
|
||||
#pagebreak()
|
||||
//-------------------
|
||||
// Exercise 5: Display the processor chip ID, CPU temperature and the MAC adress of the Ethernet controller
|
||||
//-------------------
|
||||
|
||||
#task(
|
||||
[
|
||||
Display the processor chip ID, CPU temperature and the MAC adress of the Ethernet controller
|
||||
],
|
||||
[
|
||||
- Chip ID registers: _0x01c1'4200_ to _0x01c1'420c_
|
||||
- 32 bits register of the temperature sensor: _0x01c2'5080_
|
||||
- two 32 bits registers of the Ethernet controller MAC address: _0x01c3'0050_ and _0x01c3'0054_
|
||||
|
||||
To calculate the temperature value, there is this formul:
|
||||
$
|
||||
"temperature" = -1991 dot "register value" / 10 + 223000
|
||||
$
|
||||
|
||||
The chip ID can be verified in ```/proc/iomem```.
|
||||
The register value of the temperature can be verified in the file: ```/sys/class/thermal/thermal_zone0/temp```.
|
||||
The MAC address can be verified with ``` ifconfig```.
|
||||
]
|
||||
)
|
||||
|
||||
The resources are savec in a struct:
|
||||
```c
|
||||
static struct resource* resources[3] = {[0] = 0,};
|
||||
```
|
||||
resources[0] is reserved for the chip ID, resources[1] for the temperature sensor and resources[2] for the Ethernet controller.
|
||||
|
||||
We first allocate the resources with `request_mem_region` function. Then we can map the physical address to a virtual address with `ioremap` function. Finally, we can read the value of the registers with `ioread32` function. The request fail because we have an overlap with the EEPROM, but we can ignore this error because we can still read the registers with `ioremap` function.
|
||||
|
||||
```c
|
||||
// Request the resource at (CHIP_ID_BASE_ADDR)
|
||||
resources[0] = request_mem_region(CHIP_ID_BASE_ADDR, 0x1000, "nanopi - chip ID");
|
||||
|
||||
// Map the physical address (CHIP_ID_BASE_ADDR) to a virtual address (registers[0])
|
||||
registers[0] = ioremap(CHIP_ID_BASE_ADDR, 0x1000);
|
||||
```
|
||||
|
||||
|
||||
//-------------------
|
||||
// Exercise 6: Kernel thread
|
||||
//-------------------
|
||||
|
||||
#task(
|
||||
[
|
||||
Kernel thread
|
||||
],
|
||||
[
|
||||
Develop a module which allows to instanciate a thread in the kernel. This thread will display a message every 5 seconds. Use the function ```ssleep(5)``` to sleep the thread from ``` linux/delay.h```.
|
||||
|
||||
]
|
||||
)
|
||||
|
||||
Easy exercice, a thread in the kernet is a `struct task_struct*` that can be created with `kthread_run`
|
||||
|
||||
//-------------------
|
||||
// Exercise 7: Sleeping
|
||||
//-------------------
|
||||
|
||||
#task(
|
||||
[
|
||||
Sleeping
|
||||
],
|
||||
[
|
||||
Develop a module which instanciate 2 threads in the kernel. The first one will wait a wake up notification from the second thread and will sleep. The second will send the notification every 5 seconds. Then it will sleep. We will use the waitqueue for the sleeping function. To allow debugging, each thread will send a message when it wakes up.
|
||||
]
|
||||
)
|
||||
|
||||
//-------------------
|
||||
// Exercise 8: Interrupts
|
||||
//-------------------
|
||||
|
||||
#task(
|
||||
[
|
||||
Interrupts
|
||||
],
|
||||
[
|
||||
|
||||
|
||||
|
||||
Develop a module which allows to detect every push on the button of the nanopi with interrupt. Every interrupts will send a message for debugging.
|
||||
|
||||
- Use the service ``` gpio_request(<io_nr>, <label>)```
|
||||
- Get the interrupt vector with ``` gpio_to_irq(<io_nr>)```
|
||||
- Extension card information:
|
||||
- k1 - gpio: A, pin_nr=0, io_nr=0
|
||||
- k2 - gpio: A, pin_nr=2, io_nr=2
|
||||
- k3 - gpio: A, pin_nr=3, io_nr=3
|
||||
]
|
||||
)
|
||||
#include "lab01-module/ex04.typ"
|
||||
#pagebreak()
|
||||
#include "lab01-module/ex05.typ"
|
||||
#include "lab01-module/ex06.typ"
|
||||
#pagebreak()
|
||||
#include "lab01-module/ex07.typ"
|
||||
#include "lab01-module/ex08.typ"
|
||||
|
||||
//-------------------------------------
|
||||
// Glossary
|
||||
//
|
||||
#heading(numbering:none, outlined: false)[] <sec:end>
|
||||
#make_glossary(gloss:gloss, title:i18n("gloss-title"))
|
||||
// #heading(numbering:none, outlined: false)[] <sec:end>
|
||||
// #make_glossary(gloss:gloss, title:i18n("gloss-title"))
|
||||
|
||||
@@ -35,9 +35,10 @@
|
||||
date: date,
|
||||
tableof: tableof,
|
||||
)
|
||||
#show link: set text(fill: blue.darken(60%))
|
||||
#v(5em)
|
||||
#infobox()[
|
||||
The repository for this labs can be found at the following address:
|
||||
The repository for these labs can be found at the following address:
|
||||
|
||||
#align(center)[https://github.com/Klagarge/MSE-MA-CSEL]
|
||||
]
|
||||
@@ -45,22 +46,11 @@
|
||||
|
||||
//-------------------------------------
|
||||
// Content
|
||||
//
|
||||
//
|
||||
|
||||
= Linux System Programming
|
||||
|
||||
#lorem(150)
|
||||
|
||||
#lorem(50)
|
||||
|
||||
|
||||
//--------------------------------------
|
||||
#pagebreak()
|
||||
= Linux System Optimisation
|
||||
|
||||
#lorem(150)
|
||||
|
||||
#lorem(50)
|
||||
#include "lab03-silly_led/main.typ"
|
||||
#include "lab04-multiprocessing/main.typ"
|
||||
#include "lab05-optimization/main.typ"
|
||||
|
||||
|
||||
//-------------------------------------
|
||||
|
||||
|
Before Width: | Height: | Size: 46 KiB After Width: | Height: | Size: 46 KiB |
BIN
doc/lab00-env/dev-environment.png
Normal file
|
After Width: | Height: | Size: 82 KiB |
45
doc/lab00-env/main.typ
Normal file
@@ -0,0 +1,45 @@
|
||||
= Embedded Linux Environment
|
||||
|
||||
In this laboratory, we see how to setup our environnement and how to have several way to boot. That include a `boot.cifs` that allow us to load the rootfs from samba to easily share the rootfs between the host and the target. And also a `boot.tftp` that allow us to load the kernel by tftp, which is really usefull when we want to modify the kernel and test it without having to reflash the whole system.
|
||||
|
||||
We also see how to debug our system with a remote debugger. That allow us to use debug in our code editor (vscode) a programm that run on the target.
|
||||
|
||||
#figure(
|
||||
image("./dev-environment.png"),
|
||||
caption: "Development environment schema"
|
||||
) <fig:dev-env>
|
||||
|
||||
|
||||
== Questions
|
||||
=== How to generate U-Boot?
|
||||
We use buildroot, a tool to build embedded Linux.
|
||||
It can generate the U-Boot bootloader.
|
||||
With `make menuconfig`, we can select the U-Boot package.
|
||||
U-boot can be configured with `make uboot-menuconfig`
|
||||
|
||||
And finally, when we have configured everything, we can build the whole system with `make` command.
|
||||
Or only uboot with `make uboot` command.
|
||||
|
||||
=== How to add and build a additional package in Buildroot?
|
||||
In buildroot, with `make menuconfig`, we can select the package we want in `Target packages` section. We can specifically build it with `make <package-name>` command. Otherwise, it will be built with the whole system when we run `make` command.
|
||||
|
||||
=== How to modify the Linux kernel configuration?
|
||||
Like all package, with `make <package-name>-menuconfig` command. So, for Linux kernel:
|
||||
```bash
|
||||
|> make linux-menuconfig
|
||||
```
|
||||
|
||||
=== How to generate a custom rootfs?
|
||||
First of all, select the type of filesystem you want to generate in `Filesystem images` section of `make menuconfig`. We can use an overlay to customise our rootfs.
|
||||
The overlay is a directory (in the board folder) with the same structure as rootfs and it will merge with the generated rootfs. So, we can add files and directories in the overlay and they will be added to the final rootfs.
|
||||
|
||||
|
||||
=== How to use the eMMC card instead of the SD card?
|
||||
We need to change the boot script `(boot*.cmd)` to load from eMMC by changing the `fatload` command with the correct number. Probably 1 instead of 0.
|
||||
```
|
||||
fatload mmc 1 $kernel_addr_r Image
|
||||
```
|
||||
|
||||
|
||||
=== In cours support, we find several configurations of the development environment. What would be the optimal configuration for developing only user-space applications?
|
||||
If we develop only user space program, we don't need to load kernel by tftp. But it's really usefull to have rootfs load by samba. So the best approach is to use the `boot.cifs`.
|
||||
95
doc/lab01-module/ex01.typ
Normal file
@@ -0,0 +1,95 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
|
||||
=== Generate kernel module out of tree <lab01:ex01>
|
||||
|
||||
#colorbox(title: "Exercise", color: hei-blue)[
|
||||
Create the skeleton of a kernel module and generate it outside the kernel sources using a Makefile. The module should display a message when it is registered and when it is uninstalled.
|
||||
]
|
||||
//--------------
|
||||
|
||||
We already have a skeleton in `src/02-modules/exercice01` (now `solutions/02_modules/exercice01` that we move to `src/01-skeleton`). We see on the Makefile that the module is generated outside the kernel sources with the `KDIR` variable imported from `src/kernel_settings`. This variable point to the kernel sources.
|
||||
The Makefile also use the `PWD` variable to the current directory.
|
||||
The `make` command will use these variables to generate the module in the current directory.
|
||||
|
||||
```makefile
|
||||
$(MAKE) -C $(KDIR) M=$(PWD) ARCH=$(CPU) CROSS_COMPILE=$(TOOLS) modules
|
||||
```
|
||||
|
||||
//--------------
|
||||
#colorbox(title: "Exercise", color: hei-blue)[
|
||||
Test on the host machine the command modinfo1 on your module skeleton and compare the information returned with that of the source code.
|
||||
]
|
||||
|
||||
```bash
|
||||
|> modinfo mymodule.ko
|
||||
filename: /workspace/src/01-skeleton/mymodule.ko
|
||||
license: GPL
|
||||
description: Module skeleton
|
||||
author: Klagarge <remi@heredero.ch>
|
||||
author: Fastium <fastium.pro@proton.me>
|
||||
depends:
|
||||
name: mymodule
|
||||
vermagic: 5.15.148 SMP preempt mod_unload aarch64
|
||||
parm: text:charp
|
||||
parm: elements:int
|
||||
```
|
||||
//--------------
|
||||
#colorbox(title: "Exercise", color: hei-blue)[
|
||||
Install the module (insmod) and check the kernel log (dmesg)
|
||||
]
|
||||
|
||||
```bash
|
||||
|> insmod mymodule.ko
|
||||
[ 1727.896902] mymodule: loading out-of-tree module taints kernel.
|
||||
[ 1727.903442] Linux module 01 skeleton loaded
|
||||
```
|
||||
We can see the module is indead out-of-tree and correctly loaded.
|
||||
```bash
|
||||
|> dmesg | tail -5
|
||||
[ 1381.694764] CIFS: Attempting to mount \\192.168.53.4\workspace
|
||||
[ 1727.896902] mymodule: loading out-of-tree module taints kernel.
|
||||
[ 1727.903442] Linux module 01 skeleton loaded
|
||||
[ 1727.907659] text: dummy text
|
||||
[ 1727.907659] elements: 1
|
||||
```
|
||||
|
||||
//--------------
|
||||
#colorbox(title: "Exercise", color: hei-blue)[
|
||||
Compare the results obtained by the lsmod command with those obtained with the cat /proc/modules command
|
||||
]
|
||||
|
||||
```bash
|
||||
|> lsmod
|
||||
Module Size Used by Tainted: G
|
||||
mymodule 16384 0
|
||||
···
|
||||
|
||||
|> cat /proc/modules
|
||||
mymodule 16384 0 - Live 0xffff8000011bf000 (O)
|
||||
···
|
||||
```
|
||||
The `/proc/modules` file give us more details about the state of the module. We see it is now live (charged in memory and running)
|
||||
|
||||
//--------------
|
||||
#colorbox(title: "Exercise", color: hei-blue)[
|
||||
Uninstall the module (rmmod).
|
||||
]
|
||||
|
||||
```bash
|
||||
|> rmmod mymodule.ko
|
||||
[ 2989.535793] Linux module skeleton unloaded
|
||||
```
|
||||
|
||||
//--------------
|
||||
#colorbox(title: "Exercise", color: hei-blue)[
|
||||
Adapt the Makefile of the module to allow the installation of the module with other kernel modules allowing the use of the modprobe command. The module should be installed in the root filesystem used in cifs by the target.
|
||||
]
|
||||
|
||||
```bash
|
||||
# On host:
|
||||
|> make install
|
||||
|
||||
# On target:
|
||||
|> modprobe mymodule
|
||||
[ 3359.811183] Linux module 01 skeleton loaded
|
||||
```
|
||||
19
doc/lab01-module/ex02.typ
Normal file
@@ -0,0 +1,19 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
|
||||
=== Adapt the kernel module to receive parameters <lab01:ex02>
|
||||
#colorbox(title: "Exercise", color: hei-blue)[
|
||||
Adapt the kernel module of the previous exercise to receive two or three parameters of your choice. These parameters will be displayed in the console when the module is loaded.
|
||||
]
|
||||
|
||||
```bash
|
||||
|> modprobe mymodule
|
||||
[ 3583.616662] Linux module skeleton ex02 loaded
|
||||
|> dmesg | tail -5
|
||||
[ 3559.279143] number: 1
|
||||
[ 3581.198562] Linux module skeleton unloaded
|
||||
[ 3583.616662] Linux module skeleton ex03 loaded
|
||||
[ 3583.621085] text: The answer to the Ultimate Question of Life, The Universe, and Everything
|
||||
[ 3583.621085] number: 42
|
||||
|> modprobe -r mymodule
|
||||
[ 3588.404778] Linux module skeleton unloaded
|
||||
```
|
||||
33
doc/lab01-module/ex03.typ
Normal file
@@ -0,0 +1,33 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
|
||||
=== What does it mean the 4 values in ```/proc/sys/kernel/printk``` ? <lab01:ex03>
|
||||
|
||||
We can show what there is in:
|
||||
|
||||
```bash
|
||||
|> cat /proc/sys/kernel/printk
|
||||
7 4 1 7
|
||||
```
|
||||
The number specified the level of output in a console.
|
||||
|
||||
This file specifies the log level for: \
|
||||
current (7), default (4), minimum (1) and boot-time default (7).
|
||||
|
||||
This number matches with this table (#link("https://www.kernel.org/doc/html/latest/core-api/printk-basics.html", [printk documentation])):
|
||||
|
||||
#table(
|
||||
columns: (2fr, 1fr, 3fr),
|
||||
|
||||
[*Name*], [*String*], [*Alias function*],
|
||||
|
||||
[KERN_EMERG], ["0"], [pr_emerg()],
|
||||
[KERN_ALERT], ["1"], [pr_alert()],
|
||||
[KERN_CRIT], ["2"], [pr_crit()],
|
||||
[KERN_ERR], ["3"], [pr_err()],
|
||||
[KERN_WARNING], ["4"], [pr_warning()],
|
||||
[KERN_NOTICE], ["5"], [pr_notice()],
|
||||
[KERN_INFO], ["6"], [pr_info()],
|
||||
[KERN_DEBUG], ["7"], [pr_debug() and pr_devel() if DEBUG is defined],
|
||||
[KERN_DEFAULT], [""], [],
|
||||
[KERN_CONT], ["c"], [pr_cont()],
|
||||
)
|
||||
25
doc/lab01-module/ex04.typ
Normal file
@@ -0,0 +1,25 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
|
||||
=== Create module with dynamic allocation and a chained list <lab01:ex04>
|
||||
#colorbox(title: "Exercise", color: hei-blue)[
|
||||
Create dynamically elements in the kernel. Adapt a kernel module to specify at the installation the number of element to create a initial text.
|
||||
Each element will contain a unique number. The elements are create at the installation of the module adn chained in a list.
|
||||
These elements will be destruct during the uninstallation of the module.
|
||||
Some information messages are emits to allow debugging.
|
||||
]
|
||||
|
||||
To allocate memory in the kernel, we can use the `kcalloc` function. It allows to allocate directly the memory for all element. It's also possible to use `kzalloc` in a loop to allocate memory for each element. We prefer allocate all the memory at once to avoid fragmentation and to be sure all the memory can be allocated.
|
||||
|
||||
```bash
|
||||
struct element* element_ptr = kcalloc(elements, sizeof(struct element), GFP_KERNEL);
|
||||
|
||||
for (int i = 0; i < elements; i++) {
|
||||
struct element* e = element_ptr + i;
|
||||
if (e != 0) {
|
||||
strncpy(e->text, text, TEXT_LENGTH_MAX - 1);
|
||||
e->unique_number = i;
|
||||
list_add_tail(&e->node, &list_unique_elements);
|
||||
pr_info ("add element %d: %s\n", e->unique_number, e->text);
|
||||
}
|
||||
}
|
||||
```
|
||||
33
doc/lab01-module/ex05.typ
Normal file
@@ -0,0 +1,33 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
|
||||
=== Display the processor chip ID, CPU temperature and the MAC adress of the Ethernet controller <lab01:ex05>
|
||||
#colorbox(title: "Exercise", color: hei-blue)[
|
||||
- Chip ID registers: _0x01c1'4200_ to _0x01c1'420c_
|
||||
- 32 bits register of the temperature sensor: _0x01c2'5080_
|
||||
- two 32 bits registers of the Ethernet controller MAC address: _0x01c3'0050_ and _0x01c3'0054_
|
||||
|
||||
To calculate the temperature value, there is this formul:
|
||||
$
|
||||
"temperature" = -1991 dot "register value" / 10 + 223000
|
||||
$
|
||||
|
||||
The chip ID can be verified in ```/proc/iomem```.
|
||||
The register value of the temperature can be verified in the file: ```/sys/class/thermal/thermal_zone0/temp```.
|
||||
The MAC address can be verified with ``` ifconfig```.
|
||||
]
|
||||
|
||||
The resources are savec in a struct:
|
||||
```c
|
||||
static struct resource* resources[3] = {[0] = 0,};
|
||||
```
|
||||
resources[0] is reserved for the chip ID, resources[1] for the temperature sensor and resources[2] for the Ethernet controller.
|
||||
|
||||
We first allocate the resources with `request_mem_region` function. Then we can map the physical address to a virtual address with `ioremap` function. Finally, we can read the value of the registers with `ioread32` function. The request fail because we have an overlap with the EEPROM, but we can ignore this error because we can still read the registers with `ioremap` function.
|
||||
|
||||
```c
|
||||
// Request the resource at (CHIP_ID_BASE_ADDR)
|
||||
resources[0] = request_mem_region(CHIP_ID_BASE_ADDR, 0x1000, "nanopi - chip ID");
|
||||
|
||||
// Map the physical address (CHIP_ID_BASE_ADDR) to a virtual address (registers[0])
|
||||
registers[0] = ioremap(CHIP_ID_BASE_ADDR, 0x1000);
|
||||
```
|
||||
8
doc/lab01-module/ex06.typ
Normal file
@@ -0,0 +1,8 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
|
||||
=== Kernel thread <lab01:ex06>
|
||||
#colorbox(title: "Exercise", color: hei-blue)[
|
||||
Develop a module which allows to instanciate a thread in the kernel. This thread will display a message every 5 seconds. Use the function ```ssleep(5)``` to sleep the thread from ``` linux/delay.h```.
|
||||
]
|
||||
|
||||
Easy exercice, a thread in the kernel is a `struct task_struct*` that can be created with `kthread_run`
|
||||
15
doc/lab01-module/ex07.typ
Normal file
@@ -0,0 +1,15 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
|
||||
=== Sleeping <lab01:ex07>
|
||||
#colorbox(title: "Exercise", color: hei-blue)[
|
||||
Develop a module which instanciate 2 threads in the kernel. The first one will wait a wake up notification from the second thread and will sleep. The second will send the notification every 5 seconds. Then it will sleep. We will use the waitqueue for the sleeping function. To allow debugging, each thread will send a message when it wakes up.
|
||||
]
|
||||
|
||||
This exercice make 2 threads in concurrency with wait queue. Here the queue ware declare
|
||||
statically with the macro `DECLARE_WAIT_QUEUE_HEAD`. Then for this exercice we use an atomic
|
||||
trigger with 2 queues. It important that the trigger is atomic or protected by mutex because
|
||||
there is concurrency. The wait queues are used to wait until the trigger has changed to keep
|
||||
synchronization between the threads.
|
||||
|
||||
It is very important to add `kthread_should_stop()` as a condition to wake up queue, because if there is
|
||||
a problem during the implementation, we cannot kill the code.
|
||||
24
doc/lab01-module/ex08.typ
Normal file
@@ -0,0 +1,24 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
|
||||
=== Interrupts <lab01:ex08>
|
||||
#colorbox(title: "Exercise", color: hei-blue)[
|
||||
Develop a module which allows to detect every push on the button of the nanopi with interrupt. Every interrupts will send a message for debugging.
|
||||
|
||||
- Use the service ``` gpio_request(<io_nr>, <label>)```
|
||||
- Get the interrupt vector with ``` gpio_to_irq(<io_nr>)```
|
||||
- Extension card information:
|
||||
- k1 - gpio: A, pin_nr=0, io_nr=0
|
||||
- k2 - gpio: A, pin_nr=2, io_nr=2
|
||||
- k3 - gpio: A, pin_nr=3, io_nr=3
|
||||
]
|
||||
|
||||
We made a custom structur for the gpio device that contain all useful information like the name and the id.
|
||||
```c
|
||||
struct gpio_nanopi {
|
||||
int id;
|
||||
char* name;
|
||||
};
|
||||
static struct gpio_nanopi switchK1 = {0, "K1: GPIOA.0"};
|
||||
static struct gpio_nanopi switchK2 = {2, "K2: GPIOA.2"};
|
||||
static struct gpio_nanopi switchK3 = {3, "K3: GPIOA.3"};
|
||||
```
|
||||
79
doc/lab01-module/main.typ
Normal file
@@ -0,0 +1,79 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
#let ln(num) = {
|
||||
let str_num = if int(num) < 10 { "0" + str(num) } else { str(num) }
|
||||
let lbl = label("lab01:ex" + str_num)
|
||||
link(lbl)[Ex 1.#num]
|
||||
}
|
||||
= Linux Kernel Programming
|
||||
|
||||
In this lab, we learn how to develop a tiny kernel module. We initially create a tiny skeleton that just print a message when the module is loaded and unloaded in #ln(1). Then in #ln(2), we see how to use parameters with insmod and with modprobe. To make things easier for us, we’ve added a line to the makefile that copy the module’s configuration file (that contain the parameters for the modules) to the correct directory on the target. The `install` command is used as a combination of `mkdir`, `cp` and `chmod`.
|
||||
```makefile
|
||||
install:
|
||||
$(MAKE) -C $(KDIR) M=$(PWD) INSTALL_MOD_PATH=$(MODPATH) modules_install
|
||||
install -D -m 0644 $(SOURCE).conf $(MODPATH)/etc/modprobe.d/$(SOURCE).conf
|
||||
```
|
||||
|
||||
|
||||
The exercise 3 ask us what does it mean the 4 values in `/proc/sys/kernel/printk`?
|
||||
We can show what there is in:
|
||||
```bash
|
||||
|> cat /proc/sys/kernel/printk
|
||||
7 4 1 7
|
||||
```
|
||||
The number specified the level of output in a console.
|
||||
|
||||
This file specifies the log level for: \
|
||||
current (7), default (4), minimum (1) and boot-time default (7).
|
||||
|
||||
This number matches with this table (#link("https://www.kernel.org/doc/html/latest/core-api/printk-basics.html", [printk documentation])):
|
||||
|
||||
#table(
|
||||
columns: (2fr, 1fr, 3fr),
|
||||
|
||||
[*Name*], [*String*], [*Alias function*],
|
||||
|
||||
[KERN_EMERG], ["0"], [pr_emerg()],
|
||||
[KERN_ALERT], ["1"], [pr_alert()],
|
||||
[KERN_CRIT], ["2"], [pr_crit()],
|
||||
[KERN_ERR], ["3"], [pr_err()],
|
||||
[KERN_WARNING], ["4"], [pr_warning()],
|
||||
[KERN_NOTICE], ["5"], [pr_notice()],
|
||||
[KERN_INFO], ["6"], [pr_info()],
|
||||
[KERN_DEBUG], ["7"], [pr_debug() and pr_devel() if DEBUG is defined],
|
||||
[KERN_DEFAULT], [""], [],
|
||||
[KERN_CONT], ["c"], [pr_cont()],
|
||||
)
|
||||
|
||||
In #ln(4), we see how to dynamically create elements in the kernel. We use `kcallo` instead of `kzalloc` to allocate all the memory at once and be certain we have the necessary place for all elements of our module. It also a better approach in our opinion to avoid fragmentation.
|
||||
|
||||
We spent some time on the #ln(5) to understand that the `request_mem_region` failed because we have an overlap with the EEPROM.
|
||||
|
||||
The #ln(6) was a straightforward exercise where we had to develop a module that instantiated a thread.
|
||||
|
||||
In the #ln(7) was on concurrency. We had 2 threads with a wait queue. We learn how to suspend a thread, how to wake it up and how to do atomic operation.
|
||||
|
||||
In the last exercise of this lab, #ln(8), we see how to manage interruptions and connect them to a gpio.
|
||||
|
||||
== Cheat sheet commands
|
||||
- `modinfo <module.ko>`: display information about a kernel module
|
||||
- `insmod <module.ko>`: install a kernel module (without checking for dependencies)
|
||||
- `rmmod <module.ko>`: uninstall a kernel module
|
||||
- `lsmod`: list the currently loaded kernel modules
|
||||
- `dmesg`: display the kernel log
|
||||
- `cat /proc/modules`: display the currently loaded kernel modules with more details
|
||||
- `modprobe <module>`: install a kernel module and its dependencies
|
||||
- `modprobe -r <module>`: uninstall a kernel module and its dependencies
|
||||
- `make`: build the kernel module
|
||||
- `make install`: install the kernel module in the root filesystem
|
||||
|
||||
== Zed
|
||||
For this lab, we start to work with another code editor than vscode. Not because we don't like Microsoft, ... but mostly for this reason. We use zed with the new devcontainer implementation on this wonderful code editor. To be able to work in nice condition, we add our own `.clangd` build with the help `bear`.
|
||||
|
||||
This clangd, allow us to have a perfect autocompletion and a enjoyable code navigation. We can easily jump to the definition of a function and see the documentation of a function.
|
||||
|
||||
Thanks to Zed teams for this awesome code editor and \@Fastium for his clangd
|
||||
|
||||
== Conclusion
|
||||
All this lab was done by iteration on the initial skeleton. We develop everything in the #link("https://github.com/Klagarge/MSE-MA-CSEL/tree/main/src/01-skeleton")[src/01-skeleton] folder.
|
||||
|
||||
It was a very delightful introduction lab that show us some possibilities when we want to create a kernel module. Everything was new for us, so even it's basics concept, this was a bit challenging to grasp the subject.
|
||||
1
doc/lab02-peripheral/ex01.typ
Normal file
@@ -0,0 +1 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
1
doc/lab02-peripheral/ex02.typ
Normal file
@@ -0,0 +1 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
1
doc/lab02-peripheral/ex03.typ
Normal file
@@ -0,0 +1 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
1
doc/lab02-peripheral/ex04.typ
Normal file
@@ -0,0 +1 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
1
doc/lab02-peripheral/ex05.typ
Normal file
@@ -0,0 +1 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
1
doc/lab02-peripheral/ex07.typ
Normal file
@@ -0,0 +1 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
34
doc/lab02-peripheral/main.typ
Normal file
@@ -0,0 +1,34 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
#let ln(num) = {
|
||||
// let str_num = if int(num) < 10 { "0" + str(num) } else { str(num) }
|
||||
// let lbl = label("lab02:ex" + str_num)
|
||||
// link(lbl)[Ex 2.#num]
|
||||
[Ex 2.#num]
|
||||
}
|
||||
|
||||
= Linux Kernel Programming
|
||||
|
||||
In the First exercise, we learn how to access a register thought the `/dev/mem` interface. The purpose was to read the chip ID, but we learn how to access in a specific region of the memory. How pages work and how to map them in the user space.
|
||||
|
||||
For exercise 2, we see how to create a character device driver. We learn how to create a device file, how to write a read and write functions and how to test it with `echo` and `cat`. Our module has a `MAJOR` dynamically allocated (but should be 511 with default nanopi installation) and only one minor. To verify the major number, we can use `cat /proc/devices` and look for our module name. To test the module, we need to create a character device file with the right major and minor number.
|
||||
```bash
|
||||
mknod /dev/test-device c 511 0 # Create character device
|
||||
echo "lalalalalaalalalalallala" > /dev/test-device # Write to the device
|
||||
cat /dev/test-device # Read from the device
|
||||
```
|
||||
Quite easy to extend to exercise 3 by adding the parameters as we did in the previous lab. This parameters define the number of minor available.
|
||||
|
||||
Exercise 4 is the continuity, we had to create a tiny app that basically do the `echo` and `cat` for us. We can use the `open`, `write`, `read` and `close` system calls to interact with our device file. We still need to create the device file:
|
||||
```bash
|
||||
mknod /dev/toto0 c 511 0
|
||||
```
|
||||
|
||||
The next step in exercise 5 is to create a sysfs entry for our module. Lot of theory, but once the theory is grasped, it's relatively straightforward to use the sysfs functions in our module.
|
||||
|
||||
The sysfs class is useful when we are attribute oriented. It's easy to store attributes in files. The platform driver is useful when we are processes oriented. The misc device simplify the peripheral instantiation.
|
||||
|
||||
== Adaptation for Zed environment
|
||||
For this lab, we have to work with application and not with module. We have the same problem with clang for the LSP with Zed. To solve it, we include the Linux header files and specify the path of sysroot. Like this, clang have all the dependencies that we need. And tadam, the wonderful environment we had on previous lab is back!
|
||||
|
||||
== Conclusion
|
||||
All the content of this is on #link("https://github.com/Klagarge/MSE-MA-CSEL/tree/main/src/02-driver")[src/02-driver]. It was pleasant to initially see how to manage a character device manually and step by step see how to do it with an easier method. I personally like to start from the bottom.
|
||||
49
doc/lab03-silly_led/main.typ
Normal file
@@ -0,0 +1,49 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
|
||||
= Linux System Programming
|
||||
|
||||
This laboratory implements a user-space application for the NanoPi NEO Plus2 that controls the blinking frequency of the status #gls("led", long: false) using three push buttons. The main goal was to replace a #gls("cpu", long: false)-intensive busy loop with an event-driven design.
|
||||
|
||||
|
||||
== Design
|
||||
The application is based on multithreading: one thread handles the #gls("led", long: false) timing, while another handles button events. #gls("gpio", long: false) are accessed through #gls("sysfs", long: false), which allows the #gls("led", long: false) and buttons to be managed as file descriptors. A key design choice was to centralize all events with a single #gls("epoll", long: false) instance, so both timer events and button events can be processed efficiently.
|
||||
|
||||
The timer thread uses only one timer and sets the initial time on every cycle. This allows us to allocate resources only once for the timer and avoid memory fragmentation. The button thread writes the next sleep duration to a shared variable, which the timer thread reads to set its next sleep interval. Since there is only one writer for this variable, we do not need a mutex to protect it.
|
||||
|
||||
|
||||
All logs are written to #gls("syslog", long: false) at the INFO level:
|
||||
```c
|
||||
// First, we open the syslog with a specific name and facility
|
||||
// LOG_PID to include the PID (process ID) in the logs
|
||||
// LOG_USER to specify the log facility (what type of program)
|
||||
openlog("CSEL Logs", LOG_PID, LOG_USER);
|
||||
|
||||
// Then log what you want:
|
||||
syslog(LOG_INFO, "Start logging silly led-controller"); // INFO level
|
||||
```
|
||||
|
||||
== Difficulties
|
||||
The most difficult part was understanding the #gls("gpio", long: false) mapping between the physical pins and the #gls("sysfs", long: false) #gls("gpio", long: false) numbers. This mapping can be found in the #link("https://linux-sunxi.org/GPIO", [*sunxi driver*]) documentation, which describes the driver for the #gls("gpio", long: false) controller.
|
||||
|
||||
== Results
|
||||
We demonstrate that the application works more efficiently than the provided silly #gls("led", long: false) controller:
|
||||
|
||||
#table(
|
||||
columns: (1fr, 1fr),
|
||||
align: center + horizon,
|
||||
stroke: none,
|
||||
[
|
||||
#figure(
|
||||
image("test-silly.png", height: 10em),
|
||||
caption:[Running the silly #gls("led", long: false) controller on the NanoPi]
|
||||
)<fig-silly>
|
||||
|
||||
],[
|
||||
#figure(
|
||||
image("test-epoll.png", height: 10em),
|
||||
caption:[Running the #gls("epoll", long: false)-based #gls("led", long: false) controller on the NanoPi]
|
||||
)<fig-epoll>
|
||||
]
|
||||
)
|
||||
|
||||
We see in @fig-silly, the silly #gls("led", long: false) controller use 100% of the #gls("cpu", long: false) in @fig-epoll we save CPU resources.
|
||||
BIN
doc/lab03-silly_led/test-epoll.png
Normal file
|
After Width: | Height: | Size: 94 KiB |
BIN
doc/lab03-silly_led/test-silly.png
Normal file
|
After Width: | Height: | Size: 78 KiB |
BIN
doc/lab04-multiprocessing/control_cpu_process_ex_1.png
Normal file
|
After Width: | Height: | Size: 31 KiB |
279
doc/lab04-multiprocessing/main.typ
Normal file
@@ -0,0 +1,279 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
|
||||
= Multiprocessing
|
||||
|
||||
== Process, signals, and communication
|
||||
|
||||
The aim of this laboratory is to create a child process from a parent process using `fork()`. Both processes then execute the same code until they are terminated. This is similar to parallel programming with #gls("gpu", long: false) using #gls("cuda", long: false) or #gls("openmp", long: false). The processes are differentiated by their #gls("pid", long: false).
|
||||
|
||||
The child process must communicate with the parent process using a `socketpair`:
|
||||
```c
|
||||
/* Setup socket for inter-process communication */
|
||||
int fd[2];
|
||||
int err = socketpair(AF_UNIX, SOCK_STREAM, 0, fd);
|
||||
if (err == -1) {
|
||||
perror("socketpair fail");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
```
|
||||
This creates a local UNIX socket pair for inter-process communication. It returns two file descriptors for bidirectional communication.
|
||||
|
||||
The program must handle several signals and print their names when received:
|
||||
```c
|
||||
static void catch_signal(int signal) {
|
||||
|
||||
switch (signal) {
|
||||
case SIGHUP:
|
||||
printf("SIGHUP received\n");
|
||||
break;
|
||||
case SIGINT:
|
||||
printf("SIGINT received\n");
|
||||
exit(EXIT_SUCCESS); // to avoid to be blocked and kill it with ctrl+c
|
||||
break;
|
||||
case SIGQUIT:
|
||||
printf("SIGQUIT received\n");
|
||||
break;
|
||||
case SIGTERM:
|
||||
printf("SIGTERM received\n");
|
||||
break;
|
||||
case SIGABRT:
|
||||
printf("SIGABRT received\n");
|
||||
break;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#pagebreak()
|
||||
|
||||
```c
|
||||
static void install_catch_signal()
|
||||
{
|
||||
struct sigaction act = {
|
||||
.sa_handler = catch_signal,
|
||||
};
|
||||
sigemptyset(&act.sa_mask);
|
||||
sigaction(SIGHUP, &act, 0);
|
||||
sigaction(SIGINT, &act, 0);
|
||||
sigaction(SIGQUIT, &act, 0);
|
||||
sigaction(SIGTERM, &act, 0);
|
||||
sigaction(SIGABRT, &act, 0);
|
||||
}
|
||||
```
|
||||
|
||||
One important design consideration to anticipate was signal handling behaviour. If `Ctrl+C` (SIGINT) is caught, but the handler does not terminate the process, the application would continue to run and block the terminal. In that case, the only way to kill the process would be to open another terminal and use a tool like `top` or `htop`.
|
||||
|
||||
Finally, each process is pinned to its own CPU core. This is configured using `sched_setaffinity`:
|
||||
```c
|
||||
/* Setup CPU affinity for process */
|
||||
CPU_SET(child_cpu, &set);
|
||||
int ret = sched_setaffinity(parent_pid, sizeof(set), &set);
|
||||
if (ret == -1) {
|
||||
perror("sched_setaffinity");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
```
|
||||
|
||||
This can be verified by executing the program and observing CPU usage in `htop`.
|
||||
|
||||
```bash
|
||||
$ ./multiprocessing
|
||||
Child process: pid=273
|
||||
Parent process: pid=274
|
||||
Message 0: Hallo, hallo !
|
||||
Message 1: ça geht !
|
||||
Message 2: Comment vont les olives ?
|
||||
Message 3: Sacré trucs tes trucs là.
|
||||
Message 4: Ta où les vaches !!!!!
|
||||
SIGHUP received
|
||||
SIGQUIT received
|
||||
SIGTERM received
|
||||
SIGABRT received
|
||||
SIGINT received
|
||||
|
||||
```
|
||||
#figure(
|
||||
image("control_cpu_process_ex_1.png"),
|
||||
caption: [Execution of the multiprocessing program]
|
||||
)<multiprocessus>
|
||||
|
||||
|
||||
The @multiprocessus shows the #gls("pid", long: false) and the assigned CPU core for each process, which can be compared with the console output shown above.
|
||||
The child process has PID 273 and runs on core 0, whereas the parent process has PID 274 and runs on core 1.
|
||||
|
||||
== #glspl("cgroup", long: false) memory
|
||||
|
||||
The goal of this part is to understand how to use #glspl("cgroup", long: false) to limit the resources of a process. We will initially focus on memory, but #glspl("cgroup", long: false) can also be used to limit #gls("cpu", long: false), #gls("io", long: false), and other resources.
|
||||
|
||||
To limit the memory usage of a process, we can use the `memory` subsystem of #glspl("cgroup", long: false). On this NanoPi, we use #glspl("cgroup", long: false) v1.
|
||||
|
||||
We must first mount a temporary file system for #glspl("cgroup", long: false):
|
||||
```bash
|
||||
|> mount -t tmpfs none /sys/fs/cgroup
|
||||
```
|
||||
|
||||
We can then create a directory for the memory subsystem, mount the corresponding #glspl("cgroup", long: false) file system, and create a subdirectory for our specific group:
|
||||
|
||||
```bash
|
||||
# Create a directory for the memory cgroup
|
||||
|> mkdir /sys/fs/cgroup/memory
|
||||
|
||||
# Mount the cgroup filesystem with memory
|
||||
|> mount -t cgroup -o memory cgroup /sys/fs/cgroup/memory
|
||||
|
||||
# Create a subdirectory for the memory cgroup
|
||||
|> mkdir /sys/fs/cgroup/memory/0
|
||||
```
|
||||
|
||||
We can then add the current process to this memory #gls("cgroup", long: false) and set a memory limit of 20 #gls("mib", long: false):
|
||||
|
||||
```bash
|
||||
# Add the current process to the memory cgroup
|
||||
|> echo $$ > /sys/fs/cgroup/memory/0/tasks
|
||||
|
||||
# Set the memory limit to 20 MiB
|
||||
|> echo 20M > /sys/fs/cgroup/memory/0/memory.limit_in_bytes
|
||||
```
|
||||
|
||||
We can then run our test program that allocates memory in a loop to see what happens when we exceed the memory limit.
|
||||
|
||||
```c
|
||||
for (i = 0; i < NUM_BLOCKS; i++) {
|
||||
|
||||
// Allocate a block of memory
|
||||
blocks[i] = malloc(BLOCK_SIZE);
|
||||
|
||||
// [...]
|
||||
// check if failed and error, clean and exit
|
||||
|
||||
// Touch the memory to ensure it's actually allocated
|
||||
memset(blocks[i], 0, BLOCK_SIZE);
|
||||
}
|
||||
```
|
||||
|
||||
We can use the `cgroups.sh` script in `04-multiprocessing` to set up #glspl("cgroup", long: false) and run the test program. However, to execute the script in the context of our current shell, we must source it using the `.` command:
|
||||
|
||||
```bash
|
||||
|> just cgroups # Build the test program
|
||||
|> . cgroups.sh # Run the script in the current shell
|
||||
|> ./cgroups # Run the test program that allocates memory in a loop
|
||||
```
|
||||
|
||||
=== What is the behaviour of the command `echo $$ > ...` on #glspl("cgroup", long: false)?
|
||||
|
||||
The `$$` shell variable represents the #gls("pid", long: false) of the current shell. When we execute the command `echo $$ > /sys/fs/cgroup/memory/0/tasks`, we write the PID of the current shell process into the `tasks` file of the specified cgroup. This action assigns the process to that control group, meaning that any program run from this shell will inherit the resource limits and policies defined for that cgroup.
|
||||
|
||||
|
||||
=== What is the behaviour of the memory subsystem when the memory quota is exhausted? Can we modify it? If yes, how?
|
||||
|
||||
On this NanoPi, we use #glspl("cgroup", long: false) v1, so the resource configuration is done via the `memory.limit_in_bytes` file. When a process within a #gls("cgroup", long: false) exceeds the memory limit defined by this file, the Linux kernel will attempt to reclaim memory. If it cannot reclaim sufficient memory, it will invoke the #gls("oom", long: false) killer to terminate processes within that #gls("cgroup", long: false) to free up memory.
|
||||
|
||||
It is possible to modify this behaviour in several ways:
|
||||
|
||||
+ *Use "Soft Limits" (specific to #glspl("cgroup", long: false) v1):*
|
||||
In addition to a hard limit (`memory.limit_in_bytes`), a soft limit can be set via `memory.soft_limit_in_bytes`.
|
||||
*Behaviour:* The kernel does not kill the process when the soft limit is exceeded, unless the entire system runs low on memory. If global memory is low, the kernel begins reclaiming memory from cgroups that exceed their soft limits.
|
||||
|
||||
+ *Adjust the #gls("oom", long: false) Killer priority score:*
|
||||
We can specify an #gls("oom", long: false) score adjustment for the process. By modifying the `/proc/[PID]/oom_score_adj` file to the value `-1000`, the process becomes virtually immune to the #gls("oom", long: false) killer.
|
||||
|
||||
=== How to watch the memory usage?
|
||||
|
||||
We can monitor the memory usage of a control group by reading directly from its configuration files:
|
||||
|
||||
```bash
|
||||
# Current memory usage in bytes
|
||||
|> cat /sys/fs/cgroup/memory/0/memory.usage_in_bytes
|
||||
212992
|
||||
|
||||
# Maximum memory usage in bytes
|
||||
|> cat /sys/fs/cgroup/memory/0/memory.max_usage_in_bytes
|
||||
20971520
|
||||
```
|
||||
|
||||
== #glspl("cgroup", long: false) CPU
|
||||
To check this part, we need a tiny program that consumes #gls("cpu", long: false) with at least two processes.
|
||||
The following program creates a child process that performs #gls("cpu", long: false)-intensive work, while the parent process also performs #gls("cpu", long: false)-intensive work. We can then use #glspl("cgroup", long: false) to limit the #gls("cpu", long: false) usage of one of the processes and observe the effect.
|
||||
```c
|
||||
int main() {
|
||||
pid_t pid = fork();
|
||||
|
||||
if (pid == 0) {
|
||||
cpu_intensive_work("Child process");
|
||||
exit(0);
|
||||
} else {
|
||||
cpu_intensive_work("Parent process");
|
||||
wait(NULL);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Based on the previous exercise, we should already have mounted the #glspl("cgroup", long: false) file system.
|
||||
```bash
|
||||
|> mount -t tmpfs none /sys/fs/cgroup
|
||||
```
|
||||
|
||||
We can then create and mount the #glspl("cgroup", long: false) file system for the `cpuset` subsystem:
|
||||
```bash
|
||||
# Create a directory for the cpuset cgroup
|
||||
|> mkdir /sys/fs/cgroup/cpuset
|
||||
|
||||
# Mount the cgroup filesystem with cpuset
|
||||
|> mount -t cgroup -o cpu,cpuset cpuset /sys/fs/cgroup/cpuset
|
||||
```
|
||||
|
||||
With these prerequisites met, we can create two groups, one for each instance of our running program. Using the commands below, we assign one or more #gls("cpu", long: false) cores to each group via `cpuset.cpus`. I'm not sure about the `cpuset.mems` file, but it seems to be related to memory nodes. It's definitely a topic that should be explored more in depth, but for now, we set to `0` as specified in the lab instructions:
|
||||
|
||||
```bash
|
||||
# Create and allocate CPU for program "low"
|
||||
|> mkdir /sys/fs/cgroup/cpuset/low
|
||||
|> echo 1 > /sys/fs/cgroup/cpuset/low/cpuset.cpus
|
||||
|> echo 0 > /sys/fs/cgroup/cpuset/low/cpuset.mems
|
||||
```
|
||||
|
||||
#pagebreak()
|
||||
|
||||
```bash
|
||||
# Create and allocate CPU for program "high"
|
||||
|> mkdir /sys/fs/cgroup/cpuset/high
|
||||
|> echo 2,3 > /sys/fs/cgroup/cpuset/high/cpuset.cpus
|
||||
|> echo 0 > /sys/fs/cgroup/cpuset/high/cpuset.mems
|
||||
```
|
||||
|
||||
We can then open two shells and run the test program in each of them, while adding each program to its corresponding control group:
|
||||
```bash
|
||||
# In the first shell, add it to the "low" cgroup and run the test program
|
||||
|> . ./max-cpu.sh low
|
||||
|
||||
# In the second shell, add it to the "high" cgroup and run the test program
|
||||
|> . ./max-cpu.sh high
|
||||
```
|
||||
|
||||
As shown in @max-cpu, as expected, both processes in the "low" program are limited to #gls("cpu", long: false) core 1, while the "high" program uses #gls("cpu", long: false) cores 2 and 3 (one for each process).
|
||||
|
||||
#figure(
|
||||
image("max-cpu.png", width: 90%),
|
||||
caption: [CPU usage of the two programs with dedicated resources]
|
||||
)<max-cpu>
|
||||
|
||||
To share resources at 75% and 25%, we can use the `cpu.shares` file in the `cpu` cgroup. We assign a share value to the "high" group that is three times higher than that of the "low" group:
|
||||
|
||||
```bash
|
||||
|> echo 75 > /sys/fs/cgroup/cpu/high/cpu.shares
|
||||
|> echo 25 > /sys/fs/cgroup/cpu/low/cpu.shares
|
||||
```
|
||||
|
||||
After running the test program in each shell, we can observe in @shared-cpu that the processes in the "high" #gls("cgroup", long: false) are allocated 75% of the CPU capacity, while those in the "low" #gls("cgroup", long: false) receive 25%:
|
||||
```bash
|
||||
# In the first shell, add it to the "low" cgroup and run the test program
|
||||
|> . ./shared-cpu.sh low
|
||||
|
||||
# In the second shell, add it to the "high" cgroup and run the test program
|
||||
|> . ./shared-cpu.sh high
|
||||
```
|
||||
|
||||
|
||||
#figure(
|
||||
image("shared-cpu.png", width: 80%),
|
||||
caption: [CPU usage of the two programs with shared resources]
|
||||
)<shared-cpu>
|
||||
BIN
doc/lab04-multiprocessing/max-cpu.png
Normal file
|
After Width: | Height: | Size: 36 KiB |
BIN
doc/lab04-multiprocessing/shared-cpu.png
Normal file
|
After Width: | Height: | Size: 71 KiB |
BIN
doc/lab05-optimization/command-after-optimization.png
Normal file
|
After Width: | Height: | Size: 180 KiB |
283
doc/lab05-optimization/main.typ
Normal file
@@ -0,0 +1,283 @@
|
||||
#import "/doc/metadata.typ": *
|
||||
|
||||
= Linux System Optimisation
|
||||
|
||||
In this laboratory, the usage of `#gls("perf", long: false)` as a performance analysis tool is explored.
|
||||
|
||||
|
||||
== Exercise 1
|
||||
|
||||
#task([
|
||||
Measure the performance of `ex1`
|
||||
],[
|
||||
```
|
||||
Performance counter stats for './ex1':
|
||||
|
||||
40609.10 msec task-clock # 1.000 CPUs utilized
|
||||
22 context-switches # 0.542 /sec
|
||||
0 cpu-migrations # 0.000 /sec
|
||||
48867 page-faults # 1.203 K/sec
|
||||
33136692484 cycles # 0.816 GHz
|
||||
1671194529 instructions # 0.05 insn per cycle
|
||||
269592231 branches # 6.639 M/sec
|
||||
1013366 branch-misses # 0.38% of all branches
|
||||
|
||||
40.618926728 seconds time elapsed
|
||||
|
||||
39.901620000 seconds user
|
||||
0.296158000 seconds sys
|
||||
|
||||
```
|
||||
This program performs 22 context switches and takes 40.6 seconds to run.
|
||||
])
|
||||
|
||||
#task([
|
||||
What error is present in the `ex1` program?
|
||||
],[
|
||||
The error lies in how the array memory is accessed. In C, 2D arrays are stored in "row-major" order, meaning elements of the same row are contiguous in memory. However, the original code accesses the array using `array[j][i]` within the loops, where the row index `j` is in the inner loop.
|
||||
|
||||
This causes the program to jump across memory addresses non-sequentially, triggering a cache miss almost every time. This can be solved by simply swapping the indices to `array[i][j]` (or swapping the loop order) to process memory sequentially:
|
||||
|
||||
|
||||
```c
|
||||
int i, j;
|
||||
for (i = 0; i < SIZE; i++)
|
||||
{
|
||||
for (j = 0; j < SIZE; j++)
|
||||
{
|
||||
array[i][j]+= 10;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
With these modifications, the performance is improved by a factor of nearly 80.
|
||||
|
||||
```
|
||||
Performance counter stats for './optimized':
|
||||
|
||||
474.62 msec task-clock # 0.940 CPUs utilized
|
||||
15 context-switches # 31.604 /sec
|
||||
0 cpu-migrations # 0.000 /sec
|
||||
48866 page-faults # 102.959 K/sec
|
||||
387200454 cycles # 0.816 GHz
|
||||
253128815 instructions # 0.65 insn per cycle
|
||||
39724528 branches # 83.698 M/sec
|
||||
577317 branch-misses # 1.45% of all branches
|
||||
|
||||
0.505146917 seconds time elapsed
|
||||
|
||||
0.233682000 seconds user
|
||||
0.237584000 seconds sys
|
||||
|
||||
```
|
||||
|
||||
This can be observed by running the same performance analysis with `#gls("perf", long: false)`. The elapsed time drops from around 40 seconds to approximately 0.5 seconds. A similar improvement can be observed in the cache misses:
|
||||
- optimized : 753,502
|
||||
- basic : 406,627,550
|
||||
|
||||
|
||||
])
|
||||
|
||||
|
||||
#task([
|
||||
Show `#gls("l1", long: false)` cache misses for `ex1`:
|
||||
],[
|
||||
#table(
|
||||
columns: (1.5fr, 1fr),
|
||||
stroke: none,
|
||||
[
|
||||
Not optimized
|
||||
```
|
||||
407036282 L1-dcache-load-misses
|
||||
|
||||
39.868545227 seconds time elapsed
|
||||
39.115950000 seconds user
|
||||
0.347522000 seconds sys
|
||||
|
||||
```
|
||||
],[
|
||||
Optimized
|
||||
```
|
||||
42027157 L1-dcache-load-misses
|
||||
|
||||
4.132272210 seconds time elapsed
|
||||
3.778635000 seconds user
|
||||
0.296472000 seconds sys
|
||||
```
|
||||
]
|
||||
)
|
||||
There is still an approximate 10-fold difference between the two configurations' `#gls("l1", long: false)` cache misses.
|
||||
])
|
||||
|
||||
|
||||
#task([Events analysed with `#gls("perf", long: false)`:],[
|
||||
|
||||
- *Instructions*: Indicates the total number of `#gls("cpu", long: false)` instructions executed while the program is running.
|
||||
- *Cache-misses*: This occurs when the required data is not currently stored in the cache hierarchy, forcing the processor to fetch it from slower main memory (`#gls("ram", long: false)`).
|
||||
- *Branch-misses*: Occurs during conditional branching when the `#gls("cpu", long: false)`'s branch predictor incorrectly guesses the next instruction path, resulting in pipeline flushes.
|
||||
- *L1-dcache-load-misses*: Occurs when the requested data is not present in the Level 1 Data Cache (`#gls("l1", long: false)` dcache), requiring a lookup in the next cache level (`#gls("l2", long: false)` cache).
|
||||
- *CPU-migrations*: Indicates the number of times the operating system scheduler moved the program threads from one `#gls("cpu", long: false)` core to another.
|
||||
- *Context-switches*: Occurs when the process relinquishes the `#gls("cpu", long: false)` core to allow other processes to run. This context-switch requires saving and restoring processor registers, including the `#gls("pc", long: false)`.
|
||||
|
||||
])
|
||||
|
||||
|
||||
#task([Timing performance of `#gls("perf", long: false)`], [
|
||||
Below are several execution times for the optimized program:
|
||||
|
||||
#figure(table(
|
||||
columns: (1fr, 1fr),
|
||||
// stroke: none,
|
||||
[*Without `#gls("perf", long: false)`*], [*With `#gls("perf", long: false)`*],
|
||||
[
|
||||
```
|
||||
real 0m 4.44s
|
||||
user 0m 3.83s
|
||||
sys 0m 0.29s
|
||||
|
||||
```
|
||||
],
|
||||
[
|
||||
```
|
||||
real 0m 4.38s
|
||||
user 0m 4.05s
|
||||
sys 0m 0.27s
|
||||
|
||||
```
|
||||
],[
|
||||
```
|
||||
real 0m 4.75s
|
||||
user 0m 4.09s
|
||||
sys 0m 0.34s
|
||||
|
||||
```
|
||||
],[
|
||||
```
|
||||
real 0m 4.75s
|
||||
user 0m 4.09s
|
||||
sys 0m 0.34s
|
||||
|
||||
```
|
||||
],
|
||||
),
|
||||
caption:[Impact of the `#gls("perf", long: false)` tool]
|
||||
)<impact-perf>
|
||||
|
||||
As seen in @impact-perf, running the program with `#gls("perf", long: false)` does not introduce a significant performance overhead, which can be attributed to stable `#gls("cpu", long: false)` core scheduling and allocation.
|
||||
|
||||
])
|
||||
|
||||
== Exercise 2
|
||||
|
||||
The program fills an array with random numbers between 0 and 512. Then, it iterates 10,000 times over the entire array to sum all elements that are greater than or equal to 256.
|
||||
|
||||
|
||||
#figure(
|
||||
table(
|
||||
columns: (1fr),
|
||||
[Without Optimisation],
|
||||
[
|
||||
```
|
||||
|
||||
26170.47 msec task-clock # 1.000 CPUs utilized
|
||||
17 context-switches # 0.650 /sec
|
||||
0 cpu-migrations # 0.000 /sec
|
||||
74 page-faults # 2.828 /sec
|
||||
21354981945 cycles # 0.816 GHz
|
||||
14768657990 instructions # 0.69 insn per cycle
|
||||
988541451 branches # 37.773 M/sec
|
||||
327869867 branch-misses # 33.17% of all branches
|
||||
|
||||
26.178296596 seconds time elapsed
|
||||
|
||||
26.117025000 seconds user
|
||||
0.003961000 seconds sys
|
||||
```
|
||||
], [With "sort" optimisation],[
|
||||
```
|
||||
23430.74 msec task-clock
|
||||
17 context-switches # 0.726 /sec
|
||||
0 cpu-migrations # 0.000 /sec
|
||||
109 page-faults # 4.652 /sec
|
||||
19119368029 cycles # 0.816 GHz
|
||||
14818405467 instructions # 0.78 insn per cycle
|
||||
997843744 branches # 42.587 M/sec
|
||||
805002 branch-misses # 0.08% of all branches
|
||||
|
||||
23.439504220 seconds time elapsed
|
||||
|
||||
23.382177000 seconds user
|
||||
0.003961000 seconds sys
|
||||
```
|
||||
]
|
||||
),
|
||||
caption:[Ex02 timing optimisation]
|
||||
)<sort-optimization>
|
||||
|
||||
In @sort-optimization, there is a gain of around 3 seconds due to a massive decrease in branch misses, dropping from 33.17% to 0.08%.
|
||||
|
||||
This is explained by the `#gls("cpu", long: false)`'s branch predictor. Inside the loop, the program checks if the value is `>= 256`. When the array is filled with random numbers, the processor cannot predict the outcome of this condition, resulting in frequent pipeline flushes. However, when the array is sorted, the condition is always false for the first half of the array, and always true for the second half. The `#gls("cpu", long: false)` easily predicts this pattern, avoiding branch misses and executing much faster.
|
||||
|
||||
The same test was performed with the `-O1` optimisation flag, and there is almost no difference between the two scripts. The optimized version is around 4.12s and the basic version is around 4.6s. The difference of 0.6 seconds can be explained by the sorting algorithm itself in the optimized version, as sorting is the only added operation.
|
||||
|
||||
|
||||
== Exercise 3
|
||||
By analysing the call graph with `#gls("perf", long: false) report`, we can trace the indirect calls to `std::operator==<char>` back to our application. The bottleneck originates in the `HostCounter::isNewHost` function, specifically during the `std::find` operation on a `std::vector`:
|
||||
|
||||
```c
|
||||
bool HostCounter::isNewHost(std::string hostname)
|
||||
{
|
||||
return std::find(myHosts.begin(), myHosts.end(), hostname) == myHosts.end();
|
||||
}
|
||||
```
|
||||
|
||||
Searching through an unsorted vector requires a linear comparison of strings ($O(N)$ complexity), which is highly inefficient. As shown below, processing just a sample of the logs takes over 2 minutes:
|
||||
|
||||
```
|
||||
|> time ./read-apache-logs access_log_NASA_Jul95_samples
|
||||
Processing log file access_log_NASA_Jul95_samples
|
||||
Found 14867 unique Hosts/IPs
|
||||
real 2m 15.58s
|
||||
user 2m 14.68s
|
||||
sys 0m 0.12s
|
||||
|
||||
```
|
||||
To fix this, the data structure must be changed from `std::vector` to `std::set`. A set uses a tree-based structure, reducing the search complexity to $O(log N)$ (or $O(1)$.
|
||||
|
||||
|
||||
#figure(
|
||||
image("command-after-optimization.png"),
|
||||
caption:[ `#gls("perf", long: false)` report after migrating to `std::set`]
|
||||
)<command-opti>
|
||||
|
||||
After applying these changes, the `#gls("perf", long: false)` report in @command-opti shows a much healthier execution profile. The execution time drops drastically, creating a massive performance gap compared to the initial `std::vector` implementation:
|
||||
```
|
||||
|> time ./read-apache-logs access_log_NASA_Jul95_samples
|
||||
Processing log file access_log_NASA_Jul95_samples
|
||||
Found 14867 unique Hosts/IPs
|
||||
real 0m 1.55s
|
||||
user 0m 1.36s
|
||||
sys 0m 0.10s
|
||||
```
|
||||
|
||||
Even when processing the entire log file containing roughly 2 million entries, the optimized program finishes in under 15 seconds:
|
||||
```
|
||||
|> time ./read-apache-logs access_log_NASA_Jul95
|
||||
Processing log file access_log_NASA_Jul95
|
||||
Found 81983 unique Hosts/#gls("ip", long: false)s
|
||||
real 0m 14.76s
|
||||
user 0m 13.90s
|
||||
sys 0m 0.68s
|
||||
```
|
||||
|
||||
|
||||
#task([Measure interruption latency and jitter], [
|
||||
To measure latency and jitter, a hardware-based approach using an oscilloscope and a square-wave generator was implemented.
|
||||
First, the generator toggles a processor pin to trigger the interrupt routine. Then, another pin creates a pulse as a response, which is measured by the oscilloscope. The latency is the delay between the generator's rising edge and the response pulse. The jitter is the variation of this latency over multiple measurements.
|
||||
|
||||
To differentiate between Kernel Space and User Space:
|
||||
- *Kernel Space*: The response pin is toggled directly inside the kernel's Interrupt Service Routine (`#gls("irq", long: false)` handler / driver).
|
||||
- *User Space*: The response pin is toggled by a user application that wakes up (using `#gls("epoll", long: false)()`) after the kernel has handled the interrupt.
|
||||
|
||||
The difference between these two latency measurements represents the context-switch overhead from kernel mode to user mode.
|
||||
])
|
||||
@@ -1,3 +1,7 @@
|
||||
#import "@preview/hei-synd-thesis:0.4.0": *
|
||||
#import "/doc/resources/glossary.typ": *
|
||||
#import "@preview/grape-suite:3.1.0": exercise
|
||||
#import exercise: task, subtask
|
||||
//-------------------------------------
|
||||
// Document options
|
||||
//
|
||||
@@ -55,4 +59,4 @@
|
||||
maxdepth: 3,
|
||||
)
|
||||
|
||||
#let gloss = true
|
||||
#let gloss = true
|
||||
|
||||
@@ -34,9 +34,15 @@
|
||||
date: date,
|
||||
tableof: tableof,
|
||||
)
|
||||
#import "@preview/codly:1.3.0": *
|
||||
#import "@preview/codly-languages:0.1.8": *
|
||||
#show: codly-init.with()
|
||||
|
||||
#codly(languages: codly-languages)
|
||||
|
||||
#v(5em)
|
||||
#infobox()[
|
||||
The repository for this labs can be found at the following address:
|
||||
The repository for these lab can be found at the following address:
|
||||
|
||||
#align(center)[https://github.com/Klagarge/MSE-MA-CSEL]
|
||||
]
|
||||
@@ -44,13 +50,136 @@
|
||||
|
||||
//-------------------------------------
|
||||
// Content
|
||||
//
|
||||
//
|
||||
#let general-architecture = [
|
||||
#figure(
|
||||
image("mini-project/deployement.png", width: 100%),
|
||||
caption: "General architecture"
|
||||
) <fig:general-architecture>
|
||||
]
|
||||
|
||||
= Mini-Project
|
||||
|
||||
#lorem(150)
|
||||
= Introduction
|
||||
|
||||
The purpose of this mini-project is to train different concept we saw during the semester.
|
||||
We simulate a fan controlled by the temperature of the @cpu. To simulate this fan, we blink the status @led.
|
||||
The @fig:general-architecture shows the general architecture of the project.
|
||||
|
||||
This @led and the measure of the temperature is managed by a kernel module. This module support an automatic and manual mode. In the automatic mode, the blinking frequency is automatically adjusted according to the temperature. We can switch this mode by a @sysfs entry. In the manual mode, we can set the blinking frequency by writing in another @sysfs entry. The @sysfs also provide an entry to read the current temperature and blinking frequency.
|
||||
|
||||
Another part in this mini-project is to create a daemon in user-space to control manually the fan. The buttons are read by the daemon to increase and decrease the blinking frequency in manual mode. The daemon also displays the current temperature and blinking frequency on an @oled screen. The daemon can also be controlled by an @ipc interface.
|
||||
|
||||
Finally, a tiny @cli is implemented to control the daemon through the @ipc interface.
|
||||
|
||||
#general-architecture
|
||||
|
||||
#pagebreak()
|
||||
= Architecture
|
||||
|
||||
In our architecture, we manage to separate with callback our functionalities. Then, we use threads for multiprocessing which involve to implement some atomic operations, signals and mutex. We add socket pair and @sysfs for communication. Finally, we get some information through registers.
|
||||
|
||||
== Kernel
|
||||
The kernel part is separated in three main parts: the blink, the temperature, and the @sysfs. All this part are initialized in the main but handle in a regulator that build the logic of the auto/man mode. In auto mode, the regulator sets the frequency according to the temperature. The regulator also handles the @sysfs for setting the mode and the frequency in case of the manual mode.
|
||||
|
||||
=== blink
|
||||
The `blink.c` and `blink.h` files implement the part that control the status @led. It's a kernel module, so we have an init and an exit function. The init function create a kernel thread that blink to a specific frequency. The exit function stop this thread. The period is stored in a global `atomic_t` variable, so it can be safely set with the `adjust_period` function.
|
||||
=== temperature
|
||||
|
||||
The read of temperature is done through the register. It implements the function to calculate the temperature from the register. It changes the formula when the temperature is over 70 °C, as specified in the datasheet.
|
||||
|
||||
=== #gls("sysfs", long: false)
|
||||
|
||||
It uses some callbacks for every action in the module:
|
||||
- read temperature
|
||||
- set and get mode
|
||||
- set period
|
||||
- get period
|
||||
|
||||
We separate the setter and the getter of the period to avoid some issue. Because if we set a wrong value or in automatic mode, the value would be wrong for getting it. In the way we did it, the read value will be the current.
|
||||
|
||||
#pagebreak()
|
||||
== Daemon
|
||||
|
||||
The daemon has the core in `app`. It handles the `sysfs` functions needed by the different features. It provides them for the @oled screen, buttons, @led:pl and @ipc server.
|
||||
|
||||
=== #gls("gpio", long: false)
|
||||
We develop the @gpio part as near as possible with a pseudo class for the @led and a pseudo class for the button. The @led class is quite simple and help to have a good understanding of this principle. As shown in @fig:led-class-header, we create a structure for the @led. A `LED_init` function is used to create a @led object by returning a pointer to this structure. Function to this class start with the same prefix `LED_` and take a pointer to the structure as parameter.
|
||||
|
||||
#figure(
|
||||
[```c
|
||||
typedef enum {
|
||||
LED_STATUS,
|
||||
LED_POWER,
|
||||
} LED_type; // enum to choose which led we want initialize
|
||||
|
||||
typedef struct {
|
||||
int gpio;
|
||||
} LED; // Type for our led class
|
||||
|
||||
LED* LED_init(LED_type type); // Create new LED object
|
||||
void LED_on(LED* led);
|
||||
void LED_off(LED* led);
|
||||
void LED_toggle(LED* led);
|
||||
```],
|
||||
caption: "Led class header"
|
||||
) <fig:led-class-header>
|
||||
|
||||
We develop the button in the same way, with class spirit. But a button has no function to control it, but only a callback that need to be set as shown in @fig:button-class-header. So this pseudo class abstract the complexity of a button, and we provide a simple @api with a nice callback system. Behind the scene, we have a thread that looks the button file with an `@epoll` and call the callback when the button is pushed. The first button to be initialized create this static thread. All new buttons are added on the event list of this thread.
|
||||
|
||||
#figure(
|
||||
[```c
|
||||
typedef void (*BTN_callback)();
|
||||
|
||||
BTN* BTN_init(BTN_type type);
|
||||
void BTN_set_callback(BTN* btn, BTN_callback callback);
|
||||
```],
|
||||
caption: "Button class header"
|
||||
) <fig:button-class-header>
|
||||
|
||||
=== #gls("ipc", long: false)
|
||||
|
||||
The @ipc provides a server to handle messages from other processes with a socket pair. All is defined in a common file: `src/06-mini-project/common/common_ipc.h`. This file implements the action and the format of the message through the socket.
|
||||
|
||||
#pagebreak()
|
||||
=== #gls("oled", long: false)
|
||||
The @oled part has nothing special, we basically use the provided example. But we had to modify the devicetree to add the @i2c that control the screen. It was the first time we had to modify the buildroot part. We forgot a bit how it's absolutely not enough to modify in `/config/board/.../nanopi-neo-plus2.dts`. In the `get-buildroot.sh` script, there is a rsync command that was done only at the full beginning of the semester when we initialize everything. To effectively modify the devicetree, we had to copy our modification, then rebuild (it's short because most parts are already built):
|
||||
|
||||
```bash
|
||||
rsync -a /workspace/config/board/ /buildroot/board/
|
||||
rsync -a /workspace/config/configs/ /buildroot/configs/
|
||||
cd /buildroot
|
||||
make linux-rebuild
|
||||
make uboot-rebuild
|
||||
make
|
||||
```
|
||||
|
||||
Then, if we boot with @tftp, we can simply reboot. Otherwise, we have to reflash the sd card with the new image.
|
||||
|
||||
=== application
|
||||
|
||||
This part is the core of the daemon and provides @api for the @oled screen, the buttons, and the @ipc to set and get values from the module. It uses @sysfs technology to communicate with the kernel.
|
||||
|
||||
It implements some specific action like increase and decrease the period of the @led. It provides too specifics functions for the buttons because it has to signal with the power @led when it is pushed. We called that an animation.
|
||||
|
||||
This animation is managed by a signal and a condition. The function increase and decrease for the buttons increment a counter and send a signal to the animation thread. It handles it and makes the animation until the counter reach 0. Then it waits with the `pthread_cond_wait`.
|
||||
|
||||
|
||||
|
||||
== #gls("cli", long: false)
|
||||
|
||||
The @cli is connected to the daemon through the socketpair define in the `common` as the @ipc. It uses the same struct and actions for changing mode or set, increase, decrease a period.
|
||||
|
||||
It is installed in the `/usr/bin` by the `justfile`. It allows using it from everywhere in the terminal. It can be used as a tool.
|
||||
|
||||
#pagebreak()
|
||||
= Future work
|
||||
#let link-github-project = "https://github.com/users/Klagarge/projects/3/views/1?filterQuery=is%3Aopen"
|
||||
C.f.: #link(link-github-project)[GitHub project] #footnote(link-github-project)
|
||||
|
||||
|
||||
= Conclusion
|
||||
Really fun, but sadly not enough time for more over-engineering. #emoji.face.cry
|
||||
|
||||
#lorem(50)
|
||||
|
||||
|
||||
//-------------------------------------
|
||||
@@ -58,4 +187,3 @@
|
||||
//
|
||||
#heading(numbering:none, outlined: false)[] <sec:end>
|
||||
#make_glossary(gloss:gloss, title:i18n("gloss-title"))
|
||||
|
||||
|
||||
BIN
doc/mini-project/deployement.png
Normal file
|
After Width: | Height: | Size: 138 KiB |
3
doc/mini-project/deployment.uxf
Normal file
@@ -0,0 +1,3 @@
|
||||
<diagram program="umletino" version="15.1"><zoom_level>9</zoom_level><element><id>UMLDeployment</id><coordinates><x>63</x><y>324</y><w>342</w><h>234</h></coordinates><panel_attributes>Kernel module</panel_attributes><additional_attributes></additional_attributes></element><element><id>UMLDeployment</id><coordinates><x>441</x><y>324</y><w>342</w><h>234</h></coordinates><panel_attributes>Daemon</panel_attributes><additional_attributes></additional_attributes></element><element><id>UMLDeployment</id><coordinates><x>675</x><y>261</y><w>81</w><h>45</h></coordinates><panel_attributes>CLI</panel_attributes><additional_attributes></additional_attributes></element><element><id>UMLGeneric</id><coordinates><x>81</x><y>495</y><w>126</w><h>36</h></coordinates><panel_attributes>blink</panel_attributes><additional_attributes></additional_attributes></element><element><id>UMLGeneric</id><coordinates><x>243</x><y>495</y><w>126</w><h>36</h></coordinates><panel_attributes>temperature</panel_attributes><additional_attributes></additional_attributes></element><element><id>UMLGeneric</id><coordinates><x>243</x><y>369</y><w>126</w><h>36</h></coordinates><panel_attributes>sysfs</panel_attributes><additional_attributes></additional_attributes></element><element><id>UMLGeneric</id><coordinates><x>162</x><y>432</y><w>126</w><h>36</h></coordinates><panel_attributes>symbol=component
|
||||
regulator</panel_attributes><additional_attributes></additional_attributes></element><element><id>Relation</id><coordinates><x>216</x><y>378</y><w>45</w><h>72</h></coordinates><panel_attributes>lt=<-</panel_attributes><additional_attributes>30;10;10;10;10;60</additional_attributes></element><element><id>Relation</id><coordinates><x>117</x><y>441</y><w>63</w><h>72</h></coordinates><panel_attributes>lt=-></panel_attributes><additional_attributes>50;10;10;10;10;60</additional_attributes></element><element><id>Relation</id><coordinates><x>279</x><y>441</y><w>63</w><h>72</h></coordinates><panel_attributes>lt=-></panel_attributes><additional_attributes>10;10;50;10;50;60</additional_attributes></element><element><id>UMLGeneric</id><coordinates><x>459</x><y>495</y><w>126</w><h>36</h></coordinates><panel_attributes>gpio</panel_attributes><additional_attributes></additional_attributes></element><element><id>UMLGeneric</id><coordinates><x>621</x><y>369</y><w>126</w><h>36</h></coordinates><panel_attributes>ipc</panel_attributes><additional_attributes></additional_attributes></element><element><id>UMLGeneric</id><coordinates><x>621</x><y>495</y><w>126</w><h>36</h></coordinates><panel_attributes>oled</panel_attributes><additional_attributes></additional_attributes></element><element><id>UMLGeneric</id><coordinates><x>549</x><y>432</y><w>126</w><h>36</h></coordinates><panel_attributes>symbol=component
|
||||
application</panel_attributes><additional_attributes></additional_attributes></element><element><id>Relation</id><coordinates><x>360</x><y>378</y><w>225</w><h>72</h></coordinates><panel_attributes>lt=<-</panel_attributes><additional_attributes>10;10;230;10;230;60</additional_attributes></element><element><id>Relation</id><coordinates><x>504</x><y>441</y><w>63</w><h>72</h></coordinates><panel_attributes>lt=-></panel_attributes><additional_attributes>50;10;10;10;10;60</additional_attributes></element><element><id>Relation</id><coordinates><x>666</x><y>441</y><w>63</w><h>72</h></coordinates><panel_attributes>lt=-></panel_attributes><additional_attributes>10;10;50;10;50;60</additional_attributes></element><element><id>Relation</id><coordinates><x>594</x><y>378</y><w>45</w><h>72</h></coordinates><panel_attributes>lt=<-</panel_attributes><additional_attributes>30;10;10;10;10;60</additional_attributes></element><element><id>Relation</id><coordinates><x>702</x><y>297</y><w>27</w><h>90</h></coordinates><panel_attributes>lt=<-</panel_attributes><additional_attributes>10;80;10;10</additional_attributes></element></diagram>
|
||||
@@ -27,6 +27,208 @@
|
||||
description: "Rust is a modern systems programming language focused on safety, speed, and concurrency. It prevents common programming errors such as null pointer dereferencing and data races at compile time, making it a preferred choice for performance-critical applications.",
|
||||
group: "Programming Language"
|
||||
),
|
||||
(
|
||||
key: "csel",
|
||||
short: "CSEL",
|
||||
long: "Conception de Systèmes Embarqués sous Linux",
|
||||
description: "Embedded Linux Systems Design course at HES-SO, covering kernel development, driver programming, and system optimization.",
|
||||
group: "Course"
|
||||
),
|
||||
(
|
||||
key: "cpu",
|
||||
short: "CPU",
|
||||
long: "Central Processing Unit",
|
||||
description: "The primary component of a computer that performs most of the processing inside the computer, executing instructions of computer programs.",
|
||||
group: "Hardware"
|
||||
),
|
||||
(
|
||||
key: "l1",
|
||||
short: "L1",
|
||||
long: "Level 1 Cache",
|
||||
description: "The primary cache of a CPU, typically built directly into the processor chip, representing the fastest but smallest cache level closest to the execution units.",
|
||||
group: "Hardware"
|
||||
),
|
||||
(
|
||||
key: "l2",
|
||||
short: "L2",
|
||||
long: "Level 2 Cache",
|
||||
description: "A secondary cache that is larger but slightly slower than the L1 cache, serving to catch cache misses from the L1 cache before querying system memory.",
|
||||
group: "Hardware"
|
||||
),
|
||||
(
|
||||
key: "ram",
|
||||
short: "RAM",
|
||||
long: "Random-Access Memory",
|
||||
description: "A form of volatile computer memory that can be read and changed in any order, used to store working data and machine code currently in use.",
|
||||
group: "Hardware"
|
||||
),
|
||||
(
|
||||
key: "pc",
|
||||
short: "PC",
|
||||
long: "Program Counter",
|
||||
description: "A processor register that indicates where the computer is in its program sequence, holding the address of the next instruction to be executed.",
|
||||
group: "Hardware"
|
||||
),
|
||||
(
|
||||
key: "led",
|
||||
short: "LED",
|
||||
plural: "LEDS",
|
||||
long: "Light Emitting Diode",
|
||||
description: "A semiconductor light source that emits light when current flows through it.",
|
||||
group: "Hardware"
|
||||
),
|
||||
(
|
||||
key: "gpio",
|
||||
short: "GPIO",
|
||||
plural: "GPIOs",
|
||||
long: "General-Purpose Input/Output",
|
||||
description: "Uncommitted digital signal pins on an integrated circuit or electronic circuit board whose behavior can be programmed as input or output at runtime.",
|
||||
group: "Hardware"
|
||||
),
|
||||
(
|
||||
key: "pid",
|
||||
short: "PID",
|
||||
plural: "PIDs",
|
||||
long: "Process Identifier",
|
||||
description: "A unique numerical identifier assigned by the operating system kernel to each active process, used for managing, scheduling, and tracking processes.",
|
||||
group: "Operating System"
|
||||
),
|
||||
(
|
||||
key: "irq",
|
||||
short: "IRQ",
|
||||
plural: "IRQs",
|
||||
long: "Interrupt Request",
|
||||
description: "A signal sent to the processor that temporarily suspends the current program execution to allow an Interrupt Service Routine (ISR) to run in response to a hardware event.",
|
||||
group: "Operating System"
|
||||
),
|
||||
(
|
||||
key: "gpu",
|
||||
short: "GPU",
|
||||
long: "Graphics Processing Unit",
|
||||
description: "A specialized electronic circuit designed to accelerate graphics rendering and parallel computing tasks.",
|
||||
group: "Hardware"
|
||||
),
|
||||
(
|
||||
key: "cuda",
|
||||
short: "CUDA",
|
||||
long: "Compute Unified Device Architecture",
|
||||
description: "A parallel computing platform and application programming interface model created by NVIDIA.",
|
||||
group: "Programming API"
|
||||
),
|
||||
(
|
||||
key: "openmp",
|
||||
short: "OpenMP",
|
||||
long: "Open Multi-Processing",
|
||||
description: "An application programming interface that supports multi-platform shared-memory multiprocessing programming.",
|
||||
group: "Programming API"
|
||||
),
|
||||
(
|
||||
key: "io",
|
||||
short: "I/O",
|
||||
long: "Input/Output",
|
||||
description: "The communication between an information processing system (such as a computer) and the outside world.",
|
||||
group: "Computer Science"
|
||||
),
|
||||
(
|
||||
key: "ip",
|
||||
short: "IP",
|
||||
plural: "IPs",
|
||||
long: "Internet Protocol",
|
||||
description: "The principal communications protocol in the Internet protocol suite for relaying datagrams across network boundaries.",
|
||||
group: "Computer Science"
|
||||
),
|
||||
(
|
||||
key: "oom",
|
||||
short: "OOM",
|
||||
long: "Out of Memory",
|
||||
description: "A state of computer operation where no additional memory can be allocated, often leading to the invocation of an OOM killer to terminate processes.",
|
||||
group: "Operating System"
|
||||
),
|
||||
(
|
||||
key: "sysfs",
|
||||
short: "sysfs",
|
||||
long: "System Filesystem",
|
||||
description: "A virtual pseudo-filesystem provided by the Linux kernel that exports information about hardware, device drivers, and kernel subsystems to user space.",
|
||||
group: "Operating System"
|
||||
),
|
||||
(
|
||||
key: "syslog",
|
||||
short: "syslog",
|
||||
long: "System Logging",
|
||||
description: "A standard protocol and utility for system message logging in UNIX and Linux systems, allowing applications to log messages to files, consoles, or remote syslog daemons.",
|
||||
group: "Operating System"
|
||||
),
|
||||
(
|
||||
key: "perf",
|
||||
short: "perf",
|
||||
long: "Performance Events for Linux",
|
||||
description: "A powerful performance supervising and analyzing tool in Linux, capable of profiling hardware performance counters, tracepoints, software performance counters, and dynamic probes.",
|
||||
group: "Operating System"
|
||||
),
|
||||
(
|
||||
key: "epoll",
|
||||
short: "epoll",
|
||||
long: "Event Poll",
|
||||
description: "A scalable Linux I/O event notification facility designed to monitor multiple file descriptors with high efficiency.",
|
||||
group: "Operating System"
|
||||
),
|
||||
(
|
||||
key: "cgroup",
|
||||
short: "cgroup",
|
||||
plural: "cgroups",
|
||||
long: "Control Groups",
|
||||
description: "A Linux kernel feature that limits, polices, and isolates resource usage (such as CPU, memory, and disk I/O) for groups of processes.",
|
||||
group: "Operating System"
|
||||
),
|
||||
(
|
||||
key: "mib",
|
||||
short: "MiB",
|
||||
plural: "MiBs",
|
||||
long: "Mebibyte",
|
||||
description: "A unit of digital information equal to 1,048,576 bytes (2^20 bytes).",
|
||||
group: "Computer Science"
|
||||
),
|
||||
(
|
||||
key: "ipc",
|
||||
short: "IPC",
|
||||
long: "Inter-Process Communication",
|
||||
description: "A set of programming interfaces that allow processes to communicate with each other and synchronize their actions.",
|
||||
group: "Operating System"
|
||||
),
|
||||
(
|
||||
key: "tftp",
|
||||
short: "TFTP",
|
||||
long: "Trivial File Transfer Protocol",
|
||||
description: "A simple protocol for transferring files, typically used for booting devices over a network.",
|
||||
group: "Networking"
|
||||
),
|
||||
(
|
||||
key: "cli",
|
||||
short: "CLI",
|
||||
long: "Command Line Interface",
|
||||
description: "A text-based interface used to interact with software and operating systems by typing commands into a terminal.",
|
||||
group: "Computer Science"
|
||||
),
|
||||
(
|
||||
key: "api",
|
||||
short: "API",
|
||||
long: "Application Programming Interface",
|
||||
description: "A set of defined rules that enable different software applications to communicate with each other.",
|
||||
group: "Computer Science"
|
||||
),
|
||||
(
|
||||
key: "i2c",
|
||||
short: "I2C",
|
||||
long: "Inter-Integrated Circuit",
|
||||
description: "A synchronous, multi-controller/multi-target, single-ended, serial communication bus used for attaching lower-speed peripheral ICs to processors and microcontrollers.",
|
||||
group: "Hardware"
|
||||
),
|
||||
(
|
||||
key: "oled",
|
||||
short: "OLED",
|
||||
description: "A light-emitting diode (LED) in which the emissive electroluminescent layer is a film of organic compound that emits light in response to an electric current.",
|
||||
group: "Hardware"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -54,6 +256,7 @@
|
||||
show-all: false,
|
||||
// disable the back ref at the end of the descriptions
|
||||
disable-back-references: false,
|
||||
shorthands: ("plural", "capitalize", "capitalize-plural", "short", "long"),
|
||||
)
|
||||
]}
|
||||
]}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
cmake_minimum_required(VERSION 3.28)
|
||||
project(ex7-app)
|
||||
|
||||
include(../../nanopi.cmake)
|
||||
add_executable(silly_led_control silly_led_control.c)
|
||||
@@ -1,12 +1,13 @@
|
||||
# Makefile for CMake project with intelligent configuration
|
||||
|
||||
|
||||
# Default target
|
||||
all: build/build.ninja
|
||||
all: build/build.ninja
|
||||
cmake --build build
|
||||
|
||||
# Create build directory and generate build files if needed
|
||||
build/build.ninja : CMakeLists.txt
|
||||
cmake -S . -B build -G "Ninja"
|
||||
cmake -S . -B build -G "Ninja" -DCMAKE_TOOLCHAIN_FILE=../../nanopi.cmake
|
||||
|
||||
# Clean build directory
|
||||
clean:
|
||||
@@ -16,4 +17,4 @@ clean:
|
||||
rebuild: clean all
|
||||
|
||||
# Phony targets (targets that don't represent files)
|
||||
.PHONY: all clean rebuild
|
||||
.PHONY: all clean rebuild
|
||||
|
||||
@@ -16,7 +16,7 @@ void HostCounter::notifyHost(std::string hostname)
|
||||
// add the host in the list if not already in
|
||||
if(isNewHost(hostname))
|
||||
{
|
||||
myHosts.push_back(hostname);
|
||||
myHosts.insert(hostname);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#include <string>
|
||||
|
||||
#include <vector>
|
||||
#include <set>
|
||||
|
||||
class HostCounter
|
||||
{
|
||||
@@ -18,5 +18,5 @@ class HostCounter
|
||||
// check if host is already in the list
|
||||
bool isNewHost(std::string hostname);
|
||||
|
||||
std::vector< std::string > myHosts;
|
||||
std::set< std::string > myHosts;
|
||||
};
|
||||
|
||||
@@ -28,8 +28,7 @@ clean:
|
||||
|
||||
install:
|
||||
$(MAKE) -C $(KDIR) M=$(PWD) INSTALL_MOD_PATH=$(MODPATH) modules_install
|
||||
install -d $(MODPATH)/etc/modprobe.d
|
||||
install -m 0644 $(SOURCE).conf $(MODPATH)/etc/modprobe.d/$(SOURCE).conf
|
||||
install -D -m 0644 $(SOURCE).conf $(MODPATH)/etc/modprobe.d/$(SOURCE).conf
|
||||
|
||||
endif
|
||||
|
||||
|
||||
90
src/01-skeleton/kernel-module/s02e07-sleeping.c
Normal file
@@ -0,0 +1,90 @@
|
||||
#include <linux/module.h> // needed by all modules
|
||||
#include <linux/init.h> // needed for macros
|
||||
#include <linux/kernel.h> // needed for debugging
|
||||
|
||||
#include <linux/kthread.h>
|
||||
#include <linux/delay.h>
|
||||
#include <linux/wait.h>
|
||||
#include <linux/atomic.h>
|
||||
|
||||
#define TIMEOUT_S 5
|
||||
|
||||
DECLARE_WAIT_QUEUE_HEAD(queue_1);
|
||||
DECLARE_WAIT_QUEUE_HEAD(queue_2);
|
||||
|
||||
static struct task_struct* thread_1;
|
||||
static struct task_struct* thread_2;
|
||||
static atomic_t trigger = ATOMIC_INIT(0);
|
||||
|
||||
int thread_skeleton_1(void* data) {
|
||||
// must wait 5 seconds and start thread 2
|
||||
|
||||
pr_info("Thread 1 started\n");
|
||||
|
||||
while (!kthread_should_stop()) {
|
||||
pr_info("Thread 1 wakes up\n");
|
||||
ssleep(TIMEOUT_S);
|
||||
|
||||
// Setup trigger for condition of the thread 2
|
||||
atomic_set(&trigger, 1);
|
||||
|
||||
// Wake up thread 2
|
||||
wake_up_interruptible(&queue_2);
|
||||
|
||||
// Wait until thread 2 has reset the trigger
|
||||
wait_event_interruptible(queue_1, atomic_read(&trigger) == 0 || kthread_should_stop());
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int thread_skeleton_2(void* data) {
|
||||
// have to PING when wakes up
|
||||
|
||||
pr_info("Thread 2 started\n");
|
||||
|
||||
|
||||
while (!kthread_should_stop()) {
|
||||
|
||||
// wait until trigger is set up
|
||||
wait_event_interruptible(queue_2, atomic_read(&trigger) == 1 || kthread_should_stop());
|
||||
pr_info("Thread 2 wakes up\n");
|
||||
|
||||
// reset trigger
|
||||
atomic_set(&trigger, 0);
|
||||
|
||||
// wake up thread 1
|
||||
wake_up_interruptible(&queue_1);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
void sleeping_init(void) {
|
||||
pr_info("Initialize kernel thread\n");
|
||||
|
||||
atomic_set(&trigger, 0);
|
||||
|
||||
thread_1 = kthread_run(thread_skeleton_1, NULL, "Thread 1 - sleeping");
|
||||
if (IS_ERR(thread_1)) {
|
||||
pr_err("Failed to create kernel thread 1\n");
|
||||
return;
|
||||
}
|
||||
|
||||
thread_2 = kthread_run(thread_skeleton_2, NULL, "Thread 2 - sleeping");
|
||||
if (IS_ERR(thread_2)) {
|
||||
pr_err("Failed to create kernel thread 1\n");
|
||||
return;
|
||||
}
|
||||
|
||||
pr_info("Kernel thread sleeping initialized\n");
|
||||
|
||||
}
|
||||
|
||||
void sleeping_exit(void) {
|
||||
pr_info("Exiting kernel sleeping thread\n");
|
||||
kthread_stop(thread_1);
|
||||
kthread_stop(thread_2);
|
||||
pr_info("Kernel thread sleeping exited\n");
|
||||
}
|
||||
80
src/01-skeleton/kernel-module/s02e08-interrupt.c
Normal file
@@ -0,0 +1,80 @@
|
||||
#include <linux/module.h> // needed by all modules
|
||||
#include <linux/init.h> // needed for macros
|
||||
#include <linux/kernel.h> // needed for debugging
|
||||
|
||||
#include <linux/interrupt.h>
|
||||
#include <linux/gpio.h>
|
||||
#include "linux/printk.h"
|
||||
|
||||
struct gpio_nanopi {
|
||||
int id;
|
||||
char* name;
|
||||
};
|
||||
|
||||
static struct gpio_nanopi switchK1 = {0, "K1: GPIOA.0"};
|
||||
static struct gpio_nanopi switchK2 = {2, "K2: GPIOA.2"};
|
||||
static struct gpio_nanopi switchK3 = {3, "K3: GPIOA.3"};
|
||||
|
||||
irqreturn_t isrGPIO(int irq, void* gpio_struct) {
|
||||
struct gpio_nanopi *gpio = (struct gpio_nanopi *)gpio_struct;
|
||||
pr_info("GPIO pressed: %s\n", gpio->name);
|
||||
return IRQ_HANDLED;
|
||||
}
|
||||
|
||||
|
||||
void interrupt_init(void) {
|
||||
pr_info("Initializing interrupts\n");
|
||||
|
||||
int status = 0;
|
||||
|
||||
// Switch k1
|
||||
if (gpio_request(switchK1.id, switchK1.name) == 0) {
|
||||
status = request_irq(
|
||||
gpio_to_irq(switchK1.id),
|
||||
isrGPIO,
|
||||
IRQF_TRIGGER_FALLING | IRQF_SHARED,
|
||||
switchK1.name,
|
||||
&switchK1
|
||||
);
|
||||
}
|
||||
|
||||
// Switch k2
|
||||
if (gpio_request(switchK2.id, switchK2.name) == 0) {
|
||||
status = request_irq(
|
||||
gpio_to_irq(switchK2.id),
|
||||
isrGPIO,
|
||||
IRQF_TRIGGER_FALLING | IRQF_SHARED,
|
||||
switchK2.name,
|
||||
&switchK2
|
||||
);
|
||||
}
|
||||
|
||||
// Switch k3
|
||||
if (gpio_request(switchK3.id, switchK3.name) == 0) {
|
||||
status = request_irq(
|
||||
gpio_to_irq(switchK3.id),
|
||||
isrGPIO,
|
||||
IRQF_TRIGGER_FALLING | IRQF_SHARED,
|
||||
switchK3.name,
|
||||
&switchK3
|
||||
);
|
||||
}
|
||||
|
||||
pr_info("Interrupt initialized\n");
|
||||
}
|
||||
|
||||
void interrupt_exit(void) {
|
||||
pr_info("Exiting interrupts\n");
|
||||
|
||||
gpio_free(switchK1.id);
|
||||
free_irq(gpio_to_irq(switchK1.id), &switchK1);
|
||||
|
||||
gpio_free(switchK2.id);
|
||||
free_irq(gpio_to_irq(switchK2.id), &switchK2);
|
||||
|
||||
gpio_free(switchK3.id);
|
||||
free_irq(gpio_to_irq(switchK3.id), &switchK3);
|
||||
|
||||
pr_info ("Interrupt exited\n");
|
||||
|
||||
}
|
||||
@@ -3,58 +3,105 @@
|
||||
#include <linux/init.h> // needed for macros
|
||||
#include <linux/kernel.h> // needed for debugging
|
||||
|
||||
#include "s02e02-parameters.c"
|
||||
#include "s02e04-dynamic_allocation.c"
|
||||
#include "s02e05-io_memory_mapped.c"
|
||||
#include "s02e06-thread.c"
|
||||
#include "linux/printk.h"
|
||||
#include "kernel-module/s02e02-parameters.c"
|
||||
// #define PARAMETERS
|
||||
|
||||
#include "kernel-module/s02e04-dynamic_allocation.c"
|
||||
// #define DYNAMIC_ALLOCATION
|
||||
|
||||
#include "kernel-module/s02e05-io_memory_mapped.c"
|
||||
// #define IO_MEMORY_MAPPED
|
||||
|
||||
#include "kernel-module/s02e06-thread.c"
|
||||
// #define THREAD
|
||||
|
||||
#include "kernel-module/s02e07-sleeping.c"
|
||||
// #define SLEEPING
|
||||
|
||||
#include "kernel-module/s02e08-interrupt.c"
|
||||
#define INTERRUPT
|
||||
|
||||
|
||||
static int __init skeleton_init(void) {
|
||||
pr_info("Linux module skeleton ex05 loading...\n");
|
||||
pr_info("--------------------\n");
|
||||
|
||||
// Lab02 - Exercise 2: Parameters
|
||||
#ifdef PARAMETERS
|
||||
pr_info("--------------------\n");
|
||||
parameters_print();
|
||||
|
||||
pr_info("--------------------\n");
|
||||
#endif
|
||||
|
||||
// Lab02 - Exercise 4: Dynamic memory allocation and linked list
|
||||
dynAlloc_init();
|
||||
|
||||
#ifdef DYNAMIC_ALLOCATION
|
||||
pr_info("--------------------\n");
|
||||
Alloc_init();
|
||||
#endif
|
||||
|
||||
// Lab02 - Exercise 5: Memory-mapped I/O
|
||||
ioMemoryMapped_init();
|
||||
|
||||
#ifdef IO_MEMORY_MAPPED
|
||||
pr_info("--------------------\n");
|
||||
ioMemoryMapped_init();
|
||||
#endif
|
||||
|
||||
// Lab02 - Exercise 6: Kernel thread
|
||||
#ifdef THREAD
|
||||
pr_info("--------------------\n");
|
||||
thread_init();
|
||||
#endif
|
||||
|
||||
// Lab02 - Exercise 7: Sleeping
|
||||
#ifdef SLEEPING
|
||||
pr_info("--------------------\n");
|
||||
sleeping_init();
|
||||
#endif
|
||||
|
||||
// Lab02 - Exercise 8: Interrupt
|
||||
#ifdef INTERRUPT
|
||||
pr_info("--------------------\n");
|
||||
interrupt_init();
|
||||
#endif
|
||||
|
||||
pr_info("--------------------\n");
|
||||
|
||||
pr_info("Linux module skeleton loaded\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void __exit skeleton_exit(void) {
|
||||
|
||||
|
||||
// Lab02 - Exercise 4: Dynamic memory allocation and linked list
|
||||
dynAlloc_exit();
|
||||
pr_info("Linux module skeleton unloading...\n");
|
||||
|
||||
// Lab02 - Exercise 4: Dynamic memory allocation and linked list
|
||||
#ifdef DYNAMIC_ALLOCATION
|
||||
pr_info("--------------------\n");
|
||||
dynAlloc_exit();
|
||||
#endif
|
||||
|
||||
// Lab02 - Exercise 5: Memory-mapped I/O
|
||||
ioMemoryMapped_exit();
|
||||
|
||||
#ifdef IO_MEMORY_MAPPED
|
||||
pr_info("--------------------\n");
|
||||
ioMemoryMapped_exit();
|
||||
#endif
|
||||
|
||||
// Lab02 - Exercise 6: Kernel thread
|
||||
#ifdef THREAD
|
||||
pr_info("--------------------\n");
|
||||
thread_exit();
|
||||
#endif
|
||||
|
||||
// Lab02 - Exercise 7: Sleeping
|
||||
#ifdef SLEEPING
|
||||
pr_info("--------------------\n");
|
||||
sleeping_exit();
|
||||
#endif
|
||||
|
||||
// Lab02 - Exercise 8: Interrupt
|
||||
#ifdef INTERRUPT
|
||||
pr_info("--------------------\n");
|
||||
interrupt_exit();
|
||||
#endif
|
||||
|
||||
pr_info("--------------------\n");
|
||||
|
||||
pr_info ("Linux module skeleton unloaded\n");
|
||||
}
|
||||
|
||||
|
||||
13
src/02-driver/.clangd
Normal file
@@ -0,0 +1,13 @@
|
||||
CompileFlags:
|
||||
Add:
|
||||
# Architecture and cross-compilation
|
||||
- "--target=aarch64-linux-gnu"
|
||||
|
||||
# Setup sysroot for buildroot
|
||||
- "--sysroot=/buildroot/output/host/aarch64-buildroot-linux-gnu/sysroot"
|
||||
|
||||
# Add specific header of linux from buildroot
|
||||
- "-I/buildroot/output/build/linux-headers-5.15.148/include"
|
||||
- "-I/buildroot/output/build/linux-headers-5.15.148/arch/arm64/include"
|
||||
- "-I/buildroot/output/build/linux-headers-5.15.148/arch/arm64/include/generated"
|
||||
- "-I/buildroot/output/build/linux-headers-5.15.148/**"
|
||||
44
src/02-driver/Makefile
Normal file
@@ -0,0 +1,44 @@
|
||||
EXE=app
|
||||
SRCS=$(wildcard *.c)
|
||||
|
||||
ifeq ($(target),)
|
||||
target=nano
|
||||
endif
|
||||
|
||||
CFLAGS=-Wall -Wextra -g -c -O0 -MD -std=gnu11
|
||||
|
||||
TOOLCHAIN_PATH=/buildroot/output/host/usr/bin/
|
||||
TOOLCHAIN=$(TOOLCHAIN_PATH)aarch64-linux-
|
||||
CFLAGS+=-mcpu=cortex-a53 -funwind-tables
|
||||
##CFLAGS+=-O2 -fno-omit-frame-pointer
|
||||
OBJDIR=.obj/nano
|
||||
EXEC=$(EXE)
|
||||
|
||||
CC=$(TOOLCHAIN)gcc
|
||||
LD=$(TOOLCHAIN)gcc
|
||||
AR=$(TOOLCHAIN)ar
|
||||
STRIP=$(TOOLCHAIN)strip
|
||||
|
||||
OBJDIR=.obj/$(target)
|
||||
OBJS= $(addprefix $(OBJDIR)/, $(SRCS:.c=.o))
|
||||
|
||||
$(OBJDIR)/%o: %c
|
||||
$(CC) $(CFLAGS) $< -o $@
|
||||
|
||||
all: $(OBJDIR)/ $(EXEC)
|
||||
|
||||
$(EXEC): $(OBJS) $(LINKER_SCRIPT)
|
||||
$(LD) $(OBJS) $(LDFLAGS) -o $@
|
||||
|
||||
$(OBJDIR)/:
|
||||
mkdir -p $(OBJDIR)
|
||||
|
||||
clean:
|
||||
rm -Rf $(OBJDIR) $(EXEC) $(EXEC)_s *~
|
||||
|
||||
clean_all: clean
|
||||
rm -Rf .obj $(EXE) $(EXE)_s $(EXE)_a $(EXE)_a_s $(EXE)_h $(EXE)_h_s
|
||||
|
||||
-include $(OBJS:.o=.d)
|
||||
|
||||
.PHONY: all clean clean_all
|
||||
33
src/02-driver/character-oriented/.clangd
Normal file
@@ -0,0 +1,33 @@
|
||||
CompileFlags:
|
||||
Add:
|
||||
# Architecture and cross-compilation
|
||||
- "--target=aarch64-linux-gnu"
|
||||
|
||||
# Exclude standard library
|
||||
- "-nostdinc"
|
||||
|
||||
# Mandatory kernel definitions
|
||||
- "-D__KERNEL__"
|
||||
- "-DMODULE"
|
||||
- "-DCONFIG_CC_HAS_K_CONSTRAINT=1"
|
||||
|
||||
# Force-included files
|
||||
- "-include"
|
||||
- "/buildroot/output/build/linux-5.15.148/include/linux/compiler-version.h"
|
||||
- "-include"
|
||||
- "/buildroot/output/build/linux-5.15.148/include/linux/kconfig.h"
|
||||
- "-include"
|
||||
- "/buildroot/output/build/linux-5.15.148/include/linux/compiler_types.h"
|
||||
|
||||
# Kernel include paths
|
||||
- "-I/buildroot/output/build/linux-5.15.148/arch/arm64/include"
|
||||
- "-I/buildroot/output/build/linux-5.15.148/arch/arm64/include/generated"
|
||||
- "-I/buildroot/output/build/linux-5.15.148/include"
|
||||
- "-I/buildroot/output/build/linux-5.15.148/arch/arm64/include/uapi"
|
||||
- "-I/buildroot/output/build/linux-5.15.148/arch/arm64/include/generated/uapi"
|
||||
- "-I/buildroot/output/build/linux-5.15.148/include/uapi"
|
||||
- "-I/buildroot/output/build/linux-5.15.148/include/generated/uapi"
|
||||
|
||||
# GCC compiler system include path
|
||||
- "-isystem"
|
||||
- "/buildroot/output/host/lib/gcc/aarch64-buildroot-linux-gnu/11.3.0/include"
|
||||
22
src/02-driver/character-oriented/Makefile
Normal file
@@ -0,0 +1,22 @@
|
||||
# Part executed when called from kernel build system:
|
||||
ifneq ($(KERNELRELEASE),)
|
||||
obj-m += mymodule.o ## name of the generated module
|
||||
|
||||
mymodule-objs := skeleton.o ## list of objects needed for that module
|
||||
|
||||
# Part executed when called from standard make in module source directory:
|
||||
else
|
||||
include ../../buildroot_path
|
||||
include ../../kernel_settings
|
||||
PWD := $(shell pwd)
|
||||
|
||||
all:
|
||||
$(MAKE) -C $(KDIR) M=$(PWD) ARCH=$(CPU) CROSS_COMPILE=$(TOOLS) modules
|
||||
|
||||
clean:
|
||||
$(MAKE) -C $(KDIR) M=$(PWD) clean
|
||||
|
||||
install:
|
||||
$(MAKE) -C $(KDIR) M=$(PWD) INSTALL_MOD_PATH=$(MODPATH) modules_install
|
||||
|
||||
endif
|
||||
185
src/02-driver/character-oriented/skeleton.c
Normal file
@@ -0,0 +1,185 @@
|
||||
#include <linux/module.h> // needed by all modules
|
||||
#include <linux/moduleparam.h>
|
||||
#include <linux/init.h> // needed for macros
|
||||
#include <linux/kernel.h> // needed for debugging
|
||||
#include <linux/fs.h>
|
||||
#include <linux/types.h>
|
||||
#include <linux/kdev_t.h>
|
||||
#include <linux/cdev.h>
|
||||
#include <linux/minmax.h>
|
||||
#include <stddef.h>
|
||||
#include <linux/uaccess.h>
|
||||
#include <linux/slab.h> // dynamic memory allocation
|
||||
|
||||
|
||||
// linux theory: https://linux-kernel-labs.github.io/refs/heads/master/labs/device_drivers.html
|
||||
|
||||
|
||||
#define MY_MAJOR 42
|
||||
#define MY_MAX_MINORS 5
|
||||
|
||||
#define BUFFER_SIZE 300
|
||||
|
||||
// setup as argument the number of buffer available in the device
|
||||
static int instances = 3;
|
||||
module_param(instances, int, 0);
|
||||
|
||||
struct my_device_data {
|
||||
dev_t dev_t;
|
||||
struct cdev cdev;
|
||||
/* my data starts here */
|
||||
char** buffers;
|
||||
};
|
||||
|
||||
struct my_device_data devs;
|
||||
|
||||
// inode: https://www.kernel.org/doc/html/latest/filesystems/ext4/inodes.html
|
||||
// file: https://docs.kernel.org/filesystems/api-summary.html#c.file
|
||||
|
||||
int skeleton_open(struct inode* i, struct file* f) {
|
||||
|
||||
pr_info("Open file \n major:%d\n minor:%d\n",
|
||||
imajor(i),
|
||||
iminor(i));
|
||||
|
||||
if (iminor(i) >= instances) {
|
||||
return -EFAULT;
|
||||
}
|
||||
|
||||
if ((f->f_mode & (FMODE_READ | FMODE_WRITE)) != 0) {
|
||||
pr_info("skeleton : opened for reading & writing...\n");
|
||||
} else if ((f->f_mode & FMODE_READ) != 0) {
|
||||
pr_info("skeleton : opened for reading...\n");
|
||||
} else if ((f->f_mode & FMODE_WRITE) != 0) {
|
||||
pr_info("skeleton : opened for writing...\n");
|
||||
}
|
||||
|
||||
// Get the stuct of my data
|
||||
struct my_device_data *my_data = container_of(i->i_cdev, struct my_device_data, cdev);
|
||||
|
||||
// point private data on driver data, here this is a char buffer
|
||||
// point on the right minor buffer
|
||||
f->private_data = my_data->buffers[iminor(i)];
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int skeleton_release(struct inode* i, struct file* f) {
|
||||
|
||||
pr_info("Release file\n");
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
ssize_t skeleton_read(struct file* f, char* __user buf, size_t count, loff_t* off) {
|
||||
|
||||
pr_info("Read file\n");
|
||||
|
||||
if (*off >= BUFFER_SIZE) {
|
||||
return 0; // End of the file
|
||||
}
|
||||
|
||||
ssize_t len = min((size_t)(BUFFER_SIZE - *off), count);
|
||||
|
||||
if (copy_to_user(buf, f->private_data + *off, len)) {
|
||||
pr_info("Failed to copy to user space buffer\n");
|
||||
return -EFAULT;
|
||||
}
|
||||
|
||||
*off += len;
|
||||
return len;
|
||||
}
|
||||
|
||||
ssize_t skeleton_write(struct file* f, const char* __user buf, size_t count, loff_t* off) {
|
||||
|
||||
pr_info("Write file\n");
|
||||
|
||||
if (*off >= BUFFER_SIZE) {
|
||||
return -ENOSPC; // No more space in buffer
|
||||
}
|
||||
|
||||
ssize_t len = min((size_t)(BUFFER_SIZE - *off), count);
|
||||
|
||||
if (copy_from_user(f->private_data + *off, buf, len)) {
|
||||
pr_info("Failed to copy from user space buffer\n");
|
||||
return -EFAULT;
|
||||
}
|
||||
|
||||
*off += len;
|
||||
return len;
|
||||
}
|
||||
|
||||
|
||||
static struct file_operations skeleton_fops = {
|
||||
.owner = THIS_MODULE,
|
||||
.open = skeleton_open,
|
||||
.read = skeleton_read,
|
||||
.write = skeleton_write,
|
||||
.release = skeleton_release,
|
||||
};
|
||||
|
||||
static int __init skeleton_init(void) {
|
||||
int ret = 0;
|
||||
|
||||
pr_info("My module loading...\n");
|
||||
pr_info("----------------------\n");
|
||||
|
||||
pr_info("Load exercice 3\n");
|
||||
|
||||
// ret = register_chrdev_region(MKDEV(MY_MAJOR, 0), instances, "My module"); // register statically
|
||||
|
||||
ret = alloc_chrdev_region(&devs.dev_t, 0, instances, "mymodule"); //allocate major and minor
|
||||
|
||||
if (ret != 0) {
|
||||
/* report error */
|
||||
pr_info("Module registration error: %d\n", ret);
|
||||
return ret;
|
||||
}
|
||||
|
||||
/* initialize devs fields */
|
||||
cdev_init(&devs.cdev, &skeleton_fops); // initialize device with files operations
|
||||
ret = cdev_add(&devs.cdev, devs.dev_t, instances); // notify kernel
|
||||
|
||||
if (ret != 0) {
|
||||
/* report error */
|
||||
pr_info("cdev add error: %d\n", ret);
|
||||
return ret;
|
||||
}
|
||||
|
||||
// allocate the array of buffer
|
||||
int i;
|
||||
devs.buffers = kzalloc(sizeof(char*) * instances, GFP_KERNEL);
|
||||
for (i = 0; i < instances; i++) {
|
||||
devs.buffers[i] = kzalloc(BUFFER_SIZE, GFP_KERNEL);
|
||||
}
|
||||
|
||||
pr_info("----------------------\n");
|
||||
pr_info("My module is loaded\n");
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
static void __exit skeleton_exit(void) {
|
||||
pr_info("My module unloading...\n");
|
||||
pr_info("----------------------\n");
|
||||
|
||||
cdev_del(&devs.cdev);
|
||||
unregister_chrdev_region(devs.dev_t, instances);
|
||||
|
||||
int i;
|
||||
for(i=0; i < instances; i++) {
|
||||
kfree(devs.buffers[i]);
|
||||
}
|
||||
kfree(devs.buffers);
|
||||
|
||||
pr_info("----------------------\n");
|
||||
pr_info("My module is unloaded\n");
|
||||
}
|
||||
|
||||
module_init (skeleton_init);
|
||||
module_exit (skeleton_exit);
|
||||
|
||||
MODULE_AUTHOR("Fastium <fastium.pro@proton.me>");
|
||||
MODULE_AUTHOR("Klagarge <remi@heredero.ch>");
|
||||
MODULE_DESCRIPTION ("Module pilot character oriented");
|
||||
MODULE_LICENSE ("GPL");
|
||||
56
src/02-driver/exercice/ex1-memory-oriented.c
Normal file
@@ -0,0 +1,56 @@
|
||||
#include <fcntl.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/errno.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int ex_memory_oriented(void) {
|
||||
|
||||
int fd = open("/dev/mem", O_RDWR);
|
||||
|
||||
if (fd < 0) {
|
||||
printf("Failed to open /dev/mem: %s\n", strerror(errno));
|
||||
return 1;
|
||||
}
|
||||
|
||||
size_t page_size = getpagesize(); // return the number of byte in a page
|
||||
off_t chip_id_addr = 0x01c14200; // physical address
|
||||
off_t offset = chip_id_addr % page_size; // get the number of page until the chip is address
|
||||
off_t start_page = chip_id_addr - offset; // align with pages
|
||||
|
||||
printf("page_size=0x%x offset=0x%x offset_page=0x%x\n", (unsigned int) page_size, (unsigned int) offset, (unsigned int) start_page);
|
||||
|
||||
// Get register virtual address from /dev/mem of the chip id
|
||||
volatile uint32_t* regs = mmap(0, page_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, start_page);
|
||||
|
||||
if (regs == MAP_FAILED) {
|
||||
printf("Failed to mmap: %s\n", strerror(errno));
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
|
||||
uint32_t chipid[4] = {[0] = 0,};
|
||||
|
||||
// Read values - Chip ID
|
||||
chipid[0] = *(regs + (0x00 + offset) / sizeof(uint32_t));
|
||||
chipid[1] = *(regs + (0x04 + offset) / sizeof(uint32_t));
|
||||
chipid[2] = *(regs + (0x08 + offset) / sizeof(uint32_t));
|
||||
chipid[3] = *(regs + (0x0c + offset) / sizeof(uint32_t));
|
||||
printf(
|
||||
"chipid=%08x'%08x'%08x'%08x\n",
|
||||
chipid[0], chipid[1], chipid[2], chipid[3]
|
||||
);
|
||||
|
||||
// Free space memory of the user¨
|
||||
munmap((void*)regs, page_size);
|
||||
|
||||
// Close the file
|
||||
close(fd);
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
49
src/02-driver/exercice/ex4-character-oriented.c
Normal file
@@ -0,0 +1,49 @@
|
||||
#include <fcntl.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/errno.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#define DATA_LENGTH 70
|
||||
|
||||
static const char* data = "I've got chocolate stuck to the roof of my mouth, so I can't speak\0";
|
||||
|
||||
static char data_read[DATA_LENGTH] = {};
|
||||
|
||||
int ex_character_oriented(void) {
|
||||
printf("Exercice 4 - character oriented\n");
|
||||
|
||||
int ret = 0;
|
||||
|
||||
const char* path = "/dev/toto0\0";
|
||||
|
||||
int fd = open(path, O_RDWR);
|
||||
|
||||
if (fd < 0) {
|
||||
printf("Failed to open /dev/toto0: %s\n (maybe you need to create it)\n", strerror(errno));
|
||||
return 1;
|
||||
}
|
||||
|
||||
ret = write(fd, data, DATA_LENGTH);
|
||||
|
||||
fd = open(path, O_RDWR);
|
||||
|
||||
if(ret < 0) {
|
||||
printf("Failed to write\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
ret = read(fd, data_read, DATA_LENGTH);
|
||||
|
||||
close(fd);
|
||||
|
||||
printf("Read from device: %s\n", path);
|
||||
printf("Content: %s\n", data_read);
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
25
src/02-driver/main.c
Normal file
@@ -0,0 +1,25 @@
|
||||
#include <stdio.h>
|
||||
|
||||
#include "exercice/ex1-memory-oriented.c"
|
||||
// #define MEMORY_ORIENTED
|
||||
|
||||
#include "exercice/ex4-character-oriented.c"
|
||||
#define CHARACTER_ORIENTED
|
||||
|
||||
|
||||
int main() {
|
||||
int ret = 0;
|
||||
|
||||
#ifdef MEMORY_ORIENTED
|
||||
printf("--------------------------------------\n");
|
||||
printf("Exercice 1: Memory oriented exercice\n");
|
||||
ret = ex_memory_oriented();
|
||||
#endif
|
||||
|
||||
#ifdef CHARACTER_ORIENTED
|
||||
printf("--------------------------------------\n");
|
||||
ret = ex_character_oriented();
|
||||
#endif
|
||||
|
||||
return ret;
|
||||
}
|
||||
33
src/02-driver/sysfs/.clangd
Normal file
@@ -0,0 +1,33 @@
|
||||
CompileFlags:
|
||||
Add:
|
||||
# Architecture and cross-compilation
|
||||
- "--target=aarch64-linux-gnu"
|
||||
|
||||
# Exclude standard library
|
||||
- "-nostdinc"
|
||||
|
||||
# Mandatory kernel definitions
|
||||
- "-D__KERNEL__"
|
||||
- "-DMODULE"
|
||||
- "-DCONFIG_CC_HAS_K_CONSTRAINT=1"
|
||||
|
||||
# Force-included files
|
||||
- "-include"
|
||||
- "/buildroot/output/build/linux-5.15.148/include/linux/compiler-version.h"
|
||||
- "-include"
|
||||
- "/buildroot/output/build/linux-5.15.148/include/linux/kconfig.h"
|
||||
- "-include"
|
||||
- "/buildroot/output/build/linux-5.15.148/include/linux/compiler_types.h"
|
||||
|
||||
# Kernel include paths
|
||||
- "-I/buildroot/output/build/linux-5.15.148/arch/arm64/include"
|
||||
- "-I/buildroot/output/build/linux-5.15.148/arch/arm64/include/generated"
|
||||
- "-I/buildroot/output/build/linux-5.15.148/include"
|
||||
- "-I/buildroot/output/build/linux-5.15.148/arch/arm64/include/uapi"
|
||||
- "-I/buildroot/output/build/linux-5.15.148/arch/arm64/include/generated/uapi"
|
||||
- "-I/buildroot/output/build/linux-5.15.148/include/uapi"
|
||||
- "-I/buildroot/output/build/linux-5.15.148/include/generated/uapi"
|
||||
|
||||
# GCC compiler system include path
|
||||
- "-isystem"
|
||||
- "/buildroot/output/host/lib/gcc/aarch64-buildroot-linux-gnu/11.3.0/include"
|
||||
22
src/02-driver/sysfs/Makefile
Normal file
@@ -0,0 +1,22 @@
|
||||
# Part executed when called from kernel build system:
|
||||
ifneq ($(KERNELRELEASE),)
|
||||
obj-m += mymodule.o ## name of the generated module
|
||||
|
||||
mymodule-objs := skeleton.o ## list of objects needed for that module
|
||||
|
||||
# Part executed when called from standard make in module source directory:
|
||||
else
|
||||
include ../../buildroot_path
|
||||
include ../../kernel_settings
|
||||
PWD := $(shell pwd)
|
||||
|
||||
all:
|
||||
$(MAKE) -C $(KDIR) M=$(PWD) ARCH=$(CPU) CROSS_COMPILE=$(TOOLS) modules
|
||||
|
||||
clean:
|
||||
$(MAKE) -C $(KDIR) M=$(PWD) clean
|
||||
|
||||
install:
|
||||
$(MAKE) -C $(KDIR) M=$(PWD) INSTALL_MOD_PATH=$(MODPATH) modules_install
|
||||
|
||||
endif
|
||||
60
src/02-driver/sysfs/skeleton.c
Normal file
@@ -0,0 +1,60 @@
|
||||
#include <linux/init.h> /* needed for macros */
|
||||
#include <linux/kernel.h> /* needed for debugging */
|
||||
#include <linux/module.h> /* needed by all modules */
|
||||
|
||||
#include <linux/cdev.h> /* needed for char device driver */
|
||||
#include <linux/fs.h> /* needed for device drivers */
|
||||
#include <linux/uaccess.h> /* needed to copy data to/from user */
|
||||
|
||||
#include <linux/device.h> /* needed for sysfs handling */
|
||||
#include <linux/miscdevice.h>
|
||||
#include <linux/platform_device.h> /* needed for sysfs handling */
|
||||
|
||||
static int val;
|
||||
|
||||
ssize_t sysfs_show_val(struct device* dev, struct device_attribute* attr, char* buf) {
|
||||
pr_info("sysfs_show_val: val=%d\n", val);
|
||||
sprintf(buf, "%d\n", val);
|
||||
return strlen(buf);
|
||||
}
|
||||
|
||||
ssize_t sysfs_store_val(struct device* dev, struct device_attribute* attr, const char* buf, size_t count) {
|
||||
pr_info("sysfs_store_val: buf=%s\n", buf);
|
||||
val = simple_strtol(buf, 0, 10);
|
||||
return count;
|
||||
}
|
||||
|
||||
DEVICE_ATTR(val, 0664, sysfs_show_val, sysfs_store_val);
|
||||
|
||||
static struct class* sysfs_class;
|
||||
static struct device* sysfs_device;
|
||||
|
||||
static int __init skeleton_init(void) {
|
||||
|
||||
int status = 0;
|
||||
|
||||
sysfs_class = class_create(THIS_MODULE, "my_sysfs_class");
|
||||
sysfs_device = device_create(sysfs_class, NULL, 0, NULL, "my_sysfs_device");
|
||||
if (status == 0) status = device_create_file(sysfs_device, &dev_attr_val);
|
||||
|
||||
pr_info("Linux module skeleton loaded\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
static void __exit skeleton_exit(void) {
|
||||
|
||||
device_remove_file(sysfs_device, &dev_attr_val);
|
||||
device_destroy(sysfs_class, 0);
|
||||
class_destroy(sysfs_class);
|
||||
|
||||
pr_info("Linux module skeleton unloaded\n");
|
||||
}
|
||||
|
||||
module_init (skeleton_init);
|
||||
module_exit (skeleton_exit);
|
||||
|
||||
MODULE_AUTHOR("Fastium <fastium.pro@proton.me>");
|
||||
MODULE_AUTHOR("Klagarge <remi@heredero.ch>");
|
||||
MODULE_DESCRIPTION ("Module pilot charachter oriented");
|
||||
MODULE_LICENSE ("GPL");
|
||||
13
src/03-led-controller/.clangd
Normal file
@@ -0,0 +1,13 @@
|
||||
CompileFlags:
|
||||
Add:
|
||||
# Architecture and cross-compilation
|
||||
- "--target=aarch64-linux-gnu"
|
||||
|
||||
# Setup sysroot for buildroot
|
||||
- "--sysroot=/buildroot/output/host/aarch64-buildroot-linux-gnu/sysroot"
|
||||
|
||||
# Add specific header of linux from buildroot
|
||||
- "-I/buildroot/output/build/linux-headers-5.15.148/include"
|
||||
- "-I/buildroot/output/build/linux-headers-5.15.148/arch/arm64/include"
|
||||
- "-I/buildroot/output/build/linux-headers-5.15.148/arch/arm64/include/generated"
|
||||
- "-I/buildroot/output/build/linux-headers-5.15.148/**"
|
||||
5
src/03-led-controller/Makefile
Normal file
@@ -0,0 +1,5 @@
|
||||
EXE=led-controller
|
||||
SRCS=$(wildcard *.c)
|
||||
|
||||
# Include the standard application Makefile for the CSEL1 labs
|
||||
include ../appl.mk
|
||||
44
src/03-led-controller/button.c
Normal file
@@ -0,0 +1,44 @@
|
||||
#include "button.h"
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/epoll.h>
|
||||
|
||||
|
||||
#define GPIO_EXPORT "/sys/class/gpio/export"
|
||||
#define GPIO_UNEXPORT "/sys/class/gpio/unexport"
|
||||
|
||||
int btn_open(const char* gpio_path, const char* pin) {
|
||||
int f = open(GPIO_UNEXPORT, O_WRONLY);
|
||||
write(f, pin, strlen(pin));
|
||||
close(f);
|
||||
|
||||
f = open(GPIO_EXPORT, O_WRONLY);
|
||||
write(f, pin, strlen(pin));
|
||||
close(f);
|
||||
|
||||
char direction_path[100];
|
||||
strcpy(direction_path, gpio_path);
|
||||
strcat(direction_path, "/direction");
|
||||
|
||||
f = open(direction_path, O_WRONLY);
|
||||
write(f, "in", 2);
|
||||
close(f);
|
||||
|
||||
char edge_path[100];
|
||||
strcpy(edge_path, gpio_path);
|
||||
strcat(edge_path, "/edge");
|
||||
|
||||
f = open(edge_path, O_WRONLY);
|
||||
write(f, "both", 4); // "both" means it triggers on press AND release
|
||||
close(f);
|
||||
|
||||
char value_path[100];
|
||||
strcpy(value_path, gpio_path);
|
||||
strcat(value_path, "/value");
|
||||
|
||||
f = open(value_path, O_RDONLY);
|
||||
return f;
|
||||
}
|
||||
10
src/03-led-controller/button.h
Normal file
@@ -0,0 +1,10 @@
|
||||
#ifndef BUTTON_H
|
||||
#define BUTTON_H
|
||||
|
||||
#define GPIO_EXPORT "/sys/class/gpio/export"
|
||||
#define GPIO_UNEXPORT "/sys/class/gpio/unexport"
|
||||
|
||||
int btn_open(const char* gpio_path, const char* pin);
|
||||
|
||||
|
||||
#endif
|
||||
7
src/03-led-controller/justfile
Normal file
@@ -0,0 +1,7 @@
|
||||
build:
|
||||
make
|
||||
|
||||
clean:
|
||||
rm -rf build
|
||||
rm -rf .obj
|
||||
rm led-controller
|
||||
48
src/03-led-controller/led.c
Normal file
@@ -0,0 +1,48 @@
|
||||
#include "led.h"
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/epoll.h>
|
||||
#include <sys/inotify.h>
|
||||
#include <pthread.h>
|
||||
|
||||
int led_open(const char* gpio_path, const char* pin) {
|
||||
|
||||
// unexport pin out of sysfs (reinitialization)
|
||||
int f = open(GPIO_UNEXPORT, O_WRONLY);
|
||||
write(f, pin, strlen(pin));
|
||||
close(f);
|
||||
|
||||
// export pin to sysfs
|
||||
f = open(GPIO_EXPORT, O_WRONLY);
|
||||
write(f, pin, strlen(pin));
|
||||
close(f);
|
||||
|
||||
// config pin
|
||||
char direction_path[100];
|
||||
strcpy(direction_path, gpio_path);
|
||||
strcat(direction_path, "/direction");
|
||||
|
||||
f = open(direction_path, O_WRONLY);
|
||||
write(f, "out", 3);
|
||||
close(f);
|
||||
|
||||
// open gpio value attribute
|
||||
char value_path[100];
|
||||
strcpy(value_path, gpio_path);
|
||||
strcat(value_path, "/value");
|
||||
|
||||
f = open(value_path, O_RDWR);
|
||||
return f;
|
||||
}
|
||||
|
||||
void led_on(int led) {
|
||||
pwrite(led, "1", sizeof("1"), 0);
|
||||
}
|
||||
|
||||
void led_off(int led) {
|
||||
pwrite(led, "0", sizeof("0"), 0);
|
||||
}
|
||||
14
src/03-led-controller/led.h
Normal file
@@ -0,0 +1,14 @@
|
||||
#ifndef CSEL_WORKSPACE_LED_H
|
||||
#define CSEL_WORKSPACE_LED_H
|
||||
|
||||
#define GPIO_EXPORT "/sys/class/gpio/export"
|
||||
#define GPIO_UNEXPORT "/sys/class/gpio/unexport"
|
||||
|
||||
#define GPIO_LED "/sys/class/gpio/gpio10"
|
||||
#define LED "10"
|
||||
|
||||
int led_open(const char* gpio_path, const char* pin);
|
||||
void led_on(int led);
|
||||
void led_off(int led);
|
||||
|
||||
#endif //CSEL_WORKSPACE_LED_H
|
||||
229
src/03-led-controller/main.c
Normal file
@@ -0,0 +1,229 @@
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/epoll.h>
|
||||
#include <sys/inotify.h>
|
||||
#include <pthread.h>
|
||||
#include <syslog.h>
|
||||
|
||||
#include "timer.h"
|
||||
#include "led.h"
|
||||
#include "button.h"
|
||||
|
||||
/*
|
||||
* status led - gpioa.10 --> gpio10
|
||||
* power led - gpiol.10 --> gpio362
|
||||
*/
|
||||
|
||||
#define GPIO_LED "/sys/class/gpio/gpio10"
|
||||
#define LED "10"
|
||||
|
||||
#define GPIO_BTN1 "/sys/class/gpio/gpio0"
|
||||
#define BTN1 "0"
|
||||
#define GPIO_BTN2 "/sys/class/gpio/gpio2"
|
||||
#define BTN2 "2"
|
||||
#define GPIO_BTN3 "/sys/class/gpio/gpio3"
|
||||
#define BTN3 "3"
|
||||
|
||||
#define NBR_BTN 3
|
||||
|
||||
#define DEFAULT_TIME_MS 1000
|
||||
#define DUTY_CYCLE_PERCENT 2
|
||||
|
||||
|
||||
typedef struct {
|
||||
long flash_period_ms;
|
||||
int timer_fd;
|
||||
int epoll_fd;
|
||||
} ThreadData;
|
||||
|
||||
// constant
|
||||
const char* GPIO_BTN[NBR_BTN] = {GPIO_BTN1, GPIO_BTN2, GPIO_BTN3};
|
||||
const char* BTN[NBR_BTN] = {BTN1, BTN2, BTN3};
|
||||
|
||||
|
||||
void* btn_thread(void* arg) {
|
||||
ThreadData* data = (ThreadData*)arg;
|
||||
|
||||
// Open all button with the right flags
|
||||
int btn[NBR_BTN] = {0};
|
||||
for(int i=0; i<NBR_BTN; i++) {
|
||||
btn[i] = btn_open(GPIO_BTN[i], BTN[i]);
|
||||
if (btn[i] < 0) {
|
||||
perror("Failed to open button");
|
||||
}
|
||||
}
|
||||
|
||||
// Create epoll instance to control all button files
|
||||
int epfd = epoll_create1(0);
|
||||
if (epfd < 0) {
|
||||
perror("Failed to create epoll");
|
||||
}
|
||||
|
||||
// Add buttons to epoll
|
||||
struct epoll_event ev[NBR_BTN];
|
||||
// EPOLLIN is working well as EPOLLPRI (which is more used for priority data)
|
||||
// EPOLLERR is used to detect if there is an error
|
||||
// EPOLLET is for edge triggered mode (non-blocking)
|
||||
for(int i=0; i<NBR_BTN; i++) {
|
||||
ev[i].events = EPOLLIN | EPOLLERR | EPOLLET;
|
||||
ev[i].data.fd = btn[i];
|
||||
if (epoll_ctl(epfd, EPOLL_CTL_ADD, btn[i], &ev[i]) < 0) {
|
||||
perror("Failed to add button to epoll");
|
||||
}
|
||||
}
|
||||
|
||||
// Dummy read to clear initial state before waiting
|
||||
char buf[2];
|
||||
for(int i=0; i<NBR_BTN; i++) {
|
||||
pread(btn[i], buf, sizeof(buf), 0);
|
||||
}
|
||||
|
||||
printf("Waiting for button presses...\n");
|
||||
|
||||
// Event main loop
|
||||
while (1) {
|
||||
struct epoll_event events[NBR_BTN];
|
||||
|
||||
// Timeout is -1: Block infinitely until an event occurs!
|
||||
int n = epoll_wait(epfd, events, 1, -1);
|
||||
|
||||
if (n < 0) {
|
||||
perror("epoll_wait error");
|
||||
break;
|
||||
}
|
||||
|
||||
for (int i = 0; i < n; i++) {
|
||||
// read btn file
|
||||
pread(events[i].data.fd, buf, sizeof(buf), 0);
|
||||
|
||||
if (events[i].data.fd == btn[0]) {
|
||||
if (buf[0] == '1') {
|
||||
data->flash_period_ms += 200;
|
||||
char* log_msg = malloc(100);
|
||||
snprintf(log_msg, 100, "Increase flash period to %ld ms", data->flash_period_ms);
|
||||
syslog(LOG_INFO, "%s", log_msg);
|
||||
printf("%s\n", log_msg);
|
||||
free(log_msg);
|
||||
}
|
||||
|
||||
} else if (events[i].data.fd == btn[1]) {
|
||||
if (buf[0] == '1') {
|
||||
data->flash_period_ms = DEFAULT_TIME_MS;
|
||||
char* log_msg = malloc(100);
|
||||
snprintf(log_msg, 100, "Reset flash period to %ld ms", data->flash_period_ms);
|
||||
syslog(LOG_INFO, "%s", log_msg);
|
||||
printf("%s\n", log_msg);
|
||||
free(log_msg);
|
||||
}
|
||||
|
||||
} else if (events[i].data.fd == btn[2]) {
|
||||
if (buf[0] == '1') {
|
||||
data->flash_period_ms -= 200;
|
||||
if (data->flash_period_ms <= 0) {
|
||||
data->flash_period_ms = 200; // Minimum period of 200ms
|
||||
}
|
||||
char* log_msg = malloc(100);
|
||||
snprintf(log_msg, 100, "Decrease flash period to %ld ms", data->flash_period_ms);
|
||||
syslog(LOG_INFO, "%s", log_msg);
|
||||
printf("%s\n", log_msg);
|
||||
free(log_msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int i=0; i<NBR_BTN; i++) {
|
||||
close(btn[i]);
|
||||
}
|
||||
close(epfd);
|
||||
}
|
||||
|
||||
static void* timer_thread(void* arg) {
|
||||
ThreadData* data = (ThreadData*)arg;
|
||||
|
||||
int led = led_open(GPIO_LED, LED);
|
||||
led_off(led);
|
||||
|
||||
|
||||
|
||||
struct epoll_event ev;
|
||||
|
||||
int isLedOn = 0;
|
||||
while(1) {
|
||||
|
||||
int n = epoll_wait(data->epoll_fd, &ev, 1, -1);
|
||||
if (n == -1) {
|
||||
perror("epoll_wait failed");
|
||||
break;
|
||||
}
|
||||
|
||||
uint64_t val;
|
||||
if (read(data->timer_fd, &val, sizeof(val)) != sizeof(val)) {
|
||||
perror("read timerfd failed");
|
||||
break;
|
||||
}
|
||||
|
||||
long time_on_ms = data->flash_period_ms / 100 * DUTY_CYCLE_PERCENT; // 2% duty
|
||||
long time_off_ms = data->flash_period_ms - time_on_ms; // rest of the period
|
||||
|
||||
int delay = 0;
|
||||
if (isLedOn == 0) {
|
||||
delay = time_on_ms; // 2% duty
|
||||
led_on(led);
|
||||
isLedOn = 1;
|
||||
} else {
|
||||
delay = time_off_ms; // rest of the period
|
||||
led_off(led);
|
||||
isLedOn = 0;
|
||||
}
|
||||
|
||||
timer_set_time(&data->timer_fd, delay);
|
||||
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
ThreadData data;
|
||||
pthread_t thread;
|
||||
openlog("CSEL Logs", LOG_PID, LOG_USER);
|
||||
syslog(LOG_INFO, "Start logging silly led-controller");
|
||||
|
||||
data.flash_period_ms = DEFAULT_TIME_MS;
|
||||
|
||||
// Create timerfd
|
||||
data.timer_fd = timer_create_empty();
|
||||
timer_set_time(&data.timer_fd, data.flash_period_ms);
|
||||
|
||||
// Create epoll instance
|
||||
data.epoll_fd = epoll_create1(0);
|
||||
if (data.epoll_fd == -1) {
|
||||
perror("ERROR while create epoll");
|
||||
exit(20);
|
||||
}
|
||||
|
||||
timer_link_to_epoll(&data.timer_fd, &data.epoll_fd);
|
||||
|
||||
|
||||
if (pthread_create(&thread, NULL, timer_thread, &data) != 0) {
|
||||
perror("Failed to create timer thread");
|
||||
exit(30);
|
||||
}
|
||||
|
||||
|
||||
// Setup button thread
|
||||
pthread_t btn_thread_inst;
|
||||
pthread_create(&btn_thread_inst, NULL, btn_thread, &data);
|
||||
|
||||
while (1) {
|
||||
sleep(1);
|
||||
}
|
||||
|
||||
closelog();
|
||||
return 0;
|
||||
}
|
||||
51
src/03-led-controller/timer.c
Normal file
@@ -0,0 +1,51 @@
|
||||
#include "timer.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/timerfd.h>
|
||||
#include <sys/epoll.h>
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
#include <fcntl.h>
|
||||
|
||||
|
||||
int timer_create_empty() {
|
||||
|
||||
// Create timerfd
|
||||
int timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
|
||||
if (timer_fd == -1) {
|
||||
perror("timerfd_create failed");
|
||||
exit(10);
|
||||
}
|
||||
|
||||
return timer_fd;
|
||||
}
|
||||
|
||||
|
||||
void timer_set_time(int* timer_fd, long period_ms) {
|
||||
// https://www.man7.org/linux/man-pages/man3/itimerspec.3type.html
|
||||
struct itimerspec its;
|
||||
|
||||
// Periodic interval
|
||||
its.it_interval.tv_sec = 0;
|
||||
its.it_interval.tv_nsec = 0;
|
||||
|
||||
// Initial expiration
|
||||
its.it_value.tv_sec = period_ms / 1000;
|
||||
its.it_value.tv_nsec = (period_ms % 1000) * 1000000;
|
||||
|
||||
if (timerfd_settime(*timer_fd, 0, &its, NULL) == -1) {
|
||||
perror("timerfd_settime failed");
|
||||
exit(11);
|
||||
}
|
||||
}
|
||||
|
||||
void timer_link_to_epoll(int* timer_fd, int* epoll_fd) {
|
||||
struct epoll_event ev;
|
||||
ev.events = EPOLLIN;
|
||||
ev.data.fd = *timer_fd;
|
||||
if (epoll_ctl(*epoll_fd, EPOLL_CTL_ADD, *timer_fd, &ev) == -1) {
|
||||
perror("ERROR while add timerfd to epoll");
|
||||
exit(21);
|
||||
}
|
||||
}
|
||||
8
src/03-led-controller/timer.h
Normal file
@@ -0,0 +1,8 @@
|
||||
#ifndef CSEL_WORKSPACE_TIMER_H
|
||||
#define CSEL_WORKSPACE_TIMER_H
|
||||
|
||||
int timer_create_empty();
|
||||
void timer_set_time(int* timer_fd, long period_ms);
|
||||
void timer_link_to_epoll(int* timer_fd, int* epoll_fd);
|
||||
|
||||
#endif //CSEL_WORKSPACE_TIMER_H
|
||||
7
src/04-multiprocessing/.clangd
Normal file
@@ -0,0 +1,7 @@
|
||||
CompileFlags:
|
||||
Add:
|
||||
# Architecture and cross-compilation
|
||||
- "--target=aarch64-linux-gnu"
|
||||
|
||||
# Setup sysroot for buildroot
|
||||
- "--sysroot=/buildroot/output/host/aarch64-buildroot-linux-gnu/sysroot"
|
||||
13
src/04-multiprocessing/Makefile
Normal file
@@ -0,0 +1,13 @@
|
||||
|
||||
|
||||
process:
|
||||
$(MAKE) EXE=process SRCS=process.c all
|
||||
|
||||
cgroups:
|
||||
$(MAKE) EXE=cgroups SRCS=cgroups.c all
|
||||
|
||||
max-cpu:
|
||||
$(MAKE) EXE=max-cpu SRCS=max-cpu.c all
|
||||
|
||||
# Include the standard application Makefile for the CSEL1 labs
|
||||
include ../appl.mk
|
||||
44
src/04-multiprocessing/cgroups.c
Normal file
@@ -0,0 +1,44 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define NUM_BLOCKS 50
|
||||
#define BLOCK_SIZE (1024 * 1024) // 1 MiB
|
||||
// 2^20 = 1048576
|
||||
// 1024*1024 = 1048576
|
||||
|
||||
int main() {
|
||||
void *blocks[NUM_BLOCKS];
|
||||
int i;
|
||||
|
||||
printf("Allocate %d blocks of 1 MiB\n", NUM_BLOCKS);
|
||||
|
||||
for (i = 0; i < NUM_BLOCKS; i++) {
|
||||
blocks[i] = malloc(BLOCK_SIZE);
|
||||
|
||||
if (blocks[i] == NULL) {
|
||||
fprintf(stderr, "Error: Allocation not possible for block %d (Limit reached!)\n", i);
|
||||
|
||||
for (int j = 0; j < i; j++) {
|
||||
free(blocks[j]);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
memset(blocks[i], 0, BLOCK_SIZE); // Touch the memory to ensure it's actually allocated
|
||||
|
||||
printf("Block %d allocated and initialized successfully.\n", i);
|
||||
|
||||
usleep(100000); // 100ms
|
||||
}
|
||||
|
||||
printf("Success: All blocks have been allocated.\n");
|
||||
|
||||
// Release the memory at the end
|
||||
for (i = 0; i < NUM_BLOCKS; i++) {
|
||||
free(blocks[i]);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
11
src/04-multiprocessing/cgroups.sh
Executable file
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
|
||||
mount -t tmpfs none /sys/fs/cgroup # Mount a temporary filesystem to /sys/fs/cgroup
|
||||
|
||||
# Memory
|
||||
mkdir /sys/fs/cgroup/memory # Create a directory for the memory cgroup
|
||||
mount -t cgroup -o memory cgroup /sys/fs/cgroup/memory # Mount the cgroup filesystem with memory
|
||||
mkdir /sys/fs/cgroup/memory/0 # Create a subdirectory for the memory cgroup
|
||||
echo $$ > /sys/fs/cgroup/memory/0/tasks # Add the current process to the memory cgroup
|
||||
echo 20M > /sys/fs/cgroup/memory/0/memory.limit_in_bytes # Set the memory limit to 20 MiB
|
||||
|
||||
23
src/04-multiprocessing/justfile
Normal file
@@ -0,0 +1,23 @@
|
||||
@default:
|
||||
just --list
|
||||
|
||||
@build:
|
||||
make process
|
||||
make cgroups
|
||||
make max-cpu
|
||||
|
||||
@process:
|
||||
make process
|
||||
|
||||
@cgroups:
|
||||
make cgroups
|
||||
|
||||
@max-cpu:
|
||||
make max-cpu
|
||||
|
||||
@clean:
|
||||
rm -rf build
|
||||
rm -rf .obj
|
||||
rm -f -- process
|
||||
rm -f -- cgroups
|
||||
rm -f -- max-cpu
|
||||
70
src/04-multiprocessing/max-cpu.c
Normal file
@@ -0,0 +1,70 @@
|
||||
#define _GNU_SOURCE
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <sys/wait.h>
|
||||
|
||||
#include <sched.h>
|
||||
|
||||
|
||||
int fork(void);
|
||||
|
||||
|
||||
volatile unsigned long counter = 0;
|
||||
void cpu_intensive_work(const char *process_name) {
|
||||
printf("%s (PID: %d) starting CPU-intensive work on CPU %d\n", process_name, getpid(), sched_getcpu());
|
||||
|
||||
while (1) {
|
||||
counter++;
|
||||
counter = (counter * counter + counter) % (counter * 1023);
|
||||
}
|
||||
}
|
||||
|
||||
void print_usage(const char *prog) {
|
||||
fprintf(stderr, "Usage: %s [--single] [--dual]\n", prog);
|
||||
fprintf(stderr, " --single Run single process (default)\n");
|
||||
fprintf(stderr, " --dual Run two processes\n");
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
int use_dual = 0;
|
||||
|
||||
if (argc > 1) {
|
||||
if (strcmp(argv[1], "--dual") == 0) {
|
||||
use_dual = 1;
|
||||
} else if (strcmp(argv[1], "--single") == 0) {
|
||||
use_dual = 0;
|
||||
} else {
|
||||
fprintf(stderr, "Unknown option: %s\n", argv[1]);
|
||||
print_usage(argv[0]);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (use_dual) {
|
||||
// Dual-process mode
|
||||
pid_t pid = fork();
|
||||
|
||||
if (pid == 0) {
|
||||
cpu_intensive_work("Child process");
|
||||
exit(0);
|
||||
} else if (pid > 0) {
|
||||
cpu_intensive_work("Parent process");
|
||||
wait(NULL);
|
||||
return 0;
|
||||
} else {
|
||||
perror("fork failed");
|
||||
return 1;
|
||||
}
|
||||
} else {
|
||||
// Single-process mode
|
||||
cpu_intensive_work("Process");
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
57
src/04-multiprocessing/max-cpu.sh
Executable file
@@ -0,0 +1,57 @@
|
||||
#!/bin/sh
|
||||
|
||||
usage() {
|
||||
echo "Usage: $0 {init|high|low}"
|
||||
echo " init - Initialize cgroup filesystem and cpuset groups"
|
||||
echo " high - Run ./max-cpu --dual in the 'high' cgroup (CPUs 2,3)"
|
||||
echo " low - Run ./max-cpu --dual in the 'low' cgroup (CPU 1)"
|
||||
exit 1
|
||||
}
|
||||
|
||||
if [ $# -ne 1 ]; then
|
||||
usage
|
||||
fi
|
||||
|
||||
case "$1" in
|
||||
init)
|
||||
echo "Initializing cgroup filesystem..."
|
||||
|
||||
# Mount tmpfs for cgroup
|
||||
mount -t tmpfs none /sys/fs/cgroup 2>/dev/null
|
||||
|
||||
# Create and mount cpuset cgroup
|
||||
mkdir -p /sys/fs/cgroup/cpuset
|
||||
mount -t cgroup -o cpu,cpuset cpuset /sys/fs/cgroup/cpuset 2>/dev/null
|
||||
|
||||
# Create "low" cgroup and allocate CPU 1
|
||||
mkdir -p /sys/fs/cgroup/cpuset/low
|
||||
echo 1 > /sys/fs/cgroup/cpuset/low/cpuset.cpus
|
||||
echo 0 > /sys/fs/cgroup/cpuset/low/cpuset.mems
|
||||
|
||||
# Create "high" cgroup and allocate CPUs 2,3
|
||||
mkdir -p /sys/fs/cgroup/cpuset/high
|
||||
echo 2,3 > /sys/fs/cgroup/cpuset/high/cpuset.cpus
|
||||
echo 0 > /sys/fs/cgroup/cpuset/high/cpuset.mems
|
||||
|
||||
echo "Cgroup initialization complete."
|
||||
echo " - low group: CPU 1"
|
||||
echo " - high group: CPUs 2,3"
|
||||
;;
|
||||
|
||||
high)
|
||||
echo "Running ./max-cpu --dual in 'high' cgroup (CPUs 2,3)..."
|
||||
echo $$ > /sys/fs/cgroup/cpuset/high/tasks
|
||||
./max-cpu --dual
|
||||
;;
|
||||
|
||||
low)
|
||||
echo "Running ./max-cpu --dual in 'low' cgroup (CPU 1)..."
|
||||
echo $$ > /sys/fs/cgroup/cpuset/low/tasks
|
||||
./max-cpu --dual
|
||||
;;
|
||||
|
||||
*)
|
||||
echo "Unknown command: $1"
|
||||
usage
|
||||
;;
|
||||
esac
|
||||
135
src/04-multiprocessing/process.c
Normal file
@@ -0,0 +1,135 @@
|
||||
#define _GNU_SOURCE
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/socket.h>
|
||||
#include <string.h>
|
||||
#include <sched.h>
|
||||
#include <sys/resource.h>
|
||||
#include <signal.h>
|
||||
|
||||
const int NBR_MSG = 5;
|
||||
const char * MSG[] = {
|
||||
"Hallo, hallo !\0",
|
||||
"ça geht !\0",
|
||||
"Comment vont les olives ?\0",
|
||||
"Sacré trucs tes trucs là.\0",
|
||||
"Ta où les vaches !!!!!\0"
|
||||
};
|
||||
|
||||
static void catch_signal(int signal) {
|
||||
|
||||
switch (signal) {
|
||||
case SIGHUP:
|
||||
printf("SIGHUP received\n");
|
||||
break;
|
||||
case SIGINT:
|
||||
printf("SIGINT received\n");
|
||||
exit(EXIT_SUCCESS); // to avoid to be blocked and kill it with ctrl+c
|
||||
break;
|
||||
case SIGQUIT:
|
||||
printf("SIGQUIT received\n");
|
||||
break;
|
||||
case SIGTERM:
|
||||
printf("SIGTERM received\n");
|
||||
break;
|
||||
case SIGABRT:
|
||||
printf("SIGABRT received\n");
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
static void install_catch_signal()
|
||||
{
|
||||
struct sigaction act = {
|
||||
.sa_handler = catch_signal,
|
||||
};
|
||||
sigemptyset(&act.sa_mask);
|
||||
sigaction(SIGHUP, &act, 0);
|
||||
sigaction(SIGINT, &act, 0);
|
||||
sigaction(SIGQUIT, &act, 0);
|
||||
sigaction(SIGTERM, &act, 0);
|
||||
sigaction(SIGABRT, &act, 0);
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
|
||||
install_catch_signal();
|
||||
|
||||
/* Setup socket for inter-process communication */
|
||||
int fd[2];
|
||||
int err = socketpair(AF_UNIX, SOCK_STREAM, 0, fd);
|
||||
if (err == -1) {
|
||||
perror("socketpair fail");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
/* Prepare cpu set for process affinity */
|
||||
cpu_set_t set;
|
||||
CPU_ZERO(&set);
|
||||
int child_cpu = 0;
|
||||
int parent_cpu = 1;
|
||||
|
||||
/* Fork a child process */
|
||||
pid_t pid = fork();
|
||||
|
||||
if (pid == 0) { /* Parent process */
|
||||
pid_t parent_pid = getpid();
|
||||
printf("Parent process: pid=%d\n", parent_pid);
|
||||
|
||||
/* Setup CPU for process */
|
||||
CPU_SET(child_cpu, &set);
|
||||
int ret = sched_setaffinity(parent_pid, sizeof(set), &set);
|
||||
if (ret == -1) {
|
||||
perror("sched_setaffinity");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
/* Read messages from child */
|
||||
char buffer[100];
|
||||
for (int i = 0; i < NBR_MSG; i++) {
|
||||
read(fd[1], buffer, strlen(MSG[i]));
|
||||
printf("Message %d: %s\n", i, buffer);
|
||||
memset(buffer, 0, sizeof(buffer));
|
||||
}
|
||||
|
||||
} else if (pid > 0) { /* Child process */
|
||||
pid_t child_pid = getpid();
|
||||
printf("Child process: pid=%d\n", child_pid);
|
||||
|
||||
/* Setup CPU affinity for process */
|
||||
CPU_SET(parent_cpu, &set);
|
||||
int ret = sched_setaffinity(child_pid, sizeof(set), &set);
|
||||
if (ret == -1) {
|
||||
perror("sched_setaffinity");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
/* Write messages for the parent process */
|
||||
for (int i = 0; i < NBR_MSG; i++) {
|
||||
write(fd[0], MSG[i], strlen(MSG[i]));
|
||||
}
|
||||
|
||||
exit(EXIT_SUCCESS);
|
||||
|
||||
} else {
|
||||
/* error */
|
||||
perror("fork fail");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
/* Test signal handling */
|
||||
kill(getpid(), SIGHUP);
|
||||
kill(getpid(), SIGQUIT);
|
||||
kill(getpid(), SIGTERM);
|
||||
kill(getpid(), SIGABRT);
|
||||
kill(getpid(), SIGINT);
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
96
src/04-multiprocessing/shared-cpu.sh
Executable file
@@ -0,0 +1,96 @@
|
||||
#!/bin/sh
|
||||
|
||||
usage() {
|
||||
echo "Usage: $0 {init|high|low}"
|
||||
echo " ./shared-cpu.sh init - Initialize cgroup filesystem with cpu.shares groups"
|
||||
echo " . ./shared-cpu.sh high - Run ./max-cpu --single in 'high' cgroup (75% CPU share on CPU 0)"
|
||||
echo " . ./shared-cpu.sh low - Run ./max-cpu --single in 'low' cgroup (25% CPU share on CPU 0)"
|
||||
exit 1
|
||||
}
|
||||
|
||||
if [ $# -ne 1 ]; then
|
||||
usage
|
||||
fi
|
||||
|
||||
# Helper to check if a directory is already mounted
|
||||
is_mounted() {
|
||||
mount | grep -q " $1 "
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
init)
|
||||
echo "Initializing cgroup filesystem for CPU shares..."
|
||||
|
||||
# Mount tmpfs for cgroup if not already mounted
|
||||
if ! is_mounted /sys/fs/cgroup; then
|
||||
echo "Mounting /sys/fs/cgroup..."
|
||||
mount -t tmpfs none /sys/fs/cgroup || {
|
||||
echo "ERROR: Failed to mount /sys/fs/cgroup"
|
||||
exit 1
|
||||
}
|
||||
else
|
||||
echo "/sys/fs/cgroup is already mounted."
|
||||
fi
|
||||
|
||||
# Create and mount cpuset cgroup if not already mounted
|
||||
mkdir -p /sys/fs/cgroup/cpuset
|
||||
if ! is_mounted /sys/fs/cgroup/cpuset; then
|
||||
echo "Mounting cpuset/cpu cgroup..."
|
||||
mount -t cgroup -o cpu,cpuset cpuset /sys/fs/cgroup/cpuset || {
|
||||
echo "ERROR: Failed to mount cpuset cgroup! Perhaps 'cpu' and 'cpuset' are already mounted separately elsewhere?"
|
||||
exit 1
|
||||
}
|
||||
else
|
||||
echo "/sys/fs/cgroup/cpuset is already mounted."
|
||||
fi
|
||||
|
||||
# Create "low" cgroup with 25% share
|
||||
echo "Configuring 'low' cgroup..."
|
||||
mkdir -p /sys/fs/cgroup/cpuset/low
|
||||
echo 0 > /sys/fs/cgroup/cpuset/low/cpuset.cpus || echo "WARNING: Failed to write cpuset.cpus for low cgroup"
|
||||
echo 0 > /sys/fs/cgroup/cpuset/low/cpuset.mems || echo "WARNING: Failed to write cpuset.mems for low cgroup"
|
||||
echo 25 > /sys/fs/cgroup/cpuset/low/cpu.shares || echo "WARNING: Failed to write cpu.shares for low cgroup"
|
||||
|
||||
# Create "high" cgroup with 75% share
|
||||
echo "Configuring 'high' cgroup..."
|
||||
mkdir -p /sys/fs/cgroup/cpuset/high
|
||||
echo 0 > /sys/fs/cgroup/cpuset/high/cpuset.cpus || echo "WARNING: Failed to write cpuset.cpus for high cgroup"
|
||||
echo 0 > /sys/fs/cgroup/cpuset/high/cpuset.mems || echo "WARNING: Failed to write cpuset.mems for high cgroup"
|
||||
echo 75 > /sys/fs/cgroup/cpuset/high/cpu.shares || echo "WARNING: Failed to write cpu.shares for high cgroup"
|
||||
|
||||
echo "Cgroup initialization complete."
|
||||
echo " - low group: 25 shares (25% CPU on CPU 0)"
|
||||
echo " - high group: 75 shares (75% CPU on CPU 0)"
|
||||
;;
|
||||
|
||||
high)
|
||||
echo "Running ./max-cpu --single in 'high' cgroup (75% CPU share)..."
|
||||
if [ ! -f /sys/fs/cgroup/cpuset/high/tasks ]; then
|
||||
echo "ERROR: Cgroup is not initialized or mounted! Run './shared-cpu.sh init' first."
|
||||
exit 1
|
||||
fi
|
||||
echo $$ > /sys/fs/cgroup/cpuset/high/tasks || {
|
||||
echo "ERROR: Failed to add shell process ($$) to high cgroup!"
|
||||
exit 1
|
||||
}
|
||||
./max-cpu --single
|
||||
;;
|
||||
|
||||
low)
|
||||
echo "Running ./max-cpu --single in 'low' cgroup (25% CPU share)..."
|
||||
if [ ! -f /sys/fs/cgroup/cpuset/low/tasks ]; then
|
||||
echo "ERROR: Cgroup is not initialized or mounted! Run './shared-cpu.sh init' first."
|
||||
exit 1
|
||||
fi
|
||||
echo $$ > /sys/fs/cgroup/cpuset/low/tasks || {
|
||||
echo "ERROR: Failed to add shell process ($$) to low cgroup!"
|
||||
exit 1
|
||||
}
|
||||
./max-cpu --single
|
||||
;;
|
||||
|
||||
*)
|
||||
echo "Unknown command: $1"
|
||||
usage
|
||||
;;
|
||||
esac
|
||||
5
src/05-optimization/Makefile
Normal file
@@ -0,0 +1,5 @@
|
||||
DIRS=$(filter-out Makefile, $(wildcard *))
|
||||
|
||||
all clean install clean_all:
|
||||
for dir in $(DIRS); do $(MAKE) $@ -C $$dir; done
|
||||
|
||||
54
src/05-optimization/clock/Makefile
Normal file
@@ -0,0 +1,54 @@
|
||||
EXE=clock
|
||||
SRCS=$(wildcard *.c)
|
||||
|
||||
ifeq ($(target),)
|
||||
target=nano
|
||||
endif
|
||||
|
||||
CFLAGS=-Wall -Wextra -g -c -O0 -MD -std=gnu11 -D_GNU_SOURCE
|
||||
|
||||
ifeq ($(target),nano)
|
||||
TOOLCHAIN_PATH=/buildroot/output/host/usr/bin/
|
||||
TOOLCHAIN=$(TOOLCHAIN_PATH)aarch64-linux-
|
||||
CFLAGS+=-mcpu=cortex-a53 -funwind-tables
|
||||
##CFLAGS+=-O2 -fno-omit-frame-pointer
|
||||
OBJDIR=.obj/nano
|
||||
EXEC=$(EXE)
|
||||
endif
|
||||
|
||||
ifeq ($(target),host)
|
||||
EXEC=$(EXE)_h
|
||||
endif
|
||||
|
||||
CC=$(TOOLCHAIN)gcc
|
||||
LD=$(TOOLCHAIN)gcc
|
||||
AR=$(TOOLCHAIN)ar
|
||||
STRIP=$(TOOLCHAIN)strip
|
||||
OBJDUMP=$(TOOLCHAIN)objdump
|
||||
|
||||
OBJDIR=.obj/$(target)
|
||||
OBJS= $(addprefix $(OBJDIR)/, $(SRCS:.c=.o))
|
||||
|
||||
$(OBJDIR)/%o: %c
|
||||
$(CC) $(CFLAGS) $< -o $@
|
||||
|
||||
all: $(OBJDIR)/ $(EXEC)
|
||||
|
||||
$(EXEC): $(OBJS) $(LINKER_SCRIPT)
|
||||
$(LD) $(OBJS) $(LDFLAGS) -o $@
|
||||
|
||||
$(OBJDIR)/:
|
||||
mkdir -p $(OBJDIR)
|
||||
|
||||
clean:
|
||||
rm -Rf $(OBJDIR) $(EXEC) $(EXEC)_s *~ t.txt
|
||||
|
||||
clean_all: clean
|
||||
rm -Rf .obj $(EXE) $(EXE)_s $(EXE)_a $(EXE)_a_s $(EXE)_h $(EXE)_h_s
|
||||
|
||||
dump: all
|
||||
$(OBJDUMP) -dS $(EXEC) > t.txt
|
||||
|
||||
-include $(OBJS:.o=.d)
|
||||
|
||||
.PHONY: all clean clean_all dump
|
||||
56
src/05-optimization/clock/clock.c
Normal file
@@ -0,0 +1,56 @@
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <errno.h>
|
||||
#include <time.h>
|
||||
#include <sched.h>
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
void measure (int mode, int samples)
|
||||
{
|
||||
struct timespec start_time;
|
||||
struct timespec stop_time;
|
||||
clock_gettime (mode, &start_time); // setup...
|
||||
clock_gettime (mode, &start_time);
|
||||
for (int i = 0; i<samples; i++)
|
||||
{
|
||||
clock_gettime (mode, &start_time);
|
||||
clock_gettime (mode, &stop_time);
|
||||
long long t = (stop_time.tv_nsec - start_time.tv_nsec) +
|
||||
(stop_time.tv_sec - start_time.tv_sec) * 1000000000;
|
||||
printf ("%lld\n", t);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* main program...
|
||||
*/
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
cpu_set_t my_set;
|
||||
CPU_ZERO(&my_set);
|
||||
CPU_SET(2, &my_set);
|
||||
sched_setaffinity(0, sizeof(cpu_set_t), &my_set);
|
||||
|
||||
printf ("clocks_per_sec=%ld\n", CLOCKS_PER_SEC);
|
||||
|
||||
int samples = 1000;
|
||||
if (argc == 2)
|
||||
samples = atol(argv[1]);
|
||||
|
||||
struct timespec start_time;
|
||||
clock_getres (CLOCK_MONOTONIC_RAW, &start_time);
|
||||
long t = start_time.tv_sec * 1000000000 + start_time.tv_nsec;
|
||||
printf ("time=%ld'%03ld'%03ld ns\n", t/1000000, (t/1000)%1000, t%1000);
|
||||
|
||||
measure (CLOCK_MONOTONIC_RAW, samples);
|
||||
|
||||
return 0;
|
||||
}
|
||||
BIN
src/05-optimization/clock/meazure.xlsx
Normal file
74
src/05-optimization/ex01/Makefile
Normal file
@@ -0,0 +1,74 @@
|
||||
EXE_BASIC=basic
|
||||
EXE_OPTI=optimized
|
||||
|
||||
SRCS_BASIC=basic.c
|
||||
SRCS_OPTI=optimized.c
|
||||
|
||||
ifeq ($(target),)
|
||||
target=nano
|
||||
endif
|
||||
|
||||
CFLAGS=-Wall -Wextra -g -c -O1 -MD -std=gnu11 -D_GNU_SOURCE
|
||||
|
||||
ifeq ($(target),nano)
|
||||
TOOLCHAIN_PATH=/buildroot/output/host/usr/bin/
|
||||
TOOLCHAIN=$(TOOLCHAIN_PATH)aarch64-linux-
|
||||
CFLAGS+=-mcpu=cortex-a53 -funwind-tables
|
||||
CFLAGS+=-fno-omit-frame-pointer
|
||||
##CFLAGS+=-O2
|
||||
EXEC_SUFFIX=
|
||||
endif
|
||||
|
||||
ifeq ($(target),host)
|
||||
TOOLCHAIN=
|
||||
EXEC_SUFFIX=_h
|
||||
endif
|
||||
|
||||
CC=$(TOOLCHAIN)gcc
|
||||
LD=$(TOOLCHAIN)gcc
|
||||
AR=$(TOOLCHAIN)ar
|
||||
STRIP=$(TOOLCHAIN)strip
|
||||
OBJDUMP=$(TOOLCHAIN)objdump
|
||||
|
||||
OBJDIR=.obj/$(target)
|
||||
|
||||
OBJS_BASIC = $(addprefix $(OBJDIR)/, $(SRCS_BASIC:.c=.o))
|
||||
OBJS_OPTI = $(addprefix $(OBJDIR)/, $(SRCS_OPTI:.c=.o))
|
||||
|
||||
EXEC_BASIC = $(EXE_BASIC)$(EXEC_SUFFIX)
|
||||
EXEC_OPTI = $(EXE_OPTI)$(EXEC_SUFFIX)
|
||||
|
||||
|
||||
all: $(EXEC_BASIC) $(EXEC_OPTI)
|
||||
|
||||
basic: $(EXEC_BASIC)
|
||||
opti: $(EXEC_OPTI)
|
||||
|
||||
$(OBJDIR)/%.o: %.c | $(OBJDIR)
|
||||
$(CC) $(CFLAGS) $< -o $@
|
||||
|
||||
$(EXEC_BASIC): $(OBJS_BASIC)
|
||||
$(LD) $(OBJS_BASIC) $(LDFLAGS) -o $@
|
||||
|
||||
$(EXEC_OPTI): $(OBJS_OPTI)
|
||||
$(LD) $(OBJS_OPTI) $(LDFLAGS) -o $@
|
||||
|
||||
$(OBJDIR):
|
||||
mkdir -p $(OBJDIR)
|
||||
|
||||
|
||||
clean:
|
||||
rm -Rf $(OBJDIR) $(EXEC_BASIC) $(EXEC_OPTI) *~ t_*.txt
|
||||
|
||||
clean_all: clean
|
||||
rm -Rf .obj $(EXE_BASIC)* $(EXE_OPTI)*
|
||||
|
||||
dump_basic: $(EXEC_BASIC)
|
||||
$(OBJDUMP) -dS $(EXEC_BASIC) > t_basic.txt
|
||||
|
||||
dump_opti: $(EXEC_OPTI)
|
||||
$(OBJDUMP) -dS $(EXEC_OPTI) > t_opti.txt
|
||||
|
||||
-include $(OBJS_BASIC:.o=.d) $(OBJS_OPTI:.o=.d)
|
||||
|
||||
.PHONY: all basic opti clean clean_all dump_basic dump_opti
|
||||
23
src/05-optimization/ex01/basic.c
Normal file
@@ -0,0 +1,23 @@
|
||||
#include <stdint.h>
|
||||
|
||||
#define SIZE 5000
|
||||
|
||||
static int32_t array[SIZE][SIZE];
|
||||
|
||||
int main (void)
|
||||
{
|
||||
int i, j, k;
|
||||
|
||||
for (k = 0; k < 10; k++)
|
||||
{
|
||||
for (i = 0; i < SIZE; i++)
|
||||
{
|
||||
for (j = 0; j < SIZE; j++)
|
||||
{
|
||||
array[j][i]++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
22
src/05-optimization/ex01/optimized.c
Normal file
@@ -0,0 +1,22 @@
|
||||
#include <stdint.h>
|
||||
|
||||
#define SIZE 5000
|
||||
|
||||
static int32_t array[SIZE][SIZE];
|
||||
|
||||
int main (void)
|
||||
{
|
||||
int i, j;
|
||||
|
||||
|
||||
for (i = 0; i < SIZE; i++)
|
||||
{
|
||||
for (j = 0; j < SIZE; j++)
|
||||
{
|
||||
array[i][j]+= 10;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
74
src/05-optimization/ex02/Makefile
Normal file
@@ -0,0 +1,74 @@
|
||||
EXE_BASIC=basic
|
||||
EXE_OPTI=optimized
|
||||
|
||||
SRCS_BASIC=basic.c
|
||||
SRCS_OPTI=optimized.c
|
||||
|
||||
ifeq ($(target),)
|
||||
target=nano
|
||||
endif
|
||||
|
||||
CFLAGS=-Wall -Wextra -g -c -O0 -MD -std=gnu11 -D_GNU_SOURCE
|
||||
|
||||
ifeq ($(target),nano)
|
||||
TOOLCHAIN_PATH=/buildroot/output/host/usr/bin/
|
||||
TOOLCHAIN=$(TOOLCHAIN_PATH)aarch64-linux-
|
||||
CFLAGS+=-mcpu=cortex-a53 -funwind-tables
|
||||
CFLAGS+=-fno-omit-frame-pointer
|
||||
#CFLAGS+=-O2
|
||||
EXEC_SUFFIX=
|
||||
endif
|
||||
|
||||
ifeq ($(target),host)
|
||||
TOOLCHAIN=
|
||||
EXEC_SUFFIX=_h
|
||||
endif
|
||||
|
||||
CC=$(TOOLCHAIN)gcc
|
||||
LD=$(TOOLCHAIN)gcc
|
||||
AR=$(TOOLCHAIN)ar
|
||||
STRIP=$(TOOLCHAIN)strip
|
||||
OBJDUMP=$(TOOLCHAIN)objdump
|
||||
|
||||
OBJDIR=.obj/$(target)
|
||||
|
||||
OBJS_BASIC = $(addprefix $(OBJDIR)/, $(SRCS_BASIC:.c=.o))
|
||||
OBJS_OPTI = $(addprefix $(OBJDIR)/, $(SRCS_OPTI:.c=.o))
|
||||
|
||||
EXEC_BASIC = $(EXE_BASIC)$(EXEC_SUFFIX)
|
||||
EXEC_OPTI = $(EXE_OPTI)$(EXEC_SUFFIX)
|
||||
|
||||
|
||||
all: $(EXEC_BASIC) $(EXEC_OPTI)
|
||||
|
||||
basic: $(EXEC_BASIC)
|
||||
opti: $(EXEC_OPTI)
|
||||
|
||||
$(OBJDIR)/%.o: %.c | $(OBJDIR)
|
||||
$(CC) $(CFLAGS) $< -o $@
|
||||
|
||||
$(EXEC_BASIC): $(OBJS_BASIC)
|
||||
$(LD) $(OBJS_BASIC) $(LDFLAGS) -o $@
|
||||
|
||||
$(EXEC_OPTI): $(OBJS_OPTI)
|
||||
$(LD) $(OBJS_OPTI) $(LDFLAGS) -o $@
|
||||
|
||||
$(OBJDIR):
|
||||
mkdir -p $(OBJDIR)
|
||||
|
||||
|
||||
clean:
|
||||
rm -Rf $(OBJDIR) $(EXEC_BASIC) $(EXEC_OPTI) *~ t_*.txt
|
||||
|
||||
clean_all: clean
|
||||
rm -Rf .obj $(EXE_BASIC)* $(EXE_OPTI)*
|
||||
|
||||
dump_basic: $(EXEC_BASIC)
|
||||
$(OBJDUMP) -dS $(EXEC_BASIC) > t_basic.txt
|
||||
|
||||
dump_opti: $(EXEC_OPTI)
|
||||
$(OBJDUMP) -dS $(EXEC_OPTI) > t_opti.txt
|
||||
|
||||
-include $(OBJS_BASIC:.o=.d) $(OBJS_OPTI:.o=.d)
|
||||
|
||||
.PHONY: all basic opti clean clean_all dump_basic dump_opti
|
||||
24
src/05-optimization/ex02/basic.c
Normal file
@@ -0,0 +1,24 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#define SIZE 65536
|
||||
|
||||
int main()
|
||||
{
|
||||
// generate data
|
||||
short data[SIZE];
|
||||
for (int i = 0; i < SIZE; i++) {
|
||||
data[i] = rand() % 512;
|
||||
}
|
||||
|
||||
|
||||
long long sum = 0;
|
||||
for (int j = 0; j < 10000; j++) {
|
||||
for (int i = 0; i < SIZE; i++) {
|
||||
if (data[i] >= 256) {
|
||||
sum += data[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
printf ("sum=%lld\n", sum);
|
||||
}
|
||||
31
src/05-optimization/ex02/optimized.c
Normal file
@@ -0,0 +1,31 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#define SIZE 65536
|
||||
|
||||
static int compare (const void* a, const void* b)
|
||||
{
|
||||
return *(short*)a - *(short*)b;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
// generate data
|
||||
short data[SIZE];
|
||||
for (int i = 0; i < SIZE; i++) {
|
||||
data[i] = rand() % 512;
|
||||
}
|
||||
|
||||
qsort(data, SIZE, sizeof(data[0]), compare);
|
||||
|
||||
|
||||
long long sum = 0;
|
||||
for (int j = 0; j < 10000; j++) {
|
||||
for (int i = 0; i < SIZE; i++) {
|
||||
if (data[i] >= 256) {
|
||||
sum += data[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
printf ("sum=%lld\n", sum);
|
||||
}
|
||||
37
src/05-optimization/ex03/ApacheAccessLogAnalyzer.cpp
Normal file
@@ -0,0 +1,37 @@
|
||||
#include "ApacheAccessLogAnalyzer.h"
|
||||
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <algorithm>
|
||||
|
||||
|
||||
ApacheAccessLogAnalyzer::ApacheAccessLogAnalyzer(std::string filename)
|
||||
: myFilename(filename)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void ApacheAccessLogAnalyzer::openFile()
|
||||
{
|
||||
myInFile.open(myFilename.c_str());
|
||||
}
|
||||
|
||||
void ApacheAccessLogAnalyzer::closeFile()
|
||||
{
|
||||
myInFile.close();
|
||||
}
|
||||
|
||||
void ApacheAccessLogAnalyzer::processFile()
|
||||
{
|
||||
std::cout << "Processing log file " << myFilename << std::endl;
|
||||
for( std::string line; getline( myInFile, line ); )
|
||||
{
|
||||
// parse the log line to extract the hostname / ip address
|
||||
int space_pos = line.find_first_of(" ");
|
||||
std::string hostname = line.substr(0, space_pos);
|
||||
|
||||
myHostCounter.notifyHost(hostname);
|
||||
}
|
||||
|
||||
std::cout << "Found " << myHostCounter.getNbOfHosts() << " unique Hosts/IPs" << std::endl;
|
||||
}
|
||||
20
src/05-optimization/ex03/ApacheAccessLogAnalyzer.h
Normal file
@@ -0,0 +1,20 @@
|
||||
#include "HostCounter.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <fstream>
|
||||
|
||||
class ApacheAccessLogAnalyzer
|
||||
{
|
||||
public:
|
||||
ApacheAccessLogAnalyzer(std::string filename);
|
||||
|
||||
void openFile();
|
||||
void closeFile();
|
||||
void processFile();
|
||||
|
||||
private:
|
||||
std::string myFilename;
|
||||
std::ifstream myInFile;
|
||||
HostCounter myHostCounter;
|
||||
};
|
||||
26
src/05-optimization/ex03/HostCounter.cpp
Normal file
@@ -0,0 +1,26 @@
|
||||
#include "HostCounter.h"
|
||||
|
||||
#include <algorithm> // for std::find
|
||||
|
||||
HostCounter::HostCounter()
|
||||
{
|
||||
}
|
||||
|
||||
bool HostCounter::isNewHost(std::string hostname)
|
||||
{
|
||||
return myHosts.find(hostname) == myHosts.end();
|
||||
}
|
||||
|
||||
void HostCounter::notifyHost(std::string hostname)
|
||||
{
|
||||
// add the host in the list if not already in
|
||||
if(isNewHost(hostname))
|
||||
{
|
||||
myHosts.insert(hostname);
|
||||
}
|
||||
}
|
||||
|
||||
int HostCounter::getNbOfHosts()
|
||||
{
|
||||
return myHosts.size();
|
||||
}
|
||||
22
src/05-optimization/ex03/HostCounter.h
Normal file
@@ -0,0 +1,22 @@
|
||||
#include <string>
|
||||
|
||||
#include <set>
|
||||
|
||||
class HostCounter
|
||||
{
|
||||
public:
|
||||
HostCounter();
|
||||
|
||||
// Announce a host to the HostCounter.
|
||||
// if the host is new, it will be added to the list, otherwise we ignore it.
|
||||
void notifyHost(std::string hostname);
|
||||
|
||||
// return the number of unique hosts found so far
|
||||
int getNbOfHosts();
|
||||
|
||||
private:
|
||||
// check if host is already in the list
|
||||
bool isNewHost(std::string hostname);
|
||||
|
||||
std::set< std::string > myHosts;
|
||||
};
|
||||
30
src/05-optimization/ex03/Makefile
Normal file
@@ -0,0 +1,30 @@
|
||||
##CXX?=g++
|
||||
##CXXFLAGS=-Wall -Wextra -g -O0 -MD
|
||||
|
||||
TOOLCHAIN_PATH=/buildroot/output/host/usr/bin/
|
||||
TOOLCHAIN=$(TOOLCHAIN_PATH)aarch64-linux-
|
||||
CXX=$(TOOLCHAIN)g++
|
||||
CXXFLAGS=-Wall -Wextra -g -gdwarf -O0 -MD -mcpu=cortex-a53 -fno-omit-frame-pointer -funwind-tables
|
||||
|
||||
SOURCES=$(wildcard *.cpp)
|
||||
OBJECTS=$(SOURCES:.cpp=.o)
|
||||
EXECUTABLE=read-apache-logs
|
||||
|
||||
all: $(SOURCES) $(EXECUTABLE)
|
||||
|
||||
$(EXECUTABLE): $(OBJECTS)
|
||||
$(CXX) $(CXXFLAGS) -o $@ $(OBJECTS)
|
||||
|
||||
.c.o:
|
||||
$(CXX) -c $(CXXFLAGS) $< -o $@
|
||||
|
||||
|
||||
clean:
|
||||
@rm -f $(OBJECTS)
|
||||
@rm -f *.d *~
|
||||
|
||||
clean_all: clean
|
||||
@rm -f $(EXECUTABLE)
|
||||
@rm -f perf.data perf.data.old
|
||||
|
||||
-include *.d
|
||||
3
src/05-optimization/ex03/access_log_NASA_Jul95
Normal file
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:96551161b5bdcaacbc3c17fa108191c478fb35dfe87895c16e34a8f6552bf29a
|
||||
size 205242368
|
||||
3
src/05-optimization/ex03/access_log_NASA_Jul95_samples
Normal file
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:3b9e10566fd24f42f7631c0ab9f1159cda668f11a4f4f375e716f2566b00d0a7
|
||||
size 22005531
|
||||
30
src/05-optimization/ex03/main.cpp
Normal file
@@ -0,0 +1,30 @@
|
||||
#include "ApacheAccessLogAnalyzer.h"
|
||||
|
||||
#include <iostream>
|
||||
|
||||
// forward declaration
|
||||
void usage(const char* progName);
|
||||
|
||||
int main(int argc, const char* argv[])
|
||||
{
|
||||
if(argc != 2)
|
||||
{
|
||||
usage(argv[0]);
|
||||
return -1;
|
||||
}
|
||||
|
||||
std::string filename = argv[1];
|
||||
|
||||
ApacheAccessLogAnalyzer analyzer(filename);
|
||||
|
||||
analyzer.openFile();
|
||||
analyzer.processFile();
|
||||
analyzer.closeFile();
|
||||
}
|
||||
|
||||
|
||||
void usage(const char* progName)
|
||||
{
|
||||
std::cout << "Usage: " << progName << " <filename>" << std::endl;
|
||||
std::cout << "\nWhere <filename> is the apache access log file" << std::endl;
|
||||
}
|
||||