blk-core.c 95 KB

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