]> git.proxmox.com Git - mirror_ovs.git/blame - CodingStyle.rst
ovs-ofctl: Fix memory leak in ofctl_packet_out().
[mirror_ovs.git] / CodingStyle.rst
CommitLineData
d124a408
SF
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=========================
25Open vSwitch Coding Style
26=========================
27
28This file describes the coding style used in most C files in the Open vSwitch
29distribution. However, Linux kernel code datapath directory follows the Linux
30kernel's established coding conventions. For the Windows kernel datapath code,
31use the coding style described in datapath-windows/CodingStyle.
32
33The 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
43Basics
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
57Naming
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
87Comments
88--------
89
90Comments should be written as full sentences that start with a capital letter
91and end with a period. Put two spaces between sentences.
92
93Write block comments as shown below. You may put the ``/*`` and ``*/`` on the
94same 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
105Each function and each variable declared outside a function, and each struct,
106union, and typedef declaration should be preceded by a comment. See functions_
107below for function comment guidelines.
108
109Each struct and union member should each have an inline comment that explains
110its meaning. structs and unions with many members should be additionally
111divided 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
130Use ``XXX`` or ``FIXME`` comments to mark code that needs work.
131
132Don't use ``//`` comments.
133
134Don't comment out or #if 0 out code. Just remove it. The code that was there
135will still be in version control history.
136
137.. _functions:
138
139Functions
140---------
141
142Put the return type, function name, and the braces that surround the function's
143code on separate lines, all starting in column 0.
144
145Before each function definition, write a comment that describes the function's
146purpose, including each parameter, the return value, and side effects.
147References to argument names should be given in single-quotes, e.g. 'arg'. The
148comment should not include the function name, nor need it follow any formal
149structure. The comment does not need to describe how a function does its work,
150unless this information is needed to use the function correctly (this is often
151better done with comments *inside* the function).
152
153Simple static functions do not need a comment.
154
155Within a file, non-static functions should come first, in the order that they
156are declared in the header file, followed by static functions. Static
157functions should be in one or more separate pages (separated by form feed
158characters) in logical groups. A commonly useful way to divide groups is by
159"level", with high-level functions first, followed by groups of progressively
160lower-level functions. This makes it easy for the program's reader to see the
161top-down structure by reading from top to bottom.
162
163All function declarations and definitions should include a prototype. Empty
164parentheses, e.g. ``int foo();``, do not include a prototype (they state that
165the function's parameters are unknown); write ``void`` in parentheses instead,
166e.g. ``int foo(void);``.
167
168Prototypes for static functions should either all go at the top of the file,
169separated into groups by blank lines, or they should appear at the top of each
170page of functions. Don't comment individual prototypes, but a comment on each
171group of prototypes is often appropriate.
172
173In the absence of good reasons for another order, the following parameter order
174is preferred. One notable exception is that data parameters and their
175corresponding size parameters should be paired.
176
1771. The primary object being manipulated, if any (equivalent to the "this"
178 pointer in C++).
179
1802. Input-only parameters.
181
1823. Input/output parameters.
183
1844. Output-only parameters.
185
1865. Status parameter.
187
188Example:
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
207Functions that destroy an instance of a dynamically-allocated type should
208accept and ignore a null pointer argument. Code that calls such a function
209(including the C standard library function ``free()``) should omit a
210null-pointer check. We find that this usually makes code easier to read.
211
212Functions in ``.c`` files should not normally be marked ``inline``, because it
213does not usually help code generation and it does suppress compilers warnings
214about unused functions. (Functions defined in .h usually should be marked
215inline.)
216
217.. _function prototypes:
218
219Function Prototypes
220-------------------
221
222Put 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
228Omit parameter names from function prototypes when the names do not give useful
229information, e.g.:
230
231::
232
233 int netdev_get_mtu(const struct netdev *, int *mtup);
234
235Statements
236----------
237
238Indent each level of code with 4 spaces. Use BSD-style brace placement:
239
240::
241
242 if (a()) {
243 b();
244 d();
245 }
246
247Put a space between ``if``, ``while``, ``for``, etc. and the expressions that
248follow them.
249
250Enclose single statements in braces:
251
252::
253
254 if (a > b) {
255 return a;
256 } else {
257 return b;
258 }
259
260Use comments and blank lines to divide long functions into logical groups of
261statements.
262
263Avoid assignments inside ``if`` and ``while`` conditions.
264
265Do not put gratuitous parentheses around the expression in a return statement,
266that is, write ``return 0;`` and not ``return(0);``
267
268Write only one statement per line.
269
270Indent ``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
292style:
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
304Use ``for (;;)`` to write an infinite loop.
305
306In an if/else construct where one branch is the "normal" or "common" case and
307the other branch is the "uncommon" or "error" case, put the common case after
308the "if", not the "else". This is a form of documentation. It also places the
309most important code in sequential order without forcing the reader to visually
310skip past less important details. (Some compilers also assume that the "if"
311branch is the more common case, so this can be a real form of optimization as
312well.)
313
314Return Values
315-------------
316
317For functions that return a success or failure indication, prefer one of the
318following 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
325Macros
326------
327
328Don't define an object-like macro if an enum can be used instead.
329
330Don't define a function-like macro if a "static inline" function can be used
331instead.
332
333If a macro's definition contains multiple statements, enclose them with ``do {
334... } while (0)`` to allow them to work properly in all syntactic
335circumstances.
336
337Do use macros to eliminate the need to update different parts of a single file
338in parallel, e.g. a list of enums and an array that gives the name of each
339enum. 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
364Thread Safety Annotations
365-------------------------
366
367Use the macros in ``lib/compiler.h`` to annotate locking requirements. For
368example:
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
378Pass 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
383Source Files
384------------
385
386Each source file should state its license in a comment at the very top,
387followed by a comment explaining the purpose of the code that is in that file.
388The comment should explain how the code in the file relates to code in other
389files. The goal is to allow a programmer to quickly figure out where a given
390module fits into the larger system.
391
392The 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
4001. ``#include <config.h>``
401
4022. 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
4063. 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
4114. Open vSwitch headers, in alphabetical order. Use ``""``, not ``<>``, to
412 specify Open vSwitch header names.
413
414.. _header files:
415
416Header Files
417------------
418
419Each header file should start with its license, as described under `source
420files`_ above, followed by a "header guard" to make the header file idempotent,
421like so:
422
423::
424
425 #ifndef NETDEV_H
426 #define NETDEV_H 1
427
428 ...
429
430 #endif /* netdev.h */
431
432Header files should be self-contained; that is, they should ``#include`` whatever
433additional headers are required, without requiring the client to ``#include``
434them for it.
435
436Don't define the members of a struct or union in a header file, unless client
437code is actually intended to access them directly or if the definition is
438otherwise actually needed (e.g. inline functions defined in the header need
439them).
440
441Similarly, don't ``#include`` a header file just for the declaration of a
442struct or union tag (e.g. just for ``struct ;``). Just declare the tag
443yourself. This reduces the number of header file dependencies.
444
445Types
446-----
447
448Use typedefs sparingly. Code is clearer if the actual type is visible at the
449point of declaration. Do not, in general, declare a typedef for a struct,
450union, or enum. Do not declare a typedef for a pointer type, because this can
451be very confusing to the reader.
452
453A function type is a good use for a typedef because it can clarify code. The
454type should be a function type, not a pointer-to-function type. That way, the
455typedef name can be used to declare function prototypes. (It cannot be used for
456function definitions, because that is explicitly prohibited by C89 and C99.)
457
458You may assume that ``char`` is exactly 8 bits and that ``int`` and ``long``
459are at least 32 bits.
460
461Don't assume that ``long`` is big enough to hold a pointer. If you need to cast
462a pointer to an integer, use ``intptr_t`` or ``uintptr_t`` from .
463
464Use the ``int_t`` and ``uint_t`` types from for exact-width integer types. Use
465the ``PRId``, ``PRIu``, and ``PRIx`` macros from for formatting them with
466``printf()`` and related functions.
467
468For 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
476Other variants exist for different radixes. For example, use ``"%"PRIxSIZE``
477instead of ``"%zx"`` or ``"%x"`` instead of ``"%hhx"``.
478
479Also, instead of ``"%hhd"``, use ``"%d"``. Be cautious substituting ``"%u"``,
480``"%x"``, and ``"%o"`` for the corresponding versions with ``"hh"``: cast the
481argument to unsigned char if necessary, because ``printf("%hhu", -1)`` prints
482255 but ``printf("%u", -1)`` prints 4294967295.
483
484Use bit-fields sparingly. Do not use bit-fields for layout of network
485protocol fields or in other circumstances where the exact format is
486important.
487
488Declare bit-fields to be signed or unsigned integer types or \_Bool (aka
489bool). Do *not* declare bit-fields of type ``int``: C99 allows these to be
490either signed or unsigned according to the compiler's whim. (A 1-bit bit-field
491of type ``int`` may have a range of -1...0!)
492
493Try 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
495clear organization over size optimization unless you are convinced there is a
496size or speed benefit.
497
498Pointer declarators bind to the variable name, not the type name. Write
499``int *x``, not ``int* x`` and definitely not ``int * x``.
500
501Expressions
502-----------
503
504Put 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
521Avoid comma operators.
522
523Do not put any white space around postfix, prefix, or grouping operators:
524
525::
526
527 () [] -> .
528 ! ~ ++ -- + - * &
529
530Exception 1: Put a space after (but not before) the "sizeof" keyword.
531
532Exception 2: Put a space between the () used in a cast and the expression whose
533type is cast: ``(void \*) 0``.
534
535Break long lines before the ternary operators ? and :, rather than after
536them, 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
545Do not parenthesize the operands of ``&&`` and ``||`` unless operator
546precedence makes it necessary, or unless the operands are themselves
547expressions 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
557but
558
559::
560
561 if (rule && (!best || rule->priority > best->priority)) {
562 best = rule;
563 }
564
565Do parenthesize a subexpression that must be split across more than one line,
566e.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
574Try to avoid casts. Don't cast the return value of malloc().
575
576The "sizeof" operator is unique among C operators in that it accepts two very
577different kinds of operands: an expression or a type. In general, prefer to
578specify an expression, e.g. ``int *x = xmalloc(sizeof *\ x);``. When the
579operand of sizeof is an expression, there is no need to parenthesize that
580operand, and please don't.
581
582Use the ``ARRAY_SIZE`` macro from ``lib/util.h`` to calculate the number of
583elements in an array.
584
585When using a relational operator like ``<`` or ``==``, put an expression or
586variable argument on the left and a constant argument on the right, e.g.
587``x == 0``, *not* ``0 == x``.
588
589Blank Lines
590-----------
591
592Put one blank line between top-level definitions of functions and global
593variables.
594
595C DIALECT
596---------
597
598Most 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
630As a matter of style, avoid ``//`` comments.
631
632Avoid using GCC or Clang extensions unless you also add a fallback for other
633compilers. You can, however, use C99 features or GCC extensions also supported
634by Clang in code that compiles only on GNU/Linux (such as
635``lib/netdev-linux.c``), because GCC is the system compiler there.
636
637Python
638------
639
640When 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.