module.h

 module.h 에는 임베디드 프로그램을 만드는데 유용한 매크로들이 포함되어 있다.

 여기에 그 내용을 싣는다.(커널 버전은 2.4.19)

/*
 * Dynamic loading of modules into the kernel.
 *
 * Rewritten by Richard Henderson <rth@tamu.edu> Dec 1996
 */

#ifndef _LINUX_MODULE_H
#define _LINUX_MODULE_H

#include <linux/config.h>
#include <linux/spinlock.h>
#include <linux/list.h>

#ifdef __GENKSYMS__
#  define _set_ver(sym) sym
#  undef  MODVERSIONS
#  define MODVERSIONS
#else /* ! __GENKSYMS__ */
# if !defined(MODVERSIONS) && defined(EXPORT_SYMTAB)
#   define _set_ver(sym) sym
#   include <linux/modversions.h>
# endif
#endif /* __GENKSYMS__ */

#include <asm/atomic.h>

/* Don’t need to bring in all of uaccess.h just for this decl.  */
struct exception_table_entry;

/* Used by get_kernel_syms, which is obsolete.  */
struct kernel_sym
{
    unsigned long value;
    char name[60];        /* should have been 64-sizeof(long); oh well */
};

struct module_symbol
{
    unsigned long value;
    const char *name;
};

struct module_ref
{
    struct module *dep;    /* “parent” pointer */
    struct module *ref;    /* “child” pointer */
    struct module_ref *next_ref;
};

/* TBD */
struct module_persist;

struct module
{
    unsigned long size_of_struct;    /* == sizeof(module) */
    struct module *next;
    const char *name;
    unsigned long size;

    union
    {
        atomic_t usecount;
        long pad;
    } uc;                /* Needs to keep its size – so says rth */

    unsigned long flags;        /* AUTOCLEAN et al */

    unsigned nsyms;
    unsigned ndeps;

    struct module_symbol *syms;
    struct module_ref *deps;
    struct module_ref *refs;
    int (*init)(void);
    void (*cleanup)(void);
    const struct exception_table_entry *ex_table_start;
    const struct exception_table_entry *ex_table_end;
#ifdef __alpha__
    unsigned long gp;
#endif
    /* Members past this point are extensions to the basic
       module support and are optional.  Use mod_member_present()
       to examine them.  */
    const struct module_persist *persist_start;
    const struct module_persist *persist_end;
    int (*can_unload)(void);
    int runsize;            /* In modutils, not currently used */
    const char *kallsyms_start;    /* All symbols for kernel debugging */
    const char *kallsyms_end;
    const char *archdata_start;    /* arch specific data for module */
    const char *archdata_end;
    const char *kernel_data;    /* Reserved for kernel internal use */
};

struct module_info
{
    unsigned long addr;
    unsigned long size;
    unsigned long flags;
    long usecount;
};

/* Bits of module.flags.  */

#define MOD_UNINITIALIZED    0
#define MOD_RUNNING        1
#define MOD_DELETED        2
#define MOD_AUTOCLEAN        4
#define MOD_VISITED          8
#define MOD_USED_ONCE        16
#define MOD_JUST_FREED        32
#define MOD_INITIALIZING    64

/* Values for query_module’s which.  */

#define QM_MODULES    1
#define QM_DEPS        2
#define QM_REFS        3
#define QM_SYMBOLS    4
#define QM_INFO        5

/* Can the module be queried? */
#define MOD_CAN_QUERY(mod) (((mod)->flags & (MOD_RUNNING | MOD_INITIALIZING)) && !((mod)->flags & MOD_DELETED))

/* When struct module is extended, we must test whether the new member
   is present in the header received from insmod before we can use it.  
   This function returns true if the member is present.  */

#define mod_member_present(mod,member)                     
    ((unsigned long)(&((struct module *)0L)->member + 1)        
     <= (mod)->size_of_struct)

/*
 * Ditto for archdata.  Assumes mod->archdata_start and mod->archdata_end
 * are validated elsewhere.
 */
#define mod_archdata_member_present(mod, type, member)            
    (((unsigned long)(&((type *)0L)->member) +            
      sizeof(((type *)0L)->member)) <=                
     ((mod)->archdata_end – (mod)->archdata_start))
    

/* Check if an address p with number of entries n is within the body of module m */
#define mod_bound(p, n, m) ((unsigned long)(p) >= ((unsigned long)(m) + ((m)->size_of_struct)) &&
             (unsigned long)((p)+(n)) <= (unsigned long)(m) + (m)->size)

/* Backwards compatibility definition.  */

#define GET_USE_COUNT(module)    (atomic_read(&(module)->uc.usecount))

/* Poke the use count of a module.  */

#define __MOD_INC_USE_COUNT(mod)                    
    (atomic_inc(&(mod)->uc.usecount), (mod)->flags |= MOD_VISITED|MOD_USED_ONCE)
#define __MOD_DEC_USE_COUNT(mod)                    
    (atomic_dec(&(mod)->uc.usecount), (mod)->flags |= MOD_VISITED)
#define __MOD_IN_USE(mod)                        
    (mod_member_present((mod), can_unload) && (mod)->can_unload    
     ? (mod)->can_unload() : atomic_read(&(mod)->uc.usecount))

/* Indirect stringification.  */

#define __MODULE_STRING_1(x)    #x
#define __MODULE_STRING(x)    __MODULE_STRING_1(x)

/* Generic inter module communication.
 *
 * NOTE: This interface is intended for small amounts of data that are
 *       passed between two objects and either or both of the objects
 *       might be compiled as modules.  Do not over use this interface.
 *
 *       If more than two objects need to communicate then you probably
 *       need a specific interface instead of abusing this generic
 *       interface.  If both objects are *always* built into the kernel
 *       then a global extern variable is good enough, you do not need
 *       this interface.
 *
 * Keith Owens <kaos@ocs.com.au> 28 Oct 2000.
 */

#ifdef __KERNEL__
#define HAVE_INTER_MODULE
extern void inter_module_register(const char *, struct module *, const void *);
extern void inter_module_unregister(const char *);
extern const void *inter_module_get(const char *);
extern const void *inter_module_get_request(const char *, const char *);
extern void inter_module_put(const char *);

struct inter_module_entry {
    struct list_head list;
    const char *im_name;
    struct module *owner;
    const void *userdata;
};

extern int try_inc_mod_count(struct module *mod);
#endif /* __KERNEL__ */

#if defined(MODULE) && !defined(__GENKSYMS__)

/* Embedded module documentation macros.  */

/* For documentation purposes only.  */

#define MODULE_AUTHOR(name)                          
const char __module_author[] __attribute__((section(“.modinfo”))) =       
“author=” name

#define MODULE_DESCRIPTION(desc)                      
const char __module_description[] __attribute__((section(“.modinfo”))) =  
“description=” desc

/* Could potentially be used by kmod…  */

#define MODULE_SUPPORTED_DEVICE(dev)                      
const char __module_device[] __attribute__((section(“.modinfo”))) =       
“device=” dev

/* Used to verify parameters given to the module.  The TYPE arg should
   be a string in the following format:
       [min[-max]]{b,h,i,l,s}
   The MIN and MAX specifiers delimit the length of the array.  If MAX
   is omitted, it defaults to MIN; if both are omitted, the default is 1.
   The final character is a type specifier:
    b    byte
    h    short
    i    int
    l    long
    s    string
*/

#define MODULE_PARM(var,type)            
const char __module_parm_##var[]        
__attribute__((section(“.modinfo”))) =        
“parm_” __MODULE_STRING(var) “=” type

#define MODULE_PARM_DESC(var,desc)        
const char __module_parm_desc_##var[]        
__attribute__((section(“.modinfo”))) =        
“parm_desc_” __MODULE_STRING(var) “=” desc

/*
 * MODULE_DEVICE_TABLE exports information about devices
 * currently supported by this module.  A device type, such as PCI,
 * is a C-like identifier passed as the first arg to this macro.
 * The second macro arg is the variable containing the device
 * information being made public.
 *
 * The following is a list of known device types (arg 1),
 * and the C types which are to be passed as arg 2.
 * pci – struct pci_device_id – List of PCI ids supported by this module
 * isapnp – struct isapnp_device_id – List of ISA PnP ids supported by this module
 * usb – struct usb_device_id – List of USB ids supported by this module
 */
#define MODULE_GENERIC_TABLE(gtype,name)    
static const unsigned long __module_##gtype##_size
  __attribute__ ((unused)) = sizeof(struct gtype##_id);
static const struct gtype##_id * __module_##gtype##_table
  __attribute__ ((unused)) = name

/*
 * The following license idents are currently accepted as indicating free
 * software modules
 *
 *    “GPL”                [GNU Public License v2 or later]
 *    “GPL v2”            [GNU Public License v2]
 *    “GPL and additional rights”    [GNU Public License v2 rights and more]
 *    “Dual BSD/GPL”            [GNU Public License v2 or BSD license choice]
 *    “Dual MPL/GPL”            [GNU Public License v2 or Mozilla license choice]
 *
 * The following other idents are available
 *
 *    “Proprietary”            [Non free products]
 *
 * There are dual licensed components, but when running with Linux it is the
 * GPL that is relevant so this is a non issue. Similarly LGPL linked with GPL
 * is a GPL combined work.
 *
 * This exists for several reasons
 * 1.    So modinfo can show license info for users wanting to vet their setup
 *    is free
 * 2.    So the community can ignore bug reports including proprietary modules
 * 3.    So vendors can do likewise based on their own policies
 */
 
#define MODULE_LICENSE(license)     
static const char __module_license[] __attribute__((section(“.modinfo”))) =  
“license=” license

/* Define the module variable, and usage macros.  */
extern struct module __this_module;

#define THIS_MODULE        (&__this_module)
#define MOD_INC_USE_COUNT    __MOD_INC_USE_COUNT(THIS_MODULE)
#define MOD_DEC_USE_COUNT    __MOD_DEC_USE_COUNT(THIS_MODULE)
#define MOD_IN_USE        __MOD_IN_USE(THIS_MODULE)

#include <linux/version.h>
static const char __module_kernel_version[] __attribute__((section(“.modinfo”))) =
“kernel_version=” UTS_RELEASE;
#ifdef MODVERSIONS
static const char __module_using_checksums[] __attribute__((section(“.modinfo”))) =
“using_checksums=1”;
#endif

#else /* MODULE */

#define MODULE_AUTHOR(name)
#define MODULE_LICENSE(license)
#define MODULE_DESCRIPTION(desc)
#define MODULE_SUPPORTED_DEVICE(name)
#define MODULE_PARM(var,type)
#define MODULE_PARM_DESC(var,desc)

/* Create a dummy reference to the table to suppress gcc unused warnings.  Put
 * the reference in the .data.exit section which is discarded when code is built
 * in, so the reference does not bloat the running kernel.  Note: cannot be
 * const, other exit data may be writable.
 */
#define MODULE_GENERIC_TABLE(gtype,name)
static const struct gtype##_id * __module_##gtype##_table
  __attribute__ ((unused, __section__(“.data.exit”))) = name

#ifndef __GENKSYMS__

#define THIS_MODULE        NULL
#define MOD_INC_USE_COUNT    do { } while (0)
#define MOD_DEC_USE_COUNT    do { } while (0)
#define MOD_IN_USE        1

extern struct module *module_list;

#endif /* !__GENKSYMS__ */

#endif /* MODULE */

#define MODULE_DEVICE_TABLE(type,name)        
  MODULE_GENERIC_TABLE(type##_device,name)

/* Export a symbol either from the kernel or a module.

   In the kernel, the symbol is added to the kernel’s global symbol table.

   In a module, it controls which variables are exported.  If no
   variables are explicitly exported, the action is controled by the
   insmod -[xX] flags.  Otherwise, only the variables listed are exported.
   This obviates the need for the old register_symtab() function.  */

#if defined(__GENKSYMS__)

/* We want the EXPORT_SYMBOL tag left intact for recognition.  */

#elif !defined(AUTOCONF_INCLUDED)

#define __EXPORT_SYMBOL(sym,str)   error config_must_be_included_before_module
#define EXPORT_SYMBOL(var)       error config_must_be_included_before_module
#define EXPORT_SYMBOL_NOVERS(var)  error config_must_be_included_before_module
#define EXPORT_SYMBOL_GPL(var)  error config_must_be_included_before_module

#elif !defined(CONFIG_MODULES)

#define __EXPORT_SYMBOL(sym,str)
#define EXPORT_SYMBOL(var)
#define EXPORT_SYMBOL_NOVERS(var)
#define EXPORT_SYMBOL_GPL(var)

#elif !defined(EXPORT_SYMTAB)

#define __EXPORT_SYMBOL(sym,str)   error this_object_must_be_defined_as_export_objs_in_the_Makefile
#define EXPORT_SYMBOL(var)       error this_object_must_be_defined_as_export_objs_in_the_Makefile
#define EXPORT_SYMBOL_NOVERS(var)  error this_object_must_be_defined_as_export_objs_in_the_Makefile
#define EXPORT_SYMBOL_GPL(var)  error this_object_must_be_defined_as_export_objs_in_the_Makefile

#else

#define __EXPORT_SYMBOL(sym, str)            
const char __kstrtab_##sym[]                
__attribute__((section(“.kstrtab”))) = str;        
const struct module_symbol __ksymtab_##sym         
__attribute__((section(“__ksymtab”))) =            
{ (unsigned long)&sym, __kstrtab_##sym }

#define __EXPORT_SYMBOL_GPL(sym, str)            
const char __kstrtab_##sym[]                
__attribute__((section(“.kstrtab”))) = “GPLONLY_” str;    
const struct module_symbol __ksymtab_##sym        
__attribute__((section(“__ksymtab”))) =            
{ (unsigned long)&sym, __kstrtab_##sym }

#if defined(MODVERSIONS) || !defined(CONFIG_MODVERSIONS)
#define EXPORT_SYMBOL(var)  __EXPORT_SYMBOL(var, __MODULE_STRING(var))
#define EXPORT_SYMBOL_GPL(var)  __EXPORT_SYMBOL_GPL(var, __MODULE_STRING(var))
#else
#define EXPORT_SYMBOL(var)  __EXPORT_SYMBOL(var, __MODULE_STRING(__VERSIONED_SYMBOL(var)))
#define EXPORT_SYMBOL_GPL(var)  __EXPORT_SYMBOL(var, __MODULE_STRING(__VERSIONED_SYMBOL(var)))
#endif

#define EXPORT_SYMBOL_NOVERS(var)  __EXPORT_SYMBOL(var, __MODULE_STRING(var))

#endif /* __GENKSYMS__ */

#ifdef MODULE
/* Force a module to export no symbols.  */
#define EXPORT_NO_SYMBOLS  __asm__(“.section __ksymtabn.previous”)
#else
#define EXPORT_NO_SYMBOLS
#endif /* MODULE */

#ifdef CONFIG_MODULES
#define SET_MODULE_OWNER(some_struct) do { (some_struct)->owner = THIS_MODULE; } while (0)
#else
#define SET_MODULE_OWNER(some_struct) do { } while (0)
#endif

#endif /* _LINUX_MODULE_H */

errno.h 파일 내용

 errno.h 파일에는 여러가지 에러코드에 대한 정의가 수록되어 있다.
 여기에 그 내용을 싣는다.

/usr/include/asm-generic/errno.h

#ifndef _ASM_GENERIC_ERRNO_H
#define _ASM_GENERIC_ERRNO_H

#include <asm-generic/errno-base.h>

#define    EDEADLK        35    /* Resource deadlock would occur */
#define    ENAMETOOLONG    36    /* File name too long */
#define    ENOLCK        37    /* No record locks available */
#define    ENOSYS        38    /* Function not implemented */
#define    ENOTEMPTY    39    /* Directory not empty */
#define    ELOOP        40    /* Too many symbolic links encountered */
#define    EWOULDBLOCK    EAGAIN    /* Operation would block */
#define    ENOMSG        42    /* No message of desired type */
#define    EIDRM        43    /* Identifier removed */
#define    ECHRNG        44    /* Channel number out of range */
#define    EL2NSYNC    45    /* Level 2 not synchronized */
#define    EL3HLT        46    /* Level 3 halted */
#define    EL3RST        47    /* Level 3 reset */
#define    ELNRNG        48    /* Link number out of range */
#define    EUNATCH        49    /* Protocol driver not attached */
#define    ENOCSI        50    /* No CSI structure available */
#define    EL2HLT        51    /* Level 2 halted */
#define    EBADE        52    /* Invalid exchange */
#define    EBADR        53    /* Invalid request descriptor */
#define    EXFULL        54    /* Exchange full */
#define    ENOANO        55    /* No anode */
#define    EBADRQC        56    /* Invalid request code */
#define    EBADSLT        57    /* Invalid slot */

#define    EDEADLOCK    EDEADLK

#define    EBFONT        59    /* Bad font file format */
#define    ENOSTR        60    /* Device not a stream */
#define    ENODATA        61    /* No data available */
#define    ETIME        62    /* Timer expired */
#define    ENOSR        63    /* Out of streams resources */
#define    ENONET        64    /* Machine is not on the network */
#define    ENOPKG        65    /* Package not installed */
#define    EREMOTE        66    /* Object is remote */
#define    ENOLINK        67    /* Link has been severed */
#define    EADV        68    /* Advertise error */
#define    ESRMNT        69    /* Srmount error */
#define    ECOMM        70    /* Communication error on send */
#define    EPROTO        71    /* Protocol error */
#define    EMULTIHOP    72    /* Multihop attempted */
#define    EDOTDOT        73    /* RFS specific error */
#define    EBADMSG        74    /* Not a data message */
#define    EOVERFLOW    75    /* Value too large for defined data type */
#define    ENOTUNIQ    76    /* Name not unique on network */
#define    EBADFD        77    /* File descriptor in bad state */
#define    EREMCHG        78    /* Remote address changed */
#define    ELIBACC        79    /* Can not access a needed shared library */
#define    ELIBBAD        80    /* Accessing a corrupted shared library */
#define    ELIBSCN        81    /* .lib section in a.out corrupted */
#define    ELIBMAX        82    /* Attempting to link in too many shared libraries */
#define    ELIBEXEC    83    /* Cannot exec a shared library directly */
#define    EILSEQ        84    /* Illegal byte sequence */
#define    ERESTART    85    /* Interrupted system call should be restarted */
#define    ESTRPIPE    86    /* Streams pipe error */
#define    EUSERS        87    /* Too many users */
#define    ENOTSOCK    88    /* Socket operation on non-socket */
#define    EDESTADDRREQ    89    /* Destination address required */
#define    EMSGSIZE    90    /* Message too long */
#define    EPROTOTYPE    91    /* Protocol wrong type for socket */
#define    ENOPROTOOPT    92    /* Protocol not available */
#define    EPROTONOSUPPORT    93    /* Protocol not supported */
#define    ESOCKTNOSUPPORT    94    /* Socket type not supported */
#define    EOPNOTSUPP    95    /* Operation not supported on transport endpoint */
#define    EPFNOSUPPORT    96    /* Protocol family not supported */
#define    EAFNOSUPPORT    97    /* Address family not supported by protocol */
#define    EADDRINUSE    98    /* Address already in use */
#define    EADDRNOTAVAIL    99    /* Cannot assign requested address */
#define    ENETDOWN    100    /* Network is down */
#define    ENETUNREACH    101    /* Network is unreachable */
#define    ENETRESET    102    /* Network dropped connection because of reset */
#define    ECONNABORTED    103    /* Software caused connection abort */
#define    ECONNRESET    104    /* Connection reset by peer */
#define    ENOBUFS        105    /* No buffer space available */
#define    EISCONN        106    /* Transport endpoint is already connected */
#define    ENOTCONN    107    /* Transport endpoint is not connected */
#define    ESHUTDOWN    108    /* Cannot send after transport endpoint shutdown */
#define    ETOOMANYREFS    109    /* Too many references: cannot splice */
#define    ETIMEDOUT    110    /* Connection timed out */
#define    ECONNREFUSED    111    /* Connection refused */
#define    EHOSTDOWN    112    /* Host is down */
#define    EHOSTUNREACH    113    /* No route to host */
#define    EALREADY    114    /* Operation already in progress */
#define    EINPROGRESS    115    /* Operation now in progress */
#define    ESTALE        116    /* Stale NFS file handle */
#define    EUCLEAN        117    /* Structure needs cleaning */
#define    ENOTNAM        118    /* Not a XENIX named type file */
#define    ENAVAIL        119    /* No XENIX semaphores available */
#define    EISNAM        120    /* Is a named type file */
#define    EREMOTEIO    121    /* Remote I/O error */
#define    EDQUOT        122    /* Quota exceeded */

#define    ENOMEDIUM    123    /* No medium found */
#define    EMEDIUMTYPE    124    /* Wrong medium type */
#define    ECANCELED    125    /* Operation Canceled */
#define    ENOKEY        126    /* Required key not available */
#define    EKEYEXPIRED    127    /* Key has expired */
#define    EKEYREVOKED    128    /* Key has been revoked */
#define    EKEYREJECTED    129    /* Key was rejected by service */

/* for robust mutexes */
#define    EOWNERDEAD    130    /* Owner died */
#define    ENOTRECOVERABLE    131    /* State not recoverable */

#endif

/usr/include/asm-generic/errno-base.h

#ifndef _ASM_GENERIC_ERRNO_BASE_H
#define _ASM_GENERIC_ERRNO_BASE_H

#define    EPERM         1    /* Operation not permitted */
#define    ENOENT         2    /* No such file or directory */
#define    ESRCH         3    /* No such process */
#define    EINTR         4    /* Interrupted system call */
#define    EIO         5    /* I/O error */
#define    ENXIO         6    /* No such device or address */
#define    E2BIG         7    /* Argument list too long */
#define    ENOEXEC         8    /* Exec format error */
#define    EBADF         9    /* Bad file number */
#define    ECHILD        10    /* No child processes */
#define    EAGAIN        11    /* Try again */
#define    ENOMEM        12    /* Out of memory */
#define    EACCES        13    /* Permission denied */
#define    EFAULT        14    /* Bad address */
#define    ENOTBLK        15    /* Block device required */
#define    EBUSY        16    /* Device or resource busy */
#define    EEXIST        17    /* File exists */
#define    EXDEV        18    /* Cross-device link */
#define    ENODEV        19    /* No such device */
#define    ENOTDIR        20    /* Not a directory */
#define    EISDIR        21    /* Is a directory */
#define    EINVAL        22    /* Invalid argument */
#define    ENFILE        23    /* File table overflow */
#define    EMFILE        24    /* Too many open files */
#define    ENOTTY        25    /* Not a typewriter */
#define    ETXTBSY        26    /* Text file busy */
#define    EFBIG        27    /* File too large */
#define    ENOSPC        28    /* No space left on device */
#define    ESPIPE        29    /* Illegal seek */
#define    EROFS        30    /* Read-only file system */
#define    EMLINK        31    /* Too many links */
#define    EPIPE        32    /* Broken pipe */
#define    EDOM        33    /* Math argument out of domain of func */
#define    ERANGE        34    /* Math result not representable */

#endif

디바이스 드라이버의 커널 삽입 과정

 다음과 같은 명령을 이용하여 디바이스 드라이버를 커널에 삽입한다.

 $ insmod driver.o

 여기서 driver.o는 테스트로 작성된 디바이스 드라이버 파일명이다.

 위와 같이 콘솔에서 insmod driver.o 를 실행 시키면 다음과 같은 시스템 콜이 수행되어 드라이버를 커널에 삽입한다.

 1. sys_create_module()을 사용하여 디바이스 드라이버를 적재하기 위한 메모리를 할당한다.
 2. sys_get_kernel_syms()를 이용하여 driver.o 안에 있는 심볼을 커널에 등록한다.
 3. 마지막으로 sys_init_module() 을 사용하여 driver.o를 메모리에 적재한다. 이 과정에서 driver.o 안에 있는 init_module()이 실행되고 그 안에 있는 커널 함수인 register_chrdev() 가 수행되어 디바이스 드라이버 이름과 메이저 번호와 file_operations 구조체를 커널 변수인 chrdevs에 등록한다.

 위와 같이 디바이스 드라이버를 커널에 삽입했으면 다음 해야 하는 일은 드라이버에 대응하는 특수 장치 파일(노드)을 만드는 일이다.

 다음은 콘솔에서 특수 장치 파일을 만드는 명령이다.

 $ mknod /dev/device c 주번호 부번호

  위의 명령에 의해 커널에서 수행 되는 일은 다음과 같다. mknod 명령은 커널의 sys_mknod()를 호출하고 이 함수는 다음과 같은 일을 수행한다.


 1. 먼저 /(root) 에서 시작해서 dev 디렉토리까지의 경로를 찾아 새로운 dentry를 하나 만들고 루트에 연결한다.
 2. inode 하나를 만들고 dentry의 d_inode에 연결한다.
 3. inode의 i_mode 와 i_rdev에 S_IFCHR 과 (주번호 << 8 | 부번호)을 기록한다.
 4. inode의 i_fop에 def_chr_fops의 주소값을 기록하여 이를 통해 open 메소드에 chrdev_open()이 연결되도록 한다.

 위와 같이 커널에 디바이스 드라이버를 삽입하고 이것에 대응하는 특수장치 파일을 만들어야 어플리케이션의 디바이스 드라이버 사용이 가능하다.

file_operations 구조체 원형

struct file_operations {
   struct module *owner;

   // llseek 메소드는 파일에서 현재의 read/write의 위치를 옮기며, 새로운 위치가 (양수)값으로 리턴된다. 에러는 음수값으로 반환된다.
   loff_ (*llseek) (struct file *, loff_t, int);

   // read 메소드는 디바이스에서 데이터를 가져오기 위해서 사용한다. 여기에 NULL 값을 사용하면 read 시스템
콜은 -EINVAL(“잘못된 매개 변수”)값을 돌려 주며 실패한다. 음수값이 아닌 리턴값은 성공적으로 읽은 바이트 수를 나타낸다.
   ssize_t (*read) (struct file *, char *, size_t, loff_t *);
  
   // 디바이스에 데이터를 보낸다. NULL 값을 스면 wirte 시스템 콜에 대해서 -EINVAL을 돌려준다. 리턴값이 음수가 아니면 성공적으로 작성된 데이터의 바이트 크기이다.
   ssize_t (*write) (struct file *, const char *, size_t, loff_t *);

   // 이 함수 포인터는 디바이스 노드에 대해서는 NULL이어야 한다. 이것은 디렉토리에 대해서 사용한다.
   int (*readdir) (struct file *, void *, filldir_t);

   // 현재의 프로세스를 대기 큐에 넣는다.
   unsigned int (*poll) (struct file *, struct poll_table_strcut *);

   // ioctl 시스템 콜은 디바이스에 종속적인 명령을 만들 수 있도록한다. 커널이 fops 테이블을 참조하지 않고도 인식할 수 있는 많은 ioctl 명령이 있다.
   int (*ioctl) (struct inode *, struct file *, unsigned int, unsigned long);

   // mmap은 디바이스 메모리를 프로세서의 메모리에 맵핑시키도록 요청하기 위해 사용된다. 디바이스가 이 방법을 제공하지 않으면 리턴값은 ENODEV 이다.
   int (*mmap) (struct file *, struct vm_area_struct *);

   // 이 항목이 NULL 로 되어 있으면 디바이스 open 호출은 언제나 성공적이다.
   int (*open) (struct inode *, struct file *);

   // 연린 디바이스를 닫기 이전에 모든 데이터를 쓰도록 하기 위해서 사용한다.
   int (*flush) (struct file *);

   // 노드를 닫을 때 수행된다.
   int (*release) (struct inode *, struct file *);

   // 데이터 중에서 버퍼에 있는 것은 모두 디바이스에 쓴다. 이 메소드가 지원되지 않으면 fsync 시스템 콜은 -EINVAL 리턴값을 갖는다.
   int (*fsync) (struct file *, struct dentry *, int datasync);

   // 이 동작은 FASYNC 플래그에 변화가 있는 디바이스를 확인하기 위해서 사용한다. 드라이버가 비동기 통지를 지원하지 않을 경우에 이 필드를 NULL로 두면 된다.
   int (*fasync) (int, struct file *, int);

   // 파일에 락을 걸기 위해서 사용한다.
   int (*lock) (struct file *, int, struct file_lock *);

   ssize_t (*readv) (struct file *, const struct iovec *, unsigned long, loff_t *);

   ssize_t (*writev) (struct file *, const struct iovec *, unsigned long, loff_t *);

   ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int);

   unsigned long (*get_unmapped_area) (struct file *, unsigned long,
unsigned long, unsigned long, unsigned long, unsigned long);
}

참조 : http://blog.naver.com/sglinux2418?Redirect=Log&logNo=20185596