blk-core.c 88 KB

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