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