blk-core.c 105 KB

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