blk-core.c 77 KB

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