linux-block

1 struct bio 表示一次块设备的IO请求。
2 struct request是bio(elevator)提交给IO调度器后产生的数据,一个request中存放着顺序排列的bio。当设备提交bio 给IO调度器时,新的bio可能被合并到request_queue中已有的request结构中(甚至合并到已有的bio中),或者生成新的request。request表示等待处理的块设备IO请求,结构里有sector等信息;通过queuelist把自己挂在它依附的request_queue上。
3 struct request_queue每个物理设备对应一个,是request所形成的list,其结构中有一些函数指针。

一篇很好的文章

一个很好的blog

一 主要数据结构

1 gendisk

代表一个通用块设备,每个磁盘对应个gendisk结构,包括该disk上的请求队列,分区列表/第一个分区,块设备操作表等重要信息。

[cpp]  view plain  copy
  1. struct gendisk {  
  2.     /* major, first_minor and minors are input parameters only, 
  3.      * don't use directly.  Use disk_devt() and disk_max_parts(). 
  4.      */  
  5.     int major;          /* major number of driver */  
  6.     int first_minor;  
  7.     int minors;                     /* maximum number of minors, =1 for 
  8.                                          * disks that can't be partitioned. */  
  9.   
  10.     char disk_name[DISK_NAME_LEN];  /* name of major driver */  
  11.     char *(*devnode)(struct gendisk *gd, umode_t *mode);  
  12.   
  13.     unsigned int events;        /* supported events */  
  14.     unsigned int async_events;  /* async events, subset of all */  
  15.   
  16.     /* Array of pointers to partitions indexed by partno. 
  17.      * Protected with matching bdev lock but stat and other 
  18.      * non-critical accesses use RCU.  Always access through 
  19.      * helpers. 
  20.      */  
  21.     struct disk_part_tbl __rcu *part_tbl;  
  22.     struct hd_struct part0;  
  23.   
  24.     const struct block_device_operations *fops;  
  25.     struct request_queue *queue;  
  26.     void *private_data;  
  27.   
  28.     int flags;  
  29.     struct device *driverfs_dev;  // FIXME: remove  
  30.     struct kobject *slave_dir;  
  31.   
  32.     struct timer_rand_state *random;  
  33.     atomic_t sync_io;       /* RAID */  
  34.     struct disk_events *ev;  
  35. #ifdef  CONFIG_BLK_DEV_INTEGRITY  
  36.     struct blk_integrity *integrity;  
  37. #endif  
  38.     int node_id;  
  39. };  

major:块设备的主设备号。
first_minor:起始次设备号。
minors:描述了该块设备有多少个次设备号,或者说有多少个分区,如果minors为1,则表示该块设备没有分区。
part_tbl:整个块设备的分区信息都包含在里面,其核心结构是一个struct hd_struct的指针数组,每一项都指向一个描述分区的hd_struct结构。
fops:指向特定于设备的底层操作函数集。
queue:块设备的请求队列,所有针对该设备的请求都会放入该请求队列中,经过I/O scheduler的处理再进行提交。

2 hd_struct

保存一个分区信息,包括起始扇区,扇区数,分区号等基本信息。

[cpp]  view plain  copy
  1. struct hd_struct {  
  2.     sector_t start_sect;  
  3.     /* 
  4.      * nr_sects is protected by sequence counter. One might extend a 
  5.      * partition while IO is happening to it and update of nr_sects 
  6.      * can be non-atomic on 32bit machines with 64bit sector_t. 
  7.      */  
  8.     sector_t nr_sects;  
  9.     seqcount_t nr_sects_seq;  
  10.     sector_t alignment_offset;  
  11.     unsigned int discard_alignment;  
  12.     struct device __dev;  
  13.     struct kobject *holder_dir;  
  14.     int policy, partno;  
  15.     struct partition_meta_info *info;  
  16. #ifdef CONFIG_FAIL_MAKE_REQUEST  
  17.     int make_it_fail;  
  18. #endif  
  19.     unsigned long stamp;  
  20.     atomic_t in_flight[2];  
  21. #ifdef  CONFIG_SMP  
  22.     struct disk_stats __percpu *dkstats;  
  23. #else  
  24.     struct disk_stats dkstats;  
  25. #endif  
  26.     atomic_t ref;  
  27.     struct rcu_head rcu_head;  
  28. };  

3 disk_part_tbl

磁盘的分区表。
[cpp]  view plain  copy
  1. struct disk_part_tbl {  
  2.     struct rcu_head rcu_head;  
  3.     int len;  
  4.     struct hd_struct __rcu *last_lookup;  
  5.     struct hd_struct __rcu *part[];  
  6. };  

4 block_device

可以是整个磁盘,也可以是一个分区。如果是一个分区块设备,则bd_contains会指向分区所在磁盘的block_device,bd_part则指向分区信息结构hd_struct。

[cpp]  view plain  copy
  1. struct block_device {  
  2.     dev_t           bd_dev;  /* not a kdev_t - it's a search key */  
  3.     int         bd_openers;  
  4.     struct inode *      bd_inode;   /* will die */  
  5.     struct super_block *    bd_super;  
  6.     struct mutex        bd_mutex;   /* open/close mutex */  
  7.     struct list_head    bd_inodes;  
  8.     void *          bd_claiming;  
  9.     void *          bd_holder;  
  10.     int         bd_holders;  
  11.     bool            bd_write_holder;  
  12. #ifdef CONFIG_SYSFS  
  13.     struct list_head    bd_holder_disks;  
  14. #endif  
  15.     struct block_device *   bd_contains;  
  16.     unsigned        bd_block_size;  
  17.     struct hd_struct *  bd_part;  
  18.     /* number of times partitions within this device have been opened. */  
  19.     unsigned        bd_part_count;  
  20.     int         bd_invalidated;  
  21.     struct gendisk *    bd_disk;  
  22.     struct request_queue *  bd_queue;  
  23.     struct list_head    bd_list;  
  24.     /* 
  25.      * Private data.  You must have bd_claim'ed the block_device 
  26.      * to use this.  NOTE:  bd_claim allows an owner to claim 
  27.      * the same device multiple times, the owner must take special 
  28.      * care to not mess up bd_private for that case. 
  29.      */  
  30.     unsigned long       bd_private;  
  31.   
  32.     /* The counter of freeze processes */  
  33.     int         bd_fsfreeze_count;  
  34.     /* Mutex for freeze */  
  35.     struct mutex        bd_fsfreeze_mutex;  
  36. };  

bd_dev:该设备(分区)的设备号。
bd_inode:指向该设备文件的inode。
bd_openers:一个引用计数,记录了该块设备打开的次数,或者说有多少个进程打开了该设备。
bd_contains:如果该block_device描述的是一个分区,则该变量指向描述主块设备的block_device,反之,其指向本身。
bd_part:如果该block_device描述的是一个分区,则该变量指向分区的信息。
bd_part_count:如果是分区,该变量记录了分区被打开的次数,在进行分区的重新扫描前,要保证该计数值为0。
bd_disk:指向描述整个设备的gendisk结构。

5 buffer_head

在内核层对块设备的IO请求是以块为单位的。buffer_head是一个块在内存中的元数据信息。b_data指向该块数据的实际地址。b_this_page则将通过page中的块连接起来。以前版本的buffer_head是fs到block device的io请求单元,现在已经改为bio了。
[cpp]  view plain  copy
  1. struct buffer_head {  
  2.     unsigned long b_state;      /* buffer state bitmap (see above) */  
  3.     struct buffer_head *b_this_page;/* circular list of page's buffers */  
  4.     struct page *b_page;        /* the page this bh is mapped to */  
  5.   
  6.     sector_t b_blocknr;     /* start block number */  
  7.     size_t b_size;          /* size of mapping */  
  8.     char *b_data;           /* pointer to data within the page */  
  9.   
  10.     struct block_device *b_bdev;  
  11.     bh_end_io_t *b_end_io;      /* I/O completion */  
  12.     void *b_private;        /* reserved for b_end_io */  
  13.     struct list_head b_assoc_buffers; /* associated with another mapping */  
  14.     struct address_space *b_assoc_map;  /* mapping this buffer is 
  15.                            associated with */  
  16.     atomic_t b_count;       /* users using this buffer_head */  
  17. };  

6 bio

bio封装了一次实际的块设备io请求。这是块设备io请求的基本单位。bi_vcnt表示bio_vec的数目。
[cpp]  view plain  copy
  1. struct bio {  
  2.     sector_t        bi_sector;  /* device address in 512 byte 
  3.                            sectors */  
  4.     struct bio      *bi_next;   /* request queue link */  
  5.     struct block_device *bi_bdev;  
  6.     unsigned long       bi_flags;   /* status, command, etc */  
  7.     unsigned long       bi_rw;      /* bottom bits READ/WRITE, 
  8.                          * top bits priority 
  9.                          */  
  10.   
  11.     unsigned short      bi_vcnt;    /* how many bio_vec's */  
  12.     unsigned short      bi_idx;     /* current index into bvl_vec */  
  13.   
  14.     /* Number of segments in this BIO after 
  15.      * physical address coalescing is performed. 
  16.      */  
  17.     unsigned int        bi_phys_segments;  
  18.   
  19.     unsigned int        bi_size;    /* residual I/O count */  
  20.   
  21.     /* 
  22.      * To keep track of the max segment size, we account for the 
  23.      * sizes of the first and last mergeable segments in this bio. 
  24.      */  
  25.     unsigned int        bi_seg_front_size;  
  26.     unsigned int        bi_seg_back_size;  
  27.   
  28.     bio_end_io_t        *bi_end_io;  
  29.   
  30.     void            *bi_private;  
  31. #ifdef CONFIG_BLK_CGROUP  
  32.     /* 
  33.      * Optional ioc and css associated with this bio.  Put on bio 
  34.      * release.  Read comment on top of bio_associate_current(). 
  35.      */  
  36.     struct io_context   *bi_ioc;  
  37.     struct cgroup_subsys_state *bi_css;  
  38. #endif  
  39. #if defined(CONFIG_BLK_DEV_INTEGRITY)  
  40.     struct bio_integrity_payload *bi_integrity;  /* data integrity */  
  41. #endif  
  42.   
  43.     /* 
  44.      * Everything starting with bi_max_vecs will be preserved by bio_reset() 
  45.      */  
  46.   
  47.     unsigned int        bi_max_vecs;    /* max bvl_vecs we can hold */  
  48.   
  49.     atomic_t        bi_cnt;     /* pin count */  
  50.   
  51.     struct bio_vec      *bi_io_vec; /* the actual vec list */  
  52.   
  53.     struct bio_set      *bi_pool;  
  54.   
  55.     /* 
  56.      * We can inline a number of vecs at the end of the bio, to avoid 
  57.      * double allocations for a small number of bio_vecs. This member 
  58.      * MUST obviously be kept at the very end of the bio. 
  59.      */  
  60.     struct bio_vec      bi_inline_vecs[0];  
  61. };  

bi_sector:该I/O操作的起始扇区号。
bi_rw:指明了读写方向。
bi_vcnt:该I/O操作中涉及到了多少个缓存向量,每个缓存向量由[page,offset,len]来描述。
bi_idx:指示当前的缓存向量。
bi_io_vec:缓存向量数组。

7 bio_vec

bio_vec表示一次bio涉及到的数据片段(segment),由所在内存页地址,长度,偏移地址等定位。一次bio一般包含多个segment。
[cpp]  view plain  copy
  1. struct bio_vec {  
  2.     struct page *bv_page;  
  3.     unsigned int    bv_len;  
  4.     unsigned int    bv_offset;  
  5. };  

8 request

块设备层IO等待请求(pending I/O request)。内核中的bio请求在经过io调度排序后进入块设备层,会尝试合并到已有的request。bio结构中的bi_next将队列中的bio请求串成一个队列。bio/biotail域指向队列的首尾。
[cpp]  view plain  copy
  1. struct request {  
  2.     struct list_head queuelist;  
  3.     struct call_single_data csd;  
  4.   
  5.     struct request_queue *q;  
  6.   
  7.     unsigned int cmd_flags;  
  8.     enum rq_cmd_type_bits cmd_type;  
  9.     unsigned long atomic_flags;  
  10.   
  11.     int cpu;  
  12.   
  13.     /* the following two fields are internal, NEVER access directly */  
  14.     unsigned int __data_len;    /* total data len */  
  15.     sector_t __sector;      /* sector cursor */  
  16.   
  17.     struct bio *bio;  
  18.     struct bio *biotail;  
  19.   
  20.     struct hlist_node hash; /* merge hash */  
  21.     /* 
  22.      * The rb_node is only used inside the io scheduler, requests 
  23.      * are pruned when moved to the dispatch queue. So let the 
  24.      * completion_data share space with the rb_node. 
  25.      */  
  26.     union {  
  27.         struct rb_node rb_node; /* sort/lookup */  
  28.         void *completion_data;  
  29.     };  
  30.   
  31.     /* 
  32.      * Three pointers are available for the IO schedulers, if they need 
  33.      * more they have to dynamically allocate it.  Flush requests are 
  34.      * never put on the IO scheduler. So let the flush fields share 
  35.      * space with the elevator data. 
  36.      */  
  37.     union {  
  38.         struct {  
  39.             struct io_cq        *icq;  
  40.             void            *priv[2];  
  41.         } elv;  
  42.   
  43.         struct {  
  44.             unsigned int        seq;  
  45.             struct list_head    list;  
  46.             rq_end_io_fn        *saved_end_io;  
  47.         } flush;  
  48.     };  
  49.   
  50.     struct gendisk *rq_disk;  
  51.     struct hd_struct *part;  
  52.     unsigned long start_time;  
  53. #ifdef CONFIG_BLK_CGROUP  
  54.     struct request_list *rl;        /* rl this rq is alloced from */  
  55.     unsigned long long start_time_ns;  
  56.     unsigned long long io_start_time_ns;    /* when passed to hardware */  
  57. #endif  
  58.     /* Number of scatter-gather DMA addr+len pairs after 
  59.      * physical address coalescing is performed. 
  60.      */  
  61.     unsigned short nr_phys_segments;  
  62. #if defined(CONFIG_BLK_DEV_INTEGRITY)  
  63.     unsigned short nr_integrity_segments;  
  64. #endif  
  65.   
  66.     unsigned short ioprio;  
  67.   
  68.     int ref_count;  
  69.   
  70.     void *special;      /* opaque pointer available for LLD use */  
  71.     char *buffer;       /* kaddr of the current segment if available */  
  72.   
  73.     int tag;  
  74.     int errors;  
  75.   
  76.     /* 
  77.      * when request is used as a packet command carrier 
  78.      */  
  79.     unsigned char __cmd[BLK_MAX_CDB];  
  80.     unsigned char *cmd;  
  81.     unsigned short cmd_len;  
  82.   
  83.     unsigned int extra_len; /* length of alignment and padding */  
  84.     unsigned int sense_len;  
  85.     unsigned int resid_len; /* residual count */  
  86.     void *sense;  
  87.   
  88.     unsigned long deadline;  
  89.     struct list_head timeout_list;  
  90.     unsigned int timeout;  
  91.     int retries;  
  92.   
  93.     /* 
  94.      * completion callback. 
  95.      */  
  96.     rq_end_io_fn *end_io;  
  97.     void *end_io_data;  
  98.   
  99.     /* for bidi */  
  100.     struct request *next_rq;  
  101. };  

queuelist:用于将request链入请求队列的链表元素。
q:指向所属的请求队列。
__sector:下一个要传输的bio的起始扇区号。
__data_len:request要传输的数据字节数。
bio,biotail:用于维护request中的bio链表。

9 request_queue

request_queue维护块设备层IO请求队列,队列中包含多个request。request_queue同时定义了处理队列的函数接口,不同的设备注册时需要实现这些IO处理接口。
[cpp]  view plain  copy
  1. struct request_queue {  
  2.     /* 
  3.      * Together with queue_head for cacheline sharing 
  4.      */  
  5.     struct list_head    queue_head;  
  6.     struct request      *last_merge;  
  7.     struct elevator_queue   *elevator;  
  8.     int         nr_rqs[2];  /* # allocated [a]sync rqs */  
  9.     int         nr_rqs_elvpriv; /* # allocated rqs w/ elvpriv */  
  10.   
  11.     /* 
  12.      * If blkcg is not used, @q->root_rl serves all requests.  If blkcg 
  13.      * is used, root blkg allocates from @q->root_rl and all other 
  14.      * blkgs from their own blkg->rl.  Which one to use should be 
  15.      * determined using bio_request_list(). 
  16.      */  
  17.     struct request_list root_rl;  
  18.   
  19.     request_fn_proc     *request_fn;  
  20.     make_request_fn     *make_request_fn;  
  21.     prep_rq_fn      *prep_rq_fn;  
  22.     unprep_rq_fn        *unprep_rq_fn;  
  23.     merge_bvec_fn       *merge_bvec_fn;  
  24.     softirq_done_fn     *softirq_done_fn;  
  25.     rq_timed_out_fn     *rq_timed_out_fn;  
  26.     dma_drain_needed_fn *dma_drain_needed;  
  27.     lld_busy_fn     *lld_busy_fn;  
  28.   
  29.     /* 
  30.      * Dispatch queue sorting 
  31.      */  
  32.     sector_t        end_sector;  
  33.     struct request      *boundary_rq;  
  34.   
  35.     /* 
  36.      * Delayed queue handling 
  37.      */  
  38.     struct delayed_work delay_work;  
  39.   
  40.     struct backing_dev_info backing_dev_info;  
  41.   
  42.     /* 
  43.      * The queue owner gets to use this for whatever they like. 
  44.      * ll_rw_blk doesn't touch it. 
  45.      */  
  46.     void            *queuedata;  
  47.   
  48.     /* 
  49.      * various queue flags, see QUEUE_* below 
  50.      */  
  51.     unsigned long       queue_flags;  
  52.   
  53.     /* 
  54.      * ida allocated id for this queue.  Used to index queues from 
  55.      * ioctx. 
  56.      */  
  57.     int         id;  
  58.   
  59.     /* 
  60.      * queue needs bounce pages for pages above this limit 
  61.      */  
  62.     gfp_t           bounce_gfp;  
  63.   
  64.     /* 
  65.      * protects queue structures from reentrancy. ->__queue_lock should 
  66.      * _never_ be used directly, it is queue private. always use 
  67.      * ->queue_lock. 
  68.      */  
  69.     spinlock_t      __queue_lock;  
  70.     spinlock_t      *queue_lock;  
  71.   
  72.     /* 
  73.      * queue kobject 
  74.      */  
  75.     struct kobject kobj;  
  76.   
  77. #ifdef CONFIG_PM_RUNTIME  
  78.     struct device       *dev;  
  79.     int         rpm_status;  
  80.     unsigned int        nr_pending;  
  81. #endif  
  82.   
  83.     /* 
  84.      * queue settings 
  85.      */  
  86.     unsigned long       nr_requests;    /* Max # of requests */  
  87.     unsigned int        nr_congestion_on;  
  88.     unsigned int        nr_congestion_off;  
  89.     unsigned int        nr_batching;  
  90.   
  91.     unsigned int        dma_drain_size;  
  92.     void            *dma_drain_buffer;  
  93.     unsigned int        dma_pad_mask;  
  94.     unsigned int        dma_alignment;  
  95.   
  96.     struct blk_queue_tag    *queue_tags;  
  97.     struct list_head    tag_busy_list;  
  98.   
  99.     unsigned int        nr_sorted;  
  100.     unsigned int        in_flight[2];  
  101.     /* 
  102.      * Number of active block driver functions for which blk_drain_queue() 
  103.      * must wait. Must be incremented around functions that unlock the 
  104.      * queue_lock internally, e.g. scsi_request_fn(). 
  105.      */  
  106.     unsigned int        request_fn_active;  
  107.   
  108.     unsigned int        rq_timeout;  
  109.     struct timer_list   timeout;  
  110.     struct list_head    timeout_list;  
  111.   
  112.     struct list_head    icq_list;  
  113. #ifdef CONFIG_BLK_CGROUP  
  114.     DECLARE_BITMAP      (blkcg_pols, BLKCG_MAX_POLS);  
  115.     struct blkcg_gq     *root_blkg;  
  116.     struct list_head    blkg_list;  
  117. #endif  
  118.   
  119.     struct queue_limits limits;  
  120.   
  121.     /* 
  122.      * sg stuff 
  123.      */  
  124.     unsigned int        sg_timeout;  
  125.     unsigned int        sg_reserved_size;  
  126.     int         node;  
  127. #ifdef CONFIG_BLK_DEV_IO_TRACE  
  128.     struct blk_trace    *blk_trace;  
  129. #endif  
  130.     /* 
  131.      * for flush operations 
  132.      */  
  133.     unsigned int        flush_flags;  
  134.     unsigned int        flush_not_queueable:1;  
  135.     unsigned int        flush_queue_delayed:1;  
  136.     unsigned int        flush_pending_idx:1;  
  137.     unsigned int        flush_running_idx:1;  
  138.     unsigned long       flush_pending_since;  
  139.     struct list_head    flush_queue[2];  
  140.     struct list_head    flush_data_in_flight;  
  141.     struct request      flush_rq;  
  142.   
  143.     struct mutex        sysfs_lock;  
  144.   
  145.     int         bypass_depth;  
  146.   
  147. #if defined(CONFIG_BLK_DEV_BSG)  
  148.     bsg_job_fn      *bsg_job_fn;  
  149.     int         bsg_job_size;  
  150.     struct bsg_class_device bsg_dev;  
  151. #endif  
  152.   
  153. #ifdef CONFIG_BLK_CGROUP  
  154.     struct list_head    all_q_node;  
  155. #endif  
  156. #ifdef CONFIG_BLK_DEV_THROTTLING  
  157.     /* Throttle data */  
  158.     struct throtl_data *td;  
  159. #endif  
  160.     struct rcu_head     rcu_head;  
  161. };  

二 主要函数

1 submit_bh

submit_bh是内核发送IO请求给块设备的函数,目前较新版本的内核中该函数会调用submit_bio执行实际请求。
[cpp]  view plain  copy
  1. int submit_bh(int rw, struct buffer_head *bh)  
  2. {  
  3.     return _submit_bh(rw, bh, 0);  
  4. }  
  5. int _submit_bh(int rw, struct buffer_head *bh, unsigned long bio_flags)  
  6. {  
  7.     struct bio *bio;  
  8.     int ret = 0;  
  9.   
  10.     BUG_ON(!buffer_locked(bh));  
  11.     BUG_ON(!buffer_mapped(bh));  
  12.     BUG_ON(!bh->b_end_io);  
  13.     BUG_ON(buffer_delay(bh));  
  14.     BUG_ON(buffer_unwritten(bh));  
  15.   
  16.     /* 
  17.      * Only clear out a write error when rewriting 
  18.      */  
  19.     if (test_set_buffer_req(bh) && (rw & WRITE))  
  20.         clear_buffer_write_io_error(bh);  
  21.   
  22.     /* 
  23.      * from here on down, it's all bio -- do the initial mapping, 
  24.      * submit_bio -> generic_make_request may further map this bio around 
  25.      */  
  26.     bio = bio_alloc(GFP_NOIO, 1);  
  27.   
  28.     bio->bi_sector = bh->b_blocknr * (bh->b_size >> 9);  
  29.     bio->bi_bdev = bh->b_bdev;  
  30.     bio->bi_io_vec[0].bv_page = bh->b_page;  
  31.     bio->bi_io_vec[0].bv_len = bh->b_size;  
  32.     bio->bi_io_vec[0].bv_offset = bh_offset(bh);  
  33.   
  34.     bio->bi_vcnt = 1;  
  35.     bio->bi_size = bh->b_size;  
  36.   
  37.     bio->bi_end_io = end_bio_bh_io_sync;  
  38.     bio->bi_private = bh;  
  39.     bio->bi_flags |= bio_flags;  
  40.   
  41.     /* Take care of bh's that straddle the end of the device */  
  42.     guard_bh_eod(rw, bio, bh);  
  43.   
  44.     if (buffer_meta(bh))  
  45.         rw |= REQ_META;  
  46.     if (buffer_prio(bh))  
  47.         rw |= REQ_PRIO;  
  48.   
  49.     bio_get(bio);  
  50.     submit_bio(rw, bio);  
  51.   
  52.     if (bio_flagged(bio, BIO_EOPNOTSUPP))  
  53.         ret = -EOPNOTSUPP;  
  54.   
  55.     bio_put(bio);  
  56.     return ret;  
  57. }  

2 submit_bio

submit_bio函数会调用generic_make_request执行实际的bio请求。
[cpp]  view plain  copy
  1. void submit_bio(int rw, struct bio *bio)  
  2. {  
  3.     bio->bi_rw |= rw;  
  4.   
  5.     /* 
  6.      * If it's a regular read/write or a barrier with data attached, 
  7.      * go through the normal accounting stuff before submission. 
  8.      */  
  9.     if (bio_has_data(bio)) {  
  10.         unsigned int count;  
  11.   
  12.         if (unlikely(rw & REQ_WRITE_SAME))  
  13.             count = bdev_logical_block_size(bio->bi_bdev) >> 9;  
  14.         else  
  15.             count = bio_sectors(bio);  
  16.   
  17.         if (rw & WRITE) {  
  18.             count_vm_events(PGPGOUT, count);  
  19.         } else {  
  20.             task_io_account_read(bio->bi_size);  
  21.             count_vm_events(PGPGIN, count);  
  22.         }  
  23.   
  24.         if (unlikely(block_dump)) {  
  25.             char b[BDEVNAME_SIZE];  
  26.             printk(KERN_DEBUG "%s(%d): %s block %Lu on %s (%u sectors)\n",  
  27.             current->comm, task_pid_nr(current),  
  28.                 (rw & WRITE) ? "WRITE" : "READ",  
  29.                 (unsigned long long)bio->bi_sector,  
  30.                 bdevname(bio->bi_bdev, b),  
  31.                 count);  
  32.         }  
  33.     }  
  34.   
  35.     generic_make_request(bio);  
  36. }  
3 generic_make_request
generic_make_request则循环处理bio链表。最终调用request_queue中的make_request_fn处理函数处理实际的IO请求。
[cpp]  view plain  copy
  1. void generic_make_request(struct bio *bio)  
  2. {  
  3.     struct bio_list bio_list_on_stack;  
  4.   
  5.     if (!generic_make_request_checks(bio))  
  6.         return;  
  7.   
  8.     /* 
  9.      * We only want one ->make_request_fn to be active at a time, else 
  10.      * stack usage with stacked devices could be a problem.  So use 
  11.      * current->bio_list to keep a list of requests submited by a 
  12.      * make_request_fn function.  current->bio_list is also used as a 
  13.      * flag to say if generic_make_request is currently active in this 
  14.      * task or not.  If it is NULL, then no make_request is active.  If 
  15.      * it is non-NULL, then a make_request is active, and new requests 
  16.      * should be added at the tail 
  17.      */  
  18.     if (current->bio_list) {  
  19.         bio_list_add(current->bio_list, bio);  
  20.         return;  
  21.     }  
  22.   
  23.     /* following loop may be a bit non-obvious, and so deserves some 
  24.      * explanation. 
  25.      * Before entering the loop, bio->bi_next is NULL (as all callers 
  26.      * ensure that) so we have a list with a single bio. 
  27.      * We pretend that we have just taken it off a longer list, so 
  28.      * we assign bio_list to a pointer to the bio_list_on_stack, 
  29.      * thus initialising the bio_list of new bios to be 
  30.      * added.  ->make_request() may indeed add some more bios 
  31.      * through a recursive call to generic_make_request.  If it 
  32.      * did, we find a non-NULL value in bio_list and re-enter the loop 
  33.      * from the top.  In this case we really did just take the bio 
  34.      * of the top of the list (no pretending) and so remove it from 
  35.      * bio_list, and call into ->make_request() again. 
  36.      */  
  37.     BUG_ON(bio->bi_next);  
  38.     bio_list_init(&bio_list_on_stack);  
  39.     current->bio_list = &bio_list_on_stack;  
  40.     do {  
  41.         struct request_queue *q = bdev_get_queue(bio->bi_bdev);  
  42.   
  43.         q->make_request_fn(q, bio);  
  44.   
  45.         bio = bio_list_pop(current->bio_list);  
  46.     } while (bio);  
  47.     current->bio_list = NULL; /* deactivate */  
  48. }  

4 make_request_fn

make_request_fn是于具体block设备相关的函数,mmc子系统初始化为blk_queue_bio。mmc_blk_probe()->mmc_blk_alloc()->mmc_blk_alloc_req()->mmc_init_queue()->blk_init_queue()->blk_init_queue_node()->blk_init_allocated_queue()->blk_queue_make_request(q, blk_queue_bio)。这里就用到了IO调度算法,新的bio可能被合并到request_queue中已有的request结构中(甚至合并到已有的bio中),或者生成新的request,经过这里就bio就变成了request。

[cpp]  view plain  copy
  1. void blk_queue_bio(struct request_queue *q, struct bio *bio)  
  2. {  
  3.     const bool sync = !!(bio->bi_rw & REQ_SYNC);  
  4.     struct blk_plug *plug;  
  5.     int el_ret, rw_flags, where = ELEVATOR_INSERT_SORT;  
  6.     struct request *req;  
  7.     unsigned int request_count = 0;  
  8.   
  9.     /* 
  10.      * low level driver can indicate that it wants pages above a 
  11.      * certain limit bounced to low memory (ie for highmem, or even 
  12.      * ISA dma in theory) 
  13.      */  
  14.     blk_queue_bounce(q, &bio);  
  15.   
  16.     if (bio_integrity_enabled(bio) && bio_integrity_prep(bio)) {  
  17.         bio_endio(bio, -EIO);  
  18.         return;  
  19.     }  
  20.   
  21.     if (bio->bi_rw & (REQ_FLUSH | REQ_FUA)) {  
  22.         spin_lock_irq(q->queue_lock);  
  23.         where = ELEVATOR_INSERT_FLUSH;  
  24.         goto get_rq;  
  25.     }  
  26.   
  27.     /* 
  28.      * Check if we can merge with the plugged list before grabbing 
  29.      * any locks. 
  30.      */  
  31.     if (attempt_plug_merge(q, bio, &request_count))  
  32.         return;  
  33.   
  34.     spin_lock_irq(q->queue_lock);  
  35.   
  36.     el_ret = elv_merge(q, &req, bio);  
  37.     if (el_ret == ELEVATOR_BACK_MERGE) {  
  38.         if (bio_attempt_back_merge(q, req, bio)) {  
  39.             elv_bio_merged(q, req, bio);  
  40.             if (!attempt_back_merge(q, req))  
  41.                 elv_merged_request(q, req, el_ret);  
  42.             goto out_unlock;  
  43.         }  
  44.     } else if (el_ret == ELEVATOR_FRONT_MERGE) {  
  45.         if (bio_attempt_front_merge(q, req, bio)) {  
  46.             elv_bio_merged(q, req, bio);  
  47.             if (!attempt_front_merge(q, req))  
  48.                 elv_merged_request(q, req, el_ret);  
  49.             goto out_unlock;  
  50.         }  
  51.     }  
  52.   
  53. get_rq:  
  54.     /* 
  55.      * This sync check and mask will be re-done in init_request_from_bio(), 
  56.      * but we need to set it earlier to expose the sync flag to the 
  57.      * rq allocator and io schedulers. 
  58.      */  
  59.     rw_flags = bio_data_dir(bio);  
  60.     if (sync)  
  61.         rw_flags |= REQ_SYNC;  
  62.   
  63.     /* 
  64.      * Grab a free request. This is might sleep but can not fail. 
  65.      * Returns with the queue unlocked. 
  66.      */  
  67.     req = get_request(q, rw_flags, bio, GFP_NOIO);  
  68.     if (unlikely(!req)) {  
  69.         bio_endio(bio, -ENODEV);    /* @q is dead */  
  70.         goto out_unlock;  
  71.     }  
  72.   
  73.     /* 
  74.      * After dropping the lock and possibly sleeping here, our request 
  75.      * may now be mergeable after it had proven unmergeable (above). 
  76.      * We don't worry about that case for efficiency. It won't happen 
  77.      * often, and the elevators are able to handle it. 
  78.      */  
  79.     init_request_from_bio(req, bio);  
  80.   
  81.     if (test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags))  
  82.         req->cpu = raw_smp_processor_id();  
  83.   
  84.     plug = current->plug;  
  85.     if (plug) {  
  86.         /* 
  87.          * If this is the first request added after a plug, fire 
  88.          * of a plug trace. If others have been added before, check 
  89.          * if we have multiple devices in this plug. If so, make a 
  90.          * note to sort the list before dispatch. 
  91.          */  
  92.         if (list_empty(&plug->list))  
  93.             trace_block_plug(q);  
  94.         else {  
  95.             if (request_count >= BLK_MAX_REQUEST_COUNT) {  
  96.                 blk_flush_plug_list(plug, false);  
  97.                 trace_block_plug(q);  
  98.             }  
  99.         }  
  100.         list_add_tail(&req->queuelist, &plug->list);  
  101.         drive_stat_acct(req, 1);  
  102.     } else {  
  103.         spin_lock_irq(q->queue_lock);  
  104.         add_acct_request(q, req, where);  
  105.         __blk_run_queue(q);  
  106. out_unlock:  
  107.         spin_unlock_irq(q->queue_lock);  
  108.     }  
  109. }  

5 blk_init_queue

[cpp]  view plain  copy
  1. struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)  
  2. {  
  3.     return blk_init_queue_node(rfn, lock, NUMA_NO_NODE);  
  4. }  
例如mq->queue = blk_init_queue(mmc_request_fn, lock);
分配和初始化请求队列,q->request_fn = mmc_request_fn和blk_queue_make_request(q, blk_queue_bio)就是在这里初始化的。

三 块设备驱动开发

1 分配主设备号

[cpp]  view plain  copy
  1. int register_blkdev(unsigned int major, const char *name)  
  2. {  
  3.     struct blk_major_name **n, *p;  
  4.     int index, ret = 0;  
  5.   
  6.     mutex_lock(&block_class_lock);  
  7.   
  8.     /* temporary */  
  9.     if (major == 0) {  
  10.         for (index = ARRAY_SIZE(major_names)-1; index > 0; index--) {  
  11.             if (major_names[index] == NULL)  
  12.                 break;  
  13.         }  
  14.   
  15.         if (index == 0) {  
  16.             printk("register_blkdev: failed to get major for %s\n",  
  17.                    name);  
  18.             ret = -EBUSY;  
  19.             goto out;  
  20.         }  
  21.         major = index;  
  22.         ret = major;  
  23.     }  
  24.   
  25.     p = kmalloc(sizeof(struct blk_major_name), GFP_KERNEL);  
  26.     if (p == NULL) {  
  27.         ret = -ENOMEM;  
  28.         goto out;  
  29.     }  
  30.   
  31.     p->major = major;  
  32.     strlcpy(p->name, name, sizeof(p->name));  
  33.     p->next = NULL;  
  34.     index = major_to_index(major);  
  35.   
  36.     for (n = &major_names[index]; *n; n = &(*n)->next) {  
  37.         if ((*n)->major == major)  
  38.             break;  
  39.     }  
  40.     if (!*n)  
  41.         *n = p;  
  42.     else  
  43.         ret = -EBUSY;  
  44.   
  45.     if (ret < 0) {  
  46.         printk("register_blkdev: cannot get major %d for %s\n",  
  47.                major, name);  
  48.         kfree(p);  
  49.     }  
  50. out:  
  51.     mutex_unlock(&block_class_lock);  
  52.     return ret;  
  53. }  
例如:res = register_blkdev(MMC_BLOCK_MAJOR, "mmc");
MMC_BLOCK_MAJOR是内核预留给mmc block设备的主设备号;我们自己开发的block设备没有预留的主设备号,通常都把major设置0,这样内核会给我们分配一个没被占用的设备号。怎么找到的呢?其实这个设备号动态生成的规则非常简单,内核维护了一个类型为struct blk_major_name的hash表major_names。
[cpp]  view plain  copy
  1. struct blk_major_name的hash表major_names。  
  2. static struct blk_major_name {  
  3.     struct blk_major_name *next;  
  4.     int major;  
  5.     char name[16];  
  6. } *major_names[BLKDEV_MAJOR_HASH_SIZE];  
动态主设备号生成就是遍历这个hash表,找到一个没被占用的桶,返回对应的索引号,如果都被占用则注册失败,返回错误。

2 创建和初始化gendisk结构

驱动程序在注册了块设备号之后,需要创建灵魂级的数据结构gendisk, 所有后续IO提交需要用到的数据结构比如:request,request_queue,make_request_fn,request_fn等这些东西都是绑在gendisk这个核心数据结构上的,有了它就有了块设备驱动层所需的一切。
[cpp]  view plain  copy
  1. struct gendisk alloc_disk(int minors)  
例如:md->disk = alloc_disk(perdev_minors);该函数负责创建一个gendisk数据结构,并设置分区数minors,并会按照只有一个分区的情况先初始化磁盘分区表指针数组gendisk->part_tbl的hd_struct域,后面会通过rescan_partitions重新扫描磁盘分区进行扩展,都是调用的disk_expand_part_tbl来完成,当前只是按一个分区来设置的。
gendisk数据结构创建好后,可以自行设置major,first_minor,fops,queue等成员,并通过set_capacity来设置驱动支持的最大扇区数。
md->disk->major = MMC_BLOCK_MAJOR;
md->disk->first_minor = devidx * perdev_minors;
md->disk->fops = &mmc_bdops;
md->disk->private_data = md;
md->disk->queue = md->queue.queue;
set_capacity(md->disk, size);这里单独再说下关于queue成员的创建,request_queue的创建主要要初始化它的2个重要的成员函数,分别是make_reuqest_fn/request_fn。
blk_queue_make_request(q, blk_queue_bio);//blk_queue_bio
mq->queue = blk_init_queue(mmc_request_fn, lock);//mmc_request_fn
make_request_fn负责处理来自上层文件系统submit_bio过来的bio请求,并通过IO调度模块将它转换为request插入到调度队列里。request_fn负责从IO请求队列里下发请求到card层,或者是从IO调度队列里将request派发到实际的IO请求队列,具体情况要看IO请求队列是不是空的。这两个重要函数是在创建request_queue的时候指定的,创建reuqest_queue可以通过blk_init_queue完成,通过入参指定reuqest_fn函数,blk_init_queue内部使用blk_queue_make_request初始化make_request_fn为通用块层提供bio处理函数。如果希望自己定义make_reuqest函数,则可以通过blk_alloc_queue来创建request_queue,然后手动设置reuqest_fn并通过blk_queue_make_request来指定make_request_fn。

3 向内核添加磁盘

我们分配和初始化好gendisk结构后,需要通过add_disk把磁盘添加进内核。
[cpp]  view plain  copy
  1. void add_disk(struct gendisk *disk)  
  2. {  
  3.     struct backing_dev_info *bdi;  
  4.     dev_t devt;  
  5.     int retval;  
  6.   
  7.     /* minors == 0 indicates to use ext devt from part0 and should 
  8.      * be accompanied with EXT_DEVT flag.  Make sure all 
  9.      * parameters make sense. 
  10.      */  
  11.     WARN_ON(disk->minors && !(disk->major || disk->first_minor));  
  12.     WARN_ON(!disk->minors && !(disk->flags & GENHD_FL_EXT_DEVT));  
  13.   
  14.     disk->flags |= GENHD_FL_UP;  
  15.   
  16.     retval = blk_alloc_devt(&disk->part0, &devt);  
  17.     if (retval) {  
  18.         WARN_ON(1);  
  19.         return;  
  20.     }  
  21.     disk_to_dev(disk)->devt = devt;  
  22.   
  23.     /* ->major and ->first_minor aren't supposed to be 
  24.      * dereferenced from here on, but set them just in case. 
  25.      */  
  26.     disk->major = MAJOR(devt);  
  27.     disk->first_minor = MINOR(devt);  
  28.   
  29.     disk_alloc_events(disk);  
  30.   
  31.     /* Register BDI before referencing it from bdev */  
  32.     bdi = &disk->queue->backing_dev_info;  
  33.     bdi_register_dev(bdi, disk_devt(disk));  
  34.   
  35.     blk_register_region(disk_devt(disk), disk->minors, NULL,  
  36.                 exact_match, exact_lock, disk);  
  37.     register_disk(disk);  
  38.     blk_register_queue(disk);  
  39.   
  40.     /* 
  41.      * Take an extra ref on queue which will be put on disk_release() 
  42.      * so that it sticks around as long as @disk is there. 
  43.      */  
  44.     WARN_ON_ONCE(!blk_get_queue(disk->queue));  
  45.   
  46.     retval = sysfs_create_link(&disk_to_dev(disk)->kobj, &bdi->dev->kobj,  
  47.                    "bdi");  
  48.     WARN_ON(retval);  
  49.   
  50.     disk_add_events(disk);  
  51. }  
例如:add_disk(md->disk);首先通过blk_alloc_devt为设备的0号分区分配设备号devt,然后调用blk_register_region完成设备号的注册,这一步就是通过设备映射表bdev_map建立设备号与核心数据结构gendisk的一个映射关系,这一步完成设备的注册。然后会通过register_disk设置对应的sysfs结构,并为这个gendisk的分区0关联一个block_device数据结构,后续会重新扫描磁盘分区表建立好磁盘与分区的关系。

四 IO调度

每个块设备或者块设备的分区,都对应有自身的请求队列(request_queue),而每个请求队列都可以选择一个I/O调度器来协调所递交的request。当有多个并发IO请求到块设备时,请求的顺序会影响IO的性能,因为普通的机械硬盘需要移动机械臂,相对于电和磁的传递,机械运动是非常慢速的;所以kernel一般会对IO做排序等调度后再发送到块设备层。I/O调度器的基本目的是将请求按照它们对应在块设备上的扇区号进行排列,以减少磁头的移动,提高效率。在前面讨论递交I/O请求的时候可以发现,每个request_queue都有一个request的队列,队列里的请求将按顺序被响应。实际上,除了这个队列,每个调度器自身都维护有不同数量的队列,用来对递交上来的request进行处理,而排在队列最前面的request将适时被移动到request_queue中等待响应。
IO调度算法是一种电梯算法(elevator algorithm),目前主要有cfq/deadline/anticipatory/noop,其中cfq是Linux的默认策略;anticipatory在新的内核中已经放弃;deadline在大部分OLTP数据库应用中更具优势,IO的响应时间更稳定些;noop只对IO请求进行简单的合并,其他不干涉,类似与先来先服务;在FusionIO等IO性能很好的设备上,noop反而更具优势,所以FusionIO的驱动默认使用了noop。
代码位于block目录,block/elevator.c和include/linux/elevator.h,算法block/deadline-iosched.c。

1 主要数据结构

[cpp]  view plain  copy
  1. struct elevator_type  
  2. {  
  3.     /* managed by elevator core */  
  4.     struct kmem_cache *icq_cache;  
  5.   
  6.     /* fields provided by elevator implementation */  
  7.     struct elevator_ops ops;  
  8.     size_t icq_size;    /* see iocontext.h */  
  9.     size_t icq_align;   /* ditto */  
  10.     struct elv_fs_entry *elevator_attrs;  
  11.     char elevator_name[ELV_NAME_MAX];  
  12.     struct module *elevator_owner;  
  13.   
  14.     /* managed by elevator core */  
  15.     char icq_cache_name[ELV_NAME_MAX + 5];  /* elvname + "_io_cq" */  
  16.     struct list_head list;  
  17. };  
  18. struct elevator_queue  
  19. {  
  20.     struct elevator_type *type;  
  21.     void *elevator_data;  
  22.     struct kobject kobj;  
  23.     struct mutex sysfs_lock;  
  24.     unsigned int registered:1;  
  25.     DECLARE_HASHTABLE(hash, ELV_HASH_BITS);  
  26. };  

elevator_type对应一个调度器类型,elevator_queue对应一个调度器实例,如果内核中只有上述四种类型的调度器,则只有四个elevator_type;但是多个块设备(分区)可拥有多个相应调度器的实例,也就是elevator_queue。两个数据结构中最关键的元素都是struct elevator_ops,该结构定义了一组操作函数,用来描述请求队列的相关算法,实现对请求的处理。

[cpp]  view plain  copy
  1. struct elevator_ops  
  2. {  
  3.     elevator_merge_fn *elevator_merge_fn;  
  4.     elevator_merged_fn *elevator_merged_fn;  
  5.     elevator_merge_req_fn *elevator_merge_req_fn;  
  6.     elevator_allow_merge_fn *elevator_allow_merge_fn;  
  7.     elevator_bio_merged_fn *elevator_bio_merged_fn;  
  8.   
  9.     elevator_dispatch_fn *elevator_dispatch_fn;  
  10.     elevator_add_req_fn *elevator_add_req_fn;  
  11.     elevator_activate_req_fn *elevator_activate_req_fn;  
  12.     elevator_deactivate_req_fn *elevator_deactivate_req_fn;  
  13.   
  14.     elevator_completed_req_fn *elevator_completed_req_fn;  
  15.   
  16.     elevator_request_list_fn *elevator_former_req_fn;  
  17.     elevator_request_list_fn *elevator_latter_req_fn;  
  18.   
  19.     elevator_init_icq_fn *elevator_init_icq_fn; /* see iocontext.h */  
  20.     elevator_exit_icq_fn *elevator_exit_icq_fn; /* ditto */  
  21.   
  22.     elevator_set_req_fn *elevator_set_req_fn;  
  23.     elevator_put_req_fn *elevator_put_req_fn;  
  24.   
  25.     elevator_may_queue_fn *elevator_may_queue_fn;  
  26.   
  27.     elevator_init_fn *elevator_init_fn;  
  28.     elevator_exit_fn *elevator_exit_fn;  
  29. };  
elevator_merge_fn查询一个request,用于将bio并入。
elevator_merge_req_fn将两个合并后的请求中多余的那个给删除。
elevator_dispatch_fn将调度器的队列最前面的元素取出,分派给request_queue中的请求队列以等候响应。
elevator_add_req_fn将一个新的request添加进调度器的队列。
elevator_set_req_fn和elevator_put_req_fn分别在创建新请求和将请求所占的空间释放到内存时调用。
elevator_init_fn用于初始化调度器实例。

2 elevator_init分配IO调度器elevator_queue

例如:
mmc_blk_probe()->mmc_blk_alloc()->mmc_blk_alloc_req()->mmc_init_queue()->blk_init_queue()->blk_init_queue_node()->blk_init_allocated_queue()->elevator_init(q, NULL)

[cpp]  view plain  copy
  1. int elevator_init(struct request_queue *q, char *name)  
  2. {  
  3.     struct elevator_type *e = NULL;  
  4.     int err;  
  5.   
  6.     if (unlikely(q->elevator))  
  7.         return 0;  
  8.   
  9.     INIT_LIST_HEAD(&q->queue_head);  
  10.     q->last_merge = NULL;  
  11.     q->end_sector = 0;  
  12.     q->boundary_rq = NULL;  
  13.   
  14.     if (name) {  
  15.         e = elevator_get(name, true);  
  16.         if (!e)  
  17.             return -EINVAL;  
  18.     }  
  19.   
  20.     /* 
  21.      * Use the default elevator specified by config boot param or 
  22.      * config option.  Don't try to load modules as we could be running 
  23.      * off async and request_module() isn't allowed from async. 
  24.      */  
  25.     if (!e && *chosen_elevator) {  
  26.         e = elevator_get(chosen_elevator, false);  
  27.         if (!e)  
  28.             printk(KERN_ERR "I/O scheduler %s not found\n",  
  29.                             chosen_elevator);  
  30.     }  
  31.   
  32.     if (!e) {  
  33.         e = elevator_get(CONFIG_DEFAULT_IOSCHED, false);  
  34.         if (!e) {  
  35.             printk(KERN_ERR  
  36.                 "Default I/O scheduler not found. " \  
  37.                 "Using noop.\n");  
  38.             e = elevator_get("noop"false);  
  39.         }  
  40.     }  
  41.   
  42.     err = e->ops.elevator_init_fn(q, e);  
  43.     return 0;  
  44. }  
(1) 如果name指定了elevator_type。

用e = elevator_get(name, true);来找一个elevator_type。为什么能找到呢?看一下elevator_get()。

[cpp]  view plain  copy
  1. static struct elevator_type *elevator_get(const char *name, bool try_loading)  
  2. {  
  3.     struct elevator_type *e;  
  4.   
  5.     spin_lock(&elv_list_lock);  
  6.   
  7.     e = elevator_find(name);  
  8.     if (!e && try_loading) {  
  9.         spin_unlock(&elv_list_lock);  
  10.         request_module("%s-iosched", name);  
  11.         spin_lock(&elv_list_lock);  
  12.         e = elevator_find(name);  
  13.     }  
  14.   
  15.     if (e && !try_module_get(e->elevator_owner))  
  16.         e = NULL;  
  17.   
  18.     spin_unlock(&elv_list_lock);  
  19.   
  20.     return e;  
  21. }  
  22. static struct elevator_type *elevator_find(const char *name)  
  23. {  
  24.     struct elevator_type *e;  
  25.   
  26.     list_for_each_entry(e, &elv_list, list) {  
  27.         if (!strcmp(e->elevator_name, name))  
  28.             return e;  
  29.     }  
  30.   
  31.     return NULL;  
  32. }  
是遍历elv_list,找到e->elevator_name和name相同的elevator_type *e。这个elv_list上挂的就是elevator_type *e了,是什么时候挂的?是调度器注册的时候,比如:
deadline_init()->elv_register()->list_add_tail(&e->list, &elv_list)。
(2) name没有指定,用*chosen_elevator指定的elevator_type。
chosen_elevator存的也是elevator_type的name,是什么时候设置的呢?
[cpp]  view plain  copy
  1. static int __init elevator_setup(char *str)  
  2. {  
  3.     /* 
  4.      * Be backwards-compatible with previous kernels, so users 
  5.      * won't get the wrong elevator. 
  6.      */  
  7.     strncpy(chosen_elevator, str, sizeof(chosen_elevator) - 1);  
  8.     return 1;  
  9. }  
  10. __setup("elevator=", elevator_setup);  
include/linux/init.h中有__setup宏的定义,细节见 点击打开链接

__setup宏最终会定义一个obs_kernel_param类型的结构,并放在.init.setup段。

[cpp]  view plain  copy
  1. struct obs_kernel_param {  
  2.     const char *str;  
  3.     int (*setup_func)(char *);  
  4.     int early;  
  5. };  
kernel在处理启动参数时,会与每个结构中的str对比,如果完全相同,就会调用该数据项的函数指针成员setup_func所指向的函数,并将启动参数后面的内容传给该处理函数作为参数。比如__setup("elevator=", elevator_setup);定义之后,.init.setup段就多了这样一个结构:
static const char __setup_str_elevator_setup[] __initconst 
__aligned(1) = "elevator="; 
static struct obs_kernel_param __setup_elevator_setup 
__used __section(.init.setup) 
__attribute__((aligned((sizeof(long))))) 
= { __setup_str_elevator_setup, elevator_setup, 0}
start_kernel()->parse_args()->unknown_bootoption()->obsolete_checksetup()->(p->setup_func(line + n))
kernel处理启动参数时,将启动参数和__setup_start和__setup_end(就是.init.setup段的内容)之间的结构比较,
include/asm-generic/vmlinux.lds.h
[cpp]  view plain  copy
  1. include/asm-generic/vmlinux.lds.h  
  2. #define INIT_SETUP(initsetup_align)                 \  
  3.         . = ALIGN(initsetup_align);             \  
  4.         VMLINUX_SYMBOL(__setup_start) = .;          \  
  5.         *(.init.setup)                      \  
  6.         VMLINUX_SYMBOL(__setup_end) = .;  
找到为”elevator=”的时候,就会执行elevator_setup(“deadline”);“deadline”就是内核启动参数传过来的。
early_param宏和__setup宏差不多,只是early=1。
[cpp]  view plain  copy
  1. #define __setup(str, fn)                    \  
  2.     __setup_param(str, fn, fn, 0)  
  3.   
  4. /* NOTE: fn is as per module_param, not __setup!  Emits warning if fn 
  5.  * returns non-zero. */  
  6. #define early_param(str, fn)                    \  
  7.     __setup_param(str, fn, fn, 1)  
start_kernel()->parse_early_param()->parse_early_options()->parse_args()->do_early_param()->(p->setup_func(val))
do_early_param()中会判断p->early为1才会执行p->setup_func(val)。
(3) 前两个都没有指定,用CONFIG_DEFAULT_IOSCHED默认配置的elevator_type。
(4) 如果走到这里,那就只能用默认的noop调度器了。
(5) err = e->ops.elevator_init_fn(q, e)。
以deadline为例.elevator_init_fn = deadline_init_queue,
[cpp]  view plain  copy
  1. static int deadline_init_queue(struct request_queue *q, struct elevator_type *e)  
  2. {  
  3.     struct deadline_data *dd;  
  4.     struct elevator_queue *eq;  
  5.   
  6.     eq = elevator_alloc(q, e);  
  7.     if (!eq)  
  8.         return -ENOMEM;  
  9.   
  10.     dd = kmalloc_node(sizeof(*dd), GFP_KERNEL | __GFP_ZERO, q->node);  
  11.     if (!dd) {  
  12.         kobject_put(&eq->kobj);  
  13.         return -ENOMEM;  
  14.     }  
  15.     eq->elevator_data = dd;  
  16.   
  17.     INIT_LIST_HEAD(&dd->fifo_list[READ]);  
  18.     INIT_LIST_HEAD(&dd->fifo_list[WRITE]);  
  19.     dd->sort_list[READ] = RB_ROOT;  
  20.     dd->sort_list[WRITE] = RB_ROOT;  
  21.     dd->fifo_expire[READ] = read_expire;  
  22.     dd->fifo_expire[WRITE] = write_expire;  
  23.     dd->writes_starved = writes_starved;  
  24.     dd->front_merges = 1;  
  25.     dd->fifo_batch = fifo_batch;  
  26.   
  27.     spin_lock_irq(q->queue_lock);  
  28.     q->elevator = eq;  
  29.     spin_unlock_irq(q->queue_lock);  
  30.     return 0;  
  31. }  
(a) elevator_alloc()分配和初始化一个调度器的实例elevator_queue,其成员type就是刚找到的elevator_type。
(b) 分配和初始化deadline调度器的私有数据deadline_data。
(c) request_queue(q)、elevator_queue(eq)、deadline_data(dd)之间的关联,
eq->elevator_data = dd;
q->elevator = eq;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值