├── .gitignore ├── LICENSE ├── README.md ├── chapter_01 ├── .gitignore └── helloworld.c ├── chapter_02 ├── add_custom_code.patch ├── module │ ├── Makefile │ └── dummy-code.c └── module_par │ ├── Makefile │ └── module_par.c ├── chapter_03 ├── .gitignore ├── chrdev_legacy │ ├── Makefile │ ├── chrdev_legacy.c │ └── modify_read_write_to_chrdev_legacy.patch ├── chrdev_test.c └── modify_close_open_to_chrdev_test.patch ├── chapter_04 ├── chrdev │ ├── Makefile │ ├── add_chrdev_devices.dts.patch │ ├── add_fixed_chrdev_devices.patch │ ├── add_sysfs_attrs_chrdev.patch │ ├── chrdev-fw.c │ ├── chrdev-req.c │ ├── chrdev.c │ └── chrdev.h ├── get_dt_data │ ├── Makefile │ └── get_dt_data.c └── simple_platform │ ├── .gitignore │ └── simple_platform.dts ├── chapter_05 ├── add_irqtest_module.patch ├── add_tasklet_2_to_irqtest_module.patch ├── add_tasklet_to_irqtest_module.patch ├── add_workqueue_2_to_irqtest_module.patch ├── add_workqueue_to_irqtest_module.patch ├── atomic │ ├── Makefile │ ├── atomic.c │ ├── mutex.c │ └── spinlock.c ├── notifier │ ├── Makefile │ ├── hires_timer.c │ └── notifier.c ├── timer │ ├── Makefile │ ├── hires_timer.c │ └── ktimer.c └── wait_event │ ├── Makefile │ ├── completion.c │ └── waitqueue.c ├── chapter_06 ├── data_types │ ├── Makefile │ └── data_types.c ├── hashtable │ ├── Makefile │ └── hashtable.c ├── helper_funcs │ ├── Makefile │ └── helper_funcs.c ├── list │ ├── Makefile │ └── list.c ├── mem_alloc │ ├── Makefile │ └── mem_alloc.c └── time │ ├── Makefile │ └── time.c └── chapter_07 ├── .gitignore ├── chrdev ├── Makefile ├── add_mutex_to_chrdev.patch ├── chrdev-req.c ├── chrdev.c ├── chrdev.h ├── chrdev_ioctl.h ├── chrdev_irq.c ├── chrdev_irq.h └── modify_lseek_to_chrdev_test.patch ├── chrdev_fasync.c ├── chrdev_ioctl.c ├── chrdev_mmap.c └── chrdev_select.c /.gitignore: -------------------------------------------------------------------------------- 1 | .tmp_versions/ 2 | *.o 3 | *.ko 4 | *.mod.c 5 | *.o.cmd 6 | *.ko.cmd 7 | Module.symvers 8 | modules.order 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Linux Device Driver Development Cookbook 2 | ======================================== 3 | 4 | Here the code from the book "Linux Device Driver Development Cookbook" 5 | written by Rodolfo Giometti and published by Packt 6 | Publishing (ISBN 978-1-83855-880-2). 7 | 8 | These code examples are presented into the book in order to explain to 9 | the reader how to implements the several projects presented into the 10 | book. 11 | 12 | See the URL 13 | https://www.packtpub.com/hardware-and-creative/ 14 | for further info. 15 | 16 | License 17 | ------- 18 | 19 | When not specified into each file header, all the code is published 20 | with the GNU General Public License Version 2 as reported into file 21 | LICENSE in the root directory of this repository. 22 | 23 | Downloading/updating the code 24 | ----------------------------- 25 | 26 | To get the latest version of this example codes just use the command: 27 | 28 | $ git clone https://github.com/giometti/linux_device_driver_development_cookbook.git 29 | 30 | Or, if you have an older version or you are using the Packt 31 | Publishing's code bundle and you think it's not updated, you can get 32 | the latest version by using the command: 33 | 34 | $ cd 35 | $ git pull 36 | 37 | Enjoy! :-) 38 | -------------------------------------------------------------------------------- /chapter_01/.gitignore: -------------------------------------------------------------------------------- 1 | hardcopy.0 2 | helloworld 3 | helloworld.x86_64 4 | -------------------------------------------------------------------------------- /chapter_01/helloworld.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc, char *argv[]) 4 | { 5 | printf("Hello World!\n"); 6 | 7 | return 0; 8 | } 9 | -------------------------------------------------------------------------------- /chapter_02/add_custom_code.patch: -------------------------------------------------------------------------------- 1 | diff --git a/drivers/misc/Kconfig b/drivers/misc/Kconfig 2 | index 3726eacdf65d..64aa35c08eee 100644 3 | --- a/drivers/misc/Kconfig 4 | +++ b/drivers/misc/Kconfig 5 | @@ -527,4 +527,10 @@ source "drivers/misc/echo/Kconfig" 6 | source "drivers/misc/cxl/Kconfig" 7 | source "drivers/misc/ocxl/Kconfig" 8 | source "drivers/misc/cardreader/Kconfig" 9 | + 10 | +config DUMMY_CODE 11 | + tristate "Dummy code" 12 | + default n 13 | + ---help--- 14 | + This module is just for demonstration purposes. 15 | endmenu 16 | diff --git a/drivers/misc/Makefile b/drivers/misc/Makefile 17 | index af22bbc3d00c..47ee613df600 100644 18 | --- a/drivers/misc/Makefile 19 | +++ b/drivers/misc/Makefile 20 | @@ -58,3 +58,4 @@ obj-$(CONFIG_ASPEED_LPC_SNOOP) += aspeed-lpc-snoop.o 21 | obj-$(CONFIG_PCI_ENDPOINT_TEST) += pci_endpoint_test.o 22 | obj-$(CONFIG_OCXL) += ocxl/ 23 | obj-$(CONFIG_MISC_RTSX) += cardreader/ 24 | +obj-$(CONFIG_DUMMY_CODE) += dummy-code.o 25 | diff --git a/drivers/misc/dummy-code.c b/drivers/misc/dummy-code.c 26 | new file mode 100644 27 | index 000000000000..c1bbbdfed873 28 | --- /dev/null 29 | +++ b/drivers/misc/dummy-code.c 30 | @@ -0,0 +1,23 @@ 31 | +/* 32 | + * Dummy code 33 | + */ 34 | + 35 | +#include 36 | + 37 | +static int __init dummy_code_init(void) 38 | +{ 39 | + printk(KERN_INFO "dummy-code loaded\n"); 40 | + return 0; 41 | +} 42 | + 43 | +static void __exit dummy_code_exit(void) 44 | +{ 45 | + printk(KERN_INFO "dummy-code unloaded\n"); 46 | +} 47 | + 48 | +module_init(dummy_code_init); 49 | +module_exit(dummy_code_exit); 50 | + 51 | +MODULE_LICENSE("GPL"); 52 | +MODULE_AUTHOR("Rodolfo Giometti"); 53 | +MODULE_DESCRIPTION("Dummy code"); 54 | -------------------------------------------------------------------------------- /chapter_02/module/Makefile: -------------------------------------------------------------------------------- 1 | ifndef KERNEL_DIR 2 | $(error KERNEL_DIR must be set in the command line) 3 | endif 4 | PWD := $(shell pwd) 5 | ARCH ?= arm64 6 | CROSS_COMPILE ?= aarch64-linux-gnu- 7 | 8 | # This specifies the kernel module to be compiled 9 | obj-m += dummy-code.o 10 | 11 | # The default action 12 | all: modules 13 | 14 | # The main tasks 15 | modules clean: 16 | make -C $(KERNEL_DIR) \ 17 | ARCH=$(ARCH) \ 18 | CROSS_COMPILE=$(CROSS_COMPILE) \ 19 | SUBDIRS=$(PWD) $@ 20 | -------------------------------------------------------------------------------- /chapter_02/module/dummy-code.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Dummy code 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | 8 | static int __init dummy_code_init(void) 9 | { 10 | pr_info("dummy-code loaded\n"); 11 | return 0; 12 | } 13 | 14 | static void __exit dummy_code_exit(void) 15 | { 16 | pr_info("dummy-code unloaded\n"); 17 | } 18 | 19 | module_init(dummy_code_init); 20 | module_exit(dummy_code_exit); 21 | 22 | MODULE_LICENSE("GPL"); 23 | MODULE_AUTHOR("Rodolfo Giometti"); 24 | MODULE_DESCRIPTION("Dummy code"); 25 | -------------------------------------------------------------------------------- /chapter_02/module_par/Makefile: -------------------------------------------------------------------------------- 1 | ifndef KERNEL_DIR 2 | $(error KERNEL_DIR must be set in the command line) 3 | endif 4 | PWD := $(shell pwd) 5 | ARCH ?= arm64 6 | CROSS_COMPILE ?= aarch64-linux-gnu- 7 | 8 | # This specifies the kernel module to be compiled 9 | obj-m += module_par.o 10 | 11 | # The default action 12 | all: modules 13 | 14 | # The main tasks 15 | modules clean: 16 | make -C $(KERNEL_DIR) \ 17 | ARCH=$(ARCH) \ 18 | CROSS_COMPILE=$(CROSS_COMPILE) \ 19 | SUBDIRS=$(PWD) $@ 20 | -------------------------------------------------------------------------------- /chapter_02/module_par/module_par.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Module with parameters 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | 9 | static int var = 0x3f; 10 | module_param(var, int, S_IRUSR | S_IWUSR); 11 | MODULE_PARM_DESC(var, "an integer value"); 12 | 13 | static char *str = "default string"; 14 | module_param(str, charp, S_IRUSR | S_IWUSR); 15 | MODULE_PARM_DESC(str, "a string value"); 16 | 17 | #define ARR_SIZE 8 18 | static int arr[ARR_SIZE]; 19 | static int arr_count; 20 | module_param_array(arr, int, &arr_count, S_IRUSR | S_IWUSR); 21 | MODULE_PARM_DESC(arr, "an array of " __stringify(ARR_SIZE) " values"); 22 | 23 | /* 24 | * Init & exit stuff 25 | */ 26 | 27 | static int __init module_par_init(void) 28 | { 29 | int i; 30 | 31 | pr_info("loaded\n"); 32 | pr_info("var = 0x%02x\n", var); 33 | pr_info("str = \"%s\"\n", str); 34 | pr_info("arr = "); 35 | for (i = 0; i < ARR_SIZE; i++) 36 | pr_cont("%d ", arr[i]); 37 | pr_cont("\n"); 38 | 39 | return 0; 40 | } 41 | 42 | static void __exit module_par_exit(void) 43 | { 44 | pr_info("unloaded\n"); 45 | } 46 | 47 | module_init(module_par_init); 48 | module_exit(module_par_exit); 49 | 50 | MODULE_LICENSE("GPL"); 51 | MODULE_AUTHOR("Rodolfo Giometti"); 52 | MODULE_DESCRIPTION("Module with parameters"); 53 | MODULE_VERSION("0.1"); 54 | -------------------------------------------------------------------------------- /chapter_03/.gitignore: -------------------------------------------------------------------------------- 1 | chrdev_test 2 | -------------------------------------------------------------------------------- /chapter_03/chrdev_legacy/Makefile: -------------------------------------------------------------------------------- 1 | ifndef KERNEL_DIR 2 | $(error KERNEL_DIR must be set in the command line) 3 | endif 4 | PWD := $(shell pwd) 5 | ARCH ?= arm64 6 | CROSS_COMPILE ?= aarch64-linux-gnu- 7 | 8 | obj-m = chrdev_legacy.o 9 | 10 | all: modules 11 | 12 | modules clean: 13 | make -C $(KERNEL_DIR) \ 14 | ARCH=$(ARCH) \ 15 | CROSS_COMPILE=$(CROSS_COMPILE) \ 16 | SUBDIRS=$(PWD) $@ 17 | -------------------------------------------------------------------------------- /chapter_03/chrdev_legacy/chrdev_legacy.c: -------------------------------------------------------------------------------- 1 | /* 2 | * chrdev legacy 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | 10 | /* Device major umber */ 11 | static int major; 12 | 13 | /* 14 | * Methods 15 | */ 16 | 17 | static ssize_t chrdev_read(struct file *filp, 18 | char __user *buf, size_t count, loff_t *ppos) 19 | { 20 | pr_info("return EOF\n"); 21 | 22 | return 0; 23 | } 24 | 25 | static ssize_t chrdev_write(struct file *filp, 26 | const char __user *buf, size_t count, loff_t *ppos) 27 | { 28 | pr_info("got %ld bytes\n", count); 29 | 30 | *ppos += count; 31 | return count; 32 | } 33 | 34 | static int chrdev_open(struct inode *inode, struct file *filp) 35 | { 36 | pr_info("chrdev opened\n"); 37 | 38 | return 0; 39 | } 40 | 41 | static int chrdev_release(struct inode *inode, struct file *filp) 42 | { 43 | pr_info("chrdev released\n"); 44 | 45 | return 0; 46 | } 47 | 48 | static struct file_operations chrdev_fops = { 49 | .owner = THIS_MODULE, 50 | .read = chrdev_read, 51 | .write = chrdev_write, 52 | .open = chrdev_open, 53 | .release = chrdev_release 54 | }; 55 | 56 | /* 57 | * Module stuff 58 | */ 59 | 60 | static int __init chrdev_init(void) 61 | { 62 | int ret; 63 | 64 | ret = register_chrdev(0, "chrdev", &chrdev_fops); 65 | if (ret < 0) { 66 | pr_err("unable to register char device! Error %d\n", ret); 67 | return ret; 68 | } 69 | major = ret; 70 | pr_info("got major %d\n", major); 71 | 72 | return 0; 73 | } 74 | 75 | static void __exit chrdev_exit(void) 76 | { 77 | unregister_chrdev(major, "chrdev"); 78 | } 79 | 80 | module_init(chrdev_init); 81 | module_exit(chrdev_exit); 82 | 83 | MODULE_LICENSE("GPL"); 84 | MODULE_AUTHOR("Rodolfo Giometti"); 85 | MODULE_DESCRIPTION("chrdev legacy"); 86 | -------------------------------------------------------------------------------- /chapter_03/chrdev_legacy/modify_read_write_to_chrdev_legacy.patch: -------------------------------------------------------------------------------- 1 | diff --git a/chapter_3/chrdev_legacy/chrdev_legacy.c b/chapter_3/chrdev_legacy/chrdev_legacy.c 2 | index 2fc25bc..401df1a 100644 3 | --- a/chapter_3/chrdev_legacy/chrdev_legacy.c 4 | +++ b/chapter_3/chrdev_legacy/chrdev_legacy.c 5 | @@ -6,10 +6,15 @@ 6 | #include 7 | #include 8 | #include 9 | +#include 10 | 11 | /* Device major umber */ 12 | static int major; 13 | 14 | +/* Device data */ 15 | +#define BUF_LEN 300 16 | +static char chrdev_buf[BUF_LEN]; 17 | + 18 | /* 19 | * Methods 20 | */ 21 | @@ -17,17 +22,44 @@ static int major; 22 | static ssize_t chrdev_read(struct file *filp, 23 | char __user *buf, size_t count, loff_t *ppos) 24 | { 25 | - pr_info("return EOF\n"); 26 | + int ret; 27 | 28 | - return 0; 29 | + pr_info("should read %ld bytes (*ppos=%lld)\n", count, *ppos); 30 | + 31 | + /* Check for end-of-buffer */ 32 | + if (*ppos + count >= BUF_LEN) 33 | + count = BUF_LEN - *ppos; 34 | + 35 | + /* Return data to the user space */ 36 | + ret = copy_to_user(buf, chrdev_buf + *ppos, count); 37 | + if (ret < 0) 38 | + return ret; 39 | + 40 | + *ppos += count; 41 | + pr_info("return %ld bytes (*ppos=%lld)\n", count, *ppos); 42 | + 43 | + return count; 44 | } 45 | 46 | static ssize_t chrdev_write(struct file *filp, 47 | const char __user *buf, size_t count, loff_t *ppos) 48 | { 49 | - pr_info("got %ld bytes\n", count); 50 | + int ret; 51 | + 52 | + pr_info("should write %ld bytes (*ppos=%lld)\n", count, *ppos); 53 | + 54 | + /* Check for end-of-buffer */ 55 | + if (*ppos + count >= BUF_LEN) 56 | + count = BUF_LEN - *ppos; 57 | + 58 | + /* Get data from the user space */ 59 | + ret = copy_from_user(chrdev_buf + *ppos, buf, count); 60 | + if (ret < 0) 61 | + return ret; 62 | + 63 | + *ppos += count; 64 | + pr_info("got %ld bytes (*ppos=%lld)\n", count, *ppos); 65 | 66 | - *ppos += count; 67 | return count; 68 | } 69 | 70 | -------------------------------------------------------------------------------- /chapter_03/chrdev_test.c: -------------------------------------------------------------------------------- 1 | /* 2 | * chrdev testing program 3 | */ 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | void dump(char *str, char *buf, int size) 14 | { 15 | int i; 16 | 17 | if (size <= 0) 18 | return; 19 | 20 | printf("%s", str); 21 | for (i = 0; i < size; i++) 22 | printf("%02x ", buf[i]); 23 | printf("\n"); 24 | } 25 | 26 | int main(int argc, char *argv[]) 27 | { 28 | int fd; 29 | char buf[] = "DUMMY DATA"; 30 | int n, c; 31 | int ret; 32 | 33 | if (argc < 2) { 34 | fprintf(stderr, "usage: %s \n", argv[0]); 35 | exit(EXIT_FAILURE); 36 | } 37 | 38 | ret = open(argv[1], O_RDWR); 39 | if (ret < 0) { 40 | perror("open"); 41 | exit(EXIT_FAILURE); 42 | } 43 | printf("file %s opened\n", argv[1]); 44 | fd = ret; 45 | 46 | for (c = 0; c < sizeof(buf); c += n) { 47 | ret = write(fd, buf + c, sizeof(buf) - c); 48 | if (ret < 0) { 49 | perror("write"); 50 | exit(EXIT_FAILURE); 51 | } 52 | n = ret; 53 | 54 | printf("wrote %d bytes into file %s\n", n, argv[1]); 55 | dump("data written are: ", buf + c, n); 56 | } 57 | 58 | for (c = 0; c < sizeof(buf); c += n) { 59 | ret = read(fd, buf, sizeof(buf)); 60 | if (ret == 0) { 61 | printf("read EOF\n"); 62 | break; 63 | } else if (ret < 0) { 64 | perror("read"); 65 | exit(EXIT_FAILURE); 66 | } 67 | n = ret; 68 | 69 | printf("read %d bytes from file %s\n", n, argv[1]); 70 | dump("data read are: ", buf, n); 71 | } 72 | 73 | close(fd); 74 | 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /chapter_03/modify_close_open_to_chrdev_test.patch: -------------------------------------------------------------------------------- 1 | diff --git a/chapter_3/chrdev_test.c b/chapter_3/chrdev_test.c 2 | index f72d4aa..7b5bc05 100644 3 | --- a/chapter_3/chrdev_test.c 4 | +++ b/chapter_3/chrdev_test.c 5 | @@ -55,6 +55,16 @@ int main(int argc, char *argv[]) 6 | dump("data written are: ", buf, n); 7 | } 8 | 9 | + close(fd); 10 | + 11 | + ret = open(argv[1], O_RDWR); 12 | + if (ret < 0) { 13 | + perror("open"); 14 | + exit(EXIT_FAILURE); 15 | + } 16 | + printf("file %s reopened\n", argv[1]); 17 | + fd = ret; 18 | + 19 | for (c = 0; c < sizeof(buf); c += n) { 20 | ret = read(fd, buf, sizeof(buf)); 21 | if (ret == 0) { 22 | -------------------------------------------------------------------------------- /chapter_04/chrdev/Makefile: -------------------------------------------------------------------------------- 1 | ifndef KERNEL_DIR 2 | $(error KERNEL_DIR must be set in the command line) 3 | endif 4 | PWD := $(shell pwd) 5 | ARCH ?= arm64 6 | CROSS_COMPILE ?= aarch64-linux-gnu- 7 | 8 | obj-m = chrdev.o 9 | obj-m += chrdev-req.o 10 | 11 | all: modules 12 | 13 | modules clean: 14 | make -C $(KERNEL_DIR) \ 15 | ARCH=$(ARCH) \ 16 | CROSS_COMPILE=$(CROSS_COMPILE) \ 17 | SUBDIRS=$(PWD) $@ 18 | -------------------------------------------------------------------------------- /chapter_04/chrdev/add_chrdev_devices.dts.patch: -------------------------------------------------------------------------------- 1 | diff --git a/arch/arm64/boot/dts/marvell/armada-3720-espressobin.dts b/arch/arm64/boot/dts/marvell/armada-3720-espressobin.dts 2 | index 3ab25ad402b9..71e7f4336a56 100644 3 | --- a/arch/arm64/boot/dts/marvell/armada-3720-espressobin.dts 4 | +++ b/arch/arm64/boot/dts/marvell/armada-3720-espressobin.dts 5 | @@ -41,6 +41,23 @@ 6 | 3300000 0x0>; 7 | enable-active-high; 8 | }; 9 | + 10 | + chrdev { 11 | + compatible = "ldddc,chrdev"; 12 | + #address-cells = <1>; 13 | + #size-cells = <0>; 14 | + 15 | + chrdev@2 { 16 | + label = "cdev-eeprom"; 17 | + reg = <2>; 18 | + }; 19 | + 20 | + chrdev@4 { 21 | + label = "cdev-rom"; 22 | + reg = <4>; 23 | + read-only; 24 | + }; 25 | + }; 26 | }; 27 | 28 | /* J9 */ 29 | -------------------------------------------------------------------------------- /chapter_04/chrdev/add_fixed_chrdev_devices.patch: -------------------------------------------------------------------------------- 1 | diff --git a/chapter_4/chrdev/chrdev-req.c b/chapter_4/chrdev/chrdev-req.c 2 | index 653176d..2048cd8 100644 3 | --- a/chapter_4/chrdev/chrdev-req.c 4 | +++ b/chapter_4/chrdev/chrdev-req.c 5 | @@ -9,10 +9,24 @@ 6 | #include 7 | #include 8 | #include 9 | +#include 10 | #include 11 | 12 | #include "chrdev.h" 13 | 14 | +/* 15 | + * Fixed data 16 | + */ 17 | + 18 | +static const struct chrdev_fixed_data chrdev_fd = { 19 | + .label = "cdev-fixed", 20 | +}; 21 | + 22 | +static const struct chrdev_fixed_data chrdev_fd_ro = { 23 | + .label = "cdev-fixedro", 24 | + .read_only = 1, 25 | +}; 26 | + 27 | /* 28 | * Platform driver stuff 29 | */ 30 | @@ -20,10 +34,26 @@ 31 | static int chrdev_req_probe(struct platform_device *pdev) 32 | { 33 | struct device *dev = &pdev->dev; 34 | + struct device_node *np = dev->of_node; 35 | + const struct chrdev_fixed_data *data = of_device_get_match_data(dev); 36 | struct fwnode_handle *child; 37 | struct module *owner = THIS_MODULE; 38 | int count, ret; 39 | 40 | + /* Check the chrdev device type */ 41 | + if (of_device_is_compatible(np, "ldddc,chrdev-fixed") || 42 | + of_device_is_compatible(np, "ldddc,chrdev-fixed_read-only")) { 43 | + ret = chrdev_device_register(data->label, 0, 44 | + data->read_only, owner, dev); 45 | + if (ret) 46 | + dev_err(dev, "unable to register fixed"); 47 | + 48 | + return ret; 49 | + } 50 | + 51 | + /* If we are not registering a fixed chrdev device then get 52 | + * the number of chrdev devices from DTS 53 | + */ 54 | count = device_get_child_node_count(dev); 55 | if (count == 0) 56 | return -ENODEV; 57 | @@ -65,9 +95,24 @@ static int chrdev_req_probe(struct platform_device *pdev) 58 | static int chrdev_req_remove(struct platform_device *pdev) 59 | { 60 | struct device *dev = &pdev->dev; 61 | + struct device_node *np = dev->of_node; 62 | + const struct chrdev_fixed_data *data = of_device_get_match_data(dev); 63 | struct fwnode_handle *child; 64 | int ret; 65 | 66 | + /* Check the chrdev device type */ 67 | + if (of_device_is_compatible(np, "ldddc,chrdev-fixed") || 68 | + of_device_is_compatible(np, "ldddc,chrdev-fixed_read-only")) { 69 | + ret = chrdev_device_unregister(data->label, 0); 70 | + if (ret) 71 | + dev_err(dev, "unable to unregister"); 72 | + 73 | + return ret; 74 | + } 75 | + 76 | + /* If we are not unregistering a fixed chrdev device then get 77 | + * the number of chrdev devices from DTS 78 | + */ 79 | device_for_each_child_node(dev, child) { 80 | const char *label; 81 | int id; 82 | @@ -98,6 +143,14 @@ static const struct of_device_id of_chrdev_req_match[] = { 83 | { 84 | .compatible = "ldddc,chrdev", 85 | }, 86 | + { 87 | + .compatible = "ldddc,chrdev-fixed", 88 | + .data = &chrdev_fd, 89 | + }, 90 | + { 91 | + .compatible = "ldddc,chrdev-fixed_read-only", 92 | + .data = &chrdev_fd_ro, 93 | + }, 94 | { /* sentinel */ } 95 | }; 96 | MODULE_DEVICE_TABLE(of, of_chrdev_req_match); 97 | diff --git a/chapter_4/chrdev/chrdev.h b/chapter_4/chrdev/chrdev.h 98 | index 9498467..0b5a334 100644 99 | --- a/chapter_4/chrdev/chrdev.h 100 | +++ b/chapter_4/chrdev/chrdev.h 101 | @@ -25,6 +25,12 @@ struct chrdev_device { 102 | struct device *dev; 103 | }; 104 | 105 | +struct chrdev_fixed_data { 106 | + char *label; 107 | + int read_only; 108 | +}; 109 | + 110 | + 111 | /* 112 | * Exported functions 113 | */ 114 | -------------------------------------------------------------------------------- /chapter_04/chrdev/add_sysfs_attrs_chrdev.patch: -------------------------------------------------------------------------------- 1 | diff --git a/chapter_4/chrdev/chrdev.c b/chapter_4/chrdev/chrdev.c 2 | index c9db2b6..2cb6a54 100644 3 | --- a/chapter_4/chrdev/chrdev.c 4 | +++ b/chapter_4/chrdev/chrdev.c 5 | @@ -19,6 +19,78 @@ static struct class *chrdev_class; 6 | 7 | struct chrdev_device chrdev_array[MAX_DEVICES]; 8 | 9 | +/* 10 | + * sysfs methods 11 | + */ 12 | + 13 | +static ssize_t id_show(struct device *dev, 14 | + struct device_attribute *attr, char *buf) 15 | +{ 16 | + struct chrdev_device *chrdev = dev_get_drvdata(dev); 17 | + 18 | + return sprintf(buf, "%d\n", chrdev->id); 19 | +} 20 | +static DEVICE_ATTR_RO(id); 21 | + 22 | +static ssize_t reset_to_store(struct device *dev, 23 | + struct device_attribute *attr, 24 | + const char *buf, size_t count) 25 | +{ 26 | + struct chrdev_device *chrdev = dev_get_drvdata(dev); 27 | + 28 | + if (count > BUF_LEN) 29 | + count = BUF_LEN; 30 | + memcpy(chrdev->buf, buf, count); 31 | + 32 | + return count; 33 | +} 34 | +static DEVICE_ATTR_WO(reset_to); 35 | + 36 | +static ssize_t read_only_show(struct device *dev, 37 | + struct device_attribute *attr, char *buf) 38 | +{ 39 | + struct chrdev_device *chrdev = dev_get_drvdata(dev); 40 | + 41 | + return sprintf(buf, "%d\n", chrdev->read_only); 42 | +} 43 | + 44 | +static ssize_t read_only_store(struct device *dev, 45 | + struct device_attribute *attr, 46 | + const char *buf, size_t count) 47 | +{ 48 | + struct chrdev_device *chrdev = dev_get_drvdata(dev); 49 | + int data, ret; 50 | + 51 | + ret = sscanf(buf, "%d", &data); 52 | + if (ret != 1) 53 | + return -EINVAL; 54 | + 55 | + chrdev->read_only = !!data; 56 | + 57 | + return count; 58 | +} 59 | +static DEVICE_ATTR_RW(read_only); 60 | + 61 | +/* 62 | + * Class attributes 63 | + */ 64 | + 65 | +static struct attribute *chrdev_attrs[] = { 66 | + &dev_attr_id.attr, 67 | + &dev_attr_reset_to.attr, 68 | + &dev_attr_read_only.attr, 69 | + NULL, 70 | +}; 71 | + 72 | +static const struct attribute_group chrdev_group = { 73 | + .attrs = chrdev_attrs, 74 | +}; 75 | + 76 | +static const struct attribute_group *chrdev_groups[] = { 77 | + &chrdev_group, 78 | + NULL, 79 | +}; 80 | + 81 | /* 82 | * Methods 83 | */ 84 | @@ -216,6 +288,7 @@ static int __init chrdev_init(void) 85 | pr_err("chrdev: failed to allocate class\n"); 86 | return -ENOMEM; 87 | } 88 | + chrdev_class->dev_groups = chrdev_groups; 89 | 90 | /* Allocate a region for character devices */ 91 | ret = alloc_chrdev_region(&chrdev_devt, 0, MAX_DEVICES, "chrdev"); 92 | -------------------------------------------------------------------------------- /chapter_04/chrdev/chrdev-fw.c: -------------------------------------------------------------------------------- 1 | /* 2 | * chrdev req 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | #include "chrdev.h" 17 | 18 | #define FIRMWARE_VER "1.0.0" 19 | #define FIRMWARE_NLEN 128 20 | 21 | static inline char printable(char c) 22 | { 23 | return (c < ' ') || (c > '~') ? '-' : c; 24 | } 25 | 26 | static void dump_data(const u8 *buf, size_t len) 27 | { 28 | int n, i; 29 | 30 | for (n = 0; n < len; n += i) { 31 | pr_info(""); 32 | for (i = 0; (i < 8) && (n + i < len); i++) 33 | pr_cont("%02x[%c] ", buf[n + i], printable(buf[n + i])); 34 | pr_cont("\n"); 35 | } 36 | } 37 | 38 | /* 39 | * Firmware loading callback 40 | */ 41 | 42 | static void chrdev_fw_cb(const struct firmware *fw, void *context) 43 | { 44 | struct device *dev = context; 45 | 46 | dev_info(dev, "firmware callback executed!\n"); 47 | if (!fw) { 48 | dev_err(dev, "unable to load firmware\n"); 49 | return; 50 | } 51 | 52 | dump_data(fw->data, fw->size); 53 | 54 | /* Firmware data has been read, now we can release it */ 55 | release_firmware(fw); 56 | } 57 | 58 | /* 59 | * Firmware loading functions 60 | */ 61 | 62 | static int chrdev_load_fw_wait(struct device *dev, const char *file) 63 | { 64 | char fw_name[FIRMWARE_NLEN]; 65 | const struct firmware *fw; 66 | int ret; 67 | 68 | /* Compose firmware filename */ 69 | if (strlen(file) > (128 - 6 - sizeof(FIRMWARE_VER))) 70 | return -EINVAL; 71 | sprintf(fw_name, "%s-%s.bin", file, FIRMWARE_VER); 72 | 73 | /* Do the firmware request */ 74 | ret = request_firmware(&fw, fw_name, dev); 75 | if (ret) { 76 | dev_err(dev, "unable to load firmware\n"); 77 | return ret; 78 | } 79 | 80 | dump_data(fw->data, fw->size); 81 | 82 | /* Firmware data has been read, now we can release it */ 83 | release_firmware(fw); 84 | 85 | return 0; 86 | } 87 | 88 | static int chrdev_load_fw_nowait(struct device *dev, const char *file) 89 | { 90 | char fw_name[FIRMWARE_NLEN]; 91 | int ret; 92 | 93 | /* Compose firmware filename */ 94 | if (strlen(file) > (128 - 6 - sizeof(FIRMWARE_VER))) 95 | return -EINVAL; 96 | sprintf(fw_name, "%s-%s.bin", file, FIRMWARE_VER); 97 | 98 | /* Do the firmware request */ 99 | ret = request_firmware_nowait(THIS_MODULE, false, fw_name, dev, 100 | GFP_KERNEL, dev, chrdev_fw_cb); 101 | if (ret) { 102 | dev_err(dev, 103 | "unable to register call back for firmware loading\n"); 104 | return ret; 105 | } 106 | 107 | return 0; 108 | } 109 | 110 | /* 111 | * Platform driver stuff 112 | */ 113 | 114 | static int chrdev_req_probe(struct platform_device *pdev) 115 | { 116 | struct device *dev = &pdev->dev; 117 | struct device_node *np = dev->of_node; 118 | struct fwnode_handle *fwh = of_fwnode_handle(np); 119 | struct module *owner = THIS_MODULE; 120 | const char *file; 121 | int ret = 0; 122 | 123 | /* Read device properties */ 124 | if (fwnode_property_read_string(fwh, "firmware", &file)) { 125 | dev_err(dev, "unable to get property \"firmware\"!"); 126 | return -EINVAL; 127 | } 128 | 129 | /* Load device firmware */ 130 | if (of_device_is_compatible(np, "ldddc,chrdev-fw_wait")) 131 | ret = chrdev_load_fw_wait(dev, file); 132 | else if (of_device_is_compatible(np, "ldddc,chrdev-fw_nowait")) 133 | ret = chrdev_load_fw_nowait(dev, file); 134 | if (ret) 135 | return ret; 136 | 137 | /* Register the new chr device */ 138 | ret = chrdev_device_register("chrdev-fw", 0, 0, owner, dev); 139 | if (ret) { 140 | dev_err(dev, "unable to register"); 141 | return ret; 142 | } 143 | 144 | return 0; 145 | } 146 | 147 | static int chrdev_req_remove(struct platform_device *pdev) 148 | { 149 | return chrdev_device_unregister("chrdev-fw", 0); 150 | } 151 | 152 | static const struct of_device_id of_chrdev_req_match[] = { 153 | { 154 | .compatible = "ldddc,chrdev-fw_wait", 155 | }, 156 | { 157 | .compatible = "ldddc,chrdev-fw_nowait", 158 | }, 159 | { /* sentinel */ } 160 | }; 161 | MODULE_DEVICE_TABLE(of, of_chrdev_req_match); 162 | 163 | static struct platform_driver chrdev_req_driver = { 164 | .probe = chrdev_req_probe, 165 | .remove = chrdev_req_remove, 166 | .driver = { 167 | .name = "chrdev-fw", 168 | .of_match_table = of_chrdev_req_match, 169 | }, 170 | }; 171 | module_platform_driver(chrdev_req_driver); 172 | 173 | MODULE_LICENSE("GPL"); 174 | MODULE_AUTHOR("Rodolfo Giometti"); 175 | MODULE_DESCRIPTION("chrdev firmware"); 176 | -------------------------------------------------------------------------------- /chapter_04/chrdev/chrdev-req.c: -------------------------------------------------------------------------------- 1 | /* 2 | * chrdev req 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include "chrdev.h" 15 | 16 | /* 17 | * Platform driver stuff 18 | */ 19 | 20 | static int chrdev_req_probe(struct platform_device *pdev) 21 | { 22 | struct device *dev = &pdev->dev; 23 | struct fwnode_handle *child; 24 | struct module *owner = THIS_MODULE; 25 | int count, ret; 26 | 27 | count = device_get_child_node_count(dev); 28 | if (count == 0) 29 | return -ENODEV; 30 | if (count > MAX_DEVICES) 31 | return -ENOMEM; 32 | 33 | device_for_each_child_node(dev, child) { 34 | const char *label; 35 | unsigned int id, ro; 36 | 37 | /* 38 | * Get device's properties 39 | */ 40 | 41 | if (fwnode_property_present(child, "reg")) { 42 | fwnode_property_read_u32(child, "reg", &id); 43 | } else { 44 | dev_err(dev, "property \"reg\" not present! Skipped"); 45 | continue; 46 | } 47 | if (fwnode_property_present(child, "label")) { 48 | fwnode_property_read_string(child, "label", &label); 49 | } else { 50 | dev_err(dev, "property \"label\" not present! Skipped"); 51 | continue; 52 | } 53 | ro = fwnode_property_present(child, "read-only"); 54 | 55 | /* Register the new chr device */ 56 | ret = chrdev_device_register(label, id, ro, owner, dev); 57 | if (ret) { 58 | dev_err(dev, "unable to register"); 59 | } 60 | } 61 | 62 | return 0; 63 | } 64 | 65 | static int chrdev_req_remove(struct platform_device *pdev) 66 | { 67 | struct device *dev = &pdev->dev; 68 | struct fwnode_handle *child; 69 | int ret; 70 | 71 | device_for_each_child_node(dev, child) { 72 | const char *label; 73 | int id; 74 | 75 | /* 76 | * Get device's properties 77 | */ 78 | 79 | if (fwnode_property_present(child, "reg")) 80 | fwnode_property_read_u32(child, "reg", &id); 81 | else 82 | BUG(); 83 | if (fwnode_property_present(child, "label")) 84 | fwnode_property_read_string(child, "label", &label); 85 | else 86 | BUG(); 87 | 88 | /* Register the new chr device */ 89 | ret = chrdev_device_unregister(label, id); 90 | if (ret) 91 | dev_err(dev, "unable to unregister"); 92 | } 93 | 94 | return 0; 95 | } 96 | 97 | static const struct of_device_id of_chrdev_req_match[] = { 98 | { 99 | .compatible = "ldddc,chrdev", 100 | }, 101 | { /* sentinel */ } 102 | }; 103 | MODULE_DEVICE_TABLE(of, of_chrdev_req_match); 104 | 105 | static struct platform_driver chrdev_req_driver = { 106 | .probe = chrdev_req_probe, 107 | .remove = chrdev_req_remove, 108 | .driver = { 109 | .name = "chrdev-req", 110 | .of_match_table = of_chrdev_req_match, 111 | }, 112 | }; 113 | module_platform_driver(chrdev_req_driver); 114 | 115 | MODULE_LICENSE("GPL"); 116 | MODULE_AUTHOR("Rodolfo Giometti"); 117 | MODULE_DESCRIPTION("chrdev request"); 118 | -------------------------------------------------------------------------------- /chapter_04/chrdev/chrdev.c: -------------------------------------------------------------------------------- 1 | /* 2 | * chrdev 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include "chrdev.h" 12 | 13 | /* 14 | * Local variables 15 | */ 16 | 17 | static dev_t chrdev_devt; 18 | static struct class *chrdev_class; 19 | 20 | struct chrdev_device chrdev_array[MAX_DEVICES]; 21 | 22 | /* 23 | * Methods 24 | */ 25 | 26 | static ssize_t chrdev_read(struct file *filp, 27 | char __user *buf, size_t count, loff_t *ppos) 28 | { 29 | struct chrdev_device *chrdev = filp->private_data; 30 | int ret; 31 | 32 | dev_info(chrdev->dev, "should read %ld bytes (*ppos=%lld)\n", 33 | count, *ppos); 34 | 35 | /* Check for end-of-buffer */ 36 | if (*ppos + count >= BUF_LEN) 37 | count = BUF_LEN - *ppos; 38 | 39 | /* Return data to the user space */ 40 | ret = copy_to_user(buf, chrdev->buf + *ppos, count); 41 | if (ret < 0) 42 | return -EFAULT; 43 | 44 | *ppos += count; 45 | dev_info(chrdev->dev, "return %ld bytes (*ppos=%lld)\n", count, *ppos); 46 | 47 | return count; 48 | } 49 | 50 | static ssize_t chrdev_write(struct file *filp, 51 | const char __user *buf, size_t count, loff_t *ppos) 52 | { 53 | struct chrdev_device *chrdev = filp->private_data; 54 | int ret; 55 | 56 | dev_info(chrdev->dev, "should write %ld bytes (*ppos=%lld)\n", 57 | count, *ppos); 58 | 59 | if (chrdev->read_only) 60 | return -EINVAL; 61 | 62 | /* Check for end-of-buffer */ 63 | if (*ppos + count >= BUF_LEN) 64 | count = BUF_LEN - *ppos; 65 | 66 | /* Get data from the user space */ 67 | ret = copy_from_user(chrdev->buf + *ppos, buf, count); 68 | if (ret < 0) 69 | return -EFAULT; 70 | 71 | *ppos += count; 72 | dev_info(chrdev->dev, "got %ld bytes (*ppos=%lld)\n", count, *ppos); 73 | 74 | return count; 75 | } 76 | 77 | static int chrdev_open(struct inode *inode, struct file *filp) 78 | { 79 | struct chrdev_device *chrdev = container_of(inode->i_cdev, 80 | struct chrdev_device, cdev); 81 | filp->private_data = chrdev; 82 | kobject_get(&chrdev->dev->kobj); 83 | 84 | dev_info(chrdev->dev, "chrdev (id=%d) opened\n", chrdev->id); 85 | 86 | return 0; 87 | } 88 | 89 | static int chrdev_release(struct inode *inode, struct file *filp) 90 | { 91 | struct chrdev_device *chrdev = container_of(inode->i_cdev, 92 | struct chrdev_device, cdev); 93 | kobject_put(&chrdev->dev->kobj); 94 | filp->private_data = NULL; 95 | 96 | dev_info(chrdev->dev, "chrdev (id=%d) released\n", chrdev->id); 97 | 98 | return 0; 99 | } 100 | 101 | static const struct file_operations chrdev_fops = { 102 | .owner = THIS_MODULE, 103 | .read = chrdev_read, 104 | .write = chrdev_write, 105 | .open = chrdev_open, 106 | .release = chrdev_release 107 | }; 108 | 109 | /* 110 | * Exported functions 111 | */ 112 | 113 | int chrdev_device_register(const char *label, unsigned int id, 114 | unsigned int read_only, 115 | struct module *owner, struct device *parent) 116 | { 117 | struct chrdev_device *chrdev; 118 | dev_t devt; 119 | int ret; 120 | 121 | /* First check if we are allocating a valid device... */ 122 | if (id >= MAX_DEVICES) { 123 | pr_err("invalid id %d\n", id); 124 | return -EINVAL; 125 | } 126 | chrdev = &chrdev_array[id]; 127 | 128 | /* ... then check if we have not busy id */ 129 | if (chrdev->busy) { 130 | pr_err("id %d\n is busy", id); 131 | return -EBUSY; 132 | } 133 | 134 | /* Create the device and initialize its data */ 135 | cdev_init(&chrdev->cdev, &chrdev_fops); 136 | chrdev->cdev.owner = owner; 137 | 138 | devt = MKDEV(MAJOR(chrdev_devt), id); 139 | ret = cdev_add(&chrdev->cdev, devt, 1); 140 | if (ret) { 141 | pr_err("failed to add char device %s at %d:%d\n", 142 | label, MAJOR(chrdev_devt), id); 143 | return ret; 144 | } 145 | 146 | chrdev->dev = device_create(chrdev_class, parent, devt, chrdev, 147 | "%s@%d", label, id); 148 | if (IS_ERR(chrdev->dev)) { 149 | pr_err("unable to create device %s\n", label); 150 | ret = PTR_ERR(chrdev->dev); 151 | goto del_cdev; 152 | } 153 | dev_set_drvdata(chrdev->dev, chrdev); 154 | 155 | /* Init the chrdev data */ 156 | chrdev->id = id; 157 | chrdev->read_only = read_only; 158 | chrdev->busy = 1; 159 | strncpy(chrdev->label, label, NAME_LEN); 160 | memset(chrdev->buf, 0, BUF_LEN); 161 | 162 | dev_info(chrdev->dev, "chrdev %s with id %d added\n", label, id); 163 | 164 | return 0; 165 | 166 | del_cdev: 167 | cdev_del(&chrdev->cdev); 168 | 169 | return ret; 170 | } 171 | EXPORT_SYMBOL(chrdev_device_register); 172 | 173 | int chrdev_device_unregister(const char *label, unsigned int id) 174 | { 175 | struct chrdev_device *chrdev; 176 | 177 | /* First check if we are deallocating a valid device... */ 178 | if (id >= MAX_DEVICES) { 179 | pr_err("invalid id %d\n", id); 180 | return -EINVAL; 181 | } 182 | chrdev = &chrdev_array[id]; 183 | 184 | /* ... then check if device is actualy allocated */ 185 | if (!chrdev->busy || strcmp(chrdev->label, label)) { 186 | pr_err("id %d is not busy or label %s is not known\n", 187 | id, label); 188 | return -EINVAL; 189 | } 190 | 191 | /* Deinit the chrdev data */ 192 | chrdev->id = 0; 193 | chrdev->busy = 0; 194 | 195 | dev_info(chrdev->dev, "chrdev %s with id %d removed\n", label, id); 196 | 197 | /* Dealocate the device */ 198 | device_destroy(chrdev_class, chrdev->dev->devt); 199 | cdev_del(&chrdev->cdev); 200 | 201 | return 0; 202 | } 203 | EXPORT_SYMBOL(chrdev_device_unregister); 204 | 205 | /* 206 | * Module stuff 207 | */ 208 | 209 | static int __init chrdev_init(void) 210 | { 211 | int ret; 212 | 213 | /* Create the new class for the chrdev devices */ 214 | chrdev_class = class_create(THIS_MODULE, "chrdev"); 215 | if (!chrdev_class) { 216 | pr_err("chrdev: failed to allocate class\n"); 217 | return -ENOMEM; 218 | } 219 | 220 | /* Allocate a region for character devices */ 221 | ret = alloc_chrdev_region(&chrdev_devt, 0, MAX_DEVICES, "chrdev"); 222 | if (ret < 0) { 223 | pr_err("failed to allocate char device region\n"); 224 | goto remove_class; 225 | } 226 | 227 | pr_info("got major %d\n", MAJOR(chrdev_devt)); 228 | 229 | return 0; 230 | 231 | remove_class: 232 | class_destroy(chrdev_class); 233 | 234 | return ret; 235 | } 236 | 237 | static void __exit chrdev_exit(void) 238 | { 239 | unregister_chrdev_region(chrdev_devt, MAX_DEVICES); 240 | class_destroy(chrdev_class); 241 | } 242 | 243 | module_init(chrdev_init); 244 | module_exit(chrdev_exit); 245 | 246 | MODULE_LICENSE("GPL"); 247 | MODULE_AUTHOR("Rodolfo Giometti"); 248 | MODULE_DESCRIPTION("chardev"); 249 | -------------------------------------------------------------------------------- /chapter_04/chrdev/chrdev.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Chrdev include file 3 | */ 4 | 5 | #include 6 | 7 | #define MAX_DEVICES 8 8 | #define NAME_LEN 32 9 | #define BUF_LEN 300 10 | 11 | /* 12 | * Chrdev basic structs 13 | */ 14 | 15 | /* Main struct */ 16 | struct chrdev_device { 17 | char label[NAME_LEN]; 18 | unsigned int busy : 1; 19 | char buf[BUF_LEN]; 20 | int read_only; 21 | 22 | unsigned int id; 23 | struct module *owner; 24 | struct cdev cdev; 25 | struct device *dev; 26 | }; 27 | 28 | /* 29 | * Exported functions 30 | */ 31 | 32 | #define to_class_dev(obj) container_of((obj), struct class_device, kobj) 33 | #define to_chrdev_device(obj) container_of((obj), struct chrdev_device, class) 34 | 35 | extern int chrdev_device_register(const char *label, unsigned int id, 36 | unsigned int read_only, 37 | struct module *owner, struct device *parent); 38 | extern int chrdev_device_unregister(const char *label, unsigned int id); 39 | -------------------------------------------------------------------------------- /chapter_04/get_dt_data/Makefile: -------------------------------------------------------------------------------- 1 | ifndef KERNEL_DIR 2 | $(error KERNEL_DIR must be set in the command line) 3 | endif 4 | PWD := $(shell pwd) 5 | ARCH ?= arm64 6 | CROSS_COMPILE ?= aarch64-linux-gnu- 7 | 8 | # This specifies the kernel module to be compiled 9 | obj-m += get_dt_data.o 10 | 11 | # The default action 12 | all: modules 13 | 14 | # The main tasks 15 | modules clean: 16 | make -C $(KERNEL_DIR) \ 17 | ARCH=$(ARCH) \ 18 | CROSS_COMPILE=$(CROSS_COMPILE) \ 19 | SUBDIRS=$(PWD) $@ 20 | -------------------------------------------------------------------------------- /chapter_04/get_dt_data/get_dt_data.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Module to inspect device tree from the kernel 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s: " fmt, KBUILD_MODNAME 6 | #include 7 | #include 8 | #include 9 | 10 | #define PATH_DEFAULT "/" 11 | static char *path = PATH_DEFAULT; 12 | module_param(path, charp, S_IRUSR | S_IWUSR); 13 | MODULE_PARM_DESC(path, "a device tree pathname " \ 14 | "(default is \"" PATH_DEFAULT "\")"); 15 | 16 | /* 17 | * Local functions 18 | */ 19 | 20 | static void print_property_u32(struct device_node *node, const char *name) 21 | { 22 | u32 val32; 23 | if (of_property_read_u32(node, name, &val32) == 0) 24 | pr_info(" \%s = %d\n", name, val32); 25 | } 26 | 27 | static void print_property_string(struct device_node *node, const char *name) 28 | { 29 | const char *str; 30 | if (of_property_read_string(node, name, &str) == 0) 31 | pr_info(" \%s = %s\n", name, str); 32 | } 33 | 34 | static void print_main_prop(struct device_node *node) 35 | { 36 | pr_info("+ node = %s\n", node->full_name); 37 | print_property_u32(node, "#address-cells"); 38 | print_property_u32(node, "#size-cells"); 39 | print_property_u32(node, "reg"); 40 | print_property_string(node, "name"); 41 | print_property_string(node, "compatible"); 42 | print_property_string(node, "status"); 43 | } 44 | 45 | /* 46 | * Init & exit stuff 47 | */ 48 | 49 | static int __init get_dt_data_init(void) 50 | { 51 | struct device_node *node, *child; 52 | struct property *prop; 53 | 54 | pr_info("path = \"%s\"\n", path); 55 | 56 | /* Find node by its pathname */ 57 | node = of_find_node_by_path(path); 58 | if (!node) { 59 | pr_err("failed to find device-tree node \"%s\"\n", path); 60 | return -ENODEV; 61 | } 62 | pr_info("device-tree node found!\n"); 63 | 64 | pr_info("now getting main properties...\n"); 65 | print_main_prop(node); 66 | 67 | pr_info("now move through all properties...\n"); 68 | for_each_property_of_node(node, prop) 69 | pr_info("-> %s\n", prop->name); 70 | 71 | /* Move through node's children... */ 72 | pr_info("Now move through children...\n"); 73 | for_each_child_of_node(node, child) 74 | print_main_prop(child); 75 | 76 | /* Force module unloading... */ 77 | return -EINVAL; 78 | } 79 | 80 | static void __exit get_dt_data_exit(void) 81 | { 82 | /* nop */ 83 | } 84 | 85 | module_init(get_dt_data_init); 86 | module_exit(get_dt_data_exit); 87 | 88 | MODULE_LICENSE("GPL"); 89 | MODULE_AUTHOR("Rodolfo Giometti"); 90 | MODULE_DESCRIPTION("Module to inspect device tree from the kernel"); 91 | MODULE_VERSION("0.1"); 92 | -------------------------------------------------------------------------------- /chapter_04/simple_platform/.gitignore: -------------------------------------------------------------------------------- 1 | simple_platform-reverted.dts 2 | simple_platform.dtb 3 | -------------------------------------------------------------------------------- /chapter_04/simple_platform/simple_platform.dts: -------------------------------------------------------------------------------- 1 | /dts-v1/; 2 | 3 | / { 4 | model = "fsl,mpc8572ds"; 5 | compatible = "fsl,mpc8572ds"; 6 | #address-cells = <1>; 7 | #size-cells = <1>; 8 | 9 | chosen { 10 | bootargs = "root=/dev/sda2"; 11 | }; 12 | 13 | aliases { 14 | tty0 = &serial0; 15 | }; 16 | 17 | cpus { 18 | #address-cells = <1>; 19 | #size-cells = <0>; 20 | 21 | cpu@0 { 22 | device_type = "cpu"; 23 | reg = <0>; 24 | timebase-frequency=<825000000>; 25 | clock-frequency=<825000000>; 26 | }; 27 | 28 | cpu@1 { 29 | device_type = "cpu"; 30 | reg = <1>; 31 | timebase-frequency=<825000000>; 32 | clock-frequency=<825000000>; 33 | }; 34 | 35 | 36 | }; 37 | 38 | memory@0 { 39 | device_type = "memory"; 40 | reg = <0x0 0x20000000>; 41 | }; 42 | 43 | clocks { 44 | #address-cells = <1>; 45 | #size-cells = <0>; 46 | 47 | osc: osc { 48 | compatible = "fixed-clock"; 49 | #clock-cells = <0>; 50 | clock-frequency = <33000000>; 51 | }; 52 | }; 53 | 54 | soc@80000000 { 55 | compatible = "fsl,mpc5121-immr"; 56 | #address-cells = <1>; 57 | #size-cells = <1>; 58 | device_type = "soc"; 59 | ranges = <0x0 0x80000000 0x400000>; 60 | reg = <0x80000000 0x400000>; 61 | bus-frequency = <66666666>; 62 | 63 | ipic: interrupt-controller@c00 { 64 | compatible = "fsl,mpc5121-ipic", "fsl,ipic"; 65 | interrupt-controller; 66 | #address-cells = <0>; 67 | #interrupt-cells = <2>; 68 | reg = <0xc00 0x100>; 69 | }; 70 | 71 | clks: clock@f00 { 72 | compatible = "fsl,mpc5121-clock"; 73 | reg = <0xf00 0x100>; 74 | #clock-cells = <1>; 75 | clocks = <&osc>; 76 | clock-names = "osc"; 77 | }; 78 | 79 | serial0: serial@11100 { 80 | compatible = "fsl,mpc5125-psc-uart", "fsl,mpc5125-psc"; 81 | reg = <0x11100 0x100>; 82 | interrupt-parent = <&ipic>; 83 | interrupts = <40 0x8>; 84 | fsl,rx-fifo-size = <16>; 85 | fsl,tx-fifo-size = <16>; 86 | clocks = <&clks 47>, <&clks 34>; 87 | clock-names = "ipg", "mclk"; 88 | }; 89 | }; 90 | }; 91 | -------------------------------------------------------------------------------- /chapter_05/add_irqtest_module.patch: -------------------------------------------------------------------------------- 1 | diff --git a/arch/arm64/boot/dts/marvell/armada-3720-espressobin.dts b/arch/arm64/boot/dts/marvell/armada-3720-espressobin.dts 2 | index 3ab25ad402b9..cf4831f3d7cc 100644 3 | --- a/arch/arm64/boot/dts/marvell/armada-3720-espressobin.dts 4 | +++ b/arch/arm64/boot/dts/marvell/armada-3720-espressobin.dts 5 | @@ -41,6 +41,12 @@ 6 | 3300000 0x0>; 7 | enable-active-high; 8 | }; 9 | + 10 | + irqtest { 11 | + compatible = "ldddc,irqtest"; 12 | + 13 | + gpios = <&gpiosb 20 GPIO_ACTIVE_LOW>; 14 | + }; 15 | }; 16 | 17 | /* J9 */ 18 | diff --git a/drivers/misc/Kconfig b/drivers/misc/Kconfig 19 | index 3726eacdf65d..da4ab76114ab 100644 20 | --- a/drivers/misc/Kconfig 21 | +++ b/drivers/misc/Kconfig 22 | @@ -527,4 +527,11 @@ source "drivers/misc/echo/Kconfig" 23 | source "drivers/misc/cxl/Kconfig" 24 | source "drivers/misc/ocxl/Kconfig" 25 | source "drivers/misc/cardreader/Kconfig" 26 | + 27 | +config IRQTEST_CODE 28 | + tristate "Simple IRQ test" 29 | + default n 30 | + ---help--- 31 | + The irqtest module. 32 | + 33 | endmenu 34 | diff --git a/drivers/misc/Makefile b/drivers/misc/Makefile 35 | index af22bbc3d00c..f74099e75af3 100644 36 | --- a/drivers/misc/Makefile 37 | +++ b/drivers/misc/Makefile 38 | @@ -58,3 +58,4 @@ obj-$(CONFIG_ASPEED_LPC_SNOOP) += aspeed-lpc-snoop.o 39 | obj-$(CONFIG_PCI_ENDPOINT_TEST) += pci_endpoint_test.o 40 | obj-$(CONFIG_OCXL) += ocxl/ 41 | obj-$(CONFIG_MISC_RTSX) += cardreader/ 42 | +obj-$(CONFIG_IRQTEST_CODE) += irqtest.o 43 | diff --git a/drivers/misc/irqtest.c b/drivers/misc/irqtest.c 44 | new file mode 100644 45 | index 000000000000..186b4bbb23fb 46 | --- /dev/null 47 | +++ b/drivers/misc/irqtest.c 48 | @@ -0,0 +1,125 @@ 49 | +/* 50 | + * irqtest 51 | + */ 52 | + 53 | +#define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 54 | +#include 55 | +#include 56 | +#include 57 | +#include 58 | +#include 59 | +#include 60 | +#include 61 | +#include 62 | +#include 63 | +#include 64 | +#include 65 | + 66 | +/* 67 | + * Module data 68 | + */ 69 | + 70 | +static struct irqtest_data { 71 | + int irq; 72 | + unsigned int pin; 73 | + struct device *dev; 74 | +} irqinfo; 75 | + 76 | +/* 77 | + * The interrupt handler 78 | + */ 79 | + 80 | +static irqreturn_t irqtest_interrupt(int irq, void *dev_id) 81 | +{ 82 | + struct irqtest_data *info = dev_id; 83 | + struct device *dev = info->dev; 84 | + 85 | + dev_info(dev, "interrupt occurred on IRQ %d\n", irq); 86 | + 87 | + return IRQ_HANDLED; 88 | +} 89 | + 90 | +/* 91 | + * Probe/remove functions 92 | + */ 93 | + 94 | +static int irqtest_probe(struct platform_device *pdev) 95 | +{ 96 | + struct device *dev = &pdev->dev; 97 | + struct device_node *np = dev->of_node; 98 | + int ret; 99 | + 100 | + /* Read gpios property (just the first entry) */ 101 | + ret = of_get_gpio(np, 0); 102 | + if (ret < 0) { 103 | + dev_err(dev, "failed to get GPIO from device tree\n"); 104 | + return ret; 105 | + } 106 | + irqinfo.pin = ret; 107 | + dev_info(dev, "got GPIO %u from DTS\n", irqinfo.pin); 108 | + 109 | + /* Now request the GPIO and set the line as an input */ 110 | + ret = devm_gpio_request(dev, irqinfo.pin, "irqtest"); 111 | + if (ret) { 112 | + dev_err(dev, "failed to request GPIO %u\n", irqinfo.pin); 113 | + return ret; 114 | + } 115 | + ret = gpio_direction_input(irqinfo.pin); 116 | + if (ret) { 117 | + dev_err(dev, "failed to set pin input direction\n"); 118 | + return -EINVAL; 119 | + } 120 | + 121 | + /* Now ask to the kernel to convert GPIO line into an IRQ line */ 122 | + ret = gpio_to_irq(irqinfo.pin); 123 | + if (ret < 0) { 124 | + dev_err(dev, "failed to map GPIO to IRQ!\n"); 125 | + return -EINVAL; 126 | + } 127 | + irqinfo.irq = ret; 128 | + dev_info(dev, "GPIO %u correspond to IRQ %d\n", 129 | + irqinfo.pin, irqinfo.irq); 130 | + 131 | + /* Request IRQ line and setup corresponding handler */ 132 | + irqinfo.dev = dev; 133 | + ret = request_irq(irqinfo.irq, irqtest_interrupt, 0, 134 | + "irqtest", &irqinfo); 135 | + if (ret) { 136 | + dev_err(dev, "cannot register IRQ %d\n", irqinfo.irq); 137 | + return -EIO; 138 | + } 139 | + dev_info(dev, "interrupt handler for IRQ %d is now ready!\n", 140 | + irqinfo.irq); 141 | + 142 | + return 0; 143 | +} 144 | + 145 | +static int irqtest_remove(struct platform_device *pdev) 146 | +{ 147 | + struct device *dev = &pdev->dev; 148 | + 149 | + free_irq(irqinfo.irq, &irqinfo); 150 | + dev_info(dev, "IRQ %d is now unmanaged!\n", irqinfo.irq); 151 | + 152 | + return 0; 153 | +} 154 | + 155 | +static const struct of_device_id irqtest_dt_ids[] = { 156 | + { .compatible = "ldddc,irqtest", }, 157 | + { /* sentinel */ } 158 | +}; 159 | +MODULE_DEVICE_TABLE(of, irqtest_dt_ids); 160 | + 161 | +static struct platform_driver irqtest_driver = { 162 | + .probe = irqtest_probe, 163 | + .remove = irqtest_remove, 164 | + .driver = { 165 | + .name = "irqtest", 166 | + .of_match_table = irqtest_dt_ids, 167 | + }, 168 | +}; 169 | + 170 | +module_platform_driver(irqtest_driver); 171 | +MODULE_AUTHOR("Rodolfo Giometti"); 172 | +MODULE_DESCRIPTION("IRQ test module"); 173 | +MODULE_LICENSE("GPL"); 174 | -------------------------------------------------------------------------------- /chapter_05/add_tasklet_2_to_irqtest_module.patch: -------------------------------------------------------------------------------- 1 | diff --git a/drivers/misc/irqtest.c b/drivers/misc/irqtest.c 2 | index 186b4bbb23fb..bae3e8af31f1 100644 3 | --- a/drivers/misc/irqtest.c 4 | +++ b/drivers/misc/irqtest.c 5 | @@ -23,12 +23,21 @@ static struct irqtest_data { 6 | int irq; 7 | unsigned int pin; 8 | struct device *dev; 9 | + struct tasklet_struct task; 10 | } irqinfo; 11 | 12 | /* 13 | - * The interrupt handler 14 | + * The interrupt handlers 15 | */ 16 | 17 | +static void irqtest_tasklet_handler(unsigned long flag) 18 | +{ 19 | + struct irqtest_data *info = (struct irqtest_data *) flag; 20 | + struct device *dev = info->dev; 21 | + 22 | + dev_info(dev, "tasklet executed after IRQ %d", info->irq); 23 | +} 24 | + 25 | static irqreturn_t irqtest_interrupt(int irq, void *dev_id) 26 | { 27 | struct irqtest_data *info = dev_id; 28 | @@ -36,6 +45,8 @@ static irqreturn_t irqtest_interrupt(int irq, void *dev_id) 29 | 30 | dev_info(dev, "interrupt occurred on IRQ %d\n", irq); 31 | 32 | + tasklet_schedule(&info->task); 33 | + 34 | return IRQ_HANDLED; 35 | } 36 | 37 | @@ -80,6 +91,10 @@ static int irqtest_probe(struct platform_device *pdev) 38 | dev_info(dev, "GPIO %u correspond to IRQ %d\n", 39 | irqinfo.pin, irqinfo.irq); 40 | 41 | + /* Create our tasklet */ 42 | + tasklet_init(&irqinfo.task, irqtest_tasklet_handler, 43 | + (unsigned long) &irqinfo); 44 | + 45 | /* Request IRQ line and setup corresponding handler */ 46 | irqinfo.dev = dev; 47 | ret = request_irq(irqinfo.irq, irqtest_interrupt, 0, 48 | @@ -98,6 +113,7 @@ static int irqtest_remove(struct platform_device *pdev) 49 | { 50 | struct device *dev = &pdev->dev; 51 | 52 | + tasklet_kill(&irqinfo.task); 53 | free_irq(irqinfo.irq, &irqinfo); 54 | dev_info(dev, "IRQ %d is now unmanaged!\n", irqinfo.irq); 55 | 56 | -------------------------------------------------------------------------------- /chapter_05/add_tasklet_to_irqtest_module.patch: -------------------------------------------------------------------------------- 1 | diff --git a/drivers/misc/irqtest.c b/drivers/misc/irqtest.c 2 | index 186b4bbb23fb..248bcbb0ae72 100644 3 | --- a/drivers/misc/irqtest.c 4 | +++ b/drivers/misc/irqtest.c 5 | @@ -26,9 +26,19 @@ static struct irqtest_data { 6 | } irqinfo; 7 | 8 | /* 9 | - * The interrupt handler 10 | + * The interrupt handlers 11 | */ 12 | 13 | +static void irqtest_tasklet_handler(unsigned long flag) 14 | +{ 15 | + struct irqtest_data *info = (struct irqtest_data *) flag; 16 | + struct device *dev = info->dev; 17 | + 18 | + dev_info(dev, "tasklet executed after IRQ %d", info->irq); 19 | +} 20 | +DECLARE_TASKLET(irqtest_tasklet, irqtest_tasklet_handler, 21 | + (unsigned long) &irqinfo); 22 | + 23 | static irqreturn_t irqtest_interrupt(int irq, void *dev_id) 24 | { 25 | struct irqtest_data *info = dev_id; 26 | @@ -36,6 +46,8 @@ static irqreturn_t irqtest_interrupt(int irq, void *dev_id) 27 | 28 | dev_info(dev, "interrupt occurred on IRQ %d\n", irq); 29 | 30 | + tasklet_schedule(&irqtest_tasklet); 31 | + 32 | return IRQ_HANDLED; 33 | } 34 | 35 | @@ -98,6 +110,7 @@ static int irqtest_remove(struct platform_device *pdev) 36 | { 37 | struct device *dev = &pdev->dev; 38 | 39 | + tasklet_kill(&irqtest_tasklet); 40 | free_irq(irqinfo.irq, &irqinfo); 41 | dev_info(dev, "IRQ %d is now unmanaged!\n", irqinfo.irq); 42 | 43 | -------------------------------------------------------------------------------- /chapter_05/add_workqueue_2_to_irqtest_module.patch: -------------------------------------------------------------------------------- 1 | diff --git a/drivers/misc/irqtest.c b/drivers/misc/irqtest.c 2 | index 1cb8636599d7..aeab4cc84e87 100644 3 | --- a/drivers/misc/irqtest.c 4 | +++ b/drivers/misc/irqtest.c 5 | @@ -14,6 +14,7 @@ 6 | #include 7 | #include 8 | #include 9 | +#include 10 | 11 | /* 12 | * Module data 13 | @@ -23,12 +24,35 @@ static struct irqtest_data { 14 | int irq; 15 | unsigned int pin; 16 | struct device *dev; 17 | + struct work_struct work; 18 | + struct delayed_work dwork; 19 | } irqinfo; 20 | 21 | /* 22 | - * The interrupt handler 23 | + * The interrupt handlers 24 | */ 25 | 26 | +static void irqtest_dwork_handler(struct work_struct *ptr) 27 | +{ 28 | + struct irqtest_data *info = container_of(ptr, struct irqtest_data, 29 | + dwork.work); 30 | + struct device *dev = info->dev; 31 | + 32 | + dev_info(dev, "delayed work executed after work"); 33 | +} 34 | + 35 | +static void irqtest_work_handler(struct work_struct *ptr) 36 | +{ 37 | + struct irqtest_data *info = container_of(ptr, struct irqtest_data, 38 | + work); 39 | + struct device *dev = info->dev; 40 | + 41 | + dev_info(dev, "work executed after IRQ %d", info->irq); 42 | + 43 | + /* Schedule the delayed work after 2 seconds */ 44 | + schedule_delayed_work(&info->dwork, 2*HZ); 45 | +} 46 | + 47 | static irqreturn_t irqtest_interrupt(int irq, void *dev_id) 48 | { 49 | struct irqtest_data *info = dev_id; 50 | @@ -36,6 +60,8 @@ static irqreturn_t irqtest_interrupt(int irq, void *dev_id) 51 | 52 | dev_info(dev, "interrupt occurred on IRQ %d\n", irq); 53 | 54 | + schedule_work(&info->work); 55 | + 56 | return IRQ_HANDLED; 57 | } 58 | 59 | @@ -80,6 +106,10 @@ static int irqtest_probe(struct platform_device *pdev) 60 | dev_info(dev, "GPIO %u correspond to IRQ %d\n", 61 | irqinfo.pin, irqinfo.irq); 62 | 63 | + /* Init works */ 64 | + INIT_WORK(&irqinfo.work, irqtest_work_handler); 65 | + INIT_DELAYED_WORK(&irqinfo.dwork, irqtest_dwork_handler); 66 | + 67 | /* Request IRQ line and setup corresponding handler */ 68 | irqinfo.dev = dev; 69 | ret = request_irq(irqinfo.irq, irqtest_interrupt, 0, 70 | @@ -98,6 +128,8 @@ static int irqtest_remove(struct platform_device *pdev) 71 | { 72 | struct device *dev = &pdev->dev; 73 | 74 | + cancel_work_sync(&irqinfo.work); 75 | + cancel_delayed_work_sync(&irqinfo.dwork); 76 | free_irq(irqinfo.irq, &irqinfo); 77 | dev_info(dev, "IRQ %d is now unmanaged!\n", irqinfo.irq); 78 | 79 | -------------------------------------------------------------------------------- /chapter_05/add_workqueue_to_irqtest_module.patch: -------------------------------------------------------------------------------- 1 | diff --git a/drivers/misc/irqtest.c b/drivers/misc/irqtest.c 2 | index 1cb8636599d7..e73d35e87303 100644 3 | --- a/drivers/misc/irqtest.c 4 | +++ b/drivers/misc/irqtest.c 5 | @@ -14,6 +14,7 @@ 6 | #include 7 | #include 8 | #include 9 | +#include 10 | 11 | /* 12 | * Module data 13 | @@ -23,12 +24,37 @@ static struct irqtest_data { 14 | int irq; 15 | unsigned int pin; 16 | struct device *dev; 17 | + struct work_struct work; 18 | + struct delayed_work dwork; 19 | } irqinfo; 20 | 21 | +static struct workqueue_struct *irqtest_wq; 22 | + 23 | /* 24 | - * The interrupt handler 25 | + * The interrupt handlers 26 | */ 27 | 28 | +static void irqtest_dwork_handler(struct work_struct *ptr) 29 | +{ 30 | + struct irqtest_data *info = container_of(ptr, struct irqtest_data, 31 | + dwork.work); 32 | + struct device *dev = info->dev; 33 | + 34 | + dev_info(dev, "delayed work executed after work"); 35 | +} 36 | + 37 | +static void irqtest_work_handler(struct work_struct *ptr) 38 | +{ 39 | + struct irqtest_data *info = container_of(ptr, struct irqtest_data, 40 | + work); 41 | + struct device *dev = info->dev; 42 | + 43 | + dev_info(dev, "work executed after IRQ %d", info->irq); 44 | + 45 | + /* Schedule the delayed work after 2 seconds */ 46 | + queue_delayed_work(irqtest_wq, &info->dwork, 2*HZ); 47 | +} 48 | + 49 | static irqreturn_t irqtest_interrupt(int irq, void *dev_id) 50 | { 51 | struct irqtest_data *info = dev_id; 52 | @@ -36,6 +62,8 @@ static irqreturn_t irqtest_interrupt(int irq, void *dev_id) 53 | 54 | dev_info(dev, "interrupt occurred on IRQ %d\n", irq); 55 | 56 | + queue_work(irqtest_wq, &info->work); 57 | + 58 | return IRQ_HANDLED; 59 | } 60 | 61 | @@ -80,24 +108,40 @@ static int irqtest_probe(struct platform_device *pdev) 62 | dev_info(dev, "GPIO %u correspond to IRQ %d\n", 63 | irqinfo.pin, irqinfo.irq); 64 | 65 | + /* Create our work queue and init works */ 66 | + irqtest_wq = create_singlethread_workqueue("irqtest"); 67 | + if (!irqtest_wq) { 68 | + dev_err(dev, "failed to create work queue!\n"); 69 | + return -EINVAL; 70 | + } 71 | + INIT_WORK(&irqinfo.work, irqtest_work_handler); 72 | + INIT_DELAYED_WORK(&irqinfo.dwork, irqtest_dwork_handler); 73 | + 74 | /* Request IRQ line and setup corresponding handler */ 75 | irqinfo.dev = dev; 76 | ret = request_irq(irqinfo.irq, irqtest_interrupt, 0, 77 | "irqtest", &irqinfo); 78 | if (ret) { 79 | dev_err(dev, "cannot register IRQ %d\n", irqinfo.irq); 80 | - return -EIO; 81 | + goto flush_wq; 82 | } 83 | dev_info(dev, "interrupt handler for IRQ %d is now ready!\n", 84 | irqinfo.irq); 85 | 86 | return 0; 87 | + 88 | +flush_wq: 89 | + flush_workqueue(irqtest_wq); 90 | + return -EIO; 91 | } 92 | 93 | static int irqtest_remove(struct platform_device *pdev) 94 | { 95 | struct device *dev = &pdev->dev; 96 | 97 | + cancel_work_sync(&irqinfo.work); 98 | + cancel_delayed_work_sync(&irqinfo.dwork); 99 | + flush_workqueue(irqtest_wq); 100 | free_irq(irqinfo.irq, &irqinfo); 101 | dev_info(dev, "IRQ %d is now unmanaged!\n", irqinfo.irq); 102 | 103 | -------------------------------------------------------------------------------- /chapter_05/atomic/Makefile: -------------------------------------------------------------------------------- 1 | ifndef KERNEL_DIR 2 | $(error KERNEL_DIR must be set in the command line) 3 | endif 4 | PWD := $(shell pwd) 5 | ARCH ?= arm64 6 | CROSS_COMPILE ?= aarch64-linux-gnu- 7 | 8 | # This specifies the kernel module to be compiled 9 | obj-m += mutex.o 10 | obj-m += spinlock.o 11 | obj-m += atomic.o 12 | 13 | # The default action 14 | all: modules 15 | 16 | # The main tasks 17 | modules clean: 18 | make -C $(KERNEL_DIR) \ 19 | ARCH=$(ARCH) \ 20 | CROSS_COMPILE=$(CROSS_COMPILE) \ 21 | SUBDIRS=$(PWD) $@ 22 | -------------------------------------------------------------------------------- /chapter_05/atomic/atomic.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Kernel timer 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | /* 12 | * Module parameter and data 13 | */ 14 | 15 | static int delay_ms = 1000; 16 | module_param(delay_ms, int, S_IRUSR | S_IWUSR); 17 | MODULE_PARM_DESC(delay_ms, "kernel timer delay is ms"); 18 | 19 | static atomic_t bitmap = ATOMIC_INIT(0xff); 20 | 21 | static struct ktimer_data { 22 | struct timer_list timer; 23 | long delay_jiffies; 24 | atomic_t data; 25 | } ainfo; 26 | 27 | /* 28 | * The kernel timer handler 29 | */ 30 | 31 | static void ktimer_handler(struct timer_list *t) 32 | { 33 | struct ktimer_data *info = from_timer(info, t, timer); 34 | 35 | pr_info("kernel timer expired at %ld (data=%d)\n", 36 | jiffies, atomic_dec_if_positive(&info->data)); 37 | 38 | /* Compute an atomic bitmap operation */ 39 | atomic_xor(0xff, &bitmap); 40 | pr_info("bitmap=%0x\n", atomic_read(&bitmap)); 41 | 42 | /* Reschedule kernel timer */ 43 | mod_timer(&info->timer, jiffies + info->delay_jiffies); 44 | } 45 | 46 | /* 47 | * Probe/remove functions 48 | */ 49 | 50 | static int __init ktimer_init(void) 51 | { 52 | /* Save kernel timer delay */ 53 | ainfo.delay_jiffies = msecs_to_jiffies(delay_ms); 54 | pr_info("delay is set to %dms (%ld jiffies)\n", 55 | delay_ms, ainfo.delay_jiffies); 56 | 57 | /* Init the atomic data */ 58 | atomic_set(&ainfo.data, 10); 59 | 60 | /* Setup and start the kernel timer after required delay */ 61 | timer_setup(&ainfo.timer, ktimer_handler, 0); 62 | mod_timer(&ainfo.timer, jiffies + ainfo.delay_jiffies); 63 | 64 | pr_info("kernel timer module loaded\n"); 65 | return 0; 66 | } 67 | 68 | static void __exit ktimer_exit(void) 69 | { 70 | del_timer_sync(&ainfo.timer); 71 | 72 | pr_info("kernel timer module unloaded\n"); 73 | } 74 | 75 | module_init(ktimer_init); 76 | module_exit(ktimer_exit); 77 | 78 | MODULE_AUTHOR("Rodolfo Giometti"); 79 | MODULE_DESCRIPTION("Kernel timer"); 80 | MODULE_LICENSE("GPL"); 81 | -------------------------------------------------------------------------------- /chapter_05/atomic/mutex.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Mutex 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | /* 12 | * Module parameter and data 13 | */ 14 | 15 | static int delay_ms = 1000; 16 | module_param(delay_ms, int, S_IRUSR | S_IWUSR); 17 | MODULE_PARM_DESC(delay_ms, "kernel timer delay is ms"); 18 | 19 | static struct ktimer_data { 20 | struct mutex lock; 21 | struct timer_list timer; 22 | long delay_jiffies; 23 | int data; 24 | } minfo; 25 | 26 | /* 27 | * The kernel timer handler 28 | */ 29 | 30 | static void ktimer_handler(struct timer_list *t) 31 | { 32 | struct ktimer_data *info = from_timer(info, t, timer); 33 | int ret; 34 | 35 | pr_info("kernel timer expired at %ld (data=%d)\n", 36 | jiffies, info->data); 37 | ret = mutex_trylock(&info->lock); 38 | if (ret) { 39 | info->data++; 40 | mutex_unlock(&info->lock); 41 | } else 42 | pr_err("cannot get the lock!\n"); 43 | 44 | /* Reschedule kernel timer */ 45 | mod_timer(&info->timer, jiffies + info->delay_jiffies); 46 | } 47 | 48 | /* 49 | * Probe/remove functions 50 | */ 51 | 52 | static int __init ktimer_init(void) 53 | { 54 | /* Save kernel timer delay */ 55 | minfo.delay_jiffies = msecs_to_jiffies(delay_ms); 56 | pr_info("delay is set to %dms (%ld jiffies)\n", 57 | delay_ms, minfo.delay_jiffies); 58 | 59 | /* Init the mutex */ 60 | mutex_init(&minfo.lock); 61 | 62 | /* Setup and start the kernel timer */ 63 | timer_setup(&minfo.timer, ktimer_handler, 0); 64 | mod_timer(&minfo.timer, jiffies); 65 | 66 | mutex_lock(&minfo.lock); 67 | minfo.data++; 68 | mutex_unlock(&minfo.lock); 69 | 70 | pr_info("mutex module loaded\n"); 71 | return 0; 72 | } 73 | 74 | static void __exit ktimer_exit(void) 75 | { 76 | del_timer_sync(&minfo.timer); 77 | 78 | pr_info("mutex module unloaded\n"); 79 | } 80 | 81 | module_init(ktimer_init); 82 | module_exit(ktimer_exit); 83 | 84 | MODULE_AUTHOR("Rodolfo Giometti"); 85 | MODULE_DESCRIPTION("Mutex"); 86 | MODULE_LICENSE("GPL"); 87 | -------------------------------------------------------------------------------- /chapter_05/atomic/spinlock.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Mutex 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | /* 12 | * Module parameter and data 13 | */ 14 | 15 | static int delay_ms = 1000; 16 | module_param(delay_ms, int, S_IRUSR | S_IWUSR); 17 | MODULE_PARM_DESC(delay_ms, "kernel timer delay is ms"); 18 | 19 | static struct ktimer_data { 20 | struct spinlock lock; 21 | struct timer_list timer; 22 | long delay_jiffies; 23 | int data; 24 | } sinfo; 25 | 26 | /* 27 | * The kernel timer handler 28 | */ 29 | 30 | static void ktimer_handler(struct timer_list *t) 31 | { 32 | struct ktimer_data *info = from_timer(info, t, timer); 33 | 34 | pr_info("kernel timer expired at %ld (data=%d)\n", 35 | jiffies, info->data); 36 | spin_lock(&sinfo.lock); 37 | info->data++; 38 | spin_unlock(&info->lock); 39 | 40 | /* Reschedule kernel timer */ 41 | mod_timer(&info->timer, jiffies + info->delay_jiffies); 42 | } 43 | 44 | /* 45 | * Probe/remove functions 46 | */ 47 | 48 | static int __init ktimer_init(void) 49 | { 50 | /* Save kernel timer delay */ 51 | sinfo.delay_jiffies = msecs_to_jiffies(delay_ms); 52 | pr_info("delay is set to %dms (%ld jiffies)\n", 53 | delay_ms, sinfo.delay_jiffies); 54 | 55 | /* Init the spinlock */ 56 | spin_lock_init(&sinfo.lock); 57 | 58 | /* Setup and start the kernel timer */ 59 | timer_setup(&sinfo.timer, ktimer_handler, 0); 60 | mod_timer(&sinfo.timer, jiffies); 61 | 62 | spin_lock(&sinfo.lock); 63 | sinfo.data++; 64 | spin_unlock(&sinfo.lock); 65 | 66 | pr_info("spinlock module loaded\n"); 67 | return 0; 68 | } 69 | 70 | static void __exit ktimer_exit(void) 71 | { 72 | del_timer_sync(&sinfo.timer); 73 | 74 | pr_info("spinlock module unloaded\n"); 75 | } 76 | 77 | module_init(ktimer_init); 78 | module_exit(ktimer_exit); 79 | 80 | MODULE_AUTHOR("Rodolfo Giometti"); 81 | MODULE_DESCRIPTION("Mutex"); 82 | MODULE_LICENSE("GPL"); 83 | -------------------------------------------------------------------------------- /chapter_05/notifier/Makefile: -------------------------------------------------------------------------------- 1 | ifndef KERNEL_DIR 2 | $(error KERNEL_DIR must be set in the command line) 3 | endif 4 | PWD := $(shell pwd) 5 | ARCH ?= arm64 6 | CROSS_COMPILE ?= aarch64-linux-gnu- 7 | 8 | # This specifies the kernel module to be compiled 9 | obj-m += notifier.o 10 | 11 | # The default action 12 | all: modules 13 | 14 | # The main tasks 15 | modules clean: 16 | make -C $(KERNEL_DIR) \ 17 | ARCH=$(ARCH) \ 18 | CROSS_COMPILE=$(CROSS_COMPILE) \ 19 | SUBDIRS=$(PWD) $@ 20 | -------------------------------------------------------------------------------- /chapter_05/notifier/hires_timer.c: -------------------------------------------------------------------------------- 1 | /* 2 | * High resolution timer 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | 10 | /* 11 | * Module parameter and data 12 | */ 13 | 14 | static int delay_ns = 1000000000; 15 | module_param(delay_ns, int, S_IRUSR | S_IWUSR); 16 | MODULE_PARM_DESC(delay_ns, "kernel timer delay is ns"); 17 | 18 | static struct hires_timer_data { 19 | struct hrtimer timer; 20 | unsigned int data; 21 | } hires_tinfo; 22 | 23 | /* 24 | * The kernel timer handler 25 | */ 26 | 27 | static enum hrtimer_restart hires_timer_handler(struct hrtimer *ptr) 28 | { 29 | struct hires_timer_data *info = container_of(ptr, 30 | struct hires_timer_data, timer); 31 | 32 | pr_info("kernel timer expired at %ld (data=%d)\n", 33 | jiffies, info->data++); 34 | 35 | return HRTIMER_RESTART; 36 | } 37 | 38 | /* 39 | * Probe/remove functions 40 | */ 41 | 42 | static int __init hires_timer_init(void) 43 | { 44 | /* Set up hires timer delay */ 45 | 46 | pr_info("delay is set to %dns\n", delay_ns); 47 | 48 | /* Setup and start the hires timer */ 49 | hires_tinfo.timer.function = hires_timer_handler; 50 | hrtimer_start(&hires_tinfo.timer, ns_to_ktime(delay_ns), 51 | HRTIMER_MODE_REL | HRTIMER_MODE_SOFT); 52 | 53 | pr_info("hires timer module loaded\n"); 54 | return 0; 55 | } 56 | 57 | static void __exit hires_timer_exit(void) 58 | { 59 | hrtimer_cancel(&hires_tinfo.timer); 60 | 61 | pr_info("hires timer module unloaded\n"); 62 | } 63 | 64 | module_init(hires_timer_init); 65 | module_exit(hires_timer_exit); 66 | 67 | MODULE_AUTHOR("Rodolfo Giometti"); 68 | MODULE_DESCRIPTION("High resolution timer"); 69 | MODULE_LICENSE("GPL"); 70 | -------------------------------------------------------------------------------- /chapter_05/notifier/notifier.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Kernel timer 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | /* 12 | * Module data 13 | */ 14 | 15 | static struct notifier_data { 16 | struct notifier_block netdevice_nb; 17 | struct notifier_block reboot_nb; 18 | unsigned int data; 19 | } ninfo; 20 | 21 | 22 | /* 23 | * The notifier handlers 24 | */ 25 | 26 | static int netdevice_notifier(struct notifier_block *nb, 27 | unsigned long code, void *unused) 28 | { 29 | struct notifier_data *ninfo = container_of(nb, struct notifier_data, 30 | netdevice_nb); 31 | 32 | pr_info("netdevice: event #%d with code 0x%lx caught!\n", 33 | ninfo->data++, code); 34 | 35 | return NOTIFY_DONE; 36 | } 37 | 38 | static int reboot_notifier(struct notifier_block *nb, 39 | unsigned long code, void *unused) 40 | { 41 | struct notifier_data *ninfo = container_of(nb, struct notifier_data, 42 | reboot_nb); 43 | 44 | pr_info("reboot: event #%d with code 0x%lx caught!\n", 45 | ninfo->data++, code); 46 | 47 | return NOTIFY_DONE; 48 | } 49 | 50 | /* 51 | * Probe/remove functions 52 | */ 53 | 54 | static int __init notifier_init(void) 55 | { 56 | int ret; 57 | 58 | ninfo.netdevice_nb.notifier_call = netdevice_notifier; 59 | ninfo.netdevice_nb.priority = 10; 60 | 61 | ret = register_netdevice_notifier(&ninfo.netdevice_nb); 62 | if (ret) { 63 | pr_err("unable to register netdevice notifier\n"); 64 | return ret; 65 | } 66 | 67 | ninfo.reboot_nb.notifier_call = reboot_notifier; 68 | ninfo.reboot_nb.priority = 10; 69 | 70 | ret = register_reboot_notifier(&ninfo.reboot_nb); 71 | if (ret) { 72 | pr_err("unable to register reboot notifier\n"); 73 | goto unregister_netdevice; 74 | } 75 | 76 | pr_info("notifier module loaded\n"); 77 | 78 | return 0; 79 | 80 | unregister_netdevice: 81 | unregister_netdevice_notifier(&ninfo.netdevice_nb); 82 | return ret; 83 | } 84 | 85 | static void __exit notifier_exit(void) 86 | { 87 | unregister_netdevice_notifier(&ninfo.netdevice_nb); 88 | unregister_reboot_notifier(&ninfo.reboot_nb); 89 | 90 | pr_info("notifier module unloaded\n"); 91 | } 92 | 93 | module_init(notifier_init); 94 | module_exit(notifier_exit); 95 | 96 | MODULE_AUTHOR("Rodolfo Giometti"); 97 | MODULE_DESCRIPTION("Kernel timer"); 98 | MODULE_LICENSE("GPL"); 99 | -------------------------------------------------------------------------------- /chapter_05/timer/Makefile: -------------------------------------------------------------------------------- 1 | ifndef KERNEL_DIR 2 | $(error KERNEL_DIR must be set in the command line) 3 | endif 4 | PWD := $(shell pwd) 5 | ARCH ?= arm64 6 | CROSS_COMPILE ?= aarch64-linux-gnu- 7 | 8 | # This specifies the kernel module to be compiled 9 | obj-m += hires_timer.o 10 | obj-m += ktimer.o 11 | 12 | # The default action 13 | all: modules 14 | 15 | # The main tasks 16 | modules clean: 17 | make -C $(KERNEL_DIR) \ 18 | ARCH=$(ARCH) \ 19 | CROSS_COMPILE=$(CROSS_COMPILE) \ 20 | SUBDIRS=$(PWD) $@ 21 | -------------------------------------------------------------------------------- /chapter_05/timer/hires_timer.c: -------------------------------------------------------------------------------- 1 | /* 2 | * High resolution timer 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | 10 | /* 11 | * Module parameter and data 12 | */ 13 | 14 | static int delay_ns = 1000000000; 15 | module_param(delay_ns, int, S_IRUSR | S_IWUSR); 16 | MODULE_PARM_DESC(delay_ns, "kernel timer delay is ns"); 17 | 18 | static struct hires_timer_data { 19 | struct hrtimer timer; 20 | unsigned int data; 21 | } hires_tinfo; 22 | 23 | /* 24 | * The kernel timer handler 25 | */ 26 | 27 | static enum hrtimer_restart hires_timer_handler(struct hrtimer *ptr) 28 | { 29 | struct hires_timer_data *info = container_of(ptr, 30 | struct hires_timer_data, timer); 31 | 32 | pr_info("kernel timer expired at %ld (data=%d)\n", 33 | jiffies, info->data++); 34 | 35 | /* Now forward the expiration time and ask to be rescheduled */ 36 | hrtimer_forward_now(&info->timer, ns_to_ktime(delay_ns)); 37 | return HRTIMER_RESTART; 38 | } 39 | 40 | /* 41 | * Probe/remove functions 42 | */ 43 | 44 | static int __init hires_timer_init(void) 45 | { 46 | /* Set up hires timer delay */ 47 | 48 | pr_info("delay is set to %dns\n", delay_ns); 49 | 50 | /* Setup and start the hires timer */ 51 | hrtimer_init(&hires_tinfo.timer, CLOCK_MONOTONIC, 52 | HRTIMER_MODE_REL | HRTIMER_MODE_SOFT); 53 | hires_tinfo.timer.function = hires_timer_handler; 54 | hrtimer_start(&hires_tinfo.timer, ns_to_ktime(delay_ns), 55 | HRTIMER_MODE_REL | HRTIMER_MODE_SOFT); 56 | 57 | pr_info("hires timer module loaded\n"); 58 | return 0; 59 | } 60 | 61 | static void __exit hires_timer_exit(void) 62 | { 63 | hrtimer_cancel(&hires_tinfo.timer); 64 | 65 | pr_info("hires timer module unloaded\n"); 66 | } 67 | 68 | module_init(hires_timer_init); 69 | module_exit(hires_timer_exit); 70 | 71 | MODULE_AUTHOR("Rodolfo Giometti"); 72 | MODULE_DESCRIPTION("High resolution timer"); 73 | MODULE_LICENSE("GPL"); 74 | -------------------------------------------------------------------------------- /chapter_05/timer/ktimer.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Kernel timer 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | 10 | /* 11 | * Module parameter and data 12 | */ 13 | 14 | static int delay_ms = 1000; 15 | module_param(delay_ms, int, S_IRUSR | S_IWUSR); 16 | MODULE_PARM_DESC(delay_ms, "kernel timer delay is ms"); 17 | 18 | static struct ktimer_data { 19 | struct timer_list timer; 20 | long delay_jiffies; 21 | unsigned int data; 22 | } ktinfo; 23 | 24 | /* 25 | * The kernel timer handler 26 | */ 27 | 28 | static void ktimer_handler(struct timer_list *t) 29 | { 30 | struct ktimer_data *info = from_timer(info, t, timer); 31 | 32 | pr_info("kernel timer expired at %ld (data=%d)\n", 33 | jiffies, info->data++); 34 | 35 | /* Reschedule kernel timer */ 36 | mod_timer(&info->timer, jiffies + info->delay_jiffies); 37 | } 38 | 39 | /* 40 | * Probe/remove functions 41 | */ 42 | 43 | static int __init ktimer_init(void) 44 | { 45 | /* Save kernel timer delay */ 46 | ktinfo.delay_jiffies = msecs_to_jiffies(delay_ms); 47 | pr_info("delay is set to %dms (%ld jiffies)\n", 48 | delay_ms, ktinfo.delay_jiffies); 49 | 50 | /* Setup and start the kernel timer */ 51 | timer_setup(&ktinfo.timer, ktimer_handler, 0); 52 | mod_timer(&ktinfo.timer, jiffies + ktinfo.delay_jiffies); 53 | 54 | pr_info("kernel timer module loaded\n"); 55 | return 0; 56 | } 57 | 58 | static void __exit ktimer_exit(void) 59 | { 60 | del_timer_sync(&ktinfo.timer); 61 | 62 | pr_info("kernel timer module unloaded\n"); 63 | } 64 | 65 | module_init(ktimer_init); 66 | module_exit(ktimer_exit); 67 | 68 | MODULE_AUTHOR("Rodolfo Giometti"); 69 | MODULE_DESCRIPTION("Kernel timer"); 70 | MODULE_LICENSE("GPL"); 71 | -------------------------------------------------------------------------------- /chapter_05/wait_event/Makefile: -------------------------------------------------------------------------------- 1 | ifndef KERNEL_DIR 2 | $(error KERNEL_DIR must be set in the command line) 3 | endif 4 | PWD := $(shell pwd) 5 | ARCH ?= arm64 6 | CROSS_COMPILE ?= aarch64-linux-gnu- 7 | 8 | # This specifies the kernel module to be compiled 9 | obj-m += waitqueue.o 10 | obj-m += completion.o 11 | 12 | # The default action 13 | all: modules 14 | 15 | # The main tasks 16 | modules clean: 17 | make -C $(KERNEL_DIR) \ 18 | ARCH=$(ARCH) \ 19 | CROSS_COMPILE=$(CROSS_COMPILE) \ 20 | SUBDIRS=$(PWD) $@ 21 | -------------------------------------------------------------------------------- /chapter_05/wait_event/completion.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Completion 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | /* 12 | * Module parameter and data 13 | */ 14 | 15 | static int delay_ms = 5000; 16 | module_param(delay_ms, int, S_IRUSR | S_IWUSR); 17 | MODULE_PARM_DESC(delay_ms, "kernel timer delay is ms"); 18 | 19 | static struct ktimer_data { 20 | struct completion done; 21 | struct timer_list timer; 22 | long delay_jiffies; 23 | unsigned int data; 24 | } cinfo; 25 | 26 | /* 27 | * The kernel timer handler 28 | */ 29 | 30 | static void ktimer_handler(struct timer_list *t) 31 | { 32 | struct ktimer_data *info = from_timer(info, t, timer); 33 | 34 | pr_info("kernel timer expired at %ld (data=%d)\n", 35 | jiffies, info->data++); 36 | 37 | /* Signal that job is done */ 38 | complete(&info->done); 39 | } 40 | 41 | /* 42 | * Probe/remove functions 43 | */ 44 | 45 | static int __init completion_init(void) 46 | { 47 | /* Save kernel timer delay */ 48 | cinfo.delay_jiffies = msecs_to_jiffies(delay_ms); 49 | pr_info("delay is set to %dms (%ld jiffies)\n", 50 | delay_ms, cinfo.delay_jiffies); 51 | 52 | /* Init the wait queue */ 53 | init_completion(&cinfo.done); 54 | 55 | /* Setup and start the kernel timer */ 56 | timer_setup(&cinfo.timer, ktimer_handler, 0); 57 | mod_timer(&cinfo.timer, jiffies + cinfo.delay_jiffies); 58 | 59 | /* Wait for completition... */ 60 | wait_for_completion(&cinfo.done); 61 | 62 | pr_info("job done\n"); 63 | 64 | return 0; 65 | } 66 | 67 | static void __exit completion_exit(void) 68 | { 69 | del_timer_sync(&cinfo.timer); 70 | 71 | pr_info("module unloaded\n"); 72 | } 73 | 74 | module_init(completion_init); 75 | module_exit(completion_exit); 76 | 77 | MODULE_AUTHOR("Rodolfo Giometti"); 78 | MODULE_DESCRIPTION("Completion"); 79 | MODULE_LICENSE("GPL"); 80 | -------------------------------------------------------------------------------- /chapter_05/wait_event/waitqueue.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Wait Queue 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | /* 12 | * Module parameter and data 13 | */ 14 | 15 | static int delay_ms = 1000; 16 | module_param(delay_ms, int, S_IRUSR | S_IWUSR); 17 | MODULE_PARM_DESC(delay_ms, "kernel timer delay is ms"); 18 | 19 | static struct ktimer_data { 20 | struct wait_queue_head waitq; 21 | struct timer_list timer; 22 | long delay_jiffies; 23 | unsigned int data; 24 | } wqinfo; 25 | 26 | /* 27 | * The kernel timer handler 28 | */ 29 | 30 | static void ktimer_handler(struct timer_list *t) 31 | { 32 | struct ktimer_data *info = from_timer(info, t, timer); 33 | 34 | pr_info("kernel timer expired at %ld (data=%d)\n", 35 | jiffies, info->data++); 36 | 37 | /* Wake up all sleeping processes */ 38 | wake_up_interruptible(&info->waitq); 39 | 40 | /* Reschedule kernel timer */ 41 | mod_timer(&info->timer, jiffies + info->delay_jiffies); 42 | } 43 | 44 | /* 45 | * Probe/remove functions 46 | */ 47 | 48 | static int __init waitqueue_init(void) 49 | { 50 | int ret; 51 | 52 | /* Save kernel timer delay */ 53 | wqinfo.delay_jiffies = msecs_to_jiffies(delay_ms); 54 | pr_info("delay is set to %dms (%ld jiffies)\n", 55 | delay_ms, wqinfo.delay_jiffies); 56 | 57 | /* Init the wait queue */ 58 | init_waitqueue_head(&wqinfo.waitq); 59 | 60 | /* Setup and start the kernel timer */ 61 | timer_setup(&wqinfo.timer, ktimer_handler, 0); 62 | mod_timer(&wqinfo.timer, jiffies + wqinfo.delay_jiffies); 63 | 64 | /* Wait for the wake up event... */ 65 | ret = wait_event_interruptible(wqinfo.waitq, wqinfo.data > 5); 66 | if (ret < 0) 67 | goto exit; 68 | 69 | pr_info("got event data > 5\n"); 70 | 71 | return 0; 72 | 73 | exit: 74 | if (ret == -ERESTARTSYS) 75 | pr_info("interrupted by signal!\n"); 76 | else 77 | pr_err("unable to wait for event\n"); 78 | 79 | del_timer_sync(&wqinfo.timer); 80 | 81 | return ret; 82 | } 83 | 84 | static void __exit waitqueue_exit(void) 85 | { 86 | del_timer_sync(&wqinfo.timer); 87 | 88 | pr_info("module unloaded\n"); 89 | } 90 | 91 | module_init(waitqueue_init); 92 | module_exit(waitqueue_exit); 93 | 94 | MODULE_AUTHOR("Rodolfo Giometti"); 95 | MODULE_DESCRIPTION("Wait queue"); 96 | MODULE_LICENSE("GPL"); 97 | -------------------------------------------------------------------------------- /chapter_06/data_types/Makefile: -------------------------------------------------------------------------------- 1 | ifndef KERNEL_DIR 2 | $(error KERNEL_DIR must be set in the command line) 3 | endif 4 | PWD := $(shell pwd) 5 | ARCH ?= arm64 6 | CROSS_COMPILE ?= aarch64-linux-gnu- 7 | 8 | # This specifies the kernel module to be compiled 9 | obj-m += data_types.o 10 | 11 | # The default action 12 | all: modules 13 | 14 | # The main tasks 15 | modules clean: 16 | make -C $(KERNEL_DIR) \ 17 | ARCH=$(ARCH) \ 18 | CROSS_COMPILE=$(CROSS_COMPILE) \ 19 | SUBDIRS=$(PWD) $@ 20 | -------------------------------------------------------------------------------- /chapter_06/data_types/data_types.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Kernel data types 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | 10 | static long base_addr = 0x80000000; 11 | module_param(base_addr, long, S_IRUSR | S_IWUSR); 12 | MODULE_PARM_DESC(base_addr, "base address"); 13 | 14 | /* 15 | * Peripheral mapping 16 | */ 17 | 18 | struct dtypes_s { 19 | u32 reg0; 20 | u8 pad0[2]; 21 | u16 reg1; 22 | u32 pad1[2]; 23 | u8 reg2; 24 | u8 reg3; 25 | u16 reg4; 26 | u32 reg5; 27 | } __attribute__ ((packed)); 28 | 29 | /* 30 | * Init & exit stuff 31 | */ 32 | 33 | static int __init data_types_init(void) 34 | { 35 | struct dtypes_s *ptr = (struct dtypes_s *) base_addr; 36 | 37 | pr_info("\tu8\tu16\tu32\tu64\n"); 38 | pr_info("size\t%ld\t%ld\t%ld\t%ld\n", 39 | sizeof(u8), sizeof(u16), sizeof(u32), sizeof(u64)); 40 | 41 | pr_info("name\tptr\n"); 42 | pr_info("reg0\t%px\n", &ptr->reg0); 43 | pr_info("reg1\t%px\n", &ptr->reg1); 44 | pr_info("reg2\t%px\n", &ptr->reg2); 45 | pr_info("reg3\t%px\n", &ptr->reg3); 46 | pr_info("reg4\t%px\n", &ptr->reg4); 47 | pr_info("reg5\t%px\n", &ptr->reg5); 48 | 49 | return -EINVAL; 50 | } 51 | 52 | static void __exit data_types_exit(void) 53 | { 54 | pr_info("unloaded\n"); 55 | } 56 | 57 | module_init(data_types_init); 58 | module_exit(data_types_exit); 59 | 60 | MODULE_LICENSE("GPL"); 61 | MODULE_AUTHOR("Rodolfo Giometti"); 62 | MODULE_DESCRIPTION("Kernel data types"); 63 | MODULE_VERSION("0.1"); 64 | -------------------------------------------------------------------------------- /chapter_06/hashtable/Makefile: -------------------------------------------------------------------------------- 1 | ifndef KERNEL_DIR 2 | $(error KERNEL_DIR must be set in the command line) 3 | endif 4 | PWD := $(shell pwd) 5 | ARCH ?= arm64 6 | CROSS_COMPILE ?= aarch64-linux-gnu- 7 | 8 | # This specifies the kernel module to be compiled 9 | obj-m += hashtable.o 10 | 11 | # The default action 12 | all: modules 13 | 14 | # The main tasks 15 | modules clean: 16 | make -C $(KERNEL_DIR) \ 17 | ARCH=$(ARCH) \ 18 | CROSS_COMPILE=$(CROSS_COMPILE) \ 19 | SUBDIRS=$(PWD) $@ 20 | -------------------------------------------------------------------------------- /chapter_06/hashtable/hashtable.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Kernel hash tables 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | 9 | static DEFINE_HASHTABLE(data_hash, 1); 10 | 11 | struct h_struct { 12 | int data; 13 | struct hlist_node node; 14 | }; 15 | 16 | static int hash_func(int data) 17 | { 18 | return data % 2; 19 | } 20 | 21 | /* 22 | * Local functions 23 | */ 24 | 25 | static void add_node(struct h_struct *new) 26 | { 27 | int key = hash_func(new->data); 28 | 29 | hash_add(data_hash, &new->node, key); 30 | } 31 | 32 | static void del_node(int data) 33 | { 34 | int key = hash_func(data); 35 | struct h_struct *entry; 36 | 37 | hash_for_each_possible(data_hash, entry, node, key) { 38 | if (entry->data == data) { 39 | hash_del(&entry->node); 40 | return; 41 | } 42 | } 43 | } 44 | 45 | static void print_nodes(void) 46 | { 47 | int key; 48 | struct h_struct *entry; 49 | 50 | hash_for_each(data_hash, key, entry, node) 51 | pr_info("data=%d\n", entry->data); 52 | } 53 | 54 | /* 55 | * Init & exit stuff 56 | */ 57 | 58 | static int __init hashtable_init(void) 59 | { 60 | struct h_struct e1 = { 61 | .data = 5 62 | }; 63 | struct h_struct e2 = { 64 | .data = 2 65 | }; 66 | struct h_struct e3 = { 67 | .data = 7 68 | }; 69 | 70 | pr_info("add e1...\n"); 71 | add_node(&e1); 72 | print_nodes(); 73 | 74 | pr_info("add e2, e3...\n"); 75 | add_node(&e2); 76 | add_node(&e3); 77 | print_nodes(); 78 | 79 | pr_info("del data=5\n"); 80 | del_node(5); 81 | print_nodes(); 82 | 83 | return -EINVAL; 84 | } 85 | 86 | static void __exit hashtable_exit(void) 87 | { 88 | pr_info("unloaded\n"); 89 | } 90 | 91 | module_init(hashtable_init); 92 | module_exit(hashtable_exit); 93 | 94 | MODULE_LICENSE("GPL"); 95 | MODULE_AUTHOR("Rodolfo Giometti"); 96 | MODULE_DESCRIPTION("Kernel hash tables"); 97 | MODULE_VERSION("0.1"); 98 | -------------------------------------------------------------------------------- /chapter_06/helper_funcs/Makefile: -------------------------------------------------------------------------------- 1 | ifndef KERNEL_DIR 2 | $(error KERNEL_DIR must be set in the command line) 3 | endif 4 | PWD := $(shell pwd) 5 | ARCH ?= arm64 6 | CROSS_COMPILE ?= aarch64-linux-gnu- 7 | 8 | # This specifies the kernel module to be compiled 9 | obj-m += helper_funcs.o 10 | 11 | # The default action 12 | all: modules 13 | 14 | # The main tasks 15 | modules clean: 16 | make -C $(KERNEL_DIR) \ 17 | ARCH=$(ARCH) \ 18 | CROSS_COMPILE=$(CROSS_COMPILE) \ 19 | SUBDIRS=$(PWD) $@ 20 | -------------------------------------------------------------------------------- /chapter_06/helper_funcs/helper_funcs.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Kernel helper functions 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | 10 | static char *str = "default string"; 11 | module_param(str, charp, S_IRUSR | S_IWUSR); 12 | MODULE_PARM_DESC(str, "a string value"); 13 | 14 | #define STR2_LEN 32 15 | 16 | /* 17 | * Init & exit stuff 18 | */ 19 | 20 | static int __init helper_funcs_init(void) 21 | { 22 | char str2[STR2_LEN]; 23 | 24 | pr_info("str=\"%s\"\n", str); 25 | pr_info("str size=%ld\n", strlen(str)); 26 | 27 | strncpy(str2, str, STR2_LEN); 28 | 29 | pr_info("str2=\"%s\"\n", str2); 30 | pr_info("str2 size=%ld\n", strlen(str2)); 31 | 32 | return -EINVAL; 33 | } 34 | 35 | static void __exit helper_funcs_exit(void) 36 | { 37 | pr_info("unloaded\n"); 38 | } 39 | 40 | module_init(helper_funcs_init); 41 | module_exit(helper_funcs_exit); 42 | 43 | MODULE_LICENSE("GPL"); 44 | MODULE_AUTHOR("Rodolfo Giometti"); 45 | MODULE_DESCRIPTION("Kernel helper functions"); 46 | MODULE_VERSION("0.1"); 47 | -------------------------------------------------------------------------------- /chapter_06/list/Makefile: -------------------------------------------------------------------------------- 1 | ifndef KERNEL_DIR 2 | $(error KERNEL_DIR must be set in the command line) 3 | endif 4 | PWD := $(shell pwd) 5 | ARCH ?= arm64 6 | CROSS_COMPILE ?= aarch64-linux-gnu- 7 | 8 | # This specifies the kernel module to be compiled 9 | obj-m += list.o 10 | 11 | # The default action 12 | all: modules 13 | 14 | # The main tasks 15 | modules clean: 16 | make -C $(KERNEL_DIR) \ 17 | ARCH=$(ARCH) \ 18 | CROSS_COMPILE=$(CROSS_COMPILE) \ 19 | SUBDIRS=$(PWD) $@ 20 | -------------------------------------------------------------------------------- /chapter_06/list/list.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Kernel lists 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | 9 | static LIST_HEAD(data_list); 10 | 11 | struct l_struct { 12 | int data; 13 | struct list_head list; 14 | }; 15 | 16 | /* 17 | * Local functions 18 | */ 19 | 20 | static void add_ordered_entry(struct l_struct *new) 21 | { 22 | struct list_head *ptr; 23 | struct l_struct *entry; 24 | 25 | list_for_each(ptr, &data_list) { 26 | entry = list_entry(ptr, struct l_struct, list); 27 | if (entry->data < new->data) { 28 | list_add_tail(&new->list, ptr); 29 | return; 30 | } 31 | } 32 | list_add_tail(&new->list, &data_list); 33 | } 34 | 35 | static void del_entry(int data) 36 | { 37 | struct list_head *ptr; 38 | struct l_struct *entry; 39 | 40 | list_for_each(ptr, &data_list) { 41 | entry = list_entry(ptr, struct l_struct, list); 42 | if (entry->data == data) { 43 | list_del(ptr); 44 | return; 45 | } 46 | } 47 | } 48 | 49 | static void print_entries(void) 50 | { 51 | struct l_struct *entry; 52 | 53 | list_for_each_entry(entry, &data_list, list) 54 | pr_info("data=%d\n", entry->data); 55 | } 56 | 57 | /* 58 | * Init & exit stuff 59 | */ 60 | 61 | static int __init list_init(void) 62 | { 63 | struct l_struct e1 = { 64 | .data = 5 65 | }; 66 | struct l_struct e2 = { 67 | .data = 1 68 | }; 69 | struct l_struct e3 = { 70 | .data = 7 71 | }; 72 | 73 | pr_info("add e1...\n"); 74 | add_ordered_entry(&e1); 75 | print_entries(); 76 | 77 | pr_info("add e2, e3...\n"); 78 | add_ordered_entry(&e2); 79 | add_ordered_entry(&e3); 80 | print_entries(); 81 | 82 | pr_info("del data=5...\n"); 83 | del_entry(5); 84 | print_entries(); 85 | 86 | return -EINVAL; 87 | } 88 | 89 | static void __exit list_exit(void) 90 | { 91 | pr_info("unloaded\n"); 92 | } 93 | 94 | module_init(list_init); 95 | module_exit(list_exit); 96 | 97 | MODULE_LICENSE("GPL"); 98 | MODULE_AUTHOR("Rodolfo Giometti"); 99 | MODULE_DESCRIPTION("Kernel lists"); 100 | MODULE_VERSION("0.1"); 101 | -------------------------------------------------------------------------------- /chapter_06/mem_alloc/Makefile: -------------------------------------------------------------------------------- 1 | ifndef KERNEL_DIR 2 | $(error KERNEL_DIR must be set in the command line) 3 | endif 4 | PWD := $(shell pwd) 5 | ARCH ?= arm64 6 | CROSS_COMPILE ?= aarch64-linux-gnu- 7 | 8 | # This specifies the kernel module to be compiled 9 | obj-m += mem_alloc.o 10 | 11 | # The default action 12 | all: modules 13 | 14 | # The main tasks 15 | modules clean: 16 | make -C $(KERNEL_DIR) \ 17 | ARCH=$(ARCH) \ 18 | CROSS_COMPILE=$(CROSS_COMPILE) \ 19 | SUBDIRS=$(PWD) $@ 20 | -------------------------------------------------------------------------------- /chapter_06/mem_alloc/mem_alloc.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Kernel memory allocation 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | static long size = 4; 13 | module_param(size, long, S_IRUSR | S_IWUSR); 14 | MODULE_PARM_DESC(size, "memory size in Kbytes"); 15 | 16 | /* 17 | * Init & exit stuff 18 | */ 19 | 20 | static int __init mem_alloc_init(void) 21 | { 22 | void *ptr; 23 | 24 | pr_info("size=%ldkbytes\n", size); 25 | 26 | ptr = kmalloc(size << 10, GFP_KERNEL); 27 | pr_info("kmalloc(..., GFP_KERNEL) =%px\n", ptr); 28 | kfree(ptr); 29 | 30 | ptr = kmalloc(size << 10, GFP_ATOMIC); 31 | pr_info("kmalloc(..., GFP_ATOMIC) =%px\n", ptr); 32 | kfree(ptr); 33 | 34 | ptr = vmalloc(size << 10); 35 | pr_info("vmalloc(...) =%px\n", ptr); 36 | vfree(ptr); 37 | 38 | ptr = kvmalloc(size << 10, GFP_KERNEL); 39 | pr_info("kvmalloc(..., GFP_KERNEL)=%px\n", ptr); 40 | kvfree(ptr); 41 | 42 | ptr = kvmalloc(size << 10, GFP_ATOMIC); 43 | pr_info("kvmalloc(..., GFP_ATOMIC)=%px\n", ptr); 44 | kvfree(ptr); 45 | 46 | return -EINVAL; 47 | } 48 | 49 | static void __exit mem_alloc_exit(void) 50 | { 51 | pr_info("unloaded\n"); 52 | } 53 | 54 | module_init(mem_alloc_init); 55 | module_exit(mem_alloc_exit); 56 | 57 | MODULE_LICENSE("GPL"); 58 | MODULE_AUTHOR("Rodolfo Giometti"); 59 | MODULE_DESCRIPTION("Kernel memory allocation"); 60 | MODULE_VERSION("0.1"); 61 | -------------------------------------------------------------------------------- /chapter_06/time/Makefile: -------------------------------------------------------------------------------- 1 | ifndef KERNEL_DIR 2 | $(error KERNEL_DIR must be set in the command line) 3 | endif 4 | PWD := $(shell pwd) 5 | ARCH ?= arm64 6 | CROSS_COMPILE ?= aarch64-linux-gnu- 7 | 8 | # This specifies the kernel module to be compiled 9 | obj-m += time.o 10 | 11 | # The default action 12 | all: modules 13 | 14 | # The main tasks 15 | modules clean: 16 | make -C $(KERNEL_DIR) \ 17 | ARCH=$(ARCH) \ 18 | CROSS_COMPILE=$(CROSS_COMPILE) \ 19 | SUBDIRS=$(PWD) $@ 20 | -------------------------------------------------------------------------------- /chapter_06/time/time.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Kernel timing functions 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | 10 | #define print_time(str, code) \ 11 | do { \ 12 | u64 t0, t1; \ 13 | t0 = ktime_get_real_ns(); \ 14 | code; \ 15 | t1 = ktime_get_real_ns(); \ 16 | pr_info(str " -> %lluns\n", t1 - t0); \ 17 | } while (0) 18 | 19 | /* 20 | * Init & exit stuff 21 | */ 22 | 23 | static int __init time_init(void) 24 | { 25 | pr_info("*delay() functions:\n"); 26 | print_time("10ns", ndelay(10)); 27 | print_time("10000ns", udelay(10)); 28 | print_time("10000000ns", mdelay(10)); 29 | 30 | pr_info("*sleep() functions:\n"); 31 | print_time("10000ns", usleep_range(10, 10)); 32 | print_time("10000000ns", msleep(10)); 33 | print_time("10000000ns", msleep_interruptible(10)); 34 | print_time("10000000000ns", ssleep(10)); 35 | 36 | return -EINVAL; 37 | } 38 | 39 | static void __exit time_exit(void) 40 | { 41 | pr_info("unloaded\n"); 42 | } 43 | 44 | module_init(time_init); 45 | module_exit(time_exit); 46 | 47 | MODULE_LICENSE("GPL"); 48 | MODULE_AUTHOR("Rodolfo Giometti"); 49 | MODULE_DESCRIPTION("Kernel timing functions"); 50 | MODULE_VERSION("0.1"); 51 | -------------------------------------------------------------------------------- /chapter_07/.gitignore: -------------------------------------------------------------------------------- 1 | chrdev_ioctl 2 | chrdev_mmap 3 | chrdev_fasync 4 | chrdev_select 5 | textfile.txt 6 | -------------------------------------------------------------------------------- /chapter_07/chrdev/Makefile: -------------------------------------------------------------------------------- 1 | ifndef KERNEL_DIR 2 | $(error KERNEL_DIR must be set in the command line) 3 | endif 4 | PWD := $(shell pwd) 5 | ARCH ?= arm64 6 | CROSS_COMPILE ?= aarch64-linux-gnu- 7 | 8 | obj-m = chrdev.o 9 | obj-m += chrdev_irq.o 10 | obj-m += chrdev-req.o 11 | 12 | all: modules 13 | 14 | modules clean: 15 | make -C $(KERNEL_DIR) \ 16 | ARCH=$(ARCH) \ 17 | CROSS_COMPILE=$(CROSS_COMPILE) \ 18 | SUBDIRS=$(PWD) $@ 19 | -------------------------------------------------------------------------------- /chapter_07/chrdev/add_mutex_to_chrdev.patch: -------------------------------------------------------------------------------- 1 | diff --git a/chapter_07/chrdev/chrdev.c b/chapter_07/chrdev/chrdev.c 2 | index 8c5f6d8..bb37e4c 100644 3 | --- a/chapter_07/chrdev/chrdev.c 4 | +++ b/chapter_07/chrdev/chrdev.c 5 | @@ -73,6 +73,9 @@ static long chrdev_ioctl(struct file *filp, 6 | dev_info(chrdev->dev, "cmd nr=%d size=%d dir=%x\n", 7 | _IOC_NR(cmd), _IOC_SIZE(cmd), _IOC_DIR(cmd)); 8 | 9 | + /* Grab the mutex */ 10 | + mutex_lock(&chrdev->mux); 11 | + 12 | switch (cmd) { 13 | case CHRDEV_IOC_GETINFO: 14 | dev_info(chrdev->dev, "CHRDEV_IOC_GETINFO\n"); 15 | @@ -81,8 +84,10 @@ static long chrdev_ioctl(struct file *filp, 16 | info.read_only = chrdev->read_only; 17 | 18 | ret = copy_to_user(uarg, &info, sizeof(struct chrdev_info)); 19 | - if (ret) 20 | - return -EFAULT; 21 | + if (ret) { 22 | + ret = -EFAULT; 23 | + goto unlock; 24 | + } 25 | 26 | break; 27 | 28 | @@ -90,16 +95,24 @@ static long chrdev_ioctl(struct file *filp, 29 | dev_info(chrdev->dev, "WDIOC_SET_RDONLY\n"); 30 | 31 | ret = get_user(chrdev->read_only, iuarg); 32 | - if (ret) 33 | - return -EFAULT; 34 | + if (ret) { 35 | + ret = -EFAULT; 36 | + goto unlock; 37 | + } 38 | 39 | break; 40 | 41 | default: 42 | - return -ENOIOCTLCMD; 43 | + ret = -ENOIOCTLCMD; 44 | + goto unlock; 45 | } 46 | + ret = 0; 47 | 48 | - return 0; 49 | +unlock: 50 | + /* Release the mutex */ 51 | + mutex_unlock(&chrdev->mux); 52 | + 53 | + return ret; 54 | } 55 | 56 | static loff_t chrdev_llseek(struct file *filp, loff_t offset, int whence) 57 | @@ -110,6 +123,9 @@ static loff_t chrdev_llseek(struct file *filp, loff_t offset, int whence) 58 | dev_info(chrdev->dev, "should move *ppos=%lld by whence %d off=%lld\n", 59 | filp->f_pos, whence, offset); 60 | 61 | + /* Grab the mutex */ 62 | + mutex_lock(&chrdev->mux); 63 | + 64 | switch (whence) { 65 | case SEEK_SET: 66 | newppos = offset; 67 | @@ -124,15 +140,22 @@ static loff_t chrdev_llseek(struct file *filp, loff_t offset, int whence) 68 | break; 69 | 70 | default: 71 | - return -EINVAL; 72 | + newppos = -EINVAL; 73 | + goto unlock; 74 | } 75 | 76 | - if ((newppos < 0) || (newppos >= BUF_LEN)) 77 | - return -EINVAL; 78 | + if ((newppos < 0) || (newppos >= BUF_LEN)) { 79 | + newppos = -EINVAL; 80 | + goto unlock; 81 | + } 82 | 83 | filp->f_pos = newppos; 84 | dev_info(chrdev->dev, "return *ppos=%lld\n", filp->f_pos); 85 | 86 | +unlock: 87 | + /* Release the mutex */ 88 | + mutex_unlock(&chrdev->mux); 89 | + 90 | return newppos; 91 | } 92 | 93 | @@ -145,18 +168,27 @@ static ssize_t chrdev_read(struct file *filp, 94 | dev_info(chrdev->dev, "should read %ld bytes (*ppos=%lld)\n", 95 | count, *ppos); 96 | 97 | + /* Grab the mutex */ 98 | + mutex_lock(&chrdev->mux); 99 | + 100 | /* Check for end-of-buffer */ 101 | if (*ppos + count >= BUF_LEN) 102 | count = BUF_LEN - *ppos; 103 | 104 | /* Return data to the user space */ 105 | ret = copy_to_user(buf, chrdev->buf + *ppos, count); 106 | - if (ret < 0) 107 | - return -EFAULT; 108 | + if (ret < 0) { 109 | + count = -EFAULT; 110 | + goto unlock; 111 | + } 112 | 113 | *ppos += count; 114 | dev_info(chrdev->dev, "return %ld bytes (*ppos=%lld)\n", count, *ppos); 115 | 116 | +unlock: 117 | + /* Release the mutex */ 118 | + mutex_unlock(&chrdev->mux); 119 | + 120 | return count; 121 | } 122 | 123 | @@ -172,18 +204,27 @@ static ssize_t chrdev_write(struct file *filp, 124 | if (chrdev->read_only) 125 | return -EINVAL; 126 | 127 | + /* Grab the mutex */ 128 | + mutex_lock(&chrdev->mux); 129 | + 130 | /* Check for end-of-buffer */ 131 | if (*ppos + count >= BUF_LEN) 132 | count = BUF_LEN - *ppos; 133 | 134 | /* Get data from the user space */ 135 | ret = copy_from_user(chrdev->buf + *ppos, buf, count); 136 | - if (ret < 0) 137 | - return -EFAULT; 138 | + if (ret < 0) { 139 | + count = -EFAULT; 140 | + goto unlock; 141 | + } 142 | 143 | *ppos += count; 144 | dev_info(chrdev->dev, "got %ld bytes (*ppos=%lld)\n", count, *ppos); 145 | 146 | +unlock: 147 | + /* Release the mutex */ 148 | + mutex_unlock(&chrdev->mux); 149 | + 150 | return count; 151 | } 152 | 153 | @@ -280,6 +321,7 @@ int chrdev_device_register(const char *label, unsigned int id, 154 | chrdev->read_only = read_only; 155 | chrdev->busy = 1; 156 | strncpy(chrdev->label, label, NAME_LEN); 157 | + mutex_init(&chrdev->mux); 158 | 159 | dev_info(chrdev->dev, "chrdev %s with id %d added\n", label, id); 160 | 161 | diff --git a/chapter_07/chrdev/chrdev.h b/chapter_07/chrdev/chrdev.h 162 | index 40a244f..4c8cd34 100644 163 | --- a/chapter_07/chrdev/chrdev.h 164 | +++ b/chapter_07/chrdev/chrdev.h 165 | @@ -3,6 +3,7 @@ 166 | */ 167 | 168 | #include 169 | +#include 170 | #include "chrdev_ioctl.h" 171 | 172 | #define MAX_DEVICES 8 173 | @@ -24,6 +25,8 @@ struct chrdev_device { 174 | struct module *owner; 175 | struct cdev cdev; 176 | struct device *dev; 177 | + 178 | + struct mutex mux; 179 | }; 180 | 181 | /* 182 | -------------------------------------------------------------------------------- /chapter_07/chrdev/chrdev-req.c: -------------------------------------------------------------------------------- 1 | /* 2 | * chrdev req 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include "chrdev.h" 15 | 16 | /* 17 | * Platform driver stuff 18 | */ 19 | 20 | static int chrdev_req_probe(struct platform_device *pdev) 21 | { 22 | struct device *dev = &pdev->dev; 23 | struct fwnode_handle *child; 24 | struct module *owner = THIS_MODULE; 25 | int count, ret; 26 | 27 | count = device_get_child_node_count(dev); 28 | if (count == 0) 29 | return -ENODEV; 30 | if (count > MAX_DEVICES) 31 | return -ENOMEM; 32 | 33 | device_for_each_child_node(dev, child) { 34 | const char *label; 35 | unsigned int id, ro; 36 | 37 | /* 38 | * Get device's properties 39 | */ 40 | 41 | if (fwnode_property_present(child, "reg")) { 42 | fwnode_property_read_u32(child, "reg", &id); 43 | } else { 44 | dev_err(dev, "property \"reg\" not present! Skipped"); 45 | continue; 46 | } 47 | if (fwnode_property_present(child, "label")) { 48 | fwnode_property_read_string(child, "label", &label); 49 | } else { 50 | dev_err(dev, "property \"label\" not present! Skipped"); 51 | continue; 52 | } 53 | ro = fwnode_property_present(child, "read-only"); 54 | 55 | /* Register the new chr device */ 56 | ret = chrdev_device_register(label, id, ro, owner, dev); 57 | if (ret) { 58 | dev_err(dev, "unable to register"); 59 | } 60 | } 61 | 62 | return 0; 63 | } 64 | 65 | static int chrdev_req_remove(struct platform_device *pdev) 66 | { 67 | struct device *dev = &pdev->dev; 68 | struct fwnode_handle *child; 69 | int ret; 70 | 71 | device_for_each_child_node(dev, child) { 72 | const char *label; 73 | int id; 74 | 75 | /* 76 | * Get device's properties 77 | */ 78 | 79 | if (fwnode_property_present(child, "reg")) 80 | fwnode_property_read_u32(child, "reg", &id); 81 | else 82 | BUG(); 83 | if (fwnode_property_present(child, "label")) 84 | fwnode_property_read_string(child, "label", &label); 85 | else 86 | BUG(); 87 | 88 | /* Register the new chr device */ 89 | ret = chrdev_device_unregister(label, id); 90 | if (ret) 91 | dev_err(dev, "unable to unregister"); 92 | } 93 | 94 | return 0; 95 | } 96 | 97 | static const struct of_device_id of_chrdev_req_match[] = { 98 | { 99 | .compatible = "ldddc,chrdev", 100 | }, 101 | { /* sentinel */ } 102 | }; 103 | MODULE_DEVICE_TABLE(of, of_chrdev_req_match); 104 | 105 | static struct platform_driver chrdev_req_driver = { 106 | .probe = chrdev_req_probe, 107 | .remove = chrdev_req_remove, 108 | .driver = { 109 | .name = "chrdev-req", 110 | .of_match_table = of_chrdev_req_match, 111 | }, 112 | }; 113 | module_platform_driver(chrdev_req_driver); 114 | 115 | MODULE_LICENSE("GPL"); 116 | MODULE_AUTHOR("Rodolfo Giometti"); 117 | MODULE_DESCRIPTION("chrdev request"); 118 | -------------------------------------------------------------------------------- /chapter_07/chrdev/chrdev.c: -------------------------------------------------------------------------------- 1 | /* 2 | * chrdev 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | 14 | #include "chrdev.h" 15 | 16 | /* 17 | * Local variables 18 | */ 19 | 20 | static dev_t chrdev_devt; 21 | static struct class *chrdev_class; 22 | 23 | struct chrdev_device chrdev_array[MAX_DEVICES]; 24 | 25 | /* 26 | * Methods 27 | */ 28 | 29 | static int chrdev_mmap(struct file *filp, struct vm_area_struct *vma) 30 | { 31 | struct chrdev_device *chrdev = filp->private_data; 32 | size_t size = vma->vm_end - vma->vm_start; 33 | phys_addr_t offset = (phys_addr_t) vma->vm_pgoff << PAGE_SHIFT; 34 | unsigned long pfn; 35 | 36 | /* Does it even fit in phys_addr_t? */ 37 | if (offset >> PAGE_SHIFT != vma->vm_pgoff) 38 | return -EINVAL; 39 | 40 | /* We cannot mmap too big areas */ 41 | if ((offset > BUF_LEN) || (size > BUF_LEN - offset)) 42 | return -EINVAL; 43 | 44 | /* Get the physical address belong the virtual kernel address */ 45 | pfn = virt_to_phys(chrdev->buf) >> PAGE_SHIFT; 46 | 47 | dev_info(chrdev->dev, "mmap vma=%lx pfn=%lx size=%lx", 48 | vma->vm_start, pfn, size); 49 | 50 | /* Remap-pfn-range will mark the range VM_IO */ 51 | if (remap_pfn_range(vma, vma->vm_start, 52 | pfn, size, 53 | vma->vm_page_prot)) 54 | return -EAGAIN; 55 | 56 | return 0; 57 | } 58 | 59 | static long chrdev_ioctl(struct file *filp, 60 | unsigned int cmd, unsigned long arg) 61 | { 62 | struct chrdev_device *chrdev = filp->private_data; 63 | struct chrdev_info info; 64 | void __user *uarg = (void __user *) arg; 65 | int __user *iuarg = (int __user *) arg; 66 | int ret; 67 | 68 | /* Get some command information */ 69 | if (_IOC_TYPE(cmd) != CHRDEV_IOCTL_BASE) { 70 | dev_err(chrdev->dev, "command %x is not for us!\n", cmd); 71 | return -EINVAL; 72 | } 73 | dev_info(chrdev->dev, "cmd nr=%d size=%d dir=%x\n", 74 | _IOC_NR(cmd), _IOC_SIZE(cmd), _IOC_DIR(cmd)); 75 | 76 | switch (cmd) { 77 | case CHRDEV_IOC_GETINFO: 78 | dev_info(chrdev->dev, "CHRDEV_IOC_GETINFO\n"); 79 | 80 | strncpy(info.label, chrdev->label, NAME_LEN); 81 | info.read_only = chrdev->read_only; 82 | 83 | ret = copy_to_user(uarg, &info, sizeof(struct chrdev_info)); 84 | if (ret) 85 | return -EFAULT; 86 | 87 | break; 88 | 89 | case WDIOC_SET_RDONLY: 90 | dev_info(chrdev->dev, "WDIOC_SET_RDONLY\n"); 91 | 92 | ret = get_user(chrdev->read_only, iuarg); 93 | if (ret) 94 | return -EFAULT; 95 | 96 | break; 97 | 98 | default: 99 | return -ENOIOCTLCMD; 100 | } 101 | 102 | return 0; 103 | } 104 | 105 | static loff_t chrdev_llseek(struct file *filp, loff_t offset, int whence) 106 | { 107 | struct chrdev_device *chrdev = filp->private_data; 108 | loff_t newppos; 109 | 110 | dev_info(chrdev->dev, "should move *ppos=%lld by whence %d off=%lld\n", 111 | filp->f_pos, whence, offset); 112 | 113 | switch (whence) { 114 | case SEEK_SET: 115 | newppos = offset; 116 | break; 117 | 118 | case SEEK_CUR: 119 | newppos = filp->f_pos + offset; 120 | break; 121 | 122 | case SEEK_END: 123 | newppos = BUF_LEN + offset; 124 | break; 125 | 126 | default: 127 | return -EINVAL; 128 | } 129 | 130 | if ((newppos < 0) || (newppos >= BUF_LEN)) 131 | return -EINVAL; 132 | 133 | filp->f_pos = newppos; 134 | dev_info(chrdev->dev, "return *ppos=%lld\n", filp->f_pos); 135 | 136 | return newppos; 137 | } 138 | 139 | static ssize_t chrdev_read(struct file *filp, 140 | char __user *buf, size_t count, loff_t *ppos) 141 | { 142 | struct chrdev_device *chrdev = filp->private_data; 143 | int ret; 144 | 145 | dev_info(chrdev->dev, "should read %ld bytes (*ppos=%lld)\n", 146 | count, *ppos); 147 | 148 | /* Check for end-of-buffer */ 149 | if (*ppos + count >= BUF_LEN) 150 | count = BUF_LEN - *ppos; 151 | 152 | /* Return data to the user space */ 153 | ret = copy_to_user(buf, chrdev->buf + *ppos, count); 154 | if (ret < 0) 155 | return -EFAULT; 156 | 157 | *ppos += count; 158 | dev_info(chrdev->dev, "return %ld bytes (*ppos=%lld)\n", count, *ppos); 159 | 160 | return count; 161 | } 162 | 163 | static ssize_t chrdev_write(struct file *filp, 164 | const char __user *buf, size_t count, loff_t *ppos) 165 | { 166 | struct chrdev_device *chrdev = filp->private_data; 167 | int ret; 168 | 169 | dev_info(chrdev->dev, "should write %ld bytes (*ppos=%lld)\n", 170 | count, *ppos); 171 | 172 | if (chrdev->read_only) 173 | return -EINVAL; 174 | 175 | /* Check for end-of-buffer */ 176 | if (*ppos + count >= BUF_LEN) 177 | count = BUF_LEN - *ppos; 178 | 179 | /* Get data from the user space */ 180 | ret = copy_from_user(chrdev->buf + *ppos, buf, count); 181 | if (ret < 0) 182 | return -EFAULT; 183 | 184 | *ppos += count; 185 | dev_info(chrdev->dev, "got %ld bytes (*ppos=%lld)\n", count, *ppos); 186 | 187 | return count; 188 | } 189 | 190 | static int chrdev_open(struct inode *inode, struct file *filp) 191 | { 192 | struct chrdev_device *chrdev = container_of(inode->i_cdev, 193 | struct chrdev_device, cdev); 194 | filp->private_data = chrdev; 195 | kobject_get(&chrdev->dev->kobj); 196 | 197 | dev_info(chrdev->dev, "chrdev (id=%d) opened\n", chrdev->id); 198 | 199 | return 0; 200 | } 201 | 202 | static int chrdev_release(struct inode *inode, struct file *filp) 203 | { 204 | struct chrdev_device *chrdev = container_of(inode->i_cdev, 205 | struct chrdev_device, cdev); 206 | kobject_put(&chrdev->dev->kobj); 207 | filp->private_data = NULL; 208 | 209 | dev_info(chrdev->dev, "chrdev (id=%d) released\n", chrdev->id); 210 | 211 | return 0; 212 | } 213 | 214 | static const struct file_operations chrdev_fops = { 215 | .owner = THIS_MODULE, 216 | .mmap = chrdev_mmap, 217 | .unlocked_ioctl = chrdev_ioctl, 218 | .llseek = chrdev_llseek, 219 | .read = chrdev_read, 220 | .write = chrdev_write, 221 | .open = chrdev_open, 222 | .release = chrdev_release 223 | }; 224 | 225 | /* 226 | * Exported functions 227 | */ 228 | 229 | int chrdev_device_register(const char *label, unsigned int id, 230 | unsigned int read_only, 231 | struct module *owner, struct device *parent) 232 | { 233 | struct chrdev_device *chrdev; 234 | dev_t devt; 235 | int ret; 236 | 237 | /* First check if we are allocating a valid device... */ 238 | if (id >= MAX_DEVICES) { 239 | pr_err("invalid id %d\n", id); 240 | return -EINVAL; 241 | } 242 | chrdev = &chrdev_array[id]; 243 | 244 | /* ... then check if we have not busy id */ 245 | if (chrdev->busy) { 246 | pr_err("id %d\n is busy", id); 247 | return -EBUSY; 248 | } 249 | 250 | /* First try to allocate memory for internal buffer */ 251 | chrdev->buf = kzalloc(BUF_LEN, GFP_KERNEL); 252 | if (!chrdev->buf) { 253 | dev_err(chrdev->dev, "cannot allocate memory buffer!\n"); 254 | return -ENOMEM; 255 | } 256 | 257 | /* Create the device and initialize its data */ 258 | cdev_init(&chrdev->cdev, &chrdev_fops); 259 | chrdev->cdev.owner = owner; 260 | 261 | devt = MKDEV(MAJOR(chrdev_devt), id); 262 | ret = cdev_add(&chrdev->cdev, devt, 1); 263 | if (ret) { 264 | pr_err("failed to add char device %s at %d:%d\n", 265 | label, MAJOR(chrdev_devt), id); 266 | goto kfree_buf; 267 | } 268 | 269 | chrdev->dev = device_create(chrdev_class, parent, devt, chrdev, 270 | "%s@%d", label, id); 271 | if (IS_ERR(chrdev->dev)) { 272 | pr_err("unable to create device %s\n", label); 273 | ret = PTR_ERR(chrdev->dev); 274 | goto del_cdev; 275 | } 276 | dev_set_drvdata(chrdev->dev, chrdev); 277 | 278 | /* Init the chrdev data */ 279 | chrdev->id = id; 280 | chrdev->read_only = read_only; 281 | chrdev->busy = 1; 282 | strncpy(chrdev->label, label, NAME_LEN); 283 | 284 | dev_info(chrdev->dev, "chrdev %s with id %d added\n", label, id); 285 | 286 | return 0; 287 | 288 | del_cdev: 289 | cdev_del(&chrdev->cdev); 290 | kfree_buf: 291 | kfree(chrdev->buf); 292 | 293 | return ret; 294 | } 295 | EXPORT_SYMBOL(chrdev_device_register); 296 | 297 | int chrdev_device_unregister(const char *label, unsigned int id) 298 | { 299 | struct chrdev_device *chrdev; 300 | 301 | /* First check if we are deallocating a valid device... */ 302 | if (id >= MAX_DEVICES) { 303 | pr_err("invalid id %d\n", id); 304 | return -EINVAL; 305 | } 306 | chrdev = &chrdev_array[id]; 307 | 308 | /* ... then check if device is actualy allocated */ 309 | if (!chrdev->busy || strcmp(chrdev->label, label)) { 310 | pr_err("id %d is not busy or label %s is not known\n", 311 | id, label); 312 | return -EINVAL; 313 | } 314 | 315 | /* Deinit the chrdev data */ 316 | chrdev->id = 0; 317 | chrdev->busy = 0; 318 | 319 | dev_info(chrdev->dev, "chrdev %s with id %d removed\n", label, id); 320 | 321 | /* Free allocated memory */ 322 | kfree(chrdev->buf); 323 | 324 | /* Dealocate the device */ 325 | device_destroy(chrdev_class, chrdev->dev->devt); 326 | cdev_del(&chrdev->cdev); 327 | 328 | return 0; 329 | } 330 | EXPORT_SYMBOL(chrdev_device_unregister); 331 | 332 | /* 333 | * Module stuff 334 | */ 335 | 336 | static int __init chrdev_init(void) 337 | { 338 | int ret; 339 | 340 | /* Create the new class for the chrdev devices */ 341 | chrdev_class = class_create(THIS_MODULE, "chrdev"); 342 | if (!chrdev_class) { 343 | pr_err("chrdev: failed to allocate class\n"); 344 | return -ENOMEM; 345 | } 346 | 347 | /* Allocate a region for character devices */ 348 | ret = alloc_chrdev_region(&chrdev_devt, 0, MAX_DEVICES, "chrdev"); 349 | if (ret < 0) { 350 | pr_err("failed to allocate char device region\n"); 351 | goto remove_class; 352 | } 353 | 354 | pr_info("got major %d\n", MAJOR(chrdev_devt)); 355 | 356 | return 0; 357 | 358 | remove_class: 359 | class_destroy(chrdev_class); 360 | 361 | return ret; 362 | } 363 | 364 | static void __exit chrdev_exit(void) 365 | { 366 | unregister_chrdev_region(chrdev_devt, MAX_DEVICES); 367 | class_destroy(chrdev_class); 368 | } 369 | 370 | module_init(chrdev_init); 371 | module_exit(chrdev_exit); 372 | 373 | MODULE_LICENSE("GPL"); 374 | MODULE_AUTHOR("Rodolfo Giometti"); 375 | MODULE_DESCRIPTION("chardev"); 376 | -------------------------------------------------------------------------------- /chapter_07/chrdev/chrdev.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Chrdev include file 3 | */ 4 | 5 | #include 6 | #include "chrdev_ioctl.h" 7 | 8 | #define MAX_DEVICES 8 9 | #define NAME_LEN CHRDEV_NAME_LEN 10 | #define BUF_LEN PAGE_SIZE 11 | 12 | /* 13 | * Chrdev basic structs 14 | */ 15 | 16 | /* Main struct */ 17 | struct chrdev_device { 18 | char label[NAME_LEN]; 19 | unsigned int busy : 1; 20 | char *buf; 21 | int read_only; 22 | 23 | unsigned int id; 24 | struct module *owner; 25 | struct cdev cdev; 26 | struct device *dev; 27 | }; 28 | 29 | /* 30 | * Exported functions 31 | */ 32 | 33 | #define to_class_dev(obj) container_of((obj), struct class_device, kobj) 34 | #define to_chrdev_device(obj) container_of((obj), struct chrdev_device, class) 35 | 36 | extern int chrdev_device_register(const char *label, unsigned int id, 37 | unsigned int read_only, 38 | struct module *owner, struct device *parent); 39 | extern int chrdev_device_unregister(const char *label, unsigned int id); 40 | -------------------------------------------------------------------------------- /chapter_07/chrdev/chrdev_ioctl.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Chrdev ioctl() include file 3 | */ 4 | 5 | #include 6 | #include 7 | 8 | #define CHRDEV_IOCTL_BASE 'C' 9 | #define CHRDEV_NAME_LEN 32 10 | 11 | struct chrdev_info { 12 | char label[CHRDEV_NAME_LEN]; 13 | int read_only; 14 | }; 15 | 16 | /* 17 | * The ioctl() commands 18 | */ 19 | 20 | #define CHRDEV_IOC_GETINFO _IOR(CHRDEV_IOCTL_BASE, 0, struct chrdev_info) 21 | #define WDIOC_SET_RDONLY _IOW(CHRDEV_IOCTL_BASE, 1, int) 22 | -------------------------------------------------------------------------------- /chapter_07/chrdev/chrdev_irq.c: -------------------------------------------------------------------------------- 1 | /* 2 | * chrdev 3 | */ 4 | 5 | #define pr_fmt(fmt) "%s:%s: " fmt, KBUILD_MODNAME, __func__ 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include "chrdev_irq.h" 15 | 16 | /* 17 | * Module parameter 18 | */ 19 | 20 | static int delay_ns = 1000000000; 21 | module_param(delay_ns, int, S_IRUSR | S_IWUSR); 22 | MODULE_PARM_DESC(delay_ns, "kernel timer delay is ns"); 23 | 24 | /* 25 | * Local variables 26 | */ 27 | 28 | static dev_t chrdev_devt; 29 | static struct class *chrdev_class; 30 | 31 | struct chrdev_device chrdev_array[MAX_DEVICES]; 32 | 33 | /* 34 | * Dummy function to generate data 35 | */ 36 | 37 | static char get_new_char(void) 38 | { 39 | static char d = 'A' - 1; 40 | 41 | if (++d == ('Z' + 1)) 42 | d = 'A'; 43 | 44 | return d; 45 | } 46 | 47 | /* 48 | * Circular buffer management functions 49 | */ 50 | 51 | static inline bool cbuf_is_empty(size_t head, size_t tail, size_t len) 52 | { 53 | return head == tail; 54 | } 55 | 56 | static inline bool cbuf_is_full(size_t head, size_t tail, size_t len) 57 | { 58 | head = (head + 1) % len; 59 | return head == tail; 60 | } 61 | 62 | static inline size_t cbuf_count_to_end(size_t head, size_t tail, size_t len) 63 | { 64 | if (head >= tail) 65 | return head - tail; 66 | else 67 | return len - tail + head; 68 | } 69 | 70 | static inline size_t cbuf_space_to_end(size_t head, size_t tail, size_t len) 71 | { 72 | if (head >= tail) 73 | return len - head + tail - 1; 74 | else 75 | return tail - head - 1; 76 | } 77 | 78 | static inline void cbuf_pointer_move(size_t *ptr, size_t n, size_t len) 79 | { 80 | *ptr = (*ptr + n) % len; 81 | } 82 | 83 | /* 84 | * (simulation of) IRQ handler 85 | */ 86 | 87 | static enum hrtimer_restart chrdev_timer_handler(struct hrtimer *ptr) 88 | { 89 | struct chrdev_device *chrdev = container_of(ptr, 90 | struct chrdev_device, timer); 91 | 92 | /* Grab the lock */ 93 | spin_lock(&chrdev->lock); 94 | 95 | /* Now we should check if we have some space to 96 | * save incoming data, otherwise they must be dropped... 97 | */ 98 | if (!cbuf_is_full(chrdev->head, chrdev->tail, BUF_LEN)) { 99 | chrdev->buf[chrdev->head] = get_new_char(); 100 | 101 | cbuf_pointer_move(&chrdev->head, 1, BUF_LEN); 102 | } 103 | 104 | /* Release the lock */ 105 | spin_unlock(&chrdev->lock); 106 | 107 | /* Wake up any possible sleeping process */ 108 | wake_up_interruptible(&chrdev->queue); 109 | kill_fasync(&chrdev->fasync_queue, SIGIO, POLL_IN); 110 | 111 | /* Now forward the expiration time and ask to be rescheduled */ 112 | hrtimer_forward_now(&chrdev->timer, ns_to_ktime(delay_ns)); 113 | return HRTIMER_RESTART; 114 | } 115 | 116 | /* 117 | * Methods 118 | */ 119 | 120 | static int chrdev_fasync(int fd, struct file *filp, int on) 121 | { 122 | struct chrdev_device *chrdev = filp->private_data; 123 | 124 | return fasync_helper(fd, filp, on, &chrdev->fasync_queue); 125 | } 126 | 127 | static __poll_t chrdev_poll(struct file *filp, poll_table *wait) 128 | { 129 | struct chrdev_device *chrdev = filp->private_data; 130 | __poll_t mask = 0; 131 | 132 | poll_wait(filp, &chrdev->queue, wait); 133 | 134 | /* Grab the mutex */ 135 | mutex_lock(&chrdev->mux); 136 | 137 | if (!cbuf_is_empty(chrdev->head, chrdev->tail, BUF_LEN)) 138 | mask |= EPOLLIN | EPOLLRDNORM; 139 | 140 | /* Release the mutex */ 141 | mutex_unlock(&chrdev->mux); 142 | 143 | return mask; 144 | } 145 | 146 | static ssize_t chrdev_read(struct file *filp, 147 | char __user *buf, size_t count, loff_t *ppos) 148 | { 149 | struct chrdev_device *chrdev = filp->private_data; 150 | unsigned long flags; 151 | char tmp[256]; 152 | size_t n; 153 | int ret; 154 | 155 | dev_info(chrdev->dev, "should read %ld bytes\n", count); 156 | 157 | /* Grab the mutex */ 158 | mutex_lock(&chrdev->mux); 159 | 160 | /* Check for some data into read buffer */ 161 | if (filp->f_flags & O_NONBLOCK) { 162 | if (cbuf_is_empty(chrdev->head, chrdev->tail, BUF_LEN)) { 163 | ret = -EAGAIN; 164 | goto unlock; 165 | } 166 | } else if (wait_event_interruptible(chrdev->queue, 167 | !cbuf_is_empty(chrdev->head, chrdev->tail, BUF_LEN))) { 168 | count = -ERESTARTSYS; 169 | goto unlock; 170 | } 171 | 172 | /* Grab the lock */ 173 | spin_lock_irqsave(&chrdev->lock, flags); 174 | 175 | /* Get data from the circular buffer */ 176 | n = cbuf_count_to_end(chrdev->head, chrdev->tail, BUF_LEN); 177 | count = min(count, n); 178 | memcpy(tmp, &chrdev->buf[chrdev->tail], count); 179 | 180 | /* Release the lock */ 181 | spin_unlock_irqrestore(&chrdev->lock, flags); 182 | 183 | /* Return data to the user space */ 184 | ret = copy_to_user(buf, tmp, count); 185 | if (ret < 0) { 186 | ret = -EFAULT; 187 | goto unlock; 188 | } 189 | 190 | /* Now we can safely move the tail pointer */ 191 | cbuf_pointer_move(&chrdev->tail, count, BUF_LEN); 192 | dev_info(chrdev->dev, "return %ld bytes\n", count); 193 | 194 | unlock: 195 | /* Release the mutex */ 196 | mutex_unlock(&chrdev->mux); 197 | 198 | return count; 199 | } 200 | 201 | static int chrdev_open(struct inode *inode, struct file *filp) 202 | { 203 | struct chrdev_device *chrdev = container_of(inode->i_cdev, 204 | struct chrdev_device, cdev); 205 | filp->private_data = chrdev; 206 | kobject_get(&chrdev->dev->kobj); 207 | 208 | dev_info(chrdev->dev, "chrdev (id=%d) opened\n", chrdev->id); 209 | 210 | return 0; 211 | } 212 | 213 | static int chrdev_release(struct inode *inode, struct file *filp) 214 | { 215 | struct chrdev_device *chrdev = container_of(inode->i_cdev, 216 | struct chrdev_device, cdev); 217 | kobject_put(&chrdev->dev->kobj); 218 | filp->private_data = NULL; 219 | 220 | dev_info(chrdev->dev, "chrdev (id=%d) released\n", chrdev->id); 221 | 222 | return 0; 223 | } 224 | 225 | static const struct file_operations chrdev_fops = { 226 | .owner = THIS_MODULE, 227 | .fasync = chrdev_fasync, 228 | .poll = chrdev_poll, 229 | .llseek = no_llseek, 230 | .read = chrdev_read, 231 | .open = chrdev_open, 232 | .release = chrdev_release 233 | }; 234 | 235 | /* 236 | * Exported functions 237 | */ 238 | 239 | int chrdev_device_register(const char *label, unsigned int id, 240 | unsigned int read_only, 241 | struct module *owner, struct device *parent) 242 | { 243 | struct chrdev_device *chrdev; 244 | dev_t devt; 245 | int ret; 246 | 247 | /* First check if we are allocating a valid device... */ 248 | if (id >= MAX_DEVICES) { 249 | pr_err("invalid id %d\n", id); 250 | return -EINVAL; 251 | } 252 | chrdev = &chrdev_array[id]; 253 | 254 | /* ... then check if we have not busy id */ 255 | if (chrdev->busy) { 256 | pr_err("id %d\n is busy", id); 257 | return -EBUSY; 258 | } 259 | 260 | /* First try to allocate memory for internal buffer */ 261 | chrdev->buf = kzalloc(BUF_LEN, GFP_KERNEL); 262 | if (!chrdev->buf) { 263 | dev_err(chrdev->dev, "cannot allocate memory buffer!\n"); 264 | return -ENOMEM; 265 | } 266 | 267 | /* Create the device and initialize its data */ 268 | cdev_init(&chrdev->cdev, &chrdev_fops); 269 | chrdev->cdev.owner = owner; 270 | 271 | devt = MKDEV(MAJOR(chrdev_devt), id); 272 | ret = cdev_add(&chrdev->cdev, devt, 1); 273 | if (ret) { 274 | pr_err("failed to add char device %s at %d:%d\n", 275 | label, MAJOR(chrdev_devt), id); 276 | goto kfree_buf; 277 | } 278 | 279 | chrdev->dev = device_create(chrdev_class, parent, devt, chrdev, 280 | "%s@%d", label, id); 281 | if (IS_ERR(chrdev->dev)) { 282 | pr_err("unable to create device %s\n", label); 283 | ret = PTR_ERR(chrdev->dev); 284 | goto del_cdev; 285 | } 286 | dev_set_drvdata(chrdev->dev, chrdev); 287 | 288 | /* Init the chrdev data */ 289 | chrdev->id = id; 290 | chrdev->read_only = read_only; 291 | chrdev->busy = 1; 292 | strncpy(chrdev->label, label, NAME_LEN); 293 | mutex_init(&chrdev->mux); 294 | spin_lock_init(&chrdev->lock); 295 | init_waitqueue_head(&chrdev->queue); 296 | chrdev->head = chrdev->tail = 0; 297 | chrdev->fasync_queue = NULL; 298 | 299 | /* Setup and start the hires timer */ 300 | hrtimer_init(&chrdev->timer, CLOCK_MONOTONIC, 301 | HRTIMER_MODE_REL | HRTIMER_MODE_SOFT); 302 | chrdev->timer.function = chrdev_timer_handler; 303 | hrtimer_start(&chrdev->timer, ns_to_ktime(delay_ns), 304 | HRTIMER_MODE_REL | HRTIMER_MODE_SOFT); 305 | 306 | 307 | dev_info(chrdev->dev, "chrdev %s with id %d added\n", label, id); 308 | 309 | return 0; 310 | 311 | del_cdev: 312 | cdev_del(&chrdev->cdev); 313 | kfree_buf: 314 | kfree(chrdev->buf); 315 | 316 | return ret; 317 | } 318 | EXPORT_SYMBOL(chrdev_device_register); 319 | 320 | int chrdev_device_unregister(const char *label, unsigned int id) 321 | { 322 | struct chrdev_device *chrdev; 323 | 324 | /* First check if we are deallocating a valid device... */ 325 | if (id >= MAX_DEVICES) { 326 | pr_err("invalid id %d\n", id); 327 | return -EINVAL; 328 | } 329 | chrdev = &chrdev_array[id]; 330 | 331 | /* ... then check if device is actualy allocated */ 332 | if (!chrdev->busy || strcmp(chrdev->label, label)) { 333 | pr_err("id %d is not busy or label %s is not known\n", 334 | id, label); 335 | return -EINVAL; 336 | } 337 | 338 | /* Stop the timer */ 339 | hrtimer_cancel(&chrdev->timer); 340 | 341 | /* Deinit the chrdev data */ 342 | chrdev->id = 0; 343 | chrdev->busy = 0; 344 | 345 | dev_info(chrdev->dev, "chrdev %s with id %d removed\n", label, id); 346 | 347 | /* Free allocated memory */ 348 | kfree(chrdev->buf); 349 | 350 | /* Dealocate the device */ 351 | device_destroy(chrdev_class, chrdev->dev->devt); 352 | cdev_del(&chrdev->cdev); 353 | 354 | return 0; 355 | } 356 | EXPORT_SYMBOL(chrdev_device_unregister); 357 | 358 | /* 359 | * Module stuff 360 | */ 361 | 362 | static int __init chrdev_init(void) 363 | { 364 | int ret; 365 | 366 | /* Create the new class for the chrdev devices */ 367 | chrdev_class = class_create(THIS_MODULE, "chrdev"); 368 | if (!chrdev_class) { 369 | pr_err("chrdev: failed to allocate class\n"); 370 | return -ENOMEM; 371 | } 372 | 373 | /* Allocate a region for character devices */ 374 | ret = alloc_chrdev_region(&chrdev_devt, 0, MAX_DEVICES, "chrdev"); 375 | if (ret < 0) { 376 | pr_err("failed to allocate char device region\n"); 377 | goto remove_class; 378 | } 379 | 380 | pr_info("got major %d\n", MAJOR(chrdev_devt)); 381 | 382 | return 0; 383 | 384 | remove_class: 385 | class_destroy(chrdev_class); 386 | 387 | return ret; 388 | } 389 | 390 | static void __exit chrdev_exit(void) 391 | { 392 | unregister_chrdev_region(chrdev_devt, MAX_DEVICES); 393 | class_destroy(chrdev_class); 394 | } 395 | 396 | module_init(chrdev_init); 397 | module_exit(chrdev_exit); 398 | 399 | MODULE_LICENSE("GPL"); 400 | MODULE_AUTHOR("Rodolfo Giometti"); 401 | MODULE_DESCRIPTION("chardev"); 402 | -------------------------------------------------------------------------------- /chapter_07/chrdev/chrdev_irq.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Chrdev include file 3 | */ 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #define MAX_DEVICES 8 12 | #define NAME_LEN 32 13 | #define BUF_LEN PAGE_SIZE 14 | 15 | /* 16 | * Chrdev basic structs 17 | */ 18 | 19 | /* Main struct */ 20 | struct chrdev_device { 21 | char label[NAME_LEN]; 22 | unsigned int busy : 1; 23 | char *buf; 24 | size_t head, tail; 25 | int read_only; 26 | 27 | unsigned int id; 28 | struct module *owner; 29 | struct cdev cdev; 30 | struct device *dev; 31 | 32 | struct mutex mux; 33 | struct spinlock lock; 34 | struct wait_queue_head queue; 35 | struct hrtimer timer; 36 | struct fasync_struct *fasync_queue; 37 | }; 38 | 39 | /* 40 | * Exported functions 41 | */ 42 | 43 | #define to_class_dev(obj) container_of((obj), struct class_device, kobj) 44 | #define to_chrdev_device(obj) container_of((obj), struct chrdev_device, class) 45 | 46 | extern int chrdev_device_register(const char *label, unsigned int id, 47 | unsigned int read_only, 48 | struct module *owner, struct device *parent); 49 | extern int chrdev_device_unregister(const char *label, unsigned int id); 50 | -------------------------------------------------------------------------------- /chapter_07/chrdev/modify_lseek_to_chrdev_test.patch: -------------------------------------------------------------------------------- 1 | diff --git a/chapter_03/chrdev_test.c b/chapter_03/chrdev_test.c 2 | index 94e04e0..3e8420d 100644 3 | --- a/chapter_03/chrdev_test.c 4 | +++ b/chapter_03/chrdev_test.c 5 | @@ -55,6 +55,13 @@ int main(int argc, char *argv[]) 6 | dump("data written are: ", buf + c, n); 7 | } 8 | 9 | + ret = lseek(fd, SEEK_SET, 0); 10 | + if (ret < 0) { 11 | + perror("lseek"); 12 | + exit(EXIT_FAILURE); 13 | + } 14 | + printf("*ppos moved to 0\n"); 15 | + 16 | for (c = 0; c < sizeof(buf); c += n) { 17 | ret = read(fd, buf, sizeof(buf)); 18 | if (ret == 0) { 19 | -------------------------------------------------------------------------------- /chapter_07/chrdev_fasync.c: -------------------------------------------------------------------------------- 1 | /* 2 | * chrdev fasync() testing program 3 | */ 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #define __USE_GNU 13 | #include 14 | 15 | int fd; 16 | 17 | void sigio_handler(int unused) { 18 | char c; 19 | int ret; 20 | 21 | ret = read(fd, &c, 1); 22 | if (ret < 0) { 23 | perror("read"); 24 | exit(EXIT_FAILURE); 25 | } 26 | ret = write(STDOUT_FILENO, &c, 1); 27 | if (ret < 0) { 28 | perror("write"); 29 | exit(EXIT_FAILURE); 30 | } 31 | } 32 | 33 | int main(int argc, char *argv[]) 34 | { 35 | sighandler_t sigh; 36 | long flags; 37 | char c; 38 | int ret; 39 | 40 | if (argc < 2) { 41 | fprintf(stderr, "usage: %s \n", argv[0]); 42 | exit(EXIT_FAILURE); 43 | } 44 | 45 | ret = open(argv[1], O_RDWR); 46 | if (ret < 0) { 47 | perror("open"); 48 | exit(EXIT_FAILURE); 49 | } 50 | printf("file %s opened\n", argv[1]); 51 | fd = ret; 52 | 53 | /* Try to install the signal handler and the fasync stuff */ 54 | sigh = signal(SIGIO, sigio_handler); 55 | if (sigh == SIG_ERR) { 56 | perror("signal"); 57 | exit(EXIT_FAILURE); 58 | } 59 | ret = fcntl(fd, F_SETOWN, getpid()); 60 | if (ret < 0) { 61 | perror("fcntl(..., F_SETOWN, ...)"); 62 | exit(EXIT_FAILURE); 63 | } 64 | flags = fcntl(fd, F_GETFL); 65 | if (flags < 0) { 66 | perror("fcntl(..., F_GETFL)"); 67 | exit(EXIT_FAILURE); 68 | } 69 | ret = fcntl(fd, F_SETFL, flags | FASYNC); 70 | if (flags < 0) { 71 | perror("fcntl(..., F_SETFL, ...)"); 72 | exit(EXIT_FAILURE); 73 | } 74 | 75 | /* Now we can wait for data while waiting data from stdin */ 76 | while (1) { 77 | ret = read(STDOUT_FILENO, &c, 1); 78 | if (ret < 0) { 79 | perror("read"); 80 | exit(EXIT_FAILURE); 81 | } 82 | printf("got '%c' from stdin!\n", c); 83 | } 84 | 85 | signal(SIGIO, NULL); 86 | close(fd); 87 | 88 | return 0; 89 | } 90 | -------------------------------------------------------------------------------- /chapter_07/chrdev_ioctl.c: -------------------------------------------------------------------------------- 1 | /* 2 | * chrdev ioctl() testing program 3 | */ 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | #include "chrdev_ioctl.h" 15 | 16 | int main(int argc, char *argv[]) 17 | { 18 | int fd; 19 | struct chrdev_info info; 20 | int read_only; 21 | int ret; 22 | 23 | if (argc < 2) { 24 | fprintf(stderr, "usage: %s \n", argv[0]); 25 | exit(EXIT_FAILURE); 26 | } 27 | 28 | ret = open(argv[1], O_RDWR); 29 | if (ret < 0) { 30 | perror("open"); 31 | exit(EXIT_FAILURE); 32 | } 33 | printf("file %s opened\n", argv[1]); 34 | fd = ret; 35 | 36 | /* Try reading device info */ 37 | ret = ioctl(fd, CHRDEV_IOC_GETINFO, &info); 38 | if (ret < 0) { 39 | perror("ioctl(CHRDEV_IOC_GETINFO)"); 40 | exit(EXIT_FAILURE); 41 | } 42 | printf("got label=%s and read_only=%d\n", info.label, info.read_only); 43 | 44 | /* Try toggling the device reading mode */ 45 | read_only = !info.read_only; 46 | ret = ioctl(fd, WDIOC_SET_RDONLY, &read_only); 47 | if (ret < 0) { 48 | perror("ioctl(WDIOC_SET_RDONLY)"); 49 | exit(EXIT_FAILURE); 50 | } 51 | printf("device has now read_only=%d\n", read_only); 52 | 53 | close(fd); 54 | 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /chapter_07/chrdev_mmap.c: -------------------------------------------------------------------------------- 1 | /* 2 | * chrdev mmap() testing program 3 | */ 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | int main(int argc, char *argv[]) 15 | { 16 | int fd; 17 | void *addr; 18 | long len; 19 | char *ptr; 20 | int i; 21 | int ret; 22 | 23 | if (argc < 2) { 24 | fprintf(stderr, "usage: %s []\n", argv[0]); 25 | exit(EXIT_FAILURE); 26 | } 27 | len = atol(argv[2]); 28 | 29 | ret = open(argv[1], O_RDWR); 30 | if (ret < 0) { 31 | perror("open"); 32 | exit(EXIT_FAILURE); 33 | } 34 | printf("file %s opened\n", argv[1]); 35 | fd = ret; 36 | 37 | /* Try to remap file into memory */ 38 | addr = mmap(NULL, len, PROT_READ | PROT_WRITE, 39 | MAP_FILE | MAP_SHARED, fd, 0); 40 | if (addr == MAP_FAILED) { 41 | perror("mmap"); 42 | exit(EXIT_FAILURE); 43 | } 44 | printf("got address=%p and len=%ld\n", addr, len); 45 | 46 | /* Do a (partial) dump of the file as it was a buffer of bytes */ 47 | printf("---\n"); 48 | ptr = (char *) addr; 49 | for (i = 0; i < len; i++) 50 | printf("%c", ptr[i]); 51 | 52 | /* Just in case, we modify the first byte by writing char */ 53 | if (argc == 4) { 54 | ptr[0] = argv[3][0]; 55 | printf("---\nFirst character changed to '%c'\n", ptr[0]); 56 | } 57 | 58 | munmap(addr, len); 59 | close(fd); 60 | 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /chapter_07/chrdev_select.c: -------------------------------------------------------------------------------- 1 | /* 2 | * chrdev select() testing program 3 | */ 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | int main(int argc, char *argv[]) 15 | { 16 | int fd; 17 | fd_set read_fds; 18 | char c; 19 | int ret; 20 | 21 | if (argc < 2) { 22 | fprintf(stderr, "usage: %s \n", argv[0]); 23 | exit(EXIT_FAILURE); 24 | } 25 | 26 | ret = open(argv[1], O_RDWR); 27 | if (ret < 0) { 28 | perror("open"); 29 | exit(EXIT_FAILURE); 30 | } 31 | printf("file %s opened\n", argv[1]); 32 | fd = ret; 33 | 34 | while (1) { 35 | /* Set up reading file descriptors */ 36 | FD_ZERO(&read_fds); 37 | FD_SET(STDIN_FILENO, &read_fds); 38 | FD_SET(fd, &read_fds); 39 | 40 | /* Wait for any data fro our device or stdin */ 41 | ret = select(FD_SETSIZE, &read_fds, NULL, NULL, NULL); 42 | if (ret < 0) { 43 | perror("select"); 44 | exit(EXIT_FAILURE); 45 | } 46 | 47 | if (FD_ISSET(STDIN_FILENO, &read_fds)) { 48 | ret = read(STDIN_FILENO, &c, 1); 49 | if (ret < 0) { 50 | perror("read(STDIN, ...)"); 51 | exit(EXIT_FAILURE); 52 | } 53 | printf("got '%c' from stdin!\n", c); 54 | } 55 | if (FD_ISSET(fd, &read_fds)) { 56 | ret = read(fd, &c, 1); 57 | if (ret < 0) { 58 | perror("read(fd, ...)"); 59 | exit(EXIT_FAILURE); 60 | } 61 | printf("got '%c' from device!\n", c); 62 | } 63 | } 64 | 65 | close(fd); 66 | 67 | return 0; 68 | } 69 | --------------------------------------------------------------------------------