blk-core.c 91 KB

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