### Kconfig File Indentation Example Source: https://www.kernel.org/doc/Documentation/process/coding-style This example demonstrates the indentation rules for Kconfig files. Lines within a 'config' definition are indented with one tab, and help text is further indented by two spaces. ```kconfig config AUDIT bool "Auditing support" depends on NET help Enable auditing infrastructure that can be used with another kernel subsystem, such as SELinux (which requires this for logging of avc messages output). Does not do system-call ``` -------------------------------- ### C: Editor Modelines Example (Vim) Source: https://www.kernel.org/doc/Documentation/process/coding-style An example of an editor modeline for Vim, used to configure editor settings like indentation. These should not be included in kernel source files. ```c /* vim:set sw=8 noet */ ``` -------------------------------- ### Kernel Configuration Option Example Source: https://www.kernel.org/doc/Documentation/process/coding-style Example of a kernel configuration option, specifically for ADFS write support. It demonstrates the 'config', 'bool', and 'depends on' keywords, indicating a feature that is potentially dangerous and requires another configuration to be enabled. ```c config ADFS_FS_RW bool "ADFS write support (DANGEROUS)" depends on ADFS_FS ... ``` -------------------------------- ### C Function Prototype Ordering Example Source: https://www.kernel.org/doc/Documentation/process/coding-style Demonstrates the preferred order of elements for C function prototypes in the Linux kernel. This includes storage class, attributes, return type, function name, parameters, and parameter attributes. ```c __init void * __must_check action(enum magic value, size_t size, u8 count, char *fmt, ...) __printf(4, 5) __malloc; ``` -------------------------------- ### C Function Export Example Source: https://www.kernel.org/doc/Documentation/process/coding-style Demonstrates how to define a C function and export it using the EXPORT_SYMBOL macro. This is typically used for functions intended to be available outside the current module. ```c int system_is_up(void) { return system_state == SYSTEM_RUNNING; } EXPORT_SYMBOL(system_is_up); ``` -------------------------------- ### C: Editor Modelines Example (Emacs) Source: https://www.kernel.org/doc/Documentation/process/coding-style Examples of editor modelines for Emacs, which allow editors to interpret configuration information embedded within source files. These should not be included in kernel source files. ```c -*- mode: c -*- ``` ```c /* Local Variables: compile-command: "gcc -DMAGIC_DEBUG_FLAG foo.c" End: */ ``` -------------------------------- ### C Function with Centralized Exit using goto Source: https://www.kernel.org/doc/Documentation/process/coding-style Shows an example of using the goto statement in C for centralized function exiting, particularly when common cleanup operations are needed. It highlights the importance of descriptive label names. ```c int fun(int a) { int result = 0; char *buffer; buffer = kmalloc(SIZE, GFP_KERNEL); if (!buffer) return -ENOMEM; if (condition1) { while (loop1) { ... } result = 1; goto out_free_buffer; } ... out_free_buffer: kfree(buffer); return result; } ``` -------------------------------- ### Brace Placement for Functions in C Source: https://www.kernel.org/doc/Documentation/process/coding-style Details the specific brace placement for function definitions in C according to the Linux kernel style guide. The opening brace is placed on the next line, while the closing brace is on its own line, except when followed by a continuation. ```c int function(int x) { body of function } ``` ```c do { body of do-loop } while (condition); ``` ```c if (x == y) { .. } else if (x > y) { ... } else { .... } ``` -------------------------------- ### Defining Constants with Macros in C Source: https://www.kernel.org/doc/Documentation/process/coding-style Demonstrates how to define constants using macros in C. It shows a simple macro definition for a hexadecimal value and emphasizes that macro names for constants should be capitalized. ```c #define CONSTANT 0x12345 ``` -------------------------------- ### Loop Statements: Brace Placement in C Source: https://www.kernel.org/doc/Documentation/process/coding-style Illustrates the required brace placement for loops in C when the loop body contains more than a single simple statement. This ensures clarity and proper execution of nested logic. ```c while (condition) { if (test) do_something(); } ``` -------------------------------- ### Conditional Statements: Brace Placement in C Source: https://www.kernel.org/doc/Documentation/process/coding-style Demonstrates the preferred brace placement for conditional statements in C. Single-statement blocks do not require braces, but if one branch uses braces, both should. This improves readability and consistency. ```c if (condition) action(); ``` ```c if (condition) do_this(); else do_that(); ``` ```c if (condition) { do_this(); do_that(); } else { otherwise(); } ``` -------------------------------- ### C Error Handling with Multiple goto Labels Source: https://www.kernel.org/doc/Documentation/process/coding-style Demonstrates a corrected approach to error handling in C using multiple goto labels to prevent 'one err bugs'. This ensures proper cleanup for different error paths. ```c err_free_bar: kfree(foo->bar); err_free_foo: kfree(foo); return ret; ``` -------------------------------- ### Switch Statement Indentation in C Source: https://www.kernel.org/doc/Documentation/process/coding-style Demonstrates the preferred indentation style for switch statements in C, aligning 'switch' and 'case' labels in the same column for better readability. This avoids excessive indentation levels. ```c switch (suffix) { case 'G': case 'g': mem <<= 30; break; case 'M': case 'm': mem <<= 20; break; case 'K': case 'k': mem <<= 10; fallthrough; default: break; } ``` -------------------------------- ### Brace Placement for Statements in C Source: https://www.kernel.org/doc/Documentation/process/coding-style Shows the K&R style for placing braces in C code, where the opening brace is on the same line as the statement and the closing brace is on its own line. This applies to if, switch, for, while, and do statements. ```c if (x is true) { we do y } ``` ```c switch (action) { case KOBJ_ADD: return "add"; case KOBJ_REMOVE: return "remove"; case KOBJ_CHANGE: return "change"; default: return NULL; } ``` -------------------------------- ### Macro Affecting Control Flow (Bad Practice) in C Source: https://www.kernel.org/doc/Documentation/process/coding-style An example of a macro that negatively affects control flow by returning from the calling function. This is strongly discouraged as it can confuse code parsers and readers. ```c #define FOO(x) \ do { \ if (blah(x) < 0) \ return -EBUGGERED; \ } while (0) ``` -------------------------------- ### C Multi-line Comment Style Source: https://www.kernel.org/doc/Documentation/process/coding-style Presents the preferred style for multi-line comments in the Linux kernel source code. This style uses asterisks at the beginning of each line for readability. ```c /* * This is the preferred style for multi-line * comments in the Linux kernel source code. * Please use it consistently. * ``` -------------------------------- ### Using 'indent' for C Code Formatting Source: https://www.kernel.org/doc/Documentation/process/coding-style This section describes how to use the 'indent' command-line utility to format C code according to the K&R style with 8-character indents. It suggests using the '-kr -i8' options or the 'scripts/Lindent' script for formatting. ```bash indent -kr -i8 ``` -------------------------------- ### C: Array Size Calculation Macro Source: https://www.kernel.org/doc/Documentation/process/coding-style This macro calculates the number of elements in an array. It is defined in `array_size.h` and should be used instead of manual calculation to ensure correctness and consistency. ```c #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) ``` -------------------------------- ### Inline Assembly with Multiple Instructions (C) Source: https://www.kernel.org/doc/Documentation/process/coding-style Demonstrates how to write a single inline assembly statement with multiple instructions in C. Each instruction should be on a new line within a separate quoted string, with '\n\t' appended to all but the last string to ensure proper indentation in the assembly output. ```c asm ("magic %reg1, #42\n\t" "more_magic %reg2, %reg3" : /* outputs */ : /* inputs */ : /* clobbers */); ``` -------------------------------- ### C Function Definition with Attributes Source: https://www.kernel.org/doc/Documentation/process/coding-style Illustrates the placement of function parameter attributes in a C function definition, which differs from declarations. Attributes like __printf are moved after storage class attributes. ```c static __always_inline __init __printf(4, 5) void * __must_check action(enum magic value, size_t size, u8 count, char *fmt, ...) __malloc { ... } ``` -------------------------------- ### Macro with Expression in Parentheses for Precedence in C Source: https://www.kernel.org/doc/Documentation/process/coding-style Illustrates the importance of enclosing expressions in parentheses within macros, especially when defining constants or using parameters, to avoid operator precedence issues. ```c #define CONSTANT 0x4000 #define CONSTEXP (CONSTANT | 3) ``` -------------------------------- ### Macro with Multiple Statements in C Source: https://www.kernel.org/doc/Documentation/process/coding-style Illustrates the correct way to define macros that contain multiple statements in C. It uses a 'do-while(0)' block to ensure proper execution and avoid potential issues with control flow. ```c #define macrofun(a, b, c) \ do { \ if (a == 5) \ do_this(b, c); \ } while (0) ``` -------------------------------- ### Keyword Spacing in C Source: https://www.kernel.org/doc/Documentation/process/coding-style Explains the spacing rules around C keywords. Spaces are generally used after keywords like 'if', 'switch', 'for', 'do', and 'while', but not after 'sizeof', 'typeof', 'alignof', and '__attribute__'. ```c s = sizeof(struct file); ``` -------------------------------- ### C: Structure Member Size Calculation Macro Source: https://www.kernel.org/doc/Documentation/process/coding-style This macro calculates the size of a specific member within a structure. It is defined in `stddef.h` and promotes code clarity and maintainability. ```c #define sizeof_field(t, f) (sizeof(((t*)0)->f)) ``` -------------------------------- ### Inline Function Usage Guidelines in Kernel Source: https://www.kernel.org/doc/Documentation/process/coding-style Advises against excessive use of the 'inline' keyword, suggesting a limit of 3 lines per function. Exceptions exist for functions with compile-time constant parameters that can be fully optimized. ```c // Generally avoid inline for functions longer than 3 lines // inline int complex_function(int a, int b) { ... } // Exception: Functions optimizable at compile time due to constant parameters // inline int optimized_function(const int constant_val) { // return constant_val * 2; // } // GCC can inline static functions automatically; manual 'inline' is often unnecessary. ``` -------------------------------- ### Preferred Memory Allocation Patterns in Kernel Source: https://www.kernel.org/doc/Documentation/process/coding-style Demonstrates preferred methods for allocating memory for single structures and arrays using kmalloc, kmalloc_array, and kcalloc. These functions include overflow checks and emit stack dumps on failure. ```c // Preferred for single structure allocation struct my_struct *p = kmalloc(sizeof(*p), GFP_KERNEL); // Preferred for array allocation void *array = kmalloc_array(n, sizeof(element_type), GFP_KERNEL); // Preferred for zeroed array allocation void *zeroed_array = kcalloc(n, sizeof(element_type), GFP_KERNEL); ``` -------------------------------- ### Single vs. Multiple Statements per Line in C Source: https://www.kernel.org/doc/Documentation/process/coding-style Illustrates the Linux kernel's coding style regarding single-line statements and the use of braces for multiple statements. It discourages multiple statements on one line and the use of commas to avoid braces. ```c if (condition) do_this; do_something_everytime; ``` ```c if (condition) do_this(), do_that(); ``` ```c if (condition) { do_this(); do_that(); } ``` -------------------------------- ### Kernel Message Logging with dev_printk Macros Source: https://www.kernel.org/doc/Documentation/process/coding-style Utilizes driver model diagnostic macros from for device-specific messages and for general messages. Prefer debug messages (dev_dbg, pr_debug) for normal operation. ```c #include #include // For device-specific messages dev_err(device, "Error message\n"); dev_warn(device, "Warning message\n"); dev_info(device, "Info message\n"); // For general messages pr_notice("Notice message\n"); pr_info("Info message\n"); pr_warn("Warning message\n"); pr_err("Error message\n"); // Debug messages (compiled out by default) pr_debug("Debug message\n"); dev_dbg(device, "Device debug message\n"); // Unconditional debug message printk(KERN_DEBUG "Unconditional debug message\n"); ``` -------------------------------- ### Pointer Declaration Spacing in C Source: https://www.kernel.org/doc/Documentation/process/coding-style Defines the preferred spacing for pointer declarations in C. The asterisk (*) should be adjacent to the data or function name, not the type name, to clearly indicate it's a pointer. ```c char *linux_banner; ``` ```c unsigned long long memparse(char *ptr, char **retptr); ``` ```c char *match_strdup(substring_t *s); ``` -------------------------------- ### Static Inline Function for Parameter Handling in C Source: https://www.kernel.org/doc/Documentation/process/coding-style Shows an alternative to function-like macros with unused parameters. Using a static inline function is preferred to avoid unused variable warnings and improve code clarity and documentation. ```c static inline void fun(struct foo *foo) { } ``` -------------------------------- ### Conditional Compilation using IS_ENABLED (C) Source: https://www.kernel.org/doc/Documentation/process/coding-style Shows how to use the IS_ENABLED macro in C to convert a Kconfig symbol into a C boolean expression for conditional compilation. This allows the compiler to optimize out unused code blocks without runtime overhead, while still enabling syntax checking. ```c if (IS_ENABLED(CONFIG_SOMETHING)) { ... } ``` -------------------------------- ### Conditional Compilation End Comment (C) Source: https://www.kernel.org/doc/Documentation/process/coding-style Illustrates the practice of adding a comment after an #endif directive in C code. This comment should specify the conditional expression used, making it easier to understand the context of the conditional block. ```c #ifdef CONFIG_SOMETHING ... #endif /* CONFIG_SOMETHING */ ``` -------------------------------- ### Deprecated Macro for Parameter Evaluation in C Source: https://www.kernel.org/doc/Documentation/process/coding-style Demonstrates a macro pattern that should be avoided for evaluating parameters, especially when side effects are involved. The 'cast to (void)' approach is considered outdated and less safe than static inline functions. ```c /* * Avoid doing this whenever possible and instead opt for static * inline functions */ #define macrofun(foo) do { (void) (foo); } while (0) ``` -------------------------------- ### Kernel Function Return Value Conventions Source: https://www.kernel.org/doc/Documentation/process/coding-style Highlights the importance of consistent return value conventions for indicating success or failure. It contrasts error-code integers (-Exxx = failure, 0 = success) with boolean representations (0 = failure, non-zero = success) to prevent bugs. ```c // Error-code integer convention (preferred for many kernel functions) // Returns negative error code on failure, 0 on success. // int function_that_returns_error_code(void); // Boolean convention (less common for kernel errors, more for flags) // Returns 0 on failure, non-zero on success. // int function_that_returns_boolean(void); ``` -------------------------------- ### Configure Emacs for C Kernel Coding Style Source: https://www.kernel.org/doc/Documentation/process/coding-style This Elisp code snippet configures GNU Emacs to follow the Linux kernel's C coding style. It sets indentation to 8 spaces and adjusts various alignment rules for C constructs. This configuration is applied to C files within a specified directory. ```elisp (defun c-lineup-arglist-tabs-only (ignored) "Line up argument lists by tabs, not spaces" (let* ((anchor (c-langelem-pos c-syntactic-element)) (column (c-langelem-2nd-pos c-syntactic-element)) (offset (- (1+ column) anchor)) (steps (floor offset c-basic-offset))) (* (max steps 1) c-basic-offset))) (dir-locals-set-class-variables 'linux-kernel '((c-mode . ( (c-basic-offset . 8) (c-label-minimum-indentation . 0) (c-offsets-alist . ( (arglist-close . c-lineup-arglist-tabs-only) (arglist-cont-nonempty . (c-lineup-gcc-asm-reg c-lineup-arglist-tabs-only)) (arglist-intro . +) (brace-list-intro . +) (c . c-lineup-C-comments) (case-label . 0) (comment-intro . c-lineup-comment) (cpp-define-intro . +) (cpp-macro . -1000) (cpp-macro-cont . +) (defun-block-intro . +) (else-clause . 0) (func-decl-cont . +) (inclass . +) (inher-cont . c-lineup-multi-inher) (knr-argdecl-intro . 0) (label . -1000) (statement . 0) (statement-block-intro . +) (statement-case-intro . +) (statement-cont . +) (substatement . +) )) (indent-tabs-mode . t) (show-trailing-whitespace . t) )))) (dir-locals-set-directory-class (expand-file-name("~/src/linux-trees")) 'linux-kernel) ``` -------------------------------- ### Macro with Local Variable for Namespace Safety in C Source: https://www.kernel.org/doc/Documentation/process/coding-style Shows a technique to prevent namespace collisions when defining local variables within macros. Using a more specific name like '__foo_ret' reduces the likelihood of conflicts with existing variables. ```c #define FOO(x) \ ( \ __typeof(x) ret = calc_ret(x); \ (ret)); ``` -------------------------------- ### Operator Spacing in C Source: https://www.kernel.org/doc/Documentation/process/coding-style Details the spacing rules for operators in C. Binary and ternary operators require a space on each side, while unary operators (prefix and postfix) do not have spaces around them. Structure member operators also have no surrounding spaces. ```c s = sizeof( struct file ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.