7 This document specifies the preferred style for source files in the DPDK source tree.
8 It is based on the Linux Kernel coding guidelines and the FreeBSD 7.2 Kernel Developer's Manual (see man style(9)), but was heavily modified for the needs of the DPDK.
13 The rules and guidelines given in this document cannot cover every situation, so the following general guidelines should be used as a fallback:
15 * The code style should be consistent within each individual file.
16 * In the case of creating new files, the style should be consistent within each file in a given directory or module.
17 * The primary reason for coding standards is to increase code readability and comprehensibility, therefore always use whatever option will make the code easiest to read.
19 Line length is recommended to be not more than 80 characters, including comments.
20 [Tab stop size should be assumed to be 8-characters wide].
24 The above is recommendation, and not a hard limit.
25 However, it is expected that the recommendations should be followed in all but the rarest situations.
33 These comments should be used in normal cases.
34 To document a public API, a doxygen-like format must be used: refer to Doxygen Documentation.
39 * VERY important single-line comments look like this.
42 /* Most single-line comments look like this. */
45 * Multi-line comments look like this. Make them real sentences. Fill
46 * them so they look like real paragraphs.
52 Each file should begin with a special comment containing the appropriate copyright and license for the file.
53 Generally this is the BSD License, except for code for Linux Kernel modules.
54 After any copyright header, a blank line should be left before any other contents, e.g. include statements in a C file.
56 C Preprocessor Directives
57 -------------------------
62 In DPDK sources, the include files should be ordered as following:
64 #. libc includes (system includes first)
66 #. DPDK misc libraries includes
67 #. application-specific includes
69 Include files from the local application directory are included using quotes, while includes from other paths are included using angle brackets: "<>".
81 #include <rte_mempool.h>
83 #include "application.h"
88 Headers should be protected against multiple inclusion with the usual:
103 Do not ``#define`` or declare names except with the standard DPDK prefix: ``RTE_``.
104 This is to ensure there are no collisions with definitions in the application itself.
106 The names of "unsafe" macros (ones that have side effects), and the names of macros for manifest constants, are all in uppercase.
108 The expansions of expression-like macros are either a single token or have outer parentheses.
109 If a macro is an inline expansion of a function, the function name is all in lowercase and the macro has the same name all in uppercase.
110 If the macro encapsulates a compound statement, enclose it in a do-while loop, so that it can be used safely in if statements.
111 Any final statement-terminating semicolon should be supplied by the macro invocation rather than the macro, to make parsing easier for pretty-printers and editors.
117 #define MACRO(x, y) do { \
118 variable = (x) + (y); \
124 Wherever possible, enums and inline functions should be preferred to macros, since they provide additional degrees of type-safety and can allow compilers to emit extra warnings about unsafe code.
126 Conditional Compilation
127 ~~~~~~~~~~~~~~~~~~~~~~~
129 * When code is conditionally compiled using ``#ifdef`` or ``#if``, a comment may be added following the matching
130 ``#endif`` or ``#else`` to permit the reader to easily discern where conditionally compiled code regions end.
131 * This comment should be used only for (subjectively) long regions, regions greater than 20 lines, or where a series of nested ``#ifdef``'s may be confusing to the reader.
132 Exceptions may be made for cases where code is conditionally not compiled for the purposes of lint(1), or other tools, even though the uncompiled region may be small.
133 * The comment should be separated from the ``#endif`` or ``#else`` by a single space.
134 * For short conditionally compiled regions, a closing comment should not be used.
135 * The comment for ``#endif`` should match the expression used in the corresponding ``#if`` or ``#ifdef``.
136 * The comment for ``#else`` and ``#elif`` should match the inverse of the expression(s) used in the preceding ``#if`` and/or ``#elif`` statements.
137 * In the comments, the subexpression ``defined(FOO)`` is abbreviated as "FOO".
138 For the purposes of comments, ``#ifndef FOO`` is treated as ``#if !defined(FOO)``.
143 #include <sys/ktrace.h>
147 /* A large region here, or other conditional code. */
148 #else /* !COMPAT_43 */
150 #endif /* COMPAT_43 */
153 /* Yet another large region here, or other conditional code. */
154 #else /* COMPAT_43 */
156 #endif /* !COMPAT_43 */
160 Conditional compilation should be used only when absolutely necessary, as it increases the number of target binaries that need to be built and tested.
168 For fixed/minimum-size integer values, the project uses the form uintXX_t (from stdint.h) instead of older BSD-style integer identifiers of the form u_intXX_t.
173 * Enumeration values are all uppercase.
177 enum enumtype { ONE, TWO } et;
179 * Enum types should be used in preference to macros #defining a set of (sequential) values.
180 * Enum types should be prefixed with ``rte_`` and the elements by a suitable prefix [generally starting ``RTE_<enum>_`` - where <enum> is a shortname for the enum type] to avoid namespace collisions.
185 The developer should group bitfields that are included in the same integer, as follows:
202 Variable Declarations
203 ~~~~~~~~~~~~~~~~~~~~~
205 In declarations, do not put any whitespace between asterisks and adjacent tokens, except for tokens that are identifiers related to types.
206 (These identifiers are the names of basic types, type qualifiers, and typedef-names other than the one being declared.)
207 Separate these identifiers from asterisks using a single space.
213 int *x; /* no space after asterisk */
214 int * const x; /* space after asterisk when using a type qualifier */
216 * All externally-visible variables should have an ``rte_`` prefix in the name to avoid namespace collisions.
217 * Do not use uppercase letters - either in the form of ALL_UPPERCASE, or CamelCase - in variable names.
218 Lower-case letters and underscores only.
220 Structure Declarations
221 ~~~~~~~~~~~~~~~~~~~~~~
223 * In general, when declaring variables in new structures, declare them sorted by use, then by size (largest to smallest), and then in alphabetical order.
224 Sorting by use means that commonly used variables are used together and that the structure layout makes logical sense.
225 Ordering by size then ensures that as little padding is added to the structure as possible.
226 * For existing structures, additions to structures should be added to the end so for backward compatibility reasons.
227 * Each structure element gets its own line.
228 * Try to make the structure readable by aligning the member names using spaces as shown below.
229 * Names following extremely long types, which therefore cannot be easily aligned with the rest, should be separated by a single space.
234 struct foo *next; /* List of active foo. */
235 struct mumble amumble; /* Comment for mumble. */
236 int bar; /* Try to align the comments. */
237 struct verylongtypename *baz; /* Won't fit with other members */
241 * Major structures should be declared at the top of the file in which they are used, or in separate header files if they are used in multiple source files.
242 * Use of the structures should be by separate variable declarations and those declarations must be extern if they are declared in a header file.
243 * Externally visible structure definitions should have the structure name prefixed by ``rte_`` to avoid namespace collisions.
248 Use queue(3) macros rather than rolling your own lists, whenever possible.
249 Thus, the previous example would be better written:
253 #include <sys/queue.h>
256 LIST_ENTRY(foo) link; /* Use queue macros for foo lists. */
257 struct mumble amumble; /* Comment for mumble. */
258 int bar; /* Try to align the comments. */
259 struct verylongtypename *baz; /* Won't fit with other members */
261 LIST_HEAD(, foo) foohead; /* Head of global foo list. */
264 DPDK also provides an optimized way to store elements in lockless rings.
265 This should be used in all data-path code, when there are several consumer and/or producers to avoid locking for concurrent access.
270 Avoid using typedefs for structure types.
276 struct my_struct_type {
280 struct my_struct_type my_var;
287 typedef struct my_struct_type {
291 my_struct_type my_var
294 Typedefs are problematic because they do not properly hide their underlying type;
295 for example, you need to know if the typedef is the structure itself, as shown above, or a pointer to the structure.
296 In addition, they must be declared exactly once, whereas an incomplete structure type can be mentioned as many times as necessary.
297 Typedefs are difficult to use in stand-alone header files.
298 The header that defines the typedef must be included before the header that uses it, or by the header that uses it (which causes namespace pollution),
299 or there must be a back-door mechanism for obtaining the typedef.
301 Note that #defines used instead of typedefs also are problematic (since they do not propagate the pointer type correctly due to direct text replacement).
302 For example, ``#define pint int *`` does not work as expected, while ``typedef int *pint`` does work.
303 As stated when discussing macros, typedefs should be preferred to macros in cases like this.
305 When convention requires a typedef; make its name match the struct tag.
306 Avoid typedefs ending in ``_t``, except as specified in Standard C or by POSIX.
310 It is recommended to use typedefs to define function pointer types, for reasons of code readability.
311 This is especially true when the function type is used as a parameter to another function.
318 * Definition of a remote launch function.
320 typedef int (lcore_function_t)(void *);
322 /* launch a function of lcore_function_t type */
323 int rte_eal_remote_launch(lcore_function_t *f, void *arg, unsigned slave_id);
332 * Indentation is a hard tab, that is, a tab character, not a sequence of spaces,
336 Global whitespace rule in DPDK, use tabs for indentation, spaces for alignment.
338 * Do not put any spaces before a tab for indentation.
339 * If you have to wrap a long statement, put the operator at the end of the line, and indent again.
340 * For control statements (if, while, etc.), continuation it is recommended that the next line be indented by two tabs, rather than one,
341 to prevent confusion as to whether the second line of the control statement forms part of the statement body or not.
342 Alternatively, the line continuation may use additional spaces to line up to an appropriately point on the preceding line, for example, to align to an opening brace.
346 As with all style guidelines, code should match style already in use in an existing file.
350 while (really_long_variable_name_1 == really_long_variable_name_2 &&
351 var3 == var4){ /* confusing to read as */
352 x = y + z; /* control stmt body lines up with second line of */
353 a = b + c; /* control statement itself if single indent used */
356 if (really_long_variable_name_1 == really_long_variable_name_2 &&
357 var3 == var4){ /* two tabs used */
358 x = y + z; /* statement body no longer lines up */
362 z = a + really + long + statement + that + needs +
363 two + lines + gets + indented + on + the +
364 second + and + subsequent + lines;
367 * Do not add whitespace at the end of a line.
369 * Do not add whitespace or a blank line at the end of a file.
372 Control Statements and Loops
373 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
375 * Include a space after keywords (if, while, for, return, switch).
376 * Do not use braces (``{`` and ``}``) for control statements with zero or just a single statement, unless that statement is more than a single line in which case the braces are permitted.
380 for (p = buf; *p != '\0'; ++p)
385 z = a + really + long + statement + that + needs +
386 two + lines + gets + indented + on + the +
387 second + and + subsequent + lines;
394 val = realloc(val, newsize);
397 * Parts of a for loop may be left empty.
401 for (; cnt < 15; cnt++) {
406 * Closing and opening braces go on the same line as the else keyword.
407 * Braces that are not necessary should be left out.
423 * Do not use spaces after function names.
424 * Commas should have a space after them.
425 * No spaces after ``(`` or ``[`` or preceding the ``]`` or ``)`` characters.
429 error = function(a1, a2);
437 * Unary operators do not require spaces, binary operators do.
438 * Do not use parentheses unless they are required for precedence or unless the statement is confusing without them.
439 However, remember that other people may be more easily confused than you.
444 Exits should be 0 on success, or 1 on failure.
449 * Avoid obvious comments such as
450 * "Exit 0 on success."
457 * Variables should be declared at the start of a block of code rather than in the middle.
458 The exception to this is when the variable is ``const`` in which case the declaration must be at the point of first use/assignment.
459 * When declaring variables in functions, multiple variables per line are OK.
460 However, if multiple declarations would cause the line to exceed a reasonable line length, begin a new set of declarations on the next line rather than using a line continuation.
461 * Be careful to not obfuscate the code by initializing variables in the declarations, only the last variable on a line should be initialized.
462 If multiple variables are to be initialised when defined, put one per line.
463 * Do not use function calls in initializers, except for ``const`` variables.
467 int i = 0, j = 0, k = 0; /* bad, too many initializer */
469 char a = 0; /* OK, one variable per line with initializer */
472 float x, y = 0.0; /* OK, only last variable has initializer */
478 * Casts and sizeof statements are not followed by a space.
479 * Always write sizeof statements with parenthesis.
480 The redundant parenthesis rules do not apply to sizeof(var) instances.
482 C Function Definition, Declaration and Use
483 -------------------------------------------
488 * It is recommended (and generally required by the compiler) that all non-static functions are prototyped somewhere.
489 * Functions local to one source module should be declared static, and should not be prototyped unless absolutely necessary.
490 * Functions used from other parts of code (external API) must be prototyped in the relevant include file.
491 * Function prototypes should be listed in a logical order, preferably alphabetical unless there is a compelling reason to use a different ordering.
492 * Functions that are used locally in more than one module go into a separate header file, for example, "extern.h".
493 * Do not use the ``__P`` macro.
494 * Functions that are part of an external API should be documented using Doxygen-like comments above declarations. See the Doxgen documentation topic for details.
495 * Functions that are part of the external API must have an ``rte_`` prefix on the function name.
496 * Do not use uppercase letters - either in the form of ALL_UPPERCASE, or CamelCase - in function names. Lower-case letters and underscores only.
497 * When prototyping functions, associate names with parameter types, for example:
501 void function1(int fd); /* good */
502 void function2(int); /* bad */
504 * Short function prototypes should be contained on a single line.
505 Longer prototypes, e.g. those with many parameters, can be split across multiple lines.
506 The second and subsequent lines should be further indented as for line statement continuations as described in the previous section.
510 static char *function1(int _arg, const char *_arg2,
514 static void usage(void);
518 Unlike function definitions, the function prototypes do not need to place the function return type on a separate line.
523 * The function type should be on a line by itself preceding the function.
524 * The opening brace of the function body should be on a line by itself.
529 function(int a1, int a2, float fl, int a4)
533 * Do not declare functions inside other functions.
534 ANSI C states that such declarations have file scope regardless of the nesting of the declaration.
535 Hiding file declarations in what appears to be a local scope is undesirable and will elicit complaints from a good compiler.
536 * Old-style (K&R) function declaration should not be used, use ANSI function declarations instead as shown below.
537 * Long argument lists should be wrapped as described above in the function prototypes section.
542 * All major routines should have a comment briefly describing what
543 * they do. The comment before the "main" routine should describe
544 * what the program does.
547 main(int argc, char *argv[])
553 C Statement Style and Conventions
554 ---------------------------------
559 * NULL is the preferred null pointer constant.
560 Use NULL instead of ``(type *)0`` or ``(type *)NULL``, except where the compiler does not know the destination type e.g. for variadic args to a function.
561 * Test pointers against NULL, for example, use:
565 if (p == NULL) /* Good, compare pointer to NULL */
567 if (!p) /* Bad, using ! on pointer */
570 * Do not use ! for tests unless it is a boolean, for example, use:
574 if (*p == '\0') /* check character against (char)0 */
579 * Functions which create objects, or allocate memory, should return pointer types, and NULL on error.
580 The error type should be indicated may setting the variable ``rte_errno`` appropriately.
581 * Functions which work on bursts of packets, such as RX-like or TX-like functions, should return the number of packets handled.
582 * Other functions returning int should generally behave like system calls:
583 returning 0 on success and -1 on error, setting ``rte_errno`` to indicate the specific type of error.
584 * Where already standard in a given library, the alternative error approach may be used where the negative value is not -1 but is instead ``-errno`` if relevant, for example, ``-EINVAL``.
585 Note, however, to allow consistency across functions returning integer or pointer types, the previous approach is preferred for any new libraries.
586 * For functions where no error is possible, the function type should be ``void`` not ``int``.
587 * Routines returning ``void *`` should not have their return values cast to any pointer type.
588 (Typecasting can prevent the compiler from warning about missing prototypes as any implicit definition of a function returns int,
589 which, unlike ``void *``, needs a typecast to assign to a pointer variable.)
593 The above rule about not typecasting ``void *`` applies to malloc, as well as to DPDK functions.
595 * Values in return statements should not be enclosed in parentheses.
600 In the DPDK environment, use the logging interface provided:
604 #define RTE_LOGTYPE_TESTAPP1 RTE_LOGTYPE_USER1
605 #define RTE_LOGTYPE_TESTAPP2 RTE_LOGTYPE_USER2
607 /* enable these logs type */
608 rte_set_log_type(RTE_LOGTYPE_TESTAPP1, 1);
609 rte_set_log_type(RTE_LOGTYPE_TESTAPP2, 1);
611 /* log in debug level */
612 rte_set_log_level(RTE_LOG_DEBUG);
613 RTE_LOG(DEBUG, TESTAPP1, "this is is a debug level message\n");
614 RTE_LOG(INFO, TESTAPP1, "this is is a info level message\n");
615 RTE_LOG(WARNING, TESTAPP1, "this is is a warning level message\n");
617 /* log in info level */
618 rte_set_log_level(RTE_LOG_INFO);
619 RTE_LOG(DEBUG, TESTAPP2, "debug level message (not displayed)\n");
624 * When a test is done in a critical zone (called often or in a data path) the code can use the ``likely()`` and ``unlikely()`` macros to indicate the expected, or preferred fast path.
625 They are expanded as a compiler builtin and allow the developer to indicate if the branch is likely to be taken or not. Example:
629 #include <rte_branch_prediction.h>
635 The use of ``likely()`` and ``unlikely()`` should only be done in performance critical paths,
636 and only when there is a clearly preferred path, or a measured performance increase gained from doing so.
637 These macros should be avoided in non-performance-critical code.
639 Static Variables and Functions
640 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
642 * All functions and variables that are local to a file must be declared as ``static`` because it can often help the compiler to do some optimizations (such as, inlining the code).
643 * Functions that should be inlined should to be declared as ``static inline`` and can be defined in a .c or a .h file.
646 Static functions defined in a header file must be declared as ``static inline`` in order to prevent compiler warnings about the function being unused.
651 The ``const`` attribute should be used as often as possible when a variable is read-only.
656 The ``asm`` and ``volatile`` keywords do not have underscores. The AT&T syntax should be used.
657 Input and output operands should be named to avoid confusion, as shown in the following example:
661 asm volatile("outb %[val], %[port]"
669 * Forever loops are done with for statements, not while statements.
670 * Elements in a switch statement that cascade should have a FALLTHROUGH comment. For example:
674 switch (ch) { /* Indent the switch. */
675 case 'a': /* Don't indent the case. */
676 aflag = 1; /* Indent case body one tab. */
687 Environment or Architecture-specific Sources
688 --------------------------------------------
690 In DPDK and DPDK applications, some code is specific to an architecture (i686, x86_64) or to an executive environment (bsdapp or linuxapp) and so on.
691 As far as is possible, all such instances of architecture or env-specific code should be provided via standard APIs in the EAL.
693 By convention, a file is common if it is not located in a directory indicating that it is specific.
694 For instance, a file located in a subdir of "x86_64" directory is specific to this architecture.
695 A file located in a subdir of "linuxapp" is specific to this execution environment.
699 Code in DPDK libraries and applications should be generic.
700 The correct location for architecture or executive environment specific code is in the EAL.
702 When absolutely necessary, there are several ways to handle specific code:
704 * Use a ``#ifdef`` with the CONFIG option in the C code.
705 This can be done when the differences are small and they can be embedded in the same C file:
707 .. code-block: console
715 * Use the CONFIG option in the Makefile. This is done when the differences are more significant.
716 In this case, the code is split into two separate files that are architecture or environment specific. This should only apply inside the EAL library.
720 As in the linux kernel, the "CONFIG_" prefix is not used in C code.
721 This is only needed in Makefiles or shell scripts.
723 Per Architecture Sources
724 ~~~~~~~~~~~~~~~~~~~~~~~~
726 The following config options can be used:
728 * CONFIG_RTE_ARCH is a string that contains the name of the architecture.
729 * CONFIG_RTE_ARCH_I686, CONFIG_RTE_ARCH_X86_64, CONFIG_RTE_ARCH_X86_64_32 or CONFIG_RTE_ARCH_PPC_64 are defined only if we are building for those architectures.
731 Per Execution Environment Sources
732 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
734 The following config options can be used:
736 * CONFIG_RTE_EXEC_ENV is a string that contains the name of the executive environment.
737 * CONFIG_RTE_EXEC_ENV_BSDAPP or CONFIG_RTE_EXEC_ENV_LINUXAPP are defined only if we are building for this execution environment.
739 Doxygen Documentation
740 ---------------------
742 The API documentation is automatically generated in the DPDK framework.
743 That is why all files that are part of the public API must be documented using Doxygen syntax.
745 The public API comprises functions of DPDK that can be used by an external application that will use the SDK.
746 Only the Doxygen syntax described in the coding rules (this document) should be used in the code.
747 All the Doxygen features are described in the Doxygen manual online.
749 Documenting a Function
750 ~~~~~~~~~~~~~~~~~~~~~~
752 All public functions must be documented. The documentation is placed in the header file, above the declaration of the function.
753 The definition of the function may be documented, but using standard comments (not in doxygen format).
754 The following is an example of function documentation:
759 * Summary here; one sentence on one line (should not exceed 80 chars).
761 * A more detailed description goes here.
763 * A blank line forms a paragraph. There should be no trailing white-space
767 * "@param" is a Doxygen directive to describe a function parameter. Like
768 * some other directives, it takes a term/summary on the same line and a
769 * description (this text) indented by 2 spaces on the next line. All
770 * descriptive text should wrap at 80 chars, without going over.
771 * Newlines are NOT supported within directives; if a newline would be
772 * before this text, it would be appended to the general description above.
774 * There should be no newline between multiple directives (of the same
778 * "@return" is a different Doxygen directive to describe the return value
779 * of a function, if there is any.
781 int rte_foo(int first, int second)
787 Each public file may start with a comment describing what the file does. For example:
793 * This file describes the coding rules of RTE.
795 * It contains the coding rules of C code, ASM code, reStructured
796 * Text documentation, and of course how to use doxygen to document
801 Documenting Constants and Variables
802 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
809 * The definition of a funny TRUE.
813 #define TRUE 1 /**< another way to document a macro */
816 * Frequency of the HPET counter in Hz
818 * @see rte_eal_hpet_init()
820 extern uint64_t eal_hpet_resolution_hz;
823 Documenting Structures
824 ~~~~~~~~~~~~~~~~~~~~~~
826 Public structures should also be documented.
827 The ``/**<`` sequence can be used to documented the fields of the structure, as shown in the following example:
832 * Structure describing a memzone, which is a contiguous portions of
833 * physical memory identified by a name.
837 #define MEMZONE_NAMESIZE 32
838 char name[MEMZONE_NAMESIZE]; /**< name of the memory zone */
840 phys_addr_t phys_addr; /**< start physical address */
841 void *addr; /**< start virtual address */
842 uint64_t len; /**< len of the memzone */
844 int socket_id; /**< NUMA socket id */
851 The @see keyword can be used to highlight a link to an existing function, file, or URL.
852 This directive should be placed on one line, without anything else, at the bottom of the documentation header.
857 * (documentation of function, file, ...)