blk-core.c 92 KB

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