stp: Make stp-disabled port forward stp bpdu packets.
[cascardo/ovs.git] / CodingStyle
1                       Open vSwitch Coding Style
2                       =========================
3
4 This file describes the coding style used in most C files in the Open
5 vSwitch distribution.  However, Linux kernel code datapath directory
6 follows the Linux kernel's established coding conventions.
7
8 The following GNU indent options approximate this style:
9
10     -npro -bad -bap -bbb -br -blf -brs -cdw -ce -fca -cli0 -npcs -i4 -l79 \
11     -lc79 -nbfda -nut -saf -sai -saw -sbi4 -sc -sob -st -ncdb -pi4 -cs -bs \
12     -di1 -lp -il0 -hnl
13
14
15 BASICS
16
17   Limit lines to 79 characters.
18
19   Use form feeds (control+L) to divide long source files into logical
20 pieces.  A form feed should appear as the only character on a line.
21
22   Do not use tabs for indentation.
23
24   Avoid trailing spaces on lines.
25
26
27 NAMING
28
29   Use names that explain the purpose of a function or object.
30
31   Use underscores to separate words in an identifier: multi_word_name. 
32
33   Use lowercase for most names.  Use uppercase for macros, macro
34 parameters, and members of enumerations.
35
36   Give arrays names that are plural.
37
38   Pick a unique name prefix (ending with an underscore) for each
39 module, and apply that prefix to all of that module's externally
40 visible names.  Names of macro parameters, struct and union members,
41 and parameters in function prototypes are not considered externally
42 visible for this purpose.
43
44   Do not use names that begin with _.  If you need a name for
45 "internal use only", use __ as a suffix instead of a prefix.
46
47   Avoid negative names: "found" is a better name than "not_found".
48
49   In names, a "size" is a count of bytes, a "length" is a count of
50 characters.  A buffer has size, but a string has length.  The length
51 of a string does not include the null terminator, but the size of the
52 buffer that contains the string does.
53
54
55 COMMENTS
56
57   Comments should be written as full sentences that start with a
58 capital letter and end with a period.  Put two spaces between
59 sentences.
60
61   Write block comments as shown below.  You may put the /* and */ on
62 the same line as comment text if you prefer.
63
64     /*
65      * We redirect stderr to /dev/null because we often want to remove all
66      * traffic control configuration on a port so its in a known state.  If
67      * this done when there is no such configuration, tc complains, so we just
68      * always ignore it.
69      */
70
71   Each function and each variable declared outside a function, and
72 each struct, union, and typedef declaration should be preceded by a
73 comment.  See FUNCTION DEFINITIONS below for function comment
74 guidelines.
75
76   Each struct and union member should each have an inline comment that
77 explains its meaning.  structs and unions with many members should be
78 additionally divided into logical groups of members by block comments,
79 e.g.:
80
81     /* An event that will wake the following call to poll_block(). */
82     struct poll_waiter {
83         /* Set when the waiter is created. */
84         struct list node;           /* Element in global waiters list. */
85         int fd;                     /* File descriptor. */
86         short int events;           /* Events to wait for (POLLIN, POLLOUT). */
87         poll_fd_func *function;     /* Callback function, if any, or null. */
88         void *aux;                  /* Argument to callback function. */
89         struct backtrace *backtrace; /* Event that created waiter, or null. */
90
91         /* Set only when poll_block() is called. */
92         struct pollfd *pollfd;      /* Pointer to element of the pollfds array
93                                        (null if added from a callback). */
94     };
95
96   Use XXX or FIXME comments to mark code that needs work.
97
98   Don't use // comments.
99
100   Don't comment out or #if 0 out code.  Just remove it.  The code that
101 was there will still be in version control history.
102
103
104 FUNCTIONS
105
106   Put the return type, function name, and the braces that surround the
107 function's code on separate lines, all starting in column 0.
108
109   Before each function definition, write a comment that describes the
110 function's purpose, including each parameter, the return value, and
111 side effects.  References to argument names should be given in
112 single-quotes, e.g. 'arg'.  The comment should not include the
113 function name, nor need it follow any formal structure.  The comment
114 does not need to describe how a function does its work, unless this
115 information is needed to use the function correctly (this is often
116 better done with comments *inside* the function).
117
118   Simple static functions do not need a comment.
119
120   Within a file, non-static functions should come first, in the order
121 that they are declared in the header file, followed by static
122 functions.  Static functions should be in one or more separate pages
123 (separated by form feed characters) in logical groups.  A commonly
124 useful way to divide groups is by "level", with high-level functions
125 first, followed by groups of progressively lower-level functions.
126 This makes it easy for the program's reader to see the top-down
127 structure by reading from top to bottom.
128
129   All function declarations and definitions should include a
130 prototype.  Empty parentheses, e.g. "int foo();", do not include a
131 prototype (they state that the function's parameters are unknown);
132 write "void" in parentheses instead, e.g. "int foo(void);".
133
134   Prototypes for static functions should either all go at the top of
135 the file, separated into groups by blank lines, or they should appear
136 at the top of each page of functions.  Don't comment individual
137 prototypes, but a comment on each group of prototypes is often
138 appropriate.
139
140   In the absence of good reasons for another order, the following
141 parameter order is preferred.  One notable exception is that data
142 parameters and their corresponding size parameters should be paired.
143
144     1. The primary object being manipulated, if any (equivalent to the
145        "this" pointer in C++).
146     2. Input-only parameters.
147     3. Input/output parameters.
148     4. Output-only parameters.
149     5. Status parameter. 
150
151   Example:
152
153     /* Stores the features supported by 'netdev' into each of '*current',
154      * '*advertised', '*supported', and '*peer' that are non-null.  Each value
155      * is a bitmap of "enum ofp_port_features" bits, in host byte order.
156      * Returns 0 if successful, otherwise a positive errno value.  On failure,
157      * all of the passed-in values are set to 0. */
158     int
159     netdev_get_features(struct netdev *netdev,
160                         uint32_t *current, uint32_t *advertised,
161                         uint32_t *supported, uint32_t *peer)
162     {
163         ...
164     }
165
166 Functions that destroy an instance of a dynamically-allocated type
167 should accept and ignore a null pointer argument.  Code that calls
168 such a function (including the C standard library function free())
169 should omit a null-pointer check.  We find that this usually makes
170 code easier to read.
171
172 Functions in .c files should not normally be marked "inline", because
173 it does not usually help code generation and it does suppress
174 compilers warnings about unused functions.  (Functions defined in .h
175 usually should be marked inline.)
176
177
178 FUNCTION PROTOTYPES
179
180   Put the return type and function name on the same line in a function
181 prototype:
182
183     static const struct option_class *get_option_class(int code);
184
185
186   Omit parameter names from function prototypes when the names do not
187 give useful information, e.g.:
188
189     int netdev_get_mtu(const struct netdev *, int *mtup);
190
191
192 STATEMENTS
193
194   Indent each level of code with 4 spaces.  Use BSD-style brace
195 placement:
196
197     if (a()) {
198         b();
199         d();
200     }
201
202   Put a space between "if", "while", "for", etc. and the expressions
203 that follow them.
204
205   Enclose single statements in braces:
206
207     if (a > b) {
208         return a;
209     } else {
210         return b;
211     }
212
213   Use comments and blank lines to divide long functions into logical
214 groups of statements.
215
216   Avoid assignments inside "if" and "while" conditions.
217
218   Do not put gratuitous parentheses around the expression in a return
219 statement, that is, write "return 0;" and not "return(0);"
220
221   Write only one statement per line.
222
223   Indent "switch" statements like this:
224
225     switch (conn->state) {
226     case S_RECV:
227         error = run_connection_input(conn);
228         break;
229
230     case S_PROCESS:
231         error = 0;
232         break;
233
234     case S_SEND:
235         error = run_connection_output(conn);
236         break;
237
238     default:
239         OVS_NOT_REACHED();
240     }
241
242   "switch" statements with very short, uniform cases may use an
243 abbreviated style:
244
245     switch (code) {
246     case 200: return "OK";
247     case 201: return "Created";
248     case 202: return "Accepted";
249     case 204: return "No Content";
250     default: return "Unknown";
251     }
252
253   Use "for (;;)" to write an infinite loop.
254
255   In an if/else construct where one branch is the "normal" or "common"
256 case and the other branch is the "uncommon" or "error" case, put the
257 common case after the "if", not the "else".  This is a form of
258 documentation.  It also places the most important code in sequential
259 order without forcing the reader to visually skip past less important
260 details.  (Some compilers also assume that the "if" branch is the more
261 common case, so this can be a real form of optimization as well.)
262
263
264 RETURN VALUES
265
266   For functions that return a success or failure indication, prefer
267 one of the following return value conventions:
268
269     * An "int" where 0 indicates success and a positive errno value
270       indicates a reason for failure.
271
272     * A "bool" where true indicates success and false indicates
273       failure.
274
275
276 MACROS
277
278   Don't define an object-like macro if an enum can be used instead.
279
280   Don't define a function-like macro if a "static inline" function
281 can be used instead.
282
283   If a macro's definition contains multiple statements, enclose them
284 with "do { ... } while (0)" to allow them to work properly in all
285 syntactic circumstances.
286
287   Do use macros to eliminate the need to update different parts of a
288 single file in parallel, e.g. a list of enums and an array that gives
289 the name of each enum.  For example:
290
291     /* Logging importance levels. */
292     #define VLOG_LEVELS                             \
293         VLOG_LEVEL(EMER, LOG_ALERT)                 \
294         VLOG_LEVEL(ERR, LOG_ERR)                    \
295         VLOG_LEVEL(WARN, LOG_WARNING)               \
296         VLOG_LEVEL(INFO, LOG_NOTICE)                \
297         VLOG_LEVEL(DBG, LOG_DEBUG)
298     enum vlog_level {
299     #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) VLL_##NAME,
300         VLOG_LEVELS
301     #undef VLOG_LEVEL
302         VLL_N_LEVELS
303     };
304
305     /* Name for each logging level. */
306     static const char *level_names[VLL_N_LEVELS] = {
307     #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) #NAME,
308         VLOG_LEVELS
309     #undef VLOG_LEVEL
310     };
311
312
313 THREAD SAFETY ANNOTATIONS
314
315   Use the macros in lib/compiler.h to annotate locking requirements.
316 For example:
317
318     static struct ovs_mutex mutex = OVS_MUTEX_INITIALIZER;
319     static struct ovs_rwlock rwlock = OVS_RWLOCK_INITIALIZER;
320
321     void function_require_plain_mutex(void) OVS_REQUIRES(mutex);
322     void function_require_rwlock(void) OVS_REQ_RDLOCK(rwlock);
323
324   Pass lock objects, not their addresses, to the annotation macros.
325 (Thus we have OVS_REQUIRES(mutex) above, not OVS_REQUIRES(&mutex).)
326
327
328 SOURCE FILES
329
330   Each source file should state its license in a comment at the very
331 top, followed by a comment explaining the purpose of the code that is
332 in that file. The comment should explain how the code in the file
333 relates to code in other files. The goal is to allow a programmer to
334 quickly figure out where a given module fits into the larger system.
335
336   The first non-comment line in a .c source file should be:
337
338     #include <config.h>
339
340 #include directives should appear in the following order:
341
342     1. #include <config.h>
343
344     2. The module's own headers, if any.  Including this before any
345        other header (besides <config.h>) ensures that the module's
346        header file is self-contained (see HEADER FILES) below.
347
348     3. Standard C library headers and other system headers, preferably
349        in alphabetical order.  (Occasionally one encounters a set of
350        system headers that must be included in a particular order, in
351        which case that order must take precedence.)
352
353     4. Open vSwitch headers, in alphabetical order.  Use "", not <>,
354        to specify Open vSwitch header names.
355
356
357 HEADER FILES
358
359   Each header file should start with its license, as described under
360 SOURCE FILES above, followed by a "header guard" to make the header
361 file idempotent, like so:
362
363     #ifndef NETDEV_H
364     #define NETDEV_H 1
365
366     ...
367
368     #endif /* netdev.h */
369
370   Header files should be self-contained; that is, they should #include
371 whatever additional headers are required, without requiring the client
372 to #include them for it.
373
374   Don't define the members of a struct or union in a header file,
375 unless client code is actually intended to access them directly or if
376 the definition is otherwise actually needed (e.g. inline functions
377 defined in the header need them).
378
379   Similarly, don't #include a header file just for the declaration of
380 a struct or union tag (e.g. just for "struct <name>;").  Just declare
381 the tag yourself.  This reduces the number of header file
382 dependencies.
383
384
385 TYPES
386
387   Use typedefs sparingly.  Code is clearer if the actual type is
388 visible at the point of declaration.  Do not, in general, declare a
389 typedef for a struct, union, or enum.  Do not declare a typedef for a
390 pointer type, because this can be very confusing to the reader.
391
392   A function type is a good use for a typedef because it can clarify
393 code.  The type should be a function type, not a pointer-to-function
394 type.  That way, the typedef name can be used to declare function
395 prototypes.  (It cannot be used for function definitions, because that
396 is explicitly prohibited by C89 and C99.)
397
398   You may assume that "char" is exactly 8 bits and that "int" and
399 "long" are at least 32 bits.
400
401   Don't assume that "long" is big enough to hold a pointer.  If you
402 need to cast a pointer to an integer, use "intptr_t" or "uintptr_t"
403 from <stdint.h>.
404
405   Use the int<N>_t and uint<N>_t types from <stdint.h> for exact-width
406 integer types.  Use the PRId<N>, PRIu<N>, and PRIx<N> macros from
407 <inttypes.h> for formatting them with printf() and related functions.
408
409   For compatibility with antique printf() implementations:
410
411     - Instead of "%zu", use "%"PRIuSIZE.
412
413     - Instead of "%td", use "%"PRIdPTR.
414
415     - Instead of "%ju", use "%"PRIuMAX.
416
417 Other variants exist for different radixes.  For example, use
418 "%"PRIxSIZE instead of "%zx" or "%x" instead of "%hhx".
419
420   Also, instead of "%hhd", use "%d".  Be cautious substituting "%u",
421 "%x", and "%o" for the corresponding versions with "hh": cast the
422 argument to unsigned char if necessary, because printf("%hhu", -1)
423 prints 255 but printf("%u", -1) prints 4294967295.
424
425   Use bit-fields sparingly.  Do not use bit-fields for layout of
426 network protocol fields or in other circumstances where the exact
427 format is important.
428
429   Declare bit-fields to be type "unsigned int" or "signed int".  Do
430 *not* declare bit-fields of type "int": C89 allows these to be either
431 signed or unsigned according to the compiler's whim.  (A 1-bit
432 bit-field of type "int" may have a range of -1...0!)  Do not declare
433 bit-fields of type _Bool or enum or any other type, because these are
434 not portable.
435
436   Try to order structure members such that they pack well on a system
437 with 2-byte "short", 4-byte "int", and 4- or 8-byte "long" and pointer
438 types.  Prefer clear organization over size optimization unless you
439 are convinced there is a size or speed benefit.
440
441   Pointer declarators bind to the variable name, not the type name.
442 Write "int *x", not "int* x" and definitely not "int * x".
443
444
445 EXPRESSIONS
446
447   Put one space on each side of infix binary and ternary operators:
448
449     * / %
450     + -
451     << >>
452     < <= > >=
453     == !=
454     &
455     ^
456     |
457     &&
458     ||
459     ?:
460     = += -= *= /= %= &= ^= |= <<= >>=
461
462   Avoid comma operators.
463
464   Do not put any white space around postfix, prefix, or grouping
465 operators:
466
467     () [] -> .
468     ! ~ ++ -- + - * &
469
470 Exception 1: Put a space after (but not before) the "sizeof" keyword.
471 Exception 2: Put a space between the () used in a cast and the
472 expression whose type is cast: (void *) 0.
473
474   Break long lines before the ternary operators ? and :, rather than
475 after them, e.g.
476
477     return (out_port != VIGP_CONTROL_PATH
478             ? alpheus_output_port(dp, skb, out_port)
479             : alpheus_output_control(dp, skb, fwd_save_skb(skb),
480                                      VIGR_ACTION));
481
482
483   Do not parenthesize the operands of && and || unless operator
484 precedence makes it necessary, or unless the operands are themselves
485 expressions that use && and ||.  Thus:
486
487     if (!isdigit((unsigned char)s[0])
488         || !isdigit((unsigned char)s[1])
489         || !isdigit((unsigned char)s[2])) {
490         printf("string %s does not start with 3-digit code\n", s);
491     }
492
493 but
494
495     if (rule && (!best || rule->priority > best->priority)) {
496         best = rule;
497     }
498
499   Do parenthesize a subexpression that must be split across more than
500 one line, e.g.:
501
502     *idxp = ((l1_idx << PORT_ARRAY_L1_SHIFT)
503              | (l2_idx << PORT_ARRAY_L2_SHIFT)
504              | (l3_idx << PORT_ARRAY_L3_SHIFT));
505
506   Try to avoid casts.  Don't cast the return value of malloc().
507
508   The "sizeof" operator is unique among C operators in that it accepts
509 two very different kinds of operands: an expression or a type.  In
510 general, prefer to specify an expression, e.g. "int *x =
511 xmalloc(sizeof *x);".  When the operand of sizeof is an expression,
512 there is no need to parenthesize that operand, and please don't.
513
514   Use the ARRAY_SIZE macro from lib/util.h to calculate the number of
515 elements in an array.
516
517   When using a relational operator like "<" or "==", put an expression
518 or variable argument on the left and a constant argument on the
519 right, e.g. "x == 0", *not* "0 == x".
520
521
522 BLANK LINES
523
524   Put one blank line between top-level definitions of functions and
525 global variables.
526
527
528 C DIALECT
529
530   Most C99 features are OK because they are widely implemented:
531
532     * Flexible array members (e.g. struct { int foo[]; }).
533
534     * "static inline" functions (but no other forms of "inline", for
535       which GCC and C99 have differing interpretations).
536
537     * "long long"
538
539     * <stdint.h> and <inttypes.h>.
540
541     * bool and <stdbool.h>, but don't assume that bool or _Bool can
542       only take on the values 0 or 1, because this behavior can't be
543       simulated on C89 compilers.
544
545     * Designated initializers (e.g. "struct foo foo = {.a = 1};" and
546       "int a[] = {[2] = 5};").
547
548     * Mixing of declarations and code within a block.  Please use this
549       judiciously; keep declarations nicely grouped together in the
550       beginning of a block if possible.
551
552     * Use of declarations in iteration statements (e.g.
553       "for (int i = 0; i < 10; i++)").
554
555     * Use of a trailing comma in an enum declaration (e.g.
556       "enum { x = 1, };").
557
558   As a matter of style, avoid // comments.
559
560   Avoid using GCC or Clang extensions unless you also add a fallback
561 for other compilers.  You can, however, use C99 features or GCC
562 extensions also supported by Clang in code that compiles only on
563 GNU/Linux (such as lib/netdev-linux.c), because GCC is the system
564 compiler there.