Part 3. Base Module for memory operations
Requirement:
This module is basically a memory management service that will allocate, read, write, and delete bytes of memory at the request of a user application, instead of the user application typically doing it via malloc() and pointers.
Sysfs entries are one way for a userspace program or command line to interact with a kernel module, but they are very limited. A more standard and robust way of interacting with the kernel is through device files, another type of virtual file that allow many different functions in your kernel module to be called by userspace with a variety of different, flexible parameters.
Solution
1. Device registration
There are two ways to allocate the major and minor number of a device[1]:
- Statically allocating
- Dynamically Allocating
If you want to set the particular major number to your driver, you can use statically method.
int register_chrdev(unsigned int, const char *, struct file_operations *)//int =0 dynamic allocate,return major num. int>0 static alloc
(In new version Linux 2.6+, register_chrdev_region for static, alloc_chrdev_region for dynamic[2])
What we use here is:
register_chrdev(unsigned int, const char *,struct file_operations *); //(0 or 1, device name, operations)
Dynamically advantage: can avoid conflict with other device drivers, since it dynamically allocates the device numbers for you.
Disadvantage: you can’t create the device nodes in advance, because the major number assigned to your module will vary. However, once the number has been assigned, you can read it from cat /proc/devices
.
2. Device File creation
Device file allows transparent communication between user space applications and hardware. In part one we create the major number, then we need to create device files in /dev/
directory[3].
We can create the dive file in two ways.
- Manually (using mknod: mknod -m <permissions> <name> <device type> <major> <minor>)
- Automatically(create class for device driver)
Here we introduce the second one: Automatically.
- Include the header file linux/device.h and linux/kdev_t.h
- Create the struct Class
- Create Device with the class which is created by above step
Create the struct class for our device driver(This will create a structure under/sys/class/
.):
struct class * class_create (struct module *owner, const char *name);
Create char device classes. A struct device will be created in sysfs, registered to the specified class:
struct device *device_create (struct *class, struct device *parent, dev_t dev, const char *fmt, ...);
Those three-step "register->create struct class->create device: should be written in "init_module" function. And destroy those class in cleanup_module(>linux 2.4: module_exit) when we unload the module.
3. Device file operation
After