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