1.. _codingstyle: 2 3Linux kernel coding style 4========================= 5 6This is a short document describing the preferred coding style for the 7linux kernel. Coding style is very personal, and I won't **force** my 8views on anybody, but this is what goes for anything that I have to be 9able to maintain, and I'd prefer it for most other things too. Please 10at least consider the points made here. 11 12First off, I'd suggest printing out a copy of the GNU coding standards, 13and NOT read it. Burn them, it's a great symbolic gesture. 14 15Anyway, here goes: 16 17 181) Indentation 19-------------- 20 21Tabs are 8 characters, and thus indentations are also 8 characters. 22There are heretic movements that try to make indentations 4 (or even 2!) 23characters deep, and that is akin to trying to define the value of PI to 24be 3. 25 26Rationale: The whole idea behind indentation is to clearly define where 27a block of control starts and ends. Especially when you've been looking 28at your screen for 20 straight hours, you'll find it a lot easier to see 29how the indentation works if you have large indentations. 30 31Now, some people will claim that having 8-character indentations makes 32the code move too far to the right, and makes it hard to read on a 3380-character terminal screen. The answer to that is that if you need 34more than 3 levels of indentation, you're screwed anyway, and should fix 35your program. 36 37In short, 8-char indents make things easier to read, and have the added 38benefit of warning you when you're nesting your functions too deep. 39Heed that warning. 40 41The preferred way to ease multiple indentation levels in a switch statement is 42to align the ``switch`` and its subordinate ``case`` labels in the same column 43instead of ``double-indenting`` the ``case`` labels. E.g.: 44 45.. code-block:: c 46 47 switch (suffix) { 48 case 'G': 49 case 'g': 50 mem <<= 30; 51 break; 52 case 'M': 53 case 'm': 54 mem <<= 20; 55 break; 56 case 'K': 57 case 'k': 58 mem <<= 10; 59 fallthrough; 60 default: 61 break; 62 } 63 64Don't put multiple statements on a single line unless you have 65something to hide: 66 67.. code-block:: c 68 69 if (condition) do_this; 70 do_something_everytime; 71 72Don't use commas to avoid using braces: 73 74.. code-block:: c 75 76 if (condition) 77 do_this(), do_that(); 78 79Always uses braces for multiple statements: 80 81.. code-block:: c 82 83 if (condition) { 84 do_this(); 85 do_that(); 86 } 87 88Don't put multiple assignments on a single line either. Kernel coding style 89is super simple. Avoid tricky expressions. 90 91 92Outside of comments, documentation and except in Kconfig, spaces are never 93used for indentation, and the above example is deliberately broken. 94 95Get a decent editor and don't leave whitespace at the end of lines. 96 97 982) Breaking long lines and strings 99---------------------------------- 100 101Coding style is all about readability and maintainability using commonly 102available tools. 103 104The preferred limit on the length of a single line is 80 columns. 105 106Statements longer than 80 columns should be broken into sensible chunks, 107unless exceeding 80 columns significantly increases readability and does 108not hide information. 109 110Descendants are always substantially shorter than the parent and 111are placed substantially to the right. A very commonly used style 112is to align descendants to a function open parenthesis. 113 114These same rules are applied to function headers with a long argument list. 115 116However, never break user-visible strings such as printk messages because 117that breaks the ability to grep for them. 118 119 1203) Placing Braces and Spaces 121---------------------------- 122 123The other issue that always comes up in C styling is the placement of 124braces. Unlike the indent size, there are few technical reasons to 125choose one placement strategy over the other, but the preferred way, as 126shown to us by the prophets Kernighan and Ritchie, is to put the opening 127brace last on the line, and put the closing brace first, thusly: 128 129.. code-block:: c 130 131 if (x is true) { 132 we do y 133 } 134 135This applies to all non-function statement blocks (if, switch, for, 136while, do). E.g.: 137 138.. code-block:: c 139 140 switch (action) { 141 case KOBJ_ADD: 142 return "add"; 143 case KOBJ_REMOVE: 144 return "remove"; 145 case KOBJ_CHANGE: 146 return "change"; 147 default: 148 return NULL; 149 } 150 151However, there is one special case, namely functions: they have the 152opening brace at the beginning of the next line, thus: 153 154.. code-block:: c 155 156 int function(int x) 157 { 158 body of function 159 } 160 161Heretic people all over the world have claimed that this inconsistency 162is ... well ... inconsistent, but all right-thinking people know that 163(a) K&R are **right** and (b) K&R are right. Besides, functions are 164special anyway (you can't nest them in C). 165 166Note that the closing brace is empty on a line of its own, **except** in 167the cases where it is followed by a continuation of the same statement, 168ie a ``while`` in a do-statement or an ``else`` in an if-statement, like 169this: 170 171.. code-block:: c 172 173 do { 174 body of do-loop 175 } while (condition); 176 177and 178 179.. code-block:: c 180 181 if (x == y) { 182 .. 183 } else if (x > y) { 184 ... 185 } else { 186 .... 187 } 188 189Rationale: K&R. 190 191Also, note that this brace-placement also minimizes the number of empty 192(or almost empty) lines, without any loss of readability. Thus, as the 193supply of new-lines on your screen is not a renewable resource (think 19425-line terminal screens here), you have more empty lines to put 195comments on. 196 197Do not unnecessarily use braces where a single statement will do. 198 199.. code-block:: c 200 201 if (condition) 202 action(); 203 204and 205 206.. code-block:: c 207 208 if (condition) 209 do_this(); 210 else 211 do_that(); 212 213This does not apply if only one branch of a conditional statement is a single 214statement; in the latter case use braces in both branches: 215 216.. code-block:: c 217 218 if (condition) { 219 do_this(); 220 do_that(); 221 } else { 222 otherwise(); 223 } 224 225Also, use braces when a loop contains more than a single simple statement: 226 227.. code-block:: c 228 229 while (condition) { 230 if (test) 231 do_something(); 232 } 233 2343.1) Spaces 235*********** 236 237Linux kernel style for use of spaces depends (mostly) on 238function-versus-keyword usage. Use a space after (most) keywords. The 239notable exceptions are sizeof, typeof, alignof, and __attribute__, which look 240somewhat like functions (and are usually used with parentheses in Linux, 241although they are not required in the language, as in: ``sizeof info`` after 242``struct fileinfo info;`` is declared). 243 244So use a space after these keywords:: 245 246 if, switch, case, for, do, while 247 248but not with sizeof, typeof, alignof, or __attribute__. E.g., 249 250.. code-block:: c 251 252 253 s = sizeof(struct file); 254 255Do not add spaces around (inside) parenthesized expressions. This example is 256**bad**: 257 258.. code-block:: c 259 260 261 s = sizeof( struct file ); 262 263When declaring pointer data or a function that returns a pointer type, the 264preferred use of ``*`` is adjacent to the data name or function name and not 265adjacent to the type name. Examples: 266 267.. code-block:: c 268 269 270 char *linux_banner; 271 unsigned long long memparse(char *ptr, char **retptr); 272 char *match_strdup(substring_t *s); 273 274Use one space around (on each side of) most binary and ternary operators, 275such as any of these:: 276 277 = + - < > * / % | & ^ <= >= == != ? : 278 279but no space after unary operators:: 280 281 & * + - ~ ! sizeof typeof alignof __attribute__ defined 282 283no space before the postfix increment & decrement unary operators:: 284 285 ++ -- 286 287no space after the prefix increment & decrement unary operators:: 288 289 ++ -- 290 291and no space around the ``.`` and ``->`` structure member operators. 292 293Do not leave trailing whitespace at the ends of lines. Some editors with 294``smart`` indentation will insert whitespace at the beginning of new lines as 295appropriate, so you can start typing the next line of code right away. 296However, some such editors do not remove the whitespace if you end up not 297putting a line of code there, such as if you leave a blank line. As a result, 298you end up with lines containing trailing whitespace. 299 300Git will warn you about patches that introduce trailing whitespace, and can 301optionally strip the trailing whitespace for you; however, if applying a series 302of patches, this may make later patches in the series fail by changing their 303context lines. 304 305 3064) Naming 307--------- 308 309C is a Spartan language, and your naming conventions should follow suit. 310Unlike Modula-2 and Pascal programmers, C programmers do not use cute 311names like ThisVariableIsATemporaryCounter. A C programmer would call that 312variable ``tmp``, which is much easier to write, and not the least more 313difficult to understand. 314 315HOWEVER, while mixed-case names are frowned upon, descriptive names for 316global variables are a must. To call a global function ``foo`` is a 317shooting offense. 318 319GLOBAL variables (to be used only if you **really** need them) need to 320have descriptive names, as do global functions. If you have a function 321that counts the number of active users, you should call that 322``count_active_users()`` or similar, you should **not** call it ``cntusr()``. 323 324Encoding the type of a function into the name (so-called Hungarian 325notation) is asinine - the compiler knows the types anyway and can check 326those, and it only confuses the programmer. 327 328LOCAL variable names should be short, and to the point. If you have 329some random integer loop counter, it should probably be called ``i``. 330Calling it ``loop_counter`` is non-productive, if there is no chance of it 331being mis-understood. Similarly, ``tmp`` can be just about any type of 332variable that is used to hold a temporary value. 333 334If you are afraid to mix up your local variable names, you have another 335problem, which is called the function-growth-hormone-imbalance syndrome. 336See chapter 6 (Functions). 337 338For symbol names and documentation, avoid introducing new usage of 339'master / slave' (or 'slave' independent of 'master') and 'blacklist / 340whitelist'. 341 342Recommended replacements for 'master / slave' are: 343 '{primary,main} / {secondary,replica,subordinate}' 344 '{initiator,requester} / {target,responder}' 345 '{controller,host} / {device,worker,proxy}' 346 'leader / follower' 347 'director / performer' 348 349Recommended replacements for 'blacklist/whitelist' are: 350 'denylist / allowlist' 351 'blocklist / passlist' 352 353Exceptions for introducing new usage is to maintain a userspace ABI/API, 354or when updating code for an existing (as of 2020) hardware or protocol 355specification that mandates those terms. For new specifications 356translate specification usage of the terminology to the kernel coding 357standard where possible. 358 3595) Typedefs 360----------- 361 362Please don't use things like ``vps_t``. 363It's a **mistake** to use typedef for structures and pointers. When you see a 364 365.. code-block:: c 366 367 368 vps_t a; 369 370in the source, what does it mean? 371In contrast, if it says 372 373.. code-block:: c 374 375 struct virtual_container *a; 376 377you can actually tell what ``a`` is. 378 379Lots of people think that typedefs ``help readability``. Not so. They are 380useful only for: 381 382 (a) totally opaque objects (where the typedef is actively used to **hide** 383 what the object is). 384 385 Example: ``pte_t`` etc. opaque objects that you can only access using 386 the proper accessor functions. 387 388 .. note:: 389 390 Opaqueness and ``accessor functions`` are not good in themselves. 391 The reason we have them for things like pte_t etc. is that there 392 really is absolutely **zero** portably accessible information there. 393 394 (b) Clear integer types, where the abstraction **helps** avoid confusion 395 whether it is ``int`` or ``long``. 396 397 u8/u16/u32 are perfectly fine typedefs, although they fit into 398 category (d) better than here. 399 400 .. note:: 401 402 Again - there needs to be a **reason** for this. If something is 403 ``unsigned long``, then there's no reason to do 404 405 typedef unsigned long myflags_t; 406 407 but if there is a clear reason for why it under certain circumstances 408 might be an ``unsigned int`` and under other configurations might be 409 ``unsigned long``, then by all means go ahead and use a typedef. 410 411 (c) when you use sparse to literally create a **new** type for 412 type-checking. 413 414 (d) New types which are identical to standard C99 types, in certain 415 exceptional circumstances. 416 417 Although it would only take a short amount of time for the eyes and 418 brain to become accustomed to the standard types like ``uint32_t``, 419 some people object to their use anyway. 420 421 Therefore, the Linux-specific ``u8/u16/u32/u64`` types and their 422 signed equivalents which are identical to standard types are 423 permitted -- although they are not mandatory in new code of your 424 own. 425 426 When editing existing code which already uses one or the other set 427 of types, you should conform to the existing choices in that code. 428 429 (e) Types safe for use in userspace. 430 431 In certain structures which are visible to userspace, we cannot 432 require C99 types and cannot use the ``u32`` form above. Thus, we 433 use __u32 and similar types in all structures which are shared 434 with userspace. 435 436Maybe there are other cases too, but the rule should basically be to NEVER 437EVER use a typedef unless you can clearly match one of those rules. 438 439In general, a pointer, or a struct that has elements that can reasonably 440be directly accessed should **never** be a typedef. 441 442 4436) Functions 444------------ 445 446Functions should be short and sweet, and do just one thing. They should 447fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24, 448as we all know), and do one thing and do that well. 449 450The maximum length of a function is inversely proportional to the 451complexity and indentation level of that function. So, if you have a 452conceptually simple function that is just one long (but simple) 453case-statement, where you have to do lots of small things for a lot of 454different cases, it's OK to have a longer function. 455 456However, if you have a complex function, and you suspect that a 457less-than-gifted first-year high-school student might not even 458understand what the function is all about, you should adhere to the 459maximum limits all the more closely. Use helper functions with 460descriptive names (you can ask the compiler to in-line them if you think 461it's performance-critical, and it will probably do a better job of it 462than you would have done). 463 464Another measure of the function is the number of local variables. They 465shouldn't exceed 5-10, or you're doing something wrong. Re-think the 466function, and split it into smaller pieces. A human brain can 467generally easily keep track of about 7 different things, anything more 468and it gets confused. You know you're brilliant, but maybe you'd like 469to understand what you did 2 weeks from now. 470 471In source files, separate functions with one blank line. If the function is 472exported, the **EXPORT** macro for it should follow immediately after the 473closing function brace line. E.g.: 474 475.. code-block:: c 476 477 int system_is_up(void) 478 { 479 return system_state == SYSTEM_RUNNING; 480 } 481 EXPORT_SYMBOL(system_is_up); 482 4836.1) Function prototypes 484************************ 485 486In function prototypes, include parameter names with their data types. 487Although this is not required by the C language, it is preferred in Linux 488because it is a simple way to add valuable information for the reader. 489 490Do not use the ``extern`` keyword with function declarations as this makes 491lines longer and isn't strictly necessary. 492 493When writing function prototypes, please keep the `order of elements regular 494<https://lore.kernel.org/mm-commits/CAHk-=wiOCLRny5aifWNhr621kYrJwhfURsa0vFPeUEm8mF0ufg@mail.gmail.com/>`_. 495For example, using this function declaration example:: 496 497 __init void * __must_check action(enum magic value, size_t size, u8 count, 498 char *fmt, ...) __printf(4, 5) __malloc; 499 500The preferred order of elements for a function prototype is: 501 502- storage class (below, ``static __always_inline``, noting that ``__always_inline`` 503 is technically an attribute but is treated like ``inline``) 504- storage class attributes (here, ``__init`` -- i.e. section declarations, but also 505 things like ``__cold``) 506- return type (here, ``void *``) 507- return type attributes (here, ``__must_check``) 508- function name (here, ``action``) 509- function parameters (here, ``(enum magic value, size_t size, u8 count, char *fmt, ...)``, 510 noting that parameter names should always be included) 511- function parameter attributes (here, ``__printf(4, 5)``) 512- function behavior attributes (here, ``__malloc``) 513 514Note that for a function **definition** (i.e. the actual function body), 515the compiler does not allow function parameter attributes after the 516function parameters. In these cases, they should go after the storage 517class attributes (e.g. note the changed position of ``__printf(4, 5)`` 518below, compared to the **declaration** example above):: 519 520 static __always_inline __init __printf(4, 5) void * __must_check action(enum magic value, 521 size_t size, u8 count, char *fmt, ...) __malloc 522 { 523 ... 524 } 525 5267) Centralized exiting of functions 527----------------------------------- 528 529Albeit deprecated by some people, the equivalent of the goto statement is 530used frequently by compilers in form of the unconditional jump instruction. 531 532The goto statement comes in handy when a function exits from multiple 533locations and some common work such as cleanup has to be done. If there is no 534cleanup needed then just return directly. 535 536Choose label names which say what the goto does or why the goto exists. An 537example of a good name could be ``out_free_buffer:`` if the goto frees ``buffer``. 538Avoid using GW-BASIC names like ``err1:`` and ``err2:``, as you would have to 539renumber them if you ever add or remove exit paths, and they make correctness 540difficult to verify anyway. 541 542The rationale for using gotos is: 543 544- unconditional statements are easier to understand and follow 545- nesting is reduced 546- errors by not updating individual exit points when making 547 modifications are prevented 548- saves the compiler work to optimize redundant code away ;) 549 550.. code-block:: c 551 552 int fun(int a) 553 { 554 int result = 0; 555 char *buffer; 556 557 buffer = kmalloc(SIZE, GFP_KERNEL); 558 if (!buffer) 559 return -ENOMEM; 560 561 if (condition1) { 562 while (loop1) { 563 ... 564 } 565 result = 1; 566 goto out_free_buffer; 567 } 568 ... 569 out_free_buffer: 570 kfree(buffer); 571 return result; 572 } 573 574A common type of bug to be aware of is ``one err bugs`` which look like this: 575 576.. code-block:: c 577 578 err: 579 kfree(foo->bar); 580 kfree(foo); 581 return ret; 582 583The bug in this code is that on some exit paths ``foo`` is NULL. Normally the 584fix for this is to split it up into two error labels ``err_free_bar:`` and 585``err_free_foo:``: 586 587.. code-block:: c 588 589 err_free_bar: 590 kfree(foo->bar); 591 err_free_foo: 592 kfree(foo); 593 return ret; 594 595Ideally you should simulate errors to test all exit paths. 596 597 5988) Commenting 599------------- 600 601Comments are good, but there is also a danger of over-commenting. NEVER 602try to explain HOW your code works in a comment: it's much better to 603write the code so that the **working** is obvious, and it's a waste of 604time to explain badly written code. 605 606Generally, you want your comments to tell WHAT your code does, not HOW. 607Also, try to avoid putting comments inside a function body: if the 608function is so complex that you need to separately comment parts of it, 609you should probably go back to chapter 6 for a while. You can make 610small comments to note or warn about something particularly clever (or 611ugly), but try to avoid excess. Instead, put the comments at the head 612of the function, telling people what it does, and possibly WHY it does 613it. 614 615When commenting the kernel API functions, please use the kernel-doc format. 616See the files at :ref:`Documentation/doc-guide/ <doc_guide>` and 617``scripts/kernel-doc`` for details. 618 619The preferred style for long (multi-line) comments is: 620 621.. code-block:: c 622 623 /* 624 * This is the preferred style for multi-line 625 * comments in the Linux kernel source code. 626 * Please use it consistently. 627 * 628 * Description: A column of asterisks on the left side, 629 * with beginning and ending almost-blank lines. 630 */ 631 632It's also important to comment data, whether they are basic types or derived 633types. To this end, use just one data declaration per line (no commas for 634multiple data declarations). This leaves you room for a small comment on each 635item, explaining its use. 636 637 6389) You've made a mess of it 639--------------------------- 640 641That's OK, we all do. You've probably been told by your long-time Unix 642user helper that ``GNU emacs`` automatically formats the C sources for 643you, and you've noticed that yes, it does do that, but the defaults it 644uses are less than desirable (in fact, they are worse than random 645typing - an infinite number of monkeys typing into GNU emacs would never 646make a good program). 647 648So, you can either get rid of GNU emacs, or change it to use saner 649values. To do the latter, you can stick the following in your .emacs file: 650 651.. code-block:: elisp 652 653 (defun c-lineup-arglist-tabs-only (ignored) 654 "Line up argument lists by tabs, not spaces" 655 (let* ((anchor (c-langelem-pos c-syntactic-element)) 656 (column (c-langelem-2nd-pos c-syntactic-element)) 657 (offset (- (1+ column) anchor)) 658 (steps (floor offset c-basic-offset))) 659 (* (max steps 1) 660 c-basic-offset))) 661 662 (dir-locals-set-class-variables 663 'linux-kernel 664 '((c-mode . ( 665 (c-basic-offset . 8) 666 (c-label-minimum-indentation . 0) 667 (c-offsets-alist . ( 668 (arglist-close . c-lineup-arglist-tabs-only) 669 (arglist-cont-nonempty . 670 (c-lineup-gcc-asm-reg c-lineup-arglist-tabs-only)) 671 (arglist-intro . +) 672 (brace-list-intro . +) 673 (c . c-lineup-C-comments) 674 (case-label . 0) 675 (comment-intro . c-lineup-comment) 676 (cpp-define-intro . +) 677 (cpp-macro . -1000) 678 (cpp-macro-cont . +) 679 (defun-block-intro . +) 680 (else-clause . 0) 681 (func-decl-cont . +) 682 (inclass . +) 683 (inher-cont . c-lineup-multi-inher) 684 (knr-argdecl-intro . 0) 685 (label . -1000) 686 (statement . 0) 687 (statement-block-intro . +) 688 (statement-case-intro . +) 689 (statement-cont . +) 690 (substatement . +) 691 )) 692 (indent-tabs-mode . t) 693 (show-trailing-whitespace . t) 694 )))) 695 696 (dir-locals-set-directory-class 697 (expand-file-name "~/src/linux-trees") 698 'linux-kernel) 699 700This will make emacs go better with the kernel coding style for C 701files below ``~/src/linux-trees``. 702 703But even if you fail in getting emacs to do sane formatting, not 704everything is lost: use ``indent``. 705 706Now, again, GNU indent has the same brain-dead settings that GNU emacs 707has, which is why you need to give it a few command line options. 708However, that's not too bad, because even the makers of GNU indent 709recognize the authority of K&R (the GNU people aren't evil, they are 710just severely misguided in this matter), so you just give indent the 711options ``-kr -i8`` (stands for ``K&R, 8 character indents``), or use 712``scripts/Lindent``, which indents in the latest style. 713 714``indent`` has a lot of options, and especially when it comes to comment 715re-formatting you may want to take a look at the man page. But 716remember: ``indent`` is not a fix for bad programming. 717 718Note that you can also use the ``clang-format`` tool to help you with 719these rules, to quickly re-format parts of your code automatically, 720and to review full files in order to spot coding style mistakes, 721typos and possible improvements. It is also handy for sorting ``#includes``, 722for aligning variables/macros, for reflowing text and other similar tasks. 723See the file :ref:`Documentation/dev-tools/clang-format.rst <clangformat>` 724for more details. 725 726Some basic editor settings, such as indentation and line endings, will be 727set automatically if you are using an editor that is compatible with 728EditorConfig. See the official EditorConfig website for more information: 729https://editorconfig.org/ 730 73110) Kconfig configuration files 732------------------------------- 733 734For all of the Kconfig* configuration files throughout the source tree, 735the indentation is somewhat different. Lines under a ``config`` definition 736are indented with one tab, while help text is indented an additional two 737spaces. Example:: 738 739 config AUDIT 740 bool "Auditing support" 741 depends on NET 742 help 743 Enable auditing infrastructure that can be used with another 744 kernel subsystem, such as SELinux (which requires this for 745 logging of avc messages output). Does not do system-call 746 auditing without CONFIG_AUDITSYSCALL. 747 748Seriously dangerous features (such as write support for certain 749filesystems) should advertise this prominently in their prompt string:: 750 751 config ADFS_FS_RW 752 bool "ADFS write support (DANGEROUS)" 753 depends on ADFS_FS 754 ... 755 756For full documentation on the configuration files, see the file 757Documentation/kbuild/kconfig-language.rst. 758 759 76011) Data structures 761------------------- 762 763Data structures that have visibility outside the single-threaded 764environment they are created and destroyed in should always have 765reference counts. In the kernel, garbage collection doesn't exist (and 766outside the kernel garbage collection is slow and inefficient), which 767means that you absolutely **have** to reference count all your uses. 768 769Reference counting means that you can avoid locking, and allows multiple 770users to have access to the data structure in parallel - and not having 771to worry about the structure suddenly going away from under them just 772because they slept or did something else for a while. 773 774Note that locking is **not** a replacement for reference counting. 775Locking is used to keep data structures coherent, while reference 776counting is a memory management technique. Usually both are needed, and 777they are not to be confused with each other. 778 779Many data structures can indeed have two levels of reference counting, 780when there are users of different ``classes``. The subclass count counts 781the number of subclass users, and decrements the global count just once 782when the subclass count goes to zero. 783 784Examples of this kind of ``multi-level-reference-counting`` can be found in 785memory management (``struct mm_struct``: mm_users and mm_count), and in 786filesystem code (``struct super_block``: s_count and s_active). 787 788Remember: if another thread can find your data structure, and you don't 789have a reference count on it, you almost certainly have a bug. 790 791 79212) Macros, Enums and RTL 793------------------------- 794 795Names of macros defining constants and labels in enums are capitalized. 796 797.. code-block:: c 798 799 #define CONSTANT 0x12345 800 801Enums are preferred when defining several related constants. 802 803CAPITALIZED macro names are appreciated but macros resembling functions 804may be named in lower case. 805 806Generally, inline functions are preferable to macros resembling functions. 807 808Macros with multiple statements should be enclosed in a do - while block: 809 810.. code-block:: c 811 812 #define macrofun(a, b, c) \ 813 do { \ 814 if (a == 5) \ 815 do_this(b, c); \ 816 } while (0) 817 818Function-like macros with unused parameters should be replaced by static 819inline functions to avoid the issue of unused variables: 820 821.. code-block:: c 822 823 static inline void fun(struct foo *foo) 824 { 825 } 826 827Due to historical practices, many files still employ the "cast to (void)" 828approach to evaluate parameters. However, this method is not advisable. 829Inline functions address the issue of "expression with side effects 830evaluated more than once", circumvent unused-variable problems, and 831are generally better documented than macros for some reason. 832 833.. code-block:: c 834 835 /* 836 * Avoid doing this whenever possible and instead opt for static 837 * inline functions 838 */ 839 #define macrofun(foo) do { (void) (foo); } while (0) 840 841Things to avoid when using macros: 842 8431) macros that affect control flow: 844 845.. code-block:: c 846 847 #define FOO(x) \ 848 do { \ 849 if (blah(x) < 0) \ 850 return -EBUGGERED; \ 851 } while (0) 852 853is a **very** bad idea. It looks like a function call but exits the ``calling`` 854function; don't break the internal parsers of those who will read the code. 855 8562) macros that depend on having a local variable with a magic name: 857 858.. code-block:: c 859 860 #define FOO(val) bar(index, val) 861 862might look like a good thing, but it's confusing as hell when one reads the 863code and it's prone to breakage from seemingly innocent changes. 864 8653) macros with arguments that are used as l-values: FOO(x) = y; will 866bite you if somebody e.g. turns FOO into an inline function. 867 8684) forgetting about precedence: macros defining constants using expressions 869must enclose the expression in parentheses. Beware of similar issues with 870macros using parameters. 871 872.. code-block:: c 873 874 #define CONSTANT 0x4000 875 #define CONSTEXP (CONSTANT | 3) 876 8775) namespace collisions when defining local variables in macros resembling 878functions: 879 880.. code-block:: c 881 882 #define FOO(x) \ 883 ({ \ 884 typeof(x) ret; \ 885 ret = calc_ret(x); \ 886 (ret); \ 887 }) 888 889ret is a common name for a local variable - __foo_ret is less likely 890to collide with an existing variable. 891 892The cpp manual deals with macros exhaustively. The gcc internals manual also 893covers RTL which is used frequently with assembly language in the kernel. 894 895 89613) Printing kernel messages 897---------------------------- 898 899Kernel developers like to be seen as literate. Do mind the spelling 900of kernel messages to make a good impression. Do not use incorrect 901contractions like ``dont``; use ``do not`` or ``don't`` instead. Make the 902messages concise, clear, and unambiguous. 903 904Kernel messages do not have to be terminated with a period. 905 906Printing numbers in parentheses (%d) adds no value and should be avoided. 907 908There are a number of driver model diagnostic macros in <linux/dev_printk.h> 909which you should use to make sure messages are matched to the right device 910and driver, and are tagged with the right level: dev_err(), dev_warn(), 911dev_info(), and so forth. For messages that aren't associated with a 912particular device, <linux/printk.h> defines pr_notice(), pr_info(), 913pr_warn(), pr_err(), etc. When drivers are working properly they are quiet, 914so prefer to use dev_dbg/pr_debug unless something is wrong. 915 916Coming up with good debugging messages can be quite a challenge; and once 917you have them, they can be a huge help for remote troubleshooting. However 918debug message printing is handled differently than printing other non-debug 919messages. While the other pr_XXX() functions print unconditionally, 920pr_debug() does not; it is compiled out by default, unless either DEBUG is 921defined or CONFIG_DYNAMIC_DEBUG is set. That is true for dev_dbg() also, 922and a related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to 923the ones already enabled by DEBUG. 924 925Many subsystems have Kconfig debug options to turn on -DDEBUG in the 926corresponding Makefile; in other cases specific files #define DEBUG. And 927when a debug message should be unconditionally printed, such as if it is 928already inside a debug-related #ifdef section, printk(KERN_DEBUG ...) can be 929used. 930 931 93214) Allocating memory 933--------------------- 934 935The kernel provides the following general purpose memory allocators: 936kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and 937vzalloc(). Please refer to the API documentation for further information 938about them. :ref:`Documentation/core-api/memory-allocation.rst 939<memory_allocation>` 940 941The preferred form for passing a size of a struct is the following: 942 943.. code-block:: c 944 945 p = kmalloc(sizeof(*p), ...); 946 947The alternative form where struct name is spelled out hurts readability and 948introduces an opportunity for a bug when the pointer variable type is changed 949but the corresponding sizeof that is passed to a memory allocator is not. 950 951Casting the return value which is a void pointer is redundant. The conversion 952from void pointer to any other pointer type is guaranteed by the C programming 953language. 954 955The preferred form for allocating an array is the following: 956 957.. code-block:: c 958 959 p = kmalloc_array(n, sizeof(...), ...); 960 961The preferred form for allocating a zeroed array is the following: 962 963.. code-block:: c 964 965 p = kcalloc(n, sizeof(...), ...); 966 967Both forms check for overflow on the allocation size n * sizeof(...), 968and return NULL if that occurred. 969 970These generic allocation functions all emit a stack dump on failure when used 971without __GFP_NOWARN so there is no use in emitting an additional failure 972message when NULL is returned. 973 97415) The inline disease 975---------------------- 976 977There appears to be a common misperception that gcc has a magic "make me 978faster" speedup option called ``inline``. While the use of inlines can be 979appropriate (for example as a means of replacing macros, see Chapter 12), it 980very often is not. Abundant use of the inline keyword leads to a much bigger 981kernel, which in turn slows the system as a whole down, due to a bigger 982icache footprint for the CPU and simply because there is less memory 983available for the pagecache. Just think about it; a pagecache miss causes a 984disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles 985that can go into these 5 milliseconds. 986 987A reasonable rule of thumb is to not put inline at functions that have more 988than 3 lines of code in them. An exception to this rule are the cases where 989a parameter is known to be a compile time constant, and as a result of this 990constantness you *know* the compiler will be able to optimize most of your 991function away at compile time. For a good example of this later case, see 992the kmalloc() inline function. 993 994Often people argue that adding inline to functions that are static and used 995only once is always a win since there is no space tradeoff. While this is 996technically correct, gcc is capable of inlining these automatically without 997help, and the maintenance issue of removing the inline when a second user 998appears outweighs the potential value of the hint that tells gcc to do 999something it would have done anyway. 1000 1001 100216) Function return values and names 1003------------------------------------ 1004 1005Functions can return values of many different kinds, and one of the 1006most common is a value indicating whether the function succeeded or 1007failed. Such a value can be represented as an error-code integer 1008(-Exxx = failure, 0 = success) or a ``succeeded`` boolean (0 = failure, 1009non-zero = success). 1010 1011Mixing up these two sorts of representations is a fertile source of 1012difficult-to-find bugs. If the C language included a strong distinction 1013between integers and booleans then the compiler would find these mistakes 1014for us... but it doesn't. To help prevent such bugs, always follow this 1015convention:: 1016 1017 If the name of a function is an action or an imperative command, 1018 the function should return an error-code integer. If the name 1019 is a predicate, the function should return a "succeeded" boolean. 1020 1021For example, ``add work`` is a command, and the add_work() function returns 0 1022for success or -EBUSY for failure. In the same way, ``PCI device present`` is 1023a predicate, and the pci_dev_present() function returns 1 if it succeeds in 1024finding a matching device or 0 if it doesn't. 1025 1026All EXPORTed functions must respect this convention, and so should all 1027public functions. Private (static) functions need not, but it is 1028recommended that they do. 1029 1030Functions whose return value is the actual result of a computation, rather 1031than an indication of whether the computation succeeded, are not subject to 1032this rule. Generally they indicate failure by returning some out-of-range 1033result. Typical examples would be functions that return pointers; they use 1034NULL or the ERR_PTR mechanism to report failure. 1035 1036 103717) Using bool 1038-------------- 1039 1040The Linux kernel bool type is an alias for the C99 _Bool type. bool values can 1041only evaluate to 0 or 1, and implicit or explicit conversion to bool 1042automatically converts the value to true or false. When using bool types the 1043!! construction is not needed, which eliminates a class of bugs. 1044 1045When working with bool values the true and false definitions should be used 1046instead of 1 and 0. 1047 1048bool function return types and stack variables are always fine to use whenever 1049appropriate. Use of bool is encouraged to improve readability and is often a 1050better option than 'int' for storing boolean values. 1051 1052Do not use bool if cache line layout or size of the value matters, as its size 1053and alignment varies based on the compiled architecture. Structures that are 1054optimized for alignment and size should not use bool. 1055 1056If a structure has many true/false values, consider consolidating them into a 1057bitfield with 1 bit members, or using an appropriate fixed width type, such as 1058u8. 1059 1060Similarly for function arguments, many true/false values can be consolidated 1061into a single bitwise 'flags' argument and 'flags' can often be a more 1062readable alternative if the call-sites have naked true/false constants. 1063 1064Otherwise limited use of bool in structures and arguments can improve 1065readability. 1066 106718) Don't re-invent the kernel macros 1068------------------------------------- 1069 1070The header file include/linux/kernel.h contains a number of macros that 1071you should use, rather than explicitly coding some variant of them yourself. 1072For example, if you need to calculate the length of an array, take advantage 1073of the macro 1074 1075.. code-block:: c 1076 1077 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) 1078 1079Similarly, if you need to calculate the size of some structure member, use 1080 1081.. code-block:: c 1082 1083 #define sizeof_field(t, f) (sizeof(((t*)0)->f)) 1084 1085There are also min() and max() macros that do strict type checking if you 1086need them. Feel free to peruse that header file to see what else is already 1087defined that you shouldn't reproduce in your code. 1088 1089 109019) Editor modelines and other cruft 1091------------------------------------ 1092 1093Some editors can interpret configuration information embedded in source files, 1094indicated with special markers. For example, emacs interprets lines marked 1095like this: 1096 1097.. code-block:: c 1098 1099 -*- mode: c -*- 1100 1101Or like this: 1102 1103.. code-block:: c 1104 1105 /* 1106 Local Variables: 1107 compile-command: "gcc -DMAGIC_DEBUG_FLAG foo.c" 1108 End: 1109 */ 1110 1111Vim interprets markers that look like this: 1112 1113.. code-block:: c 1114 1115 /* vim:set sw=8 noet */ 1116 1117Do not include any of these in source files. People have their own personal 1118editor configurations, and your source files should not override them. This 1119includes markers for indentation and mode configuration. People may use their 1120own custom mode, or may have some other magic method for making indentation 1121work correctly. 1122 1123 112420) Inline assembly 1125------------------- 1126 1127In architecture-specific code, you may need to use inline assembly to interface 1128with CPU or platform functionality. Don't hesitate to do so when necessary. 1129However, don't use inline assembly gratuitously when C can do the job. You can 1130and should poke hardware from C when possible. 1131 1132Consider writing simple helper functions that wrap common bits of inline 1133assembly, rather than repeatedly writing them with slight variations. Remember 1134that inline assembly can use C parameters. 1135 1136Large, non-trivial assembly functions should go in .S files, with corresponding 1137C prototypes defined in C header files. The C prototypes for assembly 1138functions should use ``asmlinkage``. 1139 1140You may need to mark your asm statement as volatile, to prevent GCC from 1141removing it if GCC doesn't notice any side effects. You don't always need to 1142do so, though, and doing so unnecessarily can limit optimization. 1143 1144When writing a single inline assembly statement containing multiple 1145instructions, put each instruction on a separate line in a separate quoted 1146string, and end each string except the last with ``\n\t`` to properly indent 1147the next instruction in the assembly output: 1148 1149.. code-block:: c 1150 1151 asm ("magic %reg1, #42\n\t" 1152 "more_magic %reg2, %reg3" 1153 : /* outputs */ : /* inputs */ : /* clobbers */); 1154 1155 115621) Conditional Compilation 1157--------------------------- 1158 1159Wherever possible, don't use preprocessor conditionals (#if, #ifdef) in .c 1160files; doing so makes code harder to read and logic harder to follow. Instead, 1161use such conditionals in a header file defining functions for use in those .c 1162files, providing no-op stub versions in the #else case, and then call those 1163functions unconditionally from .c files. The compiler will avoid generating 1164any code for the stub calls, producing identical results, but the logic will 1165remain easy to follow. 1166 1167Prefer to compile out entire functions, rather than portions of functions or 1168portions of expressions. Rather than putting an ifdef in an expression, factor 1169out part or all of the expression into a separate helper function and apply the 1170conditional to that function. 1171 1172If you have a function or variable which may potentially go unused in a 1173particular configuration, and the compiler would warn about its definition 1174going unused, mark the definition as __maybe_unused rather than wrapping it in 1175a preprocessor conditional. (However, if a function or variable *always* goes 1176unused, delete it.) 1177 1178Within code, where possible, use the IS_ENABLED macro to convert a Kconfig 1179symbol into a C boolean expression, and use it in a normal C conditional: 1180 1181.. code-block:: c 1182 1183 if (IS_ENABLED(CONFIG_SOMETHING)) { 1184 ... 1185 } 1186 1187The compiler will constant-fold the conditional away, and include or exclude 1188the block of code just as with an #ifdef, so this will not add any runtime 1189overhead. However, this approach still allows the C compiler to see the code 1190inside the block, and check it for correctness (syntax, types, symbol 1191references, etc). Thus, you still have to use an #ifdef if the code inside the 1192block references symbols that will not exist if the condition is not met. 1193 1194At the end of any non-trivial #if or #ifdef block (more than a few lines), 1195place a comment after the #endif on the same line, noting the conditional 1196expression used. For instance: 1197 1198.. code-block:: c 1199 1200 #ifdef CONFIG_SOMETHING 1201 ... 1202 #endif /* CONFIG_SOMETHING */ 1203 1204 120522) Do not crash the kernel 1206--------------------------- 1207 1208In general, the decision to crash the kernel belongs to the user, rather 1209than to the kernel developer. 1210 1211Avoid panic() 1212************* 1213 1214panic() should be used with care and primarily only during system boot. 1215panic() is, for example, acceptable when running out of memory during boot and 1216not being able to continue. 1217 1218Use WARN() rather than BUG() 1219**************************** 1220 1221Do not add new code that uses any of the BUG() variants, such as BUG(), 1222BUG_ON(), or VM_BUG_ON(). Instead, use a WARN*() variant, preferably 1223WARN_ON_ONCE(), and possibly with recovery code. Recovery code is not 1224required if there is no reasonable way to at least partially recover. 1225 1226"I'm too lazy to do error handling" is not an excuse for using BUG(). Major 1227internal corruptions with no way of continuing may still use BUG(), but need 1228good justification. 1229 1230Use WARN_ON_ONCE() rather than WARN() or WARN_ON() 1231************************************************** 1232 1233WARN_ON_ONCE() is generally preferred over WARN() or WARN_ON(), because it 1234is common for a given warning condition, if it occurs at all, to occur 1235multiple times. This can fill up and wrap the kernel log, and can even slow 1236the system enough that the excessive logging turns into its own, additional 1237problem. 1238 1239Do not WARN lightly 1240******************* 1241 1242WARN*() is intended for unexpected, this-should-never-happen situations. 1243WARN*() macros are not to be used for anything that is expected to happen 1244during normal operation. These are not pre- or post-condition asserts, for 1245example. Again: WARN*() must not be used for a condition that is expected 1246to trigger easily, for example, by user space actions. pr_warn_once() is a 1247possible alternative, if you need to notify the user of a problem. 1248 1249Do not worry about panic_on_warn users 1250************************************** 1251 1252A few more words about panic_on_warn: Remember that ``panic_on_warn`` is an 1253available kernel option, and that many users set this option. This is why 1254there is a "Do not WARN lightly" writeup, above. However, the existence of 1255panic_on_warn users is not a valid reason to avoid the judicious use 1256WARN*(). That is because, whoever enables panic_on_warn has explicitly 1257asked the kernel to crash if a WARN*() fires, and such users must be 1258prepared to deal with the consequences of a system that is somewhat more 1259likely to crash. 1260 1261Use BUILD_BUG_ON() for compile-time assertions 1262********************************************** 1263 1264The use of BUILD_BUG_ON() is acceptable and encouraged, because it is a 1265compile-time assertion that has no effect at runtime. 1266 1267Appendix I) References 1268---------------------- 1269 1270The C Programming Language, Second Edition 1271by Brian W. Kernighan and Dennis M. Ritchie. 1272Prentice Hall, Inc., 1988. 1273ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback). 1274 1275The Practice of Programming 1276by Brian W. Kernighan and Rob Pike. 1277Addison-Wesley, Inc., 1999. 1278ISBN 0-201-61586-X. 1279 1280GNU manuals - where in compliance with K&R and this text - for cpp, gcc, 1281gcc internals and indent, all available from https://www.gnu.org/manual/ 1282 1283WG14 is the international standardization working group for the programming 1284language C, URL: http://www.open-std.org/JTC1/SC22/WG14/ 1285 1286Kernel CodingStyle, by greg@kroah.com at OLS 2002: 1287http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/ 1288