Dean Leitersdorf Dean Leitersdorf - 1 year ago 73
Linux Question

Linux Character Device Modules: Why do we need both *owner and MOD_INC_USE_COUNT?

I am currently studying character device modules (drivers) and I am bewildered as to why there is both a use count and a *owner (in the file operations struct).

As can be seen in the following link, the file operations struct is:

struct file_operations {
struct module *owner;
loff_t (*llseek) (struct file *, loff_t, int);
ssize_t (*read) (struct file *, char *, size_t, loff_t *);
ssize_t (*write) (struct file *, const char *, size_t, loff_t *);
int (*readdir) (struct file *, void *, filldir_t);
unsigned int (*poll) (struct file *, struct poll_table_struct *);
int (*ioctl) (struct inode *, struct file *, unsigned int, unsigned long);
int (*mmap) (struct file *, struct vm_area_struct *);
int (*open) (struct inode *, struct file *);
int (*flush) (struct file *);
int (*release) (struct inode *, struct file *);
int (*fsync) (struct file *, struct dentry *, int datasync);
int (*fasync) (int, struct file *, int);
int (*lock) (struct file *, int, struct file_lock *);
ssize_t (*readv) (struct file *, const struct iovec *, unsigned long,
loff_t *);
ssize_t (*writev) (struct file *, const struct iovec *, unsigned long,
loff_t *);

As we were taught in class, the *owner is used to ensure that the module isn't unloaded if there is a device still using it.
However, further down the article in the link above, they describe that this is accomplished through the use of macros such as MOD_INC_USE_COUNT.

Therefore, my question is: why do we need both? Do the macros use the pointer in order to access this counter?

Answer Source

Incrementing module's usage counter requires module's structure to be in use.

Macro MOD_INC_USE_COUNT indirectly uses THIS_MODULE pointer, which corresponds to the currently compiled module. In other words, for increment module's usage counter with this macro, you need to call it from the module's code.

From the other side, file operations are issued from outside of the module (in Virtual FileSystem layer, VFS). So prevention of the module's unloading should be performed outside of the module, otherwise race conditions are unavoidable [Think about calling .open function from outside of the module and module's unloading at the same time]. That is why .owner field is needed.

Modern kernel doesn't have macro MOD_INC_USE_COUNT. Instead, it defines function

void __module_get(struct module* mod);

which directly accepts module parameter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download