歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux技術 >> ldd(linux設備驅動程序)實驗2:scull()

ldd(linux設備驅動程序)實驗2:scull()

日期:2017/3/3 11:30:02   编辑:Linux技術
轉自:http://www.cnblogs.com/yiru/archive/2012/11/29/2794658.html(博主:勒達與天鵝)
存檔,僅供學習參考。
按照ldd第三版書上的網址,下載下來的代碼是最終版的,沒有按章節剝離,不方便讀者自己實驗。
以下是我手把手敲下的書上第二個實驗scull的代碼以及安裝和測試的步驟。
按上篇搭建linux驅動開發環境(配合LDD閱讀)做完實驗1後,scull的安裝很簡單了,在任意位置保存下面兩個源文件Makefile,scull.c,執行make,生成目標模塊scull.ko,然後insmod
scull.ko。
lsmod, 看到第一個就是scull,且會生成這個文件夾/sys/module/scull,可以進去看看裡面有什麼。cat /proc/devices 可以看到"xxx scull"。因為我的scull驅動(源碼貼在下面)是隨機生成設備號,所以要進去看。
下面,我們就可以用mknod命令來申請設備文件了。
mkdir /dev/scull
mknod /dev/scull/scull0 c xxx 0
    xxx必須是剛才在proc裡看到的主設備號,此設備號是0。主、次設備號如果不符的話,這個命令不會執行失敗,但是生成的設備在將來使用時會出這個錯:scull0:No such device or address
   然後ls -li,看下新設備的主次設備號。
    到這步之後要注意力,如果你的驅動寫得有問題,而編譯時沒有檢測到的話,很可能在執行下面的步驟時使整個linux系統掛起,那只能切斷虛擬機電源重新來過了。由於書上的scull代碼極簡,而官網下載的scull源碼相對繁雜,我想用最簡的來測試,書上的代碼卻不全,我只好半用書半用網上的源碼,改了非常久。
    然後依據書上的“試試新設備”這一節來測試這個設備。可以用的命令有:cp, dd, 重新輸入輸出, free;還可以在驅動裡寫printk來跟蹤測試。還可以用strace命令來監視系統調用。
解釋下,mknod 的標准形式為: mknod DEVNAME {b | c} MAJOR MINOR
1,DEVNAME是要創建的設備文件名,如果想將設備文件放在一個特定的文件夾下,就需要先用mkdir在dev目錄下新建一個目錄;
2, b和c 分別表示塊設備和字符設備:
b表示系統從塊設備中讀取數據的時候,直接從內存的buffer中讀取數據,而不經過磁盤;
c表示字符設備文件與設備傳送數據的時候是以字符的形式傳送,一次傳送一個字符,比如打印機、終端都是以字符的形式傳送數據;
3,MAJOR和MINOR分別表示主設備號和次設備號:
為了管理設備,系統為每個設備分配一個編號,一個設備號由主設備號和次設備號組成。主設備號標示某一種類的設備,次設備號用來區分同一類型的設備。 linux操作系統中為設備文件編號分配了32位無符號整數,其中前12位是主設備號,後20位為次設備號,所以在向系統申請設備文件時主設備號不好超過 4095,次設備號不好超過2^20 -1。
模塊裝好後,書本自帶的代碼中有個scull/scull_load用以裝載,但這也是混裝了全書的架構,而我們要的是剝離出來的第三章的實驗,如果想試一試,可以在實驗完畢後(因為這會造成難以估計的混亂)運行它。
Makefile
ifneq ($(KERNELRELEASE),)
obj-m := scull.o
else
PWD := $(shell pwd)
KVER ?= $(shell uname -r)
KDIR := /lib/modules/$(KVER)/build
all:
$(MAKE) -C $(KDIR) M=$(PWD)
clean:
rm -rf .*.cmd *.o *.mod.c *.ko .tmp_versions *.symvers *.order
endif
scull.c
/*
* main.c -- the bare scull 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.
*
*/
#ifndef __KERNEL__
# define __KERNEL__
#endif
#ifndef MODULE
# define MODULE
#endif
//#include <linux/config.h>
#include <linux/slab.h> /* kmalloc() */
#include <asm/uaccess.h>
#include <linux/module.h>
#include <linux/kernel.h> /* printk() */
#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 <asm/system.h> /* cli(), *_flags */
//#include "scull.h" /* local definitions */
int scull_major;
int scull_nr_devs;
int scull_quantum;
int scull_qset;
// struct file_operations *scull_fop_array[]={
// &scull_fops, /* type 0 */
// &scull_priv_fops, /* type 1 */
// &scull_pipe_fops, type 2
// &scull_sngl_fops, /* type 3 */
// &scull_user_fops, /* type 4 */
// &scull_wusr_fops /* type 5 */
// };
// #define SCULL_MAX_TYPE 5
// static void scull_setup_cdev(struct scull_dev *dev, int index){
// int err, devno = MKDEV(scull_major, scull_minor + index);
// cdev_init(&dev->cdev, &scull_fops):
// dev->cdev.owner = THIS_MODULE;
// dev->cdev.ops = &scull_fops;
// err = cdev_add (&dev->cdev, devno, 1);
// if(err)
// printk(KERN_NOTICE "Error %d adding scull%d", err, index);
// }
struct cdev {
struct kobject kobj;
struct module *owner;
const struct file_operations *ops;
struct list_head list;
dev_t dev;
unsigned int count;
};
struct scull_dev{
struct scull_qset *data;
int quantum;
int qset;
unsigned long size;
unsigned int access_key;
struct semaphore sem;
struct cdev cdev;
struct scull_dev* next;
}scull_dev;
/* memory management */
struct scull_qset{
void **data;
struct scull_qset* next;
};
int scull_trim(struct scull_dev* dev){
struct scull_qset *next, *dptr;
int qset = dev->qset;
int i;
for(dptr = dev->data; dptr; dptr = next){
if(dptr->data){
for(i=0; i<qset; i++){
kfree(dptr->data[i]);
}
kfree(dptr->data);
dptr->data = NULL;
}
next = dptr->next;
kfree(dptr);
}
dev->size = 0;
dev->quantum = scull_quantum;
dev->qset = scull_qset;
dev->data = NULL;
return 0;
}
/*
* Open and close
*/
int scull_open(struct inode *inode, struct file *filp){
struct scull_dev *dev; /* device information */
dev = container_of(inode->i_cdev, struct scull_dev, cdev);
filp->private_data = dev; /* for other methods */
/* now trim to 0 the length of the device if open was write-only */
if( (filp->f_flags & O_ACCMODE) == O_WRONLY){
scull_trim(dev); /* ignore errors */
}
return 0; /* success */
}
int scull_release(struct inode *inode, struct file *filp)
{
return 0;
}
/*
* Follow the list
*/
struct scull_dev *scull_follow(struct scull_dev *dev, int n)
{
while (n--) {
if (!dev->next) {
dev->next = kmalloc(sizeof(scull_dev), GFP_KERNEL);
memset(dev->next, 0, sizeof(scull_dev));
}
dev = dev->next;
continue;
}
return dev;
}
/*
* Data management: read and write
*/
ssize_t scull_read(struct file *filp, char *buf, size_t count,
loff_t *f_pos)
{
struct scull_dev *dev = filp->private_data; /* the first listitem */
struct scull_qset *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 ret = 0;
if (down_interruptible(&dev->sem))
return -ERESTARTSYS;
if (*f_pos >= dev->size)
goto out;
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 = scull_follow(dev, item);
if (!dptr->data)
goto out; /* don't fill holes */
if (!dptr->data[s_pos])
goto out;
/* read only up to the end of this quantum */
if (count > quantum - q_pos)
count = quantum - q_pos;
if (copy_to_user(buf, dptr->data[s_pos]+q_pos, count)) {
ret = -EFAULT;
goto out;
}
*f_pos += count;
ret = count;
out:
up(&dev->sem);
return ret;
}
ssize_t scull_write(struct file *filp, const char *buf, size_t count,
loff_t *f_pos)
{
struct scull_dev *dev = filp->private_data;
struct scull_qset *dptr;
int quantum = dev->quantum;
int qset = dev->qset;
int itemsize = quantum * qset;
int item, s_pos, q_pos, rest;
ssize_t ret = -ENOMEM; /* value used in "goto out" statements */
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 = scull_follow(dev, item);
if (!dptr->data) {
dptr->data = kmalloc(qset * sizeof(char *), GFP_KERNEL);
if (!dptr->data)
goto out;
memset(dptr->data, 0, qset * sizeof(char *));
}
if (!dptr->data[s_pos]) {
dptr->data[s_pos] = kmalloc(quantum, GFP_KERNEL);
if (!dptr->data[s_pos])
goto out;
}
/* write only up to the end of this quantum */
if (count > quantum - q_pos)
count = quantum - q_pos;
if (copy_from_user(dptr->data[s_pos]+q_pos, buf, count)) {
ret = -EFAULT;
goto out;
}
*f_pos += count;
ret = count;
/* update the size */
if (dev->size < *f_pos)
dev-> size = *f_pos;
out:
up(&dev->sem);
return ret;
}
/*
* The cleanup function is used to handle initialization failures as well.
* Thefore, it must be careful to work correctly even if some of the items
* have not been initialized
*/
static void scull_cleanup_module(void){
// int i;
// #ifndef CONFIG_DEVFS_FS
// /* cleanup_module is never called if registering failed */
// unregister_chrdev(scull_major, "scull");
// #endif
// #ifdef SCULL_DEBUG /* use proc only if debugging */
// scull_remove_proc();
// #endif
// if (scull_devices) {
// for (i=0; i<scull_nr_devs; i++) {
// scull_trim(scull_devices+i);
// /* the following line is only used for devfs */
// devfs_unregister(scull_devices[i].handle);
// }
// kfree(scull_devices);
// }
// /* and call the cleanup functions for friend devices */
// scull_p_cleanup();
// scull_access_cleanup();
// /* once again, only for devfs */
// devfs_unregister(scull_devfs_dir);
}
static int scull_init_module(void){
// int result, i;
// SET_MODULE_OWNER(&scull_fops);
// #ifdef CONFIG_DEVFS_FS
// /* If we have devfs, create /dev/scull to put files in there */
// scull_devfs_dir = devfs_mk_dir(NULL, "scull", NULL);
// if (!scull_devfs_dir) return -EBUSY; /* problem */
// #else /* no devfs, do it the "classic" way */
// /*
// * Register your major, and accept a dynamic number. This is the
// * first thing to do, in order to avoid releasing other module's
// * fops in scull_cleanup_module()
// */
// result = register_chrdev(scull_major, "scull", &scull_fops);
// if (result < 0) {
// printk(KERN_WARNING "scull: can't get major %d\n",scull_major);
// return result;
// }
// if (scull_major == 0) scull_major = result; /* dynamic */
// #endif /* CONFIG_DEVFS_FS */
// /*
// * allocate the devices -- we can't have them static, as the number
// * can be specified at load time
// */
// scull_devices = kmalloc(scull_nr_devs * sizeof(scull_dev), GFP_KERNEL);
// if (!scull_devices) {
// result = -ENOMEM;
// goto fail;
// }
// memset(scull_devices, 0, scull_nr_devs * sizeof(scull_dev));
// for (i=0; i < scull_nr_devs; i++) {
// scull_devices[i].quantum = scull_quantum;
// scull_devices[i].qset = scull_qset;
// sema_init(&scull_devices[i].sem, 1);
// #ifdef CONFIG_DEVFS_FS
// sprintf(devname, "%i", i);
// devfs_register(scull_devfs_dir, devname,
// DEVFS_FL_AUTO_DEVNUM,
// 0, 0, S_IFCHR | S_IRUGO | S_IWUGO,
// &scull_fops,
// scull_devices+i);
// #endif
// }
// /* At this point call the init function for any friend device */
// if ( (result = scull_p_init()) )
// goto fail;
// if ( (result = scull_access_init()) )
// goto fail;
// /* ... */
// #ifndef SCULL_DEBUG
// EXPORT_NO_SYMBOLS; /* otherwise, leave global symbols visible */
// #endif
// #ifdef SCULL_DEBUG /* only when debugging */
// scull_create_proc();
// #endif
  struct file_operations scull_fops;
register_chrdev(scull_major, "scull", &scull_fops);
return 0; /* succeed */
// fail:
// scull_cleanup_module();
// return result;
}
module_init(scull_init_module);
module_exit(scull_cleanup_module);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("DYYR");
Copyright © Linux教程網 All Rights Reserved