2 Licensed under the Apache License, Version 2.0 (the "License"); you may
3 not use this file except in compliance with the License. You may obtain
4 a copy of the License at
6 http://www.apache.org/licenses/LICENSE-2.0
8 Unless required by applicable law or agreed to in writing, software
9 distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
10 WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
11 License for the specific language governing permissions and limitations
14 Convention for heading levels in Open vSwitch documentation:
16 ======= Heading 0 (reserved for the title in a document)
22 Avoid deeper levels because they do not render well.
24 =========================
25 Open vSwitch Coding Style
26 =========================
28 This file describes the coding style used in most C files in the Open vSwitch
29 distribution. However, Linux kernel code datapath directory follows the Linux
30 kernel's established coding conventions. For the Windows kernel datapath code,
31 use the coding style described in datapath-windows/CodingStyle.
33 The following GNU indent options approximate this style.
37 -npro -bad -bap -bbb -br -blf -brs -cdw -ce -fca -cli0 -npcs -i4 -l79 \
38 -lc79 -nbfda -nut -saf -sai -saw -sbi4 -sc -sob -st -ncdb -pi4 -cs -bs \
46 - Limit lines to 79 characters.
48 - Use form feeds (control+L) to divide long source files into logical pieces. A
49 form feed should appear as the only character on a line.
51 - Do not use tabs for indentation.
53 - Avoid trailing spaces on lines.
60 - Use names that explain the purpose of a function or object.
62 - Use underscores to separate words in an identifier: ``multi_word_name``.
64 - Use lowercase for most names. Use uppercase for macros, macro parameters,
65 and members of enumerations.
67 - Give arrays names that are plural.
69 - Pick a unique name prefix (ending with an underscore) for each
70 module, and apply that prefix to all of that module's externally
71 visible names. Names of macro parameters, struct and union members,
72 and parameters in function prototypes are not considered externally
73 visible for this purpose.
75 - Do not use names that begin with ``_``. If you need a name for "internal use
76 only", use ``__`` as a suffix instead of a prefix.
78 - Avoid negative names: ``found`` is a better name than ``not_found``.
80 - In names, a ``size`` is a count of bytes, a ``length`` is a count of
81 characters. A buffer has size, but a string has length. The length of a
82 string does not include the null terminator, but the size of the buffer that
83 contains the string does.
90 Comments should be written as full sentences that start with a capital letter
91 and end with a period. Put two spaces between sentences.
93 Write block comments as shown below. You may put the ``/*`` and ``*/`` on the
94 same line as comment text if you prefer.
99 * We redirect stderr to /dev/null because we often want to remove all
100 * traffic control configuration on a port so its in a known state. If
101 * this done when there is no such configuration, tc complains, so we just
105 Each function and each variable declared outside a function, and each struct,
106 union, and typedef declaration should be preceded by a comment. See functions_
107 below for function comment guidelines.
109 Each struct and union member should each have an inline comment that explains
110 its meaning. structs and unions with many members should be additionally
111 divided into logical groups of members by block comments, e.g.:
115 /* An event that will wake the following call to poll_block(). */
117 /* Set when the waiter is created. */
118 struct ovs_list node; /* Element in global waiters list. */
119 int fd; /* File descriptor. */
120 short int events; /* Events to wait for (POLLIN, POLLOUT). */
121 poll_fd_func *function; /* Callback function, if any, or null. */
122 void *aux; /* Argument to callback function. */
123 struct backtrace *backtrace; /* Event that created waiter, or null. */
125 /* Set only when poll_block() is called. */
126 struct pollfd *pollfd; /* Pointer to element of the pollfds array
127 (null if added from a callback). */
130 Use ``XXX`` or ``FIXME`` comments to mark code that needs work.
132 Don't use ``//`` comments.
134 Don't comment out or #if 0 out code. Just remove it. The code that was there
135 will still be in version control history.
142 Put the return type, function name, and the braces that surround the function's
143 code on separate lines, all starting in column 0.
145 Before each function definition, write a comment that describes the function's
146 purpose, including each parameter, the return value, and side effects.
147 References to argument names should be given in single-quotes, e.g. 'arg'. The
148 comment should not include the function name, nor need it follow any formal
149 structure. The comment does not need to describe how a function does its work,
150 unless this information is needed to use the function correctly (this is often
151 better done with comments *inside* the function).
153 Simple static functions do not need a comment.
155 Within a file, non-static functions should come first, in the order that they
156 are declared in the header file, followed by static functions. Static
157 functions should be in one or more separate pages (separated by form feed
158 characters) in logical groups. A commonly useful way to divide groups is by
159 "level", with high-level functions first, followed by groups of progressively
160 lower-level functions. This makes it easy for the program's reader to see the
161 top-down structure by reading from top to bottom.
163 All function declarations and definitions should include a prototype. Empty
164 parentheses, e.g. ``int foo();``, do not include a prototype (they state that
165 the function's parameters are unknown); write ``void`` in parentheses instead,
166 e.g. ``int foo(void);``.
168 Prototypes for static functions should either all go at the top of the file,
169 separated into groups by blank lines, or they should appear at the top of each
170 page of functions. Don't comment individual prototypes, but a comment on each
171 group of prototypes is often appropriate.
173 In the absence of good reasons for another order, the following parameter order
174 is preferred. One notable exception is that data parameters and their
175 corresponding size parameters should be paired.
177 1. The primary object being manipulated, if any (equivalent to the "this"
180 2. Input-only parameters.
182 3. Input/output parameters.
184 4. Output-only parameters.
193 /* Stores the features supported by 'netdev' into each of '*current',
194 * '*advertised', '*supported', and '*peer' that are non-null. Each value
195 * is a bitmap of "enum ofp_port_features" bits, in host byte order.
196 * Returns 0 if successful, otherwise a positive errno value. On failure,
197 * all of the passed-in values are set to 0. */
199 netdev_get_features(struct netdev *netdev,
200 uint32_t *current, uint32_t *advertised,
201 uint32_t *supported, uint32_t *peer)
207 Functions that destroy an instance of a dynamically-allocated type should
208 accept and ignore a null pointer argument. Code that calls such a function
209 (including the C standard library function ``free()``) should omit a
210 null-pointer check. We find that this usually makes code easier to read.
212 Functions in ``.c`` files should not normally be marked ``inline``, because it
213 does not usually help code generation and it does suppress compilers warnings
214 about unused functions. (Functions defined in .h usually should be marked
217 .. _function prototypes:
222 Put the return type and function name on the same line in a function prototype:
226 static const struct option_class *get_option_class(int code);
228 Omit parameter names from function prototypes when the names do not give useful
233 int netdev_get_mtu(const struct netdev *, int *mtup);
238 Indent each level of code with 4 spaces. Use BSD-style brace placement:
247 Put a space between ``if``, ``while``, ``for``, etc. and the expressions that
250 Enclose single statements in braces:
260 Use comments and blank lines to divide long functions into logical groups of
263 Avoid assignments inside ``if`` and ``while`` conditions.
265 Do not put gratuitous parentheses around the expression in a return statement,
266 that is, write ``return 0;`` and not ``return(0);``
268 Write only one statement per line.
270 Indent ``switch`` statements like this:
274 switch (conn->state) {
276 error = run_connection_input(conn);
284 error = run_connection_output(conn);
291 ``switch`` statements with very short, uniform cases may use an abbreviated
297 case 200: return "OK";
298 case 201: return "Created";
299 case 202: return "Accepted";
300 case 204: return "No Content";
301 default: return "Unknown";
304 Use ``for (;;)`` to write an infinite loop.
306 In an if/else construct where one branch is the "normal" or "common" case and
307 the other branch is the "uncommon" or "error" case, put the common case after
308 the "if", not the "else". This is a form of documentation. It also places the
309 most important code in sequential order without forcing the reader to visually
310 skip past less important details. (Some compilers also assume that the "if"
311 branch is the more common case, so this can be a real form of optimization as
317 For functions that return a success or failure indication, prefer one of the
318 following return value conventions:
320 - An ``int`` where 0 indicates success and a positive errno value indicates a
323 - A ``bool`` where true indicates success and false indicates failure.
328 Don't define an object-like macro if an enum can be used instead.
330 Don't define a function-like macro if a "static inline" function can be used
333 If a macro's definition contains multiple statements, enclose them with ``do {
334 ... } while (0)`` to allow them to work properly in all syntactic
337 Do use macros to eliminate the need to update different parts of a single file
338 in parallel, e.g. a list of enums and an array that gives the name of each
343 /* Logging importance levels. */
344 #define VLOG_LEVELS \
345 VLOG_LEVEL(EMER, LOG_ALERT) \
346 VLOG_LEVEL(ERR, LOG_ERR) \
347 VLOG_LEVEL(WARN, LOG_WARNING) \
348 VLOG_LEVEL(INFO, LOG_NOTICE) \
349 VLOG_LEVEL(DBG, LOG_DEBUG)
351 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) VLL_##NAME,
357 /* Name for each logging level. */
358 static const char *level_names[VLL_N_LEVELS] = {
359 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) #NAME,
364 Thread Safety Annotations
365 -------------------------
367 Use the macros in ``lib/compiler.h`` to annotate locking requirements. For
372 static struct ovs_mutex mutex = OVS_MUTEX_INITIALIZER;
373 static struct ovs_rwlock rwlock = OVS_RWLOCK_INITIALIZER;
375 void function_require_plain_mutex(void) OVS_REQUIRES(mutex);
376 void function_require_rwlock(void) OVS_REQ_RDLOCK(rwlock);
378 Pass lock objects, not their addresses, to the annotation macros. (Thus we have
379 ``OVS_REQUIRES(mutex)`` above, not ``OVS_REQUIRES(&mutex)``.)
386 Each source file should state its license in a comment at the very top,
387 followed by a comment explaining the purpose of the code that is in that file.
388 The comment should explain how the code in the file relates to code in other
389 files. The goal is to allow a programmer to quickly figure out where a given
390 module fits into the larger system.
392 The first non-comment line in a .c source file should be:
398 ``#include`` directives should appear in the following order:
400 1. ``#include <config.h>``
402 2. The module's own headers, if any. Including this before any other header
403 (besides ) ensures that the module's header file is self-contained (see
404 `header files`_ below).
406 3. Standard C library headers and other system headers, preferably in
407 alphabetical order. (Occasionally one encounters a set of system headers
408 that must be included in a particular order, in which case that order must
411 4. Open vSwitch headers, in alphabetical order. Use ``""``, not ``<>``, to
412 specify Open vSwitch header names.
419 Each header file should start with its license, as described under `source
420 files`_ above, followed by a "header guard" to make the header file idempotent,
430 #endif /* netdev.h */
432 Header files should be self-contained; that is, they should ``#include`` whatever
433 additional headers are required, without requiring the client to ``#include``
436 Don't define the members of a struct or union in a header file, unless client
437 code is actually intended to access them directly or if the definition is
438 otherwise actually needed (e.g. inline functions defined in the header need
441 Similarly, don't ``#include`` a header file just for the declaration of a
442 struct or union tag (e.g. just for ``struct ;``). Just declare the tag
443 yourself. This reduces the number of header file dependencies.
448 Use typedefs sparingly. Code is clearer if the actual type is visible at the
449 point of declaration. Do not, in general, declare a typedef for a struct,
450 union, or enum. Do not declare a typedef for a pointer type, because this can
451 be very confusing to the reader.
453 A function type is a good use for a typedef because it can clarify code. The
454 type should be a function type, not a pointer-to-function type. That way, the
455 typedef name can be used to declare function prototypes. (It cannot be used for
456 function definitions, because that is explicitly prohibited by C89 and C99.)
458 You may assume that ``char`` is exactly 8 bits and that ``int`` and ``long``
459 are at least 32 bits.
461 Don't assume that ``long`` is big enough to hold a pointer. If you need to cast
462 a pointer to an integer, use ``intptr_t`` or ``uintptr_t`` from .
464 Use the ``int_t`` and ``uint_t`` types from for exact-width integer types. Use
465 the ``PRId``, ``PRIu``, and ``PRIx`` macros from for formatting them with
466 ``printf()`` and related functions.
468 For compatibility with antique ``printf()`` implementations:
470 - Instead of ``"%zu"``, use ``"%"PRIuSIZE``.
472 - Instead of ``"%td"``, use ``"%"PRIdPTR``.
474 - Instead of ``"%ju"``, use ``"%"PRIuMAX``.
476 Other variants exist for different radixes. For example, use ``"%"PRIxSIZE``
477 instead of ``"%zx"`` or ``"%x"`` instead of ``"%hhx"``.
479 Also, instead of ``"%hhd"``, use ``"%d"``. Be cautious substituting ``"%u"``,
480 ``"%x"``, and ``"%o"`` for the corresponding versions with ``"hh"``: cast the
481 argument to unsigned char if necessary, because ``printf("%hhu", -1)`` prints
482 255 but ``printf("%u", -1)`` prints 4294967295.
484 Use bit-fields sparingly. Do not use bit-fields for layout of network
485 protocol fields or in other circumstances where the exact format is
488 Declare bit-fields to be signed or unsigned integer types or \_Bool (aka
489 bool). Do *not* declare bit-fields of type ``int``: C99 allows these to be
490 either signed or unsigned according to the compiler's whim. (A 1-bit bit-field
491 of type ``int`` may have a range of -1...0!)
493 Try to order structure members such that they pack well on a system with 2-byte
494 ``short``, 4-byte ``int``, and 4- or 8-byte ``long`` and pointer types. Prefer
495 clear organization over size optimization unless you are convinced there is a
496 size or speed benefit.
498 Pointer declarators bind to the variable name, not the type name. Write
499 ``int *x``, not ``int* x`` and definitely not ``int * x``.
504 Put one space on each side of infix binary and ternary operators:
519 = += -= *= /= %= &= ^= |= <<= >>=
521 Avoid comma operators.
523 Do not put any white space around postfix, prefix, or grouping operators:
530 Exception 1: Put a space after (but not before) the "sizeof" keyword.
532 Exception 2: Put a space between the () used in a cast and the expression whose
533 type is cast: ``(void \*) 0``.
535 Break long lines before the ternary operators ? and :, rather than after
540 return (out_port != VIGP_CONTROL_PATH
541 ? alpheus_output_port(dp, skb, out_port)
542 : alpheus_output_control(dp, skb, fwd_save_skb(skb),
545 Do not parenthesize the operands of ``&&`` and ``||`` unless operator
546 precedence makes it necessary, or unless the operands are themselves
547 expressions that use ``&&`` and ``||``. Thus:
551 if (!isdigit((unsigned char)s[0])
552 || !isdigit((unsigned char)s[1])
553 || !isdigit((unsigned char)s[2])) {
554 printf("string %s does not start with 3-digit code\n", s);
561 if (rule && (!best || rule->priority > best->priority)) {
565 Do parenthesize a subexpression that must be split across more than one line,
570 *idxp = ((l1_idx << PORT_ARRAY_L1_SHIFT)
571 | (l2_idx << PORT_ARRAY_L2_SHIFT)
572 | (l3_idx << PORT_ARRAY_L3_SHIFT));
574 Try to avoid casts. Don't cast the return value of malloc().
576 The "sizeof" operator is unique among C operators in that it accepts two very
577 different kinds of operands: an expression or a type. In general, prefer to
578 specify an expression, e.g. ``int *x = xmalloc(sizeof *\ x);``. When the
579 operand of sizeof is an expression, there is no need to parenthesize that
580 operand, and please don't.
582 Use the ``ARRAY_SIZE`` macro from ``lib/util.h`` to calculate the number of
583 elements in an array.
585 When using a relational operator like ``<`` or ``==``, put an expression or
586 variable argument on the left and a constant argument on the right, e.g.
587 ``x == 0``, *not* ``0 == x``.
592 Put one blank line between top-level definitions of functions and global
598 Most C99 features are OK because they are widely implemented:
600 - Flexible array members (e.g. ``struct { int foo[]; }``).
602 - ``static inline`` functions (but no other forms of ``inline``, for which GCC
603 and C99 have differing interpretations).
607 - ``bool`` and ``<stdbool.h>``, but don't assume that bool or \_Bool can only
608 take on the values 0 or 1, because this behavior can't be simulated on C89
611 Also, don't assume that a conversion to ``bool`` or ``_Bool`` follows C99
612 semantics, i.e. use ``(bool)(some_value != 0)`` rather than
613 ``(bool)some_value``. The latter might produce unexpected results on non-C99
614 environments. For example, if bool is implemented as a typedef of char and
615 ``some_value = 0x10000000``.
617 - Designated initializers (e.g. ``struct foo foo = {.a = 1};`` and ``int
620 - Mixing of declarations and code within a block. Please use this
621 judiciously; keep declarations nicely grouped together in the
622 beginning of a block if possible.
624 - Use of declarations in iteration statements (e.g. ``for (int i = 0; i
627 - Use of a trailing comma in an enum declaration (e.g. ``enum { x = 1,
630 As a matter of style, avoid ``//`` comments.
632 Avoid using GCC or Clang extensions unless you also add a fallback for other
633 compilers. You can, however, use C99 features or GCC extensions also supported
634 by Clang in code that compiles only on GNU/Linux (such as
635 ``lib/netdev-linux.c``), because GCC is the system compiler there.
640 When introducing new Python code, try to follow Python's `PEP 8
641 <http://www.python.org/dev/peps/pep-0008/>`__ style. Consider running the
642 ``pep8`` or ``flake8`` tool against your code to find issues.