blk-core.c 82 KB

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