4.Coding 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. 4: GETTING THE CODE RIGHT
  2. While there is much to be said for a solid and community-oriented design
  3. process, the proof of any kernel development project is in the resulting
  4. code. It is the code which will be examined by other developers and merged
  5. (or not) into the mainline tree. So it is the quality of this code which
  6. will determine the ultimate success of the project.
  7. This section will examine the coding process. We'll start with a look at a
  8. number of ways in which kernel developers can go wrong. Then the focus
  9. will shift toward doing things right and the tools which can help in that
  10. quest.
  11. 4.1: PITFALLS
  12. * Coding style
  13. The kernel has long had a standard coding style, described in
  14. Documentation/CodingStyle. For much of that time, the policies described
  15. in that file were taken as being, at most, advisory. As a result, there is
  16. a substantial amount of code in the kernel which does not meet the coding
  17. style guidelines. The presence of that code leads to two independent
  18. hazards for kernel developers.
  19. The first of these is to believe that the kernel coding standards do not
  20. matter and are not enforced. The truth of the matter is that adding new
  21. code to the kernel is very difficult if that code is not coded according to
  22. the standard; many developers will request that the code be reformatted
  23. before they will even review it. A code base as large as the kernel
  24. requires some uniformity of code to make it possible for developers to
  25. quickly understand any part of it. So there is no longer room for
  26. strangely-formatted code.
  27. Occasionally, the kernel's coding style will run into conflict with an
  28. employer's mandated style. In such cases, the kernel's style will have to
  29. win before the code can be merged. Putting code into the kernel means
  30. giving up a degree of control in a number of ways - including control over
  31. how the code is formatted.
  32. The other trap is to assume that code which is already in the kernel is
  33. urgently in need of coding style fixes. Developers may start to generate
  34. reformatting patches as a way of gaining familiarity with the process, or
  35. as a way of getting their name into the kernel changelogs - or both. But
  36. pure coding style fixes are seen as noise by the development community;
  37. they tend to get a chilly reception. So this type of patch is best
  38. avoided. It is natural to fix the style of a piece of code while working
  39. on it for other reasons, but coding style changes should not be made for
  40. their own sake.
  41. The coding style document also should not be read as an absolute law which
  42. can never be transgressed. If there is a good reason to go against the
  43. style (a line which becomes far less readable if split to fit within the
  44. 80-column limit, for example), just do it.
  45. * Abstraction layers
  46. Computer Science professors teach students to make extensive use of
  47. abstraction layers in the name of flexibility and information hiding.
  48. Certainly the kernel makes extensive use of abstraction; no project
  49. involving several million lines of code could do otherwise and survive.
  50. But experience has shown that excessive or premature abstraction can be
  51. just as harmful as premature optimization. Abstraction should be used to
  52. the level required and no further.
  53. At a simple level, consider a function which has an argument which is
  54. always passed as zero by all callers. One could retain that argument just
  55. in case somebody eventually needs to use the extra flexibility that it
  56. provides. By that time, though, chances are good that the code which
  57. implements this extra argument has been broken in some subtle way which was
  58. never noticed - because it has never been used. Or, when the need for
  59. extra flexibility arises, it does not do so in a way which matches the
  60. programmer's early expectation. Kernel developers will routinely submit
  61. patches to remove unused arguments; they should, in general, not be added
  62. in the first place.
  63. Abstraction layers which hide access to hardware - often to allow the bulk
  64. of a driver to be used with multiple operating systems - are especially
  65. frowned upon. Such layers obscure the code and may impose a performance
  66. penalty; they do not belong in the Linux kernel.
  67. On the other hand, if you find yourself copying significant amounts of code
  68. from another kernel subsystem, it is time to ask whether it would, in fact,
  69. make sense to pull out some of that code into a separate library or to
  70. implement that functionality at a higher level. There is no value in
  71. replicating the same code throughout the kernel.
  72. * #ifdef and preprocessor use in general
  73. The C preprocessor seems to present a powerful temptation to some C
  74. programmers, who see it as a way to efficiently encode a great deal of
  75. flexibility into a source file. But the preprocessor is not C, and heavy
  76. use of it results in code which is much harder for others to read and
  77. harder for the compiler to check for correctness. Heavy preprocessor use
  78. is almost always a sign of code which needs some cleanup work.
  79. Conditional compilation with #ifdef is, indeed, a powerful feature, and it
  80. is used within the kernel. But there is little desire to see code which is
  81. sprinkled liberally with #ifdef blocks. As a general rule, #ifdef use
  82. should be confined to header files whenever possible.
  83. Conditionally-compiled code can be confined to functions which, if the code
  84. is not to be present, simply become empty. The compiler will then quietly
  85. optimize out the call to the empty function. The result is far cleaner
  86. code which is easier to follow.
  87. C preprocessor macros present a number of hazards, including possible
  88. multiple evaluation of expressions with side effects and no type safety.
  89. If you are tempted to define a macro, consider creating an inline function
  90. instead. The code which results will be the same, but inline functions are
  91. easier to read, do not evaluate their arguments multiple times, and allow
  92. the compiler to perform type checking on the arguments and return value.
  93. * Inline functions
  94. Inline functions present a hazard of their own, though. Programmers can
  95. become enamored of the perceived efficiency inherent in avoiding a function
  96. call and fill a source file with inline functions. Those functions,
  97. however, can actually reduce performance. Since their code is replicated
  98. at each call site, they end up bloating the size of the compiled kernel.
  99. That, in turn, creates pressure on the processor's memory caches, which can
  100. slow execution dramatically. Inline functions, as a rule, should be quite
  101. small and relatively rare. The cost of a function call, after all, is not
  102. that high; the creation of large numbers of inline functions is a classic
  103. example of premature optimization.
  104. In general, kernel programmers ignore cache effects at their peril. The
  105. classic time/space tradeoff taught in beginning data structures classes
  106. often does not apply to contemporary hardware. Space *is* time, in that a
  107. larger program will run slower than one which is more compact.
  108. More recent compilers take an increasingly active role in deciding whether
  109. a given function should actually be inlined or not. So the liberal
  110. placement of "inline" keywords may not just be excessive; it could also be
  111. irrelevant.
  112. * Locking
  113. In May, 2006, the "Devicescape" networking stack was, with great
  114. fanfare, released under the GPL and made available for inclusion in the
  115. mainline kernel. This donation was welcome news; support for wireless
  116. networking in Linux was considered substandard at best, and the Devicescape
  117. stack offered the promise of fixing that situation. Yet, this code did not
  118. actually make it into the mainline until June, 2007 (2.6.22). What
  119. happened?
  120. This code showed a number of signs of having been developed behind
  121. corporate doors. But one large problem in particular was that it was not
  122. designed to work on multiprocessor systems. Before this networking stack
  123. (now called mac80211) could be merged, a locking scheme needed to be
  124. retrofitted onto it.
  125. Once upon a time, Linux kernel code could be developed without thinking
  126. about the concurrency issues presented by multiprocessor systems. Now,
  127. however, this document is being written on a dual-core laptop. Even on
  128. single-processor systems, work being done to improve responsiveness will
  129. raise the level of concurrency within the kernel. The days when kernel
  130. code could be written without thinking about locking are long past.
  131. Any resource (data structures, hardware registers, etc.) which could be
  132. accessed concurrently by more than one thread must be protected by a lock.
  133. New code should be written with this requirement in mind; retrofitting
  134. locking after the fact is a rather more difficult task. Kernel developers
  135. should take the time to understand the available locking primitives well
  136. enough to pick the right tool for the job. Code which shows a lack of
  137. attention to concurrency will have a difficult path into the mainline.
  138. * Regressions
  139. One final hazard worth mentioning is this: it can be tempting to make a
  140. change (which may bring big improvements) which causes something to break
  141. for existing users. This kind of change is called a "regression," and
  142. regressions have become most unwelcome in the mainline kernel. With few
  143. exceptions, changes which cause regressions will be backed out if the
  144. regression cannot be fixed in a timely manner. Far better to avoid the
  145. regression in the first place.
  146. It is often argued that a regression can be justified if it causes things
  147. to work for more people than it creates problems for. Why not make a
  148. change if it brings new functionality to ten systems for each one it
  149. breaks? The best answer to this question was expressed by Linus in July,
  150. 2007:
  151. So we don't fix bugs by introducing new problems. That way lies
  152. madness, and nobody ever knows if you actually make any real
  153. progress at all. Is it two steps forwards, one step back, or one
  154. step forward and two steps back?
  155. (http://lwn.net/Articles/243460/).
  156. An especially unwelcome type of regression is any sort of change to the
  157. user-space ABI. Once an interface has been exported to user space, it must
  158. be supported indefinitely. This fact makes the creation of user-space
  159. interfaces particularly challenging: since they cannot be changed in
  160. incompatible ways, they must be done right the first time. For this
  161. reason, a great deal of thought, clear documentation, and wide review for
  162. user-space interfaces is always required.
  163. 4.2: CODE CHECKING TOOLS
  164. For now, at least, the writing of error-free code remains an ideal that few
  165. of us can reach. What we can hope to do, though, is to catch and fix as
  166. many of those errors as possible before our code goes into the mainline
  167. kernel. To that end, the kernel developers have put together an impressive
  168. array of tools which can catch a wide variety of obscure problems in an
  169. automated way. Any problem caught by the computer is a problem which will
  170. not afflict a user later on, so it stands to reason that the automated
  171. tools should be used whenever possible.
  172. The first step is simply to heed the warnings produced by the compiler.
  173. Contemporary versions of gcc can detect (and warn about) a large number of
  174. potential errors. Quite often, these warnings point to real problems.
  175. Code submitted for review should, as a rule, not produce any compiler
  176. warnings. When silencing warnings, take care to understand the real cause
  177. and try to avoid "fixes" which make the warning go away without addressing
  178. its cause.
  179. Note that not all compiler warnings are enabled by default. Build the
  180. kernel with "make EXTRA_CFLAGS=-W" to get the full set.
  181. The kernel provides several configuration options which turn on debugging
  182. features; most of these are found in the "kernel hacking" submenu. Several
  183. of these options should be turned on for any kernel used for development or
  184. testing purposes. In particular, you should turn on:
  185. - ENABLE_WARN_DEPRECATED, ENABLE_MUST_CHECK, and FRAME_WARN to get an
  186. extra set of warnings for problems like the use of deprecated interfaces
  187. or ignoring an important return value from a function. The output
  188. generated by these warnings can be verbose, but one need not worry about
  189. warnings from other parts of the kernel.
  190. - DEBUG_OBJECTS will add code to track the lifetime of various objects
  191. created by the kernel and warn when things are done out of order. If
  192. you are adding a subsystem which creates (and exports) complex objects
  193. of its own, consider adding support for the object debugging
  194. infrastructure.
  195. - DEBUG_SLAB can find a variety of memory allocation and use errors; it
  196. should be used on most development kernels.
  197. - DEBUG_SPINLOCK, DEBUG_ATOMIC_SLEEP, and DEBUG_MUTEXES will find a
  198. number of common locking errors.
  199. There are quite a few other debugging options, some of which will be
  200. discussed below. Some of them have a significant performance impact and
  201. should not be used all of the time. But some time spent learning the
  202. available options will likely be paid back many times over in short order.
  203. One of the heavier debugging tools is the locking checker, or "lockdep."
  204. This tool will track the acquisition and release of every lock (spinlock or
  205. mutex) in the system, the order in which locks are acquired relative to
  206. each other, the current interrupt environment, and more. It can then
  207. ensure that locks are always acquired in the same order, that the same
  208. interrupt assumptions apply in all situations, and so on. In other words,
  209. lockdep can find a number of scenarios in which the system could, on rare
  210. occasion, deadlock. This kind of problem can be painful (for both
  211. developers and users) in a deployed system; lockdep allows them to be found
  212. in an automated manner ahead of time. Code with any sort of non-trivial
  213. locking should be run with lockdep enabled before being submitted for
  214. inclusion.
  215. As a diligent kernel programmer, you will, beyond doubt, check the return
  216. status of any operation (such as a memory allocation) which can fail. The
  217. fact of the matter, though, is that the resulting failure recovery paths
  218. are, probably, completely untested. Untested code tends to be broken code;
  219. you could be much more confident of your code if all those error-handling
  220. paths had been exercised a few times.
  221. The kernel provides a fault injection framework which can do exactly that,
  222. especially where memory allocations are involved. With fault injection
  223. enabled, a configurable percentage of memory allocations will be made to
  224. fail; these failures can be restricted to a specific range of code.
  225. Running with fault injection enabled allows the programmer to see how the
  226. code responds when things go badly. See
  227. Documentation/fault-injection/fault-injection.txt for more information on
  228. how to use this facility.
  229. Other kinds of errors can be found with the "sparse" static analysis tool.
  230. With sparse, the programmer can be warned about confusion between
  231. user-space and kernel-space addresses, mixture of big-endian and
  232. small-endian quantities, the passing of integer values where a set of bit
  233. flags is expected, and so on. Sparse must be installed separately (it can
  234. be found at https://sparse.wiki.kernel.org/index.php/Main_Page if your
  235. distributor does not package it); it can then be run on the code by adding
  236. "C=1" to your make command.
  237. The "Coccinelle" tool (http://coccinelle.lip6.fr/) is able to find a wide
  238. variety of potential coding problems; it can also propose fixes for those
  239. problems. Quite a few "semantic patches" for the kernel have been packaged
  240. under the scripts/coccinelle directory; running "make coccicheck" will run
  241. through those semantic patches and report on any problems found. See
  242. Documentation/coccinelle.txt for more information.
  243. Other kinds of portability errors are best found by compiling your code for
  244. other architectures. If you do not happen to have an S/390 system or a
  245. Blackfin development board handy, you can still perform the compilation
  246. step. A large set of cross compilers for x86 systems can be found at
  247. http://www.kernel.org/pub/tools/crosstool/
  248. Some time spent installing and using these compilers will help avoid
  249. embarrassment later.
  250. 4.3: DOCUMENTATION
  251. Documentation has often been more the exception than the rule with kernel
  252. development. Even so, adequate documentation will help to ease the merging
  253. of new code into the kernel, make life easier for other developers, and
  254. will be helpful for your users. In many cases, the addition of
  255. documentation has become essentially mandatory.
  256. The first piece of documentation for any patch is its associated
  257. changelog. Log entries should describe the problem being solved, the form
  258. of the solution, the people who worked on the patch, any relevant
  259. effects on performance, and anything else that might be needed to
  260. understand the patch. Be sure that the changelog says *why* the patch is
  261. worth applying; a surprising number of developers fail to provide that
  262. information.
  263. Any code which adds a new user-space interface - including new sysfs or
  264. /proc files - should include documentation of that interface which enables
  265. user-space developers to know what they are working with. See
  266. Documentation/ABI/README for a description of how this documentation should
  267. be formatted and what information needs to be provided.
  268. The file Documentation/kernel-parameters.txt describes all of the kernel's
  269. boot-time parameters. Any patch which adds new parameters should add the
  270. appropriate entries to this file.
  271. Any new configuration options must be accompanied by help text which
  272. clearly explains the options and when the user might want to select them.
  273. Internal API information for many subsystems is documented by way of
  274. specially-formatted comments; these comments can be extracted and formatted
  275. in a number of ways by the "kernel-doc" script. If you are working within
  276. a subsystem which has kerneldoc comments, you should maintain them and add
  277. them, as appropriate, for externally-available functions. Even in areas
  278. which have not been so documented, there is no harm in adding kerneldoc
  279. comments for the future; indeed, this can be a useful activity for
  280. beginning kernel developers. The format of these comments, along with some
  281. information on how to create kerneldoc templates can be found in the file
  282. Documentation/kernel-doc-nano-HOWTO.txt.
  283. Anybody who reads through a significant amount of existing kernel code will
  284. note that, often, comments are most notable by their absence. Once again,
  285. the expectations for new code are higher than they were in the past;
  286. merging uncommented code will be harder. That said, there is little desire
  287. for verbosely-commented code. The code should, itself, be readable, with
  288. comments explaining the more subtle aspects.
  289. Certain things should always be commented. Uses of memory barriers should
  290. be accompanied by a line explaining why the barrier is necessary. The
  291. locking rules for data structures generally need to be explained somewhere.
  292. Major data structures need comprehensive documentation in general.
  293. Non-obvious dependencies between separate bits of code should be pointed
  294. out. Anything which might tempt a code janitor to make an incorrect
  295. "cleanup" needs a comment saying why it is done the way it is. And so on.
  296. 4.4: INTERNAL API CHANGES
  297. The binary interface provided by the kernel to user space cannot be broken
  298. except under the most severe circumstances. The kernel's internal
  299. programming interfaces, instead, are highly fluid and can be changed when
  300. the need arises. If you find yourself having to work around a kernel API,
  301. or simply not using a specific functionality because it does not meet your
  302. needs, that may be a sign that the API needs to change. As a kernel
  303. developer, you are empowered to make such changes.
  304. There are, of course, some catches. API changes can be made, but they need
  305. to be well justified. So any patch making an internal API change should be
  306. accompanied by a description of what the change is and why it is
  307. necessary. This kind of change should also be broken out into a separate
  308. patch, rather than buried within a larger patch.
  309. The other catch is that a developer who changes an internal API is
  310. generally charged with the task of fixing any code within the kernel tree
  311. which is broken by the change. For a widely-used function, this duty can
  312. lead to literally hundreds or thousands of changes - many of which are
  313. likely to conflict with work being done by other developers. Needless to
  314. say, this can be a large job, so it is best to be sure that the
  315. justification is solid. Note that the Coccinelle tool can help with
  316. wide-ranging API changes.
  317. When making an incompatible API change, one should, whenever possible,
  318. ensure that code which has not been updated is caught by the compiler.
  319. This will help you to be sure that you have found all in-tree uses of that
  320. interface. It will also alert developers of out-of-tree code that there is
  321. a change that they need to respond to. Supporting out-of-tree code is not
  322. something that kernel developers need to be worried about, but we also do
  323. not have to make life harder for out-of-tree developers than it needs to
  324. be.