2 .\" Copyright (c) 1995-2005 The FreeBSD Project
3 .\" All rights reserved.
5 .\" Redistribution and use in source and binary forms, with or without
6 .\" modification, are permitted provided that the following conditions
8 .\" 1. Redistributions of source code must retain the above copyright
9 .\" notice, this list of conditions and the following disclaimer.
10 .\" 2. Redistributions in binary form must reproduce the above copyright
11 .\" notice, this list of conditions and the following disclaimer in the
12 .\" documentation and/or other materials provided with the distribution.
14 .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 .\" ARE DISCLAIMED. IN NO EVENT SHALL [your name] OR CONTRIBUTORS BE LIABLE
18 .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 .\" From: @(#)style 1.14 (Berkeley) 4/28/95
34 .Nd "kernel source file style guide"
36 This file specifies the preferred style for kernel source files in the
39 It is also a guide for the preferred userland code style.
40 Many of the style rules are implicit in the examples.
41 Be careful to check the examples before assuming that
43 is silent on an issue.
46 * Style guide for FreeBSD. Based on the CSRG's KNF (Kernel Normal Form).
48 * @(#)style 1.14 (Berkeley) 4/28/95
53 * VERY important single-line comments look like this.
56 /* Most single-line comments look like this. */
59 * Multi-line comments look like this. Make them real sentences. Fill
60 * them so they look like real paragraphs.
64 The copyright header should be a multi-line comment, with the first
65 line of the comment having a dash after the star like so:
68 * Copyright (c) 1984-2025 John Q. Public
69 * All rights reserved.
71 * Long, boring license goes here, but trimmed for brevity
75 An automatic script collects license information from the tree for
76 all comments that start in the first column with
80 to not reformat a comment that starts in the first column which is not a
81 license or copyright notice, change the dash to a star for those
83 Comments starting in columns other than the first are never
84 considered license statements.
86 After any copyright header, there is a blank line, and the
88 for non C/C++ language source files.
89 Version control system ID tags should only exist once in a file
91 Non-C/C++ source files follow the example above, while C/C++ source files
93 All VCS (version control system) revision identification in files obtained
94 from elsewhere should be maintained, including, where applicable, multiple IDs
95 showing a file's history.
96 In general, do not edit foreign IDs or their infrastructure.
97 Unless otherwise wrapped (such as
98 .Dq Li "#if defined(LIBC_SCCS)" ) ,
100 .Dq Li "#if 0 ... #endif"
101 to hide any uncompilable bits
102 and to keep the IDs out of object files.
105 in front of foreign VCS IDs if the file is renamed.
109 static char sccsid[] = "@(#)style 1.14 (Berkeley) 4/28/95";
110 #endif /* not lint */
113 #include <sys/cdefs.h>
114 __FBSDID("$FreeBSD$");
117 Leave one blank line before the header files.
131 is needed, include it before other include files.
138 The remaining kernel headers should be sorted alphabetically.
140 #include <sys/types.h> /* Non-local includes in angle brackets. */
141 #include <sys/endian.h>
142 #include <sys/lock.h>
143 #include <sys/queue.h>
146 For a network program, put the network include files next.
149 #include <net/if_dl.h>
150 #include <net/route.h>
151 #include <netinet/in.h>
152 #include <protocols/rwhod.h>
155 Do not include files from
159 Leave a blank line before the next group, the
162 which should be sorted alphabetically by name.
167 Global pathnames are defined in
172 in the local directory.
177 Leave another blank line before the local include files.
179 #include "pathnames.h" /* Local includes in double quotes. */
184 or declare names in the implementation namespace except
185 for implementing application interfaces.
189 macros (ones that have side effects), and the names of macros for
190 manifest constants, are all in uppercase.
191 The expansions of expression-like macros are either a single token
192 or have outer parentheses.
193 Put a single tab character between the
196 If a macro is an inline expansion of a function, the function name is
197 all in lowercase and the macro has the same name all in uppercase.
198 .\" XXX the above conflicts with ANSI style where the names are the
199 .\" same and you #undef the macro (if any) to get the function.
200 .\" It is not followed for MALLOC(), and not very common if inline
201 .\" functions are used.
203 backslashes; it makes it easier to read.
204 If the macro encapsulates a compound statement, enclose it in a
207 so that it can safely be used in
210 Any final statement-terminating semicolon should be
211 supplied by the macro invocation rather than the macro, to make parsing easier
212 for pretty-printers and editors.
214 #define MACRO(x, y) do { \e
215 variable = (x) + (y); \e
220 When code is conditionally compiled using
224 a comment may be added following the matching
228 to permit the reader to easily discern where conditionally compiled code
230 This comment should be used only for (subjectively) long regions, regions
231 greater than 20 lines, or where a series of nested
233 may be confusing to the reader.
234 Exceptions may be made for cases where code is conditionally not compiled for
237 even though the uncompiled region may be small.
238 The comment should be separated from the
243 For short conditionally compiled regions, a closing comment should not be
248 should match the expression used in the corresponding
256 should match the inverse of the expression(s) used in the preceding
261 In the comments, the subexpression
265 For the purposes of comments,
266 .Dq Ic #ifndef Li FOO
268 .Dq Ic #if Li !defined(FOO) .
271 #include <sys/ktrace.h>
275 /* A large region here, or other conditional code. */
276 #else /* !COMPAT_43 */
278 #endif /* COMPAT_43 */
281 /* Yet another large region here, or other conditional code. */
282 #else /* COMPAT_43 */
284 #endif /* !COMPAT_43 */
287 The project is slowly moving to use the
289 unsigned integer identifiers of the form
291 in preference to the older
293 integer identifiers of the form
295 New code should use the former, and old code should be converted to
296 the new form if other major work is being done in that area and
297 there is no overriding reason to prefer the older
299 Like white-space commits, care should be taken in making
303 Similarly, the project is slowly moving to use the
306 in preference to the older
312 and old code may be converted if it is
314 Literal values are named
318 These are preferred to the old spellings
322 Userspace code should include
324 while kernel code should include
327 Enumeration values are all uppercase.
329 enum enumtype { ONE, TWO } et;
332 The use of internal_underscores in identifiers is preferred over
333 camelCase or TitleCase.
335 In declarations, do not put any whitespace between asterisks and
336 adjacent tokens, except for tokens that are identifiers related to
338 (These identifiers are the names of basic types, type
340 .Ic typedef Ns -names
341 other than the one being declared.)
342 Separate these identifiers from asterisks using a single space.
344 When declaring variables in structures, declare them sorted by use, then
345 by size (largest to smallest), and then in alphabetical order.
346 The first category normally does not apply, but there are exceptions.
347 Each one gets its own line.
348 Try to make the structure
349 readable by aligning the member names using either one or two tabs
350 depending upon your judgment.
351 You should use one tab only if it suffices to align at least 90% of
353 Names following extremely long types
354 should be separated by a single space.
356 Major structures should be declared at the top of the file in which they
357 are used, or in separate header files if they are used in multiple
359 Use of the structures should be by separate declarations
362 if they are declared in a header file.
365 struct foo *next; /* List of active foo. */
366 struct mumble amumble; /* Comment for mumble. */
367 int bar; /* Try to align the comments. */
368 struct verylongtypename *baz; /* Won't fit in 2 tabs. */
370 struct foo *foohead; /* Head of global foo list. */
375 macros rather than rolling your own lists, whenever possible.
377 the previous example would be better written:
379 #include <sys/queue.h>
382 LIST_ENTRY(foo) link; /* Use queue macros for foo lists. */
383 struct mumble amumble; /* Comment for mumble. */
384 int bar; /* Try to align the comments. */
385 struct verylongtypename *baz; /* Won't fit in 2 tabs. */
387 LIST_HEAD(, foo) foohead; /* Head of global foo list. */
390 Avoid using typedefs for structure types.
391 Typedefs are problematic because they do not properly hide their
392 underlying type; for example you need to know if the typedef is
393 the structure itself or a pointer to the structure.
394 In addition they must be declared exactly once, whereas an
395 incomplete structure type can be mentioned as many times as
397 Typedefs are difficult to use in stand-alone header files:
398 the header that defines the typedef must be included
399 before the header that uses it, or by the header that uses
400 it (which causes namespace pollution), or there must be a
401 back-door mechanism for obtaining the typedef.
403 When convention requires a
405 make its name match the struct tag.
406 Avoid typedefs ending in
408 except as specified in Standard C or by
411 /* Make the structure name match the typedef. */
415 typedef int foo; /* This is foo. */
416 typedef const long baz; /* This is baz. */
419 All functions are prototyped somewhere.
421 Function prototypes for private functions (i.e., functions not used
422 elsewhere) go at the top of the first source module.
424 local to one source module should be declared
427 Functions used from other parts of the kernel are prototyped in the
428 relevant include file.
429 Function prototypes should be listed in a logical order, preferably
430 alphabetical unless there is a compelling reason to use a different
433 Functions that are used locally in more than one module go into a
434 separate header file, e.g.\&
441 In general code can be considered
443 when it makes up about 50% or more of the file(s) involved.
445 to break precedents in the existing code and use the current
449 The kernel has a name associated with parameter types, e.g., in the kernel
452 void function(int fd);
455 In header files visible to userland applications, prototypes that are
456 visible must use either
458 names (ones beginning with an underscore)
459 or no names with the types.
460 It is preferable to use protected names.
468 void function(int _fd);
471 Prototypes may have an extra space after a tab to enable function names
474 static char *function(int _arg, const char *_arg2, struct foo *_arg3,
476 static void usage(void);
479 * All major routines should have a comment briefly describing what
480 * they do. The comment before the "main" routine should describe
481 * what the program does.
484 main(int argc, char *argv[])
493 should be used to parse options.
495 should be sorted in the
505 statement that cascade should have a
508 Numerical arguments should be checked for accuracy.
509 Code which is unreachable for non-obvious reasons may be marked /*
513 while ((ch = getopt(argc, argv, "abNn:")) != -1)
514 switch (ch) { /* Indent the switch. */
515 case 'a': /* Don't indent the case. */
516 aflag = 1; /* Indent case body one tab. */
525 num = strtol(optarg, &ep, 10);
526 if (num <= 0 || *ep != '\e0') {
527 warnx("illegal number, -n argument -- %s",
541 .Pq Ic if , while , for , return , switch .
546 are allowed for single line statements.
547 Either they are used for all single statements, or
548 they are used only where needed for clarity.
549 Usage within a function should be consistent.
550 Forever loops are done with
555 for (p = buf; *p != '\e0'; ++p)
560 z = a + really + long + statement + that + needs +
561 two + lines + gets + indented + four + spaces +
562 on + the + second + and + subsequent + lines;
569 val = realloc(val, newsize);
574 loop may be left empty.
575 Do not put declarations
576 inside blocks unless the routine is unusually complicated.
578 for (; cnt < 15; cnt++) {
584 Indentation is an 8 character tab.
585 Second level indents are four spaces.
586 If you have to wrap a long statement, put the operator at the end of the
589 while (cnt < 20 && this_variable_name_is_too_long &&
591 z = a + really + long + statement + that + needs +
592 two + lines + gets + indented + four + spaces +
593 on + the + second + and + subsequent + lines;
596 Do not add whitespace at the end of a line, and only use tabs
598 to form the indentation.
599 Do not use more spaces than a tab will produce
600 and do not use spaces in front of tabs.
602 Closing and opening braces go on the same line as the
604 Braces that are not necessary may be left out.
615 No spaces after function names.
616 Commas have a space after them.
628 error = function(a1, a2);
633 Unary operators do not require spaces, binary operators do.
634 Do not use parentheses unless they are required for precedence or unless the
635 statement is confusing without them.
636 Remember that other people may
637 confuse easier than you.
638 Do YOU understand the following?
640 a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
644 Exits should be 0 on success, or 1 on failure.
647 * Avoid obvious comments such as
648 * "Exit 0 on success."
653 The function type should be on a line by itself
654 preceding the function.
655 The opening brace of the function body should be
659 function(int a1, int a2, float fl, int a4)
663 When declaring variables in functions declare them sorted by size,
664 then in alphabetical order; multiple ones per line are okay.
665 If a line overflows reuse the type keyword.
667 Be careful to not obfuscate the code by initializing variables in
669 Use this feature only thoughtfully.
670 DO NOT use function calls in initializers.
672 struct foo one, *two;
675 char *six, seven, eight, nine, ten, eleven, twelve;
680 Do not declare functions inside other functions; ANSI C says that
681 such declarations have file scope regardless of the nesting of the
683 Hiding file declarations in what appears to be a local
684 scope is undesirable and will elicit complaints from a good compiler.
688 are not followed by a space.
691 does not understand this rule.
693 are written with parenthesis always.
694 The redundant parenthesis rules do not apply to
699 is the preferred null pointer constant.
703 .Vt ( "type *" ) Ns 0
705 .Vt ( "type *" ) Ns Dv NULL
706 in contexts where the compiler knows the
707 type, e.g., in assignments.
709 .Vt ( "type *" ) Ns Dv NULL
711 in particular for all function args.
712 (Casting is essential for
713 variadic args and is necessary for other args if the function prototype
714 might not be in scope.)
715 Test pointers against
729 for tests unless it is a boolean, e.g.\& use:
741 should not have their return values cast
746 statements should be enclosed in parentheses.
752 do not roll your own.
754 if ((four = malloc(sizeof(struct foo))) == NULL)
755 err(1, (char *)NULL);
756 if ((six = (int *)overflow()) == NULL)
757 errx(1, "number overflowed");
762 Old-style function declarations look like this:
765 function(a1, a2, fl, a4)
766 int a1, a2; /* Declare ints, too, don't default them. */
767 float fl; /* Beware double vs. float prototype differences. */
768 int a4; /* List in order declared. */
772 Use ANSI function declarations unless you explicitly need K&R compatibility.
773 Long parameter lists are wrapped with a normal four space indent.
775 Variable numbers of arguments should look like this:
780 vaf(const char *fmt, ...)
787 /* No return needed for void functions. */
793 /* Insert an empty line if the function has no local variables. */
802 whatever; it is faster and usually cleaner, not
803 to mention avoiding stupid bugs.
805 Usage statements should look like the manual pages
807 The usage statement should be structured in the following order:
810 Options without operands come first,
811 in alphabetical order,
812 inside a single set of brackets
817 Options with operands come next,
818 also in alphabetical order,
819 with each option and its argument inside its own pair of brackets.
824 listed in the order they should be specified on the command line.
827 any optional arguments should be listed,
828 listed in the order they should be specified,
829 and all inside brackets.
837 and multiple options/arguments which are specified together are
838 placed in a single set of brackets.
839 .Bd -literal -offset 4n
840 "usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
841 "usage: f [-a | -b] [-c [-dEe] [-n number]]\en"
844 (void)fprintf(stderr, "usage: f [-ab]\en");
849 Note that the manual page options description should list the options in
850 pure alphabetical order.
851 That is, without regard to whether an option takes arguments or not.
852 The alphabetical ordering should take into account the case ordering
855 New core kernel code should be reasonably compliant with the
858 The guidelines for third-party maintained modules and device drivers are more
859 relaxed but at a minimum should be internally consistent with their style.
861 Stylistic changes (including whitespace changes) are hard on the source
862 repository and are to be avoided without good reason.
863 Code that is approximately
867 compliant in the repository must not diverge from compliance.
869 Whenever possible, code should be run through a code checker
874 and produce minimal warnings.
882 This manual page is largely based on the
883 .Pa src/admin/style/style
886 release, with occasional updates to reflect the current practice and
890 .Pa src/admin/style/style
891 is a codification by the CSRG of the programming style of Ken Thompson and