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