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
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 * Copyright (c) 1984-2025 John Q. Public. All Rights Reserved.
69 * Long, boring license goes here, but redacted for brevity
73 An automatic script collects license information from the tree for
74 all comments that start in the first column with
78 to not reformat a comment that starts in the first column which is not a
79 license or copyright notice, change the dash to a star for those
81 Comments starting in columns other than the first comment are never
82 considered license statements.
84 After any copyright header, there is a blank line, and the
87 Version control system ID tags should only exist once in a file
89 Non-C/C++ source files follow the example above, while C/C++ source files
91 All VCS (version control system) revision identification in files obtained
92 from elsewhere should be maintained, including, where applicable, multiple IDs
93 showing a file's history.
94 In general, do not edit foreign IDs or their infrastructure.
95 Unless otherwise wrapped (such as
96 .Dq Li "#if defined(LIBC_SCCS)" ) ,
98 .Dq Li "#if 0 ... #endif"
99 to hide any uncompilable bits
100 and to keep the IDs out of object files.
103 in front of foreign VCS IDs if the file is renamed.
107 static char sccsid[] = "@(#)style 1.14 (Berkeley) 4/28/95";
108 #endif /* not lint */
111 #include <sys/cdefs.h>
112 __FBSDID("$FreeBSD$");
115 Leave another blank line before the header files.
117 Kernel include files (i.e.\&
119 come first; normally, include
127 and it is okay to depend on that.
129 #include <sys/types.h> /* Non-local includes in angle brackets. */
132 For a network program, put the network include files next.
135 #include <net/if_dl.h>
136 #include <net/route.h>
137 #include <netinet/in.h>
138 #include <protocols/rwhod.h>
143 for files in the kernel.
145 Leave a blank line before the next group, the
148 which should be sorted alphabetically by name.
153 Global pathnames are defined in
158 in the local directory.
163 Leave another blank line before the user include files.
165 #include "pathnames.h" /* Local includes in double quotes. */
170 or declare names in the implementation namespace except
171 for implementing application interfaces.
175 macros (ones that have side effects), and the names of macros for
176 manifest constants, are all in uppercase.
177 The expansions of expression-like macros are either a single token
178 or have outer parentheses.
179 Put a single tab character between the
182 If a macro is an inline expansion of a function, the function name is
183 all in lowercase and the macro has the same name all in uppercase.
184 .\" XXX the above conflicts with ANSI style where the names are the
185 .\" same and you #undef the macro (if any) to get the function.
186 .\" It is not followed for MALLOC(), and not very common if inline
187 .\" functions are used.
189 backslashes; it makes it easier to read.
190 If the macro encapsulates a compound statement, enclose it in a
193 so that it can safely be used in
196 Any final statement-terminating semicolon should be
197 supplied by the macro invocation rather than the macro, to make parsing easier
198 for pretty-printers and editors.
200 #define MACRO(x, y) do { \e
201 variable = (x) + (y); \e
206 When code is conditionally compiled using
210 a comment may be added following the matching
214 to permit the reader to easily discern where conditionally compiled code
216 This comment should be used only for (subjectively) long regions, regions
217 greater than 20 lines, or where a series of nested
219 may be confusing to the reader.
220 Exceptions may be made for cases where code is conditionally not compiled for
223 even though the uncompiled region may be small.
224 The comment should be separated from the
229 For short conditionally compiled regions, a closing comment should not be
234 should match the expression used in the corresponding
242 should match the inverse of the expression(s) used in the preceding
247 In the comments, the subexpression
251 For the purposes of comments,
252 .Dq Ic #ifndef Li FOO
254 .Dq Ic #if Li !defined(FOO) .
257 #include <sys/ktrace.h>
261 /* A large region here, or other conditional code. */
262 #else /* !COMPAT_43 */
264 #endif /* COMPAT_43 */
267 /* Yet another large region here, or other conditional code. */
268 #else /* COMPAT_43 */
270 #endif /* !COMPAT_43 */
273 The project is slowly moving to use the
275 unsigned integer identifiers of the form
277 in preference to the older
279 integer identifiers of the form
281 New code should use the former, and old code should be converted to
282 the new form if other major work is being done in that area and
283 there is no overriding reason to prefer the older
285 Like white-space commits, care should be taken in making
289 Enumeration values are all uppercase.
291 enum enumtype { ONE, TWO } et;
294 In declarations, do not put any whitespace between asterisks and
295 adjacent tokens, except for tokens that are identifiers related to
297 (These identifiers are the names of basic types, type
299 .Ic typedef Ns -names
300 other than the one being declared.)
301 Separate these identifiers from asterisks using a single space.
303 When declaring variables in structures, declare them sorted by use, then
304 by size (largest to smallest), and then in alphabetical order.
305 The first category normally does not apply, but there are exceptions.
306 Each one gets its own line.
307 Try to make the structure
308 readable by aligning the member names using either one or two tabs
309 depending upon your judgment.
310 You should use one tab only if it suffices to align at least 90% of
312 Names following extremely long types
313 should be separated by a single space.
315 Major structures should be declared at the top of the file in which they
316 are used, or in separate header files if they are used in multiple
318 Use of the structures should be by separate declarations
321 if they are declared in a header file.
324 struct foo *next; /* List of active foo. */
325 struct mumble amumble; /* Comment for mumble. */
326 int bar; /* Try to align the comments. */
327 struct verylongtypename *baz; /* Won't fit in 2 tabs. */
329 struct foo *foohead; /* Head of global foo list. */
334 macros rather than rolling your own lists, whenever possible.
336 the previous example would be better written:
338 #include <sys/queue.h>
341 LIST_ENTRY(foo) link; /* Use queue macros for foo lists. */
342 struct mumble amumble; /* Comment for mumble. */
343 int bar; /* Try to align the comments. */
344 struct verylongtypename *baz; /* Won't fit in 2 tabs. */
346 LIST_HEAD(, foo) foohead; /* Head of global foo list. */
349 Avoid using typedefs for structure types.
350 Typedefs are problematic because they do not properly hide their
351 underlying type; for example you need to know if the typedef is
352 the structure itself or a pointer to the structure.
353 In addition they must be declared exactly once, whereas an
354 incomplete structure type can be mentioned as many times as
356 Typedefs are difficult to use in stand-alone header files:
357 the header that defines the typedef must be included
358 before the header that uses it, or by the header that uses
359 it (which causes namespace pollution), or there must be a
360 back-door mechanism for obtaining the typedef.
362 When convention requires a
364 make its name match the struct tag.
365 Avoid typedefs ending in
367 except as specified in Standard C or by
370 /* Make the structure name match the typedef. */
374 typedef int foo; /* This is foo. */
375 typedef const long baz; /* This is baz. */
378 All functions are prototyped somewhere.
380 Function prototypes for private functions (i.e., functions not used
381 elsewhere) go at the top of the first source module.
383 local to one source module should be declared
386 Functions used from other parts of the kernel are prototyped in the
387 relevant include file.
388 Function prototypes should be listed in a logical order, preferably
389 alphabetical unless there is a compelling reason to use a different
392 Functions that are used locally in more than one module go into a
393 separate header file, e.g.\&
400 In general code can be considered
402 when it makes up about 50% or more of the file(s) involved.
404 to break precedents in the existing code and use the current
408 The kernel has a name associated with parameter types, e.g., in the kernel
411 void function(int fd);
414 In header files visible to userland applications, prototypes that are
415 visible must use either
417 names (ones beginning with an underscore)
418 or no names with the types.
419 It is preferable to use protected names.
427 void function(int _fd);
430 Prototypes may have an extra space after a tab to enable function names
433 static char *function(int _arg, const char *_arg2, struct foo *_arg3,
435 static void usage(void);
438 * All major routines should have a comment briefly describing what
439 * they do. The comment before the "main" routine should describe
440 * what the program does.
443 main(int argc, char *argv[])
452 should be used to parse options.
454 should be sorted in the
464 statement that cascade should have a
467 Numerical arguments should be checked for accuracy.
468 Code that cannot be reached should have a
472 while ((ch = getopt(argc, argv, "abNn:")) != -1)
473 switch (ch) { /* Indent the switch. */
474 case 'a': /* Don't indent the case. */
484 num = strtol(optarg, &ep, 10);
485 if (num <= 0 || *ep != '\e0') {
486 warnx("illegal number, -n argument -- %s",
501 .Pq Ic if , while , for , return , switch .
507 used for control statements with zero or only a single statement unless that
508 statement is more than a single line in which case they are permitted.
509 Forever loops are done with
514 for (p = buf; *p != '\e0'; ++p)
519 z = a + really + long + statement + that + needs +
520 two + lines + gets + indented + four + spaces +
521 on + the + second + and + subsequent + lines;
528 val = realloc(val, newsize);
533 loop may be left empty.
534 Do not put declarations
535 inside blocks unless the routine is unusually complicated.
537 for (; cnt < 15; cnt++) {
543 Indentation is an 8 character tab.
544 Second level indents are four spaces.
545 If you have to wrap a long statement, put the operator at the end of the
548 while (cnt < 20 && this_variable_name_is_too_long &&
550 z = a + really + long + statement + that + needs +
551 two + lines + gets + indented + four + spaces +
552 on + the + second + and + subsequent + lines;
555 Do not add whitespace at the end of a line, and only use tabs
557 to form the indentation.
558 Do not use more spaces than a tab will produce
559 and do not use spaces in front of tabs.
561 Closing and opening braces go on the same line as the
563 Braces that are not necessary may be left out.
574 No spaces after function names.
575 Commas have a space after them.
587 error = function(a1, a2);
592 Unary operators do not require spaces, binary operators do.
593 Do not use parentheses unless they are required for precedence or unless the
594 statement is confusing without them.
595 Remember that other people may
596 confuse easier than you.
597 Do YOU understand the following?
599 a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
603 Exits should be 0 on success, or according to the predefined
608 * Avoid obvious comments such as
609 * "Exit 0 on success."
614 The function type should be on a line by itself
615 preceding the function.
616 The opening brace of the function body should be
620 function(int a1, int a2, float fl, int a4)
624 When declaring variables in functions declare them sorted by size,
625 then in alphabetical order; multiple ones per line are okay.
626 If a line overflows reuse the type keyword.
628 Be careful to not obfuscate the code by initializing variables in
630 Use this feature only thoughtfully.
631 DO NOT use function calls in initializers.
633 struct foo one, *two;
636 char *six, seven, eight, nine, ten, eleven, twelve;
641 Do not declare functions inside other functions; ANSI C says that
642 such declarations have file scope regardless of the nesting of the
644 Hiding file declarations in what appears to be a local
645 scope is undesirable and will elicit complaints from a good compiler.
649 are not followed by a space.
652 does not understand this rule.
654 are written with parenthesis always.
655 The redundant parenthesis rules do not apply to
660 is the preferred null pointer constant.
664 .Vt ( "type *" ) Ns 0
666 .Vt ( "type *" ) Ns Dv NULL
667 in contexts where the compiler knows the
668 type, e.g., in assignments.
670 .Vt ( "type *" ) Ns Dv NULL
672 in particular for all function args.
673 (Casting is essential for
674 variadic args and is necessary for other args if the function prototype
675 might not be in scope.)
676 Test pointers against
691 for tests unless it is a boolean, e.g.\& use:
703 should not have their return values cast
708 statements should be enclosed in parentheses.
714 do not roll your own.
716 if ((four = malloc(sizeof(struct foo))) == NULL)
717 err(1, (char *)NULL);
718 if ((six = (int *)overflow()) == NULL)
719 errx(1, "number overflowed");
724 Old-style function declarations look like this:
727 function(a1, a2, fl, a4)
728 int a1, a2; /* Declare ints, too, don't default them. */
729 float fl; /* Beware double vs. float prototype differences. */
730 int a4; /* List in order declared. */
734 Use ANSI function declarations unless you explicitly need K&R compatibility.
735 Long parameter lists are wrapped with a normal four space indent.
737 Variable numbers of arguments should look like this:
742 vaf(const char *fmt, ...)
749 /* No return needed for void functions. */
755 /* Insert an empty line if the function has no local variables. */
764 whatever; it is faster and usually cleaner, not
765 to mention avoiding stupid bugs.
767 Usage statements should look like the manual pages
769 The usage statement should be structured in the following order:
772 Options without operands come first,
773 in alphabetical order,
774 inside a single set of brackets
779 Options with operands come next,
780 also in alphabetical order,
781 with each option and its argument inside its own pair of brackets.
786 listed in the order they should be specified on the command line.
789 any optional arguments should be listed,
790 listed in the order they should be specified,
791 and all inside brackets.
799 and multiple options/arguments which are specified together are
800 placed in a single set of brackets.
801 .Bd -literal -offset 4n
802 "usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
803 "usage: f [-a | -b] [-c [-dEe] [-n number]]\en"
806 (void)fprintf(stderr, "usage: f [-ab]\en");
811 Note that the manual page options description should list the options in
812 pure alphabetical order.
813 That is, without regard to whether an option takes arguments or not.
814 The alphabetical ordering should take into account the case ordering
817 New core kernel code should be reasonably compliant with the
820 The guidelines for third-party maintained modules and device drivers are more
821 relaxed but at a minimum should be internally consistent with their style.
823 Stylistic changes (including whitespace changes) are hard on the source
824 repository and are to be avoided without good reason.
825 Code that is approximately
829 compliant in the repository must not diverge from compliance.
831 Whenever possible, code should be run through a code checker
836 and produce minimal warnings.
845 This man page is largely based on the
846 .Pa src/admin/style/style
849 release, with occasional updates to reflect the current practice and