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 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
70 * Copyright (c) 1984-2025 John Q. Public
71 * All rights reserved.
73 * Long, boring license goes here, but trimmed for brevity
77 An automatic script collects license information from the tree for
78 all comments that start in the first column with
82 to not reformat a comment that starts in the first column which is not a
83 license or copyright notice, change the dash to a star for those
85 Comments starting in columns other than the first are never
86 considered license statements.
87 Use the appropriate SPDX-License-Identifier line before the copyright.
89 After any copyright header, there is a blank line, and the
91 for non C/C++ language source files.
92 Version control system ID tags should only exist once in a file
94 Non-C/C++ source files follow the example above, while C/C++ source files
96 All VCS (version control system) revision identification in files obtained
97 from elsewhere should be maintained, including, where applicable, multiple IDs
98 showing a file's history.
99 In general, do not edit foreign IDs or their infrastructure.
100 Unless otherwise wrapped (such as
101 .Dq Li "#if defined(LIBC_SCCS)" ) ,
103 .Dq Li "#if 0 ... #endif"
104 to hide any uncompilable bits
105 and to keep the IDs out of object files.
108 in front of foreign VCS IDs if the file is renamed.
110 /* From: @(#)style 1.14 (Berkeley) 4/28/95 */
112 #include <sys/cdefs.h>
113 __FBSDID("$FreeBSD$");
116 Leave one blank line before the header files.
130 is needed, include it before other include files.
137 The remaining kernel headers should be sorted alphabetically.
139 #include <sys/types.h> /* Non-local includes in angle brackets. */
140 #include <sys/endian.h>
141 #include <sys/lock.h>
142 #include <sys/queue.h>
145 For a network program, put the network include files next.
148 #include <net/if_dl.h>
149 #include <net/route.h>
150 #include <netinet/in.h>
151 #include <protocols/rwhod.h>
154 Do not include files from
158 Leave a blank line before the next group, the
161 which should be sorted alphabetically by name.
166 Global pathnames are defined in
171 in the local directory.
176 Leave another blank line before the local include files.
178 #include "pathnames.h" /* Local includes in double quotes. */
183 or declare names in the implementation namespace except
184 for implementing application interfaces.
188 macros (ones that have side effects), and the names of macros for
189 manifest constants, are all in uppercase.
190 The expansions of expression-like macros are either a single token
191 or have outer parentheses.
192 Put a single tab character between the
195 If a macro is an inline expansion of a function, the function name is
196 all in lowercase and the macro has the same name all in uppercase.
197 .\" XXX the above conflicts with ANSI style where the names are the
198 .\" same and you #undef the macro (if any) to get the function.
199 .\" It is not followed for MALLOC(), and not very common if inline
200 .\" functions are used.
202 backslashes; it makes it easier to read.
203 If the macro encapsulates a compound statement, enclose it in a
206 so that it can safely be used in
209 Any final statement-terminating semicolon should be
210 supplied by the macro invocation rather than the macro, to make parsing easier
211 for pretty-printers and editors.
213 #define MACRO(x, y) do { \e
214 variable = (x) + (y); \e
219 When code is conditionally compiled using
223 a comment may be added following the matching
227 to permit the reader to easily discern where conditionally compiled code
229 This comment should be used only for (subjectively) long regions, regions
230 greater than 20 lines, or where a series of nested
232 may be confusing to the reader.
233 The comment should be separated from the
238 For short conditionally compiled regions, a closing comment should not be
243 should match the expression used in the corresponding
251 should match the inverse of the expression(s) used in the preceding
256 In the comments, the subexpression
260 For the purposes of comments,
261 .Dq Ic #ifndef Li FOO
263 .Dq Ic #if Li !defined(FOO) .
266 #include <sys/ktrace.h>
270 /* A large region here, or other conditional code. */
271 #else /* !COMPAT_43 */
273 #endif /* COMPAT_43 */
276 /* Yet another large region here, or other conditional code. */
277 #else /* COMPAT_43 */
279 #endif /* !COMPAT_43 */
282 The project is slowly moving to use the
284 unsigned integer identifiers of the form
286 in preference to the older
288 integer identifiers of the form
290 New code should use the former, and old code should be converted to
291 the new form if other major work is being done in that area and
292 there is no overriding reason to prefer the older
294 Like white-space commits, care should be taken in making
298 Similarly, the project is slowly moving to use the
301 in preference to the older
307 and old code may be converted if it is
309 Literal values are named
313 These are preferred to the old spellings
317 Userspace code should include
319 while kernel code should include
322 Likewise, the project is moving to using the
324 designated initializers when it makes sense to do so.
326 Enumeration values are all uppercase.
328 enum enumtype { ONE, TWO } et;
331 The use of internal_underscores in identifiers is preferred over
332 camelCase or TitleCase.
334 In declarations, do not put any whitespace between asterisks and
335 adjacent tokens, except for tokens that are identifiers related to
337 (These identifiers are the names of basic types, type
339 .Ic typedef Ns -names
340 other than the one being declared.)
341 Separate these identifiers from asterisks using a single space.
343 When declaring variables in structures, declare them sorted by use, then
344 by size (largest to smallest), and then in alphabetical order.
345 The first category normally does not apply, but there are exceptions.
346 Each one gets its own line.
347 Try to make the structure
348 readable by aligning the member names using either one or two tabs
349 depending upon your judgment.
350 You should use one tab only if it suffices to align at least 90% of
352 Names following extremely long types
353 should be separated by a single space.
355 Major structures should be declared at the top of the file in which they
356 are used, or in separate header files if they are used in multiple
358 Use of the structures should be by separate declarations
361 if they are declared in a header file.
364 struct foo *next; /* List of active foo. */
365 struct mumble amumble; /* Comment for mumble. */
366 int bar; /* Try to align the comments. */
367 struct verylongtypename *baz; /* Does not fit in 2 tabs. */
369 struct foo *foohead; /* Head of global foo list. */
374 macros rather than rolling your own lists, whenever possible.
376 the previous example would be better written:
378 #include <sys/queue.h>
381 LIST_ENTRY(foo) link; /* Use queue macros for foo lists. */
382 struct mumble amumble; /* Comment for mumble. */
383 int bar; /* Try to align the comments. */
384 struct verylongtypename *baz; /* Does not fit in 2 tabs. */
386 LIST_HEAD(, foo) foohead; /* Head of global foo list. */
389 Avoid using typedefs for structure types.
390 Typedefs are problematic because they do not properly hide their
391 underlying type; for example you need to know if the typedef is
392 the structure itself or a pointer to the structure.
393 In addition they must be declared exactly once, whereas an
394 incomplete structure type can be mentioned as many times as
396 Typedefs are difficult to use in stand-alone header files:
397 the header that defines the typedef must be included
398 before the header that uses it, or by the header that uses
399 it (which causes namespace pollution), or there must be a
400 back-door mechanism for obtaining the typedef.
402 When convention requires a
404 make its name match the struct tag.
405 Avoid typedefs ending in
407 except as specified in Standard C or by
410 /* Make the structure name match the typedef. */
414 typedef int foo; /* This is foo. */
415 typedef const long baz; /* This is baz. */
418 All functions are prototyped somewhere.
420 Function prototypes for private functions (i.e., functions not used
421 elsewhere) go at the top of the first source module.
423 local to one source module should be declared
426 Functions used from other parts of the kernel are prototyped in the
427 relevant include file.
428 Function prototypes should be listed in a logical order, preferably
429 alphabetical unless there is a compelling reason to use a different
432 Functions that are used locally in more than one module go into a
433 separate header file, e.g.,
440 In general code can be considered
442 when it makes up about 50% or more of the file(s) involved.
444 to break precedents in the existing code and use the current
448 The kernel has a name associated with parameter types, e.g., in the kernel
451 void function(int fd);
454 In header files visible to userland applications, prototypes that are
455 visible must use either
457 names (ones beginning with an underscore)
458 or no names with the types.
459 It is preferable to use protected names.
467 void function(int _fd);
470 Prototypes may have an extra space after a tab to enable function names
473 static char *function(int _arg, const char *_arg2, struct foo *_arg3,
475 static void usage(void);
478 * All major routines should have a comment briefly describing what
479 * they do. The comment before the "main" routine should describe
480 * what the program does.
483 main(int argc, char *argv[])
492 should be used to parse options.
494 should be sorted in the
504 statement that cascade should have a
507 Numerical arguments should be checked for accuracy.
508 Code which is unreachable for non-obvious reasons may be marked /*
512 while ((ch = getopt(argc, argv, "abNn:")) != -1)
513 switch (ch) { /* Indent the switch. */
514 case 'a': /* Do not indent the case. */
515 aflag = 1; /* Indent case body one tab. */
524 num = strtol(optarg, &ep, 10);
525 if (num <= 0 || *ep != '\e0') {
526 warnx("illegal number, -n argument -- %s",
540 .Pq Ic if , while , for , return , switch .
545 are allowed for single line statements.
546 Either they are used for all single statements, or
547 they are used only where needed for clarity.
548 Usage within a function should be consistent.
549 Forever loops are done with
554 for (p = buf; *p != '\e0'; ++p)
559 z = a + really + long + statement + that + needs +
560 two + lines + gets + indented + four + spaces +
561 on + the + second + and + subsequent + lines;
568 val = realloc(val, newsize);
573 loop may be left empty.
574 Do not put declarations
575 inside blocks unless the routine is unusually complicated.
577 for (; cnt < 15; cnt++) {
583 Indentation is an 8 character tab.
584 Second level indents are four spaces.
585 If you have to wrap a long statement, put the operator at the end of the
588 while (cnt < 20 && this_variable_name_is_too_long &&
590 z = a + really + long + statement + that + needs +
591 two + lines + gets + indented + four + spaces +
592 on + the + second + and + subsequent + lines;
595 Do not add whitespace at the end of a line, and only use tabs
597 to form the indentation.
598 Do not use more spaces than a tab will produce
599 and do not use spaces in front of tabs.
601 Closing and opening braces go on the same line as the
603 Braces that are not necessary may be left out.
614 No spaces after function names.
615 Commas have a space after them.
627 error = function(a1, a2);
632 Unary operators do not require spaces, binary operators do.
633 Do not use parentheses unless they are required for precedence or unless the
634 statement is confusing without them.
635 Remember that other people may
636 confuse easier than you.
637 Do YOU understand the following?
639 a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
643 Exits should be 0 on success, or 1 on failure.
646 * Avoid obvious comments such as
647 * "Exit 0 on success."
652 The function type should be on a line by itself
653 preceding the function.
654 The opening brace of the function body should be
658 function(int a1, int a2, float fl, int a4)
662 When declaring variables in functions declare them sorted by size,
663 then in alphabetical order; multiple ones per line are okay.
664 If a line overflows reuse the type keyword.
666 Be careful to not obfuscate the code by initializing variables in
668 Use this feature only thoughtfully.
669 DO NOT use function calls in initializers.
671 struct foo one, *two;
674 char *six, seven, eight, nine, ten, eleven, twelve;
679 Do not declare functions inside other functions; ANSI C says that
680 such declarations have file scope regardless of the nesting of the
682 Hiding file declarations in what appears to be a local
683 scope is undesirable and will elicit complaints from a good compiler.
687 are not followed by a space.
690 does not understand this rule.
692 are written with parenthesis always.
693 The redundant parenthesis rules do not apply to
698 is the preferred null pointer constant.
702 .Vt ( "type *" ) Ns 0
704 .Vt ( "type *" ) Ns Dv NULL
705 in contexts where the compiler knows the
706 type, e.g., in assignments.
708 .Vt ( "type *" ) Ns Dv NULL
710 in particular for all function args.
711 (Casting is essential for
712 variadic args and is necessary for other args if the function prototype
713 might not be in scope.)
714 Test pointers against
728 for tests unless it is a boolean, e.g., use:
740 should not have their return values cast
745 statements should be enclosed in parentheses.
751 do not roll your own.
753 if ((four = malloc(sizeof(struct foo))) == NULL)
754 err(1, (char *)NULL);
755 if ((six = (int *)overflow()) == NULL)
756 errx(1, "number overflowed");
761 When converting K&R style declarations to ANSI style, preserve
762 any comments about parameters.
764 Long parameter lists are wrapped with a normal four space indent.
766 Variable numbers of arguments should look like this:
771 vaf(const char *fmt, ...)
778 /* No return needed for void functions. */
784 /* Insert an empty line if the function has no local variables. */
793 whatever; it is faster and usually cleaner, not
794 to mention avoiding stupid bugs.
796 Usage statements should look like the manual pages
798 The usage statement should be structured in the following order:
801 Options without operands come first,
802 in alphabetical order,
803 inside a single set of brackets
808 Options with operands come next,
809 also in alphabetical order,
810 with each option and its argument inside its own pair of brackets.
815 listed in the order they should be specified on the command line.
818 any optional arguments should be listed,
819 listed in the order they should be specified,
820 and all inside brackets.
828 and multiple options/arguments which are specified together are
829 placed in a single set of brackets.
830 .Bd -literal -offset 4n
831 "usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
832 "usage: f [-a | -b] [-c [-dEe] [-n number]]\en"
835 (void)fprintf(stderr, "usage: f [-ab]\en");
840 Note that the manual page options description should list the options in
841 pure alphabetical order.
842 That is, without regard to whether an option takes arguments or not.
843 The alphabetical ordering should take into account the case ordering
846 New core kernel code should be reasonably compliant with the
849 The guidelines for third-party maintained modules and device drivers are more
850 relaxed but at a minimum should be internally consistent with their style.
852 Stylistic changes (including whitespace changes) are hard on the source
853 repository and are to be avoided without good reason.
854 Code that is approximately
858 compliant in the repository must not diverge from compliance.
860 Whenever possible, code should be run through a code checker
861 (e.g., various static analyzers or
863 and produce minimal warnings.
870 This manual page is largely based on the
871 .Pa src/admin/style/style
874 release, with occasional updates to reflect the current practice and
878 .Pa src/admin/style/style
879 is a codification by the CSRG of the programming style of Ken Thompson and