blk-core.c 92 KB

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