Character Device Simulation pipe driver
Let's end the simple character device with a device driver of "pipe" (The Pipe mentioned here is not a standard pipe, but it just simulates a device that writes data from one end to the other)
Test code 1 test code 2
Design Concept
Use a picture to explain (but it has been drawn for a long time)
Simply put, a process writes data to the buffer. Another process can read the data. After reading the data, the data in the original buffer is set to an invalid value,
Customize a structure
# Define max_simple_len 1024 // buffer Data Length struct simple_dev {char * data; // point to the data header char * datard; // read pointer char * datawr; // write pointer char * dataend; // point to the end of the buffer wait_queue_head_t INQ; // read the waiting queue header wait_queue_head_t outq; // write the waiting queue header struct cdev; // character device structure struct semaphore SEMP; // struct semaphore };
Apply for device number
I will not repeat the previous Introduction
Allocate Area Memory for custom struct
D("alloc simple_dev struct \n"); char7_dev = kmalloc(DEV_COUNT*sizeof(struct simple_dev), GFP_KERNEL); if( char7_dev == NULL) { printk(KERN_ERR "kmalloc simple_dev err no memory"); unregister_chrdev_region(dev, DEV_COUNT); return -ENOMEM; }
Use kmalloc to allocate memory to the device structure. Because the system may not be able to allocate memory temporarily (although rare), check whether the allocation is successful after the memory is allocated, after detecting successful memory allocation, you also need to clear the allocated memory area to avoid any strange errors that may be difficult to debug (remember)
memset(char7_dev, 0, DEV_COUNT*sizeof(struct simple_dev));
Apply for memory for the Buffer Zone
After applying for memory for a custom structure, we need to apply for memory for the buffer in each structure. The same method is used to allocate and clear the memory.
for( index = 0 ; index < DEV_COUNT ; ++index ) { //char7_dev[index].count = 0 if(( char7_dev[index].data = kmalloc(MAX_SIMPLE_LEN, GFP_KERNEL) )!= NULL ) { memset(char7_dev[index].data, 0, MAX_SIMPLE_LEN); D("kmalloc the data space OK! \n"); } else{ for( --index ; index >= 0 ; --index ) { kfree(char7_dev[index].data); } printk(KERN_ERR "kmalloc simple_dev data number err no memory"); kfree(char7_dev); unregister_chrdev_region(dev, DEV_COUNT); return -ENOMEM; }}
Note that when a buffer fails to be applied for, you need to release the successfully applied memory (else has done this)
Initialize various data pointers, semaphores, and wait queue headers in the struct.
After applying for the buffer memory of the device and each device, we need to initialize some variables in the structure,
Initialize Data Pointer
Point data to the buffer start position, datawr, and datard initialization also point to the starting position (indicating an empty buffer), and dataend points to an invalid position at the end of the buffer to determine whether the read/write position is legal
Initialize semaphores and read/write queue Headers
for( index = 0 ; index < DEV_COUNT ; ++index ) { /*init the data ptr*/ char7_dev[index].datard = char7_dev[index].data; char7_dev[index].datawr = char7_dev[index].data; char7_dev[index].dataend = char7_dev[index].data + MAX_SIMPLE_LEN; /*init semaphore, waitqueue_head and so on*/ sema_init(&(char7_dev[index].semp), 1); init_waitqueue_head(&(char7_dev[index].inq)); init_waitqueue_head(&(char7_dev[index].outq)); }
Initialize character device add character device
Device-by-device initialization (registration) and addition (inform kernel)
for( index = 0 ; index < DEV_COUNT ; ++index ) { cdev_init(&(char7_dev[index].cdev), &simple_fops); char7_dev[index].cdev.owner = THIS_MODULE; err = cdev_add(&(char7_dev[index].cdev), dev, 1); if(err < 0) { printk(KERN_ERR "add cdev err \n"); goto error1; } else { D( "add %d char dev OK!\n", index+1); } }Character device operations
struct file_operations simple_fops={ .owner = THIS_MODULE, .open = simple_open, .release = simple_close, .read = simple_read, .write = simple_write, .llseek = simple_llseek,// .ioctl = simple_ioctl, .poll = simple_poll, .mmap = simple_mmap,};
Because there is no IOCTL Method for file operations after 2.6.35, we will not introduce it anymore.
Open and Close operations
There is no difference between enable or disable the function and the driver of the previous device.
Read/write operations
First, obtain the semaphore (read and write operations are the same)
if(down_interruptible(&dev->semp) < 0) { printk(KERN_ERR "[%s]get the mutex lock error %d, %s", current->comm, __LINE__, __func__); return -ERESTARTSYS; } else { D("have get the mutex %d\n", __LINE__); }Read operations
For read operations, check whether there is data in the buffer.
If (Dev-> datawr = Dev-> datard) // empty buffer {While (Dev-> datawr = Dev-> datard) // check whether the buffer has data {up (& Dev-> SEMP); // release the semaphores if (filp-> f_flags & o_nonblock) // check whether the user is non-blocking open {d ("set nonblock mask % d \ n", _ line _); Return-eagain ;} D ("[% s] Reading going to sleep! ", Current-> comm);/* Add the calling process to the write wait queue */If (wait_event_interruptible (Dev-> INQ, Dev-> datard! = Dev-> datawr) {return-erestartsys;} If (down_interruptible (& Dev-> SEMP) <0) // wait_wvent_interrupt returns, obtain the semaphore {printk (kern_err "[% s] Get the mutex lock error % d, % s", current-> comm, _ line __, _ FUNC __); return-erestartsys;} else {d ("have get the mutex % d \ n", _ line __);}}}
Here, you may already know that the above flowchart has some errors (the up and down operations should be done in the while loop, rather than in the entire if) and will not be modified due to time issues.
Calculate the remaining buffer data
If the read pointer is after the write pointer (datard> datawr), the data in the buffer is transferred from the read position to the end of the buffer, and from the beginning of the buffer to the write position.
if(dev->datawr < dev->datard) { data_remain = (dev->dataend - dev->datard) + (dev->datawr-dev->data); } else { data_remain = dev->datawr - dev->datard; }
If you do not understand it, you can refer to the following. It is easy to understand the length of the data in the buffer.
Determine the validity of the Data Length and calculate the length of the user space that can be written.
if(data_remain < 0) { printk(KERN_ERR "the remain data we calculate is wrong check! %d \n", __LINE__); } else if(count > data_remain) { WAR("the data is less than the user want to read\n"); D("we can only copy %d bytes to user\n", data_remain); count = data_remain; } else { }
Input data to user space
1. When the read operation does not read the end of the buffer, copy the data directly to the user, adjust the read pointer, wake up the process sleeping in the write queue, and release the semaphore, returns the length of the read data.
if(( dev->datawr > dev->datard ) || (dev->datard + count <= dev->dataend)) { err = copy_to_user(userstr, dev->datard, count); if(err != 0) { printk(KERN_ERR "an error occured when copy data to user:%d\n", __LINE__); up(&dev->semp); return err; } else { D("data copy to user OK\n"); dev->datard = dev->datard + count; if(dev->datard == dataend) dev->datard = dev->data; wake_up_interruptible(&dev->outq); up(&dev->semp); return count; } }
2. If the buffer end is read, it needs to be rolled back and read from the data header.
Read the data from the read pointer to the end of the buffer.
Then read the data of the corresponding length from the header.
Similarly, after successful reading, You must wake up the write wait queue, adjust the read pointer, and release the semaphore.
Else {data_remain = (Dev-> dataend-Dev-> datard);/* read the data length from the current position to the end of the buffer */err = copy_to_user (userstr, dev-> datard + 1, data_remain); If (Err! = 0) {printk (kern_err "an error occured when copy data to user: % d \ n", _ line _); up (& Dev-> SEMP ); return err;} else {d ("data copy to user OK \ n"); // up (& Dev-> SEMP );} /* read the remaining length from the buffer header */err = copy_to_user (userstr + data_remain, Dev-> data, count-data_remain); If (Err! = 0) {printk (kern_err "an error occured when copy data to user: % d \ n", _ line _); up (& Dev-> SEMP ); return err;} else {d ("data copy to user OK \ n"); Dev-> datard = Dev-> Data + (count-data_remain ); wake_up_interruptible (& Dev-> outq); up (& Dev-> SEMP); Return count ;}}
Write operation
Similar to read Operations
Get the location to be written
Check whether the buffer is full. Check whether the address to be written is valid (whether it has reached the tail position). If the data has been written to the end of the buffer, adjust the write.
If (Dev-> datawr + 1 = Dev-> dataend) // The position to be written is at the end of the buffer next_ptr = Dev-> data; // adjust the write pointer to else next_ptr = Dev-> datawr + 1;
Determine whether the buffer is full
When the position to be written is exactly the position pointed to by the read pointer, it indicates that the buffer is full and needs to wait for the read process.
if( next_ptr == dev->datard ) { while(next_ptr == dev->datard) { up(&dev->semp); if(filp->f_flags & O_NONBLOCK) { D("set NONBLOCK mask %d\n", __LINE__); return -EAGAIN; } D("[%s] writing going to sleep!", current->comm); if(wait_event_interruptible(dev->outq, next_ptr != dev->datard)) { return -ERESTARTSYS; } if(down_interruptible(&dev->semp) < 0) { printk(KERN_ERR "[%s]get the mutex lock error %d, %s", current->comm, __LINE__, __func__); return -ERESTARTSYS; } else { D("have get the mutex %d\n", __LINE__); } } }
Calculate the remaining buffer length (the length of data that can be written)
You can refer
if(dev->datawr >= dev->datard) { remain_space = (dev->dataend - dev->datawr-1) + (dev->datard - dev->data); } else { remain_space = dev->datard - dev->datawr - 1; }
Adjust the read/write pointer for writing data to the buffer
if( (dev->datawr < dev->datard) || (dev->datawr + count < dev->dataend) ) { err = copy_from_user(dev->datawr, userstr, count); if(err != 0) { printk(KERN_ERR "error occured when copy data from user %d\n", __LINE__); up(&dev->semp); return err; } else { D("data copy from user OK\n"); dev->datawr = dev->datawr + count ; wake_up_interruptible(&dev->inq); up(&dev->semp); return count; } } else { remain_space = dev->dataend - dev->datawr ; err = copy_from_user(dev->datawr, userstr, remain_space); if(err != 0) { printk(KERN_ERR "error occured when copy data from user %d\n", __LINE__); up(&dev->semp); return err; } else { D("copy part of the data from user\n"); } err = copy_from_user(dev->data, userstr+remain_space, count-remain_space); if(err != 0) { printk(KERN_ERR "error occured when copy data from user %d\n", __LINE__); up(&dev->semp); return err; } else{ D("data copy from user OK\n"); dev->datawr = dev->data + (count-remain_space); wake_up_interruptible(&dev->inq); up(&dev->semp); return count; } }
The poll method calls poll_wait on the waiting queue.
poll_wait(filp, &dev->inq, wait); poll_wait(filp, &dev->outq, wait);
Checks whether the file is readable or writable.
if(dev->datard != dev->datawr) { mask |= POLLIN | POLLRDNORM; //can be read } if(dev->datawr+1 == dev->dataend) next_ptr = dev->data; else next_ptr = dev->datawr+1; if(next_ptr != dev->datard) { mask |= POLLOUT | POLLWRNORM; //can be write }