4
votes

I'm studying Linux Device Driver programming 3rd edition and I have some questions about the open method, here's the "scull_open" method used in that 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:

  • Shouldn't this function returns a file descriptor to the device just opened?
  • Isn't the "*filp" local to this function, then why we copy the contents of dev to it?
  • How we could use later in read and write methods?
  • could someone writes to my a typical "non-fatty" implementation of 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; ...}

2

2 Answers

2
votes

Userspace open function is what you are thinking of, that is a system call which returns a file descriptor int. Plenty of good references for that, such as APUE 3.3.

Device driver "open method" is a function within file_operations structure. It is different than userspace "file open". With the device driver installed, when user code does open of the device (e.g. accessing /dev/scull0), this "open method" would then get called.

0
votes
  1. Shouldn't this function returns a file descriptor to the device just opened ? In linux device driver, open() returns either 0 or negative error code. File descriptor is internally managed by kernel.
  2. Isn't the "*filp" local to this function, then why we copy the contents of dev to it ? filp represents opened file and a pointer to it is passed to driver by kernel. Sometimes this filp is used sometimes it is not needed by driver. Copy contents of dev is required so that when some other function let us say read() is called driver can retrieve some device specific data.
  3. How we could use later in read and write methods ? One of the most common way to use filp in read/write() is to acquire lock. When device is opened driver will create a lock. Now when a read/write occurs same lock will be used to prevent data buffer from corruption in case multiple process are accessing same device.
  4. could someone writes to my a typical "non-fatty" implementation of open method ? As you are just studying please enjoy exploring more. An implementation can be found here