Sixth. First Linux driver: Count the number of words

Source: Internet
Author: User
Tags dmesg

Now that we've entered the actual combat phase, we've learned the complete process of developing and testing a Linux driver using an example of counting the number of words. The first Linux driver is a count of the number of words.

Instead of accessing the hardware, the Linux driver uses the device files as media to interact with the application by passing a space-delimited string to the device file, taking each space-separated substring as a word, and then reading from the device file the number of words that the string contains. Before you write this Linux driver, you need to do some preparatory work, first using the command

"# Mkdir-p/root/drivers/ch06/word_count

# cd/root/drivers/ch06/word_count "establishes the directory where the Linux drivers are stored. Then execute the command "# echo ' >word_count.c" to build the drive source code file. Finally write the Makefile file, executable command "# echo ' obj-m: = WORD_COUNT.O ' > Makefile", obj-m means to compile the Linux driver as a module with the suffix. Ko. The obj-y means that the Linux driver is compiled into the Linux kernel. The obj-m or obj-y need to be assigned with ": =" and their value is WORD_COUNT.O, which means that the make command compiles the word_count.c or Word_count.s in the Linux drive source code directory into WORD_COUNT.O. Use OBJ-M,WORD_COUNT.O will be connected to the Word_count.ko, then use the command insmod or modprobe load module Word_count.ko; use Obj-y,word_ The COUNT.O will be connected into the BUILT-IN.O and will eventually be connected to the kernel. BUILT-IN.O files are intermediate target files that are generated by the. o file that connects the same class of programs. All character device drivers eventually generate a BUILT-IN.O file that contains all the character drivers that can be connected to the Linux kernel, and the make Menuconfig command configures whether each driver and other kernel programs are allowed to be compiled into the kernel. If the Linux driver relies on other programs, such as PROCESS.C, DATA.C, you need to use the following command

"Obj-m: =WORD_COUNT.O

Word_count-y: =PROCESS.O DATA.O "writes the makefile file, where the dependent file is to be specified with module-y or MODULE-OBJS, and module represents the block name.

Write the skeleton of the Linux driver, that is, initialize and exit the driver function. It uses PRINTK (), which is used to output log information similar to the printf () usage. The Linux system divides the memory into user space and kernel space, and the programs of the two spaces cannot be accessed directly. printf runs in user space and PRINTK runs in kernel space, so Linux drivers that belong to kernel programs cannot access the printf function directly, even if the header file Stdio.h is included, the stdio.h error is thrown when compiling the Linux driver. Programs running in user space cannot call PRINTK directly. However, it is still possible to interact between programs running in user space and kernel space. Device files are a major form of interaction. If the user space program to access the kernel space, as long as a driver can access the kernel space, and then the user space program through the device file and the driver to interact. Linux drivers do not have direct access to programs running in user space, and many functions need to be implemented on their own. Use malloc in C to dynamically allocate memory space, but this function is not available in Linux drivers. This has to be a replacement in the Linux kernel. Each subdirectory in the <linux kernel source code >/include directory contains a large number of C language header files, in which the functions, macros, and other resources defined are substitutes for programs running in user space. The header file corresponding to the function library running in the user space in the/usr/include directory, such as the malloc function in the kernel space of the replacement is kmalloc, use it needs to contain the header file Slab.h. User space and kernel space to complete the same or similar functions, macros and other resources names are not necessarily the same, but may be similar, there are completely two different names, such as user space atoi and kernel space simple_strtol, And the itoa of the user space and the snprintf of the kernel space.

The

does not necessarily need to be done on Android devices when testing Linux drivers, because Android and Ubuntu and Linux distributions are based on the Linux kernel, Most Linux drivers can be tested on Ubuntu or other Linux distributions and then re-use the cross-compiler to generate an arm-based target file and then install it on Android to work properly. Compiling the Linux kernel source code requires the use of the Linux kernel's header files. In order to test the driver on Ubuntu, you need to specify the directory of the Linux kernel header file using the-C command line parameter,/usr/src/linux-headers-3.0.0-15-generic, Where the Linux-headers-3.0.0-15-generic directory is the Linux kernel source code directory, in order to develop the current Linux kernel version of the driver and other kernel programs provided, the directory only include subdirectories have actual header files, other directories only makefile and some other The configuration file does not contain the Linux kernel source code, because the target file generated when compiling the Linux driver only needs the header file, when the target file link, as long as the relevant target file, do not need source code files. If you compile the Linux driver in a modular way, you need to specify the directory where the driver is located, M=root/drivers/ch06/word_count. After you use the LS command to list files in the Word_count directory, you will find a few more. o and. Ko files, and some other files that are automatically generated by the compiler. Install the driver in kernel space, first enter the Word_count directory, use the command "# insmod Word_count.ko" To install the Linux driver, "# Lsmod | grep Word_count "To see if Word_count is installed successfully," # Rmmod Word_count "To uninstall the Linux driver, and to use the command" # DMESG | grep Word_count | Tail-n 2 "or" # Cat/var/log/syslog | grep Word_count | Tail-n 2 "View log information output by Linux drivers.

The

Specifies driver-related information, which is not required, but a complete Linux driver will specify these driver-related information, respectively: module author-using Module_author macro designation, module description-Using Module_ Description macro designation, module alias-specified with Module_alis macro, open source protocol-specified with Module_license macro. In addition to this information, you can use the command "# Modinfo Word_count.ko" To view word_count.ko information, which can also be placed in the form of code at the end of the word_count.c file. Then recompile, then execute the modinfo command, and the above code sets the information contained in the Word_count.ko.

To reduce the difficulty of publishing Linux drivers and to install package sizes, many Linux drivers are open source. Use the Module_license macro in the Linux driver source code to specify the open source protocol. The most common open source protocols are 5: The ①GPL protocol: the Linux kernel uses the GPL, the GPL's starting point is free open source, but unlike other open source agreements, the GPL is more thorough open source. Not only is the GPL software open source, but it also requires that its derived code is free and "contagious". Because the GPL requires software products that use the GPL protocol to use the GPL and must be open source for free, it is not appropriate for the department to use the GPL or to refer to the GPL-based class library for commercial or code-confidential applications. In order to meet the needs of commercial companies and confidentiality, the subsequent agreement ②LGPL protocol is open source protocol designed for use in the class library, its derivative protocol is not necessary to adopt the Protocol, LGPL allows commercial software to use the class library Reference way LGPL class library without the need of open source commercial software code, This allows open source code with the LGPL protocol to be referenced and published and sold as a class library by commercial software. However, to modify the code or derivation of the LGPL protocol, you need to modify all the code, and the additional code involved in the modification and the derived code must adopt the LGPL protocol. The open source code of the LGPL agreement is suitable as a third party class library to be referenced by commercial software, but it is not suitable to use the LGPL protocol code as the basis for two times development of commercial software by modifying and deriving the ③BSD agreement gives the user a large free agreement, can be used freely, modify the source code, You can also post the modified code as open source or proprietary software. However, when releasing code that uses the BSD protocol, or developing its own product two times based on the BSD protocol code, there are 3 conditions: (1) The re-release of the product contains the source code, then in the source code must be with the BSD protocol in the original Code (2) re-released only binary class library/software, need in the class library/ The documentation and copyright notices in the software contain the BSD Protocol (3) in the original code and cannot be marketed by the author/organization name of the open source code and the name of the original product. The BSD protocol encourages code sharing, but must respect the copyright of the source code author. The ④apache Licence2.0 protocol is similar to BSD, allowing the code to be modified and re-released, with similar conditions, (1) requiring the user of the code a copy of Apache Licence (2) If the code is modified, it needs to be described in the modified file (3) In the derived code, it is necessary to include in the original code the Agreement, the trademark, the patent statement and other instructions required by the original author (4) The re-release of the product contains a notice file, the file needs to have Apache Licence, You can also add your own license ⑤mit agreement to restrict loose license agreements that must beThe release contains a statement of the original license agreement, either binary or source code release.

Registering and Unregistering device files: to drive Word_count to establish a device file-wordcount. Device files are different from normal files and cannot be established using IO functions, you need to use Misc_register () to set up device files and use Misc_deregister () to unregister device files. It is generally necessary to set up a device file when initializing Linux drivers and delete the device files when uninstalling Linux drivers. The device file also requires a struct to describe its associated information. There is a member variable fops in the Miscdevice struct that describes the function pointer of the device file in various triggering events, and the data type of the member variable is also a struct file_operations.

Need to modify word_count.c, writing code should note: The device file is described by the main device number and the secondary device number. Instead, use Misc_register () to set only the secondary device number. The master device number is set to 10, which is a simple character device with common features in a Linux system. This type of device is called a misc device. The secondary device number can be specified or dynamically generated, you need to specify Misc_dynamic_minor constants in such a way that you can use Misc_register and misc_deregister to simplify the process of registering and unregistering device files. You can use Register_chrdev_region and alloc_chrdev_region to specify both the main device number and the secondary device number to register and unregister the device file; The value of the Miscdevice.name variable is the name of the device file; file_ Multiple callback function pointer variables are defined in the operations struct, only the File_operations.owner variable is initialized, and if the value of the variable is a module struct, it represents file_ The operations can be used in these driver modules specified by the module. If the value of the owner variable is this_module, the file_operations is only applied to the current driver module, if the device file is successfully registered, Misc_register returns an integer other than 0, and if the registration fails, returns 0;WORD_ All functions and variables in COUNT.C are declared static, and these functions and variables are placed in a separate area of memory until the program exits completely, otherwise these resources will not be freed. Once the Linux driver is loaded, the driver will always reside in memory unless manually uninstalled or shut down, and these functions and variable resources will also be in memory. , that is, multiple calls to these resources do not have to stack, out of the stack operation, is conducive to improve the operating efficiency of the drive. After writing, you need to recompile the word_count.c and install the Word_count driver using the following command "# Insmod Word_count.ko". If the driver is installed, you should first use the command "# rmmod Word_count" To download the driver, and then use the Insmod command to install the driver. After the driver is installed, execute the command "# ls-a/dev" To view the devices in the/dev directory. After executing the command, there will be one more file named WordCount. Use the command "# ls-l/dev" To view the main device number and the secondary device number of the WordCount device file. After executing the above command, the first number in the white box is the main device number, and the second number is from the device number. Use the command "# cat/proc/devices" to see which main devices and main device numbers are in the current system.

Specify the callback function: No matter how complex the Linux driver is, it makes sense to allow user-space applications to interact with kernel-space drivers. The most common way to interact is to read and write device files. The File_operations.read and File_operations.write member variables specify the callback function pointer to be invoked by the read-write device file, respectively. To add two functions for word_count.c: Word_count_read and Word_count_write, respectively, handle the actions of reading data from a device file and writing data to a device file. The function of an instance is to write data to the device file/dev/wordcount, which can be read from the/dev/wordcount device file, but only once. It is important to note that the parameters of Word_count_read and word_count_write are basically the same, with only a slight difference in the 2nd parameter buf. The BUF parameter type of word_count_read is the const char* of the Char*,word_count_write buf parameter type, meaning that the parameter values in Word_count_write cannot be modified. Word_count_read its parameters represent the data that is read from the device file and how much data is read, depending on the return value of the Word_count_read. The BUF in Word_count_write represents the data written by the application of the user space. The BUF parameter has a _user macro that indicates that the memory area of BUF is in user space, and because kernel space programs do not have direct access to data in the user space, they need to be used in Word_count_read and Word_count_write respectively Copy_to_ The user and Copy_from_user functions copy data from the kernel space to the user space or vice versa, write the data once, and once the data is read, no more data can be read from the device file the second time, unless the data is written again. This is controlled by the Read_flag variable with a value of N, indicating that the device file has not been read and the data is read normally in Word_count_read. If the value of the variable is Y, it means that the data in the device file has been read, the Word_count_read return value is 0, the application cannot read any data, and the Count parameter in Word_count_read represents the number of bytes read from the device file. Test drive with the Cat command always reads 32768 bytes. The number of bytes written in Word_count_write needs to be saved, the number of bytes written directly in the Word_count_read, i.e. how many bytes are written, how many bytes are read, and all the data writtenstored in the MEM array, the array defines 10,000 characters, so the number of bytes written cannot exceed 10000, otherwise it will overflow. If you test the Word_count driver on the s3c6410 board and the Android emulator, you need to execute the shell.sh script file or the ADB shell command into the terminal of the corresponding platform. The shell.sh script is in the/root/drivers directory. The difference between the two is that if there are multiple Android devices connected to the PC, the script will have a selection menu, which allows the user to choose which Android device terminal to enter, while the ADB The shell command must have the-s command line parameter specify the ID of the Android device to enter the terminal of the corresponding Android device.

Algorithm to implement statistical word count: Start writing Word_count-driven business logic-count words. The algorithm consists of a space, a tab, a carriage return, and a newline character that are counted as one word. The function that counts the number of words in the code is get_word_count. What you need to know is: Get_word_count the first character in the Mem array as the end of the string, and the value of Men[count] in Word_count_write will be "" ", otherwise Get_word_ Count will not know where to end the string to count the number of words. The mem array has a length of 10000, and the last character of the string is "s", so the maximum length of the string to be counted is 9999; the number of words is stored using the INT type variable. In Word_count_write, the number of words is counted, and in Word_count_read the word_count integer variable is decomposed into 4 bytes stored in buf, and the 4 bytes in the application need to be combined into values of type int. The driver is all written and completed.

compiling, installing, and uninstalling Linux drivers: The Word_count driver, like the drivers in the Read_write directory, also has a build.sh script file and 3 platform-related script files. Execute the build.sh script file and select the compiled platform. Execute command

"# DMESG | Tail-n 1

# modinfo Word_count.ko "View log output information and Word_count driver module information. Install Linux drivers using the Insmod command, or use the Modprobe command. The difference between Insmod and modprobe is that modprobe can check the dependency of the driver module. If a module relies on a b module, a B must be loaded before loading a. An error occurs when loading a module with Insmod. Use the Depmod command "# Depmod/root/drivers/ch06/word_count/word_count.ko" to detect the dependencies of the Linux driver module before using Modprobe to load the drive module. Depmod actually adds the Linux driver module file to the file "/LIB/MODULES/3.0.0-16-GENERIC.DEP". After you have detected the dependency with the Depmod command, you can call the Modprobe command "# modprobe Word_count" to load the Linux driver. Use the above two commands to note that: Depmod must use the absolute path of the Linux driver module; Depmod writes the dependency information of the kernel module to the MODULES.DEP file of the kernel that is currently in use; Modprobe simply uses the driver name and does not need to follow. Ko.

Sixth. First Linux driver: Count the number of words

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.