coding-style.rst 44 KB

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