blk-core.c 95 KB

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