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