blk-core.c 93 KB

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