blk-core.c 96 KB

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