11-读写函数
6.3.3 读写函数
globalmem设备驱动的读写函数主要是让设备结构体的mem[]数组与用户空间交互数据,并随着访问的字节数变更返回给用户的文件读写偏移位置。读和写函数的实现分别如代码清单6.12 和6.13所示。
代码清单6.12 globalmem设备驱动读函数
1 static ssize_t globalmem_read(struct file filp, char __user buf, size_t count,
2 loff_t *ppos)
3 {
4 unsigned long p = *ppos;
5 int ret = 0;
6
7 /分析和获取有效的读长度/
8 if (p >= GLOBALMEM_SIZE) /* 要读的偏移位置越界
9 return 0;
10 if (count > GLOBALMEM_SIZE - p)/* 要读的字节数太大
11 count = GLOBALMEM_SIZE - p;
12
13 /内核空间→用户空间/
14 if (copy_to_user(buf, (void*)(dev.mem + p), count))
15 ret = - EFAULT;
16 else {
17 *ppos += count;
18 ret = count;
19
20 printk(KERN_INFO "read %d bytes(s) from %d\n", count, p);
21 }
22
23 return ret;
24 }
代码清单6.13 globalmem设备驱动写函数
1 static ssize_t globalmemwrite(struct file *filp, const char _user *buf,
2 size_t count, loff_t *ppos)
3 {
4 unsigned long p = *ppos;
5 int ret = 0;
6
7 /分析和获取有效的写长度/
8 if (p >= GLOBALMEM_SIZE) /* 要写的偏移位置越界
9 return 0;
10 if (count > GLOBALMEM_SIZE - p) /* 要写的字节数太多
11 count = GLOBALMEM_SIZE - p;
12
13 /用户空间→内核空间/
14 if (copy_from_user(dev.mem + p, buf, count))
15 ret = - EFAULT;
16 else {
17 *ppos += count;
18 ret = count;
19
20 printk(KERN_INFO "written %d bytes(s) from %d\n", count, p);
21 }
22
23 return ret;
24 }