blk-core.c 93 KB

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