blk-core.c 89 KB

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