860 lines · 30.6 KB · Text
RawDownload
                (setq indent-tabs-mode t)                (c-set-style "linux-tabs-only"))))) This will make emacs go better with the kernel coding style for Cfiles below ~/src/linux-trees. But even if you fail in getting emacs to do sane formatting, noteverything is lost: use "indent". Now, again, GNU indent has the same brain-dead settings that GNU emacshas, which is why you need to give it a few command line options.However, that's not too bad, because even the makers of GNU indentrecognize the authority of K&R (the GNU people aren't evil, they arejust severely misguided in this matter), so you just give indent theoptions "-kr -i8" (stands for "K&R, 8 character indents"), or use"scripts/Lindent", which indents in the latest style. "indent" has a lot of options, and especially when it comes to commentre-formatting you may want to take a look at the man page.  Butremember: "indent" is not a fix for bad programming.  		Chapter 10: Kconfig configuration files For all of the Kconfig* configuration files throughout the source tree,the indentation is somewhat different.  Lines under a "config" definitionare indented with one tab, while help text is indented an additional twospaces.  Example: 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	  auditing without CONFIG_AUDITSYSCALL. Features that might still be considered unstable should be defined asdependent on "EXPERIMENTAL": config SLUB	depends on EXPERIMENTAL && !ARCH_USES_SLAB_PAGE_STRUCT	bool "SLUB (Unqueued Allocator)"	... while seriously dangerous features (such as write support for certainfilesystems) should advertise this prominently in their prompt string: config ADFS_FS_RW	bool "ADFS write support (DANGEROUS)"	depends on ADFS_FS	... For full documentation on the configuration files, see the fileDocumentation/kbuild/kconfig-language.txt.  		Chapter 11: Data structures Data structures that have visibility outside the single-threadedenvironment they are created and destroyed in should always havereference counts.  In the kernel, garbage collection doesn't exist (andoutside the kernel garbage collection is slow and inefficient), whichmeans that you absolutely _have_ to reference count all your uses. Reference counting means that you can avoid locking, and allows multipleusers to have access to the data structure in parallel - and not havingto worry about the structure suddenly going away from under them justbecause they slept or did something else for a while. Note that locking is _not_ a replacement for reference counting.Locking is used to keep data structures coherent, while referencecounting is a memory management technique.  Usually both are needed, andthey are not to be confused with each other. Many data structures can indeed have two levels of reference counting,when there are users of different "classes".  The subclass count countsthe number of subclass users, and decrements the global count just oncewhen the subclass count goes to zero. Examples of this kind of "multi-level-reference-counting" can be found inmemory management ("struct mm_struct": mm_users and mm_count), and infilesystem code ("struct super_block": s_count and s_active). Remember: if another thread can find your data structure, and you don'thave a reference count on it, you almost certainly have a bug.  		Chapter 12: Macros, Enums and RTL Names of macros defining constants and labels in enums are capitalized. #define CONSTANT 0x12345 Enums are preferred when defining several related constants. CAPITALIZED macro names are appreciated but macros resembling functionsmay be named in lower case. Generally, inline functions are preferable to macros resembling functions. Macros with multiple statements should be enclosed in a do - while block: #define macrofun(a, b, c) 			\	do {					\		if (a == 5)			\			do_this(b, c);		\	} while (0) Things to avoid when using macros: 1) macros that affect control flow: #define FOO(x)					\	do {					\		if (blah(x) < 0)		\			return -EBUGGERED;	\	} while(0) is a _very_ bad idea.  It looks like a function call but exits the "calling"function; don't break the internal parsers of those who will read the code. 2) macros that depend on having a local variable with a magic name: #define FOO(val) bar(index, val) might look like a good thing, but it's confusing as hell when one reads thecode and it's prone to breakage from seemingly innocent changes. 3) macros with arguments that are used as l-values: FOO(x) = y; willbite you if somebody e.g. turns FOO into an inline function. 4) forgetting about precedence: macros defining constants using expressionsmust enclose the expression in parentheses. Beware of similar issues withmacros using parameters. #define CONSTANT 0x4000#define CONSTEXP (CONSTANT | 3) The cpp manual deals with macros exhaustively. The gcc internals manual alsocovers RTL which is used frequently with assembly language in the kernel.  		Chapter 13: Printing kernel messages Kernel developers like to be seen as literate. Do mind the spellingof kernel messages to make a good impression. Do not use crippledwords like "dont"; use "do not" or "don't" instead.  Make the messagesconcise, clear, and unambiguous. Kernel messages do not have to be terminated with a period. Printing numbers in parentheses (%d) adds no value and should be avoided. There are a number of driver model diagnostic macros in <linux/device.h>which you should use to make sure messages are matched to the right deviceand driver, and are tagged with the right level:  dev_err(), dev_warn(),dev_info(), and so forth.  For messages that aren't associated with aparticular device, <linux/printk.h> defines pr_debug() and pr_info(). Coming up with good debugging messages can be quite a challenge; and onceyou have them, they can be a huge help for remote troubleshooting.  Suchmessages should be compiled out when the DEBUG symbol is not defined (thatis, by default they are not included).  When you use dev_dbg() or pr_debug(),that's automatic.  Many subsystems have Kconfig options to turn on -DDEBUG.A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to theones already enabled by DEBUG.  		Chapter 14: Allocating memory The kernel provides the following general purpose memory allocators:kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), andvzalloc().  Please refer to the API documentation for further informationabout them. The preferred form for passing a size of a struct is the following: 	p = kmalloc(sizeof(*p), ...); The alternative form where struct name is spelled out hurts readability andintroduces an opportunity for a bug when the pointer variable type is changedbut the corresponding sizeof that is passed to a memory allocator is not. Casting the return value which is a void pointer is redundant. The conversionfrom void pointer to any other pointer type is guaranteed by the C programminglanguage. The preferred form for allocating an array is the following: 	p = kmalloc_array(n, sizeof(...), ...); The preferred form for allocating a zeroed array is the following: 	p = kcalloc(n, sizeof(...), ...); Both forms check for overflow on the allocation size n * sizeof(...),and return NULL if that occurred.  		Chapter 15: The inline disease There appears to be a common misperception that gcc has a magic "make mefaster" speedup option called "inline". While the use of inlines can beappropriate (for example as a means of replacing macros, see Chapter 12), itvery often is not. Abundant use of the inline keyword leads to a much biggerkernel, which in turn slows the system as a whole down, due to a biggericache footprint for the CPU and simply because there is less memoryavailable for the pagecache. Just think about it; a pagecache miss causes adisk seek, which easily takes 5 milliseconds. There are a LOT of cpu cyclesthat can go into these 5 milliseconds. A reasonable rule of thumb is to not put inline at functions that have morethan 3 lines of code in them. An exception to this rule are the cases wherea parameter is known to be a compiletime constant, and as a result of thisconstantness you *know* the compiler will be able to optimize most of yourfunction away at compile time. For a good example of this later case, seethe kmalloc() inline function. Often people argue that adding inline to functions that are static and usedonly once is always a win since there is no space tradeoff. While this istechnically correct, gcc is capable of inlining these automatically withouthelp, and the maintenance issue of removing the inline when a second userappears outweighs the potential value of the hint that tells gcc to dosomething it would have done anyway.  		Chapter 16: Function return values and names Functions can return values of many different kinds, and one of themost common is a value indicating whether the function succeeded orfailed.  Such a value can be represented as an error-code integer(-Exxx = failure, 0 = success) or a "succeeded" boolean (0 = failure,non-zero = success). Mixing up these two sorts of representations is a fertile source ofdifficult-to-find bugs.  If the C language included a strong distinctionbetween integers and booleans then the compiler would find these mistakesfor us... but it doesn't.  To help prevent such bugs, always follow thisconvention: 	If the name of a function is an action or an imperative command,	the function should return an error-code integer.  If the name	is a predicate, the function should return a "succeeded" boolean. For example, "add work" is a command, and the add_work() function returns 0for success or -EBUSY for failure.  In the same way, "PCI device present" isa predicate, and the pci_dev_present() function returns 1 if it succeeds infinding a matching device or 0 if it doesn't. All EXPORTed functions must respect this convention, and so should allpublic functions.  Private (static) functions need not, but it isrecommended that they do. Functions whose return value is the actual result of a computation, ratherthan an indication of whether the computation succeeded, are not subject tothis rule.  Generally they indicate failure by returning some out-of-rangeresult.  Typical examples would be functions that return pointers; they useNULL or the ERR_PTR mechanism to report failure.  		Chapter 17:  Don't re-invent the kernel macros The header file include/linux/kernel.h contains a number of macros thatyou should use, rather than explicitly coding some variant of them yourself.For example, if you need to calculate the length of an array, take advantageof the macro   #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) Similarly, if you need to calculate the size of some structure member, use   #define FIELD_SIZEOF(t, f) (sizeof(((t*)0)->f)) There are also min() and max() macros that do strict type checking if youneed them.  Feel free to peruse that header file to see what else is alreadydefined that you shouldn't reproduce in your code.  		Chapter 18:  Editor modelines and other cruft Some editors can interpret configuration information embedded in source files,indicated with special markers.  For example, emacs interprets lines markedlike this: -*- mode: c -*- Or like this: /*Local Variables:compile-command: "gcc -DMAGIC_DEBUG_FLAG foo.c"End:*/ Vim interprets markers that look like this: /* vim:set sw=8 noet */ Do not include any of these in source files.  People have their own personaleditor configurations, and your source files should not override them.  Thisincludes markers for indentation and mode configuration.  People may use theirown custom mode, or may have some other magic method for making indentationwork correctly.  		Chapter 19:  Inline assembly In architecture-specific code, you may need to use inline assembly to interfacewith CPU or platform functionality.  Don't hesitate to do so when necessary.However, don't use inline assembly gratuitously when C can do the job.  You canand should poke hardware from C when possible. Consider writing simple helper functions that wrap common bits of inlineassembly, rather than repeatedly writing them with slight variations.  Rememberthat inline assembly can use C parameters. Large, non-trivial assembly functions should go in .S files, with correspondingC prototypes defined in C header files.  The C prototypes for assemblyfunctions should use "asmlinkage". You may need to mark your asm statement as volatile, to prevent GCC fromremoving it if GCC doesn't notice any side effects.  You don't always need todo so, though, and doing so unnecessarily can limit optimization. When writing a single inline assembly statement containing multipleinstructions, put each instruction on a separate line in a separate quotedstring, and end each string except the last with \n\t to properly indent thenext instruction in the assembly output: 	asm ("magic %reg1, #42\n\t"	     "more_magic %reg2, %reg3"	     : /* outputs */ : /* inputs */ : /* clobbers */);   		Appendix I: References The C Programming Language, Second Editionby Brian W. Kernighan and Dennis M. Ritchie.Prentice Hall, Inc., 1988.ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).URL: http://cm.bell-labs.com/cm/cs/cbook/ The Practice of Programmingby Brian W. Kernighan and Rob Pike.Addison-Wesley, Inc., 1999.ISBN 0-201-61586-X.URL: http://cm.bell-labs.com/cm/cs/tpop/ GNU manuals - where in compliance with K&R and this text - for cpp, gcc,gcc internals and indent, all available from http://www.gnu.org/manual/ WG14 is the international standardization working group for the programminglanguage C, URL: http://www.open-std.org/JTC1/SC22/WG14/ Kernel CodingStyle, by greg@kroah.com at OLS 2002:http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/ 

Lines 501–860 of 860. Previous lines