Documentation/releases: Finalize 4.11, start 4.12
[coreboot.git] / Documentation / coding_style.md
blobac0de4ea9dfc0cd470fe8183c94ced185fdf54fe
1 # Coding Style
3 This is a short document describing the preferred coding style for the
4 coreboot project. It is in many ways exactly the same as the Linux
5 kernel coding style. In fact, most of this document has been copied from
6 the [Linux kernel coding style](http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/Documentation/CodingStyle?id=HEAD)
8 Please at least consider the points made here.
10 First off, I'd suggest printing out a copy of the GNU coding standards,
11 and NOT read it. Burn them, it's a great symbolic gesture.
13 Anyway, here goes:
15 ## Indentation
17 Tabs are 8 characters, and thus indentations are also 8 characters.
18 There are heretic movements that try to make indentations 4 (or even 2!)
19 characters deep, and that is akin to trying to define the value of PI to
20 be 3.
22 Rationale: The whole idea behind indentation is to clearly define where
23 a block of control starts and ends. Especially when you've been looking
24 at your screen for 20 straight hours, you'll find it a lot easier to
25 see how the indentation works if you have large indentations.
27 Now, some people will claim that having 8-character indentations makes
28 the code move too far to the right, and makes it hard to read on a
29 80-character terminal screen. The answer to that is that if you need
30 more than 3 levels of indentation, you're screwed anyway, and should
31 fix your program.
33 In short, 8-char indents make things easier to read, and have the added
34 benefit of warning you when you're nesting your functions too deep.
35 Heed that warning.
37 The preferred way to ease multiple indentation levels in a switch
38 statement is to align the "switch" and its subordinate "case" labels
39 in the same column instead of "double-indenting" the "case" labels.
40 E.g.:
42 ```c
43 switch (suffix) {
44 case 'G':
45 case 'g':
46         mem <<= 30;
47         break;
48 case 'M':
49 case 'm':
50         mem <<= 20;
51         break;
52 case 'K':
53 case 'k':
54         mem <<= 10;
55         /* fall through */
56 default:
57         break;
59 ```
61 Don't put multiple statements on a single line unless you have
62 something to hide:
64 ```c
65 if (condition) do_this;
66   do_something_everytime;
67 ```
69 Don't put multiple assignments on a single line either. Kernel coding
70 style is super simple. Avoid tricky expressions.
72 Outside of comments, documentation and except in Kconfig, spaces are
73 never used for indentation, and the above example is deliberately
74 broken.
76 Get a decent editor and don't leave whitespace at the end of lines.
78 ## Breaking long lines and strings
80 Coding style is all about readability and maintainability using commonly
81 available tools.
83 The limit on the length of lines is 96 columns and this is a strongly
84 preferred limit.
86 Statements longer than 96 columns will be broken into sensible chunks,
87 unless exceeding 96 columns significantly increases readability and does
88 not hide information. Descendants are always substantially shorter than
89 the parent and are placed substantially to the right. The same applies
90 to function headers with a long argument list. However, never break
91 user-visible strings such as printk messages, because that breaks the
92 ability to grep for them.
94 ## Placing Braces and Spaces
96 The other issue that always comes up in C styling is the placement of
97 braces. Unlike the indent size, there are few technical reasons to
98 choose one placement strategy over the other, but the preferred way, as
99 shown to us by the prophets Kernighan and Ritchie, is to put the opening
100 brace last on the line, and put the closing brace first, thusly:
102 ```c
103 if (x is true) {
104         we do y
108 This applies to all non-function statement blocks (if, switch, for,
109 while, do). E.g.:
111 ```c
112 switch (action) {
113 case KOBJ_ADD:
114         return "add";
115 case KOBJ_REMOVE:
116         return "remove";
117 case KOBJ_CHANGE:
118         return "change";
119 default:
120         return NULL;
124 However, there is one special case, namely functions: they have the
125 opening brace at the beginning of the next line, thus:
127 ```c
128 int function(int x)
130         body of function
134 Heretic people all over the world have claimed that this inconsistency
135 is ... well ... inconsistent, but all right-thinking people know that
136 (a) K&R are _right_ and (b) K&R are right. Besides, functions are
137 special anyway (you can't nest them in C).
139 Note that the closing brace is empty on a line of its own, _except_ in
140 the cases where it is followed by a continuation of the same statement,
141 ie a "while" in a do-statement or an "else" in an if-statement, like
142 this:
144 ```c
145 do {
146         body of do-loop
147 } while (condition);
152 ```c
153 if (x == y) {
154         ..
155 } else if (x > y) {
156         ...
157 } else {
158         ....
162 Rationale: K&R.
164 Also, note that this brace-placement also minimizes the number of empty
165 (or almost empty) lines, without any loss of readability. Thus, as the
166 supply of new-lines on your screen is not a renewable resource (think
167 25-line terminal screens here), you have more empty lines to put
168 comments on.
170 Do not unnecessarily use braces where a single statement will do.
172 ```c
173 if (condition)
174         action();
179 ```c
180 if (condition)
181         do_this();
182 else
183         do_that();
186 This does not apply if only one branch of a conditional statement is a
187 single statement; in the latter case use braces in both branches:
189 ```c
190 if (condition) {
191         do_this();
192         do_that();
193 } else {
194         otherwise();
198 ### Spaces
200 Linux kernel style for use of spaces depends (mostly) on
201 function-versus-keyword usage. Use a space after (most) keywords. The
202 notable exceptions are sizeof, typeof, alignof, and __attribute__,
203 which look somewhat like functions (and are usually used with
204 parentheses in Linux, although they are not required in the language, as
205 in: "sizeof info" after "struct fileinfo info;" is declared).
207 So use a space after these keywords:
210 if, switch, case, for, do, while
213 but not with sizeof, typeof, alignof, or __attribute__. E.g.,
215 ```c
216 s = sizeof(struct file);
219 Do not add spaces around (inside) parenthesized expressions. This
220 example is
222 -   bad*:
224 ```c
225 s = sizeof( struct file );
228 When declaring pointer data or a function that returns a pointer type,
229 the preferred use of '*' is adjacent to the data name or function
230 name and not adjacent to the type name. Examples:
232 ```c
233 char *linux_banner;
234 unsigned long long memparse(char *ptr, char **retptr);
235 char *match_strdup(substring_t *s);
238 Use one space around (on each side of) most binary and ternary
239 operators, such as any of these:
242 =  +  -  <  >  *  /  %  |  &  ^  <=  >=  ==  !=  ?  :
245 but no space after unary operators:
248 &  *  +  -  ~  !  sizeof  typeof  alignof  __attribute__  defined
251 no space before the postfix increment & decrement unary operators:
254 ++  --
257 no space after the prefix increment & decrement unary operators:
260 ++  --
263 and no space around the '.' and "->" structure member operators.
265 Do not leave trailing whitespace at the ends of lines. Some editors with
266 "smart" indentation will insert whitespace at the beginning of new
267 lines as appropriate, so you can start typing the next line of code
268 right away. However, some such editors do not remove the whitespace if
269 you end up not putting a line of code there, such as if you leave a
270 blank line. As a result, you end up with lines containing trailing
271 whitespace.
273 Git will warn you about patches that introduce trailing whitespace, and
274 can optionally strip the trailing whitespace for you; however, if
275 applying a series of patches, this may make later patches in the series
276 fail by changing their context lines.
278 ### Naming
280 C is a Spartan language, and so should your naming be. Unlike Modula-2
281 and Pascal programmers, C programmers do not use cute names like
282 ThisVariableIsATemporaryCounter. A C programmer would call that variable
283 "tmp", which is much easier to write, and not the least more difficult
284 to understand.
286 HOWEVER, while mixed-case names are frowned upon, descriptive names for
287 global variables are a must. To call a global function "foo" is a
288 shooting offense.
290 GLOBAL variables (to be used only if you _really_ need them) need to
291 have descriptive names, as do global functions. If you have a function
292 that counts the number of active users, you should call that
293 "count_active_users()" or similar, you should _not_ call it
294 "cntusr()".
296 Encoding the type of a function into the name (so-called Hungarian
297 notation) is brain damaged - the compiler knows the types anyway and can
298 check those, and it only confuses the programmer. No wonder MicroSoft
299 makes buggy programs.
301 LOCAL variable names should be short, and to the point. If you have some
302 random integer loop counter, it should probably be called "i". Calling
303 it "loop_counter" is non-productive, if there is no chance of it
304 being mis-understood. Similarly, "tmp" can be just about any type of
305 variable that is used to hold a temporary value.
307 If you are afraid to mix up your local variable names, you have another
308 problem, which is called the function-growth-hormone-imbalance syndrome.
309 See chapter 6 (Functions).
311 ## Typedefs
313 Please don't use things like "vps_t".
315 It's a _mistake_ to use typedef for structures and pointers. When you
316 see a
318 ```c
319 vps_t a;
322 in the source, what does it mean?
324 In contrast, if it says
326 ```c
327 struct virtual_container *a;
330 you can actually tell what "a" is.
332 Lots of people think that typedefs "help readability". Not so. They
333 are useful only for:
335 (a) totally opaque objects (where the typedef is actively used to
336 _hide_ what the object is).
338 Example: "pte_t" etc. opaque objects that you can only access using
339 the proper accessor functions.
341 NOTE! Opaqueness and "accessor functions" are not good in themselves.
342 The reason we have them for things like pte_t etc. is that there really
343 is absolutely _zero_ portably accessible information there.
345 (b) Clear integer types, where the abstraction _helps_ avoid confusion
346 whether it is "int" or "long".
348 u8/u16/u32 are perfectly fine typedefs, although they fit into category
349 (d) better than here.
351 NOTE! Again - there needs to be a _reason_ for this. If something is
352 "unsigned long", then there's no reason to do
354 ```c
355 typedef unsigned long myflags_t;
358 but if there is a clear reason for why it under certain circumstances
359 might be an "unsigned int" and under other configurations might be
360 "unsigned long", then by all means go ahead and use a typedef.
362 (c) when you use sparse to literally create a _new_ type for
363 type-checking.
365 (d) New types which are identical to standard C99 types, in certain
366 exceptional circumstances.
368 Although it would only take a short amount of time for the eyes and
369 brain to become accustomed to the standard types like 'uint32_t',
370 some people object to their use anyway.
372 Therefore, the Linux-specific 'u8/u16/u32/u64' types and their signed
373 equivalents which are identical to standard types are permitted --
374 although they are not mandatory in new code of your own.
376 When editing existing code which already uses one or the other set of
377 types, you should conform to the existing choices in that code.
379 (e) Types safe for use in userspace.
381 In certain structures which are visible to userspace, we cannot require
382 C99 types and cannot use the 'u32' form above. Thus, we use __u32
383 and similar types in all structures which are shared with userspace.
385 Maybe there are other cases too, but the rule should basically be to
386 NEVER EVER use a typedef unless you can clearly match one of those
387 rules.
389 In general, a pointer, or a struct that has elements that can reasonably
390 be directly accessed should _never_ be a typedef.
392 ## Functions
394 Functions should be short and sweet, and do just one thing. They should
395 fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,
396 as we all know), and do one thing and do that well.
398 The maximum length of a function is inversely proportional to the
399 complexity and indentation level of that function. So, if you have a
400 conceptually simple function that is just one long (but simple)
401 case-statement, where you have to do lots of small things for a lot of
402 different cases, it's OK to have a longer function.
404 However, if you have a complex function, and you suspect that a
405 less-than-gifted first-year high-school student might not even
406 understand what the function is all about, you should adhere to the
407 maximum limits all the more closely. Use helper functions with
408 descriptive names (you can ask the compiler to in-line them if you think
409 it's performance-critical, and it will probably do a better job of it
410 than you would have done).
412 Another measure of the function is the number of local variables. They
413 shouldn't exceed 5-10, or you're doing something wrong. Re-think the
414 function, and split it into smaller pieces. A human brain can generally
415 easily keep track of about 7 different things, anything more and it gets
416 confused. You know you're brilliant, but maybe you'd like to
417 understand what you did 2 weeks from now.
419 In source files, separate functions with one blank line. If the function
420 is exported, the EXPORT* macro for it should follow immediately after
421 the closing function brace line. E.g.:
423 ```c
424 int system_is_up(void)
426         return system_state == SYSTEM_RUNNING;
428 EXPORT_SYMBOL(system_is_up);
431 In function prototypes, include parameter names with their data types.
432 Although this is not required by the C language, it is preferred in
433 Linux because it is a simple way to add valuable information for the
434 reader.
436 ## Centralized exiting of functions
438 Albeit deprecated by some people, the equivalent of the goto statement
439 is used frequently by compilers in form of the unconditional jump
440 instruction.
442 The goto statement comes in handy when a function exits from multiple
443 locations and some common work such as cleanup has to be done. If there
444 is no cleanup needed then just return directly.
446 The rationale is:
448 -   unconditional statements are easier to understand and follow
449 -   nesting is reduced
450 -   errors by not updating individual exit points when making
451     modifications are prevented
452 -   saves the compiler work to optimize redundant code away ;)
454 ```c
455 int fun(int a)
457         int result = 0;
458         char *buffer = kmalloc(SIZE);
460         if (buffer == NULL)
461                 return -ENOMEM;
463         if (condition1) {
464                 while (loop1) {
465                         ...
466                 }
467                 result = 1;
468                 goto out;
469         }
470         ...
471         out:
472         kfree(buffer);
473         return result;
477 ## Commenting
479 Comments are good, but there is also a danger of over-commenting. NEVER
480 try to explain HOW your code works in a comment: it's much better to
481 write the code so that the _working_ is obvious, and it's a waste of
482 time to explain badly written code.
484 Generally, you want your comments to tell WHAT your code does, not HOW.
485 Also, try to avoid putting comments inside a function body: if the
486 function is so complex that you need to separately comment parts of it,
487 you should probably go back to chapter 6 for a while. You can make small
488 comments to note or warn about something particularly clever (or ugly),
489 but try to avoid excess. Instead, put the comments at the head of the
490 function, telling people what it does, and possibly WHY it does it.
492 When commenting the kernel API functions, please use the kernel-doc
493 format. See the files Documentation/kernel-doc-nano-HOWTO.txt and
494 scripts/kernel-doc for details.
496 coreboot style for comments is the C89 "/* ... */" style. You may
497 use C99-style "// ..." comments.
499 The preferred style for *short* (multi-line) comments is:
501 ```c
502 /* This is the preferred style for short multi-line
503    comments in the Linux kernel source code.
504    Please use it consistently. */
507 The preferred style for *long* (multi-line) comments is:
509 ```c
511  * This is the preferred style for multi-line
512  * comments in the Linux kernel source code.
513  * Please use it consistently.
515  * Description:  A column of asterisks on the left side,
516  * with beginning and ending almost-blank lines.
517  */
520 It's also important to comment data, whether they are basic types or
521 derived types. To this end, use just one data declaration per line (no
522 commas for multiple data declarations). This leaves you room for a small
523 comment on each item, explaining its use.
525 ## You've made a mess of it
526 That's OK, we all do. You've probably been told by your long-time Unix user
527 helper that "GNU emacs" automatically formats the C sources for you, and
528 you've noticed that yes, it does do that, but the defaults it uses are less
529 than desirable (in fact, they are worse than random typing - an infinite
530 number of monkeys typing into GNU emacs would never make a good program).
532 So, you can either get rid of GNU emacs, or change it to use saner values.
533 To do the latter, you can stick the following in your .emacs file: 
535 ```lisp
536 (defun c-lineup-arglist-tabs-only (ignored)
537   "Line up argument lists by tabs, not spaces"
538   (let* ((anchor (c-langelem-pos c-syntactic-element))
539          (column (c-langelem-2nd-pos c-syntactic-element))
540          (offset (- (1+ column) anchor))
541          (steps (floor offset c-basic-offset)))
542     (* (max steps 1)
543        c-basic-offset)))
545 (add-hook 'c-mode-common-hook
546           (lambda ()
547             ;; Add kernel style
548             (c-add-style
549              "linux-tabs-only"
550              '("linux" (c-offsets-alist
551                         (arglist-cont-nonempty
552                          c-lineup-gcc-asm-reg
553                          c-lineup-arglist-tabs-only))))))
555 (add-hook 'c-mode-hook
556           (lambda ()
557             (let ((filename (buffer-file-name)))
558               ;; Enable kernel mode for the appropriate files
559               (when (and filename
560                          (string-match (expand-file-name "~/src/linux-trees")
561                                         filename))
562                 (setq indent-tabs-mode t)
563                 (c-set-style "linux-tabs-only")))))
566 This will make emacs go better with the kernel coding style for C files
567 below ~/src/linux-trees.
569 But even if you fail in getting emacs to do sane formatting, not
570 everything is lost: use "indent".
572 Now, again, GNU indent has the same brain-dead settings that GNU emacs
573 has, which is why you need to give it a few command line options.
574 However, that's not too bad, because even the makers of GNU indent
575 recognize the authority of K&R (the GNU people aren't evil, they are
576 just severely misguided in this matter), so you just give indent the
577 options "-kr -i8" (stands for "K&R, 8 character indents"), or use
578 "scripts/Lindent", which indents in the latest style.
580 "indent" has a lot of options, and especially when it comes to comment
581 re-formatting you may want to take a look at the man page. But remember:
582 "indent" is not a fix for bad programming.
584 ## Kconfig configuration files
586 For all of the Kconfig* configuration files throughout the source tree,
587 the indentation is somewhat different. Lines under a "config"
588 definition are indented with one tab, while help text is indented an
589 additional two spaces. Example:
591 ```kconfig
592 config AUDIT
593         bool "Auditing support"
594         depends on NET
595         help
596           Enable auditing infrastructure that can be used with another
597           kernel subsystem, such as SELinux (which requires this for
598           logging of avc messages output).  Does not do system-call
599           auditing without CONFIG_AUDITSYSCALL.
602 Seriously dangerous features (such as write support for certain
603 filesystems) should advertise this prominently in their prompt string:
605 ```kconfig
606 config ADFS_FS_RW
607         bool "ADFS write support (DANGEROUS)"
608         depends on ADFS_FS
609         ...
612 For full documentation on the configuration files, see the file
613 Documentation/kbuild/kconfig-language.txt.
615 Data structures
616 ---------------
618 Data structures that have visibility outside the single-threaded
619 environment they are created and destroyed in should always have
620 reference counts. In the kernel, garbage collection doesn't exist (and
621 outside the kernel garbage collection is slow and inefficient), which
622 means that you absolutely _have_ to reference count all your uses.
624 Reference counting means that you can avoid locking, and allows multiple
625 users to have access to the data structure in parallel - and not having
626 to worry about the structure suddenly going away from under them just
627 because they slept or did something else for a while.
629 Note that locking is _not_ a replacement for reference counting.
630 Locking is used to keep data structures coherent, while reference
631 counting is a memory management technique. Usually both are needed, and
632 they are not to be confused with each other.
634 Many data structures can indeed have two levels of reference counting,
635 when there are users of different "classes". The subclass count counts
636 the number of subclass users, and decrements the global count just once
637 when the subclass count goes to zero.
639 Examples of this kind of "multi-level-reference-counting" can be found
640 in memory management ("struct mm_struct": mm_users and mm_count),
641 and in filesystem code ("struct super_block": s_count and
642 s_active).
644 Remember: if another thread can find your data structure, and you don't
645 have a reference count on it, you almost certainly have a bug.
647 Macros, Enums and RTL
648 ---------------------
650 Names of macros defining constants and labels in enums are capitalized.
652 ```c
653 #define CONSTANT 0x12345
656 Enums are preferred when defining several related constants.
658 CAPITALIZED macro names are appreciated but macros resembling functions
659 may be named in lower case.
661 Generally, inline functions are preferable to macros resembling
662 functions.
664 Macros with multiple statements should be enclosed in a do - while
665 block:
667 ```c
668 #define macrofun(a, b, c)   \
669     do {                    \
670         if (a == 5)         \
671             do_this(b, c);  \
672     } while (0)
675 Things to avoid when using macros:
677 1) macros that affect control flow:
679 ```c
680 #define FOO(x)              \
681     do {                        \
682             if (blah(x) < 0)        \
683                     return -EBUGGERED;  \
684     } while(0)
687 is a *very* bad idea. It looks like a function call but exits the
688 "calling" function; don't break the internal parsers of those who
689 will read the code.
691 2) macros that depend on having a local variable with a magic name:
693 ```c
694 #define FOO(val) bar(index, val)
697 might look like a good thing, but it's confusing as hell when one reads
698 the code and it's prone to breakage from seemingly innocent changes.
700 3) macros with arguments that are used as l-values: FOO(x) = y; will
701 bite you if somebody e.g. turns FOO into an inline function.
703 4) forgetting about precedence: macros defining constants using
704 expressions must enclose the expression in parentheses. Beware of
705 similar issues with macros using parameters.
707 ```c
708 #define CONSTANT 0x4000
709 #define CONSTEXP (CONSTANT | 3)
712 The cpp manual deals with macros exhaustively. The gcc internals manual
713 also covers RTL which is used frequently with assembly language in the
714 kernel.
716 Printing kernel messages
717 ------------------------
719 Kernel developers like to be seen as literate. Do mind the spelling of
720 kernel messages to make a good impression. Do not use crippled words
721 like "dont"; use "do not" or "don't" instead. Make the messages
722 concise, clear, and unambiguous.
724 Kernel messages do not have to be terminated with a period.
726 Printing numbers in parentheses (%d) adds no value and should be
727 avoided.
729 There are a number of driver model diagnostic macros in
730 <linux/device.h> which you should use to make sure messages are
731 matched to the right device and driver, and are tagged with the right
732 level: dev_err(), dev_warn(), dev_info(), and so forth. For messages
733 that aren't associated with a particular device, <linux/printk.h>
734 defines pr_debug() and pr_info().
736 Coming up with good debugging messages can be quite a challenge; and
737 once you have them, they can be a huge help for remote troubleshooting.
738 Such messages should be compiled out when the DEBUG symbol is not
739 defined (that is, by default they are not included). When you use
740 dev_dbg() or pr_debug(), that's automatic. Many subsystems have
741 Kconfig options to turn on -DDEBUG. A related convention uses
742 VERBOSE_DEBUG to add dev_vdbg() messages to the ones already enabled
743 by DEBUG.
745 Allocating memory
746 -----------------
748 coreboot provides a single general purpose memory allocator: malloc()
750 The preferred form for passing a size of a struct is the following:
752 ```c
753 p = malloc(sizeof(*p));
756 The alternative form where struct name is spelled out hurts readability
757 and introduces an opportunity for a bug when the pointer variable type
758 is changed but the corresponding sizeof that is passed to a memory
759 allocator is not.
761 Casting the return value which is a void pointer is redundant. The
762 conversion from void pointer to any other pointer type is guaranteed by
763 the C programming language.
765 You should contain your memory usage to stack variables whenever
766 possible. Only use malloc() as a last resort. In ramstage, you may also
767 be able to get away with using static variables. Never use malloc()
768 outside of ramstage.
770 Since coreboot only runs for a very short time, there is no memory
771 deallocator, although a corresponding free() is offered. It is a no-op.
772 Use of free() is not required though it is accepted. It is useful when
773 sharing code with other codebases that make use of free().
775 The inline disease
776 ------------------
778 There appears to be a common misperception that gcc has a magic "make
779 me faster" speedup option called "inline". While the use of inlines
780 can be appropriate (for example as a means of replacing macros, see
781 Chapter 12), it very often is not. Abundant use of the inline keyword
782 leads to a much bigger kernel, which in turn slows the system as a whole
783 down, due to a bigger icache footprint for the CPU and simply because
784 there is less memory available for the pagecache. Just think about it; a
785 pagecache miss causes a disk seek, which easily takes 5 milliseconds.
786 There are a LOT of cpu cycles that can go into these 5 milliseconds.
788 A reasonable rule of thumb is to not put inline at functions that have
789 more than 3 lines of code in them. An exception to this rule are the
790 cases where a parameter is known to be a compiletime constant, and as a
791 result of this constantness you *know* the compiler will be able to
792 optimize most of your function away at compile time. For a good example
793 of this later case, see the kmalloc() inline function.
795 Often people argue that adding inline to functions that are static and
796 used only once is always a win since there is no space tradeoff. While
797 this is technically correct, gcc is capable of inlining these
798 automatically without help, and the maintenance issue of removing the
799 inline when a second user appears outweighs the potential value of the
800 hint that tells gcc to do something it would have done anyway.
802 Function return values and names
803 --------------------------------
805 Functions can return values of many different kinds, and one of the most
806 common is a value indicating whether the function succeeded or failed.
807 Such a value can be represented as an error-code integer (-Exxx =
808 failure, 0 = success) or a "succeeded" boolean (0 = failure, non-zero
809 = success).
811 Mixing up these two sorts of representations is a fertile source of
812 difficult-to-find bugs. If the C language included a strong distinction
813 between integers and booleans then the compiler would find these
814 mistakes for us... but it doesn't. To help prevent such bugs, always
815 follow this convention:
817 If the name of a function is an action or an imperative command,
818 the function should return an error-code integer.  If the name
819 is a predicate, the function should return a "succeeded" boolean.
821 For example, "add work" is a command, and the add_work() function
822 returns 0 for success or -EBUSY for failure. In the same way, "PCI
823 device present" is a predicate, and the pci_dev_present() function
824 returns 1 if it succeeds in finding a matching device or 0 if it
825 doesn't.
827 All EXPORTed functions must respect this convention, and so should all
828 public functions. Private (static) functions need not, but it is
829 recommended that they do.
831 Functions whose return value is the actual result of a computation,
832 rather than an indication of whether the computation succeeded, are not
833 subject to this rule. Generally they indicate failure by returning some
834 out-of-range result. Typical examples would be functions that return
835 pointers; they use NULL or the ERR_PTR mechanism to report failure.
837 Don't re-invent the kernel macros
838 ----------------------------------
840 The header file include/linux/kernel.h contains a number of macros that
841 you should use, rather than explicitly coding some variant of them
842 yourself. For example, if you need to calculate the length of an array,
843 take advantage of the macro
845 ```c
846 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
849 There are also min() and max() macros that do strict type checking if
850 you need them. Feel free to peruse that header file to see what else is
851 already defined that you shouldn't reproduce in your code.
853 Editor modelines and other cruft
854 --------------------------------
856 Some editors can interpret configuration information embedded in source
857 files, indicated with special markers. For example, emacs interprets
858 lines marked like this:
861 -*- mode: c -*-
864 Or like this:
868 Local Variables:
869 compile-command: "gcc -DMAGIC_DEBUG_FLAG foo.c"
870 End:
874 Vim interprets markers that look like this:
877 /* vim:set sw=8 noet */
880 Do not include any of these in source files. People have their own
881 personal editor configurations, and your source files should not
882 override them. This includes markers for indentation and mode
883 configuration. People may use their own custom mode, or may have some
884 other magic method for making indentation work correctly.
886 Inline assembly
887 ---------------
889 In architecture-specific code, you may need to use inline assembly to
890 interface with CPU or platform functionality. Don't hesitate to do so
891 when necessary. However, don't use inline assembly gratuitously when C
892 can do the job. You can and should poke hardware from C when possible.
894 Consider writing simple helper functions that wrap common bits of inline
895 assembly, rather than repeatedly writing them with slight variations.
896 Remember that inline assembly can use C parameters.
898 Large, non-trivial assembly functions should go in .S files, with
899 corresponding C prototypes defined in C header files. The C prototypes
900 for assembly functions should use "asmlinkage".
902 You may need to mark your asm statement as volatile, to prevent GCC from
903 removing it if GCC doesn't notice any side effects. You don't always
904 need to do so, though, and doing so unnecessarily can limit
905 optimization.
907 When writing a single inline assembly statement containing multiple
908 instructions, put each instruction on a separate line in a separate
909 quoted string, and end each string except the last with nt to
910 properly indent the next instruction in the assembly output:
912 ```c
913 asm ("magic %reg1, #42nt"
914         "more_magic %reg2, %reg3"
915         : /* outputs */ : /* inputs */ : /* clobbers */);
918 References
919 ----------
921 The C Programming Language, Second Edition by Brian W. Kernighan and
922 Dennis M. Ritchie. Prentice Hall, Inc., 1988. ISBN 0-13-110362-8
923 (paperback), 0-13-110370-9 (hardback). URL:
924 <http://cm.bell-labs.com/cm/cs/cbook/>
926 The Practice of Programming by Brian W. Kernighan and Rob Pike.
927 Addison-Wesley, Inc., 1999. ISBN 0-201-61586-X. URL:
928 <http://cm.bell-labs.com/cm/cs/tpop/>
930 GNU manuals - where in compliance with K&R and this text - for cpp, gcc,
931 gcc internals and indent, all available from
932 <http://www.gnu.org/manual/>
934 WG14 is the international standardization working group for the
935 programming language C, URL: <http://www.open-std.org/JTC1/SC22/WG14/>
937 Kernel CodingStyle, by greg@kroah.com at OLS 2002:
938 <http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/>