blk-core.c 82 KB

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