# Linux Kernel Module Cheat

### 17.16. UIO

UIO is a kernel subsystem that allows to do certain types of driver operations from userland.

This would be awesome to improve debuggability and safety of kernel modules.

VFIO looks like a newer and better UIO replacement, but there do not exist any examples of how to use it: https://stackoverflow.com/questions/49309162/interfacing-with-qemu-edu-device-via-userspace-i-o-uio-linux-driver

TODO get something interesting working. I currently don’t understand the behaviour very well.

TODO how to ACK interrupts? How to ensure that every interrupt gets handled separately?

TODO how to write to registers. Currently using `/dev/mem` and `lspci`.

This example should handle interrupts from userland and print a message to stdout:

    ./uio_read.sh

TODO: what is the expected behaviour? I should have documented this when I wrote this stuff, and I’m that lazy right now that I’m in the middle of a refactor :-)

UIO interface in a nutshell:

- blocking read / poll: waits until interrupts

- `write`: call `irqcontrol` callback. Default: 0 or 1 to enable / disable interrupts.

- `mmap`: access device memory

Sources:

- userland/kernel_modules/uio_read.c

- rootfs_overlay/lkmc/uio_read.sh

Bibliography:

- https://stackoverflow.com/questions/15286772/userspace-vs-kernel-space-driver

- https://01.org/linuxgraphics/gfx-docs/drm/driver-api/uio-howto.html

- https://stackoverflow.com/questions/7986260/linux-interrupt-handling-in-user-space

- https://yurovsky.github.io/2014/10/10/linux-uio-gpio-interrupt/

- https://github.com/bmartini/zynq-axis/blob/65a3a448fda1f0ea4977adfba899eb487201853d/dev/axis.c

- https://yurovsky.github.io/2014/10/10/linux-uio-gpio-interrupt/

- http://nairobi-embedded.org/uio_example.html that website has QEMU examples for everything as usual. The example has a kernel-side which creates the memory mappings and is used by the user.

- https://stackoverflow.com/questions/49309162/interfacing-with-qemu-edu-device-via-userspace-i-o-uio-linux-driver

- userland driver stability questions:

  - https://stackoverflow.com/questions/8030758/getting-kernel-version-from-linux-kernel-module-at-runtime/45430233#45430233

  - https://stackoverflow.com/questions/37098482/how-to-build-a-linux-kernel-module-so-that-it-is-compatible-with-all-kernel-rele/45429681#45429681

  - https://liquidat.wordpress.com/2007/07/21/linux-kernel-2623-to-have-stable-userspace-driver-api/