blk-core.c 80 KB

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