In this blog, I will explore the Linux User Space , system calls and the Kernel Space.

I'll start by listing the differences between Linux User Space and Kernel Space.


Difference between Linux User Space and Kernel Space (Please  Figure 1 below)

User's Space:

  1. Programs in the user's space cannot directly talk to hardware.
  2. This is where normal programs (like ls, nano, python, etc.) run.
  3. It needs system calls to ask the kernel help to execute commands (e.g. ls).
     

Kernel's space:

  1. Kernel - part of the Linux OS that has control over everything.
  2. The kernel provides access to hardware using kernel modules (drivers).
  3. The kernel also provides basic services to all other parts of the operating system.
  4. Kernel operates in privileged mode, with direct access to hardware and system resources.
  5. User space needs system calls (syscall) to communicate with the Kernel and execute commands.

Why root user is unrestricted/special?

  1. The root user has UID 0 and has all capabilities/unrestricted access to the system.
  2. In the /etc/passwd file, UID 0 is usually mapped to the username root.
  3. Even after removing /etc/passwd, the system UID 0 still exists, and there are no limitations for this UID.
  4. Removing UID is not a very good idea, as it is needed throughout the OS.

Drivers, Kernel Modules and Device Files

  1. Hardware(e.g disks, usb) support is offered by drivers.
  2. Drivers are represented as kernel modules and loaded on demand in most cases.
  3. Device nodes are represented by files in /dev, which present as a user interface to the drivers.
  4. Many devices only send bytes to a peripheral on the computer, or receive from the peripheral.
  5. Such devices work like pipes, and for that reason, work well as character devices
  6. Other devices work like files; what you write to a specific location can later be retr.ieved from the same location. These devices are represented by block devices.
  7. Network devices are more complex as ther work with packets, instead of streams of bytes. These devices are controlled by the ioctl() system call, which permits for more advanced operations, and for that reason doesn't work well with either block or character devices.
  8. Video adapters also dont have device nodes the kernel writes directly to the memory of the video adapter as this is faster.

    Figure 1


GlibC

glibc (GNU C Library) is used by programs running in user space to communicate with the kernel using system calls.

  1. It implements the C standard library, which contains standard functions that can be used by all programs written in C.
  2. It provides core Linux facilities such as open(), read(), write(), malloc(), printf() and more.
  3. Almost all Linux programs depend on it, even if they aren’t written in C.
  4. This is the core dependency for running and compiling software.
  5. GlibC is released under General Public License. It is a free software license that encourages open-source collaboration.
  6. Works on all common hardware platforms.

Example 1: How Applications Use Shared Libraries (glibc)

In Linux, programs don't include everything they need inside their own file. Instead, they rely on shared libraries, such as glibc, to provide common functions (like printf, malloc, open, etc.).

Checking libraries used by ls with sample output. 

root@grace-ubuntu:~# ldd $(which ls)
	linux-vdso.so.1 (0x0000ef7af29dd000)
	libselinux.so.1 => /lib/aarch64-linux-gnu/libselinux.so.1 (0x0000ef7af2910000)
	libc.so.6 => /lib/aarch64-linux-gnu/libc.so.6 (0x0000ef7af2750000)
	/lib/ld-linux-aarch64.so.1 (0x0000ef7af29a0000)
	libpcre2-8.so.0 => /lib/aarch64-linux-gnu/libpcre2-8.so.0 (0x0000ef7af26a0000)
root@grace-ubuntu:~# 
  • libc.so.6 --> this is the glibc used by ls - it provides essential system call wrappers and functions like read(), write(), malloc().

Example 2: Checking libraries used by passwd

root@grace-ubuntu:~# ldd $(which passwd)
	linux-vdso.so.1 (0x0000f10fc8a94000)
	libpam.so.0 => /lib/aarch64-linux-gnu/libpam.so.0 (0x0000f10fc89f0000)
	libpam_misc.so.0 => /lib/aarch64-linux-gnu/libpam_misc.so.0 (0x0000f10fc89c0000)
	libaudit.so.1 => /lib/aarch64-linux-gnu/libaudit.so.1 (0x0000f10fc8980000)
	libselinux.so.1 => /lib/aarch64-linux-gnu/libselinux.so.1 (0x0000f10fc8930000)
	libc.so.6 => /lib/aarch64-linux-gnu/libc.so.6 (0x0000f10fc8770000)
	/lib/ld-linux-aarch64.so.1 (0x0000f10fc8a57000)
	libcap-ng.so.0 => /lib/aarch64-linux-gnu/libcap-ng.so.0 (0x0000f10fc8740000)
	libpcre2-8.so.0 => /lib/aarch64-linux-gnu/libpcre2-8.so.0 (0x0000f10fc8690000)
root@grace-ubuntu:~# 
  • The libc.so.6,libpam.so.0 and other  glibc library are used by passwd command to react the password, read(), open it open() and show it as output stdout $1 in shell.

Understanding the Shell

  1. To pass instructions to the kernel, a user interface is needed.
  2. The shell interprets commands that the user types and passes them to the underlying operating system.
  3. As a result, the computer will do something.
  4. bash is the standard shell on Linux.
  5. Other shells like dash and zsh also be used.

File Descriptors

  1. In Linux, everything is a file.
  2. This means that Linux communication happens through files.
    • Device access happens through device files
    • Pipes happen through temporary files that are created in the operating system.
  3. File descriptors are numbers used by processes to keep a list of open files
  4. All processes have at least 3 file descriptors
    • 0: STDIN, refers to the standard input device.
    • 1: STDOUT, refers to the standard output device
    • 2: STDERR, refers to the standard error device
  5. A complete list for file descriptors can be found in /proc/<PID>/fd
  6. The lsof command gives an interpreted list

Example:

grace@grace-ubuntu:/proc/3602/fd$ ps aux | grep firef | head
grace       3602  6.3 10.1 3166596 406644 ?      Sl   00:22   0:11 /snap/firefox/6098/usr/lib/firefox/firefox
grace       3854  0.0  1.0 213380 41344 ?        Sl   00:22   0:00 /snap/firefox/6098/usr/lib/firefox/firefox -contentproc -parentBuildID 20250501070206 -prefsHandle 0:33121 -prefMapHandle 1:266857 -sandboxReporter 2 -chrootClient 3 -ipcHandle 4 -initialChannelId {fb42d752-ee9a-4053-8532-0f8975a26072} -parentPid 3602 -crashReporter 5 -appDir /snap/firefox/6098/usr/lib/firefox/browser 1 socket
grace@grace-ubuntu:/proc/3602/fd$ cd /proc/3602/fd
grace@grace-ubuntu:/proc/3602/fd$ ls -l
total 0
lr-x------ 1 grace grace 64 May  7 00:22 0 -> /dev/null
lrwx------ 1 grace grace 64 May  7 00:22 1 -> 'socket:[30052]'
lrwx------ 1 grace grace 64 May  7 00:22 10 -> 'socket:[22903]'
lrwx------ 1 grace grace 64 May  7 00:22 100 -> 'socket:[23043]'
lrwx------ 1 grace grace 64 May  7 00:22 101 -> /home/grace/snap/firefox/common/.mozilla/firefox/m6yhimiv.default/favicons.sqlite-wal
lr-x------ 1 grace grace 64 May  7 00:22 102 -> /home/grace/snap/firefox/common/.mozilla/firefox/m6yhimiv.default/places.sqlite
lrwx------ 1 grace grace 64 May  7 00:22 103 -> /home/grace/snap/firefox/common/.mozilla/firefox/m6yhimiv.default/places.sqlite-wal

Using lsof:

grace@grace-ubuntu:/proc/3602/fd$ lsof -p 3602
COMMAND  PID  USER   FD      TYPE             DEVICE  SIZE/OFF    NODE NAME
firefox 3602 grace  cwd       DIR              252,0      4096 1573128 /home/grace
firefox 3602 grace  rtd       DIR               0,56       480       1 /
firefox 3602 grace  txt       REG                7,4    621072     397 /snap/firefox/6098/usr/lib/firefox/firefox
firefox 3602 grace  DEL       REG                0,1              7480 /memfd:mozilla-ipc
firefox 3602 grace  mem       CHR            226,128               326 /dev/dri/renderD128
firefox 3602 grace  mem       REG              252,0   1080900  420785 /usr/share/fonts/truetype/ubuntu/Ubu
FDDescriptionPoints toMeaning
0stdin/dev/nullStandard input is redirected to nowhere. This process is not expecting any input.
1stdoutsocket:[30052]Standard output is connected to a socket (likely for IPC or network).
10, 100, 103higher FDsocket:[22903], socket:[23043], filesThese are additional open sockets or database-related files.
101, 102, 103sqlite filesFirefox database filesFirefox is accessing internal browser data like history and icons, hence .sqlite, .sqlite-wal (write-ahead log) files.

Linux System Calls and Strace

  • Users' programs cannot directly access hardware, memory, files and network; they must ask the kernel to do it on their behalf
  • That request happens through system call
  • Strace - a debugging tool to trace system calls and signals made by a running program
    • Reading or writing files
    • Opening network connections
    • Allocating memory
    • Creating a new process
    • Communicating with devices
  • For example, if you strace ls. You will see that the shell uses glibc functions to prepare and call a execve() system call. execve() is a systems call  that transfer calls from user space to kernel space. Kernel loads the ls program binary from the filesystem into memory. The new process ls starts running in user space and uses its glib library to call open(), read(),  amd write(). Then these glibc translates to system calls, kernel executes them, interact with file system and returns results back.

    gracez@graceubuntu:~$ strace ls
    execve("/usr/bin/ls", ["ls"], 0xfffff5b6a440 /* 23 vars */) = 0
    brk(NULL)                               = 0xbffbe42d3000
    mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xf2150e1c6000
    faccessat(AT_FDCWD, "/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory)
    openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
    fstat(3, {st_mode=S_IFREG|0644, st_size=63207, ...}) = 0
    mmap(NULL, 63207, PROT_READ, MAP_PRIVATE, 3, 0) = 0xf2150e1b6000
    close(3)                                = 0
    openat(AT_FDCWD, "/lib/aarch64-linux-gnu/libselinux.so.1", O_RDONLY|O_CLOEXEC) = 3
    read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0\267\0\1\0\0\0\0\0\0\0\0\0\0\0"..., 832) = 832
    fstat(3, {st_mode=S_IFREG|0644, st_size=198800, ...}) = 0
    mmap(NULL, 337472, PROT_NONE, MAP_PRIVATE|MAP_ANO
  • strace requires the command you trace to be an actual binary file (like something under /bin or /usr/bin), not:

    • A shell built-in
    • A script function
    • An alias or internal shell command

     

    For example, I executed cd command below which is a shell built in command. You will receive an output Cannot find executable 'cd'

    grace@grace-ubuntu:~$ strace cd
    strace: Cannot find executable 'cd'

     

    Workaround: Put cd inside a script

    • Since cd is built into the shell, it doesn't exist as a file. But if you write a shell script that uses cd, like this:

      gracez@graceubuntu:~$ cat cd.sh
      cd /lookforme/

      You’ll see output like:

      grace@grace-ubuntu:~$ strace bash cd.sh |& grep lookforme
      read(3, "cd /lookforme\n", 80)          = 14
      read(255, "cd /lookforme\n", 14)        = 14
      newfstatat(AT_FDCWD, "/lookforme", 0xffffdce166a8, 0) = -1 ENOENT (No such file or directory)
      chdir("/lookforme")                     = -1 ENOENT (No such file or directory)
      chdir("/lookforme")                     = -1 ENOENT (No such file or directory)
      write(2, "cd.sh: line 1: cd: /lookforme: N"..., 57cd.sh: line 1: cd: /lookforme: No such file or directory
    • So if its running as built in shell, if I execute a shell cd.sh with cd in it, the bash itself calls real Linux system call named chdir() provided by Linux kernel. 

     

    I created a flow chart to better understand the process.

     

    Challenge question Using Strace:

    Write a one-line shell script with date  > /dev/null, then use strace with -f and -o options to flllow new processes and put the trace output into a file to determeine whetere the date command is the process that opens /dev/null

    • Check if the shell or the commands itself that opens up a file when doing redirection

      strace  -f -o strace.out bash  -f date.sh
    • As checked, it opens the /dev/null file first and afterwards, the date  inherits that open file

      3129  rt_sigaction(SIGCHLD, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=SA_RESTART}, {sa
      _handler=0xb4d1051d7d20, sa_mask=[], sa_flags=SA_RESTART}, 8) = 0
      3129  openat(AT_FDCWD, "/dev/null", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
      3129  dup3(3, 1, 0)                     = 1
      3129  close(3)                          = 0
      3129  execve("/usr/bin/date", ["date"], 0xb4d105bbdba0 /* 47 vars */) = 0
      3129  brk(NULL)                         = 0xb8e769a6b000
      3129  mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xf601f4047000

      - dup3(3, 1, 0) - It duplicates file descriptor 3 (which is /dev/null) into file descriptor 1 → this is stdout.

      - Now the shell replaces itself with the date process, after redirection is already set up.

      - bash opens /dev/null

      - bash sets fd 1 (stdout) to point to /dev/null

      - Then it runs date

      - date inherits that file descriptor 1 as its stdout

      NOTE: The shell (like bash) is the one that opens /dev/null and sets up the redirection before running the command.


Surveying the Linux Kernel

Device Files

  1. Character and block drivers use device files
  2. Device files have a major number, minor number, and type (c or b) character or block.
  3. The kernel maintains a relationship between the three characteristics and what driver to call
  4. The dirver can implement different functions for differnt minor numbers
  5. Device files are often created when a driver is loaded
    • ls -l /dev/vda1,f or example

      grace@grace-ubuntu:/sys/block/vda$ ls -l /dev/vda1
      brw-rw---- 1 root disk 253, 1 May  2 01:08 /dev/vda1
    • first character is b block device file
    • 253 is the main major iscsi device driver
    • 1 is the minor number first disk first partition

Drivers and Device Files

  1. A character driver, for example can implement open(), read(), write(), and ioctl()
  2. A process opens a device file and then read, write,etc. withh the file descriptor; the kernel arranges to have the driver's function called.
  3. echo hi > dev/null would open and then write

Challenge

  1. What other device files share the same major number as /dev/null?

    Answer: Here are the device files that shared same drives, (memory driver) 

    grace@grace-ubuntu:/sys/block/vda$ ls -l /dev | grep " 1, "
    crw-rw-rw-  1 root  root      1,   7 May  2 01:08 full
    crw-r--r--  1 root  root      1,  11 May  2 01:08 kmsg
    crw-r-----  1 root  kmem      1,   1 May  2 01:08 mem
    crw-rw-rw-  1 root  root      1,   3 May  2 01:08 null
    crw-r-----  1 root  kmem      1,   4 May  2 01:08 port
    crw-rw-rw-  1 root  root      1,   8 May  2 01:08 random
    crw-rw-rw-  1 root  root      1,   9 May  2 01:08 urandom
    crw-rw-rw-  1 root  root      1,   5 May  2 01:08 zero
    
  2. What happens when you try to read from /dev/null?
    1. Use strace with cat  /dev/null to investigate?

      grace@grace-ubuntu:/sys/block/vda$ sudo strace -f -o /tmp/stracedevnull.out cat /dev/null
      4440  openat(AT_FDCWD, "/dev/null", O_RDONLY) = 3
      4440  fstat(3, {st_mode=S_IFCHR|0666, st_rdev=makedev(0x1, 0x3), ...}) = 0
      4440  fadvise64(3, 0, 0, POSIX_FADV_SEQUENTIAL) = 0
      4440  mmap(NULL, 139264, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xf380b0a0e000
      4440  read(3, "", 131072)               = 0
      4440  munmap(0xf380b0a0e000, 139264)    = 0
      4440  close(3)                          = 0
      4440  close(1)                          = 0
      4440  close(2)                          = 0
      4440  exit_group(0)                     = ?
      
    2. For what we see, `4440  read(3, "", 131072)               = 0` it reads 131,072 and returns 0. It means no character for you and you just get end of file.

 


Kernel Modules

What is a loadable Kernel Module (LKM)?

  1. It is an object file with .ko suffix; compressed files have .zst after that.
  2. Contains code to run in kernel space.
  3. Dynamically adds functionality to the running kernel.
  4. Typically written in C and compiles for a particular kernal version - not binary compatible with other kernels.

Advantages

  1. Can be relatively minimal main kernel file.
  2. Adds functionality without rebuilding or rebooting.
  3. Allows for only the needed functionality to be loaded.
  4. Live updates.

Finding the LKM

  1. Modules are installed in a directory under /lib/modules, with each installed kernel version having its own directory.
  2. Modules are organized in different subdirectories under the kernel version.
  3. There are also config files.
  4. Each module should have a unique name.
  5. Module files can be in any directory, but the modprobe utility is designed to look only under /lib/modules/$(uname -r).
  6. Only modules built for the kernel version - and how it was configured - should be loaded.
  7. Modules run in kernel mode with all privileges - risky writing in the modules.

Challenge:

  1. How many modules are installed on you system for the kernel you are running?

    grace@grace-ubuntu:/lib/modules/6.8.0-47-generic$ find -name '*.zst' | wc -l
    7717
    
  2. How many lines are in the modules.dep file in the /lib/modules/$(uname -r) directory

    grace@grace-ubuntu:/lib/modules/6.8.0-47-generic$ wc -l modules.dep
    7717 modules.dep
    

Using LKM Commands

  1. lsmod - list the modules loaded, chronologically

    grace@grace-ubuntu:/lib/modules/6.8.0-47-generic$ lsmod
    Module                  Size  Used by
    bnep                   36864  2
    snd_seq_dummy          12288  0
    snd_hrtimer            12288  1
    ib_core               512000  0
    bluetooth            1015808  9 bnep
    ecdh_generic           16384  1 bluetooth
    ecc                    45056  1 ecdh_generic
    qrtr                   49152  2
    cfg80211             1232896  0
    binfmt_misc            28672  1
    snd_hda_codec_generic   114688  1
    snd_hda_intel          57344  1
  2. rmmod - removes the module
    • Module ma be un use, so may not be able to remove it
    • rmmod -f - may let you remove a module that the kernel thinks is in use (risky)
    • rarely done; it is easy to leave the kernel in a fragile condition
  3. modinfo - it has the information of the module.
    • Module info
    • Author
    • Parameters
    • Aliases
    • vermagix
    • More
  4. depmod
    1. For example, modules.dep
    2. You rarely need to run depmod manually, because it is usually run automatically when new kernel modules are installed or updated.
  5. insmod
    • inserts a module
    • Doesn't return until module initialization functions returns.
    • May fail, and and error message may be printed dmesg which can show more details about the problem.
    • Must provide path to the module.
  6. modprobe
    • Loads module and its dependencies.
    • Uses dependency files under /lib/mmodules/VERSION
    • Easier and more convenient then insmod.
    • Can remove modules, too.
    • Lots of options.

Challenges

  1. How many LKMs are currently dynamically loaded on your system?

    There are 73 modules. I subtracted the table header which also counts in the lines.

    grace@grace-ubuntu:/lib/modules/6.8.0-47-generic$ lsmod | wc -l
    74
    grace@grace-ubuntu:/lib/modules/6.8.0-47-generic$ lsmod | head
    Module                  Size  Used by
    bnep                   36864  2
    snd_seq_dummy          12288  0
    snd_hrtimer            12288  1
    ib_core               512000  0
    
    
  2. What was the fist module loaded?

    The aes_ce_cipher was the first one loaded.

    grace@grace-ubuntu:/lib/modules/6.8.0-47-generic$ lsmod | tail
    virtio_gpu             94208  9
    sha1_ce                12288  0
    virtio_dma_buf         12288  1 virtio_gpu
    xhci_pci               28672  0
    virtio_rng             12288  0
    xhci_pci_renesas       24576  1 xhci_pci
    aes_neon_bs            24576  0
    aes_neon_blk           28672  1 aes_neon_bs
    aes_ce_blk             36864  0
    aes_ce_cipher          12288  1 aes_ce_blk
    
  3. Is the msdos module loaded?

    1. If not load it
    grace@grace-ubuntu:/lib/modules/6.8.0-47-generic$ lsmod | grep msdos
    grace@grace-ubuntu:/lib/modules/6.8.0-47-generic$ modprobe msdos
    modprobe: ERROR: could not insert 'msdos': Operation not permitted
    grace@grace-ubuntu:/lib/modules/6.8.0-47-generic$ sudo -i
    [sudo] password for grace: 
    root@grace-ubuntu:~# modprobe msdos
    
    
  4. If you loaded it, is the use count zero?

    Yes the use count is zero

    root@grace-ubuntu:~# lsmod | grep msdos
    msdos                  16384  0
    1. If you loaded it and use count is zero, remove it

      root@grace-ubuntu:~# rmmod msdos
      root@grace-ubuntu:~# lsmod | grep msdos
      
  5. According to the module information for the sunrpc module, what are the license, the version magic, and the number of module parameters?

    License: GPL

    Version Magic: 6.8.0-47-generic SMP preempt mod_unload modversions aarch64

    Number of Module Parameters: 8

    root@grace-ubuntu:~# modinfo sunrpc
    filename:       /lib/modules/6.8.0-47-generic/kernel/net/sunrpc/sunrpc.ko.zst
    license:        GPL
    description:    Sun RPC core
    alias:          rpc_pipefs
    alias:          fs-rpc_pipefs
    srcversion:     250072A557ED0C76E9D47B6
    depends:        
    intree:         Y
    name:           sunrpc
    vermagic:       6.8.0-47-generic SMP preempt mod_unload modversions aarch64
    sig_id:         PKCS#7
    signer:         Build time autogenerated kernel key
    sig_key:        59:ED:73:9C:46:D5:37:20:6B:F1:88:C3:E9:EE:E3:4C:52:6E:00:36
    sig_hashalgo:   sha512
    signature:      BE:6B:DD:20:01:90:5F:A8:67:EF:D6:74:0E:12:F9:00:68:80:54:BA:
    		EC:38:A8:EA:BD:C8:26:72:6F:B3:2A:7C:E0:79:C5:2E:FC:A1:12:8F:
    		28:80:3C:7A:4F:CA:A6:52:E5:72:D4:61:C9:38:21:16:ED:69:0F:3C:
    		4B:9C:D5:0D:B0:DB:E0:25:5B:2A:59:8C:1B:B3:01:CA:42:59:E5:57:
    		27:69:3D:51:94:EB:B9:6A:35:C9:05:95:9C:5D:F1:B7:6B:1D:F5:67:
    		C2:4D:3E:96:58:CA:EE:4B:B9:AB:02:E2:C7:5B:A8:59:35:5B:64:86:
    		82:97:22:16:9A:DF:09:3D:87:03:34:10:22:C3:D4:B9:EB:E3:D7:A0:
    		0E:34:22:5A:05:B8:62:C3:D5:6F:BD:44:AA:0E:98:D9:26:90:B1:F7:
    		36:36:07:FA:5B:AD:D3:B9:CC:2E:C2:30:7A:B3:62:88:AD:DF:10:57:
    		00:DD:51:80:1C:04:3B:DA:53:55:8A:77:06:CE:C1:9F:E6:47:FC:74:
    		DC:45:2B:9C:30:41:AC:DA:C9:45:DD:0A:8F:CC:77:0E:0F:31:99:DE:
    		A2:03:05:06:59:4C:E0:BE:7B:50:24:BD:EA:8F:FA:A9:A5:90:43:12:
    		37:7D:87:57:4D:E7:17:29:E5:6D:82:24:5F:A6:3B:DB:18:B9:78:E5:
    		C0:1F:E0:A0:AF:DF:F3:FD:0B:36:83:76:37:60:FA:C1:D2:87:23:2F:
    		49:64:05:26:0B:3E:C1:DA:50:55:B8:6D:29:5E:6E:11:89:A1:8B:74:
    		98:08:1B:39:E7:AA:FD:57:6C:0B:BF:A4:C9:91:78:B3:31:9E:48:02:
    		4D:A6:84:E6:6A:87:4B:B4:F5:5D:5D:EE:A5:CC:FC:28:23:C8:A9:A8:
    		E8:AA:09:6B:68:F0:7B:75:A5:0D:63:72:44:8B:9B:DB:89:A4:F4:21:
    		08:AA:47:D8:E1:87:68:DF:46:71:E6:B8:3F:7B:29:21:5D:3C:8D:39:
    		D2:B8:44:D5:20:A1:B8:6E:8F:A5:C8:6D:BF:35:C9:48:26:6C:07:10:
    		7B:AB:A2:D9:39:4F:60:2E:BE:CD:30:15:33:4D:D5:E0:42:F1:6C:F2:
    		3A:CA:51:4C:12:31:F6:C7:FC:72:C2:24:97:DF:27:8E:03:F3:D7:8A:
    		08:3D:D6:50:38:BA:CB:1C:87:F8:25:C0:2B:79:2E:02:F9:CC:34:BB:
    		E9:50:AE:CB:52:20:50:DF:16:46:85:7E:7B:FB:11:E2:61:6D:74:38:
    		45:F8:61:B0:E8:6D:62:63:71:AC:94:66:CA:C2:D3:4C:EE:F8:AE:15:
    		B0:1E:13:7E:FE:21:5B:47:BC:F5:11:69
    parm:           svc_rpc_per_connection_limit:uint
    parm:           auth_hashtable_size:RPC credential cache hashtable size (hashtbl_sz)
    parm:           auth_max_cred_cachesize:RPC credential maximum total cache size (ulong)
    parm:           min_resvport:portnr
    parm:           max_resvport:portnr
    parm:           tcp_slot_table_entries:slot_table_size
    parm:           tcp_max_slot_table_entries:max_slot_table_size
    parm:           udp_slot_table_entries:slot_table_size
    

LKM Dependencies & Use Count

The use count indicates how many times a module is being used. It helps the kernel decide whether a module can be safely removed.

root@grace-ubuntu:~# lsmod 
Module                  Size  Used by
bnep                   36864  2
snd_seq_dummy          12288  0
snd_hrtimer            12288  1
ib_core               512000  0

For example, the x_tables is used by ip_tables

root@grace-ubuntu:~# lsmod | grep x_tables
x_tables               65536  1 ip_tables

A module can be in used even if another modules doesnt need it. Example if process opened up a file associated with a driver module, then that would increment the use count. The use count indicates that the modules in used and need not to remove it.

Modules.dep 

  • Dependencies: Modules can depend on other modules, and these dependencies are listed in the modules.dep file. This file helps tools like modprobe load all necessary modules.

    For example, the ip_tables_ko shows that x_table.ko depends on it

    When you load ip_tables.ko using modprobe, it will automatically load x_tables.ko first.

    race@grace-ubuntu:/lib/modules/6.8.0-47-generic$ grep ip_tables.ko /lib/modules/$(uname -r)/modules.dep
    kernel/net/ipv4/netfilter/ip_tables.ko.zst: kernel/net/netfilter/x_tables.ko.zst
    

Challenges

  1. Which module(s) loaded has the greatest "Used by" number?

    shell script:

    lsmod | while
            read line
    do
            commas=$(echo $line | sed 's/[^,]//g' | wc -c)
            echo $commas $line
    done | sort -n
    ~
    ~                                                                               
    ~                                                                               
    ~                                                                               
    ~                      
    grace@grace-ubuntu:~$ ./mostusedby.sh | tail
    2 xor 12288 2 async_xor,btrfs
    3 async_xor 16384 3 async_pq,raid456,async_raid6_recov
    3 snd_hda_core 155648 3 snd_hda_codec_generic,snd_hda_intel,snd_hda_codec
    3 snd_pcm 196608 3 snd_hda_intel,snd_hda_codec,snd_hda_core
    3 snd_seq 126976 9 snd_seq_midi,snd_seq_midi_event,snd_seq_dummy
    3 snd_seq_device 16384 3 snd_seq,snd_seq_midi,snd_rawmidi
    3 snd_timer 53248 3 snd_seq,snd_hrtimer,snd_pcm
    4 raid6_pq 110592 4 async_pq,btrfs,raid456,async_raid6_recov
    5 async_tx 16384 5 async_pq,async_memcpy,async_xor,raid456,async_raid6_recov
    9 snd 147456 13 snd_hda_codec_generic,snd_seq,snd_seq_device,snd_hwdep,snd_hda_intel,snd_hda_codec,snd_timer,snd_pcm,snd_rawmidi
    grace@grace-ubuntu:~$ 

    The most used is the snd.

  2. Which module(s) loaded has the largest use count

    snd has the largest use count

    lsmod | while
            read line
    do
            count=$(echo $line | awk '{print $3;}')
            echo $count $line
    done | sort -n
    ~
    
    grace@grace-ubuntu:~$ bash largestcount.sh | tail
    3 snd_hda_core 155648 3 snd_hda_codec_generic,snd_hda_intel,snd_hda_codec
    3 snd_pcm 196608 3 snd_hda_intel,snd_hda_codec,snd_hda_core
    3 snd_seq_device 16384 3 snd_seq,snd_seq_midi,snd_rawmidi
    3 snd_timer 53248 3 snd_seq,snd_hrtimer,snd_pcm
    4 raid6_pq 110592 4 async_pq,btrfs,raid456,async_raid6_recov
    5 async_tx 16384 5 async_pq,async_memcpy,async_xor,raid456,async_raid6_recov
    9 bluetooth 1015808 9 bnep
    9 snd_seq 126976 9 snd_seq_midi,snd_seq_midi_event,snd_seq_dummy
    9 virtio_gpu 94208 9
    13 snd 147456 13 snd_hda_codec_generic,snd_seq,snd_seq_device,snd_hwdep,snd_hda_intel,snd_hda_codec,snd_timer,snd_pcm,snd_rawmidi
    
  3. From /lib/modules/$(uname -r)/mpdules.dep, which module has the greatest number of dependencies?

    lsmod | while
            read line
    do
            mods=$(echo $line | sed 's/^.*://'| wc -w)
            echo $mods $line
    done < /lib/modules/$(uname -r)/modules.dep | sort -n

     

    As checked, cx23885.ko depends on 20 modules

    20 kernel/drivers/media/pci/cx23885/cx23885.ko.zst: kernel/drivers/media/pci/cx23885/altera-ci.ko.zst kernel/drivers/media/tuners/tda18271.ko.zst kernel/drivers/misc/altera-stapl/altera-stapl.ko.zst kernel/drivers/media/dvb-frontends/m88ds3103.ko.zst kernel/drivers/media/common/cx2341x.ko.zst kernel/drivers/media/common/tveeprom.ko.zst kernel/drivers/media/common/videobuf2/videobuf2-dvb.ko.zst kernel/drivers/media/dvb-core/dvb-core.ko.zst kernel/drivers/media/common/videobuf2/videobuf2-dma-sg.ko.zst kernel/drivers/i2c/i2c-mux.ko.zst kernel/drivers/media/rc/rc-core.ko.zst kernel/drivers/media/common/videobuf2/videobuf2-memops.ko.zst kernel/drivers/media/common/videobuf2/videobuf2-v4l2.ko.zst kernel/drivers/media/v4l2-core/videodev.ko.zst kernel/drivers/media/common/videobuf2/videobuf2-common.ko.zst kernel/drivers/media/mc/mc.ko.zst kernel/sound/core/snd-pcm.ko.zst kernel/sound/core/snd-timer.ko.zst kernel/sound/core/snd.ko.zst kernel/sound/soundcore.ko.zst
    grace@grace-ubuntu:~$ 
    

    Hints:

    Number of dependent modules on a line: echo $line | sed 's/^.*://' | wc -w

    Number of used by modules on a line: echo $line | sed 's/[^,]//g' | wc -c

Loadable Kernel Modules

How they work: Writing LKM

To compile a kernel module, you need to use the kernel makefile that goes with the kernel

make -C /lib/modules/$(uname -r)/build M=$PWD modules

+------------------+
|  hello_module.c  | <-- Your C source file
+------------------+
          |
          v
+------------------+
|     Makefile     | <-- Defines how to compile the module
+------------------+
          |
          v
+-------------------------------+
| make -C /lib/modules/...      | <-- Builds using kernel headers
| M=$(PWD) modules              |
+-------------------------------+
          |
          v
+------------------+
| hello_module.ko  | <-- Compiled kernel module
+------------------+
          |
          v
+------------------+
|  insmod command  | <-- Inserts module into kernel
+------------------+
          |
          v
+-------------------------+
|  Kernel (Loads Module)  |
+-------------------------+
          |
          v
+----------------------------+
| dmesg ("Hello, Kernel")    | <-- View kernel logs/output
+----------------------------+

 

hello_module.c

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple Hello World kernel module");
MODULE_VERSION("1.0");

static int __init hello_start(void) {
    printk(KERN_INFO "Hello, Kernel World!\n");
    return 0;
}

static void __exit hello_end(void) {
    printk(KERN_INFO "Goodbye, Kernel World!\n");
}

module_init(hello_start);
module_exit(hello_end);

 

I'll stop here. There's still a lot more to learn.

Next, I plan to explore:

  1. Create a simple module using C code.
  2. Compile  it using makefile.
  3. Be able to create a kernel module that use GPL license.
  4. check the logs in dmesg