]> git.proxmox.com Git - mirror_ovs.git/blob - CodingStyle.rst
ovs-ofctl: Fix memory leak in ofctl_packet_out().
[mirror_ovs.git] / CodingStyle.rst
1 ..
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
5
6 http://www.apache.org/licenses/LICENSE-2.0
7
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
12 under the License.
13
14 Convention for heading levels in Open vSwitch documentation:
15
16 ======= Heading 0 (reserved for the title in a document)
17 ------- Heading 1
18 ~~~~~~~ Heading 2
19 +++++++ Heading 3
20 ''''''' Heading 4
21
22 Avoid deeper levels because they do not render well.
23
24 =========================
25 Open vSwitch Coding Style
26 =========================
27
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.
32
33 The following GNU indent options approximate this style.
34
35 ::
36
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 \
39 -di1 -lp -il0 -hnl
40
41 .. _basics:
42
43 Basics
44 ------
45
46 - Limit lines to 79 characters.
47
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.
50
51 - Do not use tabs for indentation.
52
53 - Avoid trailing spaces on lines.
54
55 .. _naming:
56
57 Naming
58 ------
59
60 - Use names that explain the purpose of a function or object.
61
62 - Use underscores to separate words in an identifier: ``multi_word_name``.
63
64 - Use lowercase for most names. Use uppercase for macros, macro parameters,
65 and members of enumerations.
66
67 - Give arrays names that are plural.
68
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.
74
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.
77
78 - Avoid negative names: ``found`` is a better name than ``not_found``.
79
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.
84
85 .. _comments:
86
87 Comments
88 --------
89
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.
92
93 Write block comments as shown below. You may put the ``/*`` and ``*/`` on the
94 same line as comment text if you prefer.
95
96 ::
97
98 /*
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
102 * always ignore it.
103 */
104
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.
108
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.:
112
113 ::
114
115 /* An event that will wake the following call to poll_block(). */
116 struct poll_waiter {
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. */
124
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). */
128 };
129
130 Use ``XXX`` or ``FIXME`` comments to mark code that needs work.
131
132 Don't use ``//`` comments.
133
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.
136
137 .. _functions:
138
139 Functions
140 ---------
141
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.
144
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).
152
153 Simple static functions do not need a comment.
154
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.
162
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);``.
167
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.
172
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.
176
177 1. The primary object being manipulated, if any (equivalent to the "this"
178 pointer in C++).
179
180 2. Input-only parameters.
181
182 3. Input/output parameters.
183
184 4. Output-only parameters.
185
186 5. Status parameter.
187
188 Example:
189
190 ::
191
192 ```
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. */
198 int
199 netdev_get_features(struct netdev *netdev,
200 uint32_t *current, uint32_t *advertised,
201 uint32_t *supported, uint32_t *peer)
202 {
203 ...
204 }
205 ```
206
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.
211
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
215 inline.)
216
217 .. _function prototypes:
218
219 Function Prototypes
220 -------------------
221
222 Put the return type and function name on the same line in a function prototype:
223
224 ::
225
226 static const struct option_class *get_option_class(int code);
227
228 Omit parameter names from function prototypes when the names do not give useful
229 information, e.g.:
230
231 ::
232
233 int netdev_get_mtu(const struct netdev *, int *mtup);
234
235 Statements
236 ----------
237
238 Indent each level of code with 4 spaces. Use BSD-style brace placement:
239
240 ::
241
242 if (a()) {
243 b();
244 d();
245 }
246
247 Put a space between ``if``, ``while``, ``for``, etc. and the expressions that
248 follow them.
249
250 Enclose single statements in braces:
251
252 ::
253
254 if (a > b) {
255 return a;
256 } else {
257 return b;
258 }
259
260 Use comments and blank lines to divide long functions into logical groups of
261 statements.
262
263 Avoid assignments inside ``if`` and ``while`` conditions.
264
265 Do not put gratuitous parentheses around the expression in a return statement,
266 that is, write ``return 0;`` and not ``return(0);``
267
268 Write only one statement per line.
269
270 Indent ``switch`` statements like this:
271
272 ::
273
274 switch (conn->state) {
275 case S_RECV:
276 error = run_connection_input(conn);
277 break;
278
279 case S_PROCESS:
280 error = 0;
281 break;
282
283 case S_SEND:
284 error = run_connection_output(conn);
285 break;
286
287 default:
288 OVS_NOT_REACHED();
289 }
290
291 ``switch`` statements with very short, uniform cases may use an abbreviated
292 style:
293
294 ::
295
296 switch (code) {
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";
302 }
303
304 Use ``for (;;)`` to write an infinite loop.
305
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
312 well.)
313
314 Return Values
315 -------------
316
317 For functions that return a success or failure indication, prefer one of the
318 following return value conventions:
319
320 - An ``int`` where 0 indicates success and a positive errno value indicates a
321 reason for failure.
322
323 - A ``bool`` where true indicates success and false indicates failure.
324
325 Macros
326 ------
327
328 Don't define an object-like macro if an enum can be used instead.
329
330 Don't define a function-like macro if a "static inline" function can be used
331 instead.
332
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
335 circumstances.
336
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
339 enum. For example:
340
341 ::
342
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)
350 enum vlog_level {
351 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) VLL_##NAME,
352 VLOG_LEVELS
353 #undef VLOG_LEVEL
354 VLL_N_LEVELS
355 };
356
357 /* Name for each logging level. */
358 static const char *level_names[VLL_N_LEVELS] = {
359 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) #NAME,
360 VLOG_LEVELS
361 #undef VLOG_LEVEL
362 };
363
364 Thread Safety Annotations
365 -------------------------
366
367 Use the macros in ``lib/compiler.h`` to annotate locking requirements. For
368 example:
369
370 ::
371
372 static struct ovs_mutex mutex = OVS_MUTEX_INITIALIZER;
373 static struct ovs_rwlock rwlock = OVS_RWLOCK_INITIALIZER;
374
375 void function_require_plain_mutex(void) OVS_REQUIRES(mutex);
376 void function_require_rwlock(void) OVS_REQ_RDLOCK(rwlock);
377
378 Pass lock objects, not their addresses, to the annotation macros. (Thus we have
379 ``OVS_REQUIRES(mutex)`` above, not ``OVS_REQUIRES(&mutex)``.)
380
381 .. _source files:
382
383 Source Files
384 ------------
385
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.
391
392 The first non-comment line in a .c source file should be:
393
394 ::
395
396 #include <config.h>
397
398 ``#include`` directives should appear in the following order:
399
400 1. ``#include <config.h>``
401
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).
405
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
409 take precedence.)
410
411 4. Open vSwitch headers, in alphabetical order. Use ``""``, not ``<>``, to
412 specify Open vSwitch header names.
413
414 .. _header files:
415
416 Header Files
417 ------------
418
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,
421 like so:
422
423 ::
424
425 #ifndef NETDEV_H
426 #define NETDEV_H 1
427
428 ...
429
430 #endif /* netdev.h */
431
432 Header files should be self-contained; that is, they should ``#include`` whatever
433 additional headers are required, without requiring the client to ``#include``
434 them for it.
435
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
439 them).
440
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.
444
445 Types
446 -----
447
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.
452
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.)
457
458 You may assume that ``char`` is exactly 8 bits and that ``int`` and ``long``
459 are at least 32 bits.
460
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 .
463
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.
467
468 For compatibility with antique ``printf()`` implementations:
469
470 - Instead of ``"%zu"``, use ``"%"PRIuSIZE``.
471
472 - Instead of ``"%td"``, use ``"%"PRIdPTR``.
473
474 - Instead of ``"%ju"``, use ``"%"PRIuMAX``.
475
476 Other variants exist for different radixes. For example, use ``"%"PRIxSIZE``
477 instead of ``"%zx"`` or ``"%x"`` instead of ``"%hhx"``.
478
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.
483
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
486 important.
487
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!)
492
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.
497
498 Pointer declarators bind to the variable name, not the type name. Write
499 ``int *x``, not ``int* x`` and definitely not ``int * x``.
500
501 Expressions
502 -----------
503
504 Put one space on each side of infix binary and ternary operators:
505
506 ::
507
508 * / %
509 + -
510 << >>
511 < <= > >=
512 == !=
513 &
514 ^
515 |
516 &&
517 ||
518 ?:
519 = += -= *= /= %= &= ^= |= <<= >>=
520
521 Avoid comma operators.
522
523 Do not put any white space around postfix, prefix, or grouping operators:
524
525 ::
526
527 () [] -> .
528 ! ~ ++ -- + - * &
529
530 Exception 1: Put a space after (but not before) the "sizeof" keyword.
531
532 Exception 2: Put a space between the () used in a cast and the expression whose
533 type is cast: ``(void \*) 0``.
534
535 Break long lines before the ternary operators ? and :, rather than after
536 them, e.g.
537
538 ::
539
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),
543 VIGR_ACTION));
544
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:
548
549 ::
550
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);
555 }
556
557 but
558
559 ::
560
561 if (rule && (!best || rule->priority > best->priority)) {
562 best = rule;
563 }
564
565 Do parenthesize a subexpression that must be split across more than one line,
566 e.g.:
567
568 ::
569
570 *idxp = ((l1_idx << PORT_ARRAY_L1_SHIFT)
571 | (l2_idx << PORT_ARRAY_L2_SHIFT)
572 | (l3_idx << PORT_ARRAY_L3_SHIFT));
573
574 Try to avoid casts. Don't cast the return value of malloc().
575
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.
581
582 Use the ``ARRAY_SIZE`` macro from ``lib/util.h`` to calculate the number of
583 elements in an array.
584
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``.
588
589 Blank Lines
590 -----------
591
592 Put one blank line between top-level definitions of functions and global
593 variables.
594
595 C DIALECT
596 ---------
597
598 Most C99 features are OK because they are widely implemented:
599
600 - Flexible array members (e.g. ``struct { int foo[]; }``).
601
602 - ``static inline`` functions (but no other forms of ``inline``, for which GCC
603 and C99 have differing interpretations).
604
605 - ``long long``
606
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
609 compilers.
610
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``.
616
617 - Designated initializers (e.g. ``struct foo foo = {.a = 1};`` and ``int
618 a[] = {[2] = 5};``).
619
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.
623
624 - Use of declarations in iteration statements (e.g. ``for (int i = 0; i
625 < 10; i++)``).
626
627 - Use of a trailing comma in an enum declaration (e.g. ``enum { x = 1,
628 };``).
629
630 As a matter of style, avoid ``//`` comments.
631
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.
636
637 Python
638 ------
639
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.