coding-style.rst 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  1. .. _codingstyle:
  2. Linux kernel coding style
  3. =========================
  4. This is a short document describing the preferred coding style for the
  5. linux kernel. Coding style is very personal, and I won't **force** my
  6. views on anybody, but this is what goes for anything that I have to be
  7. able to maintain, and I'd prefer it for most other things too. Please
  8. at least consider the points made here.
  9. First off, I'd suggest printing out a copy of the GNU coding standards,
  10. and NOT read it. Burn them, it's a great symbolic gesture.
  11. Anyway, here goes:
  12. 1) Indentation
  13. --------------
  14. Tabs are 8 characters, and thus indentations are also 8 characters.
  15. There are heretic movements that try to make indentations 4 (or even 2!)
  16. characters deep, and that is akin to trying to define the value of PI to
  17. be 3.
  18. Rationale: The whole idea behind indentation is to clearly define where
  19. a block of control starts and ends. Especially when you've been looking
  20. at your screen for 20 straight hours, you'll find it a lot easier to see
  21. how the indentation works if you have large indentations.
  22. Now, some people will claim that having 8-character indentations makes
  23. the code move too far to the right, and makes it hard to read on a
  24. 80-character terminal screen. The answer to that is that if you need
  25. more than 3 levels of indentation, you're screwed anyway, and should fix
  26. your program.
  27. In short, 8-char indents make things easier to read, and have the added
  28. benefit of warning you when you're nesting your functions too deep.
  29. Heed that warning.
  30. The preferred way to ease multiple indentation levels in a switch statement is
  31. to align the ``switch`` and its subordinate ``case`` labels in the same column
  32. instead of ``double-indenting`` the ``case`` labels. E.g.:
  33. .. code-block:: c
  34. switch (suffix) {
  35. case 'G':
  36. case 'g':
  37. mem <<= 30;
  38. break;
  39. case 'M':
  40. case 'm':
  41. mem <<= 20;
  42. break;
  43. case 'K':
  44. case 'k':
  45. mem <<= 10;
  46. fallthrough;
  47. default:
  48. break;
  49. }
  50. Don't put multiple statements on a single line unless you have
  51. something to hide:
  52. .. code-block:: c
  53. if (condition) do_this;
  54. do_something_everytime;
  55. Don't put multiple assignments on a single line either. Kernel coding style
  56. is super simple. Avoid tricky expressions.
  57. Outside of comments, documentation and except in Kconfig, spaces are never
  58. used for indentation, and the above example is deliberately broken.
  59. Get a decent editor and don't leave whitespace at the end of lines.
  60. 2) Breaking long lines and strings
  61. ----------------------------------
  62. Coding style is all about readability and maintainability using commonly
  63. available tools.
  64. The preferred limit on the length of a single line is 80 columns.
  65. Statements longer than 80 columns should be broken into sensible chunks,
  66. unless exceeding 80 columns significantly increases readability and does
  67. not hide information.
  68. Descendants are always substantially shorter than the parent and
  69. are placed substantially to the right. A very commonly used style
  70. is to align descendants to a function open parenthesis.
  71. These same rules are applied to function headers with a long argument list.
  72. However, never break user-visible strings such as printk messages because
  73. that breaks the ability to grep for them.
  74. 3) Placing Braces and Spaces
  75. ----------------------------
  76. The other issue that always comes up in C styling is the placement of
  77. braces. Unlike the indent size, there are few technical reasons to
  78. choose one placement strategy over the other, but the preferred way, as
  79. shown to us by the prophets Kernighan and Ritchie, is to put the opening
  80. brace last on the line, and put the closing brace first, thusly:
  81. .. code-block:: c
  82. if (x is true) {
  83. we do y
  84. }
  85. This applies to all non-function statement blocks (if, switch, for,
  86. while, do). E.g.:
  87. .. code-block:: c
  88. switch (action) {
  89. case KOBJ_ADD:
  90. return "add";
  91. case KOBJ_REMOVE:
  92. return "remove";
  93. case KOBJ_CHANGE:
  94. return "change";
  95. default:
  96. return NULL;
  97. }
  98. However, there is one special case, namely functions: they have the
  99. opening brace at the beginning of the next line, thus:
  100. .. code-block:: c
  101. int function(int x)
  102. {
  103. body of function
  104. }
  105. Heretic people all over the world have claimed that this inconsistency
  106. is ... well ... inconsistent, but all right-thinking people know that
  107. (a) K&R are **right** and (b) K&R are right. Besides, functions are
  108. special anyway (you can't nest them in C).
  109. Note that the closing brace is empty on a line of its own, **except** in
  110. the cases where it is followed by a continuation of the same statement,
  111. ie a ``while`` in a do-statement or an ``else`` in an if-statement, like
  112. this:
  113. .. code-block:: c
  114. do {
  115. body of do-loop
  116. } while (condition);
  117. and
  118. .. code-block:: c
  119. if (x == y) {
  120. ..
  121. } else if (x > y) {
  122. ...
  123. } else {
  124. ....
  125. }
  126. Rationale: K&R.
  127. Also, note that this brace-placement also minimizes the number of empty
  128. (or almost empty) lines, without any loss of readability. Thus, as the
  129. supply of new-lines on your screen is not a renewable resource (think
  130. 25-line terminal screens here), you have more empty lines to put
  131. comments on.
  132. Do not unnecessarily use braces where a single statement will do.
  133. .. code-block:: c
  134. if (condition)
  135. action();
  136. and
  137. .. code-block:: none
  138. if (condition)
  139. do_this();
  140. else
  141. do_that();
  142. This does not apply if only one branch of a conditional statement is a single
  143. statement; in the latter case use braces in both branches:
  144. .. code-block:: c
  145. if (condition) {
  146. do_this();
  147. do_that();
  148. } else {
  149. otherwise();
  150. }
  151. Also, use braces when a loop contains more than a single simple statement:
  152. .. code-block:: c
  153. while (condition) {
  154. if (test)
  155. do_something();
  156. }
  157. 3.1) Spaces
  158. ***********
  159. Linux kernel style for use of spaces depends (mostly) on
  160. function-versus-keyword usage. Use a space after (most) keywords. The
  161. notable exceptions are sizeof, typeof, alignof, and __attribute__, which look
  162. somewhat like functions (and are usually used with parentheses in Linux,
  163. although they are not required in the language, as in: ``sizeof info`` after
  164. ``struct fileinfo info;`` is declared).
  165. So use a space after these keywords::
  166. if, switch, case, for, do, while
  167. but not with sizeof, typeof, alignof, or __attribute__. E.g.,
  168. .. code-block:: c
  169. s = sizeof(struct file);
  170. Do not add spaces around (inside) parenthesized expressions. This example is
  171. **bad**:
  172. .. code-block:: c
  173. s = sizeof( struct file );
  174. When declaring pointer data or a function that returns a pointer type, the
  175. preferred use of ``*`` is adjacent to the data name or function name and not
  176. adjacent to the type name. Examples:
  177. .. code-block:: c
  178. char *linux_banner;
  179. unsigned long long memparse(char *ptr, char **retptr);
  180. char *match_strdup(substring_t *s);
  181. Use one space around (on each side of) most binary and ternary operators,
  182. such as any of these::
  183. = + - < > * / % | & ^ <= >= == != ? :
  184. but no space after unary operators::
  185. & * + - ~ ! sizeof typeof alignof __attribute__ defined
  186. no space before the postfix increment & decrement unary operators::
  187. ++ --
  188. no space after the prefix increment & decrement unary operators::
  189. ++ --
  190. and no space around the ``.`` and ``->`` structure member operators.
  191. Do not leave trailing whitespace at the ends of lines. Some editors with
  192. ``smart`` indentation will insert whitespace at the beginning of new lines as
  193. appropriate, so you can start typing the next line of code right away.
  194. However, some such editors do not remove the whitespace if you end up not
  195. putting a line of code there, such as if you leave a blank line. As a result,
  196. you end up with lines containing trailing whitespace.
  197. Git will warn you about patches that introduce trailing whitespace, and can
  198. optionally strip the trailing whitespace for you; however, if applying a series
  199. of patches, this may make later patches in the series fail by changing their
  200. context lines.
  201. 4) Naming
  202. ---------
  203. C is a Spartan language, and your naming conventions should follow suit.
  204. Unlike Modula-2 and Pascal programmers, C programmers do not use cute
  205. names like ThisVariableIsATemporaryCounter. A C programmer would call that
  206. variable ``tmp``, which is much easier to write, and not the least more
  207. difficult to understand.
  208. HOWEVER, while mixed-case names are frowned upon, descriptive names for
  209. global variables are a must. To call a global function ``foo`` is a
  210. shooting offense.
  211. GLOBAL variables (to be used only if you **really** need them) need to
  212. have descriptive names, as do global functions. If you have a function
  213. that counts the number of active users, you should call that
  214. ``count_active_users()`` or similar, you should **not** call it ``cntusr()``.
  215. Encoding the type of a function into the name (so-called Hungarian
  216. notation) is asinine - the compiler knows the types anyway and can check
  217. those, and it only confuses the programmer. No wonder Microsoft makes buggy
  218. programs.
  219. LOCAL variable names should be short, and to the point. If you have
  220. some random integer loop counter, it should probably be called ``i``.
  221. Calling it ``loop_counter`` is non-productive, if there is no chance of it
  222. being mis-understood. Similarly, ``tmp`` can be just about any type of
  223. variable that is used to hold a temporary value.
  224. If you are afraid to mix up your local variable names, you have another
  225. problem, which is called the function-growth-hormone-imbalance syndrome.
  226. See chapter 6 (Functions).
  227. For symbol names and documentation, avoid introducing new usage of
  228. 'master / slave' (or 'slave' independent of 'master') and 'blacklist /
  229. whitelist'.
  230. Recommended replacements for 'master / slave' are:
  231. '{primary,main} / {secondary,replica,subordinate}'
  232. '{initiator,requester} / {target,responder}'
  233. '{controller,host} / {device,worker,proxy}'
  234. 'leader / follower'
  235. 'director / performer'
  236. Recommended replacements for 'blacklist/whitelist' are:
  237. 'denylist / allowlist'
  238. 'blocklist / passlist'
  239. Exceptions for introducing new usage is to maintain a userspace ABI/API,
  240. or when updating code for an existing (as of 2020) hardware or protocol
  241. specification that mandates those terms. For new specifications
  242. translate specification usage of the terminology to the kernel coding
  243. standard where possible.
  244. 5) Typedefs
  245. -----------
  246. Please don't use things like ``vps_t``.
  247. It's a **mistake** to use typedef for structures and pointers. When you see a
  248. .. code-block:: c
  249. vps_t a;
  250. in the source, what does it mean?
  251. In contrast, if it says
  252. .. code-block:: c
  253. struct virtual_container *a;
  254. you can actually tell what ``a`` is.
  255. Lots of people think that typedefs ``help readability``. Not so. They are
  256. useful only for:
  257. (a) totally opaque objects (where the typedef is actively used to **hide**
  258. what the object is).
  259. Example: ``pte_t`` etc. opaque objects that you can only access using
  260. the proper accessor functions.
  261. .. note::
  262. Opaqueness and ``accessor functions`` are not good in themselves.
  263. The reason we have them for things like pte_t etc. is that there
  264. really is absolutely **zero** portably accessible information there.
  265. (b) Clear integer types, where the abstraction **helps** avoid confusion
  266. whether it is ``int`` or ``long``.
  267. u8/u16/u32 are perfectly fine typedefs, although they fit into
  268. category (d) better than here.
  269. .. note::
  270. Again - there needs to be a **reason** for this. If something is
  271. ``unsigned long``, then there's no reason to do
  272. typedef unsigned long myflags_t;
  273. but if there is a clear reason for why it under certain circumstances
  274. might be an ``unsigned int`` and under other configurations might be
  275. ``unsigned long``, then by all means go ahead and use a typedef.
  276. (c) when you use sparse to literally create a **new** type for
  277. type-checking.
  278. (d) New types which are identical to standard C99 types, in certain
  279. exceptional circumstances.
  280. Although it would only take a short amount of time for the eyes and
  281. brain to become accustomed to the standard types like ``uint32_t``,
  282. some people object to their use anyway.
  283. Therefore, the Linux-specific ``u8/u16/u32/u64`` types and their
  284. signed equivalents which are identical to standard types are
  285. permitted -- although they are not mandatory in new code of your
  286. own.
  287. When editing existing code which already uses one or the other set
  288. of types, you should conform to the existing choices in that code.
  289. (e) Types safe for use in userspace.
  290. In certain structures which are visible to userspace, we cannot
  291. require C99 types and cannot use the ``u32`` form above. Thus, we
  292. use __u32 and similar types in all structures which are shared
  293. with userspace.
  294. Maybe there are other cases too, but the rule should basically be to NEVER
  295. EVER use a typedef unless you can clearly match one of those rules.
  296. In general, a pointer, or a struct that has elements that can reasonably
  297. be directly accessed should **never** be a typedef.
  298. 6) Functions
  299. ------------
  300. Functions should be short and sweet, and do just one thing. They should
  301. fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,
  302. as we all know), and do one thing and do that well.
  303. The maximum length of a function is inversely proportional to the
  304. complexity and indentation level of that function. So, if you have a
  305. conceptually simple function that is just one long (but simple)
  306. case-statement, where you have to do lots of small things for a lot of
  307. different cases, it's OK to have a longer function.
  308. However, if you have a complex function, and you suspect that a
  309. less-than-gifted first-year high-school student might not even
  310. understand what the function is all about, you should adhere to the
  311. maximum limits all the more closely. Use helper functions with
  312. descriptive names (you can ask the compiler to in-line them if you think
  313. it's performance-critical, and it will probably do a better job of it
  314. than you would have done).
  315. Another measure of the function is the number of local variables. They
  316. shouldn't exceed 5-10, or you're doing something wrong. Re-think the
  317. function, and split it into smaller pieces. A human brain can
  318. generally easily keep track of about 7 different things, anything more
  319. and it gets confused. You know you're brilliant, but maybe you'd like
  320. to understand what you did 2 weeks from now.
  321. In source files, separate functions with one blank line. If the function is
  322. exported, the **EXPORT** macro for it should follow immediately after the
  323. closing function brace line. E.g.:
  324. .. code-block:: c
  325. int system_is_up(void)
  326. {
  327. return system_state == SYSTEM_RUNNING;
  328. }
  329. EXPORT_SYMBOL(system_is_up);
  330. In function prototypes, include parameter names with their data types.
  331. Although this is not required by the C language, it is preferred in Linux
  332. because it is a simple way to add valuable information for the reader.
  333. Do not use the ``extern`` keyword with function prototypes as this makes
  334. lines longer and isn't strictly necessary.
  335. 7) Centralized exiting of functions
  336. -----------------------------------
  337. Albeit deprecated by some people, the equivalent of the goto statement is
  338. used frequently by compilers in form of the unconditional jump instruction.
  339. The goto statement comes in handy when a function exits from multiple
  340. locations and some common work such as cleanup has to be done. If there is no
  341. cleanup needed then just return directly.
  342. Choose label names which say what the goto does or why the goto exists. An
  343. example of a good name could be ``out_free_buffer:`` if the goto frees ``buffer``.
  344. Avoid using GW-BASIC names like ``err1:`` and ``err2:``, as you would have to
  345. renumber them if you ever add or remove exit paths, and they make correctness
  346. difficult to verify anyway.
  347. The rationale for using gotos is:
  348. - unconditional statements are easier to understand and follow
  349. - nesting is reduced
  350. - errors by not updating individual exit points when making
  351. modifications are prevented
  352. - saves the compiler work to optimize redundant code away ;)
  353. .. code-block:: c
  354. int fun(int a)
  355. {
  356. int result = 0;
  357. char *buffer;
  358. buffer = kmalloc(SIZE, GFP_KERNEL);
  359. if (!buffer)
  360. return -ENOMEM;
  361. if (condition1) {
  362. while (loop1) {
  363. ...
  364. }
  365. result = 1;
  366. goto out_free_buffer;
  367. }
  368. ...
  369. out_free_buffer:
  370. kfree(buffer);
  371. return result;
  372. }
  373. A common type of bug to be aware of is ``one err bugs`` which look like this:
  374. .. code-block:: c
  375. err:
  376. kfree(foo->bar);
  377. kfree(foo);
  378. return ret;
  379. The bug in this code is that on some exit paths ``foo`` is NULL. Normally the
  380. fix for this is to split it up into two error labels ``err_free_bar:`` and
  381. ``err_free_foo:``:
  382. .. code-block:: c
  383. err_free_bar:
  384. kfree(foo->bar);
  385. err_free_foo:
  386. kfree(foo);
  387. return ret;
  388. Ideally you should simulate errors to test all exit paths.
  389. 8) Commenting
  390. -------------
  391. Comments are good, but there is also a danger of over-commenting. NEVER
  392. try to explain HOW your code works in a comment: it's much better to
  393. write the code so that the **working** is obvious, and it's a waste of
  394. time to explain badly written code.
  395. Generally, you want your comments to tell WHAT your code does, not HOW.
  396. Also, try to avoid putting comments inside a function body: if the
  397. function is so complex that you need to separately comment parts of it,
  398. you should probably go back to chapter 6 for a while. You can make
  399. small comments to note or warn about something particularly clever (or
  400. ugly), but try to avoid excess. Instead, put the comments at the head
  401. of the function, telling people what it does, and possibly WHY it does
  402. it.
  403. When commenting the kernel API functions, please use the kernel-doc format.
  404. See the files at :ref:`Documentation/doc-guide/ <doc_guide>` and
  405. ``scripts/kernel-doc`` for details.
  406. The preferred style for long (multi-line) comments is:
  407. .. code-block:: c
  408. /*
  409. * This is the preferred style for multi-line
  410. * comments in the Linux kernel source code.
  411. * Please use it consistently.
  412. *
  413. * Description: A column of asterisks on the left side,
  414. * with beginning and ending almost-blank lines.
  415. */
  416. For files in net/ and drivers/net/ the preferred style for long (multi-line)
  417. comments is a little different.
  418. .. code-block:: c
  419. /* The preferred comment style for files in net/ and drivers/net
  420. * looks like this.
  421. *
  422. * It is nearly the same as the generally preferred comment style,
  423. * but there is no initial almost-blank line.
  424. */
  425. It's also important to comment data, whether they are basic types or derived
  426. types. To this end, use just one data declaration per line (no commas for
  427. multiple data declarations). This leaves you room for a small comment on each
  428. item, explaining its use.
  429. 9) You've made a mess of it
  430. ---------------------------
  431. That's OK, we all do. You've probably been told by your long-time Unix
  432. user helper that ``GNU emacs`` automatically formats the C sources for
  433. you, and you've noticed that yes, it does do that, but the defaults it
  434. uses are less than desirable (in fact, they are worse than random
  435. typing - an infinite number of monkeys typing into GNU emacs would never
  436. make a good program).
  437. So, you can either get rid of GNU emacs, or change it to use saner
  438. values. To do the latter, you can stick the following in your .emacs file:
  439. .. code-block:: none
  440. (defun c-lineup-arglist-tabs-only (ignored)
  441. "Line up argument lists by tabs, not spaces"
  442. (let* ((anchor (c-langelem-pos c-syntactic-element))
  443. (column (c-langelem-2nd-pos c-syntactic-element))
  444. (offset (- (1+ column) anchor))
  445. (steps (floor offset c-basic-offset)))
  446. (* (max steps 1)
  447. c-basic-offset)))
  448. (dir-locals-set-class-variables
  449. 'linux-kernel
  450. '((c-mode . (
  451. (c-basic-offset . 8)
  452. (c-label-minimum-indentation . 0)
  453. (c-offsets-alist . (
  454. (arglist-close . c-lineup-arglist-tabs-only)
  455. (arglist-cont-nonempty .
  456. (c-lineup-gcc-asm-reg c-lineup-arglist-tabs-only))
  457. (arglist-intro . +)
  458. (brace-list-intro . +)
  459. (c . c-lineup-C-comments)
  460. (case-label . 0)
  461. (comment-intro . c-lineup-comment)
  462. (cpp-define-intro . +)
  463. (cpp-macro . -1000)
  464. (cpp-macro-cont . +)
  465. (defun-block-intro . +)
  466. (else-clause . 0)
  467. (func-decl-cont . +)
  468. (inclass . +)
  469. (inher-cont . c-lineup-multi-inher)
  470. (knr-argdecl-intro . 0)
  471. (label . -1000)
  472. (statement . 0)
  473. (statement-block-intro . +)
  474. (statement-case-intro . +)
  475. (statement-cont . +)
  476. (substatement . +)
  477. ))
  478. (indent-tabs-mode . t)
  479. (show-trailing-whitespace . t)
  480. ))))
  481. (dir-locals-set-directory-class
  482. (expand-file-name "~/src/linux-trees")
  483. 'linux-kernel)
  484. This will make emacs go better with the kernel coding style for C
  485. files below ``~/src/linux-trees``.
  486. But even if you fail in getting emacs to do sane formatting, not
  487. everything is lost: use ``indent``.
  488. Now, again, GNU indent has the same brain-dead settings that GNU emacs
  489. has, which is why you need to give it a few command line options.
  490. However, that's not too bad, because even the makers of GNU indent
  491. recognize the authority of K&R (the GNU people aren't evil, they are
  492. just severely misguided in this matter), so you just give indent the
  493. options ``-kr -i8`` (stands for ``K&R, 8 character indents``), or use
  494. ``scripts/Lindent``, which indents in the latest style.
  495. ``indent`` has a lot of options, and especially when it comes to comment
  496. re-formatting you may want to take a look at the man page. But
  497. remember: ``indent`` is not a fix for bad programming.
  498. Note that you can also use the ``clang-format`` tool to help you with
  499. these rules, to quickly re-format parts of your code automatically,
  500. and to review full files in order to spot coding style mistakes,
  501. typos and possible improvements. It is also handy for sorting ``#includes``,
  502. for aligning variables/macros, for reflowing text and other similar tasks.
  503. See the file :ref:`Documentation/process/clang-format.rst <clangformat>`
  504. for more details.
  505. 10) Kconfig configuration files
  506. -------------------------------
  507. For all of the Kconfig* configuration files throughout the source tree,
  508. the indentation is somewhat different. Lines under a ``config`` definition
  509. are indented with one tab, while help text is indented an additional two
  510. spaces. Example::
  511. config AUDIT
  512. bool "Auditing support"
  513. depends on NET
  514. help
  515. Enable auditing infrastructure that can be used with another
  516. kernel subsystem, such as SELinux (which requires this for
  517. logging of avc messages output). Does not do system-call
  518. auditing without CONFIG_AUDITSYSCALL.
  519. Seriously dangerous features (such as write support for certain
  520. filesystems) should advertise this prominently in their prompt string::
  521. config ADFS_FS_RW
  522. bool "ADFS write support (DANGEROUS)"
  523. depends on ADFS_FS
  524. ...
  525. For full documentation on the configuration files, see the file
  526. Documentation/kbuild/kconfig-language.rst.
  527. 11) Data structures
  528. -------------------
  529. Data structures that have visibility outside the single-threaded
  530. environment they are created and destroyed in should always have
  531. reference counts. In the kernel, garbage collection doesn't exist (and
  532. outside the kernel garbage collection is slow and inefficient), which
  533. means that you absolutely **have** to reference count all your uses.
  534. Reference counting means that you can avoid locking, and allows multiple
  535. users to have access to the data structure in parallel - and not having
  536. to worry about the structure suddenly going away from under them just
  537. because they slept or did something else for a while.
  538. Note that locking is **not** a replacement for reference counting.
  539. Locking is used to keep data structures coherent, while reference
  540. counting is a memory management technique. Usually both are needed, and
  541. they are not to be confused with each other.
  542. Many data structures can indeed have two levels of reference counting,
  543. when there are users of different ``classes``. The subclass count counts
  544. the number of subclass users, and decrements the global count just once
  545. when the subclass count goes to zero.
  546. Examples of this kind of ``multi-level-reference-counting`` can be found in
  547. memory management (``struct mm_struct``: mm_users and mm_count), and in
  548. filesystem code (``struct super_block``: s_count and s_active).
  549. Remember: if another thread can find your data structure, and you don't
  550. have a reference count on it, you almost certainly have a bug.
  551. 12) Macros, Enums and RTL
  552. -------------------------
  553. Names of macros defining constants and labels in enums are capitalized.
  554. .. code-block:: c
  555. #define CONSTANT 0x12345
  556. Enums are preferred when defining several related constants.
  557. CAPITALIZED macro names are appreciated but macros resembling functions
  558. may be named in lower case.
  559. Generally, inline functions are preferable to macros resembling functions.
  560. Macros with multiple statements should be enclosed in a do - while block:
  561. .. code-block:: c
  562. #define macrofun(a, b, c) \
  563. do { \
  564. if (a == 5) \
  565. do_this(b, c); \
  566. } while (0)
  567. Things to avoid when using macros:
  568. 1) macros that affect control flow:
  569. .. code-block:: c
  570. #define FOO(x) \
  571. do { \
  572. if (blah(x) < 0) \
  573. return -EBUGGERED; \
  574. } while (0)
  575. is a **very** bad idea. It looks like a function call but exits the ``calling``
  576. function; don't break the internal parsers of those who will read the code.
  577. 2) macros that depend on having a local variable with a magic name:
  578. .. code-block:: c
  579. #define FOO(val) bar(index, val)
  580. might look like a good thing, but it's confusing as hell when one reads the
  581. code and it's prone to breakage from seemingly innocent changes.
  582. 3) macros with arguments that are used as l-values: FOO(x) = y; will
  583. bite you if somebody e.g. turns FOO into an inline function.
  584. 4) forgetting about precedence: macros defining constants using expressions
  585. must enclose the expression in parentheses. Beware of similar issues with
  586. macros using parameters.
  587. .. code-block:: c
  588. #define CONSTANT 0x4000
  589. #define CONSTEXP (CONSTANT | 3)
  590. 5) namespace collisions when defining local variables in macros resembling
  591. functions:
  592. .. code-block:: c
  593. #define FOO(x) \
  594. ({ \
  595. typeof(x) ret; \
  596. ret = calc_ret(x); \
  597. (ret); \
  598. })
  599. ret is a common name for a local variable - __foo_ret is less likely
  600. to collide with an existing variable.
  601. The cpp manual deals with macros exhaustively. The gcc internals manual also
  602. covers RTL which is used frequently with assembly language in the kernel.
  603. 13) Printing kernel messages
  604. ----------------------------
  605. Kernel developers like to be seen as literate. Do mind the spelling
  606. of kernel messages to make a good impression. Do not use incorrect
  607. contractions like ``dont``; use ``do not`` or ``don't`` instead. Make the
  608. messages concise, clear, and unambiguous.
  609. Kernel messages do not have to be terminated with a period.
  610. Printing numbers in parentheses (%d) adds no value and should be avoided.
  611. There are a number of driver model diagnostic macros in <linux/device.h>
  612. which you should use to make sure messages are matched to the right device
  613. and driver, and are tagged with the right level: dev_err(), dev_warn(),
  614. dev_info(), and so forth. For messages that aren't associated with a
  615. particular device, <linux/printk.h> defines pr_notice(), pr_info(),
  616. pr_warn(), pr_err(), etc.
  617. Coming up with good debugging messages can be quite a challenge; and once
  618. you have them, they can be a huge help for remote troubleshooting. However
  619. debug message printing is handled differently than printing other non-debug
  620. messages. While the other pr_XXX() functions print unconditionally,
  621. pr_debug() does not; it is compiled out by default, unless either DEBUG is
  622. defined or CONFIG_DYNAMIC_DEBUG is set. That is true for dev_dbg() also,
  623. and a related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to
  624. the ones already enabled by DEBUG.
  625. Many subsystems have Kconfig debug options to turn on -DDEBUG in the
  626. corresponding Makefile; in other cases specific files #define DEBUG. And
  627. when a debug message should be unconditionally printed, such as if it is
  628. already inside a debug-related #ifdef section, printk(KERN_DEBUG ...) can be
  629. used.
  630. 14) Allocating memory
  631. ---------------------
  632. The kernel provides the following general purpose memory allocators:
  633. kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and
  634. vzalloc(). Please refer to the API documentation for further information
  635. about them. :ref:`Documentation/core-api/memory-allocation.rst
  636. <memory_allocation>`
  637. The preferred form for passing a size of a struct is the following:
  638. .. code-block:: c
  639. p = kmalloc(sizeof(*p), ...);
  640. The alternative form where struct name is spelled out hurts readability and
  641. introduces an opportunity for a bug when the pointer variable type is changed
  642. but the corresponding sizeof that is passed to a memory allocator is not.
  643. Casting the return value which is a void pointer is redundant. The conversion
  644. from void pointer to any other pointer type is guaranteed by the C programming
  645. language.
  646. The preferred form for allocating an array is the following:
  647. .. code-block:: c
  648. p = kmalloc_array(n, sizeof(...), ...);
  649. The preferred form for allocating a zeroed array is the following:
  650. .. code-block:: c
  651. p = kcalloc(n, sizeof(...), ...);
  652. Both forms check for overflow on the allocation size n * sizeof(...),
  653. and return NULL if that occurred.
  654. These generic allocation functions all emit a stack dump on failure when used
  655. without __GFP_NOWARN so there is no use in emitting an additional failure
  656. message when NULL is returned.
  657. 15) The inline disease
  658. ----------------------
  659. There appears to be a common misperception that gcc has a magic "make me
  660. faster" speedup option called ``inline``. While the use of inlines can be
  661. appropriate (for example as a means of replacing macros, see Chapter 12), it
  662. very often is not. Abundant use of the inline keyword leads to a much bigger
  663. kernel, which in turn slows the system as a whole down, due to a bigger
  664. icache footprint for the CPU and simply because there is less memory
  665. available for the pagecache. Just think about it; a pagecache miss causes a
  666. disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles
  667. that can go into these 5 milliseconds.
  668. A reasonable rule of thumb is to not put inline at functions that have more
  669. than 3 lines of code in them. An exception to this rule are the cases where
  670. a parameter is known to be a compiletime constant, and as a result of this
  671. constantness you *know* the compiler will be able to optimize most of your
  672. function away at compile time. For a good example of this later case, see
  673. the kmalloc() inline function.
  674. Often people argue that adding inline to functions that are static and used
  675. only once is always a win since there is no space tradeoff. While this is
  676. technically correct, gcc is capable of inlining these automatically without
  677. help, and the maintenance issue of removing the inline when a second user
  678. appears outweighs the potential value of the hint that tells gcc to do
  679. something it would have done anyway.
  680. 16) Function return values and names
  681. ------------------------------------
  682. Functions can return values of many different kinds, and one of the
  683. most common is a value indicating whether the function succeeded or
  684. failed. Such a value can be represented as an error-code integer
  685. (-Exxx = failure, 0 = success) or a ``succeeded`` boolean (0 = failure,
  686. non-zero = success).
  687. Mixing up these two sorts of representations is a fertile source of
  688. difficult-to-find bugs. If the C language included a strong distinction
  689. between integers and booleans then the compiler would find these mistakes
  690. for us... but it doesn't. To help prevent such bugs, always follow this
  691. convention::
  692. If the name of a function is an action or an imperative command,
  693. the function should return an error-code integer. If the name
  694. is a predicate, the function should return a "succeeded" boolean.
  695. For example, ``add work`` is a command, and the add_work() function returns 0
  696. for success or -EBUSY for failure. In the same way, ``PCI device present`` is
  697. a predicate, and the pci_dev_present() function returns 1 if it succeeds in
  698. finding a matching device or 0 if it doesn't.
  699. All EXPORTed functions must respect this convention, and so should all
  700. public functions. Private (static) functions need not, but it is
  701. recommended that they do.
  702. Functions whose return value is the actual result of a computation, rather
  703. than an indication of whether the computation succeeded, are not subject to
  704. this rule. Generally they indicate failure by returning some out-of-range
  705. result. Typical examples would be functions that return pointers; they use
  706. NULL or the ERR_PTR mechanism to report failure.
  707. 17) Using bool
  708. --------------
  709. The Linux kernel bool type is an alias for the C99 _Bool type. bool values can
  710. only evaluate to 0 or 1, and implicit or explicit conversion to bool
  711. automatically converts the value to true or false. When using bool types the
  712. !! construction is not needed, which eliminates a class of bugs.
  713. When working with bool values the true and false definitions should be used
  714. instead of 1 and 0.
  715. bool function return types and stack variables are always fine to use whenever
  716. appropriate. Use of bool is encouraged to improve readability and is often a
  717. better option than 'int' for storing boolean values.
  718. Do not use bool if cache line layout or size of the value matters, as its size
  719. and alignment varies based on the compiled architecture. Structures that are
  720. optimized for alignment and size should not use bool.
  721. If a structure has many true/false values, consider consolidating them into a
  722. bitfield with 1 bit members, or using an appropriate fixed width type, such as
  723. u8.
  724. Similarly for function arguments, many true/false values can be consolidated
  725. into a single bitwise 'flags' argument and 'flags' can often be a more
  726. readable alternative if the call-sites have naked true/false constants.
  727. Otherwise limited use of bool in structures and arguments can improve
  728. readability.
  729. 18) Don't re-invent the kernel macros
  730. -------------------------------------
  731. The header file include/linux/kernel.h contains a number of macros that
  732. you should use, rather than explicitly coding some variant of them yourself.
  733. For example, if you need to calculate the length of an array, take advantage
  734. of the macro
  735. .. code-block:: c
  736. #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
  737. Similarly, if you need to calculate the size of some structure member, use
  738. .. code-block:: c
  739. #define sizeof_field(t, f) (sizeof(((t*)0)->f))
  740. There are also min() and max() macros that do strict type checking if you
  741. need them. Feel free to peruse that header file to see what else is already
  742. defined that you shouldn't reproduce in your code.
  743. 19) Editor modelines and other cruft
  744. ------------------------------------
  745. Some editors can interpret configuration information embedded in source files,
  746. indicated with special markers. For example, emacs interprets lines marked
  747. like this:
  748. .. code-block:: c
  749. -*- mode: c -*-
  750. Or like this:
  751. .. code-block:: c
  752. /*
  753. Local Variables:
  754. compile-command: "gcc -DMAGIC_DEBUG_FLAG foo.c"
  755. End:
  756. */
  757. Vim interprets markers that look like this:
  758. .. code-block:: c
  759. /* vim:set sw=8 noet */
  760. Do not include any of these in source files. People have their own personal
  761. editor configurations, and your source files should not override them. This
  762. includes markers for indentation and mode configuration. People may use their
  763. own custom mode, or may have some other magic method for making indentation
  764. work correctly.
  765. 20) Inline assembly
  766. -------------------
  767. In architecture-specific code, you may need to use inline assembly to interface
  768. with CPU or platform functionality. Don't hesitate to do so when necessary.
  769. However, don't use inline assembly gratuitously when C can do the job. You can
  770. and should poke hardware from C when possible.
  771. Consider writing simple helper functions that wrap common bits of inline
  772. assembly, rather than repeatedly writing them with slight variations. Remember
  773. that inline assembly can use C parameters.
  774. Large, non-trivial assembly functions should go in .S files, with corresponding
  775. C prototypes defined in C header files. The C prototypes for assembly
  776. functions should use ``asmlinkage``.
  777. You may need to mark your asm statement as volatile, to prevent GCC from
  778. removing it if GCC doesn't notice any side effects. You don't always need to
  779. do so, though, and doing so unnecessarily can limit optimization.
  780. When writing a single inline assembly statement containing multiple
  781. instructions, put each instruction on a separate line in a separate quoted
  782. string, and end each string except the last with ``\n\t`` to properly indent
  783. the next instruction in the assembly output:
  784. .. code-block:: c
  785. asm ("magic %reg1, #42\n\t"
  786. "more_magic %reg2, %reg3"
  787. : /* outputs */ : /* inputs */ : /* clobbers */);
  788. 21) Conditional Compilation
  789. ---------------------------
  790. Wherever possible, don't use preprocessor conditionals (#if, #ifdef) in .c
  791. files; doing so makes code harder to read and logic harder to follow. Instead,
  792. use such conditionals in a header file defining functions for use in those .c
  793. files, providing no-op stub versions in the #else case, and then call those
  794. functions unconditionally from .c files. The compiler will avoid generating
  795. any code for the stub calls, producing identical results, but the logic will
  796. remain easy to follow.
  797. Prefer to compile out entire functions, rather than portions of functions or
  798. portions of expressions. Rather than putting an ifdef in an expression, factor
  799. out part or all of the expression into a separate helper function and apply the
  800. conditional to that function.
  801. If you have a function or variable which may potentially go unused in a
  802. particular configuration, and the compiler would warn about its definition
  803. going unused, mark the definition as __maybe_unused rather than wrapping it in
  804. a preprocessor conditional. (However, if a function or variable *always* goes
  805. unused, delete it.)
  806. Within code, where possible, use the IS_ENABLED macro to convert a Kconfig
  807. symbol into a C boolean expression, and use it in a normal C conditional:
  808. .. code-block:: c
  809. if (IS_ENABLED(CONFIG_SOMETHING)) {
  810. ...
  811. }
  812. The compiler will constant-fold the conditional away, and include or exclude
  813. the block of code just as with an #ifdef, so this will not add any runtime
  814. overhead. However, this approach still allows the C compiler to see the code
  815. inside the block, and check it for correctness (syntax, types, symbol
  816. references, etc). Thus, you still have to use an #ifdef if the code inside the
  817. block references symbols that will not exist if the condition is not met.
  818. At the end of any non-trivial #if or #ifdef block (more than a few lines),
  819. place a comment after the #endif on the same line, noting the conditional
  820. expression used. For instance:
  821. .. code-block:: c
  822. #ifdef CONFIG_SOMETHING
  823. ...
  824. #endif /* CONFIG_SOMETHING */
  825. Appendix I) References
  826. ----------------------
  827. The C Programming Language, Second Edition
  828. by Brian W. Kernighan and Dennis M. Ritchie.
  829. Prentice Hall, Inc., 1988.
  830. ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).
  831. The Practice of Programming
  832. by Brian W. Kernighan and Rob Pike.
  833. Addison-Wesley, Inc., 1999.
  834. ISBN 0-201-61586-X.
  835. GNU manuals - where in compliance with K&R and this text - for cpp, gcc,
  836. gcc internals and indent, all available from https://www.gnu.org/manual/
  837. WG14 is the international standardization working group for the programming
  838. language C, URL: http://www.open-std.org/JTC1/SC22/WG14/
  839. Kernel :ref:`process/coding-style.rst <codingstyle>`, by greg@kroah.com at OLS 2002:
  840. http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/