⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 kernel-hacking.tmpl

📁 Linux内核源代码 为压缩文件 是<<Linux内核>>一书中的源代码
💻 TMPL
📖 第 1 页 / 共 3 页
字号:
printk(KERN_INFO "i = %u\n", i);   </programlisting>   <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.  Please submit a    patch and become my hero --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>kmem_grow: Called nonatomically from int    </errorname> warning message you called a memory 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.   </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-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/asm/softirq.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, tasklets    and bottom halves from running on the current CPU.   </para>  </sect1>  <sect1 id="routines-processorids">   <title><function>smp_processor_id</function>()/<function>cpu_[number/logical]_map()</function>    <filename class=headerfile>include/asm/smp.h</filename></title>      <para>    <function>smp_processor_id()</function> returns the current    processor number, between 0 and <symbol>NR_CPUS</symbol> (the    maximum number of CPUs supported by Linux, currently 32).  These    values are not necessarily continuous: to get a number between 0    and <function>smp_num_cpus()</function> (the number of actual    processors in this machine), the    <function>cpu_number_map()</function> function is used to map the    processor id to a logical number.    <function>cpu_logical_map()</function> does the reverse.   </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 (within    modules this directive is currently ignored).  <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.   </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).  For modules, this is    called in user context, with interrupts enabled, and the    kernel lock held, 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>  </sect1>  <sect1 id="routines-module-use-counters">   <title> <function>MOD_INC_USE_COUNT</function>/<function>MOD_DEC_USE_COUNT</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).  Every reference to    the module from user context should be reflected by this    counter (e.g. for every data structure or socket) before the    function sleeps.  To quote Tim Waugh:   </para>   <programlisting>/* THIS IS BAD */foo_open (...){        stuff..        if (fail)                return -EBUSY;        sleep.. (might get unloaded here)        stuff..        MOD_INC_USE_COUNT;        return 0;}/* THIS IS GOOD /foo_open (...){        MOD_INC_USE_COUNT;        stuff..        if (fail) {                MOD_DEC_USE_COUNT;                return -EBUSY;        }        sleep.. (safe now)        stuff..        return 0;}   </programlisting>  </sect1> </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/sched.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>  </sect1>  <sect1 id="queue-waking">   <title>Waking Up Queued Tasks</title>      <para>    Call <function>wake_up()</function>    <filename class=headerfile>include/linux/sched.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.   </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>   <filename class=headerfile>include/asm/atomic.h</filename>; this   contains a signed integer (at least 24 bits long), and you must use   these functions to manipulate or read atomic_t variables.   <function>atomic_read()</function> and   <function>atomic_set()</function> get and set the counter,   <function>atomic_add()</function>,   <function>atomic_sub()</function>,   <function>atomic_inc()</function>,   <function>atomic_dec()</function>, and   <function>atomic_dec_and_test()</function> (returns   <returnvalue>true</returnvalue> if it was decremented to zero).  </para>  <para>   Yes.  It returns <returnvalue>true</returnvalue> (i.e. != 0) if the   atomic variable is zero.  </para>  <para>   Note that these functions are slower than normal arithmetic, and   so should not be used unnecessarily.  On some platforms they   are much slower, like 32-bit Sparc where they use a spinlock.  </para>  <para>   The second class of atomic operations is atomic bit operations on a   <type>long</type>, defined in   <filename class=headerfile>include/asm/bitops.h</filename>.  These   operations generally take a pointer to the bit pattern, and a bit   number: 0 is the least significant bit.   <function>set_bit()</function>, <function>clear_bit()</function>   and <function>change_bit()</function> set, clear, and flip the   given bit.  <function>test_and_set_bit()</function>,   <function>test_and_clear_bit()</function> and

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -