blk-core.c 90 KB

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