/*1* Copyright (C) 1991, 1992 Linus Torvalds2* Copyright (C) 1994, Karl Keyte: Added support for disk statistics3* Elevator latency, (C) 2000 Andrea Arcangeli <[email protected]> SuSE4* Queue request tables / lock, selectable elevator, Jens Axboe <[email protected]>5* kernel-doc documentation started by NeilBrown <[email protected]>6* - July20007* bio rewrite, highmem i/o, etc, Jens Axboe <[email protected]> - may 20018*/910/*11* This handles all read/write requests to block devices12*/13#include <linux/kernel.h>14#include <linux/module.h>15#include <linux/backing-dev.h>16#include <linux/bio.h>17#include <linux/blkdev.h>18#include <linux/highmem.h>19#include <linux/mm.h>20#include <linux/kernel_stat.h>21#include <linux/string.h>22#include <linux/init.h>23#include <linux/completion.h>24#include <linux/slab.h>25#include <linux/swap.h>26#include <linux/writeback.h>27#include <linux/task_io_accounting_ops.h>28#include <linux/fault-inject.h>29#include <linux/list_sort.h>3031#define CREATE_TRACE_POINTS32#include <trace/events/block.h>3334#include "blk.h"3536EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap);37EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap);38EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);3940static int __make_request(struct request_queue *q, struct bio *bio);4142/*43* For the allocated request tables44*/45static struct kmem_cache *request_cachep;4647/*48* For queue allocation49*/50struct kmem_cache *blk_requestq_cachep;5152/*53* Controlling structure to kblockd54*/55static struct workqueue_struct *kblockd_workqueue;5657static void drive_stat_acct(struct request *rq, int new_io)58{59struct hd_struct *part;60int rw = rq_data_dir(rq);61int cpu;6263if (!blk_do_io_stat(rq))64return;6566cpu = part_stat_lock();6768if (!new_io) {69part = rq->part;70part_stat_inc(cpu, part, merges[rw]);71} else {72part = disk_map_sector_rcu(rq->rq_disk, blk_rq_pos(rq));73if (!hd_struct_try_get(part)) {74/*75* The partition is already being removed,76* the request will be accounted on the disk only77*78* We take a reference on disk->part0 although that79* partition will never be deleted, so we can treat80* it as any other partition.81*/82part = &rq->rq_disk->part0;83hd_struct_get(part);84}85part_round_stats(cpu, part);86part_inc_in_flight(part, rw);87rq->part = part;88}8990part_stat_unlock();91}9293void blk_queue_congestion_threshold(struct request_queue *q)94{95int nr;9697nr = q->nr_requests - (q->nr_requests / 8) + 1;98if (nr > q->nr_requests)99nr = q->nr_requests;100q->nr_congestion_on = nr;101102nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;103if (nr < 1)104nr = 1;105q->nr_congestion_off = nr;106}107108/**109* blk_get_backing_dev_info - get the address of a queue's backing_dev_info110* @bdev: device111*112* Locates the passed device's request queue and returns the address of its113* backing_dev_info114*115* Will return NULL if the request queue cannot be located.116*/117struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev)118{119struct backing_dev_info *ret = NULL;120struct request_queue *q = bdev_get_queue(bdev);121122if (q)123ret = &q->backing_dev_info;124return ret;125}126EXPORT_SYMBOL(blk_get_backing_dev_info);127128void blk_rq_init(struct request_queue *q, struct request *rq)129{130memset(rq, 0, sizeof(*rq));131132INIT_LIST_HEAD(&rq->queuelist);133INIT_LIST_HEAD(&rq->timeout_list);134rq->cpu = -1;135rq->q = q;136rq->__sector = (sector_t) -1;137INIT_HLIST_NODE(&rq->hash);138RB_CLEAR_NODE(&rq->rb_node);139rq->cmd = rq->__cmd;140rq->cmd_len = BLK_MAX_CDB;141rq->tag = -1;142rq->ref_count = 1;143rq->start_time = jiffies;144set_start_time_ns(rq);145rq->part = NULL;146}147EXPORT_SYMBOL(blk_rq_init);148149static void req_bio_endio(struct request *rq, struct bio *bio,150unsigned int nbytes, int error)151{152if (error)153clear_bit(BIO_UPTODATE, &bio->bi_flags);154else if (!test_bit(BIO_UPTODATE, &bio->bi_flags))155error = -EIO;156157if (unlikely(nbytes > bio->bi_size)) {158printk(KERN_ERR "%s: want %u bytes done, %u left\n",159__func__, nbytes, bio->bi_size);160nbytes = bio->bi_size;161}162163if (unlikely(rq->cmd_flags & REQ_QUIET))164set_bit(BIO_QUIET, &bio->bi_flags);165166bio->bi_size -= nbytes;167bio->bi_sector += (nbytes >> 9);168169if (bio_integrity(bio))170bio_integrity_advance(bio, nbytes);171172/* don't actually finish bio if it's part of flush sequence */173if (bio->bi_size == 0 && !(rq->cmd_flags & REQ_FLUSH_SEQ))174bio_endio(bio, error);175}176177void blk_dump_rq_flags(struct request *rq, char *msg)178{179int bit;180181printk(KERN_INFO "%s: dev %s: type=%x, flags=%x\n", msg,182rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->cmd_type,183rq->cmd_flags);184185printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",186(unsigned long long)blk_rq_pos(rq),187blk_rq_sectors(rq), blk_rq_cur_sectors(rq));188printk(KERN_INFO " bio %p, biotail %p, buffer %p, len %u\n",189rq->bio, rq->biotail, rq->buffer, blk_rq_bytes(rq));190191if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {192printk(KERN_INFO " cdb: ");193for (bit = 0; bit < BLK_MAX_CDB; bit++)194printk("%02x ", rq->cmd[bit]);195printk("\n");196}197}198EXPORT_SYMBOL(blk_dump_rq_flags);199200static void blk_delay_work(struct work_struct *work)201{202struct request_queue *q;203204q = container_of(work, struct request_queue, delay_work.work);205spin_lock_irq(q->queue_lock);206__blk_run_queue(q);207spin_unlock_irq(q->queue_lock);208}209210/**211* blk_delay_queue - restart queueing after defined interval212* @q: The &struct request_queue in question213* @msecs: Delay in msecs214*215* Description:216* Sometimes queueing needs to be postponed for a little while, to allow217* resources to come back. This function will make sure that queueing is218* restarted around the specified time.219*/220void blk_delay_queue(struct request_queue *q, unsigned long msecs)221{222queue_delayed_work(kblockd_workqueue, &q->delay_work,223msecs_to_jiffies(msecs));224}225EXPORT_SYMBOL(blk_delay_queue);226227/**228* blk_start_queue - restart a previously stopped queue229* @q: The &struct request_queue in question230*231* Description:232* blk_start_queue() will clear the stop flag on the queue, and call233* the request_fn for the queue if it was in a stopped state when234* entered. Also see blk_stop_queue(). Queue lock must be held.235**/236void blk_start_queue(struct request_queue *q)237{238WARN_ON(!irqs_disabled());239240queue_flag_clear(QUEUE_FLAG_STOPPED, q);241__blk_run_queue(q);242}243EXPORT_SYMBOL(blk_start_queue);244245/**246* blk_stop_queue - stop a queue247* @q: The &struct request_queue in question248*249* Description:250* The Linux block layer assumes that a block driver will consume all251* entries on the request queue when the request_fn strategy is called.252* Often this will not happen, because of hardware limitations (queue253* depth settings). If a device driver gets a 'queue full' response,254* or if it simply chooses not to queue more I/O at one point, it can255* call this function to prevent the request_fn from being called until256* the driver has signalled it's ready to go again. This happens by calling257* blk_start_queue() to restart queue operations. Queue lock must be held.258**/259void blk_stop_queue(struct request_queue *q)260{261__cancel_delayed_work(&q->delay_work);262queue_flag_set(QUEUE_FLAG_STOPPED, q);263}264EXPORT_SYMBOL(blk_stop_queue);265266/**267* blk_sync_queue - cancel any pending callbacks on a queue268* @q: the queue269*270* Description:271* The block layer may perform asynchronous callback activity272* on a queue, such as calling the unplug function after a timeout.273* A block device may call blk_sync_queue to ensure that any274* such activity is cancelled, thus allowing it to release resources275* that the callbacks might use. The caller must already have made sure276* that its ->make_request_fn will not re-add plugging prior to calling277* this function.278*279* This function does not cancel any asynchronous activity arising280* out of elevator or throttling code. That would require elevaotor_exit()281* and blk_throtl_exit() to be called with queue lock initialized.282*283*/284void blk_sync_queue(struct request_queue *q)285{286del_timer_sync(&q->timeout);287cancel_delayed_work_sync(&q->delay_work);288}289EXPORT_SYMBOL(blk_sync_queue);290291/**292* __blk_run_queue - run a single device queue293* @q: The queue to run294*295* Description:296* See @blk_run_queue. This variant must be called with the queue lock297* held and interrupts disabled.298*/299void __blk_run_queue(struct request_queue *q)300{301if (unlikely(blk_queue_stopped(q)))302return;303304q->request_fn(q);305}306EXPORT_SYMBOL(__blk_run_queue);307308/**309* blk_run_queue_async - run a single device queue in workqueue context310* @q: The queue to run311*312* Description:313* Tells kblockd to perform the equivalent of @blk_run_queue on behalf314* of us.315*/316void blk_run_queue_async(struct request_queue *q)317{318if (likely(!blk_queue_stopped(q))) {319__cancel_delayed_work(&q->delay_work);320queue_delayed_work(kblockd_workqueue, &q->delay_work, 0);321}322}323EXPORT_SYMBOL(blk_run_queue_async);324325/**326* blk_run_queue - run a single device queue327* @q: The queue to run328*329* Description:330* Invoke request handling on this queue, if it has pending work to do.331* May be used to restart queueing when a request has completed.332*/333void blk_run_queue(struct request_queue *q)334{335unsigned long flags;336337spin_lock_irqsave(q->queue_lock, flags);338__blk_run_queue(q);339spin_unlock_irqrestore(q->queue_lock, flags);340}341EXPORT_SYMBOL(blk_run_queue);342343void blk_put_queue(struct request_queue *q)344{345kobject_put(&q->kobj);346}347EXPORT_SYMBOL(blk_put_queue);348349/*350* Note: If a driver supplied the queue lock, it should not zap that lock351* unexpectedly as some queue cleanup components like elevator_exit() and352* blk_throtl_exit() need queue lock.353*/354void blk_cleanup_queue(struct request_queue *q)355{356/*357* We know we have process context here, so we can be a little358* cautious and ensure that pending block actions on this device359* are done before moving on. Going into this function, we should360* not have processes doing IO to this device.361*/362blk_sync_queue(q);363364del_timer_sync(&q->backing_dev_info.laptop_mode_wb_timer);365mutex_lock(&q->sysfs_lock);366queue_flag_set_unlocked(QUEUE_FLAG_DEAD, q);367mutex_unlock(&q->sysfs_lock);368369if (q->elevator)370elevator_exit(q->elevator);371372blk_throtl_exit(q);373374blk_put_queue(q);375}376EXPORT_SYMBOL(blk_cleanup_queue);377378static int blk_init_free_list(struct request_queue *q)379{380struct request_list *rl = &q->rq;381382if (unlikely(rl->rq_pool))383return 0;384385rl->count[BLK_RW_SYNC] = rl->count[BLK_RW_ASYNC] = 0;386rl->starved[BLK_RW_SYNC] = rl->starved[BLK_RW_ASYNC] = 0;387rl->elvpriv = 0;388init_waitqueue_head(&rl->wait[BLK_RW_SYNC]);389init_waitqueue_head(&rl->wait[BLK_RW_ASYNC]);390391rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, mempool_alloc_slab,392mempool_free_slab, request_cachep, q->node);393394if (!rl->rq_pool)395return -ENOMEM;396397return 0;398}399400struct request_queue *blk_alloc_queue(gfp_t gfp_mask)401{402return blk_alloc_queue_node(gfp_mask, -1);403}404EXPORT_SYMBOL(blk_alloc_queue);405406struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)407{408struct request_queue *q;409int err;410411q = kmem_cache_alloc_node(blk_requestq_cachep,412gfp_mask | __GFP_ZERO, node_id);413if (!q)414return NULL;415416q->backing_dev_info.ra_pages =417(VM_MAX_READAHEAD * 1024) / PAGE_CACHE_SIZE;418q->backing_dev_info.state = 0;419q->backing_dev_info.capabilities = BDI_CAP_MAP_COPY;420q->backing_dev_info.name = "block";421422err = bdi_init(&q->backing_dev_info);423if (err) {424kmem_cache_free(blk_requestq_cachep, q);425return NULL;426}427428if (blk_throtl_init(q)) {429kmem_cache_free(blk_requestq_cachep, q);430return NULL;431}432433setup_timer(&q->backing_dev_info.laptop_mode_wb_timer,434laptop_mode_timer_fn, (unsigned long) q);435setup_timer(&q->timeout, blk_rq_timed_out_timer, (unsigned long) q);436INIT_LIST_HEAD(&q->timeout_list);437INIT_LIST_HEAD(&q->flush_queue[0]);438INIT_LIST_HEAD(&q->flush_queue[1]);439INIT_LIST_HEAD(&q->flush_data_in_flight);440INIT_DELAYED_WORK(&q->delay_work, blk_delay_work);441442kobject_init(&q->kobj, &blk_queue_ktype);443444mutex_init(&q->sysfs_lock);445spin_lock_init(&q->__queue_lock);446447/*448* By default initialize queue_lock to internal lock and driver can449* override it later if need be.450*/451q->queue_lock = &q->__queue_lock;452453return q;454}455EXPORT_SYMBOL(blk_alloc_queue_node);456457/**458* blk_init_queue - prepare a request queue for use with a block device459* @rfn: The function to be called to process requests that have been460* placed on the queue.461* @lock: Request queue spin lock462*463* Description:464* If a block device wishes to use the standard request handling procedures,465* which sorts requests and coalesces adjacent requests, then it must466* call blk_init_queue(). The function @rfn will be called when there467* are requests on the queue that need to be processed. If the device468* supports plugging, then @rfn may not be called immediately when requests469* are available on the queue, but may be called at some time later instead.470* Plugged queues are generally unplugged when a buffer belonging to one471* of the requests on the queue is needed, or due to memory pressure.472*473* @rfn is not required, or even expected, to remove all requests off the474* queue, but only as many as it can handle at a time. If it does leave475* requests on the queue, it is responsible for arranging that the requests476* get dealt with eventually.477*478* The queue spin lock must be held while manipulating the requests on the479* request queue; this lock will be taken also from interrupt context, so irq480* disabling is needed for it.481*482* Function returns a pointer to the initialized request queue, or %NULL if483* it didn't succeed.484*485* Note:486* blk_init_queue() must be paired with a blk_cleanup_queue() call487* when the block device is deactivated (such as at module unload).488**/489490struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)491{492return blk_init_queue_node(rfn, lock, -1);493}494EXPORT_SYMBOL(blk_init_queue);495496struct request_queue *497blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)498{499struct request_queue *uninit_q, *q;500501uninit_q = blk_alloc_queue_node(GFP_KERNEL, node_id);502if (!uninit_q)503return NULL;504505q = blk_init_allocated_queue_node(uninit_q, rfn, lock, node_id);506if (!q)507blk_cleanup_queue(uninit_q);508509return q;510}511EXPORT_SYMBOL(blk_init_queue_node);512513struct request_queue *514blk_init_allocated_queue(struct request_queue *q, request_fn_proc *rfn,515spinlock_t *lock)516{517return blk_init_allocated_queue_node(q, rfn, lock, -1);518}519EXPORT_SYMBOL(blk_init_allocated_queue);520521struct request_queue *522blk_init_allocated_queue_node(struct request_queue *q, request_fn_proc *rfn,523spinlock_t *lock, int node_id)524{525if (!q)526return NULL;527528q->node = node_id;529if (blk_init_free_list(q))530return NULL;531532q->request_fn = rfn;533q->prep_rq_fn = NULL;534q->unprep_rq_fn = NULL;535q->queue_flags = QUEUE_FLAG_DEFAULT;536537/* Override internal queue lock with supplied lock pointer */538if (lock)539q->queue_lock = lock;540541/*542* This also sets hw/phys segments, boundary and size543*/544blk_queue_make_request(q, __make_request);545546q->sg_reserved_size = INT_MAX;547548/*549* all done550*/551if (!elevator_init(q, NULL)) {552blk_queue_congestion_threshold(q);553return q;554}555556return NULL;557}558EXPORT_SYMBOL(blk_init_allocated_queue_node);559560int blk_get_queue(struct request_queue *q)561{562if (likely(!test_bit(QUEUE_FLAG_DEAD, &q->queue_flags))) {563kobject_get(&q->kobj);564return 0;565}566567return 1;568}569EXPORT_SYMBOL(blk_get_queue);570571static inline void blk_free_request(struct request_queue *q, struct request *rq)572{573if (rq->cmd_flags & REQ_ELVPRIV)574elv_put_request(q, rq);575mempool_free(rq, q->rq.rq_pool);576}577578static struct request *579blk_alloc_request(struct request_queue *q, int flags, int priv, gfp_t gfp_mask)580{581struct request *rq = mempool_alloc(q->rq.rq_pool, gfp_mask);582583if (!rq)584return NULL;585586blk_rq_init(q, rq);587588rq->cmd_flags = flags | REQ_ALLOCED;589590if (priv) {591if (unlikely(elv_set_request(q, rq, gfp_mask))) {592mempool_free(rq, q->rq.rq_pool);593return NULL;594}595rq->cmd_flags |= REQ_ELVPRIV;596}597598return rq;599}600601/*602* ioc_batching returns true if the ioc is a valid batching request and603* should be given priority access to a request.604*/605static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)606{607if (!ioc)608return 0;609610/*611* Make sure the process is able to allocate at least 1 request612* even if the batch times out, otherwise we could theoretically613* lose wakeups.614*/615return ioc->nr_batch_requests == q->nr_batching ||616(ioc->nr_batch_requests > 0617&& time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));618}619620/*621* ioc_set_batching sets ioc to be a new "batcher" if it is not one. This622* will cause the process to be a "batcher" on all queues in the system. This623* is the behaviour we want though - once it gets a wakeup it should be given624* a nice run.625*/626static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)627{628if (!ioc || ioc_batching(q, ioc))629return;630631ioc->nr_batch_requests = q->nr_batching;632ioc->last_waited = jiffies;633}634635static void __freed_request(struct request_queue *q, int sync)636{637struct request_list *rl = &q->rq;638639if (rl->count[sync] < queue_congestion_off_threshold(q))640blk_clear_queue_congested(q, sync);641642if (rl->count[sync] + 1 <= q->nr_requests) {643if (waitqueue_active(&rl->wait[sync]))644wake_up(&rl->wait[sync]);645646blk_clear_queue_full(q, sync);647}648}649650/*651* A request has just been released. Account for it, update the full and652* congestion status, wake up any waiters. Called under q->queue_lock.653*/654static void freed_request(struct request_queue *q, int sync, int priv)655{656struct request_list *rl = &q->rq;657658rl->count[sync]--;659if (priv)660rl->elvpriv--;661662__freed_request(q, sync);663664if (unlikely(rl->starved[sync ^ 1]))665__freed_request(q, sync ^ 1);666}667668/*669* Determine if elevator data should be initialized when allocating the670* request associated with @bio.671*/672static bool blk_rq_should_init_elevator(struct bio *bio)673{674if (!bio)675return true;676677/*678* Flush requests do not use the elevator so skip initialization.679* This allows a request to share the flush and elevator data.680*/681if (bio->bi_rw & (REQ_FLUSH | REQ_FUA))682return false;683684return true;685}686687/*688* Get a free request, queue_lock must be held.689* Returns NULL on failure, with queue_lock held.690* Returns !NULL on success, with queue_lock *not held*.691*/692static struct request *get_request(struct request_queue *q, int rw_flags,693struct bio *bio, gfp_t gfp_mask)694{695struct request *rq = NULL;696struct request_list *rl = &q->rq;697struct io_context *ioc = NULL;698const bool is_sync = rw_is_sync(rw_flags) != 0;699int may_queue, priv = 0;700701may_queue = elv_may_queue(q, rw_flags);702if (may_queue == ELV_MQUEUE_NO)703goto rq_starved;704705if (rl->count[is_sync]+1 >= queue_congestion_on_threshold(q)) {706if (rl->count[is_sync]+1 >= q->nr_requests) {707ioc = current_io_context(GFP_ATOMIC, q->node);708/*709* The queue will fill after this allocation, so set710* it as full, and mark this process as "batching".711* This process will be allowed to complete a batch of712* requests, others will be blocked.713*/714if (!blk_queue_full(q, is_sync)) {715ioc_set_batching(q, ioc);716blk_set_queue_full(q, is_sync);717} else {718if (may_queue != ELV_MQUEUE_MUST719&& !ioc_batching(q, ioc)) {720/*721* The queue is full and the allocating722* process is not a "batcher", and not723* exempted by the IO scheduler724*/725goto out;726}727}728}729blk_set_queue_congested(q, is_sync);730}731732/*733* Only allow batching queuers to allocate up to 50% over the defined734* limit of requests, otherwise we could have thousands of requests735* allocated with any setting of ->nr_requests736*/737if (rl->count[is_sync] >= (3 * q->nr_requests / 2))738goto out;739740rl->count[is_sync]++;741rl->starved[is_sync] = 0;742743if (blk_rq_should_init_elevator(bio)) {744priv = !test_bit(QUEUE_FLAG_ELVSWITCH, &q->queue_flags);745if (priv)746rl->elvpriv++;747}748749if (blk_queue_io_stat(q))750rw_flags |= REQ_IO_STAT;751spin_unlock_irq(q->queue_lock);752753rq = blk_alloc_request(q, rw_flags, priv, gfp_mask);754if (unlikely(!rq)) {755/*756* Allocation failed presumably due to memory. Undo anything757* we might have messed up.758*759* Allocating task should really be put onto the front of the760* wait queue, but this is pretty rare.761*/762spin_lock_irq(q->queue_lock);763freed_request(q, is_sync, priv);764765/*766* in the very unlikely event that allocation failed and no767* requests for this direction was pending, mark us starved768* so that freeing of a request in the other direction will769* notice us. another possible fix would be to split the770* rq mempool into READ and WRITE771*/772rq_starved:773if (unlikely(rl->count[is_sync] == 0))774rl->starved[is_sync] = 1;775776goto out;777}778779/*780* ioc may be NULL here, and ioc_batching will be false. That's781* OK, if the queue is under the request limit then requests need782* not count toward the nr_batch_requests limit. There will always783* be some limit enforced by BLK_BATCH_TIME.784*/785if (ioc_batching(q, ioc))786ioc->nr_batch_requests--;787788trace_block_getrq(q, bio, rw_flags & 1);789out:790return rq;791}792793/*794* No available requests for this queue, wait for some requests to become795* available.796*797* Called with q->queue_lock held, and returns with it unlocked.798*/799static struct request *get_request_wait(struct request_queue *q, int rw_flags,800struct bio *bio)801{802const bool is_sync = rw_is_sync(rw_flags) != 0;803struct request *rq;804805rq = get_request(q, rw_flags, bio, GFP_NOIO);806while (!rq) {807DEFINE_WAIT(wait);808struct io_context *ioc;809struct request_list *rl = &q->rq;810811prepare_to_wait_exclusive(&rl->wait[is_sync], &wait,812TASK_UNINTERRUPTIBLE);813814trace_block_sleeprq(q, bio, rw_flags & 1);815816spin_unlock_irq(q->queue_lock);817io_schedule();818819/*820* After sleeping, we become a "batching" process and821* will be able to allocate at least one request, and822* up to a big batch of them for a small period time.823* See ioc_batching, ioc_set_batching824*/825ioc = current_io_context(GFP_NOIO, q->node);826ioc_set_batching(q, ioc);827828spin_lock_irq(q->queue_lock);829finish_wait(&rl->wait[is_sync], &wait);830831rq = get_request(q, rw_flags, bio, GFP_NOIO);832};833834return rq;835}836837struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)838{839struct request *rq;840841BUG_ON(rw != READ && rw != WRITE);842843spin_lock_irq(q->queue_lock);844if (gfp_mask & __GFP_WAIT) {845rq = get_request_wait(q, rw, NULL);846} else {847rq = get_request(q, rw, NULL, gfp_mask);848if (!rq)849spin_unlock_irq(q->queue_lock);850}851/* q->queue_lock is unlocked at this point */852853return rq;854}855EXPORT_SYMBOL(blk_get_request);856857/**858* blk_make_request - given a bio, allocate a corresponding struct request.859* @q: target request queue860* @bio: The bio describing the memory mappings that will be submitted for IO.861* It may be a chained-bio properly constructed by block/bio layer.862* @gfp_mask: gfp flags to be used for memory allocation863*864* blk_make_request is the parallel of generic_make_request for BLOCK_PC865* type commands. Where the struct request needs to be farther initialized by866* the caller. It is passed a &struct bio, which describes the memory info of867* the I/O transfer.868*869* The caller of blk_make_request must make sure that bi_io_vec870* are set to describe the memory buffers. That bio_data_dir() will return871* the needed direction of the request. (And all bio's in the passed bio-chain872* are properly set accordingly)873*874* If called under none-sleepable conditions, mapped bio buffers must not875* need bouncing, by calling the appropriate masked or flagged allocator,876* suitable for the target device. Otherwise the call to blk_queue_bounce will877* BUG.878*879* WARNING: When allocating/cloning a bio-chain, careful consideration should be880* given to how you allocate bios. In particular, you cannot use __GFP_WAIT for881* anything but the first bio in the chain. Otherwise you risk waiting for IO882* completion of a bio that hasn't been submitted yet, thus resulting in a883* deadlock. Alternatively bios should be allocated using bio_kmalloc() instead884* of bio_alloc(), as that avoids the mempool deadlock.885* If possible a big IO should be split into smaller parts when allocation886* fails. Partial allocation should not be an error, or you risk a live-lock.887*/888struct request *blk_make_request(struct request_queue *q, struct bio *bio,889gfp_t gfp_mask)890{891struct request *rq = blk_get_request(q, bio_data_dir(bio), gfp_mask);892893if (unlikely(!rq))894return ERR_PTR(-ENOMEM);895896for_each_bio(bio) {897struct bio *bounce_bio = bio;898int ret;899900blk_queue_bounce(q, &bounce_bio);901ret = blk_rq_append_bio(q, rq, bounce_bio);902if (unlikely(ret)) {903blk_put_request(rq);904return ERR_PTR(ret);905}906}907908return rq;909}910EXPORT_SYMBOL(blk_make_request);911912/**913* blk_requeue_request - put a request back on queue914* @q: request queue where request should be inserted915* @rq: request to be inserted916*917* Description:918* Drivers often keep queueing requests until the hardware cannot accept919* more, when that condition happens we need to put the request back920* on the queue. Must be called with queue lock held.921*/922void blk_requeue_request(struct request_queue *q, struct request *rq)923{924blk_delete_timer(rq);925blk_clear_rq_complete(rq);926trace_block_rq_requeue(q, rq);927928if (blk_rq_tagged(rq))929blk_queue_end_tag(q, rq);930931BUG_ON(blk_queued_rq(rq));932933elv_requeue_request(q, rq);934}935EXPORT_SYMBOL(blk_requeue_request);936937static void add_acct_request(struct request_queue *q, struct request *rq,938int where)939{940drive_stat_acct(rq, 1);941__elv_add_request(q, rq, where);942}943944/**945* blk_insert_request - insert a special request into a request queue946* @q: request queue where request should be inserted947* @rq: request to be inserted948* @at_head: insert request at head or tail of queue949* @data: private data950*951* Description:952* Many block devices need to execute commands asynchronously, so they don't953* block the whole kernel from preemption during request execution. This is954* accomplished normally by inserting aritficial requests tagged as955* REQ_TYPE_SPECIAL in to the corresponding request queue, and letting them956* be scheduled for actual execution by the request queue.957*958* We have the option of inserting the head or the tail of the queue.959* Typically we use the tail for new ioctls and so forth. We use the head960* of the queue for things like a QUEUE_FULL message from a device, or a961* host that is unable to accept a particular command.962*/963void blk_insert_request(struct request_queue *q, struct request *rq,964int at_head, void *data)965{966int where = at_head ? ELEVATOR_INSERT_FRONT : ELEVATOR_INSERT_BACK;967unsigned long flags;968969/*970* tell I/O scheduler that this isn't a regular read/write (ie it971* must not attempt merges on this) and that it acts as a soft972* barrier973*/974rq->cmd_type = REQ_TYPE_SPECIAL;975976rq->special = data;977978spin_lock_irqsave(q->queue_lock, flags);979980/*981* If command is tagged, release the tag982*/983if (blk_rq_tagged(rq))984blk_queue_end_tag(q, rq);985986add_acct_request(q, rq, where);987__blk_run_queue(q);988spin_unlock_irqrestore(q->queue_lock, flags);989}990EXPORT_SYMBOL(blk_insert_request);991992static void part_round_stats_single(int cpu, struct hd_struct *part,993unsigned long now)994{995if (now == part->stamp)996return;997998if (part_in_flight(part)) {999__part_stat_add(cpu, part, time_in_queue,1000part_in_flight(part) * (now - part->stamp));1001__part_stat_add(cpu, part, io_ticks, (now - part->stamp));1002}1003part->stamp = now;1004}10051006/**1007* part_round_stats() - Round off the performance stats on a struct disk_stats.1008* @cpu: cpu number for stats access1009* @part: target partition1010*1011* The average IO queue length and utilisation statistics are maintained1012* by observing the current state of the queue length and the amount of1013* time it has been in this state for.1014*1015* Normally, that accounting is done on IO completion, but that can result1016* in more than a second's worth of IO being accounted for within any one1017* second, leading to >100% utilisation. To deal with that, we call this1018* function to do a round-off before returning the results when reading1019* /proc/diskstats. This accounts immediately for all queue usage up to1020* the current jiffies and restarts the counters again.1021*/1022void part_round_stats(int cpu, struct hd_struct *part)1023{1024unsigned long now = jiffies;10251026if (part->partno)1027part_round_stats_single(cpu, &part_to_disk(part)->part0, now);1028part_round_stats_single(cpu, part, now);1029}1030EXPORT_SYMBOL_GPL(part_round_stats);10311032/*1033* queue lock must be held1034*/1035void __blk_put_request(struct request_queue *q, struct request *req)1036{1037if (unlikely(!q))1038return;1039if (unlikely(--req->ref_count))1040return;10411042elv_completed_request(q, req);10431044/* this is a bio leak */1045WARN_ON(req->bio != NULL);10461047/*1048* Request may not have originated from ll_rw_blk. if not,1049* it didn't come out of our reserved rq pools1050*/1051if (req->cmd_flags & REQ_ALLOCED) {1052int is_sync = rq_is_sync(req) != 0;1053int priv = req->cmd_flags & REQ_ELVPRIV;10541055BUG_ON(!list_empty(&req->queuelist));1056BUG_ON(!hlist_unhashed(&req->hash));10571058blk_free_request(q, req);1059freed_request(q, is_sync, priv);1060}1061}1062EXPORT_SYMBOL_GPL(__blk_put_request);10631064void blk_put_request(struct request *req)1065{1066unsigned long flags;1067struct request_queue *q = req->q;10681069spin_lock_irqsave(q->queue_lock, flags);1070__blk_put_request(q, req);1071spin_unlock_irqrestore(q->queue_lock, flags);1072}1073EXPORT_SYMBOL(blk_put_request);10741075/**1076* blk_add_request_payload - add a payload to a request1077* @rq: request to update1078* @page: page backing the payload1079* @len: length of the payload.1080*1081* This allows to later add a payload to an already submitted request by1082* a block driver. The driver needs to take care of freeing the payload1083* itself.1084*1085* Note that this is a quite horrible hack and nothing but handling of1086* discard requests should ever use it.1087*/1088void blk_add_request_payload(struct request *rq, struct page *page,1089unsigned int len)1090{1091struct bio *bio = rq->bio;10921093bio->bi_io_vec->bv_page = page;1094bio->bi_io_vec->bv_offset = 0;1095bio->bi_io_vec->bv_len = len;10961097bio->bi_size = len;1098bio->bi_vcnt = 1;1099bio->bi_phys_segments = 1;11001101rq->__data_len = rq->resid_len = len;1102rq->nr_phys_segments = 1;1103rq->buffer = bio_data(bio);1104}1105EXPORT_SYMBOL_GPL(blk_add_request_payload);11061107static bool bio_attempt_back_merge(struct request_queue *q, struct request *req,1108struct bio *bio)1109{1110const int ff = bio->bi_rw & REQ_FAILFAST_MASK;11111112if (!ll_back_merge_fn(q, req, bio))1113return false;11141115trace_block_bio_backmerge(q, bio);11161117if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)1118blk_rq_set_mixed_merge(req);11191120req->biotail->bi_next = bio;1121req->biotail = bio;1122req->__data_len += bio->bi_size;1123req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));11241125drive_stat_acct(req, 0);1126elv_bio_merged(q, req, bio);1127return true;1128}11291130static bool bio_attempt_front_merge(struct request_queue *q,1131struct request *req, struct bio *bio)1132{1133const int ff = bio->bi_rw & REQ_FAILFAST_MASK;11341135if (!ll_front_merge_fn(q, req, bio))1136return false;11371138trace_block_bio_frontmerge(q, bio);11391140if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)1141blk_rq_set_mixed_merge(req);11421143bio->bi_next = req->bio;1144req->bio = bio;11451146/*1147* may not be valid. if the low level driver said1148* it didn't need a bounce buffer then it better1149* not touch req->buffer either...1150*/1151req->buffer = bio_data(bio);1152req->__sector = bio->bi_sector;1153req->__data_len += bio->bi_size;1154req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));11551156drive_stat_acct(req, 0);1157elv_bio_merged(q, req, bio);1158return true;1159}11601161/*1162* Attempts to merge with the plugged list in the current process. Returns1163* true if merge was successful, otherwise false.1164*/1165static bool attempt_plug_merge(struct task_struct *tsk, struct request_queue *q,1166struct bio *bio)1167{1168struct blk_plug *plug;1169struct request *rq;1170bool ret = false;11711172plug = tsk->plug;1173if (!plug)1174goto out;11751176list_for_each_entry_reverse(rq, &plug->list, queuelist) {1177int el_ret;11781179if (rq->q != q)1180continue;11811182el_ret = elv_try_merge(rq, bio);1183if (el_ret == ELEVATOR_BACK_MERGE) {1184ret = bio_attempt_back_merge(q, rq, bio);1185if (ret)1186break;1187} else if (el_ret == ELEVATOR_FRONT_MERGE) {1188ret = bio_attempt_front_merge(q, rq, bio);1189if (ret)1190break;1191}1192}1193out:1194return ret;1195}11961197void init_request_from_bio(struct request *req, struct bio *bio)1198{1199req->cpu = bio->bi_comp_cpu;1200req->cmd_type = REQ_TYPE_FS;12011202req->cmd_flags |= bio->bi_rw & REQ_COMMON_MASK;1203if (bio->bi_rw & REQ_RAHEAD)1204req->cmd_flags |= REQ_FAILFAST_MASK;12051206req->errors = 0;1207req->__sector = bio->bi_sector;1208req->ioprio = bio_prio(bio);1209blk_rq_bio_prep(req->q, req, bio);1210}12111212static int __make_request(struct request_queue *q, struct bio *bio)1213{1214const bool sync = !!(bio->bi_rw & REQ_SYNC);1215struct blk_plug *plug;1216int el_ret, rw_flags, where = ELEVATOR_INSERT_SORT;1217struct request *req;12181219/*1220* low level driver can indicate that it wants pages above a1221* certain limit bounced to low memory (ie for highmem, or even1222* ISA dma in theory)1223*/1224blk_queue_bounce(q, &bio);12251226if (bio->bi_rw & (REQ_FLUSH | REQ_FUA)) {1227spin_lock_irq(q->queue_lock);1228where = ELEVATOR_INSERT_FLUSH;1229goto get_rq;1230}12311232/*1233* Check if we can merge with the plugged list before grabbing1234* any locks.1235*/1236if (attempt_plug_merge(current, q, bio))1237goto out;12381239spin_lock_irq(q->queue_lock);12401241el_ret = elv_merge(q, &req, bio);1242if (el_ret == ELEVATOR_BACK_MERGE) {1243if (bio_attempt_back_merge(q, req, bio)) {1244if (!attempt_back_merge(q, req))1245elv_merged_request(q, req, el_ret);1246goto out_unlock;1247}1248} else if (el_ret == ELEVATOR_FRONT_MERGE) {1249if (bio_attempt_front_merge(q, req, bio)) {1250if (!attempt_front_merge(q, req))1251elv_merged_request(q, req, el_ret);1252goto out_unlock;1253}1254}12551256get_rq:1257/*1258* This sync check and mask will be re-done in init_request_from_bio(),1259* but we need to set it earlier to expose the sync flag to the1260* rq allocator and io schedulers.1261*/1262rw_flags = bio_data_dir(bio);1263if (sync)1264rw_flags |= REQ_SYNC;12651266/*1267* Grab a free request. This is might sleep but can not fail.1268* Returns with the queue unlocked.1269*/1270req = get_request_wait(q, rw_flags, bio);12711272/*1273* After dropping the lock and possibly sleeping here, our request1274* may now be mergeable after it had proven unmergeable (above).1275* We don't worry about that case for efficiency. It won't happen1276* often, and the elevators are able to handle it.1277*/1278init_request_from_bio(req, bio);12791280if (test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags) ||1281bio_flagged(bio, BIO_CPU_AFFINE)) {1282req->cpu = blk_cpu_to_group(get_cpu());1283put_cpu();1284}12851286plug = current->plug;1287if (plug) {1288/*1289* If this is the first request added after a plug, fire1290* of a plug trace. If others have been added before, check1291* if we have multiple devices in this plug. If so, make a1292* note to sort the list before dispatch.1293*/1294if (list_empty(&plug->list))1295trace_block_plug(q);1296else if (!plug->should_sort) {1297struct request *__rq;12981299__rq = list_entry_rq(plug->list.prev);1300if (__rq->q != q)1301plug->should_sort = 1;1302}1303list_add_tail(&req->queuelist, &plug->list);1304drive_stat_acct(req, 1);1305} else {1306spin_lock_irq(q->queue_lock);1307add_acct_request(q, req, where);1308__blk_run_queue(q);1309out_unlock:1310spin_unlock_irq(q->queue_lock);1311}1312out:1313return 0;1314}13151316/*1317* If bio->bi_dev is a partition, remap the location1318*/1319static inline void blk_partition_remap(struct bio *bio)1320{1321struct block_device *bdev = bio->bi_bdev;13221323if (bio_sectors(bio) && bdev != bdev->bd_contains) {1324struct hd_struct *p = bdev->bd_part;13251326bio->bi_sector += p->start_sect;1327bio->bi_bdev = bdev->bd_contains;13281329trace_block_bio_remap(bdev_get_queue(bio->bi_bdev), bio,1330bdev->bd_dev,1331bio->bi_sector - p->start_sect);1332}1333}13341335static void handle_bad_sector(struct bio *bio)1336{1337char b[BDEVNAME_SIZE];13381339printk(KERN_INFO "attempt to access beyond end of device\n");1340printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",1341bdevname(bio->bi_bdev, b),1342bio->bi_rw,1343(unsigned long long)bio->bi_sector + bio_sectors(bio),1344(long long)(i_size_read(bio->bi_bdev->bd_inode) >> 9));13451346set_bit(BIO_EOF, &bio->bi_flags);1347}13481349#ifdef CONFIG_FAIL_MAKE_REQUEST13501351static DECLARE_FAULT_ATTR(fail_make_request);13521353static int __init setup_fail_make_request(char *str)1354{1355return setup_fault_attr(&fail_make_request, str);1356}1357__setup("fail_make_request=", setup_fail_make_request);13581359static int should_fail_request(struct bio *bio)1360{1361struct hd_struct *part = bio->bi_bdev->bd_part;13621363if (part_to_disk(part)->part0.make_it_fail || part->make_it_fail)1364return should_fail(&fail_make_request, bio->bi_size);13651366return 0;1367}13681369static int __init fail_make_request_debugfs(void)1370{1371return init_fault_attr_dentries(&fail_make_request,1372"fail_make_request");1373}13741375late_initcall(fail_make_request_debugfs);13761377#else /* CONFIG_FAIL_MAKE_REQUEST */13781379static inline int should_fail_request(struct bio *bio)1380{1381return 0;1382}13831384#endif /* CONFIG_FAIL_MAKE_REQUEST */13851386/*1387* Check whether this bio extends beyond the end of the device.1388*/1389static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)1390{1391sector_t maxsector;13921393if (!nr_sectors)1394return 0;13951396/* Test device or partition size, when known. */1397maxsector = i_size_read(bio->bi_bdev->bd_inode) >> 9;1398if (maxsector) {1399sector_t sector = bio->bi_sector;14001401if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {1402/*1403* This may well happen - the kernel calls bread()1404* without checking the size of the device, e.g., when1405* mounting a device.1406*/1407handle_bad_sector(bio);1408return 1;1409}1410}14111412return 0;1413}14141415/**1416* generic_make_request - hand a buffer to its device driver for I/O1417* @bio: The bio describing the location in memory and on the device.1418*1419* generic_make_request() is used to make I/O requests of block1420* devices. It is passed a &struct bio, which describes the I/O that needs1421* to be done.1422*1423* generic_make_request() does not return any status. The1424* success/failure status of the request, along with notification of1425* completion, is delivered asynchronously through the bio->bi_end_io1426* function described (one day) else where.1427*1428* The caller of generic_make_request must make sure that bi_io_vec1429* are set to describe the memory buffer, and that bi_dev and bi_sector are1430* set to describe the device address, and the1431* bi_end_io and optionally bi_private are set to describe how1432* completion notification should be signaled.1433*1434* generic_make_request and the drivers it calls may use bi_next if this1435* bio happens to be merged with someone else, and may change bi_dev and1436* bi_sector for remaps as it sees fit. So the values of these fields1437* should NOT be depended on after the call to generic_make_request.1438*/1439static inline void __generic_make_request(struct bio *bio)1440{1441struct request_queue *q;1442sector_t old_sector;1443int ret, nr_sectors = bio_sectors(bio);1444dev_t old_dev;1445int err = -EIO;14461447might_sleep();14481449if (bio_check_eod(bio, nr_sectors))1450goto end_io;14511452/*1453* Resolve the mapping until finished. (drivers are1454* still free to implement/resolve their own stacking1455* by explicitly returning 0)1456*1457* NOTE: we don't repeat the blk_size check for each new device.1458* Stacking drivers are expected to know what they are doing.1459*/1460old_sector = -1;1461old_dev = 0;1462do {1463char b[BDEVNAME_SIZE];14641465q = bdev_get_queue(bio->bi_bdev);1466if (unlikely(!q)) {1467printk(KERN_ERR1468"generic_make_request: Trying to access "1469"nonexistent block-device %s (%Lu)\n",1470bdevname(bio->bi_bdev, b),1471(long long) bio->bi_sector);1472goto end_io;1473}14741475if (unlikely(!(bio->bi_rw & REQ_DISCARD) &&1476nr_sectors > queue_max_hw_sectors(q))) {1477printk(KERN_ERR "bio too big device %s (%u > %u)\n",1478bdevname(bio->bi_bdev, b),1479bio_sectors(bio),1480queue_max_hw_sectors(q));1481goto end_io;1482}14831484if (unlikely(test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)))1485goto end_io;14861487if (should_fail_request(bio))1488goto end_io;14891490/*1491* If this device has partitions, remap block n1492* of partition p to block n+start(p) of the disk.1493*/1494blk_partition_remap(bio);14951496if (bio_integrity_enabled(bio) && bio_integrity_prep(bio))1497goto end_io;14981499if (old_sector != -1)1500trace_block_bio_remap(q, bio, old_dev, old_sector);15011502old_sector = bio->bi_sector;1503old_dev = bio->bi_bdev->bd_dev;15041505if (bio_check_eod(bio, nr_sectors))1506goto end_io;15071508/*1509* Filter flush bio's early so that make_request based1510* drivers without flush support don't have to worry1511* about them.1512*/1513if ((bio->bi_rw & (REQ_FLUSH | REQ_FUA)) && !q->flush_flags) {1514bio->bi_rw &= ~(REQ_FLUSH | REQ_FUA);1515if (!nr_sectors) {1516err = 0;1517goto end_io;1518}1519}15201521if ((bio->bi_rw & REQ_DISCARD) &&1522(!blk_queue_discard(q) ||1523((bio->bi_rw & REQ_SECURE) &&1524!blk_queue_secdiscard(q)))) {1525err = -EOPNOTSUPP;1526goto end_io;1527}15281529if (blk_throtl_bio(q, &bio))1530goto end_io;15311532/*1533* If bio = NULL, bio has been throttled and will be submitted1534* later.1535*/1536if (!bio)1537break;15381539trace_block_bio_queue(q, bio);15401541ret = q->make_request_fn(q, bio);1542} while (ret);15431544return;15451546end_io:1547bio_endio(bio, err);1548}15491550/*1551* We only want one ->make_request_fn to be active at a time,1552* else stack usage with stacked devices could be a problem.1553* So use current->bio_list to keep a list of requests1554* submited by a make_request_fn function.1555* current->bio_list is also used as a flag to say if1556* generic_make_request is currently active in this task or not.1557* If it is NULL, then no make_request is active. If it is non-NULL,1558* then a make_request is active, and new requests should be added1559* at the tail1560*/1561void generic_make_request(struct bio *bio)1562{1563struct bio_list bio_list_on_stack;15641565if (current->bio_list) {1566/* make_request is active */1567bio_list_add(current->bio_list, bio);1568return;1569}1570/* following loop may be a bit non-obvious, and so deserves some1571* explanation.1572* Before entering the loop, bio->bi_next is NULL (as all callers1573* ensure that) so we have a list with a single bio.1574* We pretend that we have just taken it off a longer list, so1575* we assign bio_list to a pointer to the bio_list_on_stack,1576* thus initialising the bio_list of new bios to be1577* added. __generic_make_request may indeed add some more bios1578* through a recursive call to generic_make_request. If it1579* did, we find a non-NULL value in bio_list and re-enter the loop1580* from the top. In this case we really did just take the bio1581* of the top of the list (no pretending) and so remove it from1582* bio_list, and call into __generic_make_request again.1583*1584* The loop was structured like this to make only one call to1585* __generic_make_request (which is important as it is large and1586* inlined) and to keep the structure simple.1587*/1588BUG_ON(bio->bi_next);1589bio_list_init(&bio_list_on_stack);1590current->bio_list = &bio_list_on_stack;1591do {1592__generic_make_request(bio);1593bio = bio_list_pop(current->bio_list);1594} while (bio);1595current->bio_list = NULL; /* deactivate */1596}1597EXPORT_SYMBOL(generic_make_request);15981599/**1600* submit_bio - submit a bio to the block device layer for I/O1601* @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)1602* @bio: The &struct bio which describes the I/O1603*1604* submit_bio() is very similar in purpose to generic_make_request(), and1605* uses that function to do most of the work. Both are fairly rough1606* interfaces; @bio must be presetup and ready for I/O.1607*1608*/1609void submit_bio(int rw, struct bio *bio)1610{1611int count = bio_sectors(bio);16121613bio->bi_rw |= rw;16141615/*1616* If it's a regular read/write or a barrier with data attached,1617* go through the normal accounting stuff before submission.1618*/1619if (bio_has_data(bio) && !(rw & REQ_DISCARD)) {1620if (rw & WRITE) {1621count_vm_events(PGPGOUT, count);1622} else {1623task_io_account_read(bio->bi_size);1624count_vm_events(PGPGIN, count);1625}16261627if (unlikely(block_dump)) {1628char b[BDEVNAME_SIZE];1629printk(KERN_DEBUG "%s(%d): %s block %Lu on %s (%u sectors)\n",1630current->comm, task_pid_nr(current),1631(rw & WRITE) ? "WRITE" : "READ",1632(unsigned long long)bio->bi_sector,1633bdevname(bio->bi_bdev, b),1634count);1635}1636}16371638generic_make_request(bio);1639}1640EXPORT_SYMBOL(submit_bio);16411642/**1643* blk_rq_check_limits - Helper function to check a request for the queue limit1644* @q: the queue1645* @rq: the request being checked1646*1647* Description:1648* @rq may have been made based on weaker limitations of upper-level queues1649* in request stacking drivers, and it may violate the limitation of @q.1650* Since the block layer and the underlying device driver trust @rq1651* after it is inserted to @q, it should be checked against @q before1652* the insertion using this generic function.1653*1654* This function should also be useful for request stacking drivers1655* in some cases below, so export this function.1656* Request stacking drivers like request-based dm may change the queue1657* limits while requests are in the queue (e.g. dm's table swapping).1658* Such request stacking drivers should check those requests agaist1659* the new queue limits again when they dispatch those requests,1660* although such checkings are also done against the old queue limits1661* when submitting requests.1662*/1663int blk_rq_check_limits(struct request_queue *q, struct request *rq)1664{1665if (rq->cmd_flags & REQ_DISCARD)1666return 0;16671668if (blk_rq_sectors(rq) > queue_max_sectors(q) ||1669blk_rq_bytes(rq) > queue_max_hw_sectors(q) << 9) {1670printk(KERN_ERR "%s: over max size limit.\n", __func__);1671return -EIO;1672}16731674/*1675* queue's settings related to segment counting like q->bounce_pfn1676* may differ from that of other stacking queues.1677* Recalculate it to check the request correctly on this queue's1678* limitation.1679*/1680blk_recalc_rq_segments(rq);1681if (rq->nr_phys_segments > queue_max_segments(q)) {1682printk(KERN_ERR "%s: over max segments limit.\n", __func__);1683return -EIO;1684}16851686return 0;1687}1688EXPORT_SYMBOL_GPL(blk_rq_check_limits);16891690/**1691* blk_insert_cloned_request - Helper for stacking drivers to submit a request1692* @q: the queue to submit the request1693* @rq: the request being queued1694*/1695int blk_insert_cloned_request(struct request_queue *q, struct request *rq)1696{1697unsigned long flags;16981699if (blk_rq_check_limits(q, rq))1700return -EIO;17011702#ifdef CONFIG_FAIL_MAKE_REQUEST1703if (rq->rq_disk && rq->rq_disk->part0.make_it_fail &&1704should_fail(&fail_make_request, blk_rq_bytes(rq)))1705return -EIO;1706#endif17071708spin_lock_irqsave(q->queue_lock, flags);17091710/*1711* Submitting request must be dequeued before calling this function1712* because it will be linked to another request_queue1713*/1714BUG_ON(blk_queued_rq(rq));17151716add_acct_request(q, rq, ELEVATOR_INSERT_BACK);1717spin_unlock_irqrestore(q->queue_lock, flags);17181719return 0;1720}1721EXPORT_SYMBOL_GPL(blk_insert_cloned_request);17221723/**1724* blk_rq_err_bytes - determine number of bytes till the next failure boundary1725* @rq: request to examine1726*1727* Description:1728* A request could be merge of IOs which require different failure1729* handling. This function determines the number of bytes which1730* can be failed from the beginning of the request without1731* crossing into area which need to be retried further.1732*1733* Return:1734* The number of bytes to fail.1735*1736* Context:1737* queue_lock must be held.1738*/1739unsigned int blk_rq_err_bytes(const struct request *rq)1740{1741unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;1742unsigned int bytes = 0;1743struct bio *bio;17441745if (!(rq->cmd_flags & REQ_MIXED_MERGE))1746return blk_rq_bytes(rq);17471748/*1749* Currently the only 'mixing' which can happen is between1750* different fastfail types. We can safely fail portions1751* which have all the failfast bits that the first one has -1752* the ones which are at least as eager to fail as the first1753* one.1754*/1755for (bio = rq->bio; bio; bio = bio->bi_next) {1756if ((bio->bi_rw & ff) != ff)1757break;1758bytes += bio->bi_size;1759}17601761/* this could lead to infinite loop */1762BUG_ON(blk_rq_bytes(rq) && !bytes);1763return bytes;1764}1765EXPORT_SYMBOL_GPL(blk_rq_err_bytes);17661767static void blk_account_io_completion(struct request *req, unsigned int bytes)1768{1769if (blk_do_io_stat(req)) {1770const int rw = rq_data_dir(req);1771struct hd_struct *part;1772int cpu;17731774cpu = part_stat_lock();1775part = req->part;1776part_stat_add(cpu, part, sectors[rw], bytes >> 9);1777part_stat_unlock();1778}1779}17801781static void blk_account_io_done(struct request *req)1782{1783/*1784* Account IO completion. flush_rq isn't accounted as a1785* normal IO on queueing nor completion. Accounting the1786* containing request is enough.1787*/1788if (blk_do_io_stat(req) && !(req->cmd_flags & REQ_FLUSH_SEQ)) {1789unsigned long duration = jiffies - req->start_time;1790const int rw = rq_data_dir(req);1791struct hd_struct *part;1792int cpu;17931794cpu = part_stat_lock();1795part = req->part;17961797part_stat_inc(cpu, part, ios[rw]);1798part_stat_add(cpu, part, ticks[rw], duration);1799part_round_stats(cpu, part);1800part_dec_in_flight(part, rw);18011802hd_struct_put(part);1803part_stat_unlock();1804}1805}18061807/**1808* blk_peek_request - peek at the top of a request queue1809* @q: request queue to peek at1810*1811* Description:1812* Return the request at the top of @q. The returned request1813* should be started using blk_start_request() before LLD starts1814* processing it.1815*1816* Return:1817* Pointer to the request at the top of @q if available. Null1818* otherwise.1819*1820* Context:1821* queue_lock must be held.1822*/1823struct request *blk_peek_request(struct request_queue *q)1824{1825struct request *rq;1826int ret;18271828while ((rq = __elv_next_request(q)) != NULL) {1829if (!(rq->cmd_flags & REQ_STARTED)) {1830/*1831* This is the first time the device driver1832* sees this request (possibly after1833* requeueing). Notify IO scheduler.1834*/1835if (rq->cmd_flags & REQ_SORTED)1836elv_activate_rq(q, rq);18371838/*1839* just mark as started even if we don't start1840* it, a request that has been delayed should1841* not be passed by new incoming requests1842*/1843rq->cmd_flags |= REQ_STARTED;1844trace_block_rq_issue(q, rq);1845}18461847if (!q->boundary_rq || q->boundary_rq == rq) {1848q->end_sector = rq_end_sector(rq);1849q->boundary_rq = NULL;1850}18511852if (rq->cmd_flags & REQ_DONTPREP)1853break;18541855if (q->dma_drain_size && blk_rq_bytes(rq)) {1856/*1857* make sure space for the drain appears we1858* know we can do this because max_hw_segments1859* has been adjusted to be one fewer than the1860* device can handle1861*/1862rq->nr_phys_segments++;1863}18641865if (!q->prep_rq_fn)1866break;18671868ret = q->prep_rq_fn(q, rq);1869if (ret == BLKPREP_OK) {1870break;1871} else if (ret == BLKPREP_DEFER) {1872/*1873* the request may have been (partially) prepped.1874* we need to keep this request in the front to1875* avoid resource deadlock. REQ_STARTED will1876* prevent other fs requests from passing this one.1877*/1878if (q->dma_drain_size && blk_rq_bytes(rq) &&1879!(rq->cmd_flags & REQ_DONTPREP)) {1880/*1881* remove the space for the drain we added1882* so that we don't add it again1883*/1884--rq->nr_phys_segments;1885}18861887rq = NULL;1888break;1889} else if (ret == BLKPREP_KILL) {1890rq->cmd_flags |= REQ_QUIET;1891/*1892* Mark this request as started so we don't trigger1893* any debug logic in the end I/O path.1894*/1895blk_start_request(rq);1896__blk_end_request_all(rq, -EIO);1897} else {1898printk(KERN_ERR "%s: bad return=%d\n", __func__, ret);1899break;1900}1901}19021903return rq;1904}1905EXPORT_SYMBOL(blk_peek_request);19061907void blk_dequeue_request(struct request *rq)1908{1909struct request_queue *q = rq->q;19101911BUG_ON(list_empty(&rq->queuelist));1912BUG_ON(ELV_ON_HASH(rq));19131914list_del_init(&rq->queuelist);19151916/*1917* the time frame between a request being removed from the lists1918* and to it is freed is accounted as io that is in progress at1919* the driver side.1920*/1921if (blk_account_rq(rq)) {1922q->in_flight[rq_is_sync(rq)]++;1923set_io_start_time_ns(rq);1924}1925}19261927/**1928* blk_start_request - start request processing on the driver1929* @req: request to dequeue1930*1931* Description:1932* Dequeue @req and start timeout timer on it. This hands off the1933* request to the driver.1934*1935* Block internal functions which don't want to start timer should1936* call blk_dequeue_request().1937*1938* Context:1939* queue_lock must be held.1940*/1941void blk_start_request(struct request *req)1942{1943blk_dequeue_request(req);19441945/*1946* We are now handing the request to the hardware, initialize1947* resid_len to full count and add the timeout handler.1948*/1949req->resid_len = blk_rq_bytes(req);1950if (unlikely(blk_bidi_rq(req)))1951req->next_rq->resid_len = blk_rq_bytes(req->next_rq);19521953blk_add_timer(req);1954}1955EXPORT_SYMBOL(blk_start_request);19561957/**1958* blk_fetch_request - fetch a request from a request queue1959* @q: request queue to fetch a request from1960*1961* Description:1962* Return the request at the top of @q. The request is started on1963* return and LLD can start processing it immediately.1964*1965* Return:1966* Pointer to the request at the top of @q if available. Null1967* otherwise.1968*1969* Context:1970* queue_lock must be held.1971*/1972struct request *blk_fetch_request(struct request_queue *q)1973{1974struct request *rq;19751976rq = blk_peek_request(q);1977if (rq)1978blk_start_request(rq);1979return rq;1980}1981EXPORT_SYMBOL(blk_fetch_request);19821983/**1984* blk_update_request - Special helper function for request stacking drivers1985* @req: the request being processed1986* @error: %0 for success, < %0 for error1987* @nr_bytes: number of bytes to complete @req1988*1989* Description:1990* Ends I/O on a number of bytes attached to @req, but doesn't complete1991* the request structure even if @req doesn't have leftover.1992* If @req has leftover, sets it up for the next range of segments.1993*1994* This special helper function is only for request stacking drivers1995* (e.g. request-based dm) so that they can handle partial completion.1996* Actual device drivers should use blk_end_request instead.1997*1998* Passing the result of blk_rq_bytes() as @nr_bytes guarantees1999* %false return from this function.2000*2001* Return:2002* %false - this request doesn't have any more data2003* %true - this request has more data2004**/2005bool blk_update_request(struct request *req, int error, unsigned int nr_bytes)2006{2007int total_bytes, bio_nbytes, next_idx = 0;2008struct bio *bio;20092010if (!req->bio)2011return false;20122013trace_block_rq_complete(req->q, req);20142015/*2016* For fs requests, rq is just carrier of independent bio's2017* and each partial completion should be handled separately.2018* Reset per-request error on each partial completion.2019*2020* TODO: tj: This is too subtle. It would be better to let2021* low level drivers do what they see fit.2022*/2023if (req->cmd_type == REQ_TYPE_FS)2024req->errors = 0;20252026if (error && req->cmd_type == REQ_TYPE_FS &&2027!(req->cmd_flags & REQ_QUIET)) {2028char *error_type;20292030switch (error) {2031case -ENOLINK:2032error_type = "recoverable transport";2033break;2034case -EREMOTEIO:2035error_type = "critical target";2036break;2037case -EBADE:2038error_type = "critical nexus";2039break;2040case -EIO:2041default:2042error_type = "I/O";2043break;2044}2045printk(KERN_ERR "end_request: %s error, dev %s, sector %llu\n",2046error_type, req->rq_disk ? req->rq_disk->disk_name : "?",2047(unsigned long long)blk_rq_pos(req));2048}20492050blk_account_io_completion(req, nr_bytes);20512052total_bytes = bio_nbytes = 0;2053while ((bio = req->bio) != NULL) {2054int nbytes;20552056if (nr_bytes >= bio->bi_size) {2057req->bio = bio->bi_next;2058nbytes = bio->bi_size;2059req_bio_endio(req, bio, nbytes, error);2060next_idx = 0;2061bio_nbytes = 0;2062} else {2063int idx = bio->bi_idx + next_idx;20642065if (unlikely(idx >= bio->bi_vcnt)) {2066blk_dump_rq_flags(req, "__end_that");2067printk(KERN_ERR "%s: bio idx %d >= vcnt %d\n",2068__func__, idx, bio->bi_vcnt);2069break;2070}20712072nbytes = bio_iovec_idx(bio, idx)->bv_len;2073BIO_BUG_ON(nbytes > bio->bi_size);20742075/*2076* not a complete bvec done2077*/2078if (unlikely(nbytes > nr_bytes)) {2079bio_nbytes += nr_bytes;2080total_bytes += nr_bytes;2081break;2082}20832084/*2085* advance to the next vector2086*/2087next_idx++;2088bio_nbytes += nbytes;2089}20902091total_bytes += nbytes;2092nr_bytes -= nbytes;20932094bio = req->bio;2095if (bio) {2096/*2097* end more in this run, or just return 'not-done'2098*/2099if (unlikely(nr_bytes <= 0))2100break;2101}2102}21032104/*2105* completely done2106*/2107if (!req->bio) {2108/*2109* Reset counters so that the request stacking driver2110* can find how many bytes remain in the request2111* later.2112*/2113req->__data_len = 0;2114return false;2115}21162117/*2118* if the request wasn't completed, update state2119*/2120if (bio_nbytes) {2121req_bio_endio(req, bio, bio_nbytes, error);2122bio->bi_idx += next_idx;2123bio_iovec(bio)->bv_offset += nr_bytes;2124bio_iovec(bio)->bv_len -= nr_bytes;2125}21262127req->__data_len -= total_bytes;2128req->buffer = bio_data(req->bio);21292130/* update sector only for requests with clear definition of sector */2131if (req->cmd_type == REQ_TYPE_FS || (req->cmd_flags & REQ_DISCARD))2132req->__sector += total_bytes >> 9;21332134/* mixed attributes always follow the first bio */2135if (req->cmd_flags & REQ_MIXED_MERGE) {2136req->cmd_flags &= ~REQ_FAILFAST_MASK;2137req->cmd_flags |= req->bio->bi_rw & REQ_FAILFAST_MASK;2138}21392140/*2141* If total number of sectors is less than the first segment2142* size, something has gone terribly wrong.2143*/2144if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {2145blk_dump_rq_flags(req, "request botched");2146req->__data_len = blk_rq_cur_bytes(req);2147}21482149/* recalculate the number of segments */2150blk_recalc_rq_segments(req);21512152return true;2153}2154EXPORT_SYMBOL_GPL(blk_update_request);21552156static bool blk_update_bidi_request(struct request *rq, int error,2157unsigned int nr_bytes,2158unsigned int bidi_bytes)2159{2160if (blk_update_request(rq, error, nr_bytes))2161return true;21622163/* Bidi request must be completed as a whole */2164if (unlikely(blk_bidi_rq(rq)) &&2165blk_update_request(rq->next_rq, error, bidi_bytes))2166return true;21672168if (blk_queue_add_random(rq->q))2169add_disk_randomness(rq->rq_disk);21702171return false;2172}21732174/**2175* blk_unprep_request - unprepare a request2176* @req: the request2177*2178* This function makes a request ready for complete resubmission (or2179* completion). It happens only after all error handling is complete,2180* so represents the appropriate moment to deallocate any resources2181* that were allocated to the request in the prep_rq_fn. The queue2182* lock is held when calling this.2183*/2184void blk_unprep_request(struct request *req)2185{2186struct request_queue *q = req->q;21872188req->cmd_flags &= ~REQ_DONTPREP;2189if (q->unprep_rq_fn)2190q->unprep_rq_fn(q, req);2191}2192EXPORT_SYMBOL_GPL(blk_unprep_request);21932194/*2195* queue lock must be held2196*/2197static void blk_finish_request(struct request *req, int error)2198{2199if (blk_rq_tagged(req))2200blk_queue_end_tag(req->q, req);22012202BUG_ON(blk_queued_rq(req));22032204if (unlikely(laptop_mode) && req->cmd_type == REQ_TYPE_FS)2205laptop_io_completion(&req->q->backing_dev_info);22062207blk_delete_timer(req);22082209if (req->cmd_flags & REQ_DONTPREP)2210blk_unprep_request(req);221122122213blk_account_io_done(req);22142215if (req->end_io)2216req->end_io(req, error);2217else {2218if (blk_bidi_rq(req))2219__blk_put_request(req->next_rq->q, req->next_rq);22202221__blk_put_request(req->q, req);2222}2223}22242225/**2226* blk_end_bidi_request - Complete a bidi request2227* @rq: the request to complete2228* @error: %0 for success, < %0 for error2229* @nr_bytes: number of bytes to complete @rq2230* @bidi_bytes: number of bytes to complete @rq->next_rq2231*2232* Description:2233* Ends I/O on a number of bytes attached to @rq and @rq->next_rq.2234* Drivers that supports bidi can safely call this member for any2235* type of request, bidi or uni. In the later case @bidi_bytes is2236* just ignored.2237*2238* Return:2239* %false - we are done with this request2240* %true - still buffers pending for this request2241**/2242static bool blk_end_bidi_request(struct request *rq, int error,2243unsigned int nr_bytes, unsigned int bidi_bytes)2244{2245struct request_queue *q = rq->q;2246unsigned long flags;22472248if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))2249return true;22502251spin_lock_irqsave(q->queue_lock, flags);2252blk_finish_request(rq, error);2253spin_unlock_irqrestore(q->queue_lock, flags);22542255return false;2256}22572258/**2259* __blk_end_bidi_request - Complete a bidi request with queue lock held2260* @rq: the request to complete2261* @error: %0 for success, < %0 for error2262* @nr_bytes: number of bytes to complete @rq2263* @bidi_bytes: number of bytes to complete @rq->next_rq2264*2265* Description:2266* Identical to blk_end_bidi_request() except that queue lock is2267* assumed to be locked on entry and remains so on return.2268*2269* Return:2270* %false - we are done with this request2271* %true - still buffers pending for this request2272**/2273static bool __blk_end_bidi_request(struct request *rq, int error,2274unsigned int nr_bytes, unsigned int bidi_bytes)2275{2276if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))2277return true;22782279blk_finish_request(rq, error);22802281return false;2282}22832284/**2285* blk_end_request - Helper function for drivers to complete the request.2286* @rq: the request being processed2287* @error: %0 for success, < %0 for error2288* @nr_bytes: number of bytes to complete2289*2290* Description:2291* Ends I/O on a number of bytes attached to @rq.2292* If @rq has leftover, sets it up for the next range of segments.2293*2294* Return:2295* %false - we are done with this request2296* %true - still buffers pending for this request2297**/2298bool blk_end_request(struct request *rq, int error, unsigned int nr_bytes)2299{2300return blk_end_bidi_request(rq, error, nr_bytes, 0);2301}2302EXPORT_SYMBOL(blk_end_request);23032304/**2305* blk_end_request_all - Helper function for drives to finish the request.2306* @rq: the request to finish2307* @error: %0 for success, < %0 for error2308*2309* Description:2310* Completely finish @rq.2311*/2312void blk_end_request_all(struct request *rq, int error)2313{2314bool pending;2315unsigned int bidi_bytes = 0;23162317if (unlikely(blk_bidi_rq(rq)))2318bidi_bytes = blk_rq_bytes(rq->next_rq);23192320pending = blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);2321BUG_ON(pending);2322}2323EXPORT_SYMBOL(blk_end_request_all);23242325/**2326* blk_end_request_cur - Helper function to finish the current request chunk.2327* @rq: the request to finish the current chunk for2328* @error: %0 for success, < %0 for error2329*2330* Description:2331* Complete the current consecutively mapped chunk from @rq.2332*2333* Return:2334* %false - we are done with this request2335* %true - still buffers pending for this request2336*/2337bool blk_end_request_cur(struct request *rq, int error)2338{2339return blk_end_request(rq, error, blk_rq_cur_bytes(rq));2340}2341EXPORT_SYMBOL(blk_end_request_cur);23422343/**2344* blk_end_request_err - Finish a request till the next failure boundary.2345* @rq: the request to finish till the next failure boundary for2346* @error: must be negative errno2347*2348* Description:2349* Complete @rq till the next failure boundary.2350*2351* Return:2352* %false - we are done with this request2353* %true - still buffers pending for this request2354*/2355bool blk_end_request_err(struct request *rq, int error)2356{2357WARN_ON(error >= 0);2358return blk_end_request(rq, error, blk_rq_err_bytes(rq));2359}2360EXPORT_SYMBOL_GPL(blk_end_request_err);23612362/**2363* __blk_end_request - Helper function for drivers to complete the request.2364* @rq: the request being processed2365* @error: %0 for success, < %0 for error2366* @nr_bytes: number of bytes to complete2367*2368* Description:2369* Must be called with queue lock held unlike blk_end_request().2370*2371* Return:2372* %false - we are done with this request2373* %true - still buffers pending for this request2374**/2375bool __blk_end_request(struct request *rq, int error, unsigned int nr_bytes)2376{2377return __blk_end_bidi_request(rq, error, nr_bytes, 0);2378}2379EXPORT_SYMBOL(__blk_end_request);23802381/**2382* __blk_end_request_all - Helper function for drives to finish the request.2383* @rq: the request to finish2384* @error: %0 for success, < %0 for error2385*2386* Description:2387* Completely finish @rq. Must be called with queue lock held.2388*/2389void __blk_end_request_all(struct request *rq, int error)2390{2391bool pending;2392unsigned int bidi_bytes = 0;23932394if (unlikely(blk_bidi_rq(rq)))2395bidi_bytes = blk_rq_bytes(rq->next_rq);23962397pending = __blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);2398BUG_ON(pending);2399}2400EXPORT_SYMBOL(__blk_end_request_all);24012402/**2403* __blk_end_request_cur - Helper function to finish the current request chunk.2404* @rq: the request to finish the current chunk for2405* @error: %0 for success, < %0 for error2406*2407* Description:2408* Complete the current consecutively mapped chunk from @rq. Must2409* be called with queue lock held.2410*2411* Return:2412* %false - we are done with this request2413* %true - still buffers pending for this request2414*/2415bool __blk_end_request_cur(struct request *rq, int error)2416{2417return __blk_end_request(rq, error, blk_rq_cur_bytes(rq));2418}2419EXPORT_SYMBOL(__blk_end_request_cur);24202421/**2422* __blk_end_request_err - Finish a request till the next failure boundary.2423* @rq: the request to finish till the next failure boundary for2424* @error: must be negative errno2425*2426* Description:2427* Complete @rq till the next failure boundary. Must be called2428* with queue lock held.2429*2430* Return:2431* %false - we are done with this request2432* %true - still buffers pending for this request2433*/2434bool __blk_end_request_err(struct request *rq, int error)2435{2436WARN_ON(error >= 0);2437return __blk_end_request(rq, error, blk_rq_err_bytes(rq));2438}2439EXPORT_SYMBOL_GPL(__blk_end_request_err);24402441void blk_rq_bio_prep(struct request_queue *q, struct request *rq,2442struct bio *bio)2443{2444/* Bit 0 (R/W) is identical in rq->cmd_flags and bio->bi_rw */2445rq->cmd_flags |= bio->bi_rw & REQ_WRITE;24462447if (bio_has_data(bio)) {2448rq->nr_phys_segments = bio_phys_segments(q, bio);2449rq->buffer = bio_data(bio);2450}2451rq->__data_len = bio->bi_size;2452rq->bio = rq->biotail = bio;24532454if (bio->bi_bdev)2455rq->rq_disk = bio->bi_bdev->bd_disk;2456}24572458#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE2459/**2460* rq_flush_dcache_pages - Helper function to flush all pages in a request2461* @rq: the request to be flushed2462*2463* Description:2464* Flush all pages in @rq.2465*/2466void rq_flush_dcache_pages(struct request *rq)2467{2468struct req_iterator iter;2469struct bio_vec *bvec;24702471rq_for_each_segment(bvec, rq, iter)2472flush_dcache_page(bvec->bv_page);2473}2474EXPORT_SYMBOL_GPL(rq_flush_dcache_pages);2475#endif24762477/**2478* blk_lld_busy - Check if underlying low-level drivers of a device are busy2479* @q : the queue of the device being checked2480*2481* Description:2482* Check if underlying low-level drivers of a device are busy.2483* If the drivers want to export their busy state, they must set own2484* exporting function using blk_queue_lld_busy() first.2485*2486* Basically, this function is used only by request stacking drivers2487* to stop dispatching requests to underlying devices when underlying2488* devices are busy. This behavior helps more I/O merging on the queue2489* of the request stacking driver and prevents I/O throughput regression2490* on burst I/O load.2491*2492* Return:2493* 0 - Not busy (The request stacking driver should dispatch request)2494* 1 - Busy (The request stacking driver should stop dispatching request)2495*/2496int blk_lld_busy(struct request_queue *q)2497{2498if (q->lld_busy_fn)2499return q->lld_busy_fn(q);25002501return 0;2502}2503EXPORT_SYMBOL_GPL(blk_lld_busy);25042505/**2506* blk_rq_unprep_clone - Helper function to free all bios in a cloned request2507* @rq: the clone request to be cleaned up2508*2509* Description:2510* Free all bios in @rq for a cloned request.2511*/2512void blk_rq_unprep_clone(struct request *rq)2513{2514struct bio *bio;25152516while ((bio = rq->bio) != NULL) {2517rq->bio = bio->bi_next;25182519bio_put(bio);2520}2521}2522EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);25232524/*2525* Copy attributes of the original request to the clone request.2526* The actual data parts (e.g. ->cmd, ->buffer, ->sense) are not copied.2527*/2528static void __blk_rq_prep_clone(struct request *dst, struct request *src)2529{2530dst->cpu = src->cpu;2531dst->cmd_flags = (src->cmd_flags & REQ_CLONE_MASK) | REQ_NOMERGE;2532dst->cmd_type = src->cmd_type;2533dst->__sector = blk_rq_pos(src);2534dst->__data_len = blk_rq_bytes(src);2535dst->nr_phys_segments = src->nr_phys_segments;2536dst->ioprio = src->ioprio;2537dst->extra_len = src->extra_len;2538}25392540/**2541* blk_rq_prep_clone - Helper function to setup clone request2542* @rq: the request to be setup2543* @rq_src: original request to be cloned2544* @bs: bio_set that bios for clone are allocated from2545* @gfp_mask: memory allocation mask for bio2546* @bio_ctr: setup function to be called for each clone bio.2547* Returns %0 for success, non %0 for failure.2548* @data: private data to be passed to @bio_ctr2549*2550* Description:2551* Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.2552* The actual data parts of @rq_src (e.g. ->cmd, ->buffer, ->sense)2553* are not copied, and copying such parts is the caller's responsibility.2554* Also, pages which the original bios are pointing to are not copied2555* and the cloned bios just point same pages.2556* So cloned bios must be completed before original bios, which means2557* the caller must complete @rq before @rq_src.2558*/2559int blk_rq_prep_clone(struct request *rq, struct request *rq_src,2560struct bio_set *bs, gfp_t gfp_mask,2561int (*bio_ctr)(struct bio *, struct bio *, void *),2562void *data)2563{2564struct bio *bio, *bio_src;25652566if (!bs)2567bs = fs_bio_set;25682569blk_rq_init(NULL, rq);25702571__rq_for_each_bio(bio_src, rq_src) {2572bio = bio_alloc_bioset(gfp_mask, bio_src->bi_max_vecs, bs);2573if (!bio)2574goto free_and_out;25752576__bio_clone(bio, bio_src);25772578if (bio_integrity(bio_src) &&2579bio_integrity_clone(bio, bio_src, gfp_mask, bs))2580goto free_and_out;25812582if (bio_ctr && bio_ctr(bio, bio_src, data))2583goto free_and_out;25842585if (rq->bio) {2586rq->biotail->bi_next = bio;2587rq->biotail = bio;2588} else2589rq->bio = rq->biotail = bio;2590}25912592__blk_rq_prep_clone(rq, rq_src);25932594return 0;25952596free_and_out:2597if (bio)2598bio_free(bio, bs);2599blk_rq_unprep_clone(rq);26002601return -ENOMEM;2602}2603EXPORT_SYMBOL_GPL(blk_rq_prep_clone);26042605int kblockd_schedule_work(struct request_queue *q, struct work_struct *work)2606{2607return queue_work(kblockd_workqueue, work);2608}2609EXPORT_SYMBOL(kblockd_schedule_work);26102611int kblockd_schedule_delayed_work(struct request_queue *q,2612struct delayed_work *dwork, unsigned long delay)2613{2614return queue_delayed_work(kblockd_workqueue, dwork, delay);2615}2616EXPORT_SYMBOL(kblockd_schedule_delayed_work);26172618#define PLUG_MAGIC 0x9182736426192620void blk_start_plug(struct blk_plug *plug)2621{2622struct task_struct *tsk = current;26232624plug->magic = PLUG_MAGIC;2625INIT_LIST_HEAD(&plug->list);2626INIT_LIST_HEAD(&plug->cb_list);2627plug->should_sort = 0;26282629/*2630* If this is a nested plug, don't actually assign it. It will be2631* flushed on its own.2632*/2633if (!tsk->plug) {2634/*2635* Store ordering should not be needed here, since a potential2636* preempt will imply a full memory barrier2637*/2638tsk->plug = plug;2639}2640}2641EXPORT_SYMBOL(blk_start_plug);26422643static int plug_rq_cmp(void *priv, struct list_head *a, struct list_head *b)2644{2645struct request *rqa = container_of(a, struct request, queuelist);2646struct request *rqb = container_of(b, struct request, queuelist);26472648return !(rqa->q <= rqb->q);2649}26502651/*2652* If 'from_schedule' is true, then postpone the dispatch of requests2653* until a safe kblockd context. We due this to avoid accidental big2654* additional stack usage in driver dispatch, in places where the originally2655* plugger did not intend it.2656*/2657static void queue_unplugged(struct request_queue *q, unsigned int depth,2658bool from_schedule)2659__releases(q->queue_lock)2660{2661trace_block_unplug(q, depth, !from_schedule);26622663/*2664* If we are punting this to kblockd, then we can safely drop2665* the queue_lock before waking kblockd (which needs to take2666* this lock).2667*/2668if (from_schedule) {2669spin_unlock(q->queue_lock);2670blk_run_queue_async(q);2671} else {2672__blk_run_queue(q);2673spin_unlock(q->queue_lock);2674}26752676}26772678static void flush_plug_callbacks(struct blk_plug *plug)2679{2680LIST_HEAD(callbacks);26812682if (list_empty(&plug->cb_list))2683return;26842685list_splice_init(&plug->cb_list, &callbacks);26862687while (!list_empty(&callbacks)) {2688struct blk_plug_cb *cb = list_first_entry(&callbacks,2689struct blk_plug_cb,2690list);2691list_del(&cb->list);2692cb->callback(cb);2693}2694}26952696void blk_flush_plug_list(struct blk_plug *plug, bool from_schedule)2697{2698struct request_queue *q;2699unsigned long flags;2700struct request *rq;2701LIST_HEAD(list);2702unsigned int depth;27032704BUG_ON(plug->magic != PLUG_MAGIC);27052706flush_plug_callbacks(plug);2707if (list_empty(&plug->list))2708return;27092710list_splice_init(&plug->list, &list);27112712if (plug->should_sort) {2713list_sort(NULL, &list, plug_rq_cmp);2714plug->should_sort = 0;2715}27162717q = NULL;2718depth = 0;27192720/*2721* Save and disable interrupts here, to avoid doing it for every2722* queue lock we have to take.2723*/2724local_irq_save(flags);2725while (!list_empty(&list)) {2726rq = list_entry_rq(list.next);2727list_del_init(&rq->queuelist);2728BUG_ON(!rq->q);2729if (rq->q != q) {2730/*2731* This drops the queue lock2732*/2733if (q)2734queue_unplugged(q, depth, from_schedule);2735q = rq->q;2736depth = 0;2737spin_lock(q->queue_lock);2738}2739/*2740* rq is already accounted, so use raw insert2741*/2742if (rq->cmd_flags & (REQ_FLUSH | REQ_FUA))2743__elv_add_request(q, rq, ELEVATOR_INSERT_FLUSH);2744else2745__elv_add_request(q, rq, ELEVATOR_INSERT_SORT_MERGE);27462747depth++;2748}27492750/*2751* This drops the queue lock2752*/2753if (q)2754queue_unplugged(q, depth, from_schedule);27552756local_irq_restore(flags);2757}27582759void blk_finish_plug(struct blk_plug *plug)2760{2761blk_flush_plug_list(plug, false);27622763if (plug == current->plug)2764current->plug = NULL;2765}2766EXPORT_SYMBOL(blk_finish_plug);27672768int __init blk_dev_init(void)2769{2770BUILD_BUG_ON(__REQ_NR_BITS > 8 *2771sizeof(((struct request *)0)->cmd_flags));27722773/* used for unplugging and affects IO latency/throughput - HIGHPRI */2774kblockd_workqueue = alloc_workqueue("kblockd",2775WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);2776if (!kblockd_workqueue)2777panic("Failed to create kblockd\n");27782779request_cachep = kmem_cache_create("blkdev_requests",2780sizeof(struct request), 0, SLAB_PANIC, NULL);27812782blk_requestq_cachep = kmem_cache_create("blkdev_queue",2783sizeof(struct request_queue), 0, SLAB_PANIC, NULL);27842785return 0;2786}278727882789