blk-core.c 91 KB

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