blk-core.c 78 KB

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