当kmalloc已经返回指向内存位置的指针时,为什么需要container_of?

时间:2015-09-17 08:30:25

标签: linux linux-kernel linux-device-driver

kmalloc()返回一个指向初始化期间分配的内存位置的指针,如果有一个包含cdev的结构指向它,为什么需要在文件操作open调用中执行container_of再次获取包含cdev的struct的地址?

1 个答案:

答案 0 :(得分:3)

我认为你指的是这样的事情:

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);
    // ...

kmalloc使用如下:

    scull_p_devices = kmalloc(scull_p_nr_devs * sizeof(struct scull_pipe), GFP_KERNEL);

struct scull_pipe的位置:

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 */
};

使用container_of的原因是,在scull_p_open回调中,您没有指向struct scull_pipe实例的指针,但您可以访问cdev成员{ {1}}结构(通过struct scull_pipe)。要获取inode->i_cdev的容器地址(换句话说,cdev实例的地址),您需要使用struct scull_pipe

container_of