blk-core.c 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862
  1. /*
  2. * Copyright (C) 1991, 1992 Linus Torvalds
  3. * Copyright (C) 1994, Karl Keyte: Added support for disk statistics
  4. * Elevator latency, (C) 2000 Andrea Arcangeli <andrea@suse.de> SuSE
  5. * Queue request tables / lock, selectable elevator, Jens Axboe <axboe@suse.de>
  6. * kernel-doc documentation started by NeilBrown <neilb@cse.unsw.edu.au>
  7. * - July2000
  8. * bio rewrite, highmem i/o, etc, Jens Axboe <axboe@suse.de> - may 2001
  9. */
  10. /*
  11. * This handles all read/write requests to block devices
  12. */
  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>
  30. #include <linux/delay.h>
  31. #define CREATE_TRACE_POINTS
  32. #include <trace/events/block.h>
  33. #include "blk.h"
  34. EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_remap);
  35. EXPORT_TRACEPOINT_SYMBOL_GPL(block_rq_remap);
  36. EXPORT_TRACEPOINT_SYMBOL_GPL(block_bio_complete);
  37. /*
  38. * For the allocated request tables
  39. */
  40. static struct kmem_cache *request_cachep;
  41. /*
  42. * For queue allocation
  43. */
  44. struct kmem_cache *blk_requestq_cachep;
  45. /*
  46. * Controlling structure to kblockd
  47. */
  48. static struct workqueue_struct *kblockd_workqueue;
  49. static void drive_stat_acct(struct request *rq, int new_io)
  50. {
  51. struct hd_struct *part;
  52. int rw = rq_data_dir(rq);
  53. int cpu;
  54. if (!blk_do_io_stat(rq))
  55. return;
  56. cpu = part_stat_lock();
  57. if (!new_io) {
  58. part = rq->part;
  59. part_stat_inc(cpu, part, merges[rw]);
  60. } else {
  61. part = disk_map_sector_rcu(rq->rq_disk, blk_rq_pos(rq));
  62. if (!hd_struct_try_get(part)) {
  63. /*
  64. * The partition is already being removed,
  65. * the request will be accounted on the disk only
  66. *
  67. * We take a reference on disk->part0 although that
  68. * partition will never be deleted, so we can treat
  69. * it as any other partition.
  70. */
  71. part = &rq->rq_disk->part0;
  72. hd_struct_get(part);
  73. }
  74. part_round_stats(cpu, part);
  75. part_inc_in_flight(part, rw);
  76. rq->part = part;
  77. }
  78. part_stat_unlock();
  79. }
  80. void blk_queue_congestion_threshold(struct request_queue *q)
  81. {
  82. int nr;
  83. nr = q->nr_requests - (q->nr_requests / 8) + 1;
  84. if (nr > q->nr_requests)
  85. nr = q->nr_requests;
  86. q->nr_congestion_on = nr;
  87. nr = q->nr_requests - (q->nr_requests / 8) - (q->nr_requests / 16) - 1;
  88. if (nr < 1)
  89. nr = 1;
  90. q->nr_congestion_off = nr;
  91. }
  92. /**
  93. * blk_get_backing_dev_info - get the address of a queue's backing_dev_info
  94. * @bdev: device
  95. *
  96. * Locates the passed device's request queue and returns the address of its
  97. * backing_dev_info
  98. *
  99. * Will return NULL if the request queue cannot be located.
  100. */
  101. struct backing_dev_info *blk_get_backing_dev_info(struct block_device *bdev)
  102. {
  103. struct backing_dev_info *ret = NULL;
  104. struct request_queue *q = bdev_get_queue(bdev);
  105. if (q)
  106. ret = &q->backing_dev_info;
  107. return ret;
  108. }
  109. EXPORT_SYMBOL(blk_get_backing_dev_info);
  110. void blk_rq_init(struct request_queue *q, struct request *rq)
  111. {
  112. memset(rq, 0, sizeof(*rq));
  113. INIT_LIST_HEAD(&rq->queuelist);
  114. INIT_LIST_HEAD(&rq->timeout_list);
  115. rq->cpu = -1;
  116. rq->q = q;
  117. rq->__sector = (sector_t) -1;
  118. INIT_HLIST_NODE(&rq->hash);
  119. RB_CLEAR_NODE(&rq->rb_node);
  120. rq->cmd = rq->__cmd;
  121. rq->cmd_len = BLK_MAX_CDB;
  122. rq->tag = -1;
  123. rq->ref_count = 1;
  124. rq->start_time = jiffies;
  125. set_start_time_ns(rq);
  126. rq->part = NULL;
  127. }
  128. EXPORT_SYMBOL(blk_rq_init);
  129. static void req_bio_endio(struct request *rq, struct bio *bio,
  130. unsigned int nbytes, int error)
  131. {
  132. if (error)
  133. clear_bit(BIO_UPTODATE, &bio->bi_flags);
  134. else if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
  135. error = -EIO;
  136. if (unlikely(nbytes > bio->bi_size)) {
  137. printk(KERN_ERR "%s: want %u bytes done, %u left\n",
  138. __func__, nbytes, bio->bi_size);
  139. nbytes = bio->bi_size;
  140. }
  141. if (unlikely(rq->cmd_flags & REQ_QUIET))
  142. set_bit(BIO_QUIET, &bio->bi_flags);
  143. bio->bi_size -= nbytes;
  144. bio->bi_sector += (nbytes >> 9);
  145. if (bio_integrity(bio))
  146. bio_integrity_advance(bio, nbytes);
  147. /* don't actually finish bio if it's part of flush sequence */
  148. if (bio->bi_size == 0 && !(rq->cmd_flags & REQ_FLUSH_SEQ))
  149. bio_endio(bio, error);
  150. }
  151. void blk_dump_rq_flags(struct request *rq, char *msg)
  152. {
  153. int bit;
  154. printk(KERN_INFO "%s: dev %s: type=%x, flags=%x\n", msg,
  155. rq->rq_disk ? rq->rq_disk->disk_name : "?", rq->cmd_type,
  156. rq->cmd_flags);
  157. printk(KERN_INFO " sector %llu, nr/cnr %u/%u\n",
  158. (unsigned long long)blk_rq_pos(rq),
  159. blk_rq_sectors(rq), blk_rq_cur_sectors(rq));
  160. printk(KERN_INFO " bio %p, biotail %p, buffer %p, len %u\n",
  161. rq->bio, rq->biotail, rq->buffer, blk_rq_bytes(rq));
  162. if (rq->cmd_type == REQ_TYPE_BLOCK_PC) {
  163. printk(KERN_INFO " cdb: ");
  164. for (bit = 0; bit < BLK_MAX_CDB; bit++)
  165. printk("%02x ", rq->cmd[bit]);
  166. printk("\n");
  167. }
  168. }
  169. EXPORT_SYMBOL(blk_dump_rq_flags);
  170. static void blk_delay_work(struct work_struct *work)
  171. {
  172. struct request_queue *q;
  173. q = container_of(work, struct request_queue, delay_work.work);
  174. spin_lock_irq(q->queue_lock);
  175. __blk_run_queue(q);
  176. spin_unlock_irq(q->queue_lock);
  177. }
  178. /**
  179. * blk_delay_queue - restart queueing after defined interval
  180. * @q: The &struct request_queue in question
  181. * @msecs: Delay in msecs
  182. *
  183. * Description:
  184. * Sometimes queueing needs to be postponed for a little while, to allow
  185. * resources to come back. This function will make sure that queueing is
  186. * restarted around the specified time.
  187. */
  188. void blk_delay_queue(struct request_queue *q, unsigned long msecs)
  189. {
  190. queue_delayed_work(kblockd_workqueue, &q->delay_work,
  191. msecs_to_jiffies(msecs));
  192. }
  193. EXPORT_SYMBOL(blk_delay_queue);
  194. /**
  195. * blk_start_queue - restart a previously stopped queue
  196. * @q: The &struct request_queue in question
  197. *
  198. * Description:
  199. * blk_start_queue() will clear the stop flag on the queue, and call
  200. * the request_fn for the queue if it was in a stopped state when
  201. * entered. Also see blk_stop_queue(). Queue lock must be held.
  202. **/
  203. void blk_start_queue(struct request_queue *q)
  204. {
  205. WARN_ON(!irqs_disabled());
  206. queue_flag_clear(QUEUE_FLAG_STOPPED, q);
  207. __blk_run_queue(q);
  208. }
  209. EXPORT_SYMBOL(blk_start_queue);
  210. /**
  211. * blk_stop_queue - stop a queue
  212. * @q: The &struct request_queue in question
  213. *
  214. * Description:
  215. * The Linux block layer assumes that a block driver will consume all
  216. * entries on the request queue when the request_fn strategy is called.
  217. * Often this will not happen, because of hardware limitations (queue
  218. * depth settings). If a device driver gets a 'queue full' response,
  219. * or if it simply chooses not to queue more I/O at one point, it can
  220. * call this function to prevent the request_fn from being called until
  221. * the driver has signalled it's ready to go again. This happens by calling
  222. * blk_start_queue() to restart queue operations. Queue lock must be held.
  223. **/
  224. void blk_stop_queue(struct request_queue *q)
  225. {
  226. __cancel_delayed_work(&q->delay_work);
  227. queue_flag_set(QUEUE_FLAG_STOPPED, q);
  228. }
  229. EXPORT_SYMBOL(blk_stop_queue);
  230. /**
  231. * blk_sync_queue - cancel any pending callbacks on a queue
  232. * @q: the queue
  233. *
  234. * Description:
  235. * The block layer may perform asynchronous callback activity
  236. * on a queue, such as calling the unplug function after a timeout.
  237. * A block device may call blk_sync_queue to ensure that any
  238. * such activity is cancelled, thus allowing it to release resources
  239. * that the callbacks might use. The caller must already have made sure
  240. * that its ->make_request_fn will not re-add plugging prior to calling
  241. * this function.
  242. *
  243. * This function does not cancel any asynchronous activity arising
  244. * out of elevator or throttling code. That would require elevaotor_exit()
  245. * and blk_throtl_exit() to be called with queue lock initialized.
  246. *
  247. */
  248. void blk_sync_queue(struct request_queue *q)
  249. {
  250. del_timer_sync(&q->timeout);
  251. cancel_delayed_work_sync(&q->delay_work);
  252. }
  253. EXPORT_SYMBOL(blk_sync_queue);
  254. /**
  255. * __blk_run_queue - run a single device queue
  256. * @q: The queue to run
  257. *
  258. * Description:
  259. * See @blk_run_queue. This variant must be called with the queue lock
  260. * held and interrupts disabled.
  261. */
  262. void __blk_run_queue(struct request_queue *q)
  263. {
  264. if (unlikely(blk_queue_stopped(q)))
  265. return;
  266. q->request_fn(q);
  267. }
  268. EXPORT_SYMBOL(__blk_run_queue);
  269. /**
  270. * blk_run_queue_async - run a single device queue in workqueue context
  271. * @q: The queue to run
  272. *
  273. * Description:
  274. * Tells kblockd to perform the equivalent of @blk_run_queue on behalf
  275. * of us.
  276. */
  277. void blk_run_queue_async(struct request_queue *q)
  278. {
  279. if (likely(!blk_queue_stopped(q))) {
  280. __cancel_delayed_work(&q->delay_work);
  281. queue_delayed_work(kblockd_workqueue, &q->delay_work, 0);
  282. }
  283. }
  284. EXPORT_SYMBOL(blk_run_queue_async);
  285. /**
  286. * blk_run_queue - run a single device queue
  287. * @q: The queue to run
  288. *
  289. * Description:
  290. * Invoke request handling on this queue, if it has pending work to do.
  291. * May be used to restart queueing when a request has completed.
  292. */
  293. void blk_run_queue(struct request_queue *q)
  294. {
  295. unsigned long flags;
  296. spin_lock_irqsave(q->queue_lock, flags);
  297. __blk_run_queue(q);
  298. spin_unlock_irqrestore(q->queue_lock, flags);
  299. }
  300. EXPORT_SYMBOL(blk_run_queue);
  301. void blk_put_queue(struct request_queue *q)
  302. {
  303. kobject_put(&q->kobj);
  304. }
  305. EXPORT_SYMBOL(blk_put_queue);
  306. /**
  307. * blk_drain_queue - drain requests from request_queue
  308. * @q: queue to drain
  309. * @drain_all: whether to drain all requests or only the ones w/ ELVPRIV
  310. *
  311. * Drain requests from @q. If @drain_all is set, all requests are drained.
  312. * If not, only ELVPRIV requests are drained. The caller is responsible
  313. * for ensuring that no new requests which need to be drained are queued.
  314. */
  315. void blk_drain_queue(struct request_queue *q, bool drain_all)
  316. {
  317. while (true) {
  318. int nr_rqs;
  319. spin_lock_irq(q->queue_lock);
  320. elv_drain_elevator(q);
  321. if (drain_all)
  322. blk_throtl_drain(q);
  323. __blk_run_queue(q);
  324. if (drain_all)
  325. nr_rqs = q->rq.count[0] + q->rq.count[1];
  326. else
  327. nr_rqs = q->rq.elvpriv;
  328. spin_unlock_irq(q->queue_lock);
  329. if (!nr_rqs)
  330. break;
  331. msleep(10);
  332. }
  333. }
  334. /**
  335. * blk_cleanup_queue - shutdown a request queue
  336. * @q: request queue to shutdown
  337. *
  338. * Mark @q DEAD, drain all pending requests, destroy and put it. All
  339. * future requests will be failed immediately with -ENODEV.
  340. */
  341. void blk_cleanup_queue(struct request_queue *q)
  342. {
  343. spinlock_t *lock = q->queue_lock;
  344. /* mark @q DEAD, no new request or merges will be allowed afterwards */
  345. mutex_lock(&q->sysfs_lock);
  346. queue_flag_set_unlocked(QUEUE_FLAG_DEAD, q);
  347. spin_lock_irq(lock);
  348. queue_flag_set(QUEUE_FLAG_NOMERGES, q);
  349. queue_flag_set(QUEUE_FLAG_NOXMERGES, q);
  350. queue_flag_set(QUEUE_FLAG_DEAD, q);
  351. if (q->queue_lock != &q->__queue_lock)
  352. q->queue_lock = &q->__queue_lock;
  353. spin_unlock_irq(lock);
  354. mutex_unlock(&q->sysfs_lock);
  355. /*
  356. * Drain all requests queued before DEAD marking. The caller might
  357. * be trying to tear down @q before its elevator is initialized, in
  358. * which case we don't want to call into draining.
  359. */
  360. if (q->elevator)
  361. blk_drain_queue(q, true);
  362. /* @q won't process any more request, flush async actions */
  363. del_timer_sync(&q->backing_dev_info.laptop_mode_wb_timer);
  364. blk_sync_queue(q);
  365. /* @q is and will stay empty, shutdown and put */
  366. blk_put_queue(q);
  367. }
  368. EXPORT_SYMBOL(blk_cleanup_queue);
  369. static int blk_init_free_list(struct request_queue *q)
  370. {
  371. struct request_list *rl = &q->rq;
  372. if (unlikely(rl->rq_pool))
  373. return 0;
  374. rl->count[BLK_RW_SYNC] = rl->count[BLK_RW_ASYNC] = 0;
  375. rl->starved[BLK_RW_SYNC] = rl->starved[BLK_RW_ASYNC] = 0;
  376. rl->elvpriv = 0;
  377. init_waitqueue_head(&rl->wait[BLK_RW_SYNC]);
  378. init_waitqueue_head(&rl->wait[BLK_RW_ASYNC]);
  379. rl->rq_pool = mempool_create_node(BLKDEV_MIN_RQ, mempool_alloc_slab,
  380. mempool_free_slab, request_cachep, q->node);
  381. if (!rl->rq_pool)
  382. return -ENOMEM;
  383. return 0;
  384. }
  385. struct request_queue *blk_alloc_queue(gfp_t gfp_mask)
  386. {
  387. return blk_alloc_queue_node(gfp_mask, -1);
  388. }
  389. EXPORT_SYMBOL(blk_alloc_queue);
  390. struct request_queue *blk_alloc_queue_node(gfp_t gfp_mask, int node_id)
  391. {
  392. struct request_queue *q;
  393. int err;
  394. q = kmem_cache_alloc_node(blk_requestq_cachep,
  395. gfp_mask | __GFP_ZERO, node_id);
  396. if (!q)
  397. return NULL;
  398. q->backing_dev_info.ra_pages =
  399. (VM_MAX_READAHEAD * 1024) / PAGE_CACHE_SIZE;
  400. q->backing_dev_info.state = 0;
  401. q->backing_dev_info.capabilities = BDI_CAP_MAP_COPY;
  402. q->backing_dev_info.name = "block";
  403. err = bdi_init(&q->backing_dev_info);
  404. if (err) {
  405. kmem_cache_free(blk_requestq_cachep, q);
  406. return NULL;
  407. }
  408. if (blk_throtl_init(q)) {
  409. kmem_cache_free(blk_requestq_cachep, q);
  410. return NULL;
  411. }
  412. setup_timer(&q->backing_dev_info.laptop_mode_wb_timer,
  413. laptop_mode_timer_fn, (unsigned long) q);
  414. setup_timer(&q->timeout, blk_rq_timed_out_timer, (unsigned long) q);
  415. INIT_LIST_HEAD(&q->timeout_list);
  416. INIT_LIST_HEAD(&q->flush_queue[0]);
  417. INIT_LIST_HEAD(&q->flush_queue[1]);
  418. INIT_LIST_HEAD(&q->flush_data_in_flight);
  419. INIT_DELAYED_WORK(&q->delay_work, blk_delay_work);
  420. kobject_init(&q->kobj, &blk_queue_ktype);
  421. mutex_init(&q->sysfs_lock);
  422. spin_lock_init(&q->__queue_lock);
  423. /*
  424. * By default initialize queue_lock to internal lock and driver can
  425. * override it later if need be.
  426. */
  427. q->queue_lock = &q->__queue_lock;
  428. return q;
  429. }
  430. EXPORT_SYMBOL(blk_alloc_queue_node);
  431. /**
  432. * blk_init_queue - prepare a request queue for use with a block device
  433. * @rfn: The function to be called to process requests that have been
  434. * placed on the queue.
  435. * @lock: Request queue spin lock
  436. *
  437. * Description:
  438. * If a block device wishes to use the standard request handling procedures,
  439. * which sorts requests and coalesces adjacent requests, then it must
  440. * call blk_init_queue(). The function @rfn will be called when there
  441. * are requests on the queue that need to be processed. If the device
  442. * supports plugging, then @rfn may not be called immediately when requests
  443. * are available on the queue, but may be called at some time later instead.
  444. * Plugged queues are generally unplugged when a buffer belonging to one
  445. * of the requests on the queue is needed, or due to memory pressure.
  446. *
  447. * @rfn is not required, or even expected, to remove all requests off the
  448. * queue, but only as many as it can handle at a time. If it does leave
  449. * requests on the queue, it is responsible for arranging that the requests
  450. * get dealt with eventually.
  451. *
  452. * The queue spin lock must be held while manipulating the requests on the
  453. * request queue; this lock will be taken also from interrupt context, so irq
  454. * disabling is needed for it.
  455. *
  456. * Function returns a pointer to the initialized request queue, or %NULL if
  457. * it didn't succeed.
  458. *
  459. * Note:
  460. * blk_init_queue() must be paired with a blk_cleanup_queue() call
  461. * when the block device is deactivated (such as at module unload).
  462. **/
  463. struct request_queue *blk_init_queue(request_fn_proc *rfn, spinlock_t *lock)
  464. {
  465. return blk_init_queue_node(rfn, lock, -1);
  466. }
  467. EXPORT_SYMBOL(blk_init_queue);
  468. struct request_queue *
  469. blk_init_queue_node(request_fn_proc *rfn, spinlock_t *lock, int node_id)
  470. {
  471. struct request_queue *uninit_q, *q;
  472. uninit_q = blk_alloc_queue_node(GFP_KERNEL, node_id);
  473. if (!uninit_q)
  474. return NULL;
  475. q = blk_init_allocated_queue_node(uninit_q, rfn, lock, node_id);
  476. if (!q)
  477. blk_cleanup_queue(uninit_q);
  478. return q;
  479. }
  480. EXPORT_SYMBOL(blk_init_queue_node);
  481. struct request_queue *
  482. blk_init_allocated_queue(struct request_queue *q, request_fn_proc *rfn,
  483. spinlock_t *lock)
  484. {
  485. return blk_init_allocated_queue_node(q, rfn, lock, -1);
  486. }
  487. EXPORT_SYMBOL(blk_init_allocated_queue);
  488. struct request_queue *
  489. blk_init_allocated_queue_node(struct request_queue *q, request_fn_proc *rfn,
  490. spinlock_t *lock, int node_id)
  491. {
  492. if (!q)
  493. return NULL;
  494. q->node = node_id;
  495. if (blk_init_free_list(q))
  496. return NULL;
  497. q->request_fn = rfn;
  498. q->prep_rq_fn = NULL;
  499. q->unprep_rq_fn = NULL;
  500. q->queue_flags = QUEUE_FLAG_DEFAULT;
  501. /* Override internal queue lock with supplied lock pointer */
  502. if (lock)
  503. q->queue_lock = lock;
  504. /*
  505. * This also sets hw/phys segments, boundary and size
  506. */
  507. blk_queue_make_request(q, blk_queue_bio);
  508. q->sg_reserved_size = INT_MAX;
  509. /*
  510. * all done
  511. */
  512. if (!elevator_init(q, NULL)) {
  513. blk_queue_congestion_threshold(q);
  514. return q;
  515. }
  516. return NULL;
  517. }
  518. EXPORT_SYMBOL(blk_init_allocated_queue_node);
  519. int blk_get_queue(struct request_queue *q)
  520. {
  521. if (likely(!test_bit(QUEUE_FLAG_DEAD, &q->queue_flags))) {
  522. kobject_get(&q->kobj);
  523. return 0;
  524. }
  525. return 1;
  526. }
  527. EXPORT_SYMBOL(blk_get_queue);
  528. static inline void blk_free_request(struct request_queue *q, struct request *rq)
  529. {
  530. if (rq->cmd_flags & REQ_ELVPRIV)
  531. elv_put_request(q, rq);
  532. mempool_free(rq, q->rq.rq_pool);
  533. }
  534. static struct request *
  535. blk_alloc_request(struct request_queue *q, unsigned int flags, gfp_t gfp_mask)
  536. {
  537. struct request *rq = mempool_alloc(q->rq.rq_pool, gfp_mask);
  538. if (!rq)
  539. return NULL;
  540. blk_rq_init(q, rq);
  541. rq->cmd_flags = flags | REQ_ALLOCED;
  542. if ((flags & REQ_ELVPRIV) &&
  543. unlikely(elv_set_request(q, rq, gfp_mask))) {
  544. mempool_free(rq, q->rq.rq_pool);
  545. return NULL;
  546. }
  547. return rq;
  548. }
  549. /*
  550. * ioc_batching returns true if the ioc is a valid batching request and
  551. * should be given priority access to a request.
  552. */
  553. static inline int ioc_batching(struct request_queue *q, struct io_context *ioc)
  554. {
  555. if (!ioc)
  556. return 0;
  557. /*
  558. * Make sure the process is able to allocate at least 1 request
  559. * even if the batch times out, otherwise we could theoretically
  560. * lose wakeups.
  561. */
  562. return ioc->nr_batch_requests == q->nr_batching ||
  563. (ioc->nr_batch_requests > 0
  564. && time_before(jiffies, ioc->last_waited + BLK_BATCH_TIME));
  565. }
  566. /*
  567. * ioc_set_batching sets ioc to be a new "batcher" if it is not one. This
  568. * will cause the process to be a "batcher" on all queues in the system. This
  569. * is the behaviour we want though - once it gets a wakeup it should be given
  570. * a nice run.
  571. */
  572. static void ioc_set_batching(struct request_queue *q, struct io_context *ioc)
  573. {
  574. if (!ioc || ioc_batching(q, ioc))
  575. return;
  576. ioc->nr_batch_requests = q->nr_batching;
  577. ioc->last_waited = jiffies;
  578. }
  579. static void __freed_request(struct request_queue *q, int sync)
  580. {
  581. struct request_list *rl = &q->rq;
  582. if (rl->count[sync] < queue_congestion_off_threshold(q))
  583. blk_clear_queue_congested(q, sync);
  584. if (rl->count[sync] + 1 <= q->nr_requests) {
  585. if (waitqueue_active(&rl->wait[sync]))
  586. wake_up(&rl->wait[sync]);
  587. blk_clear_queue_full(q, sync);
  588. }
  589. }
  590. /*
  591. * A request has just been released. Account for it, update the full and
  592. * congestion status, wake up any waiters. Called under q->queue_lock.
  593. */
  594. static void freed_request(struct request_queue *q, unsigned int flags)
  595. {
  596. struct request_list *rl = &q->rq;
  597. int sync = rw_is_sync(flags);
  598. rl->count[sync]--;
  599. if (flags & REQ_ELVPRIV)
  600. rl->elvpriv--;
  601. __freed_request(q, sync);
  602. if (unlikely(rl->starved[sync ^ 1]))
  603. __freed_request(q, sync ^ 1);
  604. }
  605. /*
  606. * Determine if elevator data should be initialized when allocating the
  607. * request associated with @bio.
  608. */
  609. static bool blk_rq_should_init_elevator(struct bio *bio)
  610. {
  611. if (!bio)
  612. return true;
  613. /*
  614. * Flush requests do not use the elevator so skip initialization.
  615. * This allows a request to share the flush and elevator data.
  616. */
  617. if (bio->bi_rw & (REQ_FLUSH | REQ_FUA))
  618. return false;
  619. return true;
  620. }
  621. /**
  622. * get_request - get a free request
  623. * @q: request_queue to allocate request from
  624. * @rw_flags: RW and SYNC flags
  625. * @bio: bio to allocate request for (can be %NULL)
  626. * @gfp_mask: allocation mask
  627. *
  628. * Get a free request from @q. This function may fail under memory
  629. * pressure or if @q is dead.
  630. *
  631. * Must be callled with @q->queue_lock held and,
  632. * Returns %NULL on failure, with @q->queue_lock held.
  633. * Returns !%NULL on success, with @q->queue_lock *not held*.
  634. */
  635. static struct request *get_request(struct request_queue *q, int rw_flags,
  636. struct bio *bio, gfp_t gfp_mask)
  637. {
  638. struct request *rq = NULL;
  639. struct request_list *rl = &q->rq;
  640. struct io_context *ioc = NULL;
  641. const bool is_sync = rw_is_sync(rw_flags) != 0;
  642. int may_queue;
  643. if (unlikely(test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)))
  644. return NULL;
  645. may_queue = elv_may_queue(q, rw_flags);
  646. if (may_queue == ELV_MQUEUE_NO)
  647. goto rq_starved;
  648. if (rl->count[is_sync]+1 >= queue_congestion_on_threshold(q)) {
  649. if (rl->count[is_sync]+1 >= q->nr_requests) {
  650. ioc = current_io_context(GFP_ATOMIC, q->node);
  651. /*
  652. * The queue will fill after this allocation, so set
  653. * it as full, and mark this process as "batching".
  654. * This process will be allowed to complete a batch of
  655. * requests, others will be blocked.
  656. */
  657. if (!blk_queue_full(q, is_sync)) {
  658. ioc_set_batching(q, ioc);
  659. blk_set_queue_full(q, is_sync);
  660. } else {
  661. if (may_queue != ELV_MQUEUE_MUST
  662. && !ioc_batching(q, ioc)) {
  663. /*
  664. * The queue is full and the allocating
  665. * process is not a "batcher", and not
  666. * exempted by the IO scheduler
  667. */
  668. goto out;
  669. }
  670. }
  671. }
  672. blk_set_queue_congested(q, is_sync);
  673. }
  674. /*
  675. * Only allow batching queuers to allocate up to 50% over the defined
  676. * limit of requests, otherwise we could have thousands of requests
  677. * allocated with any setting of ->nr_requests
  678. */
  679. if (rl->count[is_sync] >= (3 * q->nr_requests / 2))
  680. goto out;
  681. rl->count[is_sync]++;
  682. rl->starved[is_sync] = 0;
  683. if (blk_rq_should_init_elevator(bio) &&
  684. !test_bit(QUEUE_FLAG_ELVSWITCH, &q->queue_flags)) {
  685. rw_flags |= REQ_ELVPRIV;
  686. rl->elvpriv++;
  687. }
  688. if (blk_queue_io_stat(q))
  689. rw_flags |= REQ_IO_STAT;
  690. spin_unlock_irq(q->queue_lock);
  691. rq = blk_alloc_request(q, rw_flags, gfp_mask);
  692. if (unlikely(!rq)) {
  693. /*
  694. * Allocation failed presumably due to memory. Undo anything
  695. * we might have messed up.
  696. *
  697. * Allocating task should really be put onto the front of the
  698. * wait queue, but this is pretty rare.
  699. */
  700. spin_lock_irq(q->queue_lock);
  701. freed_request(q, rw_flags);
  702. /*
  703. * in the very unlikely event that allocation failed and no
  704. * requests for this direction was pending, mark us starved
  705. * so that freeing of a request in the other direction will
  706. * notice us. another possible fix would be to split the
  707. * rq mempool into READ and WRITE
  708. */
  709. rq_starved:
  710. if (unlikely(rl->count[is_sync] == 0))
  711. rl->starved[is_sync] = 1;
  712. goto out;
  713. }
  714. /*
  715. * ioc may be NULL here, and ioc_batching will be false. That's
  716. * OK, if the queue is under the request limit then requests need
  717. * not count toward the nr_batch_requests limit. There will always
  718. * be some limit enforced by BLK_BATCH_TIME.
  719. */
  720. if (ioc_batching(q, ioc))
  721. ioc->nr_batch_requests--;
  722. trace_block_getrq(q, bio, rw_flags & 1);
  723. out:
  724. return rq;
  725. }
  726. /**
  727. * get_request_wait - get a free request with retry
  728. * @q: request_queue to allocate request from
  729. * @rw_flags: RW and SYNC flags
  730. * @bio: bio to allocate request for (can be %NULL)
  731. *
  732. * Get a free request from @q. This function keeps retrying under memory
  733. * pressure and fails iff @q is dead.
  734. *
  735. * Must be callled with @q->queue_lock held and,
  736. * Returns %NULL on failure, with @q->queue_lock held.
  737. * Returns !%NULL on success, with @q->queue_lock *not held*.
  738. */
  739. static struct request *get_request_wait(struct request_queue *q, int rw_flags,
  740. struct bio *bio)
  741. {
  742. const bool is_sync = rw_is_sync(rw_flags) != 0;
  743. struct request *rq;
  744. rq = get_request(q, rw_flags, bio, GFP_NOIO);
  745. while (!rq) {
  746. DEFINE_WAIT(wait);
  747. struct io_context *ioc;
  748. struct request_list *rl = &q->rq;
  749. if (unlikely(test_bit(QUEUE_FLAG_DEAD, &q->queue_flags)))
  750. return NULL;
  751. prepare_to_wait_exclusive(&rl->wait[is_sync], &wait,
  752. TASK_UNINTERRUPTIBLE);
  753. trace_block_sleeprq(q, bio, rw_flags & 1);
  754. spin_unlock_irq(q->queue_lock);
  755. io_schedule();
  756. /*
  757. * After sleeping, we become a "batching" process and
  758. * will be able to allocate at least one request, and
  759. * up to a big batch of them for a small period time.
  760. * See ioc_batching, ioc_set_batching
  761. */
  762. ioc = current_io_context(GFP_NOIO, q->node);
  763. ioc_set_batching(q, ioc);
  764. spin_lock_irq(q->queue_lock);
  765. finish_wait(&rl->wait[is_sync], &wait);
  766. rq = get_request(q, rw_flags, bio, GFP_NOIO);
  767. };
  768. return rq;
  769. }
  770. struct request *blk_get_request(struct request_queue *q, int rw, gfp_t gfp_mask)
  771. {
  772. struct request *rq;
  773. BUG_ON(rw != READ && rw != WRITE);
  774. spin_lock_irq(q->queue_lock);
  775. if (gfp_mask & __GFP_WAIT)
  776. rq = get_request_wait(q, rw, NULL);
  777. else
  778. rq = get_request(q, rw, NULL, gfp_mask);
  779. if (!rq)
  780. spin_unlock_irq(q->queue_lock);
  781. /* q->queue_lock is unlocked at this point */
  782. return rq;
  783. }
  784. EXPORT_SYMBOL(blk_get_request);
  785. /**
  786. * blk_make_request - given a bio, allocate a corresponding struct request.
  787. * @q: target request queue
  788. * @bio: The bio describing the memory mappings that will be submitted for IO.
  789. * It may be a chained-bio properly constructed by block/bio layer.
  790. * @gfp_mask: gfp flags to be used for memory allocation
  791. *
  792. * blk_make_request is the parallel of generic_make_request for BLOCK_PC
  793. * type commands. Where the struct request needs to be farther initialized by
  794. * the caller. It is passed a &struct bio, which describes the memory info of
  795. * the I/O transfer.
  796. *
  797. * The caller of blk_make_request must make sure that bi_io_vec
  798. * are set to describe the memory buffers. That bio_data_dir() will return
  799. * the needed direction of the request. (And all bio's in the passed bio-chain
  800. * are properly set accordingly)
  801. *
  802. * If called under none-sleepable conditions, mapped bio buffers must not
  803. * need bouncing, by calling the appropriate masked or flagged allocator,
  804. * suitable for the target device. Otherwise the call to blk_queue_bounce will
  805. * BUG.
  806. *
  807. * WARNING: When allocating/cloning a bio-chain, careful consideration should be
  808. * given to how you allocate bios. In particular, you cannot use __GFP_WAIT for
  809. * anything but the first bio in the chain. Otherwise you risk waiting for IO
  810. * completion of a bio that hasn't been submitted yet, thus resulting in a
  811. * deadlock. Alternatively bios should be allocated using bio_kmalloc() instead
  812. * of bio_alloc(), as that avoids the mempool deadlock.
  813. * If possible a big IO should be split into smaller parts when allocation
  814. * fails. Partial allocation should not be an error, or you risk a live-lock.
  815. */
  816. struct request *blk_make_request(struct request_queue *q, struct bio *bio,
  817. gfp_t gfp_mask)
  818. {
  819. struct request *rq = blk_get_request(q, bio_data_dir(bio), gfp_mask);
  820. if (unlikely(!rq))
  821. return ERR_PTR(-ENOMEM);
  822. for_each_bio(bio) {
  823. struct bio *bounce_bio = bio;
  824. int ret;
  825. blk_queue_bounce(q, &bounce_bio);
  826. ret = blk_rq_append_bio(q, rq, bounce_bio);
  827. if (unlikely(ret)) {
  828. blk_put_request(rq);
  829. return ERR_PTR(ret);
  830. }
  831. }
  832. return rq;
  833. }
  834. EXPORT_SYMBOL(blk_make_request);
  835. /**
  836. * blk_requeue_request - put a request back on queue
  837. * @q: request queue where request should be inserted
  838. * @rq: request to be inserted
  839. *
  840. * Description:
  841. * Drivers often keep queueing requests until the hardware cannot accept
  842. * more, when that condition happens we need to put the request back
  843. * on the queue. Must be called with queue lock held.
  844. */
  845. void blk_requeue_request(struct request_queue *q, struct request *rq)
  846. {
  847. blk_delete_timer(rq);
  848. blk_clear_rq_complete(rq);
  849. trace_block_rq_requeue(q, rq);
  850. if (blk_rq_tagged(rq))
  851. blk_queue_end_tag(q, rq);
  852. BUG_ON(blk_queued_rq(rq));
  853. elv_requeue_request(q, rq);
  854. }
  855. EXPORT_SYMBOL(blk_requeue_request);
  856. static void add_acct_request(struct request_queue *q, struct request *rq,
  857. int where)
  858. {
  859. drive_stat_acct(rq, 1);
  860. __elv_add_request(q, rq, where);
  861. }
  862. /**
  863. * blk_insert_request - insert a special request into a request queue
  864. * @q: request queue where request should be inserted
  865. * @rq: request to be inserted
  866. * @at_head: insert request at head or tail of queue
  867. * @data: private data
  868. *
  869. * Description:
  870. * Many block devices need to execute commands asynchronously, so they don't
  871. * block the whole kernel from preemption during request execution. This is
  872. * accomplished normally by inserting aritficial requests tagged as
  873. * REQ_TYPE_SPECIAL in to the corresponding request queue, and letting them
  874. * be scheduled for actual execution by the request queue.
  875. *
  876. * We have the option of inserting the head or the tail of the queue.
  877. * Typically we use the tail for new ioctls and so forth. We use the head
  878. * of the queue for things like a QUEUE_FULL message from a device, or a
  879. * host that is unable to accept a particular command.
  880. */
  881. void blk_insert_request(struct request_queue *q, struct request *rq,
  882. int at_head, void *data)
  883. {
  884. int where = at_head ? ELEVATOR_INSERT_FRONT : ELEVATOR_INSERT_BACK;
  885. unsigned long flags;
  886. /*
  887. * tell I/O scheduler that this isn't a regular read/write (ie it
  888. * must not attempt merges on this) and that it acts as a soft
  889. * barrier
  890. */
  891. rq->cmd_type = REQ_TYPE_SPECIAL;
  892. rq->special = data;
  893. spin_lock_irqsave(q->queue_lock, flags);
  894. /*
  895. * If command is tagged, release the tag
  896. */
  897. if (blk_rq_tagged(rq))
  898. blk_queue_end_tag(q, rq);
  899. add_acct_request(q, rq, where);
  900. __blk_run_queue(q);
  901. spin_unlock_irqrestore(q->queue_lock, flags);
  902. }
  903. EXPORT_SYMBOL(blk_insert_request);
  904. static void part_round_stats_single(int cpu, struct hd_struct *part,
  905. unsigned long now)
  906. {
  907. if (now == part->stamp)
  908. return;
  909. if (part_in_flight(part)) {
  910. __part_stat_add(cpu, part, time_in_queue,
  911. part_in_flight(part) * (now - part->stamp));
  912. __part_stat_add(cpu, part, io_ticks, (now - part->stamp));
  913. }
  914. part->stamp = now;
  915. }
  916. /**
  917. * part_round_stats() - Round off the performance stats on a struct disk_stats.
  918. * @cpu: cpu number for stats access
  919. * @part: target partition
  920. *
  921. * The average IO queue length and utilisation statistics are maintained
  922. * by observing the current state of the queue length and the amount of
  923. * time it has been in this state for.
  924. *
  925. * Normally, that accounting is done on IO completion, but that can result
  926. * in more than a second's worth of IO being accounted for within any one
  927. * second, leading to >100% utilisation. To deal with that, we call this
  928. * function to do a round-off before returning the results when reading
  929. * /proc/diskstats. This accounts immediately for all queue usage up to
  930. * the current jiffies and restarts the counters again.
  931. */
  932. void part_round_stats(int cpu, struct hd_struct *part)
  933. {
  934. unsigned long now = jiffies;
  935. if (part->partno)
  936. part_round_stats_single(cpu, &part_to_disk(part)->part0, now);
  937. part_round_stats_single(cpu, part, now);
  938. }
  939. EXPORT_SYMBOL_GPL(part_round_stats);
  940. /*
  941. * queue lock must be held
  942. */
  943. void __blk_put_request(struct request_queue *q, struct request *req)
  944. {
  945. if (unlikely(!q))
  946. return;
  947. if (unlikely(--req->ref_count))
  948. return;
  949. elv_completed_request(q, req);
  950. /* this is a bio leak */
  951. WARN_ON(req->bio != NULL);
  952. /*
  953. * Request may not have originated from ll_rw_blk. if not,
  954. * it didn't come out of our reserved rq pools
  955. */
  956. if (req->cmd_flags & REQ_ALLOCED) {
  957. unsigned int flags = req->cmd_flags;
  958. BUG_ON(!list_empty(&req->queuelist));
  959. BUG_ON(!hlist_unhashed(&req->hash));
  960. blk_free_request(q, req);
  961. freed_request(q, flags);
  962. }
  963. }
  964. EXPORT_SYMBOL_GPL(__blk_put_request);
  965. void blk_put_request(struct request *req)
  966. {
  967. unsigned long flags;
  968. struct request_queue *q = req->q;
  969. spin_lock_irqsave(q->queue_lock, flags);
  970. __blk_put_request(q, req);
  971. spin_unlock_irqrestore(q->queue_lock, flags);
  972. }
  973. EXPORT_SYMBOL(blk_put_request);
  974. /**
  975. * blk_add_request_payload - add a payload to a request
  976. * @rq: request to update
  977. * @page: page backing the payload
  978. * @len: length of the payload.
  979. *
  980. * This allows to later add a payload to an already submitted request by
  981. * a block driver. The driver needs to take care of freeing the payload
  982. * itself.
  983. *
  984. * Note that this is a quite horrible hack and nothing but handling of
  985. * discard requests should ever use it.
  986. */
  987. void blk_add_request_payload(struct request *rq, struct page *page,
  988. unsigned int len)
  989. {
  990. struct bio *bio = rq->bio;
  991. bio->bi_io_vec->bv_page = page;
  992. bio->bi_io_vec->bv_offset = 0;
  993. bio->bi_io_vec->bv_len = len;
  994. bio->bi_size = len;
  995. bio->bi_vcnt = 1;
  996. bio->bi_phys_segments = 1;
  997. rq->__data_len = rq->resid_len = len;
  998. rq->nr_phys_segments = 1;
  999. rq->buffer = bio_data(bio);
  1000. }
  1001. EXPORT_SYMBOL_GPL(blk_add_request_payload);
  1002. static bool bio_attempt_back_merge(struct request_queue *q, struct request *req,
  1003. struct bio *bio)
  1004. {
  1005. const int ff = bio->bi_rw & REQ_FAILFAST_MASK;
  1006. if (!ll_back_merge_fn(q, req, bio))
  1007. return false;
  1008. trace_block_bio_backmerge(q, bio);
  1009. if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
  1010. blk_rq_set_mixed_merge(req);
  1011. req->biotail->bi_next = bio;
  1012. req->biotail = bio;
  1013. req->__data_len += bio->bi_size;
  1014. req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
  1015. drive_stat_acct(req, 0);
  1016. elv_bio_merged(q, req, bio);
  1017. return true;
  1018. }
  1019. static bool bio_attempt_front_merge(struct request_queue *q,
  1020. struct request *req, struct bio *bio)
  1021. {
  1022. const int ff = bio->bi_rw & REQ_FAILFAST_MASK;
  1023. if (!ll_front_merge_fn(q, req, bio))
  1024. return false;
  1025. trace_block_bio_frontmerge(q, bio);
  1026. if ((req->cmd_flags & REQ_FAILFAST_MASK) != ff)
  1027. blk_rq_set_mixed_merge(req);
  1028. bio->bi_next = req->bio;
  1029. req->bio = bio;
  1030. /*
  1031. * may not be valid. if the low level driver said
  1032. * it didn't need a bounce buffer then it better
  1033. * not touch req->buffer either...
  1034. */
  1035. req->buffer = bio_data(bio);
  1036. req->__sector = bio->bi_sector;
  1037. req->__data_len += bio->bi_size;
  1038. req->ioprio = ioprio_best(req->ioprio, bio_prio(bio));
  1039. drive_stat_acct(req, 0);
  1040. elv_bio_merged(q, req, bio);
  1041. return true;
  1042. }
  1043. /**
  1044. * attempt_plug_merge - try to merge with %current's plugged list
  1045. * @q: request_queue new bio is being queued at
  1046. * @bio: new bio being queued
  1047. * @request_count: out parameter for number of traversed plugged requests
  1048. *
  1049. * Determine whether @bio being queued on @q can be merged with a request
  1050. * on %current's plugged list. Returns %true if merge was successful,
  1051. * otherwise %false.
  1052. *
  1053. * This function is called without @q->queue_lock; however, elevator is
  1054. * accessed iff there already are requests on the plugged list which in
  1055. * turn guarantees validity of the elevator.
  1056. *
  1057. * Note that, on successful merge, elevator operation
  1058. * elevator_bio_merged_fn() will be called without queue lock. Elevator
  1059. * must be ready for this.
  1060. */
  1061. static bool attempt_plug_merge(struct request_queue *q, struct bio *bio,
  1062. unsigned int *request_count)
  1063. {
  1064. struct blk_plug *plug;
  1065. struct request *rq;
  1066. bool ret = false;
  1067. plug = current->plug;
  1068. if (!plug)
  1069. goto out;
  1070. *request_count = 0;
  1071. list_for_each_entry_reverse(rq, &plug->list, queuelist) {
  1072. int el_ret;
  1073. (*request_count)++;
  1074. if (rq->q != q)
  1075. continue;
  1076. el_ret = elv_try_merge(rq, bio);
  1077. if (el_ret == ELEVATOR_BACK_MERGE) {
  1078. ret = bio_attempt_back_merge(q, rq, bio);
  1079. if (ret)
  1080. break;
  1081. } else if (el_ret == ELEVATOR_FRONT_MERGE) {
  1082. ret = bio_attempt_front_merge(q, rq, bio);
  1083. if (ret)
  1084. break;
  1085. }
  1086. }
  1087. out:
  1088. return ret;
  1089. }
  1090. void init_request_from_bio(struct request *req, struct bio *bio)
  1091. {
  1092. req->cmd_type = REQ_TYPE_FS;
  1093. req->cmd_flags |= bio->bi_rw & REQ_COMMON_MASK;
  1094. if (bio->bi_rw & REQ_RAHEAD)
  1095. req->cmd_flags |= REQ_FAILFAST_MASK;
  1096. req->errors = 0;
  1097. req->__sector = bio->bi_sector;
  1098. req->ioprio = bio_prio(bio);
  1099. blk_rq_bio_prep(req->q, req, bio);
  1100. }
  1101. void blk_queue_bio(struct request_queue *q, struct bio *bio)
  1102. {
  1103. const bool sync = !!(bio->bi_rw & REQ_SYNC);
  1104. struct blk_plug *plug;
  1105. int el_ret, rw_flags, where = ELEVATOR_INSERT_SORT;
  1106. struct request *req;
  1107. unsigned int request_count = 0;
  1108. /*
  1109. * low level driver can indicate that it wants pages above a
  1110. * certain limit bounced to low memory (ie for highmem, or even
  1111. * ISA dma in theory)
  1112. */
  1113. blk_queue_bounce(q, &bio);
  1114. if (bio->bi_rw & (REQ_FLUSH | REQ_FUA)) {
  1115. spin_lock_irq(q->queue_lock);
  1116. where = ELEVATOR_INSERT_FLUSH;
  1117. goto get_rq;
  1118. }
  1119. /*
  1120. * Check if we can merge with the plugged list before grabbing
  1121. * any locks.
  1122. */
  1123. if (attempt_plug_merge(q, bio, &request_count))
  1124. return;
  1125. spin_lock_irq(q->queue_lock);
  1126. el_ret = elv_merge(q, &req, bio);
  1127. if (el_ret == ELEVATOR_BACK_MERGE) {
  1128. if (bio_attempt_back_merge(q, req, bio)) {
  1129. if (!attempt_back_merge(q, req))
  1130. elv_merged_request(q, req, el_ret);
  1131. goto out_unlock;
  1132. }
  1133. } else if (el_ret == ELEVATOR_FRONT_MERGE) {
  1134. if (bio_attempt_front_merge(q, req, bio)) {
  1135. if (!attempt_front_merge(q, req))
  1136. elv_merged_request(q, req, el_ret);
  1137. goto out_unlock;
  1138. }
  1139. }
  1140. get_rq:
  1141. /*
  1142. * This sync check and mask will be re-done in init_request_from_bio(),
  1143. * but we need to set it earlier to expose the sync flag to the
  1144. * rq allocator and io schedulers.
  1145. */
  1146. rw_flags = bio_data_dir(bio);
  1147. if (sync)
  1148. rw_flags |= REQ_SYNC;
  1149. /*
  1150. * Grab a free request. This is might sleep but can not fail.
  1151. * Returns with the queue unlocked.
  1152. */
  1153. req = get_request_wait(q, rw_flags, bio);
  1154. if (unlikely(!req)) {
  1155. bio_endio(bio, -ENODEV); /* @q is dead */
  1156. goto out_unlock;
  1157. }
  1158. /*
  1159. * After dropping the lock and possibly sleeping here, our request
  1160. * may now be mergeable after it had proven unmergeable (above).
  1161. * We don't worry about that case for efficiency. It won't happen
  1162. * often, and the elevators are able to handle it.
  1163. */
  1164. init_request_from_bio(req, bio);
  1165. if (test_bit(QUEUE_FLAG_SAME_COMP, &q->queue_flags))
  1166. req->cpu = raw_smp_processor_id();
  1167. plug = current->plug;
  1168. if (plug) {
  1169. /*
  1170. * If this is the first request added after a plug, fire
  1171. * of a plug trace. If others have been added before, check
  1172. * if we have multiple devices in this plug. If so, make a
  1173. * note to sort the list before dispatch.
  1174. */
  1175. if (list_empty(&plug->list))
  1176. trace_block_plug(q);
  1177. else if (!plug->should_sort) {
  1178. struct request *__rq;
  1179. __rq = list_entry_rq(plug->list.prev);
  1180. if (__rq->q != q)
  1181. plug->should_sort = 1;
  1182. }
  1183. if (request_count >= BLK_MAX_REQUEST_COUNT)
  1184. blk_flush_plug_list(plug, false);
  1185. list_add_tail(&req->queuelist, &plug->list);
  1186. drive_stat_acct(req, 1);
  1187. } else {
  1188. spin_lock_irq(q->queue_lock);
  1189. add_acct_request(q, req, where);
  1190. __blk_run_queue(q);
  1191. out_unlock:
  1192. spin_unlock_irq(q->queue_lock);
  1193. }
  1194. }
  1195. EXPORT_SYMBOL_GPL(blk_queue_bio); /* for device mapper only */
  1196. /*
  1197. * If bio->bi_dev is a partition, remap the location
  1198. */
  1199. static inline void blk_partition_remap(struct bio *bio)
  1200. {
  1201. struct block_device *bdev = bio->bi_bdev;
  1202. if (bio_sectors(bio) && bdev != bdev->bd_contains) {
  1203. struct hd_struct *p = bdev->bd_part;
  1204. bio->bi_sector += p->start_sect;
  1205. bio->bi_bdev = bdev->bd_contains;
  1206. trace_block_bio_remap(bdev_get_queue(bio->bi_bdev), bio,
  1207. bdev->bd_dev,
  1208. bio->bi_sector - p->start_sect);
  1209. }
  1210. }
  1211. static void handle_bad_sector(struct bio *bio)
  1212. {
  1213. char b[BDEVNAME_SIZE];
  1214. printk(KERN_INFO "attempt to access beyond end of device\n");
  1215. printk(KERN_INFO "%s: rw=%ld, want=%Lu, limit=%Lu\n",
  1216. bdevname(bio->bi_bdev, b),
  1217. bio->bi_rw,
  1218. (unsigned long long)bio->bi_sector + bio_sectors(bio),
  1219. (long long)(i_size_read(bio->bi_bdev->bd_inode) >> 9));
  1220. set_bit(BIO_EOF, &bio->bi_flags);
  1221. }
  1222. #ifdef CONFIG_FAIL_MAKE_REQUEST
  1223. static DECLARE_FAULT_ATTR(fail_make_request);
  1224. static int __init setup_fail_make_request(char *str)
  1225. {
  1226. return setup_fault_attr(&fail_make_request, str);
  1227. }
  1228. __setup("fail_make_request=", setup_fail_make_request);
  1229. static bool should_fail_request(struct hd_struct *part, unsigned int bytes)
  1230. {
  1231. return part->make_it_fail && should_fail(&fail_make_request, bytes);
  1232. }
  1233. static int __init fail_make_request_debugfs(void)
  1234. {
  1235. struct dentry *dir = fault_create_debugfs_attr("fail_make_request",
  1236. NULL, &fail_make_request);
  1237. return IS_ERR(dir) ? PTR_ERR(dir) : 0;
  1238. }
  1239. late_initcall(fail_make_request_debugfs);
  1240. #else /* CONFIG_FAIL_MAKE_REQUEST */
  1241. static inline bool should_fail_request(struct hd_struct *part,
  1242. unsigned int bytes)
  1243. {
  1244. return false;
  1245. }
  1246. #endif /* CONFIG_FAIL_MAKE_REQUEST */
  1247. /*
  1248. * Check whether this bio extends beyond the end of the device.
  1249. */
  1250. static inline int bio_check_eod(struct bio *bio, unsigned int nr_sectors)
  1251. {
  1252. sector_t maxsector;
  1253. if (!nr_sectors)
  1254. return 0;
  1255. /* Test device or partition size, when known. */
  1256. maxsector = i_size_read(bio->bi_bdev->bd_inode) >> 9;
  1257. if (maxsector) {
  1258. sector_t sector = bio->bi_sector;
  1259. if (maxsector < nr_sectors || maxsector - nr_sectors < sector) {
  1260. /*
  1261. * This may well happen - the kernel calls bread()
  1262. * without checking the size of the device, e.g., when
  1263. * mounting a device.
  1264. */
  1265. handle_bad_sector(bio);
  1266. return 1;
  1267. }
  1268. }
  1269. return 0;
  1270. }
  1271. static noinline_for_stack bool
  1272. generic_make_request_checks(struct bio *bio)
  1273. {
  1274. struct request_queue *q;
  1275. int nr_sectors = bio_sectors(bio);
  1276. int err = -EIO;
  1277. char b[BDEVNAME_SIZE];
  1278. struct hd_struct *part;
  1279. might_sleep();
  1280. if (bio_check_eod(bio, nr_sectors))
  1281. goto end_io;
  1282. q = bdev_get_queue(bio->bi_bdev);
  1283. if (unlikely(!q)) {
  1284. printk(KERN_ERR
  1285. "generic_make_request: Trying to access "
  1286. "nonexistent block-device %s (%Lu)\n",
  1287. bdevname(bio->bi_bdev, b),
  1288. (long long) bio->bi_sector);
  1289. goto end_io;
  1290. }
  1291. if (unlikely(!(bio->bi_rw & REQ_DISCARD) &&
  1292. nr_sectors > queue_max_hw_sectors(q))) {
  1293. printk(KERN_ERR "bio too big device %s (%u > %u)\n",
  1294. bdevname(bio->bi_bdev, b),
  1295. bio_sectors(bio),
  1296. queue_max_hw_sectors(q));
  1297. goto end_io;
  1298. }
  1299. part = bio->bi_bdev->bd_part;
  1300. if (should_fail_request(part, bio->bi_size) ||
  1301. should_fail_request(&part_to_disk(part)->part0,
  1302. bio->bi_size))
  1303. goto end_io;
  1304. /*
  1305. * If this device has partitions, remap block n
  1306. * of partition p to block n+start(p) of the disk.
  1307. */
  1308. blk_partition_remap(bio);
  1309. if (bio_integrity_enabled(bio) && bio_integrity_prep(bio))
  1310. goto end_io;
  1311. if (bio_check_eod(bio, nr_sectors))
  1312. goto end_io;
  1313. /*
  1314. * Filter flush bio's early so that make_request based
  1315. * drivers without flush support don't have to worry
  1316. * about them.
  1317. */
  1318. if ((bio->bi_rw & (REQ_FLUSH | REQ_FUA)) && !q->flush_flags) {
  1319. bio->bi_rw &= ~(REQ_FLUSH | REQ_FUA);
  1320. if (!nr_sectors) {
  1321. err = 0;
  1322. goto end_io;
  1323. }
  1324. }
  1325. if ((bio->bi_rw & REQ_DISCARD) &&
  1326. (!blk_queue_discard(q) ||
  1327. ((bio->bi_rw & REQ_SECURE) &&
  1328. !blk_queue_secdiscard(q)))) {
  1329. err = -EOPNOTSUPP;
  1330. goto end_io;
  1331. }
  1332. if (blk_throtl_bio(q, bio))
  1333. return false; /* throttled, will be resubmitted later */
  1334. trace_block_bio_queue(q, bio);
  1335. return true;
  1336. end_io:
  1337. bio_endio(bio, err);
  1338. return false;
  1339. }
  1340. /**
  1341. * generic_make_request - hand a buffer to its device driver for I/O
  1342. * @bio: The bio describing the location in memory and on the device.
  1343. *
  1344. * generic_make_request() is used to make I/O requests of block
  1345. * devices. It is passed a &struct bio, which describes the I/O that needs
  1346. * to be done.
  1347. *
  1348. * generic_make_request() does not return any status. The
  1349. * success/failure status of the request, along with notification of
  1350. * completion, is delivered asynchronously through the bio->bi_end_io
  1351. * function described (one day) else where.
  1352. *
  1353. * The caller of generic_make_request must make sure that bi_io_vec
  1354. * are set to describe the memory buffer, and that bi_dev and bi_sector are
  1355. * set to describe the device address, and the
  1356. * bi_end_io and optionally bi_private are set to describe how
  1357. * completion notification should be signaled.
  1358. *
  1359. * generic_make_request and the drivers it calls may use bi_next if this
  1360. * bio happens to be merged with someone else, and may resubmit the bio to
  1361. * a lower device by calling into generic_make_request recursively, which
  1362. * means the bio should NOT be touched after the call to ->make_request_fn.
  1363. */
  1364. void generic_make_request(struct bio *bio)
  1365. {
  1366. struct bio_list bio_list_on_stack;
  1367. if (!generic_make_request_checks(bio))
  1368. return;
  1369. /*
  1370. * We only want one ->make_request_fn to be active at a time, else
  1371. * stack usage with stacked devices could be a problem. So use
  1372. * current->bio_list to keep a list of requests submited by a
  1373. * make_request_fn function. current->bio_list is also used as a
  1374. * flag to say if generic_make_request is currently active in this
  1375. * task or not. If it is NULL, then no make_request is active. If
  1376. * it is non-NULL, then a make_request is active, and new requests
  1377. * should be added at the tail
  1378. */
  1379. if (current->bio_list) {
  1380. bio_list_add(current->bio_list, bio);
  1381. return;
  1382. }
  1383. /* following loop may be a bit non-obvious, and so deserves some
  1384. * explanation.
  1385. * Before entering the loop, bio->bi_next is NULL (as all callers
  1386. * ensure that) so we have a list with a single bio.
  1387. * We pretend that we have just taken it off a longer list, so
  1388. * we assign bio_list to a pointer to the bio_list_on_stack,
  1389. * thus initialising the bio_list of new bios to be
  1390. * added. ->make_request() may indeed add some more bios
  1391. * through a recursive call to generic_make_request. If it
  1392. * did, we find a non-NULL value in bio_list and re-enter the loop
  1393. * from the top. In this case we really did just take the bio
  1394. * of the top of the list (no pretending) and so remove it from
  1395. * bio_list, and call into ->make_request() again.
  1396. */
  1397. BUG_ON(bio->bi_next);
  1398. bio_list_init(&bio_list_on_stack);
  1399. current->bio_list = &bio_list_on_stack;
  1400. do {
  1401. struct request_queue *q = bdev_get_queue(bio->bi_bdev);
  1402. q->make_request_fn(q, bio);
  1403. bio = bio_list_pop(current->bio_list);
  1404. } while (bio);
  1405. current->bio_list = NULL; /* deactivate */
  1406. }
  1407. EXPORT_SYMBOL(generic_make_request);
  1408. /**
  1409. * submit_bio - submit a bio to the block device layer for I/O
  1410. * @rw: whether to %READ or %WRITE, or maybe to %READA (read ahead)
  1411. * @bio: The &struct bio which describes the I/O
  1412. *
  1413. * submit_bio() is very similar in purpose to generic_make_request(), and
  1414. * uses that function to do most of the work. Both are fairly rough
  1415. * interfaces; @bio must be presetup and ready for I/O.
  1416. *
  1417. */
  1418. void submit_bio(int rw, struct bio *bio)
  1419. {
  1420. int count = bio_sectors(bio);
  1421. bio->bi_rw |= rw;
  1422. /*
  1423. * If it's a regular read/write or a barrier with data attached,
  1424. * go through the normal accounting stuff before submission.
  1425. */
  1426. if (bio_has_data(bio) && !(rw & REQ_DISCARD)) {
  1427. if (rw & WRITE) {
  1428. count_vm_events(PGPGOUT, count);
  1429. } else {
  1430. task_io_account_read(bio->bi_size);
  1431. count_vm_events(PGPGIN, count);
  1432. }
  1433. if (unlikely(block_dump)) {
  1434. char b[BDEVNAME_SIZE];
  1435. printk(KERN_DEBUG "%s(%d): %s block %Lu on %s (%u sectors)\n",
  1436. current->comm, task_pid_nr(current),
  1437. (rw & WRITE) ? "WRITE" : "READ",
  1438. (unsigned long long)bio->bi_sector,
  1439. bdevname(bio->bi_bdev, b),
  1440. count);
  1441. }
  1442. }
  1443. generic_make_request(bio);
  1444. }
  1445. EXPORT_SYMBOL(submit_bio);
  1446. /**
  1447. * blk_rq_check_limits - Helper function to check a request for the queue limit
  1448. * @q: the queue
  1449. * @rq: the request being checked
  1450. *
  1451. * Description:
  1452. * @rq may have been made based on weaker limitations of upper-level queues
  1453. * in request stacking drivers, and it may violate the limitation of @q.
  1454. * Since the block layer and the underlying device driver trust @rq
  1455. * after it is inserted to @q, it should be checked against @q before
  1456. * the insertion using this generic function.
  1457. *
  1458. * This function should also be useful for request stacking drivers
  1459. * in some cases below, so export this function.
  1460. * Request stacking drivers like request-based dm may change the queue
  1461. * limits while requests are in the queue (e.g. dm's table swapping).
  1462. * Such request stacking drivers should check those requests agaist
  1463. * the new queue limits again when they dispatch those requests,
  1464. * although such checkings are also done against the old queue limits
  1465. * when submitting requests.
  1466. */
  1467. int blk_rq_check_limits(struct request_queue *q, struct request *rq)
  1468. {
  1469. if (rq->cmd_flags & REQ_DISCARD)
  1470. return 0;
  1471. if (blk_rq_sectors(rq) > queue_max_sectors(q) ||
  1472. blk_rq_bytes(rq) > queue_max_hw_sectors(q) << 9) {
  1473. printk(KERN_ERR "%s: over max size limit.\n", __func__);
  1474. return -EIO;
  1475. }
  1476. /*
  1477. * queue's settings related to segment counting like q->bounce_pfn
  1478. * may differ from that of other stacking queues.
  1479. * Recalculate it to check the request correctly on this queue's
  1480. * limitation.
  1481. */
  1482. blk_recalc_rq_segments(rq);
  1483. if (rq->nr_phys_segments > queue_max_segments(q)) {
  1484. printk(KERN_ERR "%s: over max segments limit.\n", __func__);
  1485. return -EIO;
  1486. }
  1487. return 0;
  1488. }
  1489. EXPORT_SYMBOL_GPL(blk_rq_check_limits);
  1490. /**
  1491. * blk_insert_cloned_request - Helper for stacking drivers to submit a request
  1492. * @q: the queue to submit the request
  1493. * @rq: the request being queued
  1494. */
  1495. int blk_insert_cloned_request(struct request_queue *q, struct request *rq)
  1496. {
  1497. unsigned long flags;
  1498. int where = ELEVATOR_INSERT_BACK;
  1499. if (blk_rq_check_limits(q, rq))
  1500. return -EIO;
  1501. if (rq->rq_disk &&
  1502. should_fail_request(&rq->rq_disk->part0, blk_rq_bytes(rq)))
  1503. return -EIO;
  1504. spin_lock_irqsave(q->queue_lock, flags);
  1505. /*
  1506. * Submitting request must be dequeued before calling this function
  1507. * because it will be linked to another request_queue
  1508. */
  1509. BUG_ON(blk_queued_rq(rq));
  1510. if (rq->cmd_flags & (REQ_FLUSH|REQ_FUA))
  1511. where = ELEVATOR_INSERT_FLUSH;
  1512. add_acct_request(q, rq, where);
  1513. if (where == ELEVATOR_INSERT_FLUSH)
  1514. __blk_run_queue(q);
  1515. spin_unlock_irqrestore(q->queue_lock, flags);
  1516. return 0;
  1517. }
  1518. EXPORT_SYMBOL_GPL(blk_insert_cloned_request);
  1519. /**
  1520. * blk_rq_err_bytes - determine number of bytes till the next failure boundary
  1521. * @rq: request to examine
  1522. *
  1523. * Description:
  1524. * A request could be merge of IOs which require different failure
  1525. * handling. This function determines the number of bytes which
  1526. * can be failed from the beginning of the request without
  1527. * crossing into area which need to be retried further.
  1528. *
  1529. * Return:
  1530. * The number of bytes to fail.
  1531. *
  1532. * Context:
  1533. * queue_lock must be held.
  1534. */
  1535. unsigned int blk_rq_err_bytes(const struct request *rq)
  1536. {
  1537. unsigned int ff = rq->cmd_flags & REQ_FAILFAST_MASK;
  1538. unsigned int bytes = 0;
  1539. struct bio *bio;
  1540. if (!(rq->cmd_flags & REQ_MIXED_MERGE))
  1541. return blk_rq_bytes(rq);
  1542. /*
  1543. * Currently the only 'mixing' which can happen is between
  1544. * different fastfail types. We can safely fail portions
  1545. * which have all the failfast bits that the first one has -
  1546. * the ones which are at least as eager to fail as the first
  1547. * one.
  1548. */
  1549. for (bio = rq->bio; bio; bio = bio->bi_next) {
  1550. if ((bio->bi_rw & ff) != ff)
  1551. break;
  1552. bytes += bio->bi_size;
  1553. }
  1554. /* this could lead to infinite loop */
  1555. BUG_ON(blk_rq_bytes(rq) && !bytes);
  1556. return bytes;
  1557. }
  1558. EXPORT_SYMBOL_GPL(blk_rq_err_bytes);
  1559. static void blk_account_io_completion(struct request *req, unsigned int bytes)
  1560. {
  1561. if (blk_do_io_stat(req)) {
  1562. const int rw = rq_data_dir(req);
  1563. struct hd_struct *part;
  1564. int cpu;
  1565. cpu = part_stat_lock();
  1566. part = req->part;
  1567. part_stat_add(cpu, part, sectors[rw], bytes >> 9);
  1568. part_stat_unlock();
  1569. }
  1570. }
  1571. static void blk_account_io_done(struct request *req)
  1572. {
  1573. /*
  1574. * Account IO completion. flush_rq isn't accounted as a
  1575. * normal IO on queueing nor completion. Accounting the
  1576. * containing request is enough.
  1577. */
  1578. if (blk_do_io_stat(req) && !(req->cmd_flags & REQ_FLUSH_SEQ)) {
  1579. unsigned long duration = jiffies - req->start_time;
  1580. const int rw = rq_data_dir(req);
  1581. struct hd_struct *part;
  1582. int cpu;
  1583. cpu = part_stat_lock();
  1584. part = req->part;
  1585. part_stat_inc(cpu, part, ios[rw]);
  1586. part_stat_add(cpu, part, ticks[rw], duration);
  1587. part_round_stats(cpu, part);
  1588. part_dec_in_flight(part, rw);
  1589. hd_struct_put(part);
  1590. part_stat_unlock();
  1591. }
  1592. }
  1593. /**
  1594. * blk_peek_request - peek at the top of a request queue
  1595. * @q: request queue to peek at
  1596. *
  1597. * Description:
  1598. * Return the request at the top of @q. The returned request
  1599. * should be started using blk_start_request() before LLD starts
  1600. * processing it.
  1601. *
  1602. * Return:
  1603. * Pointer to the request at the top of @q if available. Null
  1604. * otherwise.
  1605. *
  1606. * Context:
  1607. * queue_lock must be held.
  1608. */
  1609. struct request *blk_peek_request(struct request_queue *q)
  1610. {
  1611. struct request *rq;
  1612. int ret;
  1613. while ((rq = __elv_next_request(q)) != NULL) {
  1614. if (!(rq->cmd_flags & REQ_STARTED)) {
  1615. /*
  1616. * This is the first time the device driver
  1617. * sees this request (possibly after
  1618. * requeueing). Notify IO scheduler.
  1619. */
  1620. if (rq->cmd_flags & REQ_SORTED)
  1621. elv_activate_rq(q, rq);
  1622. /*
  1623. * just mark as started even if we don't start
  1624. * it, a request that has been delayed should
  1625. * not be passed by new incoming requests
  1626. */
  1627. rq->cmd_flags |= REQ_STARTED;
  1628. trace_block_rq_issue(q, rq);
  1629. }
  1630. if (!q->boundary_rq || q->boundary_rq == rq) {
  1631. q->end_sector = rq_end_sector(rq);
  1632. q->boundary_rq = NULL;
  1633. }
  1634. if (rq->cmd_flags & REQ_DONTPREP)
  1635. break;
  1636. if (q->dma_drain_size && blk_rq_bytes(rq)) {
  1637. /*
  1638. * make sure space for the drain appears we
  1639. * know we can do this because max_hw_segments
  1640. * has been adjusted to be one fewer than the
  1641. * device can handle
  1642. */
  1643. rq->nr_phys_segments++;
  1644. }
  1645. if (!q->prep_rq_fn)
  1646. break;
  1647. ret = q->prep_rq_fn(q, rq);
  1648. if (ret == BLKPREP_OK) {
  1649. break;
  1650. } else if (ret == BLKPREP_DEFER) {
  1651. /*
  1652. * the request may have been (partially) prepped.
  1653. * we need to keep this request in the front to
  1654. * avoid resource deadlock. REQ_STARTED will
  1655. * prevent other fs requests from passing this one.
  1656. */
  1657. if (q->dma_drain_size && blk_rq_bytes(rq) &&
  1658. !(rq->cmd_flags & REQ_DONTPREP)) {
  1659. /*
  1660. * remove the space for the drain we added
  1661. * so that we don't add it again
  1662. */
  1663. --rq->nr_phys_segments;
  1664. }
  1665. rq = NULL;
  1666. break;
  1667. } else if (ret == BLKPREP_KILL) {
  1668. rq->cmd_flags |= REQ_QUIET;
  1669. /*
  1670. * Mark this request as started so we don't trigger
  1671. * any debug logic in the end I/O path.
  1672. */
  1673. blk_start_request(rq);
  1674. __blk_end_request_all(rq, -EIO);
  1675. } else {
  1676. printk(KERN_ERR "%s: bad return=%d\n", __func__, ret);
  1677. break;
  1678. }
  1679. }
  1680. return rq;
  1681. }
  1682. EXPORT_SYMBOL(blk_peek_request);
  1683. void blk_dequeue_request(struct request *rq)
  1684. {
  1685. struct request_queue *q = rq->q;
  1686. BUG_ON(list_empty(&rq->queuelist));
  1687. BUG_ON(ELV_ON_HASH(rq));
  1688. list_del_init(&rq->queuelist);
  1689. /*
  1690. * the time frame between a request being removed from the lists
  1691. * and to it is freed is accounted as io that is in progress at
  1692. * the driver side.
  1693. */
  1694. if (blk_account_rq(rq)) {
  1695. q->in_flight[rq_is_sync(rq)]++;
  1696. set_io_start_time_ns(rq);
  1697. }
  1698. }
  1699. /**
  1700. * blk_start_request - start request processing on the driver
  1701. * @req: request to dequeue
  1702. *
  1703. * Description:
  1704. * Dequeue @req and start timeout timer on it. This hands off the
  1705. * request to the driver.
  1706. *
  1707. * Block internal functions which don't want to start timer should
  1708. * call blk_dequeue_request().
  1709. *
  1710. * Context:
  1711. * queue_lock must be held.
  1712. */
  1713. void blk_start_request(struct request *req)
  1714. {
  1715. blk_dequeue_request(req);
  1716. /*
  1717. * We are now handing the request to the hardware, initialize
  1718. * resid_len to full count and add the timeout handler.
  1719. */
  1720. req->resid_len = blk_rq_bytes(req);
  1721. if (unlikely(blk_bidi_rq(req)))
  1722. req->next_rq->resid_len = blk_rq_bytes(req->next_rq);
  1723. blk_add_timer(req);
  1724. }
  1725. EXPORT_SYMBOL(blk_start_request);
  1726. /**
  1727. * blk_fetch_request - fetch a request from a request queue
  1728. * @q: request queue to fetch a request from
  1729. *
  1730. * Description:
  1731. * Return the request at the top of @q. The request is started on
  1732. * return and LLD can start processing it immediately.
  1733. *
  1734. * Return:
  1735. * Pointer to the request at the top of @q if available. Null
  1736. * otherwise.
  1737. *
  1738. * Context:
  1739. * queue_lock must be held.
  1740. */
  1741. struct request *blk_fetch_request(struct request_queue *q)
  1742. {
  1743. struct request *rq;
  1744. rq = blk_peek_request(q);
  1745. if (rq)
  1746. blk_start_request(rq);
  1747. return rq;
  1748. }
  1749. EXPORT_SYMBOL(blk_fetch_request);
  1750. /**
  1751. * blk_update_request - Special helper function for request stacking drivers
  1752. * @req: the request being processed
  1753. * @error: %0 for success, < %0 for error
  1754. * @nr_bytes: number of bytes to complete @req
  1755. *
  1756. * Description:
  1757. * Ends I/O on a number of bytes attached to @req, but doesn't complete
  1758. * the request structure even if @req doesn't have leftover.
  1759. * If @req has leftover, sets it up for the next range of segments.
  1760. *
  1761. * This special helper function is only for request stacking drivers
  1762. * (e.g. request-based dm) so that they can handle partial completion.
  1763. * Actual device drivers should use blk_end_request instead.
  1764. *
  1765. * Passing the result of blk_rq_bytes() as @nr_bytes guarantees
  1766. * %false return from this function.
  1767. *
  1768. * Return:
  1769. * %false - this request doesn't have any more data
  1770. * %true - this request has more data
  1771. **/
  1772. bool blk_update_request(struct request *req, int error, unsigned int nr_bytes)
  1773. {
  1774. int total_bytes, bio_nbytes, next_idx = 0;
  1775. struct bio *bio;
  1776. if (!req->bio)
  1777. return false;
  1778. trace_block_rq_complete(req->q, req);
  1779. /*
  1780. * For fs requests, rq is just carrier of independent bio's
  1781. * and each partial completion should be handled separately.
  1782. * Reset per-request error on each partial completion.
  1783. *
  1784. * TODO: tj: This is too subtle. It would be better to let
  1785. * low level drivers do what they see fit.
  1786. */
  1787. if (req->cmd_type == REQ_TYPE_FS)
  1788. req->errors = 0;
  1789. if (error && req->cmd_type == REQ_TYPE_FS &&
  1790. !(req->cmd_flags & REQ_QUIET)) {
  1791. char *error_type;
  1792. switch (error) {
  1793. case -ENOLINK:
  1794. error_type = "recoverable transport";
  1795. break;
  1796. case -EREMOTEIO:
  1797. error_type = "critical target";
  1798. break;
  1799. case -EBADE:
  1800. error_type = "critical nexus";
  1801. break;
  1802. case -EIO:
  1803. default:
  1804. error_type = "I/O";
  1805. break;
  1806. }
  1807. printk(KERN_ERR "end_request: %s error, dev %s, sector %llu\n",
  1808. error_type, req->rq_disk ? req->rq_disk->disk_name : "?",
  1809. (unsigned long long)blk_rq_pos(req));
  1810. }
  1811. blk_account_io_completion(req, nr_bytes);
  1812. total_bytes = bio_nbytes = 0;
  1813. while ((bio = req->bio) != NULL) {
  1814. int nbytes;
  1815. if (nr_bytes >= bio->bi_size) {
  1816. req->bio = bio->bi_next;
  1817. nbytes = bio->bi_size;
  1818. req_bio_endio(req, bio, nbytes, error);
  1819. next_idx = 0;
  1820. bio_nbytes = 0;
  1821. } else {
  1822. int idx = bio->bi_idx + next_idx;
  1823. if (unlikely(idx >= bio->bi_vcnt)) {
  1824. blk_dump_rq_flags(req, "__end_that");
  1825. printk(KERN_ERR "%s: bio idx %d >= vcnt %d\n",
  1826. __func__, idx, bio->bi_vcnt);
  1827. break;
  1828. }
  1829. nbytes = bio_iovec_idx(bio, idx)->bv_len;
  1830. BIO_BUG_ON(nbytes > bio->bi_size);
  1831. /*
  1832. * not a complete bvec done
  1833. */
  1834. if (unlikely(nbytes > nr_bytes)) {
  1835. bio_nbytes += nr_bytes;
  1836. total_bytes += nr_bytes;
  1837. break;
  1838. }
  1839. /*
  1840. * advance to the next vector
  1841. */
  1842. next_idx++;
  1843. bio_nbytes += nbytes;
  1844. }
  1845. total_bytes += nbytes;
  1846. nr_bytes -= nbytes;
  1847. bio = req->bio;
  1848. if (bio) {
  1849. /*
  1850. * end more in this run, or just return 'not-done'
  1851. */
  1852. if (unlikely(nr_bytes <= 0))
  1853. break;
  1854. }
  1855. }
  1856. /*
  1857. * completely done
  1858. */
  1859. if (!req->bio) {
  1860. /*
  1861. * Reset counters so that the request stacking driver
  1862. * can find how many bytes remain in the request
  1863. * later.
  1864. */
  1865. req->__data_len = 0;
  1866. return false;
  1867. }
  1868. /*
  1869. * if the request wasn't completed, update state
  1870. */
  1871. if (bio_nbytes) {
  1872. req_bio_endio(req, bio, bio_nbytes, error);
  1873. bio->bi_idx += next_idx;
  1874. bio_iovec(bio)->bv_offset += nr_bytes;
  1875. bio_iovec(bio)->bv_len -= nr_bytes;
  1876. }
  1877. req->__data_len -= total_bytes;
  1878. req->buffer = bio_data(req->bio);
  1879. /* update sector only for requests with clear definition of sector */
  1880. if (req->cmd_type == REQ_TYPE_FS || (req->cmd_flags & REQ_DISCARD))
  1881. req->__sector += total_bytes >> 9;
  1882. /* mixed attributes always follow the first bio */
  1883. if (req->cmd_flags & REQ_MIXED_MERGE) {
  1884. req->cmd_flags &= ~REQ_FAILFAST_MASK;
  1885. req->cmd_flags |= req->bio->bi_rw & REQ_FAILFAST_MASK;
  1886. }
  1887. /*
  1888. * If total number of sectors is less than the first segment
  1889. * size, something has gone terribly wrong.
  1890. */
  1891. if (blk_rq_bytes(req) < blk_rq_cur_bytes(req)) {
  1892. blk_dump_rq_flags(req, "request botched");
  1893. req->__data_len = blk_rq_cur_bytes(req);
  1894. }
  1895. /* recalculate the number of segments */
  1896. blk_recalc_rq_segments(req);
  1897. return true;
  1898. }
  1899. EXPORT_SYMBOL_GPL(blk_update_request);
  1900. static bool blk_update_bidi_request(struct request *rq, int error,
  1901. unsigned int nr_bytes,
  1902. unsigned int bidi_bytes)
  1903. {
  1904. if (blk_update_request(rq, error, nr_bytes))
  1905. return true;
  1906. /* Bidi request must be completed as a whole */
  1907. if (unlikely(blk_bidi_rq(rq)) &&
  1908. blk_update_request(rq->next_rq, error, bidi_bytes))
  1909. return true;
  1910. if (blk_queue_add_random(rq->q))
  1911. add_disk_randomness(rq->rq_disk);
  1912. return false;
  1913. }
  1914. /**
  1915. * blk_unprep_request - unprepare a request
  1916. * @req: the request
  1917. *
  1918. * This function makes a request ready for complete resubmission (or
  1919. * completion). It happens only after all error handling is complete,
  1920. * so represents the appropriate moment to deallocate any resources
  1921. * that were allocated to the request in the prep_rq_fn. The queue
  1922. * lock is held when calling this.
  1923. */
  1924. void blk_unprep_request(struct request *req)
  1925. {
  1926. struct request_queue *q = req->q;
  1927. req->cmd_flags &= ~REQ_DONTPREP;
  1928. if (q->unprep_rq_fn)
  1929. q->unprep_rq_fn(q, req);
  1930. }
  1931. EXPORT_SYMBOL_GPL(blk_unprep_request);
  1932. /*
  1933. * queue lock must be held
  1934. */
  1935. static void blk_finish_request(struct request *req, int error)
  1936. {
  1937. if (blk_rq_tagged(req))
  1938. blk_queue_end_tag(req->q, req);
  1939. BUG_ON(blk_queued_rq(req));
  1940. if (unlikely(laptop_mode) && req->cmd_type == REQ_TYPE_FS)
  1941. laptop_io_completion(&req->q->backing_dev_info);
  1942. blk_delete_timer(req);
  1943. if (req->cmd_flags & REQ_DONTPREP)
  1944. blk_unprep_request(req);
  1945. blk_account_io_done(req);
  1946. if (req->end_io)
  1947. req->end_io(req, error);
  1948. else {
  1949. if (blk_bidi_rq(req))
  1950. __blk_put_request(req->next_rq->q, req->next_rq);
  1951. __blk_put_request(req->q, req);
  1952. }
  1953. }
  1954. /**
  1955. * blk_end_bidi_request - Complete a bidi request
  1956. * @rq: the request to complete
  1957. * @error: %0 for success, < %0 for error
  1958. * @nr_bytes: number of bytes to complete @rq
  1959. * @bidi_bytes: number of bytes to complete @rq->next_rq
  1960. *
  1961. * Description:
  1962. * Ends I/O on a number of bytes attached to @rq and @rq->next_rq.
  1963. * Drivers that supports bidi can safely call this member for any
  1964. * type of request, bidi or uni. In the later case @bidi_bytes is
  1965. * just ignored.
  1966. *
  1967. * Return:
  1968. * %false - we are done with this request
  1969. * %true - still buffers pending for this request
  1970. **/
  1971. static bool blk_end_bidi_request(struct request *rq, int error,
  1972. unsigned int nr_bytes, unsigned int bidi_bytes)
  1973. {
  1974. struct request_queue *q = rq->q;
  1975. unsigned long flags;
  1976. if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
  1977. return true;
  1978. spin_lock_irqsave(q->queue_lock, flags);
  1979. blk_finish_request(rq, error);
  1980. spin_unlock_irqrestore(q->queue_lock, flags);
  1981. return false;
  1982. }
  1983. /**
  1984. * __blk_end_bidi_request - Complete a bidi request with queue lock held
  1985. * @rq: the request to complete
  1986. * @error: %0 for success, < %0 for error
  1987. * @nr_bytes: number of bytes to complete @rq
  1988. * @bidi_bytes: number of bytes to complete @rq->next_rq
  1989. *
  1990. * Description:
  1991. * Identical to blk_end_bidi_request() except that queue lock is
  1992. * assumed to be locked on entry and remains so on return.
  1993. *
  1994. * Return:
  1995. * %false - we are done with this request
  1996. * %true - still buffers pending for this request
  1997. **/
  1998. bool __blk_end_bidi_request(struct request *rq, int error,
  1999. unsigned int nr_bytes, unsigned int bidi_bytes)
  2000. {
  2001. if (blk_update_bidi_request(rq, error, nr_bytes, bidi_bytes))
  2002. return true;
  2003. blk_finish_request(rq, error);
  2004. return false;
  2005. }
  2006. /**
  2007. * blk_end_request - Helper function for drivers to complete the request.
  2008. * @rq: the request being processed
  2009. * @error: %0 for success, < %0 for error
  2010. * @nr_bytes: number of bytes to complete
  2011. *
  2012. * Description:
  2013. * Ends I/O on a number of bytes attached to @rq.
  2014. * If @rq has leftover, sets it up for the next range of segments.
  2015. *
  2016. * Return:
  2017. * %false - we are done with this request
  2018. * %true - still buffers pending for this request
  2019. **/
  2020. bool blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
  2021. {
  2022. return blk_end_bidi_request(rq, error, nr_bytes, 0);
  2023. }
  2024. EXPORT_SYMBOL(blk_end_request);
  2025. /**
  2026. * blk_end_request_all - Helper function for drives to finish the request.
  2027. * @rq: the request to finish
  2028. * @error: %0 for success, < %0 for error
  2029. *
  2030. * Description:
  2031. * Completely finish @rq.
  2032. */
  2033. void blk_end_request_all(struct request *rq, int error)
  2034. {
  2035. bool pending;
  2036. unsigned int bidi_bytes = 0;
  2037. if (unlikely(blk_bidi_rq(rq)))
  2038. bidi_bytes = blk_rq_bytes(rq->next_rq);
  2039. pending = blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
  2040. BUG_ON(pending);
  2041. }
  2042. EXPORT_SYMBOL(blk_end_request_all);
  2043. /**
  2044. * blk_end_request_cur - Helper function to finish the current request chunk.
  2045. * @rq: the request to finish the current chunk for
  2046. * @error: %0 for success, < %0 for error
  2047. *
  2048. * Description:
  2049. * Complete the current consecutively mapped chunk from @rq.
  2050. *
  2051. * Return:
  2052. * %false - we are done with this request
  2053. * %true - still buffers pending for this request
  2054. */
  2055. bool blk_end_request_cur(struct request *rq, int error)
  2056. {
  2057. return blk_end_request(rq, error, blk_rq_cur_bytes(rq));
  2058. }
  2059. EXPORT_SYMBOL(blk_end_request_cur);
  2060. /**
  2061. * blk_end_request_err - Finish a request till the next failure boundary.
  2062. * @rq: the request to finish till the next failure boundary for
  2063. * @error: must be negative errno
  2064. *
  2065. * Description:
  2066. * Complete @rq till the next failure boundary.
  2067. *
  2068. * Return:
  2069. * %false - we are done with this request
  2070. * %true - still buffers pending for this request
  2071. */
  2072. bool blk_end_request_err(struct request *rq, int error)
  2073. {
  2074. WARN_ON(error >= 0);
  2075. return blk_end_request(rq, error, blk_rq_err_bytes(rq));
  2076. }
  2077. EXPORT_SYMBOL_GPL(blk_end_request_err);
  2078. /**
  2079. * __blk_end_request - Helper function for drivers to complete the request.
  2080. * @rq: the request being processed
  2081. * @error: %0 for success, < %0 for error
  2082. * @nr_bytes: number of bytes to complete
  2083. *
  2084. * Description:
  2085. * Must be called with queue lock held unlike blk_end_request().
  2086. *
  2087. * Return:
  2088. * %false - we are done with this request
  2089. * %true - still buffers pending for this request
  2090. **/
  2091. bool __blk_end_request(struct request *rq, int error, unsigned int nr_bytes)
  2092. {
  2093. return __blk_end_bidi_request(rq, error, nr_bytes, 0);
  2094. }
  2095. EXPORT_SYMBOL(__blk_end_request);
  2096. /**
  2097. * __blk_end_request_all - Helper function for drives to finish the request.
  2098. * @rq: the request to finish
  2099. * @error: %0 for success, < %0 for error
  2100. *
  2101. * Description:
  2102. * Completely finish @rq. Must be called with queue lock held.
  2103. */
  2104. void __blk_end_request_all(struct request *rq, int error)
  2105. {
  2106. bool pending;
  2107. unsigned int bidi_bytes = 0;
  2108. if (unlikely(blk_bidi_rq(rq)))
  2109. bidi_bytes = blk_rq_bytes(rq->next_rq);
  2110. pending = __blk_end_bidi_request(rq, error, blk_rq_bytes(rq), bidi_bytes);
  2111. BUG_ON(pending);
  2112. }
  2113. EXPORT_SYMBOL(__blk_end_request_all);
  2114. /**
  2115. * __blk_end_request_cur - Helper function to finish the current request chunk.
  2116. * @rq: the request to finish the current chunk for
  2117. * @error: %0 for success, < %0 for error
  2118. *
  2119. * Description:
  2120. * Complete the current consecutively mapped chunk from @rq. Must
  2121. * be called with queue lock held.
  2122. *
  2123. * Return:
  2124. * %false - we are done with this request
  2125. * %true - still buffers pending for this request
  2126. */
  2127. bool __blk_end_request_cur(struct request *rq, int error)
  2128. {
  2129. return __blk_end_request(rq, error, blk_rq_cur_bytes(rq));
  2130. }
  2131. EXPORT_SYMBOL(__blk_end_request_cur);
  2132. /**
  2133. * __blk_end_request_err - Finish a request till the next failure boundary.
  2134. * @rq: the request to finish till the next failure boundary for
  2135. * @error: must be negative errno
  2136. *
  2137. * Description:
  2138. * Complete @rq till the next failure boundary. Must be called
  2139. * with queue lock held.
  2140. *
  2141. * Return:
  2142. * %false - we are done with this request
  2143. * %true - still buffers pending for this request
  2144. */
  2145. bool __blk_end_request_err(struct request *rq, int error)
  2146. {
  2147. WARN_ON(error >= 0);
  2148. return __blk_end_request(rq, error, blk_rq_err_bytes(rq));
  2149. }
  2150. EXPORT_SYMBOL_GPL(__blk_end_request_err);
  2151. void blk_rq_bio_prep(struct request_queue *q, struct request *rq,
  2152. struct bio *bio)
  2153. {
  2154. /* Bit 0 (R/W) is identical in rq->cmd_flags and bio->bi_rw */
  2155. rq->cmd_flags |= bio->bi_rw & REQ_WRITE;
  2156. if (bio_has_data(bio)) {
  2157. rq->nr_phys_segments = bio_phys_segments(q, bio);
  2158. rq->buffer = bio_data(bio);
  2159. }
  2160. rq->__data_len = bio->bi_size;
  2161. rq->bio = rq->biotail = bio;
  2162. if (bio->bi_bdev)
  2163. rq->rq_disk = bio->bi_bdev->bd_disk;
  2164. }
  2165. #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE
  2166. /**
  2167. * rq_flush_dcache_pages - Helper function to flush all pages in a request
  2168. * @rq: the request to be flushed
  2169. *
  2170. * Description:
  2171. * Flush all pages in @rq.
  2172. */
  2173. void rq_flush_dcache_pages(struct request *rq)
  2174. {
  2175. struct req_iterator iter;
  2176. struct bio_vec *bvec;
  2177. rq_for_each_segment(bvec, rq, iter)
  2178. flush_dcache_page(bvec->bv_page);
  2179. }
  2180. EXPORT_SYMBOL_GPL(rq_flush_dcache_pages);
  2181. #endif
  2182. /**
  2183. * blk_lld_busy - Check if underlying low-level drivers of a device are busy
  2184. * @q : the queue of the device being checked
  2185. *
  2186. * Description:
  2187. * Check if underlying low-level drivers of a device are busy.
  2188. * If the drivers want to export their busy state, they must set own
  2189. * exporting function using blk_queue_lld_busy() first.
  2190. *
  2191. * Basically, this function is used only by request stacking drivers
  2192. * to stop dispatching requests to underlying devices when underlying
  2193. * devices are busy. This behavior helps more I/O merging on the queue
  2194. * of the request stacking driver and prevents I/O throughput regression
  2195. * on burst I/O load.
  2196. *
  2197. * Return:
  2198. * 0 - Not busy (The request stacking driver should dispatch request)
  2199. * 1 - Busy (The request stacking driver should stop dispatching request)
  2200. */
  2201. int blk_lld_busy(struct request_queue *q)
  2202. {
  2203. if (q->lld_busy_fn)
  2204. return q->lld_busy_fn(q);
  2205. return 0;
  2206. }
  2207. EXPORT_SYMBOL_GPL(blk_lld_busy);
  2208. /**
  2209. * blk_rq_unprep_clone - Helper function to free all bios in a cloned request
  2210. * @rq: the clone request to be cleaned up
  2211. *
  2212. * Description:
  2213. * Free all bios in @rq for a cloned request.
  2214. */
  2215. void blk_rq_unprep_clone(struct request *rq)
  2216. {
  2217. struct bio *bio;
  2218. while ((bio = rq->bio) != NULL) {
  2219. rq->bio = bio->bi_next;
  2220. bio_put(bio);
  2221. }
  2222. }
  2223. EXPORT_SYMBOL_GPL(blk_rq_unprep_clone);
  2224. /*
  2225. * Copy attributes of the original request to the clone request.
  2226. * The actual data parts (e.g. ->cmd, ->buffer, ->sense) are not copied.
  2227. */
  2228. static void __blk_rq_prep_clone(struct request *dst, struct request *src)
  2229. {
  2230. dst->cpu = src->cpu;
  2231. dst->cmd_flags = (src->cmd_flags & REQ_CLONE_MASK) | REQ_NOMERGE;
  2232. dst->cmd_type = src->cmd_type;
  2233. dst->__sector = blk_rq_pos(src);
  2234. dst->__data_len = blk_rq_bytes(src);
  2235. dst->nr_phys_segments = src->nr_phys_segments;
  2236. dst->ioprio = src->ioprio;
  2237. dst->extra_len = src->extra_len;
  2238. }
  2239. /**
  2240. * blk_rq_prep_clone - Helper function to setup clone request
  2241. * @rq: the request to be setup
  2242. * @rq_src: original request to be cloned
  2243. * @bs: bio_set that bios for clone are allocated from
  2244. * @gfp_mask: memory allocation mask for bio
  2245. * @bio_ctr: setup function to be called for each clone bio.
  2246. * Returns %0 for success, non %0 for failure.
  2247. * @data: private data to be passed to @bio_ctr
  2248. *
  2249. * Description:
  2250. * Clones bios in @rq_src to @rq, and copies attributes of @rq_src to @rq.
  2251. * The actual data parts of @rq_src (e.g. ->cmd, ->buffer, ->sense)
  2252. * are not copied, and copying such parts is the caller's responsibility.
  2253. * Also, pages which the original bios are pointing to are not copied
  2254. * and the cloned bios just point same pages.
  2255. * So cloned bios must be completed before original bios, which means
  2256. * the caller must complete @rq before @rq_src.
  2257. */
  2258. int blk_rq_prep_clone(struct request *rq, struct request *rq_src,
  2259. struct bio_set *bs, gfp_t gfp_mask,
  2260. int (*bio_ctr)(struct bio *, struct bio *, void *),
  2261. void *data)
  2262. {
  2263. struct bio *bio, *bio_src;
  2264. if (!bs)
  2265. bs = fs_bio_set;
  2266. blk_rq_init(NULL, rq);
  2267. __rq_for_each_bio(bio_src, rq_src) {
  2268. bio = bio_alloc_bioset(gfp_mask, bio_src->bi_max_vecs, bs);
  2269. if (!bio)
  2270. goto free_and_out;
  2271. __bio_clone(bio, bio_src);
  2272. if (bio_integrity(bio_src) &&
  2273. bio_integrity_clone(bio, bio_src, gfp_mask, bs))
  2274. goto free_and_out;
  2275. if (bio_ctr && bio_ctr(bio, bio_src, data))
  2276. goto free_and_out;
  2277. if (rq->bio) {
  2278. rq->biotail->bi_next = bio;
  2279. rq->biotail = bio;
  2280. } else
  2281. rq->bio = rq->biotail = bio;
  2282. }
  2283. __blk_rq_prep_clone(rq, rq_src);
  2284. return 0;
  2285. free_and_out:
  2286. if (bio)
  2287. bio_free(bio, bs);
  2288. blk_rq_unprep_clone(rq);
  2289. return -ENOMEM;
  2290. }
  2291. EXPORT_SYMBOL_GPL(blk_rq_prep_clone);
  2292. int kblockd_schedule_work(struct request_queue *q, struct work_struct *work)
  2293. {
  2294. return queue_work(kblockd_workqueue, work);
  2295. }
  2296. EXPORT_SYMBOL(kblockd_schedule_work);
  2297. int kblockd_schedule_delayed_work(struct request_queue *q,
  2298. struct delayed_work *dwork, unsigned long delay)
  2299. {
  2300. return queue_delayed_work(kblockd_workqueue, dwork, delay);
  2301. }
  2302. EXPORT_SYMBOL(kblockd_schedule_delayed_work);
  2303. #define PLUG_MAGIC 0x91827364
  2304. /**
  2305. * blk_start_plug - initialize blk_plug and track it inside the task_struct
  2306. * @plug: The &struct blk_plug that needs to be initialized
  2307. *
  2308. * Description:
  2309. * Tracking blk_plug inside the task_struct will help with auto-flushing the
  2310. * pending I/O should the task end up blocking between blk_start_plug() and
  2311. * blk_finish_plug(). This is important from a performance perspective, but
  2312. * also ensures that we don't deadlock. For instance, if the task is blocking
  2313. * for a memory allocation, memory reclaim could end up wanting to free a
  2314. * page belonging to that request that is currently residing in our private
  2315. * plug. By flushing the pending I/O when the process goes to sleep, we avoid
  2316. * this kind of deadlock.
  2317. */
  2318. void blk_start_plug(struct blk_plug *plug)
  2319. {
  2320. struct task_struct *tsk = current;
  2321. plug->magic = PLUG_MAGIC;
  2322. INIT_LIST_HEAD(&plug->list);
  2323. INIT_LIST_HEAD(&plug->cb_list);
  2324. plug->should_sort = 0;
  2325. /*
  2326. * If this is a nested plug, don't actually assign it. It will be
  2327. * flushed on its own.
  2328. */
  2329. if (!tsk->plug) {
  2330. /*
  2331. * Store ordering should not be needed here, since a potential
  2332. * preempt will imply a full memory barrier
  2333. */
  2334. tsk->plug = plug;
  2335. }
  2336. }
  2337. EXPORT_SYMBOL(blk_start_plug);
  2338. static int plug_rq_cmp(void *priv, struct list_head *a, struct list_head *b)
  2339. {
  2340. struct request *rqa = container_of(a, struct request, queuelist);
  2341. struct request *rqb = container_of(b, struct request, queuelist);
  2342. return !(rqa->q <= rqb->q);
  2343. }
  2344. /*
  2345. * If 'from_schedule' is true, then postpone the dispatch of requests
  2346. * until a safe kblockd context. We due this to avoid accidental big
  2347. * additional stack usage in driver dispatch, in places where the originally
  2348. * plugger did not intend it.
  2349. */
  2350. static void queue_unplugged(struct request_queue *q, unsigned int depth,
  2351. bool from_schedule)
  2352. __releases(q->queue_lock)
  2353. {
  2354. trace_block_unplug(q, depth, !from_schedule);
  2355. /*
  2356. * If we are punting this to kblockd, then we can safely drop
  2357. * the queue_lock before waking kblockd (which needs to take
  2358. * this lock).
  2359. */
  2360. if (from_schedule) {
  2361. spin_unlock(q->queue_lock);
  2362. blk_run_queue_async(q);
  2363. } else {
  2364. __blk_run_queue(q);
  2365. spin_unlock(q->queue_lock);
  2366. }
  2367. }
  2368. static void flush_plug_callbacks(struct blk_plug *plug)
  2369. {
  2370. LIST_HEAD(callbacks);
  2371. if (list_empty(&plug->cb_list))
  2372. return;
  2373. list_splice_init(&plug->cb_list, &callbacks);
  2374. while (!list_empty(&callbacks)) {
  2375. struct blk_plug_cb *cb = list_first_entry(&callbacks,
  2376. struct blk_plug_cb,
  2377. list);
  2378. list_del(&cb->list);
  2379. cb->callback(cb);
  2380. }
  2381. }
  2382. void blk_flush_plug_list(struct blk_plug *plug, bool from_schedule)
  2383. {
  2384. struct request_queue *q;
  2385. unsigned long flags;
  2386. struct request *rq;
  2387. LIST_HEAD(list);
  2388. unsigned int depth;
  2389. BUG_ON(plug->magic != PLUG_MAGIC);
  2390. flush_plug_callbacks(plug);
  2391. if (list_empty(&plug->list))
  2392. return;
  2393. list_splice_init(&plug->list, &list);
  2394. if (plug->should_sort) {
  2395. list_sort(NULL, &list, plug_rq_cmp);
  2396. plug->should_sort = 0;
  2397. }
  2398. q = NULL;
  2399. depth = 0;
  2400. /*
  2401. * Save and disable interrupts here, to avoid doing it for every
  2402. * queue lock we have to take.
  2403. */
  2404. local_irq_save(flags);
  2405. while (!list_empty(&list)) {
  2406. rq = list_entry_rq(list.next);
  2407. list_del_init(&rq->queuelist);
  2408. BUG_ON(!rq->q);
  2409. if (rq->q != q) {
  2410. /*
  2411. * This drops the queue lock
  2412. */
  2413. if (q)
  2414. queue_unplugged(q, depth, from_schedule);
  2415. q = rq->q;
  2416. depth = 0;
  2417. spin_lock(q->queue_lock);
  2418. }
  2419. /*
  2420. * rq is already accounted, so use raw insert
  2421. */
  2422. if (rq->cmd_flags & (REQ_FLUSH | REQ_FUA))
  2423. __elv_add_request(q, rq, ELEVATOR_INSERT_FLUSH);
  2424. else
  2425. __elv_add_request(q, rq, ELEVATOR_INSERT_SORT_MERGE);
  2426. depth++;
  2427. }
  2428. /*
  2429. * This drops the queue lock
  2430. */
  2431. if (q)
  2432. queue_unplugged(q, depth, from_schedule);
  2433. local_irq_restore(flags);
  2434. }
  2435. void blk_finish_plug(struct blk_plug *plug)
  2436. {
  2437. blk_flush_plug_list(plug, false);
  2438. if (plug == current->plug)
  2439. current->plug = NULL;
  2440. }
  2441. EXPORT_SYMBOL(blk_finish_plug);
  2442. int __init blk_dev_init(void)
  2443. {
  2444. BUILD_BUG_ON(__REQ_NR_BITS > 8 *
  2445. sizeof(((struct request *)0)->cmd_flags));
  2446. /* used for unplugging and affects IO latency/throughput - HIGHPRI */
  2447. kblockd_workqueue = alloc_workqueue("kblockd",
  2448. WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
  2449. if (!kblockd_workqueue)
  2450. panic("Failed to create kblockd\n");
  2451. request_cachep = kmem_cache_create("blkdev_requests",
  2452. sizeof(struct request), 0, SLAB_PANIC, NULL);
  2453. blk_requestq_cachep = kmem_cache_create("blkdev_queue",
  2454. sizeof(struct request_queue), 0, SLAB_PANIC, NULL);
  2455. return 0;
  2456. }