blk-core.c 89 KB

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