#include <linux/init.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kdev_t.h>
#include <linux/fs.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h> /* printk(), min() */
#include <linux/slab.h> /* kmalloc() */
#include <linux/proc_fs.h>
#include <linux/errno.h> /* error codes */
#include <linux/fcntl.h>
#include <linux/poll.h>
#include <linux/cdev.h>
#include <asm/uaccess.h>
//向内核申请主设备与次设备编号
int ipanda_major=0;
int ipanda_minor=0;
struct cdev ipanda_cdev;
MODULE_LICENSE("Dual BSD/GPL");
int ipanda_open(struct inode *inode, struct file *filp)
{
printk("Hello, ipanda is opened\n");
return 0; /* success */
}
ssize_t ipanda_read(struct file *filp, char __user *buff, size_t count, loff_t *offp)
{
printk("Hello, ipanda is reading\n");
return 0;
}
ssize_t ipanda_write(struct file *filp, const char __user *buff, size_t count, loff_t *offp)
{
printk("Hello, ipanda is writting\n");
return 0;
}
int ipanda_release(struct inode *inode, struct file *filep)
{
printk("Hello, ipanda is release\n");
return 0;
}
struct file_operations ipanda_fops = {
.owner = THIS_MODULE,
.open = ipanda_open,
.read = ipanda_read,
.write = ipanda_write,
.release = ipanda_release
};
static int ipanda_init(void)
{
dev_t dev;
int result,devno,err;
//动态申请设备编号
result = alloc_chrdev_region(&dev,ipanda_minor,1,"ipanda");
ipanda_major=MAJOR(dev);
if(result<0)
{
printk("ipanda:can't get major %d\n",ipanda_major);
return result;
}else{
printk("ipanda:major %d,minor %d\n",ipanda_major,ipanda_minor);
}
cdev_init(&ipanda_cdev, &ipanda_fops);
ipanda_cdev.owner=THIS_MODULE;
ipanda_cdev.ops = &ipanda_fops;
devno=MKDEV(ipanda_major, ipanda_minor);
err = cdev_add (&ipanda_cdev, devno, 1);
/* Fail gracefully if need be */
if (err)
printk(KERN_NOTICE "Error %d adding", err);
/* result=register_chrdev_region(devno,1,"ipanda");
if (result < 0) {
printk(KERN_NOTICE "Unable to get ipanda region, error %d\n", result);
return 0;
} */
/* cull_devices = kmalloc(ipanda_nr_devs * sizeof(struct ipanda_dev), GFP_KERNEL);
if (!ipanda_devices) {
result = -ENOMEM;
goto fail;
}
memset(ipanda_devices, 0, ipanda_nr_devs * sizeof(struct ipanda_dev));
for (i = 0; i < ipanda_nr_devs; i++) {
ipanda_devices[i].quantum = ipanda_quantum;
ipanda_devices[i].qset = ipanda_qset;
init_MUTEX(&ipanda_devices[i].sem);
ipanda_setup_cdev(&ipanda_devices[i], i);
} */
return 0;
}
static void ipanda_exit(void)
{
int devno;
devno = MKDEV(ipanda_major, ipanda_minor);
unregister_chrdev_region(devno, 1);
printk("Goodbye, ipanda world\n");
}
module_init(ipanda_init);
module_exit(ipanda_exit);
|