blk-core.c 90 KB

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