blk-core.c 94 KB

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