blk-core.c 81 KB

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