Linux 设备驱动程序(3)- 字符驱动(3)

在了解了字符设备驱动的原理后,现在就以scull 驱动来使用掌握字符设备驱动的开发

1. SCULL 设计

scull( Simple Character Utility for Loading Localities). scull 是一个字符驱动, 操作一块内存区域好像它是一个设备. 因为scull 的这个怪特性, 我们可互换地使用设备这个词和"scull 使用的内存区".

scull 的优势在于它不依赖硬件. scull 只是操作一些从内核分配的内存. 任何人都可以编译和运行

scull, 并且 scull 在 Linux 运行的体系结构中可移植. 另一方面, 这个设备除了演示内核和字符驱

动的接口和允许用户运行一些测试之外, 不做任何有用的事情

编写驱动的第一步是定义驱动将要提供给用户程序的能力(机制).因为我们的"设备"是计算机内存的一部分, 我们可自由做我们想做的事情. 它可以是一个顺序的或者随机存取的设备, 一个或多个设备, 等等

为使 scull 作为一个模板来编写真实设备的真实驱动, 我们将展示给你如何在计算机内存上实现几个设备抽象, 每个有不同的个性.

scull 源码实现下面的设备. 模块实现的每种设备都被引用做一种类型

scull0 到 scull3

4 个设备, 每个由一个全局永久的内存区组成. 全局意味着如果设备被多次打开,设备中含有的数据由所有打开它的文件描述符共享. 永久意味着如果设备关闭又重新打开, 数据不会丢失. 这个设备用起来有意思, 因为它可以用惯常的命令来存取和测试, 例如 cp, cat, 以及 I/O 重定向.

scullpipe0 到 scullpipe3

4 个 FIFO (先入先出) 设备, 行为像管道. 一个进程读的内容来自另一个进程所写的. 如果多个进程读同一个设备, 它们竞争数据. scullpipe 的内部将展示阻塞读写和非阻塞读写如何实现, 而不必采取中断. 尽管真实的驱动使用硬件中断来同步它们的设备, 阻塞和非阻塞操作的主题是重要的并且与中断处理是分开的.

scullsingle

scullpriv

sculluid

scullwuid

这些设备与 scull0 相似, 但是在什么时候允许打开上有一些限制. 第一个( snullsingle) 只允许一次一个进程使用驱动, 而 scullpriv 对每个虚拟终端(或者 X 终端会话)是私有的, 因为每个控制台/终端上的进程有不同的内存区.

sculluid 和 scullwuid 可以多次打开, 但是一次只能是一个用户; 前者返回一个"设备忙"错误, 如果另一个用户锁着设备, 而后者实现阻塞打开. 这些 scull 的变体可能看来混淆了策略和机制, 但是它们值得看看, 因为一些实际设备需要这类管理.

每个 scull 设备演示了驱动的不同特色, 并且呈现了不同的难度. 本章涉及 scull0 到scull3 的内部; 更高级的设备在第 6 章涉及. scullpipe 在"一个阻塞 I/O 例子"一节中述, 其他的在"设备文件上的存取控制"中描述.

2.SCULL 字符设备源码

scullc.c

复制代码
/* -*- C -*-
 * main.c -- the bare scullc char module
 *
 * Copyright (C) 2001 Alessandro Rubini and Jonathan Corbet
 * Copyright (C) 2001 O'Reilly & Associates
 *
 * The source code in this file can be freely used, adapted,
 * and redistributed in source or binary form, so long as an
 * acknowledgment appears in derived source files.  The citation
 * should list that the code comes from the book "Linux Device
 * Drivers" by Alessandro Rubini and Jonathan Corbet, published
 * by O'Reilly & Associates.   No warranty is attached;
 * we cannot take responsibility for errors or fitness for use.
 *
 * $Id: _main.c.in,v 1.21 2004/10/14 20:11:39 corbet Exp $
 */

#include <linux/config.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/kernel.h>	/* printk() */
#include <linux/slab.h>		/* kmalloc() */
#include <linux/fs.h>		/* everything... */
#include <linux/errno.h>	/* error codes */
#include <linux/types.h>	/* size_t */
#include <linux/proc_fs.h>
#include <linux/fcntl.h>	/* O_ACCMODE */
#include <linux/aio.h>
#include <asm/uaccess.h>
#include "scullc.h"		/* local definitions */


int scullc_major =   SCULLC_MAJOR;
int scullc_devs =    SCULLC_DEVS;	/* number of bare scullc devices */
int scullc_qset =    SCULLC_QSET;
int scullc_quantum = SCULLC_QUANTUM;

module_param(scullc_major, int, 0);
module_param(scullc_devs, int, 0);
module_param(scullc_qset, int, 0);
module_param(scullc_quantum, int, 0);
MODULE_AUTHOR("Alessandro Rubini");
MODULE_LICENSE("Dual BSD/GPL");

struct scullc_dev *scullc_devices; /* allocated in scullc_init */

int scullc_trim(struct scullc_dev *dev);
void scullc_cleanup(void);

/* declare one cache pointer: use it for all devices */
kmem_cache_t *scullc_cache;





#ifdef SCULLC_USE_PROC /* don't waste space if unused */
/*
 * The proc filesystem: function to read and entry
 */

void scullc_proc_offset(char *buf, char **start, off_t *offset, int *len)
{
	if (*offset == 0)
		return;
	if (*offset >= *len) {
		/* Not there yet */
		*offset -= *len;
		*len = 0;
	} else {
		/* We're into the interesting stuff now */
		*start = buf + *offset;
		*offset = 0;
	}
}

/* FIXME: Do we need this here??  It be ugly  */
int scullc_read_procmem(char *buf, char **start, off_t offset,
                   int count, int *eof, void *data)
{
	int i, j, quantum, qset, len = 0;
	int limit = count - 80; /* Don't print more than this */
	struct scullc_dev *d;

	*start = buf;
	for(i = 0; i < scullc_devs; i++) {
		d = &scullc_devices[i];
		if (down_interruptible (&d->sem))
			return -ERESTARTSYS;
		qset = d->qset;  /* retrieve the features of each device */
		quantum=d->quantum;
		len += sprintf(buf+len,"\nDevice %i: qset %i, quantum %i, sz %li\n",
				i, qset, quantum, (long)(d->size));
		for (; d; d = d->next) { /* scan the list */
			len += sprintf(buf+len,"  item at %p, qset at %p\n",d,d->data);
			scullc_proc_offset (buf, start, &offset, &len);
			if (len > limit)
				goto out;
			if (d->data && !d->next) /* dump only the last item - save space */
				for (j = 0; j < qset; j++) {
					if (d->data[j])
						len += sprintf(buf+len,"    % 4i:%8p\n",j,d->data[j]);
					scullc_proc_offset (buf, start, &offset, &len);
					if (len > limit)
						goto out;
				}
		}
	  out:
		up (&scullc_devices[i].sem);
		if (len > limit)
			break;
	}
	*eof = 1;
	return len;
}

#endif /* SCULLC_USE_PROC */

/*
 * Open and close
 */

int scullc_open (struct inode *inode, struct file *filp)
{
	struct scullc_dev *dev; /* device information */

	/*  Find the device */
	dev = container_of(inode->i_cdev, struct scullc_dev, cdev);

    	/* now trim to 0 the length of the device if open was write-only */
	if ( (filp->f_flags & O_ACCMODE) == O_WRONLY) {
		if (down_interruptible (&dev->sem))
			return -ERESTARTSYS;
		scullc_trim(dev); /* ignore errors */
		up (&dev->sem);
	}

	/* and use filp->private_data to point to the device data */
	filp->private_data = dev;

	return 0;          /* success */
}

int scullc_release (struct inode *inode, struct file *filp)
{
	return 0;
}

/*
 * Follow the list 
 */
struct scullc_dev *scullc_follow(struct scullc_dev *dev, int n)
{
	while (n--) {
		if (!dev->next) {
			dev->next = kmalloc(sizeof(struct scullc_dev), GFP_KERNEL);
			memset(dev->next, 0, sizeof(struct scullc_dev));
		}
		dev = dev->next;
		continue;
	}
	return dev;
}

/*
 * Data management: read and write
 */

ssize_t scullc_read (struct file *filp, char __user *buf, size_t count,
                loff_t *f_pos)
{
	struct scullc_dev *dev = filp->private_data; /* the first listitem */
	struct scullc_dev *dptr;
	int quantum = dev->quantum;
	int qset = dev->qset;
	int itemsize = quantum * qset; /* how many bytes in the listitem */
	int item, s_pos, q_pos, rest;
	ssize_t retval = 0;

	if (down_interruptible (&dev->sem))
		return -ERESTARTSYS;
	if (*f_pos > dev->size) 
		goto nothing;
	if (*f_pos + count > dev->size)
		count = dev->size - *f_pos;
	/* find listitem, qset index, and offset in the quantum */
	item = ((long) *f_pos) / itemsize;
	rest = ((long) *f_pos) % itemsize;
	s_pos = rest / quantum; q_pos = rest % quantum;

    	/* follow the list up to the right position (defined elsewhere) */
	dptr = scullc_follow(dev, item);

	if (!dptr->data)
		goto nothing; /* don't fill holes */
	if (!dptr->data[s_pos])
		goto nothing;
	if (count > quantum - q_pos)
		count = quantum - q_pos; /* read only up to the end of this quantum */

	if (copy_to_user (buf, dptr->data[s_pos]+q_pos, count)) {
		retval = -EFAULT;
		goto nothing;
	}
	up (&dev->sem);

	*f_pos += count;
	return count;

  nothing:
	up (&dev->sem);
	return retval;
}



ssize_t scullc_write (struct file *filp, const char __user *buf, size_t count,
                loff_t *f_pos)
{
	struct scullc_dev *dev = filp->private_data;
	struct scullc_dev *dptr;
	int quantum = dev->quantum;
	int qset = dev->qset;
	int itemsize = quantum * qset;
	int item, s_pos, q_pos, rest;
	ssize_t retval = -ENOMEM; /* our most likely error */

	if (down_interruptible (&dev->sem))
		return -ERESTARTSYS;

	/* find listitem, qset index and offset in the quantum */
	item = ((long) *f_pos) / itemsize;
	rest = ((long) *f_pos) % itemsize;
	s_pos = rest / quantum; q_pos = rest % quantum;

	/* follow the list up to the right position */
	dptr = scullc_follow(dev, item);
	if (!dptr->data) {
		dptr->data = kmalloc(qset * sizeof(void *), GFP_KERNEL);
		if (!dptr->data)
			goto nomem;
		memset(dptr->data, 0, qset * sizeof(char *));
	}
	/* Allocate a quantum using the memory cache */
	if (!dptr->data[s_pos]) {
		dptr->data[s_pos] = kmem_cache_alloc(scullc_cache, GFP_KERNEL);
		if (!dptr->data[s_pos])
			goto nomem;
		memset(dptr->data[s_pos], 0, scullc_quantum);
	}
	if (count > quantum - q_pos)
		count = quantum - q_pos; /* write only up to the end of this quantum */
	if (copy_from_user (dptr->data[s_pos]+q_pos, buf, count)) {
		retval = -EFAULT;
		goto nomem;
	}
	*f_pos += count;
 
    	/* update the size */
	if (dev->size < *f_pos)
		dev->size = *f_pos;
	up (&dev->sem);
	return count;

  nomem:
	up (&dev->sem);
	return retval;
}

/*
 * The ioctl() implementation
 */

int scullc_ioctl (struct inode *inode, struct file *filp,
                 unsigned int cmd, unsigned long arg)
{

	int err = 0, ret = 0, tmp;

	/* don't even decode wrong cmds: better returning  ENOTTY than EFAULT */
	if (_IOC_TYPE(cmd) != SCULLC_IOC_MAGIC) return -ENOTTY;
	if (_IOC_NR(cmd) > SCULLC_IOC_MAXNR) return -ENOTTY;

	/*
	 * the type is a bitmask, and VERIFY_WRITE catches R/W
	 * transfers. Note that the type is user-oriented, while
	 * verify_area is kernel-oriented, so the concept of "read" and
	 * "write" is reversed
	 */
	if (_IOC_DIR(cmd) & _IOC_READ)
		err = !access_ok(VERIFY_WRITE, (void __user *)arg, _IOC_SIZE(cmd));
	else if (_IOC_DIR(cmd) & _IOC_WRITE)
		err =  !access_ok(VERIFY_READ, (void __user *)arg, _IOC_SIZE(cmd));
	if (err)
		return -EFAULT;

	switch(cmd) {

	case SCULLC_IOCRESET:
		scullc_qset = SCULLC_QSET;
		scullc_quantum = SCULLC_QUANTUM;
		break;

	case SCULLC_IOCSQUANTUM: /* Set: arg points to the value */
		ret = __get_user(scullc_quantum, (int __user *) arg);
		break;

	case SCULLC_IOCTQUANTUM: /* Tell: arg is the value */
		scullc_quantum = arg;
		break;

	case SCULLC_IOCGQUANTUM: /* Get: arg is pointer to result */
		ret = __put_user (scullc_quantum, (int __user *) arg);
		break;

	case SCULLC_IOCQQUANTUM: /* Query: return it (it's positive) */
		return scullc_quantum;

	case SCULLC_IOCXQUANTUM: /* eXchange: use arg as pointer */
		tmp = scullc_quantum;
		ret = __get_user(scullc_quantum, (int __user *) arg);
		if (ret == 0)
			ret = __put_user(tmp, (int __user *) arg);
		break;

	case SCULLC_IOCHQUANTUM: /* sHift: like Tell + Query */
		tmp = scullc_quantum;
		scullc_quantum = arg;
		return tmp;

	case SCULLC_IOCSQSET:
		ret = __get_user(scullc_qset, (int __user *) arg);
		break;

	case SCULLC_IOCTQSET:
		scullc_qset = arg;
		break;

	case SCULLC_IOCGQSET:
		ret = __put_user(scullc_qset, (int __user *)arg);
		break;

	case SCULLC_IOCQQSET:
		return scullc_qset;

	case SCULLC_IOCXQSET:
		tmp = scullc_qset;
		ret = __get_user(scullc_qset, (int __user *)arg);
		if (ret == 0)
			ret = __put_user(tmp, (int __user *)arg);
		break;

	case SCULLC_IOCHQSET:
		tmp = scullc_qset;
		scullc_qset = arg;
		return tmp;

	default:  /* redundant, as cmd was checked against MAXNR */
		return -ENOTTY;
	}

	return ret;
}

/*
 * The "extended" operations
 */

loff_t scullc_llseek (struct file *filp, loff_t off, int whence)
{
	struct scullc_dev *dev = filp->private_data;
	long newpos;

	switch(whence) {
	case 0: /* SEEK_SET */
		newpos = off;
		break;

	case 1: /* SEEK_CUR */
		newpos = filp->f_pos + off;
		break;

	case 2: /* SEEK_END */
		newpos = dev->size + off;
		break;

	default: /* can't happen */
		return -EINVAL;
	}
	if (newpos<0) return -EINVAL;
	filp->f_pos = newpos;
	return newpos;
}


/*
 * A simple asynchronous I/O implementation.
 */

struct async_work {
	struct kiocb *iocb;
	int result;
	struct work_struct work;
};

/*
 * "Complete" an asynchronous operation.
 */
static void scullc_do_deferred_op(void *p)
{
	struct async_work *stuff = (struct async_work *) p;
	aio_complete(stuff->iocb, stuff->result, 0);
	kfree(stuff);
}


static int scullc_defer_op(int write, struct kiocb *iocb, char __user *buf,
		size_t count, loff_t pos)
{
	struct async_work *stuff;
	int result;

	/* Copy now while we can access the buffer */
	if (write)
		result = scullc_write(iocb->ki_filp, buf, count, &pos);
	else
		result = scullc_read(iocb->ki_filp, buf, count, &pos);

	/* If this is a synchronous IOCB, we return our status now. */
	if (is_sync_kiocb(iocb))
		return result;

	/* Otherwise defer the completion for a few milliseconds. */
	stuff = kmalloc (sizeof (*stuff), GFP_KERNEL);
	if (stuff == NULL)
		return result; /* No memory, just complete now */
	stuff->iocb = iocb;
	stuff->result = result;
	INIT_WORK(&stuff->work, scullc_do_deferred_op, stuff);
	schedule_delayed_work(&stuff->work, HZ/100);
	return -EIOCBQUEUED;
}


static ssize_t scullc_aio_read(struct kiocb *iocb, char __user *buf, size_t count,
		loff_t pos)
{
	return scullc_defer_op(0, iocb, buf, count, pos);
}

static ssize_t scullc_aio_write(struct kiocb *iocb, const char __user *buf,
		size_t count, loff_t pos)
{
	return scullc_defer_op(1, iocb, (char __user *) buf, count, pos);
}


 

/*
 * The fops
 */

struct file_operations scullc_fops = {
	.owner =     THIS_MODULE,
	.llseek =    scullc_llseek,
	.read =	     scullc_read,
	.write =     scullc_write,
	.ioctl =     scullc_ioctl,
	.open =	     scullc_open,
	.release =   scullc_release,
	.aio_read =  scullc_aio_read,
	.aio_write = scullc_aio_write,
};

int scullc_trim(struct scullc_dev *dev)
{
	struct scullc_dev *next, *dptr;
	int qset = dev->qset;   /* "dev" is not-null */
	int i;

	if (dev->vmas) /* don't trim: there are active mappings */
		return -EBUSY;

	for (dptr = dev; dptr; dptr = next) { /* all the list items */
		if (dptr->data) {
			for (i = 0; i < qset; i++)
				if (dptr->data[i])
					kmem_cache_free(scullc_cache, dptr->data[i]);

			kfree(dptr->data);
			dptr->data=NULL;
		}
		next=dptr->next;
		if (dptr != dev) kfree(dptr); /* all of them but the first */
	}
	dev->size = 0;
	dev->qset = scullc_qset;
	dev->quantum = scullc_quantum;
	dev->next = NULL;
	return 0;
}


static void scullc_setup_cdev(struct scullc_dev *dev, int index)
{
	int err, devno = MKDEV(scullc_major, index);
    
	cdev_init(&dev->cdev, &scullc_fops);
	dev->cdev.owner = THIS_MODULE;
	dev->cdev.ops = &scullc_fops;
	err = cdev_add (&dev->cdev, devno, 1);
	/* Fail gracefully if need be */
	if (err)
		printk(KERN_NOTICE "Error %d adding scull%d", err, index);
}



/*
 * Finally, the module stuff
 */

int scullc_init(void)
{
	int result, i;
	dev_t dev = MKDEV(scullc_major, 0);
	
	/*
	 * Register your major, and accept a dynamic number.
	 */
	if (scullc_major)
		result = register_chrdev_region(dev, scullc_devs, "scullc");
	else {
		result = alloc_chrdev_region(&dev, 0, scullc_devs, "scullc");
		scullc_major = MAJOR(dev);
	}
	if (result < 0)
		return result;

	
	/* 
	 * allocate the devices -- we can't have them static, as the number
	 * can be specified at load time
	 */
	scullc_devices = kmalloc(scullc_devs*sizeof (struct scullc_dev), GFP_KERNEL);
	if (!scullc_devices) {
		result = -ENOMEM;
		goto fail_malloc;
	}
	memset(scullc_devices, 0, scullc_devs*sizeof (struct scullc_dev));
	for (i = 0; i < scullc_devs; i++) {
		scullc_devices[i].quantum = scullc_quantum;
		scullc_devices[i].qset = scullc_qset;
		sema_init (&scullc_devices[i].sem, 1);
		scullc_setup_cdev(scullc_devices + i, i);
	}

	scullc_cache = kmem_cache_create("scullc", scullc_quantum,
			0, SLAB_HWCACHE_ALIGN, NULL, NULL); /* no ctor/dtor */
	if (!scullc_cache) {
		scullc_cleanup();
		return -ENOMEM;
	}

#ifdef SCULLC_USE_PROC /* only when available */
	create_proc_read_entry("scullcmem", 0, NULL, scullc_read_procmem, NULL);
#endif
	return 0; /* succeed */

  fail_malloc:
	unregister_chrdev_region(dev, scullc_devs);
	return result;
}



void scullc_cleanup(void)
{
	int i;

#ifdef SCULLC_USE_PROC
	remove_proc_entry("scullcmem", NULL);
#endif

	for (i = 0; i < scullc_devs; i++) {
		cdev_del(&scullc_devices[i].cdev);
		scullc_trim(scullc_devices + i);
	}
	kfree(scullc_devices);

	if (scullc_cache)
		kmem_cache_destroy(scullc_cache);
	unregister_chrdev_region(MKDEV (scullc_major, 0), scullc_devs);
}


module_init(scullc_init);
module_exit(scullc_cleanup);

scullc.h

复制代码
/* -*- C -*-
 * scullc.h -- definitions for the scullc char module
 *
 * Copyright (C) 2001 Alessandro Rubini and Jonathan Corbet
 * Copyright (C) 2001 O'Reilly & Associates
 *
 * The source code in this file can be freely used, adapted,
 * and redistributed in source or binary form, so long as an
 * acknowledgment appears in derived source files.  The citation
 * should list that the code comes from the book "Linux Device
 * Drivers" by Alessandro Rubini and Jonathan Corbet, published
 * by O'Reilly & Associates.   No warranty is attached;
 * we cannot take responsibility for errors or fitness for use.
 */

#include <linux/ioctl.h>
#include <linux/cdev.h>

/*
 * Macros to help debugging
 */

#undef PDEBUG             /* undef it, just in case */
#ifdef SCULLC_DEBUG
#  ifdef __KERNEL__
     /* This one if debugging is on, and kernel space */
#    define PDEBUG(fmt, args...) printk( KERN_DEBUG "scullc: " fmt, ## args)
#  else
     /* This one for user space */
#    define PDEBUG(fmt, args...) fprintf(stderr, fmt, ## args)
#  endif
#else
#  define PDEBUG(fmt, args...) /* not debugging: nothing */
#endif

#undef PDEBUGG
#define PDEBUGG(fmt, args...) /* nothing: it's a placeholder */

#define SCULLC_MAJOR 0   /* dynamic major by default */

#define SCULLC_DEVS 4    /* scullc0 through scullc3 */

/*
 * The bare device is a variable-length region of memory.
 * Use a linked list of indirect blocks.
 *
 * "scullc_dev->data" points to an array of pointers, each
 * pointer refers to a memory page.
 *
 * The array (quantum-set) is SCULLC_QSET long.
 */
#define SCULLC_QUANTUM  4000 /* use a quantum size like scull */
#define SCULLC_QSET     500

struct scullc_dev {
	void **data;
	struct scullc_dev *next;  /* next listitem */
	int vmas;                 /* active mappings */
	int quantum;              /* the current allocation size */
	int qset;                 /* the current array size */
	size_t size;              /* 32-bit will suffice */
	struct semaphore sem;     /* Mutual exclusion */
	struct cdev cdev;
};

extern struct scullc_dev *scullc_devices;

extern struct file_operations scullc_fops;

/*
 * The different configurable parameters
 */
extern int scullc_major;     /* main.c */
extern int scullc_devs;
extern int scullc_order;
extern int scullc_qset;

/*
 * Prototypes for shared functions
 */
int scullc_trim(struct scullc_dev *dev);
struct scullc_dev *scullc_follow(struct scullc_dev *dev, int n);


#ifdef SCULLC_DEBUG
#  define SCULLC_USE_PROC
#endif

/*
 * Ioctl definitions
 */

/* Use 'K' as magic number */
#define SCULLC_IOC_MAGIC  'K'

#define SCULLC_IOCRESET    _IO(SCULLC_IOC_MAGIC, 0)

/*
 * S means "Set" through a ptr,
 * T means "Tell" directly
 * G means "Get" (to a pointed var)
 * Q means "Query", response is on the return value
 * X means "eXchange": G and S atomically
 * H means "sHift": T and Q atomically
 */
#define SCULLC_IOCSQUANTUM _IOW(SCULLC_IOC_MAGIC,  1, int)
#define SCULLC_IOCTQUANTUM _IO(SCULLC_IOC_MAGIC,   2)
#define SCULLC_IOCGQUANTUM _IOR(SCULLC_IOC_MAGIC,  3, int)
#define SCULLC_IOCQQUANTUM _IO(SCULLC_IOC_MAGIC,   4)
#define SCULLC_IOCXQUANTUM _IOWR(SCULLC_IOC_MAGIC, 5, int)
#define SCULLC_IOCHQUANTUM _IO(SCULLC_IOC_MAGIC,   6)
#define SCULLC_IOCSQSET    _IOW(SCULLC_IOC_MAGIC,  7, int)
#define SCULLC_IOCTQSET    _IO(SCULLC_IOC_MAGIC,   8)
#define SCULLC_IOCGQSET    _IOR(SCULLC_IOC_MAGIC,  9, int)
#define SCULLC_IOCQQSET    _IO(SCULLC_IOC_MAGIC,  10)
#define SCULLC_IOCXQSET    _IOWR(SCULLC_IOC_MAGIC,11, int)
#define SCULLC_IOCHQSET    _IO(SCULLC_IOC_MAGIC,  12)

#define SCULLC_IOC_MAXNR 12

3. SCULL整体流程分析

1.核心数据结构

复制代码
struct scullc_dev {
    void **data;           // 指向指针数组(量子集)
    struct scullc_dev *next; // 下一个链表项
    int vmas;              // 活动映射计数
    int quantum;           // 量子大小(每个内存块的大小)
    int qset;              // 量子集大小(指针数组的大小)
    size_t size;           // 设备总大小
    struct semaphore sem;  // 信号量(互斥锁)
    struct cdev cdev;      // 字符设备结构
};

数据组织结构:'

复制代码
scullc_dev (链表头)
  ├─ data → [量子0][量子1][量子2]...[量子qset-1]
  └─ next → scullc_dev (链表项1)
             ├─ data → [量子0][量子1]...
             └─ next → scullc_dev (链表项2)
                        ...

2.1 模块初始化与清理

2.1.1 scullc_init - 模块初始化函数

功能: 初始化 scullc 模块,注册设备,分配资源

主要步骤:

  1. 设备号分配

    • 静态分配: register_chrdev_region

    • 动态分配: alloc_chrdev_region

  2. 设备数组分配

    • 使用 kmalloc 分配 scullc_dev 数组

    • 初始化每个设备结构

  3. 设备初始化

    • 设置 quantum 和 qset

    • 初始化信号量 sema_init(&dev-&gt;sem, 1)

    • 设置字符设备 scullc_setup_cdev

  4. Slab 缓存创建

    • kmem_cache_create("scullc", scullc_quantum, ...)
  5. Proc 文件系统入口

    • 可选: create_proc_read_entry("scullcmem", ...)

返回值: 0 表示成功,负错误码表示失败


2.1.2 scullc_cleanup - 模块清理函数

功能: 释放模块占用的所有资源

主要步骤:

  1. 移除 Proc 文件系统入口

  2. 删除所有字符设备

  3. 清空所有设备数据

  4. 释放设备数组内存

  5. 销毁 Slab 缓存

  6. 注销设备号


2.2 设备打开与关闭

2.2.1 scullc_open - 设备打开函数

功能: 打开设备文件,初始化设备结构

主要步骤:

  1. 使用 container_of 从 cdev 获取设备结构

  2. 如果是只写打开,清空设备内容 scullc_trim

  3. 将设备结构存储到 filp-&gt;private_data

参数:

  • inode: inode 结构

  • filp: 文件结构

返回值: 0 表示成功,负错误码表示失败


2.2.2 scullc_release - 设备关闭函数

功能: 关闭设备文件

返回值: 0 表示成功


2.3 数据读写操作

2.3.1 scullc_read - 读取数据函数

功能: 从设备读取数据到用户空间

主要步骤:

  1. 获取信号量 down_interruptible

  2. 验证文件位置有效性

  3. 计算位置:

    • item: 链表项索引 = f_pos / itemsize

    • s_pos: 量子集索引 = (f_pos % itemsize) / quantum

    • q_pos: 量子内偏移 = (f_pos % itemsize) % quantum

  4. 使用 scullc_follow 找到正确的链表项

  5. 验证内存指针有效性

  6. 使用 copy_to_user 复制数据到用户空间

  7. 释放信号量 up

  8. 更新文件位置

参数:

  • filp: 文件结构

  • buf: 用户空间缓冲区

  • count: 读取字节数

  • f_pos: 文件位置指针

返回值: 实际读取的字节数,负错误码表示失败


2.3.2 scullc_write - 写入数据函数

功能: 从用户空间写入数据到设备

主要步骤:

  1. 获取信号量 down_interruptible

  2. 计算位置(同读取)

  3. 使用 scullc_follow 找到正确的链表项

  4. 按需分配内存:

    • 量子集: kmalloc(qset * sizeof(void *), GFP_KERNEL)

    • 量子: kmem_cache_alloc(scullc_cache, GFP_KERNEL)

  5. 使用 copy_from_user 从用户空间复制数据

  6. 更新文件位置和设备大小

  7. 释放信号量 up

参数:

  • filp: 文件结构

  • buf: 用户空间缓冲区

  • count: 写入字节数

  • f_pos: 文件位置指针

返回值: 实际写入的字节数,负错误码表示失败


2.4 辅助功能

2.4.1 scullc_follow - 链表遍历函数

功能: 遍历链表,按需创建新节点

参数:

  • dev: 起始设备结构

  • n: 需要前进的步数

返回值: 目标设备结构指针


2.4.2 scullc_trim - 设备清空函数

功能: 释放设备占用的所有内存

主要步骤:

  1. 检查是否有活动映射

  2. 释放所有量子内存 kmem_cache_free

  3. 释放量子集 kfree

  4. 释放链表节点

  5. 重置设备状态

参数:

  • dev: 设备结构指针

返回值: 0 表示成功,-EBUSY 表示有活动映射


2.4.3 scullc_setup_cdev - 字符设备设置函数

功能: 初始化并添加字符设备

参数:

  • dev: 设备结构指针

  • index: 设备索引


2.5 ioctl 控制操作

2.5.1 scullc_ioctl - ioctl 处理函数

功能: 处理设备控制命令

支持的命令:

  • SCULLC_IOCRESET: 重置 quantum 和 qset 为默认值

  • SCULLC_IOCSQUANTUM: 设置 quantum(通过指针)

  • SCULLC_IOCTQUANTUM: 设置 quantum(直接传递)

  • SCULLC_IOCGQUANTUM: 获取 quantum(通过指针)

  • SCULLC_IOCQQUANTUM: 查询 quantum(返回值)

  • SCULLC_IOCXQUANTUM: 交换 quantum(原子操作)

  • SCULLC_IOCHQUANTUM: 切换 quantum(直接传递+返回)

  • SCULLC_IOCSQSET: 设置 qset(通过指针)

  • SCULLC_IOCTQSET: 设置 qset(直接传递)

  • SCULLC_IOCGQSET: 获取 qset(通过指针)

  • SCULLC_IOCQQSET: 查询 qset(返回值)

  • SCULLC_IOCXQSET: 交换 qset(原子操作)

  • SCULLC_IOCHQSET: 切换 qset(直接传递+返回)

参数:

  • inode: inode 结构

  • filp: 文件结构

  • cmd: ioctl 命令

  • arg: 命令参数

返回值: 0 表示成功,负错误码表示失败


2.6 文件定位操作

2.6.1 scullc_llseek - 文件定位函数

功能: 移动文件读写指针

支持的定位方式:

  • SEEK_SET: 从文件开头

  • SEEK_CUR: 从当前位置

  • SEEK_END: 从文件结尾

参数:

  • filp: 文件结构

  • off: 偏移量

  • whence: 定位方式

返回值: 新的文件位置,-EINVAL 表示无效参数


2.7 异步 I/O 操作

2.7.1 scullc_aio_read - 异步读取函数

功能: 异步读取数据


2.7.2 scullc_aio_write - 异步写入函数

功能: 异步写入数据


2.7.3 scullc_defer_op - 延迟操作处理

功能: 处理异步 I/O 操作

主要步骤:

  1. 立即执行同步的读写操作

  2. 如果是同步 kiocb,直接返回结果

  3. 否则,创建工作项并使用 schedule_delayed_work 延迟完成


2.7.4 scullc_do_deferred_op - 完成异步操作

功能: 完成延迟的异步 I/O 操作


2.8 Proc 文件系统(可选)

2.8.1 scullc_read_procmem - Proc 读取函数

功能: 读取设备信息到 Proc 文件系统