blk-core.c 81 KB

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