blk-core.c 97 KB

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