Linux环境下用户空间与内核空间数据的交换方式

在linux环境开发过程中,经常会需要在用户空间和内核空间之间进行数据交换。
介绍了 Linux 系统下用户空间与内核空间数据交换的几种方式
 
第一节:使用procfs实现内核交互简明教程(1)
 
第二节:使用procfs实现内核交互简明教程(2)
 
第三节:基于register_sysctl_table实现内核数据交互(Sysctl方式)
 
第四节:通过bootloader向内核传输启动参数
 
第五节:Linux的kobject机制
 
第六节:利用内核模块添加系统调用

 
第七节:使用ioctl向linux内核传递参数的方法实例
 
第一:procfs信息读取实现案例

  procfs是比较老的一种用户态与内核态的数据交换方式,内核的很多数据都是通过这种方式出口给用户的,内核的很多参数也是通过这种方式来让用户方便设置的。

  1. struct proc_dir_entry *create_proc_entry(const char *name, mode_t mode,  
  2.                      struct proc_dir_entry *parent)  

       该函数用于创建一个正常的proc条目,参数name给出要建立的proc条目的名称,参数mode给出了建立的该proc条目的访问权限,参数parent指定建立的proc条目所在的目录。如果要在/proc下建立proc条目,parent应当为NULL。

  1. /* 
  2.  * Remove a /proc entry and free it if it's not currently in use. 
  3.  */  
  4. void remove_proc_entry(const char *name, struct proc_dir_entry *parent)  

        该函数用于删除上面函数创建的proc条目,参数name给出要删除的proc条目的名称,参数parent指定建立的proc条目所在的目录。

  1. struct proc_dir_entry {  
  2.          ……  
  1. read_proc_t *read_proc; /* 读接口 */  
  2. write_proc_t *write_proc; /* 写接口 */  
  3. ……  
  1. };  

      procfs读写信息实例:

  1. /********************************************** 
  2.  * Author: lewiyon@hotmail.com 
  3.  * File name: proc_sample.c 
  4.  * Description: create a file "proc_example" in the /proc,  
  5.  *              which allows both input and output. 
  6.  * Date: 2011-12-12 
  7.  *********************************************/  
  8.   
  9. #include <linux/kernel.h> /* We're doing kernel work */  
  10. #include <linux/module.h> /* Specifically, a module */  
  11. #include <linux/proc_fs.h>    /* Necessary because we use proc fs */  
  12. #include <asm/uaccess.h>  /* for get_user and put_user */  
  13.   
  14. #define MSG_LEN 10  
  15. #define PROC_NAME "sample"  
  16.   
  17. char chflag[MSG_LEN] = "sample";   
  18.   
  19. static struct proc_dir_entry *sample;  
  20.   
  21. /** 
  22.  * proc_read_data() 
  23.  * @page - buffer to write the data in 
  24.  * @start - where the actual data has been written in page 
  25.  * @offset - same meaning as the read system call 
  26.  * @count - same meaning as the read system call 
  27.  * @eof - set if no more data needs to be returned 
  28.  * @data - pointer to our soft state 
  29.  */  
  30. static int proc_read_rwdata(char *page, char **stat, off_t off,  
  31.                           int count, int *eof, void *data)  
  32. {  
  33.     int len;  
  34.     len = sprintf(page,"%s\n", chflag);  
  35.     return len;  
  36. }  
  37.   
  38. static int proc_write_rwdata(struct file *file, const char __user *buf,  
  39.                           unsigned long count, void *data)  
  40. {  
  41.     if (count > MSG_LEN)  
  42.         count = MSG_LEN;  
  43.   
  44.     if (copy_from_user(&chflag, buf, count))  
  45.         return -EFAULT;  
  46.       
  47.     return count;  
  48. }  
  49. /*  
  50.  * 模块初始化  
  51.  */  
  52. static int __init sample_init(void)  
  53. {     
  54.     int ret = 0;  
  55.       
  56.     /* 
  57.      * create_proc_entry(name, mode,parent) 
  58.      * 在parent对应的目录下创建name文件 
  59.      * 返回目录对应的proc_dir_dentry 
  60.      */  
  61.     sample = create_proc_entry(PROC_NAME, 0644, NULL);    
  62.     if (NULL == sample) {  
  63.         ret = -ENOMEM;    
  64.         goto sample_err;  
  65.     }  
  66.     sample->read_proc = &proc_read_rwdata,  
  67.     sample->write_proc = &proc_write_rwdata,  
  68.   
  69.     printk(KERN_INFO "Create sample\n");   
  70.     return ret;  
  71.   
  72. sample_err:  
  73.     return ret;  
  74. }  
  75.   
  76. /* 
  77.  * 模块清理 
  78.  */  
  79. static void __exit sample_exit(void)  
  80. {  
  81.     remove_proc_entry(PROC_NAME, NULL);  
  82.     printk(KERN_INFO "Remove /proc/proc_sample\n");  
  83. }  
  84.   
  85. module_init(sample_init);  
  86. module_exit(sample_exit);  
  87. MODULE_LICENSE("GPL");  
  88. MODULE_AUTHOR("lewiyon <lewiyon@hotmail.com>");  

  1. /********************************************** 
  2.  * Author: lewiyon@hotmail.com 
  3.  * File name: proc_sample.c 
  4.  * Description: create a file "proc_example" in the /proc,  
  5.  *              which allows read. 
  6.  * Date: 2011-12-11 
  7.  * Version: V1.0 
  8.  *********************************************/  
  9.   
  10. #include <linux/kernel.h> /* We're doing kernel work */  
  11. #include <linux/module.h> /* Specifically, a module */  
  12. #include <linux/proc_fs.h>    /* Necessary because we use proc fs */  
  13. #include <asm/uaccess.h>  /* for get_user and put_user */  
  14.   
  15. #define MESSAGE_LENGTH 80  
  16. #define PROC_NAME "proc_sample"  
  17.   
  18. unsigned int flag = 100;   
  19.   
  20. static struct proc_dir_entry *proc_sample;  
  21. static struct proc_dir_entry *sample, *sample_r;  
  22.   
  23. /** 
  24.  * proc_read_data() 
  25.  * @page - buffer to write the data in 
  26.  * @start - where the actual data has been written in page 
  27.  * @offset - same meaning as the read system call 
  28.  * @count - same meaning as the read system call 
  29.  * @eof - set if no more data needs to be returned 
  30.  * @data - pointer to our soft state 
  31.  */  
  32. static int proc_read_data(char *page, char **stat, off_t off,  
  33.                           int count, int *eof, void *data)  
  34. {  
  35.     int len;  
  36.     len = sprintf(page, "jiffies = %ld\n", jiffies);  
  37.     return len;  
  38. }  
  39.   
  40. /*  
  41.  * 模块初始化  
  42.  */  
  43. static int __init sample_init(void)  
  44. {     
  45.     int ret = 0;  
  46.       
  47.     /* 
  48.      * proc_mkdir(name, parent) 
  49.      * 在parent对应的目录下创建name目录 
  50.      * 返回目录对应的proc_dir_dentry 
  51.      */  
  52.     proc_sample = proc_mkdir(PROC_NAME, NULL);    
  53.     if (NULL == proc_sample) {  
  54.         ret = -ENOMEM;    
  55.         goto proc_sample_err;  
  56.     }  
  57.     /* 
  58.      * create_proc_entry(name, mode,parent) 
  59.      * 在parent对应的目录下创建name文件 
  60.      * 返回目录对应的proc_dir_dentry 
  61.      */  
  62.     sample = create_proc_entry("sample", 0644, proc_sample);      
  63.     if (NULL == sample) {  
  64.         ret = -ENOMEM;    
  65.         goto sample_err;  
  66.     }  
  67.       
  68.     sample_r = create_proc_read_entry("sample_r", 0444,   
  69.                 proc_sample, proc_read_data, NULL);   
  70.     if (NULL == sample_r) {  
  71.         ret = -ENOMEM;    
  72.         goto sample_r_err;  
  73.     }  
  74.   
  75.     printk(KERN_INFO "Create sample\n");   
  76.     return ret;  
  77.   
  78. sample_r_err:  
  79.     remove_proc_entry("sample", proc_sample);  
  80. sample_err:  
  81.     remove_proc_entry(PROC_NAME, NULL);  
  82. proc_sample_err:  
  83.     return ret;  
  84. }  
  85.   
  86. /* 
  87.  * 模块清理 
  88.  */  
  89. static void __exit sample_exit(void)  
  90. {  
  91.     remove_proc_entry("sample", proc_sample);  
  92.     remove_proc_entry("sample_r", proc_sample);  
  93.     remove_proc_entry(PROC_NAME, NULL);  
  94.     printk(KERN_INFO "Remove /proc/proc_sample\n");  
  95. }  
  96.   
  97. module_init(sample_init);  
  98. module_exit(sample_exit);  
  99. MODULE_LICENSE("GPL");  
  100. MODULE_AUTHOR("lewiyon <lewiyon@hotmail.com>");  
在/proc/创建文件目录proc_sampe,然后在其下创建了两个文件。其中sample_r可读取数据


第二: register_sysctl_table实现内核数据交互

 Sysctl是一种用户应用来设置和获得运行时内核的配置参数的一种有效方式,通过这种方式,用户应用可以在内核运行的任何时刻来改变内核的配置参数,也可以在任何时候获得内核的配置参数。

通常,内核的这些配置参数也出现在proc文件系统的/proc/sys
目录下,用户应用可以直接通过这个目录下的文件来实现内核配置的读写操作。
使用register_sysctl_table方式实现内核数据交互,就不得不用提到struct ctl_table
。下面来介绍一下这个结构体。
1 结构体ctl_table
每一个sysctl条目对应一个 struct ctl_table 结构,在该结构体定义在文件./include/
linux/sysctl.h中,定义及解释如下:
/* A sysctl table is an array of struct ctl_table: */
  1. struct ctl_table  
  2. {  
  3.     const char *procname; /* Text ID for /proc/sys, or zero */  
  4.     void *data;  
  5.     int maxlen;  
  6.     mode_t mode;  
  7.     struct ctl_table *child;  
  8.     struct ctl_table *parent; /* Automatically set */  
  9.     proc_handler *proc_handler; /* Callback for text         formatting */  
  10.     void *extra1;  
  11.     void *extra2;  
  12. };  
 
成员变量解释:
const char *procname; /* 表示在proc/sys/下显示的文件名称 */
void *data;           /* 表示对应于内核中的变量名称    */
int maxlen;           /* 表示条目允许的最大长度         */
mode_t mode;             /* 条目在proc文件系统下的访问权限 */
struct ctl_table *child;
struct ctl_table *parent; /* Automatically set */
proc_handler *proc_handler; /*回调函数&proc_dointvec/&proc_dostring */
void *extra1;
void *extra2;

字段maxlen,它主要用于字符串内核变量,以便在对该条目设置时,对超过该最大长度的字符串截掉后面超长的部分.

字段proc_handler,表示回调函数,对于整型内核变量,应当设置为&proc_dointvec,而对于字符串内核变量,则设置为 &proc_dostring。

 

Sysctl 条目也可以是目录,此时 mode 字段应当设置为 0555,否则通过 sysctl 系统调用将无法访问它下面的 sysctl 条目,child 则指向该目录条目下面的所有条目,对于在同一目录下的多个条目,不必一一注册,用户可以把它们组织成一个 struct ctl_table 类型的数组,然后一次注册就可以。

2 注册register_sysctl_table
注册sysctl条目使用函数register_sysctl_table,函数原型如下:
struct ctl_table_header *register_sysctl_table(struct ctl_table *table)
第一个参数为定义的struct ctl_table结构的sysctl条目或条目数组指针;
 
3 卸载unregister_sysctl_table
当模块卸载时,需要使用函数unregister_sysctl_table,其原型:
void unregister_sysctl_table(struct ctl_table_header * header)
其中struct ctl_table_header是通过函数register_sysctl_table
注册时返回的结构体指针。
 
4 实例
 
  1. /********************************************** 
  2.   * Author: lewiyon@hotmail.com 
  3.   * File name: sysctl_example.c 
  4.   * Description: sysctl example 
  5.   * Date: 2013-04-24 
  6.   *********************************************/  
  7.   
  8. #include <linux/module.h>  
  9. #include <linux/init.h>  
  10. #include <linux/kernel.h>  
  11. #include <linux/sysctl.h>  
  12.   
  13. static int sysctl_kernusr_data = 1024;  
  14.   
  15. static int kernusr_callback(ctl_table *table, int write,  
  16.         void __user *buffer, size_t *lenp, loff_t *ppos)  
  17. {  
  18.     int rc;  
  19.     int *data = table->data;  
  20.   
  21.     printk(KERN_INFO "original value = %d\n", *data);  
  22.   
  23.     rc = proc_dointvec(table, write, buffer, lenp, ppos);  
  24.     if (write)  
  25.         printk(KERN_INFO "this is write operation, current value = %d\n", *  
  26. data);  
  27.   
  28.     return rc;  
  29. }  
  30.   
  31. static struct ctl_table kernusr_ctl_table[] = {  
  32.     {  
  33.         .procname       = "kernusr",  
  34.         .data           = &sysctl_kernusr_data,  
  35.         .maxlen         = sizeof(int),  
  36.         .mode           = 0644,  
  37.         .proc_handler   = kernusr_callback,  
  38.     },  
  39.     {  
  40.         /* sentinel */  
  41.     },  
  42. };  
  43.   
  44. static struct ctl_table_header *sysctl_header;  
  45.   
  46. static int __init sysctl_example_init(void)  
  47. {  
  48.     sysctl_header = register_sysctl_table(kernusr_ctl_table);  
  49.     if (sysctl_header == NULL) {  
  50.         printk(KERN_INFO "ERR: register_sysctl_table!");  
  51.         return -1;  
  52.     }  
  53.   
  54.     printk(KERN_INFO "sysctl register success.\n");  
  55.     return 0;  
  56.   
  57. }  
  58.   
  59. static void __exit sysctl_example_exit(void)  
  60. {  
  61.     unregister_sysctl_table(sysctl_header);  
  62.     printk(KERN_INFO "sysctl unregister success.\n");  
  63. }  
  64.   
  65. module_init(sysctl_example_init);  
  66. module_exit(sysctl_example_exit);  
  67. MODULE_LICENSE("GPL");  
5 参考文献
http://www.ibm.com/developerworks/cn/linux/l-kerns-usrs/
http://blog.chinaunix.net/uid-7210505-id-146429.html

Linux提供了一种通过bootloader向其传输启动参数的功能,内核开发者可以通过这种方式来向内核传输数据,从而控制内核启动行为。

通常的使用方式是,定义一个分析参数的函数,而后使用内核提供的宏 __setup把它注册到内核中,该宏定义在 linux/init.h 中,因此要使用它必须包含该头文件:

__setup("para_name=", parse_func)

其中:@para_name为参数名;@parse_func为分析参数值的函数,它负责把该参数的值转换成相应的内核变量的值并设置那个内核变量。

内核为整数参数值的分析提供了函数 get_option get_options,前者用于分析参数值为一个整数的情况,而后者用于分析参数值为逗号分割的一系列整数的情况,对于参数值为字符串的情况,需要开发者自定义相应的分析函数。

 

1          setup使用案例

在文件./mm/slub.c

  1. static int __init setup_slub_min_order(char *str)  
  2. {  
  3.     get_option(&str, &slub_min_order);  
  4.     return 1;  
  5. }  
  6. __setup("slub_min_order=", setup_slub_min_order);  
  7.   
  8. static int __init setup_slub_max_order(char *str)  
  9. {  
  10.     get_option(&str, &slub_max_order);  
  11.     slub_max_order = min(slub_max_order, MAX_ORDER - 1);  
  12.     return 1;  
  13. }  
  14. __setup("slub_max_order=", setup_slub_max_order);  

 

2          内核程序kern-boot-params测试

在源代码包中的内核程序kern-boot-params.c说明了三种情况的使用。该程序列举了参数为一个整数、逗号分割的整数串以及字符串三种情况,读者要想测试该程序,需要把该程序拷贝到要使用的内核的源码目录树的一个目录下,为了避免与内核其他部分混淆,作者建议在内核源码树的根目录下创建一个新目录,如examples,然后把该程序拷贝到 examples 目录下并重新命名为 setup_example.c,并且为该目录创建一个 Makefile文件:

obj-y = setup_example.o

Makefile 仅需这一行就足够了,然后需要修改源码树的根目录下的 Makefile文件的一行,把下面行

core-y          := usr/

修改为

core-y          := usr/ examples/

注意:如果读者创建的新目录和重新命名的文件名与上面不同,需要修改上面所说 Makefile文件相应的位置。做完以上工作就可以按照内核构建步骤去构建新的内核。

  1. //filename: kern-boot-params.c  
  2. #include <linux/kernel.h>  
  3. #include <linux/init.h>  
  4. #include <linux/string.h>      
  5.   
  6. #define MAX_SIZE 5      
  7.   
  8. static int setup_example_int;  
  9. static int setup_example_int_array[MAX_SIZE];  
  10. static char setup_example_string[16];     
  11.   
  12. static int __init parse_int(char * s)  
  13. {  
  14.         int ret;     
  15.   
  16.         ret = get_option(&s, &setup_example_int);  
  17.         if (ret == 1) {  
  18.                 printk("setup_example_int=%d\n", setup_example_int);  
  19.         }     
  20.   
  21.         return 1;  
  22. }     
  23.   
  24. static int __init parse_int_string(char *s)  
  25. {  
  26.         char * ret_str;  
  27.         int i;     
  28.   
  29.         ret_str = get_options(s, MAX_SIZE, setup_example_int_array);  
  30.         if (*ret_str != '\0') {  
  31.                 printk("incorrect setup_example_int_array paramters: %s\n", ret_str);  
  32.         }  
  33.         else {  
  34.                printk("setup_example_int_array=");  
  35.                 for (i=1; i<MAX_SIZE; i++) {  
  36.                         printk("%d", setup_example_int_array[i]);  
  37.                         if (i < (MAX_SIZE -1)) {  
  38.                                 printk(",");  
  39.                         }  
  40.                 }  
  41.                 printk("\n");  
  42.                 printk("setup_example_int_array includes %d intergers\n", setup_example_int_array[0]);  
  43.         }     
  44.   
  45.         return 1;  
  46. }     
  47.   
  48. static int __init parse_string(char *s)  
  49. {  
  50.         if (strlen(s) > 15) {  
  51.                 printk("Too long setup_example_string parameter, \n");  
  52.                 printk("maximum length is less than or equal to 15\n");  
  53.         }  
  54.         else {  
  55.                 memcpy(setup_example_string, s, strlen(s) + 1);  
  56.                 printk("setup_example_string=%s\n", setup_example_string);  
  57.         }  
  58.         return 1;  
  59. }     
  60.   
  61. __setup("setup_example_int=", parse_int);  
  62. __setup("setup_example_int_array=", parse_int_string);  
  63. __setup("setup_example_string=", parse_string);  

 

3          变量配置方法

在构建好内核并设置好lilogrub为该内核的启动条目后,就可以启动该内核,然后使用lilogrub的编辑功能为该内核的启动参数行增加如下参数串:

setup_example_int=1234 setup_example_int_array=100,200,300,400 setup_example_string=Thisisatest

当然,该参数串也可以直接写入到lilo或grub的配置文件中对应于该新内核的内核命令行参数串中。读者可以使用其它参数值来测试该功能.

  1. [root@RedHat ~]# cat /boot/grub/menu.lst  
  2. # grub.conf generated by anaconda  
  3. #  
  4. # Note that you do not have to rerun grub after making changes to this file  
  5. # NOTICE:  You have a /boot partition.  This means that  
  6. #          all kernel and initrd paths are relative to /boot/, eg.  
  7. #          root (hd0,0)  
  8. #          kernel /vmlinuz-version ro root=/dev/mapper/VolGroup-lv_root  
  9. #          initrd /initrd-[generic-]version.img  
  10. #boot=/dev/sda  
  11. default=0  
  12. timeout=3  
  13. splashimage=(hd0,0)/grub/splash.xpm.gz  
  14. hiddenmenu  
  15. title Red Hat Enterprise Linux Server (3.2.0trace)  
  16. root (hd0,0)  
  17. kernel /vmlinuz-3.2.0trace ro root=/dev/mapper/VolGroup-lv_root rd_LVM_LV=VolGroup/lv_root rd_LVM_LV=VolGroup/lv_swap rd_NO_LUKS rd_NO_MD rd_NO_DM LANG=en_US.UTF-8 SYSFONT=latarcyrheb-sun16 KEYBOARDTYPE=pc KEYTABLE=us crashkernel=auto rhgb quiet setup_example_int=1234 setup_example_int_array=10,20,30,40 setup_example_string=lewiyon  
  18.         initrd /initramfs-3.2.0trace.img  
  19.   
  20. title Red Hat Enterprise Linux (2.6.32-71.el6.i686)  
  21. root (hd0,0)  
  22. kernel /vmlinuz-2.6.32-71.el6.i686 ro root=/dev/mapper/VolGroup-lv_root rd_LVM_LV=VolGroup/lv_root rd_LVM_LV=VolGroup/lv_swap rd_NO_LUKS rd_NO_MD rd_NO_DM LANG=en_US.UTF-8 SYSFONT=latarcyrheb-sun16 KEYBOARDTYPE=pc KEYTABLE=us crashkernel=auto rhgb quiet  
  23. initrd /initramfs-2.6.32-71.el6.i686.img  
  24. [root@RedHat ~]#  

 

使用dmesg | grep setup来查看该程序的输出。
  
  
  1. [root@RedHat ~]# dmesg | grep setup  
  2. setup_percpu: NR_CPUS:32 nr_cpumask_bits:32 nr_cpu_ids:1 nr_node_ids:1  
  3.    
  4. Kernel command line: ro root=/dev/mapper/VolGroup-lv_root rd_LVM_LV=VolGroup/lv_root rd_LVM_LV=VolGroup/lv_swap rd_NO_LUKS rd_NO_MD rd_NO_DM LANG=en_US.UTF-8 SYSFONT=latarcyrheb-sun16 KEYBOARDTYPE=pc KEYTABLE=us crashkernel=auto rhgb quiet setup_example_int=1234 setup_example_int_array=10,20,30,40 setup_example_string=lewiyon  
  5. setup_example_int=1234  
  6. setup_example_int_array=10,20,30,40,  
  7. setup_example_int_array includes 4 intergers  
  8. setup_example_string=lewiyon  
  9. [root@RedHat ~]#  
 

4          参考文献

http://www.ibm.com/developerworks/cn/linux/l-kerns-usrs/

第四: Linux的kobject机制

sysfs文件系统下的每个目录对应于一个kobj,kset是kobj的封装,内嵌了一个kobj,其代表kset自身,ktype代表属性操作集,但由于通用性,因此把ktype单独剥离出来,kobj,kset,ktype成为了各个驱动模型最底层的关联元素,并由此形成了sys下的各种拓扑结构。

1          kobject,kset,子系统层次结构

内核通常用kobject结构将各个对象连接起来组成一个分层的结构体系。

 

一个 kset是嵌入到相同类型结构的 kobject的集合。

struct kobj_type 关注的是对象的类型,而struct kset关心的是对象的集合,可认为kset是kobjects的顶层容器类。每个 kset 在内部包含自己的 kobject,并可以用多种处理kobject的方法处理kset。 kset总是在 sysfs中出现;一旦设置了 kset并把它添加到系统中,将在 sysfs 中创建一个目录;kobjects不必在 sysfs中表示, 但kset中的每一个 kobject成员都在sysfs中得到表述。

 

2          如何实现sysfs接口

kobject 是在 sysfs虚拟文件系统后的机制。对每个在 sysfs中的目录,在内核中都会有一个 kobject与之对应。每个 kobject都输出一个或多个属性,它在 kobject 的 sysfs目录中以文件的形式出现,其中的内容由内核产生。

当创建kobject 时,每个 kobject都被给定一系列默认属性。这些属性保存在 kobj_type结构中:

  1. struct kobj_type {  
  2.     void (*release)(struct kobject *);  
  3.     struct sysfs_ops *sysfs_ops;/*提供实现以下属性的方法*/  
  4.     struct attribute **default_attrs; /*用于保存类型属性列表(指针的指针) */  
  5. };  
  6. struct attribute {  
  7.     char *name;/*属性的名字( 在 kobject 的 sysfs 目录中显示)*/  
  8.     struct module *owner;/*指向模块的指针(如果有), 此模块负责实现这个属性*/  
  9.     mode_t mode; /*属性的保护位,modes 的宏定义在 <linux/stat.h>:例如S_IRUGO 为只读属性等等*/  
  10. }; /*default_attrs 列表中的最后一个元素必须用 0 填充*/  

sysfs 读写这些属性是由 kobj_type->sysfs_ops成员中的函数完成的:

  1. struct sysfs_ops {  
  2.     ssize_t (*show)(struct kobject *, struct attribute *,char *);  
  3.     ssize_t (*store)(struct kobject *,struct attribute *,const char *, size_t);  
  4.     const void *(*namespace)(struct kobject *, const struct attribute *);  
  5. };  

当用户空间读取一个属性时,内核会使用指向 kobject的指针(kobj)和正确的属性结构(*attr)来调用show方法,该方法将给定属性值编码进缓冲(buffer)(注意不要越界( PAGE_SIZE字节)),并返回实际数据长度。sysfs的约定要求每个属性应当包含一个可读值;若返回大量信息,需将它分为多个属性.

也可对所有 kobject关联的属性使用同一个 show方法,用传递到函数的 attr指针来判断所请求的属性。有的 show方法包含对属性名字的检查。有的show方法会将属性结构嵌入另一个结构,这个结构包含需要返回属性值的信息,这时可用container_of获得上层结构的指针以返回属性值的信息。

store 方法将存在缓冲(buffer)的数据( size为数据的长度,不能超过 PAGE_SIZE )解码并保存新值到属性(*attr),返回实际解码的字节数。store方法只在拥有属性的写权限时才能被调用。此时注意:接收来自用户空间的数据一定要验证其合法性。如果到数据不匹配,返回一个负的错误值。

3          案例

  1. /********************************************** 
  2.  * Author: lewiyon@hotmail.com 
  3.  * File name: kset_sample.c 
  4.  * Description: kset example 
  5.  * Date: 2011-12-10 
  6.  *********************************************/  
  7.   
  8. #include <linux/kobject.h>  
  9. #include <linux/string.h>  
  10. #include <linux/sysfs.h>  
  11. #include <linux/slab.h>  
  12. #include <linux/module.h>  
  13. #include <linux/init.h>  
  14.   
  15. /* 
  16.  * 将要创建的文件foo对应的kobj. 
  17.  */  
  18. struct foo_obj {  
  19.        struct kobject kobj;  
  20.        int foo;  
  21.        int baz;  
  22.        int bar;  
  23. };  
  24.   
  25. /* 通过域成员返回结构体的指针 */  
  26. #define to_foo_obj(x) container_of(x, struct foo_obj, kobj)  
  27.   
  28. /* 属性 */  
  29. struct foo_attribute {  
  30.        struct attribute attr;  
  31.        ssize_t (*show)(struct foo_obj *foo, struct foo_attribute *attr, char *buf);  
  32.        ssize_t (*store)(struct foo_obj *foo, struct foo_attribute *attr, const char *buf, size_t count);  
  33. };  
  34.   
  35. #define to_foo_attr(x) container_of(x, struct foo_attribute, attr)  
  36.   
  37. /* 
  38.  * 属性foo信息显示函数 (涉及文件目录foo/) 
  39.  */  
  40. static ssize_t foo_attr_show(struct kobject *kobj,  
  41.                           struct attribute *attr,  
  42.                           char *buf)  
  43. {  
  44.        struct foo_attribute *attribute;  
  45.        struct foo_obj *foo;  
  46.   
  47.        attribute = to_foo_attr(attr);  
  48.        foo = to_foo_obj(kobj);  
  49.   
  50.        if (!attribute->show)  
  51.               return -EIO;  
  52.   
  53.        return attribute->show(foo, attribute, buf);  
  54. }  
  55.   
  56. /* 
  57.  * 属性foo存储函数(涉及文件目录foo/) (when a value is written to a file.) 
  58.  */  
  59. static ssize_t foo_attr_store(struct kobject *kobj,  
  60.                            struct attribute *attr,  
  61.                            const char *buf, size_t len)  
  62. {  
  63.        struct foo_attribute *attribute;  
  64.        struct foo_obj *foo;  
  65.   
  66.        attribute = to_foo_attr(attr);  
  67.        foo = to_foo_obj(kobj);  
  68.   
  69.        if (!attribute->store)  
  70.               return -EIO;  
  71.   
  72.        return attribute->store(foo, attribute, buf, len);  
  73. }  
  74.   
  75. /* 
  76.  * foo的show/store列表 
  77.  */  
  78. static const struct sysfs_ops foo_sysfs_ops = {  
  79.        .show = foo_attr_show,  
  80.        .store = foo_attr_store,  
  81. };  
  82.   
  83. /* 
  84.  * The release function for our object.  This is REQUIRED by the kernel to 
  85.  * have.  We free the memory held in our object here. 
  86.  */  
  87. static void foo_release(struct kobject *kobj)  
  88. {  
  89.        struct foo_obj *foo;  
  90.   
  91.        foo = to_foo_obj(kobj);  
  92.        kfree(foo);  
  93. }  
  94.   
  95. /* 
  96.  * 当需要从foo文件中读取信息时,调用此函数 
  97.  */  
  98. static ssize_t foo_show(struct foo_obj *foo_obj, struct foo_attribute *attr,  
  99.                      char *buf)  
  100. {  
  101.        return sprintf(buf, "%d\n", foo_obj->foo);  
  102. }  
  103.   
  104. /* 
  105.  * 当往foo文件写入信息时,调用此函数 
  106.  */  
  107. static ssize_t foo_store(struct foo_obj *foo_obj, struct foo_attribute *attr,  
  108.                       const char *buf, size_t count)  
  109. {  
  110.        sscanf(buf, "%du", &foo_obj->foo);  
  111.        return count;  
  112. }  
  113.   
  114. static struct foo_attribute foo_attribute =  
  115.        __ATTR(foo, 0666, foo_show, foo_store);  
  116.   
  117. /* 
  118.  * foo_ktype的属性列表 
  119.  */  
  120. static struct attribute *foo_default_attrs[] = {  
  121.        &foo_attribute.attr,  
  122.        NULL,     /* need to NULL terminate the list of attributes */  
  123. };  
  124.   
  125. /* 
  126.  * 定义kobj_type结构体 
  127.  * 指定sysfs_ops,release函数, 属性列表foo_default_attrs 
  128.  */  
  129. static struct kobj_type foo_ktype = {  
  130.        .sysfs_ops = &foo_sysfs_ops,  
  131.        .release = foo_release,  
  132.        .default_attrs = foo_default_attrs,  
  133. };  
  134.   
  135. static struct kset *example_kset;  
  136. static struct foo_obj *foo_obj;  
  137.   
  138. static struct foo_obj *create_foo_obj(const char *name)  
  139. {  
  140.        struct foo_obj *foo;  
  141.        int retval;  
  142.   
  143.        /* allocate the memory for the whole object */  
  144.        foo = kzalloc(sizeof(*foo), GFP_KERNEL);  
  145.        if (!foo)  
  146.               return NULL;  
  147.   
  148.        foo->kobj.kset = example_kset;  
  149.   
  150.     /* 
  151.      * 初始化kobject数据结结构foo->lobj, 
  152.      * 即 在foo->kobj的层次组织kset中创建个名为name的文件foo/foo 
  153.      * 成功返回0 
  154.      */  
  155.        retval = kobject_init_and_add(&foo->kobj, &foo_ktype, NULL, "%s", name);  
  156.        if (retval) {  
  157.         /* 减小kobj的引用计数 */  
  158.               kobject_put(&foo->kobj);  
  159.               return NULL;  
  160.        }  
  161.   
  162.        /* 
  163.         * 发送 KOBJ_ADD / KOBJ_REMOVE 等事件 
  164.         * We are always responsible for sending the uevent that the kobject 
  165.         * was added to the system. 
  166.         */  
  167.        kobject_uevent(&foo->kobj, KOBJ_ADD);  
  168.   
  169.        return foo;  
  170. }  
  171.   
  172. static void destroy_foo_obj(struct foo_obj *foo)  
  173. {  
  174.     /* 减小kobj的引用计数 */  
  175.        kobject_put(&foo->kobj);  
  176. }  
  177.   
  178. static int __init example_init(void)  
  179. {  
  180.        /* 
  181.         * 动态地在kernel_kobj所对应的目录/sys/kernel/下创建一个目录kset_example 
  182.         * 并返回kset_example对应的kset 
  183.         */  
  184.        example_kset = kset_create_and_add("kset_example", NULL, kernel_kobj);  
  185.        if (!example_kset)  
  186.               return -ENOMEM;  
  187.   
  188.        foo_obj = create_foo_obj("foo");  
  189.        if (!foo_obj)  
  190.               goto foo_error;  
  191.   
  192.        return 0;  
  193.   
  194. foo_error:  
  195.        return -EINVAL;  
  196. }  
  197.   
  198. static void __exit example_exit(void)  
  199. {  
  200.        destroy_foo_obj(foo_obj);  
  201.        kset_unregister(example_kset);  
  202. }  
  203.   
  204. module_init(example_init);  
  205. module_exit(example_exit);  
  206. MODULE_LICENSE("GPL");  
  207. MODULE_AUTHOR("Younger Liu <younger.liucn@gmail.com>");  
4          参考资料:
sysfs文件系统详解:http://blog.chinaunix.net/u1/55599/showart_1089096.html
sysfs.h源码详析:http://blog.chinaunix.net/u1/55599/showart_1091002.html
http://www.diybl.com/course/6_system/linux/Linuxjs/2008727/134055.html
第五: 利用内核模块添加系统调用

 操作系统的主要功能是为应用程序的运行创建良好的环境,为了达到这个目的,内核提供一系列具备预定功能的多内核函数,通过一组称为系统调用(system call)的接口呈现给用户。系统调用把应用程序的请求传给内核,调用相应的的内核函数完成所需的处理,将处理结果返回给应用程序,如果没有系统调用和内核函数,用户将不能编写大型应用程序。
Linux系统调用,包含了大部分常用系统调用和由系统调用派生出的的函数。

其步骤如下,

第一:增加系统调用号

在文件unistd_32.h或unistd_64.h(取决去您的机器是32位还是64位的)下,添加系统调用号,

比如:(最后一个系统调用号为348)

#define __NR_mysyscall  349

如果存在系统调用总数目宏,那么也需要修改系统调用号的数目(原来为349)

#define NR_syscalls 350

第二:实现int sys_yoursyscall()系统调用

新增一个系统调用就意味着要给内核增加1个函数,将新函数放入文件kernel/sys.c中(当然你也可以新增一个文件,那么就必须将新增文件添加到Makefile文件中使得随着内核一起编译)。新函数代码如下:

asmlingkage sys_testsyscall()
{
    ……
    return 0;
}

第三:内核编译及重启

(2.6.32之后标准linux内核版本编译)

make clean;

make –j (-j表示并行编译,速度较快,但也会使得您的机器无法做其他工作)

make install

reboot

第四:测试新系统调用


第六:使用ioctl向linux内核传递参数的方法实例

一、应用层

uint16 data16;

if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)

{

    printf("socket failed\n\r");

}

if(ioctl(fd, SIOCSIFVLAN_PVID_PRI, &data16) < 0)

{

    printf("ioctl pvid failed\n\r");

}

 

二、linux内核

1  sockios.h中定义

 #define SIOCSIFVLAN_PVID_PRI     0x8985         /* Set 802.1Q VLAN pvid   */

 

2、在af_inet.c

     添加 

extern int VLAN1QEN(unsigned int ,void *arg);

inet_ioctl()函数中添加

    case SIOCSIFVLAN_PVID_PRI:

        return VLAN1QEN(cmd, arg);

 

3、另外定义:

 static unsigned int VLAN_PVID_PRI = 0;

int VLAN1QEN(unsigned int cmd,void *arg)

{

    unsigned int data;

    if (copy_from_user(&data, arg, sizeof(int)))

        return -EFAULT;

 

    switch (cmd) {

    case SIOCSIFVLAN_PVID_PRI:

        VLAN_PVID_PRI = data;

        break;

    default:

        return -EINVAL;

    }

}



本文转自:http://blog.csdn.net/younger_china/article/details/11181081






  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值