blk-core.c 97 KB

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