Reputation: 127
kmalloc() returns a pointer to the memory location allocated during initialization and if one makes the struct containing cdev point to it, why would one need to do container_of in the file operations open call to get the address of struct containing cdev again ?
Upvotes: 0
Views: 367
Reputation: 22157
I presume you're referring to something like this:
http://www.cs.uni.edu/~diesburg/courses/dd/code/scull/pipe.c
static int scull_p_open(struct inode *inode, struct file *filp)
{
struct scull_pipe *dev;
dev = container_of(inode->i_cdev, struct scull_pipe, cdev);
// ...
And kmalloc
is used like this:
scull_p_devices = kmalloc(scull_p_nr_devs * sizeof(struct scull_pipe), GFP_KERNEL);
Where struct scull_pipe
is:
struct scull_pipe {
wait_queue_head_t inq, outq; /* read and write queues */
char *buffer, *end; /* begin of buf, end of buf */
int buffersize; /* used in pointer arithmetic */
char *rp, *wp; /* where to read, where to write */
int nreaders, nwriters; /* number of openings for r/w */
struct fasync_struct *async_queue; /* asynchronous readers */
struct semaphore sem; /* mutual exclusion semaphore */
struct cdev cdev; /* Char device structure */
};
The reason for using container_of
is that in scull_p_open
callback you don't have pointer to struct scull_pipe
instance, but you have access to cdev
member of struct scull_pipe
structure (through inode->i_cdev
). In order to get the container address of cdev
(in other words address of struct scull_pipe
instance), you need to use container_of
:
struct scull_pipe *dev;
dev = container_of(inode->i_cdev, struct scull_pipe, cdev);
Upvotes: 3