blk-core.c 90 KB

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