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 The preferred line width is 80 characters, but some exceptions are
40 made when a slightly longer line is clearer or easier to read.
41 Anything that is frequently grepped for, such as diagnostic, error or panic
42 messages, should not be broken up over multiple lines despite this rule.
43 Many of the style rules are implicit in the examples.
44 Be careful to check the examples before assuming that
46 is silent on an issue.
49 * Style guide for FreeBSD. Based on the CSRG's KNF (Kernel Normal Form).
51 * @(#)style 1.14 (Berkeley) 4/28/95
56 * VERY important single-line comments look like this.
59 /* Most single-line comments look like this. */
62 * Multi-line comments look like this. Make them real sentences. Fill
63 * them so they look like real paragraphs.
67 The copyright header should be a multi-line comment, with the first
68 line of the comment having a dash after the star like so:
71 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
73 * Copyright (c) 1984-2025 John Q. Public
75 * Long, boring license goes here, but trimmed for brevity
79 An automatic script collects license information from the tree for
80 all comments that start in the first column with
84 to not reformat a comment that starts in the first column which is not a
85 license or copyright notice, change the dash to a star for those
87 Comments starting in columns other than the first are never
88 considered license statements.
89 Use the appropriate SPDX-License-Identifier line before the copyright.
90 If the copyright assertion contains the phrase
91 .Dq Li "All Rights Reserved"
92 that should be on the same line as the word
94 You should not insert a new copyright line between an old
95 copyright line and this phrase.
96 Instead, you should insert a new copyright phrase after
98 .Dq Li "All Rights Reserved"
100 When making changes, it is acceptable to fold an
101 .Dq Li "All Rights Reserved"
102 line with each of the
105 For files that have the
106 .Dq Li "All Rights Reserved"
107 line on the same line(s) as the word
109 new copyright assertions should be added last.
112 lines should only be added when making substantial changes to the file,
113 not for trivial changes.
115 After any copyright and license comment, there is a blank line.
116 If your code needs to be merged into stable/12 or earlier, it
120 Otherwise, this tag should be omitted in new code.
121 Legacy code will have the tag removed in the future.
122 For non C/C++ language source files,
124 is next, if applicable.
125 Non-C/C++ source files follow the example above, while C/C++ source files
126 follow the one below.
127 Version control system ID tags should only exist once in a file
128 (unlike in this one).
129 All VCS (version control system) revision identification in files obtained
130 from elsewhere should be maintained, including, where applicable, multiple IDs
131 showing a file's history.
132 In general, do not edit foreign IDs or their infrastructure.
133 Unless otherwise wrapped (such as
134 .Dq Li "#if defined(LIBC_SCCS)" ) ,
136 .Dq Li "#if 0 ... #endif"
137 to hide any uncompilable bits
138 and to keep the IDs out of object files.
141 in front of foreign VCS IDs if the file is renamed.
144 and FreeBSD git hash with full path name if the file was derived
145 from another FreeBSD file and include relevant copyright info
146 from the original file.
148 /* From: @(#)style 1.14 (Berkeley) 4/28/95 */
150 #include <sys/cdefs.h>
151 __FBSDID("$FreeBSD$");
154 Leave one blank line before the header files.
168 is needed, include it before other include files.
178 The remaining kernel headers should be sorted alphabetically.
180 #include <sys/types.h> /* Non-local includes in angle brackets. */
181 #include <sys/systm.h>
182 #include <sys/endian.h>
183 #include <sys/lock.h>
184 #include <sys/queue.h>
187 For a network program, put the network include files next.
190 #include <net/if_dl.h>
191 #include <net/route.h>
192 #include <netinet/in.h>
193 #include <protocols/rwhod.h>
196 Do not include files from
200 Leave a blank line before the next group, the
203 which should be sorted alphabetically by name.
208 Global pathnames are defined in
213 in the local directory.
218 Leave another blank line before the local include files.
220 #include "pathnames.h" /* Local includes in double quotes. */
225 or declare names in the implementation namespace except
226 for implementing application interfaces.
230 macros (ones that have side effects), and the names of macros for
231 manifest constants, are all in uppercase.
232 The expansions of expression-like macros are either a single token
233 or have outer parentheses.
234 Put a single space or tab character between the
236 and the macro name, but be consistent within a file.
237 If a macro is an inline expansion of a function, the function name is
238 all in lowercase and the macro has the same name all in uppercase.
239 .\" XXX the above conflicts with ANSI style where the names are the
240 .\" same and you #undef the macro (if any) to get the function.
241 .\" It is not followed for MALLOC(), and not very common if inline
242 .\" functions are used.
244 backslashes; it makes it easier to read.
245 If the macro encapsulates a compound statement, enclose it in a
248 so that it can safely be used in
251 Any final statement-terminating semicolon should be
252 supplied by the macro invocation rather than the macro, to make parsing easier
253 for pretty-printers and editors.
255 #define MACRO(x, y) do { \e
256 variable = (x) + (y); \e
261 When code is conditionally compiled using
265 a comment may be added following the matching
269 to permit the reader to easily discern where conditionally compiled code
271 This comment should be used only for (subjectively) long regions, regions
272 greater than 20 lines, or where a series of nested
274 may be confusing to the reader.
275 The comment should be separated from the
280 For short conditionally compiled regions, a closing comment should not be
285 should match the expression used in the corresponding
293 should match the inverse of the expression(s) used in the preceding
298 In the comments, the subexpression
302 For the purposes of comments,
303 .Dq Ic #ifndef Li FOO
305 .Dq Ic #if Li !defined(FOO) .
308 #include <sys/ktrace.h>
312 /* A large region here, or other conditional code. */
313 #else /* !COMPAT_43 */
315 #endif /* COMPAT_43 */
318 /* Yet another large region here, or other conditional code. */
319 #else /* COMPAT_43 */
321 #endif /* !COMPAT_43 */
324 The project prefers the use of
326 unsigned integer identifiers of the form
328 rather than the older
330 integer identifiers of the form
332 New code should use the former, and old code should be converted to
333 the new form if other major work is being done in that area and
334 there is no overriding reason to prefer the older
336 Like white-space commits, care should be taken in making
340 Similarly, the project prefers the use of
343 rather than the older
349 and old code may be converted if it is
351 Literal values are named
355 These are preferred to the old spellings
359 Userspace code should include
361 while kernel code should include
364 Likewise, the project prefers
366 designated initializers when it makes sense to do so.
368 Enumeration values are all uppercase.
370 enum enumtype { ONE, TWO } et;
373 The use of internal_underscores in identifiers is preferred over
374 camelCase or TitleCase.
376 In declarations, do not put any whitespace between asterisks and
377 adjacent tokens, except for tokens that are identifiers related to
379 (These identifiers are the names of basic types, type
381 .Ic typedef Ns -names
382 other than the one being declared.)
383 Separate these identifiers from asterisks using a single space.
385 When declaring variables in structures, declare them sorted by use, then
386 by size (largest to smallest), and then in alphabetical order.
387 The first category normally does not apply, but there are exceptions.
388 Each one gets its own line.
389 Try to make the structure
390 readable by aligning the member names using either one or two tabs
391 depending upon your judgment.
392 You should use one tab only if it suffices to align at least 90% of
394 Names following extremely long types
395 should be separated by a single space.
397 Major structures should be declared at the top of the file in which they
398 are used, or in separate header files if they are used in multiple
400 Use of the structures should be by separate declarations
403 if they are declared in a header file.
406 struct foo *next; /* List of active foo. */
407 struct mumble amumble; /* Comment for mumble. */
408 int bar; /* Try to align the comments. */
409 struct verylongtypename *baz; /* Does not fit in 2 tabs. */
411 struct foo *foohead; /* Head of global foo list. */
416 macros rather than rolling your own lists, whenever possible.
418 the previous example would be better written:
420 #include <sys/queue.h>
423 LIST_ENTRY(foo) link; /* Use queue macros for foo lists. */
424 struct mumble amumble; /* Comment for mumble. */
425 int bar; /* Try to align the comments. */
426 struct verylongtypename *baz; /* Does not fit in 2 tabs. */
428 LIST_HEAD(, foo) foohead; /* Head of global foo list. */
431 Avoid using typedefs for structure types.
432 Typedefs are problematic because they do not properly hide their
433 underlying type; for example you need to know if the typedef is
434 the structure itself or a pointer to the structure.
435 In addition they must be declared exactly once, whereas an
436 incomplete structure type can be mentioned as many times as
438 Typedefs are difficult to use in stand-alone header files:
439 the header that defines the typedef must be included
440 before the header that uses it, or by the header that uses
441 it (which causes namespace pollution), or there must be a
442 back-door mechanism for obtaining the typedef.
444 When convention requires a
446 make its name match the struct tag.
447 Avoid typedefs ending in
449 except as specified in Standard C or by POSIX.
451 /* Make the structure name match the typedef. */
455 typedef int foo; /* This is foo. */
456 typedef const long baz; /* This is baz. */
459 All functions are prototyped somewhere.
461 Function prototypes for private functions (i.e., functions not used
462 elsewhere) go at the top of the first source module.
464 local to one source module should be declared
467 Functions used from other parts of the kernel are prototyped in the
468 relevant include file.
469 Function prototypes should be listed in a logical order, preferably
470 alphabetical unless there is a compelling reason to use a different
473 Functions that are used locally in more than one module go into a
474 separate header file, e.g.,
481 In general code can be considered
483 when it makes up about 50% or more of the file(s) involved.
485 to break precedents in the existing code and use the current
489 The kernel has a name associated with parameter types, e.g., in the kernel
492 void function(int fd);
495 In header files visible to userland applications, prototypes that are
496 visible must use either
498 names (ones beginning with an underscore)
499 or no names with the types.
500 It is preferable to use protected names.
508 void function(int _fd);
511 Prototypes may have an extra space after a tab to enable function names
514 static char *function(int _arg, const char *_arg2, struct foo *_arg3,
516 static void usage(void);
519 * All major routines should have a comment briefly describing what
520 * they do. The comment before the "main" routine should describe
521 * what the program does.
524 main(int argc, char *argv[])
533 should be used to parse options.
535 should be sorted in the
545 statement that cascade should have a
548 Numerical arguments should be checked for accuracy.
549 Code which is unreachable for non-obvious reasons may be marked /*
553 while ((ch = getopt(argc, argv, "abNn:")) != -1)
554 switch (ch) { /* Indent the switch. */
555 case 'a': /* Do not indent the case. */
556 aflag = 1; /* Indent case body one tab. */
565 num = strtol(optarg, &ep, 10);
566 if (num <= 0 || *ep != '\e0') {
567 warnx("illegal number, -n argument -- %s",
581 .Pq Ic if , while , for , return , switch .
586 are allowed for single line statements.
587 Either they are used for all single statements, or
588 they are used only where needed for clarity.
589 Usage within a function should be consistent.
590 Forever loops are done with
595 for (p = buf; *p != '\e0'; ++p)
600 z = a + really + long + statement + that + needs +
601 two + lines + gets + indented + four + spaces +
602 on + the + second + and + subsequent + lines;
609 val = realloc(val, newsize);
614 loop may be left empty.
616 for (; cnt < 15; cnt++) {
624 loop may declare and initialize its counting variable.
626 for (int i = 0; i < 15; i++) {
631 Indentation is an 8 character tab.
632 Second level indents are four spaces.
633 If you have to wrap a long statement, put the operator at the end of the
636 while (cnt < 20 && this_variable_name_is_too_long &&
638 z = a + really + long + statement + that + needs +
639 two + lines + gets + indented + four + spaces +
640 on + the + second + and + subsequent + lines;
643 Do not add whitespace at the end of a line, and only use tabs
645 to form the indentation.
646 Do not use more spaces than a tab will produce
647 and do not use spaces in front of tabs.
649 Closing and opening braces go on the same line as the
651 Braces that are not necessary may be left out.
662 No spaces after function names.
663 Commas have a space after them.
675 error = function(a1, a2);
680 Unary operators do not require spaces, binary operators do.
681 Do not use parentheses unless they are required for precedence or unless the
682 statement is confusing without them.
683 Remember that other people may
684 confuse easier than you.
685 Do YOU understand the following?
687 a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
691 Exits should be 0 on success, or 1 on failure.
694 * Avoid obvious comments such as
695 * "Exit 0 on success."
700 The function type should be on a line by itself
701 preceding the function.
702 The opening brace of the function body should be
706 function(int a1, int a2, float fl, int a4, struct bar *bar)
710 When declaring variables in functions declare them sorted by size,
711 then in alphabetical order; multiple ones per line are okay.
712 If a line overflows reuse the type keyword.
713 Variables may be initialized where declared especially when they
714 are constant for the rest of the scope.
715 Declarations may be placed before executable lines at the start
717 Calls to complicated functions should be avoided when initializing variables.
719 struct foo one, *two;
720 struct baz *three = bar_get_baz(bar);
723 char *seven, eight, nine, ten, eleven, twelve;
725 four = my_complicated_function(a1, f1, a4);
728 Do not declare functions inside other functions; ANSI C says that
729 such declarations have file scope regardless of the nesting of the
731 Hiding file declarations in what appears to be a local
732 scope is undesirable and will elicit complaints from a good compiler.
736 are not followed by a space.
739 does not understand this rule.
741 are written with parenthesis always.
742 The redundant parenthesis rules do not apply to
747 is the preferred null pointer constant.
751 .Vt ( "type *" ) Ns 0
753 .Vt ( "type *" ) Ns Dv NULL
754 in contexts where the compiler knows the
755 type, e.g., in assignments.
757 .Vt ( "type *" ) Ns Dv NULL
759 in particular for all function args.
760 (Casting is essential for
761 variadic args and is necessary for other args if the function prototype
762 might not be in scope.)
763 Test pointers against
777 for tests unless it is a boolean, e.g., use:
789 should not have their return values cast
794 statements should be enclosed in parentheses.
800 do not roll your own.
802 if ((four = malloc(sizeof(struct foo))) == NULL)
803 err(1, (char *)NULL);
804 if ((six = (int *)overflow()) == NULL)
805 errx(1, "number overflowed");
810 When converting K&R style declarations to ANSI style, preserve
811 any comments about parameters.
813 Long parameter lists are wrapped with a normal four space indent.
815 Variable numbers of arguments should look like this:
820 vaf(const char *fmt, ...)
827 /* No return needed for void functions. */
833 /* Optional blank line goes here. */
836 Optionally, insert a blank line at the beginning of functions with no local
838 Older versions of this
840 document required the blank line convention, so it is widely used in existing
843 Do not insert a blank line at the beginning of functions with local variables.
844 Instead, these should have local variable declarations first, followed by one
845 blank line, followed by the first statement.
853 whatever; it is faster and usually cleaner, not
854 to mention avoiding stupid bugs.
856 Usage statements should look like the manual pages
858 The usage statement should be structured in the following order:
861 Options without operands come first,
862 in alphabetical order,
863 inside a single set of brackets
868 Options with operands come next,
869 also in alphabetical order,
870 with each option and its argument inside its own pair of brackets.
875 listed in the order they should be specified on the command line.
878 any optional arguments should be listed,
879 listed in the order they should be specified,
880 and all inside brackets.
888 and multiple options/arguments which are specified together are
889 placed in a single set of brackets.
890 .Bd -literal -offset 4n
891 "usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
892 "usage: f [-a | -b] [-c [-dEe] [-n number]]\en"
895 (void)fprintf(stderr, "usage: f [-ab]\en");
900 Note that the manual page options description should list the options in
901 pure alphabetical order.
902 That is, without regard to whether an option takes arguments or not.
903 The alphabetical ordering should take into account the case ordering
906 New core kernel code should be reasonably compliant with the
909 The guidelines for third-party maintained modules and device drivers are more
910 relaxed but at a minimum should be internally consistent with their style.
912 Stylistic changes (including whitespace changes) are hard on the source
913 repository and are to be avoided without good reason.
914 Code that is approximately
918 compliant in the repository must not diverge from compliance.
920 Whenever possible, code should be run through a code checker
921 (e.g., various static analyzers or
923 and produce minimal warnings.
930 .Bl -tag -width indent
931 .It Pa /usr/src/tools/tools/editing/freebsd.el
932 An Emacs plugin to follow the
936 .It Pa /usr/src/tools/tools/editing/freebsd.vim
937 A Vim plugin to follow the
946 .Xr style.Makefile 5 ,
950 This manual page is largely based on the
951 .Pa src/admin/style/style
954 release, with occasional updates to reflect the current practice and
958 .Pa src/admin/style/style
959 is a codification by the CSRG of the programming style of Ken Thompson and