0001 .. _development_coding:
0002
0003 Getting the code right
0004 ======================
0005
0006 While there is much to be said for a solid and community-oriented design
0007 process, the proof of any kernel development project is in the resulting
0008 code. It is the code which will be examined by other developers and merged
0009 (or not) into the mainline tree. So it is the quality of this code which
0010 will determine the ultimate success of the project.
0011
0012 This section will examine the coding process. We'll start with a look at a
0013 number of ways in which kernel developers can go wrong. Then the focus
0014 will shift toward doing things right and the tools which can help in that
0015 quest.
0016
0017
0018 Pitfalls
0019 ---------
0020
0021 Coding style
0022 ************
0023
0024 The kernel has long had a standard coding style, described in
0025 :ref:`Documentation/process/coding-style.rst <codingstyle>`. For much of
0026 that time, the policies described in that file were taken as being, at most,
0027 advisory. As a result, there is a substantial amount of code in the kernel
0028 which does not meet the coding style guidelines. The presence of that code
0029 leads to two independent hazards for kernel developers.
0030
0031 The first of these is to believe that the kernel coding standards do not
0032 matter and are not enforced. The truth of the matter is that adding new
0033 code to the kernel is very difficult if that code is not coded according to
0034 the standard; many developers will request that the code be reformatted
0035 before they will even review it. A code base as large as the kernel
0036 requires some uniformity of code to make it possible for developers to
0037 quickly understand any part of it. So there is no longer room for
0038 strangely-formatted code.
0039
0040 Occasionally, the kernel's coding style will run into conflict with an
0041 employer's mandated style. In such cases, the kernel's style will have to
0042 win before the code can be merged. Putting code into the kernel means
0043 giving up a degree of control in a number of ways - including control over
0044 how the code is formatted.
0045
0046 The other trap is to assume that code which is already in the kernel is
0047 urgently in need of coding style fixes. Developers may start to generate
0048 reformatting patches as a way of gaining familiarity with the process, or
0049 as a way of getting their name into the kernel changelogs - or both. But
0050 pure coding style fixes are seen as noise by the development community;
0051 they tend to get a chilly reception. So this type of patch is best
0052 avoided. It is natural to fix the style of a piece of code while working
0053 on it for other reasons, but coding style changes should not be made for
0054 their own sake.
0055
0056 The coding style document also should not be read as an absolute law which
0057 can never be transgressed. If there is a good reason to go against the
0058 style (a line which becomes far less readable if split to fit within the
0059 80-column limit, for example), just do it.
0060
0061 Note that you can also use the ``clang-format`` tool to help you with
0062 these rules, to quickly re-format parts of your code automatically,
0063 and to review full files in order to spot coding style mistakes,
0064 typos and possible improvements. It is also handy for sorting ``#includes``,
0065 for aligning variables/macros, for reflowing text and other similar tasks.
0066 See the file :ref:`Documentation/process/clang-format.rst <clangformat>`
0067 for more details.
0068
0069
0070 Abstraction layers
0071 ******************
0072
0073 Computer Science professors teach students to make extensive use of
0074 abstraction layers in the name of flexibility and information hiding.
0075 Certainly the kernel makes extensive use of abstraction; no project
0076 involving several million lines of code could do otherwise and survive.
0077 But experience has shown that excessive or premature abstraction can be
0078 just as harmful as premature optimization. Abstraction should be used to
0079 the level required and no further.
0080
0081 At a simple level, consider a function which has an argument which is
0082 always passed as zero by all callers. One could retain that argument just
0083 in case somebody eventually needs to use the extra flexibility that it
0084 provides. By that time, though, chances are good that the code which
0085 implements this extra argument has been broken in some subtle way which was
0086 never noticed - because it has never been used. Or, when the need for
0087 extra flexibility arises, it does not do so in a way which matches the
0088 programmer's early expectation. Kernel developers will routinely submit
0089 patches to remove unused arguments; they should, in general, not be added
0090 in the first place.
0091
0092 Abstraction layers which hide access to hardware - often to allow the bulk
0093 of a driver to be used with multiple operating systems - are especially
0094 frowned upon. Such layers obscure the code and may impose a performance
0095 penalty; they do not belong in the Linux kernel.
0096
0097 On the other hand, if you find yourself copying significant amounts of code
0098 from another kernel subsystem, it is time to ask whether it would, in fact,
0099 make sense to pull out some of that code into a separate library or to
0100 implement that functionality at a higher level. There is no value in
0101 replicating the same code throughout the kernel.
0102
0103
0104 #ifdef and preprocessor use in general
0105 **************************************
0106
0107 The C preprocessor seems to present a powerful temptation to some C
0108 programmers, who see it as a way to efficiently encode a great deal of
0109 flexibility into a source file. But the preprocessor is not C, and heavy
0110 use of it results in code which is much harder for others to read and
0111 harder for the compiler to check for correctness. Heavy preprocessor use
0112 is almost always a sign of code which needs some cleanup work.
0113
0114 Conditional compilation with #ifdef is, indeed, a powerful feature, and it
0115 is used within the kernel. But there is little desire to see code which is
0116 sprinkled liberally with #ifdef blocks. As a general rule, #ifdef use
0117 should be confined to header files whenever possible.
0118 Conditionally-compiled code can be confined to functions which, if the code
0119 is not to be present, simply become empty. The compiler will then quietly
0120 optimize out the call to the empty function. The result is far cleaner
0121 code which is easier to follow.
0122
0123 C preprocessor macros present a number of hazards, including possible
0124 multiple evaluation of expressions with side effects and no type safety.
0125 If you are tempted to define a macro, consider creating an inline function
0126 instead. The code which results will be the same, but inline functions are
0127 easier to read, do not evaluate their arguments multiple times, and allow
0128 the compiler to perform type checking on the arguments and return value.
0129
0130
0131 Inline functions
0132 ****************
0133
0134 Inline functions present a hazard of their own, though. Programmers can
0135 become enamored of the perceived efficiency inherent in avoiding a function
0136 call and fill a source file with inline functions. Those functions,
0137 however, can actually reduce performance. Since their code is replicated
0138 at each call site, they end up bloating the size of the compiled kernel.
0139 That, in turn, creates pressure on the processor's memory caches, which can
0140 slow execution dramatically. Inline functions, as a rule, should be quite
0141 small and relatively rare. The cost of a function call, after all, is not
0142 that high; the creation of large numbers of inline functions is a classic
0143 example of premature optimization.
0144
0145 In general, kernel programmers ignore cache effects at their peril. The
0146 classic time/space tradeoff taught in beginning data structures classes
0147 often does not apply to contemporary hardware. Space *is* time, in that a
0148 larger program will run slower than one which is more compact.
0149
0150 More recent compilers take an increasingly active role in deciding whether
0151 a given function should actually be inlined or not. So the liberal
0152 placement of "inline" keywords may not just be excessive; it could also be
0153 irrelevant.
0154
0155
0156 Locking
0157 *******
0158
0159 In May, 2006, the "Devicescape" networking stack was, with great
0160 fanfare, released under the GPL and made available for inclusion in the
0161 mainline kernel. This donation was welcome news; support for wireless
0162 networking in Linux was considered substandard at best, and the Devicescape
0163 stack offered the promise of fixing that situation. Yet, this code did not
0164 actually make it into the mainline until June, 2007 (2.6.22). What
0165 happened?
0166
0167 This code showed a number of signs of having been developed behind
0168 corporate doors. But one large problem in particular was that it was not
0169 designed to work on multiprocessor systems. Before this networking stack
0170 (now called mac80211) could be merged, a locking scheme needed to be
0171 retrofitted onto it.
0172
0173 Once upon a time, Linux kernel code could be developed without thinking
0174 about the concurrency issues presented by multiprocessor systems. Now,
0175 however, this document is being written on a dual-core laptop. Even on
0176 single-processor systems, work being done to improve responsiveness will
0177 raise the level of concurrency within the kernel. The days when kernel
0178 code could be written without thinking about locking are long past.
0179
0180 Any resource (data structures, hardware registers, etc.) which could be
0181 accessed concurrently by more than one thread must be protected by a lock.
0182 New code should be written with this requirement in mind; retrofitting
0183 locking after the fact is a rather more difficult task. Kernel developers
0184 should take the time to understand the available locking primitives well
0185 enough to pick the right tool for the job. Code which shows a lack of
0186 attention to concurrency will have a difficult path into the mainline.
0187
0188
0189 Regressions
0190 ***********
0191
0192 One final hazard worth mentioning is this: it can be tempting to make a
0193 change (which may bring big improvements) which causes something to break
0194 for existing users. This kind of change is called a "regression," and
0195 regressions have become most unwelcome in the mainline kernel. With few
0196 exceptions, changes which cause regressions will be backed out if the
0197 regression cannot be fixed in a timely manner. Far better to avoid the
0198 regression in the first place.
0199
0200 It is often argued that a regression can be justified if it causes things
0201 to work for more people than it creates problems for. Why not make a
0202 change if it brings new functionality to ten systems for each one it
0203 breaks? The best answer to this question was expressed by Linus in July,
0204 2007:
0205
0206 ::
0207
0208 So we don't fix bugs by introducing new problems. That way lies
0209 madness, and nobody ever knows if you actually make any real
0210 progress at all. Is it two steps forwards, one step back, or one
0211 step forward and two steps back?
0212
0213 (https://lwn.net/Articles/243460/).
0214
0215 An especially unwelcome type of regression is any sort of change to the
0216 user-space ABI. Once an interface has been exported to user space, it must
0217 be supported indefinitely. This fact makes the creation of user-space
0218 interfaces particularly challenging: since they cannot be changed in
0219 incompatible ways, they must be done right the first time. For this
0220 reason, a great deal of thought, clear documentation, and wide review for
0221 user-space interfaces is always required.
0222
0223
0224 Code checking tools
0225 -------------------
0226
0227 For now, at least, the writing of error-free code remains an ideal that few
0228 of us can reach. What we can hope to do, though, is to catch and fix as
0229 many of those errors as possible before our code goes into the mainline
0230 kernel. To that end, the kernel developers have put together an impressive
0231 array of tools which can catch a wide variety of obscure problems in an
0232 automated way. Any problem caught by the computer is a problem which will
0233 not afflict a user later on, so it stands to reason that the automated
0234 tools should be used whenever possible.
0235
0236 The first step is simply to heed the warnings produced by the compiler.
0237 Contemporary versions of gcc can detect (and warn about) a large number of
0238 potential errors. Quite often, these warnings point to real problems.
0239 Code submitted for review should, as a rule, not produce any compiler
0240 warnings. When silencing warnings, take care to understand the real cause
0241 and try to avoid "fixes" which make the warning go away without addressing
0242 its cause.
0243
0244 Note that not all compiler warnings are enabled by default. Build the
0245 kernel with "make KCFLAGS=-W" to get the full set.
0246
0247 The kernel provides several configuration options which turn on debugging
0248 features; most of these are found in the "kernel hacking" submenu. Several
0249 of these options should be turned on for any kernel used for development or
0250 testing purposes. In particular, you should turn on:
0251
0252 - FRAME_WARN to get warnings for stack frames larger than a given amount.
0253 The output generated can be verbose, but one need not worry about
0254 warnings from other parts of the kernel.
0255
0256 - DEBUG_OBJECTS will add code to track the lifetime of various objects
0257 created by the kernel and warn when things are done out of order. If
0258 you are adding a subsystem which creates (and exports) complex objects
0259 of its own, consider adding support for the object debugging
0260 infrastructure.
0261
0262 - DEBUG_SLAB can find a variety of memory allocation and use errors; it
0263 should be used on most development kernels.
0264
0265 - DEBUG_SPINLOCK, DEBUG_ATOMIC_SLEEP, and DEBUG_MUTEXES will find a
0266 number of common locking errors.
0267
0268 There are quite a few other debugging options, some of which will be
0269 discussed below. Some of them have a significant performance impact and
0270 should not be used all of the time. But some time spent learning the
0271 available options will likely be paid back many times over in short order.
0272
0273 One of the heavier debugging tools is the locking checker, or "lockdep."
0274 This tool will track the acquisition and release of every lock (spinlock or
0275 mutex) in the system, the order in which locks are acquired relative to
0276 each other, the current interrupt environment, and more. It can then
0277 ensure that locks are always acquired in the same order, that the same
0278 interrupt assumptions apply in all situations, and so on. In other words,
0279 lockdep can find a number of scenarios in which the system could, on rare
0280 occasion, deadlock. This kind of problem can be painful (for both
0281 developers and users) in a deployed system; lockdep allows them to be found
0282 in an automated manner ahead of time. Code with any sort of non-trivial
0283 locking should be run with lockdep enabled before being submitted for
0284 inclusion.
0285
0286 As a diligent kernel programmer, you will, beyond doubt, check the return
0287 status of any operation (such as a memory allocation) which can fail. The
0288 fact of the matter, though, is that the resulting failure recovery paths
0289 are, probably, completely untested. Untested code tends to be broken code;
0290 you could be much more confident of your code if all those error-handling
0291 paths had been exercised a few times.
0292
0293 The kernel provides a fault injection framework which can do exactly that,
0294 especially where memory allocations are involved. With fault injection
0295 enabled, a configurable percentage of memory allocations will be made to
0296 fail; these failures can be restricted to a specific range of code.
0297 Running with fault injection enabled allows the programmer to see how the
0298 code responds when things go badly. See
0299 Documentation/fault-injection/fault-injection.rst for more information on
0300 how to use this facility.
0301
0302 Other kinds of errors can be found with the "sparse" static analysis tool.
0303 With sparse, the programmer can be warned about confusion between
0304 user-space and kernel-space addresses, mixture of big-endian and
0305 small-endian quantities, the passing of integer values where a set of bit
0306 flags is expected, and so on. Sparse must be installed separately (it can
0307 be found at https://sparse.wiki.kernel.org/index.php/Main_Page if your
0308 distributor does not package it); it can then be run on the code by adding
0309 "C=1" to your make command.
0310
0311 The "Coccinelle" tool (http://coccinelle.lip6.fr/) is able to find a wide
0312 variety of potential coding problems; it can also propose fixes for those
0313 problems. Quite a few "semantic patches" for the kernel have been packaged
0314 under the scripts/coccinelle directory; running "make coccicheck" will run
0315 through those semantic patches and report on any problems found. See
0316 :ref:`Documentation/dev-tools/coccinelle.rst <devtools_coccinelle>`
0317 for more information.
0318
0319 Other kinds of portability errors are best found by compiling your code for
0320 other architectures. If you do not happen to have an S/390 system or a
0321 Blackfin development board handy, you can still perform the compilation
0322 step. A large set of cross compilers for x86 systems can be found at
0323
0324 https://www.kernel.org/pub/tools/crosstool/
0325
0326 Some time spent installing and using these compilers will help avoid
0327 embarrassment later.
0328
0329
0330 Documentation
0331 -------------
0332
0333 Documentation has often been more the exception than the rule with kernel
0334 development. Even so, adequate documentation will help to ease the merging
0335 of new code into the kernel, make life easier for other developers, and
0336 will be helpful for your users. In many cases, the addition of
0337 documentation has become essentially mandatory.
0338
0339 The first piece of documentation for any patch is its associated
0340 changelog. Log entries should describe the problem being solved, the form
0341 of the solution, the people who worked on the patch, any relevant
0342 effects on performance, and anything else that might be needed to
0343 understand the patch. Be sure that the changelog says *why* the patch is
0344 worth applying; a surprising number of developers fail to provide that
0345 information.
0346
0347 Any code which adds a new user-space interface - including new sysfs or
0348 /proc files - should include documentation of that interface which enables
0349 user-space developers to know what they are working with. See
0350 Documentation/ABI/README for a description of how this documentation should
0351 be formatted and what information needs to be provided.
0352
0353 The file :ref:`Documentation/admin-guide/kernel-parameters.rst
0354 <kernelparameters>` describes all of the kernel's boot-time parameters.
0355 Any patch which adds new parameters should add the appropriate entries to
0356 this file.
0357
0358 Any new configuration options must be accompanied by help text which
0359 clearly explains the options and when the user might want to select them.
0360
0361 Internal API information for many subsystems is documented by way of
0362 specially-formatted comments; these comments can be extracted and formatted
0363 in a number of ways by the "kernel-doc" script. If you are working within
0364 a subsystem which has kerneldoc comments, you should maintain them and add
0365 them, as appropriate, for externally-available functions. Even in areas
0366 which have not been so documented, there is no harm in adding kerneldoc
0367 comments for the future; indeed, this can be a useful activity for
0368 beginning kernel developers. The format of these comments, along with some
0369 information on how to create kerneldoc templates can be found at
0370 :ref:`Documentation/doc-guide/ <doc_guide>`.
0371
0372 Anybody who reads through a significant amount of existing kernel code will
0373 note that, often, comments are most notable by their absence. Once again,
0374 the expectations for new code are higher than they were in the past;
0375 merging uncommented code will be harder. That said, there is little desire
0376 for verbosely-commented code. The code should, itself, be readable, with
0377 comments explaining the more subtle aspects.
0378
0379 Certain things should always be commented. Uses of memory barriers should
0380 be accompanied by a line explaining why the barrier is necessary. The
0381 locking rules for data structures generally need to be explained somewhere.
0382 Major data structures need comprehensive documentation in general.
0383 Non-obvious dependencies between separate bits of code should be pointed
0384 out. Anything which might tempt a code janitor to make an incorrect
0385 "cleanup" needs a comment saying why it is done the way it is. And so on.
0386
0387
0388 Internal API changes
0389 --------------------
0390
0391 The binary interface provided by the kernel to user space cannot be broken
0392 except under the most severe circumstances. The kernel's internal
0393 programming interfaces, instead, are highly fluid and can be changed when
0394 the need arises. If you find yourself having to work around a kernel API,
0395 or simply not using a specific functionality because it does not meet your
0396 needs, that may be a sign that the API needs to change. As a kernel
0397 developer, you are empowered to make such changes.
0398
0399 There are, of course, some catches. API changes can be made, but they need
0400 to be well justified. So any patch making an internal API change should be
0401 accompanied by a description of what the change is and why it is
0402 necessary. This kind of change should also be broken out into a separate
0403 patch, rather than buried within a larger patch.
0404
0405 The other catch is that a developer who changes an internal API is
0406 generally charged with the task of fixing any code within the kernel tree
0407 which is broken by the change. For a widely-used function, this duty can
0408 lead to literally hundreds or thousands of changes - many of which are
0409 likely to conflict with work being done by other developers. Needless to
0410 say, this can be a large job, so it is best to be sure that the
0411 justification is solid. Note that the Coccinelle tool can help with
0412 wide-ranging API changes.
0413
0414 When making an incompatible API change, one should, whenever possible,
0415 ensure that code which has not been updated is caught by the compiler.
0416 This will help you to be sure that you have found all in-tree uses of that
0417 interface. It will also alert developers of out-of-tree code that there is
0418 a change that they need to respond to. Supporting out-of-tree code is not
0419 something that kernel developers need to be worried about, but we also do
0420 not have to make life harder for out-of-tree developers than it needs to
0421 be.