Understand the purpose and basic usage of a Linux character device
What is a character device?
Why do we want to use character devices
How does the user interact with character devices?
How does a kernel module implement a character device?
Character by character kernel interface
Streamed, not buffered
Not necessarily related to physical device
Can implement a device driver
We will come back to this
A file in /dev
/dev
Generally implemented by a kernel module
Generally located in the /dev directory
ls -l /dev
mknod(7)
cat /proc/devices
Same interface as any other file
cat, echo, and other commands
cat
echo
System calls in a program
Playing with devices:
/dev/null: discard input
/dev/null
/dev/zero: zero output
/dev/zero
/dev/tty: this terminal
/dev/tty
/dev/kmsg: kernel ring buffer access
/dev/kmsg
/dev/urandom: random bytes (click for mythology)
/dev/urandom
/dev/mem: physical memory access
/dev/mem
Random number generator
Between 0 and 256
Read with cat
Need major and minor numbers
Need file operations
Register device with cdev subsystem
Implement open and close handlers
Implement read and write handlers
__init
Special section
Can reclaim after module load
kdlpdev4.c
Contained in dev_t type
dev_t
Related: MAJOR, MINOR, and MKDEV
MAJOR
MINOR
MKDEV
In init(): alloc_chrdev_region()
init()
alloc_chrdev_region()
In exit(): unregister_chrdev_region()
exit()
unregister_chrdev_region()
register_chrdev_region()
Static rather than dynamic
Why don't we use this?
kdlpdev3.c
struct cdev
struct file_operations
In init(): cdev_init() and cdev_add()
cdev_init()
cdev_add()
Alternative: cdev_alloc()
cdev_alloc()
Why or why not?
In exit(): cdev_del()
cdev_del()
kdlpdev2.c
struct inode
struct file
kdlpdev1.c
copy_to_user()
__user macro
__user
Useful for static analysis and documentation
No runtime effect
The complete kdlpdev.c
kdlpdev.c
A character device implements a character-by-character interface with the kernel
A kernel module can implement a character device
A character device is identified by a major and minor number
Character devices are generally located in /dev
Not required
Only the major and minor matter to the kernel
Character devices are labeled by 'c' in ls -l output
ls -l
The /proc/devices file contains a list of major numbers and character devices
/proc/devices
Use open(2), close(2), read(2), write(2), and more to interact with the character device
open(2)
close(2)
read(2)
write(2)