blk-core.c 81 KB

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