blk-core.c 94 KB

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