Chinaunix首页 | 论坛 | 博客
  • 博客访问: 539689
  • 博文数量: 120
  • 博客积分: 3030
  • 博客等级: 中校
  • 技术积分: 1445
  • 用 户 组: 普通用户
  • 注册时间: 2006-03-05 01:00
文章存档

2011年(1)

2009年(2)

2008年(32)

2007年(33)

2006年(52)

我的朋友

分类: LINUX

2006-03-24 14:35:44

这次实践ldd2上面的例子程序scullc,本意是想学习一下ioctol的用法 ,但目前却仍然没有机会分析到ioctol,主要的原因是因为不知道什么时候需要用到ioctol ,所以对ioctol的分析就感觉无地放矢 。
    在这里把ioctol以外的分析先贴出来 ,希望有了解ioctol用法的同伴能够回复本贴 ,指点俺iocotl实际的用处和用法
    实际上跟我的实践4是一样的功能 ,甚至测试例子都可以用实践4的例子 ,唯一不同的地方就是内存分配的地方不一样 ,增加了同时打开多个设备的处理,以及我不懂的io处理 。(其实我更想知道像阻塞处理 ,ioctol的用法等,可是本次实践却没有达到目的呵呵最多也是实践4的翻版)
     既然跟实践4差不多也就不多说了 ,贴出程序 ,大家自己看
/* -*- 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.19 2001/07/18 22:28:18 rubini Exp $
 */
#ifndef __KERNEL__
#  define __KERNEL__
#endif
#ifndef MODULE
#  define MODULE
#endif
#include
#include
/* modversion stuff: no #ifdef needed if 2.0 support is not needed */
#ifdef CONFIG_MODVERSIONS
#  include
#endif
#include /* printk() */
#include /* kmalloc() */
#include      /* everything... */
#include   /* error codes */
#include   /* size_t */
#include
#include         /* O_ACCMODE */
#include    /* cli(), *_flags */
#include /*VERTIFY*/
#include "scullc.h"        /* local definitions */
#define __PUT_USER __put_user
#define __GET_USER __get_user
/* Kmem caches were not available in 2.0. Disallow compilation in that case */
#ifdef LINUX_20
#  error "Kmem_cache functions are not available in Linux-2.0"
#else
#  if defined(LINUX_22) && LINUX_VERSION_CODE < KERNEL_VERSION(2,2,18)
#    error "This module needs at least 2.2.18 to run"
#  endif
/* leave the #ifdef open, so 2.0 won't get other errors */

/*
 * I don't use static symbols here, because register_symtab is called
 */
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_PARM(scullc_major, "i");
MODULE_PARM(scullc_devs, "i");
MODULE_PARM(scullc_qset, "i");
MODULE_PARM(scullc_quantum, "i");
MODULE_AUTHOR("Alessandro Rubini");

ScullC_Dev *scullc_devices; /* allocated in scullc_init */
int scullc_trim(ScullC_Dev *dev);
/* 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;
    }
}
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 */
    ScullC_Dev *d;
    *start = buf;
    for(i=0; 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                    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;
}
#ifdef USE_PROC_REGISTER
static int scullc_get_info (char *buf, char **start, off_t offset,
                int len, int unused)
{
    int eof = 0;
    return scullc_read_procmem(buf, start, offset, len, &eof, NULL);
}

struct proc_dir_entry scullc_proc_entry = {
        0,                 /* low_ino: the inode -- dynamic */
        9, "scullcmem",     /* len of name and name */
        S_IFREG | S_IRUGO, /* mode */
        1, 0, 0,           /* nlinks, owner, group */
        0, NULL,           /* size - unused; operations -- use default */
        scullc_get_info,   /* function used to read data */
        /* nothing more */
    };

static inline void create_proc_read_entry (const char *name, mode_t mode,
                struct proc_dir_entry *base, void *read_func, void *data)
{
    proc_register_dynamic (&proc_root, &scullc_proc_entry);
}
static inline void remove_proc_entry (char *name, void *parent)
{
    proc_unregister (&proc_root, scullc_proc_entry.low_ino);
}
#endif /* USE_PROC_REGISTER */
#endif /* SCULLC_USE_PROC */
/*
 * Open and close
 */
int scullc_open (struct inode *inode, struct file *filp)
{
    int num = MINOR(inode->i_rdev);    
  要哭了 ,查找原码才知道阿
   /*
   #define MAJOR(dev) ((dev)>>8)
   #define MINOR(dev) ((dev) & 0xff)
   #define MKDEV(ma,mi) ((ma)<<8 | (mi))*/
 
 
    ScullC_Dev *dev; /* device information */
     printk("__the MINOR num = %d \n",num) ;
    /*  check the device number */
    多同时打开4个设备scullc_devs = 4 ,
    //scullc_devices在INIT的时候已经被初始化
    if (num >= scullc_devs) return -ENODEV; //scullc_devs = 4
    dev = &scullc_devices[num];
    /* 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 */   the vloid**data kfree(data[i]) ;
        up (&dev->sem);                         信号量
    }
    /* and use filp->private_data to point to the device data */
    filp->private_data = dev;
 /*
 struct file {
  struct list_head f_list;
  struct dentry  *f_dentry;
  struct vfsmount         *f_vfsmnt;
  struct file_operations *f_op;
  atomic_t  f_count;
  unsigned int   f_flags;
  mode_t   f_mode;
  loff_t   f_pos;
  unsigned long   f_reada, f_ramax, f_raend, f_ralen, f_rawin;
  struct fown_struct f_owner;
  unsigned int  f_uid, f_gid;
  int   f_error;
  unsigned long  f_version;
  // needed for tty driver, and maybe others
  void   *private_data;
  // preallocated helper kiobuf to speedup O_DIRECT //
  struct kiobuf  *f_iobuf;
  long   f_iobuf_lock;
 };
 */
    MOD_INC_USE_COUNT;
    return 0;          /* success */
}
int scullc_release (struct inode *inode, struct file *filp)
{
    MOD_DEC_USE_COUNT;
    return 0;
}
/*
 * Follow the list
 */
ScullC_Dev *scullc_follow(ScullC_Dev *dev, int n)
{
    while (n--) {
        if (!dev->next) {
            dev->next = kmalloc(sizeof(ScullC_Dev), GFP_KERNEL);
            memset(dev->next, 0, sizeof(ScullC_Dev));
        }
        dev = dev->next;
        continue;
    }
    return dev;
}
/*
 * Data management: read and write
 */
ssize_t scullc_read (struct file *filp, char *buf, size_t count,
                loff_t *f_pos)    纪录文件当前的读写位置
               
{
    ScullC_Dev *dev = filp->private_data; /* the first listitem */
    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;
   /*此处需要说明一下 ,比如一个设备文件同时可以打开4个设备
   ,那么 一个设备的数据长度为quantum * qset,那么如果是第2个的话
   就应该是在 quantum * qset之后的开始处理,所以用设备的当前读写
   位置/一个设备的长度就可以得出当前打开的是第几个设备
   */
  
    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); file://dev[item]
    时dptr已经指向了我们读取的设备正确地址了,这样 ,
    可以开始考虑真正的相对于某个专门设备的读写pos了
    如我们打开第2个scull设备,那么现在的dptr实际上是dev[1]
    后spos 实际上 是相对dev[1]的读写位置 ,这个位置是以quantum
    单位的,例如dev[1] ->data[spos] ,可是我们读的时候是以byte为单位的
    以此时用到了q_pos,表示相对于dev[1] ->data[spos] 的byte为单位的偏移,
    if (!dptr->data)
        goto nothing; /* don't fill holes */
    if (!dptr->data[s_pos])
        goto nothing;
    if (count > quantum - q_pos)   次读写的数据不能超过quantum
                                   边 界,也就是说不能次读取2个
                                   的内容
    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;  改设备当前的pos ,下次读写从这里开始
    return count;
  nothing:
    up (&dev->sem);
    return retval;
}
 
ssize_t scullc_write (struct file *filp, const char *buf, size_t count,
                loff_t *f_pos)
{
    ScullC_Dev *dev = filp->private_data;
    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 *)arg, _IOC_SIZE(cmd));
    else if (_IOC_DIR(cmd) & _IOC_WRITE)
        err =  !access_ok(VERIFY_READ, (void *)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 *) 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 *) 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 *) arg);
        if (ret == 0)
            ret = __PUT_USER(tmp, (int *) 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 *) arg);
        break;
      case SCULLC_IOCTQSET:
        scullc_qset = arg;
        break;
      case SCULLC_IOCGQSET:
        ret = __PUT_USER(scullc_qset, (int *)arg);
        break;
      case SCULLC_IOCQQSET:
        return scullc_qset;
      case SCULLC_IOCXQSET:
        tmp = scullc_qset;
        ret = __GET_USER(scullc_qset, (int *) arg);
        if (ret == 0)
            ret = __PUT_USER(tmp, (int *)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)
{
    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;
}
 
/*
 * The 2.0 wrappers
 */
#ifdef LINUX_20
int scullc_lseek_20 (struct inode *ino, struct file *f,
                off_t offset, int whence)
{
    return (int)scullc_llseek(f, offset, whence);
}
int scullc_read_20 (struct inode *ino, struct file *f, char *buf, int count)
{
    return (int)scullc_read(f, buf, count, &f->f_pos);
}
int scullc_write_20 (struct inode *ino, struct file *f, const char *b, int c)
{
    return (int)scullc_write(f, b, c, &f->f_pos);
}
void scullc_release_20 (struct inode *ino, struct file *f)
{
    scullc_release(ino, f);
}
#define scullc_llseek scullc_lseek_20
#define scullc_read scullc_read_20
#define scullc_write scullc_write_20
#define scullc_release scullc_release_20
#define llseek lseek
#endif /* LINUX_20 */
/*
 * The fops
 */
struct file_operations scullc_fops = {
    llseek: scullc_llseek,
    read: scullc_read,
    write: scullc_write,
    ioctl: scullc_ioctl,
    open: scullc_open,
    release: scullc_release,
};
int scullc_trim(ScullC_Dev *dev)
{
    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]);
  放data指向的指针对应的内容
       
            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;
}
 

/*
 * Finally, the module stuff
 */
int scullc_init(void)
{
    int result, i;
    SET_MODULE_OWNER(&scullc_fops);
    /*
     * Register your major, and accept a dynamic number
     */
    result = register_chrdev(scullc_major, "scullc", &scullc_fops);
    if (result < 0) return result;
    if (scullc_major == 0) scullc_major = result; /* dynamic */
    /*
     * allocate the devices -- we can't have them static, as the number
     * can be specified at load time
     */
    scullc_devices = kmalloc(scullc_devs * sizeof (ScullC_Dev), GFP_KERNEL);
    if (!scullc_devices) {
        result = -ENOMEM;
        goto fail_malloc;
    }
    memset(scullc_devices, 0, scullc_devs * sizeof (ScullC_Dev));
    始化设备信息数组
    for (i=0; i < scullc_devs; i++) {
   /*
        #define SCULLC_QUANTUM  4000 // use a quantum size like scull
        #define SCULLC_QSET     500
        */
        scullc_devices[i].quantum = scullc_quantum;
        scullc_devices[i].qset = scullc_qset;
        sema_init (&scullc_devices[i].sem, 1);
 步信号量初始化,大哥快疯了
 出函数原型?
 /*
  static inline void sema_init (struct semaphore *sem, int val)
  {
    * *sem = (struct semaphore)__SEMAPHORE_INITIALIZER((*sem),val);
    *
    * i'd rather use the more flexible initialization above, but sadly
    * GCC 2.7.2.3 emits a bogus warning. EGCS doesnt. Oh well.
  
   atomic_set(&sem->count, val);
   sem->sleepers = 0;
   init_waitqueue_head(&sem->wait);
   #if WAITQUEUE_DEBUG
    sem->__magic = (int)&sem->__magic;
   #endif
  } 
 */
    
    }
 
    /* init_module: create a cache for our quanta */
    scullc_cache =
 kmem_cache_create("scullc", scullc_quantum,
     0, SLAB_HWCACHE_ALIGN,
     NULL, NULL); /* no ctor/dtor */
    if (!scullc_cache) {
        result = -ENOMEM;
        goto fail_malloc2;
    }
#ifdef SCULLC_USE_PROC /* only when available */
    create_proc_read_entry("scullcmem", 0, NULL, scullc_read_procmem, NULL);
#endif
    return 0; /* succeed */
  fail_malloc2:
    kfree(scullc_devices);
  fail_malloc:
    unregister_chrdev(scullc_major, "scullc");
    return result;
}
void scullc_cleanup(void)
{
    int i;
    unregister_chrdev(scullc_major, "scullc");
#ifdef SCULLC_USE_PROC
    remove_proc_entry("scullcmem", 0);
#endif
    for (i=0; i        scullc_trim(scullc_devices+i);
    kfree(scullc_devices);
    /* cleanup_module: release the cache of our quanta */
    kmem_cache_destroy(scullc_cache);
}
#endif /* not linux-2.0 */
module_init(scullc_init);
module_exit(scullc_cleanup);
阅读(2126) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~