blk-core.c 82 KB

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