162306a36Sopenharmony_ci.. _kernel_hacking_hack:
262306a36Sopenharmony_ci
362306a36Sopenharmony_ci============================================
462306a36Sopenharmony_ciUnreliable Guide To Hacking The Linux Kernel
562306a36Sopenharmony_ci============================================
662306a36Sopenharmony_ci
762306a36Sopenharmony_ci:Author: Rusty Russell
862306a36Sopenharmony_ci
962306a36Sopenharmony_ciIntroduction
1062306a36Sopenharmony_ci============
1162306a36Sopenharmony_ci
1262306a36Sopenharmony_ciWelcome, gentle reader, to Rusty's Remarkably Unreliable Guide to Linux
1362306a36Sopenharmony_ciKernel Hacking. This document describes the common routines and general
1462306a36Sopenharmony_cirequirements for kernel code: its goal is to serve as a primer for Linux
1562306a36Sopenharmony_cikernel development for experienced C programmers. I avoid implementation
1662306a36Sopenharmony_cidetails: that's what the code is for, and I ignore whole tracts of
1762306a36Sopenharmony_ciuseful routines.
1862306a36Sopenharmony_ci
1962306a36Sopenharmony_ciBefore you read this, please understand that I never wanted to write
2062306a36Sopenharmony_cithis document, being grossly under-qualified, but I always wanted to
2162306a36Sopenharmony_ciread it, and this was the only way. I hope it will grow into a
2262306a36Sopenharmony_cicompendium of best practice, common starting points and random
2362306a36Sopenharmony_ciinformation.
2462306a36Sopenharmony_ci
2562306a36Sopenharmony_ciThe Players
2662306a36Sopenharmony_ci===========
2762306a36Sopenharmony_ci
2862306a36Sopenharmony_ciAt any time each of the CPUs in a system can be:
2962306a36Sopenharmony_ci
3062306a36Sopenharmony_ci-  not associated with any process, serving a hardware interrupt;
3162306a36Sopenharmony_ci
3262306a36Sopenharmony_ci-  not associated with any process, serving a softirq or tasklet;
3362306a36Sopenharmony_ci
3462306a36Sopenharmony_ci-  running in kernel space, associated with a process (user context);
3562306a36Sopenharmony_ci
3662306a36Sopenharmony_ci-  running a process in user space.
3762306a36Sopenharmony_ci
3862306a36Sopenharmony_ciThere is an ordering between these. The bottom two can preempt each
3962306a36Sopenharmony_ciother, but above that is a strict hierarchy: each can only be preempted
4062306a36Sopenharmony_ciby the ones above it. For example, while a softirq is running on a CPU,
4162306a36Sopenharmony_cino other softirq will preempt it, but a hardware interrupt can. However,
4262306a36Sopenharmony_ciany other CPUs in the system execute independently.
4362306a36Sopenharmony_ci
4462306a36Sopenharmony_ciWe'll see a number of ways that the user context can block interrupts,
4562306a36Sopenharmony_cito become truly non-preemptable.
4662306a36Sopenharmony_ci
4762306a36Sopenharmony_ciUser Context
4862306a36Sopenharmony_ci------------
4962306a36Sopenharmony_ci
5062306a36Sopenharmony_ciUser context is when you are coming in from a system call or other trap:
5162306a36Sopenharmony_cilike userspace, you can be preempted by more important tasks and by
5262306a36Sopenharmony_ciinterrupts. You can sleep, by calling :c:func:`schedule()`.
5362306a36Sopenharmony_ci
5462306a36Sopenharmony_ci.. note::
5562306a36Sopenharmony_ci
5662306a36Sopenharmony_ci    You are always in user context on module load and unload, and on
5762306a36Sopenharmony_ci    operations on the block device layer.
5862306a36Sopenharmony_ci
5962306a36Sopenharmony_ciIn user context, the ``current`` pointer (indicating the task we are
6062306a36Sopenharmony_cicurrently executing) is valid, and :c:func:`in_interrupt()`
6162306a36Sopenharmony_ci(``include/linux/preempt.h``) is false.
6262306a36Sopenharmony_ci
6362306a36Sopenharmony_ci.. warning::
6462306a36Sopenharmony_ci
6562306a36Sopenharmony_ci    Beware that if you have preemption or softirqs disabled (see below),
6662306a36Sopenharmony_ci    :c:func:`in_interrupt()` will return a false positive.
6762306a36Sopenharmony_ci
6862306a36Sopenharmony_ciHardware Interrupts (Hard IRQs)
6962306a36Sopenharmony_ci-------------------------------
7062306a36Sopenharmony_ci
7162306a36Sopenharmony_ciTimer ticks, network cards and keyboard are examples of real hardware
7262306a36Sopenharmony_ciwhich produce interrupts at any time. The kernel runs interrupt
7362306a36Sopenharmony_cihandlers, which services the hardware. The kernel guarantees that this
7462306a36Sopenharmony_cihandler is never re-entered: if the same interrupt arrives, it is queued
7562306a36Sopenharmony_ci(or dropped). Because it disables interrupts, this handler has to be
7662306a36Sopenharmony_cifast: frequently it simply acknowledges the interrupt, marks a 'software
7762306a36Sopenharmony_ciinterrupt' for execution and exits.
7862306a36Sopenharmony_ci
7962306a36Sopenharmony_ciYou can tell you are in a hardware interrupt, because in_hardirq() returns
8062306a36Sopenharmony_citrue.
8162306a36Sopenharmony_ci
8262306a36Sopenharmony_ci.. warning::
8362306a36Sopenharmony_ci
8462306a36Sopenharmony_ci    Beware that this will return a false positive if interrupts are
8562306a36Sopenharmony_ci    disabled (see below).
8662306a36Sopenharmony_ci
8762306a36Sopenharmony_ciSoftware Interrupt Context: Softirqs and Tasklets
8862306a36Sopenharmony_ci-------------------------------------------------
8962306a36Sopenharmony_ci
9062306a36Sopenharmony_ciWhenever a system call is about to return to userspace, or a hardware
9162306a36Sopenharmony_ciinterrupt handler exits, any 'software interrupts' which are marked
9262306a36Sopenharmony_cipending (usually by hardware interrupts) are run (``kernel/softirq.c``).
9362306a36Sopenharmony_ci
9462306a36Sopenharmony_ciMuch of the real interrupt handling work is done here. Early in the
9562306a36Sopenharmony_citransition to SMP, there were only 'bottom halves' (BHs), which didn't
9662306a36Sopenharmony_citake advantage of multiple CPUs. Shortly after we switched from wind-up
9762306a36Sopenharmony_cicomputers made of match-sticks and snot, we abandoned this limitation
9862306a36Sopenharmony_ciand switched to 'softirqs'.
9962306a36Sopenharmony_ci
10062306a36Sopenharmony_ci``include/linux/interrupt.h`` lists the different softirqs. A very
10162306a36Sopenharmony_ciimportant softirq is the timer softirq (``include/linux/timer.h``): you
10262306a36Sopenharmony_cican register to have it call functions for you in a given length of
10362306a36Sopenharmony_citime.
10462306a36Sopenharmony_ci
10562306a36Sopenharmony_ciSoftirqs are often a pain to deal with, since the same softirq will run
10662306a36Sopenharmony_cisimultaneously on more than one CPU. For this reason, tasklets
10762306a36Sopenharmony_ci(``include/linux/interrupt.h``) are more often used: they are
10862306a36Sopenharmony_cidynamically-registrable (meaning you can have as many as you want), and
10962306a36Sopenharmony_cithey also guarantee that any tasklet will only run on one CPU at any
11062306a36Sopenharmony_citime, although different tasklets can run simultaneously.
11162306a36Sopenharmony_ci
11262306a36Sopenharmony_ci.. warning::
11362306a36Sopenharmony_ci
11462306a36Sopenharmony_ci    The name 'tasklet' is misleading: they have nothing to do with
11562306a36Sopenharmony_ci    'tasks'.
11662306a36Sopenharmony_ci
11762306a36Sopenharmony_ciYou can tell you are in a softirq (or tasklet) using the
11862306a36Sopenharmony_ci:c:func:`in_softirq()` macro (``include/linux/preempt.h``).
11962306a36Sopenharmony_ci
12062306a36Sopenharmony_ci.. warning::
12162306a36Sopenharmony_ci
12262306a36Sopenharmony_ci    Beware that this will return a false positive if a
12362306a36Sopenharmony_ci    :ref:`bottom half lock <local_bh_disable>` is held.
12462306a36Sopenharmony_ci
12562306a36Sopenharmony_ciSome Basic Rules
12662306a36Sopenharmony_ci================
12762306a36Sopenharmony_ci
12862306a36Sopenharmony_ciNo memory protection
12962306a36Sopenharmony_ci    If you corrupt memory, whether in user context or interrupt context,
13062306a36Sopenharmony_ci    the whole machine will crash. Are you sure you can't do what you
13162306a36Sopenharmony_ci    want in userspace?
13262306a36Sopenharmony_ci
13362306a36Sopenharmony_ciNo floating point or MMX
13462306a36Sopenharmony_ci    The FPU context is not saved; even in user context the FPU state
13562306a36Sopenharmony_ci    probably won't correspond with the current process: you would mess
13662306a36Sopenharmony_ci    with some user process' FPU state. If you really want to do this,
13762306a36Sopenharmony_ci    you would have to explicitly save/restore the full FPU state (and
13862306a36Sopenharmony_ci    avoid context switches). It is generally a bad idea; use fixed point
13962306a36Sopenharmony_ci    arithmetic first.
14062306a36Sopenharmony_ci
14162306a36Sopenharmony_ciA rigid stack limit
14262306a36Sopenharmony_ci    Depending on configuration options the kernel stack is about 3K to
14362306a36Sopenharmony_ci    6K for most 32-bit architectures: it's about 14K on most 64-bit
14462306a36Sopenharmony_ci    archs, and often shared with interrupts so you can't use it all.
14562306a36Sopenharmony_ci    Avoid deep recursion and huge local arrays on the stack (allocate
14662306a36Sopenharmony_ci    them dynamically instead).
14762306a36Sopenharmony_ci
14862306a36Sopenharmony_ciThe Linux kernel is portable
14962306a36Sopenharmony_ci    Let's keep it that way. Your code should be 64-bit clean, and
15062306a36Sopenharmony_ci    endian-independent. You should also minimize CPU specific stuff,
15162306a36Sopenharmony_ci    e.g. inline assembly should be cleanly encapsulated and minimized to
15262306a36Sopenharmony_ci    ease porting. Generally it should be restricted to the
15362306a36Sopenharmony_ci    architecture-dependent part of the kernel tree.
15462306a36Sopenharmony_ci
15562306a36Sopenharmony_ciioctls: Not writing a new system call
15662306a36Sopenharmony_ci=====================================
15762306a36Sopenharmony_ci
15862306a36Sopenharmony_ciA system call generally looks like this::
15962306a36Sopenharmony_ci
16062306a36Sopenharmony_ci    asmlinkage long sys_mycall(int arg)
16162306a36Sopenharmony_ci    {
16262306a36Sopenharmony_ci            return 0;
16362306a36Sopenharmony_ci    }
16462306a36Sopenharmony_ci
16562306a36Sopenharmony_ci
16662306a36Sopenharmony_ciFirst, in most cases you don't want to create a new system call. You
16762306a36Sopenharmony_cicreate a character device and implement an appropriate ioctl for it.
16862306a36Sopenharmony_ciThis is much more flexible than system calls, doesn't have to be entered
16962306a36Sopenharmony_ciin every architecture's ``include/asm/unistd.h`` and
17062306a36Sopenharmony_ci``arch/kernel/entry.S`` file, and is much more likely to be accepted by
17162306a36Sopenharmony_ciLinus.
17262306a36Sopenharmony_ci
17362306a36Sopenharmony_ciIf all your routine does is read or write some parameter, consider
17462306a36Sopenharmony_ciimplementing a :c:func:`sysfs()` interface instead.
17562306a36Sopenharmony_ci
17662306a36Sopenharmony_ciInside the ioctl you're in user context to a process. When a error
17762306a36Sopenharmony_cioccurs you return a negated errno (see
17862306a36Sopenharmony_ci``include/uapi/asm-generic/errno-base.h``,
17962306a36Sopenharmony_ci``include/uapi/asm-generic/errno.h`` and ``include/linux/errno.h``),
18062306a36Sopenharmony_ciotherwise you return 0.
18162306a36Sopenharmony_ci
18262306a36Sopenharmony_ciAfter you slept you should check if a signal occurred: the Unix/Linux
18362306a36Sopenharmony_ciway of handling signals is to temporarily exit the system call with the
18462306a36Sopenharmony_ci``-ERESTARTSYS`` error. The system call entry code will switch back to
18562306a36Sopenharmony_ciuser context, process the signal handler and then your system call will
18662306a36Sopenharmony_cibe restarted (unless the user disabled that). So you should be prepared
18762306a36Sopenharmony_cito process the restart, e.g. if you're in the middle of manipulating
18862306a36Sopenharmony_cisome data structure.
18962306a36Sopenharmony_ci
19062306a36Sopenharmony_ci::
19162306a36Sopenharmony_ci
19262306a36Sopenharmony_ci    if (signal_pending(current))
19362306a36Sopenharmony_ci            return -ERESTARTSYS;
19462306a36Sopenharmony_ci
19562306a36Sopenharmony_ci
19662306a36Sopenharmony_ciIf you're doing longer computations: first think userspace. If you
19762306a36Sopenharmony_ci**really** want to do it in kernel you should regularly check if you need
19862306a36Sopenharmony_cito give up the CPU (remember there is cooperative multitasking per CPU).
19962306a36Sopenharmony_ciIdiom::
20062306a36Sopenharmony_ci
20162306a36Sopenharmony_ci    cond_resched(); /* Will sleep */
20262306a36Sopenharmony_ci
20362306a36Sopenharmony_ci
20462306a36Sopenharmony_ciA short note on interface design: the UNIX system call motto is "Provide
20562306a36Sopenharmony_cimechanism not policy".
20662306a36Sopenharmony_ci
20762306a36Sopenharmony_ciRecipes for Deadlock
20862306a36Sopenharmony_ci====================
20962306a36Sopenharmony_ci
21062306a36Sopenharmony_ciYou cannot call any routines which may sleep, unless:
21162306a36Sopenharmony_ci
21262306a36Sopenharmony_ci-  You are in user context.
21362306a36Sopenharmony_ci
21462306a36Sopenharmony_ci-  You do not own any spinlocks.
21562306a36Sopenharmony_ci
21662306a36Sopenharmony_ci-  You have interrupts enabled (actually, Andi Kleen says that the
21762306a36Sopenharmony_ci   scheduling code will enable them for you, but that's probably not
21862306a36Sopenharmony_ci   what you wanted).
21962306a36Sopenharmony_ci
22062306a36Sopenharmony_ciNote that some functions may sleep implicitly: common ones are the user
22162306a36Sopenharmony_cispace access functions (\*_user) and memory allocation functions
22262306a36Sopenharmony_ciwithout ``GFP_ATOMIC``.
22362306a36Sopenharmony_ci
22462306a36Sopenharmony_ciYou should always compile your kernel ``CONFIG_DEBUG_ATOMIC_SLEEP`` on,
22562306a36Sopenharmony_ciand it will warn you if you break these rules. If you **do** break the
22662306a36Sopenharmony_cirules, you will eventually lock up your box.
22762306a36Sopenharmony_ci
22862306a36Sopenharmony_ciReally.
22962306a36Sopenharmony_ci
23062306a36Sopenharmony_ciCommon Routines
23162306a36Sopenharmony_ci===============
23262306a36Sopenharmony_ci
23362306a36Sopenharmony_ci:c:func:`printk()`
23462306a36Sopenharmony_ci------------------
23562306a36Sopenharmony_ci
23662306a36Sopenharmony_ciDefined in ``include/linux/printk.h``
23762306a36Sopenharmony_ci
23862306a36Sopenharmony_ci:c:func:`printk()` feeds kernel messages to the console, dmesg, and
23962306a36Sopenharmony_cithe syslog daemon. It is useful for debugging and reporting errors, and
24062306a36Sopenharmony_cican be used inside interrupt context, but use with caution: a machine
24162306a36Sopenharmony_ciwhich has its console flooded with printk messages is unusable. It uses
24262306a36Sopenharmony_cia format string mostly compatible with ANSI C printf, and C string
24362306a36Sopenharmony_ciconcatenation to give it a first "priority" argument::
24462306a36Sopenharmony_ci
24562306a36Sopenharmony_ci    printk(KERN_INFO "i = %u\n", i);
24662306a36Sopenharmony_ci
24762306a36Sopenharmony_ci
24862306a36Sopenharmony_ciSee ``include/linux/kern_levels.h``; for other ``KERN_`` values; these are
24962306a36Sopenharmony_ciinterpreted by syslog as the level. Special case: for printing an IP
25062306a36Sopenharmony_ciaddress use::
25162306a36Sopenharmony_ci
25262306a36Sopenharmony_ci    __be32 ipaddress;
25362306a36Sopenharmony_ci    printk(KERN_INFO "my ip: %pI4\n", &ipaddress);
25462306a36Sopenharmony_ci
25562306a36Sopenharmony_ci
25662306a36Sopenharmony_ci:c:func:`printk()` internally uses a 1K buffer and does not catch
25762306a36Sopenharmony_cioverruns. Make sure that will be enough.
25862306a36Sopenharmony_ci
25962306a36Sopenharmony_ci.. note::
26062306a36Sopenharmony_ci
26162306a36Sopenharmony_ci    You will know when you are a real kernel hacker when you start
26262306a36Sopenharmony_ci    typoing printf as printk in your user programs :)
26362306a36Sopenharmony_ci
26462306a36Sopenharmony_ci.. note::
26562306a36Sopenharmony_ci
26662306a36Sopenharmony_ci    Another sidenote: the original Unix Version 6 sources had a comment
26762306a36Sopenharmony_ci    on top of its printf function: "Printf should not be used for
26862306a36Sopenharmony_ci    chit-chat". You should follow that advice.
26962306a36Sopenharmony_ci
27062306a36Sopenharmony_ci:c:func:`copy_to_user()` / :c:func:`copy_from_user()` / :c:func:`get_user()` / :c:func:`put_user()`
27162306a36Sopenharmony_ci---------------------------------------------------------------------------------------------------
27262306a36Sopenharmony_ci
27362306a36Sopenharmony_ciDefined in ``include/linux/uaccess.h`` / ``asm/uaccess.h``
27462306a36Sopenharmony_ci
27562306a36Sopenharmony_ci**[SLEEPS]**
27662306a36Sopenharmony_ci
27762306a36Sopenharmony_ci:c:func:`put_user()` and :c:func:`get_user()` are used to get
27862306a36Sopenharmony_ciand put single values (such as an int, char, or long) from and to
27962306a36Sopenharmony_ciuserspace. A pointer into userspace should never be simply dereferenced:
28062306a36Sopenharmony_cidata should be copied using these routines. Both return ``-EFAULT`` or
28162306a36Sopenharmony_ci0.
28262306a36Sopenharmony_ci
28362306a36Sopenharmony_ci:c:func:`copy_to_user()` and :c:func:`copy_from_user()` are
28462306a36Sopenharmony_cimore general: they copy an arbitrary amount of data to and from
28562306a36Sopenharmony_ciuserspace.
28662306a36Sopenharmony_ci
28762306a36Sopenharmony_ci.. warning::
28862306a36Sopenharmony_ci
28962306a36Sopenharmony_ci    Unlike :c:func:`put_user()` and :c:func:`get_user()`, they
29062306a36Sopenharmony_ci    return the amount of uncopied data (ie. 0 still means success).
29162306a36Sopenharmony_ci
29262306a36Sopenharmony_ci[Yes, this objectionable interface makes me cringe. The flamewar comes
29362306a36Sopenharmony_ciup every year or so. --RR.]
29462306a36Sopenharmony_ci
29562306a36Sopenharmony_ciThe functions may sleep implicitly. This should never be called outside
29662306a36Sopenharmony_ciuser context (it makes no sense), with interrupts disabled, or a
29762306a36Sopenharmony_cispinlock held.
29862306a36Sopenharmony_ci
29962306a36Sopenharmony_ci:c:func:`kmalloc()`/:c:func:`kfree()`
30062306a36Sopenharmony_ci-------------------------------------
30162306a36Sopenharmony_ci
30262306a36Sopenharmony_ciDefined in ``include/linux/slab.h``
30362306a36Sopenharmony_ci
30462306a36Sopenharmony_ci**[MAY SLEEP: SEE BELOW]**
30562306a36Sopenharmony_ci
30662306a36Sopenharmony_ciThese routines are used to dynamically request pointer-aligned chunks of
30762306a36Sopenharmony_cimemory, like malloc and free do in userspace, but
30862306a36Sopenharmony_ci:c:func:`kmalloc()` takes an extra flag word. Important values:
30962306a36Sopenharmony_ci
31062306a36Sopenharmony_ci``GFP_KERNEL``
31162306a36Sopenharmony_ci    May sleep and swap to free memory. Only allowed in user context, but
31262306a36Sopenharmony_ci    is the most reliable way to allocate memory.
31362306a36Sopenharmony_ci
31462306a36Sopenharmony_ci``GFP_ATOMIC``
31562306a36Sopenharmony_ci    Don't sleep. Less reliable than ``GFP_KERNEL``, but may be called
31662306a36Sopenharmony_ci    from interrupt context. You should **really** have a good
31762306a36Sopenharmony_ci    out-of-memory error-handling strategy.
31862306a36Sopenharmony_ci
31962306a36Sopenharmony_ci``GFP_DMA``
32062306a36Sopenharmony_ci    Allocate ISA DMA lower than 16MB. If you don't know what that is you
32162306a36Sopenharmony_ci    don't need it. Very unreliable.
32262306a36Sopenharmony_ci
32362306a36Sopenharmony_ciIf you see a sleeping function called from invalid context warning
32462306a36Sopenharmony_cimessage, then maybe you called a sleeping allocation function from
32562306a36Sopenharmony_ciinterrupt context without ``GFP_ATOMIC``. You should really fix that.
32662306a36Sopenharmony_ciRun, don't walk.
32762306a36Sopenharmony_ci
32862306a36Sopenharmony_ciIf you are allocating at least ``PAGE_SIZE`` (``asm/page.h`` or
32962306a36Sopenharmony_ci``asm/page_types.h``) bytes, consider using :c:func:`__get_free_pages()`
33062306a36Sopenharmony_ci(``include/linux/gfp.h``). It takes an order argument (0 for page sized,
33162306a36Sopenharmony_ci1 for double page, 2 for four pages etc.) and the same memory priority
33262306a36Sopenharmony_ciflag word as above.
33362306a36Sopenharmony_ci
33462306a36Sopenharmony_ciIf you are allocating more than a page worth of bytes you can use
33562306a36Sopenharmony_ci:c:func:`vmalloc()`. It'll allocate virtual memory in the kernel
33662306a36Sopenharmony_cimap. This block is not contiguous in physical memory, but the MMU makes
33762306a36Sopenharmony_ciit look like it is for you (so it'll only look contiguous to the CPUs,
33862306a36Sopenharmony_cinot to external device drivers). If you really need large physically
33962306a36Sopenharmony_cicontiguous memory for some weird device, you have a problem: it is
34062306a36Sopenharmony_cipoorly supported in Linux because after some time memory fragmentation
34162306a36Sopenharmony_ciin a running kernel makes it hard. The best way is to allocate the block
34262306a36Sopenharmony_ciearly in the boot process via the :c:func:`alloc_bootmem()`
34362306a36Sopenharmony_ciroutine.
34462306a36Sopenharmony_ci
34562306a36Sopenharmony_ciBefore inventing your own cache of often-used objects consider using a
34662306a36Sopenharmony_cislab cache in ``include/linux/slab.h``
34762306a36Sopenharmony_ci
34862306a36Sopenharmony_ci:c:macro:`current`
34962306a36Sopenharmony_ci------------------
35062306a36Sopenharmony_ci
35162306a36Sopenharmony_ciDefined in ``include/asm/current.h``
35262306a36Sopenharmony_ci
35362306a36Sopenharmony_ciThis global variable (really a macro) contains a pointer to the current
35462306a36Sopenharmony_citask structure, so is only valid in user context. For example, when a
35562306a36Sopenharmony_ciprocess makes a system call, this will point to the task structure of
35662306a36Sopenharmony_cithe calling process. It is **not NULL** in interrupt context.
35762306a36Sopenharmony_ci
35862306a36Sopenharmony_ci:c:func:`mdelay()`/:c:func:`udelay()`
35962306a36Sopenharmony_ci-------------------------------------
36062306a36Sopenharmony_ci
36162306a36Sopenharmony_ciDefined in ``include/asm/delay.h`` / ``include/linux/delay.h``
36262306a36Sopenharmony_ci
36362306a36Sopenharmony_ciThe :c:func:`udelay()` and :c:func:`ndelay()` functions can be
36462306a36Sopenharmony_ciused for small pauses. Do not use large values with them as you risk
36562306a36Sopenharmony_cioverflow - the helper function :c:func:`mdelay()` is useful here, or
36662306a36Sopenharmony_ciconsider :c:func:`msleep()`.
36762306a36Sopenharmony_ci
36862306a36Sopenharmony_ci:c:func:`cpu_to_be32()`/:c:func:`be32_to_cpu()`/:c:func:`cpu_to_le32()`/:c:func:`le32_to_cpu()`
36962306a36Sopenharmony_ci-----------------------------------------------------------------------------------------------
37062306a36Sopenharmony_ci
37162306a36Sopenharmony_ciDefined in ``include/asm/byteorder.h``
37262306a36Sopenharmony_ci
37362306a36Sopenharmony_ciThe :c:func:`cpu_to_be32()` family (where the "32" can be replaced
37462306a36Sopenharmony_ciby 64 or 16, and the "be" can be replaced by "le") are the general way
37562306a36Sopenharmony_cito do endian conversions in the kernel: they return the converted value.
37662306a36Sopenharmony_ciAll variations supply the reverse as well:
37762306a36Sopenharmony_ci:c:func:`be32_to_cpu()`, etc.
37862306a36Sopenharmony_ci
37962306a36Sopenharmony_ciThere are two major variations of these functions: the pointer
38062306a36Sopenharmony_civariation, such as :c:func:`cpu_to_be32p()`, which take a pointer
38162306a36Sopenharmony_cito the given type, and return the converted value. The other variation
38262306a36Sopenharmony_ciis the "in-situ" family, such as :c:func:`cpu_to_be32s()`, which
38362306a36Sopenharmony_ciconvert value referred to by the pointer, and return void.
38462306a36Sopenharmony_ci
38562306a36Sopenharmony_ci:c:func:`local_irq_save()`/:c:func:`local_irq_restore()`
38662306a36Sopenharmony_ci--------------------------------------------------------
38762306a36Sopenharmony_ci
38862306a36Sopenharmony_ciDefined in ``include/linux/irqflags.h``
38962306a36Sopenharmony_ci
39062306a36Sopenharmony_ciThese routines disable hard interrupts on the local CPU, and restore
39162306a36Sopenharmony_cithem. They are reentrant; saving the previous state in their one
39262306a36Sopenharmony_ci``unsigned long flags`` argument. If you know that interrupts are
39362306a36Sopenharmony_cienabled, you can simply use :c:func:`local_irq_disable()` and
39462306a36Sopenharmony_ci:c:func:`local_irq_enable()`.
39562306a36Sopenharmony_ci
39662306a36Sopenharmony_ci.. _local_bh_disable:
39762306a36Sopenharmony_ci
39862306a36Sopenharmony_ci:c:func:`local_bh_disable()`/:c:func:`local_bh_enable()`
39962306a36Sopenharmony_ci--------------------------------------------------------
40062306a36Sopenharmony_ci
40162306a36Sopenharmony_ciDefined in ``include/linux/bottom_half.h``
40262306a36Sopenharmony_ci
40362306a36Sopenharmony_ci
40462306a36Sopenharmony_ciThese routines disable soft interrupts on the local CPU, and restore
40562306a36Sopenharmony_cithem. They are reentrant; if soft interrupts were disabled before, they
40662306a36Sopenharmony_ciwill still be disabled after this pair of functions has been called.
40762306a36Sopenharmony_ciThey prevent softirqs and tasklets from running on the current CPU.
40862306a36Sopenharmony_ci
40962306a36Sopenharmony_ci:c:func:`smp_processor_id()`
41062306a36Sopenharmony_ci----------------------------
41162306a36Sopenharmony_ci
41262306a36Sopenharmony_ciDefined in ``include/linux/smp.h``
41362306a36Sopenharmony_ci
41462306a36Sopenharmony_ci:c:func:`get_cpu()` disables preemption (so you won't suddenly get
41562306a36Sopenharmony_cimoved to another CPU) and returns the current processor number, between
41662306a36Sopenharmony_ci0 and ``NR_CPUS``. Note that the CPU numbers are not necessarily
41762306a36Sopenharmony_cicontinuous. You return it again with :c:func:`put_cpu()` when you
41862306a36Sopenharmony_ciare done.
41962306a36Sopenharmony_ci
42062306a36Sopenharmony_ciIf you know you cannot be preempted by another task (ie. you are in
42162306a36Sopenharmony_ciinterrupt context, or have preemption disabled) you can use
42262306a36Sopenharmony_cismp_processor_id().
42362306a36Sopenharmony_ci
42462306a36Sopenharmony_ci``__init``/``__exit``/``__initdata``
42562306a36Sopenharmony_ci------------------------------------
42662306a36Sopenharmony_ci
42762306a36Sopenharmony_ciDefined in  ``include/linux/init.h``
42862306a36Sopenharmony_ci
42962306a36Sopenharmony_ciAfter boot, the kernel frees up a special section; functions marked with
43062306a36Sopenharmony_ci``__init`` and data structures marked with ``__initdata`` are dropped
43162306a36Sopenharmony_ciafter boot is complete: similarly modules discard this memory after
43262306a36Sopenharmony_ciinitialization. ``__exit`` is used to declare a function which is only
43362306a36Sopenharmony_cirequired on exit: the function will be dropped if this file is not
43462306a36Sopenharmony_cicompiled as a module. See the header file for use. Note that it makes no
43562306a36Sopenharmony_cisense for a function marked with ``__init`` to be exported to modules
43662306a36Sopenharmony_ciwith :c:func:`EXPORT_SYMBOL()` or :c:func:`EXPORT_SYMBOL_GPL()`- this
43762306a36Sopenharmony_ciwill break.
43862306a36Sopenharmony_ci
43962306a36Sopenharmony_ci:c:func:`__initcall()`/:c:func:`module_init()`
44062306a36Sopenharmony_ci----------------------------------------------
44162306a36Sopenharmony_ci
44262306a36Sopenharmony_ciDefined in  ``include/linux/init.h`` / ``include/linux/module.h``
44362306a36Sopenharmony_ci
44462306a36Sopenharmony_ciMany parts of the kernel are well served as a module
44562306a36Sopenharmony_ci(dynamically-loadable parts of the kernel). Using the
44662306a36Sopenharmony_ci:c:func:`module_init()` and :c:func:`module_exit()` macros it
44762306a36Sopenharmony_ciis easy to write code without #ifdefs which can operate both as a module
44862306a36Sopenharmony_cior built into the kernel.
44962306a36Sopenharmony_ci
45062306a36Sopenharmony_ciThe :c:func:`module_init()` macro defines which function is to be
45162306a36Sopenharmony_cicalled at module insertion time (if the file is compiled as a module),
45262306a36Sopenharmony_cior at boot time: if the file is not compiled as a module the
45362306a36Sopenharmony_ci:c:func:`module_init()` macro becomes equivalent to
45462306a36Sopenharmony_ci:c:func:`__initcall()`, which through linker magic ensures that
45562306a36Sopenharmony_cithe function is called on boot.
45662306a36Sopenharmony_ci
45762306a36Sopenharmony_ciThe function can return a negative error number to cause module loading
45862306a36Sopenharmony_cito fail (unfortunately, this has no effect if the module is compiled
45962306a36Sopenharmony_ciinto the kernel). This function is called in user context with
46062306a36Sopenharmony_ciinterrupts enabled, so it can sleep.
46162306a36Sopenharmony_ci
46262306a36Sopenharmony_ci:c:func:`module_exit()`
46362306a36Sopenharmony_ci-----------------------
46462306a36Sopenharmony_ci
46562306a36Sopenharmony_ci
46662306a36Sopenharmony_ciDefined in  ``include/linux/module.h``
46762306a36Sopenharmony_ci
46862306a36Sopenharmony_ciThis macro defines the function to be called at module removal time (or
46962306a36Sopenharmony_cinever, in the case of the file compiled into the kernel). It will only
47062306a36Sopenharmony_cibe called if the module usage count has reached zero. This function can
47162306a36Sopenharmony_cialso sleep, but cannot fail: everything must be cleaned up by the time
47262306a36Sopenharmony_ciit returns.
47362306a36Sopenharmony_ci
47462306a36Sopenharmony_ciNote that this macro is optional: if it is not present, your module will
47562306a36Sopenharmony_cinot be removable (except for 'rmmod -f').
47662306a36Sopenharmony_ci
47762306a36Sopenharmony_ci:c:func:`try_module_get()`/:c:func:`module_put()`
47862306a36Sopenharmony_ci-------------------------------------------------
47962306a36Sopenharmony_ci
48062306a36Sopenharmony_ciDefined in ``include/linux/module.h``
48162306a36Sopenharmony_ci
48262306a36Sopenharmony_ciThese manipulate the module usage count, to protect against removal (a
48362306a36Sopenharmony_cimodule also can't be removed if another module uses one of its exported
48462306a36Sopenharmony_cisymbols: see below). Before calling into module code, you should call
48562306a36Sopenharmony_ci:c:func:`try_module_get()` on that module: if it fails, then the
48662306a36Sopenharmony_cimodule is being removed and you should act as if it wasn't there.
48762306a36Sopenharmony_ciOtherwise, you can safely enter the module, and call
48862306a36Sopenharmony_ci:c:func:`module_put()` when you're finished.
48962306a36Sopenharmony_ci
49062306a36Sopenharmony_ciMost registerable structures have an owner field, such as in the
49162306a36Sopenharmony_ci:c:type:`struct file_operations <file_operations>` structure.
49262306a36Sopenharmony_ciSet this field to the macro ``THIS_MODULE``.
49362306a36Sopenharmony_ci
49462306a36Sopenharmony_ciWait Queues ``include/linux/wait.h``
49562306a36Sopenharmony_ci====================================
49662306a36Sopenharmony_ci
49762306a36Sopenharmony_ci**[SLEEPS]**
49862306a36Sopenharmony_ci
49962306a36Sopenharmony_ciA wait queue is used to wait for someone to wake you up when a certain
50062306a36Sopenharmony_cicondition is true. They must be used carefully to ensure there is no
50162306a36Sopenharmony_cirace condition. You declare a :c:type:`wait_queue_head_t`, and then processes
50262306a36Sopenharmony_ciwhich want to wait for that condition declare a :c:type:`wait_queue_entry_t`
50362306a36Sopenharmony_cireferring to themselves, and place that in the queue.
50462306a36Sopenharmony_ci
50562306a36Sopenharmony_ciDeclaring
50662306a36Sopenharmony_ci---------
50762306a36Sopenharmony_ci
50862306a36Sopenharmony_ciYou declare a ``wait_queue_head_t`` using the
50962306a36Sopenharmony_ci:c:func:`DECLARE_WAIT_QUEUE_HEAD()` macro, or using the
51062306a36Sopenharmony_ci:c:func:`init_waitqueue_head()` routine in your initialization
51162306a36Sopenharmony_cicode.
51262306a36Sopenharmony_ci
51362306a36Sopenharmony_ciQueuing
51462306a36Sopenharmony_ci-------
51562306a36Sopenharmony_ci
51662306a36Sopenharmony_ciPlacing yourself in the waitqueue is fairly complex, because you must
51762306a36Sopenharmony_ciput yourself in the queue before checking the condition. There is a
51862306a36Sopenharmony_cimacro to do this: :c:func:`wait_event_interruptible()`
51962306a36Sopenharmony_ci(``include/linux/wait.h``) The first argument is the wait queue head, and
52062306a36Sopenharmony_cithe second is an expression which is evaluated; the macro returns 0 when
52162306a36Sopenharmony_cithis expression is true, or ``-ERESTARTSYS`` if a signal is received. The
52262306a36Sopenharmony_ci:c:func:`wait_event()` version ignores signals.
52362306a36Sopenharmony_ci
52462306a36Sopenharmony_ciWaking Up Queued Tasks
52562306a36Sopenharmony_ci----------------------
52662306a36Sopenharmony_ci
52762306a36Sopenharmony_ciCall :c:func:`wake_up()` (``include/linux/wait.h``), which will wake
52862306a36Sopenharmony_ciup every process in the queue. The exception is if one has
52962306a36Sopenharmony_ci``TASK_EXCLUSIVE`` set, in which case the remainder of the queue will
53062306a36Sopenharmony_cinot be woken. There are other variants of this basic function available
53162306a36Sopenharmony_ciin the same header.
53262306a36Sopenharmony_ci
53362306a36Sopenharmony_ciAtomic Operations
53462306a36Sopenharmony_ci=================
53562306a36Sopenharmony_ci
53662306a36Sopenharmony_ciCertain operations are guaranteed atomic on all platforms. The first
53762306a36Sopenharmony_ciclass of operations work on :c:type:`atomic_t` (``include/asm/atomic.h``);
53862306a36Sopenharmony_cithis contains a signed integer (at least 32 bits long), and you must use
53962306a36Sopenharmony_cithese functions to manipulate or read :c:type:`atomic_t` variables.
54062306a36Sopenharmony_ci:c:func:`atomic_read()` and :c:func:`atomic_set()` get and set
54162306a36Sopenharmony_cithe counter, :c:func:`atomic_add()`, :c:func:`atomic_sub()`,
54262306a36Sopenharmony_ci:c:func:`atomic_inc()`, :c:func:`atomic_dec()`, and
54362306a36Sopenharmony_ci:c:func:`atomic_dec_and_test()` (returns true if it was
54462306a36Sopenharmony_cidecremented to zero).
54562306a36Sopenharmony_ci
54662306a36Sopenharmony_ciYes. It returns true (i.e. != 0) if the atomic variable is zero.
54762306a36Sopenharmony_ci
54862306a36Sopenharmony_ciNote that these functions are slower than normal arithmetic, and so
54962306a36Sopenharmony_cishould not be used unnecessarily.
55062306a36Sopenharmony_ci
55162306a36Sopenharmony_ciThe second class of atomic operations is atomic bit operations on an
55262306a36Sopenharmony_ci``unsigned long``, defined in ``include/linux/bitops.h``. These
55362306a36Sopenharmony_cioperations generally take a pointer to the bit pattern, and a bit
55462306a36Sopenharmony_cinumber: 0 is the least significant bit. :c:func:`set_bit()`,
55562306a36Sopenharmony_ci:c:func:`clear_bit()` and :c:func:`change_bit()` set, clear,
55662306a36Sopenharmony_ciand flip the given bit. :c:func:`test_and_set_bit()`,
55762306a36Sopenharmony_ci:c:func:`test_and_clear_bit()` and
55862306a36Sopenharmony_ci:c:func:`test_and_change_bit()` do the same thing, except return
55962306a36Sopenharmony_citrue if the bit was previously set; these are particularly useful for
56062306a36Sopenharmony_ciatomically setting flags.
56162306a36Sopenharmony_ci
56262306a36Sopenharmony_ciIt is possible to call these operations with bit indices greater than
56362306a36Sopenharmony_ci``BITS_PER_LONG``. The resulting behavior is strange on big-endian
56462306a36Sopenharmony_ciplatforms though so it is a good idea not to do this.
56562306a36Sopenharmony_ci
56662306a36Sopenharmony_ciSymbols
56762306a36Sopenharmony_ci=======
56862306a36Sopenharmony_ci
56962306a36Sopenharmony_ciWithin the kernel proper, the normal linking rules apply (ie. unless a
57062306a36Sopenharmony_cisymbol is declared to be file scope with the ``static`` keyword, it can
57162306a36Sopenharmony_cibe used anywhere in the kernel). However, for modules, a special
57262306a36Sopenharmony_ciexported symbol table is kept which limits the entry points to the
57362306a36Sopenharmony_cikernel proper. Modules can also export symbols.
57462306a36Sopenharmony_ci
57562306a36Sopenharmony_ci:c:func:`EXPORT_SYMBOL()`
57662306a36Sopenharmony_ci-------------------------
57762306a36Sopenharmony_ci
57862306a36Sopenharmony_ciDefined in ``include/linux/export.h``
57962306a36Sopenharmony_ci
58062306a36Sopenharmony_ciThis is the classic method of exporting a symbol: dynamically loaded
58162306a36Sopenharmony_cimodules will be able to use the symbol as normal.
58262306a36Sopenharmony_ci
58362306a36Sopenharmony_ci:c:func:`EXPORT_SYMBOL_GPL()`
58462306a36Sopenharmony_ci-----------------------------
58562306a36Sopenharmony_ci
58662306a36Sopenharmony_ciDefined in ``include/linux/export.h``
58762306a36Sopenharmony_ci
58862306a36Sopenharmony_ciSimilar to :c:func:`EXPORT_SYMBOL()` except that the symbols
58962306a36Sopenharmony_ciexported by :c:func:`EXPORT_SYMBOL_GPL()` can only be seen by
59062306a36Sopenharmony_cimodules with a :c:func:`MODULE_LICENSE()` that specifies a GPL
59162306a36Sopenharmony_cicompatible license. It implies that the function is considered an
59262306a36Sopenharmony_ciinternal implementation issue, and not really an interface. Some
59362306a36Sopenharmony_cimaintainers and developers may however require EXPORT_SYMBOL_GPL()
59462306a36Sopenharmony_ciwhen adding any new APIs or functionality.
59562306a36Sopenharmony_ci
59662306a36Sopenharmony_ci:c:func:`EXPORT_SYMBOL_NS()`
59762306a36Sopenharmony_ci----------------------------
59862306a36Sopenharmony_ci
59962306a36Sopenharmony_ciDefined in ``include/linux/export.h``
60062306a36Sopenharmony_ci
60162306a36Sopenharmony_ciThis is the variant of `EXPORT_SYMBOL()` that allows specifying a symbol
60262306a36Sopenharmony_cinamespace. Symbol Namespaces are documented in
60362306a36Sopenharmony_ciDocumentation/core-api/symbol-namespaces.rst
60462306a36Sopenharmony_ci
60562306a36Sopenharmony_ci:c:func:`EXPORT_SYMBOL_NS_GPL()`
60662306a36Sopenharmony_ci--------------------------------
60762306a36Sopenharmony_ci
60862306a36Sopenharmony_ciDefined in ``include/linux/export.h``
60962306a36Sopenharmony_ci
61062306a36Sopenharmony_ciThis is the variant of `EXPORT_SYMBOL_GPL()` that allows specifying a symbol
61162306a36Sopenharmony_cinamespace. Symbol Namespaces are documented in
61262306a36Sopenharmony_ciDocumentation/core-api/symbol-namespaces.rst
61362306a36Sopenharmony_ci
61462306a36Sopenharmony_ciRoutines and Conventions
61562306a36Sopenharmony_ci========================
61662306a36Sopenharmony_ci
61762306a36Sopenharmony_ciDouble-linked lists ``include/linux/list.h``
61862306a36Sopenharmony_ci--------------------------------------------
61962306a36Sopenharmony_ci
62062306a36Sopenharmony_ciThere used to be three sets of linked-list routines in the kernel
62162306a36Sopenharmony_ciheaders, but this one is the winner. If you don't have some particular
62262306a36Sopenharmony_cipressing need for a single list, it's a good choice.
62362306a36Sopenharmony_ci
62462306a36Sopenharmony_ciIn particular, :c:func:`list_for_each_entry()` is useful.
62562306a36Sopenharmony_ci
62662306a36Sopenharmony_ciReturn Conventions
62762306a36Sopenharmony_ci------------------
62862306a36Sopenharmony_ci
62962306a36Sopenharmony_ciFor code called in user context, it's very common to defy C convention,
63062306a36Sopenharmony_ciand return 0 for success, and a negative error number (eg. ``-EFAULT``) for
63162306a36Sopenharmony_cifailure. This can be unintuitive at first, but it's fairly widespread in
63262306a36Sopenharmony_cithe kernel.
63362306a36Sopenharmony_ci
63462306a36Sopenharmony_ciUsing :c:func:`ERR_PTR()` (``include/linux/err.h``) to encode a
63562306a36Sopenharmony_cinegative error number into a pointer, and :c:func:`IS_ERR()` and
63662306a36Sopenharmony_ci:c:func:`PTR_ERR()` to get it back out again: avoids a separate
63762306a36Sopenharmony_cipointer parameter for the error number. Icky, but in a good way.
63862306a36Sopenharmony_ci
63962306a36Sopenharmony_ciBreaking Compilation
64062306a36Sopenharmony_ci--------------------
64162306a36Sopenharmony_ci
64262306a36Sopenharmony_ciLinus and the other developers sometimes change function or structure
64362306a36Sopenharmony_cinames in development kernels; this is not done just to keep everyone on
64462306a36Sopenharmony_citheir toes: it reflects a fundamental change (eg. can no longer be
64562306a36Sopenharmony_cicalled with interrupts on, or does extra checks, or doesn't do checks
64662306a36Sopenharmony_ciwhich were caught before). Usually this is accompanied by a fairly
64762306a36Sopenharmony_cicomplete note to the appropriate kernel development mailing list; search
64862306a36Sopenharmony_cithe archives. Simply doing a global replace on the file usually makes
64962306a36Sopenharmony_cithings **worse**.
65062306a36Sopenharmony_ci
65162306a36Sopenharmony_ciInitializing structure members
65262306a36Sopenharmony_ci------------------------------
65362306a36Sopenharmony_ci
65462306a36Sopenharmony_ciThe preferred method of initializing structures is to use designated
65562306a36Sopenharmony_ciinitialisers, as defined by ISO C99, eg::
65662306a36Sopenharmony_ci
65762306a36Sopenharmony_ci    static struct block_device_operations opt_fops = {
65862306a36Sopenharmony_ci            .open               = opt_open,
65962306a36Sopenharmony_ci            .release            = opt_release,
66062306a36Sopenharmony_ci            .ioctl              = opt_ioctl,
66162306a36Sopenharmony_ci            .check_media_change = opt_media_change,
66262306a36Sopenharmony_ci    };
66362306a36Sopenharmony_ci
66462306a36Sopenharmony_ci
66562306a36Sopenharmony_ciThis makes it easy to grep for, and makes it clear which structure
66662306a36Sopenharmony_cifields are set. You should do this because it looks cool.
66762306a36Sopenharmony_ci
66862306a36Sopenharmony_ciGNU Extensions
66962306a36Sopenharmony_ci--------------
67062306a36Sopenharmony_ci
67162306a36Sopenharmony_ciGNU Extensions are explicitly allowed in the Linux kernel. Note that
67262306a36Sopenharmony_cisome of the more complex ones are not very well supported, due to lack
67362306a36Sopenharmony_ciof general use, but the following are considered standard (see the GCC
67462306a36Sopenharmony_ciinfo page section "C Extensions" for more details - Yes, really the info
67562306a36Sopenharmony_cipage, the man page is only a short summary of the stuff in info).
67662306a36Sopenharmony_ci
67762306a36Sopenharmony_ci-  Inline functions
67862306a36Sopenharmony_ci
67962306a36Sopenharmony_ci-  Statement expressions (ie. the ({ and }) constructs).
68062306a36Sopenharmony_ci
68162306a36Sopenharmony_ci-  Declaring attributes of a function / variable / type
68262306a36Sopenharmony_ci   (__attribute__)
68362306a36Sopenharmony_ci
68462306a36Sopenharmony_ci-  typeof
68562306a36Sopenharmony_ci
68662306a36Sopenharmony_ci-  Zero length arrays
68762306a36Sopenharmony_ci
68862306a36Sopenharmony_ci-  Macro varargs
68962306a36Sopenharmony_ci
69062306a36Sopenharmony_ci-  Arithmetic on void pointers
69162306a36Sopenharmony_ci
69262306a36Sopenharmony_ci-  Non-Constant initializers
69362306a36Sopenharmony_ci
69462306a36Sopenharmony_ci-  Assembler Instructions (not outside arch/ and include/asm/)
69562306a36Sopenharmony_ci
69662306a36Sopenharmony_ci-  Function names as strings (__func__).
69762306a36Sopenharmony_ci
69862306a36Sopenharmony_ci-  __builtin_constant_p()
69962306a36Sopenharmony_ci
70062306a36Sopenharmony_ciBe wary when using long long in the kernel, the code gcc generates for
70162306a36Sopenharmony_ciit is horrible and worse: division and multiplication does not work on
70262306a36Sopenharmony_cii386 because the GCC runtime functions for it are missing from the
70362306a36Sopenharmony_cikernel environment.
70462306a36Sopenharmony_ci
70562306a36Sopenharmony_ciC++
70662306a36Sopenharmony_ci---
70762306a36Sopenharmony_ci
70862306a36Sopenharmony_ciUsing C++ in the kernel is usually a bad idea, because the kernel does
70962306a36Sopenharmony_cinot provide the necessary runtime environment and the include files are
71062306a36Sopenharmony_cinot tested for it. It is still possible, but not recommended. If you
71162306a36Sopenharmony_cireally want to do this, forget about exceptions at least.
71262306a36Sopenharmony_ci
71362306a36Sopenharmony_ci#if
71462306a36Sopenharmony_ci---
71562306a36Sopenharmony_ci
71662306a36Sopenharmony_ciIt is generally considered cleaner to use macros in header files (or at
71762306a36Sopenharmony_cithe top of .c files) to abstract away functions rather than using \`#if'
71862306a36Sopenharmony_cipre-processor statements throughout the source code.
71962306a36Sopenharmony_ci
72062306a36Sopenharmony_ciPutting Your Stuff in the Kernel
72162306a36Sopenharmony_ci================================
72262306a36Sopenharmony_ci
72362306a36Sopenharmony_ciIn order to get your stuff into shape for official inclusion, or even to
72462306a36Sopenharmony_cimake a neat patch, there's administrative work to be done:
72562306a36Sopenharmony_ci
72662306a36Sopenharmony_ci-  Figure out who are the owners of the code you've been modifying. Look
72762306a36Sopenharmony_ci   at the top of the source files, inside the ``MAINTAINERS`` file, and
72862306a36Sopenharmony_ci   last of all in the ``CREDITS`` file. You should coordinate with these
72962306a36Sopenharmony_ci   people to make sure you're not duplicating effort, or trying something
73062306a36Sopenharmony_ci   that's already been rejected.
73162306a36Sopenharmony_ci
73262306a36Sopenharmony_ci   Make sure you put your name and email address at the top of any files
73362306a36Sopenharmony_ci   you create or modify significantly. This is the first place people
73462306a36Sopenharmony_ci   will look when they find a bug, or when **they** want to make a change.
73562306a36Sopenharmony_ci
73662306a36Sopenharmony_ci-  Usually you want a configuration option for your kernel hack. Edit
73762306a36Sopenharmony_ci   ``Kconfig`` in the appropriate directory. The Config language is
73862306a36Sopenharmony_ci   simple to use by cut and paste, and there's complete documentation in
73962306a36Sopenharmony_ci   ``Documentation/kbuild/kconfig-language.rst``.
74062306a36Sopenharmony_ci
74162306a36Sopenharmony_ci   In your description of the option, make sure you address both the
74262306a36Sopenharmony_ci   expert user and the user who knows nothing about your feature.
74362306a36Sopenharmony_ci   Mention incompatibilities and issues here. **Definitely** end your
74462306a36Sopenharmony_ci   description with “if in doubt, say N” (or, occasionally, \`Y'); this
74562306a36Sopenharmony_ci   is for people who have no idea what you are talking about.
74662306a36Sopenharmony_ci
74762306a36Sopenharmony_ci-  Edit the ``Makefile``: the CONFIG variables are exported here so you
74862306a36Sopenharmony_ci   can usually just add a "obj-$(CONFIG_xxx) += xxx.o" line. The syntax
74962306a36Sopenharmony_ci   is documented in ``Documentation/kbuild/makefiles.rst``.
75062306a36Sopenharmony_ci
75162306a36Sopenharmony_ci-  Put yourself in ``CREDITS`` if you consider what you've done
75262306a36Sopenharmony_ci   noteworthy, usually beyond a single file (your name should be at the
75362306a36Sopenharmony_ci   top of the source files anyway). ``MAINTAINERS`` means you want to be
75462306a36Sopenharmony_ci   consulted when changes are made to a subsystem, and hear about bugs;
75562306a36Sopenharmony_ci   it implies a more-than-passing commitment to some part of the code.
75662306a36Sopenharmony_ci
75762306a36Sopenharmony_ci-  Finally, don't forget to read
75862306a36Sopenharmony_ci   ``Documentation/process/submitting-patches.rst``
75962306a36Sopenharmony_ci
76062306a36Sopenharmony_ciKernel Cantrips
76162306a36Sopenharmony_ci===============
76262306a36Sopenharmony_ci
76362306a36Sopenharmony_ciSome favorites from browsing the source. Feel free to add to this list.
76462306a36Sopenharmony_ci
76562306a36Sopenharmony_ci``arch/x86/include/asm/delay.h``::
76662306a36Sopenharmony_ci
76762306a36Sopenharmony_ci    #define ndelay(n) (__builtin_constant_p(n) ? \
76862306a36Sopenharmony_ci            ((n) > 20000 ? __bad_ndelay() : __const_udelay((n) * 5ul)) : \
76962306a36Sopenharmony_ci            __ndelay(n))
77062306a36Sopenharmony_ci
77162306a36Sopenharmony_ci
77262306a36Sopenharmony_ci``include/linux/fs.h``::
77362306a36Sopenharmony_ci
77462306a36Sopenharmony_ci    /*
77562306a36Sopenharmony_ci     * Kernel pointers have redundant information, so we can use a
77662306a36Sopenharmony_ci     * scheme where we can return either an error code or a dentry
77762306a36Sopenharmony_ci     * pointer with the same return value.
77862306a36Sopenharmony_ci     *
77962306a36Sopenharmony_ci     * This should be a per-architecture thing, to allow different
78062306a36Sopenharmony_ci     * error and pointer decisions.
78162306a36Sopenharmony_ci     */
78262306a36Sopenharmony_ci     #define ERR_PTR(err)    ((void *)((long)(err)))
78362306a36Sopenharmony_ci     #define PTR_ERR(ptr)    ((long)(ptr))
78462306a36Sopenharmony_ci     #define IS_ERR(ptr)     ((unsigned long)(ptr) > (unsigned long)(-1000))
78562306a36Sopenharmony_ci
78662306a36Sopenharmony_ci``arch/x86/include/asm/uaccess_32.h:``::
78762306a36Sopenharmony_ci
78862306a36Sopenharmony_ci    #define copy_to_user(to,from,n)                         \
78962306a36Sopenharmony_ci            (__builtin_constant_p(n) ?                      \
79062306a36Sopenharmony_ci             __constant_copy_to_user((to),(from),(n)) :     \
79162306a36Sopenharmony_ci             __generic_copy_to_user((to),(from),(n)))
79262306a36Sopenharmony_ci
79362306a36Sopenharmony_ci
79462306a36Sopenharmony_ci``arch/sparc/kernel/head.S:``::
79562306a36Sopenharmony_ci
79662306a36Sopenharmony_ci    /*
79762306a36Sopenharmony_ci     * Sun people can't spell worth damn. "compatability" indeed.
79862306a36Sopenharmony_ci     * At least we *know* we can't spell, and use a spell-checker.
79962306a36Sopenharmony_ci     */
80062306a36Sopenharmony_ci
80162306a36Sopenharmony_ci    /* Uh, actually Linus it is I who cannot spell. Too much murky
80262306a36Sopenharmony_ci     * Sparc assembly will do this to ya.
80362306a36Sopenharmony_ci     */
80462306a36Sopenharmony_ci    C_LABEL(cputypvar):
80562306a36Sopenharmony_ci            .asciz "compatibility"
80662306a36Sopenharmony_ci
80762306a36Sopenharmony_ci    /* Tested on SS-5, SS-10. Probably someone at Sun applied a spell-checker. */
80862306a36Sopenharmony_ci            .align 4
80962306a36Sopenharmony_ci    C_LABEL(cputypvar_sun4m):
81062306a36Sopenharmony_ci            .asciz "compatible"
81162306a36Sopenharmony_ci
81262306a36Sopenharmony_ci
81362306a36Sopenharmony_ci``arch/sparc/lib/checksum.S:``::
81462306a36Sopenharmony_ci
81562306a36Sopenharmony_ci            /* Sun, you just can't beat me, you just can't.  Stop trying,
81662306a36Sopenharmony_ci             * give up.  I'm serious, I am going to kick the living shit
81762306a36Sopenharmony_ci             * out of you, game over, lights out.
81862306a36Sopenharmony_ci             */
81962306a36Sopenharmony_ci
82062306a36Sopenharmony_ci
82162306a36Sopenharmony_ciThanks
82262306a36Sopenharmony_ci======
82362306a36Sopenharmony_ci
82462306a36Sopenharmony_ciThanks to Andi Kleen for the idea, answering my questions, fixing my
82562306a36Sopenharmony_cimistakes, filling content, etc. Philipp Rumpf for more spelling and
82662306a36Sopenharmony_ciclarity fixes, and some excellent non-obvious points. Werner Almesberger
82762306a36Sopenharmony_cifor giving me a great summary of :c:func:`disable_irq()`, and Jes
82862306a36Sopenharmony_ciSorensen and Andrea Arcangeli added caveats. Michael Elizabeth Chastain
82962306a36Sopenharmony_cifor checking and adding to the Configure section. Telsa Gwynne for
83062306a36Sopenharmony_citeaching me DocBook.
831