├── .gitignore ├── Atomic ├── Makefile ├── README.md └── atomic_demo.c ├── LICENSE ├── PerCpuCounter ├── Makefile ├── README.md └── totaler.c ├── RCU ├── Makefile ├── README.md └── rcu_demo.c ├── README.md ├── RwLock ├── Makefile ├── README.md └── rwdemo.c ├── SeqLock ├── Makefile ├── README.md └── seq_demo.c ├── Spinlock ├── Makefile ├── README.md └── spindemo.c └── WaitEvent ├── Makefile ├── README.md └── wait_demo.c /.gitignore: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: GPL-2.0-only 2 | # 3 | # NOTE! Don't add files that are generated in specific 4 | # subdirectories here. Add them in the ".gitignore" file 5 | # in that subdirectory instead. 6 | # 7 | # NOTE! Please use 'git ls-files -i --exclude-standard' 8 | # command after changing this file, to see if there are 9 | # any tracked files which get ignored after the change. 10 | # 11 | # Normal rules (sorted alphabetically) 12 | # 13 | .* 14 | *.a 15 | *.asn1.[ch] 16 | *.bin 17 | *.bz2 18 | *.c.[012]*.* 19 | *.dt.yaml 20 | *.dtb 21 | *.dtbo 22 | *.dtb.S 23 | *.dwo 24 | *.elf 25 | *.gcno 26 | *.gz 27 | *.i 28 | *.ko 29 | *.lex.c 30 | *.ll 31 | *.lst 32 | *.lz4 33 | *.lzma 34 | *.lzo 35 | *.mod 36 | *.mod.c 37 | *.o 38 | *.o.* 39 | *.patch 40 | *.s 41 | *.so 42 | *.so.dbg 43 | *.su 44 | *.symtypes 45 | *.symversions 46 | *.tab.[ch] 47 | *.tar 48 | *.xz 49 | *.zst 50 | Module.symvers 51 | modules.order 52 | 53 | # 54 | # Top-level generic files 55 | # 56 | /linux 57 | /modules-only.symvers 58 | /vmlinux 59 | /vmlinux.32 60 | /vmlinux.map 61 | /vmlinux.symvers 62 | /vmlinux-gdb.py 63 | /vmlinuz 64 | /System.map 65 | /Module.markers 66 | /modules.builtin 67 | /modules.builtin.modinfo 68 | /modules.nsdeps 69 | 70 | # 71 | # RPM spec file (make rpm-pkg) 72 | # 73 | /*.spec 74 | 75 | # 76 | # Debian directory (make deb-pkg) 77 | # 78 | /debian/ 79 | 80 | # 81 | # Snap directory (make snap-pkg) 82 | # 83 | /snap/ 84 | 85 | # 86 | # tar directory (make tar*-pkg) 87 | # 88 | /tar-install/ 89 | 90 | # 91 | # We don't want to ignore the following even if they are dot-files 92 | # 93 | !.clang-format 94 | !.cocciconfig 95 | !.get_maintainer.ignore 96 | !.gitattributes 97 | !.gitignore 98 | !.mailmap 99 | 100 | # 101 | # Generated include files 102 | # 103 | /include/config/ 104 | /include/generated/ 105 | /include/ksym/ 106 | /arch/*/include/generated/ 107 | 108 | # stgit generated dirs 109 | patches-* 110 | 111 | # quilt's files 112 | patches 113 | series 114 | 115 | # ctags files 116 | tags 117 | TAGS 118 | 119 | # cscope files 120 | cscope.* 121 | ncscope.* 122 | 123 | # gnu global files 124 | GPATH 125 | GRTAGS 126 | GSYMS 127 | GTAGS 128 | 129 | # id-utils files 130 | ID 131 | 132 | *.orig 133 | *~ 134 | \#*# 135 | 136 | # 137 | # Leavings from module signing 138 | # 139 | extra_certificates 140 | signing_key.pem 141 | signing_key.priv 142 | signing_key.x509 143 | x509.genkey 144 | 145 | # Kconfig presets 146 | /all.config 147 | /alldef.config 148 | /allmod.config 149 | /allno.config 150 | /allrandom.config 151 | /allyes.config 152 | 153 | # Kconfig savedefconfig output 154 | /defconfig 155 | 156 | # Kdevelop4 157 | *.kdev4 158 | 159 | # Clang's compilation database file 160 | /compile_commands.json 161 | 162 | # Documentation toolchain 163 | sphinx_*/ 164 | -------------------------------------------------------------------------------- /Atomic/Makefile: -------------------------------------------------------------------------------- 1 | obj-m += atomic_demo.o 2 | 3 | KDIR = /lib/modules/$(shell uname -r)/build 4 | 5 | all: 6 | make -C $(KDIR) M=$(shell pwd) modules 7 | 8 | clean: 9 | make -C $(KDIR) M=$(shell pwd) clean 10 | -------------------------------------------------------------------------------- /Atomic/README.md: -------------------------------------------------------------------------------- 1 | # Atomic demo 2 | This is a creates a character device /dev/demo_atomic. 3 | The device implements a counter that gets incremented by a work queue 4 | once per second as long as the device is open. 5 | 6 | The counter can be read by reading the device 7 | and set by writing to the device. 8 | 9 | ## Building 10 | To build and install this module use make and insmod. 11 | 12 | ## Sample 13 | Simple interaction with the device. 14 | 15 | 16 | ``` 17 | # insmod atomic_demo.ko 18 | # sleep 30 < /dev/demo_atomic 19 | # cat /dev/demo_atomic 20 | 29 21 | # echo 11 >/dev/demo_atomic 22 | # sleep 4 < /dev/demo_atomic 23 | # cat /dev/demo_atomic 24 | 14 25 | # rmmod atomic_demo 26 | ``` 27 | -------------------------------------------------------------------------------- /Atomic/atomic_demo.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0-or-later 2 | /* 3 | * Demo usage of atomic for a counter 4 | */ 5 | 6 | /* include module name in all messages */ 7 | #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | static struct global_data { 22 | atomic_t refcnt; 23 | atomic_long_t counter; 24 | struct delayed_work dwork; 25 | } global; 26 | 27 | /* Called from delayed work every second to increment counter. */ 28 | static void counter_tick(struct work_struct *work) 29 | { 30 | atomic_long_inc(&global.counter); 31 | schedule_delayed_work(&global.dwork, HZ); 32 | } 33 | 34 | static ssize_t 35 | demo_atomic_read(struct file *filp, char __user *buf, size_t count, loff_t *off) 36 | { 37 | char tmp[64]; 38 | loff_t pos; 39 | ssize_t ret; 40 | int len; 41 | 42 | len = snprintf(tmp, sizeof(tmp), "%ld\n", 43 | atomic_long_read(&global.counter)); 44 | 45 | pos = *off; 46 | if (pos >= len) 47 | return 0; /* read past eof */ 48 | 49 | ret = min_t(ssize_t, count, len - pos); 50 | if (copy_to_user(buf, tmp + pos, ret)) 51 | return -EFAULT; 52 | 53 | *off += ret; 54 | return ret; 55 | } 56 | 57 | static ssize_t 58 | demo_atomic_write(struct file *filp, const char __user *buf, size_t len, loff_t *off) 59 | { 60 | long val; 61 | int ret; 62 | 63 | ret = kstrtol_from_user(buf, len, 10, &val); 64 | if (ret < 0) 65 | return ret; 66 | 67 | atomic_long_set(&global.counter, val); 68 | 69 | return len; 70 | } 71 | 72 | static int demo_atomic_open(struct inode *inode, struct file *file) 73 | { 74 | if (atomic_inc_return(&global.refcnt) == 1) { 75 | pr_info("starting work\n"); 76 | schedule_delayed_work(&global.dwork, HZ); 77 | } 78 | 79 | return 0; 80 | } 81 | 82 | static int demo_atomic_release(struct inode *inode, struct file *file) 83 | { 84 | if (atomic_dec_and_test(&global.refcnt)) { 85 | pr_info("stopping timer\n"); 86 | cancel_delayed_work(&global.dwork); 87 | } 88 | 89 | return 0; 90 | } 91 | 92 | static const struct file_operations demo_fops = { 93 | .owner = THIS_MODULE, 94 | .read = demo_atomic_read, 95 | .write = demo_atomic_write, 96 | .open = demo_atomic_open, 97 | .release = demo_atomic_release, 98 | }; 99 | 100 | 101 | static struct miscdevice demo_miscdev = { 102 | .name = "demo_atomic", 103 | .minor = MISC_DYNAMIC_MINOR, 104 | .fops = &demo_fops, 105 | }; 106 | 107 | static int __init demo_atomic_init(void) 108 | { 109 | atomic_long_set(&global.counter, 0); 110 | atomic_set(&global.refcnt, 0); 111 | INIT_DELAYED_WORK(&global.dwork, counter_tick); 112 | 113 | if (misc_register(&demo_miscdev) != 0) { 114 | pr_err("Cannot initialize misc dev\n"); 115 | return -1; 116 | } 117 | 118 | pr_info("node %d:%d\n", MISC_MAJOR, demo_miscdev.minor); 119 | return 0; 120 | 121 | } 122 | 123 | static void __exit demo_atomic_exit(void) 124 | { 125 | cancel_delayed_work_sync(&global.dwork); 126 | misc_deregister(&demo_miscdev); 127 | } 128 | 129 | module_init(demo_atomic_init); 130 | module_exit(demo_atomic_exit); 131 | 132 | MODULE_LICENSE("GPL"); 133 | -------------------------------------------------------------------------------- /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 | 294 | Copyright (C) 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 | , 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 | -------------------------------------------------------------------------------- /PerCpuCounter/Makefile: -------------------------------------------------------------------------------- 1 | obj-m += totaler.o 2 | 3 | KDIR = /lib/modules/$(shell uname -r)/build 4 | 5 | all: 6 | make -C $(KDIR) M=$(shell pwd) modules 7 | 8 | clean: 9 | make -C $(KDIR) M=$(shell pwd) clean 10 | -------------------------------------------------------------------------------- /PerCpuCounter/README.md: -------------------------------------------------------------------------------- 1 | # Per CPU Counter 2 | This module creates a character device /dev/totaler. 3 | The device implements a counter that can be read and written. 4 | 5 | When the counter is written, it adds the increment value to the total. 6 | When the counter is read, it returns the current total. 7 | 8 | ## Building 9 | To build and install this module use make and insmod. 10 | 11 | ``` 12 | $ cd PerCpuCounter/ 13 | $ make 14 | make -C /lib/modules/5.13.0-1023-azure/build M=/home/azureuser/kernel-examples/PerCpuCounter modules 15 | make[1]: Entering directory '/usr/src/linux-headers-5.13.0-1023-azure' 16 | CC [M] /home/azureuser/kernel-examples/Spinlock/totaler.o 17 | MODPOST /home/azureuser/kernel-examples/Spinlock/Module.symvers 18 | CC [M] /home/azureuser/kernel-examples/Spinlock/totaler.mod.o 19 | LD [M] /home/azureuser/kernel-examples/Spinlock/totaler.ko 20 | BTF [M] /home/azureuser/kernel-examples/Spinlock/totaler.ko 21 | 22 | $ sudo insmod totaler.ko 23 | ``` 24 | ## Sample 25 | Since device is created with root only permission need sudo here. 26 | Simple interaction with the device; set the counter twice (on different CPU) 27 | and see the total. 28 | 29 | 30 | ``` 31 | # cat /dev/totaler 32 | 0 33 | # taskset 1 echo 2 >/dev/totaler 34 | # taskset 2 echo 2 >/dev/totaler 35 | # cat /dev/totaler 36 | 4 37 | # rmmod totaler 38 | ``` 39 | 40 | -------------------------------------------------------------------------------- /PerCpuCounter/totaler.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0-or-later 2 | /* 3 | * Demo of totaling with percpu counter 4 | */ 5 | 6 | /* include module name in all messages */ 7 | #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | static struct global_data { 19 | struct percpu_counter pcpu; 20 | } global; 21 | 22 | static ssize_t 23 | totaler_read(struct file *filp, char __user *buf, size_t count, 24 | loff_t *off) 25 | { 26 | char tmp[64]; 27 | loff_t pos; 28 | ssize_t ret; 29 | int len; 30 | s64 total; 31 | 32 | total = percpu_counter_sum(&global.pcpu); 33 | 34 | len = snprintf(tmp, sizeof(tmp), "%ld\n", (long)total); 35 | 36 | pos = *off; 37 | if (pos >= len) 38 | return 0; /* read past eof */ 39 | 40 | ret = min_t(ssize_t, count, len - pos); 41 | if (copy_to_user(buf, tmp + pos, ret)) 42 | return -EFAULT; 43 | 44 | *off += ret; 45 | return ret; 46 | } 47 | 48 | static ssize_t 49 | totaler_write(struct file *filp, const char __user *buf, size_t len, 50 | loff_t *off) 51 | { 52 | int ret; 53 | long val; 54 | 55 | ret = kstrtol_from_user(buf, len, 10, &val); 56 | if (ret < 0) 57 | return ret; 58 | 59 | percpu_counter_add(&global.pcpu, val); 60 | 61 | return len; 62 | } 63 | 64 | static const struct file_operations demo_fops = { 65 | .owner = THIS_MODULE, 66 | .read = totaler_read, 67 | .write = totaler_write, 68 | }; 69 | 70 | static struct miscdevice demo_miscdev = { 71 | .name = "demo_percpu", 72 | .minor = MISC_DYNAMIC_MINOR, 73 | .fops = &demo_fops, 74 | }; 75 | 76 | static int __init totaler_init(void) 77 | { 78 | if (percpu_counter_init(&global.pcpu, 0, GFP_KERNEL) != 0) { 79 | pr_err("Cannot init counter\n"); 80 | return -1; 81 | } 82 | 83 | if (misc_register(&demo_miscdev) != 0) { 84 | pr_err("Cannot register miscdev\n"); 85 | return -1; 86 | } 87 | 88 | pr_info("node %d:%d\n", MISC_MAJOR, demo_miscdev.minor); 89 | return 0; 90 | } 91 | 92 | static void __exit totaler_exit(void) 93 | { 94 | misc_deregister(&demo_miscdev); 95 | percpu_counter_destroy(&global.pcpu); 96 | } 97 | 98 | module_init(totaler_init); 99 | module_exit(totaler_exit); 100 | 101 | MODULE_LICENSE("GPL"); 102 | -------------------------------------------------------------------------------- /RCU/Makefile: -------------------------------------------------------------------------------- 1 | obj-m += rcu_demo.o 2 | 3 | KDIR = /lib/modules/$(shell uname -r)/build 4 | 5 | all: 6 | make -C $(KDIR) M=$(shell pwd) modules 7 | 8 | clean: 9 | make -C $(KDIR) M=$(shell pwd) clean 10 | -------------------------------------------------------------------------------- /RCU/README.md: -------------------------------------------------------------------------------- 1 | # RCU counter demo 2 | This module creates a character device /dev/demo_rcu. 3 | The device implements a simple string storage facility 4 | 5 | When the device is written, the string is saved. 6 | When the device is read, it returns the saved value. 7 | 8 | ## Building 9 | To build and install this module use make and insmod. 10 | 11 | ## Sample 12 | Simple interaction with the device. 13 | 14 | ``` 15 | # insmod rcu_demo.ko 16 | # echo 'may the force be with you' >/dev/rcu_demo 17 | # cat /dev/rcu_demo 18 | may the force be with you 19 | # echo 'all people are created equal' >/dev/rcu_demo 20 | # cat /dev/rcu_demo 21 | all people are created equal 22 | # rmmod rcu_demo 23 | ``` 24 | -------------------------------------------------------------------------------- /RCU/rcu_demo.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0-or-later 2 | /* 3 | * Demo usage of RCU to read a counter 4 | */ 5 | 6 | /* include module name in all messages */ 7 | #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | struct save_value { 20 | struct rcu_head rcu; 21 | char str[]; 22 | }; 23 | 24 | static struct save_value __rcu *global; 25 | 26 | static ssize_t 27 | demo_rcu_read(struct file *filp, char __user *buf, size_t count, loff_t *off) 28 | { 29 | struct save_value *data; 30 | loff_t pos; 31 | ssize_t ret; 32 | size_t len; 33 | 34 | rcu_read_lock(); 35 | data = rcu_dereference(global); 36 | if (data == NULL) { 37 | ret = -EINVAL; /* no value has been set */ 38 | } else { 39 | len = strlen(data->str); 40 | ret = min_t(ssize_t, count, len - pos); 41 | if (copy_to_user(buf, data->str + pos, ret)) 42 | ret = -EFAULT; 43 | else 44 | *off += ret; 45 | } 46 | rcu_read_unlock(); 47 | return ret; 48 | } 49 | 50 | static ssize_t 51 | demo_rcu_write(struct file *filp, const char __user *buf, size_t len, loff_t *off) 52 | { 53 | struct save_value *data; 54 | int ret; 55 | 56 | data = kmalloc(sizeof(*data) + len, GFP_USER); 57 | if (data == NULL) 58 | return -ENOMEM; 59 | 60 | ret = strncpy_from_user(data->str, buf, len); 61 | if (ret < 0) 62 | return ret; 63 | 64 | /* replace original pointer with new value */ 65 | data = xchg(&global, data); 66 | 67 | /* Free old one after grace period */ 68 | if (data != NULL) 69 | kfree_rcu(data, rcu); 70 | 71 | return len; 72 | } 73 | 74 | static const struct file_operations demo_fops = { 75 | .owner = THIS_MODULE, 76 | .read = demo_rcu_read, 77 | .write = demo_rcu_write, 78 | }; 79 | 80 | static struct miscdevice demo_miscdev = { 81 | .name = "demo_percpu", 82 | .minor = MISC_DYNAMIC_MINOR, 83 | .fops = &demo_fops, 84 | }; 85 | 86 | static int __init demo_rcu_init(void) 87 | { 88 | RCU_INIT_POINTER(global, NULL); 89 | 90 | if (misc_register(&demo_miscdev) != 0) { 91 | pr_err("Cannot register miscdev\n"); 92 | return -1; 93 | } 94 | 95 | pr_info("node %d:%d\n", MISC_MAJOR, demo_miscdev.minor); 96 | return 0; 97 | } 98 | 99 | static void __exit demo_rcu_exit(void) 100 | { 101 | misc_deregister(&demo_miscdev); 102 | 103 | kfree(global); /* why is this safe? */ 104 | } 105 | 106 | module_init(demo_rcu_init); 107 | module_exit(demo_rcu_exit); 108 | 109 | MODULE_LICENSE("GPL"); 110 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # kernel-examples 2 | Locking and concurrency in Linux kernel examples 3 | 4 | This repository has small sample kernel driver examples. 5 | Originally done for an internal class. 6 | 7 | # Prerequisite 8 | Building these examples assume you already have all the necessary 9 | packages to build a kernel module and headers for your distribution. 10 | 11 | # Building module 12 | Each subdirectory contains a different small example. 13 | 14 | - [Spin locks](Spinlock/README.md) 15 | - [Reader Writer locks](RwLock/README.md) 16 | - [Sequence locks](SeqLock/README.md) 17 | - [Wait Event](WaitEvent/README.md) 18 | - [Atomic](Atomic/README.md) 19 | - [Per CPU Counter](PerCpuCounter/README.md) 20 | - [Read Copy Update](RCU/README.md) 21 | 22 | -------------------------------------------------------------------------------- /RwLock/Makefile: -------------------------------------------------------------------------------- 1 | obj-m += rwdemo.o 2 | 3 | KDIR = /lib/modules/$(shell uname -r)/build 4 | 5 | all: 6 | make -C $(KDIR) M=$(shell pwd) modules 7 | 8 | clean: 9 | make -C $(KDIR) M=$(shell pwd) clean 10 | -------------------------------------------------------------------------------- /RwLock/README.md: -------------------------------------------------------------------------------- 1 | # Reader Writer Lock 2 | This is a very simplistic module creates a character device /dev/demo_rwlock. 3 | The device implements a counter that gets incremented by a work queue 4 | once per second. 5 | 6 | ## Building 7 | To build and install this module use make and insmod. 8 | 9 | ## Sample 10 | Simple interaction with the device. 11 | Since device is created with root only permission need sudo here. 12 | 13 | ``` 14 | # cat /dev/demo_rwlock 15 | 27 16 | # echo 33 >/dev/demo_rwlock 17 | # cat /dev/demo_rwlock 18 | 39 19 | # cat /dev/demo_rwlock 20 | 41 21 | # rmmod rwdemo 22 | 23 | ``` 24 | -------------------------------------------------------------------------------- /RwLock/rwdemo.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0-or-later 2 | /* 3 | * Demo usage of reader/writer lock 4 | */ 5 | 6 | /* include module name in all messages */ 7 | #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | static struct global_data { 22 | unsigned long counter; 23 | rwlock_t lock; 24 | struct delayed_work dwork; 25 | } global; 26 | 27 | /* Called from delayed work every second to increment counter. */ 28 | static void counter_tick(struct work_struct *work) 29 | { 30 | write_lock(&global.lock); 31 | ++global.counter; 32 | write_unlock(&global.lock); 33 | 34 | schedule_delayed_work(&global.dwork, HZ); 35 | } 36 | 37 | static ssize_t demo_rwlock_read(struct file *filp, char __user *buf, size_t count, 38 | loff_t *off) 39 | { 40 | char tmp[64]; 41 | loff_t pos; 42 | ssize_t ret; 43 | int len; 44 | 45 | read_lock(&global.lock); 46 | len = snprintf(tmp, sizeof(tmp), "%lu\n", global.counter); 47 | read_unlock(&global.lock); 48 | 49 | pos = *off; 50 | if (pos >= len) 51 | return 0; /* read past eof */ 52 | 53 | ret = min_t(ssize_t, count, len - pos); 54 | if (copy_to_user(buf, tmp + pos, ret)) 55 | return -EFAULT; 56 | 57 | *off += ret; 58 | return ret; 59 | } 60 | 61 | static ssize_t 62 | demo_rwlock_write(struct file *filp, const char __user *buf, size_t len, loff_t *off) 63 | { 64 | unsigned long val; 65 | int ret; 66 | 67 | ret = kstrtoul_from_user(buf, len, 10, &val); 68 | if (ret < 0) 69 | return ret; 70 | 71 | write_lock(&global.lock); 72 | global.counter = val; 73 | write_unlock(&global.lock); 74 | 75 | return len; 76 | } 77 | 78 | /* this device does nothing */ 79 | static const struct file_operations demo_fops = { 80 | .owner = THIS_MODULE, 81 | .read = demo_rwlock_read, 82 | .write = demo_rwlock_write, 83 | }; 84 | 85 | static struct miscdevice demo_miscdev = { 86 | .name = "demo_rwlock", 87 | .minor = MISC_DYNAMIC_MINOR, 88 | .fops = &demo_fops, 89 | }; 90 | 91 | static int __init demo_rwlock_init(void) 92 | { 93 | if (misc_register(&demo_miscdev) != 0) { 94 | pr_err("Cannot initialize misc dev\n"); 95 | return -1; 96 | } 97 | pr_info("node %d:%d\n", MISC_MAJOR, demo_miscdev.minor); 98 | 99 | rwlock_init(&global.lock); 100 | INIT_DELAYED_WORK(&global.dwork, counter_tick); 101 | schedule_delayed_work(&global.dwork, HZ); 102 | 103 | return 0; 104 | } 105 | 106 | static void __exit demo_rwlock_exit(void) 107 | { 108 | pr_info("module exit\n"); 109 | 110 | cancel_delayed_work_sync(&global.dwork); 111 | misc_deregister(&demo_miscdev); 112 | } 113 | 114 | module_init(demo_rwlock_init); 115 | module_exit(demo_rwlock_exit); 116 | 117 | MODULE_LICENSE("GPL"); 118 | -------------------------------------------------------------------------------- /SeqLock/Makefile: -------------------------------------------------------------------------------- 1 | obj-m += seq_demo.o 2 | 3 | KDIR = /lib/modules/$(shell uname -r)/build 4 | 5 | all: 6 | make -C $(KDIR) M=$(shell pwd) modules 7 | 8 | clean: 9 | make -C $(KDIR) M=$(shell pwd) clean 10 | -------------------------------------------------------------------------------- /SeqLock/README.md: -------------------------------------------------------------------------------- 1 | # Sequence Lock 2 | This module creates a character device /dev/demo_seqlock. 3 | The device implements a 128 bit counter that can be read and written. 4 | 5 | ## Building 6 | To build and install this module use make and insmod. 7 | 8 | ## Sample 9 | Simple interaction with the device. 10 | -------------------------------------------------------------------------------- /SeqLock/seq_demo.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0-or-later 2 | /* 3 | * Demo using seqlock to read a value 4 | */ 5 | 6 | /* include module name in all messages */ 7 | #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | static struct global_data { 21 | seqlock_t lock; 22 | unsigned long long counter; 23 | } global; 24 | 25 | static ssize_t 26 | demo_seqlock_read(struct file *filp, char __user *buf, size_t count, loff_t *off) 27 | { 28 | unsigned seq; 29 | char tmp[64]; 30 | loff_t pos; 31 | ssize_t ret; 32 | int len; 33 | 34 | do { 35 | seq = read_seqbegin(&global.lock); 36 | len = snprintf(tmp, sizeof(tmp), 37 | "%llu\n", global.counter); 38 | pr_info("%s(): seq=%u len=%d\n", __func__, seq, len); 39 | } while (read_seqretry(&global.lock, seq)); 40 | 41 | pos = *off; 42 | if (pos >= len) 43 | return 0; /* read past eof */ 44 | 45 | ret = min_t(ssize_t, count, len - pos); 46 | if (copy_to_user(buf, tmp + pos, ret)) 47 | return -EFAULT; 48 | 49 | *off += ret; 50 | return ret; 51 | } 52 | 53 | static ssize_t 54 | demo_seqlock_write(struct file *filp, const char __user *buf, size_t len, loff_t *off) 55 | { 56 | unsigned long long val; 57 | int ret; 58 | 59 | pr_info("Called %s len=%zu\n", __func__, len); 60 | ret = kstrtoull_from_user(buf, len, 10, &val); 61 | if (ret < 0) { 62 | pr_err("kstrtoull ret %d\n", ret); 63 | return ret; 64 | } 65 | 66 | pr_info("seqlock write value=%llu\n", val); 67 | write_seqlock(&global.lock); 68 | global.counter = val; 69 | write_sequnlock(&global.lock); 70 | 71 | return len; 72 | } 73 | 74 | static const struct file_operations demo_fops = { 75 | .owner = THIS_MODULE, 76 | .read = demo_seqlock_read, 77 | .write = demo_seqlock_write, 78 | }; 79 | 80 | static struct miscdevice demo_miscdev = { 81 | .name = "demo_seqlock", 82 | .minor = MISC_DYNAMIC_MINOR, 83 | .fops = &demo_fops, 84 | }; 85 | 86 | static int __init demo_seqlock_init(void) 87 | { 88 | seqlock_init(&global.lock); 89 | 90 | if (misc_register(&demo_miscdev) != 0) { 91 | pr_err("Cannot initialize misc dev\n"); 92 | return -1; 93 | } 94 | pr_info("node %d:%d\n", MISC_MAJOR, demo_miscdev.minor); 95 | return 0; 96 | } 97 | 98 | static void __exit demo_seqlock_exit(void) 99 | { 100 | misc_deregister(&demo_miscdev); 101 | } 102 | 103 | module_init(demo_seqlock_init); 104 | module_exit(demo_seqlock_exit); 105 | 106 | MODULE_LICENSE("GPL"); 107 | -------------------------------------------------------------------------------- /Spinlock/Makefile: -------------------------------------------------------------------------------- 1 | obj-m += spindemo.o 2 | 3 | KDIR = /lib/modules/$(shell uname -r)/build 4 | 5 | all: 6 | make -C $(KDIR) M=$(shell pwd) modules 7 | 8 | clean: 9 | make -C $(KDIR) M=$(shell pwd) clean 10 | -------------------------------------------------------------------------------- /Spinlock/README.md: -------------------------------------------------------------------------------- 1 | # Spinlock 2 | This is a very simplistic module which prints messages the system log. 3 | It spawns two kernel threads and each one outputs a line into the log 4 | once per second. 5 | 6 | ## Building 7 | To build and install the useless module: 8 | ``` 9 | $ cd Spinlock/ 10 | $ make 11 | make -C /lib/modules/5.13.0-1023-azure/build M=/home/azureuser/kernel-examples/Spinlock modules 12 | make[1]: Entering directory '/usr/src/linux-headers-5.13.0-1023-azure' 13 | CC [M] /home/azureuser/kernel-examples/Spinlock/spindemo.o 14 | MODPOST /home/azureuser/kernel-examples/Spinlock/Module.symvers 15 | CC [M] /home/azureuser/kernel-examples/Spinlock/spindemo.mod.o 16 | LD [M] /home/azureuser/kernel-examples/Spinlock/spindemo.ko 17 | BTF [M] /home/azureuser/kernel-examples/Spinlock/spindemo.ko 18 | 19 | $ sudo insmod spindemo.ko 20 | ``` 21 | 22 | After several seconds remove the module to avoid overfilling disk and logs! 23 | ``` 24 | $ sudo rmmod spindemo 25 | ``` 26 | 27 | ## Expected output 28 | You should see output like this at the end of dmesg: 29 | ``` 30 | [ 561.385570] spindemo: loading out-of-tree module taints kernel. 31 | [ 561.385605] spindemo: module verification failed: signature and/or required key missing - tainting kernel 32 | [ 561.385843] Major = 236 Minor = 0 33 | [ 561.385988] Kthread1 Created Successfully... 34 | [ 561.385993] In thread_function1 1 35 | [ 561.386043] Kthread2 Created Successfully... 36 | [ 561.386045] Inserted spin_demo 37 | [ 561.386048] spin_demo thread2 2 38 | [ 562.402501] spin_demo thread2 3 39 | [ 562.402548] spin_demo thread1 4 40 | [ 563.426537] spin_demo thread2 5 41 | [ 563.426582] spin_demo thread1 6 42 | [ 564.450452] spin_demo thread1 7 43 | [ 564.450514] spin_demo thread2 8 44 | [ 565.474509] spin_demo thread2 9 45 | [ 565.474519] spin_demo thread1 10 46 | [ 566.498496] spin_demo thread1 11 47 | ``` 48 | -------------------------------------------------------------------------------- /Spinlock/spindemo.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0-or-later 2 | /* 3 | * Demo of spin lock 4 | */ 5 | 6 | /* include module name in all messages */ 7 | #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | DEFINE_SPINLOCK(demo_spinlock); 17 | 18 | static unsigned long demo_global_variable = 0; 19 | 20 | static struct task_struct *demo_thread1; 21 | static struct task_struct *demo_thread2; 22 | 23 | static int thread_function(void *arg) 24 | { 25 | const char *my_name = arg; 26 | 27 | while (!kthread_should_stop()) { 28 | spin_lock(&demo_spinlock); 29 | demo_global_variable++; 30 | pr_info("%s = %lu\n", my_name, demo_global_variable); 31 | spin_unlock(&demo_spinlock); 32 | 33 | msleep(1000); 34 | } 35 | return 0; 36 | } 37 | 38 | static int __init demo_spin_init(void) 39 | { 40 | demo_thread1 = kthread_run(thread_function, "thread1", "spin_demo1"); 41 | if (demo_thread1 == NULL) { 42 | pr_err("Cannot create kthread1\n"); 43 | return -1; 44 | } 45 | 46 | demo_thread2 = kthread_run(thread_function, "thread2", "spin_demo2"); 47 | if (demo_thread2 == NULL) { 48 | pr_err("Cannot create kthread2\n"); 49 | kthread_stop(demo_thread1); 50 | return -1; 51 | } 52 | 53 | pr_info("module inserted\n"); 54 | return 0; 55 | 56 | } 57 | 58 | static void __exit demo_spin_exit(void) 59 | { 60 | pr_info("module exit\n"); 61 | 62 | kthread_stop(demo_thread1); 63 | kthread_stop(demo_thread2); 64 | } 65 | 66 | module_init(demo_spin_init); 67 | module_exit(demo_spin_exit); 68 | 69 | MODULE_LICENSE("GPL"); 70 | -------------------------------------------------------------------------------- /WaitEvent/Makefile: -------------------------------------------------------------------------------- 1 | obj-m += wait_demo.o 2 | 3 | KDIR = /lib/modules/$(shell uname -r)/build 4 | 5 | all: 6 | make -C $(KDIR) M=$(shell pwd) modules 7 | 8 | clean: 9 | make -C $(KDIR) M=$(shell pwd) clean 10 | -------------------------------------------------------------------------------- /WaitEvent/README.md: -------------------------------------------------------------------------------- 1 | # Blocking reader channel 2 | This module creates a character device /dev/demo_wait. 3 | The device implements a counter that can be read and written. 4 | 5 | When the counter is read, it blocks until the value is changed 6 | by a writer. The value set by the writer is then returned. 7 | 8 | ## Building 9 | To build and install this module use make and insmod. 10 | 11 | ## Sample 12 | Simple interaction with the device. 13 | Start a cat in background that reads the device, and it blocks. 14 | Put some data into device and the cat wakes up and prints output 15 | and then it goes back to sleep. 16 | 17 | ``` 18 | # insmod wait_demo.ko 19 | # cat /dev/demo_wait & 20 | [1] 16616 21 | # echo 33 >/dev/demo_wait 22 | 33 23 | ``` 24 | -------------------------------------------------------------------------------- /WaitEvent/wait_demo.c: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-2.0-or-later 2 | /* 3 | * Demo using wait queue 4 | */ 5 | 6 | /* include module name in all messages */ 7 | #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | 19 | static struct global_data { 20 | struct wait_queue_head wq; 21 | atomic_long_t counter; 22 | } global; 23 | 24 | struct user_data { 25 | long lastread; 26 | }; 27 | 28 | static bool 29 | counter_changed(long *counter_ret) 30 | { 31 | long value = atomic_long_read(&global.counter); 32 | 33 | if (value == *counter_ret) 34 | return false; 35 | 36 | *counter_ret = value; 37 | return true; 38 | } 39 | 40 | static ssize_t 41 | demo_read(struct file *filp, char __user *buf, size_t count, loff_t *off) 42 | { 43 | struct user_data *ud = filp->private_data; 44 | char tmp[64]; 45 | loff_t pos; 46 | ssize_t ret; 47 | int len; 48 | 49 | if (wait_event_interruptible(global.wq, counter_changed(&ud->lastread))) 50 | return -EINTR; 51 | 52 | len = snprintf(tmp, sizeof(tmp), "%ld\n", ud->lastread); 53 | pos = *off; 54 | if (pos >= len) 55 | return 0; /* read past eof */ 56 | 57 | ret = min_t(ssize_t, count, len - pos); 58 | if (copy_to_user(buf, tmp + pos, ret)) 59 | return -EFAULT; 60 | 61 | *off += ret; 62 | return ret; 63 | } 64 | 65 | static ssize_t 66 | demo_write(struct file *filp, const char __user *buf, size_t len, loff_t *off) 67 | { 68 | long val; 69 | int ret; 70 | 71 | ret = kstrtol_from_user(buf, len, 10, &val); 72 | if (ret < 0) 73 | return ret; 74 | 75 | atomic_long_set(&global.counter, val); 76 | wake_up_interruptible(&global.wq); 77 | 78 | return len; 79 | } 80 | 81 | static int demo_open(struct inode *inode, struct file *filp) 82 | { 83 | struct user_data *ud; 84 | 85 | ud = kmalloc(sizeof(*ud), GFP_USER); 86 | if (ud == NULL) 87 | return -ENOMEM; 88 | 89 | ud->lastread = atomic_long_read(&global.counter); 90 | filp->private_data = ud; 91 | return 0; 92 | } 93 | 94 | static int demo_release(struct inode *inode, struct file *filp) 95 | { 96 | struct user_data *ud = filp->private_data; 97 | 98 | kfree(ud); 99 | return 0; 100 | } 101 | 102 | static const struct file_operations demo_fops = { 103 | .owner = THIS_MODULE, 104 | .read = demo_read, 105 | .write = demo_write, 106 | .open = demo_open, 107 | .release = demo_release, 108 | }; 109 | 110 | static struct miscdevice demo_miscdev = { 111 | .name = "demo_wait", 112 | .minor = MISC_DYNAMIC_MINOR, 113 | .fops = &demo_fops, 114 | }; 115 | 116 | static int __init demo_init(void) 117 | { 118 | 119 | atomic_long_set(&global.counter, 0); 120 | init_waitqueue_head(&global.wq); 121 | 122 | if (misc_register(&demo_miscdev) != 0) { 123 | pr_err("Cannot initialize misc dev\n"); 124 | return -1; 125 | } 126 | 127 | pr_info("node %d:%d\n", MISC_MAJOR, demo_miscdev.minor); 128 | return 0; 129 | } 130 | 131 | static void __exit demo_exit(void) 132 | { 133 | misc_deregister(&demo_miscdev); 134 | } 135 | 136 | module_init(demo_init); 137 | module_exit(demo_exit); 138 | 139 | MODULE_LICENSE("GPL"); 140 | --------------------------------------------------------------------------------