1.\"- 2.\" Copyright (c) 1995-2005 The FreeBSD Project 3.\" All rights reserved. 4.\" 5.\" Redistribution and use in source and binary forms, with or without 6.\" modification, are permitted provided that the following conditions 7.\" are met: 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. 13.\" 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 24.\" SUCH DAMAGE. 25.\" 26.Dd December 7, 2001 27.Dt STYLE 9 28.Os 29.Sh NAME 30.Nm style 31.Nd "kernel source file style guide" 32.Sh DESCRIPTION 33This file specifies the preferred style for kernel source files in the 34.Fx 35source tree. 36It is also a guide for the preferred userland code style. 37Many of the style rules are implicit in the examples. 38Be careful to check the examples before assuming that 39.Nm 40is silent on an issue. 41.Bd -literal 42/* 43 * Style guide for FreeBSD. Based on the CSRG's KNF (Kernel Normal Form). 44 * 45 * @(#)style 1.14 (Berkeley) 4/28/95 46 * $FreeBSD$ 47 */ 48 49/* 50 * VERY important single-line comments look like this. 51 */ 52 53/* Most single-line comments look like this. */ 54 55/* 56 * Multi-line comments look like this. Make them real sentences. Fill 57 * them so they look like real paragraphs. 58 */ 59.Ed 60.Pp 61The copyright header should be a multi-line comment, with the first 62line of the comment having a dash after the star like so: 63.Bd -literal 64/*- 65 * Copyright (c) 1984-2025 John Q. Public. All Rights Reserved. 66 * 67 * Long, boring license goes here, but redacted for brevity 68 */ 69.Ed 70.Pp 71An automatic script collects license information from the tree for 72all comments that start in the first column with 73.Dq Li "/*-" . 74If you desire to flag 75.Xr indent 1 76to not reformat a comment that starts in the first column which is not a 77license or copyright notice, change the dash to a star for those 78comments. 79Comments starting in columns other than the first comment are never 80considered license statements. 81.Pp 82After any copyright header, there is a blank line, and the 83.Va rcsid 84for source files. 85Version control system ID tags should only exist once in a file 86(unlike in this one). 87Non-C/C++ source files follow the example above, while C/C++ source files 88follow the one below. 89All VCS (version control system) revision identification in files obtained 90from elsewhere should be maintained, including, where applicable, multiple IDs 91showing a file's history. 92In general, do not edit foreign IDs or their infrastructure. 93Unless otherwise wrapped (such as 94.Dq Li "#if defined(LIBC_SCCS)" ) , 95enclose both in 96.Dq Li "#if 0 ... #endif" 97to hide any uncompilable bits 98and to keep the IDs out of object files. 99Only add 100.Dq Li "From: " 101in front of foreign VCS IDs if the file is renamed. 102.Bd -literal 103#if 0 104#ifndef lint 105static char sccsid[] = "@(#)style 1.14 (Berkeley) 4/28/95"; 106#endif /* not lint */ 107#endif 108 109#include <sys/cdefs.h> 110__FBSDID("$FreeBSD$"); 111.Ed 112.Pp 113Leave another blank line before the header files. 114.Pp 115Kernel include files (i.e.\& 116.Pa sys/*.h ) 117come first; normally, include 118.In sys/types.h 119OR 120.In sys/param.h , 121but not both. 122.In sys/types.h 123includes 124.In sys/cdefs.h , 125and it is okay to depend on that. 126.Bd -literal 127#include <sys/types.h> /* Non-local includes in angle brackets. */ 128.Ed 129.Pp 130For a network program, put the network include files next. 131.Bd -literal 132#include <net/if.h> 133#include <net/if_dl.h> 134#include <net/route.h> 135#include <netinet/in.h> 136#include <protocols/rwhod.h> 137.Ed 138.Pp 139Do not use files in 140.Pa /usr/include 141for files in the kernel. 142.Pp 143Leave a blank line before the next group, the 144.Pa /usr/include 145files, 146which should be sorted alphabetically by name. 147.Bd -literal 148#include <stdio.h> 149.Ed 150.Pp 151Global pathnames are defined in 152.In paths.h . 153Pathnames local 154to the program go in 155.Qq Pa pathnames.h 156in the local directory. 157.Bd -literal 158#include <paths.h> 159.Ed 160.Pp 161Leave another blank line before the user include files. 162.Bd -literal 163#include "pathnames.h" /* Local includes in double quotes. */ 164.Ed 165.Pp 166Do not 167.Ic #define 168or declare names in the implementation namespace except 169for implementing application interfaces. 170.Pp 171The names of 172.Dq unsafe 173macros (ones that have side effects), and the names of macros for 174manifest constants, are all in uppercase. 175The expansions of expression-like macros are either a single token 176or have outer parentheses. 177Put a single tab character between the 178.Ic #define 179and the macro name. 180If a macro is an inline expansion of a function, the function name is 181all in lowercase and the macro has the same name all in uppercase. 182.\" XXX the above conflicts with ANSI style where the names are the 183.\" same and you #undef the macro (if any) to get the function. 184.\" It is not followed for MALLOC(), and not very common if inline 185.\" functions are used. 186Right-justify the 187backslashes; it makes it easier to read. 188If the macro encapsulates a compound statement, enclose it in a 189.Ic do 190loop, 191so that it can safely be used in 192.Ic if 193statements. 194Any final statement-terminating semicolon should be 195supplied by the macro invocation rather than the macro, to make parsing easier 196for pretty-printers and editors. 197.Bd -literal 198#define MACRO(x, y) do { \e 199 variable = (x) + (y); \e 200 (y) += 2; \e 201} while (0) 202.Ed 203.Pp 204When code is conditionally compiled using 205.Ic #ifdef 206or 207.Ic #if , 208a comment may be added following the matching 209.Ic #endif 210or 211.Ic #else 212to permit the reader to easily discern where conditionally compiled code 213regions end. 214This comment should be used only for (subjectively) long regions, regions 215greater than 20 lines, or where a series of nested 216.Ic #ifdef 's 217may be confusing to the reader. 218Exceptions may be made for cases where code is conditionally not compiled for 219the purposes of 220.Xr lint 1 , 221even though the uncompiled region may be small. 222The comment should be separated from the 223.Ic #endif 224or 225.Ic #else 226by a single space. 227For short conditionally compiled regions, a closing comment should not be 228used. 229.Pp 230The comment for 231.Ic #endif 232should match the expression used in the corresponding 233.Ic #if 234or 235.Ic #ifdef . 236The comment for 237.Ic #else 238and 239.Ic #elif 240should match the inverse of the expression(s) used in the preceding 241.Ic #if 242and/or 243.Ic #elif 244statements. 245In the comments, the subexpression 246.Dq Li defined(FOO) 247is abbreviated as 248.Dq Li FOO . 249For the purposes of comments, 250.Dq Ic #ifndef Li FOO 251is treated as 252.Dq Ic #if Li !defined(FOO) . 253.Bd -literal 254#ifdef KTRACE 255#include <sys/ktrace.h> 256#endif 257 258#ifdef COMPAT_43 259/* A large region here, or other conditional code. */ 260#else /* !COMPAT_43 */ 261/* Or here. */ 262#endif /* COMPAT_43 */ 263 264#ifndef COMPAT_43 265/* Yet another large region here, or other conditional code. */ 266#else /* COMPAT_43 */ 267/* Or here. */ 268#endif /* !COMPAT_43 */ 269.Ed 270.Pp 271The project is slowly moving to use the 272.St -isoC-99 273unsigned integer identifiers of the form 274.Vt uintXX_t 275in preference to the older 276.Bx Ns -style 277integer identifiers of the form 278.Vt u_intXX_t . 279New code should use the former, and old code should be converted to 280the new form if other major work is being done in that area and 281there is no overriding reason to prefer the older 282.Bx Ns -style . 283Like white-space commits, care should be taken in making 284.Vt uintXX_t 285only commits. 286.Pp 287Enumeration values are all uppercase. 288.Bd -literal 289enum enumtype { ONE, TWO } et; 290.Ed 291.Pp 292In declarations, do not put any whitespace between asterisks and 293adjacent tokens, except for tokens that are identifiers related to 294types. 295(These identifiers are the names of basic types, type 296qualifiers, and 297.Ic typedef Ns -names 298other than the one being declared.) 299Separate these identifiers from asterisks using a single space. 300.Pp 301When declaring variables in structures, declare them sorted by use, then 302by size (largest to smallest), and then in alphabetical order. 303The first category normally does not apply, but there are exceptions. 304Each one gets its own line. 305Try to make the structure 306readable by aligning the member names using either one or two tabs 307depending upon your judgment. 308You should use one tab only if it suffices to align at least 90% of 309the member names. 310Names following extremely long types 311should be separated by a single space. 312.Pp 313Major structures should be declared at the top of the file in which they 314are used, or in separate header files if they are used in multiple 315source files. 316Use of the structures should be by separate declarations 317and should be 318.Ic extern 319if they are declared in a header file. 320.Bd -literal 321struct foo { 322 struct foo *next; /* List of active foo. */ 323 struct mumble amumble; /* Comment for mumble. */ 324 int bar; /* Try to align the comments. */ 325 struct verylongtypename *baz; /* Won't fit in 2 tabs. */ 326}; 327struct foo *foohead; /* Head of global foo list. */ 328.Ed 329.Pp 330Use 331.Xr queue 3 332macros rather than rolling your own lists, whenever possible. 333Thus, 334the previous example would be better written: 335.Bd -literal 336#include <sys/queue.h> 337 338struct foo { 339 LIST_ENTRY(foo) link; /* Use queue macros for foo lists. */ 340 struct mumble amumble; /* Comment for mumble. */ 341 int bar; /* Try to align the comments. */ 342 struct verylongtypename *baz; /* Won't fit in 2 tabs. */ 343}; 344LIST_HEAD(, foo) foohead; /* Head of global foo list. */ 345.Ed 346.Pp 347Avoid using typedefs for structure types. 348Typedefs are problematic because they do not properly hide their 349underlying type; for example you need to know if the typedef is 350the structure itself or a pointer to the structure. 351In addition they must be declared exactly once, whereas an 352incomplete structure type can be mentioned as many times as 353necessary. 354Typedefs are difficult to use in stand-alone header files: 355the header that defines the typedef must be included 356before the header that uses it, or by the header that uses 357it (which causes namespace pollution), or there must be a 358back-door mechanism for obtaining the typedef. 359.Pp 360When convention requires a 361.Ic typedef , 362make its name match the struct tag. 363Avoid typedefs ending in 364.Dq Li _t , 365except as specified in Standard C or by 366.Tn POSIX . 367.Bd -literal 368/* Make the structure name match the typedef. */ 369typedef struct bar { 370 int level; 371} BAR; 372typedef int foo; /* This is foo. */ 373typedef const long baz; /* This is baz. */ 374.Ed 375.Pp 376All functions are prototyped somewhere. 377.Pp 378Function prototypes for private functions (i.e., functions not used 379elsewhere) go at the top of the first source module. 380Functions 381local to one source module should be declared 382.Ic static . 383.Pp 384Functions used from other parts of the kernel are prototyped in the 385relevant include file. 386Function prototypes should be listed in a logical order, preferably 387alphabetical unless there is a compelling reason to use a different 388ordering. 389.Pp 390Functions that are used locally in more than one module go into a 391separate header file, e.g.\& 392.Qq Pa extern.h . 393.Pp 394Do not use the 395.Dv __P 396macro. 397.Pp 398In general code can be considered 399.Dq "new code" 400when it makes up about 50% or more of the file(s) involved. 401This is enough 402to break precedents in the existing code and use the current 403.Nm 404guidelines. 405.Pp 406The kernel has a name associated with parameter types, e.g., in the kernel 407use: 408.Bd -literal 409void function(int fd); 410.Ed 411.Pp 412In header files visible to userland applications, prototypes that are 413visible must use either 414.Dq protected 415names (ones beginning with an underscore) 416or no names with the types. 417It is preferable to use protected names. 418E.g., use: 419.Bd -literal 420void function(int); 421.Ed 422.Pp 423or: 424.Bd -literal 425void function(int _fd); 426.Ed 427.Pp 428Prototypes may have an extra space after a tab to enable function names 429to line up: 430.Bd -literal 431static char *function(int _arg, const char *_arg2, struct foo *_arg3, 432 struct bar *_arg4); 433static void usage(void); 434 435/* 436 * All major routines should have a comment briefly describing what 437 * they do. The comment before the "main" routine should describe 438 * what the program does. 439 */ 440int 441main(int argc, char *argv[]) 442{ 443 char *ep; 444 long num; 445 int ch; 446.Ed 447.Pp 448For consistency, 449.Xr getopt 3 450should be used to parse options. 451Options 452should be sorted in the 453.Xr getopt 3 454call and the 455.Ic switch 456statement, unless 457parts of the 458.Ic switch 459cascade. 460Elements in a 461.Ic switch 462statement that cascade should have a 463.Li FALLTHROUGH 464comment. 465Numerical arguments should be checked for accuracy. 466Code that cannot be reached should have a 467.Li NOTREACHED 468comment. 469.Bd -literal 470 while ((ch = getopt(argc, argv, "abNn:")) != -1) 471 switch (ch) { /* Indent the switch. */ 472 case 'a': /* Don't indent the case. */ 473 aflag = 1; 474 /* FALLTHROUGH */ 475 case 'b': 476 bflag = 1; 477 break; 478 case 'N': 479 Nflag = 1; 480 break; 481 case 'n': 482 num = strtol(optarg, &ep, 10); 483 if (num <= 0 || *ep != '\e0') { 484 warnx("illegal number, -n argument -- %s", 485 optarg); 486 usage(); 487 } 488 break; 489 case '?': 490 default: 491 usage(); 492 /* NOTREACHED */ 493 } 494 argc -= optind; 495 argv += optind; 496.Ed 497.Pp 498Space after keywords 499.Pq Ic if , while , for , return , switch . 500No braces 501.Ql ( \&{ 502and 503.Ql \&} ) 504are 505used for control statements with zero or only a single statement unless that 506statement is more than a single line in which case they are permitted. 507Forever loops are done with 508.Ic for Ns 's , 509not 510.Ic while Ns 's . 511.Bd -literal 512 for (p = buf; *p != '\e0'; ++p) 513 ; /* nothing */ 514 for (;;) 515 stmt; 516 for (;;) { 517 z = a + really + long + statement + that + needs + 518 two + lines + gets + indented + four + spaces + 519 on + the + second + and + subsequent + lines; 520 } 521 for (;;) { 522 if (cond) 523 stmt; 524 } 525 if (val != NULL) 526 val = realloc(val, newsize); 527.Ed 528.Pp 529Parts of a 530.Ic for 531loop may be left empty. 532Do not put declarations 533inside blocks unless the routine is unusually complicated. 534.Bd -literal 535 for (; cnt < 15; cnt++) { 536 stmt1; 537 stmt2; 538 } 539.Ed 540.Pp 541Indentation is an 8 character tab. 542Second level indents are four spaces. 543If you have to wrap a long statement, put the operator at the end of the 544line. 545.Bd -literal 546 while (cnt < 20 && this_variable_name_is_too_long && 547 ep != NULL) 548 z = a + really + long + statement + that + needs + 549 two + lines + gets + indented + four + spaces + 550 on + the + second + and + subsequent + lines; 551.Ed 552.Pp 553Do not add whitespace at the end of a line, and only use tabs 554followed by spaces 555to form the indentation. 556Do not use more spaces than a tab will produce 557and do not use spaces in front of tabs. 558.Pp 559Closing and opening braces go on the same line as the 560.Ic else . 561Braces that are not necessary may be left out. 562.Bd -literal 563 if (test) 564 stmt; 565 else if (bar) { 566 stmt; 567 stmt; 568 } else 569 stmt; 570.Ed 571.Pp 572No spaces after function names. 573Commas have a space after them. 574No spaces 575after 576.Ql \&( 577or 578.Ql \&[ 579or preceding 580.Ql \&] 581or 582.Ql \&) 583characters. 584.Bd -literal 585 error = function(a1, a2); 586 if (error != 0) 587 exit(error); 588.Ed 589.Pp 590Unary operators do not require spaces, binary operators do. 591Do not use parentheses unless they are required for precedence or unless the 592statement is confusing without them. 593Remember that other people may 594confuse easier than you. 595Do YOU understand the following? 596.Bd -literal 597 a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1; 598 k = !(l & FLAGS); 599.Ed 600.Pp 601Exits should be 0 on success, or according to the predefined 602values in 603.Xr sysexits 3 . 604.Bd -literal 605 exit(EX_OK); /* 606 * Avoid obvious comments such as 607 * "Exit 0 on success." 608 */ 609} 610.Ed 611.Pp 612The function type should be on a line by itself 613preceding the function. 614The opening brace of the function body should be 615on a line by itself. 616.Bd -literal 617static char * 618function(int a1, int a2, float fl, int a4) 619{ 620.Ed 621.Pp 622When declaring variables in functions declare them sorted by size, 623then in alphabetical order; multiple ones per line are okay. 624If a line overflows reuse the type keyword. 625.Pp 626Be careful to not obfuscate the code by initializing variables in 627the declarations. 628Use this feature only thoughtfully. 629DO NOT use function calls in initializers. 630.Bd -literal 631 struct foo one, *two; 632 double three; 633 int *four, five; 634 char *six, seven, eight, nine, ten, eleven, twelve; 635 636 four = myfunction(); 637.Ed 638.Pp 639Do not declare functions inside other functions; ANSI C says that 640such declarations have file scope regardless of the nesting of the 641declaration. 642Hiding file declarations in what appears to be a local 643scope is undesirable and will elicit complaints from a good compiler. 644.Pp 645Casts and 646.Ic sizeof Ns 's 647are not followed by a space. 648Note that 649.Xr indent 1 650does not understand this rule. 651.Ic sizeof Ns 's 652are written with parenthesis always. 653The redundant parenthesis rules do not apply to 654.Fn sizeof var 655instances. 656.Pp 657.Dv NULL 658is the preferred null pointer constant. 659Use 660.Dv NULL 661instead of 662.Vt ( "type *" ) Ns 0 663or 664.Vt ( "type *" ) Ns Dv NULL 665in contexts where the compiler knows the 666type, e.g., in assignments. 667Use 668.Vt ( "type *" ) Ns Dv NULL 669in other contexts, 670in particular for all function args. 671(Casting is essential for 672variadic args and is necessary for other args if the function prototype 673might not be in scope.) 674Test pointers against 675.Dv NULL , 676e.g., use: 677.Pp 678.Bd -literal 679(p = f()) == NULL 680.Ed 681.Pp 682not: 683.Bd -literal 684!(p = f()) 685.Ed 686.Pp 687Do not use 688.Ic \&! 689for tests unless it is a boolean, e.g.\& use 690.Bd -literal 691if (*p == '\e0') 692.Ed 693.Pp 694not 695.Bd -literal 696if (!*p) 697.Ed 698.Pp 699Routines returning 700.Vt "void *" 701should not have their return values cast 702to any pointer type. 703.Pp 704Values in 705.Ic return 706statements should be enclosed in parentheses. 707.Pp 708Use 709.Xr err 3 710or 711.Xr warn 3 , 712do not roll your own. 713.Bd -literal 714 if ((four = malloc(sizeof(struct foo))) == NULL) 715 err(1, (char *)NULL); 716 if ((six = (int *)overflow()) == NULL) 717 errx(1, "number overflowed"); 718 return (eight); 719} 720.Ed 721.Pp 722Old-style function declarations look like this: 723.Bd -literal 724static char * 725function(a1, a2, fl, a4) 726 int a1, a2; /* Declare ints, too, don't default them. */ 727 float fl; /* Beware double vs. float prototype differences. */ 728 int a4; /* List in order declared. */ 729{ 730.Ed 731.Pp 732Use ANSI function declarations unless you explicitly need K&R compatibility. 733Long parameter lists are wrapped with a normal four space indent. 734.Pp 735Variable numbers of arguments should look like this. 736.Bd -literal 737#include <stdarg.h> 738 739void 740vaf(const char *fmt, ...) 741{ 742 va_list ap; 743 744 va_start(ap, fmt); 745 STUFF; 746 va_end(ap); 747 /* No return needed for void functions. */ 748} 749 750static void 751usage() 752{ 753 /* Insert an empty line if the function has no local variables. */ 754.Ed 755.Pp 756Use 757.Xr printf 3 , 758not 759.Xr fputs 3 , 760.Xr puts 3 , 761.Xr putchar 3 , 762whatever; it is faster and usually cleaner, not 763to mention avoiding stupid bugs. 764.Pp 765Usage statements should look like the manual pages 766.Sx SYNOPSIS . 767The usage statement should be structured in the following order: 768.Bl -enum 769.It 770Options without operands come first, 771in alphabetical order, 772inside a single set of brackets 773.Ql ( \&[ 774and 775.Ql \&] ) . 776.It 777Options with operands come next, 778also in alphabetical order, 779with each option and its argument inside its own pair of brackets. 780.It 781Required arguments 782(if any) 783are next, 784listed in the order they should be specified on the command line. 785.It 786Finally, 787any optional arguments should be listed, 788listed in the order they should be specified, 789and all inside brackets. 790.El 791.Pp 792A bar 793.Pq Ql \&| 794separates 795.Dq either-or 796options/arguments, 797and multiple options/arguments which are specified together are 798placed in a single set of brackets. 799.Bd -literal -offset 4n 800"usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en" 801"usage: f [-a | -b] [-c [-dEe] [-n number]]\en" 802.Ed 803.Bd -literal 804 (void)fprintf(stderr, "usage: f [-ab]\en"); 805 exit(EX_USAGE); 806} 807.Ed 808.Pp 809Note that the manual page options description should list the options in 810pure alphabetical order. 811That is, without regard to whether an option takes arguments or not. 812The alphabetical ordering should take into account the case ordering 813shown above. 814.Pp 815New core kernel code should be reasonably compliant with the 816.Nm 817guides. 818The guidelines for third-party maintained modules and device drivers are more 819relaxed but at a minimum should be internally consistent with their style. 820.Pp 821Stylistic changes (including whitespace changes) are hard on the source 822repository and are to be avoided without good reason. 823Code that is approximately 824.Fx 825KNF 826.Nm 827compliant in the repository must not diverge from compliance. 828.Pp 829Whenever possible, code should be run through a code checker 830(e.g., 831.Xr lint 1 832or 833.Nm gcc Fl Wall ) 834and produce minimal warnings. 835.Sh SEE ALSO 836.Xr indent 1 , 837.Xr lint 1 , 838.Xr err 3 , 839.Xr sysexits 3 , 840.Xr warn 3 , 841.Xr style.Makefile 5 842.Sh HISTORY 843This man page is largely based on the 844.Pa src/admin/style/style 845file from the 846.Bx 4.4 Lite2 847release, with occasional updates to reflect the current practice and 848desire of the 849.Fx 850project. 851