先看看字符设备驱动的架构:
cdev结构体是字符设备的核心数据结构,用于描述一个字符设备,cdev定义如下:
#include <linux/cdev.h> struct cdev { struct kobject kobj; struct module *owner; const struct file_operations *ops; // 文件操作结构体 struct list_head list; dev_t dev; // 设备号,12bit主设备号+20bit次设备号 unsigned int count; // 设备个数 };设备号相关宏定义:MAJOR(dev); // 获取主设备号MINOR(dev); // 获取从设备号MKDEV(major,minor); // 生产设备号 cdev相关函数接口:
void cdev_init(struct cdev *, const struct file_operations *); // 将cdev与file_operations挂钩struct cdev *cdev_alloc(void);void cdev_put(struct cdev *p);int cdev_add(struct cdev *, dev_t, unsigned); // 向系统中添加cdev,同时将cdev与设备号挂钩(设备号和设备名称是文件系统的组成部分,与用户交互的桥梁) // 注意判断返回值, A negative error code is returned on failure.返回1个负数void cdev_del(struct cdev *); // 从系统中删除cdev
注册设备号和释放设备号,设备号也是系统资源,需要注意在注销函数时释放:
#include <linux/fs.h>/** * alloc_chrdev_region() - register a range of char device numbers * @dev: output parameter for first assigned number * @baseminor: first of the requested range of minor numbers * @count: the number of minor numbers required * @name: the name of the associated device or driver * * Allocates a range of char device numbers. The major number will be * chosen dynamically, and returned (along with the first minor number) * in @dev. Returns zero or a negative error code. */int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count,const char *name); // 动态分配,并注册设备号
/** * register_chrdev_region() - register a range of device numbers * @from: the first in the desired range of device numbers; must include the major number. * @count: the number of consecutive device numbers required * @name: the name of the device or driver. * * Return value is zero on success, a negative error code on failure. */int register_chrdev_region(dev_t from, unsigned count, const char *name); // 将已知的设备号注册到系统中
/** * unregister_chrdev_region() - return a range of device numbers * @from: the first in the range of numbers to unregister * @count: the number of device numbers to unregister * * This function will unregister a range of @count device numbers, * starting with @from. The caller should normally be the one who * allocated those numbers in the first place... */void unregister_chrdev_region(dev_t from, unsigned count); // 注销设备号
file_operations是字符设备驱动设计的主要内容, 应用程序进行open、close、write、read等操作时,通过文件系统简介调用file_operations里驱动实现的函数接口。
#include <linux/fs.h> struct file_operations { struct module *owner; // module是内核表示模块的单元,THIS_MODULE表示当前模块,insmod时内核创建一个module结构体 loff_t (*llseek) (struct file *, loff_t, int); // 修改文件当前读写位置,返回新位置,出错时返回-1 ssize_t (*read) (struct file *, char __user *, size_t, loff_t *); // 读数据,与应用程序的read和fread对应 ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *); // 写数据,与应用程序的write和fwrite对应;若未实现,应用调用时返回-EINVAL ssize_t (*aio_read) (struct kiocb *, const struct iovec *, unsigned long, loff_t); ssize_t (*aio_write) (struct kiocb *, const struct iovec *, unsigned long, loff_t); int (*iterate) (struct file *, struct dir_context *); unsigned int (*poll) (struct file *, struct poll_table_struct *); // 多路复用 long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long); // 对应应用程序的ioctl long (*compat_ioctl) (struct file *, unsigned int, unsigned long); int (*mmap) (struct file *, struct vm_area_struct *); // 帧缓存是有用,应用映射后可直接访问内存空间,与应用程序的mmap对应。若驱动未实现时如果应用调用,返回-ENODEV int (*open) (struct inode *, struct file *); // 若未定义,应用调用时返回成功 int (*flush) (struct file *, fl_owner_t id); int (*release) (struct inode *, struct file *); int (*fsync) (struct file *, loff_t, loff_t, int datasync); int (*aio_fsync) (struct kiocb *, int datasync); int (*fasync) (int, struct file *, int); int (*lock) (struct file *, int, struct file_lock *); ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int); unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long); int (*check_flags)(int); int (*flock) (struct file *, int, struct file_lock *); ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int); ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int); int (*setlease)(struct file *, long, struct file_lock **); long (*fallocate)(struct file *file, int mode, loff_t offset, loff_t len); int (*show_fdinfo)(struct seq_file *m, struct file *f); };【注意】各结构体成员的参数是struct file和struct inode,而不是应用程序里的文件描述符fd;
原书中没有介绍如何在/dev目录下自动生成设备文件,可使用如下函数实现
#include <linux/device.h>#define class_create(owner, name) ({ \ static struct lock_class_key __key; \ __class_create(owner, name, &__key); \ })
/** * class_create - create a struct class structure * @owner: pointer to the module that is to "own" this struct class * @name: pointer to a string for the name of this class. * @key: the lock_class_key for this class; used by mutex lock debugging * * This is used to create a struct class pointer that can then be used * in calls to device_create(). * * Returns &struct class pointer on success, or ERR_PTR() on error. * * Note, the pointer created here is to be destroyed when finished by * making a call to class_destroy(). */ struct class *__class_create(struct module *owner, const char *name,struct lock_class_key *key)
/** * device_create - creates a device and registers it with sysfs * @class: pointer to the struct class that this device should be registered to * @parent: pointer to the parent struct device of this new device, if any * @devt: the dev_t for the char device to be added * @drvdata: the data to be added to the device for callbacks * @fmt: string for the device's name * * This function can be used by char device classes. A struct device * will be created in sysfs, registered to the specified class. * * A "dev" file will be created, showing the dev_t for the device, if * the dev_t is not 0,0. * If a pointer to a parent struct device is passed in, the newly created * struct device will be a child of that device in sysfs. * The pointer to the struct device will be returned from the call. * Any further sysfs files that might be required can be created using this * pointer. * * Returns &struct device pointer on success, or ERR_PTR() on error. * * Note: the struct class passed to this function must have previously * been created with a call to class_create(). */ struct device *device_create(struct class *class, struct device *parent, dev_t devt, void *drvdata, const char *fmt, ...)/*** device_destroy - removes a device that was created with device_create()* @class: pointer to the struct class that this device was registered with* @devt: the dev_t of the device that was previously registered** This call unregisters and cleans up a device that was created with a* call to device_create().*/void device_destroy(struct class *class, dev_t devt);
#include <linux/cdev.h> // cdev#include <linux/fs.h> // file_operations#include <linux/device.h> // class,device/* 设备结构体 */ struct xxx_dev_t { struct cdev cdev; // 一般cdev结构体不进行动态分配,直接定义在驱动程序里 struct class class; // 定义class,为了生成/dev/设备文件 ....}xxx_dev; /* 驱动模块加载函数 */ static int __init xxx_init( void ){ ... cdev_init( &xxx_dev.cdev, &xxx_fops ); // 建立cdev与file_operations的关联 xxx_dev.cdev.owner = THIS_MODULE; /* 注册设备号 */ if( xxx_major ){ register_chrdev_region( xxx_dev_no, 1, DEV_NAME ); } else{ alloc_chrdev_region( &xxx_dev_no,0,1,DEV_NAME ); } ret = cdev_add( &xxx_dev.cdev, xxx_dev_no,1 ); // 注册字符设备 if(ret){ // err proccess } /* 设备文件相关 */ xxx_dev.class = class_create( THIS_MODULE, DEV_NAME ); // 创建class device_create( &xxx_dev.class, NULL, xxx_dev_no,NULL, DEV_NAME ); // 创建device,会在/dev目录下生成名字为DEV_NAME的设备文件 ...} /* 驱动模块卸载函数 */static void __exit xxx_exit( void ){ unregister_chrdev_region( xxx_dev_no, 1); // 释放占用的设备号 cdev_del( &xxx_dev.cdev ); // 注销字符设备}module_init(xxx_init);module_eixt(xxx_exit);
【注意】
init和exit函数的格式,static int __init xxx_init( void ),否则大多数驱动都要实现read、write、ioctl等函数 【注意】:
1.参数中的*f_pos实际应该就是指向filp->f_pos的指针,由文件系统统一管理的偏移,驱动中read/write要直接使用这个偏移,并在完成操作后更新这个指针;
2.llseek的参数中没有*f_pos,直接操作filp->f_pos即可。
struct file_operations xxx_fops = { .owner = THIS_MODULE, .read = xxx_read, .write = xxx_write, .unlocked_ioctl = xxx_ioctl, ...}ssize_t xxx_read( struct file * filp, char __user *buf, size_t count, loff_t * f_pos ){ ... copy_to_user( buf, ..., ...); ...} ssize_t xxx_write( struct file * filp, char __user *buf, size_t count, loff_t * f_pos ){ ... copy_from_user( buf, ..., ...); ...}long xxx_ioctrl( struct file * filp, unsigned int cmd, unsigned long arg ){ ... switch( cmd ){ case XXX_CMD1: ... break; case XXX_CMD2: ... break; default: // 不支持的命令 return -ENOTTY; } return 0;}
【注意】:
1.读写函数的参数中,buf是用户空间的,处于内核态的驱动不应该直接读写,应该调用特定接口,如下:
2. 注意copy_to/from_user的参数位置,都是从第2个参数拷贝到第一个参数,有点类似memcpy,别搞反了!
3. 注意检查copy函数的返回值,返回值n是剩余的字节数,正常时应该为0
#include <linux/uaccess.h> // 内部包含 arch/arm/inculde/asm/uaccess.h,看来除了linux源码根目录的include目录,arch/arm/include也是驱动搜索的头文件目录static inline unsigned long __must_check copy_from_user(void *to, const void __user *from, unsigned long n) { if (access_ok(VERIFY_READ, from, n)) // 先检查是否传入的缓冲区是否属于用户空间 n = __copy_from_user(to, from, n); else /* security hole - plug it */ memset(to, 0, n); return n; } static inline unsigned long __must_check copy_to_user(void __user *to, const void *from, unsigned long n) { if (access_ok(VERIFY_WRITE, to, n)) n = __copy_to_user(to, from, n); return n; }对于简单类型,如char,int,long可以使用简单的函数进行复制,如下:#define get_user(x,p) __get_user(x,p) // x是变量,p是用户空间地址, x = *p #define put_user(x,p) __put_user(x,p) // *p = x
#define __get_user(x,ptr) \ ({ \ long __gu_err = 0; \ __get_user_err((x),(ptr),__gu_err); \ __gu_err; \ })
#define __put_user(x,ptr) \ ({ \ long __pu_err = 0; \ __put_user_err((x),(ptr),__pu_err); \ __pu_err; \ })
命令最好能区分不同设备,如果所有驱动都采用1,2,3这类命令,会造成命令码污染。linux有一套统一的ioctl命令生成的方式,最好使用该机制。 强制使用土鳖的1/2/3,没不会有啥大的问题。
设备类型type,是1个幻数,应参考内核中的ioctl-number.txt,不要与已使用的冲突;
序列号nr,8bit;
方向dir,_IOC_NONE( 无数据传输) 、_IOC_READ( 读) 、 _IOC_WRITE( 写) 和_IOC_READ|_IOC_WRITE( 双向) 。 数据传送的方向是从应用程序的角度来看的;
数据尺寸size,13~14bit;
用下述宏来生成命令:
#include <linux/ioctl.h> // 实际是 include/uapi/linux/ioctl.h,看来uapi也是驱动搜索的目录之一#define _IO(type,nr) _IOC(_IOC_NONE,(type),(nr),0) #define _IOR(type,nr,size) _IOC(_IOC_READ,(type),(nr),(_IOC_TYPECHECK(size))) #define _IOW(type,nr,size) _IOC(_IOC_WRITE,(type),(nr),(_IOC_TYPECHECK(size))) #define _IOWR(type,nr,size) _IOC(_IOC_READ|_IOC_WRITE,(type),(nr),(_IOC_TYPECHECK(size)))// 例如#define GLOBALMEM_CMD_CLR _IO('g',0)
这本书使用globalmem模拟一种物理设备,所有的驱动都在这个设备上进行实例操作。
【注意】
1.模块编译的Makefile文件,首字母必须大写,否则make modules找不到Makefile文件,貌似是make modules时写死了,只认"Makefile"字样的文件;
$ echo "hello world" > /dev/globalmem $ cat /dev/globalmem hello world
另一个终端监视printk的显示(用dmesg脚本)
[ 3158.660191] enter globalmem_init()[ 3231.664661] open filp->private_data = 0xc0270480[ 3231.664669] open filp->f_pos = 0[ 3231.717074] write 4 bytes from 0 pos[ 3598.704506] open filp->private_data = 0xc0270480[ 3598.704519] open filp->f_pos = 0[ 3598.704547] read 1024 bytes from 0 pos[ 3598.707040] read 0 bytes from 1024 pos
原则:cdev和file_operations本质上与驱动程序对应,理论上只需要1个就可以。同理,class定义设备的一种类型, 也不用定义多个。 具体设备(多个globalmem的buf)是多个,驱动程序要想办法把驱动文件file、inode与设备对应上就可以了。
上述原则与书中测试用例不太一致,书中定义了多个cdev。
$ echo "mem0" > /dev/globalmem0$ echo "mem1" > /dev/globalmem1$ echo "mem2" > /dev/globalmem2$ cat /dev/globalmem0mem0$ cat /dev/globalmem1mem1$ cat /dev/globalmem2mem2
【问题1】 printk在ubuntu的shell终端里无法显示
printk打印的是控制台,也就是/dev/console。而图形界面中的终端,其实是把stdin,stdout,stderr三个文件重定向了一下。所以printk是无法再图形界面中的终端中显示的,当然可以再/var/log/syslog或者用dmesg查看。
在嵌入式设备中,其中初始化的时候把stdin,stdout,stderr均定向到了/dev/console中(main.c中的init_post函数里)。一般的情况下控制台就是串口。
【问题2】 ubuntu里怎么显示printk
ubuntu这类的发行版linux,有专门的守护进程负责记录log信息,有些log信息里就保存着printk的打印信息(内核信息),可以用dmesg命令或者查看/proc/kmsg文件
在一个单独的窗口里,可以输入如下命令,单独监测内核的日志文件,从而监控printk信息
// 方法1:sudo cat /proc/kmsg // 阻塞显示内核信息,只显示增量信息,感觉没有dmesg好用,会漏一些信息// 方法2:可运行如下脚本,定期用dmesg查看内核信息while truedo sudo dmesg -c // dmesg不是增量显示,会打印所有的存量信息,所以用-c,显示后删除 sleep 1 done
驱动中注意使用这些标准的错误返回码
// base error#define EPERM 1 /* Operation not permitted */ #define ENOENT 2 /* No such file or directory */ #define ESRCH 3 /* No such process */ #define EINTR 4 /* Interrupted system call */ #define EIO 5 /* I/O error */ #define ENXIO 6 /* No such device or address */ #define E2BIG 7 /* Argument list too long */ #define ENOEXEC 8 /* Exec format error */ #define EBADF 9 /* Bad file number */ #define ECHILD 10 /* No child processes */ #define EAGAIN 11 /* Try again */ #define ENOMEM 12 /* Out of memory */ #define EACCES 13 /* Permission denied */ #define EFAULT 14 /* Bad address */ #define ENOTBLK 15 /* Block device required */ #define EBUSY 16 /* Device or resource busy */ #define EEXIST 17 /* File exists */ #define EXDEV 18 /* Cross-device link */ #define ENODEV 19 /* No such device */ #define ENOTDIR 20 /* Not a directory */ #define EISDIR 21 /* Is a directory */ #define EINVAL 22 /* Invalid argument */ #define ENFILE 23 /* File table overflow */ #define EMFILE 24 /* Too many open files */ #define ENOTTY 25 /* Not a typewriter */ #define ETXTBSY 26 /* Text file busy */ #define EFBIG 27 /* File too large */ #define ENOSPC 28 /* No space left on device */ #define ESPIPE 29 /* Illegal seek */ #define EROFS 30 /* Read-only file system */ #define EMLINK 31 /* Too many links */ #define EPIPE 32 /* Broken pipe */ #define EDOM 33 /* Math argument out of domain of func */ #define ERANGE 34 /* Math result not representable */ // not base error #define EDEADLK 35 /* Resource deadlock would occur */ #define ENAMETOOLONG 36 /* File name too long */ #define ENOLCK 37 /* No record locks available */ #define ENOSYS 38 /* Function not implemented */ #define ENOTEMPTY 39 /* Directory not empty */ #define ELOOP 40 /* Too many symbolic links encountered */ #define EWOULDBLOCK EAGAIN /* Operation would block */ #define ENOMSG 42 /* No message of desired type */ #define EIDRM 43 /* Identifier removed */ #define ECHRNG 44 /* Channel number out of range */ #define EL2NSYNC 45 /* Level 2 not synchronized */ #define EL3HLT 46 /* Level 3 halted */ #define EL3RST 47 /* Level 3 reset */ #define ELNRNG 48 /* Link number out of range */ #define EUNATCH 49 /* Protocol driver not attached */ #define ENOCSI 50 /* No CSI structure available */ #define EL2HLT 51 /* Level 2 halted */ #define EBADE 52 /* Invalid exchange */ #define EBADR 53 /* Invalid request descriptor */ #define EXFULL 54 /* Exchange full */ #define ENOANO 55 /* No anode */ #define EBADRQC 56 /* Invalid request code */ #define EBADSLT 57 /* Invalid slot */ #define EDEADLOCK EDEADLK #define EBFONT 59 /* Bad font file format */ #define ENOSTR 60 /* Device not a stream */ #define ENODATA 61 /* No data available */ #define ETIME 62 /* Timer expired */ #define ENOSR 63 /* Out of streams resources */ #define ENONET 64 /* Machine is not on the network */ #define ENOPKG 65 /* Package not installed */ #define EREMOTE 66 /* Object is remote */ #define ENOLINK 67 /* Link has been severed */ #define EADV 68 /* Advertise error */ #define ESRMNT 69 /* Srmount error */ #define ECOMM 70 /* Communication error on send */ #define EPROTO 71 /* Protocol error */ #define EMULTIHOP 72 /* Multihop attempted */ #define EDOTDOT 73 /* RFS specific error */ #define EBADMSG 74 /* Not a data message */ #define EOVERFLOW 75 /* Value too large for defined data type */ #define ENOTUNIQ 76 /* Name not unique on network */ #define EBADFD 77 /* File descriptor in bad state */ #define EREMCHG 78 /* Remote address changed */ #define ELIBACC 79 /* Can not access a needed shared library */ #define ELIBBAD 80 /* Accessing a corrupted shared library */ #define ELIBSCN 81 /* .lib section in a.out corrupted */ #define ELIBMAX 82 /* Attempting to link in too many shared libraries */ #define ELIBEXEC 83 /* Cannot exec a shared library directly */ #define EILSEQ 84 /* Illegal byte sequence */ #define ERESTART 85 /* Interrupted system call should be restarted */ #define ESTRPIPE 86 /* Streams pipe error */ #define EUSERS 87 /* Too many users */ #define ENOTSOCK 88 /* Socket operation on non-socket */ #define EDESTADDRREQ 89 /* Destination address required */ #define EMSGSIZE 90 /* Message too long */ #define EPROTOTYPE 91 /* Protocol wrong type for socket */ #define ENOPROTOOPT 92 /* Protocol not available */ #define EPROTONOSUPPORT 93 /* Protocol not supported */ #define ESOCKTNOSUPPORT 94 /* Socket type not supported */ #define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ #define EPFNOSUPPORT 96 /* Protocol family not supported */ #define EAFNOSUPPORT 97 /* Address family not supported by protocol */ #define EADDRINUSE 98 /* Address already in use */ #define EADDRNOTAVAIL 99 /* Cannot assign requested address */ #define ENETDOWN 100 /* Network is down */ #define ENETUNREACH 101 /* Network is unreachable */ #define ENETRESET 102 /* Network dropped connection because of reset */ #define ECONNABORTED 103 /* Software caused connection abort */ #define ECONNRESET 104 /* Connection reset by peer */ #define ENOBUFS 105 /* No buffer space available */ #define EISCONN 106 /* Transport endpoint is already connected */ #define ENOTCONN 107 /* Transport endpoint is not connected */ #define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */ #define ETOOMANYREFS 109 /* Too many references: cannot splice */ #define ETIMEDOUT 110 /* Connection timed out */ #define ECONNREFUSED 111 /* Connection refused */ #define EHOSTDOWN 112 /* Host is down */ #define EHOSTUNREACH 113 /* No route to host */ #define EALREADY 114 /* Operation already in progress */ #define EINPROGRESS 115 /* Operation now in progress */ #define ESTALE 116 /* Stale file handle */ #define EUCLEAN 117 /* Structure needs cleaning */ #define ENOTNAM 118 /* Not a XENIX named type file */ #define ENAVAIL 119 /* No XENIX semaphores available */ #define EISNAM 120 /* Is a named type file */ #define EREMOTEIO 121 /* Remote I/O error */ #define EDQUOT 122 /* Quota exceeded */ #define ENOMEDIUM 123 /* No medium found */ #define EMEDIUMTYPE 124 /* Wrong medium type */ #define ECANCELED 125 /* Operation Canceled */ #define ENOKEY 126 /* Required key not available */ #define EKEYEXPIRED 127 /* Key has expired */ #define EKEYREVOKED 128 /* Key has been revoked */ #define EKEYREJECTED 129 /* Key was rejected by service */ /* for robust mutexes */ #define EOWNERDEAD 130 /* Owner died */ #define ENOTRECOVERABLE 131 /* State not recoverable */ #define ERFKILL 132 /* Operation not possible due to RF-kill */ #define EHWPOISON 133 /* Memory page has hardware error */
总结一下应注意的事项:
1.write和read的pos指针的含义,llseek的f_pos的处理 2.copy_to/from_user的参数顺序 3.printk的查看方法 4.没有注册license引发的问题,MODULE_LICENSE("GPL") 5.错误类型及返回 6.使用私有数据的方法 7.一套驱动对应多个设备的方法
转载于:https://www.cnblogs.com/liuwanpeng/p/6700277.html
相关资源:DirectX修复工具V4.0增强版