blk-core.c 105 KB

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