11 #define CNAME "myled"
12 dev_t devno;
13
14 unsigned count=3;
15
16 struct cdev *devp;
17
18 #if 0
19 unsigned major =0;
20 #else
21 unsigned major =500;
22 #endif
23
24 unsigned minor =0;
25
26
27 struct class *cls;
28 struct device *dev;
29
30
31 int (myled_open) (struct inode *inode, struct file *file)
32 {
33
34 return 0;
35 }
36
37 ssize_t (myled_read) (struct file *file, char __user *ubuf, size_t size,loff_t *loff)
38 {
39
40
41 return size;
42
43 }
44
45 ssize_t (myled_write) (struct file *file, const char __user *ubuf, size_t size,loff_t *l
46 {
47
48 return size; //5.返回拷贝数据大小
49 }
50
51 int (myled_release) (struct inode *inode, struct file *file)
52 {
53
54
55 }
56
57 const struct file_operations fops=
58 {
59
60 .open=myled_open,
61 .read=myled_read,
62 .write=myled_write,
63 .release=myled_release,
64 };
65
66
67 static int __init demo_init(void)
68 {
69 int ret,i;
70
71 devp=cdev_alloc();
72 if(NULL==devp)
73 {
74 printk("对象分配内存失败\n");
75 ret=-ENOMEN;
76 goto ERR1;
77 }
78 printk("对象分配内存成功\n");
79
80
81 cdev_init(devp,&fops);
82
83 if(major==0)
84 {
85 ret=alloc_chrdev_region(&devno,minor,count,"led");
86 if(ret)
87 {
88 printk("动态申请设备号失败\n");
89 }
90
91 major=MAJOR(devno);
92 minor=MINOR(devno);
93
94 }
95 else if(major>0)
96 {
97 ret=register_chrdev_region(MK(major,minor),3,"led");
98 if(ret)
99 {
100 printk("静态申请设备号失败\n");
101 }
102 }
103
104 ret=cdev_add(devp,MKDEV(major,minor),3);
105 if(ret)
106 {
107 printk("驱动对象注册进内核失败\n");
108 }
109 printk("驱动对象注册进内核成功\n");
110
111
112 cls=class_create(THIS_MODULE,"myled");
113 if(IS_ERR(cls))
114 {
115 printk("向上提交目录失败\n");
116 }
117 printk("向上提交目录成功\n");
118
119
120 for(i=0;i<3;i++)
121 {
122 dev=device_create(cls,NULL,MKDEV(major,minor),"mycdev%d",i);
123 if(IS_ERR(dev))
124 {
125 printk("向上提交节点失败\n");
126 }
127
128 printk("向上提交节点成功\n");
129 }
130
131 ERR5:
132 for(--i;i>=0;i--)
133 {
134 device_destroy(cls,MK(major,i));
135 }
136
137 class_destroy(cls);
138
139 ERR4:
140 cdev_del(devp);
141
142 ERR3:
143 unregister_chrdev_region(MKDEV(major,minor),3);
144
145 ERR2:
146 kfree(devp);
147
148 ERR1:
149 return ret;
150
151
152
153 return 0;
154 }
155
156 static void __exit demo_exit(void)
157 {
158
159 int i;
160
161 for(i=0;i<3;i++)
162 {
163 device_destroy(cls,MKDEV(major,i));
164 }
165
166 class_destroy(cls);
167
168 cdev_del(devp);
169
170 unregister_chrdev_region(MKDEV(major,minor),3);
171
172 kfree(cdev);
173
174 }
175
176
177
178
179
180 module_init(demo_init);
181 module_exit(demo_exit);
182
183 MODULE_LICENSE("GPL");
184
185