blk-core.c 95 KB

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