您的位置:首页 > 其它

ioctl 的使用方法详细说明与例子

2012-08-17 10:01 639 查看
Talking To Device Files

与设备文件对话 (writes and IOCTLs)

设备文件是用来代表相对应的硬件设备。绝大多数的硬件设备是用来进行输出和输入操作的,所以在内核中肯定有内核从进程中获得发送到设备的输出的机制。这是通过打开一个设备文件然后向其中进行写操作来实现的,如同对普通文件的写操作。在下面的的例子中,这是通过 device_write实现的。

但这并不总是够用。设想你有一个通过串口连接的调制解调器(即使你使用的是内置调制解调器,对于CPU来说同样也是通过连接在串口上来实现工作的)。通常我们通过打开一个设备文件向调制解调器发送信息(将要通过通信线路传输的指令或数据)或读取信息(从通信线路中返回的响应指令或数据)。但是,我们如何设置同串口对话的速率,也就是向串口传输数据的速率这个问题仍然没有解决。

解决之道是在Unix系统中的函数ioctl(Input Output ConTroL的简写)。每个设备可以有自己的ioctl命令,通过读取ioctl's 可以从进程中向内核发送信息,或写ioctl's向进程返回信息 [1],或者两者都是,或都不是。函数ioctl 调用时需要三个参数:合适的设备文件的文件描述符,ioctl号,和一个可以被一个任务使用来传递任何东西的long类型的参数[2]

ioctl号是反映主设备号,ioctl的种类,对应的命令和参数类型的数字。它通常是通过在头文件中宏调用 (_IO, _IOR, _IOW 或_IOWR,取决于其种类)来建立的。该头文件应该被使用 ioctl的用户程序包含(这样它们就可以生成正确的ioctl's)和内核驱动模块包含(这样模块才能理解它)。在下面的例子中,头文件为chardev.h,源程序为ioctl.c。

即使你只想在自己的模块中使用ioctls,你最好还是接收正式的 ioctl标准,这样当你意外的使用别人的ioctls, 或别人使用你的时,你会知道有错误发生。详情参见内核代码目录树下的文件 Documentation/ioctl-number.txt.

Example 7-1. chardev.c

CODE:

/*

* chardev.c - Create an input/output character device

*/

#include <linux/kernel.h> /* We're doing kernel work */

#include <linux/module.h> /* Specifically, a module */

#include <linux/fs.h>

#include <asm/uaccess.h> /* for get_user and put_user */

#include "chardev.h"

#define SUCCESS 0

#define DEVICE_NAME "char_dev"

#define BUF_LEN 80

/*

* Is the device open right now? Used to prevent

* concurent access into the same device

*/

static int Device_Open = 0;

/*

* The message the device will give when asked

*/

static char Message[BUF_LEN];

/*

* How far did the process reading the message get?

* Useful if the message is larger than the size of the

* buffer we get to fill in device_read.

*/

static char *Message_Ptr;

/*

* This is called whenever a process attempts to open the device file

*/

static int device_open(struct inode *inode, struct file *file)

{

#ifdef DEBUG

printk("device_open(%p)\n", file);

#endif

/*

* We don't want to talk to two processes at the same time

*/

if (Device_Open)

return -EBUSY;

Device_Open++;

/*

* Initialize the message

*/

Message_Ptr = Message;

try_module_get(THIS_MODULE);

return SUCCESS;

}

static int device_release(struct inode *inode, struct file *file)

{

#ifdef DEBUG

printk("device_release(%p,%p)\n", inode, file);

#endif

/*

* We're now ready for our next caller

*/

Device_Open--;

module_put(THIS_MODULE);

return SUCCESS;

}

/*

* This function is called whenever a process which has already opened the

* device file attempts to read from it.

*/

static ssize_t device_read(struct file *file, /* see include/linux/fs.h */

char __user * buffer, /* buffer to be

* filled with data */

size_t length, /* length of the buffer */

loff_t * offset)

{

/*

* Number of bytes actually written to the buffer

*/

int bytes_read = 0;

#ifdef DEBUG

printk("device_read(%p,%p,%d)\n", file, buffer, length);

#endif

/*

* If we're at the end of the message, return 0

* (which signifies end of file)

*/

if (*Message_Ptr == 0)

return 0;

/*

* Actually put the data into the buffer

*/

while (length && *Message_Ptr) {

/*

* Because the buffer is in the user data segment,

* not the kernel data segment, assignment wouldn't

* work. Instead, we have to use put_user which

* copies data from the kernel data segment to the

* user data segment.

*/

put_user(*(Message_Ptr++), buffer++);

length--;

bytes_read++;

}

#ifdef DEBUG

printk("Read %d bytes, %d left\n", bytes_read, length);

#endif

/*

* Read functions are supposed to return the number

* of bytes actually inserted into the buffer

*/

return bytes_read;

}

/*

* This function is called when somebody tries to

* write into our device file.

*/

static ssize_t

device_write(struct file *file,

const char __user * buffer, size_t length, loff_t * offset)

{

int i;

#ifdef DEBUG

printk("device_write(%p,%s,%d)", file, buffer, length);

#endif

for (i = 0; i < length && i < BUF_LEN; i++)

get_user(Message, buffer + i);

Message_Ptr = Message;

/*

* Again, return the number of input characters used

*/

return i;

}

/*

* This function is called whenever a process tries to do an ioctl on our

* device file. We get two extra parameters (additional to the inode and file

* structures, which all device functions get): the number of the ioctl called

* and the parameter given to the ioctl function.

*

* If the ioctl is write or read/write (meaning output is returned to the

* calling process), the ioctl call returns the output of this function.

*

*/

int device_ioctl(struct inode *inode, /* see include/linux/fs.h */

struct file *file, /* ditto */

unsigned int ioctl_num, /* number and param for ioctl */

unsigned long ioctl_param)

{

int i;

char *temp;

char ch;

/*

* Switch according to the ioctl called

*/

switch (ioctl_num) {

case IOCTL_SET_MSG:

/*

* Receive a pointer to a message (in user space) and set that

* to be the device's message. Get the parameter given to

* ioctl by the process.

*/

temp = (char *)ioctl_param;

/*

* Find the length of the message

*/

get_user(ch, temp);

for (i = 0; ch && i < BUF_LEN; i++, temp++)

get_user(ch, temp);

device_write(file, (char *)ioctl_param, i, 0);

break;

case IOCTL_GET_MSG:

/*

* Give the current message to the calling process -

* the parameter we got is a pointer, fill it.

*/

i = device_read(file, (char *)ioctl_param, 99, 0);

/*

* Put a zero at the end of the buffer, so it will be

* properly terminated

*/

put_user('\0', (char *)ioctl_param + i);

break;

case IOCTL_GET_NTH_BYTE:

/*

* This ioctl is both input (ioctl_param) and

* output (the return value of this function)

*/

return Message[ioctl_param];

break;

}

return SUCCESS;

}

/* Module Declarations */

/*

* This structure will hold the functions to be called

* when a process does something to the device we

* created. Since a pointer to this structure is kept in

* the devices table, it can't be local to

* init_module. NULL is for unimplemented functions.

*/

struct file_operations Fops = {

.read = device_read,

.write = device_write,

.ioctl = device_ioctl,

.open = device_open,

.release = device_release, /* a.k.a. close */

};

/*

* Initialize the module - Register the character device

*/

int init_module()

{

int ret_val;

/*

* Register the character device (atleast try)

*/

ret_val = register_chrdev(MAJOR_NUM, DEVICE_NAME, &Fops);

/*

* Negative values signify an error

*/

if (ret_val < 0) {

printk("%s failed with %d\n",

"Sorry, registering the character device ", ret_val);

return ret_val;

}

printk("%s The major device number is %d.\n",

"Registeration is a success", MAJOR_NUM);

printk("If you want to talk to the device driver,\n");

printk("you'll have to create a device file. \n");

printk("We suggest you use:\n");

printk("mknod %s c %d 0\n", DEVICE_FILE_NAME, MAJOR_NUM);

printk("The device file name is important, because\n");

printk("the ioctl program assumes that's the\n");

printk("file you'll use.\n");

return 0;

}

/*

* Cleanup - unregister the appropriate file from /proc

*/

void cleanup_module()

{

int ret;

/*

* Unregister the device

*/

ret = unregister_chrdev(MAJOR_NUM, DEVICE_NAME);

/*

* If there's an error, report it

*/

if (ret < 0)

printk("Error in module_unregister_chrdev: %d\n", ret);

}

Example 7-2. chardev.h

CODE:
/*

* chardev.h - the header file with the ioctl definitions.

*

* The declarations here have to be in a header file, because

* they need to be known both to the kernel module

* (in chardev.c) and the process calling ioctl (ioctl.c)

*/

#ifndef CHARDEV_H

#define CHARDEV_H

#include <linux/ioctl.h>

/*

* The major device number. We can't rely on dynamic

* registration any more, because ioctls need to know

* it.

*/

#define MAJOR_NUM 100

/*

* Set the message of the device driver

*/

#define IOCTL_SET_MSG _IOR(MAJOR_NUM, 0, char *)

/*

* _IOR means that we're creating an ioctl command

* number for passing information from a user process

* to the kernel module.

*

* The first arguments, MAJOR_NUM, is the major device

* number we're using.

*

* The second argument is the number of the command

* (there could be several with different meanings).

*

* The third argument is the type we want to get from

* the process to the kernel.

*/

/*

* Get the message of the device driver

*/

#define IOCTL_GET_MSG _IOR(MAJOR_NUM, 1, char *)

/*

* This IOCTL is used for output, to get the message

* of the device driver. However, we still need the

* buffer to place the message in to be input,

* as it is allocated by the process.

*/

/*

* Get the n'th byte of the message

*/

#define IOCTL_GET_NTH_BYTE _IOWR(MAJOR_NUM, 2, int)

/*

* The IOCTL is used for both input and output. It

* receives from the user a number, n, and returns

* Message
.

*/

/*

* The name of the device file

*/

#define DEVICE_FILE_NAME "char_dev"

#endif

Example 7-3. ioctl.c

CODE:
/*

* ioctl.c - the process to use ioctl's to control the kernel module

*

* Until now we could have used cat for input and output. But now

* we need to do ioctl's, which require writing our own process.

*/

/*

* device specifics, such as ioctl numbers and the

* major device file.

*/

#include "chardev.h"

#include <fcntl.h> /* open */

#include <unistd.h> /* exit */

#include <sys/ioctl.h> /* ioctl */

/*

* Functions for the ioctl calls

*/

ioctl_set_msg(int file_desc, char *message)

{

int ret_val;

ret_val = ioctl(file_desc, IOCTL_SET_MSG, message);

if (ret_val < 0) {

printf("ioctl_set_msg failed:%d\n", ret_val);

exit(-1);

}

}

ioctl_get_msg(int file_desc)

{

int ret_val;

char message[100];

/*

* Warning - this is dangerous because we don't tell

* the kernel how far it's allowed to write, so it

* might overflow the buffer. In a real production

* program, we would have used two ioctls - one to tell

* the kernel the buffer length and another to give

* it the buffer to fill

*/

ret_val = ioctl(file_desc, IOCTL_GET_MSG, message);

if (ret_val < 0) {

printf("ioctl_get_msg failed:%d\n", ret_val);

exit(-1);

}

printf("get_msg message:%s\n", message);

}

ioctl_get_nth_byte(int file_desc)

{

int i;

char c;

printf("get_nth_byte message:");

i = 0;

while (c != 0) {

c = ioctl(file_desc, IOCTL_GET_NTH_BYTE, i++);

if (c < 0) {

printf

("ioctl_get_nth_byte failed at the %d'th byte:\n",

i);

exit(-1);

}

putchar(c);

}

putchar('\n');

}

CODE:
/*

* Main - Call the ioctl functions

*/

main()

{

int file_desc, ret_val;

char *msg = "Message passed by ioctl\n";

file_desc = open(DEVICE_FILE_NAME, 0);

if (file_desc < 0) {

printf("Can't open device file: %s\n", DEVICE_FILE_NAME);

exit(-1);

}

ioctl_get_nth_byte(file_desc);

ioctl_get_msg(file_desc);

ioctl_set_msg(file_desc, msg);

close(file_desc);

}

Notes

[1] 注意这儿“读”与“写”的角色再次翻转过来,在ioctl's中读是向内核发送信息, 而写是从内核获取信息。

[2] 这样的表述并不准确。 例如你不能在ioctl中传递一个结构体,但你可以通过传递指向这个结构体的指针实现。

函数名: ioctl

  头文件:#include<sys/ioctl.h>

  功 能: 控制I/O设备 ,提供了一种获得设备信息和向设备发送控制参数的手段。用于向设备发控制和配置命令 ,有些命令需要控制参数,这些数据是不能用read / write 读写的,称为Out-of-band数据。也就是说,read / write 读写的数据是in-band数据,是I/O操作的主体,而ioctl 命令传送的是控制信息,其中的数据是辅助的数据。

  用 法: int ioctl(int handle, int cmd,[int *argdx, int argcx]);

  返回值:成功为0,出错为-1

  usr/include/asm-generic/ioctl.h中定义的宏的注释:

  #define _IOC_NRBITS 8 //序数(number)字段的字位宽度,8bits

  #define _IOC_TYPEBITS 8 //幻数(type)字段的字位宽度,8bits

  #define _IOC_SIZEBITS 14 //大小(size)字段的字位宽度,14bits

  #define _IOC_DIRBITS 2 //方向(direction)字段的字位宽度,2bits

  #define _IOC_NRMASK ((1 << _IOC_NRBITS)-1) //序数字段的掩码,0x000000FF

  #define _IOC_TYPEMASK ((1 << _IOC_TYPEBITS)-1) //幻数字段的掩码,0x000000FF

  #define _IOC_SIZEMASK ((1 << _IOC_SIZEBITS)-1) //大小字段的掩码,0x00003FFF

  #define _IOC_DIRMASK ((1 << _IOC_DIRBITS)-1) //方向字段的掩码,0x00000003

  #define _IOC_NRSHIFT 0 //序数字段在整个字段中的位移,0

  #define _IOC_TYPESHIFT (_IOC_NRSHIFT+_IOC_NRBITS) //幻数字段的位移,8

  #define _IOC_SIZESHIFT (_IOC_TYPESHIFT+_IOC_TYPEBITS) //大小字段的位移,16

  #define _IOC_DIRSHIFT (_IOC_SIZESHIFT+_IOC_SIZEBITS) //方向字段的位移,30

  /*

  * Direction bits.

  */

  #define _IOC_NONE 0U //没有数据传输

  #define _IOC_WRITE 1U //向设备写入数据,驱动程序必须从用户空间读入数据

  #define _IOC_READ 2U //从设备中读取数据,驱动程序必须向用户空间写入数据

  #define _IOC(dir,type,nr,size) \

  (((dir) << _IOC_DIRSHIFT) | \

  ((type) << _IOC_TYPESHIFT) | \

  ((nr) << _IOC_NRSHIFT) | \

  ((size) << _IOC_SIZESHIFT))

  /*

  * used to create numbers

  */

  //构造无参数的命令编号

  #define _IO(type,nr) _IOC(_IOC_NONE,(type),(nr),0)

  //构造从驱动程序中读取数据的命令编号

  #define _IOR(type,nr,size) _IOC(_IOC_READ,(type),(nr),sizeof(size))

  //用于向驱动程序写入数据命令

  #define _IOW(type,nr,size) _IOC(_IOC_WRITE,(type),(nr),sizeof(size))

  //用于双向传输

  #define _IOWR(type,nr,size) _IOC(_IOC_READ|_IOC_WRITE,(type),(nr),sizeof(size))

  /*

  *used to decode ioctl numbers..

  */

  //从命令参数中解析出数据方向,即写进还是读出

  #define _IOC_DIR(nr) (((nr) >> _IOC_DIRSHIFT) & _IOC_DIRMASK)

  //从命令参数中解析出幻数type

  #define _IOC_TYPE(nr) (((nr) >> _IOC_TYPESHIFT) & _IOC_TYPEMASK)

  //从命令参数中解析出序数number

  #define _IOC_NR(nr) (((nr) >> _IOC_NRSHIFT) & _IOC_NRMASK)

  //从命令参数中解析出用户数据大小

  #define _IOC_SIZE(nr) (((nr) >> _IOC_SIZESHIFT) & _IOC_SIZEMASK)

  /* ...and for the drivers/sound files... */

  #define IOC_IN (_IOC_WRITE << _IOC_DIRSHIFT)

  #define IOC_OUT (_IOC_READ << _IOC_DIRSHIFT)

  #define IOC_INOUT ((_IOC_WRITE|_IOC_READ) << _IOC_DIRSHIFT)

  #define IOCSIZE_MASK (_IOC_SIZEMASK << _IOC_SIZESHIFT)

  #define IOCSIZE_SHIFT (_IOC_SIZESHIFT)

  程序例:

  #include <stdlib.h>

  #include <stdio.h>

  #include <sys/ioctl.h>

  int main(void) {

  ..int stat;

  /* use func 8 to determine if the default drive is removable */

  ..stat = ioctl(0, 8, 0, 0);

  ..if (!stat)

  ....printf("Drive %c is removable.\n", getdisk() + 'A');

  ..else

  ....printf("Drive %c is not removable.\n", getdisk() + 'A');

  ..return 0;

  }

  int ioctl( int fd, int request, .../* void *arg */ ) 详解

  第三个参数总是一个指针,但指针的类型依赖于request 参数。我们可以把和网络相关的请求划分为6 类:

  套接口操作

  文件操作

  接口操作

  ARP 高速缓存操作

  路由表操作

  流系统

  下表列出了网络相关ioctl请求的request 参数以及arg 地址必须指向的数据类型:

  
类别Request说明数据类型




SIOCATMARK

SIOCSPGRP

SIOCGPGRP
是否位于带外标记

设置套接口的进程ID 或进程组ID

获取套接口的进程ID 或进程组ID
int

int

int


FIONBIO

FIOASYNC

FIONREAD

FIOSETOWN

FIOGETOWN
设置/ 清除非阻塞I/O 标志

设置/ 清除信号驱动异步I/O 标志

获取接收缓存区中的字节数

设置文件的进程ID 或进程组ID

获取文件的进程ID 或进程组ID
int

int

int

int

int


SIOCGIFCONF

SIOCSIFADDR

SIOCGIFADDR

SIOCSIFFLAGS

SIOCGIFFLAGS

SIOCSIFDSTADDR

SIOCGIFDSTADDR

SIOCGIFBRDADDR

SIOCSIFBRDADDR

SIOCGIFNETMASK

SIOCSIFNETMASK

SIOCGIFMETRIC

SIOCSIFMETRIC

SIOCGIFMTU

SIOCxxx
获取所有接口的清单

设置接口地址

获取接口地址

设置接口标志

获取接口标志

设置点到点地址

获取点到点地址

获取广播地址

设置广播地址

获取子网掩码

设置子网掩码

获取接口的测度

设置接口的测度

获取接口MTU

(还有很多取决于系统的实现)
struct ifconf

struct ifreq

struct ifreq

struct ifreq

struct ifreq

struct ifreq

struct ifreq

struct ifreq

struct ifreq

struct ifreq

struct ifreq

struct ifreq

struct ifreq

struct ifreq
ARPSIOCSARP

SIOCGARP

SIOCDARP
创建/ 修改ARP 表项

获取ARP 表项

删除ARP 表项
struct arpreq

struct arpreq

struct arpreq


SIOCADDRT

SIOCDELRT
增加路径

删除路径
struct rtentry

struct rtentry
I_xxx
套接口操作:

  明确用于套接口操作的ioctl请求有三个, 它们都要求ioctl的第三个参数是指向某个整数的一个指针。

  SIOCATMARK: 如果本套接口的的度指针当前位于带外标记,那就通过由第三个参数指向的整数返回一个非0 值;否则返回一个0 值。POSIX 以函数sockatmark 替换本请求。

  SIOCGPGRP : 通过第三个参数指向的整数返回本套接口的进程ID 或进程组ID ,该ID 指定针对本套接口的SIGIO 或SIGURG 信号的接收进程。本请求和fcntl 的F_GETOWN 命令等效,POSIX 标准化的是fcntl 函数。

  SIOCSPGRP : 把本套接口的进程ID 或者进程组ID 设置成第三个参数指向的整数,该ID 指定针对本套接口的SIGIO 或SIGURG 信号的接收进程,本请求和fcntl 的F_SETOWN 命令等效,POSIX 标准化的是fcntl 操作。

  文件操作:

  以下5 个请求都要求ioctl的第三个参数指向一个整数。

  FIONBIO : 根据ioctl的第三个参数指向一个0 或非0 值分别清除或设置本套接口的非阻塞标志。本请求和O_NONBLOCK 文件状态标志等效,而该标志通过fcntl 的F_SETFL 命令清除或设置。

  FIOASYNC : 根据iocl 的第三个参数指向一个0 值或非0 值分别清除或设置针对本套接口的信号驱动异步I/O 标志,它决定是否收取针对本套接口的异步I/O 信号(SIGIO )。本请求和O_ASYNC 文件状态标志等效,而该标志可以通过fcntl 的F_SETFL 命令清除或设置。

  FIONREAD : 通过由ioctl的第三个参数指向的整数返回当前在本套接口接收缓冲区中的字节数。本特性同样适用于文件,管道和终端。

  FIOSETOWN : 对于套接口和SIOCSPGRP 等效。

  FIOGETOWN : 对于套接口和SIOCGPGRP 等效。

定义

  ioctl是设备驱动程序中对设备的I/O通道进行管理的函数。所谓对I/O通道进行管理,就

  是对设备的一些特性进行控制,例如串口的传输波特率、马达的转速等等。它的调用个数

  如下:

  int ioctl(int fd, int cmd, …);

  其中fd就是用户程序打开设备时使用open函数返回的文件标示符,cmd就是用户程序对设

  备的控制命令,至于后面的省略号,那是一些补充参数,一般最多一个,有或没有是和

  cmd的意义相关的。

  ioctl函数是文件结构中的一个属性分量,就是说如果你的驱动程序提供了对ioctl的支

  持,用户就能在用户程序中使用ioctl函数控制设备的I/O通道。

必要性

  如果不用IOCTL的话,也能实现对设备I/O通道的控制,但那就是蛮拧了。例如,我们可

  以在驱动程式中实现WRITE的时候检查一下是否有特别约定的数据流通过,如果有的话,

  那么后面就跟着控制命令(一般在SOCKET编程中常常这样做)。不过如果这样做的话,会

  导致代码分工不明,程式结构混乱,程式员自己也会头昏眼花的。

  所以,我们就使用IOCTL来实现控制的功能。要记住,用户程式所作的只是通过命令码告

  诉驱动程式他想做什么,至于怎么解释这些命令和怎么实现这些命令,这都是驱动程式要

  做的事情。

实现操作

  这是个非常麻烦的问题,我是能省则省。要说清晰他,没有四五千字是不行的,所以我这

  里是不可能把他说得非常清晰了,不过如果有读者对用户程式怎么和驱动程式联系起来感

  兴趣的话,能看我前一阵子写的《write的奥秘》。读者只要把write换成ioctl,就知

  道用户程式的ioctl是怎么和驱动程式中的ioctl实现联系在一起的了。

  我这里说一个大概思路,因为我觉得《Linux设备驱动程式》这本书已说的非常清晰

  了,不过得花一些时间来看。

  在驱动程式中实现的ioctl函数体内,实际上是有一个switch{case}结构,每一个case对

  应一个命令码,做出一些相应的操作。怎么实现这些操作,这是每一个程式员自己的事

  情,因为设备都是特定的,这里也没法说。关键在于怎么样组织命令码,因为在ioctl中

  命令码是唯一联系用户程式命令和驱动程式支持的途径。

  命令码的组织是有一些讲究的,因为我们一定要做到命令和设备是一一对应的,这样才不

  会将正确的命令发给错误的设备,或是把错误的命令发给正确的设备,或是把错误的

  命令发给错误的设备。这些错误都会导致不可预料的事情发生,而当程式员发现了这些奇

  怪的事情的时候,再来调试程式查找错误,那将是非常困难的事情。

  所以在Linux核心中是这样定义一个命令码的:

  ____________________________________

  | 设备类型 | 序列号 | 方向 |数据尺寸|

  |----------|--------|------|--------|

  | 8 bit | 8 bit |2 bit |8~14 bit|

  |----------|--------|------|--------|

  这样一来,一个命令就变成了一个整数形式的命令码。不过命令码非常的不直观,所以

  Linux Kernel中提供了一些宏,这些宏可根据便于理解的字符串生成命令码,或是从

  命令码得到一些用户能理解的字符串以标明这个命令对应的设备类型、设备序列号、数

  据传送方向和数据传输尺寸。

  这些宏我就不在这里解释了,具体的形式请读者察看Linux核心原始码中的和,文件里给

  除了这些宏完整的定义。这里我只多说一个地方,那就是"幻数"。

  幻数是个字母,数据长度也是8,所以就用一个特定的字母来标明设备类型,这和用一

  个数字是相同的,只是更加利于记忆和理解。就是这样,再没有更复杂的了。

  更多的说了也没有,读者还是看一看原始码吧,推荐各位阅读《Linux 设备驱动程式》所

  带原始码中的short一例,因为他比较短小,功能比较简单,能看明白ioctl的功能和细

  节。

cmd参数怎么得出

  这里确实要说一说,cmd参数在用户程式端由一些宏根据设备类型、序列号、传送方向、

  数据尺寸等生成,这个整数通过系统调用传递到内核中的驱动程式,再由驱动程式使用解

  码宏从这个整数中得到设备的类型、序列号、传送方向、数据尺寸等信息,然后通过

  switch{case}结构进行相应的操作。

  要透彻理解,只能是通过阅读原始码,我这篇文章实际上只是个引子。Cmd参数的组织

  还是比较复杂的,我认为要搞熟他还是得花不少时间的,不过这是值得的,驱动程式中最

  难的是对中断的理解。

  五、 小结

  ioctl其实没有什么非常难的东西需要理解,关键是理解cmd命令码是怎么在用户程式里生成

  并在驱动程式里解析的,程式员最主要的工作量在switch{case}结构中,因为对设备的

  I/O控制都是通过这一部分的代码实现的。

一般来讲ioctl在用户程序中的调用是:ioctl(int fd,int command, (char*)argstruct)。ioctl调用与网络编程有关,文件描述符fd实际上是由socket()系统调用返回的。参数command的取值由/usr/include/linux/sockios.h所规定。这些command的由于功能的不同,可分为以下几个小类:

• 改变路由表 (例如 SIOCADDRT, SIOCDELRT),

• 读/更新 ARP/RARP 缓存(如:SIOCDARP, SIOCSRARP),

• 一般的与网络接口有关的(例如 SIOCGIFNAME, SIOCSIFADDR 等等)

在Gooodies目录下有很多样例程序展示了如何使用ioctl。当你看这些程序时,注意参数argstruct是与参数command相关的。例如,与路由表相关的ioctl使用rtentry这种结构,rtentry定义在/usr/include/linux/route.h(参见例子adddefault.c)。与ARP有关的ioctl调用使用arpreq结构,arpreq定义在/usr/include/linux/if_arp.h(参见例子arpread.c)

与网络接口有关的ioctl调用使用的command参数通常看起来像SIOCxIFyyyy的形式,这里x要么是S(设定set,写write),要么是G(得到get,读 read)。在getifinfo.c程序中就使用了这种形式的command参数来读IP地址,硬件地址,广播地址和得到与网络接口有关的一些标志(flag)。在这些ioctl调用中,第三个参数是ifreq结构,它在/usr/include/linux/if.h 中定义。在某些情况下, ioctrl调用可能会使用到在sockios.h之外的新的定义,例如,WaveLAN无线网络卡会保存有关无线网络信号强度的信息,这对用户的程序可能有用。但用户怎么得到这种信息呢?我们的第一个本能是在sockios.h中定义新的ioctl命令,例如SIOCGIFWVLNSS(它的英文缩写表示WaveLAN的信号强度)。但不幸的是,这种命令不是对所有其他的网络接口(例如:loopback环回接口)有意义,而且不应当允许对于WAVLAN卡以外的网络接口使用ioctl命令。那么,我们需要的是这样一种机制:它能够定义一种与网络接口相关的ioctl命令。幸运的是,在Linux操作系统中已经为实现这个目的内建了一种挂钩(hook)机制。当你再次看sockios.h文件时,你将发现每一种设备已经预先定义了SIOCDEVPRIVATE的ioctl命令。而它的实现将留给开发相应驱动程序的人去完成。

通常,一个用户程序使用ioctl(sockid,SIOCDEVPRIVATE,(char*)&ifr)来调用与某种设备(指像WaveLAN那样的特殊设备)相关的ioctl命令,这里ifr是struct ifreq ifr形式的变量。用户程序应当在ifr.ifr_name中填充与这个设备相关的名字,例如,假设WaveLAN使用的接口号为eth1。一般的,一个用户程序还需要与内核互相交换ioctl的command参数和结果,这可以通过ifr.ifr_data这个变量来实现,例如,想得到WaveLAN中表示信号强度的信息时,可以通过返回这个变量来实现。Linux的源代码已经包括了两种设备de4x5和ewrk3,它们定义并且实现了特定的ioctl调用。这两个设备的源代码在de4x5.h,de4x5.c,ewrk3.h,ewrk3.c中(在/usr/src/linux/drivers/net/目录中)。这两种设备都定义了它们特有的结构(struct
ewrk3_ioctl 和 struct de4x5_ioctl)来方便用户程序和设备驱动之间交换信息。每次调用ioctl前,用户程序应当在相应的结构变量中设定合适的初值,并且将ifr.ifr_data指向该值。

在我们进一步讨论ewrk3和de4x5的代码前,让我们仔细看看ioctl调用是如何一步步地实现的。所有的和接口相关的ioctl请求(SIOCxIFyyyy 和 SIOCDEVPRIVATE)将会调用dev_ioctl()(在/usr/src/linux/net/core/dev.c中)。但这只是一个包装器(wrapper),实际的动作将由dev_ifsioc()(也在dev.c中)来实现。差不多dev_ioctl()这个函数所做的所有工作只是检查这个调用是否已经有了正当的权限(例如,改变路由表需要有root的权限)。而dev_ifsioc()这个函数首先要做的一些事情包括得到与ifr.ifr_name相匹配的设备的结构(在/usr/include/linux/netdevice.h
中定义)。但这是在实现特定的接口命令(例如:SIOCGIFADDR)之后。这些特定的接口命令被放置到一个巨大的switch语句之中。其中 SIOCDEVPRIVATE命令和其他的在0x89F0到0x89FF之间的代码将出现在switch语句中的一个分支——default语句中。内核会检查表示设备的结构变量中,是否已经定义了一个与设备相关的ioctl句柄(handler)。这里的句柄是一个函数指针,它在表示设备的结构变量中do_ioctl部分。如果已经设置了这个句柄,那么内核将会执行它。

所以,如果要实现一个与设备相关的ioctl命令,所要做的只是编写一个与这个设备相关的ioctl句柄,并且将表示这个设备的结构变量中do_ioctl部分指向这个句柄。对于ewrk3这个设备,它的句柄是ewrk3_ioctl()(在ewrk3.c里面)并且相应的表示该设备的结构变量由ewrk3_init()来初始化。在ewrk3_ioctl() 的代码中清晰的指出ifr.ifr_data是用作设备驱动程序和用户程序之间交换信息的。注意,这部分的内存可以双向的交流信息。例如,在ewrk3的驱动程序代码中,if.ifr_data的头两个字节是用来表示特殊的动作(例如,EWRK3_SET_PROM,EWRK3_CLR_PROM),而这个动作是符合使用者(驱动程序实现了多个与设备相关的、由SIOCDEVPRIVATE调用的命令)的要求的。另外,ifr.ifr_data中第5个字节指向的缓冲区(buffer)被用来交换其他的信息(如:当使用EWRK3_SET_HWADDR和EWRK3_GET_HWADDR时为硬件地址)

在你深入ewrk3_ioctl() 时,请注意一般情况下一个用户进程不能直接访问内核所在的内存。为此,驱动开发者可以使用两个特殊的函数memcpy_tofs()和 memcpy_fromfs()。内核函数memcpy_tofs(arg1, arg2, arg3) 从地址arg2(用户空间)向地址arg1(内核空间)拷贝arg3个字节。类似的,memcpy_fromfs(arg1,arg2,arg3)从地址 arg2(用户空间)向地址arg1(内核空间)拷贝arg3个字节。在这些调用之前,verify_area()将会检查这个进程是否拥有合适的访问权限。另外,注意使用printk()函数可以输出debug信息。这个函数与printf()函数类似,但不能处理浮点类型的数。内核代码不能够使用
printf()函数。printk()函数产生的结果将记录在/usr/adm/messages里。如果想知道更多的关于这些函数的或者与它们相关的信息,可以参考《Linux Kernel Hacker’s Guide》(在Linux文档网站的首页) 这本书中Supporting Functions部分。

毕业后头五年决定你的一生 10类最急需IT人才:Java开发者居首
海量Android教程、开发资料和源码 给将成为“Android高手”的10个建议
成为Java高手的25个学习目标--非常经典 Android
4.1果冻豆新特性详解
Java侵权诉讼Google获胜,Android厚积薄发 面试必备:Android笔试总结
Android高手必须掌握的28大内容和10个建议 Android平台研发人才缺口30万
Android开发环境安装和配置步骤详细图解 2012国内移动App开发者大调查结果
Windows 7下搭建android开发环境步骤图解 Android
4.0的30个突出的新特性
Android高手要经过的6个阶段和6个境界 linux下搭建Android开发环境步骤
从IT菜鸟变为“IT骨干开发者”的11个建议 程序员编程技术迅速提高的终极攻略
2012世界各国人均GDP排名,中国超泰国 2012年全国各省平均工资排行
2012年中国大学高校排行榜(580强排名) 中国各省市面积和人口数量排名
中国百万开发者大调查:程序员的薪水不错 Java高手需要越过的10座高山
周立功谈嵌入式:我的25年嵌入式生涯 Android和Java语言的异同和关系
华为中国区手机销量达千万,80%为智能机 谷歌Android碎片化严重
2012年中国各省GDP和人均GDP排名 90后就业“钱景”:IT仍是最佳选择
2012全球城市竞争力500强,69个中国城市上榜 不要做浮躁的软件工程师
2012年世界500强,79家大陆香港台湾公司上榜名单 给IT新兵的15个建议
美国知名科技公司入门级软件工程师的薪水排名 回顾Java经过的风风雨雨
71道经典Android面试题和答案--重要知识点都涉及到了
芯片巨头海思和展讯:给中国芯片业带来信心 海量经典Java教程、学习资料和源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: