# The Linux Kernel API

This documentation is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

For more details see the file COPYING in the source distribution of Linux.

## Driver Basics

### Driver Entry and Exit points

#### LINUX

Kernel Hackers Manual March 2006
module_init
9

#### module_init

driver initialization entry point

##### Synopsis

        module_init
        x

##### Arguments

`x`

  function to be run at kernel boot time or module insertion

##### Description

`module_init` will either be called during do_initcalls (if builtin) or at module insertion time (if a module). There can only be one per module.

#### LINUX

Kernel Hackers Manual March 2006
module_exit
9

#### module_exit

driver exit entry point

##### Synopsis

        module_exit
        x

##### Arguments

`x`

  function to be run when driver is removed

##### Description

`module_exit` will wrap the driver clean-up code with `cleanup_module` when used with rmmod when the driver is a module. If the driver is statically compiled into the kernel, `module_exit` has no effect. There can only be one per module.

### Atomic and pointer manipulation

#### LINUX

Kernel Hackers Manual March 2006
atomic_read
9

#### atomic_read

read atomic variable

##### Synopsis

        atomic_read
        v

##### Arguments

`v`

  pointer of type atomic_t

##### Description

Atomically reads the value of `v`.

#### LINUX

Kernel Hackers Manual March 2006
atomic_set
9

#### atomic_set

set atomic variable

##### Synopsis

        atomic_set
        v
        i

##### Arguments

`v`

  pointer of type atomic_t

`i`

  required value

##### Description

Atomically sets the value of `v` to `i`.

#### LINUX

Kernel Hackers Manual March 2006
atomic_add
9

#### atomic_add

add integer to atomic variable

##### Synopsis

       void atomic_add
       int i
       atomic_t * v

##### Arguments

`i`

  integer value to add

`v`

  pointer of type atomic_t

##### Description

Atomically adds `i` to `v`.

#### LINUX

Kernel Hackers Manual March 2006
atomic_sub
9

#### atomic_sub

subtract the atomic variable

##### Synopsis

       void atomic_sub
       int i
       atomic_t * v

##### Arguments

`i`

  integer value to subtract

`v`

  pointer of type atomic_t

##### Description

Atomically subtracts `i` from `v`.

#### LINUX

Kernel Hackers Manual March 2006
atomic_sub_and_test
9

#### atomic_sub_and_test

subtract value from variable and test result

##### Synopsis

       int atomic_sub_and_test
       int i
       atomic_t * v

##### Arguments

`i`

  integer value to subtract

`v`

  pointer of type atomic_t

##### Description

Atomically subtracts `i` from `v` and returns true if the result is zero, or false for all other cases.

#### LINUX

Kernel Hackers Manual March 2006
atomic_inc
9

#### atomic_inc

increment atomic variable

##### Synopsis

       void atomic_inc
       atomic_t * v

##### Arguments

`v`

  pointer of type atomic_t

##### Description

Atomically increments `v` by 1.

#### LINUX

Kernel Hackers Manual March 2006
atomic_dec
9

#### atomic_dec

decrement atomic variable

##### Synopsis

       void atomic_dec
       atomic_t * v

##### Arguments

`v`

  pointer of type atomic_t

##### Description

Atomically decrements `v` by 1.

#### LINUX

Kernel Hackers Manual March 2006
atomic_dec_and_test
9

#### atomic_dec_and_test

decrement and test

##### Synopsis

       int atomic_dec_and_test
       atomic_t * v

##### Arguments

`v`

  pointer of type atomic_t

##### Description

Atomically decrements `v` by 1 and returns true if the result is 0, or false for all other cases.

#### LINUX

Kernel Hackers Manual March 2006
atomic_inc_and_test
9

#### atomic_inc_and_test

increment and test

##### Synopsis

       int atomic_inc_and_test
       atomic_t * v

##### Arguments

`v`

  pointer of type atomic_t

##### Description

Atomically increments `v` by 1 and returns true if the result is zero, or false for all other cases.

#### LINUX

Kernel Hackers Manual March 2006
atomic_add_negative
9

#### atomic_add_negative

add and test if negative

##### Synopsis

       int atomic_add_negative
       int i
       atomic_t * v

##### Arguments

`i`

  integer value to add

`v`

  pointer of type atomic_t

##### Description

Atomically adds `i` to `v` and returns true if the result is negative, or false when result is greater than or equal to zero.

#### LINUX

Kernel Hackers Manual March 2006
atomic_add_return
9

#### atomic_add_return

add and return

##### Synopsis

       int atomic_add_return
       int i
       atomic_t * v

##### Arguments

`i`

  integer value to add

`v`

  pointer of type atomic_t

##### Description

Atomically adds `i` to `v` and returns `i` + `v`

#### LINUX

Kernel Hackers Manual March 2006
atomic_add_unless
9

#### atomic_add_unless

add unless the number is a given value

##### Synopsis

        atomic_add_unless
        v
        a
        u

##### Arguments

`v`

  pointer of type atomic_t

`a`

  the amount to add to v...

`u`

  ...unless v is equal to u.

##### Description

Atomically adds `a` to `v`, so long as it was not `u`. Returns non-zero if `v` was not `u`, and zero otherwise.

#### LINUX

Kernel Hackers Manual March 2006
get_unaligned
9

#### get_unaligned

get value from possibly mis-aligned location

##### Synopsis

        get_unaligned
        ptr

##### Arguments

`ptr`

  pointer to value

##### Description

This macro should be used for accessing values larger in size than single bytes at locations that are expected to be improperly aligned, e.g. retrieving a u16 value from a location not u16-aligned.

Note that unaligned accesses can be very expensive on some architectures.

#### LINUX

Kernel Hackers Manual March 2006
put_unaligned
9

#### put_unaligned

put value to a possibly mis-aligned location

##### Synopsis

        put_unaligned
        val
        ptr

##### Arguments

`val`

  value to place

`ptr`

  pointer to location

##### Description

This macro should be used for placing values larger in size than single bytes at locations that are expected to be improperly aligned, e.g. writing a u16 value to a location not u16-aligned.

Note that unaligned accesses can be very expensive on some architectures.

### Delaying, scheduling, and timer routines

#### LINUX

Kernel Hackers Manual March 2006
pid_alive
9

#### pid_alive

check that a task structure is not stale

##### Synopsis

       int pid_alive
       struct task_struct * p

##### Arguments

`p`

  Task structure to be checked.

##### Description

Test if a process is not yet dead (at most zombie state) If pid_alive fails, then pointers within the task structure can be stale and must not be dereferenced.

#### LINUX

Kernel Hackers Manual March 2006
__wake_up
9

#### __wake_up

wake up threads blocked on a waitqueue.

##### Synopsis

       void fastcall __wake_up
       wait_queue_head_t * q
       unsigned int mode
       int nr_exclusive
       void * key

##### Arguments

`q`

  the waitqueue

`mode`

  which threads

`nr_exclusive`

  how many wake-one or wake-many threads to wake up

`key`

  is directly passed to the wakeup function

#### LINUX

Kernel Hackers Manual March 2006
__wake_up_sync
9

#### __wake_up_sync

wake up threads blocked on a waitqueue.

##### Synopsis

       void fastcall __wake_up_sync
       wait_queue_head_t * q
       unsigned int mode
       int nr_exclusive

##### Arguments

`q`

  the waitqueue

`mode`

  which threads

`nr_exclusive`

  how many wake-one or wake-many threads to wake up

##### Description

The sync wakeup differs that the waker knows that it will schedule away soon, so while the target thread will be woken up, it will not be migrated to another CPU - ie. the two threads are 'synchronized' with each other. This can prevent needless bouncing between CPUs.

On UP it can prevent extra preemption.

#### LINUX

Kernel Hackers Manual March 2006
task_nice
9

#### task_nice

return the nice value of a given task.

##### Synopsis

       int task_nice
       const task_t * p

##### Arguments

`p`

  the task in question.

#### LINUX

Kernel Hackers Manual March 2006
sched_setscheduler
9

#### sched_setscheduler

change the scheduling policy and/or RT priority of

##### Synopsis

       int sched_setscheduler
       struct task_struct * p
       int policy
       struct sched_param * param

##### Arguments

`p`

  the task in question.

`policy`

  new policy.

`param`

  structure containing the new RT priority.

##### Description

a thread.

#### LINUX

Kernel Hackers Manual March 2006
yield
9

#### yield

yield the current processor to other threads.

##### Synopsis

       void __sched yield
        void

##### Arguments

`void`

  no arguments

##### Description

this is a shortcut for kernel-space yielding - it marks the thread runnable and calls `sys_sched_yield`.

#### LINUX

Kernel Hackers Manual March 2006
schedule_timeout
9

#### schedule_timeout

sleep until timeout

##### Synopsis

       signed long __sched schedule_timeout
       signed long timeout

##### Arguments

`timeout`

  timeout value in jiffies

##### Description

Make the current task sleep until `timeout` jiffies have elapsed. The routine will return immediately unless the current task state has been set (see `set_current_state`).

You can set the task state as follows -

`TASK_UNINTERRUPTIBLE` - at least `timeout` jiffies are guaranteed to pass before the routine returns. The routine will return 0

`TASK_INTERRUPTIBLE` - the routine may return early if a signal is delivered to the current task. In this case the remaining time in jiffies will be returned, or 0 if the timer expired in time

The current task state is guaranteed to be TASK_RUNNING when this routine returns.

Specifying a `timeout` value of `MAX_SCHEDULE_TIMEOUT` will schedule the CPU away without a bound on the timeout. In this case the return value will be `MAX_SCHEDULE_TIMEOUT`.

In all cases the return value is guaranteed to be non-negative.

#### LINUX

Kernel Hackers Manual March 2006
msleep
9

#### msleep

sleep safely even with waitqueue interruptions

##### Synopsis

       void msleep
       unsigned int msecs

##### Arguments

`msecs`

  Time in milliseconds to sleep for

#### LINUX

Kernel Hackers Manual March 2006
msleep_interruptible
9

#### msleep_interruptible

sleep waiting for signals

##### Synopsis

       unsigned long msleep_interruptible
       unsigned int msecs

##### Arguments

`msecs`

  Time in milliseconds to sleep for

### High-resolution timers

#### LINUX

Kernel Hackers Manual March 2006
ktime_set
9

#### ktime_set

Set a ktime_t variable from a seconds/nanoseconds value

##### Synopsis

       ktime_t ktime_set
       const long secs
       const unsigned long nsecs

##### Arguments

`secs`

  seconds to set

`nsecs`

  nanoseconds to set

##### Description

Return the ktime_t representation of the value

##### Description

Return the ktime_t representation of the value

#### LINUX

Kernel Hackers Manual March 2006
ktime_sub
9

#### ktime_sub

subtract two ktime_t variables

##### Synopsis

       ktime_t ktime_sub
       const ktime_t lhs
       const ktime_t rhs

##### Arguments

`lhs`

  minuend

`rhs`

  subtrahend

##### Description

Returns the remainder of the substraction

##### Description

Returns the remainder of the substraction

#### LINUX

Kernel Hackers Manual March 2006
ktime_add
9

#### ktime_add

add two ktime_t variables

##### Synopsis

       ktime_t ktime_add
       const ktime_t add1
       const ktime_t add2

##### Arguments

`add1`

  addend1

`add2`

  addend2

##### Description

Returns the sum of addend1 and addend2

##### Description

Returns the sum of addend1 and addend2

#### LINUX

Kernel Hackers Manual March 2006
ktime_add_ns
9

#### ktime_add_ns

Add a scalar nanoseconds value to a ktime_t variable

##### Synopsis

       ktime_t ktime_add_ns
       const ktime_t kt
       u64 nsec

##### Arguments

`kt`

  addend

`nsec`

  the scalar nsec value to add

##### Description

Returns the sum of kt and nsec in ktime_t format

##### Description

Returns the sum of kt and nsec in ktime_t format

#### LINUX

Kernel Hackers Manual March 2006
timespec_to_ktime
9

#### timespec_to_ktime

convert a timespec to ktime_t format

##### Synopsis

       ktime_t timespec_to_ktime
       const struct timespec ts

##### Arguments

`ts`

  the timespec variable to convert

##### Description

Returns a ktime_t variable with the converted timespec value

##### Description

Returns a ktime_t variable with the converted timespec value

#### LINUX

Kernel Hackers Manual March 2006
timeval_to_ktime
9

#### timeval_to_ktime

convert a timeval to ktime_t format

##### Synopsis

       ktime_t timeval_to_ktime
       const struct timeval tv

##### Arguments

`tv`

  the timeval variable to convert

##### Description

Returns a ktime_t variable with the converted timeval value

##### Description

Returns a ktime_t variable with the converted timeval value

#### LINUX

Kernel Hackers Manual March 2006
ktime_to_timespec
9

#### ktime_to_timespec

convert a ktime_t variable to timespec format

##### Synopsis

       struct timespec ktime_to_timespec
       const ktime_t kt

##### Arguments

`kt`

  the ktime_t variable to convert

##### Description

Returns the timespec representation of the ktime value

##### Description

Returns the timespec representation of the ktime value

#### LINUX

Kernel Hackers Manual March 2006
ktime_to_timeval
9

#### ktime_to_timeval

convert a ktime_t variable to timeval format

##### Synopsis

       struct timeval ktime_to_timeval
       const ktime_t kt

##### Arguments

`kt`

  the ktime_t variable to convert

##### Description

Returns the timeval representation of the ktime value

##### Description

Returns the timeval representation of the ktime value

#### LINUX

Kernel Hackers Manual March 2006
ktime_to_clock_t
9

#### ktime_to_clock_t

convert a ktime_t variable to clock_t format

##### Synopsis

       clock_t ktime_to_clock_t
       const ktime_t kt

##### Arguments

`kt`

  the ktime_t variable to convert

##### Description

Returns a clock_t variable with the converted value

#### LINUX

Kernel Hackers Manual March 2006
ktime_to_ns
9

#### ktime_to_ns

convert a ktime_t variable to scalar nanoseconds

##### Synopsis

       u64 ktime_to_ns
       const ktime_t kt

##### Arguments

`kt`

  the ktime_t variable to convert

##### Description

Returns the scalar nanoseconds representation of kt

#### LINUX

Kernel Hackers Manual March 2006
struct hrtimer
9

#### struct hrtimer

the basic hrtimer structure

##### Synopsis

    struct hrtimer {
      struct rb_node node;
      ktime_t expires;
      enum hrtimer_state state;
      int (* function) (void *);
      void * data;
      struct hrtimer_base * base;
    };

##### Members

node

  red black tree node for time ordered insertion

expires

  the absolute expiry time in the hrtimers internal representation. The time is related to the clock on which the timer is based.

state

  state of the timer

function

  timer expiry callback function

data

  argument for the callback function

base

  pointer to the timer base (per cpu and per clock)

##### Description

The hrtimer structure must be initialized by init_hrtimer_#`CLOCKTYPE`

##### Description

The hrtimer structure must be initialized by init_hrtimer_#`CLOCKTYPE`

#### LINUX

Kernel Hackers Manual March 2006
struct hrtimer_base
9

#### struct hrtimer_base

the timer base for a specific clock

##### Synopsis

    struct hrtimer_base {
      clockid_t index;
      spinlock_t lock;
      struct rb_root active;
      struct rb_node * first;
      ktime_t resolution;
      ktime_t (* get_time) (void);
      struct hrtimer * curr_timer;
    };

##### Members

index

  clock type index for per_cpu support when moving a timer to a base on another cpu.

lock

  lock protecting the base and associated timers

active

  red black tree root node for the active timers

first

  pointer to the timer node which expires first

resolution

  the resolution of the clock, in nanoseconds

get_time

  function to retrieve the current time of the clock

curr_timer

  the timer which is executing a callback right now

##### Description

#### LINUX

Kernel Hackers Manual March 2006
ktime_get_real
9

#### ktime_get_real

get the real (wall-) time in ktime_t format

##### Synopsis

       ktime_t ktime_get_real
        void

##### Arguments

`void`

  no arguments

##### Description

returns the time in ktime_t format

#### LINUX

Kernel Hackers Manual March 2006
ktime_get_ts
9

#### ktime_get_ts

get the monotonic clock in timespec format

##### Synopsis

       void ktime_get_ts
       struct timespec * ts

##### Arguments

`ts`

  pointer to timespec variable

##### Description

The function calculates the monotonic clock from the realtime clock and the wall_to_monotonic offset and stores the result in normalized timespec format in the variable pointed to by ts.

##### Description

The function calculates the monotonic clock from the realtime clock and the wall_to_monotonic offset and stores the result in normalized timespec format in the variable pointed to by ts.

### Internal Functions

#### LINUX

Kernel Hackers Manual March 2006
reparent_to_init
9

#### reparent_to_init

Reparent the calling kernel thread to the init task.

##### Synopsis

       void reparent_to_init
        void

##### Arguments

`void`

  no arguments

##### Description

If a kernel thread is launched as a result of a system call, or if it ever exits, it should generally reparent itself to init so that it is correctly cleaned up on exit.

The various task state such as scheduling policy and priority may have been inherited from a user process, so we reset them to sane values here.

NOTE that `reparent_to_init` gives the caller full capabilities.

#### LINUX

Kernel Hackers Manual March 2006
sys_tgkill
9

#### sys_tgkill

send signal to one specific thread

##### Synopsis

       long sys_tgkill
       int tgid
       int pid
       int sig

##### Arguments

`tgid`

  the thread group ID of the thread

`pid`

  the PID of the thread

`sig`

  signal to be sent

##### Description

This syscall also checks the tgid and returns -ESRCH even if the PID exists but it's not belonging to the target process anymore. This method solves the problem of threads exiting and PIDs getting reused.

### Kernel objects manipulation

#### LINUX

Kernel Hackers Manual March 2006
kobject_init
9

#### kobject_init

initialize object.

##### Synopsis

       void kobject_init
       struct kobject * kobj

##### Arguments

`kobj`

  object in question.

#### LINUX

Kernel Hackers Manual March 2006
kobject_add
9

#### kobject_add

add an object to the hierarchy.

##### Synopsis

       int kobject_add
       struct kobject * kobj

##### Arguments

`kobj`

  object.

#### LINUX

Kernel Hackers Manual March 2006
kobject_register
9

#### kobject_register

initialize and add an object.

##### Synopsis

       int kobject_register
       struct kobject * kobj

##### Arguments

`kobj`

  object in question.

#### LINUX

Kernel Hackers Manual March 2006
kobject_set_name
9

#### kobject_set_name

Set the name of an object

##### Synopsis

       int kobject_set_name
       struct kobject * kobj
       const char * fmt
        ...

##### Arguments

`kobj`

  object.

`fmt`

  format string used to build the name

`...`

  variable arguments

##### Description

If strlen(name) >= KOBJ_NAME_LEN, then use a dynamically allocated string that `kobj`->k_name points to. Otherwise, use the static `kobj`->name array.

#### LINUX

Kernel Hackers Manual March 2006
kobject_del
9

#### kobject_del

unlink kobject from hierarchy.

##### Synopsis

       void kobject_del
       struct kobject * kobj

##### Arguments

`kobj`

  object.

#### LINUX

Kernel Hackers Manual March 2006
kobject_unregister
9

#### kobject_unregister

remove object from hierarchy and decrement refcount.

##### Synopsis

       void kobject_unregister
       struct kobject * kobj

##### Arguments

`kobj`

  object going away.

#### LINUX

Kernel Hackers Manual March 2006
kobject_get
9

#### kobject_get

increment refcount for object.

##### Synopsis

       struct kobject * kobject_get
       struct kobject * kobj

##### Arguments

`kobj`

  object.

#### LINUX

Kernel Hackers Manual March 2006
kobject_put
9

#### kobject_put

decrement refcount for object.

##### Synopsis

       void kobject_put
       struct kobject * kobj

##### Arguments

`kobj`

  object.

##### Description

Decrement the refcount, and if 0, call `kobject_cleanup`.

#### LINUX

Kernel Hackers Manual March 2006
kset_register
9

#### kset_register

initialize and add a kset.

##### Synopsis

       int kset_register
       struct kset * k

##### Arguments

`k`

  kset.

#### LINUX

Kernel Hackers Manual March 2006
kset_unregister
9

#### kset_unregister

remove a kset.

##### Synopsis

       void kset_unregister
       struct kset * k

##### Arguments

`k`

  kset.

#### LINUX

Kernel Hackers Manual March 2006
kset_find_obj
9

#### kset_find_obj

search for object in kset.

##### Synopsis

       struct kobject * kset_find_obj
       struct kset * kset
       const char * name

##### Arguments

`kset`

  kset we're looking in.

`name`

  object's name.

##### Description

Lock kset via `kset`->subsys, and iterate over `kset`->list, looking for a matching kobject. If matching object is found take a reference and return the object.

#### LINUX

Kernel Hackers Manual March 2006
subsystem_register
9

#### subsystem_register

register a subsystem.

##### Synopsis

       int subsystem_register
       struct subsystem * s

##### Arguments

`s`

  the subsystem we're registering.

##### Description

Once we register the subsystem, we want to make sure that the kset points back to this subsystem for correct usage of the rwsem.

#### LINUX

Kernel Hackers Manual March 2006
subsys_create_file
9

#### subsys_create_file

export sysfs attribute file.

##### Synopsis

       int subsys_create_file
       struct subsystem * s
       struct subsys_attribute * a

##### Arguments

`s`

  subsystem.

`a`

  subsystem attribute descriptor.

#### LINUX

Kernel Hackers Manual March 2006
subsys_remove_file
9

#### subsys_remove_file

remove sysfs attribute file.

##### Synopsis

       void subsys_remove_file
       struct subsystem * s
       struct subsys_attribute * a

##### Arguments

`s`

  subsystem.

`a`

  attribute desciptor.

### Kernel utility functions

#### LINUX

Kernel Hackers Manual March 2006
container_of
9

#### container_of

cast a member of a structure out to the containing structure

##### Synopsis

        container_of
        ptr
        type
        member

##### Arguments

`ptr`

  the pointer to the member.

`type`

  the type of the container struct this is embedded in.

`member`

  the name of the member within the struct.

#### LINUX

Kernel Hackers Manual March 2006
printk
9

#### printk

print a kernel message

##### Synopsis

       int printk
       const char * fmt
        ...

##### Arguments

`fmt`

  format string

`...`

  variable arguments

##### Description

This is printk. It can be called from any context. We want it to work.

We try to grab the console_sem. If we succeed, it's easy - we log the output and call the console drivers. If we fail to get the semaphore we place the output into the log buffer and return. The current holder of the console_sem will notice the new output in `release_console_sem` and will send it to the consoles before releasing the semaphore.

One effect of this deferred printing is that code which calls `printk` and then changes console_loglevel may break. This is because console_loglevel is inspected when the actual printing occurs.

##### See also

printf(3)

#### LINUX

Kernel Hackers Manual March 2006
acquire_console_sem
9

#### acquire_console_sem

lock the console system for exclusive use.

##### Synopsis

       void acquire_console_sem
        void

##### Arguments

`void`

  no arguments

##### Description

Acquires a semaphore which guarantees that the caller has exclusive access to the console system and the console_drivers list.

Can sleep, returns nothing.

#### LINUX

Kernel Hackers Manual March 2006
release_console_sem
9

#### release_console_sem

unlock the console system

##### Synopsis

       void release_console_sem
        void

##### Arguments

`void`

  no arguments

##### Description

Releases the semaphore which the caller holds on the console system and the console driver list.

While the semaphore was held, console output may have been buffered by `printk`. If this is the case, `release_console_sem` emits the output prior to releasing the semaphore.

If there is output waiting for klogd, we wake it up.

`release_console_sem` may be called from any context.

#### LINUX

Kernel Hackers Manual March 2006
console_conditional_schedule
9

#### console_conditional_schedule

yield the CPU if required

##### Synopsis

       void __sched console_conditional_schedule
        void

##### Arguments

`void`

  no arguments

##### Description

If the console code is currently allowed to sleep, and if this CPU should yield the CPU to another task, do so here.

Must be called within `acquire_console_sem`.

#### LINUX

Kernel Hackers Manual March 2006
panic
9

#### panic

halt the system

##### Synopsis

       NORET_TYPE void panic
       const char * fmt
        ...

##### Arguments

`fmt`

  The text string to print

`...`

  variable arguments

##### Description

Display a message, then perform cleanups.

This function never returns.

#### LINUX

Kernel Hackers Manual March 2006
notifier_chain_register
9

#### notifier_chain_register

Add notifier to a notifier chain

##### Synopsis

       int notifier_chain_register
       struct notifier_block ** list
       struct notifier_block * n

##### Arguments

`list`

  Pointer to root list pointer

`n`

  New entry in notifier chain

##### Description

Adds a notifier to a notifier chain.

Currently always returns zero.

#### LINUX

Kernel Hackers Manual March 2006
notifier_chain_unregister
9

#### notifier_chain_unregister

Remove notifier from a notifier chain

##### Synopsis

       int notifier_chain_unregister
       struct notifier_block ** nl
       struct notifier_block * n

##### Arguments

`nl`

  Pointer to root list pointer

`n`

  New entry in notifier chain

##### Description

Removes a notifier from a notifier chain.

Returns zero on success, or `-ENOENT` on failure.

#### LINUX

Kernel Hackers Manual March 2006
notifier_call_chain
9

#### notifier_call_chain

Call functions in a notifier chain

##### Synopsis

       int __kprobes notifier_call_chain
       struct notifier_block ** n
       unsigned long val
       void * v

##### Arguments

`n`

  Pointer to root pointer of notifier chain

`val`

  Value passed unmodified to notifier function

`v`

  Pointer passed unmodified to notifier function

##### Description

Calls each function in a notifier chain in turn.

If the return value of the notifier can be and'd with `NOTIFY_STOP_MASK`, then notifier_call_chain will return immediately, with the return value of the notifier function which halted execution. Otherwise, the return value is the return value of the last notifier function called.

#### LINUX

Kernel Hackers Manual March 2006
register_reboot_notifier
9

#### register_reboot_notifier

Register function to be called at reboot time

##### Synopsis

       int register_reboot_notifier
       struct notifier_block * nb

##### Arguments

`nb`

  Info about notifier function to be called

##### Description

Registers a function with the list of functions to be called at reboot time.

Currently always returns zero, as notifier_chain_register always returns zero.

#### LINUX

Kernel Hackers Manual March 2006
unregister_reboot_notifier
9

#### unregister_reboot_notifier

Unregister previously registered reboot notifier

##### Synopsis

       int unregister_reboot_notifier
       struct notifier_block * nb

##### Arguments

`nb`

  Hook to be unregistered

##### Description

Unregisters a previously registered reboot notifier function.

Returns zero on success, or `-ENOENT` on failure.

#### LINUX

Kernel Hackers Manual March 2006
emergency_restart
9

#### emergency_restart

reboot the system

##### Synopsis

       void emergency_restart
        void

##### Arguments

`void`

  no arguments

##### Description

Without shutting down any hardware or taking any locks reboot the system. This is called when we know we are in trouble so this is our best effort to reboot. This is safe to call in interrupt context.

#### LINUX

Kernel Hackers Manual March 2006
kernel_restart
9

#### kernel_restart

reboot the system

##### Synopsis

       void kernel_restart
       char * cmd

##### Arguments

`cmd`

  pointer to buffer containing command to execute for restart or `NULL`

##### Description

Shutdown everything and perform a clean reboot. This is not safe to call in interrupt context.

#### LINUX

Kernel Hackers Manual March 2006
kernel_kexec
9

#### kernel_kexec

reboot the system

##### Synopsis

       void kernel_kexec
        void

##### Arguments

`void`

  no arguments

##### Description

Move into place and start executing a preloaded standalone executable. If nothing was preloaded return an error.

#### LINUX

Kernel Hackers Manual March 2006
kernel_halt
9

#### kernel_halt

halt the system

##### Synopsis

       void kernel_halt
        void

##### Arguments

`void`

  no arguments

##### Description

Shutdown everything and perform a clean system halt.

#### LINUX

Kernel Hackers Manual March 2006
kernel_power_off
9

#### kernel_power_off

power_off the system

##### Synopsis

       void kernel_power_off
        void

##### Arguments

`void`

  no arguments

##### Description

Shutdown everything and perform a clean system power_off.

#### LINUX

Kernel Hackers Manual March 2006
call_rcu
9

#### call_rcu

Queue an RCU callback for invocation after a grace period.

##### Synopsis

       void fastcall call_rcu
       struct rcu_head * head
       void (*func)
         struct rcu_head *rcu

##### Arguments

`head`

  structure to be used for queueing the RCU updates.

`func`

  actual update function to be invoked after the grace period

##### Description

The update function will be invoked some time after a full grace period elapses, in other words after all currently executing RCU read-side critical sections have completed. RCU read-side critical sections are delimited by `rcu_read_lock` and `rcu_read_unlock`, and may be nested.

#### LINUX

Kernel Hackers Manual March 2006
call_rcu_bh
9

#### call_rcu_bh

Queue an RCU for invocation after a quicker grace period.

##### Synopsis

       void fastcall call_rcu_bh
       struct rcu_head * head
       void (*func)
         struct rcu_head *rcu

##### Arguments

`head`

  structure to be used for queueing the RCU updates.

`func`

  actual update function to be invoked after the grace period

##### Description

The update function will be invoked some time after a full grace period elapses, in other words after all currently executing RCU read-side critical sections have completed. `call_rcu_bh` assumes that the read-side critical sections end on completion of a softirq handler. This means that read-side critical sections in process context must not be interrupted by softirqs. This interface is to be used when most of the read-side critical sections are in softirq context. RCU read-side critical sections are delimited by `rcu_read_lock` and `rcu_read_unlock`, * if in interrupt context or `rcu_read_lock_bh` and `rcu_read_unlock_bh`, if in process context. These may be nested.

#### LINUX

Kernel Hackers Manual March 2006
rcu_barrier
9

#### rcu_barrier

Wait until all the in-flight RCUs are complete.

##### Synopsis

       void rcu_barrier
        void

##### Arguments

`void`

  no arguments

#### LINUX

Kernel Hackers Manual March 2006
synchronize_rcu
9

#### synchronize_rcu

wait until a grace period has elapsed.

##### Synopsis

       void synchronize_rcu
        void

##### Arguments

`void`

  no arguments

##### Description

Control will return to the caller some time after a full grace period has elapsed, in other words after all currently executing RCU read-side critical sections have completed. RCU read-side critical sections are delimited by `rcu_read_lock` and `rcu_read_unlock`, and may be nested.

If your read-side code is not protected by `rcu_read_lock`, do -not- use `synchronize_rcu`.

## Data Types

### Doubly Linked Lists

#### LINUX

Kernel Hackers Manual March 2006
list_add
9

#### list_add

add a new entry

##### Synopsis

       void list_add
       struct list_head * new
       struct list_head * head

##### Arguments

`new`

  new entry to be added

`head`

  list head to add it after

##### Description

Insert a new entry after the specified head. This is good for implementing stacks.

#### LINUX

Kernel Hackers Manual March 2006
list_add_tail
9

#### list_add_tail

add a new entry

##### Synopsis

       void list_add_tail
       struct list_head * new
       struct list_head * head

##### Arguments

`new`

  new entry to be added

`head`

  list head to add it before

##### Description

Insert a new entry before the specified head. This is useful for implementing queues.

#### LINUX

Kernel Hackers Manual March 2006
list_add_rcu
9

#### list_add_rcu

add a new entry to rcu-protected list

##### Synopsis

       void list_add_rcu
       struct list_head * new
       struct list_head * head

##### Arguments

`new`

  new entry to be added

`head`

  list head to add it after

##### Description

Insert a new entry after the specified head. This is good for implementing stacks.

The caller must take whatever precautions are necessary (such as holding appropriate locks) to avoid racing with another list-mutation primitive, such as `list_add_rcu` or `list_del_rcu`, running on this same list. However, it is perfectly legal to run concurrently with the _rcu list-traversal primitives, such as `list_for_each_entry_rcu`.

#### LINUX

Kernel Hackers Manual March 2006
list_add_tail_rcu
9

#### list_add_tail_rcu

add a new entry to rcu-protected list

##### Synopsis

       void list_add_tail_rcu
       struct list_head * new
       struct list_head * head

##### Arguments

`new`

  new entry to be added

`head`

  list head to add it before

##### Description

Insert a new entry before the specified head. This is useful for implementing queues.

The caller must take whatever precautions are necessary (such as holding appropriate locks) to avoid racing with another list-mutation primitive, such as `list_add_tail_rcu` or `list_del_rcu`, running on this same list. However, it is perfectly legal to run concurrently with the _rcu list-traversal primitives, such as `list_for_each_entry_rcu`.

#### LINUX

Kernel Hackers Manual March 2006
list_del
9

#### list_del

deletes entry from list.

##### Synopsis

       void list_del
       struct list_head * entry

##### Arguments

`entry`

  the element to delete from the list.

##### Note

list_empty on entry does not return true after this, the entry is in an undefined state.

#### LINUX

Kernel Hackers Manual March 2006
list_del_rcu
9

#### list_del_rcu

deletes entry from list without re-initialization

##### Synopsis

       void list_del_rcu
       struct list_head * entry

##### Arguments

`entry`

  the element to delete from the list.

##### Note

list_empty on entry does not return true after this, the entry is in an undefined state. It is useful for RCU based lockfree traversal.

In particular, it means that we can not poison the forward pointers that may still be used for walking the list.

The caller must take whatever precautions are necessary (such as holding appropriate locks) to avoid racing with another list-mutation primitive, such as `list_del_rcu` or `list_add_rcu`, running on this same list. However, it is perfectly legal to run concurrently with the _rcu list-traversal primitives, such as `list_for_each_entry_rcu`.

Note that the caller is not permitted to immediately free the newly deleted entry. Instead, either `synchronize_rcu` or `call_rcu` must be used to defer freeing until an RCU grace period has elapsed.

#### LINUX

Kernel Hackers Manual March 2006
list_del_init
9

#### list_del_init

deletes entry from list and reinitialize it.

##### Synopsis

       void list_del_init
       struct list_head * entry

##### Arguments

`entry`

  the element to delete from the list.

#### LINUX

Kernel Hackers Manual March 2006
list_move
9

#### list_move

delete from one list and add as another's head

##### Synopsis

       void list_move
       struct list_head * list
       struct list_head * head

##### Arguments

`list`

  the entry to move

`head`

  the head that will precede our entry

#### LINUX

Kernel Hackers Manual March 2006
list_move_tail
9

#### list_move_tail

delete from one list and add as another's tail

##### Synopsis

       void list_move_tail
       struct list_head * list
       struct list_head * head

##### Arguments

`list`

  the entry to move

`head`

  the head that will follow our entry

#### LINUX

Kernel Hackers Manual March 2006
list_empty
9

#### list_empty

tests whether a list is empty

##### Synopsis

       int list_empty
       const struct list_head * head

##### Arguments

`head`

  the list to test.

#### LINUX

Kernel Hackers Manual March 2006
list_empty_careful
9

#### list_empty_careful

tests whether a list is

##### Synopsis

       int list_empty_careful
       const struct list_head * head

##### Arguments

`head`

  the list to test.

##### Description

empty _and_ checks that no other CPU might be in the process of still modifying either member

##### NOTE

using `list_empty_careful` without synchronization can only be safe if the only activity that can happen to the list entry is `list_del_init`. Eg. it cannot be used if another CPU could re-`list_add` it.

#### LINUX

Kernel Hackers Manual March 2006
list_splice
9

#### list_splice

join two lists

##### Synopsis

       void list_splice
       struct list_head * list
       struct list_head * head

##### Arguments

`list`

  the new list to add.

`head`

  the place to add it in the first list.

#### LINUX

Kernel Hackers Manual March 2006
list_splice_init
9

#### list_splice_init

join two lists and reinitialise the emptied list.

##### Synopsis

       void list_splice_init
       struct list_head * list
       struct list_head * head

##### Arguments

`list`

  the new list to add.

`head`

  the place to add it in the first list.

##### Description

The list at `list` is reinitialised

#### LINUX

Kernel Hackers Manual March 2006
list_entry
9

#### list_entry

get the struct for this entry

##### Synopsis

        list_entry
        ptr
        type
        member

##### Arguments

`ptr`

  the &struct list_head pointer.

`type`

  the type of the struct this is embedded in.

`member`

  the name of the list_struct within the struct.

#### LINUX

Kernel Hackers Manual March 2006
list_for_each
9

#### list_for_each

iterate over a list

##### Synopsis

        list_for_each
        pos
        head

##### Arguments

`pos`

  the &struct list_head to use as a loop counter.

`head`

  the head for your list.

#### LINUX

Kernel Hackers Manual March 2006
__list_for_each
9

#### __list_for_each

iterate over a list

##### Synopsis

        __list_for_each
        pos
        head

##### Arguments

`pos`

  the &struct list_head to use as a loop counter.

`head`

  the head for your list.

##### Description

This variant differs from `list_for_each` in that it's the simplest possible list iteration code, no prefetching is done. Use this for code that knows the list to be very short (empty or 1 entry) most of the time.

#### LINUX

Kernel Hackers Manual March 2006
list_for_each_prev
9

#### list_for_each_prev

iterate over a list backwards

##### Synopsis

        list_for_each_prev
        pos
        head

##### Arguments

`pos`

  the &struct list_head to use as a loop counter.

`head`

  the head for your list.

#### LINUX

Kernel Hackers Manual March 2006
list_for_each_safe
9

#### list_for_each_safe

iterate over a list safe against removal of list entry

##### Synopsis

        list_for_each_safe
        pos
        n
        head

##### Arguments

`pos`

  the &struct list_head to use as a loop counter.

`n`

  another &struct list_head to use as temporary storage

`head`

  the head for your list.

#### LINUX

Kernel Hackers Manual March 2006
list_for_each_entry
9

#### list_for_each_entry

iterate over list of given type

##### Synopsis

        list_for_each_entry
        pos
        head
        member

##### Arguments

`pos`

  the type * to use as a loop counter.

`head`

  the head for your list.

`member`

  the name of the list_struct within the struct.

#### LINUX

Kernel Hackers Manual March 2006
list_for_each_entry_reverse
9

#### list_for_each_entry_reverse

iterate backwards over list of given type.

##### Synopsis

        list_for_each_entry_reverse
        pos
        head
        member

##### Arguments

`pos`

  the type * to use as a loop counter.

`head`

  the head for your list.

`member`

  the name of the list_struct within the struct.

#### LINUX

Kernel Hackers Manual March 2006
list_prepare_entry
9

#### list_prepare_entry

prepare a pos entry for use as a start point in

##### Synopsis

        list_prepare_entry
        pos
        head
        member

##### Arguments

`pos`

  the type * to use as a start point

`head`

  the head of the list

`member`

  the name of the list_struct within the struct.

##### Description

list_for_each_entry_continue

#### LINUX

Kernel Hackers Manual March 2006
list_for_each_entry_continue
9

#### list_for_each_entry_continue

iterate over list of given type

##### Synopsis

        list_for_each_entry_continue
        pos
        head
        member

##### Arguments

`pos`

  the type * to use as a loop counter.

`head`

  the head for your list.

`member`

  the name of the list_struct within the struct.

##### Description

continuing after existing point

#### LINUX

Kernel Hackers Manual March 2006
list_for_each_entry_safe
9

#### list_for_each_entry_safe

iterate over list of given type safe against removal of list entry

##### Synopsis

        list_for_each_entry_safe
        pos
        n
        head
        member

##### Arguments

`pos`

  the type * to use as a loop counter.

`n`

  another type * to use as temporary storage

`head`

  the head for your list.

`member`

  the name of the list_struct within the struct.

#### LINUX

Kernel Hackers Manual March 2006
list_for_each_entry_safe_continue
9

#### list_for_each_entry_safe_continue

iterate over list of given type

##### Synopsis

        list_for_each_entry_safe_continue
        pos
        n
        head
        member

##### Arguments

`pos`

  the type * to use as a loop counter.

`n`

  another type * to use as temporary storage

`head`

  the head for your list.

`member`

  the name of the list_struct within the struct.

##### Description

continuing after existing point safe against removal of list entry

#### LINUX

Kernel Hackers Manual March 2006
list_for_each_entry_safe_reverse
9

#### list_for_each_entry_safe_reverse

iterate backwards over list of given type safe against

##### Synopsis

        list_for_each_entry_safe_reverse
        pos
        n
        head
        member

##### Arguments

`pos`

  the type * to use as a loop counter.

`n`

  another type * to use as temporary storage

`head`

  the head for your list.

`member`

  the name of the list_struct within the struct.

##### Description

removal of list entry

#### LINUX

Kernel Hackers Manual March 2006
list_for_each_rcu
9

#### list_for_each_rcu

iterate over an rcu-protected list

##### Synopsis

        list_for_each_rcu
        pos
        head

##### Arguments

`pos`

  the &struct list_head to use as a loop counter.

`head`

  the head for your list.

##### Description

This list-traversal primitive may safely run concurrently with the _rcu list-mutation primitives such as `list_add_rcu` as long as the traversal is guarded by `rcu_read_lock`.

#### LINUX

Kernel Hackers Manual March 2006
list_for_each_safe_rcu
9

#### list_for_each_safe_rcu

iterate over an rcu-protected list safe

##### Synopsis

        list_for_each_safe_rcu
        pos
        n
        head

##### Arguments

`pos`

  the &struct list_head to use as a loop counter.

`n`

  another &struct list_head to use as temporary storage

`head`

  the head for your list.

##### Description

This list-traversal primitive may safely run concurrently with the _rcu list-mutation primitives such as `list_add_rcu` as long as the traversal is guarded by `rcu_read_lock`.

##### Description

This list-traversal primitive may safely run concurrently with the _rcu list-mutation primitives such as `list_add_rcu` as long as the traversal is guarded by `rcu_read_lock`.

#### LINUX

Kernel Hackers Manual March 2006
list_for_each_entry_rcu
9

#### list_for_each_entry_rcu

iterate over rcu list of given type

##### Synopsis

        list_for_each_entry_rcu
        pos
        head
        member

##### Arguments

`pos`

  the type * to use as a loop counter.

`head`

  the head for your list.

`member`

  the name of the list_struct within the struct.

##### Description

This list-traversal primitive may safely run concurrently with the _rcu list-mutation primitives such as `list_add_rcu` as long as the traversal is guarded by `rcu_read_lock`.

#### LINUX

Kernel Hackers Manual March 2006
list_for_each_continue_rcu
9

#### list_for_each_continue_rcu

iterate over an rcu-protected list

##### Synopsis

        list_for_each_continue_rcu
        pos
        head

##### Arguments

`pos`

  the &struct list_head to use as a loop counter.

`head`

  the head for your list.

##### Description

This list-traversal primitive may safely run concurrently with the _rcu list-mutation primitives such as `list_add_rcu` as long as the traversal is guarded by `rcu_read_lock`.

##### Description

This list-traversal primitive may safely run concurrently with the _rcu list-mutation primitives such as `list_add_rcu` as long as the traversal is guarded by `rcu_read_lock`.

#### LINUX

Kernel Hackers Manual March 2006
hlist_del_rcu
9

#### hlist_del_rcu

deletes entry from hash list without re-initialization

##### Synopsis

       void hlist_del_rcu
       struct hlist_node * n

##### Arguments

`n`

  the element to delete from the hash list.

##### Note

`list_unhashed` on entry does not return true after this, the entry is in an undefined state. It is useful for RCU based lockfree traversal.

In particular, it means that we can not poison the forward pointers that may still be used for walking the hash list.

The caller must take whatever precautions are necessary (such as holding appropriate locks) to avoid racing with another list-mutation primitive, such as `hlist_add_head_rcu` or `hlist_del_rcu`, running on this same list. However, it is perfectly legal to run concurrently with the _rcu list-traversal primitives, such as `hlist_for_each_entry`.

#### LINUX

Kernel Hackers Manual March 2006
hlist_add_head_rcu
9

#### hlist_add_head_rcu

adds the specified element to the specified hlist,

##### Synopsis

       void hlist_add_head_rcu
       struct hlist_node * n
       struct hlist_head * h

##### Arguments

`n`

  the element to add to the hash list.

`h`

  the list to add to.

##### Description

The caller must take whatever precautions are necessary (such as holding appropriate locks) to avoid racing with another list-mutation primitive, such as `hlist_add_head_rcu` or `hlist_del_rcu`, running on this same list. However, it is perfectly legal to run concurrently with the _rcu list-traversal primitives, such as `hlist_for_each_entry_rcu`, used to prevent memory-consistency problems on Alpha CPUs. Regardless of the type of CPU, the list-traversal primitive must be guarded by `rcu_read_lock`.

##### Description

The caller must take whatever precautions are necessary (such as holding appropriate locks) to avoid racing with another list-mutation primitive, such as `hlist_add_head_rcu` or `hlist_del_rcu`, running on this same list. However, it is perfectly legal to run concurrently with the _rcu list-traversal primitives, such as `hlist_for_each_entry_rcu`, used to prevent memory-consistency problems on Alpha CPUs. Regardless of the type of CPU, the list-traversal primitive must be guarded by `rcu_read_lock`.

#### LINUX

Kernel Hackers Manual March 2006
hlist_add_before_rcu
9

#### hlist_add_before_rcu

adds the specified element to the specified hlist

##### Synopsis

       void hlist_add_before_rcu
       struct hlist_node * n
       struct hlist_node * next

##### Arguments

`n`

  the new element to add to the hash list.

`next`

  the existing element to add the new element before.

##### Description

The caller must take whatever precautions are necessary (such as holding appropriate locks) to avoid racing with another list-mutation primitive, such as `hlist_add_head_rcu` or `hlist_del_rcu`, running on this same list. However, it is perfectly legal to run concurrently with the _rcu list-traversal primitives, such as `hlist_for_each_entry_rcu`, used to prevent memory-consistency problems on Alpha CPUs.

##### Description

The caller must take whatever precautions are necessary (such as holding appropriate locks) to avoid racing with another list-mutation primitive, such as `hlist_add_head_rcu` or `hlist_del_rcu`, running on this same list. However, it is perfectly legal to run concurrently with the _rcu list-traversal primitives, such as `hlist_for_each_entry_rcu`, used to prevent memory-consistency problems on Alpha CPUs.

#### LINUX

Kernel Hackers Manual March 2006
hlist_add_after_rcu
9

#### hlist_add_after_rcu

adds the specified element to the specified hlist

##### Synopsis

       void hlist_add_after_rcu
       struct hlist_node * prev
       struct hlist_node * n

##### Arguments

`prev`

  the existing element to add the new element after.

`n`

  the new element to add to the hash list.

##### Description

The caller must take whatever precautions are necessary (such as holding appropriate locks) to avoid racing with another list-mutation primitive, such as `hlist_add_head_rcu` or `hlist_del_rcu`, running on this same list. However, it is perfectly legal to run concurrently with the _rcu list-traversal primitives, such as `hlist_for_each_entry_rcu`, used to prevent memory-consistency problems on Alpha CPUs.

##### Description

The caller must take whatever precautions are necessary (such as holding appropriate locks) to avoid racing with another list-mutation primitive, such as `hlist_add_head_rcu` or `hlist_del_rcu`, running on this same list. However, it is perfectly legal to run concurrently with the _rcu list-traversal primitives, such as `hlist_for_each_entry_rcu`, used to prevent memory-consistency problems on Alpha CPUs.

#### LINUX

Kernel Hackers Manual March 2006
hlist_for_each_entry
9

#### hlist_for_each_entry

iterate over list of given type

##### Synopsis

        hlist_for_each_entry
        tpos
        pos
        head
        member

##### Arguments

`tpos`

  the type * to use as a loop counter.

`pos`

  the &struct hlist_node to use as a loop counter.

`head`

  the head for your list.

`member`

  the name of the hlist_node within the struct.

#### LINUX

Kernel Hackers Manual March 2006
hlist_for_each_entry_continue
9

#### hlist_for_each_entry_continue

iterate over a hlist continuing after existing point

##### Synopsis

        hlist_for_each_entry_continue
        tpos
        pos
        member

##### Arguments

`tpos`

  the type * to use as a loop counter.

`pos`

  the &struct hlist_node to use as a loop counter.

`member`

  the name of the hlist_node within the struct.

#### LINUX

Kernel Hackers Manual March 2006
hlist_for_each_entry_from
9

#### hlist_for_each_entry_from

iterate over a hlist continuing from existing point

##### Synopsis

        hlist_for_each_entry_from
        tpos
        pos
        member

##### Arguments

`tpos`

  the type * to use as a loop counter.

`pos`

  the &struct hlist_node to use as a loop counter.

`member`

  the name of the hlist_node within the struct.

#### LINUX

Kernel Hackers Manual March 2006
hlist_for_each_entry_safe
9

#### hlist_for_each_entry_safe

iterate over list of given type safe against removal of list entry

##### Synopsis

        hlist_for_each_entry_safe
        tpos
        pos
        n
        head
        member

##### Arguments

`tpos`

  the type * to use as a loop counter.

`pos`

  the &struct hlist_node to use as a loop counter.

`n`

  another &struct hlist_node to use as temporary storage

`head`

  the head for your list.

`member`

  the name of the hlist_node within the struct.

#### LINUX

Kernel Hackers Manual March 2006
hlist_for_each_entry_rcu
9

#### hlist_for_each_entry_rcu

iterate over rcu list of given type

##### Synopsis

        hlist_for_each_entry_rcu
        tpos
        pos
        head
        member

##### Arguments

`tpos`

  the type * to use as a loop counter.

`pos`

  the &struct hlist_node to use as a loop counter.

`head`

  the head for your list.

`member`

  the name of the hlist_node within the struct.

##### Description

This list-traversal primitive may safely run concurrently with the _rcu list-mutation primitives such as `hlist_add_head_rcu` as long as the traversal is guarded by `rcu_read_lock`.

## Basic C Library Functions

When writing drivers, you cannot in general use routines which are from the C Library. Some of the functions have been found generally useful and they are listed below. The behaviour of these functions may vary slightly from those defined by ANSI, and these deviations are noted in the text.

### String Conversions

#### LINUX

Kernel Hackers Manual March 2006
simple_strtoll
9

#### simple_strtoll

convert a string to a signed long long

##### Synopsis

       long long simple_strtoll
       const char * cp
       char ** endp
       unsigned int base

##### Arguments

`cp`

  The start of the string

`endp`

  A pointer to the end of the parsed string will be placed here

`base`

  The number base to use

#### LINUX

Kernel Hackers Manual March 2006
simple_strtoul
9

#### simple_strtoul

convert a string to an unsigned long

##### Synopsis

       unsigned long simple_strtoul
       const char * cp
       char ** endp
       unsigned int base

##### Arguments

`cp`

  The start of the string

`endp`

  A pointer to the end of the parsed string will be placed here

`base`

  The number base to use

#### LINUX

Kernel Hackers Manual March 2006
simple_strtol
9

#### simple_strtol

convert a string to a signed long

##### Synopsis

       long simple_strtol
       const char * cp
       char ** endp
       unsigned int base

##### Arguments

`cp`

  The start of the string

`endp`

  A pointer to the end of the parsed string will be placed here

`base`

  The number base to use

#### LINUX

Kernel Hackers Manual March 2006
simple_strtoull
9

#### simple_strtoull

convert a string to an unsigned long long

##### Synopsis

       unsigned long long simple_strtoull
       const char * cp
       char ** endp
       unsigned int base

##### Arguments

`cp`

  The start of the string

`endp`

  A pointer to the end of the parsed string will be placed here

`base`

  The number base to use

#### LINUX

Kernel Hackers Manual March 2006
vsnprintf
9

#### vsnprintf

Format a string and place it in a buffer

##### Synopsis

       int vsnprintf
       char * buf
       size_t size
       const char * fmt
       va_list args

##### Arguments

`buf`

  The buffer to place the result into

`size`

  The size of the buffer, including the trailing null space

`fmt`

  The format string to use

`args`

  Arguments for the format string

##### Description

The return value is the number of characters which would be generated for the given input, excluding the trailing '\0', as per ISO C99. If you want to have the exact number of characters written into `buf` as return value (not including the trailing '\0'), use vscnprintf. If the return is greater than or equal to `size`, the resulting string is truncated.

Call this function if you are already dealing with a va_list. You probably want snprintf instead.

#### LINUX

Kernel Hackers Manual March 2006
vscnprintf
9

#### vscnprintf

Format a string and place it in a buffer

##### Synopsis

       int vscnprintf
       char * buf
       size_t size
       const char * fmt
       va_list args

##### Arguments

`buf`

  The buffer to place the result into

`size`

  The size of the buffer, including the trailing null space

`fmt`

  The format string to use

`args`

  Arguments for the format string

##### Description

The return value is the number of characters which have been written into the `buf` not including the trailing '\0'. If `size` is <= 0 the function returns 0.

Call this function if you are already dealing with a va_list. You probably want scnprintf instead.

#### LINUX

Kernel Hackers Manual March 2006
snprintf
9

#### snprintf

Format a string and place it in a buffer

##### Synopsis

       int snprintf
       char * buf
       size_t size
       const char * fmt
        ...

##### Arguments

`buf`

  The buffer to place the result into

`size`

  The size of the buffer, including the trailing null space

`fmt`

  The format string to use @...: Arguments for the format string

`...`

  variable arguments

##### Description

The return value is the number of characters which would be generated for the given input, excluding the trailing null, as per ISO C99. If the return is greater than or equal to `size`, the resulting string is truncated.

#### LINUX

Kernel Hackers Manual March 2006
scnprintf
9

#### scnprintf

Format a string and place it in a buffer

##### Synopsis

       int scnprintf
       char * buf
       size_t size
       const char * fmt
        ...

##### Arguments

`buf`

  The buffer to place the result into

`size`

  The size of the buffer, including the trailing null space

`fmt`

  The format string to use @...: Arguments for the format string

`...`

  variable arguments

##### Description

The return value is the number of characters written into `buf` not including the trailing '\0'. If `size` is <= 0 the function returns 0. If the return is greater than or equal to `size`, the resulting string is truncated.

#### LINUX

Kernel Hackers Manual March 2006
vsprintf
9

#### vsprintf

Format a string and place it in a buffer

##### Synopsis

       int vsprintf
       char * buf
       const char * fmt
       va_list args

##### Arguments

`buf`

  The buffer to place the result into

`fmt`

  The format string to use

`args`

  Arguments for the format string

##### Description

The function returns the number of characters written into `buf`. Use vsnprintf or vscnprintf in order to avoid buffer overflows.

Call this function if you are already dealing with a va_list. You probably want sprintf instead.

#### LINUX

Kernel Hackers Manual March 2006
sprintf
9

#### sprintf

Format a string and place it in a buffer

##### Synopsis

       int sprintf
       char * buf
       const char * fmt
        ...

##### Arguments

`buf`

  The buffer to place the result into

`fmt`

  The format string to use @...: Arguments for the format string

`...`

  variable arguments

##### Description

The function returns the number of characters written into `buf`. Use snprintf or scnprintf in order to avoid buffer overflows.

#### LINUX

Kernel Hackers Manual March 2006
vsscanf
9

#### vsscanf

Unformat a buffer into a list of arguments

##### Synopsis

       int vsscanf
       const char * buf
       const char * fmt
       va_list args

##### Arguments

`buf`

  input buffer

`fmt`

  format of buffer

`args`

  arguments

#### LINUX

Kernel Hackers Manual March 2006
sscanf
9

#### sscanf

Unformat a buffer into a list of arguments

##### Synopsis

       int sscanf
       const char * buf
       const char * fmt
        ...

##### Arguments

`buf`

  input buffer

`fmt`

  formatting of buffer @...: resulting arguments

`...`

  variable arguments

### String Manipulation

#### LINUX

Kernel Hackers Manual March 2006
strnicmp
9

#### strnicmp

Case insensitive, length-limited string comparison

##### Synopsis

       int strnicmp
       const char * s1
       const char * s2
       size_t len

##### Arguments

`s1`

  One string

`s2`

  The other string

`len`

  the maximum number of characters to compare

#### LINUX

Kernel Hackers Manual March 2006
strcpy
9

#### strcpy

Copy a `NUL` terminated string

##### Synopsis

       char * strcpy
       char * dest
       const char * src

##### Arguments

`dest`

  Where to copy the string to

`src`

  Where to copy the string from

#### LINUX

Kernel Hackers Manual March 2006
strncpy
9

#### strncpy

Copy a length-limited, `NUL-terminated` string

##### Synopsis

       char * strncpy
       char * dest
       const char * src
       size_t count

##### Arguments

`dest`

  Where to copy the string to

`src`

  Where to copy the string from

`count`

  The maximum number of bytes to copy

##### Description

The result is not `NUL-terminated` if the source exceeds `count` bytes.

In the case where the length of `src` is less than that of count, the remainder of `dest` will be padded with `NUL`.

#### LINUX

Kernel Hackers Manual March 2006
strlcpy
9

#### strlcpy

Copy a `NUL` terminated string into a sized buffer

##### Synopsis

       size_t strlcpy
       char * dest
       const char * src
       size_t size

##### Arguments

`dest`

  Where to copy the string to

`src`

  Where to copy the string from

`size`

  size of destination buffer

##### BSD

the result is always a valid NUL-terminated string that fits in the buffer (unless, of course, the buffer size is zero). It does not pad out the result like `strncpy` does.

#### LINUX

Kernel Hackers Manual March 2006
strcat
9

#### strcat

Append one `NUL-terminated` string to another

##### Synopsis

       char * strcat
       char * dest
       const char * src

##### Arguments

`dest`

  The string to be appended to

`src`

  The string to append to it

#### LINUX

Kernel Hackers Manual March 2006
strncat
9

#### strncat

Append a length-limited, `NUL-terminated` string to another

##### Synopsis

       char * strncat
       char * dest
       const char * src
       size_t count

##### Arguments

`dest`

  The string to be appended to

`src`

  The string to append to it

`count`

  The maximum numbers of bytes to copy

##### Description

Note that in contrast to strncpy, strncat ensures the result is terminated.

#### LINUX

Kernel Hackers Manual March 2006
strlcat
9

#### strlcat

Append a length-limited, `NUL-terminated` string to another

##### Synopsis

       size_t strlcat
       char * dest
       const char * src
       size_t count

##### Arguments

`dest`

  The string to be appended to

`src`

  The string to append to it

`count`

  The size of the destination buffer.

#### LINUX

Kernel Hackers Manual March 2006
strcmp
9

#### strcmp

Compare two strings

##### Synopsis

       int strcmp
       const char * cs
       const char * ct

##### Arguments

`cs`

  One string

`ct`

  Another string

#### LINUX

Kernel Hackers Manual March 2006
strncmp
9

#### strncmp

Compare two length-limited strings

##### Synopsis

       int strncmp
       const char * cs
       const char * ct
       size_t count

##### Arguments

`cs`

  One string

`ct`

  Another string

`count`

  The maximum number of bytes to compare

#### LINUX

Kernel Hackers Manual March 2006
strchr
9

#### strchr

Find the first occurrence of a character in a string

##### Synopsis

       char * strchr
       const char * s
       int c

##### Arguments

`s`

  The string to be searched

`c`

  The character to search for

#### LINUX

Kernel Hackers Manual March 2006
strrchr
9

#### strrchr

Find the last occurrence of a character in a string

##### Synopsis

       char * strrchr
       const char * s
       int c

##### Arguments

`s`

  The string to be searched

`c`

  The character to search for

#### LINUX

Kernel Hackers Manual March 2006
strnchr
9

#### strnchr

Find a character in a length limited string

##### Synopsis

       char * strnchr
       const char * s
       size_t count
       int c

##### Arguments

`s`

  The string to be searched

`count`

  The number of characters to be searched

`c`

  The character to search for

#### LINUX

Kernel Hackers Manual March 2006
strlen
9

#### strlen

Find the length of a string

##### Synopsis

       size_t strlen
       const char * s

##### Arguments

`s`

  The string to be sized

#### LINUX

Kernel Hackers Manual March 2006
strnlen
9

#### strnlen

Find the length of a length-limited string

##### Synopsis

       size_t strnlen
       const char * s
       size_t count

##### Arguments

`s`

  The string to be sized

`count`

  The maximum number of bytes to search

#### LINUX

Kernel Hackers Manual March 2006
strspn
9

#### strspn

Calculate the length of the initial substring of `s` which only

##### Synopsis

       size_t strspn
       const char * s
       const char * accept

##### Arguments

`s`

  The string to be searched

`accept`

  The string to search for

##### Description

contain letters in `accept`

#### LINUX

Kernel Hackers Manual March 2006
strcspn
9

#### strcspn

Calculate the length of the initial substring of `s` which does

##### Synopsis

       size_t strcspn
       const char * s
       const char * reject

##### Arguments

`s`

  The string to be searched

`reject`

  The string to avoid

##### Description

not contain letters in `reject`

#### LINUX

Kernel Hackers Manual March 2006
strpbrk
9

#### strpbrk

Find the first occurrence of a set of characters

##### Synopsis

       char * strpbrk
       const char * cs
       const char * ct

##### Arguments

`cs`

  The string to be searched

`ct`

  The characters to search for

#### LINUX

Kernel Hackers Manual March 2006
strsep
9

#### strsep

Split a string into tokens

##### Synopsis

       char * strsep
       char ** s
       const char * ct

##### Arguments

`s`

  The string to be searched

`ct`

  The characters to search for

##### Description

`strsep` updates `s` to point after the token, ready for the next call.

It returns empty tokens, too, behaving exactly like the libc function of that name. In fact, it was stolen from glibc2 and de-fancy-fied. Same semantics, slimmer shape. ;)

#### LINUX

Kernel Hackers Manual March 2006
memset
9

#### memset

Fill a region of memory with the given value

##### Synopsis

       void * memset
       void * s
       int c
       size_t count

##### Arguments

`s`

  Pointer to the start of the area.

`c`

  The byte to fill the area with

`count`

  The size of the area.

##### Description

Do not use `memset` to access IO space, use `memset_io` instead.

#### LINUX

Kernel Hackers Manual March 2006
memcpy
9

#### memcpy

Copy one area of memory to another

##### Synopsis

       void * memcpy
       void * dest
       const void * src
       size_t count

##### Arguments

`dest`

  Where to copy to

`src`

  Where to copy from

`count`

  The size of the area.

##### Description

You should not use this function to access IO space, use `memcpy_toio` or `memcpy_fromio` instead.

#### LINUX

Kernel Hackers Manual March 2006
memmove
9

#### memmove

Copy one area of memory to another

##### Synopsis

       void * memmove
       void * dest
       const void * src
       size_t count

##### Arguments

`dest`

  Where to copy to

`src`

  Where to copy from

`count`

  The size of the area.

##### Description

Unlike `memcpy`, `memmove` copes with overlapping areas.

#### LINUX

Kernel Hackers Manual March 2006
memcmp
9

#### memcmp

Compare two areas of memory

##### Synopsis

       int memcmp
       const void * cs
       const void * ct
       size_t count

##### Arguments

`cs`

  One area of memory

`ct`

  Another area of memory

`count`

  The size of the area.

#### LINUX

Kernel Hackers Manual March 2006
memscan
9

#### memscan

Find a character in an area of memory.

##### Synopsis

       void * memscan
       void * addr
       int c
       size_t size

##### Arguments

`addr`

  The memory area

`c`

  The byte to search for

`size`

  The size of the area.

##### Description

returns the address of the first occurrence of `c`, or 1 byte past the area if `c` is not found

#### LINUX

Kernel Hackers Manual March 2006
strstr
9

#### strstr

Find the first substring in a `NUL` terminated string

##### Synopsis

       char * strstr
       const char * s1
       const char * s2

##### Arguments

`s1`

  The string to be searched

`s2`

  The string to search for

#### LINUX

Kernel Hackers Manual March 2006
memchr
9

#### memchr

Find a character in an area of memory.

##### Synopsis

       void * memchr
       const void * s
       int c
       size_t n

##### Arguments

`s`

  The memory area

`c`

  The byte to search for

`n`

  The size of the area.

##### Description

returns the address of the first occurrence of `c`, or `NULL` if `c` is not found

### Bit Operations

#### LINUX

Kernel Hackers Manual March 2006
set_bit
9

#### set_bit

Atomically set a bit in memory

##### Synopsis

       void set_bit
       int nr
       volatile unsigned long * addr

##### Arguments

`nr`

  the bit to set

`addr`

  the address to start counting from

##### Description

This function is atomic and may not be reordered. See `__set_bit` if you do not require the atomic guarantees.

##### Note

there are no guarantees that this function will not be reordered on non x86 architectures, so if you are writting portable code, make sure not to rely on its reordering guarantees.

Note that `nr` may be almost arbitrarily large; this function is not restricted to acting on a single-word quantity.

#### LINUX

Kernel Hackers Manual March 2006
__set_bit
9

#### __set_bit

Set a bit in memory

##### Synopsis

       void __set_bit
       int nr
       volatile unsigned long * addr

##### Arguments

`nr`

  the bit to set

`addr`

  the address to start counting from

##### Description

Unlike `set_bit`, this function is non-atomic and may be reordered. If it's called on the same region of memory simultaneously, the effect may be that only one operation succeeds.

#### LINUX

Kernel Hackers Manual March 2006
clear_bit
9

#### clear_bit

Clears a bit in memory

##### Synopsis

       void clear_bit
       int nr
       volatile unsigned long * addr

##### Arguments

`nr`

  Bit to clear

`addr`

  Address to start counting from

##### Description

`clear_bit` is atomic and may not be reordered. However, it does not contain a memory barrier, so if it is used for locking purposes, you should call `smp_mb__before_clear_bit` and/or `smp_mb__after_clear_bit` in order to ensure changes are visible on other processors.

#### LINUX

Kernel Hackers Manual March 2006
__change_bit
9

#### __change_bit

Toggle a bit in memory

##### Synopsis

       void __change_bit
       int nr
       volatile unsigned long * addr

##### Arguments

`nr`

  the bit to change

`addr`

  the address to start counting from

##### Description

Unlike `change_bit`, this function is non-atomic and may be reordered. If it's called on the same region of memory simultaneously, the effect may be that only one operation succeeds.

#### LINUX

Kernel Hackers Manual March 2006
change_bit
9

#### change_bit

Toggle a bit in memory

##### Synopsis

       void change_bit
       int nr
       volatile unsigned long * addr

##### Arguments

`nr`

  Bit to change

`addr`

  Address to start counting from

##### Description

`change_bit` is atomic and may not be reordered. It may be reordered on other architectures than x86. Note that `nr` may be almost arbitrarily large; this function is not restricted to acting on a single-word quantity.

#### LINUX

Kernel Hackers Manual March 2006
test_and_set_bit
9

#### test_and_set_bit

Set a bit and return its old value

##### Synopsis

       int test_and_set_bit
       int nr
       volatile unsigned long * addr

##### Arguments

`nr`

  Bit to set

`addr`

  Address to count from

##### Description

This operation is atomic and cannot be reordered. It may be reordered on other architectures than x86. It also implies a memory barrier.

#### LINUX

Kernel Hackers Manual March 2006
__test_and_set_bit
9

#### __test_and_set_bit

Set a bit and return its old value

##### Synopsis

       int __test_and_set_bit
       int nr
       volatile unsigned long * addr

##### Arguments

`nr`

  Bit to set

`addr`

  Address to count from

##### Description

This operation is non-atomic and can be reordered. If two examples of this operation race, one can appear to succeed but actually fail. You must protect multiple accesses with a lock.

#### LINUX

Kernel Hackers Manual March 2006
test_and_clear_bit
9

#### test_and_clear_bit

Clear a bit and return its old value

##### Synopsis

       int test_and_clear_bit
       int nr
       volatile unsigned long * addr

##### Arguments

`nr`

  Bit to clear

`addr`

  Address to count from

##### Description

This operation is atomic and cannot be reordered. It can be reorderdered on other architectures other than x86. It also implies a memory barrier.

#### LINUX

Kernel Hackers Manual March 2006
__test_and_clear_bit
9

#### __test_and_clear_bit

Clear a bit and return its old value

##### Synopsis

       int __test_and_clear_bit
       int nr
       volatile unsigned long * addr

##### Arguments

`nr`

  Bit to clear

`addr`

  Address to count from

##### Description

This operation is non-atomic and can be reordered. If two examples of this operation race, one can appear to succeed but actually fail. You must protect multiple accesses with a lock.

#### LINUX

Kernel Hackers Manual March 2006
test_and_change_bit
9

#### test_and_change_bit

Change a bit and return its old value

##### Synopsis

       int test_and_change_bit
       int nr
       volatile unsigned long * addr

##### Arguments

`nr`

  Bit to change

`addr`

  Address to count from

##### Description

This operation is atomic and cannot be reordered. It also implies a memory barrier.

#### LINUX

Kernel Hackers Manual March 2006
test_bit
9

#### test_bit

Determine whether a bit is set

##### Synopsis

       int test_bit
       int nr
       const volatile void * addr

##### Arguments

`nr`

  bit number to test

`addr`

  Address to start counting from

#### LINUX

Kernel Hackers Manual March 2006
find_first_zero_bit
9

#### find_first_zero_bit

find the first zero bit in a memory region

##### Synopsis

       int find_first_zero_bit
       const unsigned long * addr
       unsigned size

##### Arguments

`addr`

  The address to start the search at

`size`

  The maximum size to search

##### Description

Returns the bit-number of the first zero bit, not the number of the byte containing a bit.

#### LINUX

Kernel Hackers Manual March 2006
find_next_zero_bit
9

#### find_next_zero_bit

find the first zero bit in a memory region

##### Synopsis

       int find_next_zero_bit
       const unsigned long * addr
       int size
       int offset

##### Arguments

`addr`

  The address to base the search on

`size`

  The maximum size to search

`offset`

  The bitnumber to start searching at

#### LINUX

Kernel Hackers Manual March 2006
__ffs
9

#### __ffs

find first bit in word.

##### Synopsis

       unsigned long __ffs
       unsigned long word

##### Arguments

`word`

  The word to search

##### Description

Undefined if no bit exists, so code should check against 0 first.

#### LINUX

Kernel Hackers Manual March 2006
find_first_bit
9

#### find_first_bit

find the first set bit in a memory region

##### Synopsis

       unsigned find_first_bit
       const unsigned long * addr
       unsigned size

##### Arguments

`addr`

  The address to start the search at

`size`

  The maximum size to search

##### Description

Returns the bit-number of the first set bit, not the number of the byte containing a bit.

#### LINUX

Kernel Hackers Manual March 2006
find_next_bit
9

#### find_next_bit

find the first set bit in a memory region

##### Synopsis

       int find_next_bit
       const unsigned long * addr
       int size
       int offset

##### Arguments

`addr`

  The address to base the search on

`size`

  The maximum size to search

`offset`

  The bitnumber to start searching at

#### LINUX

Kernel Hackers Manual March 2006
ffz
9

#### ffz

find first zero in word.

##### Synopsis

       unsigned long ffz
       unsigned long word

##### Arguments

`word`

  The word to search

##### Description

Undefined if no zero exists, so code should check against ~0UL first.

#### LINUX

Kernel Hackers Manual March 2006
ffs
9

#### ffs

find first bit set

##### Synopsis

       int ffs
       int x

##### Arguments

`x`

  the word to search

##### Description

This is defined the same way as the libc and compiler builtin ffs routines, therefore differs in spirit from the above ffz (man ffs).

#### LINUX

Kernel Hackers Manual March 2006
fls
9

#### fls

find last bit set

##### Synopsis

       int fls
       int x

##### Arguments

`x`

  the word to search

##### Description

This is defined the same way as ffs.

#### LINUX

Kernel Hackers Manual March 2006
hweight32
9

#### hweight32

returns the hamming weight of a N-bit word

##### Synopsis

        hweight32
        x

##### Arguments

`x`

  the word to weigh

##### Description

The Hamming Weight of a number is the total number of bits set in it.

## Memory Management in Linux

### The Slab Cache

#### LINUX

Kernel Hackers Manual March 2006
kmem_cache_create
9

#### kmem_cache_create

Create a cache.

##### Synopsis

       struct kmem_cache * kmem_cache_create
       const char * name
       size_t size
       size_t align
       unsigned long flags
       void (*ctor)
         void*, struct kmem_cache *, unsigned long
       void (*dtor)
         void*, struct kmem_cache *, unsigned long

##### Arguments

`name`

  A string which is used in /proc/slabinfo to identify this cache.

`size`

  The size of objects to be created in this cache.

`align`

  The required alignment for the objects.

`flags`

  SLAB flags

`ctor`

  A constructor for the objects.

`dtor`

  A destructor for the objects.

##### Description

Returns a ptr to the cache on success, NULL on failure. Cannot be called within a int, but can be interrupted. The `ctor` is run when new pages are allocated by the cache and the `dtor` is run before the pages are handed back.

`name` must be valid until the cache is destroyed. This implies that the module calling this has to destroy the cache before getting unloaded.

The flags are

`SLAB_POISON` - Poison the slab with a known test pattern (a5a5a5a5) to catch references to uninitialised memory.

`SLAB_RED_ZONE` - Insert `Red' zones around the allocated memory to check for buffer overruns.

`SLAB_NO_REAP` - Don't automatically reap this cache when we're under memory pressure.

`SLAB_HWCACHE_ALIGN` - Align the objects in this cache to a hardware cacheline. This can be beneficial if you're counting cycles as closely as davem.

#### LINUX

Kernel Hackers Manual March 2006
kmem_cache_shrink
9

#### kmem_cache_shrink

Shrink a cache.

##### Synopsis

       int kmem_cache_shrink
       struct kmem_cache * cachep

##### Arguments

`cachep`

  The cache to shrink.

##### Description

Releases as many slabs as possible for a cache. To help debugging, a zero exit status indicates all slabs were released.

#### LINUX

Kernel Hackers Manual March 2006
kmem_cache_destroy
9

#### kmem_cache_destroy

delete a cache

##### Synopsis

       int kmem_cache_destroy
       struct kmem_cache * cachep

##### Arguments

`cachep`

  the cache to destroy

##### Description

Remove a struct kmem_cache object from the slab cache. Returns 0 on success.

It is expected this function will be called by a module when it is unloaded. This will remove the cache completely, and avoid a duplicate cache being allocated each time a module is loaded and unloaded, if the module doesn't have persistent in-kernel storage across loads and unloads.

The cache must be empty before calling this function.

The caller must guarantee that noone will allocate memory from the cache during the `kmem_cache_destroy`.

#### LINUX

Kernel Hackers Manual March 2006
kmem_cache_alloc
9

#### kmem_cache_alloc

Allocate an object

##### Synopsis

       void * kmem_cache_alloc
       struct kmem_cache * cachep
       gfp_t flags

##### Arguments

`cachep`

  The cache to allocate from.

`flags`

  See `kmalloc`.

##### Description

Allocate an object from this cache. The flags are only relevant if the cache has no available objects.

#### LINUX

Kernel Hackers Manual March 2006
kmem_cache_alloc_node
9

#### kmem_cache_alloc_node

Allocate an object on the specified node

##### Synopsis

       void * kmem_cache_alloc_node
       struct kmem_cache * cachep
       gfp_t flags
       int nodeid

##### Arguments

`cachep`

  The cache to allocate from.

`flags`

  See `kmalloc`.

`nodeid`

  node number of the target node.

##### Description

Identical to kmem_cache_alloc, except that this function is slow and can sleep. And it will allocate memory on the given node, which can improve the performance for cpu bound structures.

##### New and improved

it will now make sure that the object gets put on the correct node list so that there is no false sharing.

#### LINUX

Kernel Hackers Manual March 2006
__alloc_percpu
9

#### __alloc_percpu

allocate one copy of the object for every present

##### Synopsis

       void * __alloc_percpu
       size_t size

##### Arguments

`size`

  how many bytes of memory are required.

##### Description

cpu in the system, zeroing them. Objects should be dereferenced using the per_cpu_ptr macro only.

#### LINUX

Kernel Hackers Manual March 2006
kmem_cache_free
9

#### kmem_cache_free

Deallocate an object

##### Synopsis

       void kmem_cache_free
       struct kmem_cache * cachep
       void * objp

##### Arguments

`cachep`

  The cache the allocation was from.

`objp`

  The previously allocated object.

##### Description

Free an object which was previously allocated from this cache.

#### LINUX

Kernel Hackers Manual March 2006
kfree
9

#### kfree

free previously allocated memory

##### Synopsis

       void kfree
       const void * objp

##### Arguments

`objp`

  pointer returned by kmalloc.

##### Description

If `objp` is NULL, no operation is performed.

Don't free memory not originally allocated by `kmalloc` or you will run into trouble.

#### LINUX

Kernel Hackers Manual March 2006
free_percpu
9

#### free_percpu

free previously allocated percpu memory

##### Synopsis

       void free_percpu
       const void * objp

##### Arguments

`objp`

  pointer returned by alloc_percpu.

##### Description

Don't free memory not originally allocated by `alloc_percpu` The complemented objp is to check for that.

### User Space Memory Access

#### LINUX

Kernel Hackers Manual March 2006
access_ok
9

#### access_ok

Checks if a user space pointer is valid

##### Synopsis

        access_ok
        type
        addr
        size

##### Arguments

`type`

  Type of access: `VERIFY_READ` or `VERIFY_WRITE`. Note that `VERIFY_WRITE` is a superset of `VERIFY_READ` - if it is safe to write to a block, it is always safe to read from it.

`addr`

  User space pointer to start of block to check

`size`

  Size of block to check

##### Context

User context only. This function may sleep.

##### Description

Checks if a pointer to a block of memory in user space is valid.

Returns true (nonzero) if the memory block may be valid, false (zero) if it is definitely invalid.

Note that, depending on architecture, this function probably just checks that the pointer is in the user space range - after calling this function, memory access functions may still return -EFAULT.

#### LINUX

Kernel Hackers Manual March 2006
get_user
9

#### get_user

Get a simple variable from user space.

##### Synopsis

        get_user
        x
        ptr

##### Arguments

`x`

  Variable to store result.

`ptr`

  Source address, in user space.

##### Context

User context only. This function may sleep.

##### Description

This macro copies a single simple variable from user space to kernel space. It supports simple types like char and int, but not larger data types like structures or arrays.

`ptr` must have pointer-to-simple-variable type, and the result of dereferencing `ptr` must be assignable to `x` without a cast.

Returns zero on success, or -EFAULT on error. On error, the variable `x` is set to zero.

#### LINUX

Kernel Hackers Manual March 2006
put_user
9

#### put_user

Write a simple value into user space.

##### Synopsis

        put_user
        x
        ptr

##### Arguments

`x`

  Value to copy to user space.

`ptr`

  Destination address, in user space.

##### Context

User context only. This function may sleep.

##### Description

This macro copies a single simple value from kernel space to user space. It supports simple types like char and int, but not larger data types like structures or arrays.

`ptr` must have pointer-to-simple-variable type, and `x` must be assignable to the result of dereferencing `ptr`.

Returns zero on success, or -EFAULT on error.

#### LINUX

Kernel Hackers Manual March 2006
__get_user
9

#### __get_user

Get a simple variable from user space, with less checking.

##### Synopsis

        __get_user
        x
        ptr

##### Arguments

`x`

  Variable to store result.

`ptr`

  Source address, in user space.

##### Context

User context only. This function may sleep.

##### Description

This macro copies a single simple variable from user space to kernel space. It supports simple types like char and int, but not larger data types like structures or arrays.

`ptr` must have pointer-to-simple-variable type, and the result of dereferencing `ptr` must be assignable to `x` without a cast.

Caller must check the pointer with `access_ok` before calling this function.

Returns zero on success, or -EFAULT on error. On error, the variable `x` is set to zero.

#### LINUX

Kernel Hackers Manual March 2006
__put_user
9

#### __put_user

Write a simple value into user space, with less checking.

##### Synopsis

        __put_user
        x
        ptr

##### Arguments

`x`

  Value to copy to user space.

`ptr`

  Destination address, in user space.

##### Context

User context only. This function may sleep.

##### Description

This macro copies a single simple value from kernel space to user space. It supports simple types like char and int, but not larger data types like structures or arrays.

`ptr` must have pointer-to-simple-variable type, and `x` must be assignable to the result of dereferencing `ptr`.

Caller must check the pointer with `access_ok` before calling this function.

Returns zero on success, or -EFAULT on error.

#### LINUX

Kernel Hackers Manual March 2006
__copy_to_user_inatomic
9

#### __copy_to_user_inatomic

Copy a block of data into user space, with less checking.

##### Synopsis

       __always_inline unsigned long __must_check __copy_to_user_inatomic
       void __user * to
       const void * from
       unsigned long n

##### Arguments

`to`

  Destination address, in user space.

`from`

  Source address, in kernel space.

`n`

  Number of bytes to copy.

##### Context

User context only. This function may sleep.

##### Description

Copy data from kernel space to user space. Caller must check the specified block with `access_ok` before calling this function.

Returns number of bytes that could not be copied. On success, this will be zero.

#### LINUX

Kernel Hackers Manual March 2006
__copy_from_user_inatomic
9

#### __copy_from_user_inatomic

Copy a block of data from user space, with less checking.

##### Synopsis

       __always_inline unsigned long __copy_from_user_inatomic
       void * to
       const void __user * from
       unsigned long n

##### Arguments

`to`

  Destination address, in kernel space.

`from`

  Source address, in user space.

`n`

  Number of bytes to copy.

##### Context

User context only. This function may sleep.

##### Description

Copy data from user space to kernel space. Caller must check the specified block with `access_ok` before calling this function.

Returns number of bytes that could not be copied. On success, this will be zero.

If some data could not be copied, this function will pad the copied data to the requested size using zero bytes.

#### LINUX

Kernel Hackers Manual March 2006
strlen_user
9

#### strlen_user

Get the size of a string in user space.

##### Synopsis

        strlen_user
        str

##### Arguments

`str`

  The string to measure.

##### Context

User context only. This function may sleep.

##### Description

Get the size of a NUL-terminated string in user space.

Returns the size of the string INCLUDING the terminating NUL. On exception, returns 0.

If there is a limit on the length of a valid string, you may wish to consider using `strnlen_user` instead.

#### LINUX

Kernel Hackers Manual March 2006
__strncpy_from_user
9

#### __strncpy_from_user

Copy a NUL terminated string from userspace, with less checking.

##### Synopsis

       long __strncpy_from_user
       char * dst
       const char __user * src
       long count

##### Arguments

`dst`

  Destination address, in kernel space. This buffer must be at least `count` bytes long.

`src`

  Source address, in user space.

`count`

  Maximum number of bytes to copy, including the trailing NUL.

##### Description

Copies a NUL-terminated string from userspace to kernel space. Caller must check the specified block with `access_ok` before calling this function.

On success, returns the length of the string (not including the trailing NUL).

If access to userspace fails, returns -EFAULT (some data may have been copied).

If `count` is smaller than the length of the string, copies `count` bytes and returns `count`.

#### LINUX

Kernel Hackers Manual March 2006
strncpy_from_user
9

#### strncpy_from_user

Copy a NUL terminated string from userspace.

##### Synopsis

       long strncpy_from_user
       char * dst
       const char __user * src
       long count

##### Arguments

`dst`

  Destination address, in kernel space. This buffer must be at least `count` bytes long.

`src`

  Source address, in user space.

`count`

  Maximum number of bytes to copy, including the trailing NUL.

##### Description

Copies a NUL-terminated string from userspace to kernel space.

On success, returns the length of the string (not including the trailing NUL).

If access to userspace fails, returns -EFAULT (some data may have been copied).

If `count` is smaller than the length of the string, copies `count` bytes and returns `count`.

#### LINUX

Kernel Hackers Manual March 2006
clear_user
9

#### clear_user

Zero a block of memory in user space.

##### Synopsis

       unsigned long clear_user
       void __user * to
       unsigned long n

##### Arguments

`to`

  Destination address, in user space.

`n`

  Number of bytes to zero.

##### Description

Zero a block of memory in user space.

Returns number of bytes that could not be cleared. On success, this will be zero.

#### LINUX

Kernel Hackers Manual March 2006
__clear_user
9

#### __clear_user

Zero a block of memory in user space, with less checking.

##### Synopsis

       unsigned long __clear_user
       void __user * to
       unsigned long n

##### Arguments

`to`

  Destination address, in user space.

`n`

  Number of bytes to zero.

##### Description

Zero a block of memory in user space. Caller must check the specified block with `access_ok` before calling this function.

Returns number of bytes that could not be cleared. On success, this will be zero.

#### LINUX

Kernel Hackers Manual March 2006
strnlen_user
9

#### strnlen_user

Get the size of a string in user space.

##### Synopsis

       long strnlen_user
       const char __user * s
       long n

##### Arguments

`s`

  The string to measure.

`n`

  The maximum valid length

##### Description

Get the size of a NUL-terminated string in user space.

Returns the size of the string INCLUDING the terminating NUL. On exception, returns 0. If the string is too long, returns a value greater than `n`.

#### LINUX

Kernel Hackers Manual March 2006
copy_to_user
9

#### copy_to_user

Copy a block of data into user space.

##### Synopsis

       unsigned long copy_to_user
       void __user * to
       const void * from
       unsigned long n

##### Arguments

`to`

  Destination address, in user space.

`from`

  Source address, in kernel space.

`n`

  Number of bytes to copy.

##### Context

User context only. This function may sleep.

##### Description

Copy data from kernel space to user space.

Returns number of bytes that could not be copied. On success, this will be zero.

#### LINUX

Kernel Hackers Manual March 2006
copy_from_user
9

#### copy_from_user

Copy a block of data from user space.

##### Synopsis

       unsigned long copy_from_user
       void * to
       const void __user * from
       unsigned long n

##### Arguments

`to`

  Destination address, in kernel space.

`from`

  Source address, in user space.

`n`

  Number of bytes to copy.

##### Context

User context only. This function may sleep.

##### Description

Copy data from user space to kernel space.

Returns number of bytes that could not be copied. On success, this will be zero.

If some data could not be copied, this function will pad the copied data to the requested size using zero bytes.

### More Memory Management Functions

#### LINUX

Kernel Hackers Manual March 2006
page_dup_rmap
9

#### page_dup_rmap

duplicate pte mapping to a page

##### Synopsis

       void page_dup_rmap
       struct page * page

##### Arguments

`page`

  the page to add the mapping to

##### For copy_page_range only

minimal extract from page_add_rmap, avoiding unnecessary tests (already checked) so it's quicker.

#### LINUX

Kernel Hackers Manual March 2006
read_cache_pages
9

#### read_cache_pages

populate an address space with some pages, and

##### Synopsis

       int read_cache_pages
       struct address_space * mapping
       struct list_head * pages
       int (*filler)
         void *, struct page *
       void * data

##### Arguments

`mapping`

  the address_space

`pages`

  The address of a list_head which contains the target pages. These pages have their ->index populated and are otherwise uninitialised.

`filler`

  callback routine for filling a single page.

`data`

  private data for the callback routine.

##### Description

Hides the details of the LRU cache etc from the filesystems.

##### Description

Hides the details of the LRU cache etc from the filesystems.

#### LINUX

Kernel Hackers Manual March 2006
filemap_fdatawait
9

#### filemap_fdatawait

walk the list of under-writeback pages of the given

##### Synopsis

       int filemap_fdatawait
       struct address_space * mapping

##### Arguments

`mapping`

  address space structure to wait for

##### Description

address space and wait for all of them.

#### LINUX

Kernel Hackers Manual March 2006
unlock_page
9

#### unlock_page

unlock a locked page

##### Synopsis

       void fastcall unlock_page
       struct page * page

##### Arguments

`page`

  the page

##### Description

Unlocks the page and wakes up sleepers in `___wait_on_page_locked`. Also wakes sleepers in `wait_on_page_writeback` because the wakeup mechananism between PageLocked pages and PageWriteback pages is shared. But that's OK - sleepers in `wait_on_page_writeback` just go back to sleep.

The first mb is necessary to safely close the critical section opened by the `TestSetPageLocked`, the second mb is necessary to enforce ordering between the clear_bit and the read of the waitqueue (to avoid SMP races with a parallel `wait_on_page_locked`).

##### Description

Unlocks the page and wakes up sleepers in `___wait_on_page_locked`. Also wakes sleepers in `wait_on_page_writeback` because the wakeup mechananism between PageLocked pages and PageWriteback pages is shared. But that's OK - sleepers in `wait_on_page_writeback` just go back to sleep.

The first mb is necessary to safely close the critical section opened by the `TestSetPageLocked`, the second mb is necessary to enforce ordering between the clear_bit and the read of the waitqueue (to avoid SMP races with a parallel `wait_on_page_locked`).

#### LINUX

Kernel Hackers Manual March 2006
find_lock_page
9

#### find_lock_page

locate, pin and lock a pagecache page

##### Synopsis

       struct page * find_lock_page
       struct address_space * mapping
       unsigned long offset

##### Arguments

`mapping`

  the address_space to search

`offset`

  the page index

##### Description

Locates the desired pagecache page, locks it, increments its reference count and returns its address.

Returns zero if the page was not present. `find_lock_page` may sleep.

##### Description

Locates the desired pagecache page, locks it, increments its reference count and returns its address.

Returns zero if the page was not present. `find_lock_page` may sleep.

#### LINUX

Kernel Hackers Manual March 2006
find_or_create_page
9

#### find_or_create_page

locate or add a pagecache page

##### Synopsis

       struct page * find_or_create_page
       struct address_space * mapping
       unsigned long index
       gfp_t gfp_mask

##### Arguments

`mapping`

  the page's address_space

`index`

  the page's index into the mapping

`gfp_mask`

  page allocation mode

##### Description

Locates a page in the pagecache. If the page is not present, a new page is allocated using `gfp_mask` and is added to the pagecache and to the VM's LRU list. The returned page is locked and has its reference count incremented.

`find_or_create_page` may sleep, even if `gfp_flags` specifies an atomic allocation!

`find_or_create_page` returns the desired page's address, or zero on memory exhaustion.

##### Description

Locates a page in the pagecache. If the page is not present, a new page is allocated using `gfp_mask` and is added to the pagecache and to the VM's LRU list. The returned page is locked and has its reference count incremented.

`find_or_create_page` may sleep, even if `gfp_flags` specifies an atomic allocation!

`find_or_create_page` returns the desired page's address, or zero on memory exhaustion.

#### LINUX

Kernel Hackers Manual March 2006
unmap_mapping_range
9

#### unmap_mapping_range

unmap the portion of all mmaps

##### Synopsis

       void unmap_mapping_range
       struct address_space * mapping
       loff_t const holebegin
       loff_t const holelen
       int even_cows

##### Arguments

`mapping`

  the address space containing mmaps to be unmapped.

`holebegin`

  byte in first page to unmap, relative to the start of the underlying file. This will be rounded down to a PAGE_SIZE boundary. Note that this is different from `vmtruncate`, which must keep the partial page. In contrast, we must get rid of partial pages.

`holelen`

  size of prospective hole in bytes. This will be rounded up to a PAGE_SIZE boundary. A holelen of zero truncates to the end of the file.

`even_cows`

  1 when truncating a file, unmap even private COWed pages; but 0 when invalidating pagecache, don't throw away private data.

##### Description

in the specified address_space corresponding to the specified page range in the underlying file.

#### LINUX

Kernel Hackers Manual March 2006
vfree
9

#### vfree

release memory allocated by `vmalloc`

##### Synopsis

       void vfree
       void * addr

##### Arguments

`addr`

  memory base address

##### Description

Free the virtually contiguous memory area starting at `addr`, as obtained from `vmalloc`, `vmalloc_32` or `__vmalloc`. If `addr` is NULL, no operation is performed.

Must not be called in interrupt context.

##### Description

Free the virtually contiguous memory area starting at `addr`, as obtained from `vmalloc`, `vmalloc_32` or `__vmalloc`. If `addr` is NULL, no operation is performed.

Must not be called in interrupt context.

#### LINUX

Kernel Hackers Manual March 2006
vunmap
9

#### vunmap

release virtual mapping obtained by `vmap`

##### Synopsis

       void vunmap
       void * addr

##### Arguments

`addr`

  memory base address

##### Description

Free the virtually contiguous memory area starting at `addr`, which was created from the page array passed to `vmap`.

Must not be called in interrupt context.

##### Description

Free the virtually contiguous memory area starting at `addr`, which was created from the page array passed to `vmap`.

Must not be called in interrupt context.

#### LINUX

Kernel Hackers Manual March 2006
vmap
9

#### vmap

map an array of pages into virtually contiguous space

##### Synopsis

       void * vmap
       struct page ** pages
       unsigned int count
       unsigned long flags
       pgprot_t prot

##### Arguments

`pages`

  array of page pointers

`count`

  number of pages to map

`flags`

  vm_area->flags

`prot`

  page protection for the mapping

##### Description

Maps `count` pages from `pages` into contiguous kernel virtual space.

##### Description

Maps `count` pages from `pages` into contiguous kernel virtual space.

#### LINUX

Kernel Hackers Manual March 2006
__vmalloc_node
9

#### __vmalloc_node

allocate virtually contiguous memory

##### Synopsis

       void * __vmalloc_node
       unsigned long size
       gfp_t gfp_mask
       pgprot_t prot
       int node

##### Arguments

`size`

  allocation size

`gfp_mask`

  flags for the page level allocator

`prot`

  protection mask for the allocated pages

`node`

  node to use for allocation or -1

##### Description

Allocate enough pages to cover `size` from the page level allocator with `gfp_mask` flags. Map them into contiguous kernel virtual space, using a pagetable protection of `prot`.

##### Description

Allocate enough pages to cover `size` from the page level allocator with `gfp_mask` flags. Map them into contiguous kernel virtual space, using a pagetable protection of `prot`.

#### LINUX

Kernel Hackers Manual March 2006
vmalloc
9

#### vmalloc

allocate virtually contiguous memory

##### Synopsis

       void * vmalloc
       unsigned long size

##### Arguments

`size`

  allocation size

##### Description

Allocate enough pages to cover `size` from the page level allocator and map them into contiguous kernel virtual space.

For tight cotrol over page level allocator and protection flags use `__vmalloc` instead.

##### Description

Allocate enough pages to cover `size` from the page level allocator and map them into contiguous kernel virtual space.

For tight cotrol over page level allocator and protection flags use `__vmalloc` instead.

#### LINUX

Kernel Hackers Manual March 2006
vmalloc_node
9

#### vmalloc_node

allocate memory on a specific node

##### Synopsis

       void * vmalloc_node
       unsigned long size
       int node

##### Arguments

`size`

  allocation size

`node`

  numa node

##### Description

Allocate enough pages to cover `size` from the page level allocator and map them into contiguous kernel virtual space.

For tight cotrol over page level allocator and protection flags use `__vmalloc` instead.

##### Description

Allocate enough pages to cover `size` from the page level allocator and map them into contiguous kernel virtual space.

For tight cotrol over page level allocator and protection flags use `__vmalloc` instead.

#### LINUX

Kernel Hackers Manual March 2006
vmalloc_32
9

#### vmalloc_32

allocate virtually contiguous memory (32bit addressable)

##### Synopsis

       void * vmalloc_32
       unsigned long size

##### Arguments

`size`

  allocation size

##### Description

Allocate enough 32bit PA addressable pages to cover `size` from the page level allocator and map them into contiguous kernel virtual space.

##### Description

Allocate enough 32bit PA addressable pages to cover `size` from the page level allocator and map them into contiguous kernel virtual space.

#### LINUX

Kernel Hackers Manual March 2006
mempool_create
9

#### mempool_create

create a memory pool

##### Synopsis

       mempool_t * mempool_create
       int min_nr
       mempool_alloc_t * alloc_fn
       mempool_free_t * free_fn
       void * pool_data

##### Arguments

`min_nr`

  the minimum number of elements guaranteed to be allocated for this pool.

`alloc_fn`

  user-defined element-allocation function.

`free_fn`

  user-defined element-freeing function.

`pool_data`

  optional private data available to the user-defined functions.

##### Description

this function creates and allocates a guaranteed size, preallocated memory pool. The pool can be used from the mempool_alloc and mempool_free functions. This function might sleep. Both the `alloc_fn` and the `free_fn` functions might sleep - as long as the mempool_alloc function is not called from IRQ contexts.

#### LINUX

Kernel Hackers Manual March 2006
mempool_resize
9

#### mempool_resize

resize an existing memory pool

##### Synopsis

       int mempool_resize
       mempool_t * pool
       int new_min_nr
       gfp_t gfp_mask

##### Arguments

`pool`

  pointer to the memory pool which was allocated via `mempool_create`.

`new_min_nr`

  the new minimum number of elements guaranteed to be allocated for this pool.

`gfp_mask`

  the usual allocation bitmask.

##### Description

This function shrinks/grows the pool. In the case of growing, it cannot be guaranteed that the pool will be grown to the new size immediately, but new `mempool_free` calls will refill it.

Note, the caller must guarantee that no mempool_destroy is called while this function is running. `mempool_alloc` & `mempool_free` might be called (eg. from IRQ contexts) while this function executes.

#### LINUX

Kernel Hackers Manual March 2006
mempool_destroy
9

#### mempool_destroy

deallocate a memory pool

##### Synopsis

       void mempool_destroy
       mempool_t * pool

##### Arguments

`pool`

  pointer to the memory pool which was allocated via `mempool_create`.

##### Description

this function only sleeps if the `free_fn` function sleeps. The caller has to guarantee that all elements have been returned to the pool (ie: freed) prior to calling `mempool_destroy`.

#### LINUX

Kernel Hackers Manual March 2006
mempool_alloc
9

#### mempool_alloc

allocate an element from a specific memory pool

##### Synopsis

       void * mempool_alloc
       mempool_t * pool
       gfp_t gfp_mask

##### Arguments

`pool`

  pointer to the memory pool which was allocated via `mempool_create`.

`gfp_mask`

  the usual allocation bitmask.

##### Description

this function only sleeps if the alloc_fn function sleeps or returns NULL. Note that due to preallocation, this function *never* fails when called from process contexts. (it might fail if called from an IRQ context.)

#### LINUX

Kernel Hackers Manual March 2006
mempool_free
9

#### mempool_free

return an element to the pool.

##### Synopsis

       void mempool_free
       void * element
       mempool_t * pool

##### Arguments

`element`

  pool element pointer.

`pool`

  pointer to the memory pool which was allocated via `mempool_create`.

##### Description

this function only sleeps if the `free_fn` function sleeps.

#### LINUX

Kernel Hackers Manual March 2006
balance_dirty_pages_ratelimited
9

#### balance_dirty_pages_ratelimited

balance dirty memory state

##### Synopsis

       void balance_dirty_pages_ratelimited
       struct address_space * mapping

##### Arguments

`mapping`

  address_space which was dirtied

##### Description

Processes which are dirtying memory should call in here once for each page which was newly dirtied. The function will periodically check the system's dirty state and will initiate writeback if needed.

On really big machines, get_writeback_state is expensive, so try to avoid calling it too often (ratelimiting). But once we're over the dirty memory limit we decrease the ratelimiting by a lot, to prevent individual processes from overshooting the limit by (ratelimit_pages) each.

#### LINUX

Kernel Hackers Manual March 2006
write_one_page
9

#### write_one_page

write out a single page and optionally wait on I/O

##### Synopsis

       int write_one_page
       struct page * page
       int wait

##### Arguments

`page`

  the page to write

`wait`

  if true, wait on writeout

##### Description

The page must be locked by the caller and will be unlocked upon return.

`write_one_page` returns a negative error code if I/O failed.

##### Description

The page must be locked by the caller and will be unlocked upon return.

`write_one_page` returns a negative error code if I/O failed.

#### LINUX

Kernel Hackers Manual March 2006
truncate_inode_pages_range
9

#### truncate_inode_pages_range

truncate range of pages specified by start and

##### Synopsis

       void truncate_inode_pages_range
       struct address_space * mapping
       loff_t lstart
       loff_t lend

##### Arguments

`mapping`

  mapping to truncate

`lstart`

  offset from which to truncate

`lend`

  offset to which to truncate

##### Description

Truncate the page cache, removing the pages that are between specified offsets (and zeroing out partial page (if lstart is not page aligned)).

Truncate takes two passes - the first pass is nonblocking. It will not block on page locks and it will not block on writeback. The second pass will wait. This is to prevent as much IO as possible in the affected region. The first pass will remove most pages, so the search cost of the second pass is low.

When looking at page->index outside the page lock we need to be careful to copy it into a local to avoid races (it could change at any time).

We pass down the cache-hot hint to the page freeing code. Even if the mapping is large, it is probably the case that the final pages are the most recently touched, and freeing happens in ascending file offset order.

##### Description

Truncate the page cache, removing the pages that are between specified offsets (and zeroing out partial page (if lstart is not page aligned)).

Truncate takes two passes - the first pass is nonblocking. It will not block on page locks and it will not block on writeback. The second pass will wait. This is to prevent as much IO as possible in the affected region. The first pass will remove most pages, so the search cost of the second pass is low.

When looking at page->index outside the page lock we need to be careful to copy it into a local to avoid races (it could change at any time).

We pass down the cache-hot hint to the page freeing code. Even if the mapping is large, it is probably the case that the final pages are the most recently touched, and freeing happens in ascending file offset order.

#### LINUX

Kernel Hackers Manual March 2006
truncate_inode_pages
9

#### truncate_inode_pages

truncate *all* the pages from an offset

##### Synopsis

       void truncate_inode_pages
       struct address_space * mapping
       loff_t lstart

##### Arguments

`mapping`

  mapping to truncate

`lstart`

  offset from which to truncate

##### Description

Called under (and serialised by) inode->i_mutex.

#### LINUX

Kernel Hackers Manual March 2006
invalidate_inode_pages2_range
9

#### invalidate_inode_pages2_range

remove range of pages from an address_space

##### Synopsis

       int invalidate_inode_pages2_range
       struct address_space * mapping
       pgoff_t start
       pgoff_t end

##### Arguments

`mapping`

  the address_space

`start`

  the page offset 'from' which to invalidate

`end`

  the page offset 'to' which to invalidate (inclusive)

##### Description

Any pages which are found to be mapped into pagetables are unmapped prior to invalidation.

Returns -EIO if any pages could not be invalidated.

#### LINUX

Kernel Hackers Manual March 2006
invalidate_inode_pages2
9

#### invalidate_inode_pages2

remove all pages from an address_space

##### Synopsis

       int invalidate_inode_pages2
       struct address_space * mapping

##### Arguments

`mapping`

  the address_space

##### Description

Any pages which are found to be mapped into pagetables are unmapped prior to invalidation.

Returns -EIO if any pages could not be invalidated.

## Kernel IPC facilities

### IPC utilities

#### LINUX

Kernel Hackers Manual March 2006
ipc_init
9

#### ipc_init

initialise IPC subsystem

##### Synopsis

       int __init ipc_init
        void

##### Arguments

`void`

  no arguments

##### Description

The various system5 IPC resources (semaphores, messages and shared memory are initialised

#### LINUX

Kernel Hackers Manual March 2006
ipc_init_ids
9

#### ipc_init_ids

initialise IPC identifiers

##### Synopsis

       void __init ipc_init_ids
       struct ipc_ids * ids
       int size

##### Arguments

`ids`

  Identifier set

`size`

  Number of identifiers

##### Description

Given a size for the ipc identifier range (limited below IPCMNI) set up the sequence range to use then allocate and initialise the array itself.

#### LINUX

Kernel Hackers Manual March 2006
ipc_init_proc_interface
9

#### ipc_init_proc_interface

Create a proc interface for sysipc types

##### Synopsis

       void __init ipc_init_proc_interface
       const char * path
       const char * header
       struct ipc_ids * ids
       int (*show)
         struct seq_file *, void *

##### Arguments

`path`

  Path in procfs

`header`

  Banner to be printed at the beginning of the file.

`ids`

  ipc id table to iterate.

`show`

  show routine.

##### Description

using a seq_file interface.

#### LINUX

Kernel Hackers Manual March 2006
ipc_findkey
9

#### ipc_findkey

find a key in an ipc identifier set

##### Synopsis

       int ipc_findkey
       struct ipc_ids * ids
       key_t key

##### Arguments

`ids`

  Identifier set

`key`

  The key to find

##### Description

Requires ipc_ids.sem locked. Returns the identifier if found or -1 if not.

#### LINUX

Kernel Hackers Manual March 2006
ipc_addid
9

#### ipc_addid

add an IPC identifier

##### Synopsis

       int ipc_addid
       struct ipc_ids * ids
       struct kern_ipc_perm * new
       int size

##### Arguments

`ids`

  IPC identifier set

`new`

  new IPC permission set

`size`

  new size limit for the id array

##### Description

Add an entry 'new' to the IPC arrays. The permissions object is initialised and the first free entry is set up and the id assigned is returned. The list is returned in a locked state on success. On failure the list is not locked and -1 is returned.

Called with ipc_ids.sem held.

#### LINUX

Kernel Hackers Manual March 2006
ipc_rmid
9

#### ipc_rmid

remove an IPC identifier

##### Synopsis

       struct kern_ipc_perm* ipc_rmid
       struct ipc_ids * ids
       int id

##### Arguments

`ids`

  identifier set

`id`

  Identifier to remove

##### Description

The identifier must be valid, and in use. The kernel will panic if fed an invalid identifier. The entry is removed and internal variables recomputed. The object associated with the identifier is returned. ipc_ids.sem and the spinlock for this ID is hold before this function is called, and remain locked on the exit.

#### LINUX

Kernel Hackers Manual March 2006
ipc_alloc
9

#### ipc_alloc

allocate ipc space

##### Synopsis

       void* ipc_alloc
       int size

##### Arguments

`size`

  size desired

##### Description

Allocate memory from the appropriate pools and return a pointer to it. NULL is returned if the allocation fails

#### LINUX

Kernel Hackers Manual March 2006
ipc_free
9

#### ipc_free

free ipc space

##### Synopsis

       void ipc_free
       void * ptr
       int size

##### Arguments

`ptr`

  pointer returned by ipc_alloc

`size`

  size of block

##### Description

Free a block created with ipc_alloc. The caller must know the size used in the allocation call.

#### LINUX

Kernel Hackers Manual March 2006
ipc_rcu_alloc
9

#### ipc_rcu_alloc

allocate ipc and rcu space

##### Synopsis

       void* ipc_rcu_alloc
       int size

##### Arguments

`size`

  size desired

##### Description

Allocate memory for the rcu header structure + the object. Returns the pointer to the object. NULL is returned if the allocation fails.

#### LINUX

Kernel Hackers Manual March 2006
ipc_schedule_free
9

#### ipc_schedule_free

free ipc + rcu space

##### Synopsis

       void ipc_schedule_free
       struct rcu_head * head

##### Arguments

`head`

  RCU callback structure for queued work

##### Description

Since RCU callback function is called in bh, we need to defer the vfree to schedule_work

#### LINUX

Kernel Hackers Manual March 2006
ipc_immediate_free
9

#### ipc_immediate_free

free ipc + rcu space

##### Synopsis

       void ipc_immediate_free
       struct rcu_head * head

##### Arguments

`head`

  RCU callback structure that contains pointer to be freed

##### Description

Free from the RCU callback context

#### LINUX

Kernel Hackers Manual March 2006
ipcperms
9

#### ipcperms

check IPC permissions

##### Synopsis

       int ipcperms
       struct kern_ipc_perm * ipcp
       short flag

##### Arguments

`ipcp`

  IPC permission set

`flag`

  desired permission set.

##### Description

Check user, group, other permissions for access to ipc resources. return 0 if allowed

#### LINUX

Kernel Hackers Manual March 2006
kernel_to_ipc64_perm
9

#### kernel_to_ipc64_perm

convert kernel ipc permissions to user

##### Synopsis

       void kernel_to_ipc64_perm
       struct kern_ipc_perm * in
       struct ipc64_perm * out

##### Arguments

`in`

  kernel permissions

`out`

  new style IPC permissions

##### Description

Turn the kernel object 'in' into a set of permissions descriptions for returning to userspace (out).

#### LINUX

Kernel Hackers Manual March 2006
ipc64_perm_to_ipc_perm
9

#### ipc64_perm_to_ipc_perm

convert old ipc permissions to new

##### Synopsis

       void ipc64_perm_to_ipc_perm
       struct ipc64_perm * in
       struct ipc_perm * out

##### Arguments

`in`

  new style IPC permissions

`out`

  old style IPC permissions

##### Description

Turn the new style permissions object in into a compatibility object and store it into the 'out' pointer.

#### LINUX

Kernel Hackers Manual March 2006
ipc_parse_version
9

#### ipc_parse_version

IPC call version

##### Synopsis

       int ipc_parse_version
       int * cmd

##### Arguments

`cmd`

  pointer to command

##### Description

Return IPC_64 for new style IPC and IPC_OLD for old style IPC. The cmd value is turned from an encoding command and version into just the command code.

## FIFO Buffer

### kfifo interface

#### LINUX

Kernel Hackers Manual March 2006
__kfifo_reset
9

#### __kfifo_reset

removes the entire FIFO contents, no locking version

##### Synopsis

       void __kfifo_reset
       struct kfifo * fifo

##### Arguments

`fifo`

  the fifo to be emptied.

#### LINUX

Kernel Hackers Manual March 2006
kfifo_reset
9

#### kfifo_reset

removes the entire FIFO contents

##### Synopsis

       void kfifo_reset
       struct kfifo * fifo

##### Arguments

`fifo`

  the fifo to be emptied.

#### LINUX

Kernel Hackers Manual March 2006
kfifo_put
9

#### kfifo_put

puts some data into the FIFO

##### Synopsis

       unsigned int kfifo_put
       struct kfifo * fifo
       unsigned char * buffer
       unsigned int len

##### Arguments

`fifo`

  the fifo to be used.

`buffer`

  the data to be added.

`len`

  the length of the data to be added.

##### Description

This function copies at most 'len' bytes from the 'buffer' into the FIFO depending on the free space, and returns the number of bytes copied.

#### LINUX

Kernel Hackers Manual March 2006
kfifo_get
9

#### kfifo_get

gets some data from the FIFO

##### Synopsis

       unsigned int kfifo_get
       struct kfifo * fifo
       unsigned char * buffer
       unsigned int len

##### Arguments

`fifo`

  the fifo to be used.

`buffer`

  where the data must be copied.

`len`

  the size of the destination buffer.

##### Description

This function copies at most 'len' bytes from the FIFO into the 'buffer' and returns the number of copied bytes.

#### LINUX

Kernel Hackers Manual March 2006
__kfifo_len
9

#### __kfifo_len

returns the number of bytes available in the FIFO, no locking version

##### Synopsis

       unsigned int __kfifo_len
       struct kfifo * fifo

##### Arguments

`fifo`

  the fifo to be used.

#### LINUX

Kernel Hackers Manual March 2006
kfifo_len
9

#### kfifo_len

returns the number of bytes available in the FIFO

##### Synopsis

       unsigned int kfifo_len
       struct kfifo * fifo

##### Arguments

`fifo`

  the fifo to be used.

#### LINUX

Kernel Hackers Manual March 2006
kfifo_init
9

#### kfifo_init

allocates a new FIFO using a preallocated buffer

##### Synopsis

       struct kfifo * kfifo_init
       unsigned char * buffer
       unsigned int size
       gfp_t gfp_mask
       spinlock_t * lock

##### Arguments

`buffer`

  the preallocated buffer to be used.

`size`

  the size of the internal buffer, this have to be a power of 2.

`gfp_mask`

  get_free_pages mask, passed to `kmalloc`

`lock`

  the lock to be used to protect the fifo buffer

##### Description

Do NOT pass the kfifo to `kfifo_free` after use ! Simply free the struct kfifo with `kfree`.

#### LINUX

Kernel Hackers Manual March 2006
kfifo_alloc
9

#### kfifo_alloc

allocates a new FIFO and its internal buffer

##### Synopsis

       struct kfifo * kfifo_alloc
       unsigned int size
       gfp_t gfp_mask
       spinlock_t * lock

##### Arguments

`size`

  the size of the internal buffer to be allocated.

`gfp_mask`

  get_free_pages mask, passed to `kmalloc`

`lock`

  the lock to be used to protect the fifo buffer

##### Description

The size will be rounded-up to a power of 2.

#### LINUX

Kernel Hackers Manual March 2006
kfifo_free
9

#### kfifo_free

frees the FIFO

##### Synopsis

       void kfifo_free
       struct kfifo * fifo

##### Arguments

`fifo`

  the fifo to be freed.

#### LINUX

Kernel Hackers Manual March 2006
__kfifo_put
9

#### __kfifo_put

puts some data into the FIFO, no locking version

##### Synopsis

       unsigned int __kfifo_put
       struct kfifo * fifo
       unsigned char * buffer
       unsigned int len

##### Arguments

`fifo`

  the fifo to be used.

`buffer`

  the data to be added.

`len`

  the length of the data to be added.

##### Description

This function copies at most 'len' bytes from the 'buffer' into the FIFO depending on the free space, and returns the number of bytes copied.

Note that with only one concurrent reader and one concurrent writer, you don't need extra locking to use these functions.

#### LINUX

Kernel Hackers Manual March 2006
__kfifo_get
9

#### __kfifo_get

gets some data from the FIFO, no locking version

##### Synopsis

       unsigned int __kfifo_get
       struct kfifo * fifo
       unsigned char * buffer
       unsigned int len

##### Arguments

`fifo`

  the fifo to be used.

`buffer`

  where the data must be copied.

`len`

  the size of the destination buffer.

##### Description

This function copies at most 'len' bytes from the FIFO into the 'buffer' and returns the number of copied bytes.

Note that with only one concurrent reader and one concurrent writer, you don't need extra locking to use these functions.

## The proc filesystem

### sysctl interface

#### LINUX

Kernel Hackers Manual March 2006
register_sysctl_table
9

#### register_sysctl_table

register a sysctl hierarchy

##### Synopsis

       struct ctl_table_header * register_sysctl_table
       ctl_table * table
       int insert_at_head

##### Arguments

`table`

  the top-level table structure

`insert_at_head`

  whether the entry should be inserted in front or at the end

##### Description

Register a sysctl table hierarchy. `table` should be a filled in ctl_table array. An entry with a ctl_name of 0 terminates the table.

The members of the &ctl_table structure are used as follows:

ctl_name - This is the numeric sysctl value used by sysctl(2). The number must be unique within that level of sysctl

procname - the name of the sysctl file under /proc/sys. Set to `NULL` to not enter a sysctl file

data - a pointer to data for use by proc_handler

maxlen - the maximum size in bytes of the data

mode - the file permissions for the /proc/sys file, and for sysctl(2)

child - a pointer to the child sysctl table if this entry is a directory, or `NULL`.

proc_handler - the text handler routine (described below)

strategy - the strategy routine (described below)

de - for internal use by the sysctl routines

extra1, extra2 - extra pointers usable by the proc handler routines

Leaf nodes in the sysctl tree will be represented by a single file under /proc; non-leaf nodes will be represented by directories.

sysctl(2) can automatically manage read and write requests through the sysctl table. The data and maxlen fields of the ctl_table struct enable minimal validation of the values being written to be performed, and the mode field allows minimal authentication.

More sophisticated management can be enabled by the provision of a strategy routine with the table entry. This will be called before any automatic read or write of the data is performed.

The strategy routine may return

< 0 - Error occurred (error is passed to user process)

0 - OK - proceed with automatic read or write.

> 0 - OK - read or write has been done by the strategy routine, so return immediately.

There must be a proc_handler routine for any terminal nodes mirrored under /proc/sys (non-terminals are handled by a built-in directory handler). Several default handlers are available to cover common cases -

`proc_dostring`, `proc_dointvec`, `proc_dointvec_jiffies`, `proc_dointvec_userhz_jiffies`, `proc_dointvec_minmax`, `proc_doulongvec_ms_jiffies_minmax`, `proc_doulongvec_minmax`

It is the handler's job to read the input buffer from user memory and process it. The handler should return 0 on success.

This routine returns `NULL` on a failure to register, and a pointer to the table header on success.

#### LINUX

Kernel Hackers Manual March 2006
unregister_sysctl_table
9

#### unregister_sysctl_table

unregister a sysctl table hierarchy

##### Synopsis

       void unregister_sysctl_table
       struct ctl_table_header * header

##### Arguments

`header`

  the header returned from register_sysctl_table

##### Description

Unregisters the sysctl table and all children. proc entries may not actually be removed until they are no longer used by anyone.

#### LINUX

Kernel Hackers Manual March 2006
proc_dostring
9

#### proc_dostring

read a string sysctl

##### Synopsis

       int proc_dostring
       ctl_table * table
       int write
       struct file * filp
       void __user * buffer
       size_t * lenp
       loff_t * ppos

##### Arguments

`table`

  the sysctl table

`write`

  `TRUE` if this is a write to the sysctl file

`filp`

  the file structure

`buffer`

  the user buffer

`lenp`

  the size of the user buffer

`ppos`

  file position

##### Description

Reads/writes a string from/to the user buffer. If the kernel buffer provided is not large enough to hold the string, the string is truncated. The copied string is `NULL-terminated`. If the string is being read by the user process, it is copied and a newline '\n' is added. It is truncated if the buffer is not large enough.

Returns 0 on success.

#### LINUX

Kernel Hackers Manual March 2006
proc_dointvec
9

#### proc_dointvec

read a vector of integers

##### Synopsis

       int proc_dointvec
       ctl_table * table
       int write
       struct file * filp
       void __user * buffer
       size_t * lenp
       loff_t * ppos

##### Arguments

`table`

  the sysctl table

`write`

  `TRUE` if this is a write to the sysctl file

`filp`

  the file structure

`buffer`

  the user buffer

`lenp`

  the size of the user buffer

`ppos`

  file position

##### Description

Reads/writes up to table->maxlen/sizeof(unsigned int) integer values from/to the user buffer, treated as an ASCII string.

Returns 0 on success.

#### LINUX

Kernel Hackers Manual March 2006
proc_dointvec_minmax
9

#### proc_dointvec_minmax

read a vector of integers with min/max values

##### Synopsis

       int proc_dointvec_minmax
       ctl_table * table
       int write
       struct file * filp
       void __user * buffer
       size_t * lenp
       loff_t * ppos

##### Arguments

`table`

  the sysctl table

`write`

  `TRUE` if this is a write to the sysctl file

`filp`

  the file structure

`buffer`

  the user buffer

`lenp`

  the size of the user buffer

`ppos`

  file position

##### Description

Reads/writes up to table->maxlen/sizeof(unsigned int) integer values from/to the user buffer, treated as an ASCII string.

This routine will ensure the values are within the range specified by table->extra1 (min) and table->extra2 (max).

Returns 0 on success.

#### LINUX

Kernel Hackers Manual March 2006
proc_doulongvec_minmax
9

#### proc_doulongvec_minmax

read a vector of long integers with min/max values

##### Synopsis

       int proc_doulongvec_minmax
       ctl_table * table
       int write
       struct file * filp
       void __user * buffer
       size_t * lenp
       loff_t * ppos

##### Arguments

`table`

  the sysctl table

`write`

  `TRUE` if this is a write to the sysctl file

`filp`

  the file structure

`buffer`

  the user buffer

`lenp`

  the size of the user buffer

`ppos`

  file position

##### Description

Reads/writes up to table->maxlen/sizeof(unsigned long) unsigned long values from/to the user buffer, treated as an ASCII string.

This routine will ensure the values are within the range specified by table->extra1 (min) and table->extra2 (max).

Returns 0 on success.

#### LINUX

Kernel Hackers Manual March 2006
proc_doulongvec_ms_jiffies_minmax
9

#### proc_doulongvec_ms_jiffies_minmax

read a vector of millisecond values with min/max values

##### Synopsis

       int proc_doulongvec_ms_jiffies_minmax
       ctl_table * table
       int write
       struct file * filp
       void __user * buffer
       size_t * lenp
       loff_t * ppos

##### Arguments

`table`

  the sysctl table

`write`

  `TRUE` if this is a write to the sysctl file

`filp`

  the file structure

`buffer`

  the user buffer

`lenp`

  the size of the user buffer

`ppos`

  file position

##### Description

Reads/writes up to table->maxlen/sizeof(unsigned long) unsigned long values from/to the user buffer, treated as an ASCII string. The values are treated as milliseconds, and converted to jiffies when they are stored.

This routine will ensure the values are within the range specified by table->extra1 (min) and table->extra2 (max).

Returns 0 on success.

#### LINUX

Kernel Hackers Manual March 2006
proc_dointvec_jiffies
9

#### proc_dointvec_jiffies

read a vector of integers as seconds

##### Synopsis

       int proc_dointvec_jiffies
       ctl_table * table
       int write
       struct file * filp
       void __user * buffer
       size_t * lenp
       loff_t * ppos

##### Arguments

`table`

  the sysctl table

`write`

  `TRUE` if this is a write to the sysctl file

`filp`

  the file structure

`buffer`

  the user buffer

`lenp`

  the size of the user buffer

`ppos`

  file position

##### Description

Reads/writes up to table->maxlen/sizeof(unsigned int) integer values from/to the user buffer, treated as an ASCII string. The values read are assumed to be in seconds, and are converted into jiffies.

Returns 0 on success.

#### LINUX

Kernel Hackers Manual March 2006
proc_dointvec_userhz_jiffies
9

#### proc_dointvec_userhz_jiffies

read a vector of integers as 1/USER_HZ seconds

##### Synopsis

       int proc_dointvec_userhz_jiffies
       ctl_table * table
       int write
       struct file * filp
       void __user * buffer
       size_t * lenp
       loff_t * ppos

##### Arguments

`table`

  the sysctl table

`write`

  `TRUE` if this is a write to the sysctl file

`filp`

  the file structure

`buffer`

  the user buffer

`lenp`

  the size of the user buffer

`ppos`

  pointer to the file position

##### Description

Reads/writes up to table->maxlen/sizeof(unsigned int) integer values from/to the user buffer, treated as an ASCII string. The values read are assumed to be in 1/USER_HZ seconds, and are converted into jiffies.

Returns 0 on success.

#### LINUX

Kernel Hackers Manual March 2006
proc_dointvec_ms_jiffies
9

#### proc_dointvec_ms_jiffies

read a vector of integers as 1 milliseconds

##### Synopsis

       int proc_dointvec_ms_jiffies
       ctl_table * table
       int write
       struct file * filp
       void __user * buffer
       size_t * lenp
       loff_t * ppos

##### Arguments

`table`

  the sysctl table

`write`

  `TRUE` if this is a write to the sysctl file

`filp`

  the file structure

`buffer`

  the user buffer

`lenp`

  the size of the user buffer

`ppos`

  the current position in the file

##### Description

Reads/writes up to table->maxlen/sizeof(unsigned int) integer values from/to the user buffer, treated as an ASCII string. The values read are assumed to be in 1/1000 seconds, and are converted into jiffies.

Returns 0 on success.

### proc filesystem interface

#### LINUX

Kernel Hackers Manual March 2006
proc_pid_unhash
9

#### proc_pid_unhash

Unhash /proc/`pid` entry from the dcache.

##### Synopsis

       struct dentry * proc_pid_unhash
       struct task_struct * p

##### Arguments

`p`

  task that should be flushed.

##### Description

Drops the /proc/`pid` dcache entry from the hash chains.

Dropping /proc/`pid` entries and detach_pid must be synchroneous, otherwise e.g. /proc/`pid`/exe might point to the wrong executable, if the pid value is immediately reused. This is enforced by - caller must acquire spin_lock(p->proc_lock) - must be called before `detach_pid` - proc_pid_lookup acquires proc_lock, and checks that the target is not dead by looking at the attach count of PIDTYPE_PID.

#### LINUX

Kernel Hackers Manual March 2006
proc_pid_flush
9

#### proc_pid_flush

recover memory used by stale /proc/`pid`/x entries

##### Synopsis

       void proc_pid_flush
       struct dentry * proc_dentry

##### Arguments

`proc_dentry`

  directoy to prune.

##### Description

Shrink the /proc directory that was used by the just killed thread.

## The debugfs filesystem

### debugfs interface

#### LINUX

Kernel Hackers Manual March 2006
debugfs_create_file
9

#### debugfs_create_file

create a file in the debugfs filesystem

##### Synopsis

       struct dentry * debugfs_create_file
       const char * name
       mode_t mode
       struct dentry * parent
       void * data
       struct file_operations * fops

##### Arguments

`name`

  a pointer to a string containing the name of the file to create.

`mode`

  the permission that the file should have

`parent`

  a pointer to the parent dentry for this file. This should be a directory dentry if set. If this paramater is NULL, then the file will be created in the root of the debugfs filesystem.

`data`

  a pointer to something that the caller will want to get to later on. The inode.u.generic_ip pointer will point to this value on the `open` call.

`fops`

  a pointer to a struct file_operations that should be used for this file.

##### Description

This is the basic create a file function for debugfs. It allows for a wide range of flexibility in createing a file, or a directory (if you want to create a directory, the `debugfs_create_dir` function is recommended to be used instead.)

This function will return a pointer to a dentry if it succeeds. This pointer must be passed to the `debugfs_remove` function when the file is to be removed (no automatic cleanup happens if your module is unloaded, you are responsible here.) If an error occurs, NULL will be returned.

If debugfs is not enabled in the kernel, the value -ENODEV will be returned. It is not wise to check for this value, but rather, check for NULL or !NULL instead as to eliminate the need for #ifdef in the calling code.

##### Description

This is the basic create a file function for debugfs. It allows for a wide range of flexibility in createing a file, or a directory (if you want to create a directory, the `debugfs_create_dir` function is recommended to be used instead.)

This function will return a pointer to a dentry if it succeeds. This pointer must be passed to the `debugfs_remove` function when the file is to be removed (no automatic cleanup happens if your module is unloaded, you are responsible here.) If an error occurs, NULL will be returned.

If debugfs is not enabled in the kernel, the value -ENODEV will be returned. It is not wise to check for this value, but rather, check for NULL or !NULL instead as to eliminate the need for #ifdef in the calling code.

#### LINUX

Kernel Hackers Manual March 2006
debugfs_create_dir
9

#### debugfs_create_dir

create a directory in the debugfs filesystem

##### Synopsis

       struct dentry * debugfs_create_dir
       const char * name
       struct dentry * parent

##### Arguments

`name`

  a pointer to a string containing the name of the directory to create.

`parent`

  a pointer to the parent dentry for this file. This should be a directory dentry if set. If this paramater is NULL, then the directory will be created in the root of the debugfs filesystem.

##### Description

This function creates a directory in debugfs with the given name.

This function will return a pointer to a dentry if it succeeds. This pointer must be passed to the `debugfs_remove` function when the file is to be removed (no automatic cleanup happens if your module is unloaded, you are responsible here.) If an error occurs, NULL will be returned.

If debugfs is not enabled in the kernel, the value -ENODEV will be returned. It is not wise to check for this value, but rather, check for NULL or !NULL instead as to eliminate the need for #ifdef in the calling code.

##### Description

This function creates a directory in debugfs with the given name.

This function will return a pointer to a dentry if it succeeds. This pointer must be passed to the `debugfs_remove` function when the file is to be removed (no automatic cleanup happens if your module is unloaded, you are responsible here.) If an error occurs, NULL will be returned.

If debugfs is not enabled in the kernel, the value -ENODEV will be returned. It is not wise to check for this value, but rather, check for NULL or !NULL instead as to eliminate the need for #ifdef in the calling code.

#### LINUX

Kernel Hackers Manual March 2006
debugfs_remove
9

#### debugfs_remove

removes a file or directory from the debugfs filesystem

##### Synopsis

       void debugfs_remove
       struct dentry * dentry

##### Arguments

`dentry`

  a pointer to a the dentry of the file or directory to be removed.

##### Description

This function removes a file or directory in debugfs that was previously created with a call to another debugfs function (like `debufs_create_file` or variants thereof.)

This function is required to be called in order for the file to be removed, no automatic cleanup of files will happen when a module is removed, you are responsible here.

##### Description

This function removes a file or directory in debugfs that was previously created with a call to another debugfs function (like `debufs_create_file` or variants thereof.)

This function is required to be called in order for the file to be removed, no automatic cleanup of files will happen when a module is removed, you are responsible here.

#### LINUX

Kernel Hackers Manual March 2006
debugfs_create_u8
9

#### debugfs_create_u8

create a file in the debugfs filesystem that is used to read and write an unsigned 8 bit value.

##### Synopsis

       struct dentry * debugfs_create_u8
       const char * name
       mode_t mode
       struct dentry * parent
       u8 * value

##### Arguments

`name`

  a pointer to a string containing the name of the file to create.

`mode`

  the permission that the file should have

`parent`

  a pointer to the parent dentry for this file. This should be a directory dentry if set. If this paramater is NULL, then the file will be created in the root of the debugfs filesystem.

`value`

  a pointer to the variable that the file should read to and write from.

##### Description

This function creates a file in debugfs with the given name that contains the value of the variable `value`. If the `mode` variable is so set, it can be read from, and written to.

This function will return a pointer to a dentry if it succeeds. This pointer must be passed to the `debugfs_remove` function when the file is to be removed (no automatic cleanup happens if your module is unloaded, you are responsible here.) If an error occurs, NULL will be returned.

If debugfs is not enabled in the kernel, the value -ENODEV will be returned. It is not wise to check for this value, but rather, check for NULL or !NULL instead as to eliminate the need for #ifdef in the calling code.

##### Description

This function creates a file in debugfs with the given name that contains the value of the variable `value`. If the `mode` variable is so set, it can be read from, and written to.

This function will return a pointer to a dentry if it succeeds. This pointer must be passed to the `debugfs_remove` function when the file is to be removed (no automatic cleanup happens if your module is unloaded, you are responsible here.) If an error occurs, NULL will be returned.

If debugfs is not enabled in the kernel, the value -ENODEV will be returned. It is not wise to check for this value, but rather, check for NULL or !NULL instead as to eliminate the need for #ifdef in the calling code.

#### LINUX

Kernel Hackers Manual March 2006
debugfs_create_u16
9

#### debugfs_create_u16

create a file in the debugfs filesystem that is used to read and write an unsigned 16 bit value.

##### Synopsis

       struct dentry * debugfs_create_u16
       const char * name
       mode_t mode
       struct dentry * parent
       u16 * value

##### Arguments

`name`

  a pointer to a string containing the name of the file to create.

`mode`

  the permission that the file should have

`parent`

  a pointer to the parent dentry for this file. This should be a directory dentry if set. If this paramater is NULL, then the file will be created in the root of the debugfs filesystem.

`value`

  a pointer to the variable that the file should read to and write from.

##### Description

This function creates a file in debugfs with the given name that contains the value of the variable `value`. If the `mode` variable is so set, it can be read from, and written to.

This function will return a pointer to a dentry if it succeeds. This pointer must be passed to the `debugfs_remove` function when the file is to be removed (no automatic cleanup happens if your module is unloaded, you are responsible here.) If an error occurs, NULL will be returned.

If debugfs is not enabled in the kernel, the value -ENODEV will be returned. It is not wise to check for this value, but rather, check for NULL or !NULL instead as to eliminate the need for #ifdef in the calling code.

##### Description

This function creates a file in debugfs with the given name that contains the value of the variable `value`. If the `mode` variable is so set, it can be read from, and written to.

This function will return a pointer to a dentry if it succeeds. This pointer must be passed to the `debugfs_remove` function when the file is to be removed (no automatic cleanup happens if your module is unloaded, you are responsible here.) If an error occurs, NULL will be returned.

If debugfs is not enabled in the kernel, the value -ENODEV will be returned. It is not wise to check for this value, but rather, check for NULL or !NULL instead as to eliminate the need for #ifdef in the calling code.

#### LINUX

Kernel Hackers Manual March 2006
debugfs_create_u32
9

#### debugfs_create_u32

create a file in the debugfs filesystem that is used to read and write an unsigned 32 bit value.

##### Synopsis

       struct dentry * debugfs_create_u32
       const char * name
       mode_t mode
       struct dentry * parent
       u32 * value

##### Arguments

`name`

  a pointer to a string containing the name of the file to create.

`mode`

  the permission that the file should have

`parent`

  a pointer to the parent dentry for this file. This should be a directory dentry if set. If this paramater is NULL, then the file will be created in the root of the debugfs filesystem.

`value`

  a pointer to the variable that the file should read to and write from.

##### Description

This function creates a file in debugfs with the given name that contains the value of the variable `value`. If the `mode` variable is so set, it can be read from, and written to.

This function will return a pointer to a dentry if it succeeds. This pointer must be passed to the `debugfs_remove` function when the file is to be removed (no automatic cleanup happens if your module is unloaded, you are responsible here.) If an error occurs, NULL will be returned.

If debugfs is not enabled in the kernel, the value -ENODEV will be returned. It is not wise to check for this value, but rather, check for NULL or !NULL instead as to eliminate the need for #ifdef in the calling code.

##### Description

This function creates a file in debugfs with the given name that contains the value of the variable `value`. If the `mode` variable is so set, it can be read from, and written to.

This function will return a pointer to a dentry if it succeeds. This pointer must be passed to the `debugfs_remove` function when the file is to be removed (no automatic cleanup happens if your module is unloaded, you are responsible here.) If an error occurs, NULL will be returned.

If debugfs is not enabled in the kernel, the value -ENODEV will be returned. It is not wise to check for this value, but rather, check for NULL or !NULL instead as to eliminate the need for #ifdef in the calling code.

#### LINUX

Kernel Hackers Manual March 2006
debugfs_create_bool
9

#### debugfs_create_bool

create a file in the debugfs filesystem that is used to read and write a boolean value.

##### Synopsis

       struct dentry * debugfs_create_bool
       const char * name
       mode_t mode
       struct dentry * parent
       u32 * value

##### Arguments

`name`

  a pointer to a string containing the name of the file to create.

`mode`

  the permission that the file should have

`parent`

  a pointer to the parent dentry for this file. This should be a directory dentry if set. If this paramater is NULL, then the file will be created in the root of the debugfs filesystem.

`value`

  a pointer to the variable that the file should read to and write from.

##### Description

This function creates a file in debugfs with the given name that contains the value of the variable `value`. If the `mode` variable is so set, it can be read from, and written to.

This function will return a pointer to a dentry if it succeeds. This pointer must be passed to the `debugfs_remove` function when the file is to be removed (no automatic cleanup happens if your module is unloaded, you are responsible here.) If an error occurs, NULL will be returned.

If debugfs is not enabled in the kernel, the value -ENODEV will be returned. It is not wise to check for this value, but rather, check for NULL or !NULL instead as to eliminate the need for #ifdef in the calling code.

##### Description

This function creates a file in debugfs with the given name that contains the value of the variable `value`. If the `mode` variable is so set, it can be read from, and written to.

This function will return a pointer to a dentry if it succeeds. This pointer must be passed to the `debugfs_remove` function when the file is to be removed (no automatic cleanup happens if your module is unloaded, you are responsible here.) If an error occurs, NULL will be returned.

If debugfs is not enabled in the kernel, the value -ENODEV will be returned. It is not wise to check for this value, but rather, check for NULL or !NULL instead as to eliminate the need for #ifdef in the calling code.

## The Linux VFS

### The Filesystem types

#### LINUX

Kernel Hackers Manual March 2006
enum positive_aop_returns
9

#### enum positive_aop_returns

aop return codes with specific semantics

##### Synopsis

    enum positive_aop_returns {
      AOP_WRITEPAGE_ACTIVATE,
      AOP_TRUNCATED_PAGE
    };

##### Constants

AOP_WRITEPAGE_ACTIVATE

  Informs the caller that page writeback has completed, that the page is still locked, and should be considered active. The VM uses this hint to return the page to the active list -- it won't be a candidate for writeback again in the near future. Other callers must be careful to unlock the page if they get this return. Returned by `writepage`;

AOP_TRUNCATED_PAGE

  The AOP method that was handed a locked page has unlocked it and the page might have been truncated. The caller should back up to acquiring a new page and trying again. The aop will be taking reasonable precautions not to livelock. If the caller held a page reference, it should drop it before retrying. Returned by `readpage`, `prepare_write`, and `commit_write`.

##### Description

address_space_operation functions return these large constants to indicate special semantics to the caller. These are much larger than the bytes in a page to allow for functions that return the number of bytes operated on in a given page.

##### Description

address_space_operation functions return these large constants to indicate special semantics to the caller. These are much larger than the bytes in a page to allow for functions that return the number of bytes operated on in a given page.

#### LINUX

Kernel Hackers Manual March 2006
struct export_operations
9

#### struct export_operations

for nfsd to communicate with file systems

##### Synopsis

    struct export_operations {
      struct dentry *(* decode_fh) (struct super_block *sb, __u32 *fh, int fh_len, int fh_type,int (*acceptable);
      int (* encode_fh) (struct dentry *de, __u32 *fh, int *max_len,int connectable);
      int (* get_name) (struct dentry *parent, char *name,struct dentry *child);
      struct dentry * (* get_parent) (struct dentry *child);
      struct dentry * (* get_dentry) (struct super_block *sb, void *inump);
      struct dentry * (* find_exported_dentry) (struct super_block *sb, void *obj, void *parent,int (*acceptable);
    };

##### Members

decode_fh

  decode a file handle fragment and return a &struct dentry

encode_fh

  encode a file handle fragment from a dentry

get_name

  find the name for a given inode in a given directory

get_parent

  find the parent of a given directory

get_dentry

  find a dentry for the inode given a file handle sub-fragment

find_exported_dentry

  set by the exporting module to a standard helper function.

##### Description

The export_operations structure provides a means for nfsd to communicate with a particular exported file system - particularly enabling nfsd and the filesystem to co-operate when dealing with file handles.

export_operations contains two basic operation for dealing with file handles, `decode_fh` and `encode_fh`, and allows for some other operations to be defined which standard helper routines use to get specific information from the filesystem.

nfsd encodes information use to determine which filesystem a filehandle applies to in the initial part of the file handle. The remainder, termed a file handle fragment, is controlled completely by the filesystem. The standard helper routines assume that this fragment will contain one or two sub-fragments, one which identifies the file, and one which may be used to identify the (a) directory containing the file.

In some situations, nfsd needs to get a dentry which is connected into a specific part of the file tree. To allow for this, it passes the function `acceptable` together with a `context` which can be used to see if the dentry is acceptable. As there can be multiple dentrys for a given file, the filesystem should check each one for acceptability before looking for the next. As soon as an acceptable one is found, it should be returned.

##### decode_fh

`decode_fh` is given a &struct super_block (`sb`), a file handle fragment (`fh`, `fh_len`) and an acceptability testing function (`acceptable`, `context`). It should return a &struct dentry which refers to the same file that the file handle fragment refers to, and which passes the acceptability test. If it cannot, it should return a `NULL` pointer if the file was found but no acceptable &dentries were available, or a `ERR_PTR` error code indicating why it couldn't be found (e.g. `ENOENT` or `ENOMEM`).

##### encode_fh

`encode_fh` should store in the file handle fragment `fh` (using at most `max_len` bytes) information that can be used by `decode_fh` to recover the file refered to by the &struct dentry `de`. If the `connectable` flag is set, the `encode_fh` should store sufficient information so that a good attempt can be made to find not only the file but also it's place in the filesystem. This typically means storing a reference to de->d_parent in the filehandle fragment. `encode_fh` should return the number of bytes stored or a negative error code such as `-ENOSPC`

##### get_name

`get_name` should find a name for the given `child` in the given `parent` directory. The name should be stored in the `name` (with the understanding that it is already pointing to a a `NAME_MAX`+1 sized buffer. `get_name` should return `0` on success, a negative error code or error. `get_name` will be called without `parent`->i_mutex held.

##### get_parent

`get_parent` should find the parent directory for the given `child` which is also a directory. In the event that it cannot be found, or storage space cannot be allocated, a `ERR_PTR` should be returned.

##### get_dentry

Given a &super_block (`sb`) and a pointer to a file-system specific inode identifier, possibly an inode number, (`inump`) `get_dentry` should find the identified inode and return a dentry for that inode. Any suitable dentry can be returned including, if necessary, a new dentry created with d_alloc_root. The caller can then find any other extant dentrys by following the d_alias links. If a new dentry was created using d_alloc_root, DCACHE_NFSD_DISCONNECTED should be set, and the dentry should be `d_rehash`ed.

If the inode cannot be found, either a `NULL` pointer or an `ERR_PTR` code can be returned. The `inump` will be whatever was passed to `nfsd_find_fh_dentry` in either the `obj` or `parent` parameters.

##### Locking rules

get_parent is called with child->d_inode->i_mutex down get_name is not (which is possibly inconsistent)

### The Directory Cache

#### LINUX

Kernel Hackers Manual March 2006
d_invalidate
9

#### d_invalidate

invalidate a dentry

##### Synopsis

       int d_invalidate
       struct dentry * dentry

##### Arguments

`dentry`

  dentry to invalidate

##### Description

Try to invalidate the dentry if it turns out to be possible. If there are other dentries that can be reached through this one we can't delete it and we return -EBUSY. On success we return 0.

no dcache lock.

#### LINUX

Kernel Hackers Manual March 2006
shrink_dcache_sb
9

#### shrink_dcache_sb

shrink dcache for a superblock

##### Synopsis

       void shrink_dcache_sb
       struct super_block * sb

##### Arguments

`sb`

  superblock

##### Description

Shrink the dcache for the specified super block. This is used to free the dcache before unmounting a file system

#### LINUX

Kernel Hackers Manual March 2006
have_submounts
9

#### have_submounts

check for mounts over a dentry

##### Synopsis

       int have_submounts
       struct dentry * parent

##### Arguments

`parent`

  dentry to check.

##### Description

Return true if the parent or its subdirectories contain a mount point

#### LINUX

Kernel Hackers Manual March 2006
shrink_dcache_parent
9

#### shrink_dcache_parent

prune dcache

##### Synopsis

       void shrink_dcache_parent
       struct dentry * parent

##### Arguments

`parent`

  parent of entries to prune

##### Description

Prune the dcache to remove unused children of the parent dentry.

#### LINUX

Kernel Hackers Manual March 2006
d_alloc
9

#### d_alloc

allocate a dcache entry

##### Synopsis

       struct dentry * d_alloc
       struct dentry * parent
       const struct qstr * name

##### Arguments

`parent`

  parent of entry to allocate

`name`

  qstr of the name

##### Description

Allocates a dentry. It returns `NULL` if there is insufficient memory available. On a success the dentry is returned. The name passed in is copied and the copy passed in may be reused after this call.

#### LINUX

Kernel Hackers Manual March 2006
d_instantiate
9

#### d_instantiate

fill in inode information for a dentry

##### Synopsis

       void d_instantiate
       struct dentry * entry
       struct inode * inode

##### Arguments

`entry`

  dentry to complete

`inode`

  inode to attach to this dentry

##### Description

Fill in inode information in the entry.

This turns negative dentries into productive full members of society.

NOTE! This assumes that the inode count has been incremented (or otherwise set) by the caller to indicate that it is now in use by the dcache.

#### LINUX

Kernel Hackers Manual March 2006
d_instantiate_unique
9

#### d_instantiate_unique

instantiate a non-aliased dentry

##### Synopsis

       struct dentry * d_instantiate_unique
       struct dentry * entry
       struct inode * inode

##### Arguments

`entry`

  dentry to instantiate

`inode`

  inode to attach to this dentry

##### Description

Fill in inode information in the entry. On success, it returns NULL. If an unhashed alias of entry already exists, then we return the aliased dentry instead and drop one reference to inode.

Note that in order to avoid conflicts with `rename` etc, the caller had better be holding the parent directory semaphore.

This also assumes that the inode count has been incremented (or otherwise set) by the caller to indicate that it is now in use by the dcache.

#### LINUX

Kernel Hackers Manual March 2006
d_alloc_root
9

#### d_alloc_root

allocate root dentry

##### Synopsis

       struct dentry * d_alloc_root
       struct inode * root_inode

##### Arguments

`root_inode`

  inode to allocate the root for

##### Description

Allocate a root (/) dentry for the inode given. The inode is instantiated and returned. `NULL` is returned if there is insufficient memory or the inode passed is `NULL`.

#### LINUX

Kernel Hackers Manual March 2006
d_alloc_anon
9

#### d_alloc_anon

allocate an anonymous dentry

##### Synopsis

       struct dentry * d_alloc_anon
       struct inode * inode

##### Arguments

`inode`

  inode to allocate the dentry for

##### Description

This is similar to d_alloc_root. It is used by filesystems when creating a dentry for a given inode, often in the process of mapping a filehandle to a dentry. The returned dentry may be anonymous, or may have a full name (if the inode was already in the cache). The file system may need to make further efforts to connect this dentry into the dcache properly.

When called on a directory inode, we must ensure that the inode only ever has one dentry. If a dentry is found, that is returned instead of allocating a new one.

On successful return, the reference to the inode has been transferred to the dentry. If `NULL` is returned (indicating kmalloc failure), the reference on the inode has not been released.

#### LINUX

Kernel Hackers Manual March 2006
d_splice_alias
9

#### d_splice_alias

splice a disconnected dentry into the tree if one exists

##### Synopsis

       struct dentry * d_splice_alias
       struct inode * inode
       struct dentry * dentry

##### Arguments

`inode`

  the inode which may have a disconnected dentry

`dentry`

  a negative dentry which we want to point to the inode.

##### Description

If inode is a directory and has a 'disconnected' dentry (i.e. IS_ROOT and DCACHE_DISCONNECTED), then d_move that in place of the given dentry and return it, else simply d_add the inode to the dentry and return NULL.

This is needed in the lookup routine of any filesystem that is exportable (via knfsd) so that we can build dcache paths to directories effectively.

If a dentry was found and moved, then it is returned. Otherwise NULL is returned. This matches the expected return value of ->lookup.

#### LINUX

Kernel Hackers Manual March 2006
d_lookup
9

#### d_lookup

search for a dentry

##### Synopsis

       struct dentry * d_lookup
       struct dentry * parent
       struct qstr * name

##### Arguments

`parent`

  parent dentry

`name`

  qstr of name we wish to find

##### Description

Searches the children of the parent dentry for the name in question. If the dentry is found its reference count is incremented and the dentry is returned. The caller must use d_put to free the entry when it has finished using it. `NULL` is returned on failure.

__d_lookup is dcache_lock free. The hash list is protected using RCU. Memory barriers are used while updating and doing lockless traversal. To avoid races with d_move while rename is happening, d_lock is used.

Overflows in `memcmp`, while d_move, are avoided by keeping the length and name pointer in one structure pointed by d_qstr.

`rcu_read_lock` and `rcu_read_unlock` are used to disable preemption while lookup is going on.

dentry_unused list is not updated even if lookup finds the required dentry in there. It is updated in places such as prune_dcache, shrink_dcache_sb, select_parent and __dget_locked. This laziness saves lookup from dcache_lock acquisition.

`d_lookup` is protected against the concurrent renames in some unrelated directory using the seqlockt_t rename_lock.

#### LINUX

Kernel Hackers Manual March 2006
d_validate
9

#### d_validate

verify dentry provided from insecure source

##### Synopsis

       int d_validate
       struct dentry * dentry
       struct dentry * dparent

##### Arguments

`dentry`

  The dentry alleged to be valid child of `dparent`

`dparent`

  The parent dentry (known to be valid)

##### Description

An insecure source has sent us a dentry, here we verify it and `dget` it. This is used by ncpfs in its readdir implementation. Zero is returned in the dentry is invalid.

#### LINUX

Kernel Hackers Manual March 2006
d_delete
9

#### d_delete

delete a dentry

##### Synopsis

       void d_delete
       struct dentry * dentry

##### Arguments

`dentry`

  The dentry to delete

##### Description

Turn the dentry into a negative dentry if possible, otherwise remove it from the hash queues so it can be deleted later

#### LINUX

Kernel Hackers Manual March 2006
d_rehash
9

#### d_rehash

add an entry back to the hash

##### Synopsis

       void d_rehash
       struct dentry * entry

##### Arguments

`entry`

  dentry to add to the hash

##### Description

Adds a dentry to the hash according to its name.

#### LINUX

Kernel Hackers Manual March 2006
d_move
9

#### d_move

move a dentry

##### Synopsis

       void d_move
       struct dentry * dentry
       struct dentry * target

##### Arguments

`dentry`

  entry to move

`target`

  new dentry

##### Description

Update the dcache to reflect the move of a file name. Negative dcache entries should not be moved in this way.

#### LINUX

Kernel Hackers Manual March 2006
find_inode_number
9

#### find_inode_number

check for dentry with name

##### Synopsis

       ino_t find_inode_number
       struct dentry * dir
       struct qstr * name

##### Arguments

`dir`

  directory to check

`name`

  Name to find.

##### Description

Check whether a dentry already exists for the given name, and return the inode number if it has an inode. Otherwise 0 is returned.

This routine is used to post-process directory listings for filesystems using synthetic inode numbers, and is necessary to keep `getcwd` working.

#### LINUX

Kernel Hackers Manual March 2006
__d_drop
9

#### __d_drop

drop a dentry

##### Synopsis

       void __d_drop
       struct dentry * dentry

##### Arguments

`dentry`

  dentry to drop

##### Description

`d_drop` unhashes the entry from the parent dentry hashes, so that it won't be found through a VFS lookup any more. Note that this is different from deleting the dentry - d_delete will try to mark the dentry negative if possible, giving a successful _negative_ lookup, while d_drop will just make the cache lookup fail.

`d_drop` is used mainly for stuff that wants to invalidate a dentry for some reason (NFS timeouts or autofs deletes).

__d_drop requires dentry->d_lock.

#### LINUX

Kernel Hackers Manual March 2006
d_add
9

#### d_add

add dentry to hash queues

##### Synopsis

       void d_add
       struct dentry * entry
       struct inode * inode

##### Arguments

`entry`

  dentry to add

`inode`

  The inode to attach to this dentry

##### Description

This adds the entry to the hash queues and initializes `inode`. The entry was actually filled in earlier during `d_alloc`.

#### LINUX

Kernel Hackers Manual March 2006
d_add_unique
9

#### d_add_unique

add dentry to hash queues without aliasing

##### Synopsis

       struct dentry * d_add_unique
       struct dentry * entry
       struct inode * inode

##### Arguments

`entry`

  dentry to add

`inode`

  The inode to attach to this dentry

##### Description

This adds the entry to the hash queues and initializes `inode`. The entry was actually filled in earlier during `d_alloc`.

#### LINUX

Kernel Hackers Manual March 2006
dget
9

#### dget

get a reference to a dentry

##### Synopsis

       struct dentry * dget
       struct dentry * dentry

##### Arguments

`dentry`

  dentry to get a reference to

##### Description

Given a dentry or `NULL` pointer increment the reference count if appropriate and return the dentry. A dentry will not be destroyed when it has references. `dget` should never be called for dentries with zero reference counter. For these cases (preferably none, functions in dcache.c are sufficient for normal needs and they take necessary precautions) you should hold dcache_lock and call `dget_locked` instead of `dget`.

#### LINUX

Kernel Hackers Manual March 2006
d_unhashed
9

#### d_unhashed

is dentry hashed

##### Synopsis

       int d_unhashed
       struct dentry * dentry

##### Arguments

`dentry`

  entry to check

##### Description

Returns true if the dentry passed is not currently hashed.

### Inode Handling

#### LINUX

Kernel Hackers Manual March 2006
clear_inode
9

#### clear_inode

clear an inode

##### Synopsis

       void clear_inode
       struct inode * inode

##### Arguments

`inode`

  inode to clear

##### Description

This is called by the filesystem to tell us that the inode is no longer useful. We just terminate it with extreme prejudice.

#### LINUX

Kernel Hackers Manual March 2006
invalidate_inodes
9

#### invalidate_inodes

discard the inodes on a device

##### Synopsis

       int invalidate_inodes
       struct super_block * sb

##### Arguments

`sb`

  superblock

##### Description

Discard all of the inodes for a given superblock. If the discard fails because there are busy inodes then a non zero value is returned. If the discard is successful all the inodes have been discarded.

#### LINUX

Kernel Hackers Manual March 2006
new_inode
9

#### new_inode

obtain an inode

##### Synopsis

       struct inode * new_inode
       struct super_block * sb

##### Arguments

`sb`

  superblock

##### Description

Allocates a new inode for given superblock.

#### LINUX

Kernel Hackers Manual March 2006
iunique
9

#### iunique

get a unique inode number

##### Synopsis

       ino_t iunique
       struct super_block * sb
       ino_t max_reserved

##### Arguments

`sb`

  superblock

`max_reserved`

  highest reserved inode number

##### Description

Obtain an inode number that is unique on the system for a given superblock. This is used by file systems that have no natural permanent inode numbering system. An inode number is returned that is higher than the reserved limit but unique.

##### BUGS

With a large number of inodes live on the file system this function currently becomes quite slow.

#### LINUX

Kernel Hackers Manual March 2006
ilookup5_nowait
9

#### ilookup5_nowait

search for an inode in the inode cache

##### Synopsis

       struct inode * ilookup5_nowait
       struct super_block * sb
       unsigned long hashval
       int (*test)
         struct inode *, void *
       void * data

##### Arguments

`sb`

  super block of file system to search

`hashval`

  hash value (usually inode number) to search for

`test`

  callback used for comparisons between inodes

`data`

  opaque data pointer to pass to `test`

##### Description

`ilookup5` uses `ifind` to search for the inode specified by `hashval` and `data` in the inode cache. This is a generalized version of `ilookup` for file systems where the inode number is not sufficient for unique identification of an inode.

If the inode is in the cache, the inode is returned with an incremented reference count. Note, the inode lock is not waited upon so you have to be very careful what you do with the returned inode. You probably should be using `ilookup5` instead.

Otherwise NULL is returned.

Note, `test` is called with the inode_lock held, so can't sleep.

#### LINUX

Kernel Hackers Manual March 2006
ilookup5
9

#### ilookup5

search for an inode in the inode cache

##### Synopsis

       struct inode * ilookup5
       struct super_block * sb
       unsigned long hashval
       int (*test)
         struct inode *, void *
       void * data

##### Arguments

`sb`

  super block of file system to search

`hashval`

  hash value (usually inode number) to search for

`test`

  callback used for comparisons between inodes

`data`

  opaque data pointer to pass to `test`

##### Description

`ilookup5` uses `ifind` to search for the inode specified by `hashval` and `data` in the inode cache. This is a generalized version of `ilookup` for file systems where the inode number is not sufficient for unique identification of an inode.

If the inode is in the cache, the inode lock is waited upon and the inode is returned with an incremented reference count.

Otherwise NULL is returned.

Note, `test` is called with the inode_lock held, so can't sleep.

#### LINUX

Kernel Hackers Manual March 2006
ilookup
9

#### ilookup

search for an inode in the inode cache

##### Synopsis

       struct inode * ilookup
       struct super_block * sb
       unsigned long ino

##### Arguments

`sb`

  super block of file system to search

`ino`

  inode number to search for

##### Description

`ilookup` uses `ifind_fast` to search for the inode `ino` in the inode cache. This is for file systems where the inode number is sufficient for unique identification of an inode.

If the inode is in the cache, the inode is returned with an incremented reference count.

Otherwise NULL is returned.

#### LINUX

Kernel Hackers Manual March 2006
iget5_locked
9

#### iget5_locked

obtain an inode from a mounted file system

##### Synopsis

       struct inode * iget5_locked
       struct super_block * sb
       unsigned long hashval
       int (*test)
         struct inode *, void *
       int (*set)
         struct inode *, void *
       void * data

##### Arguments

`sb`

  super block of file system

`hashval`

  hash value (usually inode number) to get

`test`

  callback used for comparisons between inodes

`set`

  callback used to initialize a new struct inode

`data`

  opaque data pointer to pass to `test` and `set`

##### Description

This is `iget` without the `read_inode` portion of `get_new_inode`.

`iget5_locked` uses `ifind` to search for the inode specified by `hashval` and `data` in the inode cache and if present it is returned with an increased reference count. This is a generalized version of `iget_locked` for file systems where the inode number is not sufficient for unique identification of an inode.

If the inode is not in cache, `get_new_inode` is called to allocate a new inode and this is returned locked, hashed, and with the I_NEW flag set. The file system gets to fill it in before unlocking it via `unlock_new_inode`.

Note both `test` and `set` are called with the inode_lock held, so can't sleep.

#### LINUX

Kernel Hackers Manual March 2006
iget_locked
9

#### iget_locked

obtain an inode from a mounted file system

##### Synopsis

       struct inode * iget_locked
       struct super_block * sb
       unsigned long ino

##### Arguments

`sb`

  super block of file system

`ino`

  inode number to get

##### Description

This is `iget` without the `read_inode` portion of `get_new_inode_fast`.

`iget_locked` uses `ifind_fast` to search for the inode specified by `ino` in the inode cache and if present it is returned with an increased reference count. This is for file systems where the inode number is sufficient for unique identification of an inode.

If the inode is not in cache, `get_new_inode_fast` is called to allocate a new inode and this is returned locked, hashed, and with the I_NEW flag set. The file system gets to fill it in before unlocking it via `unlock_new_inode`.

#### LINUX

Kernel Hackers Manual March 2006
__insert_inode_hash
9

#### __insert_inode_hash

hash an inode

##### Synopsis

       void __insert_inode_hash
       struct inode * inode
       unsigned long hashval

##### Arguments

`inode`

  unhashed inode

`hashval`

  unsigned long value used to locate this object in the inode_hashtable.

##### Description

Add an inode to the inode hash for this superblock.

#### LINUX

Kernel Hackers Manual March 2006
remove_inode_hash
9

#### remove_inode_hash

remove an inode from the hash

##### Synopsis

       void remove_inode_hash
       struct inode * inode

##### Arguments

`inode`

  inode to unhash

##### Description

Remove an inode from the superblock.

#### LINUX

Kernel Hackers Manual March 2006
iput
9

#### iput

put an inode

##### Synopsis

       void iput
       struct inode * inode

##### Arguments

`inode`

  inode to put

##### Description

Puts an inode, dropping its usage count. If the inode use count hits zero, the inode is then freed and may also be destroyed.

Consequently, `iput` can sleep.

#### LINUX

Kernel Hackers Manual March 2006
bmap
9

#### bmap

find a block number in a file

##### Synopsis

       sector_t bmap
       struct inode * inode
       sector_t block

##### Arguments

`inode`

  inode of file

`block`

  block to find

##### Description

Returns the block number on the device holding the inode that is the disk block number for the block of the file requested. That is, asked for block 4 of inode 1 the function will return the disk block relative to the disk start that holds that block of the file.

#### LINUX

Kernel Hackers Manual March 2006
touch_atime
9

#### touch_atime

update the access time

##### Synopsis

       void touch_atime
       struct vfsmount * mnt
       struct dentry * dentry

##### Arguments

`mnt`

  mount the inode is accessed on

`dentry`

  dentry accessed

##### Description

Update the accessed time on an inode and mark it for writeback. This function automatically handles read only file systems and media, as well as the noatime flag and inode specific noatime markers.

#### LINUX

Kernel Hackers Manual March 2006
file_update_time
9

#### file_update_time

update mtime and ctime time

##### Synopsis

       void file_update_time
       struct file * file

##### Arguments

`file`

  file accessed

##### Description

Update the mtime and ctime members of an inode and mark the inode for writeback. Note that this function is meant exclusively for usage in the file write path of filesystems, and filesystems may choose to explicitly ignore update via this function with the S_NOCTIME inode flag, e.g. for network filesystem where these timestamps are handled by the server.

#### LINUX

Kernel Hackers Manual March 2006
make_bad_inode
9

#### make_bad_inode

mark an inode bad due to an I/O error

##### Synopsis

       void make_bad_inode
       struct inode * inode

##### Arguments

`inode`

  Inode to mark bad

##### Description

When an inode cannot be read due to a media or remote network failure this function makes the inode bad and causes I/O operations on it to fail from this point on.

#### LINUX

Kernel Hackers Manual March 2006
is_bad_inode
9

#### is_bad_inode

is an inode errored

##### Synopsis

       int is_bad_inode
       struct inode * inode

##### Arguments

`inode`

  inode to test

##### Description

Returns true if the inode in question has been marked as bad.

### Registration and Superblocks

#### LINUX

Kernel Hackers Manual March 2006
deactivate_super
9

#### deactivate_super

drop an active reference to superblock

##### Synopsis

       void deactivate_super
       struct super_block * s

##### Arguments

`s`

  superblock to deactivate

##### Description

Drops an active reference to superblock, acquiring a temprory one if there is no active references left. In that case we lock superblock, tell fs driver to shut it down and drop the temporary reference we had just acquired.

#### LINUX

Kernel Hackers Manual March 2006
generic_shutdown_super
9

#### generic_shutdown_super

common helper for ->`kill_sb`

##### Synopsis

       void generic_shutdown_super
       struct super_block * sb

##### Arguments

`sb`

  superblock to kill

##### Description

`generic_shutdown_super` does all fs-independent work on superblock shutdown. Typical ->`kill_sb` should pick all fs-specific objects that need destruction out of superblock, call `generic_shutdown_super` and release aforementioned objects. Note: dentries and inodes _are_ taken care of and do not need specific handling.

#### LINUX

Kernel Hackers Manual March 2006
sget
9

#### sget

find or create a superblock

##### Synopsis

       struct super_block * sget
       struct file_system_type * type
       int (*test)
         struct super_block *,void *
       int (*set)
         struct super_block *,void *
       void * data

##### Arguments

`type`

  filesystem type superblock should belong to

`test`

  comparison callback

`set`

  setup callback

`data`

  argument to each of them

#### LINUX

Kernel Hackers Manual March 2006
get_super
9

#### get_super

get the superblock of a device

##### Synopsis

       struct super_block * get_super
       struct block_device * bdev

##### Arguments

`bdev`

  device to get the superblock for

##### Description

Scans the superblock list and finds the superblock of the file system mounted on the device given. `NULL` is returned if no match is found.

### File Locks

#### LINUX

Kernel Hackers Manual March 2006
posix_lock_file
9

#### posix_lock_file

Apply a POSIX-style lock to a file

##### Synopsis

       int posix_lock_file
       struct file * filp
       struct file_lock * fl

##### Arguments

`filp`

  The file to apply the lock to

`fl`

  The lock to be applied

##### Description

Add a POSIX style lock to a file. We merge adjacent & overlapping locks whenever possible. POSIX locks are sorted by owner task, then by starting address

#### LINUX

Kernel Hackers Manual March 2006
posix_lock_file_wait
9

#### posix_lock_file_wait

Apply a POSIX-style lock to a file

##### Synopsis

       int posix_lock_file_wait
       struct file * filp
       struct file_lock * fl

##### Arguments

`filp`

  The file to apply the lock to

`fl`

  The lock to be applied

##### Description

Add a POSIX style lock to a file. We merge adjacent & overlapping locks whenever possible. POSIX locks are sorted by owner task, then by starting address

#### LINUX

Kernel Hackers Manual March 2006
locks_mandatory_area
9

#### locks_mandatory_area

Check for a conflicting lock

##### Synopsis

       int locks_mandatory_area
       int read_write
       struct inode * inode
       struct file * filp
       loff_t offset
       size_t count

##### Arguments

`read_write`

  `FLOCK_VERIFY_WRITE` for exclusive access, `FLOCK_VERIFY_READ` for shared

`inode`

  the file to check

`filp`

  how the file was opened (if it was)

`offset`

  start of area to check

`count`

  length of area to check

##### Description

Searches the inode's list of locks to find any POSIX locks which conflict. This function is called from `rw_verify_area` and `locks_verify_truncate`.

#### LINUX

Kernel Hackers Manual March 2006
__break_lease
9

#### __break_lease

revoke all outstanding leases on file

##### Synopsis

       int __break_lease
       struct inode * inode
       unsigned int mode

##### Arguments

`inode`

  the inode of the file to return

`mode`

  the open mode (read or write)

##### Description

break_lease (inlined for speed) has checked there already is a lease on this file. Leases are broken on a call to `open` or `truncate`. This function can sleep unless you specified `O_NONBLOCK` to your `open`.

#### LINUX

Kernel Hackers Manual March 2006
lease_get_mtime
9

#### lease_get_mtime

##### Synopsis

       void lease_get_mtime
       struct inode * inode
       struct timespec * time

##### Arguments

`inode`

  the inode

`time`

  pointer to a timespec which will contain the last modified time

##### Description

This is to force NFS clients to flush their caches for files with exclusive leases. The justification is that if someone has an exclusive lease, then they could be modifiying it.

#### LINUX

Kernel Hackers Manual March 2006
flock_lock_file_wait
9

#### flock_lock_file_wait

Apply a FLOCK-style lock to a file

##### Synopsis

       int flock_lock_file_wait
       struct file * filp
       struct file_lock * fl

##### Arguments

`filp`

  The file to apply the lock to

`fl`

  The lock to be applied

##### Description

Add a FLOCK style lock to a file.

#### LINUX

Kernel Hackers Manual March 2006
posix_block_lock
9

#### posix_block_lock

blocks waiting for a file lock

##### Synopsis

       void posix_block_lock
       struct file_lock * blocker
       struct file_lock * waiter

##### Arguments

`blocker`

  the lock which is blocking

`waiter`

  the lock which conflicts and has to wait

##### Description

lockd needs to block waiting for locks.

#### LINUX

Kernel Hackers Manual March 2006
posix_unblock_lock
9

#### posix_unblock_lock

stop waiting for a file lock

##### Synopsis

       int posix_unblock_lock
       struct file * filp
       struct file_lock * waiter

##### Arguments

`filp`

  how the file was opened

`waiter`

  the lock which was waiting

##### Description

lockd needs to block waiting for locks.

#### LINUX

Kernel Hackers Manual March 2006
lock_may_read
9

#### lock_may_read

checks that the region is free of locks

##### Synopsis

       int lock_may_read
       struct inode * inode
       loff_t start
       unsigned long len

##### Arguments

`inode`

  the inode that is being read

`start`

  the first byte to read

`len`

  the number of bytes to read

##### Description

Emulates Windows locking requirements. Whole-file mandatory locks (share modes) can prohibit a read and byte-range POSIX locks can prohibit a read if they overlap.

N.B. this function is only ever called from knfsd and ownership of locks is never checked.

#### LINUX

Kernel Hackers Manual March 2006
lock_may_write
9

#### lock_may_write

checks that the region is free of locks

##### Synopsis

       int lock_may_write
       struct inode * inode
       loff_t start
       unsigned long len

##### Arguments

`inode`

  the inode that is being written

`start`

  the first byte to write

`len`

  the number of bytes to write

##### Description

Emulates Windows locking requirements. Whole-file mandatory locks (share modes) can prohibit a write and byte-range POSIX locks can prohibit a write if they overlap.

N.B. this function is only ever called from knfsd and ownership of locks is never checked.

#### LINUX

Kernel Hackers Manual March 2006
locks_mandatory_locked
9

#### locks_mandatory_locked

Check for an active lock

##### Synopsis

       int locks_mandatory_locked
       struct inode * inode

##### Arguments

`inode`

  the file to check

##### Description

Searches the inode's list of locks to find any POSIX locks which conflict. This function is called from `locks_verify_locked` only.

#### LINUX

Kernel Hackers Manual March 2006
fcntl_getlease
9

#### fcntl_getlease

Enquire what lease is currently active

##### Synopsis

       int fcntl_getlease
       struct file * filp

##### Arguments

`filp`

  the file

##### Description

The value returned by this function will be one of (if no lease break is pending):

`F_RDLCK` to indicate a shared lease is held.

`F_WRLCK` to indicate an exclusive lease is held.

`F_UNLCK` to indicate no lease is held.

(if a lease break is pending):

`F_RDLCK` to indicate an exclusive lease needs to be changed to a shared lease (or removed).

`F_UNLCK` to indicate the lease needs to be removed.

##### XXX

sfr & willy disagree over whether F_INPROGRESS should be returned to userspace.

#### LINUX

Kernel Hackers Manual March 2006
__setlease
9

#### __setlease

sets a lease on an open file

##### Synopsis

       int __setlease
       struct file * filp
       long arg
       struct file_lock ** flp

##### Arguments

`filp`

  file pointer

`arg`

  type of lease to obtain

`flp`

  input - file_lock to use, output - file_lock inserted

##### Description

The (input) flp->fl_lmops->fl_break function is required by `break_lease`.

Called with kernel lock held.

#### LINUX

Kernel Hackers Manual March 2006
fcntl_setlease
9

#### fcntl_setlease

sets a lease on an open file

##### Synopsis

       int fcntl_setlease
       unsigned int fd
       struct file * filp
       long arg

##### Arguments

`fd`

  open file descriptor

`filp`

  file pointer

`arg`

  type of lease to obtain

##### Description

Call this fcntl to establish a lease on the file. Note that you also need to call `F_SETSIG` to receive a signal when the lease is broken.

#### LINUX

Kernel Hackers Manual March 2006
sys_flock
9

#### sys_flock

flock
system call.

##### Synopsis

       long sys_flock
       unsigned int fd
       unsigned int cmd

##### Arguments

`fd`

  the file descriptor to lock.

`cmd`

  the type of lock to apply.

##### Description

Apply a `FL_FLOCK` style lock to an open file descriptor. The `cmd` can be one of

`LOCK_SH` -- a shared lock.

`LOCK_EX` -- an exclusive lock.

`LOCK_UN` -- remove an existing lock.

`LOCK_MAND` -- a `mandatory' flock. This exists to emulate Windows Share Modes.

`LOCK_MAND` can be combined with `LOCK_READ` or `LOCK_WRITE` to allow other processes read and write access respectively.

#### LINUX

Kernel Hackers Manual March 2006
get_locks_status
9

#### get_locks_status

reports lock usage in /proc/locks

##### Synopsis

       int get_locks_status
       char * buffer
       char ** start
       off_t offset
       int length

##### Arguments

`buffer`

  address in userspace to write into

`start`

  ?

`offset`

  how far we are through the buffer

`length`

  how much to read

### Other Functions

#### LINUX

Kernel Hackers Manual March 2006
mpage_readpages
9

#### mpage_readpages

populate an address space with some pages, and

##### Synopsis

       int mpage_readpages
       struct address_space * mapping
       struct list_head * pages
       unsigned nr_pages
       get_block_t get_block

##### Arguments

`mapping`

  the address_space

`pages`

  The address of a list_head which contains the target pages. These pages have their ->index populated and are otherwise uninitialised.

`nr_pages`

  The number of pages at *`pages`

`get_block`

  The filesystem's block mapper function.

##### Description

This function walks the pages and the blocks within each page, building and emitting large BIOs.

If anything unusual happens, such as:

- encountering a page which has buffers - encountering a page which has a non-hole after a hole - encountering a page with non-contiguous blocks

then this code just gives up and calls the buffer_head-based read function. It does handle a page which has holes at the end - that is a common case: the end-of-file on blocksize < PAGE_CACHE_SIZE setups.

##### Description

This function walks the pages and the blocks within each page, building and emitting large BIOs.

If anything unusual happens, such as:

- encountering a page which has buffers - encountering a page which has a non-hole after a hole - encountering a page with non-contiguous blocks

then this code just gives up and calls the buffer_head-based read function. It does handle a page which has holes at the end - that is a common case: the end-of-file on blocksize < PAGE_CACHE_SIZE setups.

##### Description

This function walks the pages and the blocks within each page, building and emitting large BIOs.

If anything unusual happens, such as:

- encountering a page which has buffers - encountering a page which has a non-hole after a hole - encountering a page with non-contiguous blocks

then this code just gives up and calls the buffer_head-based read function. It does handle a page which has holes at the end - that is a common case: the end-of-file on blocksize < PAGE_CACHE_SIZE setups.

##### BH_Boundary explanation

There is a problem. The mpage read code assembles several pages, gets all their disk mappings, and then submits them all. That's fine, but obtaining the disk mappings may require I/O. Reads of indirect blocks, for example.

So an mpage read of the first 16 blocks of an ext2 file will cause I/O to be

##### submitted in the following order

12 0 1 2 3 4 5 6 7 8 9 10 11 13 14 15 16 because the indirect block has to be read to get the mappings of blocks 13,14,15,16. Obviously, this impacts performance.

So what we do it to allow the filesystem's `get_block` function to set BH_Boundary when it maps block 11. BH_Boundary says: mapping of the block after this one will require I/O against a block which is probably close to this one. So you should push what I/O you have currently accumulated.

This all causes the disk requests to be issued in the correct order.

#### LINUX

Kernel Hackers Manual March 2006
mpage_writepages
9

#### mpage_writepages

walk the list of dirty pages of the given

##### Synopsis

       int mpage_writepages
       struct address_space * mapping
       struct writeback_control * wbc
       get_block_t get_block

##### Arguments

`mapping`

  address space structure to write

`wbc`

  subtract the number of written pages from *`wbc`->nr_to_write

`get_block`

  the filesystem's block mapper function. If this is NULL then use a_ops->writepage. Otherwise, go direct-to-BIO.

##### Description

This is a library function, which implements the `writepages` address_space_operation.

If a page is already under I/O, `generic_writepages` skips it, even if it's dirty. This is desirable behaviour for memory-cleaning writeback, but it is INCORRECT for data-integrity system calls such as `fsync`. `fsync` and `msync` need to guarantee that all the data which was dirty at the time the call was made get new I/O started against them. If wbc->sync_mode is WB_SYNC_ALL then we were called for data integrity and we must wait for existing IO to complete.

##### Description

This is a library function, which implements the `writepages` address_space_operation.

If a page is already under I/O, `generic_writepages` skips it, even if it's dirty. This is desirable behaviour for memory-cleaning writeback, but it is INCORRECT for data-integrity system calls such as `fsync`. `fsync` and `msync` need to guarantee that all the data which was dirty at the time the call was made get new I/O started against them. If wbc->sync_mode is WB_SYNC_ALL then we were called for data integrity and we must wait for existing IO to complete.

#### LINUX

Kernel Hackers Manual March 2006
generic_permission
9

#### generic_permission

check for access rights on a Posix-like filesystem

##### Synopsis

       int generic_permission
       struct inode * inode
       int mask
       int (*check_acl)
         struct inode *inode, int mask

##### Arguments

`inode`

  inode to check access rights for

`mask`

  right to check for (`MAY_READ`, `MAY_WRITE`, `MAY_EXEC`)

`check_acl`

  optional callback to check for Posix ACLs

##### Description

Used to check for read/write/execute permissions on a file. We use fsuid for this, letting us set arbitrary permissions for filesystem access without changing the normal uids which are used for other things..

#### LINUX

Kernel Hackers Manual March 2006
vfs_permission
9

#### vfs_permission

check for access rights to a given path

##### Synopsis

       int vfs_permission
       struct nameidata * nd
       int mask

##### Arguments

`nd`

  lookup result that describes the path

`mask`

  right to check for (`MAY_READ`, `MAY_WRITE`, `MAY_EXEC`)

##### Description

Used to check for read/write/execute permissions on a path. We use fsuid for this, letting us set arbitrary permissions for filesystem access without changing the normal uids which are used for other things.

#### LINUX

Kernel Hackers Manual March 2006
file_permission
9

#### file_permission

check for additional access rights to a given file

##### Synopsis

       int file_permission
       struct file * file
       int mask

##### Arguments

`file`

  file to check access rights for

`mask`

  right to check for (`MAY_READ`, `MAY_WRITE`, `MAY_EXEC`)

##### Description

Used to check for read/write/execute permissions on an already opened file.

##### Note

Do not use this function in new code. All access checks should be done using `vfs_permission`.

#### LINUX

Kernel Hackers Manual March 2006
lookup_create
9

#### lookup_create

lookup a dentry, creating it if it doesn't exist

##### Synopsis

       struct dentry * lookup_create
       struct nameidata * nd
       int is_dir

##### Arguments

`nd`

  nameidata info

`is_dir`

  directory flag

##### Description

Simple function to lookup and return a dentry and create it if it doesn't exist. Is SMP-safe.

Returns with nd->dentry->d_inode->i_mutex locked.

#### LINUX

Kernel Hackers Manual March 2006
freeze_bdev
9

#### freeze_bdev

- lock a filesystem and force it into a consistent state

##### Synopsis

       struct super_block * freeze_bdev
       struct block_device * bdev

##### Arguments

`bdev`

  blockdevice to lock

##### Description

This takes the block device bd_mount_sem to make sure no new mounts happen on bdev until `thaw_bdev` is called. If a superblock is found on this device, we take the s_umount semaphore on it to make sure nobody unmounts until the snapshot creation is done.

#### LINUX

Kernel Hackers Manual March 2006
thaw_bdev
9

#### thaw_bdev

- unlock filesystem

##### Synopsis

       void thaw_bdev
       struct block_device * bdev
       struct super_block * sb

##### Arguments

`bdev`

  blockdevice to unlock

`sb`

  associated superblock

##### Description

Unlocks the filesystem and marks it writeable again after `freeze_bdev`.

#### LINUX

Kernel Hackers Manual March 2006
sync_mapping_buffers
9

#### sync_mapping_buffers

write out and wait upon a mapping's associated

##### Synopsis

       int sync_mapping_buffers
       struct address_space * mapping

##### Arguments

`mapping`

  the mapping which wants those buffers written

##### Description

Starts I/O against the buffers at mapping->private_list, and waits upon that I/O.

Basically, this is a convenience function for `fsync`. `mapping` is a file or directory which needs those buffers to be written for a successful `fsync`.

##### Description

Starts I/O against the buffers at mapping->private_list, and waits upon that I/O.

Basically, this is a convenience function for `fsync`. `mapping` is a file or directory which needs those buffers to be written for a successful `fsync`.

#### LINUX

Kernel Hackers Manual March 2006
mark_buffer_dirty
9

#### mark_buffer_dirty

mark a buffer_head as needing writeout

##### Synopsis

       void fastcall mark_buffer_dirty
       struct buffer_head * bh

##### Arguments

`bh`

  the buffer_head to mark dirty

##### Description

`mark_buffer_dirty` will set the dirty bit against the buffer, then set its backing page dirty, then tag the page as dirty in its address_space's radix tree and then attach the address_space's inode to its superblock's dirty inode list.

`mark_buffer_dirty` is atomic. It takes bh->b_page->mapping->private_lock, mapping->tree_lock and the global inode_lock.

#### LINUX

Kernel Hackers Manual March 2006
__bread
9

#### __bread

reads a specified block and returns the bh

##### Synopsis

       struct buffer_head * __bread
       struct block_device * bdev
       sector_t block
       int size

##### Arguments

`bdev`

  the block_device to read from

`block`

  number of block

`size`

  size (in bytes) to read

##### Description

Reads a specified block, and returns buffer head that contains it. It returns NULL if the block was unreadable.

#### LINUX

Kernel Hackers Manual March 2006
try_to_release_page
9

#### try_to_release_page

release old fs-specific metadata on a page

##### Synopsis

       int try_to_release_page
       struct page * page
       gfp_t gfp_mask

##### Arguments

`page`

  the page which the kernel is trying to free

`gfp_mask`

  memory allocation flags (and I/O mode)

##### Description

The address_space is to try to release any data against the page (presumably at page->private). If the release was successful, return `1'. Otherwise return zero.

The `gfp_mask` argument specifies whether I/O may be performed to release this page (__GFP_IO), and whether the call may block (__GFP_WAIT).

##### Description

The address_space is to try to release any data against the page (presumably at page->private). If the release was successful, return `1'. Otherwise return zero.

The `gfp_mask` argument specifies whether I/O may be performed to release this page (__GFP_IO), and whether the call may block (__GFP_WAIT).

##### NOTE

`gfp_mask` may go away, and this function may become non-blocking.

#### LINUX

Kernel Hackers Manual March 2006
block_invalidatepage
9

#### block_invalidatepage

invalidate part of all of a buffer-backed page

##### Synopsis

       int block_invalidatepage
       struct page * page
       unsigned long offset

##### Arguments

`page`

  the page which is affected

`offset`

  the index of the truncation point

##### Description

`block_invalidatepage` is called when all or part of the page has become invalidatedby a truncate operation.

`block_invalidatepage` does not have to release all buffers, but it must ensure that no dirty buffer is left outside `offset` and that no I/O is underway against any of the blocks which are outside the truncation point. Because the caller is about to free (and possibly reuse) those blocks on-disk.

##### Description

`block_invalidatepage` is called when all or part of the page has become invalidatedby a truncate operation.

`block_invalidatepage` does not have to release all buffers, but it must ensure that no dirty buffer is left outside `offset` and that no I/O is underway against any of the blocks which are outside the truncation point. Because the caller is about to free (and possibly reuse) those blocks on-disk.

#### LINUX

Kernel Hackers Manual March 2006
ll_rw_block
9

#### ll_rw_block

level access to block devices (DEPRECATED)

##### Synopsis

       void ll_rw_block
       int rw
       int nr
       struct buffer_head * bhs[]

##### Arguments

`rw`

  whether to `READ` or `WRITE` or `SWRITE` or maybe `READA` (readahead)

`nr`

  number of &struct buffer_heads in the array

`bhs[]`

  array of pointers to &struct buffer_head

##### Description

`ll_rw_block` takes an array of pointers to &struct buffer_heads, and requests an I/O operation on them, either a `READ` or a `WRITE`. The third `SWRITE` is like `WRITE` only we make sure that the *current* data in buffers are sent to disk. The fourth `READA` option is described in the documentation for `generic_make_request` which `ll_rw_block` calls.

This function drops any buffer that it cannot get a lock on (with the BH_Lock state bit) unless SWRITE is required, any buffer that appears to be clean when doing a write request, and any buffer that appears to be up-to-date when doing read request. Further it marks as clean buffers that are processed for writing (the buffer cache won't assume that they are actually clean until the buffer gets unlocked).

ll_rw_block sets b_end_io to simple completion handler that marks the buffer up-to-date (if approriate), unlocks the buffer and wakes any waiters.

All of the buffers must be for the same device, and must also be a multiple of the current approved size for the device.

#### LINUX

Kernel Hackers Manual March 2006
bio_alloc_bioset
9

#### bio_alloc_bioset

allocate a bio for I/O

##### Synopsis

       struct bio * bio_alloc_bioset
       gfp_t gfp_mask
       int nr_iovecs
       struct bio_set * bs

##### Arguments

`gfp_mask`

  the GFP_ mask given to the slab allocator

`nr_iovecs`

  number of iovecs to pre-allocate

`bs`

  the bio_set to allocate from

##### Description

bio_alloc_bioset will first try it's on mempool to satisfy the allocation. If `__GFP_WAIT` is set then we will block on the internal pool waiting for a &struct bio to become free.

allocate bio and iovecs from the memory pools specified by the bio_set structure.

#### LINUX

Kernel Hackers Manual March 2006
bio_put
9

#### bio_put

release a reference to a bio

##### Synopsis

       void bio_put
       struct bio * bio

##### Arguments

`bio`

  bio to release reference to

##### Description

Put a reference to a &struct bio, either one you have gotten with bio_alloc or bio_get. The last put of a bio will free it.

#### LINUX

Kernel Hackers Manual March 2006
__bio_clone
9

#### __bio_clone

clone a bio

##### Synopsis

       void __bio_clone
       struct bio * bio
       struct bio * bio_src

##### Arguments

`bio`

  destination bio

`bio_src`

  bio to clone

##### Description

Clone a &bio. Caller will own the returned bio, but not the actual data it points to. Reference count of returned bio will be one.

#### LINUX

Kernel Hackers Manual March 2006
bio_clone
9

#### bio_clone

clone a bio

##### Synopsis

       struct bio * bio_clone
       struct bio * bio
       gfp_t gfp_mask

##### Arguments

`bio`

  bio to clone

`gfp_mask`

  allocation priority

##### Description

Like __bio_clone, only also allocates the returned bio

#### LINUX

Kernel Hackers Manual March 2006
bio_get_nr_vecs
9

#### bio_get_nr_vecs

return approx number of vecs

##### Synopsis

       int bio_get_nr_vecs
       struct block_device * bdev

##### Arguments

`bdev`

  I/O target

##### Description

Return the approximate number of pages we can send to this target. There's no guarantee that you will be able to fit this number of pages into a bio, it does not account for dynamic restrictions that vary on offset.

#### LINUX

Kernel Hackers Manual March 2006
bio_add_pc_page
9

#### bio_add_pc_page

attempt to add page to bio

##### Synopsis

       int bio_add_pc_page
       request_queue_t * q
       struct bio * bio
       struct page * page
       unsigned int len
       unsigned int offset

##### Arguments

`q`

  the target queue

`bio`

  destination bio

`page`

  page to add

`len`

  vec entry length

`offset`

  vec entry offset

##### Description

Attempt to add a page to the bio_vec maplist. This can fail for a number of reasons, such as the bio being full or target block device limitations. The target block device must allow bio's smaller than PAGE_SIZE, so it is always possible to add a single page to an empty bio. This should only be used by REQ_PC bios.

#### LINUX

Kernel Hackers Manual March 2006
bio_add_page
9

#### bio_add_page

attempt to add page to bio

##### Synopsis

       int bio_add_page
       struct bio * bio
       struct page * page
       unsigned int len
       unsigned int offset

##### Arguments

`bio`

  destination bio

`page`

  page to add

`len`

  vec entry length

`offset`

  vec entry offset

##### Description

Attempt to add a page to the bio_vec maplist. This can fail for a number of reasons, such as the bio being full or target block device limitations. The target block device must allow bio's smaller than PAGE_SIZE, so it is always possible to add a single page to an empty bio.

#### LINUX

Kernel Hackers Manual March 2006
bio_uncopy_user
9

#### bio_uncopy_user

finish previously mapped bio

##### Synopsis

       int bio_uncopy_user
       struct bio * bio

##### Arguments

`bio`

  bio being terminated

##### Description

Free pages allocated from `bio_copy_user` and write back data to user space in case of a read.

#### LINUX

Kernel Hackers Manual March 2006
bio_copy_user
9

#### bio_copy_user

copy user data to bio

##### Synopsis

       struct bio * bio_copy_user
       request_queue_t * q
       unsigned long uaddr
       unsigned int len
       int write_to_vm

##### Arguments

`q`

  destination block queue

`uaddr`

  start of user address

`len`

  length in bytes

`write_to_vm`

  bool indicating writing to pages or not

##### Description

Prepares and returns a bio for indirect user io, bouncing data to/from kernel pages as necessary. Must be paired with call `bio_uncopy_user` on io completion.

#### LINUX

Kernel Hackers Manual March 2006
bio_map_user
9

#### bio_map_user

map user address into bio

##### Synopsis

       struct bio * bio_map_user
       request_queue_t * q
       struct block_device * bdev
       unsigned long uaddr
       unsigned int len
       int write_to_vm

##### Arguments

`q`

  the request_queue_t for the bio

`bdev`

  destination block device

`uaddr`

  start of user address

`len`

  length in bytes

`write_to_vm`

  bool indicating writing to pages or not

##### Description

Map the user space address into a bio suitable for io to a block device. Returns an error pointer in case of error.

#### LINUX

Kernel Hackers Manual March 2006
bio_unmap_user
9

#### bio_unmap_user

unmap a bio

##### Synopsis

       void bio_unmap_user
       struct bio * bio

##### Arguments

`bio`

  the bio being unmapped

##### Description

Unmap a bio previously mapped by `bio_map_user`. Must be called with a process context.

`bio_unmap_user` may sleep.

#### LINUX

Kernel Hackers Manual March 2006
bio_map_kern
9

#### bio_map_kern

map kernel address into bio

##### Synopsis

       struct bio * bio_map_kern
       request_queue_t * q
       void * data
       unsigned int len
       gfp_t gfp_mask

##### Arguments

`q`

  the request_queue_t for the bio

`data`

  pointer to buffer to map

`len`

  length in bytes

`gfp_mask`

  allocation flags for bio allocation

##### Description

Map the kernel address into a bio suitable for io to a block device. Returns an error pointer in case of error.

#### LINUX

Kernel Hackers Manual March 2006
bio_endio
9

#### bio_endio

end I/O on a bio

##### Synopsis

       void bio_endio
       struct bio * bio
       unsigned int bytes_done
       int error

##### Arguments

`bio`

  bio

`bytes_done`

  number of bytes completed

`error`

  error, if any

##### Description

`bio_endio` will end I/O on `bytes_done` number of bytes. This may be just a partial part of the bio, or it may be the whole bio. `bio_endio` is the preferred way to end I/O on a bio, it takes care of decrementing bi_size and clearing BIO_UPTODATE on error. `error` is 0 on success, and and one of the established -Exxxx (-EIO, for instance) error values in case something went wrong. Noone should call `bi_end_io` directly on a bio unless they own it and thus know that it has an end_io function.

#### LINUX

Kernel Hackers Manual March 2006
seq_open
9

#### seq_open

initialize sequential file

##### Synopsis

       int seq_open
       struct file * file
       struct seq_operations * op

##### Arguments

`file`

  file we initialize

`op`

  method table describing the sequence

##### Description

`seq_open` sets `file`, associating it with a sequence described by `op`. `op`->`start` sets the iterator up and returns the first element of sequence. `op`->`stop` shuts it down. `op`->`next` returns the next element of sequence. `op`->`show` prints element into the buffer. In case of error ->`start` and ->`next` return ERR_PTR(error). In the end of sequence they return `NULL`. ->`show` returns 0 in case of success and negative number in case of error.

#### LINUX

Kernel Hackers Manual March 2006
seq_read
9

#### seq_read

->`read` method for sequential files.

##### Synopsis

       ssize_t seq_read
       struct file * file
       char __user * buf
       size_t size
       loff_t * ppos

##### Arguments

`file`

  the file to read from

`buf`

  the buffer to read to

`size`

  the maximum number of bytes to read

`ppos`

  the current position in the file

##### Description

Ready-made ->f_op->`read`

#### LINUX

Kernel Hackers Manual March 2006
seq_lseek
9

#### seq_lseek

->`llseek` method for sequential files.

##### Synopsis

       loff_t seq_lseek
       struct file * file
       loff_t offset
       int origin

##### Arguments

`file`

  the file in question

`offset`

  new position

`origin`

  0 for absolute, 1 for relative position

##### Description

Ready-made ->f_op->`llseek`

#### LINUX

Kernel Hackers Manual March 2006
seq_release
9

#### seq_release

free the structures associated with sequential file.

##### Synopsis

       int seq_release
       struct inode * inode
       struct file * file

##### Arguments

`inode`

  file->f_dentry->d_inode

`file`

  file in question

##### Description

Frees the structures associated with sequential file; can be used as ->f_op->`release` if you don't have private data to destroy.

#### LINUX

Kernel Hackers Manual March 2006
seq_escape
9

#### seq_escape

print string into buffer, escaping some characters

##### Synopsis

       int seq_escape
       struct seq_file * m
       const char * s
       const char * esc

##### Arguments

`m`

  target buffer

`s`

  string

`esc`

  set of characters that need escaping

##### Description

Puts string into buffer, replacing each occurrence of character from `esc` with usual octal escape. Returns 0 in case of success, -1 - in case of overflow.

#### LINUX

Kernel Hackers Manual March 2006
register_filesystem
9

#### register_filesystem

register a new filesystem

##### Synopsis

       int register_filesystem
       struct file_system_type * fs

##### Arguments

`fs`

  the file system structure

##### Description

Adds the file system passed to the list of file systems the kernel is aware of for mount and other syscalls. Returns 0 on success, or a negative errno code on an error.

The &struct file_system_type that is passed is linked into the kernel structures and must not be freed until the file system has been unregistered.

#### LINUX

Kernel Hackers Manual March 2006
unregister_filesystem
9

#### unregister_filesystem

unregister a file system

##### Synopsis

       int unregister_filesystem
       struct file_system_type * fs

##### Arguments

`fs`

  filesystem to unregister

##### Description

Remove a file system that was previously successfully registered with the kernel. An error is returned if the file system is not found. Zero is returned on a success.

Once this function has returned the &struct file_system_type structure may be freed or reused.

#### LINUX

Kernel Hackers Manual March 2006
__mark_inode_dirty
9

#### __mark_inode_dirty

internal function

##### Synopsis

       void __mark_inode_dirty
       struct inode * inode
       int flags

##### Arguments

`inode`

  inode to mark

`flags`

  what kind of dirty (i.e. I_DIRTY_SYNC) Mark an inode as dirty. Callers should use mark_inode_dirty or mark_inode_dirty_sync.

##### Description

Put the inode on the super block's dirty list.

CAREFUL! We mark it dirty unconditionally, but move it onto the dirty list only if it is hashed or if it refers to a blockdev. If it was not hashed, it will never be added to the dirty list even if it is later hashed, as it will have been marked dirty already.

In short, make sure you hash any inodes _before_ you start marking them dirty.

This function *must* be atomic for the I_DIRTY_PAGES case - `set_page_dirty` is called under spinlock in several places.

Note that for blockdevs, inode->dirtied_when represents the dirtying time of the block-special inode (/dev/hda1) itself. And the ->dirtied_when field of the kernel-internal blockdev inode represents the dirtying time of the blockdev's pages. This is why for I_DIRTY_PAGES we always use page->mapping->host, so the page-dirtying time is recorded in the internal blockdev inode.

#### LINUX

Kernel Hackers Manual March 2006
write_inode_now
9

#### write_inode_now

write an inode to disk

##### Synopsis

       int write_inode_now
       struct inode * inode
       int sync

##### Arguments

`inode`

  inode to write to disk

`sync`

  whether the write should be synchronous or not

##### Description

This function commits an inode to disk immediately if it is dirty. This is primarily needed by knfsd.

The caller must either have a ref on the inode or must have set I_WILL_FREE.

#### LINUX

Kernel Hackers Manual March 2006
sync_inode
9

#### sync_inode

write an inode and its pages to disk.

##### Synopsis

       int sync_inode
       struct inode * inode
       struct writeback_control * wbc

##### Arguments

`inode`

  the inode to sync

`wbc`

  controls the writeback mode

##### Description

`sync_inode` will write an inode and its pages to disk. It will also correctly update the inode on its superblock's dirty inode lists and will update inode->i_state.

The caller must have a ref on the inode.

#### LINUX

Kernel Hackers Manual March 2006
generic_osync_inode
9

#### generic_osync_inode

flush all dirty data for a given inode to disk

##### Synopsis

       int generic_osync_inode
       struct inode * inode
       struct address_space * mapping
       int what

##### Arguments

`inode`

  inode to write

`mapping`

  the address_space that should be flushed

`what`

  what to write and wait upon

##### Description

This can be called by file_write functions for files which have the O_SYNC flag set, to flush dirty writes to disk.

`what` is a bitmask, specifying which part of the inode's data should be written and waited upon.

##### OSYNC_DATA

i_mapping's dirty data

##### OSYNC_METADATA

the buffers at i_mapping->private_list

##### OSYNC_INODE

the inode itself

#### LINUX

Kernel Hackers Manual March 2006
open_bdev_excl
9

#### open_bdev_excl

open a block device by name and set it up for use

##### Synopsis

       struct block_device * open_bdev_excl
       const char * path
       int flags
       void * holder

##### Arguments

`path`

  special file representing the block device

`flags`

  `MS_RDONLY` for opening read-only

`holder`

  owner for exclusion

##### Description

Open the blockdevice described by the special file at `path`, claim it for the `holder`.

##### Description

Open the blockdevice described by the special file at `path`, claim it for the `holder`.

#### LINUX

Kernel Hackers Manual March 2006
close_bdev_excl
9

#### close_bdev_excl

release a blockdevice openen by `open_bdev_excl`

##### Synopsis

       void close_bdev_excl
       struct block_device * bdev

##### Arguments

`bdev`

  blockdevice to close

##### Description

This is the counterpart to `open_bdev_excl`.

##### Description

This is the counterpart to `open_bdev_excl`.

## Linux Networking

### Networking Base Types

#### LINUX

Kernel Hackers Manual March 2006
enum sock_type
9

#### enum sock_type

Socket types

##### Synopsis

    enum sock_type {
      SOCK_STREAM,
      SOCK_DGRAM,
      SOCK_RAW,
      SOCK_RDM,
      SOCK_SEQPACKET,
      SOCK_DCCP,
      SOCK_PACKET
    };

##### Constants

SOCK_STREAM

  stream (connection) socket

SOCK_DGRAM

  datagram (conn.less) socket

SOCK_RAW

  raw socket

SOCK_RDM

  reliably-delivered message

SOCK_SEQPACKET

  sequential packet socket

SOCK_DCCP

  Datagram Congestion Control Protocol socket

SOCK_PACKET

  linux specific way of getting packets at the dev level. For writing rarp and other similar things on the user level.

##### Description

When adding some new socket type please grep ARCH_HAS_SOCKET_TYPE include/asm-* /socket.h, at least MIPS overrides this enum for binary compat reasons.

#### LINUX

Kernel Hackers Manual March 2006
struct socket
9

#### struct socket

general BSD socket

##### Synopsis

    struct socket {
      socket_state state;
      unsigned long flags;
      const struct proto_ops * ops;
      struct fasync_struct * fasync_list;
      struct file * file;
      struct sock * sk;
      wait_queue_head_t wait;
      short type;
    };

##### Members

state

  socket state (`SS_CONNECTED`, etc)

flags

  socket flags (`SOCK_ASYNC_NOSPACE`, etc)

ops

  protocol specific socket operations

fasync_list

  Asynchronous wake up list

file

  File back pointer for gc

sk

  internal networking protocol agnostic socket representation

wait

  wait queue for several uses

type

  socket type (`SOCK_STREAM`, etc)

### Socket Buffer Functions

#### LINUX

Kernel Hackers Manual March 2006
struct sk_buff
9

#### struct sk_buff

socket buffer

##### Synopsis

    struct sk_buff {
      struct sk_buff * next;
      struct sk_buff * prev;
      struct sock * sk;
      struct skb_timeval tstamp;
      struct net_device * dev;
      struct net_device * input_dev;
      union h;
      union nh;
      union mac;
      struct dst_entry * dst;
      struct sec_path * sp;
      char cb[48];
      unsigned int len;
      unsigned int data_len;
      unsigned int mac_len;
      unsigned int csum;
      __u32 priority;
      __u8 local_df:1;
      __u8 cloned:1;
      __u8 ip_summed:2;
      __u8 nohdr:1;
      __u8 nfctinfo:3;
      __u8 pkt_type:3;
      __u8 fclone:2;
      __u8 ipvs_property:1;
      __be16 protocol;
      void (* destructor) (struct sk_buff *skb);
    #ifdef CONFIG_NETFILTER
      __u32 nfmark;
      struct nf_conntrack * nfct;
    #if defined(CONFIG_NF_CONNTRACK) || defined(CONFIG_NF_CONNTRACK_MODULE)
      struct sk_buff * nfct_reasm;
    #endif
    #ifdef CONFIG_BRIDGE_NETFILTER
      struct nf_bridge_info * nf_bridge;
    #endif
    #endif
    #ifdef CONFIG_NET_SCHED
      __u16 tc_index;
    #ifdef CONFIG_NET_CLS_ACT
      __u16 tc_verd;
    #endif
    #endif
      unsigned int truesize;
      atomic_t users;
      unsigned char * head;
      unsigned char * data;
      unsigned char * tail;
      unsigned char * end;
    };

##### Members

next

  Next buffer in list

prev

  Previous buffer in list

sk

  Socket we are owned by

tstamp

  Time we arrived

dev

  Device we arrived on/are leaving by

input_dev

  Device we arrived on

h

  Transport layer header

nh

  Network layer header

mac

  Link layer header

dst

  destination entry

sp

  the security path, used for xfrm

cb[48]

  Control buffer. Free for use by every layer. Put private vars here

len

  Length of actual data

data_len

  Data length

mac_len

  Length of link layer header

csum

  Checksum

priority

  Packet queueing priority

local_df

  allow local fragmentation

cloned

  Head may be cloned (check refcnt to be sure)

ip_summed

  Driver fed us an IP checksum

nohdr

  Payload reference only, must not modify header

nfctinfo

  Relationship of this skb to the connection

pkt_type

  Packet class

fclone

  skbuff clone status

ipvs_property

  skbuff is owned by ipvs

protocol

  Packet protocol from driver

destructor

  Destruct function

nfmark

  Can be used for communication between hooks

nfct

  Associated connection, if any

nfct_reasm

  netfilter conntrack re-assembly pointer

nf_bridge

  Saved data about a bridged frame - see br_netfilter.c

tc_index

  Traffic control index

tc_verd

  traffic control verdict

truesize

  Buffer size

users

  User count - see {datagram,tcp}.c

head

  Head of buffer

data

  Data head pointer

tail

  Tail pointer

end

  End pointer

#### LINUX

Kernel Hackers Manual March 2006
skb_queue_empty
9

#### skb_queue_empty

check if a queue is empty

##### Synopsis

       int skb_queue_empty
       const struct sk_buff_head * list

##### Arguments

`list`

  queue head

##### Description

Returns true if the queue is empty, false otherwise.

#### LINUX

Kernel Hackers Manual March 2006
skb_get
9

#### skb_get

reference buffer

##### Synopsis

       struct sk_buff * skb_get
       struct sk_buff * skb

##### Arguments

`skb`

  buffer to reference

##### Description

Makes another reference to a socket buffer and returns a pointer to the buffer.

#### LINUX

Kernel Hackers Manual March 2006
kfree_skb
9

#### kfree_skb

free an sk_buff

##### Synopsis

       void kfree_skb
       struct sk_buff * skb

##### Arguments

`skb`

  buffer to free

##### Description

Drop a reference to the buffer and free it if the usage count has hit zero.

#### LINUX

Kernel Hackers Manual March 2006
skb_cloned
9

#### skb_cloned

is the buffer a clone

##### Synopsis

       int skb_cloned
       const struct sk_buff * skb

##### Arguments

`skb`

  buffer to check

##### Description

Returns true if the buffer was generated with `skb_clone` and is one of multiple shared copies of the buffer. Cloned buffers are shared data so must not be written to under normal circumstances.

#### LINUX

Kernel Hackers Manual March 2006
skb_header_cloned
9

#### skb_header_cloned

is the header a clone

##### Synopsis

       int skb_header_cloned
       const struct sk_buff * skb

##### Arguments

`skb`

  buffer to check

##### Description

Returns true if modifying the header part of the buffer requires the data to be copied.

#### LINUX

Kernel Hackers Manual March 2006
skb_header_release
9

#### skb_header_release

release reference to header

##### Synopsis

       void skb_header_release
       struct sk_buff * skb

##### Arguments

`skb`

  buffer to operate on

##### Description

Drop a reference to the header part of the buffer. This is done by acquiring a payload reference. You must not read from the header part of skb->data after this.

#### LINUX

Kernel Hackers Manual March 2006
skb_shared
9

#### skb_shared

is the buffer shared

##### Synopsis

       int skb_shared
       const struct sk_buff * skb

##### Arguments

`skb`

  buffer to check

##### Description

Returns true if more than one person has a reference to this buffer.

#### LINUX

Kernel Hackers Manual March 2006
skb_share_check
9

#### skb_share_check

check if buffer is shared and if so clone it

##### Synopsis

       struct sk_buff * skb_share_check
       struct sk_buff * skb
       gfp_t pri

##### Arguments

`skb`

  buffer to check

`pri`

  priority for memory allocation

##### Description

If the buffer is shared the buffer is cloned and the old copy drops a reference. A new clone with a single reference is returned. If the buffer is not shared the original buffer is returned. When being called from interrupt status or with spinlocks held pri must be GFP_ATOMIC.

NULL is returned on a memory allocation failure.

#### LINUX

Kernel Hackers Manual March 2006
skb_unshare
9

#### skb_unshare

make a copy of a shared buffer

##### Synopsis

       struct sk_buff * skb_unshare
       struct sk_buff * skb
       gfp_t pri

##### Arguments

`skb`

  buffer to check

`pri`

  priority for memory allocation

##### Description

If the socket buffer is a clone then this function creates a new copy of the data, drops a reference count on the old copy and returns the new copy with the reference count at 1. If the buffer is not a clone the original buffer is returned. When called with a spinlock held or from interrupt state `pri` must be `GFP_ATOMIC`

`NULL` is returned on a memory allocation failure.

#### LINUX

Kernel Hackers Manual March 2006
skb_peek
9

#### skb_peek

##### Synopsis

       struct sk_buff * skb_peek
       struct sk_buff_head * list_

##### Arguments

`list_`

  list to peek at

##### Description

Peek an &sk_buff. Unlike most other operations you _MUST_ be careful with this one. A peek leaves the buffer on the list and someone else may run off with it. You must hold the appropriate locks or have a private queue to do this.

Returns `NULL` for an empty list or a pointer to the head element. The reference count is not incremented and the reference is therefore volatile. Use with caution.

#### LINUX

Kernel Hackers Manual March 2006
skb_peek_tail
9

#### skb_peek_tail

##### Synopsis

       struct sk_buff * skb_peek_tail
       struct sk_buff_head * list_

##### Arguments

`list_`

  list to peek at

##### Description

Peek an &sk_buff. Unlike most other operations you _MUST_ be careful with this one. A peek leaves the buffer on the list and someone else may run off with it. You must hold the appropriate locks or have a private queue to do this.

Returns `NULL` for an empty list or a pointer to the tail element. The reference count is not incremented and the reference is therefore volatile. Use with caution.

#### LINUX

Kernel Hackers Manual March 2006
skb_queue_len
9

#### skb_queue_len

get queue length

##### Synopsis

       __u32 skb_queue_len
       const struct sk_buff_head * list_

##### Arguments

`list_`

  list to measure

##### Description

Return the length of an &sk_buff queue.

#### LINUX

Kernel Hackers Manual March 2006
__skb_queue_after
9

#### __skb_queue_after

queue a buffer at the list head

##### Synopsis

       void __skb_queue_after
       struct sk_buff_head * list
       struct sk_buff * prev
       struct sk_buff * newsk

##### Arguments

`list`

  list to use

`prev`

  place after this buffer

`newsk`

  buffer to queue

##### Description

Queue a buffer int the middle of a list. This function takes no locks and you must therefore hold required locks before calling it.

A buffer cannot be placed on two lists at the same time.

#### LINUX

Kernel Hackers Manual March 2006
skb_put
9

#### skb_put

add data to a buffer

##### Synopsis

       unsigned char * skb_put
       struct sk_buff * skb
       unsigned int len

##### Arguments

`skb`

  buffer to use

`len`

  amount of data to add

##### Description

This function extends the used data area of the buffer. If this would exceed the total buffer size the kernel will panic. A pointer to the first byte of the extra data is returned.

#### LINUX

Kernel Hackers Manual March 2006
skb_push
9

#### skb_push

add data to the start of a buffer

##### Synopsis

       unsigned char * skb_push
       struct sk_buff * skb
       unsigned int len

##### Arguments

`skb`

  buffer to use

`len`

  amount of data to add

##### Description

This function extends the used data area of the buffer at the buffer start. If this would exceed the total buffer headroom the kernel will panic. A pointer to the first byte of the extra data is returned.

#### LINUX

Kernel Hackers Manual March 2006
skb_pull
9

#### skb_pull

remove data from the start of a buffer

##### Synopsis

       unsigned char * skb_pull
       struct sk_buff * skb
       unsigned int len

##### Arguments

`skb`

  buffer to use

`len`

  amount of data to remove

##### Description

This function removes data from the start of a buffer, returning the memory to the headroom. A pointer to the next data in the buffer is returned. Once the data has been pulled future pushes will overwrite the old data.

#### LINUX

Kernel Hackers Manual March 2006
skb_headroom
9

#### skb_headroom

bytes at buffer head

##### Synopsis

       int skb_headroom
       const struct sk_buff * skb

##### Arguments

`skb`

  buffer to check

##### Description

Return the number of bytes of free space at the head of an &sk_buff.

#### LINUX

Kernel Hackers Manual March 2006
skb_tailroom
9

#### skb_tailroom

bytes at buffer end

##### Synopsis

       int skb_tailroom
       const struct sk_buff * skb

##### Arguments

`skb`

  buffer to check

##### Description

Return the number of bytes of free space at the tail of an sk_buff

#### LINUX

Kernel Hackers Manual March 2006
skb_reserve
9

#### skb_reserve

adjust headroom

##### Synopsis

       void skb_reserve
       struct sk_buff * skb
       int len

##### Arguments

`skb`

  buffer to alter

`len`

  bytes to move

##### Description

Increase the headroom of an empty &sk_buff by reducing the tail room. This is only allowed for an empty buffer.

#### LINUX

Kernel Hackers Manual March 2006
skb_trim
9

#### skb_trim

remove end from a buffer

##### Synopsis

       void skb_trim
       struct sk_buff * skb
       unsigned int len

##### Arguments

`skb`

  buffer to alter

`len`

  new length

##### Description

Cut the length of a buffer down by removing data from the tail. If the buffer is already under the length specified it is not modified.

#### LINUX

Kernel Hackers Manual March 2006
skb_orphan
9

#### skb_orphan

orphan a buffer

##### Synopsis

       void skb_orphan
       struct sk_buff * skb

##### Arguments

`skb`

  buffer to orphan

##### Description

If a buffer currently has an owner then we call the owner's destructor function and make the `skb` unowned. The buffer continues to exist but is no longer charged to its former owner.

#### LINUX

Kernel Hackers Manual March 2006
__dev_alloc_skb
9

#### __dev_alloc_skb

allocate an skbuff for sending

##### Synopsis

       struct sk_buff * __dev_alloc_skb
       unsigned int length
       gfp_t gfp_mask

##### Arguments

`length`

  length to allocate

`gfp_mask`

  get_free_pages mask, passed to alloc_skb

##### Description

Allocate a new &sk_buff and assign it a usage count of one. The buffer has unspecified headroom built in. Users should allocate the headroom they think they need without accounting for the built in space. The built in space is used for optimisations.

`NULL` is returned in there is no free memory.

#### LINUX

Kernel Hackers Manual March 2006
dev_alloc_skb
9

#### dev_alloc_skb

allocate an skbuff for sending

##### Synopsis

       struct sk_buff * dev_alloc_skb
       unsigned int length

##### Arguments

`length`

  length to allocate

##### Description

Allocate a new &sk_buff and assign it a usage count of one. The buffer has unspecified headroom built in. Users should allocate the headroom they think they need without accounting for the built in space. The built in space is used for optimisations.

`NULL` is returned in there is no free memory. Although this function allocates memory it can be called from an interrupt.

#### LINUX

Kernel Hackers Manual March 2006
skb_cow
9

#### skb_cow

copy header of skb when it is required

##### Synopsis

       int skb_cow
       struct sk_buff * skb
       unsigned int headroom

##### Arguments

`skb`

  buffer to cow

`headroom`

  needed headroom

##### Description

If the skb passed lacks sufficient headroom or its data part is shared, data is reallocated. If reallocation fails, an error is returned and original skb is not changed.

The result is skb with writable area skb->head...skb->tail and at least `headroom` of space at head.

#### LINUX

Kernel Hackers Manual March 2006
skb_padto
9

#### skb_padto

pad an skbuff up to a minimal size

##### Synopsis

       struct sk_buff * skb_padto
       struct sk_buff * skb
       unsigned int len

##### Arguments

`skb`

  buffer to pad

`len`

  minimal length

##### Description

Pads up a buffer to ensure the trailing bytes exist and are blanked. If the buffer already contains sufficient data it is untouched. Returns the buffer, which may be a replacement for the original, or NULL for out of memory - in which case the original buffer is still freed.

#### LINUX

Kernel Hackers Manual March 2006
skb_postpull_rcsum
9

#### skb_postpull_rcsum

update checksum for received skb after pull

##### Synopsis

       void skb_postpull_rcsum
       struct sk_buff * skb
       const void * start
       int len

##### Arguments

`skb`

  buffer to update

`start`

  start of data before pull

`len`

  length of data pulled

##### Description

After doing a pull on a received packet, you need to call this to update the CHECKSUM_HW checksum, or set ip_summed to CHECKSUM_NONE so that it can be recomputed from scratch.

#### LINUX

Kernel Hackers Manual March 2006
pskb_trim_rcsum
9

#### pskb_trim_rcsum

trim received skb and update checksum

##### Synopsis

       int pskb_trim_rcsum
       struct sk_buff * skb
       unsigned int len

##### Arguments

`skb`

  buffer to trim

`len`

  new length

##### Description

This is exactly the same as pskb_trim except that it ensures the checksum of received packets are still valid after the operation.

#### LINUX

Kernel Hackers Manual March 2006
skb_get_timestamp
9

#### skb_get_timestamp

get timestamp from a skb

##### Synopsis

       void skb_get_timestamp
       const struct sk_buff * skb
       struct timeval * stamp

##### Arguments

`skb`

  skb to get stamp from

`stamp`

  pointer to struct timeval to store stamp in

##### Description

Timestamps are stored in the skb as offsets to a base timestamp. This function converts the offset back to a struct timeval and stores it in stamp.

#### LINUX

Kernel Hackers Manual March 2006
skb_set_timestamp
9

#### skb_set_timestamp

set timestamp of a skb

##### Synopsis

       void skb_set_timestamp
       struct sk_buff * skb
       const struct timeval * stamp

##### Arguments

`skb`

  skb to set stamp of

`stamp`

  pointer to struct timeval to get stamp from

##### Description

Timestamps are stored in the skb as offsets to a base timestamp. This function converts a struct timeval to an offset and stores it in the skb.

#### LINUX

Kernel Hackers Manual March 2006
skb_checksum_complete
9

#### skb_checksum_complete

Calculate checksum of an entire packet

##### Synopsis

       unsigned int skb_checksum_complete
       struct sk_buff * skb

##### Arguments

`skb`

  packet to process

##### Description

This function calculates the checksum over the entire packet plus the value of skb->csum. The latter can be used to supply the checksum of a pseudo header as used by TCP/UDP. It returns the checksum.

For protocols that contain complete checksums such as ICMP/TCP/UDP, this function can be used to verify that checksum on received packets. In that case the function should return zero if the checksum is correct. In particular, this function will return zero if skb->ip_summed is CHECKSUM_UNNECESSARY which indicates that the hardware has already verified the correctness of the checksum.

#### LINUX

Kernel Hackers Manual March 2006
struct sock_common
9

#### struct sock_common

minimal network layer representation of sockets

##### Synopsis

    struct sock_common {
      unsigned short skc_family;
      volatile unsigned char skc_state;
      unsigned char skc_reuse;
      int skc_bound_dev_if;
      struct hlist_node skc_node;
      struct hlist_node skc_bind_node;
      atomic_t skc_refcnt;
      unsigned int skc_hash;
      struct proto * skc_prot;
    };

##### Members

skc_family

  network address family

skc_state

  Connection state

skc_reuse

  `SO_REUSEADDR` setting

skc_bound_dev_if

  bound device index if != 0

skc_node

  main hash linkage for various protocol lookup tables

skc_bind_node

  bind hash linkage for various protocol lookup tables

skc_refcnt

  reference count

skc_hash

  hash value used with various protocol lookup tables

skc_prot

  protocol handlers inside a network family

##### Description

This is the minimal network layer representation of sockets, the header for struct sock and struct inet_timewait_sock.

#### LINUX

Kernel Hackers Manual March 2006
struct sock
9

#### struct sock

network layer representation of sockets

##### Synopsis

    struct sock {
      struct sock_common __sk_common;
    #define sk_family		__sk_common.skc_family
    #define sk_state		__sk_common.skc_state
    #define sk_reuse		__sk_common.skc_reuse
    #define sk_bound_dev_if		__sk_common.skc_bound_dev_if
    #define sk_node			__sk_common.skc_node
    #define sk_bind_node		__sk_common.skc_bind_node
    #define sk_refcnt		__sk_common.skc_refcnt
    #define sk_hash			__sk_common.skc_hash
    #define sk_prot			__sk_common.skc_prot
      unsigned char sk_shutdown:2;
      unsigned char sk_no_check:2;
      unsigned char sk_userlocks:4;
      unsigned char sk_protocol;
      unsigned short sk_type;
      int sk_rcvbuf;
      socket_lock_t sk_lock;
      wait_queue_head_t * sk_sleep;
      struct dst_entry * sk_dst_cache;
      struct xfrm_policy * sk_policy[2];
      rwlock_t sk_dst_lock;
      atomic_t sk_rmem_alloc;
      atomic_t sk_wmem_alloc;
      atomic_t sk_omem_alloc;
      struct sk_buff_head sk_receive_queue;
      struct sk_buff_head sk_write_queue;
      int sk_wmem_queued;
      int sk_forward_alloc;
      gfp_t sk_allocation;
      int sk_sndbuf;
      int sk_route_caps;
      unsigned long sk_flags;
      unsigned long sk_lingertime;
      struct sk_backlog;
      struct sk_buff_head sk_error_queue;
      struct proto * sk_prot_creator;
      rwlock_t sk_callback_lock;
      int sk_err;
      int sk_err_soft;
      unsigned short sk_ack_backlog;
      unsigned short sk_max_ack_backlog;
      __u32 sk_priority;
      struct ucred sk_peercred;
      int sk_rcvlowat;
      long sk_rcvtimeo;
      long sk_sndtimeo;
      struct sk_filter * sk_filter;
      void * sk_protinfo;
      struct timer_list sk_timer;
      struct timeval sk_stamp;
      struct socket * sk_socket;
      void * sk_user_data;
      struct page * sk_sndmsg_page;
      struct sk_buff * sk_send_head;
      __u32 sk_sndmsg_off;
      int sk_write_pending;
      void * sk_security;
      void (* sk_state_change) (struct sock *sk);
      void (* sk_data_ready) (struct sock *sk, int bytes);
      void (* sk_write_space) (struct sock *sk);
      void (* sk_error_report) (struct sock *sk);
      int (* sk_backlog_rcv) (struct sock *sk,struct sk_buff *skb);
      void (* sk_destruct) (struct sock *sk);
    };

##### Members

__sk_common

  shared layout with inet_timewait_sock

sk_shutdown

  mask of `SEND_SHUTDOWN` and/or `RCV_SHUTDOWN`

sk_no_check

  `SO_NO_CHECK` setting, wether or not checkup packets

sk_userlocks

  `SO_SNDBUF` and `SO_RCVBUF` settings

sk_protocol

  which protocol this socket belongs in this network family

sk_type

  socket type (`SOCK_STREAM`, etc)

sk_rcvbuf

  size of receive buffer in bytes

sk_lock

  synchronizer

sk_sleep

  sock wait queue

sk_dst_cache

  destination cache

sk_policy[2]

  flow policy

sk_dst_lock

  destination cache lock

sk_rmem_alloc

  receive queue bytes committed

sk_wmem_alloc

  transmit queue bytes committed

sk_omem_alloc

  o is option or other

sk_receive_queue

  incoming packets

sk_write_queue

  Packet sending queue

sk_wmem_queued

  persistent queue size

sk_forward_alloc

  space allocated forward

sk_allocation

  allocation mode

sk_sndbuf

  size of send buffer in bytes

sk_route_caps

  route capabilities (e.g. `NETIF_F_TSO`)

sk_flags

  `SO_LINGER` (l_onoff), `SO_BROADCAST`, `SO_KEEPALIVE`, `SO_OOBINLINE` settings

sk_lingertime

  `SO_LINGER` l_linger setting

sk_backlog

  always used with the per-socket spinlock held

sk_error_queue

  rarely used

sk_prot_creator

  sk_prot of original sock creator (see ipv6_setsockopt, IPV6_ADDRFORM for instance)

sk_callback_lock

  used with the callbacks in the end of this struct

sk_err

  last error

sk_err_soft

  errors that don't cause failure but are the cause of a persistent failure not just 'timed out'

sk_ack_backlog

  current listen backlog

sk_max_ack_backlog

  listen backlog set in `listen`

sk_priority

  `SO_PRIORITY` setting

sk_peercred

  `SO_PEERCRED` setting

sk_rcvlowat

  `SO_RCVLOWAT` setting

sk_rcvtimeo

  `SO_RCVTIMEO` setting

sk_sndtimeo

  `SO_SNDTIMEO` setting

sk_filter

  socket filtering instructions

sk_protinfo

  private area, net family specific, when not using slab

sk_timer

  sock cleanup timer

sk_stamp

  time stamp of last packet received

sk_socket

  Identd and reporting IO signals

sk_user_data

  RPC layer private data

sk_sndmsg_page

  cached page for sendmsg

sk_send_head

  front of stuff to transmit

sk_sndmsg_off

  cached offset for sendmsg

sk_write_pending

  a write to stream socket waits to start

sk_security

  used by security modules

sk_state_change

  callback to indicate change in the state of the sock

sk_data_ready

  callback to indicate there is data to be processed

sk_write_space

  callback to indicate there is bf sending space available

sk_error_report

  callback to indicate errors (e.g. `MSG_ERRQUEUE`)

sk_backlog_rcv

  callback to process the backlog

sk_destruct

  called at sock freeing time, i.e. when all refcnt == 0

#### LINUX

Kernel Hackers Manual March 2006
sk_filter
9

#### sk_filter

run a packet through a socket filter

##### Synopsis

       int sk_filter
       struct sock * sk
       struct sk_buff * skb
       int needlock

##### Arguments

`sk`

  sock associated with &sk_buff

`skb`

  buffer to filter

`needlock`

  set to 1 if the sock is not locked by caller.

##### Description

Run the filter code and then cut skb->data to correct size returned by sk_run_filter. If pkt_len is 0 we toss packet. If skb->len is smaller than pkt_len we keep whole skb->data. This is the socket level wrapper to sk_run_filter. It returns 0 if the packet should be accepted or -EPERM if the packet should be tossed.

#### LINUX

Kernel Hackers Manual March 2006
sk_filter_release
9

#### sk_filter_release

##### Synopsis

       void sk_filter_release
       struct sock * sk
       struct sk_filter * fp

##### Arguments

`sk`

  socket

`fp`

  filter to remove

##### Description

Remove a filter from a socket and release its resources.

#### LINUX

Kernel Hackers Manual March 2006
sk_eat_skb
9

#### sk_eat_skb

Release a skb if it is no longer needed

##### Synopsis

       void sk_eat_skb
       struct sock * sk
       struct sk_buff * skb

##### Arguments

`sk`

  socket to eat this skb from

`skb`

  socket buffer to eat

##### Description

This routine must be called with interrupts disabled or with the socket locked so that the sk_buff queue operation is ok.

#### LINUX

Kernel Hackers Manual March 2006
move_addr_to_kernel
9

#### move_addr_to_kernel

copy a socket address into kernel space

##### Synopsis

       int move_addr_to_kernel
       void __user * uaddr
       int ulen
       void * kaddr

##### Arguments

`uaddr`

  Address in user space

`ulen`

  Length in user space

`kaddr`

  Address in kernel space

##### Description

The address is copied into kernel space. If the provided address is too long an error code of -EINVAL is returned. If the copy gives invalid addresses -EFAULT is returned. On a success 0 is returned.

#### LINUX

Kernel Hackers Manual March 2006
move_addr_to_user
9

#### move_addr_to_user

copy an address to user space

##### Synopsis

       int move_addr_to_user
       void * kaddr
       int klen
       void __user * uaddr
       int __user * ulen

##### Arguments

`kaddr`

  kernel space address

`klen`

  length of address in kernel

`uaddr`

  user space address

`ulen`

  pointer to user length field

##### Description

The value pointed to by ulen on entry is the buffer length available. This is overwritten with the buffer space used. -EINVAL is returned if an overlong buffer is specified or a negative buffer size. -EFAULT is returned if either the buffer or the length field are not accessible. After copying the data up to the limit the user specifies, the true length of the data is written over the length limit the user specified. Zero is returned for a success.

#### LINUX

Kernel Hackers Manual March 2006
sockfd_lookup
9

#### sockfd_lookup

Go from a file number to its socket slot

##### Synopsis

       struct socket * sockfd_lookup
       int fd
       int * err

##### Arguments

`fd`

  file handle

`err`

  pointer to an error code return

##### Description

The file handle passed in is locked and the socket it is bound too is returned. If an error occurs the err pointer is overwritten with a negative errno code and NULL is returned. The function checks for both invalid handles and passing a handle which is not a socket.

On a success the socket object pointer is returned.

#### LINUX

Kernel Hackers Manual March 2006
sock_release
9

#### sock_release

close a socket

##### Synopsis

       void sock_release
       struct socket * sock

##### Arguments

`sock`

  socket to close

##### Description

The socket is released from the protocol stack if it has a release callback, and the inode is then released if the socket is bound to an inode not a file.

#### LINUX

Kernel Hackers Manual March 2006
skb_over_panic
9

#### skb_over_panic

private function

##### Synopsis

       void skb_over_panic
       struct sk_buff * skb
       int sz
       void * here

##### Arguments

`skb`

  buffer

`sz`

  size

`here`

  address

##### Description

Out of line support code for `skb_put`. Not user callable.

#### LINUX

Kernel Hackers Manual March 2006
skb_under_panic
9

#### skb_under_panic

private function

##### Synopsis

       void skb_under_panic
       struct sk_buff * skb
       int sz
       void * here

##### Arguments

`skb`

  buffer

`sz`

  size

`here`

  address

##### Description

Out of line support code for `skb_push`. Not user callable.

#### LINUX

Kernel Hackers Manual March 2006
__alloc_skb
9

#### __alloc_skb

allocate a network buffer

##### Synopsis

       struct sk_buff * __alloc_skb
       unsigned int size
       gfp_t gfp_mask
       int fclone

##### Arguments

`size`

  size to allocate

`gfp_mask`

  allocation mask

`fclone`

  allocate from fclone cache instead of head cache and allocate a cloned (child) skb

##### Description

Allocate a new &sk_buff. The returned buffer has no headroom and a tail room of size bytes. The object has a reference count of one. The return is the buffer. On a failure the return is `NULL`.

Buffers may only be allocated from interrupts using a `gfp_mask` of `GFP_ATOMIC`.

#### LINUX

Kernel Hackers Manual March 2006
__kfree_skb
9

#### __kfree_skb

private function

##### Synopsis

       void __kfree_skb
       struct sk_buff * skb

##### Arguments

`skb`

  buffer

##### Description

Free an sk_buff. Release anything attached to the buffer. Clean the state. This is an internal helper function. Users should always call kfree_skb

#### LINUX

Kernel Hackers Manual March 2006
skb_clone
9

#### skb_clone

duplicate an sk_buff

##### Synopsis

       struct sk_buff * skb_clone
       struct sk_buff * skb
       gfp_t gfp_mask

##### Arguments

`skb`

  buffer to clone

`gfp_mask`

  allocation priority

##### Description

Duplicate an &sk_buff. The new one is not owned by a socket. Both copies share the same packet data but not structure. The new buffer has a reference count of 1. If the allocation fails the function returns `NULL` otherwise the new buffer is returned.

If this function is called from an interrupt `gfp_mask` must be `GFP_ATOMIC`.

#### LINUX

Kernel Hackers Manual March 2006
skb_copy
9

#### skb_copy

create private copy of an sk_buff

##### Synopsis

       struct sk_buff * skb_copy
       const struct sk_buff * skb
       gfp_t gfp_mask

##### Arguments

`skb`

  buffer to copy

`gfp_mask`

  allocation priority

##### Description

Make a copy of both an &sk_buff and its data. This is used when the caller wishes to modify the data and needs a private copy of the data to alter. Returns `NULL` on failure or the pointer to the buffer on success. The returned buffer has a reference count of 1.

As by-product this function converts non-linear &sk_buff to linear one, so that &sk_buff becomes completely private and caller is allowed to modify all the data of returned buffer. This means that this function is not recommended for use in circumstances when only header is going to be modified. Use `pskb_copy` instead.

#### LINUX

Kernel Hackers Manual March 2006
pskb_copy
9

#### pskb_copy

create copy of an sk_buff with private head.

##### Synopsis

       struct sk_buff * pskb_copy
       struct sk_buff * skb
       gfp_t gfp_mask

##### Arguments

`skb`

  buffer to copy

`gfp_mask`

  allocation priority

##### Description

Make a copy of both an &sk_buff and part of its data, located in header. Fragmented data remain shared. This is used when the caller wishes to modify only header of &sk_buff and needs private copy of the header to alter. Returns `NULL` on failure or the pointer to the buffer on success. The returned buffer has a reference count of 1.

#### LINUX

Kernel Hackers Manual March 2006
pskb_expand_head
9

#### pskb_expand_head

reallocate header of &sk_buff

##### Synopsis

       int pskb_expand_head
       struct sk_buff * skb
       int nhead
       int ntail
       gfp_t gfp_mask

##### Arguments

`skb`

  buffer to reallocate

`nhead`

  room to add at head

`ntail`

  room to add at tail

`gfp_mask`

  allocation priority

##### Description

Expands (or creates identical copy, if &nhead and &ntail are zero) header of skb. &sk_buff itself is not changed. &sk_buff MUST have reference count of 1. Returns zero in the case of success or error, if expansion failed. In the last case, &sk_buff is not changed.

All the pointers pointing into skb header may change and must be reloaded after call to this function.

#### LINUX

Kernel Hackers Manual March 2006
skb_copy_expand
9

#### skb_copy_expand

copy and expand sk_buff

##### Synopsis

       struct sk_buff * skb_copy_expand
       const struct sk_buff * skb
       int newheadroom
       int newtailroom
       gfp_t gfp_mask

##### Arguments

`skb`

  buffer to copy

`newheadroom`

  new free bytes at head

`newtailroom`

  new free bytes at tail

`gfp_mask`

  allocation priority

##### Description

Make a copy of both an &sk_buff and its data and while doing so allocate additional space.

This is used when the caller wishes to modify the data and needs a private copy of the data to alter as well as more space for new fields. Returns `NULL` on failure or the pointer to the buffer on success. The returned buffer has a reference count of 1.

You must pass `GFP_ATOMIC` as the allocation priority if this function is called from an interrupt.

##### BUG ALERT

ip_summed is not copied. Why does this work? Is it used only by netfilter in the cases when checksum is recalculated? --ANK

#### LINUX

Kernel Hackers Manual March 2006
skb_pad
9

#### skb_pad

zero pad the tail of an skb

##### Synopsis

       struct sk_buff * skb_pad
       struct sk_buff * skb
       int pad

##### Arguments

`skb`

  buffer to pad

`pad`

  space to pad

##### Description

Ensure that a buffer is followed by a padding area that is zero filled. Used by network drivers which may DMA or transfer data beyond the buffer end onto the wire.

May return NULL in out of memory cases.

#### LINUX

Kernel Hackers Manual March 2006
__pskb_pull_tail
9

#### __pskb_pull_tail

advance tail of skb header

##### Synopsis

       unsigned char * __pskb_pull_tail
       struct sk_buff * skb
       int delta

##### Arguments

`skb`

  buffer to reallocate

`delta`

  number of bytes to advance tail

##### Description

The function makes a sense only on a fragmented &sk_buff, it expands header moving its tail forward and copying necessary data from fragmented part.

&sk_buff MUST have reference count of 1.

Returns `NULL` (and &sk_buff does not change) if pull failed or value of new tail of skb in the case of success.

All the pointers pointing into skb header may change and must be reloaded after call to this function.

#### LINUX

Kernel Hackers Manual March 2006
skb_store_bits
9

#### skb_store_bits

store bits from kernel buffer to skb

##### Synopsis

       int skb_store_bits
       const struct sk_buff * skb
       int offset
       void * from
       int len

##### Arguments

`skb`

  destination buffer

`offset`

  offset in destination

`from`

  source buffer

`len`

  number of bytes to copy

##### Description

Copy the specified number of bytes from the source buffer to the destination skb. This function handles all the messy bits of traversing fragment lists and such.

#### LINUX

Kernel Hackers Manual March 2006
skb_dequeue
9

#### skb_dequeue

remove from the head of the queue

##### Synopsis

       struct sk_buff * skb_dequeue
       struct sk_buff_head * list

##### Arguments

`list`

  list to dequeue from

##### Description

Remove the head of the list. The list lock is taken so the function may be used safely with other locking list functions. The head item is returned or `NULL` if the list is empty.

#### LINUX

Kernel Hackers Manual March 2006
skb_dequeue_tail
9

#### skb_dequeue_tail

remove from the tail of the queue

##### Synopsis

       struct sk_buff * skb_dequeue_tail
       struct sk_buff_head * list

##### Arguments

`list`

  list to dequeue from

##### Description

Remove the tail of the list. The list lock is taken so the function may be used safely with other locking list functions. The tail item is returned or `NULL` if the list is empty.

#### LINUX

Kernel Hackers Manual March 2006
skb_queue_purge
9

#### skb_queue_purge

empty a list

##### Synopsis

       void skb_queue_purge
       struct sk_buff_head * list

##### Arguments

`list`

  list to empty

##### Description

Delete all buffers on an &sk_buff list. Each buffer is removed from the list and one reference dropped. This function takes the list lock and is atomic with respect to other list locking functions.

#### LINUX

Kernel Hackers Manual March 2006
skb_queue_head
9

#### skb_queue_head

queue a buffer at the list head

##### Synopsis

       void skb_queue_head
       struct sk_buff_head * list
       struct sk_buff * newsk

##### Arguments

`list`

  list to use

`newsk`

  buffer to queue

##### Description

Queue a buffer at the start of the list. This function takes the list lock and can be used safely with other locking &sk_buff functions safely.

A buffer cannot be placed on two lists at the same time.

#### LINUX

Kernel Hackers Manual March 2006
skb_queue_tail
9

#### skb_queue_tail

queue a buffer at the list tail

##### Synopsis

       void skb_queue_tail
       struct sk_buff_head * list
       struct sk_buff * newsk

##### Arguments

`list`

  list to use

`newsk`

  buffer to queue

##### Description

Queue a buffer at the tail of the list. This function takes the list lock and can be used safely with other locking &sk_buff functions safely.

A buffer cannot be placed on two lists at the same time.

#### LINUX

Kernel Hackers Manual March 2006
skb_unlink
9

#### skb_unlink

remove a buffer from a list

##### Synopsis

       void skb_unlink
       struct sk_buff * skb
       struct sk_buff_head * list

##### Arguments

`skb`

  buffer to remove

`list`

  list to use

##### Description

Remove a packet from a list. The list locks are taken and this function is atomic with respect to other list locked calls

You must know what list the SKB is on.

#### LINUX

Kernel Hackers Manual March 2006
skb_append
9

#### skb_append

append a buffer

##### Synopsis

       void skb_append
       struct sk_buff * old
       struct sk_buff * newsk
       struct sk_buff_head * list

##### Arguments

`old`

  buffer to insert after

`newsk`

  buffer to insert

`list`

  list to use

##### Description

Place a packet after a given packet in a list. The list locks are taken and this function is atomic with respect to other list locked calls. A buffer cannot be placed on two lists at the same time.

#### LINUX

Kernel Hackers Manual March 2006
skb_insert
9

#### skb_insert

insert a buffer

##### Synopsis

       void skb_insert
       struct sk_buff * old
       struct sk_buff * newsk
       struct sk_buff_head * list

##### Arguments

`old`

  buffer to insert before

`newsk`

  buffer to insert

`list`

  list to use

##### Description

Place a packet before a given packet in a list. The list locks are taken and this function is atomic with respect to other list locked calls.

A buffer cannot be placed on two lists at the same time.

#### LINUX

Kernel Hackers Manual March 2006
skb_split
9

#### skb_split

Split fragmented skb to two parts at length len.

##### Synopsis

       void skb_split
       struct sk_buff * skb
       struct sk_buff * skb1
       const u32 len

##### Arguments

`skb`

  the buffer to split

`skb1`

  the buffer to receive the second part

`len`

  new length for skb

#### LINUX

Kernel Hackers Manual March 2006
skb_prepare_seq_read
9

#### skb_prepare_seq_read

Prepare a sequential read of skb data

##### Synopsis

       void skb_prepare_seq_read
       struct sk_buff * skb
       unsigned int from
       unsigned int to
       struct skb_seq_state * st

##### Arguments

`skb`

  the buffer to read

`from`

  lower offset of data to be read

`to`

  upper offset of data to be read

`st`

  state variable

##### Description

Initializes the specified state variable. Must be called before invoking `skb_seq_read` for the first time.

#### LINUX

Kernel Hackers Manual March 2006
skb_seq_read
9

#### skb_seq_read

Sequentially read skb data

##### Synopsis

       unsigned int skb_seq_read
       unsigned int consumed
       const u8 ** data
       struct skb_seq_state * st

##### Arguments

`consumed`

  number of bytes consumed by the caller so far

`data`

  destination pointer for data to be returned

`st`

  state variable

##### Description

Reads a block of skb data at &consumed relative to the lower offset specified to `skb_prepare_seq_read`. Assigns the head of the data block to &data and returns the length of the block or 0 if the end of the skb data or the upper offset has been reached.

The caller is not required to consume all of the data returned, i.e. &consumed is typically set to the number of bytes already consumed and the next call to `skb_seq_read` will return the remaining part of the block.

##### Note

Fragment lists within fragments are not implemented at the moment, state->root_skb could be replaced with a stack for this purpose.

##### Note

Fragment lists within fragments are not implemented at the moment, state->root_skb could be replaced with a stack for this purpose.

#### LINUX

Kernel Hackers Manual March 2006
skb_abort_seq_read
9

#### skb_abort_seq_read

Abort a sequential read of skb data

##### Synopsis

       void skb_abort_seq_read
       struct skb_seq_state * st

##### Arguments

`st`

  state variable

##### Description

Must be called if `skb_seq_read` was not called until it returned 0.

#### LINUX

Kernel Hackers Manual March 2006
skb_find_text
9

#### skb_find_text

Find a text pattern in skb data

##### Synopsis

       unsigned int skb_find_text
       struct sk_buff * skb
       unsigned int from
       unsigned int to
       struct ts_config * config
       struct ts_state * state

##### Arguments

`skb`

  the buffer to look in

`from`

  search offset

`to`

  search limit

`config`

  textsearch configuration

`state`

  uninitialized textsearch state variable

##### Description

Finds a pattern in the skb data according to the specified textsearch configuration. Use `textsearch_next` to retrieve subsequent occurrences of the pattern. Returns the offset to the first occurrence or UINT_MAX if no match was found.

#### LINUX

Kernel Hackers Manual March 2006
skb_append_datato_frags
9

#### skb_append_datato_frags

append the user data to a skb

##### Synopsis

       int skb_append_datato_frags
       struct sock * sk
       struct sk_buff * skb
       int (*getfrag)
         void *from, char *to, int offset, 					int len, int odd, struct sk_buff *skb
       void * from
       int length

##### Arguments

`sk`

  sock structure

`skb`

  skb structure to be appened with user data.

`getfrag`

  call back function to be used for getting the user data

`from`

  pointer to user message iov

`length`

  length of the iov message

##### Description

This procedure append the user data in the fragment part of the skb if any page alloc fails user this procedure returns -ENOMEM

#### LINUX

Kernel Hackers Manual March 2006
sk_alloc
9

#### sk_alloc

All socket objects are allocated here

##### Synopsis

       struct sock * sk_alloc
       int family
       gfp_t priority
       struct proto * prot
       int zero_it

##### Arguments

`family`

  protocol family

`priority`

  for allocation (`GFP_KERNEL`, `GFP_ATOMIC`, etc)

`prot`

  struct proto associated with this new sock instance

`zero_it`

  if we should zero the newly allocated sock

#### LINUX

Kernel Hackers Manual March 2006
sk_wait_data
9

#### sk_wait_data

wait for data to arrive at sk_receive_queue

##### Synopsis

       int sk_wait_data
       struct sock * sk
       long * timeo

##### Arguments

`sk`

  sock to wait on

`timeo`

  for how long

##### Description

Now socket state including sk->sk_err is changed only under lock, hence we may omit checks after joining wait queue. We check receive queue before `schedule` only as optimization; it is very likely that `release_sock` added new data.

#### LINUX

Kernel Hackers Manual March 2006
skb_recv_datagram
9

#### skb_recv_datagram

Receive a datagram skbuff

##### Synopsis

       struct sk_buff * skb_recv_datagram
       struct sock * sk
       unsigned flags
       int noblock
       int * err

##### Arguments

`sk`

  socket

`flags`

  MSG_ flags

`noblock`

  blocking operation?

`err`

  error code returned

##### Description

Get a datagram skbuff, understands the peeking, nonblocking wakeups and possible races. This replaces identical code in packet, raw and udp, as well as the IPX AX.25 and Appletalk. It also finally fixes the long standing peek and read race for datagram sockets. If you alter this routine remember it must be re-entrant.

This function will lock the socket if a skb is returned, so the caller needs to unlock the socket in that case (usually by calling skb_free_datagram)

* It does not lock socket since today. This function is * free of race conditions. This measure should/can improve * significantly datagram socket latencies at high loads, * when data copying to user space takes lots of time. * (BTW I've just killed the last `cli` in IP/IPv6/core/netlink/packet * 8) Great win.) * --ANK (980729)

The order of the tests when we find no data waiting are specified quite explicitly by POSIX 1003.1g, don't change them without having the standard around please.

#### LINUX

Kernel Hackers Manual March 2006
skb_kill_datagram
9

#### skb_kill_datagram

Free a datagram skbuff forcibly

##### Synopsis

       void skb_kill_datagram
       struct sock * sk
       struct sk_buff * skb
       unsigned int flags

##### Arguments

`sk`

  socket

`skb`

  datagram skbuff

`flags`

  MSG_ flags

##### Description

This function frees a datagram skbuff that was received by skb_recv_datagram. The flags argument must match the one used for skb_recv_datagram.

If the MSG_PEEK flag is set, and the packet is still on the receive queue of the socket, it will be taken off the queue before it is freed.

This function currently only disables BH when acquiring the sk_receive_queue lock. Therefore it must not be used in a context where that lock is acquired in an IRQ context.

#### LINUX

Kernel Hackers Manual March 2006
skb_copy_datagram_iovec
9

#### skb_copy_datagram_iovec

Copy a datagram to an iovec.

##### Synopsis

       int skb_copy_datagram_iovec
       const struct sk_buff * skb
       int offset
       struct iovec * to
       int len

##### Arguments

`skb`

  buffer to copy

`offset`

  offset in the buffer to start copying from

`to`

  io vector to copy to

`len`

  amount of data to copy from buffer to iovec

##### Note

the iovec is modified during the copy.

#### LINUX

Kernel Hackers Manual March 2006
skb_copy_and_csum_datagram_iovec
9

#### skb_copy_and_csum_datagram_iovec

Copy and checkum skb to user iovec.

##### Synopsis

       int skb_copy_and_csum_datagram_iovec
       struct sk_buff * skb
       int hlen
       struct iovec * iov

##### Arguments

`skb`

  skbuff

`hlen`

  hardware length

`iov`

  io vector

##### Description

Caller _must_ check that skb will fit to this iovec.

##### Returns

0 - success. -EINVAL - checksum failure. -EFAULT - fault during copy. Beware, in this case iovec can be modified!

#### LINUX

Kernel Hackers Manual March 2006
datagram_poll
9

#### datagram_poll

generic datagram poll

##### Synopsis

       unsigned int datagram_poll
       struct file * file
       struct socket * sock
       poll_table * wait

##### Arguments

`file`

  file struct

`sock`

  socket

`wait`

  poll table

##### Datagram poll

Again totally generic. This also handles sequenced packet sockets providing the socket receive queue is only ever holding data ready to receive.

##### Note

when you _don't_ use this routine for this protocol, and you use a different write policy from `sock_writeable` then please supply your own write_space callback.

#### LINUX

Kernel Hackers Manual March 2006
sk_stream_write_space
9

#### sk_stream_write_space

stream socket write_space callback.

##### Synopsis

       void sk_stream_write_space
       struct sock * sk

##### Arguments

`sk`

  socket

##### FIXME

write proper description

#### LINUX

Kernel Hackers Manual March 2006
sk_stream_wait_connect
9

#### sk_stream_wait_connect

Wait for a socket to get into the connected state

##### Synopsis

       int sk_stream_wait_connect
       struct sock * sk
       long * timeo_p

##### Arguments

`sk`

  sock to wait on

`timeo_p`

  for how long to wait

##### Description

Must be called with the socket locked.

#### LINUX

Kernel Hackers Manual March 2006
sk_stream_wait_memory
9

#### sk_stream_wait_memory

Wait for more memory for a socket

##### Synopsis

       int sk_stream_wait_memory
       struct sock * sk
       long * timeo_p

##### Arguments

`sk`

  socket to wait for memory

`timeo_p`

  for how long

### Socket Filter

#### LINUX

Kernel Hackers Manual March 2006
sk_run_filter
9

#### sk_run_filter

run a filter on a socket

##### Synopsis

       unsigned int sk_run_filter
       struct sk_buff * skb
       struct sock_filter * filter
       int flen

##### Arguments

`skb`

  buffer to run the filter on

`filter`

  filter to apply

`flen`

  length of filter

##### Description

Decode and apply filter instructions to the skb->data. Return length to keep, 0 for none. skb is the data we are filtering, filter is the array of filter instructions, and len is the number of filter blocks in the array.

#### LINUX

Kernel Hackers Manual March 2006
sk_chk_filter
9

#### sk_chk_filter

verify socket filter code

##### Synopsis

       int sk_chk_filter
       struct sock_filter * filter
       int flen

##### Arguments

`filter`

  filter to verify

`flen`

  length of filter

##### Description

Check the user's filter code. If we let some ugly filter code slip through kaboom! The filter must contain no references or jumps that are out of range, no illegal instructions, and must end with a RET instruction.

All jumps are forward as they are not signed.

Returns 0 if the rule set is legal or -EINVAL if not.

### Generic Network Statistics

#### LINUX

Kernel Hackers Manual March 2006
struct gnet_stats_basic
9

#### struct gnet_stats_basic

byte/packet throughput statistics

##### Synopsis

    struct gnet_stats_basic {
      __u64 bytes;
      __u32 packets;
    };

##### Members

bytes

  number of seen bytes

packets

  number of seen packets

#### LINUX

Kernel Hackers Manual March 2006
struct gnet_stats_rate_est
9

#### struct gnet_stats_rate_est

rate estimator

##### Synopsis

    struct gnet_stats_rate_est {
      __u32 bps;
      __u32 pps;
    };

##### Members

bps

  current byte rate

pps

  current packet rate

#### LINUX

Kernel Hackers Manual March 2006
struct gnet_stats_queue
9

#### struct gnet_stats_queue

queuing statistics

##### Synopsis

    struct gnet_stats_queue {
      __u32 qlen;
      __u32 backlog;
      __u32 drops;
      __u32 requeues;
      __u32 overlimits;
    };

##### Members

qlen

  queue length

backlog

  backlog size of queue

drops

  number of dropped packets

requeues

  number of requeues

overlimits

  number of enqueues over the limit

#### LINUX

Kernel Hackers Manual March 2006
struct gnet_estimator
9

#### struct gnet_estimator

rate estimator configuration

##### Synopsis

    struct gnet_estimator {
      signed char interval;
      unsigned char ewma_log;
    };

##### Members

interval

  sampling period

ewma_log

  the log of measurement window weight

#### LINUX

Kernel Hackers Manual March 2006
gnet_stats_start_copy_compat
9

#### gnet_stats_start_copy_compat

start dumping procedure in compatibility mode

##### Synopsis

       int gnet_stats_start_copy_compat
       struct sk_buff * skb
       int type
       int tc_stats_type
       int xstats_type
       spinlock_t * lock
       struct gnet_dump * d

##### Arguments

`skb`

  socket buffer to put statistics TLVs into

`type`

  TLV type for top level statistic TLV

`tc_stats_type`

  TLV type for backward compatibility struct tc_stats TLV

`xstats_type`

  TLV type for backward compatibility xstats TLV

`lock`

  statistics lock

`d`

  dumping handle

##### Description

Initializes the dumping handle, grabs the statistic lock and appends an empty TLV header to the socket buffer for use a container for all other statistic TLVS.

The dumping handle is marked to be in backward compatibility mode telling all `gnet_stats_copy_XXX` functions to fill a local copy of struct tc_stats.

Returns 0 on success or -1 if the room in the socket buffer was not sufficient.

#### LINUX

Kernel Hackers Manual March 2006
gnet_stats_start_copy
9

#### gnet_stats_start_copy

start dumping procedure in compatibility mode

##### Synopsis

       int gnet_stats_start_copy
       struct sk_buff * skb
       int type
       spinlock_t * lock
       struct gnet_dump * d

##### Arguments

`skb`

  socket buffer to put statistics TLVs into

`type`

  TLV type for top level statistic TLV

`lock`

  statistics lock

`d`

  dumping handle

##### Description

Initializes the dumping handle, grabs the statistic lock and appends an empty TLV header to the socket buffer for use a container for all other statistic TLVS.

Returns 0 on success or -1 if the room in the socket buffer was not sufficient.

#### LINUX

Kernel Hackers Manual March 2006
gnet_stats_copy_basic
9

#### gnet_stats_copy_basic

copy basic statistics into statistic TLV

##### Synopsis

       int gnet_stats_copy_basic
       struct gnet_dump * d
       struct gnet_stats_basic * b

##### Arguments

`d`

  dumping handle

`b`

  basic statistics

##### Description

Appends the basic statistics to the top level TLV created by `gnet_stats_start_copy`.

Returns 0 on success or -1 with the statistic lock released if the room in the socket buffer was not sufficient.

#### LINUX

Kernel Hackers Manual March 2006
gnet_stats_copy_rate_est
9

#### gnet_stats_copy_rate_est

copy rate estimator statistics into statistics TLV

##### Synopsis

       int gnet_stats_copy_rate_est
       struct gnet_dump * d
       struct gnet_stats_rate_est * r

##### Arguments

`d`

  dumping handle

`r`

  rate estimator statistics

##### Description

Appends the rate estimator statistics to the top level TLV created by `gnet_stats_start_copy`.

Returns 0 on success or -1 with the statistic lock released if the room in the socket buffer was not sufficient.

#### LINUX

Kernel Hackers Manual March 2006
gnet_stats_copy_queue
9

#### gnet_stats_copy_queue

copy queue statistics into statistics TLV

##### Synopsis

       int gnet_stats_copy_queue
       struct gnet_dump * d
       struct gnet_stats_queue * q

##### Arguments

`d`

  dumping handle

`q`

  queue statistics

##### Description

Appends the queue statistics to the top level TLV created by `gnet_stats_start_copy`.

Returns 0 on success or -1 with the statistic lock released if the room in the socket buffer was not sufficient.

#### LINUX

Kernel Hackers Manual March 2006
gnet_stats_copy_app
9

#### gnet_stats_copy_app

copy application specific statistics into statistics TLV

##### Synopsis

       int gnet_stats_copy_app
       struct gnet_dump * d
       void * st
       int len

##### Arguments

`d`

  dumping handle

`st`

  application specific statistics data

`len`

  length of data

##### Description

Appends the application sepecific statistics to the top level TLV created by `gnet_stats_start_copy` and remembers the data for XSTATS if the dumping handle is in backward compatibility mode.

Returns 0 on success or -1 with the statistic lock released if the room in the socket buffer was not sufficient.

#### LINUX

Kernel Hackers Manual March 2006
gnet_stats_finish_copy
9

#### gnet_stats_finish_copy

finish dumping procedure

##### Synopsis

       int gnet_stats_finish_copy
       struct gnet_dump * d

##### Arguments

`d`

  dumping handle

##### Description

Corrects the length of the top level TLV to include all TLVs added by `gnet_stats_copy_XXX` calls. Adds the backward compatibility TLVs if `gnet_stats_start_copy_compat` was used and releases the statistics lock.

Returns 0 on success or -1 with the statistic lock released if the room in the socket buffer was not sufficient.

#### LINUX

Kernel Hackers Manual March 2006
gen_new_estimator
9

#### gen_new_estimator

create a new rate estimator

##### Synopsis

       int gen_new_estimator
       struct gnet_stats_basic * bstats
       struct gnet_stats_rate_est * rate_est
       spinlock_t * stats_lock
       struct rtattr * opt

##### Arguments

`bstats`

  basic statistics

`rate_est`

  rate estimator statistics

`stats_lock`

  statistics lock

`opt`

  rate estimator configuration TLV

##### Description

Creates a new rate estimator with &bstats as source and &rate_est as destination. A new timer with the interval specified in the configuration TLV is created. Upon each interval, the latest statistics will be read from &bstats and the estimated rate will be stored in &rate_est with the statistics lock grabed during this period.

Returns 0 on success or a negative error code.

#### LINUX

Kernel Hackers Manual March 2006
gen_kill_estimator
9

#### gen_kill_estimator

remove a rate estimator

##### Synopsis

       void gen_kill_estimator
       struct gnet_stats_basic * bstats
       struct gnet_stats_rate_est * rate_est

##### Arguments

`bstats`

  basic statistics

`rate_est`

  rate estimator statistics

##### Description

Removes the rate estimator specified by &bstats and &rate_est and deletes the timer.

#### LINUX

Kernel Hackers Manual March 2006
gen_replace_estimator
9

#### gen_replace_estimator

replace rate estimator configruation

##### Synopsis

       int gen_replace_estimator
       struct gnet_stats_basic * bstats
       struct gnet_stats_rate_est * rate_est
       spinlock_t * stats_lock
       struct rtattr * opt

##### Arguments

`bstats`

  basic statistics

`rate_est`

  rate estimator statistics

`stats_lock`

  statistics lock

`opt`

  rate estimator configuration TLV

##### Description

Replaces the configuration of a rate estimator by calling `gen_kill_estimator` and `gen_new_estimator`.

Returns 0 on success or a negative error code.

### SUN RPC subsystem

#### LINUX

Kernel Hackers Manual March 2006
xdr_encode_opaque_fixed
9

#### xdr_encode_opaque_fixed

Encode fixed length opaque data

##### Synopsis

       u32 * xdr_encode_opaque_fixed
       u32 * p
       const void * ptr
       unsigned int nbytes

##### Arguments

`p`

  pointer to current position in XDR buffer.

`ptr`

  pointer to data to encode (or NULL)

`nbytes`

  size of data.

##### Description

Copy the array of data of length nbytes at ptr to the XDR buffer at position p, then align to the next 32-bit boundary by padding with zero bytes (see RFC1832).

##### Note

if ptr is NULL, only the padding is performed.

Returns the updated current XDR buffer position

#### LINUX

Kernel Hackers Manual March 2006
xdr_encode_opaque
9

#### xdr_encode_opaque

Encode variable length opaque data

##### Synopsis

       u32 * xdr_encode_opaque
       u32 * p
       const void * ptr
       unsigned int nbytes

##### Arguments

`p`

  pointer to current position in XDR buffer.

`ptr`

  pointer to data to encode (or NULL)

`nbytes`

  size of data.

##### Description

Returns the updated current XDR buffer position

#### LINUX

Kernel Hackers Manual March 2006
xdr_init_encode
9

#### xdr_init_encode

Initialize a struct xdr_stream for sending data.

##### Synopsis

       void xdr_init_encode
       struct xdr_stream * xdr
       struct xdr_buf * buf
       uint32_t * p

##### Arguments

`xdr`

  pointer to xdr_stream struct

`buf`

  pointer to XDR buffer in which to encode data

`p`

  current pointer inside XDR buffer

##### Note

at the moment the RPC client only passes the length of our scratch buffer in the xdr_buf's header kvec. Previously this meant we needed to call `xdr_adjust_iovec` after encoding the data. With the new scheme, the xdr_stream manages the details of the buffer length, and takes care of adjusting the kvec length for us.

#### LINUX

Kernel Hackers Manual March 2006
xdr_reserve_space
9

#### xdr_reserve_space

Reserve buffer space for sending

##### Synopsis

       uint32_t * xdr_reserve_space
       struct xdr_stream * xdr
       size_t nbytes

##### Arguments

`xdr`

  pointer to xdr_stream

`nbytes`

  number of bytes to reserve

##### Description

Checks that we have enough buffer space to encode 'nbytes' more bytes of data. If so, update the total xdr_buf length, and adjust the length of the current kvec.

#### LINUX

Kernel Hackers Manual March 2006
xdr_write_pages
9

#### xdr_write_pages

Insert a list of pages into an XDR buffer for sending

##### Synopsis

       void xdr_write_pages
       struct xdr_stream * xdr
       struct page ** pages
       unsigned int base
       unsigned int len

##### Arguments

`xdr`

  pointer to xdr_stream

`pages`

  list of pages

`base`

  offset of first byte

`len`

  length of data in bytes

#### LINUX

Kernel Hackers Manual March 2006
xdr_init_decode
9

#### xdr_init_decode

Initialize an xdr_stream for decoding data.

##### Synopsis

       void xdr_init_decode
       struct xdr_stream * xdr
       struct xdr_buf * buf
       uint32_t * p

##### Arguments

`xdr`

  pointer to xdr_stream struct

`buf`

  pointer to XDR buffer from which to decode data

`p`

  current pointer inside XDR buffer

#### LINUX

Kernel Hackers Manual March 2006
xdr_inline_decode
9

#### xdr_inline_decode

Retrieve non-page XDR data to decode

##### Synopsis

       uint32_t * xdr_inline_decode
       struct xdr_stream * xdr
       size_t nbytes

##### Arguments

`xdr`

  pointer to xdr_stream struct

`nbytes`

  number of bytes of data to decode

##### Description

Check if the input buffer is long enough to enable us to decode 'nbytes' more bytes of data starting at the current position. If so return the current pointer, then update the current pointer position.

#### LINUX

Kernel Hackers Manual March 2006
xdr_read_pages
9

#### xdr_read_pages

Ensure page-based XDR data to decode is aligned at current pointer position

##### Synopsis

       void xdr_read_pages
       struct xdr_stream * xdr
       unsigned int len

##### Arguments

`xdr`

  pointer to xdr_stream struct

`len`

  number of bytes of page data

##### Description

Moves data beyond the current pointer position from the XDR head[] buffer into the page list. Any data that lies beyond current position + len bytes is moved into the XDR tail[]. The current pointer is then repositioned at the beginning of the XDR tail.

#### LINUX

Kernel Hackers Manual March 2006
svc_reserve
9

#### svc_reserve

change the space reserved for the reply to a request.

##### Synopsis

       void svc_reserve
       struct svc_rqst * rqstp
       int space

##### Arguments

`rqstp`

  The request in question

`space`

  new max space to reserve

##### Description

Each request reserves some space on the output queue of the socket to make sure the reply fits. This function reduces that reserved space to be the amount of space used already, plus `space`.

#### LINUX

Kernel Hackers Manual March 2006
rpc_wake_up
9

#### rpc_wake_up

wake up all rpc_tasks

##### Synopsis

       void rpc_wake_up
       struct rpc_wait_queue * queue

##### Arguments

`queue`

  rpc_wait_queue on which the tasks are sleeping

##### Description

Grabs queue->lock

#### LINUX

Kernel Hackers Manual March 2006
rpc_wake_up_status
9

#### rpc_wake_up_status

wake up all rpc_tasks and set their status value.

##### Synopsis

       void rpc_wake_up_status
       struct rpc_wait_queue * queue
       int status

##### Arguments

`queue`

  rpc_wait_queue on which the tasks are sleeping

`status`

  status value to set

##### Description

Grabs queue->lock

#### LINUX

Kernel Hackers Manual March 2006
rpc_run_task
9

#### rpc_run_task

Allocate a new RPC task, then run rpc_execute against it

##### Synopsis

       struct rpc_task * rpc_run_task
       struct rpc_clnt * clnt
       int flags
       const struct rpc_call_ops * ops
       void * data

##### Arguments

`clnt`

  pointer to RPC client

`flags`

  RPC flags

`ops`

  RPC call ops

`data`

  user call data

## Network device support

### Driver Support

#### LINUX

Kernel Hackers Manual March 2006
dev_add_pack
9

#### dev_add_pack

add packet handler

##### Synopsis

       void dev_add_pack
       struct packet_type * pt

##### Arguments

`pt`

  packet type declaration

##### Description

Add a protocol handler to the networking stack. The passed &packet_type is linked into kernel lists and may not be freed until it has been removed from the kernel lists.

This call does not sleep therefore it can not guarantee all CPU's that are in middle of receiving packets will see the new packet type (until the next received packet).

#### LINUX

Kernel Hackers Manual March 2006
__dev_remove_pack
9

#### __dev_remove_pack

remove packet handler

##### Synopsis

       void __dev_remove_pack
       struct packet_type * pt

##### Arguments

`pt`

  packet type declaration

##### Description

Remove a protocol handler that was previously added to the kernel protocol handlers by `dev_add_pack`. The passed &packet_type is removed from the kernel lists and can be freed or reused once this function returns.

The packet type might still be in use by receivers and must not be freed until after all the CPU's have gone through a quiescent state.

#### LINUX

Kernel Hackers Manual March 2006
dev_remove_pack
9

#### dev_remove_pack

remove packet handler

##### Synopsis

       void dev_remove_pack
       struct packet_type * pt

##### Arguments

`pt`

  packet type declaration

##### Description

Remove a protocol handler that was previously added to the kernel protocol handlers by `dev_add_pack`. The passed &packet_type is removed from the kernel lists and can be freed or reused once this function returns.

This call sleeps to guarantee that no CPU is looking at the packet type after return.

#### LINUX

Kernel Hackers Manual March 2006
netdev_boot_setup_check
9

#### netdev_boot_setup_check

check boot time settings

##### Synopsis

       int netdev_boot_setup_check
       struct net_device * dev

##### Arguments

`dev`

  the netdevice

##### Description

Check boot time settings for the device. The found settings are set for the device to be used later in the device probing. Returns 0 if no settings found, 1 if they are.

#### LINUX

Kernel Hackers Manual March 2006
__dev_get_by_name
9

#### __dev_get_by_name

find a device by its name

##### Synopsis

       struct net_device * __dev_get_by_name
       const char * name

##### Arguments

`name`

  name to find

##### Description

Find an interface by name. Must be called under RTNL semaphore or `dev_base_lock`. If the name is found a pointer to the device is returned. If the name is not found then `NULL` is returned. The reference counters are not incremented so the caller must be careful with locks.

#### LINUX

Kernel Hackers Manual March 2006
dev_get_by_name
9

#### dev_get_by_name

find a device by its name

##### Synopsis

       struct net_device * dev_get_by_name
       const char * name

##### Arguments

`name`

  name to find

##### Description

Find an interface by name. This can be called from any context and does its own locking. The returned handle has the usage count incremented and the caller must use `dev_put` to release it when it is no longer needed. `NULL` is returned if no matching device is found.

#### LINUX

Kernel Hackers Manual March 2006
__dev_get_by_index
9

#### __dev_get_by_index

find a device by its ifindex

##### Synopsis

       struct net_device * __dev_get_by_index
       int ifindex

##### Arguments

`ifindex`

  index of device

##### Description

Search for an interface by index. Returns `NULL` if the device is not found or a pointer to the device. The device has not had its reference counter increased so the caller must be careful about locking. The caller must hold either the RTNL semaphore or `dev_base_lock`.

#### LINUX

Kernel Hackers Manual March 2006
dev_get_by_index
9

#### dev_get_by_index

find a device by its ifindex

##### Synopsis

       struct net_device * dev_get_by_index
       int ifindex

##### Arguments

`ifindex`

  index of device

##### Description

Search for an interface by index. Returns NULL if the device is not found or a pointer to the device. The device returned has had a reference added and the pointer is safe until the user calls dev_put to indicate they have finished with it.

#### LINUX

Kernel Hackers Manual March 2006
dev_getbyhwaddr
9

#### dev_getbyhwaddr

find a device by its hardware address

##### Synopsis

       struct net_device * dev_getbyhwaddr
       unsigned short type
       char * ha

##### Arguments

`type`

  media type of device

`ha`

  hardware address

##### Description

Search for an interface by MAC address. Returns NULL if the device is not found or a pointer to the device. The caller must hold the rtnl semaphore. The returned device has not had its ref count increased and the caller must therefore be careful about locking

##### BUGS

If the API was consistent this would be __dev_get_by_hwaddr

#### LINUX

Kernel Hackers Manual March 2006
dev_get_by_flags
9

#### dev_get_by_flags

find any device with given flags

##### Synopsis

       struct net_device * dev_get_by_flags
       unsigned short if_flags
       unsigned short mask

##### Arguments

`if_flags`

  IFF_* values

`mask`

  bitmask of bits in if_flags to check

##### Description

Search for any interface with the given flags. Returns NULL if a device is not found or a pointer to the device. The device returned has had a reference added and the pointer is safe until the user calls dev_put to indicate they have finished with it.

#### LINUX

Kernel Hackers Manual March 2006
dev_valid_name
9

#### dev_valid_name

check if name is okay for network device

##### Synopsis

       int dev_valid_name
       const char * name

##### Arguments

`name`

  name string

##### Description

Network device names need to be valid file names to to allow sysfs to work

#### LINUX

Kernel Hackers Manual March 2006
dev_alloc_name
9

#### dev_alloc_name

allocate a name for a device

##### Synopsis

       int dev_alloc_name
       struct net_device * dev
       const char * name

##### Arguments

`dev`

  device

`name`

  name format string

##### Description

Passed a format string - eg lt`d` it will try and find a suitable id. Not efficient for many devices, not called a lot. The caller must hold the dev_base or rtnl lock while allocating the name and adding the device in order to avoid duplicates. Returns the number of the unit assigned or a negative errno code.

#### LINUX

Kernel Hackers Manual March 2006
netdev_features_change
9

#### netdev_features_change

device changes fatures

##### Synopsis

       void netdev_features_change
       struct net_device * dev

##### Arguments

`dev`

  device to cause notification

##### Description

Called to indicate a device has changed features.

#### LINUX

Kernel Hackers Manual March 2006
netdev_state_change
9

#### netdev_state_change

device changes state

##### Synopsis

       void netdev_state_change
       struct net_device * dev

##### Arguments

`dev`

  device to cause notification

##### Description

Called to indicate a device has changed state. This function calls the notifier chains for netdev_chain and sends a NEWLINK message to the routing socket.

#### LINUX

Kernel Hackers Manual March 2006
dev_load
9

#### dev_load

load a network module

##### Synopsis

       void dev_load
       const char * name

##### Arguments

`name`

  name of interface

##### Description

If a network interface is not present and the process has suitable privileges this function loads the module. If module loading is not available in this kernel then it becomes a nop.

#### LINUX

Kernel Hackers Manual March 2006
dev_open
9

#### dev_open

prepare an interface for use.

##### Synopsis

       int dev_open
       struct net_device * dev

##### Arguments

`dev`

  device to open

##### Description

Takes a device from down to up state. The device's private open function is invoked and then the multicast lists are loaded. Finally the device is moved into the up state and a `NETDEV_UP` message is sent to the netdev notifier chain.

Calling this function on an active interface is a nop. On a failure a negative errno code is returned.

#### LINUX

Kernel Hackers Manual March 2006
dev_close
9

#### dev_close

shutdown an interface.

##### Synopsis

       int dev_close
       struct net_device * dev

##### Arguments

`dev`

  device to shutdown

##### Description

This function moves an active device into down state. A `NETDEV_GOING_DOWN` is sent to the netdev notifier chain. The device is then deactivated and finally a `NETDEV_DOWN` is sent to the notifier chain.

#### LINUX

Kernel Hackers Manual March 2006
register_netdevice_notifier
9

#### register_netdevice_notifier

register a network notifier block

##### Synopsis

       int register_netdevice_notifier
       struct notifier_block * nb

##### Arguments

`nb`

  notifier

##### Description

Register a notifier to be called when network device events occur. The notifier passed is linked into the kernel structures and must not be reused until it has been unregistered. A negative errno code is returned on a failure.

When registered all registration and up events are replayed to the new notifier to allow device to have a race free view of the network device list.

#### LINUX

Kernel Hackers Manual March 2006
unregister_netdevice_notifier
9

#### unregister_netdevice_notifier

unregister a network notifier block

##### Synopsis

       int unregister_netdevice_notifier
       struct notifier_block * nb

##### Arguments

`nb`

  notifier

##### Description

Unregister a notifier previously registered by `register_netdevice_notifier`. The notifier is unlinked into the kernel structures and may then be reused. A negative errno code is returned on a failure.

#### LINUX

Kernel Hackers Manual March 2006
dev_queue_xmit
9

#### dev_queue_xmit

transmit a buffer

##### Synopsis

       int dev_queue_xmit
       struct sk_buff * skb

##### Arguments

`skb`

  buffer to transmit

##### Description

Queue a buffer for transmission to a network device. The caller must have set the device and priority and built the buffer before calling this function. The function can be called from an interrupt.

A negative errno code is returned on a failure. A success does not guarantee the frame will be transmitted as it may be dropped due to congestion or traffic shaping.

----------------------------------------------------------------------------------- I notice this method can also return errors from the queue disciplines, including NET_XMIT_DROP, which is a positive value. So, errors can also be positive.

Regardless of the return value, the skb is consumed, so it is currently difficult to retry a send to this method. (You can bump the ref count before sending to hold a reference for retry if you are careful.)

When calling this method, interrupts MUST be enabled. This is because the BH enable code must have IRQs enabled so that it will not deadlock. --BLG

#### LINUX

Kernel Hackers Manual March 2006
netif_rx
9

#### netif_rx

post buffer to the network code

##### Synopsis

       int netif_rx
       struct sk_buff * skb

##### Arguments

`skb`

  buffer to post

##### Description

This function receives a packet from a device driver and queues it for the upper (protocol) levels to process. It always succeeds. The buffer may be dropped during processing for congestion control or by the protocol layers.

##### return values

NET_RX_SUCCESS (no congestion) NET_RX_CN_LOW (low congestion) NET_RX_CN_MOD (moderate congestion) NET_RX_CN_HIGH (high congestion) NET_RX_DROP (packet was dropped)

#### LINUX

Kernel Hackers Manual March 2006
register_gifconf
9

#### register_gifconf

register a SIOCGIF handler

##### Synopsis

       int register_gifconf
       unsigned int family
       gifconf_func_t * gifconf

##### Arguments

`family`

  Address family

`gifconf`

  Function handler

##### Description

Register protocol dependent address dumping routines. The handler that is passed must not be freed or reused until it has been replaced by another handler.

#### LINUX

Kernel Hackers Manual March 2006
netdev_set_master
9

#### netdev_set_master

set up master/slave pair

##### Synopsis

       int netdev_set_master
       struct net_device * slave
       struct net_device * master

##### Arguments

`slave`

  slave device

`master`

  new master device

##### Description

Changes the master device of the slave. Pass `NULL` to break the bonding. The caller must hold the RTNL semaphore. On a failure a negative errno code is returned. On success the reference counts are adjusted, `RTM_NEWLINK` is sent to the routing socket and the function returns zero.

#### LINUX

Kernel Hackers Manual March 2006
dev_set_promiscuity
9

#### dev_set_promiscuity

update promiscuity count on a device

##### Synopsis

       void dev_set_promiscuity
       struct net_device * dev
       int inc

##### Arguments

`dev`

  device

`inc`

  modifier

##### Description

Add or remove promsicuity from a device. While the count in the device remains above zero the interface remains promiscuous. Once it hits zero the device reverts back to normal filtering operation. A negative inc value is used to drop promiscuity on the device.

#### LINUX

Kernel Hackers Manual March 2006
dev_set_allmulti
9

#### dev_set_allmulti

update allmulti count on a device

##### Synopsis

       void dev_set_allmulti
       struct net_device * dev
       int inc

##### Arguments

`dev`

  device

`inc`

  modifier

##### Description

Add or remove reception of all multicast frames to a device. While the count in the device remains above zero the interface remains listening to all interfaces. Once it hits zero the device reverts back to normal filtering operation. A negative `inc` value is used to drop the counter when releasing a resource needing all multicasts.

#### LINUX

Kernel Hackers Manual March 2006
register_netdevice
9

#### register_netdevice

register a network device

##### Synopsis

       int register_netdevice
       struct net_device * dev

##### Arguments

`dev`

  device to register

##### Description

Take a completed network device structure and add it to the kernel interfaces. A `NETDEV_REGISTER` message is sent to the netdev notifier chain. 0 is returned on success. A negative errno code is returned on a failure to set up the device, or if the name is a duplicate.

Callers must hold the rtnl semaphore. You may want `register_netdev` instead of this.

##### BUGS

The locking appears insufficient to guarantee two parallel registers will not get the same name.

#### LINUX

Kernel Hackers Manual March 2006
register_netdev
9

#### register_netdev

register a network device

##### Synopsis

       int register_netdev
       struct net_device * dev

##### Arguments

`dev`

  device to register

##### Description

Take a completed network device structure and add it to the kernel interfaces. A `NETDEV_REGISTER` message is sent to the netdev notifier chain. 0 is returned on success. A negative errno code is returned on a failure to set up the device, or if the name is a duplicate.

This is a wrapper around register_netdev that takes the rtnl semaphore and expands the device name if you passed a format string to alloc_netdev.

#### LINUX

Kernel Hackers Manual March 2006
alloc_netdev
9

#### alloc_netdev

allocate network device

##### Synopsis

       struct net_device * alloc_netdev
       int sizeof_priv
       const char * name
       void (*setup)
         struct net_device *

##### Arguments

`sizeof_priv`

  size of private data to allocate space for

`name`

  device name format string

`setup`

  callback to initialize device

##### Description

Allocates a struct net_device with private data area for driver use and performs basic initialization.

#### LINUX

Kernel Hackers Manual March 2006
free_netdev
9

#### free_netdev

free network device

##### Synopsis

       void free_netdev
       struct net_device * dev

##### Arguments

`dev`

  device

##### Description

This function does the last stage of destroying an allocated device interface. The reference to the device object is released. If this is the last reference then it will be freed.

#### LINUX

Kernel Hackers Manual March 2006
unregister_netdevice
9

#### unregister_netdevice

remove device from the kernel

##### Synopsis

       int unregister_netdevice
       struct net_device * dev

##### Arguments

`dev`

  device

##### Description

This function shuts down a device interface and removes it from the kernel tables. On success 0 is returned, on a failure a negative errno code is returned.

Callers must hold the rtnl semaphore. You may want `unregister_netdev` instead of this.

#### LINUX

Kernel Hackers Manual March 2006
unregister_netdev
9

#### unregister_netdev

remove device from the kernel

##### Synopsis

       void unregister_netdev
       struct net_device * dev

##### Arguments

`dev`

  device

##### Description

This function shuts down a device interface and removes it from the kernel tables. On success 0 is returned, on a failure a negative errno code is returned.

This is just a wrapper for unregister_netdevice that takes the rtnl semaphore. In general you want to use this and not unregister_netdevice.

#### LINUX

Kernel Hackers Manual March 2006
alloc_etherdev
9

#### alloc_etherdev

Allocates and sets up an ethernet device

##### Synopsis

       struct net_device * alloc_etherdev
       int sizeof_priv

##### Arguments

`sizeof_priv`

  Size of additional driver-private structure to be allocated for this ethernet device

##### Description

Fill in the fields of the device structure with ethernet-generic values. Basically does everything except registering the device.

Constructs a new net device, complete with a private data area of size `sizeof_priv`. A 32-byte (not bit) alignment is enforced for this private data area.

#### LINUX

Kernel Hackers Manual March 2006
is_zero_ether_addr
9

#### is_zero_ether_addr

Determine if give Ethernet address is all zeros.

##### Synopsis

       int is_zero_ether_addr
       const u8 * addr

##### Arguments

`addr`

  Pointer to a six-byte array containing the Ethernet address

##### Description

Return true if the address is all zeroes.

#### LINUX

Kernel Hackers Manual March 2006
is_multicast_ether_addr
9

#### is_multicast_ether_addr

Determine if the Ethernet address is a multicast.

##### Synopsis

       int is_multicast_ether_addr
       const u8 * addr

##### Arguments

`addr`

  Pointer to a six-byte array containing the Ethernet address

##### Description

Return true if the address is a multicast address. By definition the broadcast address is also a multicast address.

#### LINUX

Kernel Hackers Manual March 2006
is_broadcast_ether_addr
9

#### is_broadcast_ether_addr

Determine if the Ethernet address is broadcast

##### Synopsis

       int is_broadcast_ether_addr
       const u8 * addr

##### Arguments

`addr`

  Pointer to a six-byte array containing the Ethernet address

##### Description

Return true if the address is the broadcast address.

#### LINUX

Kernel Hackers Manual March 2006
is_valid_ether_addr
9

#### is_valid_ether_addr

Determine if the given Ethernet address is valid

##### Synopsis

       int is_valid_ether_addr
       const u8 * addr

##### Arguments

`addr`

  Pointer to a six-byte array containing the Ethernet address

##### Description

Check that the Ethernet address (MAC) is not 00:00:00:00:00:00, is not a multicast address, and is not FF:FF:FF:FF:FF:FF.

Return true if the address is valid.

#### LINUX

Kernel Hackers Manual March 2006
random_ether_addr
9

#### random_ether_addr

Generate software assigned random Ethernet address

##### Synopsis

       void random_ether_addr
       u8 * addr

##### Arguments

`addr`

  Pointer to a six-byte array containing the Ethernet address

##### Description

Generate a random Ethernet address (MAC) that is not multicast and has the local assigned bit set.

#### LINUX

Kernel Hackers Manual March 2006
compare_ether_addr
9

#### compare_ether_addr

Compare two Ethernet addresses

##### Synopsis

       unsigned compare_ether_addr
       const u8 * addr1
       const u8 * addr2

##### Arguments

`addr1`

  Pointer to a six-byte array containing the Ethernet address

`addr2`

  Pointer other six-byte array containing the Ethernet address

##### Description

Compare two ethernet addresses, returns 0 if equal

### Synchronous PPP

#### LINUX

Kernel Hackers Manual March 2006
sppp_close
9

#### sppp_close

close down a synchronous PPP or Cisco HDLC link

##### Synopsis

       int sppp_close
       struct net_device * dev

##### Arguments

`dev`

  The network device to drop the link of

##### Description

This drops the logical interface to the channel. It is not done politely as we assume we will also be dropping DTR. Any timeouts are killed.

#### LINUX

Kernel Hackers Manual March 2006
sppp_open
9

#### sppp_open

open a synchronous PPP or Cisco HDLC link

##### Synopsis

       int sppp_open
       struct net_device * dev

##### Arguments

`dev`

  Network device to activate

##### Description

Close down any existing synchronous session and commence from scratch. In the PPP case this means negotiating LCP/IPCP and friends, while for Cisco HDLC we simply need to start sending keepalives

#### LINUX

Kernel Hackers Manual March 2006
sppp_reopen
9

#### sppp_reopen

notify of physical link loss

##### Synopsis

       int sppp_reopen
       struct net_device * dev

##### Arguments

`dev`

  Device that lost the link

##### Description

This function informs the synchronous protocol code that the underlying link died (for example a carrier drop on X.21)

We increment the magic numbers to ensure that if the other end failed to notice we will correctly start a new session. It happens do to the nature of telco circuits is that you can lose carrier on one endonly.

Having done this we go back to negotiating. This function may be called from an interrupt context.

#### LINUX

Kernel Hackers Manual March 2006
sppp_do_ioctl
9

#### sppp_do_ioctl

Ioctl handler for ppp/hdlc

##### Synopsis

       int sppp_do_ioctl
       struct net_device * dev
       struct ifreq * ifr
       int cmd

##### Arguments

`dev`

  Device subject to ioctl

`ifr`

  Interface request block from the user

`cmd`

  Command that is being issued

##### Description

This function handles the ioctls that may be issued by the user to control the settings of a PPP/HDLC link. It does both busy and security checks. This function is intended to be wrapped by callers who wish to add additional ioctl calls of their own.

#### LINUX

Kernel Hackers Manual March 2006
sppp_attach
9

#### sppp_attach

attach synchronous PPP/HDLC to a device

##### Synopsis

       void sppp_attach
       struct ppp_device * pd

##### Arguments

`pd`

  PPP device to initialise

##### Description

This initialises the PPP/HDLC support on an interface. At the time of calling the dev element must point to the network device that this interface is attached to. The interface should not yet be registered.

#### LINUX

Kernel Hackers Manual March 2006
sppp_detach
9

#### sppp_detach

release PPP resources from a device

##### Synopsis

       void sppp_detach
       struct net_device * dev

##### Arguments

`dev`

  Network device to release

##### Description

Stop and free up any PPP/HDLC resources used by this interface. This must be called before the device is freed.

## Module Support

### Module Loading

#### LINUX

Kernel Hackers Manual March 2006
request_module
9

#### request_module

try to load a kernel module

##### Synopsis

       int request_module
       const char * fmt
        ...

##### Arguments

`fmt`

  printf style format string for the name of the module

`...`

  variable arguments

##### Description

Load a module using the user mode module loader. The function returns zero on success or a negative errno code on failure. Note that a successful module load does not mean the module did not then unload and exit on an error of its own. Callers must check that the service they requested is now available not blindly invoke it.

If module auto-loading support is disabled then this function becomes a no-operation.

#### LINUX

Kernel Hackers Manual March 2006
call_usermodehelper_keys
9

#### call_usermodehelper_keys

start a usermode application

##### Synopsis

       int call_usermodehelper_keys
       char * path
       char ** argv
       char ** envp
       struct key * session_keyring
       int wait

##### Arguments

`path`

  pathname for the application

`argv`

  null-terminated argument list

`envp`

  null-terminated environment list

`session_keyring`

  session keyring for process (NULL for an empty keyring)

`wait`

  wait for the application to finish and return status.

##### Description

Runs a user-space application. The application is started asynchronously if wait is not set, and runs as a child of keventd. (ie. it runs with full root capabilities).

Must be called from process context. Returns a negative error code if program was not execed successfully, or 0.

### Inter Module support

Refer to the file kernel/module.c for more information.

## Hardware Interfaces

### Interrupt Handling

#### LINUX

Kernel Hackers Manual March 2006
synchronize_irq
9

#### synchronize_irq

wait for pending IRQ handlers (on other CPUs)

##### Synopsis

       void synchronize_irq
       unsigned int irq

##### Arguments

`irq`

  interrupt number to wait for

##### Description

This function waits for any pending IRQ handlers for this interrupt to complete before returning. If you use this function while holding a resource the IRQ handler may need you will deadlock.

This function may be called - with care - from IRQ context.

#### LINUX

Kernel Hackers Manual March 2006
disable_irq_nosync
9

#### disable_irq_nosync

disable an irq without waiting

##### Synopsis

       void disable_irq_nosync
       unsigned int irq

##### Arguments

`irq`

  Interrupt to disable

##### Description

Disable the selected interrupt line. Disables and Enables are nested. Unlike `disable_irq`, this function does not ensure existing instances of the IRQ handler have completed before returning.

This function may be called from IRQ context.

#### LINUX

Kernel Hackers Manual March 2006
disable_irq
9

#### disable_irq

disable an irq and wait for completion

##### Synopsis

       void disable_irq
       unsigned int irq

##### Arguments

`irq`

  Interrupt to disable

##### Description

Disable the selected interrupt line. Enables and Disables are nested. This function waits for any pending IRQ handlers for this interrupt to complete before returning. If you use this function while holding a resource the IRQ handler may need you will deadlock.

This function may be called - with care - from IRQ context.

#### LINUX

Kernel Hackers Manual March 2006
enable_irq
9

#### enable_irq

enable handling of an irq

##### Synopsis

       void enable_irq
       unsigned int irq

##### Arguments

`irq`

  Interrupt to enable

##### Description

Undoes the effect of one call to `disable_irq`. If this matches the last disable, processing of interrupts on this IRQ line is re-enabled.

This function may be called from IRQ context.

#### LINUX

Kernel Hackers Manual March 2006
free_irq
9

#### free_irq

free an interrupt

##### Synopsis

       void free_irq
       unsigned int irq
       void * dev_id

##### Arguments

`irq`

  Interrupt line to free

`dev_id`

  Device identity to free

##### Description

Remove an interrupt handler. The handler is removed and if the interrupt line is no longer in use by any driver it is disabled. On a shared IRQ the caller must ensure the interrupt is disabled on the card it drives before calling this function. The function does not return until any executing interrupts for this IRQ have completed.

This function must not be called from interrupt context.

#### LINUX

Kernel Hackers Manual March 2006
request_irq
9

#### request_irq

allocate an interrupt line

##### Synopsis

       int request_irq
       unsigned int irq
       irqreturn_t (*handler)
         int, void *, struct pt_regs *
       unsigned long irqflags
       const char * devname
       void * dev_id

##### Arguments

`irq`

  Interrupt line to allocate

`handler`

  Function to be called when the IRQ occurs

`irqflags`

  Interrupt type flags

`devname`

  An ascii name for the claiming device

`dev_id`

  A cookie passed back to the handler function

##### Description

This call allocates interrupt resources and enables the interrupt line and IRQ handling. From the point this call is made your handler function may be invoked. Since your handler function must clear any interrupt the board raises, you must take care both to initialise your hardware and to set up the interrupt handler in the right order.

Dev_id must be globally unique. Normally the address of the device data structure is used as the cookie. Since the handler receives this value it makes sense to use it.

If your interrupt is shared you must pass a non NULL dev_id as this is required when freeing the interrupt.

##### Flags

SA_SHIRQ Interrupt is shared SA_INTERRUPT Disable local interrupts while processing SA_SAMPLE_RANDOM The interrupt can be used for entropy

### Resources Management

#### LINUX

Kernel Hackers Manual March 2006
insert_resource
9

#### insert_resource

Inserts a resource in the resource tree

##### Synopsis

       int insert_resource
       struct resource * parent
       struct resource * new

##### Arguments

`parent`

  parent of the new resource

`new`

  new resource to insert

##### Description

Returns 0 on success, -EBUSY if the resource can't be inserted.

This function is equivalent of request_resource when no conflict happens. If a conflict happens, and the conflicting resources entirely fit within the range of the new resource, then the new resource is inserted and the conflicting resources become childs of the new resource. Otherwise the new resource becomes the child of the conflicting resource

### MTRR Handling

#### LINUX

Kernel Hackers Manual March 2006
mtrr_add
9

#### mtrr_add

Add a memory type region

##### Synopsis

       int mtrr_add
       unsigned long base
       unsigned long size
       unsigned int type
       char increment

##### Arguments

`base`

  Physical base address of region

`size`

  Physical size of region

`type`

  Type of MTRR desired

`increment`

  If this is true do usage counting on the region

##### Description

Memory type region registers control the caching on newer Intel and non Intel processors. This function allows drivers to request an MTRR is added. The details and hardware specifics of each processor's implementation are hidden from the caller, but nevertheless the caller should expect to need to provide a power of two size on an equivalent power of two boundary.

If the region cannot be added either because all regions are in use or the CPU cannot support it a negative value is returned. On success the register number for this entry is returned, but should be treated as a cookie only.

On a multiprocessor machine the changes are made to all processors. This is required on x86 by the Intel processors.

The available types are

`MTRR_TYPE_UNCACHABLE` - No caching

`MTRR_TYPE_WRBACK` - Write data back in bursts whenever

`MTRR_TYPE_WRCOMB` - Write data back soon but allow bursts

`MTRR_TYPE_WRTHROUGH` - Cache reads but not writes

##### BUGS

Needs a quiet flag for the cases where drivers do not mind failures and do not wish system log messages to be sent.

#### LINUX

Kernel Hackers Manual March 2006
mtrr_del
9

#### mtrr_del

delete a memory type region

##### Synopsis

       int mtrr_del
       int reg
       unsigned long base
       unsigned long size

##### Arguments

`reg`

  Register returned by mtrr_add

`base`

  Physical base address

`size`

  Size of region

##### Description

If register is supplied then base and size are ignored. This is how drivers should call it.

Releases an MTRR region. If the usage count drops to zero the register is freed and the region returns to default state. On success the register is returned, on failure a negative error code.

### PCI Support Library

#### LINUX

Kernel Hackers Manual March 2006
pci_find_capability
9

#### pci_find_capability

query for devices' capabilities

##### Synopsis

       int pci_find_capability
       struct pci_dev * dev
       int cap

##### Arguments

`dev`

  PCI device to query

`cap`

  capability code

##### Description

Tell if a device supports a given PCI capability. Returns the address of the requested capability structure within the device's PCI configuration space or 0 in case the device does not support it. Possible values for `cap`:

`PCI_CAP_ID_PM` Power Management `PCI_CAP_ID_AGP` Accelerated Graphics Port `PCI_CAP_ID_VPD` Vital Product Data `PCI_CAP_ID_SLOTID` Slot Identification `PCI_CAP_ID_MSI` Message Signalled Interrupts `PCI_CAP_ID_CHSWP` CompactPCI HotSwap `PCI_CAP_ID_PCIX` PCI-X `PCI_CAP_ID_EXP` PCI Express

#### LINUX

Kernel Hackers Manual March 2006
pci_bus_find_capability
9

#### pci_bus_find_capability

query for devices' capabilities

##### Synopsis

       int pci_bus_find_capability
       struct pci_bus * bus
       unsigned int devfn
       int cap

##### Arguments

`bus`

  the PCI bus to query

`devfn`

  PCI device to query

`cap`

  capability code

##### Description

Like `pci_find_capability` but works for pci devices that do not have a pci_dev structure set up yet.

Returns the address of the requested capability structure within the device's PCI configuration space or 0 in case the device does not support it.

#### LINUX

Kernel Hackers Manual March 2006
pci_find_parent_resource
9

#### pci_find_parent_resource

return resource region of parent bus of given region

##### Synopsis

       struct resource * pci_find_parent_resource
       const struct pci_dev * dev
       struct resource * res

##### Arguments

`dev`

  PCI device structure contains resources to be searched

`res`

  child resource record for which parent is sought

##### Description

For given resource region of given device, return the resource region of parent bus the given region is contained in or where it should be allocated from.

#### LINUX

Kernel Hackers Manual March 2006
pci_restore_bars
9

#### pci_restore_bars

restore a devices BAR values (e.g. after wake-up)

##### Synopsis

       void pci_restore_bars
       struct pci_dev * dev

##### Arguments

`dev`

  PCI device to have its BARs restored

##### Description

Restore the BAR values for a given device, so as to make it accessible by its driver.

#### LINUX

Kernel Hackers Manual March 2006
pci_set_power_state
9

#### pci_set_power_state

Set the power state of a PCI device

##### Synopsis

       int pci_set_power_state
       struct pci_dev * dev
       pci_power_t state

##### Arguments

`dev`

  PCI device to be suspended

`state`

  PCI power state (D0, D1, D2, D3hot, D3cold) we're entering

##### Description

Transition a device to a new power state, using the Power Management Capabilities in the device's config space.

##### RETURN VALUE

-EINVAL if trying to enter a lower state than we're already in. 0 if we're already in the requested state. -EIO if device does not support PCI PM. 0 if we can successfully change the power state.

#### LINUX

Kernel Hackers Manual March 2006
pci_choose_state
9

#### pci_choose_state

Choose the power state of a PCI device

##### Synopsis

       pci_power_t pci_choose_state
       struct pci_dev * dev
       pm_message_t state

##### Arguments

`dev`

  PCI device to be suspended

`state`

  target sleep state for the whole system. This is the value that is passed to `suspend` function.

##### Description

Returns PCI power state suitable for given device and given system message.

#### LINUX

Kernel Hackers Manual March 2006
pci_save_state
9

#### pci_save_state

save the PCI configuration space of a device before suspending

##### Synopsis

       int pci_save_state
       struct pci_dev * dev

##### Arguments

`dev`

  - PCI device that we're dealing with

#### LINUX

Kernel Hackers Manual March 2006
pci_restore_state
9

#### pci_restore_state

Restore the saved state of a PCI device

##### Synopsis

       int pci_restore_state
       struct pci_dev * dev

##### Arguments

`dev`

  - PCI device that we're dealing with

#### LINUX

Kernel Hackers Manual March 2006
pci_enable_device_bars
9

#### pci_enable_device_bars

Initialize some of a device for use

##### Synopsis

       int pci_enable_device_bars
       struct pci_dev * dev
       int bars

##### Arguments

`dev`

  PCI device to be initialized

`bars`

  bitmask of BAR's that must be configured

##### Description

Initialize device before it's used by a driver. Ask low-level code to enable selected I/O and memory resources. Wake up the device if it was suspended. Beware, this function can fail.

#### LINUX

Kernel Hackers Manual March 2006
pci_enable_device
9

#### pci_enable_device

Initialize device before it's used by a driver.

##### Synopsis

       int pci_enable_device
       struct pci_dev * dev

##### Arguments

`dev`

  PCI device to be initialized

##### Description

Initialize device before it's used by a driver. Ask low-level code to enable I/O and memory. Wake up the device if it was suspended. Beware, this function can fail.

#### LINUX

Kernel Hackers Manual March 2006
pci_disable_device
9

#### pci_disable_device

Disable PCI device after use

##### Synopsis

       void pci_disable_device
       struct pci_dev * dev

##### Arguments

`dev`

  PCI device to be disabled

##### Description

Signal to the system that the PCI device is not in use by the system anymore. This only involves disabling PCI bus-mastering, if active.

#### LINUX

Kernel Hackers Manual March 2006
pci_enable_wake
9

#### pci_enable_wake

enable device to generate PME# when suspended

##### Synopsis

       int pci_enable_wake
       struct pci_dev * dev
       pci_power_t state
       int enable

##### Arguments

`dev`

  - PCI device to operate on

`state`

  - Current state of device.

`enable`

  - Flag to enable or disable generation

##### Description

Set the bits in the device's PM Capabilities to generate PME# when the system is suspended.

-EIO is returned if device doesn't have PM Capabilities. -EINVAL is returned if device supports it, but can't generate wake events. 0 if operation is successful.

#### LINUX

Kernel Hackers Manual March 2006
pci_release_region
9

#### pci_release_region

Release a PCI bar

##### Synopsis

       void pci_release_region
       struct pci_dev * pdev
       int bar

##### Arguments

`pdev`

  PCI device whose resources were previously reserved by pci_request_region

`bar`

  BAR to release

##### Description

Releases the PCI I/O and memory resources previously reserved by a successful call to pci_request_region. Call this function only after all use of the PCI regions has ceased.

#### LINUX

Kernel Hackers Manual March 2006
pci_request_region
9

#### pci_request_region

Reserved PCI I/O and memory resource

##### Synopsis

       int pci_request_region
       struct pci_dev * pdev
       int bar
       char * res_name

##### Arguments

`pdev`

  PCI device whose resources are to be reserved

`bar`

  BAR to be reserved

`res_name`

  Name to be associated with resource.

##### Description

Mark the PCI region associated with PCI device `pdev` BR `bar` as being reserved by owner `res_name`. Do not access any address inside the PCI regions unless this call returns successfully.

Returns 0 on success, or `EBUSY` on error. A warning message is also printed on failure.

#### LINUX

Kernel Hackers Manual March 2006
pci_release_regions
9

#### pci_release_regions

Release reserved PCI I/O and memory resources

##### Synopsis

       void pci_release_regions
       struct pci_dev * pdev

##### Arguments

`pdev`

  PCI device whose resources were previously reserved by pci_request_regions

##### Description

Releases all PCI I/O and memory resources previously reserved by a successful call to pci_request_regions. Call this function only after all use of the PCI regions has ceased.

#### LINUX

Kernel Hackers Manual March 2006
pci_request_regions
9

#### pci_request_regions

Reserved PCI I/O and memory resources

##### Synopsis

       int pci_request_regions
       struct pci_dev * pdev
       char * res_name

##### Arguments

`pdev`

  PCI device whose resources are to be reserved

`res_name`

  Name to be associated with resource.

##### Description

Mark all PCI regions associated with PCI device `pdev` as being reserved by owner `res_name`. Do not access any address inside the PCI regions unless this call returns successfully.

Returns 0 on success, or `EBUSY` on error. A warning message is also printed on failure.

#### LINUX

Kernel Hackers Manual March 2006
pci_set_master
9

#### pci_set_master

enables bus-mastering for device dev

##### Synopsis

       void pci_set_master
       struct pci_dev * dev

##### Arguments

`dev`

  the PCI device to enable

##### Description

Enables bus-mastering on the device and calls `pcibios_set_master` to do the needed arch specific settings.

#### LINUX

Kernel Hackers Manual March 2006
pci_set_mwi
9

#### pci_set_mwi

enables memory-write-invalidate PCI transaction

##### Synopsis

       int pci_set_mwi
       struct pci_dev * dev

##### Arguments

`dev`

  the PCI device for which MWI is enabled

##### Description

Enables the Memory-Write-Invalidate transaction in `PCI_COMMAND`, and then calls `pcibios_set_mwi` to do the needed arch specific operations or a generic mwi-prep function.

##### RETURNS

An appropriate -ERRNO error value on error, or zero for success.

#### LINUX

Kernel Hackers Manual March 2006
pci_clear_mwi
9

#### pci_clear_mwi

disables Memory-Write-Invalidate for device dev

##### Synopsis

       void pci_clear_mwi
       struct pci_dev * dev

##### Arguments

`dev`

  the PCI device to disable

##### Description

Disables PCI Memory-Write-Invalidate transaction on the device

#### LINUX

Kernel Hackers Manual March 2006
pci_intx
9

#### pci_intx

enables/disables PCI INTx for device dev

##### Synopsis

       void pci_intx
       struct pci_dev * pdev
       int enable

##### Arguments

`pdev`

  the PCI device to operate on

`enable`

  boolean: whether to enable or disable PCI INTx

##### Description

Enables/disables PCI INTx for device dev

#### LINUX

Kernel Hackers Manual March 2006
pci_match_id
9

#### pci_match_id

See if a pci device matches a given pci_id table

##### Synopsis

       const struct pci_device_id * pci_match_id
       const struct pci_device_id * ids
       struct pci_dev * dev

##### Arguments

`ids`

  array of PCI device id structures to search in

`dev`

  the PCI device structure to match against.

##### Description

Used by a driver to check whether a PCI device present in the system is in its list of supported devices. Returns the matching pci_device_id structure or `NULL` if there is no match.

Depreciated, don't use this as it will not catch any dynamic ids that a driver might want to check for.

#### LINUX

Kernel Hackers Manual March 2006
pci_match_device
9

#### pci_match_device

Tell if a PCI device structure has a matching

##### Synopsis

       const struct pci_device_id * pci_match_device
       struct pci_driver * drv
       struct pci_dev * dev

##### Arguments

`drv`

  the PCI driver to match against

`dev`

  the PCI device structure to match against

##### Description

Used by a driver to check whether a PCI device present in the system is in its list of supported devices. Returns the matching pci_device_id structure or `NULL` if there is no match.

##### Description

Used by a driver to check whether a PCI device present in the system is in its list of supported devices. Returns the matching pci_device_id structure or `NULL` if there is no match.

#### LINUX

Kernel Hackers Manual March 2006
__pci_register_driver
9

#### __pci_register_driver

register a new pci driver

##### Synopsis

       int __pci_register_driver
       struct pci_driver * drv
       struct module * owner

##### Arguments

`drv`

  the driver structure to register

`owner`

  owner module of drv

##### Description

Adds the driver structure to the list of registered drivers. Returns a negative value on error, otherwise 0. If no error occurred, the driver remains registered even if no device was claimed during registration.

#### LINUX

Kernel Hackers Manual March 2006
pci_unregister_driver
9

#### pci_unregister_driver

unregister a pci driver

##### Synopsis

       void pci_unregister_driver
       struct pci_driver * drv

##### Arguments

`drv`

  the driver structure to unregister

##### Description

Deletes the driver structure from the list of registered PCI drivers, gives it a chance to clean up by calling its `remove` function for each device it was responsible for, and marks those devices as driverless.

#### LINUX

Kernel Hackers Manual March 2006
pci_dev_driver
9

#### pci_dev_driver

get the pci_driver of a device

##### Synopsis

       struct pci_driver * pci_dev_driver
       const struct pci_dev * dev

##### Arguments

`dev`

  the device to query

##### Description

Returns the appropriate pci_driver structure or `NULL` if there is no registered driver for the device.

#### LINUX

Kernel Hackers Manual March 2006
pci_dev_get
9

#### pci_dev_get

increments the reference count of the pci device structure

##### Synopsis

       struct pci_dev * pci_dev_get
       struct pci_dev * dev

##### Arguments

`dev`

  the device being referenced

##### Description

Each live reference to a device should be refcounted.

Drivers for PCI devices should normally record such references in their `probe` methods, when they bind to a device, and release them by calling `pci_dev_put`, in their `disconnect` methods.

A pointer to the device with the incremented reference counter is returned.

#### LINUX

Kernel Hackers Manual March 2006
pci_dev_put
9

#### pci_dev_put

release a use of the pci device structure

##### Synopsis

       void pci_dev_put
       struct pci_dev * dev

##### Arguments

`dev`

  device that's been disconnected

##### Description

Must be called when a user of a device is finished with it. When the last user of the device calls this function, the memory of the device is freed.

#### LINUX

Kernel Hackers Manual March 2006
pci_remove_bus_device
9

#### pci_remove_bus_device

remove a PCI device and any children

##### Synopsis

       void pci_remove_bus_device
       struct pci_dev * dev

##### Arguments

`dev`

  the device to remove

##### Description

Remove a PCI device from the device lists, informing the drivers that the device has been removed. We also remove any subordinate buses and children in a depth-first manner.

For each device we remove, delete the device structure from the device lists, remove the /proc entry, and notify userspace (/sbin/hotplug).

#### LINUX

Kernel Hackers Manual March 2006
pci_remove_behind_bridge
9

#### pci_remove_behind_bridge

remove all devices behind a PCI bridge

##### Synopsis

       void pci_remove_behind_bridge
       struct pci_dev * dev

##### Arguments

`dev`

  PCI bridge device

##### Description

Remove all devices on the bus, except for the parent bridge. This also removes any child buses, and any devices they may contain in a depth-first manner.

#### LINUX

Kernel Hackers Manual March 2006
pci_osc_support_set
9

#### pci_osc_support_set

register OS support to Firmware

##### Synopsis

       acpi_status pci_osc_support_set
       u32 flags

##### Arguments

`flags`

  OS support bits

##### Description

Update OS support fields and doing a _OSC Query to obtain an update from Firmware on supported control bits.

#### LINUX

Kernel Hackers Manual March 2006
pci_osc_control_set
9

#### pci_osc_control_set

commit requested control to Firmware

##### Synopsis

       acpi_status pci_osc_control_set
       acpi_handle handle
       u32 flags

##### Arguments

`handle`

  acpi_handle for the target ACPI object

`flags`

  driver's requested control bits

##### Description

Attempt to take control from Firmware on requested control bits.

#### LINUX

Kernel Hackers Manual March 2006
pci_enable_msi
9

#### pci_enable_msi

configure device's MSI capability structure

##### Synopsis

       int pci_enable_msi
       struct pci_dev * dev

##### Arguments

`dev`

  pointer to the pci_dev data structure of MSI device function

##### Description

Setup the MSI capability structure of device function with a single MSI vector upon its software driver call to request for MSI mode enabled on its hardware device function. A return of zero indicates the successful setup of an entry zero with the new MSI vector or non-zero for otherwise.

#### LINUX

Kernel Hackers Manual March 2006
pci_enable_msix
9

#### pci_enable_msix

configure device's MSI-X capability structure

##### Synopsis

       int pci_enable_msix
       struct pci_dev * dev
       struct msix_entry * entries
       int nvec

##### Arguments

`dev`

  pointer to the pci_dev data structure of MSI-X device function

`entries`

  pointer to an array of MSI-X entries

`nvec`

  number of MSI-X vectors requested for allocation by device driver

##### Description

Setup the MSI-X capability structure of device function with the number of requested vectors upon its software driver call to request for MSI-X mode enabled on its hardware device function. A return of zero indicates the successful configuration of MSI-X capability structure with new allocated MSI-X vectors. A return of < 0 indicates a failure. Or a return of > 0 indicates that driver request is exceeding the number of vectors available. Driver should use the returned value to re-send its request.

#### LINUX

Kernel Hackers Manual March 2006
pci_bus_alloc_resource
9

#### pci_bus_alloc_resource

allocate a resource from a parent bus

##### Synopsis

       int pci_bus_alloc_resource
       struct pci_bus * bus
       struct resource * res
       unsigned long size
       unsigned long align
       unsigned long min
       unsigned int type_mask
       void (*alignf)
         void *, struct resource *, 			unsigned long, unsigned long
       void * alignf_data

##### Arguments

`bus`

  PCI bus

`res`

  resource to allocate

`size`

  size of resource to allocate

`align`

  alignment of resource to allocate

`min`

  minimum /proc/iomem address to allocate

`type_mask`

  IORESOURCE_* type flags

`alignf`

  resource alignment function

`alignf_data`

  data argument for resource alignment function

##### Description

Given the PCI bus a device resides on, the size, minimum address, alignment and type, try to find an acceptable resource allocation for a specific device resource.

#### LINUX

Kernel Hackers Manual March 2006
pci_bus_add_device
9

#### pci_bus_add_device

##### Synopsis

       void __devinit pci_bus_add_device
       struct pci_dev * dev

##### Arguments

`dev`

  device to add

##### Description

This adds a single pci device to the global device list and adds sysfs and procfs entries

#### LINUX

Kernel Hackers Manual March 2006
pci_bus_add_devices
9

#### pci_bus_add_devices

insert newly discovered PCI devices

##### Synopsis

       void __devinit pci_bus_add_devices
       struct pci_bus * bus

##### Arguments

`bus`

  bus to check for new devices

##### Description

Add newly discovered PCI devices (which are on the bus->devices list) to the global PCI device list, add the sysfs and procfs entries. Where a bridge is found, add the discovered bus to the parents list of child buses, and recurse (breadth-first to be compatible with 2.4)

Call hotplug for each new devices.

#### LINUX

Kernel Hackers Manual March 2006
pci_scan_slot
9

#### pci_scan_slot

scan a PCI slot on a bus for devices.

##### Synopsis

       int __devinit pci_scan_slot
       struct pci_bus * bus
       int devfn

##### Arguments

`bus`

  PCI bus to scan

`devfn`

  slot number to scan (must have zero function.)

##### Description

Scan a PCI slot on the specified PCI bus for devices, adding discovered devices to the `bus`->devices list. New devices will have an empty dev->global_list head.

#### LINUX

Kernel Hackers Manual March 2006
pci_map_rom
9

#### pci_map_rom

map a PCI ROM to kernel space

##### Synopsis

       void __iomem * pci_map_rom
       struct pci_dev * pdev
       size_t * size

##### Arguments

`pdev`

  pointer to pci device struct

`size`

  pointer to receive size of pci window over ROM

##### Description

Map a PCI ROM into kernel space. If ROM is boot video ROM, the shadow BIOS copy will be returned instead of the actual ROM.

#### LINUX

Kernel Hackers Manual March 2006
pci_map_rom_copy
9

#### pci_map_rom_copy

map a PCI ROM to kernel space, create a copy

##### Synopsis

       void __iomem * pci_map_rom_copy
       struct pci_dev * pdev
       size_t * size

##### Arguments

`pdev`

  pointer to pci device struct

`size`

  pointer to receive size of pci window over ROM

##### Description

Map a PCI ROM into kernel space. If ROM is boot video ROM, the shadow BIOS copy will be returned instead of the actual ROM.

#### LINUX

Kernel Hackers Manual March 2006
pci_unmap_rom
9

#### pci_unmap_rom

unmap the ROM from kernel space

##### Synopsis

       void pci_unmap_rom
       struct pci_dev * pdev
       void __iomem * rom

##### Arguments

`pdev`

  pointer to pci device struct

`rom`

  virtual address of the previous mapping

##### Description

Remove a mapping of a previously mapped ROM

#### LINUX

Kernel Hackers Manual March 2006
pci_remove_rom
9

#### pci_remove_rom

disable the ROM and remove its sysfs attribute

##### Synopsis

       void pci_remove_rom
       struct pci_dev * pdev

##### Arguments

`pdev`

  pointer to pci device struct

##### Description

Remove the rom file in sysfs and disable ROM decoding.

### PCI Hotplug Support Library

#### LINUX

Kernel Hackers Manual March 2006
pci_hp_register
9

#### pci_hp_register

register a hotplug_slot with the PCI hotplug subsystem

##### Synopsis

       int pci_hp_register
       struct hotplug_slot * slot

##### Arguments

`slot`

  pointer to the &struct hotplug_slot to register

##### Description

Registers a hotplug slot with the pci hotplug subsystem, which will allow userspace interaction to the slot.

Returns 0 if successful, anything else for an error.

#### LINUX

Kernel Hackers Manual March 2006
pci_hp_deregister
9

#### pci_hp_deregister

deregister a hotplug_slot with the PCI hotplug subsystem

##### Synopsis

       int pci_hp_deregister
       struct hotplug_slot * slot

##### Arguments

`slot`

  pointer to the &struct hotplug_slot to deregister

##### Description

The `slot` must have been registered with the pci hotplug subsystem previously with a call to `pci_hp_register`.

Returns 0 if successful, anything else for an error.

#### LINUX

Kernel Hackers Manual March 2006
pci_hp_change_slot_info
9

#### pci_hp_change_slot_info

changes the slot's information structure in the core

##### Synopsis

       int pci_hp_change_slot_info
       struct hotplug_slot * slot
       struct hotplug_slot_info * info

##### Arguments

`slot`

  pointer to the slot whose info has changed

`info`

  pointer to the info copy into the slot's info structure

##### Description

`slot` must have been registered with the pci hotplug subsystem previously with a call to `pci_hp_register`.

Returns 0 if successful, anything else for an error.

### MCA Architecture

#### MCA Device Functions

Refer to the file arch/i386/kernel/mca.c for more information.

#### MCA Bus DMA

##### LINUX

Kernel Hackers Manual March 2006
mca_enable_dma
9

##### mca_enable_dma

channel to enable DMA on

###### Synopsis

       void mca_enable_dma
       unsigned int dmanr

###### Arguments

`dmanr`

  DMA channel

###### Description

Enable the MCA bus DMA on a channel. This can be called from IRQ context.

##### LINUX

Kernel Hackers Manual March 2006
mca_disable_dma
9

##### mca_disable_dma

channel to disable DMA on

###### Synopsis

       void mca_disable_dma
       unsigned int dmanr

###### Arguments

`dmanr`

  DMA channel

###### Description

Enable the MCA bus DMA on a channel. This can be called from IRQ context.

##### LINUX

Kernel Hackers Manual March 2006
mca_set_dma_addr
9

##### mca_set_dma_addr

load a 24bit DMA address

###### Synopsis

       void mca_set_dma_addr
       unsigned int dmanr
       unsigned int a

###### Arguments

`dmanr`

  DMA channel

`a`

  24bit bus address

###### Description

Load the address register in the DMA controller. This has a 24bit limitation (16Mb).

##### LINUX

Kernel Hackers Manual March 2006
mca_get_dma_addr
9

##### mca_get_dma_addr

load a 24bit DMA address

###### Synopsis

       unsigned int mca_get_dma_addr
       unsigned int dmanr

###### Arguments

`dmanr`

  DMA channel

###### Description

Read the address register in the DMA controller. This has a 24bit limitation (16Mb). The return is a bus address.

##### LINUX

Kernel Hackers Manual March 2006
mca_set_dma_count
9

##### mca_set_dma_count

load a 16bit transfer count

###### Synopsis

       void mca_set_dma_count
       unsigned int dmanr
       unsigned int count

###### Arguments

`dmanr`

  DMA channel

`count`

  count

###### Description

Set the DMA count for this channel. This can be up to 64Kbytes. Setting a count of zero will not do what you expect.

##### LINUX

Kernel Hackers Manual March 2006
mca_get_dma_residue
9

##### mca_get_dma_residue

get the remaining bytes to transfer

###### Synopsis

       unsigned int mca_get_dma_residue
       unsigned int dmanr

###### Arguments

`dmanr`

  DMA channel

###### Description

This function returns the number of bytes left to transfer on this DMA channel.

##### LINUX

Kernel Hackers Manual March 2006
mca_set_dma_io
9

##### mca_set_dma_io

set the port for an I/O transfer

###### Synopsis

       void mca_set_dma_io
       unsigned int dmanr
       unsigned int io_addr

###### Arguments

`dmanr`

  DMA channel

`io_addr`

  an I/O port number

###### Description

Unlike the ISA bus DMA controllers the DMA on MCA bus can transfer with an I/O port target.

##### LINUX

Kernel Hackers Manual March 2006
mca_set_dma_mode
9

##### mca_set_dma_mode

set the DMA mode

###### Synopsis

       void mca_set_dma_mode
       unsigned int dmanr
       unsigned int mode

###### Arguments

`dmanr`

  DMA channel

`mode`

  mode to set

###### Description

The DMA controller supports several modes. The mode values you can

###### set are

`MCA_DMA_MODE_READ` when reading from the DMA device.

`MCA_DMA_MODE_WRITE` to writing to the DMA device.

`MCA_DMA_MODE_IO` to do DMA to or from an I/O port.

`MCA_DMA_MODE_16` to do 16bit transfers.

## The Device File System

### LINUX

Kernel Hackers Manual March 2006
devfs_mk_dir
9

### devfs_mk_dir

Create a directory in the devfs namespace.

#### Synopsis

       int devfs_mk_dir
       const char * fmt
        ...

#### Arguments

`fmt`

  The name of the entry.

`...`

  variable arguments

#### Description

Use of this function is optional. The `devfs_register` function will automatically create intermediate directories as needed. This function is provided for efficiency reasons, as it provides a handle to a directory. On failure `NULL` is returned.

#### Description

Use of this function is optional. The `devfs_register` function will automatically create intermediate directories as needed. This function is provided for efficiency reasons, as it provides a handle to a directory. On failure `NULL` is returned.

## The Filesystem for Exporting Kernel Objects

### LINUX

Kernel Hackers Manual March 2006
sysfs_create_file
9

### sysfs_create_file

create an attribute file for an object.

#### Synopsis

       int sysfs_create_file
       struct kobject * kobj
       const struct attribute * attr

#### Arguments

`kobj`

  object we're creating for.

`attr`

  atrribute descriptor.

### LINUX

Kernel Hackers Manual March 2006
sysfs_update_file
9

### sysfs_update_file

update the modified timestamp on an object attribute.

#### Synopsis

       int sysfs_update_file
       struct kobject * kobj
       const struct attribute * attr

#### Arguments

`kobj`

  object we're acting for.

`attr`

  attribute descriptor.

### LINUX

Kernel Hackers Manual March 2006
sysfs_chmod_file
9

### sysfs_chmod_file

update the modified mode value on an object attribute.

#### Synopsis

       int sysfs_chmod_file
       struct kobject * kobj
       struct attribute * attr
       mode_t mode

#### Arguments

`kobj`

  object we're acting for.

`attr`

  attribute descriptor.

`mode`

  file permissions.

### LINUX

Kernel Hackers Manual March 2006
sysfs_remove_file
9

### sysfs_remove_file

remove an object attribute.

#### Synopsis

       void sysfs_remove_file
       struct kobject * kobj
       const struct attribute * attr

#### Arguments

`kobj`

  object we're acting for.

`attr`

  attribute descriptor.

#### Description

Hash the attribute name and kill the victim.

### LINUX

Kernel Hackers Manual March 2006
sysfs_create_dir
9

### sysfs_create_dir

create a directory for an object.

#### Synopsis

       int sysfs_create_dir
       struct kobject * kobj

#### Arguments

`kobj`

  object we're creating directory for.

### LINUX

Kernel Hackers Manual March 2006
sysfs_remove_dir
9

### sysfs_remove_dir

remove an object's directory.

#### Synopsis

       void sysfs_remove_dir
       struct kobject * kobj

#### Arguments

`kobj`

  object.

#### Description

The only thing special about this is that we remove any files in the directory before we remove the directory, and we've inlined what used to be `sysfs_rmdir` below, instead of calling separately.

### LINUX

Kernel Hackers Manual March 2006
sysfs_create_link
9

### sysfs_create_link

create symlink between two objects.

#### Synopsis

       int sysfs_create_link
       struct kobject * kobj
       struct kobject * target
       const char * name

#### Arguments

`kobj`

  object whose directory we're creating the link in.

`target`

  object we're pointing to.

`name`

  name of the symlink.

### LINUX

Kernel Hackers Manual March 2006
sysfs_remove_link
9

### sysfs_remove_link

remove symlink in object's directory.

#### Synopsis

       void sysfs_remove_link
       struct kobject * kobj
       const char * name

#### Arguments

`kobj`

  object we're acting for.

`name`

  name of the symlink to remove.

### LINUX

Kernel Hackers Manual March 2006
sysfs_create_bin_file
9

### sysfs_create_bin_file

create binary file for object.

#### Synopsis

       int sysfs_create_bin_file
       struct kobject * kobj
       struct bin_attribute * attr

#### Arguments

`kobj`

  object.

`attr`

  attribute descriptor.

### LINUX

Kernel Hackers Manual March 2006
sysfs_remove_bin_file
9

### sysfs_remove_bin_file

remove binary file for object.

#### Synopsis

       int sysfs_remove_bin_file
       struct kobject * kobj
       struct bin_attribute * attr

#### Arguments

`kobj`

  object.

`attr`

  attribute descriptor.

## Security Framework

### LINUX

Kernel Hackers Manual March 2006
register_security
9

### register_security

registers a security framework with the kernel

#### Synopsis

       int register_security
       struct security_operations * ops

#### Arguments

`ops`

  a pointer to the struct security_options that is to be registered

#### Description

This function is to allow a security module to register itself with the kernel security subsystem. Some rudimentary checking is done on the `ops` value passed to this function. A call to `unregister_security` should be done to remove this security_options structure from the kernel.

If there is already a security module registered with the kernel, an error will be returned. Otherwise 0 is returned on success.

### LINUX

Kernel Hackers Manual March 2006
unregister_security
9

### unregister_security

unregisters a security framework with the kernel

#### Synopsis

       int unregister_security
       struct security_operations * ops

#### Arguments

`ops`

  a pointer to the struct security_options that is to be registered

#### Description

This function removes a struct security_operations variable that had previously been registered with a successful call to `register_security`.

If `ops` does not match the valued previously passed to `register_security` an error is returned. Otherwise the default security options is set to the the dummy_security_ops structure, and 0 is returned.

### LINUX

Kernel Hackers Manual March 2006
mod_reg_security
9

### mod_reg_security

allows security modules to be stacked

#### Synopsis

       int mod_reg_security
       const char * name
       struct security_operations * ops

#### Arguments

`name`

  a pointer to a string with the name of the security_options to be registered

`ops`

  a pointer to the struct security_options that is to be registered

#### Description

This function allows security modules to be stacked if the currently loaded security module allows this to happen. It passes the `name` and `ops` to the register_security function of the currently loaded security module.

The return value depends on the currently loaded security module, with 0 as success.

### LINUX

Kernel Hackers Manual March 2006
mod_unreg_security
9

### mod_unreg_security

allows a security module registered with `mod_reg_security` to be unloaded

#### Synopsis

       int mod_unreg_security
       const char * name
       struct security_operations * ops

#### Arguments

`name`

  a pointer to a string with the name of the security_options to be removed

`ops`

  a pointer to the struct security_options that is to be removed

#### Description

This function allows security modules that have been successfully registered with a call to `mod_reg_security` to be unloaded from the system. This calls the currently loaded security module's `unregister_security` call with the `name` and `ops` variables.

The return value depends on the currently loaded security module, with 0 as success.

### LINUX

Kernel Hackers Manual March 2006
capable
9

### capable

calls the currently loaded security module's `capable` function with the specified capability

#### Synopsis

       int capable
       int cap

#### Arguments

`cap`

  the requested capability level.

#### Description

This function calls the currently loaded security module's `capable` function with a pointer to the current task and the specified `cap` value.

This allows the security module to implement the capable function call however it chooses to.

## Power Management

### LINUX

Kernel Hackers Manual March 2006
pm_register
9

### pm_register

register a device with power management

#### Synopsis

       struct pm_dev * pm_register
       pm_dev_t type
       unsigned long id
       pm_callback callback

#### Arguments

`type`

  device type

`id`

  device ID

`callback`

  callback function

#### Description

Add a device to the list of devices that wish to be notified about power management events. A &pm_dev structure is returned on success, on failure the return is `NULL`.

The callback function will be called in process context and it may sleep.

### LINUX

Kernel Hackers Manual March 2006
pm_unregister
9

### pm_unregister

unregister a device with power management

#### Synopsis

       void pm_unregister
       struct pm_dev * dev

#### Arguments

`dev`

  device to unregister

#### Description

Remove a device from the power management notification lists. The dev passed must be a handle previously returned by pm_register.

### LINUX

Kernel Hackers Manual March 2006
pm_unregister_all
9

### pm_unregister_all

unregister all devices with matching callback

#### Synopsis

       void pm_unregister_all
       pm_callback callback

#### Arguments

`callback`

  callback function pointer

#### Description

Unregister every device that would call the callback passed. This is primarily meant as a helper function for loadable modules. It enables a module to give up all its managed devices without keeping its own private list.

### LINUX

Kernel Hackers Manual March 2006
pm_send_all
9

### pm_send_all

send request to all managed devices

#### Synopsis

       int pm_send_all
       pm_request_t rqst
       void * data

#### Arguments

`rqst`

  power management request

`data`

  data for the callback

#### Description

Issue a power management request to a all devices. The `PM_SUSPEND` events are handled specially. Any device is permitted to fail a suspend by returning a non zero (error) value from its callback function. If any device vetoes a suspend request then all other devices that have suspended during the processing of this request are restored to their previous state.

#### WARNING

This function takes the pm_devs_lock. The lock is not dropped until the callbacks have completed. This prevents races against pm locking functions, races against module unload pm_unregister code. It does mean however that you must not issue pm_ functions within the callback or you will deadlock and users will hate you.

Zero is returned on success. If a suspend fails then the status from the device that vetoes the suspend is returned.

#### BUGS

what stops two power management requests occurring in parallel and conflicting.

## Device drivers infrastructure

### Device Drivers Base

#### LINUX

Kernel Hackers Manual March 2006
driver_for_each_device
9

#### driver_for_each_device

Iterator for devices bound to a driver.

##### Synopsis

       int driver_for_each_device
       struct device_driver * drv
       struct device * start
       void * data
       int (*fn)
         struct device *, void *

##### Arguments

`drv`

  Driver we're iterating.

`start`

  Device to begin with

`data`

  Data to pass to the callback.

`fn`

  Function to call for each device.

##### Description

Iterate over the `drv`'s list of devices calling `fn` for each one.

#### LINUX

Kernel Hackers Manual March 2006
driver_find_device
9

#### driver_find_device

device iterator for locating a particular device.

##### Synopsis

       struct device * driver_find_device
       struct device_driver * drv
       struct device * start
       void * data
       int (*match)
         struct device *, void *

##### Arguments

`drv`

  The device's driver

`start`

  Device to begin with

`data`

  Data to pass to match function

`match`

  Callback function to check device

##### Description

This is similar to the `driver_for_each_device` function above, but it returns a reference to a device that is 'found' for later use, as determined by the `match` callback.

The callback should return 0 if the device doesn't match and non-zero if it does. If the callback returns non-zero, this function will return to the caller and not iterate over any more devices.

#### LINUX

Kernel Hackers Manual March 2006
driver_create_file
9

#### driver_create_file

create sysfs file for driver.

##### Synopsis

       int driver_create_file
       struct device_driver * drv
       struct driver_attribute * attr

##### Arguments

`drv`

  driver.

`attr`

  driver attribute descriptor.

#### LINUX

Kernel Hackers Manual March 2006
driver_remove_file
9

#### driver_remove_file

remove sysfs file for driver.

##### Synopsis

       void driver_remove_file
       struct device_driver * drv
       struct driver_attribute * attr

##### Arguments

`drv`

  driver.

`attr`

  driver attribute descriptor.

#### LINUX

Kernel Hackers Manual March 2006
get_driver
9

#### get_driver

increment driver reference count.

##### Synopsis

       struct device_driver * get_driver
       struct device_driver * drv

##### Arguments

`drv`

  driver.

#### LINUX

Kernel Hackers Manual March 2006
put_driver
9

#### put_driver

decrement driver's refcount.

##### Synopsis

       void put_driver
       struct device_driver * drv

##### Arguments

`drv`

  driver.

#### LINUX

Kernel Hackers Manual March 2006
driver_register
9

#### driver_register

register driver with bus

##### Synopsis

       int driver_register
       struct device_driver * drv

##### Arguments

`drv`

  driver to register

##### Description

We pass off most of the work to the `bus_add_driver` call, since most of the things we have to do deal with the bus structures.

The one interesting aspect is that we setup `drv`->unloaded as a completion that gets complete when the driver reference count reaches 0.

#### LINUX

Kernel Hackers Manual March 2006
driver_unregister
9

#### driver_unregister

remove driver from system.

##### Synopsis

       void driver_unregister
       struct device_driver * drv

##### Arguments

`drv`

  driver.

##### Description

Again, we pass off most of the work to the bus-level call.

Though, once that is done, we wait until `drv`->unloaded is completed. This will block until the driver refcount reaches 0, and it is released. Only modular drivers will call this function, and we have to guarantee that it won't complete, letting the driver unload until all references are gone.

#### LINUX

Kernel Hackers Manual March 2006
driver_find
9

#### driver_find

locate driver on a bus by its name.

##### Synopsis

       struct device_driver * driver_find
       const char * name
       struct bus_type * bus

##### Arguments

`name`

  name of the driver.

`bus`

  bus to scan for the driver.

##### Description

Call `kset_find_obj` to iterate over list of drivers on a bus to find driver by name. Return driver if found.

Note that kset_find_obj increments driver's reference count.

#### LINUX

Kernel Hackers Manual March 2006
device_create_file
9

#### device_create_file

create sysfs attribute file for device.

##### Synopsis

       int device_create_file
       struct device * dev
       struct device_attribute * attr

##### Arguments

`dev`

  device.

`attr`

  device attribute descriptor.

#### LINUX

Kernel Hackers Manual March 2006
device_remove_file
9

#### device_remove_file

remove sysfs attribute file.

##### Synopsis

       void device_remove_file
       struct device * dev
       struct device_attribute * attr

##### Arguments

`dev`

  device.

`attr`

  device attribute descriptor.

#### LINUX

Kernel Hackers Manual March 2006
device_initialize
9

#### device_initialize

init device structure.

##### Synopsis

       void device_initialize
       struct device * dev

##### Arguments

`dev`

  device.

##### Description

This prepares the device for use by other layers, including adding it to the device hierarchy. It is the first half of `device_register`, if called by that, though it can also be called separately, so one may use `dev`'s fields (e.g. the refcount).

#### LINUX

Kernel Hackers Manual March 2006
device_add
9

#### device_add

add device to device hierarchy.

##### Synopsis

       int device_add
       struct device * dev

##### Arguments

`dev`

  device.

##### Description

This is part 2 of `device_register`, though may be called separately _iff_ `device_initialize` has been called separately.

This adds it to the kobject hierarchy via `kobject_add`, adds it to the global and sibling lists for the device, then adds it to the other relevant subsystems of the driver model.

#### LINUX

Kernel Hackers Manual March 2006
device_register
9

#### device_register

register a device with the system.

##### Synopsis

       int device_register
       struct device * dev

##### Arguments

`dev`

  pointer to the device structure

##### Description

This happens in two clean steps - initialize the device and add it to the system. The two steps can be called separately, but this is the easiest and most common. I.e. you should only call the two helpers separately if have a clearly defined need to use and refcount the device before it is added to the hierarchy.

#### LINUX

Kernel Hackers Manual March 2006
get_device
9

#### get_device

increment reference count for device.

##### Synopsis

       struct device * get_device
       struct device * dev

##### Arguments

`dev`

  device.

##### Description

This simply forwards the call to `kobject_get`, though we do take care to provide for the case that we get a NULL pointer passed in.

#### LINUX

Kernel Hackers Manual March 2006
put_device
9

#### put_device

decrement reference count.

##### Synopsis

       void put_device
       struct device * dev

##### Arguments

`dev`

  device in question.

#### LINUX

Kernel Hackers Manual March 2006
device_del
9

#### device_del

delete device from system.

##### Synopsis

       void device_del
       struct device * dev

##### Arguments

`dev`

  device.

##### Description

This is the first part of the device unregistration sequence. This removes the device from the lists we control from here, has it removed from the other driver model subsystems it was added to in `device_add`, and removes it from the kobject hierarchy.

##### NOTE

this should be called manually _iff_ `device_add` was also called manually.

#### LINUX

Kernel Hackers Manual March 2006
device_unregister
9

#### device_unregister

unregister device from system.

##### Synopsis

       void device_unregister
       struct device * dev

##### Arguments

`dev`

  device going away.

##### Description

We do this in two parts, like we do `device_register`. First, we remove it from all the subsystems with `device_del`, then we decrement the reference count via `put_device`. If that is the final reference count, the device will be cleaned up via `device_release` above. Otherwise, the structure will stick around until the final reference to the device is dropped.

#### LINUX

Kernel Hackers Manual March 2006
device_for_each_child
9

#### device_for_each_child

device child iterator.

##### Synopsis

       int device_for_each_child
       struct device * parent
       void * data
       int (*fn)
         struct device *, void *

##### Arguments

`parent`

  parent struct device.

`data`

  data for the callback.

`fn`

  function to be called for each device.

##### Description

Iterate over `parent`'s child devices, and call `fn` for each, passing it `data`.

We check the return of `fn` each time. If it returns anything other than 0, we break out and return that value.

#### LINUX

Kernel Hackers Manual March 2006
request_firmware
9

#### request_firmware

send firmware request and wait for it

##### Synopsis

       int request_firmware
       const struct firmware ** firmware_p
       const char * name
       struct device * device

##### Arguments

`firmware_p`

  pointer to firmware image

`name`

  name of firmware file

`device`

  device for which firmware is being loaded

##### Description

`firmware_p` will be used to return a firmware image by the name of `name` for device `device`.

Should be called from user context where sleeping is allowed.

`name` will be used as `$FIRMWARE` in the uevent environment and should be distinctive enough not to be confused with any other firmware image for this or any other device.

#### LINUX

Kernel Hackers Manual March 2006
release_firmware
9

#### release_firmware

release the resource associated with a firmware image

##### Synopsis

       void release_firmware
       const struct firmware * fw

##### Arguments

`fw`

  firmware resource to release

#### LINUX

Kernel Hackers Manual March 2006
register_firmware
9

#### register_firmware

provide a firmware image for later usage

##### Synopsis

       void register_firmware
       const char * name
       const u8 * data
       size_t size

##### Arguments

`name`

  name of firmware image file

`data`

  buffer pointer for the firmware image

`size`

  size of the data buffer area

##### Description

Make sure that `data` will be available by requesting firmware `name`.

##### Note

This will not be possible until some kind of persistence is available.

#### LINUX

Kernel Hackers Manual March 2006
request_firmware_nowait
9

#### request_firmware_nowait

##### Synopsis

       int request_firmware_nowait
       struct module * module
       int uevent
       const char * name
       struct device * device
       void * context
       void (*cont)
         const struct firmware *fw, void *context

##### Arguments

`module`

  module requesting the firmware

`uevent`

  sends uevent to copy the firmware image if this flag is non-zero else the firmware copy must be done manually.

`name`

  name of firmware file

`device`

  device for which firmware is being loaded

`context`

  will be passed over to `cont`, and `fw` may be `NULL` if firmware request fails.

`cont`

  function will be called asynchronously when the firmware request is over.

##### Description

Asynchronous variant of `request_firmware` for contexts where it is not possible to sleep.

#### LINUX

Kernel Hackers Manual March 2006
transport_class_register
9

#### transport_class_register

register an initial transport class

##### Synopsis

       int transport_class_register
       struct transport_class * tclass

##### Arguments

`tclass`

  a pointer to the transport class structure to be initialised

##### Description

The transport class contains an embedded class which is used to identify it. The caller should initialise this structure with zeros and then generic class must have been initialised with the actual transport class unique name. There's a macro `DECLARE_TRANSPORT_CLASS` to do this (declared classes still must be registered).

Returns 0 on success or error on failure.

##### Description

The transport class contains an embedded class which is used to identify it. The caller should initialise this structure with zeros and then generic class must have been initialised with the actual transport class unique name. There's a macro `DECLARE_TRANSPORT_CLASS` to do this (declared classes still must be registered).

Returns 0 on success or error on failure.

#### LINUX

Kernel Hackers Manual March 2006
transport_class_unregister
9

#### transport_class_unregister

unregister a previously registered class

##### Synopsis

       void transport_class_unregister
       struct transport_class * tclass

##### Arguments

`tclass`

  The transport class to unregister

##### Description

Must be called prior to deallocating the memory for the transport class.

##### Description

Must be called prior to deallocating the memory for the transport class.

#### LINUX

Kernel Hackers Manual March 2006
anon_transport_class_register
9

#### anon_transport_class_register

register an anonymous class

##### Synopsis

       int anon_transport_class_register
       struct anon_transport_class * atc

##### Arguments

`atc`

  The anon transport class to register

##### Description

The anonymous transport class contains both a transport class and a container. The idea of an anonymous class is that it never actually has any device attributes associated with it (and thus saves on container storage). So it can only be used for triggering events. Use prezero and then use `DECLARE_ANON_TRANSPORT_CLASS` to initialise the anon transport class storage.

##### Description

The anonymous transport class contains both a transport class and a container. The idea of an anonymous class is that it never actually has any device attributes associated with it (and thus saves on container storage). So it can only be used for triggering events. Use prezero and then use `DECLARE_ANON_TRANSPORT_CLASS` to initialise the anon transport class storage.

#### LINUX

Kernel Hackers Manual March 2006
anon_transport_class_unregister
9

#### anon_transport_class_unregister

unregister an anon class

##### Synopsis

       void anon_transport_class_unregister
       struct anon_transport_class * atc

##### Arguments

`atc`

  Pointer to the anon transport class to unregister

##### Description

Must be called prior to deallocating the memory for the anon transport class.

##### Description

Must be called prior to deallocating the memory for the anon transport class.

#### LINUX

Kernel Hackers Manual March 2006
transport_setup_device
9

#### transport_setup_device

declare a new dev for transport class association

##### Synopsis

       void transport_setup_device
       struct device * dev

##### Arguments

`dev`

  the generic device representing the entity being added

##### Description

Usually, dev represents some component in the HBA system (either the HBA itself or a device remote across the HBA bus). This routine is simply a trigger point to see if any set of transport classes wishes to associate with the added device. This allocates storage for the class device and initialises it, but does not yet add it to the system or add attributes to it (you do this with transport_add_device). If you have no need for a separate setup and add operations, use transport_register_device (see transport_class.h).

##### Description

Usually, dev represents some component in the HBA system (either the HBA itself or a device remote across the HBA bus). This routine is simply a trigger point to see if any set of transport classes wishes to associate with the added device. This allocates storage for the class device and initialises it, but does not yet add it to the system or add attributes to it (you do this with transport_add_device). If you have no need for a separate setup and add operations, use transport_register_device (see transport_class.h).

#### LINUX

Kernel Hackers Manual March 2006
transport_add_device
9

#### transport_add_device

declare a new dev for transport class association

##### Synopsis

       void transport_add_device
       struct device * dev

##### Arguments

`dev`

  the generic device representing the entity being added

##### Description

Usually, dev represents some component in the HBA system (either the HBA itself or a device remote across the HBA bus). This routine is simply a trigger point used to add the device to the system and register attributes for it.

##### Description

Usually, dev represents some component in the HBA system (either the HBA itself or a device remote across the HBA bus). This routine is simply a trigger point used to add the device to the system and register attributes for it.

#### LINUX

Kernel Hackers Manual March 2006
transport_configure_device
9

#### transport_configure_device

configure an already set up device

##### Synopsis

       void transport_configure_device
       struct device * dev

##### Arguments

`dev`

  generic device representing device to be configured

##### Description

The idea of configure is simply to provide a point within the setup process to allow the transport class to extract information from a device after it has been setup. This is used in SCSI because we have to have a setup device to begin using the HBA, but after we send the initial inquiry, we use configure to extract the device parameters. The device need not have been added to be configured.

##### Description

The idea of configure is simply to provide a point within the setup process to allow the transport class to extract information from a device after it has been setup. This is used in SCSI because we have to have a setup device to begin using the HBA, but after we send the initial inquiry, we use configure to extract the device parameters. The device need not have been added to be configured.

#### LINUX

Kernel Hackers Manual March 2006
transport_remove_device
9

#### transport_remove_device

remove the visibility of a device

##### Synopsis

       void transport_remove_device
       struct device * dev

##### Arguments

`dev`

  generic device to remove

##### Description

This call removes the visibility of the device (to the user from sysfs), but does not destroy it. To eliminate a device entirely you must also call transport_destroy_device. If you don't need to do remove and destroy as separate operations, use `transport_unregister_device` (see transport_class.h) which will perform both calls for you.

##### Description

This call removes the visibility of the device (to the user from sysfs), but does not destroy it. To eliminate a device entirely you must also call transport_destroy_device. If you don't need to do remove and destroy as separate operations, use `transport_unregister_device` (see transport_class.h) which will perform both calls for you.

#### LINUX

Kernel Hackers Manual March 2006
transport_destroy_device
9

#### transport_destroy_device

destroy a removed device

##### Synopsis

       void transport_destroy_device
       struct device * dev

##### Arguments

`dev`

  device to eliminate from the transport class.

##### Description

This call triggers the elimination of storage associated with the transport classdev. Note: all it really does is relinquish a reference to the classdev. The memory will not be freed until the last reference goes to zero. Note also that the classdev retains a reference count on dev, so dev too will remain for as long as the transport class device remains around.

##### Description

This call triggers the elimination of storage associated with the transport classdev. Note: all it really does is relinquish a reference to the classdev. The memory will not be freed until the last reference goes to zero. Note also that the classdev retains a reference count on dev, so dev too will remain for as long as the transport class device remains around.

#### LINUX

Kernel Hackers Manual March 2006
dma_pool_create
9

#### dma_pool_create

Creates a pool of consistent memory blocks, for dma.

##### Synopsis

       struct dma_pool * dma_pool_create
       const char * name
       struct device * dev
       size_t size
       size_t align
       size_t allocation

##### Arguments

`name`

  name of pool, for diagnostics

`dev`

  device that will be doing the DMA

`size`

  size of the blocks in this pool.

`align`

  alignment requirement for blocks; must be a power of two

`allocation`

  returned blocks won't cross this boundary (or zero)

##### Context

!`in_interrupt`

##### Description

Returns a dma allocation pool with the requested characteristics, or null if one can't be created. Given one of these pools, `dma_pool_alloc` may be used to allocate memory. Such memory will all have consistent DMA mappings, accessible by the device and its driver without using cache flushing primitives. The actual size of blocks allocated may be larger than requested because of alignment.

If allocation is nonzero, objects returned from `dma_pool_alloc` won't cross that size boundary. This is useful for devices which have addressing restrictions on individual DMA transfers, such as not crossing boundaries of 4KBytes.

#### LINUX

Kernel Hackers Manual March 2006
dma_pool_destroy
9

#### dma_pool_destroy

destroys a pool of dma memory blocks.

##### Synopsis

       void dma_pool_destroy
       struct dma_pool * pool

##### Arguments

`pool`

  dma pool that will be destroyed

##### Context

!`in_interrupt`

##### Description

Caller guarantees that no more memory from the pool is in use, and that nothing will try to use the pool after this call.

#### LINUX

Kernel Hackers Manual March 2006
dma_pool_alloc
9

#### dma_pool_alloc

get a block of consistent memory

##### Synopsis

       void * dma_pool_alloc
       struct dma_pool * pool
       gfp_t mem_flags
       dma_addr_t * handle

##### Arguments

`pool`

  dma pool that will produce the block

`mem_flags`

  GFP_* bitmask

`handle`

  pointer to dma address of block

##### Description

This returns the kernel virtual address of a currently unused block, and reports its dma address through the handle. If such a memory block can't be allocated, null is returned.

#### LINUX

Kernel Hackers Manual March 2006
dma_pool_free
9

#### dma_pool_free

put block back into dma pool

##### Synopsis

       void dma_pool_free
       struct dma_pool * pool
       void * vaddr
       dma_addr_t dma

##### Arguments

`pool`

  the dma pool holding the block

`vaddr`

  virtual address of block

`dma`

  dma address of block

##### Description

Caller promises neither device nor driver will again touch this block unless it is first re-allocated.

#### LINUX

Kernel Hackers Manual March 2006
sysdev_driver_register
9

#### sysdev_driver_register

Register auxillary driver

##### Synopsis

       int sysdev_driver_register
       struct sysdev_class * cls
       struct sysdev_driver * drv

##### Arguments

`cls`

  Device class driver belongs to.

`drv`

  Driver.

##### Description

If `cls` is valid, then `drv` is inserted into `cls`->drivers to be called on each operation on devices of that class. The refcount of `cls` is incremented. Otherwise, `drv` is inserted into sysdev_drivers, and called for each device.

#### LINUX

Kernel Hackers Manual March 2006
sysdev_driver_unregister
9

#### sysdev_driver_unregister

Remove an auxillary driver.

##### Synopsis

       void sysdev_driver_unregister
       struct sysdev_class * cls
       struct sysdev_driver * drv

##### Arguments

`cls`

  Class driver belongs to.

`drv`

  Driver.

#### LINUX

Kernel Hackers Manual March 2006
sysdev_register
9

#### sysdev_register

add a system device to the tree

##### Synopsis

       int sysdev_register
       struct sys_device * sysdev

##### Arguments

`sysdev`

  device in question

#### LINUX

Kernel Hackers Manual March 2006
platform_get_resource
9

#### platform_get_resource

get a resource for a device

##### Synopsis

       struct resource * platform_get_resource
       struct platform_device * dev
       unsigned int type
       unsigned int num

##### Arguments

`dev`

  platform device

`type`

  resource type

`num`

  resource index

#### LINUX

Kernel Hackers Manual March 2006
platform_get_irq
9

#### platform_get_irq

get an IRQ for a device

##### Synopsis

       int platform_get_irq
       struct platform_device * dev
       unsigned int num

##### Arguments

`dev`

  platform device

`num`

  IRQ number index

#### LINUX

Kernel Hackers Manual March 2006
platform_get_resource_byname
9

#### platform_get_resource_byname

get a resource for a device by name

##### Synopsis

       struct resource * platform_get_resource_byname
       struct platform_device * dev
       unsigned int type
       char * name

##### Arguments

`dev`

  platform device

`type`

  resource type

`name`

  resource name

#### LINUX

Kernel Hackers Manual March 2006
platform_get_irq_byname
9

#### platform_get_irq_byname

get an IRQ for a device

##### Synopsis

       int platform_get_irq_byname
       struct platform_device * dev
       char * name

##### Arguments

`dev`

  platform device

`name`

  IRQ name

#### LINUX

Kernel Hackers Manual March 2006
platform_add_devices
9

#### platform_add_devices

add a numbers of platform devices

##### Synopsis

       int platform_add_devices
       struct platform_device ** devs
       int num

##### Arguments

`devs`

  array of platform devices to add

`num`

  number of platform devices in array

#### LINUX

Kernel Hackers Manual March 2006
platform_device_put
9

#### platform_device_put

##### Synopsis

       void platform_device_put
       struct platform_device * pdev

##### Arguments

`pdev`

  platform device to free

##### Description

Free all memory associated with a platform device. This function must _only_ be externally called in error cases. All other usage is a bug.

#### LINUX

Kernel Hackers Manual March 2006
platform_device_alloc
9

#### platform_device_alloc

##### Synopsis

       struct platform_device * platform_device_alloc
       const char * name
       unsigned int id

##### Arguments

`name`

  base name of the device we're adding

`id`

  instance id

##### Description

Create a platform device object which can have other objects attached to it, and which will have attached objects freed when it is released.

#### LINUX

Kernel Hackers Manual March 2006
platform_device_add_resources
9

#### platform_device_add_resources

##### Synopsis

       int platform_device_add_resources
       struct platform_device * pdev
       struct resource * res
       unsigned int num

##### Arguments

`pdev`

  platform device allocated by platform_device_alloc to add resources to

`res`

  set of resources that needs to be allocated for the device

`num`

  number of resources

##### Description

Add a copy of the resources to the platform device. The memory associated with the resources will be freed when the platform device is released.

#### LINUX

Kernel Hackers Manual March 2006
platform_device_add_data
9

#### platform_device_add_data

##### Synopsis

       int platform_device_add_data
       struct platform_device * pdev
       void * data
       size_t size

##### Arguments

`pdev`

  platform device allocated by platform_device_alloc to add resources to

`data`

  platform specific data for this platform device

`size`

  size of platform specific data

##### Description

Add a copy of platform specific data to the platform device's platform_data pointer. The memory associated with the platform data will be freed when the platform device is released.

#### LINUX

Kernel Hackers Manual March 2006
platform_device_add
9

#### platform_device_add

add a platform device to device hierarchy

##### Synopsis

       int platform_device_add
       struct platform_device * pdev

##### Arguments

`pdev`

  platform device we're adding

##### Description

This is part 2 of `platform_device_register`, though may be called separately _iff_ pdev was allocated by `platform_device_alloc`.

#### LINUX

Kernel Hackers Manual March 2006
platform_device_del
9

#### platform_device_del

remove a platform-level device

##### Synopsis

       void platform_device_del
       struct platform_device * pdev

##### Arguments

`pdev`

  platform device we're removing

##### Description

Note that this function will also release all memory- and port-based resources owned by the device (`dev`->resource).

#### LINUX

Kernel Hackers Manual March 2006
platform_device_register
9

#### platform_device_register

add a platform-level device

##### Synopsis

       int platform_device_register
       struct platform_device * pdev

##### Arguments

`pdev`

  platform device we're adding

#### LINUX

Kernel Hackers Manual March 2006
platform_device_unregister
9

#### platform_device_unregister

unregister a platform-level device

##### Synopsis

       void platform_device_unregister
       struct platform_device * pdev

##### Arguments

`pdev`

  platform device we're unregistering

##### Description

Unregistration is done in 2 steps. Fisrt we release all resources and remove it from the subsystem, then we drop reference count by calling `platform_device_put`.

#### LINUX

Kernel Hackers Manual March 2006
platform_device_register_simple
9

#### platform_device_register_simple

##### Synopsis

       struct platform_device * platform_device_register_simple
       char * name
       unsigned int id
       struct resource * res
       unsigned int num

##### Arguments

`name`

  base name of the device we're adding

`id`

  instance id

`res`

  set of resources that needs to be allocated for the device

`num`

  number of resources

##### Description

This function creates a simple platform device that requires minimal resource and memory management. Canned release function freeing memory allocated for the device allows drivers using such devices to be unloaded iwithout waiting for the last reference to the device to be dropped.

#### LINUX

Kernel Hackers Manual March 2006
platform_driver_register
9

#### platform_driver_register

##### Synopsis

       int platform_driver_register
       struct platform_driver * drv

##### Arguments

`drv`

  platform driver structure

#### LINUX

Kernel Hackers Manual March 2006
platform_driver_unregister
9

#### platform_driver_unregister

##### Synopsis

       void platform_driver_unregister
       struct platform_driver * drv

##### Arguments

`drv`

  platform driver structure

#### LINUX

Kernel Hackers Manual March 2006
bus_for_each_dev
9

#### bus_for_each_dev

device iterator.

##### Synopsis

       int bus_for_each_dev
       struct bus_type * bus
       struct device * start
       void * data
       int (*fn)
         struct device *, void *

##### Arguments

`bus`

  bus type.

`start`

  device to start iterating from.

`data`

  data for the callback.

`fn`

  function to be called for each device.

##### Description

Iterate over `bus`'s list of devices, and call `fn` for each, passing it `data`. If `start` is not NULL, we use that device to begin iterating from.

We check the return of `fn` each time. If it returns anything other than 0, we break out and return that value.

##### NOTE

The device that returns a non-zero value is not retained in any way, nor is its refcount incremented. If the caller needs to retain this data, it should do, and increment the reference count in the supplied callback.

#### LINUX

Kernel Hackers Manual March 2006
bus_find_device
9

#### bus_find_device

device iterator for locating a particular device.

##### Synopsis

       struct device * bus_find_device
       struct bus_type * bus
       struct device * start
       void * data
       int (*match)
         struct device *, void *

##### Arguments

`bus`

  bus type

`start`

  Device to begin with

`data`

  Data to pass to match function

`match`

  Callback function to check device

##### Description

This is similar to the `bus_for_each_dev` function above, but it returns a reference to a device that is 'found' for later use, as determined by the `match` callback.

The callback should return 0 if the device doesn't match and non-zero if it does. If the callback returns non-zero, this function will return to the caller and not iterate over any more devices.

#### LINUX

Kernel Hackers Manual March 2006
bus_for_each_drv
9

#### bus_for_each_drv

driver iterator

##### Synopsis

       int bus_for_each_drv
       struct bus_type * bus
       struct device_driver * start
       void * data
       int (*fn)
         struct device_driver *, void *

##### Arguments

`bus`

  bus we're dealing with.

`start`

  driver to start iterating on.

`data`

  data to pass to the callback.

`fn`

  function to call for each driver.

##### Description

This is nearly identical to the device iterator above. We iterate over each driver that belongs to `bus`, and call `fn` for each. If `fn` returns anything but 0, we break out and return it. If `start` is not NULL, we use it as the head of the list.

##### NOTE

we don't return the driver that returns a non-zero value, nor do we leave the reference count incremented for that driver. If the caller needs to know that info, it must set it in the callback. It must also be sure to increment the refcount so it doesn't disappear before returning to the caller.

#### LINUX

Kernel Hackers Manual March 2006
bus_add_device
9

#### bus_add_device

add device to bus

##### Synopsis

       int bus_add_device
       struct device * dev

##### Arguments

`dev`

  device being added

##### Description

- Add the device to its bus's list of devices. - Try to attach to driver. - Create link to device's physical location.

#### LINUX

Kernel Hackers Manual March 2006
bus_remove_device
9

#### bus_remove_device

remove device from bus

##### Synopsis

       void bus_remove_device
       struct device * dev

##### Arguments

`dev`

  device to be removed

##### Description

- Remove symlink from bus's directory. - Delete device from bus's list. - Detach from its driver. - Drop reference taken in `bus_add_device`.

#### LINUX

Kernel Hackers Manual March 2006
bus_rescan_devices
9

#### bus_rescan_devices

rescan devices on the bus for possible drivers

##### Synopsis

       void bus_rescan_devices
       struct bus_type * bus

##### Arguments

`bus`

  the bus to scan.

##### Description

This function will look for devices on the bus with no driver attached and rescan it against existing drivers to see if it matches any by calling `device_attach` for the unbound devices.

#### LINUX

Kernel Hackers Manual March 2006
find_bus
9

#### find_bus

locate bus by name.

##### Synopsis

       struct bus_type * find_bus
       char * name

##### Arguments

`name`

  name of bus.

##### Description

Call `kset_find_obj` to iterate over list of buses to find a bus by name. Return bus if found.

Note that kset_find_obj increments bus' reference count.

#### LINUX

Kernel Hackers Manual March 2006
bus_register
9

#### bus_register

register a bus with the system.

##### Synopsis

       int bus_register
       struct bus_type * bus

##### Arguments

`bus`

  bus.

##### Description

Once we have that, we registered the bus with the kobject infrastructure, then register the children subsystems it has: the devices and drivers that belong to the bus.

#### LINUX

Kernel Hackers Manual March 2006
bus_unregister
9

#### bus_unregister

remove a bus from the system

##### Synopsis

       void bus_unregister
       struct bus_type * bus

##### Arguments

`bus`

  bus.

##### Description

Unregister the child subsystems and the bus itself. Finally, we call `put_bus` to release the refcount

### Device Drivers Power Management

#### LINUX

Kernel Hackers Manual March 2006
device_pm_set_parent
9

#### device_pm_set_parent

Specify power dependency.

##### Synopsis

       void device_pm_set_parent
       struct device * dev
       struct device * parent

##### Arguments

`dev`

  Device who needs power.

`parent`

  Device that supplies power.

##### Description

This function is used to manually describe a power-dependency relationship. It may be used to specify a transversal relationship (where the power supplier is not the physical (or electrical) ancestor of a specific device. The effect of this is that the supplier will not be powered down before the power dependent.

#### LINUX

Kernel Hackers Manual March 2006
device_resume
9

#### device_resume

Restore state of each device in system.

##### Synopsis

       void device_resume
        void

##### Arguments

`void`

  no arguments

##### Description

Walk the dpm_off list, remove each entry, resume the device, then add it to the dpm_active list.

#### LINUX

Kernel Hackers Manual March 2006
device_power_up
9

#### device_power_up

Turn on all devices that need special attention.

##### Synopsis

       void device_power_up
        void

##### Arguments

`void`

  no arguments

##### Description

Power on system devices then devices that required we shut them down with interrupts disabled. Called with interrupts disabled.

#### LINUX

Kernel Hackers Manual March 2006
device_suspend
9

#### device_suspend

Save state and stop all devices in system.

##### Synopsis

       int device_suspend
       pm_message_t state

##### Arguments

`state`

  Power state to put each device in.

##### Description

Walk the dpm_active list, call ->`suspend` for each device, and move it to dpm_off. Check the return value for each. If it returns 0, then we move the the device to the dpm_off list. If it returns -EAGAIN, we move it to the dpm_off_irq list. If we get a different error, try and back out.

If we hit a failure with any of the devices, call `device_resume` above to bring the suspended devices back to life.

#### LINUX

Kernel Hackers Manual March 2006
device_power_down
9

#### device_power_down

Shut down special devices.

##### Synopsis

       int device_power_down
       pm_message_t state

##### Arguments

`state`

  Power state to enter.

##### Description

Walk the dpm_off_irq list, calling ->`power_down` for each device that couldn't power down the device with interrupts enabled. When we're done, power down system devices.

### Device Drivers ACPI Support

#### LINUX

Kernel Hackers Manual March 2006
acpi_bus_register_driver
9

#### acpi_bus_register_driver

register a driver with the ACPI bus

##### Synopsis

       int acpi_bus_register_driver
       struct acpi_driver * driver

##### Arguments

`driver`

  driver being registered

##### Description

Registers a driver with the ACPI bus. Searches the namespace for all devices that match the driver's criteria and binds. Returns the number of devices that were claimed by the driver, or a negative error status for failure.

#### LINUX

Kernel Hackers Manual March 2006
acpi_bus_unregister_driver
9

#### acpi_bus_unregister_driver

unregisters a driver with the APIC bus

##### Synopsis

       int acpi_bus_unregister_driver
       struct acpi_driver * driver

##### Arguments

`driver`

  driver to unregister

##### Description

Unregisters a driver with the ACPI bus. Searches the namespace for all devices that match the driver's criteria and unbinds.

#### LINUX

Kernel Hackers Manual March 2006
setup_sys_fs_device_files
9

#### setup_sys_fs_device_files

sets up the device files under device namespace

##### Synopsis

       void setup_sys_fs_device_files
       struct acpi_device * dev
       acpi_device_sysfs_files * func

##### Arguments

`dev`

  acpi_device object

`func`

  function pointer to create or destroy the device file

#### LINUX

Kernel Hackers Manual March 2006
acpi_bus_match
9

#### acpi_bus_match

match device IDs to driver's supported IDs

##### Synopsis

       int acpi_bus_match
       struct acpi_device * device
       struct acpi_driver * driver

##### Arguments

`device`

  the device that we are trying to match to a driver

`driver`

  driver whose device id table is being checked

##### Description

Checks the device's hardware (_HID) or compatible (_CID) ids to see if it matches the specified driver's criteria.

#### LINUX

Kernel Hackers Manual March 2006
acpi_bus_driver_init
9

#### acpi_bus_driver_init

add a device to a driver

##### Synopsis

       int acpi_bus_driver_init
       struct acpi_device * device
       struct acpi_driver * driver

##### Arguments

`device`

  the device to add and initialize

`driver`

  driver for the device

##### Description

Used to initialize a device via its device driver. Called whenever a driver is bound to a device. Invokes the driver's `add` and `start` ops.

#### LINUX

Kernel Hackers Manual March 2006
acpi_bus_find_driver
9

#### acpi_bus_find_driver

check if there is a driver installed for the device

##### Synopsis

       int acpi_bus_find_driver
       struct acpi_device * device

##### Arguments

`device`

  device that we are trying to find a supporting driver for

##### Description

Parses the list of registered drivers looking for a driver applicable for the specified device.

### Device drivers PnP support

#### LINUX

Kernel Hackers Manual March 2006
pnp_register_protocol
9

#### pnp_register_protocol

adds a pnp protocol to the pnp layer

##### Synopsis

       int pnp_register_protocol
       struct pnp_protocol * protocol

##### Arguments

`protocol`

  pointer to the corresponding pnp_protocol structure

##### Ex protocols

ISAPNP, PNPBIOS, etc

#### LINUX

Kernel Hackers Manual March 2006
pnp_unregister_protocol
9

#### pnp_unregister_protocol

removes a pnp protocol from the pnp layer

##### Synopsis

       void pnp_unregister_protocol
       struct pnp_protocol * protocol

##### Arguments

`protocol`

  pointer to the corresponding pnp_protocol structure

#### LINUX

Kernel Hackers Manual March 2006
pnp_remove_device
9

#### pnp_remove_device

removes a pnp device from the pnp layer

##### Synopsis

       void pnp_remove_device
       struct pnp_dev * dev

##### Arguments

`dev`

  pointer to dev to add

##### Description

this function will free all mem used by dev

#### LINUX

Kernel Hackers Manual March 2006
pnp_add_card_id
9

#### pnp_add_card_id

adds an EISA id to the specified card

##### Synopsis

       int pnp_add_card_id
       struct pnp_id * id
       struct pnp_card * card

##### Arguments

`id`

  pointer to a pnp_id structure

`card`

  pointer to the desired card

#### LINUX

Kernel Hackers Manual March 2006
pnp_add_card
9

#### pnp_add_card

adds a PnP card to the PnP Layer

##### Synopsis

       int pnp_add_card
       struct pnp_card * card

##### Arguments

`card`

  pointer to the card to add

#### LINUX

Kernel Hackers Manual March 2006
pnp_remove_card
9

#### pnp_remove_card

removes a PnP card from the PnP Layer

##### Synopsis

       void pnp_remove_card
       struct pnp_card * card

##### Arguments

`card`

  pointer to the card to remove

#### LINUX

Kernel Hackers Manual March 2006
pnp_add_card_device
9

#### pnp_add_card_device

adds a device to the specified card

##### Synopsis

       int pnp_add_card_device
       struct pnp_card * card
       struct pnp_dev * dev

##### Arguments

`card`

  pointer to the card to add to

`dev`

  pointer to the device to add

#### LINUX

Kernel Hackers Manual March 2006
pnp_remove_card_device
9

#### pnp_remove_card_device

removes a device from the specified card

##### Synopsis

       void pnp_remove_card_device
       struct pnp_dev * dev

##### Arguments

`dev`

  pointer to the device to remove

#### LINUX

Kernel Hackers Manual March 2006
pnp_request_card_device
9

#### pnp_request_card_device

Searches for a PnP device under the specified card

##### Synopsis

       struct pnp_dev * pnp_request_card_device
       struct pnp_card_link * clink
       const char * id
       struct pnp_dev * from

##### Arguments

`clink`

  pointer to the card link, cannot be NULL

`id`

  pointer to a PnP ID structure that explains the rules for finding the device

`from`

  Starting place to search from. If NULL it will start from the begining.

#### LINUX

Kernel Hackers Manual March 2006
pnp_release_card_device
9

#### pnp_release_card_device

call this when the driver no longer needs the device

##### Synopsis

       void pnp_release_card_device
       struct pnp_dev * dev

##### Arguments

`dev`

  pointer to the PnP device stucture

#### LINUX

Kernel Hackers Manual March 2006
pnp_register_card_driver
9

#### pnp_register_card_driver

registers a PnP card driver with the PnP Layer

##### Synopsis

       int pnp_register_card_driver
       struct pnp_card_driver * drv

##### Arguments

`drv`

  pointer to the driver to register

#### LINUX

Kernel Hackers Manual March 2006
pnp_unregister_card_driver
9

#### pnp_unregister_card_driver

unregisters a PnP card driver from the PnP Layer

##### Synopsis

       void pnp_unregister_card_driver
       struct pnp_card_driver * drv

##### Arguments

`drv`

  pointer to the driver to unregister

#### LINUX

Kernel Hackers Manual March 2006
pnp_add_id
9

#### pnp_add_id

adds an EISA id to the specified device

##### Synopsis

       int pnp_add_id
       struct pnp_id * id
       struct pnp_dev * dev

##### Arguments

`id`

  pointer to a pnp_id structure

`dev`

  pointer to the desired device

#### LINUX

Kernel Hackers Manual March 2006
pnp_init_resource_table
9

#### pnp_init_resource_table

Resets a resource table to default values.

##### Synopsis

       void pnp_init_resource_table
       struct pnp_resource_table * table

##### Arguments

`table`

  pointer to the desired resource table

#### LINUX

Kernel Hackers Manual March 2006
pnp_manual_config_dev
9

#### pnp_manual_config_dev

Disables Auto Config and Manually sets the resource table

##### Synopsis

       int pnp_manual_config_dev
       struct pnp_dev * dev
       struct pnp_resource_table * res
       int mode

##### Arguments

`dev`

  pointer to the desired device

`res`

  pointer to the new resource config

`mode`

  0 or PNP_CONFIG_FORCE

##### Description

This function can be used by drivers that want to manually set thier resources.

#### LINUX

Kernel Hackers Manual March 2006
pnp_auto_config_dev
9

#### pnp_auto_config_dev

automatically assigns resources to a device

##### Synopsis

       int pnp_auto_config_dev
       struct pnp_dev * dev

##### Arguments

`dev`

  pointer to the desired device

#### LINUX

Kernel Hackers Manual March 2006
pnp_start_dev
9

#### pnp_start_dev

low-level start of the PnP device

##### Synopsis

       int pnp_start_dev
       struct pnp_dev * dev

##### Arguments

`dev`

  pointer to the desired device

##### Description

assumes that resources have alread been allocated

#### LINUX

Kernel Hackers Manual March 2006
pnp_stop_dev
9

#### pnp_stop_dev

low-level disable of the PnP device

##### Synopsis

       int pnp_stop_dev
       struct pnp_dev * dev

##### Arguments

`dev`

  pointer to the desired device

##### Description

does not free resources

#### LINUX

Kernel Hackers Manual March 2006
pnp_activate_dev
9

#### pnp_activate_dev

activates a PnP device for use

##### Synopsis

       int pnp_activate_dev
       struct pnp_dev * dev

##### Arguments

`dev`

  pointer to the desired device

##### Description

does not validate or set resources so be careful.

#### LINUX

Kernel Hackers Manual March 2006
pnp_disable_dev
9

#### pnp_disable_dev

disables device

##### Synopsis

       int pnp_disable_dev
       struct pnp_dev * dev

##### Arguments

`dev`

  pointer to the desired device

##### Description

inform the correct pnp protocol so that resources can be used by other devices

#### LINUX

Kernel Hackers Manual March 2006
pnp_resource_change
9

#### pnp_resource_change

change one resource

##### Synopsis

       void pnp_resource_change
       struct resource * resource
       unsigned long start
       unsigned long size

##### Arguments

`resource`

  pointer to resource to be changed

`start`

  start of region

`size`

  size of region

#### LINUX

Kernel Hackers Manual March 2006
pnp_is_active
9

#### pnp_is_active

Determines if a device is active based on its current resources

##### Synopsis

       int pnp_is_active
       struct pnp_dev * dev

##### Arguments

`dev`

  pointer to the desired PnP device

## Block Devices

### LINUX

Kernel Hackers Manual March 2006
blk_get_backing_dev_info
9

### blk_get_backing_dev_info

get the address of a queue's backing_dev_info

#### Synopsis

       struct backing_dev_info * blk_get_backing_dev_info
       struct block_device * bdev

#### Arguments

`bdev`

  device

#### Description

Locates the passed device's request queue and returns the address of its backing_dev_info

Will return NULL if the request queue cannot be located.

### LINUX

Kernel Hackers Manual March 2006
blk_queue_prep_rq
9

### blk_queue_prep_rq

set a prepare_request function for queue

#### Synopsis

       void blk_queue_prep_rq
       request_queue_t * q
       prep_rq_fn * pfn

#### Arguments

`q`

  queue

`pfn`

  prepare_request function

#### Description

It's possible for a queue to register a prepare_request callback which is invoked before the request is handed to the request_fn. The goal of the function is to prepare a request for I/O, it can be used to build a cdb from the request data for instance.

### LINUX

Kernel Hackers Manual March 2006
blk_queue_merge_bvec
9

### blk_queue_merge_bvec

set a merge_bvec function for queue

#### Synopsis

       void blk_queue_merge_bvec
       request_queue_t * q
       merge_bvec_fn * mbfn

#### Arguments

`q`

  queue

`mbfn`

  merge_bvec_fn

#### Description

Usually queues have static limitations on the max sectors or segments that we can put in a request. Stacking drivers may have some settings that are dynamic, and thus we have to query the queue whether it is ok to add a new bio_vec to a bio at a given offset or not. If the block device has such limitations, it needs to register a merge_bvec_fn to control the size of bio's sent to it. Note that a block device *must* allow a single page to be added to an empty bio. The block device driver may want to use the `bio_split` function to deal with these bio's. By default no merge_bvec_fn is defined for a queue, and only the fixed limits are honored.

### LINUX

Kernel Hackers Manual March 2006
blk_queue_make_request
9

### blk_queue_make_request

define an alternate make_request function for a device

#### Synopsis

       void blk_queue_make_request
       request_queue_t * q
       make_request_fn * mfn

#### Arguments

`q`

  the request queue for the device to be affected

`mfn`

  the alternate make_request function

#### Description

The normal way for &struct bios to be passed to a device driver is for them to be collected into requests on a request queue, and then to allow the device driver to select requests off that queue when it is ready. This works well for many block devices. However some block devices (typically virtual devices such as md or lvm) do not benefit from the processing on the request queue, and are served best by having the requests passed directly to them. This can be achieved by providing a function to `blk_queue_make_request`.

#### Caveat

The driver that does this *must* be able to deal appropriately with buffers in highmemory. This can be accomplished by either calling `__bio_kmap_atomic` to get a temporary kernel mapping, or by calling `blk_queue_bounce` to create a buffer in normal memory.

### LINUX

Kernel Hackers Manual March 2006
blk_queue_ordered
9

### blk_queue_ordered

does this queue support ordered writes

#### Synopsis

       int blk_queue_ordered
       request_queue_t * q
       unsigned ordered
       prepare_flush_fn * prepare_flush_fn

#### Arguments

`q`

  the request queue

`ordered`

  one of QUEUE_ORDERED_*

`prepare_flush_fn`

  rq setup helper for cache flush ordered writes

#### Description

For journalled file systems, doing ordered writes on a commit block instead of explicitly doing wait_on_buffer (which is bad for performance) can be a big win. Block drivers supporting this feature should call this function and indicate so.

### LINUX

Kernel Hackers Manual March 2006
blk_queue_issue_flush_fn
9

### blk_queue_issue_flush_fn

set function for issuing a flush

#### Synopsis

       void blk_queue_issue_flush_fn
       request_queue_t * q
       issue_flush_fn * iff

#### Arguments

`q`

  the request queue

`iff`

  the function to be called issuing the flush

#### Description

If a driver supports issuing a flush command, the support is notified to the block layer by defining it through this call.

### LINUX

Kernel Hackers Manual March 2006
blk_queue_bounce_limit
9

### blk_queue_bounce_limit

set bounce buffer limit for queue

#### Synopsis

       void blk_queue_bounce_limit
       request_queue_t * q
       u64 dma_addr

#### Arguments

`q`

  the request queue for the device

`dma_addr`

  bus address limit

#### Description

Different hardware can have different requirements as to what pages it can do I/O directly to. A low level driver can call blk_queue_bounce_limit to have lower memory pages allocated as bounce buffers for doing I/O to pages residing above `page`.

### LINUX

Kernel Hackers Manual March 2006
blk_queue_max_sectors
9

### blk_queue_max_sectors

set max sectors for a request for this queue

#### Synopsis

       void blk_queue_max_sectors
       request_queue_t * q
       unsigned int max_sectors

#### Arguments

`q`

  the request queue for the device

`max_sectors`

  max sectors in the usual 512b unit

#### Description

Enables a low level driver to set an upper limit on the size of received requests.

### LINUX

Kernel Hackers Manual March 2006
blk_queue_max_phys_segments
9

### blk_queue_max_phys_segments

set max phys segments for a request for this queue

#### Synopsis

       void blk_queue_max_phys_segments
       request_queue_t * q
       unsigned short max_segments

#### Arguments

`q`

  the request queue for the device

`max_segments`

  max number of segments

#### Description

Enables a low level driver to set an upper limit on the number of physical data segments in a request. This would be the largest sized scatter list the driver could handle.

### LINUX

Kernel Hackers Manual March 2006
blk_queue_max_hw_segments
9

### blk_queue_max_hw_segments

set max hw segments for a request for this queue

#### Synopsis

       void blk_queue_max_hw_segments
       request_queue_t * q
       unsigned short max_segments

#### Arguments

`q`

  the request queue for the device

`max_segments`

  max number of segments

#### Description

Enables a low level driver to set an upper limit on the number of hw data segments in a request. This would be the largest number of address/length pairs the host adapter can actually give as once to the device.

### LINUX

Kernel Hackers Manual March 2006
blk_queue_max_segment_size
9

### blk_queue_max_segment_size

set max segment size for blk_rq_map_sg

#### Synopsis

       void blk_queue_max_segment_size
       request_queue_t * q
       unsigned int max_size

#### Arguments

`q`

  the request queue for the device

`max_size`

  max size of segment in bytes

#### Description

Enables a low level driver to set an upper limit on the size of a coalesced segment

### LINUX

Kernel Hackers Manual March 2006
blk_queue_hardsect_size
9

### blk_queue_hardsect_size

set hardware sector size for the queue

#### Synopsis

       void blk_queue_hardsect_size
       request_queue_t * q
       unsigned short size

#### Arguments

`q`

  the request queue for the device

`size`

  the hardware sector size, in bytes

#### Description

This should typically be set to the lowest possible sector size that the hardware can operate on (possible without reverting to even internal read-modify-write operations). Usually the default of 512 covers most hardware.

### LINUX

Kernel Hackers Manual March 2006
blk_queue_stack_limits
9

### blk_queue_stack_limits

inherit underlying queue limits for stacked drivers

#### Synopsis

       void blk_queue_stack_limits
       request_queue_t * t
       request_queue_t * b

#### Arguments

`t`

  the stacking driver (top)

`b`

  the underlying device (bottom)

### LINUX

Kernel Hackers Manual March 2006
blk_queue_segment_boundary
9

### blk_queue_segment_boundary

set boundary rules for segment merging

#### Synopsis

       void blk_queue_segment_boundary
       request_queue_t * q
       unsigned long mask

#### Arguments

`q`

  the request queue for the device

`mask`

  the memory boundary mask

### LINUX

Kernel Hackers Manual March 2006
blk_queue_dma_alignment
9

### blk_queue_dma_alignment

set dma length and memory alignment

#### Synopsis

       void blk_queue_dma_alignment
       request_queue_t * q
       int mask

#### Arguments

`q`

  the request queue for the device

`mask`

  alignment mask

#### description

set required memory and length aligment for direct dma transactions. this is used when buiding direct io requests for the queue.

### LINUX

Kernel Hackers Manual March 2006
blk_queue_find_tag
9

### blk_queue_find_tag

find a request by its tag and queue

#### Synopsis

       struct request * blk_queue_find_tag
       request_queue_t * q
       int tag

#### Arguments

`q`

  The request queue for the device

`tag`

  The tag of the request

#### Notes

Should be used when a device returns a tag and you want to match it with a request.

no locks need be held.

### LINUX

Kernel Hackers Manual March 2006
blk_queue_free_tags
9

### blk_queue_free_tags

release tag maintenance info

#### Synopsis

       void blk_queue_free_tags
       request_queue_t * q

#### Arguments

`q`

  the request queue for the device

#### Notes

This is used to disabled tagged queuing to a device, yet leave queue in function.

### LINUX

Kernel Hackers Manual March 2006
blk_queue_init_tags
9

### blk_queue_init_tags

initialize the queue tag info

#### Synopsis

       int blk_queue_init_tags
       request_queue_t * q
       int depth
       struct blk_queue_tag * tags

#### Arguments

`q`

  the request queue for the device

`depth`

  the maximum queue depth supported

`tags`

  the tag to use

### LINUX

Kernel Hackers Manual March 2006
blk_queue_resize_tags
9

### blk_queue_resize_tags

change the queueing depth

#### Synopsis

       int blk_queue_resize_tags
       request_queue_t * q
       int new_depth

#### Arguments

`q`

  the request queue for the device

`new_depth`

  the new max command queueing depth

#### Notes

Must be called with the queue lock held.

### LINUX

Kernel Hackers Manual March 2006
blk_queue_end_tag
9

### blk_queue_end_tag

end tag operations for a request

#### Synopsis

       void blk_queue_end_tag
       request_queue_t * q
       struct request * rq

#### Arguments

`q`

  the request queue for the device

`rq`

  the request that has completed

#### Description

Typically called when `end_that_request_first` returns 0, meaning all transfers have been done for a request. It's important to call this function before `end_that_request_last`, as that will put the request back on the free list thus corrupting the internal tag list.

#### Notes

queue lock must be held.

### LINUX

Kernel Hackers Manual March 2006
blk_queue_start_tag
9

### blk_queue_start_tag

find a free tag and assign it

#### Synopsis

       int blk_queue_start_tag
       request_queue_t * q
       struct request * rq

#### Arguments

`q`

  the request queue for the device

`rq`

  the block request that needs tagging

#### Description

This can either be used as a stand-alone helper, or possibly be assigned as the queue &prep_rq_fn (in which case &struct request automagically gets a tag assigned). Note that this function assumes that any type of request can be queued! if this is not true for your device, you must check the request type before calling this function. The request will also be removed from the request queue, so it's the drivers responsibility to readd it if it should need to be restarted for some reason.

#### Notes

queue lock must be held.

### LINUX

Kernel Hackers Manual March 2006
blk_queue_invalidate_tags
9

### blk_queue_invalidate_tags

invalidate all pending tags

#### Synopsis

       void blk_queue_invalidate_tags
       request_queue_t * q

#### Arguments

`q`

  the request queue for the device

#### Description

Hardware conditions may dictate a need to stop all pending requests. In this case, we will safely clear the block side of the tag queue and readd all requests to the request queue in the right order.

#### Notes

queue lock must be held.

### LINUX

Kernel Hackers Manual March 2006
generic_unplug_device
9

### generic_unplug_device

fire a request queue

#### Synopsis

       void generic_unplug_device
       request_queue_t * q

#### Arguments

`q`

  The &request_queue_t in question

#### Description

Linux uses plugging to build bigger requests queues before letting the device have at them. If a queue is plugged, the I/O scheduler is still adding and merging requests on the queue. Once the queue gets unplugged, the request_fn defined for the queue is invoked and transfers started.

### LINUX

Kernel Hackers Manual March 2006
blk_start_queue
9

### blk_start_queue

restart a previously stopped queue

#### Synopsis

       void blk_start_queue
       request_queue_t * q

#### Arguments

`q`

  The &request_queue_t in question

#### Description

`blk_start_queue` will clear the stop flag on the queue, and call the request_fn for the queue if it was in a stopped state when entered. Also see `blk_stop_queue`. Queue lock must be held.

### LINUX

Kernel Hackers Manual March 2006
blk_stop_queue
9

### blk_stop_queue

stop a queue

#### Synopsis

       void blk_stop_queue
       request_queue_t * q

#### Arguments

`q`

  The &request_queue_t in question

#### Description

The Linux block layer assumes that a block driver will consume all entries on the request queue when the request_fn strategy is called. Often this will not happen, because of hardware limitations (queue depth settings). If a device driver gets a 'queue full' response, or if it simply chooses not to queue more I/O at one point, it can call this function to prevent the request_fn from being called until the driver has signalled it's ready to go again. This happens by calling `blk_start_queue` to restart queue operations. Queue lock must be held.

### LINUX

Kernel Hackers Manual March 2006
blk_sync_queue
9

### blk_sync_queue

cancel any pending callbacks on a queue

#### Synopsis

       void blk_sync_queue
       struct request_queue * q

#### Arguments

`q`

  the queue

#### Description

The block layer may perform asynchronous callback activity on a queue, such as calling the unplug function after a timeout. A block device may call blk_sync_queue to ensure that any such activity is cancelled, thus allowing it to release resources the the callbacks might use. The caller must already have made sure that its ->make_request_fn will not re-add plugging prior to calling this function.

### LINUX

Kernel Hackers Manual March 2006
blk_run_queue
9

### blk_run_queue

run a single device queue

#### Synopsis

       void blk_run_queue
       struct request_queue * q

#### Arguments

`q`

  The queue to run

### LINUX

Kernel Hackers Manual March 2006
blk_cleanup_queue
9

### blk_cleanup_queue

release a &request_queue_t when it is no longer needed

#### Synopsis

       void blk_cleanup_queue
       request_queue_t * q

#### Arguments

`q`

  the request queue to be released

#### Description

blk_cleanup_queue is the pair to `blk_init_queue` or `blk_queue_make_request`. It should be called when a request queue is being released; typically when a block device is being de-registered. Currently, its primary task it to free all the &struct request structures that were allocated to the queue and the queue itself.

#### Caveat

Hopefully the low level driver will have finished any outstanding requests first...

### LINUX

Kernel Hackers Manual March 2006
blk_init_queue
9

### blk_init_queue

prepare a request queue for use with a block device

#### Synopsis

       request_queue_t * blk_init_queue
       request_fn_proc * rfn
       spinlock_t * lock

#### Arguments

`rfn`

  The function to be called to process requests that have been placed on the queue.

`lock`

  Request queue spin lock

#### Description

If a block device wishes to use the standard request handling procedures, which sorts requests and coalesces adjacent requests, then it must call `blk_init_queue`. The function `rfn` will be called when there are requests on the queue that need to be processed. If the device supports plugging, then `rfn` may not be called immediately when requests are available on the queue, but may be called at some time later instead. Plugged queues are generally unplugged when a buffer belonging to one of the requests on the queue is needed, or due to memory pressure.

`rfn` is not required, or even expected, to remove all requests off the queue, but only as many as it can handle at a time. If it does leave requests on the queue, it is responsible for arranging that the requests get dealt with eventually.

The queue spin lock must be held while manipulating the requests on the request queue.

Function returns a pointer to the initialized request queue, or NULL if it didn't succeed.

#### Note

`blk_init_queue` must be paired with a `blk_cleanup_queue` call when the block device is deactivated (such as at module unload).

### LINUX

Kernel Hackers Manual March 2006
blk_requeue_request
9

### blk_requeue_request

put a request back on queue

#### Synopsis

       void blk_requeue_request
       request_queue_t * q
       struct request * rq

#### Arguments

`q`

  request queue where request should be inserted

`rq`

  request to be inserted

#### Description

Drivers often keep queueing requests until the hardware cannot accept more, when that condition happens we need to put the request back on the queue. Must be called with queue lock held.

### LINUX

Kernel Hackers Manual March 2006
blk_insert_request
9

### blk_insert_request

insert a special request in to a request queue

#### Synopsis

       void blk_insert_request
       request_queue_t * q
       struct request * rq
       int at_head
       void * data

#### Arguments

`q`

  request queue where request should be inserted

`rq`

  request to be inserted

`at_head`

  insert request at head or tail of queue

`data`

  private data

#### Description

Many block devices need to execute commands asynchronously, so they don't block the whole kernel from preemption during request execution. This is accomplished normally by inserting aritficial requests tagged as REQ_SPECIAL in to the corresponding request queue, and letting them be scheduled for actual execution by the request queue.

We have the option of inserting the head or the tail of the queue. Typically we use the tail for new ioctls and so forth. We use the head of the queue for things like a QUEUE_FULL message from a device, or a host that is unable to accept a particular command.

### LINUX

Kernel Hackers Manual March 2006
blk_rq_map_user
9

### blk_rq_map_user

map user data to a request, for REQ_BLOCK_PC usage

#### Synopsis

       int blk_rq_map_user
       request_queue_t * q
       struct request * rq
       void __user * ubuf
       unsigned int len

#### Arguments

`q`

  request queue where request should be inserted

`rq`

  request structure to fill

`ubuf`

  the user buffer

`len`

  length of user data

#### Description

Data will be mapped directly for zero copy io, if possible. Otherwise a kernel bounce buffer is used.

A matching `blk_rq_unmap_user` must be issued at the end of io, while still in process context.

#### Note

The mapped bio may need to be bounced through `blk_queue_bounce` before being submitted to the device, as pages mapped may be out of reach. It's the callers responsibility to make sure this happens. The original bio must be passed back in to `blk_rq_unmap_user` for proper unmapping.

### LINUX

Kernel Hackers Manual March 2006
blk_rq_map_user_iov
9

### blk_rq_map_user_iov

map user data to a request, for REQ_BLOCK_PC usage

#### Synopsis

       int blk_rq_map_user_iov
       request_queue_t * q
       struct request * rq
       struct sg_iovec * iov
       int iov_count

#### Arguments

`q`

  request queue where request should be inserted

`rq`

  request to map data to

`iov`

  pointer to the iovec

`iov_count`

  number of elements in the iovec

#### Description

Data will be mapped directly for zero copy io, if possible. Otherwise a kernel bounce buffer is used.

A matching `blk_rq_unmap_user` must be issued at the end of io, while still in process context.

#### Note

The mapped bio may need to be bounced through `blk_queue_bounce` before being submitted to the device, as pages mapped may be out of reach. It's the callers responsibility to make sure this happens. The original bio must be passed back in to `blk_rq_unmap_user` for proper unmapping.

### LINUX

Kernel Hackers Manual March 2006
blk_rq_unmap_user
9

### blk_rq_unmap_user

unmap a request with user data

#### Synopsis

       int blk_rq_unmap_user
       struct bio * bio
       unsigned int ulen

#### Arguments

`bio`

  bio to be unmapped

`ulen`

  length of user buffer

#### Description

Unmap a bio previously mapped by `blk_rq_map_user`.

### LINUX

Kernel Hackers Manual March 2006
blk_rq_map_kern
9

### blk_rq_map_kern

map kernel data to a request, for REQ_BLOCK_PC usage

#### Synopsis

       int blk_rq_map_kern
       request_queue_t * q
       struct request * rq
       void * kbuf
       unsigned int len
       gfp_t gfp_mask

#### Arguments

`q`

  request queue where request should be inserted

`rq`

  request to fill

`kbuf`

  the kernel buffer

`len`

  length of user data

`gfp_mask`

  memory allocation flags

### LINUX

Kernel Hackers Manual March 2006
blk_execute_rq_nowait
9

### blk_execute_rq_nowait

insert a request into queue for execution

#### Synopsis

       void blk_execute_rq_nowait
       request_queue_t * q
       struct gendisk * bd_disk
       struct request * rq
       int at_head
       rq_end_io_fn * done

#### Arguments

`q`

  queue to insert the request in

`bd_disk`

  matching gendisk

`rq`

  request to insert

`at_head`

  insert request at head or tail of queue

`done`

  I/O completion handler

#### Description

Insert a fully prepared request at the back of the io scheduler queue for execution. Don't wait for completion.

### LINUX

Kernel Hackers Manual March 2006
blk_execute_rq
9

### blk_execute_rq

insert a request into queue for execution

#### Synopsis

       int blk_execute_rq
       request_queue_t * q
       struct gendisk * bd_disk
       struct request * rq
       int at_head

#### Arguments

`q`

  queue to insert the request in

`bd_disk`

  matching gendisk

`rq`

  request to insert

`at_head`

  insert request at head or tail of queue

#### Description

Insert a fully prepared request at the back of the io scheduler queue for execution and wait for completion.

### LINUX

Kernel Hackers Manual March 2006
blkdev_issue_flush
9

### blkdev_issue_flush

queue a flush

#### Synopsis

       int blkdev_issue_flush
       struct block_device * bdev
       sector_t * error_sector

#### Arguments

`bdev`

  blockdev to issue flush for

`error_sector`

  error sector

#### Description

Issue a flush for the block device in question. Caller can supply room for storing the error offset in case of a flush error, if they wish to. Caller must run `wait_for_completion` on its own.

### LINUX

Kernel Hackers Manual March 2006
blk_end_sync_rq
9

### blk_end_sync_rq

executes a completion event on a request

#### Synopsis

       void blk_end_sync_rq
       struct request * rq
       int error

#### Arguments

`rq`

  request to complete

`error`

  end io status of the request

### LINUX

Kernel Hackers Manual March 2006
blk_congestion_wait
9

### blk_congestion_wait

wait for a queue to become uncongested

#### Synopsis

       long blk_congestion_wait
       int rw
       long timeout

#### Arguments

`rw`

  READ or WRITE

`timeout`

  timeout in jiffies

#### Description

Waits for up to `timeout` jiffies for a queue (any queue) to exit congestion. If no queues are congested then just wait for the next request to be returned.

### LINUX

Kernel Hackers Manual March 2006
generic_make_request
9

### generic_make_request

#### Synopsis

       void generic_make_request
       struct bio * bio

#### Arguments

`bio`

  The bio describing the location in memory and on the device.

#### Description

`generic_make_request` is used to make I/O requests of block devices. It is passed a &struct bio, which describes the I/O that needs to be done.

`generic_make_request` does not return any status. The success/failure status of the request, along with notification of completion, is delivered asynchronously through the bio->bi_end_io function described (one day) else where.

The caller of generic_make_request must make sure that bi_io_vec are set to describe the memory buffer, and that bi_dev and bi_sector are set to describe the device address, and the bi_end_io and optionally bi_private are set to describe how completion notification should be signaled.

generic_make_request and the drivers it calls may use bi_next if this bio happens to be merged with someone else, and may change bi_dev and bi_sector for remaps as it sees fit. So the values of these fields should NOT be depended on after the call to generic_make_request.

### LINUX

Kernel Hackers Manual March 2006
submit_bio
9

### submit_bio

#### Synopsis

       void submit_bio
       int rw
       struct bio * bio

#### Arguments

`rw`

  whether to `READ` or `WRITE`, or maybe to `READA` (read ahead)

`bio`

  The &struct bio which describes the I/O

#### Description

`submit_bio` is very similar in purpose to `generic_make_request`, and uses that function to do most of the work. Both are fairly rough interfaces, `bio` must be presetup and ready for I/O.

### LINUX

Kernel Hackers Manual March 2006
end_that_request_first
9

### end_that_request_first

end I/O on a request

#### Synopsis

       int end_that_request_first
       struct request * req
       int uptodate
       int nr_sectors

#### Arguments

`req`

  the request being processed

`uptodate`

  1 for success, 0 for I/O error, < 0 for specific error

`nr_sectors`

  number of sectors to end I/O on

#### Description

Ends I/O on a number of sectors attached to `req`, and sets it up for the next range of segments (if any) in the cluster.

#### Return

0 - we are done with this request, call `end_that_request_last` 1 - still buffers pending for this request

### LINUX

Kernel Hackers Manual March 2006
end_that_request_chunk
9

### end_that_request_chunk

end I/O on a request

#### Synopsis

       int end_that_request_chunk
       struct request * req
       int uptodate
       int nr_bytes

#### Arguments

`req`

  the request being processed

`uptodate`

  1 for success, 0 for I/O error, < 0 for specific error

`nr_bytes`

  number of bytes to complete

#### Description

Ends I/O on a number of bytes attached to `req`, and sets it up for the next range of segments (if any). Like `end_that_request_first`, but deals with bytes instead of sectors.

#### Return

0 - we are done with this request, call `end_that_request_last` 1 - still buffers pending for this request

### LINUX

Kernel Hackers Manual March 2006
blk_complete_request
9

### blk_complete_request

end I/O on a request

#### Synopsis

       void blk_complete_request
       struct request * req

#### Arguments

`req`

  the request being processed

#### Description

Ends all I/O on a request. It does not handle partial completions, unless the driver actually implements this in its completionc callback through requeueing. Theh actual completion happens out-of-order, through a softirq handler. The user must have registered a completion callback through `blk_queue_softirq_done`.

## Miscellaneous Devices

### LINUX

Kernel Hackers Manual March 2006
misc_register
9

### misc_register

register a miscellaneous device

#### Synopsis

       int misc_register
       struct miscdevice * misc

#### Arguments

`misc`

  device structure

#### Description

Register a miscellaneous device with the kernel. If the minor number is set to `MISC_DYNAMIC_MINOR` a minor number is assigned and placed in the minor field of the structure. For other cases the minor number requested is used.

The structure passed is linked into the kernel and may not be destroyed until it has been unregistered.

A zero is returned on success and a negative errno code for failure.

### LINUX

Kernel Hackers Manual March 2006
misc_deregister
9

### misc_deregister

unregister a miscellaneous device

#### Synopsis

       int misc_deregister
       struct miscdevice * misc

#### Arguments

`misc`

  device to unregister

#### Description

Unregister a miscellaneous device that was previously successfully registered with `misc_register`. Success is indicated by a zero return, a negative errno code indicates an error.

## Video4Linux

### LINUX

Kernel Hackers Manual March 2006
video_register_device
9

### video_register_device

register video4linux devices

#### Synopsis

       int video_register_device
       struct video_device * vfd
       int type
       int nr

#### Arguments

`vfd`

  video device structure we want to register

`type`

  type of device to register

`nr`

  which device number (0 == /dev/video0, 1 == /dev/video1, ... -1 == first free)

#### Description

The registration code assigns minor numbers based on the type requested. -ENFILE is returned in all the device slots for this category are full. If not then the minor field is set and the driver initialize function is called (if non `NULL`).

Zero is returned on success.

Valid types are

`VFL_TYPE_GRABBER` - A frame grabber

`VFL_TYPE_VTX` - A teletext device

`VFL_TYPE_VBI` - Vertical blank data (undecoded)

`VFL_TYPE_RADIO` - A radio card

### LINUX

Kernel Hackers Manual March 2006
video_unregister_device
9

### video_unregister_device

unregister a video4linux device

#### Synopsis

       void video_unregister_device
       struct video_device * vfd

#### Arguments

`vfd`

  the device to unregister

#### Description

This unregisters the passed device and deassigns the minor number. Future open calls will be met with errors.

## Sound Devices

### LINUX

Kernel Hackers Manual March 2006
snd_printk
9

### snd_printk

printk wrapper

#### Synopsis

        snd_printk
        fmt
        args...

#### Arguments

`fmt`

  format string

`args...`

  variable arguments

#### Description

Works like `print` but prints the file and the line of the caller when configured with CONFIG_SND_VERBOSE_PRINTK.

### LINUX

Kernel Hackers Manual March 2006
snd_printd
9

### snd_printd

debug printk

#### Synopsis

        snd_printd
        fmt
        args...

#### Arguments

`fmt`

  format string

`args...`

  variable arguments

#### Description

Compiled only when Works like `snd_printk` for debugging purpose. Ignored when CONFIG_SND_DEBUG is not set.

### LINUX

Kernel Hackers Manual March 2006
snd_assert
9

### snd_assert

run-time assertion macro

#### Synopsis

        snd_assert
        expr
        args...

#### Arguments

`expr`

  expression

`args...`

  variable arguments

#### Description

This macro checks the expression in run-time and invokes the commands given in the rest arguments if the assertion is failed. When CONFIG_SND_DEBUG is not set, the expression is executed but not checked.

### LINUX

Kernel Hackers Manual March 2006
snd_printdd
9

### snd_printdd

debug printk

#### Synopsis

        snd_printdd
        format
        args...

#### Arguments

`format`

  format string

`args...`

  variable arguments

#### Description

Compiled only when Works like `snd_printk` for debugging purpose. Ignored when CONFIG_SND_DEBUG_DETECT is not set.

### LINUX

Kernel Hackers Manual March 2006
register_sound_special_device
9

### register_sound_special_device

register a special sound node

#### Synopsis

       int register_sound_special_device
       struct file_operations * fops
       int unit
       struct device * dev

#### Arguments

`fops`

  File operations for the driver

`unit`

  Unit number to allocate

`dev`

  device pointer

#### Description

Allocate a special sound device by minor number from the sound subsystem. The allocated number is returned on succes. On failure a negative error code is returned.

### LINUX

Kernel Hackers Manual March 2006
register_sound_mixer
9

### register_sound_mixer

register a mixer device

#### Synopsis

       int register_sound_mixer
       struct file_operations * fops
       int dev

#### Arguments

`fops`

  File operations for the driver

`dev`

  Unit number to allocate

#### Description

Allocate a mixer device. Unit is the number of the mixer requested. Pass -1 to request the next free mixer unit. On success the allocated number is returned, on failure a negative error code is returned.

### LINUX

Kernel Hackers Manual March 2006
register_sound_midi
9

### register_sound_midi

register a midi device

#### Synopsis

       int register_sound_midi
       struct file_operations * fops
       int dev

#### Arguments

`fops`

  File operations for the driver

`dev`

  Unit number to allocate

#### Description

Allocate a midi device. Unit is the number of the midi device requested. Pass -1 to request the next free midi unit. On success the allocated number is returned, on failure a negative error code is returned.

### LINUX

Kernel Hackers Manual March 2006
register_sound_dsp
9

### register_sound_dsp

register a DSP device

#### Synopsis

       int register_sound_dsp
       struct file_operations * fops
       int dev

#### Arguments

`fops`

  File operations for the driver

`dev`

  Unit number to allocate

#### Description

Allocate a DSP device. Unit is the number of the DSP requested. Pass -1 to request the next free DSP unit. On success the allocated number is returned, on failure a negative error code is returned.

This function allocates both the audio and dsp device entries together and will always allocate them as a matching pair - eg dsp3/audio3

### LINUX

Kernel Hackers Manual March 2006
register_sound_synth
9

### register_sound_synth

register a synth device

#### Synopsis

       int register_sound_synth
       struct file_operations * fops
       int dev

#### Arguments

`fops`

  File operations for the driver

`dev`

  Unit number to allocate

#### Description

Allocate a synth device. Unit is the number of the synth device requested. Pass -1 to request the next free synth unit. On success the allocated number is returned, on failure a negative error code is returned.

### LINUX

Kernel Hackers Manual March 2006
unregister_sound_special
9

### unregister_sound_special

unregister a special sound device

#### Synopsis

       void unregister_sound_special
       int unit

#### Arguments

`unit`

  unit number to allocate

#### Description

Release a sound device that was allocated with `register_sound_special`. The unit passed is the return value from the register function.

### LINUX

Kernel Hackers Manual March 2006
unregister_sound_mixer
9

### unregister_sound_mixer

unregister a mixer

#### Synopsis

       void unregister_sound_mixer
       int unit

#### Arguments

`unit`

  unit number to allocate

#### Description

Release a sound device that was allocated with `register_sound_mixer`. The unit passed is the return value from the register function.

### LINUX

Kernel Hackers Manual March 2006
unregister_sound_midi
9

### unregister_sound_midi

unregister a midi device

#### Synopsis

       void unregister_sound_midi
       int unit

#### Arguments

`unit`

  unit number to allocate

#### Description

Release a sound device that was allocated with `register_sound_midi`. The unit passed is the return value from the register function.

### LINUX

Kernel Hackers Manual March 2006
unregister_sound_dsp
9

### unregister_sound_dsp

unregister a DSP device

#### Synopsis

       void unregister_sound_dsp
       int unit

#### Arguments

`unit`

  unit number to allocate

#### Description

Release a sound device that was allocated with `register_sound_dsp`. The unit passed is the return value from the register function.

Both of the allocated units are released together automatically.

### LINUX

Kernel Hackers Manual March 2006
unregister_sound_synth
9

### unregister_sound_synth

unregister a synth device

#### Synopsis

       void unregister_sound_synth
       int unit

#### Arguments

`unit`

  unit number to allocate

#### Description

Release a sound device that was allocated with `register_sound_synth`. The unit passed is the return value from the register function.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_playback_ready
9

### snd_pcm_playback_ready

check whether the playback buffer is available

#### Synopsis

       int snd_pcm_playback_ready
       struct snd_pcm_substream * substream

#### Arguments

`substream`

  the pcm substream instance

#### Description

Checks whether enough free space is available on the playback buffer.

Returns non-zero if available, or zero if not.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_capture_ready
9

### snd_pcm_capture_ready

check whether the capture buffer is available

#### Synopsis

       int snd_pcm_capture_ready
       struct snd_pcm_substream * substream

#### Arguments

`substream`

  the pcm substream instance

#### Description

Checks whether enough capture data is available on the capture buffer.

Returns non-zero if available, or zero if not.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_playback_data
9

### snd_pcm_playback_data

check whether any data exists on the playback buffer

#### Synopsis

       int snd_pcm_playback_data
       struct snd_pcm_substream * substream

#### Arguments

`substream`

  the pcm substream instance

#### Description

Checks whether any data exists on the playback buffer. If stop_threshold is bigger or equal to boundary, then this function returns always non-zero.

Returns non-zero if exists, or zero if not.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_playback_empty
9

### snd_pcm_playback_empty

check whether the playback buffer is empty

#### Synopsis

       int snd_pcm_playback_empty
       struct snd_pcm_substream * substream

#### Arguments

`substream`

  the pcm substream instance

#### Description

Checks whether the playback buffer is empty.

Returns non-zero if empty, or zero if not.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_capture_empty
9

### snd_pcm_capture_empty

check whether the capture buffer is empty

#### Synopsis

       int snd_pcm_capture_empty
       struct snd_pcm_substream * substream

#### Arguments

`substream`

  the pcm substream instance

#### Description

Checks whether the capture buffer is empty.

Returns non-zero if empty, or zero if not.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_format_cpu_endian
9

### snd_pcm_format_cpu_endian

Check the PCM format is CPU-endian

#### Synopsis

       int snd_pcm_format_cpu_endian
       snd_pcm_format_t format

#### Arguments

`format`

  the format to check

#### Description

Returns 1 if the given PCM format is CPU-endian, 0 if opposite, or a negative error code if endian not specified.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_new_stream
9

### snd_pcm_new_stream

create a new PCM stream

#### Synopsis

       int snd_pcm_new_stream
       struct snd_pcm * pcm
       int stream
       int substream_count

#### Arguments

`pcm`

  the pcm instance

`stream`

  the stream direction, SNDRV_PCM_STREAM_XXX

`substream_count`

  the number of substreams

#### Description

Creates a new stream for the pcm. The corresponding stream on the pcm must have been empty before calling this, i.e. zero must be given to the argument of `snd_pcm_new`.

Returns zero if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_new
9

### snd_pcm_new

create a new PCM instance

#### Synopsis

       int snd_pcm_new
       struct snd_card * card
       char * id
       int device
       int playback_count
       int capture_count
       struct snd_pcm ** rpcm

#### Arguments

`card`

  the card instance

`id`

  the id string

`device`

  the device index (zero based)

`playback_count`

  the number of substreams for playback

`capture_count`

  the number of substreams for capture

`rpcm`

  the pointer to store the new pcm instance

#### Description

Creates a new PCM instance.

The pcm operators have to be set afterwards to the new instance via `snd_pcm_set_ops`.

Returns zero if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_device_new
9

### snd_device_new

create an ALSA device component

#### Synopsis

       int snd_device_new
       struct snd_card * card
       snd_device_type_t type
       void * device_data
       struct snd_device_ops * ops

#### Arguments

`card`

  the card instance

`type`

  the device type, SNDRV_DEV_XXX

`device_data`

  the data pointer of this device

`ops`

  the operator table

#### Description

Creates a new device component for the given data pointer. The device will be assigned to the card and managed together by the card.

The data pointer plays a role as the identifier, too, so the pointer address must be unique and unchanged.

Returns zero if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_device_free
9

### snd_device_free

release the device from the card

#### Synopsis

       int snd_device_free
       struct snd_card * card
       void * device_data

#### Arguments

`card`

  the card instance

`device_data`

  the data pointer to release

#### Description

Removes the device from the list on the card and invokes the callback, dev_unregister or dev_free, corresponding to the state. Then release the device.

Returns zero if successful, or a negative error code on failure or if the device not found.

### LINUX

Kernel Hackers Manual March 2006
snd_device_register
9

### snd_device_register

register the device

#### Synopsis

       int snd_device_register
       struct snd_card * card
       void * device_data

#### Arguments

`card`

  the card instance

`device_data`

  the data pointer to register

#### Description

Registers the device which was already created via `snd_device_new`. Usually this is called from `snd_card_register`, but it can be called later if any new devices are created after invocation of `snd_card_register`.

Returns zero if successful, or a negative error code on failure or if the device not found.

### LINUX

Kernel Hackers Manual March 2006
snd_iprintf
9

### snd_iprintf

printf on the procfs buffer

#### Synopsis

       int snd_iprintf
       struct snd_info_buffer * buffer
       char * fmt
        ...

#### Arguments

`buffer`

  the procfs buffer

`fmt`

  the printf format

`...`

  variable arguments

#### Description

Outputs the string on the procfs buffer just like `printf`.

Returns the size of output string.

### LINUX

Kernel Hackers Manual March 2006
snd_info_get_line
9

### snd_info_get_line

read one line from the procfs buffer

#### Synopsis

       int snd_info_get_line
       struct snd_info_buffer * buffer
       char * line
       int len

#### Arguments

`buffer`

  the procfs buffer

`line`

  the buffer to store

`len`

  the max. buffer size - 1

#### Description

Reads one line from the buffer and stores the string.

Returns zero if successful, or 1 if error or EOF.

### LINUX

Kernel Hackers Manual March 2006
snd_info_get_str
9

### snd_info_get_str

parse a string token

#### Synopsis

       char * snd_info_get_str
       char * dest
       char * src
       int len

#### Arguments

`dest`

  the buffer to store the string token

`src`

  the original string

`len`

  the max. length of token - 1

#### Description

Parses the original string and copy a token to the given string buffer.

Returns the updated pointer of the original string so that it can be used for the next call.

### LINUX

Kernel Hackers Manual March 2006
snd_info_create_module_entry
9

### snd_info_create_module_entry

create an info entry for the given module

#### Synopsis

       struct snd_info_entry * snd_info_create_module_entry
       struct module * module
       const char * name
       struct snd_info_entry * parent

#### Arguments

`module`

  the module pointer

`name`

  the file name

`parent`

  the parent directory

#### Description

Creates a new info entry and assigns it to the given module.

Returns the pointer of the new instance, or NULL on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_info_create_card_entry
9

### snd_info_create_card_entry

create an info entry for the given card

#### Synopsis

       struct snd_info_entry * snd_info_create_card_entry
       struct snd_card * card
       const char * name
       struct snd_info_entry * parent

#### Arguments

`card`

  the card instance

`name`

  the file name

`parent`

  the parent directory

#### Description

Creates a new info entry and assigns it to the given card.

Returns the pointer of the new instance, or NULL on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_card_proc_new
9

### snd_card_proc_new

create an info entry for the given card

#### Synopsis

       int snd_card_proc_new
       struct snd_card * card
       const char * name
       struct snd_info_entry ** entryp

#### Arguments

`card`

  the card instance

`name`

  the file name

`entryp`

  the pointer to store the new info entry

#### Description

Creates a new info entry and assigns it to the given card. Unlike `snd_info_create_card_entry`, this function registers the info entry as an ALSA device component, so that it can be unregistered/released without explicit call. Also, you don't have to register this entry via `snd_info_register`, since this will be registered by `snd_card_register` automatically.

The parent is assumed as card->proc_root.

For releasing this entry, use `snd_device_free` instead of `snd_info_free_entry`.

Returns zero if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_info_free_entry
9

### snd_info_free_entry

release the info entry

#### Synopsis

       void snd_info_free_entry
       struct snd_info_entry * entry

#### Arguments

`entry`

  the info entry

#### Description

Releases the info entry. Don't call this after registered.

### LINUX

Kernel Hackers Manual March 2006
snd_info_register
9

### snd_info_register

register the info entry

#### Synopsis

       int snd_info_register
       struct snd_info_entry * entry

#### Arguments

`entry`

  the info entry

#### Description

Registers the proc info entry.

Returns zero if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_info_unregister
9

### snd_info_unregister

de-register the info entry

#### Synopsis

       int snd_info_unregister
       struct snd_info_entry * entry

#### Arguments

`entry`

  the info entry

#### Description

De-registers the info entry and releases the instance.

Returns zero if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_rawmidi_receive
9

### snd_rawmidi_receive

receive the input data from the device

#### Synopsis

       int snd_rawmidi_receive
       struct snd_rawmidi_substream * substream
       const unsigned char * buffer
       int count

#### Arguments

`substream`

  the rawmidi substream

`buffer`

  the buffer pointer

`count`

  the data size to read

#### Description

Reads the data from the internal buffer.

Returns the size of read data, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_rawmidi_transmit_empty
9

### snd_rawmidi_transmit_empty

check whether the output buffer is empty

#### Synopsis

       int snd_rawmidi_transmit_empty
       struct snd_rawmidi_substream * substream

#### Arguments

`substream`

  the rawmidi substream

#### Description

Returns 1 if the internal output buffer is empty, 0 if not.

### LINUX

Kernel Hackers Manual March 2006
snd_rawmidi_transmit_peek
9

### snd_rawmidi_transmit_peek

copy data from the internal buffer

#### Synopsis

       int snd_rawmidi_transmit_peek
       struct snd_rawmidi_substream * substream
       unsigned char * buffer
       int count

#### Arguments

`substream`

  the rawmidi substream

`buffer`

  the buffer pointer

`count`

  data size to transfer

#### Description

Copies data from the internal output buffer to the given buffer.

Call this in the interrupt handler when the midi output is ready, and call `snd_rawmidi_transmit_ack` after the transmission is finished.

Returns the size of copied data, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_rawmidi_transmit_ack
9

### snd_rawmidi_transmit_ack

acknowledge the transmission

#### Synopsis

       int snd_rawmidi_transmit_ack
       struct snd_rawmidi_substream * substream
       int count

#### Arguments

`substream`

  the rawmidi substream

`count`

  the tranferred count

#### Description

Advances the hardware pointer for the internal output buffer with the given size and updates the condition. Call after the transmission is finished.

Returns the advanced size if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_rawmidi_transmit
9

### snd_rawmidi_transmit

copy from the buffer to the device

#### Synopsis

       int snd_rawmidi_transmit
       struct snd_rawmidi_substream * substream
       unsigned char * buffer
       int count

#### Arguments

`substream`

  the rawmidi substream

`buffer`

  the buffer pointer

`count`

  the data size to transfer

#### Description

Copies data from the buffer to the device and advances the pointer.

Returns the copied size if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_rawmidi_new
9

### snd_rawmidi_new

create a rawmidi instance

#### Synopsis

       int snd_rawmidi_new
       struct snd_card * card
       char * id
       int device
       int output_count
       int input_count
       struct snd_rawmidi ** rrawmidi

#### Arguments

`card`

  the card instance

`id`

  the id string

`device`

  the device index

`output_count`

  the number of output streams

`input_count`

  the number of input streams

`rrawmidi`

  the pointer to store the new rawmidi instance

#### Description

Creates a new rawmidi instance. Use `snd_rawmidi_set_ops` to set the operators to the new instance.

Returns zero if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_rawmidi_set_ops
9

### snd_rawmidi_set_ops

set the rawmidi operators

#### Synopsis

       void snd_rawmidi_set_ops
       struct snd_rawmidi * rmidi
       int stream
       struct snd_rawmidi_ops * ops

#### Arguments

`rmidi`

  the rawmidi instance

`stream`

  the stream direction, SNDRV_RAWMIDI_STREAM_XXX

`ops`

  the operator table

#### Description

Sets the rawmidi operators for the given stream direction.

### LINUX

Kernel Hackers Manual March 2006
snd_request_card
9

### snd_request_card

try to load the card module

#### Synopsis

       void snd_request_card
       int card

#### Arguments

`card`

  the card number

#### Description

Tries to load the module snd-card-X for the given card number via KMOD. Returns immediately if already loaded.

### LINUX

Kernel Hackers Manual March 2006
snd_lookup_minor_data
9

### snd_lookup_minor_data

get user data of a registered device

#### Synopsis

       void * snd_lookup_minor_data
       unsigned int minor
       int type

#### Arguments

`minor`

  the minor number

`type`

  device type (SNDRV_DEVICE_TYPE_XXX)

#### Description

Checks that a minor device with the specified type is registered, and returns its user data pointer.

### LINUX

Kernel Hackers Manual March 2006
snd_register_device
9

### snd_register_device

Register the ALSA device file for the card

#### Synopsis

       int snd_register_device
       int type
       struct snd_card * card
       int dev
       struct file_operations * f_ops
       void * private_data
       const char * name

#### Arguments

`type`

  the device type, SNDRV_DEVICE_TYPE_XXX

`card`

  the card instance

`dev`

  the device index

`f_ops`

  the file operations

`private_data`

  user pointer for f_ops->`open`

`name`

  the device file name

#### Description

Registers an ALSA device file for the given card. The operators have to be set in reg parameter.

Retrurns zero if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_unregister_device
9

### snd_unregister_device

unregister the device on the given card

#### Synopsis

       int snd_unregister_device
       int type
       struct snd_card * card
       int dev

#### Arguments

`type`

  the device type, SNDRV_DEVICE_TYPE_XXX

`card`

  the card instance

`dev`

  the device index

#### Description

Unregisters the device file already registered via `snd_register_device`.

Returns zero if sucecessful, or a negative error code on failure

### LINUX

Kernel Hackers Manual March 2006
copy_to_user_fromio
9

### copy_to_user_fromio

copy data from mmio-space to user-space

#### Synopsis

       int copy_to_user_fromio
       void __user * dst
       const volatile void __iomem * src
       size_t count

#### Arguments

`dst`

  the destination pointer on user-space

`src`

  the source pointer on mmio

`count`

  the data size to copy in bytes

#### Description

Copies the data from mmio-space to user-space.

Returns zero if successful, or non-zero on failure.

### LINUX

Kernel Hackers Manual March 2006
copy_from_user_toio
9

### copy_from_user_toio

copy data from user-space to mmio-space

#### Synopsis

       int copy_from_user_toio
       volatile void __iomem * dst
       const void __user * src
       size_t count

#### Arguments

`dst`

  the destination pointer on mmio-space

`src`

  the source pointer on user-space

`count`

  the data size to copy in bytes

#### Description

Copies the data from user-space to mmio-space.

Returns zero if successful, or non-zero on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_lib_preallocate_free_for_all
9

### snd_pcm_lib_preallocate_free_for_all

release all pre-allocated buffers on the pcm

#### Synopsis

       int snd_pcm_lib_preallocate_free_for_all
       struct snd_pcm * pcm

#### Arguments

`pcm`

  the pcm instance

#### Description

Releases all the pre-allocated buffers on the given pcm.

Returns zero if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_lib_preallocate_pages
9

### snd_pcm_lib_preallocate_pages

pre-allocation for the given DMA type

#### Synopsis

       int snd_pcm_lib_preallocate_pages
       struct snd_pcm_substream * substream
       int type
       struct device * data
       size_t size
       size_t max

#### Arguments

`substream`

  the pcm substream instance

`type`

  DMA type (SNDRV_DMA_TYPE_*)

`data`

  DMA type dependant data

`size`

  the requested pre-allocation size in bytes

`max`

  the max. allowed pre-allocation size

#### Description

Do pre-allocation for the given DMA buffer type.

When substream->dma_buf_id is set, the function tries to look for the reserved buffer, and the buffer is not freed but reserved at destruction time. The dma_buf_id must be unique for all systems (in the same DMA buffer type) e.g. using `snd_dma_pci_buf_id`.

Returns zero if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_lib_preallocate_pages_for_all
9

### snd_pcm_lib_preallocate_pages_for_all

pre-allocation for continous memory type (all substreams)

#### Synopsis

       int snd_pcm_lib_preallocate_pages_for_all
       struct snd_pcm * pcm
       int type
       void * data
       size_t size
       size_t max

#### Arguments

`pcm`

  the pcm instance

`type`

  DMA type (SNDRV_DMA_TYPE_*)

`data`

  DMA type dependant data

`size`

  the requested pre-allocation size in bytes

`max`

  the max. allowed pre-allocation size

#### Description

Do pre-allocation to all substreams of the given pcm for the specified DMA type.

Returns zero if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_sgbuf_ops_page
9

### snd_pcm_sgbuf_ops_page

get the page struct at the given offset

#### Synopsis

       struct page * snd_pcm_sgbuf_ops_page
       struct snd_pcm_substream * substream
       unsigned long offset

#### Arguments

`substream`

  the pcm substream instance

`offset`

  the buffer offset

#### Description

Returns the page struct at the given buffer offset. Used as the page callback of PCM ops.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_lib_malloc_pages
9

### snd_pcm_lib_malloc_pages

allocate the DMA buffer

#### Synopsis

       int snd_pcm_lib_malloc_pages
       struct snd_pcm_substream * substream
       size_t size

#### Arguments

`substream`

  the substream to allocate the DMA buffer to

`size`

  the requested buffer size in bytes

#### Description

Allocates the DMA buffer on the BUS type given earlier to `snd_pcm_lib_preallocate_xxx_pages`.

Returns 1 if the buffer is changed, 0 if not changed, or a negative code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_lib_free_pages
9

### snd_pcm_lib_free_pages

release the allocated DMA buffer.

#### Synopsis

       int snd_pcm_lib_free_pages
       struct snd_pcm_substream * substream

#### Arguments

`substream`

  the substream to release the DMA buffer

#### Description

Releases the DMA buffer allocated via `snd_pcm_lib_malloc_pages`.

Returns zero if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_card_new
9

### snd_card_new

create and initialize a soundcard structure

#### Synopsis

       struct snd_card * snd_card_new
       int idx
       const char * xid
       struct module * module
       int extra_size

#### Arguments

`idx`

  card index (address) [0 ... (SNDRV_CARDS-1)]

`xid`

  card identification (ASCII string)

`module`

  top level module for locking

`extra_size`

  allocate this extra size after the main soundcard structure

#### Description

Creates and initializes a soundcard structure.

Returns kmallocated snd_card structure. Creates the ALSA control interface (which is blocked until snd_card_register function is called).

### LINUX

Kernel Hackers Manual March 2006
snd_card_disconnect
9

### snd_card_disconnect

disconnect all APIs from the file-operations (user space)

#### Synopsis

       int snd_card_disconnect
       struct snd_card * card

#### Arguments

`card`

  soundcard structure

#### Description

Disconnects all APIs from the file-operations (user space).

Returns zero, otherwise a negative error code.

#### Note

The current implementation replaces all active file->f_op with special dummy file operations (they do nothing except release).

### LINUX

Kernel Hackers Manual March 2006
snd_card_free
9

### snd_card_free

frees given soundcard structure

#### Synopsis

       int snd_card_free
       struct snd_card * card

#### Arguments

`card`

  soundcard structure

#### Description

This function releases the soundcard structure and the all assigned devices automatically. That is, you don't have to release the devices by yourself.

Returns zero. Frees all associated devices and frees the control interface associated to given soundcard.

### LINUX

Kernel Hackers Manual March 2006
snd_card_free_in_thread
9

### snd_card_free_in_thread

call `snd_card_free` in thread

#### Synopsis

       int snd_card_free_in_thread
       struct snd_card * card

#### Arguments

`card`

  soundcard structure

#### Description

This function schedules the call of `snd_card_free` function in a work queue. When all devices are released (non-busy), the work is woken up and calls `snd_card_free`.

When a card can be disconnected at any time by hotplug service, this function should be used in disconnect (or detach) callback instead of calling `snd_card_free` directly.

Returns - zero otherwise a negative error code if the start of thread failed.

### LINUX

Kernel Hackers Manual March 2006
snd_card_register
9

### snd_card_register

register the soundcard

#### Synopsis

       int snd_card_register
       struct snd_card * card

#### Arguments

`card`

  soundcard structure

#### Description

This function registers all the devices assigned to the soundcard. Until calling this, the ALSA control interface is blocked from the external accesses. Thus, you should call this function at the end of the initialization of the card.

Returns zero otherwise a negative error code if the registrain failed.

### LINUX

Kernel Hackers Manual March 2006
snd_component_add
9

### snd_component_add

add a component string

#### Synopsis

       int snd_component_add
       struct snd_card * card
       const char * component

#### Arguments

`card`

  soundcard structure

`component`

  the component id string

#### Description

This function adds the component id string to the supported list. The component can be referred from the alsa-lib.

Returns zero otherwise a negative error code.

### LINUX

Kernel Hackers Manual March 2006
snd_card_file_add
9

### snd_card_file_add

add the file to the file list of the card

#### Synopsis

       int snd_card_file_add
       struct snd_card * card
       struct file * file

#### Arguments

`card`

  soundcard structure

`file`

  file pointer

#### Description

This function adds the file to the file linked-list of the card. This linked-list is used to keep tracking the connection state, and to avoid the release of busy resources by hotplug.

Returns zero or a negative error code.

### LINUX

Kernel Hackers Manual March 2006
snd_card_file_remove
9

### snd_card_file_remove

remove the file from the file list

#### Synopsis

       int snd_card_file_remove
       struct snd_card * card
       struct file * file

#### Arguments

`card`

  soundcard structure

`file`

  file pointer

#### Description

This function removes the file formerly added to the card via `snd_card_file_add` function. If all files are removed and the release of the card is scheduled, it will wake up the the thread to call `snd_card_free` (see `snd_card_free_in_thread` function).

Returns zero or a negative error code.

### LINUX

Kernel Hackers Manual March 2006
snd_power_wait
9

### snd_power_wait

wait until the power-state is changed.

#### Synopsis

       int snd_power_wait
       struct snd_card * card
       unsigned int power_state
       struct file * file

#### Arguments

`card`

  soundcard structure

`power_state`

  expected power state

`file`

  file structure for the O_NONBLOCK check (optional)

#### Description

Waits until the power-state is changed.

#### Note

the power lock must be active before call.

### LINUX

Kernel Hackers Manual March 2006
snd_dma_program
9

### snd_dma_program

program an ISA DMA transfer

#### Synopsis

       void snd_dma_program
       unsigned long dma
       unsigned long addr
       unsigned int size
       unsigned short mode

#### Arguments

`dma`

  the dma number

`addr`

  the physical address of the buffer

`size`

  the DMA transfer size

`mode`

  the DMA transfer mode, DMA_MODE_XXX

#### Description

Programs an ISA DMA transfer for the given buffer.

### LINUX

Kernel Hackers Manual March 2006
snd_dma_disable
9

### snd_dma_disable

stop the ISA DMA transfer

#### Synopsis

       void snd_dma_disable
       unsigned long dma

#### Arguments

`dma`

  the dma number

#### Description

Stops the ISA DMA transfer.

### LINUX

Kernel Hackers Manual March 2006
snd_dma_pointer
9

### snd_dma_pointer

return the current pointer to DMA transfer buffer in bytes

#### Synopsis

       unsigned int snd_dma_pointer
       unsigned long dma
       unsigned int size

#### Arguments

`dma`

  the dma number

`size`

  the dma transfer size

#### Description

Returns the current pointer in DMA tranfer buffer in bytes

### LINUX

Kernel Hackers Manual March 2006
snd_ctl_new
9

### snd_ctl_new

create a control instance from the template

#### Synopsis

       struct snd_kcontrol * snd_ctl_new
       struct snd_kcontrol * control
       unsigned int access

#### Arguments

`control`

  the control template

`access`

  the default control access

#### Description

Allocates a new struct snd_kcontrol instance and copies the given template to the new instance. It does not copy volatile data (access).

Returns the pointer of the new instance, or NULL on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_ctl_new1
9

### snd_ctl_new1

create a control instance from the template

#### Synopsis

       struct snd_kcontrol * snd_ctl_new1
       const struct snd_kcontrol_new * ncontrol
       void * private_data

#### Arguments

`ncontrol`

  the initialization record

`private_data`

  the private data to set

#### Description

Allocates a new struct snd_kcontrol instance and initialize from the given template. When the access field of ncontrol is 0, it's assumed as READWRITE access. When the count field is 0, it's assumes as one.

Returns the pointer of the newly generated instance, or NULL on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_ctl_free_one
9

### snd_ctl_free_one

release the control instance

#### Synopsis

       void snd_ctl_free_one
       struct snd_kcontrol * kcontrol

#### Arguments

`kcontrol`

  the control instance

#### Description

Releases the control instance created via `snd_ctl_new` or `snd_ctl_new1`. Don't call this after the control was added to the card.

### LINUX

Kernel Hackers Manual March 2006
snd_ctl_add
9

### snd_ctl_add

add the control instance to the card

#### Synopsis

       int snd_ctl_add
       struct snd_card * card
       struct snd_kcontrol * kcontrol

#### Arguments

`card`

  the card instance

`kcontrol`

  the control instance to add

#### Description

Adds the control instance created via `snd_ctl_new` or `snd_ctl_new1` to the given card. Assigns also an unique numid used for fast search.

Returns zero if successful, or a negative error code on failure.

It frees automatically the control which cannot be added.

### LINUX

Kernel Hackers Manual March 2006
snd_ctl_remove
9

### snd_ctl_remove

remove the control from the card and release it

#### Synopsis

       int snd_ctl_remove
       struct snd_card * card
       struct snd_kcontrol * kcontrol

#### Arguments

`card`

  the card instance

`kcontrol`

  the control instance to remove

#### Description

Removes the control from the card and then releases the instance. You don't need to call `snd_ctl_free_one`. You must be in the write lock - down_write(&card->controls_rwsem).

Returns 0 if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_ctl_remove_id
9

### snd_ctl_remove_id

remove the control of the given id and release it

#### Synopsis

       int snd_ctl_remove_id
       struct snd_card * card
       struct snd_ctl_elem_id * id

#### Arguments

`card`

  the card instance

`id`

  the control id to remove

#### Description

Finds the control instance with the given id, removes it from the card list and releases it.

Returns 0 if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_ctl_rename_id
9

### snd_ctl_rename_id

replace the id of a control on the card

#### Synopsis

       int snd_ctl_rename_id
       struct snd_card * card
       struct snd_ctl_elem_id * src_id
       struct snd_ctl_elem_id * dst_id

#### Arguments

`card`

  the card instance

`src_id`

  the old id

`dst_id`

  the new id

#### Description

Finds the control with the old id from the card, and replaces the id with the new one.

Returns zero if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_ctl_find_numid
9

### snd_ctl_find_numid

find the control instance with the given number-id

#### Synopsis

       struct snd_kcontrol * snd_ctl_find_numid
       struct snd_card * card
       unsigned int numid

#### Arguments

`card`

  the card instance

`numid`

  the number-id to search

#### Description

Finds the control instance with the given number-id from the card.

Returns the pointer of the instance if found, or NULL if not.

The caller must down card->controls_rwsem before calling this function (if the race condition can happen).

### LINUX

Kernel Hackers Manual March 2006
snd_ctl_find_id
9

### snd_ctl_find_id

find the control instance with the given id

#### Synopsis

       struct snd_kcontrol * snd_ctl_find_id
       struct snd_card * card
       struct snd_ctl_elem_id * id

#### Arguments

`card`

  the card instance

`id`

  the id to search

#### Description

Finds the control instance with the given id from the card.

Returns the pointer of the instance if found, or NULL if not.

The caller must down card->controls_rwsem before calling this function (if the race condition can happen).

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_set_ops
9

### snd_pcm_set_ops

set the PCM operators

#### Synopsis

       void snd_pcm_set_ops
       struct snd_pcm * pcm
       int direction
       struct snd_pcm_ops * ops

#### Arguments

`pcm`

  the pcm instance

`direction`

  stream direction, SNDRV_PCM_STREAM_XXX

`ops`

  the operator table

#### Description

Sets the given PCM operators to the pcm instance.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_set_sync
9

### snd_pcm_set_sync

set the PCM sync id

#### Synopsis

       void snd_pcm_set_sync
       struct snd_pcm_substream * substream

#### Arguments

`substream`

  the pcm substream

#### Description

Sets the PCM sync identifier for the card.

### LINUX

Kernel Hackers Manual March 2006
snd_interval_refine
9

### snd_interval_refine

refine the interval value of configurator

#### Synopsis

       int snd_interval_refine
       struct snd_interval * i
       const struct snd_interval * v

#### Arguments

`i`

  the interval value to refine

`v`

  the interval value to refer to

#### Description

Refines the interval value with the reference value. The interval is changed to the range satisfying both intervals. The interval status (min, max, integer, etc.) are evaluated.

Returns non-zero if the value is changed, zero if not changed.

### LINUX

Kernel Hackers Manual March 2006
snd_interval_ratnum
9

### snd_interval_ratnum

refine the interval value

#### Synopsis

       int snd_interval_ratnum
       struct snd_interval * i
       unsigned int rats_count
       struct snd_ratnum * rats
       unsigned int * nump
       unsigned int * denp

#### Arguments

`i`

  interval to refine

`rats_count`

  number of ratnum_t

`rats`

  ratnum_t array

`nump`

  pointer to store the resultant numerator

`denp`

  pointer to store the resultant denominator

#### Description

Returns non-zero if the value is changed, zero if not changed.

### LINUX

Kernel Hackers Manual March 2006
snd_interval_list
9

### snd_interval_list

refine the interval value from the list

#### Synopsis

       int snd_interval_list
       struct snd_interval * i
       unsigned int count
       unsigned int * list
       unsigned int mask

#### Arguments

`i`

  the interval value to refine

`count`

  the number of elements in the list

`list`

  the value list

`mask`

  the bit-mask to evaluate

#### Description

Refines the interval value from the list. When mask is non-zero, only the elements corresponding to bit 1 are evaluated.

Returns non-zero if the value is changed, zero if not changed.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_hw_rule_add
9

### snd_pcm_hw_rule_add

add the hw-constraint rule

#### Synopsis

       int snd_pcm_hw_rule_add
       struct snd_pcm_runtime * runtime
       unsigned int cond
       int var
       snd_pcm_hw_rule_func_t func
       void * private
       int dep
        ...

#### Arguments

`runtime`

  the pcm runtime instance

`cond`

  condition bits

`var`

  the variable to evaluate

`func`

  the evaluation function

`private`

  the private data pointer passed to function

`dep`

  the dependent variables

`...`

  variable arguments

#### Description

Returns zero if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_hw_constraint_integer
9

### snd_pcm_hw_constraint_integer

#### Synopsis

       int snd_pcm_hw_constraint_integer
       struct snd_pcm_runtime * runtime
       snd_pcm_hw_param_t var

#### Arguments

`runtime`

  PCM runtime instance

`var`

  hw_params variable to apply the integer constraint

#### Description

Apply the constraint of integer to an interval parameter.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_hw_constraint_minmax
9

### snd_pcm_hw_constraint_minmax

#### Synopsis

       int snd_pcm_hw_constraint_minmax
       struct snd_pcm_runtime * runtime
       snd_pcm_hw_param_t var
       unsigned int min
       unsigned int max

#### Arguments

`runtime`

  PCM runtime instance

`var`

  hw_params variable to apply the range

`min`

  the minimal value

`max`

  the maximal value

#### Description

Apply the min/max range constraint to an interval parameter.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_hw_constraint_list
9

### snd_pcm_hw_constraint_list

#### Synopsis

       int snd_pcm_hw_constraint_list
       struct snd_pcm_runtime * runtime
       unsigned int cond
       snd_pcm_hw_param_t var
       struct snd_pcm_hw_constraint_list * l

#### Arguments

`runtime`

  PCM runtime instance

`cond`

  condition bits

`var`

  hw_params variable to apply the list constraint

`l`

  list

#### Description

Apply the list of constraints to an interval parameter.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_hw_constraint_ratnums
9

### snd_pcm_hw_constraint_ratnums

#### Synopsis

       int snd_pcm_hw_constraint_ratnums
       struct snd_pcm_runtime * runtime
       unsigned int cond
       snd_pcm_hw_param_t var
       struct snd_pcm_hw_constraint_ratnums * r

#### Arguments

`runtime`

  PCM runtime instance

`cond`

  condition bits

`var`

  hw_params variable to apply the ratnums constraint

`r`

  struct snd_ratnums constriants

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_hw_constraint_ratdens
9

### snd_pcm_hw_constraint_ratdens

#### Synopsis

       int snd_pcm_hw_constraint_ratdens
       struct snd_pcm_runtime * runtime
       unsigned int cond
       snd_pcm_hw_param_t var
       struct snd_pcm_hw_constraint_ratdens * r

#### Arguments

`runtime`

  PCM runtime instance

`cond`

  condition bits

`var`

  hw_params variable to apply the ratdens constraint

`r`

  struct snd_ratdens constriants

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_hw_constraint_msbits
9

### snd_pcm_hw_constraint_msbits

#### Synopsis

       int snd_pcm_hw_constraint_msbits
       struct snd_pcm_runtime * runtime
       unsigned int cond
       unsigned int width
       unsigned int msbits

#### Arguments

`runtime`

  PCM runtime instance

`cond`

  condition bits

`width`

  sample bits width

`msbits`

  msbits width

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_hw_constraint_step
9

### snd_pcm_hw_constraint_step

#### Synopsis

       int snd_pcm_hw_constraint_step
       struct snd_pcm_runtime * runtime
       unsigned int cond
       snd_pcm_hw_param_t var
       unsigned long step

#### Arguments

`runtime`

  PCM runtime instance

`cond`

  condition bits

`var`

  hw_params variable to apply the step constraint

`step`

  step size

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_hw_constraint_pow2
9

### snd_pcm_hw_constraint_pow2

#### Synopsis

       int snd_pcm_hw_constraint_pow2
       struct snd_pcm_runtime * runtime
       unsigned int cond
       snd_pcm_hw_param_t var

#### Arguments

`runtime`

  PCM runtime instance

`cond`

  condition bits

`var`

  hw_params variable to apply the power-of-2 constraint

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_hw_param_value_min
9

### snd_pcm_hw_param_value_min

#### Synopsis

       unsigned int snd_pcm_hw_param_value_min
       const struct snd_pcm_hw_params * params
       snd_pcm_hw_param_t var
       int * dir

#### Arguments

`params`

  the hw_params instance

`var`

  parameter to retrieve

`dir`

  pointer to the direction (-1,0,1) or NULL

#### Description

Return the minimum value for field PAR.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_hw_param_value_max
9

### snd_pcm_hw_param_value_max

#### Synopsis

       unsigned int snd_pcm_hw_param_value_max
       const struct snd_pcm_hw_params * params
       snd_pcm_hw_param_t var
       int * dir

#### Arguments

`params`

  the hw_params instance

`var`

  parameter to retrieve

`dir`

  pointer to the direction (-1,0,1) or NULL

#### Description

Return the maximum value for field PAR.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_hw_param_first
9

### snd_pcm_hw_param_first

#### Synopsis

       int snd_pcm_hw_param_first
       struct snd_pcm_substream * pcm
       struct snd_pcm_hw_params * params
       snd_pcm_hw_param_t var
       int * dir

#### Arguments

`pcm`

  PCM instance

`params`

  the hw_params instance

`var`

  parameter to retrieve

`dir`

  pointer to the direction (-1,0,1) or NULL

#### Description

Inside configuration space defined by PARAMS remove from PAR all values > minimum. Reduce configuration space accordingly. Return the minimum.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_hw_param_last
9

### snd_pcm_hw_param_last

#### Synopsis

       int snd_pcm_hw_param_last
       struct snd_pcm_substream * pcm
       struct snd_pcm_hw_params * params
       snd_pcm_hw_param_t var
       int * dir

#### Arguments

`pcm`

  PCM instance

`params`

  the hw_params instance

`var`

  parameter to retrieve

`dir`

  pointer to the direction (-1,0,1) or NULL

#### Description

Inside configuration space defined by PARAMS remove from PAR all values < maximum. Reduce configuration space accordingly. Return the maximum.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_hw_param_set
9

### snd_pcm_hw_param_set

#### Synopsis

       int snd_pcm_hw_param_set
       struct snd_pcm_substream * pcm
       struct snd_pcm_hw_params * params
       snd_pcm_hw_param_t var
       unsigned int val
       int dir

#### Arguments

`pcm`

  PCM instance

`params`

  the hw_params instance

`var`

  parameter to retrieve

`val`

  value to set

`dir`

  pointer to the direction (-1,0,1) or NULL

#### Description

Inside configuration space defined by PARAMS remove from PAR all values != VAL. Reduce configuration space accordingly. Return VAL or -EINVAL if the configuration space is empty

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_hw_param_mask
9

### snd_pcm_hw_param_mask

#### Synopsis

       int snd_pcm_hw_param_mask
       struct snd_pcm_substream * pcm
       struct snd_pcm_hw_params * params
       snd_pcm_hw_param_t var
       const struct snd_mask * val

#### Arguments

`pcm`

  PCM instance

`params`

  the hw_params instance

`var`

  parameter to retrieve

`val`

  mask to apply

#### Description

Inside configuration space defined by PARAMS remove from PAR all values not contained in MASK. Reduce configuration space accordingly. This function can be called only for SNDRV_PCM_HW_PARAM_ACCESS, SNDRV_PCM_HW_PARAM_FORMAT, SNDRV_PCM_HW_PARAM_SUBFORMAT. Return 0 on success or -EINVAL if the configuration space is empty

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_hw_param_near
9

### snd_pcm_hw_param_near

#### Synopsis

       int snd_pcm_hw_param_near
       struct snd_pcm_substream * pcm
       struct snd_pcm_hw_params * params
       snd_pcm_hw_param_t var
       unsigned int best
       int * dir

#### Arguments

`pcm`

  PCM instance

`params`

  the hw_params instance

`var`

  parameter to retrieve

`best`

  value to set

`dir`

  pointer to the direction (-1,0,1) or NULL

#### Description

Inside configuration space defined by PARAMS set PAR to the available value nearest to VAL. Reduce configuration space accordingly. This function cannot be called for SNDRV_PCM_HW_PARAM_ACCESS, SNDRV_PCM_HW_PARAM_FORMAT, SNDRV_PCM_HW_PARAM_SUBFORMAT. Return the value found.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_lib_ioctl
9

### snd_pcm_lib_ioctl

a generic PCM ioctl callback

#### Synopsis

       int snd_pcm_lib_ioctl
       struct snd_pcm_substream * substream
       unsigned int cmd
       void * arg

#### Arguments

`substream`

  the pcm substream instance

`cmd`

  ioctl command

`arg`

  ioctl argument

#### Description

Processes the generic ioctl commands for PCM. Can be passed as the ioctl callback for PCM ops.

Returns zero if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_period_elapsed
9

### snd_pcm_period_elapsed

update the pcm status for the next period

#### Synopsis

       void snd_pcm_period_elapsed
       struct snd_pcm_substream * substream

#### Arguments

`substream`

  the pcm substream instance

#### Description

This function is called from the interrupt handler when the PCM has processed the period size. It will update the current pointer, set up the tick, wake up sleepers, etc.

Even if more than one periods have elapsed since the last call, you have to call this only once.

### LINUX

Kernel Hackers Manual March 2006
snd_hwdep_new
9

### snd_hwdep_new

create a new hwdep instance

#### Synopsis

       int snd_hwdep_new
       struct snd_card * card
       char * id
       int device
       struct snd_hwdep ** rhwdep

#### Arguments

`card`

  the card instance

`id`

  the id string

`device`

  the device index (zero-based)

`rhwdep`

  the pointer to store the new hwdep instance

#### Description

Creates a new hwdep instance with the given index on the card. The callbacks (hwdep->ops) must be set on the returned instance after this call manually by the caller.

Returns zero if successful, or a negative error code on failure.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_stop
9

### snd_pcm_stop

#### Synopsis

       int snd_pcm_stop
       struct snd_pcm_substream * substream
       int state

#### Arguments

`substream`

  the PCM substream instance

`state`

  PCM state after stopping the stream

#### Description

Try to stop all running streams in the substream group. The state of each stream is changed to the given value after that unconditionally.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_suspend
9

### snd_pcm_suspend

#### Synopsis

       int snd_pcm_suspend
       struct snd_pcm_substream * substream

#### Arguments

`substream`

  the PCM substream

#### Description

Trigger SUSPEND to all linked streams. After this call, all streams are changed to SUSPENDED state.

### LINUX

Kernel Hackers Manual March 2006
snd_pcm_suspend_all
9

### snd_pcm_suspend_all

#### Synopsis

       int snd_pcm_suspend_all
       struct snd_pcm * pcm

#### Arguments

`pcm`

  the PCM instance

#### Description

Trigger SUSPEND to all substreams in the given pcm. After this call, all streams are changed to SUSPENDED state.

### LINUX

Kernel Hackers Manual March 2006
snd_malloc_pages
9

### snd_malloc_pages

allocate pages with the given size

#### Synopsis

       void * snd_malloc_pages
       size_t size
       gfp_t gfp_flags

#### Arguments

`size`

  the size to allocate in bytes

`gfp_flags`

  the allocation conditions, GFP_XXX

#### Description

Allocates the physically contiguous pages with the given size.

Returns the pointer of the buffer, or NULL if no enoguh memory.

### LINUX

Kernel Hackers Manual March 2006
snd_free_pages
9

### snd_free_pages

release the pages

#### Synopsis

       void snd_free_pages
       void * ptr
       size_t size

#### Arguments

`ptr`

  the buffer pointer to release

`size`

  the allocated buffer size

#### Description

Releases the buffer allocated via `snd_malloc_pages`.

### LINUX

Kernel Hackers Manual March 2006
snd_dma_alloc_pages
9

### snd_dma_alloc_pages

allocate the buffer area according to the given type

#### Synopsis

       int snd_dma_alloc_pages
       int type
       struct device * device
       size_t size
       struct snd_dma_buffer * dmab

#### Arguments

`type`

  the DMA buffer type

`device`

  the device pointer

`size`

  the buffer size to allocate

`dmab`

  buffer allocation record to store the allocated data

#### Description

Calls the memory-allocator function for the corresponding buffer type.

Returns zero if the buffer with the given size is allocated successfuly, other a negative value at error.

### LINUX

Kernel Hackers Manual March 2006
snd_dma_alloc_pages_fallback
9

### snd_dma_alloc_pages_fallback

allocate the buffer area according to the given type with fallback

#### Synopsis

       int snd_dma_alloc_pages_fallback
       int type
       struct device * device
       size_t size
       struct snd_dma_buffer * dmab

#### Arguments

`type`

  the DMA buffer type

`device`

  the device pointer

`size`

  the buffer size to allocate

`dmab`

  buffer allocation record to store the allocated data

#### Description

Calls the memory-allocator function for the corresponding buffer type. When no space is left, this function reduces the size and tries to allocate again. The size actually allocated is stored in res_size argument.

Returns zero if the buffer with the given size is allocated successfuly, other a negative value at error.

### LINUX

Kernel Hackers Manual March 2006
snd_dma_free_pages
9

### snd_dma_free_pages

release the allocated buffer

#### Synopsis

       void snd_dma_free_pages
       struct snd_dma_buffer * dmab

#### Arguments

`dmab`

  the buffer allocation record to release

#### Description

Releases the allocated buffer via `snd_dma_alloc_pages`.

### LINUX

Kernel Hackers Manual March 2006
snd_dma_get_reserved_buf
9

### snd_dma_get_reserved_buf

get the reserved buffer for the given device

#### Synopsis

       size_t snd_dma_get_reserved_buf
       struct snd_dma_buffer * dmab
       unsigned int id

#### Arguments

`dmab`

  the buffer allocation record to store

`id`

  the buffer id

#### Description

Looks for the reserved-buffer list and re-uses if the same buffer is found in the list. When the buffer is found, it's removed from the free list.

Returns the size of buffer if the buffer is found, or zero if not found.

### LINUX

Kernel Hackers Manual March 2006
snd_dma_reserve_buf
9

### snd_dma_reserve_buf

reserve the buffer

#### Synopsis

       int snd_dma_reserve_buf
       struct snd_dma_buffer * dmab
       unsigned int id

#### Arguments

`dmab`

  the buffer to reserve

`id`

  the buffer id

#### Description

Reserves the given buffer as a reserved buffer.

Returns zero if successful, or a negative code at error.

## 16x50 UART Driver

### LINUX

Kernel Hackers Manual March 2006
uart_handle_dcd_change
9

### uart_handle_dcd_change

handle a change of carrier detect state

#### Synopsis

       void uart_handle_dcd_change
       struct uart_port * port
       unsigned int status

#### Arguments

`port`

  uart_port structure for the open port

`status`

  new carrier detect status, nonzero if active

### LINUX

Kernel Hackers Manual March 2006
uart_handle_cts_change
9

### uart_handle_cts_change

handle a change of clear-to-send state

#### Synopsis

       void uart_handle_cts_change
       struct uart_port * port
       unsigned int status

#### Arguments

`port`

  uart_port structure for the open port

`status`

  new clear to send status, nonzero if active

### LINUX

Kernel Hackers Manual March 2006
uart_update_timeout
9

### uart_update_timeout

update per-port FIFO timeout.

#### Synopsis

       void uart_update_timeout
       struct uart_port * port
       unsigned int cflag
       unsigned int baud

#### Arguments

`port`

  uart_port structure describing the port

`cflag`

  termios cflag value

`baud`

  speed of the port

#### Description

Set the port FIFO timeout value. The `cflag` value should reflect the actual hardware settings.

### LINUX

Kernel Hackers Manual March 2006
uart_get_baud_rate
9

### uart_get_baud_rate

return baud rate for a particular port

#### Synopsis

       unsigned int uart_get_baud_rate
       struct uart_port * port
       struct termios * termios
       struct termios * old
       unsigned int min
       unsigned int max

#### Arguments

`port`

  uart_port structure describing the port in question.

`termios`

  desired termios settings.

`old`

  old termios (or NULL)

`min`

  minimum acceptable baud rate

`max`

  maximum acceptable baud rate

#### Description

Decode the termios structure into a numeric baud rate, taking account of the magic 38400 baud rate (with spd_* flags), and mapping the `B0` rate to 9600 baud.

If the new baud rate is invalid, try the old termios setting. If it's still invalid, we try 9600 baud.

Update the `termios` structure to reflect the baud rate we're actually going to be using.

### LINUX

Kernel Hackers Manual March 2006
uart_get_divisor
9

### uart_get_divisor

return uart clock divisor

#### Synopsis

       unsigned int uart_get_divisor
       struct uart_port * port
       unsigned int baud

#### Arguments

`port`

  uart_port structure describing the port.

`baud`

  desired baud rate

#### Description

Calculate the uart clock divisor for the port.

### LINUX

Kernel Hackers Manual March 2006
uart_register_driver
9

### uart_register_driver

register a driver with the uart core layer

#### Synopsis

       int uart_register_driver
       struct uart_driver * drv

#### Arguments

`drv`

  low level driver structure

#### Description

Register a uart driver with the core driver. We in turn register with the tty layer, and initialise the core driver per-port state.

We have a proc file in /proc/tty/driver which is named after the normal driver.

drv->port should be NULL, and the per-port structures should be registered using uart_add_one_port after this call has succeeded.

### LINUX

Kernel Hackers Manual March 2006
uart_unregister_driver
9

### uart_unregister_driver

remove a driver from the uart core layer

#### Synopsis

       void uart_unregister_driver
       struct uart_driver * drv

#### Arguments

`drv`

  low level driver structure

#### Description

Remove all references to a driver from the core driver. The low level driver must have removed all its ports via the `uart_remove_one_port` if it registered them with `uart_add_one_port`. (ie, drv->port == NULL)

### LINUX

Kernel Hackers Manual March 2006
uart_add_one_port
9

### uart_add_one_port

attach a driver-defined port structure

#### Synopsis

       int uart_add_one_port
       struct uart_driver * drv
       struct uart_port * port

#### Arguments

`drv`

  pointer to the uart low level driver structure for this port

`port`

  uart port structure to use for this port.

#### Description

This allows the driver to register its own uart_port structure with the core driver. The main purpose is to allow the low level uart drivers to expand uart_port, rather than having yet more levels of structures.

### LINUX

Kernel Hackers Manual March 2006
uart_remove_one_port
9

### uart_remove_one_port

detach a driver defined port structure

#### Synopsis

       int uart_remove_one_port
       struct uart_driver * drv
       struct uart_port * port

#### Arguments

`drv`

  pointer to the uart low level driver structure for this port

`port`

  uart port structure for this port

#### Description

This unhooks (and hangs up) the specified port structure from the core driver. No further calls will be made to the low-level code for this port.

### LINUX

Kernel Hackers Manual March 2006
serial8250_suspend_port
9

### serial8250_suspend_port

suspend one serial port

#### Synopsis

       void serial8250_suspend_port
       int line

#### Arguments

`line`

  serial line number

#### Description

Suspend one serial port.

### LINUX

Kernel Hackers Manual March 2006
serial8250_resume_port
9

### serial8250_resume_port

resume one serial port

#### Synopsis

       void serial8250_resume_port
       int line

#### Arguments

`line`

  serial line number

#### Description

Resume one serial port.

### LINUX

Kernel Hackers Manual March 2006
serial8250_register_port
9

### serial8250_register_port

register a serial port

#### Synopsis

       int serial8250_register_port
       struct uart_port * port

#### Arguments

`port`

  serial port template

#### Description

Configure the serial port specified by the request. If the port exists and is in use, it is hung up and unregistered first.

The port is then probed and if necessary the IRQ is autodetected If this fails an error is returned.

On success the port is ready to use and the line number is returned.

### LINUX

Kernel Hackers Manual March 2006
serial8250_unregister_port
9

### serial8250_unregister_port

remove a 16x50 serial port at runtime

#### Synopsis

       void serial8250_unregister_port
       int line

#### Arguments

`line`

  serial line number

#### Description

Remove one serial port. This may not be called from interrupt context. We hand the port back to the our control.

## Z85230 Support Library

### LINUX

Kernel Hackers Manual March 2006
z8530_interrupt
9

### z8530_interrupt

Handle an interrupt from a Z8530

#### Synopsis

       irqreturn_t z8530_interrupt
       int irq
       void * dev_id
       struct pt_regs * regs

#### Arguments

`irq`

  Interrupt number

`dev_id`

  The Z8530 device that is interrupting.

`regs`

  unused

#### Description

A Z85[2]30 device has stuck its hand in the air for attention. We scan both the channels on the chip for events and then call the channel specific call backs for each channel that has events. We have to use callback functions because the two channels can be in different modes.

Locking is done for the handlers. Note that locking is done at the chip level (the 5uS delay issue is per chip not per channel). c->lock for both channels points to dev->lock

### LINUX

Kernel Hackers Manual March 2006
z8530_sync_open
9

### z8530_sync_open

Open a Z8530 channel for PIO

#### Synopsis

       int z8530_sync_open
       struct net_device * dev
       struct z8530_channel * c

#### Arguments

`dev`

  The network interface we are using

`c`

  The Z8530 channel to open in synchronous PIO mode

#### Description

Switch a Z8530 into synchronous mode without DMA assist. We raise the RTS/DTR and commence network operation.

### LINUX

Kernel Hackers Manual March 2006
z8530_sync_close
9

### z8530_sync_close

Close a PIO Z8530 channel

#### Synopsis

       int z8530_sync_close
       struct net_device * dev
       struct z8530_channel * c

#### Arguments

`dev`

  Network device to close

`c`

  Z8530 channel to disassociate and move to idle

#### Description

Close down a Z8530 interface and switch its interrupt handlers to discard future events.

### LINUX

Kernel Hackers Manual March 2006
z8530_sync_dma_open
9

### z8530_sync_dma_open

Open a Z8530 for DMA I/O

#### Synopsis

       int z8530_sync_dma_open
       struct net_device * dev
       struct z8530_channel * c

#### Arguments

`dev`

  The network device to attach

`c`

  The Z8530 channel to configure in sync DMA mode.

#### Description

Set up a Z85x30 device for synchronous DMA in both directions. Two ISA DMA channels must be available for this to work. We assume ISA DMA driven I/O and PC limits on access.

### LINUX

Kernel Hackers Manual March 2006
z8530_sync_dma_close
9

### z8530_sync_dma_close

Close down DMA I/O

#### Synopsis

       int z8530_sync_dma_close
       struct net_device * dev
       struct z8530_channel * c

#### Arguments

`dev`

  Network device to detach

`c`

  Z8530 channel to move into discard mode

#### Description

Shut down a DMA mode synchronous interface. Halt the DMA, and free the buffers.

### LINUX

Kernel Hackers Manual March 2006
z8530_sync_txdma_open
9

### z8530_sync_txdma_open

Open a Z8530 for TX driven DMA

#### Synopsis

       int z8530_sync_txdma_open
       struct net_device * dev
       struct z8530_channel * c

#### Arguments

`dev`

  The network device to attach

`c`

  The Z8530 channel to configure in sync DMA mode.

#### Description

Set up a Z85x30 device for synchronous DMA tranmission. One ISA DMA channel must be available for this to work. The receive side is run in PIO mode, but then it has the bigger FIFO.

### LINUX

Kernel Hackers Manual March 2006
z8530_sync_txdma_close
9

### z8530_sync_txdma_close

Close down a TX driven DMA channel

#### Synopsis

       int z8530_sync_txdma_close
       struct net_device * dev
       struct z8530_channel * c

#### Arguments

`dev`

  Network device to detach

`c`

  Z8530 channel to move into discard mode

#### Description

Shut down a DMA/PIO split mode synchronous interface. Halt the DMA, and free the buffers.

### LINUX

Kernel Hackers Manual March 2006
z8530_describe
9

### z8530_describe

Uniformly describe a Z8530 port

#### Synopsis

       void z8530_describe
       struct z8530_dev * dev
       char * mapping
       unsigned long io

#### Arguments

`dev`

  Z8530 device to describe

`mapping`

  string holding mapping type (eg I/O or Mem)

`io`

  the port value in question

#### Description

Describe a Z8530 in a standard format. We must pass the I/O as the port offset isnt predictable. The main reason for this function is to try and get a common format of report.

### LINUX

Kernel Hackers Manual March 2006
z8530_init
9

### z8530_init

Initialise a Z8530 device

#### Synopsis

       int z8530_init
       struct z8530_dev * dev

#### Arguments

`dev`

  Z8530 device to initialise.

#### Description

Configure up a Z8530/Z85C30 or Z85230 chip. We check the device is present, identify the type and then program it to hopefully keep quite and behave. This matters a lot, a Z8530 in the wrong state will sometimes get into stupid modes generating 10Khz interrupt streams and the like.

We set the interrupt handler up to discard any events, in case we get them during reset or setp.

Return 0 for success, or a negative value indicating the problem in errno form.

### LINUX

Kernel Hackers Manual March 2006
z8530_shutdown
9

### z8530_shutdown

Shutdown a Z8530 device

#### Synopsis

       int z8530_shutdown
       struct z8530_dev * dev

#### Arguments

`dev`

  The Z8530 chip to shutdown

#### Description

We set the interrupt handlers to silence any interrupts. We then reset the chip and wait 100uS to be sure the reset completed. Just in case the caller then tries to do stuff.

This is called without the lock held

### LINUX

Kernel Hackers Manual March 2006
z8530_channel_load
9

### z8530_channel_load

Load channel data

#### Synopsis

       int z8530_channel_load
       struct z8530_channel * c
       u8 * rtable

#### Arguments

`c`

  Z8530 channel to configure

`rtable`

  table of register, value pairs

#### FIXME

ioctl to allow user uploaded tables

Load a Z8530 channel up from the system data. We use +16 to indicate the prime registers. The value 255 terminates the table.

### LINUX

Kernel Hackers Manual March 2006
z8530_null_rx
9

### z8530_null_rx

Discard a packet

#### Synopsis

       void z8530_null_rx
       struct z8530_channel * c
       struct sk_buff * skb

#### Arguments

`c`

  The channel the packet arrived on

`skb`

  The buffer

#### Description

We point the receive handler at this function when idle. Instead of syncppp processing the frames we get to throw them away.

### LINUX

Kernel Hackers Manual March 2006
z8530_queue_xmit
9

### z8530_queue_xmit

Queue a packet

#### Synopsis

       int z8530_queue_xmit
       struct z8530_channel * c
       struct sk_buff * skb

#### Arguments

`c`

  The channel to use

`skb`

  The packet to kick down the channel

#### Description

Queue a packet for transmission. Because we have rather hard to hit interrupt latencies for the Z85230 per packet even in DMA mode we do the flip to DMA buffer if needed here not in the IRQ.

Called from the network code. The lock is not held at this point.

### LINUX

Kernel Hackers Manual March 2006
z8530_get_stats
9

### z8530_get_stats

Get network statistics

#### Synopsis

       struct net_device_stats * z8530_get_stats
       struct z8530_channel * c

#### Arguments

`c`

  The channel to use

#### Description

Get the statistics block. We keep the statistics in software as the chip doesn't do it for us.

Locking is ignored here - we could lock for a copy but its not likely to be that big an issue

## Frame Buffer Library

The frame buffer drivers depend heavily on four data structures. These structures are declared in include/linux/fb.h. They are fb_info, fb_var_screeninfo, fb_fix_screeninfo and fb_monospecs. The last three can be made available to and from userland.

fb_info defines the current state of a particular video card. Inside fb_info, there exists a fb_ops structure which is a collection of needed functions to make fbdev and fbcon work. fb_info is only visible to the kernel.

fb_var_screeninfo is used to describe the features of a video card that are user defined. With fb_var_screeninfo, things such as depth and the resolution may be defined.

The next structure is fb_fix_screeninfo. This defines the properties of a card that are created when a mode is set and can't be changed otherwise. A good example of this is the start of the frame buffer memory. This "locks" the address of the frame buffer memory, so that it cannot be changed or moved.

The last structure is fb_monospecs. In the old API, there was little importance for fb_monospecs. This allowed for forbidden things such as setting a mode of 800x600 on a fix frequency monitor. With the new API, fb_monospecs prevents such things, and if used correctly, can prevent a monitor from being cooked. fb_monospecs will not be useful until kernels 2.5.x.

### Frame Buffer Memory

#### LINUX

Kernel Hackers Manual March 2006
register_framebuffer
9

#### register_framebuffer

registers a frame buffer device

##### Synopsis

       int register_framebuffer
       struct fb_info * fb_info

##### Arguments

`fb_info`

  frame buffer info structure

##### Description

Registers a frame buffer device `fb_info`.

Returns negative errno on error, or zero for success.

#### LINUX

Kernel Hackers Manual March 2006
unregister_framebuffer
9

#### unregister_framebuffer

releases a frame buffer device

##### Synopsis

       int unregister_framebuffer
       struct fb_info * fb_info

##### Arguments

`fb_info`

  frame buffer info structure

##### Description

Unregisters a frame buffer device `fb_info`.

Returns negative errno on error, or zero for success.

#### LINUX

Kernel Hackers Manual March 2006
fb_register_client
9

#### fb_register_client

register a client notifier

##### Synopsis

       int fb_register_client
       struct notifier_block * nb

##### Arguments

`nb`

  notifier block to callback on events

#### LINUX

Kernel Hackers Manual March 2006
fb_unregister_client
9

#### fb_unregister_client

unregister a client notifier

##### Synopsis

       int fb_unregister_client
       struct notifier_block * nb

##### Arguments

`nb`

  notifier block to callback on events

#### LINUX

Kernel Hackers Manual March 2006
fb_set_suspend
9

#### fb_set_suspend

low level driver signals suspend

##### Synopsis

       void fb_set_suspend
       struct fb_info * info
       int state

##### Arguments

`info`

  framebuffer affected

`state`

  0 = resuming, !=0 = suspending

##### Description

This is meant to be used by low level drivers to signal suspend/resume to the core & clients. It must be called with the console semaphore held

#### LINUX

Kernel Hackers Manual March 2006
fb_con_duit
9

#### fb_con_duit

user<->fbcon passthrough

##### Synopsis

       int fb_con_duit
       struct fb_info * info
       int event
       void * data

##### Arguments

`info`

  struct fb_info

`event`

  notification event to be passed to fbcon

`data`

  private data

##### Description

DESCRIPTION This function is an fbcon-user event passing channel which bypasses fbdev. This is hopefully temporary until a user interface for fbcon is created

#### LINUX

Kernel Hackers Manual March 2006
fb_get_options
9

#### fb_get_options

get kernel boot parameters

##### Synopsis

       int fb_get_options
       char * name
       char ** option

##### Arguments

`name`

  framebuffer name as it would appear in the boot parameter line (video=<name>:<options>)

`option`

  the option will be stored here

##### NOTE

Needed to maintain backwards compatibility

### Frame Buffer Colormap

#### LINUX

Kernel Hackers Manual March 2006
fb_alloc_cmap
9

#### fb_alloc_cmap

allocate a colormap

##### Synopsis

       int fb_alloc_cmap
       struct fb_cmap * cmap
       int len
       int transp

##### Arguments

`cmap`

  frame buffer colormap structure

`len`

  length of `cmap`

`transp`

  boolean, 1 if there is transparency, 0 otherwise

##### Description

Allocates memory for a colormap `cmap`. `len` is the number of entries in the palette.

Returns -1 errno on error, or zero on success.

#### LINUX

Kernel Hackers Manual March 2006
fb_dealloc_cmap
9

#### fb_dealloc_cmap

deallocate a colormap

##### Synopsis

       void fb_dealloc_cmap
       struct fb_cmap * cmap

##### Arguments

`cmap`

  frame buffer colormap structure

##### Description

Deallocates a colormap that was previously allocated with `fb_alloc_cmap`.

#### LINUX

Kernel Hackers Manual March 2006
fb_copy_cmap
9

#### fb_copy_cmap

copy a colormap

##### Synopsis

       int fb_copy_cmap
       struct fb_cmap * from
       struct fb_cmap * to

##### Arguments

`from`

  frame buffer colormap structure

`to`

  frame buffer colormap structure

##### Description

Copy contents of colormap from `from` to `to`.

#### LINUX

Kernel Hackers Manual March 2006
fb_set_cmap
9

#### fb_set_cmap

set the colormap

##### Synopsis

       int fb_set_cmap
       struct fb_cmap * cmap
       struct fb_info * info

##### Arguments

`cmap`

  frame buffer colormap structure

`info`

  frame buffer info structure

##### Description

Sets the colormap `cmap` for a screen of device `info`.

Returns negative errno on error, or zero on success.

#### LINUX

Kernel Hackers Manual March 2006
fb_default_cmap
9

#### fb_default_cmap

get default colormap

##### Synopsis

       struct fb_cmap * fb_default_cmap
       int len

##### Arguments

`len`

  size of palette for a depth

##### Description

Gets the default colormap for a specific screen depth. `len` is the size of the palette for a particular screen depth.

Returns pointer to a frame buffer colormap structure.

#### LINUX

Kernel Hackers Manual March 2006
fb_invert_cmaps
9

#### fb_invert_cmaps

invert all defaults colormaps

##### Synopsis

       void fb_invert_cmaps
        void

##### Arguments

`void`

  no arguments

##### Description

Invert all default colormaps.

### Frame Buffer Video Mode Database

#### LINUX

Kernel Hackers Manual March 2006
fb_try_mode
9

#### fb_try_mode

test a video mode

##### Synopsis

       int fb_try_mode
       struct fb_var_screeninfo * var
       struct fb_info * info
       const struct fb_videomode * mode
       unsigned int bpp

##### Arguments

`var`

  frame buffer user defined part of display

`info`

  frame buffer info structure

`mode`

  frame buffer video mode structure

`bpp`

  color depth in bits per pixel

##### Description

Tries a video mode to test it's validity for device `info`.

Returns 1 on success.

#### LINUX

Kernel Hackers Manual March 2006
fb_find_mode
9

#### fb_find_mode

finds a valid video mode

##### Synopsis

       int fb_find_mode
       struct fb_var_screeninfo * var
       struct fb_info * info
       const char * mode_option
       const struct fb_videomode * db
       unsigned int dbsize
       const struct fb_videomode * default_mode
       unsigned int default_bpp

##### Arguments

`var`

  frame buffer user defined part of display

`info`

  frame buffer info structure

`mode_option`

  string video mode to find

`db`

  video mode database

`dbsize`

  size of `db`

`default_mode`

  default video mode to fall back to

`default_bpp`

  default color depth in bits per pixel

##### Description

Finds a suitable video mode, starting with the specified mode in `mode_option` with fallback to `default_mode`. If `default_mode` fails, all modes in the video mode database will be tried.

Valid mode specifiers for `mode_option`:

<xres>x<yres>[M][R][-<bpp>][@<refresh>][i][m] or <name>[-<bpp>][@<refresh>]

with <xres>, <yres>, <bpp> and <refresh> decimal numbers and <name> a string.

If 'M' is present after yres (and before refresh/bpp if present), the function will compute the timings using VESA(tm) Coordinated Video Timings (CVT). If 'R' is present after 'M', will compute with reduced blanking (for flatpanels). If 'i' is present, compute interlaced mode. If 'm' is present, add margins equal to 1.8% of xres rounded down to 8 pixels, and 1.8% of yres. The char 'i' and 'm' must be after 'M' and 'R'. Example:

1024x768MR-8`60m` - Reduced blank with margins at 60Hz.

##### NOTE

The passed struct `var` is _not_ cleared! This allows you to supply values for e.g. the grayscale and accel_flags fields.

Returns zero for failure, 1 if using specified `mode_option`, 2 if using specified `mode_option` with an ignored refresh rate, 3 if default mode is used, 4 if fall back to any valid mode.

#### LINUX

Kernel Hackers Manual March 2006
fb_var_to_videomode
9

#### fb_var_to_videomode

convert fb_var_screeninfo to fb_videomode

##### Synopsis

       void fb_var_to_videomode
       struct fb_videomode * mode
       struct fb_var_screeninfo * var

##### Arguments

`mode`

  pointer to struct fb_videomode

`var`

  pointer to struct fb_var_screeninfo

#### LINUX

Kernel Hackers Manual March 2006
fb_videomode_to_var
9

#### fb_videomode_to_var

convert fb_videomode to fb_var_screeninfo

##### Synopsis

       void fb_videomode_to_var
       struct fb_var_screeninfo * var
       struct fb_videomode * mode

##### Arguments

`var`

  pointer to struct fb_var_screeninfo

`mode`

  pointer to struct fb_videomode

#### LINUX

Kernel Hackers Manual March 2006
fb_mode_is_equal
9

#### fb_mode_is_equal

compare 2 videomodes

##### Synopsis

       int fb_mode_is_equal
       struct fb_videomode * mode1
       struct fb_videomode * mode2

##### Arguments

`mode1`

  first videomode

`mode2`

  second videomode

##### RETURNS

1 if equal, 0 if not

#### LINUX

Kernel Hackers Manual March 2006
fb_find_best_mode
9

#### fb_find_best_mode

find best matching videomode

##### Synopsis

       struct fb_videomode * fb_find_best_mode
       struct fb_var_screeninfo * var
       struct list_head * head

##### Arguments

`var`

  pointer to struct fb_var_screeninfo

`head`

  pointer to struct list_head of modelist

##### RETURNS

struct fb_videomode, NULL if none found

##### IMPORTANT

This function assumes that all modelist entries in info->modelist are valid.

##### NOTES

Finds best matching videomode which has an equal or greater dimension than var->xres and var->yres. If more than 1 videomode is found, will return the videomode with the highest refresh rate

#### LINUX

Kernel Hackers Manual March 2006
fb_find_nearest_mode
9

#### fb_find_nearest_mode

find closest videomode

##### Synopsis

       struct fb_videomode * fb_find_nearest_mode
       struct fb_videomode * mode
       struct list_head * head

##### Arguments

`mode`

  pointer to struct fb_videomode

`head`

  pointer to modelist

##### Description

Finds best matching videomode, smaller or greater in dimension. If more than 1 videomode is found, will return the videomode with the closest refresh rate.

##### Description

Finds best matching videomode, smaller or greater in dimension. If more than 1 videomode is found, will return the videomode with the closest refresh rate.

#### LINUX

Kernel Hackers Manual March 2006
fb_match_mode
9

#### fb_match_mode

find a videomode which exactly matches the timings in var

##### Synopsis

       struct fb_videomode * fb_match_mode
       struct fb_var_screeninfo * var
       struct list_head * head

##### Arguments

`var`

  pointer to struct fb_var_screeninfo

`head`

  pointer to struct list_head of modelist

##### RETURNS

struct fb_videomode, NULL if none found

#### LINUX

Kernel Hackers Manual March 2006
fb_add_videomode
9

#### fb_add_videomode

##### Synopsis

       int fb_add_videomode
       struct fb_videomode * mode
       struct list_head * head

##### Arguments

`mode`

  videomode to add

`head`

  struct list_head of modelist

##### NOTES

Will only add unmatched mode entries

#### LINUX

Kernel Hackers Manual March 2006
fb_delete_videomode
9

#### fb_delete_videomode

##### Synopsis

       void fb_delete_videomode
       struct fb_videomode * mode
       struct list_head * head

##### Arguments

`mode`

  videomode to remove

`head`

  struct list_head of modelist

##### NOTES

Will remove all matching mode entries

#### LINUX

Kernel Hackers Manual March 2006
fb_destroy_modelist
9

#### fb_destroy_modelist

##### Synopsis

       void fb_destroy_modelist
       struct list_head * head

##### Arguments

`head`

  struct list_head of modelist

#### LINUX

Kernel Hackers Manual March 2006
fb_videomode_to_modelist
9

#### fb_videomode_to_modelist

##### Synopsis

       void fb_videomode_to_modelist
       struct fb_videomode * modedb
       int num
       struct list_head * head

##### Arguments

`modedb`

  array of struct fb_videomode

`num`

  number of entries in array

`head`

  struct list_head of modelist

### Frame Buffer Macintosh Video Mode Database

#### LINUX

Kernel Hackers Manual March 2006
mac_vmode_to_var
9

#### mac_vmode_to_var

converts vmode/cmode pair to var structure

##### Synopsis

       int mac_vmode_to_var
       int vmode
       int cmode
       struct fb_var_screeninfo * var

##### Arguments

`vmode`

  MacOS video mode

`cmode`

  MacOS color mode

`var`

  frame buffer video mode structure

##### Description

Converts a MacOS vmode/cmode pair to a frame buffer video mode structure.

Returns negative errno on error, or zero for success.

#### LINUX

Kernel Hackers Manual March 2006
mac_var_to_vmode
9

#### mac_var_to_vmode

convert var structure to MacOS vmode/cmode pair

##### Synopsis

       int mac_var_to_vmode
       const struct fb_var_screeninfo * var
       int * vmode
       int * cmode

##### Arguments

`var`

  frame buffer video mode structure

`vmode`

  MacOS video mode

`cmode`

  MacOS color mode

##### Description

Converts a frame buffer video mode structure to a MacOS vmode/cmode pair.

Returns negative errno on error, or zero for success.

#### LINUX

Kernel Hackers Manual March 2006
mac_map_monitor_sense
9

#### mac_map_monitor_sense

Convert monitor sense to vmode

##### Synopsis

       int mac_map_monitor_sense
       int sense

##### Arguments

`sense`

  Macintosh monitor sense number

##### Description

Converts a Macintosh monitor sense number to a MacOS vmode number.

Returns MacOS vmode video mode number.

#### LINUX

Kernel Hackers Manual March 2006
mac_find_mode
9

#### mac_find_mode

find a video mode

##### Synopsis

       int __init mac_find_mode
       struct fb_var_screeninfo * var
       struct fb_info * info
       const char * mode_option
       unsigned int default_bpp

##### Arguments

`var`

  frame buffer user defined part of display

`info`

  frame buffer info structure

`mode_option`

  video mode name (see mac_modedb[])

`default_bpp`

  default color depth in bits per pixel

##### Description

Finds a suitable video mode. Tries to set mode specified by `mode_option`. If the name of the wanted mode begins with 'mac', the Mac video mode database will be used, otherwise it will fall back to the standard video mode database.

##### Note

Function marked as __init and can only be used during system boot.

Returns error code from fb_find_mode (see fb_find_mode function).

### Frame Buffer Fonts

Refer to the file drivers/video/console/fonts.c for more information.