blk-core.c 73 KB

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