字符设备驱动第三课---私有数据

来源:互联网 发布:windows安装ant 编辑:程序博客网 时间:2024/05/23 13:46

一、设备中的私有属性

struct file 结构体中专门为用户留了一个域用于定义私有数据,是个void *型的指针。通过它可以将私有数据一路从open带到read, write,层层传入。一般是在open 的时候赋值,reads时用。

1、结构体定义:

struct file {union {struct llist_nodefu_llist;struct rcu_head fu_rcuhead;} f_u;struct pathf_path;struct inode*f_inode;/* cached value */const struct file_operations*f_op;/* * Protects f_ep_links, f_flags. * Must not be taken from IRQ context. */spinlock_tf_lock;atomic_long_tf_count;unsigned int f_flags;fmode_tf_mode;struct mutexf_pos_lock;loff_tf_pos;struct fown_structf_owner;const struct cred*f_cred;struct file_ra_statef_ra;u64f_version;#ifdef CONFIG_SECURITYvoid*f_security;#endif/* needed for tty driver, and maybe others */void*private_data;//私有数据#ifdef CONFIG_EPOLL/* Used by fs/eventpoll.c to link all the hooks to this file */struct list_headf_ep_links;struct list_headf_tfile_llink;#endif /* #ifdef CONFIG_EPOLL */struct address_space*f_mapping;} __attribute__((aligned(4)));/* lest something weird decides that 2 is OK */

2、open中对file结构体中的私有域赋值:

static int i2cdev_open(struct inode *inode, struct file *file){unsigned int minor = iminor(inode);struct i2c_client *client;struct i2c_adapter *adap;adap = i2c_get_adapter(minor);if (!adap)return -ENODEV;/* This creates an anonymous i2c_client, which may later be * pointed to some address using I2C_SLAVE or I2C_SLAVE_FORCE. * * This client is ** NEVER REGISTERED ** with the driver model * or I2C core code!!  It just holds private copies of addressing * information and maybe a PEC flag. */client = kzalloc(sizeof(*client), GFP_KERNEL);if (!client) {i2c_put_adapter(adap);return -ENOMEM;}snprintf(client->name, I2C_NAME_SIZE, "i2c-dev %d", adap->nr);client->adapter = adap;file->private_data = client;//对私有域进行赋值return 0;}

3、在read中引用:

static ssize_t i2cdev_read(struct file *file, char __user *buf, size_t count,loff_t *offset){char *tmp;int ret;struct i2c_client *client = file->private_data;//用用私有数据域if (count > 8192)count = 8192;tmp = kmalloc(count, GFP_KERNEL);if (tmp == NULL)return -ENOMEM;pr_debug("i2c-dev: i2c-%d reading %zu bytes.\n",iminor(file_inode(file)), count);ret = i2c_master_recv(client, tmp, count);if (ret >= 0)ret = copy_to_user(buf, tmp, count) ? -EFAULT : ret;kfree(tmp);return ret;}




4、对私有域进行释放:

static int i2cdev_release(struct inode *inode, struct file *file){struct i2c_client *client = file->private_data;i2c_put_adapter(client->adapter);kfree(client);file->private_data = NULL;//对私有域进行释放return 0;}


0 0
原创粉丝点击