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