📄 kernel-hacking.tmpl
字号:
<para> See <filename class="headerfile">include/linux/kernel.h</filename>; for other KERN_ values; these are interpreted by syslog as the level. Special case: for printing an IP address use </para> <programlisting>__u32 ipaddress;printk(KERN_INFO "my ip: %d.%d.%d.%d\n", NIPQUAD(ipaddress)); </programlisting> <para> <function>printk()</function> internally uses a 1K buffer and does not catch overruns. Make sure that will be enough. </para> <note> <para> You will know when you are a real kernel hacker when you start typoing printf as printk in your user programs :) </para> </note> <!--- From the Lions book reader department --> <note> <para> 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. </para> </note> </sect1> <sect1 id="routines-copy"> <title> <function>copy_[to/from]_user()</function> / <function>get_user()</function> / <function>put_user()</function> <filename class="headerfile">include/asm/uaccess.h</filename> </title> <para> <emphasis>[SLEEPS]</emphasis> </para> <para> <function>put_user()</function> and <function>get_user()</function> 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 <constant>-EFAULT</constant> or 0. </para> <para> <function>copy_to_user()</function> and <function>copy_from_user()</function> are more general: they copy an arbitrary amount of data to and from userspace. <caution> <para> Unlike <function>put_user()</function> and <function>get_user()</function>, they return the amount of uncopied data (ie. <returnvalue>0</returnvalue> still means success). </para> </caution> [Yes, this moronic interface makes me cringe. The flamewar comes up every year or so. --RR.] </para> <para> The functions may sleep implicitly. This should never be called outside user context (it makes no sense), with interrupts disabled, or a spinlock held. </para> </sect1> <sect1 id="routines-kmalloc"> <title><function>kmalloc()</function>/<function>kfree()</function> <filename class="headerfile">include/linux/slab.h</filename></title> <para> <emphasis>[MAY SLEEP: SEE BELOW]</emphasis> </para> <para> These routines are used to dynamically request pointer-aligned chunks of memory, like malloc and free do in userspace, but <function>kmalloc()</function> takes an extra flag word. Important values: </para> <variablelist> <varlistentry> <term> <constant> GFP_KERNEL </constant> </term> <listitem> <para> May sleep and swap to free memory. Only allowed in user context, but is the most reliable way to allocate memory. </para> </listitem> </varlistentry> <varlistentry> <term> <constant> GFP_ATOMIC </constant> </term> <listitem> <para> Don't sleep. Less reliable than <constant>GFP_KERNEL</constant>, but may be called from interrupt context. You should <emphasis>really</emphasis> have a good out-of-memory error-handling strategy. </para> </listitem> </varlistentry> <varlistentry> <term> <constant> GFP_DMA </constant> </term> <listitem> <para> Allocate ISA DMA lower than 16MB. If you don't know what that is you don't need it. Very unreliable. </para> </listitem> </varlistentry> </variablelist> <para> If you see a <errorname>sleeping function called from invalid context</errorname> warning message, then maybe you called a sleeping allocation function from interrupt context without <constant>GFP_ATOMIC</constant>. You should really fix that. Run, don't walk. </para> <para> If you are allocating at least <constant>PAGE_SIZE</constant> (<filename class="headerfile">include/asm/page.h</filename>) bytes, consider using <function>__get_free_pages()</function> (<filename class="headerfile">include/linux/mm.h</filename>). 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. </para> <para> If you are allocating more than a page worth of bytes you can use <function>vmalloc()</function>. It'll allocate virtual memory in the kernel map. This block is not contiguous in physical memory, but the <acronym>MMU</acronym> 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 <function>alloc_bootmem()</function> routine. </para> <para> Before inventing your own cache of often-used objects consider using a slab cache in <filename class="headerfile">include/linux/slab.h</filename> </para> </sect1> <sect1 id="routines-current"> <title><function>current</function> <filename class="headerfile">include/asm/current.h</filename></title> <para> 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 <emphasis>not NULL</emphasis> in interrupt context. </para> </sect1> <sect1 id="routines-udelay"> <title><function>mdelay()</function>/<function>udelay()</function> <filename class="headerfile">include/asm/delay.h</filename> <filename class="headerfile">include/linux/delay.h</filename> </title> <para> The <function>udelay()</function> and <function>ndelay()</function> functions can be used for small pauses. Do not use large values with them as you risk overflow - the helper function <function>mdelay()</function> is useful here, or consider <function>msleep()</function>. </para> </sect1> <sect1 id="routines-endian"> <title><function>cpu_to_be32()</function>/<function>be32_to_cpu()</function>/<function>cpu_to_le32()</function>/<function>le32_to_cpu()</function> <filename class="headerfile">include/asm/byteorder.h</filename> </title> <para> The <function>cpu_to_be32()</function> 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: <function>be32_to_cpu()</function>, etc. </para> <para> There are two major variations of these functions: the pointer variation, such as <function>cpu_to_be32p()</function>, which take a pointer to the given type, and return the converted value. The other variation is the "in-situ" family, such as <function>cpu_to_be32s()</function>, which convert value referred to by the pointer, and return void. </para> </sect1> <sect1 id="routines-local-irqs"> <title><function>local_irq_save()</function>/<function>local_irq_restore()</function> <filename class="headerfile">include/asm/system.h</filename> </title> <para> These routines disable hard interrupts on the local CPU, and restore them. They are reentrant; saving the previous state in their one <varname>unsigned long flags</varname> argument. If you know that interrupts are enabled, you can simply use <function>local_irq_disable()</function> and <function>local_irq_enable()</function>. </para> </sect1> <sect1 id="routines-softirqs"> <title><function>local_bh_disable()</function>/<function>local_bh_enable()</function> <filename class="headerfile">include/linux/interrupt.h</filename></title> <para> 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. </para> </sect1> <sect1 id="routines-processorids"> <title><function>smp_processor_id</function>() <filename class="headerfile">include/asm/smp.h</filename></title> <para> <function>get_cpu()</function> disables preemption (so you won't suddenly get moved to another CPU) and returns the current processor number, between 0 and <symbol>NR_CPUS</symbol>. Note that the CPU numbers are not necessarily continuous. You return it again with <function>put_cpu()</function> when you are done. </para> <para> 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(). </para> </sect1> <sect1 id="routines-init"> <title><type>__init</type>/<type>__exit</type>/<type>__initdata</type> <filename class="headerfile">include/linux/init.h</filename></title> <para> After boot, the kernel frees up a special section; functions marked with <type>__init</type> and data structures marked with <type>__initdata</type> are dropped after boot is complete: similarly modules discard this memory after initialization. <type>__exit</type> 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 <type>__init</type> to be exported to modules with <function>EXPORT_SYMBOL()</function> - this will break. </para> </sect1> <sect1 id="routines-init-again"> <title><function>__initcall()</function>/<function>module_init()</function> <filename class="headerfile">include/linux/init.h</filename></title> <para> Many parts of the kernel are well served as a module (dynamically-loadable parts of the kernel). Using the <function>module_init()</function> and <function>module_exit()</function> macros it is easy to write code without #ifdefs which can operate both as a module or built into the kernel. </para> <para> The <function>module_init()</function> 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 <function>module_init()</function> macro becomes equivalent to <function>__initcall()</function>, which through linker magic ensures that the function is called on boot. </para> <para> 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. </para> </sect1> <sect1 id="routines-moduleexit"> <title> <function>module_exit()</function> <filename class="headerfile">include/linux/init.h</filename> </title> <para> 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. </para> <para> Note that this macro is optional: if it is not present, your module will not be removable (except for 'rmmod -f'). </para> </sect1> <sect1 id="routines-module-use-counters"> <title> <function>try_module_get()</function>/<function>module_put()</function> <filename class="headerfile">include/linux/module.h</filename></title> <para> 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 <function>try_module_get()</function> 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 <function>module_put()</function> when you're finished. </para> <para> Most registerable structures have an <structfield>owner</structfield> field, such as in the <structname>file_operations</structname> structure. Set this field to the macro <symbol>THIS_MODULE</symbol>. </para> </sect1> <!-- add info on new-style module refcounting here --> </chapter> <chapter id="queues"> <title>Wait Queues <filename class="headerfile">include/linux/wait.h</filename> </title> <para> <emphasis>[SLEEPS]</emphasis> </para> <para> 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 <type>wait_queue_head_t</type>, and then processes which want to wait for that condition declare a <type>wait_queue_t</type> referring to themselves, and place that in the queue. </para> <sect1 id="queue-declaring"> <title>Declaring</title> <para> You declare a <type>wait_queue_head_t</type> using the <function>DECLARE_WAIT_QUEUE_HEAD()</function> macro, or using the <function>init_waitqueue_head()</function> routine in your initialization code. </para> </sect1> <sect1 id="queue-waitqueue"> <title>Queuing</title> <para> 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: <function>wait_event_interruptible()</function> <filename class="headerfile">include/linux/wait.h</filename> The first argument is the wait queue head, and the second is an expression which is evaluated; the macro returns <returnvalue>0</returnvalue> when this expression is true, or <returnvalue>-ERESTARTSYS</returnvalue> if a signal is received. The <function>wait_event()</function> version ignores signals. </para> <para> Do not use the <function>sleep_on()</function> function family - it is very easy to accidentally introduce races; almost certainly one of the <function>wait_event()</function> family will do, or a loop around <function>schedule_timeout()</function>. If you choose to loop around <function>schedule_timeout()</function> remember you must set the task state (with <function>set_current_state()</function>) on each iteration to avoid busy-looping. </para> </sect1> <sect1 id="queue-waking"> <title>Waking Up Queued Tasks</title> <para> Call <function>wake_up()</function> <filename class="headerfile">include/linux/wait.h</filename>;, which will wake up every process in the queue. The exception is if one has <constant>TASK_EXCLUSIVE</constant> 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. </para> </sect1> </chapter> <chapter id="atomic-ops"> <title>Atomic Operations</title> <para> Certain operations are guaranteed atomic on all platforms. The first class of operations work on <type>atomic_t</type>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -