요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
Memory protection, FPU와 kernel stack
hacking.rst:125-154Kernel code의 잘못된 pointer write는 process 하나가 아니라 시스템 전체 memory를 손상시킵니다. 가능한 기능을 user space에 둘 수 있는지 먼저 검토합니다. Kernel stack은 크기가 제한되어 있으므로 큰 local array, 깊은 recursion과 거대한 call frame을 피합니다.
일반 C처럼 FPU register를 임의로 사용하면 user task state를 훼손할 수 있습니다. SIMD가 꼭 필요하면 architecture가 제공하는 kernel_fpu_begin/end 같은 context save와 preemption 보호 API를 사용하고 해당 호출 가능 문맥을 지켜야 합니다.
UAPI 선택과 sleep 금지 조건
hacking.rst:155-229단순 parameter read/write라면 sysfs, procfs, debugfs, netlink 또는 기존 subsystem UAPI가 맞는지 먼저 봅니다. Device-specific command는 character device ioctl이 후보지만 ABI 구조체 layout, compat와 lifetime을 설계해야 합니다. 새 syscall은 architecture 공통 wiring과 장기 ABI 유지가 필요한 별도 절차입니다.
- Sleep 가능한 함수는 process context에서만 호출한다.
- Spinlock을 보유하거나 preemption·IRQ가 disabled인 상태에서는 sleep하지 않는다.
- copy_*_user와 GFP_KERNEL allocation은 page fault 또는 reclaim으로 암묵적으로 sleep할 수 있다.
- CONFIG_DEBUG_ATOMIC_SLEEP를 켜서 atomic context sleep을 조기에 찾는다.
User pointer와 printk
hacking.rst:230-298User pointer를 직접 dereference하지 않습니다. Scalar는 get_user()/put_user(), buffer는 copy_from_user()/copy_to_user()를 사용합니다. Access 중 page fault가 발생할 수 있으므로 기본 variant는 sleep 가능한 context가 필요합니다.
get_user와 put_user는 성공 0 또는 -EFAULT를 반환합니다. copy_to_user와 copy_from_user는 복사하지 못한 byte 수를 반환하므로 0만 성공입니다. 반환 규약을 혼동하면 일부 복사를 성공으로 처리하는 bug가 됩니다.
printk는 interrupt에서도 사용할 수 있지만 console flood는 시스템을 사실상 멈추게 할 수 있습니다. pr_* level, dynamic debug와 rate limit helper를 사용하고 pointer format 등 kernel 전용 format rule을 지킵니다.
kmalloc flag와 실패 경로
hacking.rst:299-347| Flag | Sleep | 사용처 |
|---|---|---|
| GFP_KERNEL | reclaim과 wait 가능 | 일반 process context |
| GFP_ATOMIC | sleep하지 않음 | interrupt 또는 spinlock 보유 구간의 불가피한 소량 allocation |
GFP_ATOMIC은 더 강한 성공 보장이 아니라 sleep을 피하는 제한된 reserve allocation입니다. Data path에서 반복 필요하면 미리 allocate하거나 mempool, per-CPU cache와 subsystem allocator를 사용합니다. 모든 allocation은 NULL failure와 unwind를 설계해야 합니다.
CPU pinning, delay와 endian
hacking.rst:348-423current는 interrupt context에서도 NULL이 아닐 수 있지만 그 interrupt의 논리적 caller를 뜻하지 않습니다. Process identity가 필요한 작업은 process context에서 capture하여 deferred work에 명시적으로 전달합니다.
get_cpu()는 preemption을 막고 CPU 번호를 돌려주며 put_cpu()와 짝을 이룹니다. 이미 migration이 불가능하다는 계약이 있을 때만 smp_processor_id()를 직접 사용합니다. PREEMPT_RT에서는 per-CPU 보호에 local_lock이나 migrate_disable이 필요한 경우를 구분합니다.
ndelay/udelay은 busy-wait이므로 짧은 hardware timing에만 사용하고 긴 지연은 sleep 가능한 msleep 계열로 바꿉니다. Device와 protocol field에는 cpu_to_le32, le32_to_cpu, cpu_to_be32 같은 명시적 conversion을 사용합니다.
Init section과 module lifetime
hacking.rst:424-493__init function과 __initdata는 boot 또는 module init 뒤 버려집니다. Runtime code가 그 address를 참조하거나 export하면 use-after-free가 됩니다. __exit code는 built-in kernel에서는 필요 없어 link 단계에서 제거될 수 있습니다.
module_init()은 module이면 insertion 때, built-in이면 initcall level에서 실행됩니다. module_exit()은 usage count가 0인 unload에서 호출되고 실패를 반환할 수 없으므로 모든 callback, timer, work와 reference가 이미 정리 가능해야 합니다.
다른 code가 module function pointer를 호출하기 전 try_module_get()으로 unload와 경쟁을 막고 완료 후 module_put()합니다. Registerable operations 구조체의 owner를 THIS_MODULE로 설정하면 framework가 이 reference를 관리할 수 있습니다.
Wait queue와 atomic operation
hacking.rst:494-565wait_event_interruptible(queue, condition);
/* state를 condition이 true가 되도록 갱신한 뒤 */
wake_up(&queue);
Waiter는 condition을 검사하기 전에 queue에 자신을 연결해야 wakeup 사이의 race를 피할 수 있습니다. wait_event 계열 macro가 이 순서를 구현하며 interruptible variant는 signal 시 -ERESTARTSYS를 반환합니다. Waker는 condition state를 publish한 뒤 wake_up을 호출합니다.
atomic_t helper는 단일 counter operation의 atomicity를 보장하지만 여러 field invariant나 object lifetime을 자동으로 보호하지 않습니다. 단순 reference count에는 refcount_t가 overflow와 misuse 검출까지 제공하므로 더 적합합니다.
Export symbol, namespace와 error pointer
hacking.rst:566-667Module이 사용할 수 있는 entry point만 EXPORT_SYMBOL 또는 EXPORT_SYMBOL_GPL로 export합니다. Namespace variant는 symbol group을 명시하고 consumer가 MODULE_IMPORT_NS로 의존을 선언하게 합니다. Export는 안정 ABI 약속이 아니며 최소한으로 유지합니다.
Kernel 함수는 성공 0, 실패 -Exxx를 반환하는 관례가 널리 쓰입니다. Pointer 반환 함수는 ERR_PTR(error)로 negative errno를 encode하고 IS_ERR, PTR_ERR로 검사합니다. NULL과 error pointer가 각각 어떤 의미인지 API contract에 명확히 둡니다.
구조체 static initializer는 designated field syntax를 사용하여 field 추가와 순서 변경에 강하게 만듭니다. Kernel API compile break는 종종 호출 context나 lifetime contract가 바뀌었다는 신호이므로 이름만 전역 치환하지 말고 commit과 새 semantics를 확인합니다.
C 확장과 upstream 준비
hacking.rst:668-759Kernel은 inline, statement expression, __attribute__, typeof와 variadic macro 같은 GNU C 확장을 사용합니다. C++ runtime, exception과 일반 standard library는 제공하지 않습니다. Configuration 차이는 source 곳곳의 #if보다 header helper와 stub function으로 감싸는 편이 읽기 쉽습니다.
- MAINTAINERS와 git history로 실제 owner와 mailing list를 찾는다.
- Kconfig와 Makefile에 build 조건을 연결한다.
- 모든 지원 config와 architecture에서 warning 없이 build되는지 확인한다.
- Documentation, ABI, test와 cleanup path를 code와 같은 patch series에 포함한다.
- Coding style과 subsystem submission rule에 맞춰 review 가능한 단위로 보낸다.
역사적 guide를 현재 kernel에서 읽는 법
hacking.rst:760-831문서의 일부 header 경로, tasklet 권장 방식과 API 이름은 현재 source와 다를 수 있습니다. Linux v6.18.37에서 symbol을 grep하고 generated kernel-doc, compiler annotation과 lockdep assertion을 우선합니다. 이 문서의 가치는 API 목록보다 context와 lifetime을 먼저 따지는 사고방식에 있습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
.. _kernel_hacking_hack:
============================================
Unreliable Guide To Hacking The Linux Kernel
============================================
:Author: Rusty Russell
Introduction
============
Welcome, gentle reader, to Rusty's Remarkably Unreliable Guide to Linux
Kernel Hacking. This document describes the common routines and general
requirements for kernel code: its goal is to serve as a primer for Linux
kernel development for experienced C programmers. I avoid implementation
details: that's what the code is for, and I ignore whole tracts of
useful routines.
Before you read this, please understand that I never wanted to write
this document, being grossly under-qualified, but I always wanted to
read it, and this was the only way. I hope it will grow into a
compendium of best practice, common starting points and random
information.
The Players
===========
At any time each of the CPUs in a system can be:
- not associated with any process, serving a hardware interrupt;
- not associated with any process, serving a softirq or tasklet;
- running in kernel space, associated with a process (user context);
- running a process in user space.
There is an ordering between these. The bottom two can preempt each
other, but above that is a strict hierarchy: each can only be preempted
by the ones above it. For example, while a softirq is running on a CPU,
no other softirq will preempt it, but a hardware interrupt can. However,
any other CPUs in the system execute independently.
We'll see a number of ways that the user context can block interrupts,
to become truly non-preemptable.
User Context
------------
User context is when you are coming in from a system call or other trap:
like userspace, you can be preempted by more important tasks and by
interrupts. You can sleep, by calling :c:func:`schedule()`.
.. note::
You are always in user context on module load and unload, and on
operations on the block device layer.
In user context, the ``current`` pointer (indicating the task we are
currently executing) is valid, and :c:func:`in_interrupt()`
(``include/linux/preempt.h``) is false.
.. warning::
Beware that if you have preemption or softirqs disabled (see below),
:c:func:`in_interrupt()` will return a false positive.
Hardware Interrupts (Hard IRQs)
-------------------------------
Timer ticks, network cards and keyboard are examples of real hardware
which produce interrupts at any time. The kernel runs interrupt
handlers, which services the hardware. The kernel guarantees that this
handler is never re-entered: if the same interrupt arrives, it is queued
(or dropped). Because it disables interrupts, this handler has to be
fast: frequently it simply acknowledges the interrupt, marks a 'software
interrupt' for execution and exits.
You can tell you are in a hardware interrupt, because in_hardirq() returns
true.
.. warning::
Beware that this will return a false positive if interrupts are
disabled (see below).
Software Interrupt Context: Softirqs and Tasklets
-------------------------------------------------
Whenever a system call is about to return to userspace, or a hardware
interrupt handler exits, any 'software interrupts' which are marked
pending (usually by hardware interrupts) are run (``kernel/softirq.c``).
Much of the real interrupt handling work is done here. Early in the
transition to SMP, there were only 'bottom halves' (BHs), which didn't
take advantage of multiple CPUs. Shortly after we switched from wind-up
computers made of match-sticks and snot, we abandoned this limitation
and switched to 'softirqs'.
``include/linux/interrupt.h`` lists the different softirqs. A very
important softirq is the timer softirq (``include/linux/timer.h``): you
can register to have it call functions for you in a given length of
time.
Softirqs are often a pain to deal with, since the same softirq will run
simultaneously on more than one CPU. For this reason, tasklets
(``include/linux/interrupt.h``) are more often used: they are
dynamically-registrable (meaning you can have as many as you want), and
they also guarantee that any tasklet will only run on one CPU at any
time, although different tasklets can run simultaneously.
.. warning::
The name 'tasklet' is misleading: they have nothing to do with
'tasks'.
You can tell you are in a softirq (or tasklet) using the
:c:func:`in_softirq()` macro (``include/linux/preempt.h``).
.. warning::
Beware that this will return a false positive if a
:ref:`bottom half lock <local_bh_disable>` is held.
Some Basic Rules
================
No memory protection
If you corrupt memory, whether in user context or interrupt context,
the whole machine will crash. Are you sure you can't do what you
want in userspace?
No floating point or MMX
The FPU context is not saved; even in user context the FPU state
probably won't correspond with the current process: you would mess
with some user process' FPU state. If you really want to do this,
you would have to explicitly save/restore the full FPU state (and
avoid context switches). It is generally a bad idea; use fixed point
arithmetic first.
A rigid stack limit
Depending on configuration options the kernel stack is about 3K to
6K for most 32-bit architectures: it's about 14K on most 64-bit
archs, and often shared with interrupts so you can't use it all.
Avoid deep recursion and huge local arrays on the stack (allocate
them dynamically instead).
The Linux kernel is portable
Let's keep it that way. Your code should be 64-bit clean, and
endian-independent. You should also minimize CPU specific stuff,
e.g. inline assembly should be cleanly encapsulated and minimized to
ease porting. Generally it should be restricted to the
architecture-dependent part of the kernel tree.
ioctls: Not writing a new system call
=====================================
A system call generally looks like this::
asmlinkage long sys_mycall(int arg)
{
return 0;
}
First, in most cases you don't want to create a new system call. You
create a character device and implement an appropriate ioctl for it.
This is much more flexible than system calls, doesn't have to be entered
in every architecture's ``include/asm/unistd.h`` and
``arch/kernel/entry.S`` file, and is much more likely to be accepted by
Linus.
If all your routine does is read or write some parameter, consider
implementing a :c:func:`sysfs()` interface instead.
Inside the ioctl you're in user context to a process. When a error
occurs you return a negated errno (see
``include/uapi/asm-generic/errno-base.h``,
``include/uapi/asm-generic/errno.h`` and ``include/linux/errno.h``),
otherwise you return 0.
After you slept you should check if a signal occurred: the Unix/Linux
way of handling signals is to temporarily exit the system call with the
``-ERESTARTSYS`` error. The system call entry code will switch back to
user context, process the signal handler and then your system call will
be restarted (unless the user disabled that). So you should be prepared
to process the restart, e.g. if you're in the middle of manipulating
some data structure.
::
if (signal_pending(current))
return -ERESTARTSYS;
If you're doing longer computations: first think userspace. If you
**really** want to do it in kernel you should regularly check if you need
to give up the CPU (remember there is cooperative multitasking per CPU).
Idiom::
cond_resched(); /* Will sleep */
A short note on interface design: the UNIX system call motto is "Provide
mechanism not policy".
Recipes for Deadlock
====================
You cannot call any routines which may sleep, unless:
- You are in user context.
- You do not own any spinlocks.
- You have interrupts enabled (actually, Andi Kleen says that the
scheduling code will enable them for you, but that's probably not
what you wanted).
Note that some functions may sleep implicitly: common ones are the user
space access functions (\*_user) and memory allocation functions
without ``GFP_ATOMIC``.
You should always compile your kernel ``CONFIG_DEBUG_ATOMIC_SLEEP`` on,
and it will warn you if you break these rules. If you **do** break the
rules, you will eventually lock up your box.
Really.
Common Routines
===============
:c:func:`printk()`
------------------
Defined in ``include/linux/printk.h``
:c:func:`printk()` feeds kernel messages to the console, dmesg, and
the syslog daemon. It is useful for debugging and reporting errors, and
can be used inside interrupt context, but use with caution: a machine
which has its console flooded with printk messages is unusable. It uses
a format string mostly compatible with ANSI C printf, and C string
concatenation to give it a first "priority" argument::
printk(KERN_INFO "i = %u\n", i);
See ``include/linux/kern_levels.h``; for other ``KERN_`` values; these are
interpreted by syslog as the level. Special case: for printing an IP
address use::
__be32 ipaddress;
printk(KERN_INFO "my ip: %pI4\n", &ipaddress);
:c:func:`printk()` internally uses a 1K buffer and does not catch
overruns. Make sure that will be enough.
.. note::
You will know when you are a real kernel hacker when you start
typoing printf as printk in your user programs :)
.. note::
Another sidenote: the original Unix Version 6 sources had a comment
on top of its printf function: "Printf should not be used for
chit-chat". You should follow that advice.
:c:func:`copy_to_user()` / :c:func:`copy_from_user()` / :c:func:`get_user()` / :c:func:`put_user()`
---------------------------------------------------------------------------------------------------
Defined in ``include/linux/uaccess.h`` / ``asm/uaccess.h``
**[SLEEPS]**
:c:func:`put_user()` and :c:func:`get_user()` are used to get
and put single values (such as an int, char, or long) from and to
userspace. A pointer into userspace should never be simply dereferenced:
data should be copied using these routines. Both return ``-EFAULT`` or
0.
:c:func:`copy_to_user()` and :c:func:`copy_from_user()` are
more general: they copy an arbitrary amount of data to and from
userspace.
.. warning::
Unlike :c:func:`put_user()` and :c:func:`get_user()`, they
return the amount of uncopied data (ie. 0 still means success).
[Yes, this objectionable interface makes me cringe. The flamewar comes
up every year or so. --RR.]
The functions may sleep implicitly. This should never be called outside
user context (it makes no sense), with interrupts disabled, or a
spinlock held.
:c:func:`kmalloc()`/:c:func:`kfree()`
-------------------------------------
Defined in ``include/linux/slab.h``
**[MAY SLEEP: SEE BELOW]**
These routines are used to dynamically request pointer-aligned chunks of
memory, like malloc and free do in userspace, but
:c:func:`kmalloc()` takes an extra flag word. Important values:
``GFP_KERNEL``
May sleep and swap to free memory. Only allowed in user context, but
is the most reliable way to allocate memory.
``GFP_ATOMIC``
Don't sleep. Less reliable than ``GFP_KERNEL``, but may be called
from interrupt context. You should **really** have a good
out-of-memory error-handling strategy.
``GFP_DMA``
Allocate ISA DMA lower than 16MB. If you don't know what that is you
don't need it. Very unreliable.
If you see a sleeping function called from invalid context warning
message, then maybe you called a sleeping allocation function from
interrupt context without ``GFP_ATOMIC``. You should really fix that.
Run, don't walk.
If you are allocating at least ``PAGE_SIZE`` (``asm/page.h`` or
``asm/page_types.h``) bytes, consider using :c:func:`__get_free_pages()`
(``include/linux/gfp.h``). It takes an order argument (0 for page sized,
1 for double page, 2 for four pages etc.) and the same memory priority
flag word as above.
If you are allocating more than a page worth of bytes you can use
:c:func:`vmalloc()`. It'll allocate virtual memory in the kernel
map. This block is not contiguous in physical memory, but the MMU makes
it look like it is for you (so it'll only look contiguous to the CPUs,
not to external device drivers). If you really need large physically
contiguous memory for some weird device, you have a problem: it is
poorly supported in Linux because after some time memory fragmentation
in a running kernel makes it hard. The best way is to allocate the block
early in the boot process via the :c:func:`alloc_bootmem()`
routine.
Before inventing your own cache of often-used objects consider using a
slab cache in ``include/linux/slab.h``
:c:macro:`current`
------------------
Defined in ``include/asm/current.h``
This global variable (really a macro) contains a pointer to the current
task structure, so is only valid in user context. For example, when a
process makes a system call, this will point to the task structure of
the calling process. It is **not NULL** in interrupt context.
:c:func:`mdelay()`/:c:func:`udelay()`
-------------------------------------
Defined in ``include/asm/delay.h`` / ``include/linux/delay.h``
The :c:func:`udelay()` and :c:func:`ndelay()` functions can be
used for small pauses. Do not use large values with them as you risk
overflow - the helper function :c:func:`mdelay()` is useful here, or
consider :c:func:`msleep()`.
:c:func:`cpu_to_be32()`/:c:func:`be32_to_cpu()`/:c:func:`cpu_to_le32()`/:c:func:`le32_to_cpu()`
-----------------------------------------------------------------------------------------------
Defined in ``include/asm/byteorder.h``
The :c:func:`cpu_to_be32()` family (where the "32" can be replaced
by 64 or 16, and the "be" can be replaced by "le") are the general way
to do endian conversions in the kernel: they return the converted value.
All variations supply the reverse as well:
:c:func:`be32_to_cpu()`, etc.
There are two major variations of these functions: the pointer
variation, such as :c:func:`cpu_to_be32p()`, which take a pointer
to the given type, and return the converted value. The other variation
is the "in-situ" family, such as :c:func:`cpu_to_be32s()`, which
convert value referred to by the pointer, and return void.
:c:func:`local_irq_save()`/:c:func:`local_irq_restore()`
--------------------------------------------------------
Defined in ``include/linux/irqflags.h``
These routines disable hard interrupts on the local CPU, and restore
them. They are reentrant; saving the previous state in their one
``unsigned long flags`` argument. If you know that interrupts are
enabled, you can simply use :c:func:`local_irq_disable()` and
:c:func:`local_irq_enable()`.
.. _local_bh_disable:
:c:func:`local_bh_disable()`/:c:func:`local_bh_enable()`
--------------------------------------------------------
Defined in ``include/linux/bottom_half.h``
These routines disable soft interrupts on the local CPU, and restore
them. They are reentrant; if soft interrupts were disabled before, they
will still be disabled after this pair of functions has been called.
They prevent softirqs and tasklets from running on the current CPU.
:c:func:`smp_processor_id()`
----------------------------
Defined in ``include/linux/smp.h``
:c:func:`get_cpu()` disables preemption (so you won't suddenly get
moved to another CPU) and returns the current processor number, between
0 and ``NR_CPUS``. Note that the CPU numbers are not necessarily
continuous. You return it again with :c:func:`put_cpu()` when you
are done.
If you know you cannot be preempted by another task (ie. you are in
interrupt context, or have preemption disabled) you can use
smp_processor_id().
``__init``/``__exit``/``__initdata``
------------------------------------
Defined in ``include/linux/init.h``
After boot, the kernel frees up a special section; functions marked with
``__init`` and data structures marked with ``__initdata`` are dropped
after boot is complete: similarly modules discard this memory after
initialization. ``__exit`` is used to declare a function which is only
required on exit: the function will be dropped if this file is not
compiled as a module. See the header file for use. Note that it makes no
sense for a function marked with ``__init`` to be exported to modules
with :c:func:`EXPORT_SYMBOL()` or :c:func:`EXPORT_SYMBOL_GPL()`- this
will break.
:c:func:`__initcall()`/:c:func:`module_init()`
----------------------------------------------
Defined in ``include/linux/init.h`` / ``include/linux/module.h``
Many parts of the kernel are well served as a module
(dynamically-loadable parts of the kernel). Using the
:c:func:`module_init()` and :c:func:`module_exit()` macros it
is easy to write code without #ifdefs which can operate both as a module
or built into the kernel.
The :c:func:`module_init()` macro defines which function is to be
called at module insertion time (if the file is compiled as a module),
or at boot time: if the file is not compiled as a module the
:c:func:`module_init()` macro becomes equivalent to
:c:func:`__initcall()`, which through linker magic ensures that
the function is called on boot.
The function can return a negative error number to cause module loading
to fail (unfortunately, this has no effect if the module is compiled
into the kernel). This function is called in user context with
interrupts enabled, so it can sleep.
:c:func:`module_exit()`
-----------------------
Defined in ``include/linux/module.h``
This macro defines the function to be called at module removal time (or
never, in the case of the file compiled into the kernel). It will only
be called if the module usage count has reached zero. This function can
also sleep, but cannot fail: everything must be cleaned up by the time
it returns.
Note that this macro is optional: if it is not present, your module will
not be removable (except for 'rmmod -f').
:c:func:`try_module_get()`/:c:func:`module_put()`
-------------------------------------------------
Defined in ``include/linux/module.h``
These manipulate the module usage count, to protect against removal (a
module also can't be removed if another module uses one of its exported
symbols: see below). Before calling into module code, you should call
:c:func:`try_module_get()` on that module: if it fails, then the
module is being removed and you should act as if it wasn't there.
Otherwise, you can safely enter the module, and call
:c:func:`module_put()` when you're finished.
Most registerable structures have an owner field, such as in the
:c:type:`struct file_operations <file_operations>` structure.
Set this field to the macro ``THIS_MODULE``.
Wait Queues ``include/linux/wait.h``
====================================
**[SLEEPS]**
A wait queue is used to wait for someone to wake you up when a certain
condition is true. They must be used carefully to ensure there is no
race condition. You declare a :c:type:`wait_queue_head_t`, and then processes
which want to wait for that condition declare a :c:type:`wait_queue_entry_t`
referring to themselves, and place that in the queue.
Declaring
---------
You declare a ``wait_queue_head_t`` using the
:c:func:`DECLARE_WAIT_QUEUE_HEAD()` macro, or using the
:c:func:`init_waitqueue_head()` routine in your initialization
code.
Queuing
-------
Placing yourself in the waitqueue is fairly complex, because you must
put yourself in the queue before checking the condition. There is a
macro to do this: :c:func:`wait_event_interruptible()`
(``include/linux/wait.h``) The first argument is the wait queue head, and
the second is an expression which is evaluated; the macro returns 0 when
this expression is true, or ``-ERESTARTSYS`` if a signal is received. The
:c:func:`wait_event()` version ignores signals.
Waking Up Queued Tasks
----------------------
Call :c:func:`wake_up()` (``include/linux/wait.h``), which will wake
up every process in the queue. The exception is if one has
``TASK_EXCLUSIVE`` set, in which case the remainder of the queue will
not be woken. There are other variants of this basic function available
in the same header.
Atomic Operations
=================
Certain operations are guaranteed atomic on all platforms. The first
class of operations work on :c:type:`atomic_t` (``include/asm/atomic.h``);
this contains a signed integer (at least 32 bits long), and you must use
these functions to manipulate or read :c:type:`atomic_t` variables.
:c:func:`atomic_read()` and :c:func:`atomic_set()` get and set
the counter, :c:func:`atomic_add()`, :c:func:`atomic_sub()`,
:c:func:`atomic_inc()`, :c:func:`atomic_dec()`, and
:c:func:`atomic_dec_and_test()` (returns true if it was
decremented to zero).
Yes. It returns true (i.e. != 0) if the atomic variable is zero.
Note that these functions are slower than normal arithmetic, and so
should not be used unnecessarily.
The second class of atomic operations is atomic bit operations on an
``unsigned long``, defined in ``include/linux/bitops.h``. These
operations generally take a pointer to the bit pattern, and a bit
number: 0 is the least significant bit. :c:func:`set_bit()`,
:c:func:`clear_bit()` and :c:func:`change_bit()` set, clear,
and flip the given bit. :c:func:`test_and_set_bit()`,
:c:func:`test_and_clear_bit()` and
:c:func:`test_and_change_bit()` do the same thing, except return
true if the bit was previously set; these are particularly useful for
atomically setting flags.
It is possible to call these operations with bit indices greater than
``BITS_PER_LONG``. The resulting behavior is strange on big-endian
platforms though so it is a good idea not to do this.
Symbols
=======
Within the kernel proper, the normal linking rules apply (ie. unless a
symbol is declared to be file scope with the ``static`` keyword, it can
be used anywhere in the kernel). However, for modules, a special
exported symbol table is kept which limits the entry points to the
kernel proper. Modules can also export symbols.
:c:func:`EXPORT_SYMBOL()`
-------------------------
Defined in ``include/linux/export.h``
This is the classic method of exporting a symbol: dynamically loaded
modules will be able to use the symbol as normal.
:c:func:`EXPORT_SYMBOL_GPL()`
-----------------------------
Defined in ``include/linux/export.h``
Similar to :c:func:`EXPORT_SYMBOL()` except that the symbols
exported by :c:func:`EXPORT_SYMBOL_GPL()` can only be seen by
modules with a :c:func:`MODULE_LICENSE()` that specifies a GPLv2
compatible license. It implies that the function is considered an
internal implementation issue, and not really an interface. Some
maintainers and developers may however require EXPORT_SYMBOL_GPL()
when adding any new APIs or functionality.
:c:func:`EXPORT_SYMBOL_NS()`
----------------------------
Defined in ``include/linux/export.h``
This is the variant of `EXPORT_SYMBOL()` that allows specifying a symbol
namespace. Symbol Namespaces are documented in
Documentation/core-api/symbol-namespaces.rst
:c:func:`EXPORT_SYMBOL_NS_GPL()`
--------------------------------
Defined in ``include/linux/export.h``
This is the variant of `EXPORT_SYMBOL_GPL()` that allows specifying a symbol
namespace. Symbol Namespaces are documented in
Documentation/core-api/symbol-namespaces.rst
Routines and Conventions
========================
Double-linked lists ``include/linux/list.h``
--------------------------------------------
There used to be three sets of linked-list routines in the kernel
headers, but this one is the winner. If you don't have some particular
pressing need for a single list, it's a good choice.
In particular, :c:func:`list_for_each_entry()` is useful.
Return Conventions
------------------
For code called in user context, it's very common to defy C convention,
and return 0 for success, and a negative error number (eg. ``-EFAULT``) for
failure. This can be unintuitive at first, but it's fairly widespread in
the kernel.
Using :c:func:`ERR_PTR()` (``include/linux/err.h``) to encode a
negative error number into a pointer, and :c:func:`IS_ERR()` and
:c:func:`PTR_ERR()` to get it back out again: avoids a separate
pointer parameter for the error number. Icky, but in a good way.
Breaking Compilation
--------------------
Linus and the other developers sometimes change function or structure
names in development kernels; this is not done just to keep everyone on
their toes: it reflects a fundamental change (eg. can no longer be
called with interrupts on, or does extra checks, or doesn't do checks
which were caught before). Usually this is accompanied by a fairly
complete note to the appropriate kernel development mailing list; search
the archives. Simply doing a global replace on the file usually makes
things **worse**.
Initializing structure members
------------------------------
The preferred method of initializing structures is to use designated
initialisers, as defined by ISO C99, eg::
static struct block_device_operations opt_fops = {
.open = opt_open,
.release = opt_release,
.ioctl = opt_ioctl,
.check_media_change = opt_media_change,
};
This makes it easy to grep for, and makes it clear which structure
fields are set. You should do this because it looks cool.
GNU Extensions
--------------
GNU Extensions are explicitly allowed in the Linux kernel. Note that
some of the more complex ones are not very well supported, due to lack
of general use, but the following are considered standard (see the GCC
info page section "C Extensions" for more details - Yes, really the info
page, the man page is only a short summary of the stuff in info).
- Inline functions
- Statement expressions (ie. the ({ and }) constructs).
- Declaring attributes of a function / variable / type
(__attribute__)
- typeof
- Zero length arrays
- Macro varargs
- Arithmetic on void pointers
- Non-Constant initializers
- Assembler Instructions (not outside arch/ and include/asm/)
- Function names as strings (__func__).
- __builtin_constant_p()
Be wary when using long long in the kernel, the code gcc generates for
it is horrible and worse: division and multiplication does not work on
i386 because the GCC runtime functions for it are missing from the
kernel environment.
C++
---
Using C++ in the kernel is usually a bad idea, because the kernel does
not provide the necessary runtime environment and the include files are
not tested for it. It is still possible, but not recommended. If you
really want to do this, forget about exceptions at least.
#if
---
It is generally considered cleaner to use macros in header files (or at
the top of .c files) to abstract away functions rather than using \`#if'
pre-processor statements throughout the source code.
Putting Your Stuff in the Kernel
================================
In order to get your stuff into shape for official inclusion, or even to
make a neat patch, there's administrative work to be done:
- Figure out who are the owners of the code you've been modifying. Look
at the top of the source files, inside the ``MAINTAINERS`` file, and
last of all in the ``CREDITS`` file. You should coordinate with these
people to make sure you're not duplicating effort, or trying something
that's already been rejected.
Make sure you put your name and email address at the top of any files
you create or modify significantly. This is the first place people
will look when they find a bug, or when **they** want to make a change.
- Usually you want a configuration option for your kernel hack. Edit
``Kconfig`` in the appropriate directory. The Config language is
simple to use by cut and paste, and there's complete documentation in
``Documentation/kbuild/kconfig-language.rst``.
In your description of the option, make sure you address both the
expert user and the user who knows nothing about your feature.
Mention incompatibilities and issues here. **Definitely** end your
description with “if in doubt, say N” (or, occasionally, \`Y'); this
is for people who have no idea what you are talking about.
- Edit the ``Makefile``: the CONFIG variables are exported here so you
can usually just add a "obj-$(CONFIG_xxx) += xxx.o" line. The syntax
is documented in ``Documentation/kbuild/makefiles.rst``.
- Put yourself in ``CREDITS`` if you consider what you've done
noteworthy, usually beyond a single file (your name should be at the
top of the source files anyway). ``MAINTAINERS`` means you want to be
consulted when changes are made to a subsystem, and hear about bugs;
it implies a more-than-passing commitment to some part of the code.
- Finally, don't forget to read
``Documentation/process/submitting-patches.rst``
Kernel Cantrips
===============
Some favorites from browsing the source. Feel free to add to this list.
``arch/x86/include/asm/delay.h``::
#define ndelay(n) (__builtin_constant_p(n) ? \
((n) > 20000 ? __bad_ndelay() : __const_udelay((n) * 5ul)) : \
__ndelay(n))
``include/linux/fs.h``::
/*
* Kernel pointers have redundant information, so we can use a
* scheme where we can return either an error code or a dentry
* pointer with the same return value.
*
* This should be a per-architecture thing, to allow different
* error and pointer decisions.
*/
#define ERR_PTR(err) ((void *)((long)(err)))
#define PTR_ERR(ptr) ((long)(ptr))
#define IS_ERR(ptr) ((unsigned long)(ptr) > (unsigned long)(-1000))
``arch/x86/include/asm/uaccess_32.h:``::
#define copy_to_user(to,from,n) \
(__builtin_constant_p(n) ? \
__constant_copy_to_user((to),(from),(n)) : \
__generic_copy_to_user((to),(from),(n)))
``arch/sparc/kernel/head.S:``::
/*
* Sun people can't spell worth damn. "compatability" indeed.
* At least we *know* we can't spell, and use a spell-checker.
*/
/* Uh, actually Linus it is I who cannot spell. Too much murky
* Sparc assembly will do this to ya.
*/
C_LABEL(cputypvar):
.asciz "compatibility"
/* Tested on SS-5, SS-10. Probably someone at Sun applied a spell-checker. */
.align 4
C_LABEL(cputypvar_sun4m):
.asciz "compatible"
``arch/sparc/lib/checksum.S:``::
/* Sun, you just can't beat me, you just can't. Stop trying,
* give up. I'm serious, I am going to kick the living shit
* out of you, game over, lights out.
*/
Thanks
======
Thanks to Andi Kleen for the idea, answering my questions, fixing my
mistakes, filling content, etc. Philipp Rumpf for more spelling and
clarity fixes, and some excellent non-obvious points. Werner Almesberger
for giving me a great summary of :c:func:`disable_irq()`, and Jes
Sorensen and Andrea Arcangeli added caveats. Michael Elizabeth Chastain
for checking and adding to the Configure section. Telsa Gwynne for
teaching me DocBook.
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
이 안내서의 범위와 CPU 실행 주체
1-45Rusty Russell이 쓴 “Unreliable Guide To Hacking The Linux Kernel”은 경험 있는 C programmer를 위한 Linux kernel development 입문서다. Kernel code의 공통 routine과 일반 요구 사항을 설명하지만 implementation detail은 code에 맡기며 유용한 routine 전체를 다루지는 않는다.
저자는 자신이 이 문서를 쓸 자격이 크게 부족하다고 느껴 쓰고 싶지 않았지만 이런 문서를 읽고 싶었기 때문에 직접 작성했다고 말한다. Best practice, 흔한 출발점, 여러 실용 정보의 compendium으로 자라기를 기대한다.
어떤 시점이든 system의 각 CPU는 네 상태 중 하나에 있다.
- 어떤 process와도 연결되지 않은 채 hardware interrupt를 처리
- 어떤 process와도 연결되지 않은 채 softirq 또는 tasklet을 처리
- Process와 연결된 kernel space, 즉 user context에서 실행
- User space에서 process를 실행
이 네 상태에는 순서가 있다. 아래 두 상태는 서로 preempt할 수 있지만 그 위는 엄격한 hierarchy다. 각 level은 자기보다 위에 있는 level에게만 preempt된다. 예를 들어 한 CPU에서 softirq가 실행 중이면 다른 softirq가 이를 preempt하지 않지만 hardware interrupt는 preempt할 수 있다. 다른 CPU는 독립적으로 실행한다.
User context가 interrupt를 막아 완전히 non-preemptable 상태가 되는 여러 방법도 이후 설명한다.
위쪽 context가 아래쪽 실행을 preempt할 수 있다. 다른 CPU에서는 같은 종류의 context가 독립적으로 동시에 실행될 수 있다.
User context, hard IRQ, softirq와 tasklet
47-124User context
System call이나 다른 trap에서 kernel로 들어오면 user context다. Userspace처럼 더 중요한 task와 interrupt에 preempt될 수 있고 schedule()을 호출해 sleep할 수 있다.
Module load·unload와 block device layer operation은 항상 user context에서 실행된다.
User context에서는 현재 실행 중인 task를 나타내는 current pointer가 valid하고 include/linux/preempt.h의 in_interrupt()는 false다. 단, preemption 또는 softirq를 disable하면 in_interrupt()가 false positive를 반환할 수 있다.
Hardware interrupt, hard IRQ
Timer tick, network card, keyboard 같은 실제 hardware는 언제든 interrupt를 만들 수 있다. Kernel은 hardware를 service하는 interrupt handler를 실행한다. 같은 interrupt가 다시 들어오면 queue에 넣거나 drop하므로 같은 handler가 재진입하지 않음을 보장한다.
Interrupt를 disable한 채 실행하므로 handler는 빨라야 한다. 흔히 interrupt를 acknowledge하고 software interrupt를 실행 대상으로 표시한 뒤 종료한다. in_hardirq()가 true면 hardware interrupt 안이다. 다만 interrupt가 disabled인 것만으로 false positive가 나올 수 있다.
Softirq와 tasklet
System call이 userspace로 돌아가기 직전 또는 hardware interrupt handler가 끝날 때 pending으로 표시된 software interrupt를 실행한다. 보통 hardware interrupt가 표시하며 implementation은 kernel/softirq.c에 있다. 실제 interrupt 처리 작업의 상당 부분이 여기서 수행된다.
SMP 전환 초기에는 multi-CPU를 활용하지 못하는 bottom half(BH)만 있었다. 이후 그 제한을 버리고 softirq로 전환했다. Softirq 종류는 include/linux/interrupt.h에 나열된다.
중요한 softirq 중 하나는 include/linux/timer.h의 timer softirq다. 지정한 시간이 지난 뒤 function을 호출하도록 등록할 수 있다.
같은 softirq가 여러 CPU에서 동시에 실행될 수 있어 다루기 까다롭다. 그래서 tasklet을 더 자주 사용한다. Tasklet은 dynamic하게 원하는 수만큼 등록할 수 있고 특정 tasklet instance가 어느 시점에든 CPU 하나에서만 실행됨을 보장한다. 서로 다른 tasklet은 동시에 실행될 수 있다.
Tasklet이라는 이름은 오해를 부르지만 task와는 아무 관계가 없다.
include/linux/preempt.h의 in_softirq()로 softirq 또는 tasklet context를 확인할 수 있다. Bottom half lock을 보유했을 때는 false positive가 날 수 있다.
Kernel code의 기본 제약
125-154Memory protection이 없다
User context든 interrupt context든 memory를 훼손하면 machine 전체가 crash한다. 원하는 일을 userspace에서 할 수 없는지 먼저 확인해야 한다.
Floating point와 MMX를 쓰지 않는다
FPU context가 save되지 않으며 user context에서도 FPU state가 current process와 일치하지 않을 수 있다. 사용하면 어떤 user process의 FPU state를 망가뜨릴 수 있다. 정말 필요하면 전체 FPU state를 명시적으로 save·restore하고 context switch도 피해야 한다. 일반적으로 나쁜 선택이므로 fixed-point arithmetic을 먼저 사용한다.
Kernel stack은 작다
Configuration에 따라 32-bit architecture 대부분의 kernel stack은 약 3~6K, 64-bit architecture 대부분은 약 14K다. Interrupt와 stack을 공유하는 경우가 많아 전부 사용할 수도 없다. 깊은 recursion과 큰 local array를 피하고 대신 dynamic allocation을 사용한다.
Portable code를 유지한다
Code는 64-bit clean하고 endian-independent해야 한다. CPU-specific 부분을 최소화한다. Inline assembly 같은 code는 porting을 쉽게 하도록 명확히 캡슐화하고 최소화하며 보통 kernel tree의 architecture-dependent 영역에 한정한다.
새 system call 대신 ioctl과 sysfs 검토
155-205일반적인 system call 형태는 다음과 같다.
asmlinkage long sys_mycall(int arg)
{
return 0;
}
대부분은 새 system call을 만들지 않는 편이 낫다. Character device를 만들고 적절한 ioctl을 구현한다. System call보다 유연하고 모든 architecture의 include/asm/unistd.h와 arch/kernel/entry.S에 추가할 필요도 없어 받아들여질 가능성이 높다.
Routine이 어떤 parameter를 읽거나 쓰기만 한다면 sysfs interface도 검토한다.
Ioctl 내부는 process에 연결된 user context다. Error가 나면 include/uapi/asm-generic/errno-base.h, include/uapi/asm-generic/errno.h, include/linux/errno.h에 정의된 errno의 음수 값을 반환하고 성공하면 0을 반환한다.
Sleep한 뒤 signal이 발생했는지 확인한다. Unix/Linux는 -ERESTARTSYS로 system call에서 일시적으로 빠져나와 signal을 처리한다. System call entry code가 user context로 돌아가 signal handler를 실행한 뒤 사용자가 restart를 disable하지 않았다면 system call을 다시 시작한다.
if (signal_pending(current))
return -ERESTARTSYS;
따라서 data structure를 수정하던 중이었다면 restart를 안전하게 처리할 수 있어야 한다.
긴 computation은 먼저 userspace 구현을 생각한다. 정말 kernel에서 해야 한다면 CPU를 양보해야 하는지 주기적으로 확인한다. CPU별 cooperative multitasking을 기억해야 한다.
cond_resched(); /* Will sleep */
UNIX system call interface design의 표어는 “policy가 아니라 mechanism을 제공하라”다.
Sleep이 허용되는 조건
207-228Sleep할 수 있는 routine은 다음 세 조건을 모두 만족할 때만 호출할 수 있다.
- User context에 있다.
- 어떤 spinlock도 보유하지 않는다.
- Interrupt가 enabled다. Scheduling code가 enable해 줄 수 있어도 의도한 동작은 아닐 가능성이 크다.
일부 function은 암묵적으로 sleep한다. 흔한 예는 *_user userspace access function과 GFP_ATOMIC을 쓰지 않은 memory allocation function이다.
Kernel은 항상 CONFIG_DEBUG_ATOMIC_SLEEP을 켜고 compile하는 것이 좋다. Rule을 어기면 warning을 내며, 무시하면 결국 machine이 lockup된다.
printk()와 kernel log
230-269printk()는 include/linux/printk.h에 정의되며 kernel message를 console, dmesg, syslog daemon으로 보낸다. Debug와 error report에 유용하고 interrupt context에서도 쓸 수 있다.
그러나 printk message가 console을 가득 채우면 machine을 사용할 수 없으므로 주의한다. ANSI C printf와 대체로 호환되는 format string을 사용하고 C string concatenation으로 첫 priority argument를 붙인다.
printk(KERN_INFO "i = %u\n", i);
다른 KERN_ 값은 include/linux/kern_levels.h에 있으며 syslog가 log level로 해석한다. IP address는 다음처럼 출력한다.
__be32 ipaddress;
printk(KERN_INFO "my ip: %pI4\n", &ipaddress);
printk()는 내부적으로 1K buffer를 사용하고 overflow를 잡지 않으므로 message가 그 안에 들어가는지 확인한다.
User program에서 printf를 printk로 잘못 입력하기 시작하면 진짜 kernel hacker가 된 것이라는 농담이 있다. Original Unix Version 6 source의 printf 위에는 “Printf should not be used for chit-chat”이라는 comment가 있었고 이 조언을 따르는 편이 좋다.
Userspace memory access
270-298copy_to_user(), copy_from_user(), get_user(), put_user()는 include/linux/uaccess.h 또는 asm/uaccess.h에 정의되며 sleep할 수 있다.
put_user()와 get_user()는 int, char, long 같은 single value를 userspace에 쓰거나 userspace에서 읽는다. Userspace pointer를 직접 dereference해서는 안 되며 반드시 이 routine으로 copy한다. 둘은 -EFAULT 또는 0을 반환한다.
copy_to_user()와 copy_from_user()는 임의 길이의 data를 userspace와 주고받는다. put_user()/get_user()와 달리 copy하지 못한 byte 수를 반환하므로 0이 성공이다. 저자는 이 interface가 불쾌하지만 주기적으로 논쟁이 반복된다고 덧붙인다.
이 function들은 암묵적으로 sleep할 수 있다. 의미상 user context 밖에서 호출해서는 안 되며 interrupt disabled 상태나 spinlock 보유 상태에서도 호출하면 안 된다.
Memory allocation, current, delay와 endian
299-384kmalloc()과 kfree()
include/linux/slab.h의 kmalloc()/kfree()는 userspace malloc/free처럼 pointer-aligned memory chunk를 dynamic하게 할당하고 해제한다. kmalloc()에는 추가 flag word가 필요하다.
| Flag | 의미 |
|---|---|
| GFP_KERNEL | Memory 확보를 위해 sleep하거나 swap할 수 있다. User context에서만 허용되며 가장 신뢰할 수 있는 allocation 방식이다. |
| GFP_ATOMIC | Sleep하지 않는다. GFP_KERNEL보다 실패 가능성이 높지만 interrupt context에서 쓸 수 있다. OOM 처리 전략이 반드시 필요하다. |
| GFP_DMA | 16MB 아래 ISA DMA memory를 할당한다. 무엇인지 모른다면 필요하지 않으며 매우 신뢰하기 어렵다. |
Invalid context에서 sleeping function을 호출했다는 warning이 보이면 interrupt context에서 GFP_ATOMIC 없이 allocation했을 수 있다. 즉시 고쳐야 한다.
PAGE_SIZE 이상을 할당한다면 include/linux/gfp.h의 __get_free_pages()를 검토한다. Order 0은 한 page, 1은 두 page, 2는 네 page를 뜻하며 같은 memory priority flag를 받는다.
한 page보다 큰 byte 영역에는 vmalloc()을 사용할 수 있다. Kernel virtual map에 allocation하며 physical memory는 contiguous하지 않지만 MMU가 CPU에 contiguous하게 보이게 한다. External device에는 contiguous하게 보이지 않는다.
장치에 큰 physically contiguous memory가 정말 필요하면 running kernel의 fragmentation 때문에 지원하기 어렵다. 가장 좋은 방법은 boot 초기에 alloc_bootmem()으로 block을 할당하는 것이다. 자주 쓰는 object의 자체 cache를 만들기 전에는 include/linux/slab.h의 slab cache를 검토한다.
current
include/asm/current.h의 current는 실제로는 macro이며 current task structure pointer를 담는다. User context에서만 의미가 있다. Process가 system call을 하면 caller task structure를 가리킨다. Interrupt context에서도 NULL은 아니므로 non-NULL이라는 사실만으로 사용해서는 안 된다.
udelay(), ndelay(), mdelay()
include/asm/delay.h와 include/linux/delay.h의 udelay()/ndelay()는 짧은 pause에 쓴다. 큰 값은 overflow 위험이 있으므로 mdelay() helper를 쓰거나 msleep()을 검토한다.
Endian conversion
include/asm/byteorder.h의 cpu_to_be32() family는 kernel의 일반적인 endian conversion 방법이다. 32는 64나 16으로, be는 le로 바꿀 수 있고 converted value를 반환한다. be32_to_cpu()처럼 모든 reverse variation도 제공한다.
cpu_to_be32p() 같은 pointer variation은 해당 type pointer를 받아 converted value를 반환한다. cpu_to_be32s() 같은 in-situ family는 pointer가 가리키는 value 자체를 변환하고 void를 반환한다.
Local IRQ·bottom half와 CPU ID
385-423local_irq_save()/local_irq_restore()
include/linux/irqflags.h에 정의되며 local CPU의 hard interrupt를 disable하고 이전 상태로 restore한다. 하나의 unsigned long flags argument에 이전 state를 저장하므로 reentrant하다. Interrupt가 enabled임을 확실히 알면 local_irq_disable()/local_irq_enable()을 쓸 수 있다.
local_bh_disable()/local_bh_enable()
include/linux/bottom_half.h에 정의되며 local CPU의 soft interrupt를 disable하고 restore한다. 이전부터 disabled였다면 pair 호출 뒤에도 disabled 상태를 유지해 reentrant하다. Current CPU에서 softirq와 tasklet 실행을 막는다.
get_cpu(), put_cpu(), smp_processor_id()
get_cpu()는 preemption을 disable해 다른 CPU로 이동하지 않게 한 뒤 0과 NR_CPUS 사이 current processor number를 반환한다. CPU number는 연속적이지 않을 수 있다. 작업이 끝나면 put_cpu()를 호출한다.
Interrupt context이거나 preemption을 disable해 다른 task에 preempt될 수 없음을 안다면 smp_processor_id()를 직접 사용할 수 있다.
Init section과 module lifecycle
424-493__init, __exit, __initdata
include/linux/init.h에 정의된다. Boot가 끝나면 kernel은 special section을 해제한다. __init function과 __initdata data structure는 boot 완료 뒤 버려지며 module도 initialization 뒤 이 memory를 버린다.
__exit는 exit에서만 필요한 function을 선언한다. File이 module로 compile되지 않으면 function은 버려진다. __init function을 EXPORT_SYMBOL() 또는 EXPORT_SYMBOL_GPL()로 module에 export하면 memory가 사라진 뒤 참조하게 되어 깨진다.
__initcall()과 module_init()
Kernel의 많은 부분은 dynamic load 가능한 module로 구현하기 좋다. module_init()/module_exit()을 사용하면 #ifdef 없이 module과 built-in 양쪽에서 동작하는 code를 작성할 수 있다.
module_init()은 module compile이면 insertion 때 부를 function을 정한다. Built-in이면 __initcall()과 같아져 linker mechanism으로 boot 때 호출된다.
Init function이 음수 error를 반환하면 module load를 실패시킬 수 있다. Built-in일 때는 불행히도 효과가 없다. Interrupt enabled인 user context에서 호출되므로 sleep할 수 있다.
module_exit()
Module removal 때 부를 function을 정의한다. Built-in이면 호출되지 않는다. Module usage count가 0에 도달한 경우에만 호출된다. Sleep할 수 있지만 실패할 수는 없으므로 return 시점까지 모든 resource를 정리해야 한다. Macro를 생략하면 rmmod -f 외에는 module을 제거할 수 없다.
try_module_get()과 module_put()
Module usage count를 조작해 removal을 막는다. 다른 module이 exported symbol을 사용 중이어도 제거할 수 없다. Module code를 호출하기 전에 try_module_get()을 호출한다. 실패하면 removal 중이므로 없는 것으로 처리한다. 성공하면 안전하게 진입하고 끝난 뒤 module_put()을 호출한다.
struct file_operations 같은 registerable structure 대부분에는 owner field가 있다. 이 field를 THIS_MODULE로 설정한다.
Wait queue를 race 없이 사용하는 순서
494-532include/linux/wait.h의 wait queue는 특정 condition이 true가 될 때 누군가 깨워 주기를 기다리는 mechanism이며 sleep한다. Race가 없도록 주의해서 사용한다.
wait_queue_head_t를 선언하고 condition을 기다릴 process가 자신을 가리키는 wait_queue_entry_t를 만들어 queue에 넣는다. Head는 DECLARE_WAIT_QUEUE_HEAD()로 선언하거나 initialization code에서 init_waitqueue_head()로 초기화한다.
Queue에 들어가는 순서가 중요하다. Condition을 검사하기 전에 자신을 queue에 넣어야 한다. wait_event_interruptible() macro가 이 과정을 처리한다. 첫 argument는 wait queue head, 둘째는 평가할 expression이다.
Expression이 true가 되면 0을 반환하고 signal을 받으면 -ERESTARTSYS를 반환한다. wait_event() version은 signal을 무시한다.
wake_up()은 queue의 모든 process를 깨운다. TASK_EXCLUSIVE가 설정된 entry를 만나면 queue의 나머지는 깨우지 않는다. 같은 header에 다른 variant도 있다.
Waiter는 condition 검사보다 먼저 queue에 등록되어야 한다. Producer가 condition을 바꾸고 wake_up()을 호출하면 waiter가 다시 검사한 뒤 진행한다.
Atomic operation과 exported symbol
533-613atomic_t operation
모든 platform에서 atomic으로 보장되는 operation이 있다. 첫 class는 include/asm/atomic.h의 atomic_t를 대상으로 한다. 최소 32-bit인 signed integer를 담으며 atomic_t는 전용 function으로만 읽고 수정한다.
atomic_read()/atomic_set()은 counter를 읽고 설정한다. atomic_add(), atomic_sub(), atomic_inc(), atomic_dec()가 산술 operation을 제공한다. atomic_dec_and_test()는 감소 결과가 0이면 true를 반환한다. 일반 arithmetic보다 느리므로 불필요하게 사용하지 않는다.
Atomic bit operation
두 번째 class는 include/linux/bitops.h의 unsigned long 대상 atomic bit operation이다. 보통 bit pattern pointer와 bit number를 받으며 0이 least significant bit다.
set_bit(), clear_bit(), change_bit()는 지정 bit를 set, clear, flip한다. test_and_set_bit(), test_and_clear_bit(), test_and_change_bit()은 같은 동작을 하면서 이전 bit가 set돼 있었으면 true를 반환해 flag를 atomic하게 설정할 때 유용하다.
BITS_PER_LONG보다 큰 bit index로도 호출할 수 있지만 big-endian platform에서 결과가 이상하므로 피하는 것이 좋다.
Kernel symbol export
Kernel proper 안에서는 일반 linking rule이 적용된다. static으로 file scope를 지정하지 않은 symbol은 kernel 어디서든 사용할 수 있다. Module은 kernel proper 진입점을 제한하는 별도 exported symbol table을 사용하며 module도 symbol을 export할 수 있다.
| Macro | 의미 |
|---|---|
| EXPORT_SYMBOL() | 일반 export. Dynamic module이 symbol을 정상적으로 사용할 수 있다. |
| EXPORT_SYMBOL_GPL() | MODULE_LICENSE()가 GPLv2-compatible license를 지정한 module만 볼 수 있다. Internal implementation에 가깝다는 뜻이며 maintainer에 따라 새 API 전부에 요구할 수 있다. |
| EXPORT_SYMBOL_NS() | Symbol namespace를 지정할 수 있는 EXPORT_SYMBOL() variant |
| EXPORT_SYMBOL_NS_GPL() | Symbol namespace를 지정할 수 있는 EXPORT_SYMBOL_GPL() variant |
Namespace는 Documentation/core-api/symbol-namespaces.rst에 설명되어 있다. 모든 macro는 include/linux/export.h에 정의된다.
Kernel routine convention과 C language 사용
614-719Double-linked list
Kernel header에는 한때 linked-list routine set이 세 개 있었지만 include/linux/list.h가 표준으로 남았다. Single list가 반드시 필요한 특별한 이유가 없다면 좋은 선택이며 list_for_each_entry()가 특히 유용하다.
Return convention과 error pointer
User context에서 호출되는 code는 C 관례와 달리 성공에 0, 실패에 -EFAULT 같은 음수 error number를 반환하는 경우가 매우 흔하다.
include/linux/err.h의 ERR_PTR()로 negative error를 pointer에 encode하고 IS_ERR()와 PTR_ERR()로 검사·복원하면 error number용 별도 pointer parameter를 피할 수 있다.
Development kernel의 compile breakage
Linus와 developer는 development kernel에서 function이나 structure 이름을 바꾸기도 한다. 단순히 외부 code를 귀찮게 하려는 것이 아니라 interrupt enabled 상태에서 더는 호출할 수 없거나 check가 추가·제거되는 등 근본적인 변화를 반영한다.
보통 관련 development mailing list에 자세한 note가 올라오므로 archive를 검색한다. File 전체를 global replace하면 대개 더 나빠진다.
Designated initializer
Structure는 ISO C99 designated initializer로 초기화하는 것이 선호된다. Grep하기 쉽고 어떤 field를 설정했는지 분명하다.
static struct block_device_operations opt_fops = {
.open = opt_open,
.release = opt_release,
.ioctl = opt_ioctl,
.check_media_change = opt_media_change,
};
GNU extension
Linux kernel은 GNU extension을 명시적으로 허용한다. 일반 사용이 적은 복잡한 extension은 지원이 좋지 않을 수 있다. 자세한 내용은 GCC info page의 C Extensions 절을 본다. Man page는 info 내용의 짧은 요약일 뿐이다.
- Inline function
- Statement expression, 즉 ({ ... }) construct
- __attribute__로 function, variable, type attribute 선언
- typeof
- Zero-length array
- Macro varargs
- void pointer arithmetic
- Non-constant initializer
- Assembler instruction. arch/와 include/asm/ 밖에서는 사용하지 않는다.
- __func__ function name string
- __builtin_constant_p()
Kernel에서 long long 사용은 주의한다. GCC가 만드는 code가 좋지 않고 i386 kernel environment에는 GCC runtime function이 없어 division과 multiplication이 동작하지 않는다.
C++와 #if
Kernel은 필요한 runtime environment를 제공하지 않고 include file도 C++로 test하지 않으므로 C++ 사용은 보통 나쁜 생각이다. 가능은 하지만 권장하지 않으며 정말 사용한다면 최소한 exception은 포기해야 한다.
Source code 곳곳에 #if preprocessor statement를 두기보다 header file 또는 .c file 위쪽의 macro로 function 차이를 abstraction하는 편이 더 깔끔하다고 여겨진다.
Code를 kernel inclusion 형태로 준비하기
720-759Official inclusion 또는 정돈된 patch를 만들려면 administrative 작업이 필요하다.
- 수정한 code의 owner를 찾는다. Source file 위쪽, MAINTAINERS, 마지막으로 CREDITS를 확인한다. 중복 작업이나 이미 거부된 시도를 피하도록 이들과 조율한다.
- 새로 만들거나 크게 수정한 file 위쪽에 자신의 이름과 email을 넣는다. Bug를 찾거나 다른 change를 하려는 사람이 가장 먼저 보는 곳이다.
- 보통 Kconfig에 configuration option을 추가한다. 언어는 Documentation/kbuild/kconfig-language.rst에 설명되어 있다.
- Option description은 expert와 기능을 전혀 모르는 사용자 모두를 대상으로 쓰고 incompatibility와 issue를 언급한다. 마지막에는 “if in doubt, say N” 또는 드물게 Y를 명확히 적는다.
- Makefile에 보통 obj-$(CONFIG_xxx) += xxx.o line을 추가한다. Syntax는 Documentation/kbuild/makefiles.rst에 있다.
- 한 file을 넘어 주목할 만한 일을 했다면 CREDITS에 자신을 추가할 수 있다. MAINTAINERS에 들어간다는 것은 subsystem change 때 협의하고 bug report를 받겠다는 지속적인 책임을 뜻한다.
- 마지막으로 Documentation/process/submitting-patches.rst를 읽는다.
Kernel source의 흥미로운 code 예시
760-820Source를 탐색하며 찾은 저자의 예시들이다. arch/x86/include/asm/delay.h의 ndelay()는 n이 compile-time constant인지 검사해 constant path와 generic path를 고르고 너무 큰 constant는 __bad_ndelay()로 보낸다.
#define ndelay(n) (__builtin_constant_p(n) ? \
((n) > 20000 ? __bad_ndelay() : __const_udelay((n) * 5ul)) : \
__ndelay(n))
include/linux/fs.h의 ERR_PTR 계열은 kernel pointer의 redundant information을 이용해 하나의 return value에 error code 또는 dentry pointer를 담는다. Architecture마다 error와 pointer 범위를 다르게 정할 수 있어 원래는 per-architecture여야 한다는 comment가 있다.
#define ERR_PTR(err) ((void *)((long)(err)))
#define PTR_ERR(ptr) ((long)(ptr))
#define IS_ERR(ptr) ((unsigned long)(ptr) > (unsigned long)(-1000))
arch/x86/include/asm/uaccess_32.h의 copy_to_user macro는 n이 compile-time constant이면 optimized constant copy를, 아니면 generic copy를 선택한다.
#define copy_to_user(to,from,n) \
(__builtin_constant_p(n) ? \
__constant_copy_to_user((to),(from),(n)) : \
__generic_copy_to_user((to),(from),(n)))
arch/sparc/kernel/head.S에는 Sun의 “compatability” 오타를 놀리는 comment와, 실제로 오타를 낸 쪽은 자신이었다고 정정하는 comment가 이어진다. SS-5와 SS-10에서 test한 뒤 “compatible” string을 둔 code도 있다.
/* Uh, actually Linus it is I who cannot spell. Too much murky
* Sparc assembly will do this to ya.
*/
C_LABEL(cputypvar):
.asciz "compatibility"
/* Tested on SS-5, SS-10. Probably someone at Sun applied a spell-checker. */
.align 4
C_LABEL(cputypvar_sun4m):
.asciz "compatible"
arch/sparc/lib/checksum.S에는 Sun과의 성능 경쟁에서 질 수 없다는 매우 거친 어조의 comment도 실려 있다.
/* Sun, you just can't beat me, you just can't. Stop trying,
* give up. I'm serious, I am going to kick the living shit
* out of you, game over, lights out.
*/
감사의 말
821-830아이디어를 주고 질문에 답하며 오류 수정과 내용 보강을 도운 Andi Kleen, spelling·clarity 수정과 중요한 비직관적 지적을 더한 Philipp Rumpf, disable_irq()를 훌륭하게 요약한 Werner Almesberger에게 감사한다.
Caveat를 추가한 Jes Sorensen과 Andrea Arcangeli, Configure section을 확인하고 보강한 Michael Elizabeth Chastain, DocBook을 가르쳐 준 Telsa Gwynne에게도 감사한다.
CPU가 실행할 수 있는 네 문맥
hacking.rst:25-124System call이나 fault에서 kernel로 들어온 process context는 current가 의미 있고 schedule할 수 있습니다. Hardirq는 hardware를 acknowledge하고 최소 state만 기록한 뒤 softirq, threaded IRQ, workqueue 같은 뒤 단계로 일을 넘겨야 합니다. Softirq는 return-to-user 또는 interrupt exit 지점에서 pending work를 처리하며 다른 CPU에서 동시에 실행될 수 있습니다.
in_interrupt()나 in_hardirq()는 일부 disable state에서 false positive를 낼 수 있어 API 설계의 sleep 가능 여부를 runtime probe 하나로 결정하는 방법은 적절하지 않습니다. 호출 계약으로 context를 명시합니다.