hacking.rst 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. .. _kernel_hacking_hack:
  2. ============================================
  3. Unreliable Guide To Hacking The Linux Kernel
  4. ============================================
  5. :Author: Rusty Russell
  6. Introduction
  7. ============
  8. Welcome, gentle reader, to Rusty's Remarkably Unreliable Guide to Linux
  9. Kernel Hacking. This document describes the common routines and general
  10. requirements for kernel code: its goal is to serve as a primer for Linux
  11. kernel development for experienced C programmers. I avoid implementation
  12. details: that's what the code is for, and I ignore whole tracts of
  13. useful routines.
  14. Before you read this, please understand that I never wanted to write
  15. this document, being grossly under-qualified, but I always wanted to
  16. read it, and this was the only way. I hope it will grow into a
  17. compendium of best practice, common starting points and random
  18. information.
  19. The Players
  20. ===========
  21. At any time each of the CPUs in a system can be:
  22. - not associated with any process, serving a hardware interrupt;
  23. - not associated with any process, serving a softirq or tasklet;
  24. - running in kernel space, associated with a process (user context);
  25. - running a process in user space.
  26. There is an ordering between these. The bottom two can preempt each
  27. other, but above that is a strict hierarchy: each can only be preempted
  28. by the ones above it. For example, while a softirq is running on a CPU,
  29. no other softirq will preempt it, but a hardware interrupt can. However,
  30. any other CPUs in the system execute independently.
  31. We'll see a number of ways that the user context can block interrupts,
  32. to become truly non-preemptable.
  33. User Context
  34. ------------
  35. User context is when you are coming in from a system call or other trap:
  36. like userspace, you can be preempted by more important tasks and by
  37. interrupts. You can sleep, by calling :c:func:`schedule()`.
  38. .. note::
  39. You are always in user context on module load and unload, and on
  40. operations on the block device layer.
  41. In user context, the ``current`` pointer (indicating the task we are
  42. currently executing) is valid, and :c:func:`in_interrupt()`
  43. (``include/linux/preempt.h``) is false.
  44. .. warning::
  45. Beware that if you have preemption or softirqs disabled (see below),
  46. :c:func:`in_interrupt()` will return a false positive.
  47. Hardware Interrupts (Hard IRQs)
  48. -------------------------------
  49. Timer ticks, network cards and keyboard are examples of real hardware
  50. which produce interrupts at any time. The kernel runs interrupt
  51. handlers, which services the hardware. The kernel guarantees that this
  52. handler is never re-entered: if the same interrupt arrives, it is queued
  53. (or dropped). Because it disables interrupts, this handler has to be
  54. fast: frequently it simply acknowledges the interrupt, marks a 'software
  55. interrupt' for execution and exits.
  56. You can tell you are in a hardware interrupt, because in_hardirq() returns
  57. true.
  58. .. warning::
  59. Beware that this will return a false positive if interrupts are
  60. disabled (see below).
  61. Software Interrupt Context: Softirqs and Tasklets
  62. -------------------------------------------------
  63. Whenever a system call is about to return to userspace, or a hardware
  64. interrupt handler exits, any 'software interrupts' which are marked
  65. pending (usually by hardware interrupts) are run (``kernel/softirq.c``).
  66. Much of the real interrupt handling work is done here. Early in the
  67. transition to SMP, there were only 'bottom halves' (BHs), which didn't
  68. take advantage of multiple CPUs. Shortly after we switched from wind-up
  69. computers made of match-sticks and snot, we abandoned this limitation
  70. and switched to 'softirqs'.
  71. ``include/linux/interrupt.h`` lists the different softirqs. A very
  72. important softirq is the timer softirq (``include/linux/timer.h``): you
  73. can register to have it call functions for you in a given length of
  74. time.
  75. Softirqs are often a pain to deal with, since the same softirq will run
  76. simultaneously on more than one CPU. For this reason, tasklets
  77. (``include/linux/interrupt.h``) are more often used: they are
  78. dynamically-registrable (meaning you can have as many as you want), and
  79. they also guarantee that any tasklet will only run on one CPU at any
  80. time, although different tasklets can run simultaneously.
  81. .. warning::
  82. The name 'tasklet' is misleading: they have nothing to do with
  83. 'tasks'.
  84. You can tell you are in a softirq (or tasklet) using the
  85. :c:func:`in_softirq()` macro (``include/linux/preempt.h``).
  86. .. warning::
  87. Beware that this will return a false positive if a
  88. :ref:`bottom half lock <local_bh_disable>` is held.
  89. Some Basic Rules
  90. ================
  91. No memory protection
  92. If you corrupt memory, whether in user context or interrupt context,
  93. the whole machine will crash. Are you sure you can't do what you
  94. want in userspace?
  95. No floating point or MMX
  96. The FPU context is not saved; even in user context the FPU state
  97. probably won't correspond with the current process: you would mess
  98. with some user process' FPU state. If you really want to do this,
  99. you would have to explicitly save/restore the full FPU state (and
  100. avoid context switches). It is generally a bad idea; use fixed point
  101. arithmetic first.
  102. A rigid stack limit
  103. Depending on configuration options the kernel stack is about 3K to
  104. 6K for most 32-bit architectures: it's about 14K on most 64-bit
  105. archs, and often shared with interrupts so you can't use it all.
  106. Avoid deep recursion and huge local arrays on the stack (allocate
  107. them dynamically instead).
  108. The Linux kernel is portable
  109. Let's keep it that way. Your code should be 64-bit clean, and
  110. endian-independent. You should also minimize CPU specific stuff,
  111. e.g. inline assembly should be cleanly encapsulated and minimized to
  112. ease porting. Generally it should be restricted to the
  113. architecture-dependent part of the kernel tree.
  114. ioctls: Not writing a new system call
  115. =====================================
  116. A system call generally looks like this::
  117. asmlinkage long sys_mycall(int arg)
  118. {
  119. return 0;
  120. }
  121. First, in most cases you don't want to create a new system call. You
  122. create a character device and implement an appropriate ioctl for it.
  123. This is much more flexible than system calls, doesn't have to be entered
  124. in every architecture's ``include/asm/unistd.h`` and
  125. ``arch/kernel/entry.S`` file, and is much more likely to be accepted by
  126. Linus.
  127. If all your routine does is read or write some parameter, consider
  128. implementing a :c:func:`sysfs()` interface instead.
  129. Inside the ioctl you're in user context to a process. When a error
  130. occurs you return a negated errno (see
  131. ``include/uapi/asm-generic/errno-base.h``,
  132. ``include/uapi/asm-generic/errno.h`` and ``include/linux/errno.h``),
  133. otherwise you return 0.
  134. After you slept you should check if a signal occurred: the Unix/Linux
  135. way of handling signals is to temporarily exit the system call with the
  136. ``-ERESTARTSYS`` error. The system call entry code will switch back to
  137. user context, process the signal handler and then your system call will
  138. be restarted (unless the user disabled that). So you should be prepared
  139. to process the restart, e.g. if you're in the middle of manipulating
  140. some data structure.
  141. ::
  142. if (signal_pending(current))
  143. return -ERESTARTSYS;
  144. If you're doing longer computations: first think userspace. If you
  145. **really** want to do it in kernel you should regularly check if you need
  146. to give up the CPU (remember there is cooperative multitasking per CPU).
  147. Idiom::
  148. cond_resched(); /* Will sleep */
  149. A short note on interface design: the UNIX system call motto is "Provide
  150. mechanism not policy".
  151. Recipes for Deadlock
  152. ====================
  153. You cannot call any routines which may sleep, unless:
  154. - You are in user context.
  155. - You do not own any spinlocks.
  156. - You have interrupts enabled (actually, Andi Kleen says that the
  157. scheduling code will enable them for you, but that's probably not
  158. what you wanted).
  159. Note that some functions may sleep implicitly: common ones are the user
  160. space access functions (\*_user) and memory allocation functions
  161. without ``GFP_ATOMIC``.
  162. You should always compile your kernel ``CONFIG_DEBUG_ATOMIC_SLEEP`` on,
  163. and it will warn you if you break these rules. If you **do** break the
  164. rules, you will eventually lock up your box.
  165. Really.
  166. Common Routines
  167. ===============
  168. :c:func:`printk()`
  169. ------------------
  170. Defined in ``include/linux/printk.h``
  171. :c:func:`printk()` feeds kernel messages to the console, dmesg, and
  172. the syslog daemon. It is useful for debugging and reporting errors, and
  173. can be used inside interrupt context, but use with caution: a machine
  174. which has its console flooded with printk messages is unusable. It uses
  175. a format string mostly compatible with ANSI C printf, and C string
  176. concatenation to give it a first "priority" argument::
  177. printk(KERN_INFO "i = %u\n", i);
  178. See ``include/linux/kern_levels.h``; for other ``KERN_`` values; these are
  179. interpreted by syslog as the level. Special case: for printing an IP
  180. address use::
  181. __be32 ipaddress;
  182. printk(KERN_INFO "my ip: %pI4\n", &ipaddress);
  183. :c:func:`printk()` internally uses a 1K buffer and does not catch
  184. overruns. Make sure that will be enough.
  185. .. note::
  186. You will know when you are a real kernel hacker when you start
  187. typoing printf as printk in your user programs :)
  188. .. note::
  189. Another sidenote: the original Unix Version 6 sources had a comment
  190. on top of its printf function: "Printf should not be used for
  191. chit-chat". You should follow that advice.
  192. :c:func:`copy_to_user()` / :c:func:`copy_from_user()` / :c:func:`get_user()` / :c:func:`put_user()`
  193. ---------------------------------------------------------------------------------------------------
  194. Defined in ``include/linux/uaccess.h`` / ``asm/uaccess.h``
  195. **[SLEEPS]**
  196. :c:func:`put_user()` and :c:func:`get_user()` are used to get
  197. and put single values (such as an int, char, or long) from and to
  198. userspace. A pointer into userspace should never be simply dereferenced:
  199. data should be copied using these routines. Both return ``-EFAULT`` or
  200. 0.
  201. :c:func:`copy_to_user()` and :c:func:`copy_from_user()` are
  202. more general: they copy an arbitrary amount of data to and from
  203. userspace.
  204. .. warning::
  205. Unlike :c:func:`put_user()` and :c:func:`get_user()`, they
  206. return the amount of uncopied data (ie. 0 still means success).
  207. [Yes, this objectionable interface makes me cringe. The flamewar comes
  208. up every year or so. --RR.]
  209. The functions may sleep implicitly. This should never be called outside
  210. user context (it makes no sense), with interrupts disabled, or a
  211. spinlock held.
  212. :c:func:`kmalloc()`/:c:func:`kfree()`
  213. -------------------------------------
  214. Defined in ``include/linux/slab.h``
  215. **[MAY SLEEP: SEE BELOW]**
  216. These routines are used to dynamically request pointer-aligned chunks of
  217. memory, like malloc and free do in userspace, but
  218. :c:func:`kmalloc()` takes an extra flag word. Important values:
  219. ``GFP_KERNEL``
  220. May sleep and swap to free memory. Only allowed in user context, but
  221. is the most reliable way to allocate memory.
  222. ``GFP_ATOMIC``
  223. Don't sleep. Less reliable than ``GFP_KERNEL``, but may be called
  224. from interrupt context. You should **really** have a good
  225. out-of-memory error-handling strategy.
  226. ``GFP_DMA``
  227. Allocate ISA DMA lower than 16MB. If you don't know what that is you
  228. don't need it. Very unreliable.
  229. If you see a sleeping function called from invalid context warning
  230. message, then maybe you called a sleeping allocation function from
  231. interrupt context without ``GFP_ATOMIC``. You should really fix that.
  232. Run, don't walk.
  233. If you are allocating at least ``PAGE_SIZE`` (``asm/page.h`` or
  234. ``asm/page_types.h``) bytes, consider using :c:func:`__get_free_pages()`
  235. (``include/linux/gfp.h``). It takes an order argument (0 for page sized,
  236. 1 for double page, 2 for four pages etc.) and the same memory priority
  237. flag word as above.
  238. If you are allocating more than a page worth of bytes you can use
  239. :c:func:`vmalloc()`. It'll allocate virtual memory in the kernel
  240. map. This block is not contiguous in physical memory, but the MMU makes
  241. it look like it is for you (so it'll only look contiguous to the CPUs,
  242. not to external device drivers). If you really need large physically
  243. contiguous memory for some weird device, you have a problem: it is
  244. poorly supported in Linux because after some time memory fragmentation
  245. in a running kernel makes it hard. The best way is to allocate the block
  246. early in the boot process via the :c:func:`alloc_bootmem()`
  247. routine.
  248. Before inventing your own cache of often-used objects consider using a
  249. slab cache in ``include/linux/slab.h``
  250. :c:macro:`current`
  251. ------------------
  252. Defined in ``include/asm/current.h``
  253. This global variable (really a macro) contains a pointer to the current
  254. task structure, so is only valid in user context. For example, when a
  255. process makes a system call, this will point to the task structure of
  256. the calling process. It is **not NULL** in interrupt context.
  257. :c:func:`mdelay()`/:c:func:`udelay()`
  258. -------------------------------------
  259. Defined in ``include/asm/delay.h`` / ``include/linux/delay.h``
  260. The :c:func:`udelay()` and :c:func:`ndelay()` functions can be
  261. used for small pauses. Do not use large values with them as you risk
  262. overflow - the helper function :c:func:`mdelay()` is useful here, or
  263. consider :c:func:`msleep()`.
  264. :c:func:`cpu_to_be32()`/:c:func:`be32_to_cpu()`/:c:func:`cpu_to_le32()`/:c:func:`le32_to_cpu()`
  265. -----------------------------------------------------------------------------------------------
  266. Defined in ``include/asm/byteorder.h``
  267. The :c:func:`cpu_to_be32()` family (where the "32" can be replaced
  268. by 64 or 16, and the "be" can be replaced by "le") are the general way
  269. to do endian conversions in the kernel: they return the converted value.
  270. All variations supply the reverse as well:
  271. :c:func:`be32_to_cpu()`, etc.
  272. There are two major variations of these functions: the pointer
  273. variation, such as :c:func:`cpu_to_be32p()`, which take a pointer
  274. to the given type, and return the converted value. The other variation
  275. is the "in-situ" family, such as :c:func:`cpu_to_be32s()`, which
  276. convert value referred to by the pointer, and return void.
  277. :c:func:`local_irq_save()`/:c:func:`local_irq_restore()`
  278. --------------------------------------------------------
  279. Defined in ``include/linux/irqflags.h``
  280. These routines disable hard interrupts on the local CPU, and restore
  281. them. They are reentrant; saving the previous state in their one
  282. ``unsigned long flags`` argument. If you know that interrupts are
  283. enabled, you can simply use :c:func:`local_irq_disable()` and
  284. :c:func:`local_irq_enable()`.
  285. .. _local_bh_disable:
  286. :c:func:`local_bh_disable()`/:c:func:`local_bh_enable()`
  287. --------------------------------------------------------
  288. Defined in ``include/linux/bottom_half.h``
  289. These routines disable soft interrupts on the local CPU, and restore
  290. them. They are reentrant; if soft interrupts were disabled before, they
  291. will still be disabled after this pair of functions has been called.
  292. They prevent softirqs and tasklets from running on the current CPU.
  293. :c:func:`smp_processor_id()`
  294. ----------------------------
  295. Defined in ``include/linux/smp.h``
  296. :c:func:`get_cpu()` disables preemption (so you won't suddenly get
  297. moved to another CPU) and returns the current processor number, between
  298. 0 and ``NR_CPUS``. Note that the CPU numbers are not necessarily
  299. continuous. You return it again with :c:func:`put_cpu()` when you
  300. are done.
  301. If you know you cannot be preempted by another task (ie. you are in
  302. interrupt context, or have preemption disabled) you can use
  303. smp_processor_id().
  304. ``__init``/``__exit``/``__initdata``
  305. ------------------------------------
  306. Defined in ``include/linux/init.h``
  307. After boot, the kernel frees up a special section; functions marked with
  308. ``__init`` and data structures marked with ``__initdata`` are dropped
  309. after boot is complete: similarly modules discard this memory after
  310. initialization. ``__exit`` is used to declare a function which is only
  311. required on exit: the function will be dropped if this file is not
  312. compiled as a module. See the header file for use. Note that it makes no
  313. sense for a function marked with ``__init`` to be exported to modules
  314. with :c:func:`EXPORT_SYMBOL()` or :c:func:`EXPORT_SYMBOL_GPL()`- this
  315. will break.
  316. :c:func:`__initcall()`/:c:func:`module_init()`
  317. ----------------------------------------------
  318. Defined in ``include/linux/init.h`` / ``include/linux/module.h``
  319. Many parts of the kernel are well served as a module
  320. (dynamically-loadable parts of the kernel). Using the
  321. :c:func:`module_init()` and :c:func:`module_exit()` macros it
  322. is easy to write code without #ifdefs which can operate both as a module
  323. or built into the kernel.
  324. The :c:func:`module_init()` macro defines which function is to be
  325. called at module insertion time (if the file is compiled as a module),
  326. or at boot time: if the file is not compiled as a module the
  327. :c:func:`module_init()` macro becomes equivalent to
  328. :c:func:`__initcall()`, which through linker magic ensures that
  329. the function is called on boot.
  330. The function can return a negative error number to cause module loading
  331. to fail (unfortunately, this has no effect if the module is compiled
  332. into the kernel). This function is called in user context with
  333. interrupts enabled, so it can sleep.
  334. :c:func:`module_exit()`
  335. -----------------------
  336. Defined in ``include/linux/module.h``
  337. This macro defines the function to be called at module removal time (or
  338. never, in the case of the file compiled into the kernel). It will only
  339. be called if the module usage count has reached zero. This function can
  340. also sleep, but cannot fail: everything must be cleaned up by the time
  341. it returns.
  342. Note that this macro is optional: if it is not present, your module will
  343. not be removable (except for 'rmmod -f').
  344. :c:func:`try_module_get()`/:c:func:`module_put()`
  345. -------------------------------------------------
  346. Defined in ``include/linux/module.h``
  347. These manipulate the module usage count, to protect against removal (a
  348. module also can't be removed if another module uses one of its exported
  349. symbols: see below). Before calling into module code, you should call
  350. :c:func:`try_module_get()` on that module: if it fails, then the
  351. module is being removed and you should act as if it wasn't there.
  352. Otherwise, you can safely enter the module, and call
  353. :c:func:`module_put()` when you're finished.
  354. Most registerable structures have an owner field, such as in the
  355. :c:type:`struct file_operations <file_operations>` structure.
  356. Set this field to the macro ``THIS_MODULE``.
  357. Wait Queues ``include/linux/wait.h``
  358. ====================================
  359. **[SLEEPS]**
  360. A wait queue is used to wait for someone to wake you up when a certain
  361. condition is true. They must be used carefully to ensure there is no
  362. race condition. You declare a :c:type:`wait_queue_head_t`, and then processes
  363. which want to wait for that condition declare a :c:type:`wait_queue_entry_t`
  364. referring to themselves, and place that in the queue.
  365. Declaring
  366. ---------
  367. You declare a ``wait_queue_head_t`` using the
  368. :c:func:`DECLARE_WAIT_QUEUE_HEAD()` macro, or using the
  369. :c:func:`init_waitqueue_head()` routine in your initialization
  370. code.
  371. Queuing
  372. -------
  373. Placing yourself in the waitqueue is fairly complex, because you must
  374. put yourself in the queue before checking the condition. There is a
  375. macro to do this: :c:func:`wait_event_interruptible()`
  376. (``include/linux/wait.h``) The first argument is the wait queue head, and
  377. the second is an expression which is evaluated; the macro returns 0 when
  378. this expression is true, or ``-ERESTARTSYS`` if a signal is received. The
  379. :c:func:`wait_event()` version ignores signals.
  380. Waking Up Queued Tasks
  381. ----------------------
  382. Call :c:func:`wake_up()` (``include/linux/wait.h``), which will wake
  383. up every process in the queue. The exception is if one has
  384. ``TASK_EXCLUSIVE`` set, in which case the remainder of the queue will
  385. not be woken. There are other variants of this basic function available
  386. in the same header.
  387. Atomic Operations
  388. =================
  389. Certain operations are guaranteed atomic on all platforms. The first
  390. class of operations work on :c:type:`atomic_t` (``include/asm/atomic.h``);
  391. this contains a signed integer (at least 32 bits long), and you must use
  392. these functions to manipulate or read :c:type:`atomic_t` variables.
  393. :c:func:`atomic_read()` and :c:func:`atomic_set()` get and set
  394. the counter, :c:func:`atomic_add()`, :c:func:`atomic_sub()`,
  395. :c:func:`atomic_inc()`, :c:func:`atomic_dec()`, and
  396. :c:func:`atomic_dec_and_test()` (returns true if it was
  397. decremented to zero).
  398. Yes. It returns true (i.e. != 0) if the atomic variable is zero.
  399. Note that these functions are slower than normal arithmetic, and so
  400. should not be used unnecessarily.
  401. The second class of atomic operations is atomic bit operations on an
  402. ``unsigned long``, defined in ``include/linux/bitops.h``. These
  403. operations generally take a pointer to the bit pattern, and a bit
  404. number: 0 is the least significant bit. :c:func:`set_bit()`,
  405. :c:func:`clear_bit()` and :c:func:`change_bit()` set, clear,
  406. and flip the given bit. :c:func:`test_and_set_bit()`,
  407. :c:func:`test_and_clear_bit()` and
  408. :c:func:`test_and_change_bit()` do the same thing, except return
  409. true if the bit was previously set; these are particularly useful for
  410. atomically setting flags.
  411. It is possible to call these operations with bit indices greater than
  412. ``BITS_PER_LONG``. The resulting behavior is strange on big-endian
  413. platforms though so it is a good idea not to do this.
  414. Symbols
  415. =======
  416. Within the kernel proper, the normal linking rules apply (ie. unless a
  417. symbol is declared to be file scope with the ``static`` keyword, it can
  418. be used anywhere in the kernel). However, for modules, a special
  419. exported symbol table is kept which limits the entry points to the
  420. kernel proper. Modules can also export symbols.
  421. :c:func:`EXPORT_SYMBOL()`
  422. -------------------------
  423. Defined in ``include/linux/export.h``
  424. This is the classic method of exporting a symbol: dynamically loaded
  425. modules will be able to use the symbol as normal.
  426. :c:func:`EXPORT_SYMBOL_GPL()`
  427. -----------------------------
  428. Defined in ``include/linux/export.h``
  429. Similar to :c:func:`EXPORT_SYMBOL()` except that the symbols
  430. exported by :c:func:`EXPORT_SYMBOL_GPL()` can only be seen by
  431. modules with a :c:func:`MODULE_LICENSE()` that specifies a GPL
  432. compatible license. It implies that the function is considered an
  433. internal implementation issue, and not really an interface. Some
  434. maintainers and developers may however require EXPORT_SYMBOL_GPL()
  435. when adding any new APIs or functionality.
  436. :c:func:`EXPORT_SYMBOL_NS()`
  437. ----------------------------
  438. Defined in ``include/linux/export.h``
  439. This is the variant of `EXPORT_SYMBOL()` that allows specifying a symbol
  440. namespace. Symbol Namespaces are documented in
  441. Documentation/core-api/symbol-namespaces.rst
  442. :c:func:`EXPORT_SYMBOL_NS_GPL()`
  443. --------------------------------
  444. Defined in ``include/linux/export.h``
  445. This is the variant of `EXPORT_SYMBOL_GPL()` that allows specifying a symbol
  446. namespace. Symbol Namespaces are documented in
  447. Documentation/core-api/symbol-namespaces.rst
  448. Routines and Conventions
  449. ========================
  450. Double-linked lists ``include/linux/list.h``
  451. --------------------------------------------
  452. There used to be three sets of linked-list routines in the kernel
  453. headers, but this one is the winner. If you don't have some particular
  454. pressing need for a single list, it's a good choice.
  455. In particular, :c:func:`list_for_each_entry()` is useful.
  456. Return Conventions
  457. ------------------
  458. For code called in user context, it's very common to defy C convention,
  459. and return 0 for success, and a negative error number (eg. ``-EFAULT``) for
  460. failure. This can be unintuitive at first, but it's fairly widespread in
  461. the kernel.
  462. Using :c:func:`ERR_PTR()` (``include/linux/err.h``) to encode a
  463. negative error number into a pointer, and :c:func:`IS_ERR()` and
  464. :c:func:`PTR_ERR()` to get it back out again: avoids a separate
  465. pointer parameter for the error number. Icky, but in a good way.
  466. Breaking Compilation
  467. --------------------
  468. Linus and the other developers sometimes change function or structure
  469. names in development kernels; this is not done just to keep everyone on
  470. their toes: it reflects a fundamental change (eg. can no longer be
  471. called with interrupts on, or does extra checks, or doesn't do checks
  472. which were caught before). Usually this is accompanied by a fairly
  473. complete note to the appropriate kernel development mailing list; search
  474. the archives. Simply doing a global replace on the file usually makes
  475. things **worse**.
  476. Initializing structure members
  477. ------------------------------
  478. The preferred method of initializing structures is to use designated
  479. initialisers, as defined by ISO C99, eg::
  480. static struct block_device_operations opt_fops = {
  481. .open = opt_open,
  482. .release = opt_release,
  483. .ioctl = opt_ioctl,
  484. .check_media_change = opt_media_change,
  485. };
  486. This makes it easy to grep for, and makes it clear which structure
  487. fields are set. You should do this because it looks cool.
  488. GNU Extensions
  489. --------------
  490. GNU Extensions are explicitly allowed in the Linux kernel. Note that
  491. some of the more complex ones are not very well supported, due to lack
  492. of general use, but the following are considered standard (see the GCC
  493. info page section "C Extensions" for more details - Yes, really the info
  494. page, the man page is only a short summary of the stuff in info).
  495. - Inline functions
  496. - Statement expressions (ie. the ({ and }) constructs).
  497. - Declaring attributes of a function / variable / type
  498. (__attribute__)
  499. - typeof
  500. - Zero length arrays
  501. - Macro varargs
  502. - Arithmetic on void pointers
  503. - Non-Constant initializers
  504. - Assembler Instructions (not outside arch/ and include/asm/)
  505. - Function names as strings (__func__).
  506. - __builtin_constant_p()
  507. Be wary when using long long in the kernel, the code gcc generates for
  508. it is horrible and worse: division and multiplication does not work on
  509. i386 because the GCC runtime functions for it are missing from the
  510. kernel environment.
  511. C++
  512. ---
  513. Using C++ in the kernel is usually a bad idea, because the kernel does
  514. not provide the necessary runtime environment and the include files are
  515. not tested for it. It is still possible, but not recommended. If you
  516. really want to do this, forget about exceptions at least.
  517. #if
  518. ---
  519. It is generally considered cleaner to use macros in header files (or at
  520. the top of .c files) to abstract away functions rather than using \`#if'
  521. pre-processor statements throughout the source code.
  522. Putting Your Stuff in the Kernel
  523. ================================
  524. In order to get your stuff into shape for official inclusion, or even to
  525. make a neat patch, there's administrative work to be done:
  526. - Figure out who are the owners of the code you've been modifying. Look
  527. at the top of the source files, inside the ``MAINTAINERS`` file, and
  528. last of all in the ``CREDITS`` file. You should coordinate with these
  529. people to make sure you're not duplicating effort, or trying something
  530. that's already been rejected.
  531. Make sure you put your name and email address at the top of any files
  532. you create or modify significantly. This is the first place people
  533. will look when they find a bug, or when **they** want to make a change.
  534. - Usually you want a configuration option for your kernel hack. Edit
  535. ``Kconfig`` in the appropriate directory. The Config language is
  536. simple to use by cut and paste, and there's complete documentation in
  537. ``Documentation/kbuild/kconfig-language.rst``.
  538. In your description of the option, make sure you address both the
  539. expert user and the user who knows nothing about your feature.
  540. Mention incompatibilities and issues here. **Definitely** end your
  541. description with “if in doubt, say N” (or, occasionally, \`Y'); this
  542. is for people who have no idea what you are talking about.
  543. - Edit the ``Makefile``: the CONFIG variables are exported here so you
  544. can usually just add a "obj-$(CONFIG_xxx) += xxx.o" line. The syntax
  545. is documented in ``Documentation/kbuild/makefiles.rst``.
  546. - Put yourself in ``CREDITS`` if you consider what you've done
  547. noteworthy, usually beyond a single file (your name should be at the
  548. top of the source files anyway). ``MAINTAINERS`` means you want to be
  549. consulted when changes are made to a subsystem, and hear about bugs;
  550. it implies a more-than-passing commitment to some part of the code.
  551. - Finally, don't forget to read
  552. ``Documentation/process/submitting-patches.rst``
  553. Kernel Cantrips
  554. ===============
  555. Some favorites from browsing the source. Feel free to add to this list.
  556. ``arch/x86/include/asm/delay.h``::
  557. #define ndelay(n) (__builtin_constant_p(n) ? \
  558. ((n) > 20000 ? __bad_ndelay() : __const_udelay((n) * 5ul)) : \
  559. __ndelay(n))
  560. ``include/linux/fs.h``::
  561. /*
  562. * Kernel pointers have redundant information, so we can use a
  563. * scheme where we can return either an error code or a dentry
  564. * pointer with the same return value.
  565. *
  566. * This should be a per-architecture thing, to allow different
  567. * error and pointer decisions.
  568. */
  569. #define ERR_PTR(err) ((void *)((long)(err)))
  570. #define PTR_ERR(ptr) ((long)(ptr))
  571. #define IS_ERR(ptr) ((unsigned long)(ptr) > (unsigned long)(-1000))
  572. ``arch/x86/include/asm/uaccess_32.h:``::
  573. #define copy_to_user(to,from,n) \
  574. (__builtin_constant_p(n) ? \
  575. __constant_copy_to_user((to),(from),(n)) : \
  576. __generic_copy_to_user((to),(from),(n)))
  577. ``arch/sparc/kernel/head.S:``::
  578. /*
  579. * Sun people can't spell worth damn. "compatability" indeed.
  580. * At least we *know* we can't spell, and use a spell-checker.
  581. */
  582. /* Uh, actually Linus it is I who cannot spell. Too much murky
  583. * Sparc assembly will do this to ya.
  584. */
  585. C_LABEL(cputypvar):
  586. .asciz "compatibility"
  587. /* Tested on SS-5, SS-10. Probably someone at Sun applied a spell-checker. */
  588. .align 4
  589. C_LABEL(cputypvar_sun4m):
  590. .asciz "compatible"
  591. ``arch/sparc/lib/checksum.S:``::
  592. /* Sun, you just can't beat me, you just can't. Stop trying,
  593. * give up. I'm serious, I am going to kick the living shit
  594. * out of you, game over, lights out.
  595. */
  596. Thanks
  597. ======
  598. Thanks to Andi Kleen for the idea, answering my questions, fixing my
  599. mistakes, filling content, etc. Philipp Rumpf for more spelling and
  600. clarity fixes, and some excellent non-obvious points. Werner Almesberger
  601. for giving me a great summary of :c:func:`disable_irq()`, and Jes
  602. Sorensen and Andrea Arcangeli added caveats. Michael Elizabeth Chastain
  603. for checking and adding to the Configure section. Telsa Gwynne for
  604. teaching me DocBook.