2 .\" Copyright (c) 1995-2019 The FreeBSD Project
4 .\" Redistribution and use in source and binary forms, with or without
5 .\" modification, are permitted provided that the following conditions
7 .\" 1. Redistributions of source code must retain the above copyright
8 .\" notice, this list of conditions and the following disclaimer.
9 .\" 2. Redistributions in binary form must reproduce the above copyright
10 .\" notice, this list of conditions and the following disclaimer in the
11 .\" documentation and/or other materials provided with the distribution.
13 .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 .\" ARE DISCLAIMED. IN NO EVENT SHALL [your name] OR CONTRIBUTORS BE LIABLE
17 .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 .\" From: @(#)style 1.14 (Berkeley) 4/28/95
33 .Nd "kernel source file style guide"
35 This file specifies the preferred style for kernel source files in the
38 It is also a guide for the preferred userland code style.
39 Many of the style rules are implicit in the examples.
40 Be careful to check the examples before assuming that
42 is silent on an issue.
45 * Style guide for FreeBSD. Based on the CSRG's KNF (Kernel Normal Form).
47 * @(#)style 1.14 (Berkeley) 4/28/95
52 * VERY important single-line comments look like this.
55 /* Most single-line comments look like this. */
58 * Multi-line comments look like this. Make them real sentences. Fill
59 * them so they look like real paragraphs.
63 The copyright header should be a multi-line comment, with the first
64 line of the comment having a dash after the star like so:
67 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
69 * Copyright (c) 1984-2025 John Q. Public
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.
85 Use the appropriate SPDX-License-Identifier line before the copyright.
86 If the copyright assertion contains the phrase
87 .Dq Li "All Rights Reserved"
88 that should be on the same line as the word
90 You should not insert a new copyright line between an old
91 copyright line and this phrase.
92 Instead, you should insert a new copyright phrase after
94 .Dq Li "All Rights Reserved"
96 When making changes, it is acceptable to fold an
97 .Dq Li "All Rights Reserved"
101 For files that have the
102 .Dq Li "All Rights Reserved"
103 line on the same line(s) as the word
105 new copyright assertions should be added last.
108 lines should only be added when making substantial changes to the file,
109 not for trivial changes.
111 After any copyright and license comment, there is a blank line, and the
113 for non C/C++ language source files.
114 Version control system ID tags should only exist once in a file
115 (unlike in this one).
116 Non-C/C++ source files follow the example above, while C/C++ source files
117 follow the one below.
118 All VCS (version control system) revision identification in files obtained
119 from elsewhere should be maintained, including, where applicable, multiple IDs
120 showing a file's history.
121 In general, do not edit foreign IDs or their infrastructure.
122 Unless otherwise wrapped (such as
123 .Dq Li "#if defined(LIBC_SCCS)" ) ,
125 .Dq Li "#if 0 ... #endif"
126 to hide any uncompilable bits
127 and to keep the IDs out of object files.
130 in front of foreign VCS IDs if the file is renamed.
132 /* From: @(#)style 1.14 (Berkeley) 4/28/95 */
134 #include <sys/cdefs.h>
135 __FBSDID("$FreeBSD$");
138 Leave one blank line before the header files.
152 is needed, include it before other include files.
162 The remaining kernel headers should be sorted alphabetically.
164 #include <sys/types.h> /* Non-local includes in angle brackets. */
165 #include <sys/systm.h>
166 #include <sys/endian.h>
167 #include <sys/lock.h>
168 #include <sys/queue.h>
171 For a network program, put the network include files next.
174 #include <net/if_dl.h>
175 #include <net/route.h>
176 #include <netinet/in.h>
177 #include <protocols/rwhod.h>
180 Do not include files from
184 Leave a blank line before the next group, the
187 which should be sorted alphabetically by name.
192 Global pathnames are defined in
197 in the local directory.
202 Leave another blank line before the local include files.
204 #include "pathnames.h" /* Local includes in double quotes. */
209 or declare names in the implementation namespace except
210 for implementing application interfaces.
214 macros (ones that have side effects), and the names of macros for
215 manifest constants, are all in uppercase.
216 The expansions of expression-like macros are either a single token
217 or have outer parentheses.
218 Put a single tab character between the
221 If a macro is an inline expansion of a function, the function name is
222 all in lowercase and the macro has the same name all in uppercase.
223 .\" XXX the above conflicts with ANSI style where the names are the
224 .\" same and you #undef the macro (if any) to get the function.
225 .\" It is not followed for MALLOC(), and not very common if inline
226 .\" functions are used.
228 backslashes; it makes it easier to read.
229 If the macro encapsulates a compound statement, enclose it in a
232 so that it can safely be used in
235 Any final statement-terminating semicolon should be
236 supplied by the macro invocation rather than the macro, to make parsing easier
237 for pretty-printers and editors.
239 #define MACRO(x, y) do { \e
240 variable = (x) + (y); \e
245 When code is conditionally compiled using
249 a comment may be added following the matching
253 to permit the reader to easily discern where conditionally compiled code
255 This comment should be used only for (subjectively) long regions, regions
256 greater than 20 lines, or where a series of nested
258 may be confusing to the reader.
259 The comment should be separated from the
264 For short conditionally compiled regions, a closing comment should not be
269 should match the expression used in the corresponding
277 should match the inverse of the expression(s) used in the preceding
282 In the comments, the subexpression
286 For the purposes of comments,
287 .Dq Ic #ifndef Li FOO
289 .Dq Ic #if Li !defined(FOO) .
292 #include <sys/ktrace.h>
296 /* A large region here, or other conditional code. */
297 #else /* !COMPAT_43 */
299 #endif /* COMPAT_43 */
302 /* Yet another large region here, or other conditional code. */
303 #else /* COMPAT_43 */
305 #endif /* !COMPAT_43 */
308 The project prefers the use of
310 unsigned integer identifiers of the form
312 rather than the older
314 integer identifiers of the form
316 New code should use the former, and old code should be converted to
317 the new form if other major work is being done in that area and
318 there is no overriding reason to prefer the older
320 Like white-space commits, care should be taken in making
324 Similarly, the project prefers the use of
327 rather than the older
333 and old code may be converted if it is
335 Literal values are named
339 These are preferred to the old spellings
343 Userspace code should include
345 while kernel code should include
348 Likewise, the project prefers
350 designated initializers when it makes sense to do so.
352 Enumeration values are all uppercase.
354 enum enumtype { ONE, TWO } et;
357 The use of internal_underscores in identifiers is preferred over
358 camelCase or TitleCase.
360 In declarations, do not put any whitespace between asterisks and
361 adjacent tokens, except for tokens that are identifiers related to
363 (These identifiers are the names of basic types, type
365 .Ic typedef Ns -names
366 other than the one being declared.)
367 Separate these identifiers from asterisks using a single space.
369 When declaring variables in structures, declare them sorted by use, then
370 by size (largest to smallest), and then in alphabetical order.
371 The first category normally does not apply, but there are exceptions.
372 Each one gets its own line.
373 Try to make the structure
374 readable by aligning the member names using either one or two tabs
375 depending upon your judgment.
376 You should use one tab only if it suffices to align at least 90% of
378 Names following extremely long types
379 should be separated by a single space.
381 Major structures should be declared at the top of the file in which they
382 are used, or in separate header files if they are used in multiple
384 Use of the structures should be by separate declarations
387 if they are declared in a header file.
390 struct foo *next; /* List of active foo. */
391 struct mumble amumble; /* Comment for mumble. */
392 int bar; /* Try to align the comments. */
393 struct verylongtypename *baz; /* Does not fit in 2 tabs. */
395 struct foo *foohead; /* Head of global foo list. */
400 macros rather than rolling your own lists, whenever possible.
402 the previous example would be better written:
404 #include <sys/queue.h>
407 LIST_ENTRY(foo) link; /* Use queue macros for foo lists. */
408 struct mumble amumble; /* Comment for mumble. */
409 int bar; /* Try to align the comments. */
410 struct verylongtypename *baz; /* Does not fit in 2 tabs. */
412 LIST_HEAD(, foo) foohead; /* Head of global foo list. */
415 Avoid using typedefs for structure types.
416 Typedefs are problematic because they do not properly hide their
417 underlying type; for example you need to know if the typedef is
418 the structure itself or a pointer to the structure.
419 In addition they must be declared exactly once, whereas an
420 incomplete structure type can be mentioned as many times as
422 Typedefs are difficult to use in stand-alone header files:
423 the header that defines the typedef must be included
424 before the header that uses it, or by the header that uses
425 it (which causes namespace pollution), or there must be a
426 back-door mechanism for obtaining the typedef.
428 When convention requires a
430 make its name match the struct tag.
431 Avoid typedefs ending in
433 except as specified in Standard C or by POSIX.
435 /* Make the structure name match the typedef. */
439 typedef int foo; /* This is foo. */
440 typedef const long baz; /* This is baz. */
443 All functions are prototyped somewhere.
445 Function prototypes for private functions (i.e., functions not used
446 elsewhere) go at the top of the first source module.
448 local to one source module should be declared
451 Functions used from other parts of the kernel are prototyped in the
452 relevant include file.
453 Function prototypes should be listed in a logical order, preferably
454 alphabetical unless there is a compelling reason to use a different
457 Functions that are used locally in more than one module go into a
458 separate header file, e.g.,
465 In general code can be considered
467 when it makes up about 50% or more of the file(s) involved.
469 to break precedents in the existing code and use the current
473 The kernel has a name associated with parameter types, e.g., in the kernel
476 void function(int fd);
479 In header files visible to userland applications, prototypes that are
480 visible must use either
482 names (ones beginning with an underscore)
483 or no names with the types.
484 It is preferable to use protected names.
492 void function(int _fd);
495 Prototypes may have an extra space after a tab to enable function names
498 static char *function(int _arg, const char *_arg2, struct foo *_arg3,
500 static void usage(void);
503 * All major routines should have a comment briefly describing what
504 * they do. The comment before the "main" routine should describe
505 * what the program does.
508 main(int argc, char *argv[])
517 should be used to parse options.
519 should be sorted in the
529 statement that cascade should have a
532 Numerical arguments should be checked for accuracy.
533 Code which is unreachable for non-obvious reasons may be marked /*
537 while ((ch = getopt(argc, argv, "abNn:")) != -1)
538 switch (ch) { /* Indent the switch. */
539 case 'a': /* Do not indent the case. */
540 aflag = 1; /* Indent case body one tab. */
549 num = strtol(optarg, &ep, 10);
550 if (num <= 0 || *ep != '\e0') {
551 warnx("illegal number, -n argument -- %s",
565 .Pq Ic if , while , for , return , switch .
570 are allowed for single line statements.
571 Either they are used for all single statements, or
572 they are used only where needed for clarity.
573 Usage within a function should be consistent.
574 Forever loops are done with
579 for (p = buf; *p != '\e0'; ++p)
584 z = a + really + long + statement + that + needs +
585 two + lines + gets + indented + four + spaces +
586 on + the + second + and + subsequent + lines;
593 val = realloc(val, newsize);
598 loop may be left empty.
600 for (; cnt < 15; cnt++) {
608 loop may declare and initialize its counting variable.
610 for (int i = 0; i < 15; i++) {
615 Indentation is an 8 character tab.
616 Second level indents are four spaces.
617 If you have to wrap a long statement, put the operator at the end of the
620 while (cnt < 20 && this_variable_name_is_too_long &&
622 z = a + really + long + statement + that + needs +
623 two + lines + gets + indented + four + spaces +
624 on + the + second + and + subsequent + lines;
627 Do not add whitespace at the end of a line, and only use tabs
629 to form the indentation.
630 Do not use more spaces than a tab will produce
631 and do not use spaces in front of tabs.
633 Closing and opening braces go on the same line as the
635 Braces that are not necessary may be left out.
646 No spaces after function names.
647 Commas have a space after them.
659 error = function(a1, a2);
664 Unary operators do not require spaces, binary operators do.
665 Do not use parentheses unless they are required for precedence or unless the
666 statement is confusing without them.
667 Remember that other people may
668 confuse easier than you.
669 Do YOU understand the following?
671 a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
675 Exits should be 0 on success, or 1 on failure.
678 * Avoid obvious comments such as
679 * "Exit 0 on success."
684 The function type should be on a line by itself
685 preceding the function.
686 The opening brace of the function body should be
690 function(int a1, int a2, float fl, int a4, struct bar *bar)
694 When declaring variables in functions declare them sorted by size,
695 then in alphabetical order; multiple ones per line are okay.
696 If a line overflows reuse the type keyword.
697 Variables may be initialized where declared especially when they
698 are constant for the rest of the scope.
699 Declarations may be placed before executable lines at the start
701 Calls to complicated functions should be avoided when initializing variables.
703 struct foo one, *two;
704 struct baz *three = bar_get_baz(bar);
707 char *seven, eight, nine, ten, eleven, twelve;
709 four = my_complicated_function(a1, f1, a4);
712 Do not declare functions inside other functions; ANSI C says that
713 such declarations have file scope regardless of the nesting of the
715 Hiding file declarations in what appears to be a local
716 scope is undesirable and will elicit complaints from a good compiler.
720 are not followed by a space.
723 does not understand this rule.
725 are written with parenthesis always.
726 The redundant parenthesis rules do not apply to
731 is the preferred null pointer constant.
735 .Vt ( "type *" ) Ns 0
737 .Vt ( "type *" ) Ns Dv NULL
738 in contexts where the compiler knows the
739 type, e.g., in assignments.
741 .Vt ( "type *" ) Ns Dv NULL
743 in particular for all function args.
744 (Casting is essential for
745 variadic args and is necessary for other args if the function prototype
746 might not be in scope.)
747 Test pointers against
761 for tests unless it is a boolean, e.g., use:
773 should not have their return values cast
778 statements should be enclosed in parentheses.
784 do not roll your own.
786 if ((four = malloc(sizeof(struct foo))) == NULL)
787 err(1, (char *)NULL);
788 if ((six = (int *)overflow()) == NULL)
789 errx(1, "number overflowed");
794 When converting K&R style declarations to ANSI style, preserve
795 any comments about parameters.
797 Long parameter lists are wrapped with a normal four space indent.
799 Variable numbers of arguments should look like this:
804 vaf(const char *fmt, ...)
811 /* No return needed for void functions. */
817 /* Optional blank line goes here. */
820 Optionally, insert a blank line at the beginning of functions with no local
822 Older versions of this
824 document required the blank line convention, so it is widely used in existing
827 Do not insert a blank line at the beginning of functions with local variables.
828 Instead, these should have local variable declarations first, followed by one
829 blank line, followed by the first statement.
837 whatever; it is faster and usually cleaner, not
838 to mention avoiding stupid bugs.
840 Usage statements should look like the manual pages
842 The usage statement should be structured in the following order:
845 Options without operands come first,
846 in alphabetical order,
847 inside a single set of brackets
852 Options with operands come next,
853 also in alphabetical order,
854 with each option and its argument inside its own pair of brackets.
859 listed in the order they should be specified on the command line.
862 any optional arguments should be listed,
863 listed in the order they should be specified,
864 and all inside brackets.
872 and multiple options/arguments which are specified together are
873 placed in a single set of brackets.
874 .Bd -literal -offset 4n
875 "usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
876 "usage: f [-a | -b] [-c [-dEe] [-n number]]\en"
879 (void)fprintf(stderr, "usage: f [-ab]\en");
884 Note that the manual page options description should list the options in
885 pure alphabetical order.
886 That is, without regard to whether an option takes arguments or not.
887 The alphabetical ordering should take into account the case ordering
890 New core kernel code should be reasonably compliant with the
893 The guidelines for third-party maintained modules and device drivers are more
894 relaxed but at a minimum should be internally consistent with their style.
896 Stylistic changes (including whitespace changes) are hard on the source
897 repository and are to be avoided without good reason.
898 Code that is approximately
902 compliant in the repository must not diverge from compliance.
904 Whenever possible, code should be run through a code checker
905 (e.g., various static analyzers or
907 and produce minimal warnings.
914 .Bl -tag -width indent
915 .It Pa /usr/src/tools/tools/editing/freebsd.el
916 An Emacs plugin to follow the
920 .It Pa /usr/src/tools/tools/editing/freebsd.vim
921 A Vim plugin to follow the
930 .Xr style.Makefile 5 ,
934 This manual page is largely based on the
935 .Pa src/admin/style/style
938 release, with occasional updates to reflect the current practice and
942 .Pa src/admin/style/style
943 is a codification by the CSRG of the programming style of Ken Thompson and