blk-core.c 88 KB

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