blk-core.c 91 KB

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