Should I open the method in the Linux device driver, return the file descriptor?

I am learning about Linux device driver 3rd edition programming, and I have some questions about the open method, using the scull_open method used in this book:

int scull_open(struct inode *inode, struct file *filp){ struct scull_dev *dev; /* device information */ dev = container_of(inode->i_cdev, struct scull_dev, cdev); filp->private_data = dev; /* for other methods */ /* now trim to 0 the length of the device if open was write-only */ if ( (filp->f_flags & O_ACCMODE) == O_WRONLY) { if (down_interruptible(&dev->sem)) return -ERESTARTSYS; scull_trim(dev); /* ignore errors */ up(&dev->sem); } return 0; /* success */ } 

And my questions are:

  • Should this function not return a file descriptor to a newly opened device?
  • Isn't that "* filp" for this function, why are we copying the contents of dev to it?
  • How could we use read and write methods later?
  • can someone write my typical "inanimate" implementation of an open method?

    ssize_t scull_read (struct file * filp, char __user * buf, size_t count, loff_t * f_pos) {struct scull_dev * dev = filp-> private_data; ...}

+4
source share
2 answers

The function of open access to the user is what you think about, it is a system call that returns an int file descriptor. Lots of good links for this, like APUE . 3.3.

An open method device driver is a function in the file_operations structure. It differs from the "open file" in user space. When the device driver is installed, when user code opens the device (for example, calls to / dev / scull 0), this "public method" will be called.

+2
source
  • Should this function not return a file descriptor to a newly opened device? In the linux device driver, the open () function returns either 0 or a negative error code. The file descriptor is internally managed by the kernel.
  • Is this "* filp" local to this function, why are we copying the contents of dev to it? filp represents an open file and a pointer to it is passed to the driver through the kernel. Sometimes this file is used sometimes when the driver is not needed. Copying the contents of dev is required so that when some other function allows us to say that read () is called a driver, it can retrieve some device-specific data.
  • How could we use read and write methods later? One of the most common ways to use filp in read / write () is to get a lock. When the device is open, the driver will create a lock. Now that read / write occurs, the same lock will be used to prevent damage to the data buffer in the event that multiple processes access the same device.
  • can someone write my typical "inanimate" implementation of an open method? As you study, please learn more. The implementation can be found here.
0
source

Source: https://habr.com/ru/post/1495112/


All Articles