blk-core.c 82 KB

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