io_uring.c 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Shared application/kernel submission and completion ring pairs, for
  4. * supporting fast/efficient IO.
  5. *
  6. * A note on the read/write ordering memory barriers that are matched between
  7. * the application and kernel side.
  8. *
  9. * After the application reads the CQ ring tail, it must use an
  10. * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
  11. * before writing the tail (using smp_load_acquire to read the tail will
  12. * do). It also needs a smp_mb() before updating CQ head (ordering the
  13. * entry load(s) with the head store), pairing with an implicit barrier
  14. * through a control-dependency in io_get_cqe (smp_store_release to
  15. * store head will do). Failure to do so could lead to reading invalid
  16. * CQ entries.
  17. *
  18. * Likewise, the application must use an appropriate smp_wmb() before
  19. * writing the SQ tail (ordering SQ entry stores with the tail store),
  20. * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
  21. * to store the tail will do). And it needs a barrier ordering the SQ
  22. * head load before writing new SQ entries (smp_load_acquire to read
  23. * head will do).
  24. *
  25. * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
  26. * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
  27. * updating the SQ tail; a full memory barrier smp_mb() is needed
  28. * between.
  29. *
  30. * Also see the examples in the liburing library:
  31. *
  32. * git://git.kernel.dk/liburing
  33. *
  34. * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
  35. * from data shared between the kernel and application. This is done both
  36. * for ordering purposes, but also to ensure that once a value is loaded from
  37. * data that the application could potentially modify, it remains stable.
  38. *
  39. * Copyright (C) 2018-2019 Jens Axboe
  40. * Copyright (c) 2018-2019 Christoph Hellwig
  41. */
  42. #include <linux/kernel.h>
  43. #include <linux/init.h>
  44. #include <linux/errno.h>
  45. #include <linux/syscalls.h>
  46. #include <net/compat.h>
  47. #include <linux/refcount.h>
  48. #include <linux/uio.h>
  49. #include <linux/bits.h>
  50. #include <linux/sched/signal.h>
  51. #include <linux/fs.h>
  52. #include <linux/file.h>
  53. #include <linux/fdtable.h>
  54. #include <linux/mm.h>
  55. #include <linux/mman.h>
  56. #include <linux/percpu.h>
  57. #include <linux/slab.h>
  58. #include <linux/bvec.h>
  59. #include <linux/net.h>
  60. #include <net/sock.h>
  61. #include <linux/anon_inodes.h>
  62. #include <linux/sched/mm.h>
  63. #include <linux/uaccess.h>
  64. #include <linux/nospec.h>
  65. #include <linux/fsnotify.h>
  66. #include <linux/fadvise.h>
  67. #include <linux/task_work.h>
  68. #include <linux/io_uring.h>
  69. #include <linux/io_uring/cmd.h>
  70. #include <linux/audit.h>
  71. #include <linux/security.h>
  72. #include <asm/shmparam.h>
  73. #define CREATE_TRACE_POINTS
  74. #include <trace/events/io_uring.h>
  75. #include <uapi/linux/io_uring.h>
  76. #include "io-wq.h"
  77. #include "io_uring.h"
  78. #include "opdef.h"
  79. #include "refs.h"
  80. #include "tctx.h"
  81. #include "register.h"
  82. #include "sqpoll.h"
  83. #include "fdinfo.h"
  84. #include "kbuf.h"
  85. #include "rsrc.h"
  86. #include "cancel.h"
  87. #include "net.h"
  88. #include "notif.h"
  89. #include "waitid.h"
  90. #include "futex.h"
  91. #include "napi.h"
  92. #include "uring_cmd.h"
  93. #include "msg_ring.h"
  94. #include "memmap.h"
  95. #include "timeout.h"
  96. #include "poll.h"
  97. #include "rw.h"
  98. #include "alloc_cache.h"
  99. #include "eventfd.h"
  100. #define IORING_MAX_ENTRIES 32768
  101. #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
  102. #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
  103. IOSQE_IO_HARDLINK | IOSQE_ASYNC)
  104. #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
  105. IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
  106. #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
  107. REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
  108. REQ_F_ASYNC_DATA)
  109. #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
  110. IO_REQ_CLEAN_FLAGS)
  111. #define IO_TCTX_REFS_CACHE_NR (1U << 10)
  112. #define IO_COMPL_BATCH 32
  113. #define IO_REQ_ALLOC_BATCH 8
  114. struct io_defer_entry {
  115. struct list_head list;
  116. struct io_kiocb *req;
  117. u32 seq;
  118. };
  119. /* requests with any of those set should undergo io_disarm_next() */
  120. #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
  121. #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
  122. /*
  123. * No waiters. It's larger than any valid value of the tw counter
  124. * so that tests against ->cq_wait_nr would fail and skip wake_up().
  125. */
  126. #define IO_CQ_WAKE_INIT (-1U)
  127. /* Forced wake up if there is a waiter regardless of ->cq_wait_nr */
  128. #define IO_CQ_WAKE_FORCE (IO_CQ_WAKE_INIT >> 1)
  129. static bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
  130. struct task_struct *task,
  131. bool cancel_all);
  132. static void io_queue_sqe(struct io_kiocb *req);
  133. struct kmem_cache *req_cachep;
  134. static struct workqueue_struct *iou_wq __ro_after_init;
  135. static int __read_mostly sysctl_io_uring_disabled;
  136. static int __read_mostly sysctl_io_uring_group = -1;
  137. #ifdef CONFIG_SYSCTL
  138. static struct ctl_table kernel_io_uring_disabled_table[] = {
  139. {
  140. .procname = "io_uring_disabled",
  141. .data = &sysctl_io_uring_disabled,
  142. .maxlen = sizeof(sysctl_io_uring_disabled),
  143. .mode = 0644,
  144. .proc_handler = proc_dointvec_minmax,
  145. .extra1 = SYSCTL_ZERO,
  146. .extra2 = SYSCTL_TWO,
  147. },
  148. {
  149. .procname = "io_uring_group",
  150. .data = &sysctl_io_uring_group,
  151. .maxlen = sizeof(gid_t),
  152. .mode = 0644,
  153. .proc_handler = proc_dointvec,
  154. },
  155. };
  156. #endif
  157. static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
  158. {
  159. return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
  160. }
  161. static inline unsigned int __io_cqring_events_user(struct io_ring_ctx *ctx)
  162. {
  163. return READ_ONCE(ctx->rings->cq.tail) - READ_ONCE(ctx->rings->cq.head);
  164. }
  165. static bool io_match_linked(struct io_kiocb *head)
  166. {
  167. struct io_kiocb *req;
  168. io_for_each_link(req, head) {
  169. if (req->flags & REQ_F_INFLIGHT)
  170. return true;
  171. }
  172. return false;
  173. }
  174. /*
  175. * As io_match_task() but protected against racing with linked timeouts.
  176. * User must not hold timeout_lock.
  177. */
  178. bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
  179. bool cancel_all)
  180. {
  181. bool matched;
  182. if (task && head->task != task)
  183. return false;
  184. if (cancel_all)
  185. return true;
  186. if (head->flags & REQ_F_LINK_TIMEOUT) {
  187. struct io_ring_ctx *ctx = head->ctx;
  188. /* protect against races with linked timeouts */
  189. spin_lock_irq(&ctx->timeout_lock);
  190. matched = io_match_linked(head);
  191. spin_unlock_irq(&ctx->timeout_lock);
  192. } else {
  193. matched = io_match_linked(head);
  194. }
  195. return matched;
  196. }
  197. static inline void req_fail_link_node(struct io_kiocb *req, int res)
  198. {
  199. req_set_fail(req);
  200. io_req_set_res(req, res, 0);
  201. }
  202. static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
  203. {
  204. wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
  205. }
  206. static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
  207. {
  208. struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
  209. complete(&ctx->ref_comp);
  210. }
  211. static __cold void io_fallback_req_func(struct work_struct *work)
  212. {
  213. struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
  214. fallback_work.work);
  215. struct llist_node *node = llist_del_all(&ctx->fallback_llist);
  216. struct io_kiocb *req, *tmp;
  217. struct io_tw_state ts = {};
  218. percpu_ref_get(&ctx->refs);
  219. mutex_lock(&ctx->uring_lock);
  220. llist_for_each_entry_safe(req, tmp, node, io_task_work.node)
  221. req->io_task_work.func(req, &ts);
  222. io_submit_flush_completions(ctx);
  223. mutex_unlock(&ctx->uring_lock);
  224. percpu_ref_put(&ctx->refs);
  225. }
  226. static int io_alloc_hash_table(struct io_hash_table *table, unsigned bits)
  227. {
  228. unsigned hash_buckets = 1U << bits;
  229. size_t hash_size = hash_buckets * sizeof(table->hbs[0]);
  230. table->hbs = kmalloc(hash_size, GFP_KERNEL);
  231. if (!table->hbs)
  232. return -ENOMEM;
  233. table->hash_bits = bits;
  234. init_hash_table(table, hash_buckets);
  235. return 0;
  236. }
  237. static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
  238. {
  239. struct io_ring_ctx *ctx;
  240. int hash_bits;
  241. bool ret;
  242. ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
  243. if (!ctx)
  244. return NULL;
  245. xa_init(&ctx->io_bl_xa);
  246. /*
  247. * Use 5 bits less than the max cq entries, that should give us around
  248. * 32 entries per hash list if totally full and uniformly spread, but
  249. * don't keep too many buckets to not overconsume memory.
  250. */
  251. hash_bits = ilog2(p->cq_entries) - 5;
  252. hash_bits = clamp(hash_bits, 1, 8);
  253. if (io_alloc_hash_table(&ctx->cancel_table, hash_bits))
  254. goto err;
  255. if (io_alloc_hash_table(&ctx->cancel_table_locked, hash_bits))
  256. goto err;
  257. if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
  258. 0, GFP_KERNEL))
  259. goto err;
  260. ctx->flags = p->flags;
  261. atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT);
  262. init_waitqueue_head(&ctx->sqo_sq_wait);
  263. INIT_LIST_HEAD(&ctx->sqd_list);
  264. INIT_LIST_HEAD(&ctx->cq_overflow_list);
  265. INIT_LIST_HEAD(&ctx->io_buffers_cache);
  266. ret = io_alloc_cache_init(&ctx->rsrc_node_cache, IO_NODE_ALLOC_CACHE_MAX,
  267. sizeof(struct io_rsrc_node));
  268. ret |= io_alloc_cache_init(&ctx->apoll_cache, IO_POLL_ALLOC_CACHE_MAX,
  269. sizeof(struct async_poll));
  270. ret |= io_alloc_cache_init(&ctx->netmsg_cache, IO_ALLOC_CACHE_MAX,
  271. sizeof(struct io_async_msghdr));
  272. ret |= io_alloc_cache_init(&ctx->rw_cache, IO_ALLOC_CACHE_MAX,
  273. sizeof(struct io_async_rw));
  274. ret |= io_alloc_cache_init(&ctx->uring_cache, IO_ALLOC_CACHE_MAX,
  275. sizeof(struct uring_cache));
  276. spin_lock_init(&ctx->msg_lock);
  277. ret |= io_alloc_cache_init(&ctx->msg_cache, IO_ALLOC_CACHE_MAX,
  278. sizeof(struct io_kiocb));
  279. ret |= io_futex_cache_init(ctx);
  280. if (ret)
  281. goto free_ref;
  282. init_completion(&ctx->ref_comp);
  283. xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
  284. mutex_init(&ctx->uring_lock);
  285. init_waitqueue_head(&ctx->cq_wait);
  286. init_waitqueue_head(&ctx->poll_wq);
  287. init_waitqueue_head(&ctx->rsrc_quiesce_wq);
  288. spin_lock_init(&ctx->completion_lock);
  289. spin_lock_init(&ctx->timeout_lock);
  290. INIT_WQ_LIST(&ctx->iopoll_list);
  291. INIT_LIST_HEAD(&ctx->io_buffers_comp);
  292. INIT_LIST_HEAD(&ctx->defer_list);
  293. INIT_LIST_HEAD(&ctx->timeout_list);
  294. INIT_LIST_HEAD(&ctx->ltimeout_list);
  295. INIT_LIST_HEAD(&ctx->rsrc_ref_list);
  296. init_llist_head(&ctx->work_llist);
  297. INIT_LIST_HEAD(&ctx->tctx_list);
  298. ctx->submit_state.free_list.next = NULL;
  299. INIT_HLIST_HEAD(&ctx->waitid_list);
  300. #ifdef CONFIG_FUTEX
  301. INIT_HLIST_HEAD(&ctx->futex_list);
  302. #endif
  303. INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
  304. INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
  305. INIT_HLIST_HEAD(&ctx->cancelable_uring_cmd);
  306. io_napi_init(ctx);
  307. return ctx;
  308. free_ref:
  309. percpu_ref_exit(&ctx->refs);
  310. err:
  311. io_alloc_cache_free(&ctx->rsrc_node_cache, kfree);
  312. io_alloc_cache_free(&ctx->apoll_cache, kfree);
  313. io_alloc_cache_free(&ctx->netmsg_cache, io_netmsg_cache_free);
  314. io_alloc_cache_free(&ctx->rw_cache, io_rw_cache_free);
  315. io_alloc_cache_free(&ctx->uring_cache, kfree);
  316. io_alloc_cache_free(&ctx->msg_cache, io_msg_cache_free);
  317. io_futex_cache_free(ctx);
  318. kfree(ctx->cancel_table.hbs);
  319. kfree(ctx->cancel_table_locked.hbs);
  320. xa_destroy(&ctx->io_bl_xa);
  321. kfree(ctx);
  322. return NULL;
  323. }
  324. static void io_account_cq_overflow(struct io_ring_ctx *ctx)
  325. {
  326. struct io_rings *r = ctx->rings;
  327. WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
  328. ctx->cq_extra--;
  329. }
  330. static bool req_need_defer(struct io_kiocb *req, u32 seq)
  331. {
  332. if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
  333. struct io_ring_ctx *ctx = req->ctx;
  334. return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
  335. }
  336. return false;
  337. }
  338. static void io_clean_op(struct io_kiocb *req)
  339. {
  340. if (req->flags & REQ_F_BUFFER_SELECTED) {
  341. spin_lock(&req->ctx->completion_lock);
  342. io_kbuf_drop(req);
  343. spin_unlock(&req->ctx->completion_lock);
  344. }
  345. if (req->flags & REQ_F_NEED_CLEANUP) {
  346. const struct io_cold_def *def = &io_cold_defs[req->opcode];
  347. if (def->cleanup)
  348. def->cleanup(req);
  349. }
  350. if ((req->flags & REQ_F_POLLED) && req->apoll) {
  351. kfree(req->apoll->double_poll);
  352. kfree(req->apoll);
  353. req->apoll = NULL;
  354. }
  355. if (req->flags & REQ_F_INFLIGHT) {
  356. struct io_uring_task *tctx = req->task->io_uring;
  357. atomic_dec(&tctx->inflight_tracked);
  358. }
  359. if (req->flags & REQ_F_CREDS)
  360. put_cred(req->creds);
  361. if (req->flags & REQ_F_ASYNC_DATA) {
  362. kfree(req->async_data);
  363. req->async_data = NULL;
  364. }
  365. req->flags &= ~IO_REQ_CLEAN_FLAGS;
  366. }
  367. static inline void io_req_track_inflight(struct io_kiocb *req)
  368. {
  369. if (!(req->flags & REQ_F_INFLIGHT)) {
  370. req->flags |= REQ_F_INFLIGHT;
  371. atomic_inc(&req->task->io_uring->inflight_tracked);
  372. }
  373. }
  374. static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
  375. {
  376. if (WARN_ON_ONCE(!req->link))
  377. return NULL;
  378. req->flags &= ~REQ_F_ARM_LTIMEOUT;
  379. req->flags |= REQ_F_LINK_TIMEOUT;
  380. /* linked timeouts should have two refs once prep'ed */
  381. io_req_set_refcount(req);
  382. __io_req_set_refcount(req->link, 2);
  383. return req->link;
  384. }
  385. static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
  386. {
  387. if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
  388. return NULL;
  389. return __io_prep_linked_timeout(req);
  390. }
  391. static noinline void __io_arm_ltimeout(struct io_kiocb *req)
  392. {
  393. io_queue_linked_timeout(__io_prep_linked_timeout(req));
  394. }
  395. static inline void io_arm_ltimeout(struct io_kiocb *req)
  396. {
  397. if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
  398. __io_arm_ltimeout(req);
  399. }
  400. static void io_prep_async_work(struct io_kiocb *req)
  401. {
  402. const struct io_issue_def *def = &io_issue_defs[req->opcode];
  403. struct io_ring_ctx *ctx = req->ctx;
  404. if (!(req->flags & REQ_F_CREDS)) {
  405. req->flags |= REQ_F_CREDS;
  406. req->creds = get_current_cred();
  407. }
  408. req->work.list.next = NULL;
  409. atomic_set(&req->work.flags, 0);
  410. if (req->flags & REQ_F_FORCE_ASYNC)
  411. atomic_or(IO_WQ_WORK_CONCURRENT, &req->work.flags);
  412. if (req->file && !(req->flags & REQ_F_FIXED_FILE))
  413. req->flags |= io_file_get_flags(req->file);
  414. if (req->file && (req->flags & REQ_F_ISREG)) {
  415. bool should_hash = def->hash_reg_file;
  416. /* don't serialize this request if the fs doesn't need it */
  417. if (should_hash && (req->file->f_flags & O_DIRECT) &&
  418. (req->file->f_op->fop_flags & FOP_DIO_PARALLEL_WRITE))
  419. should_hash = false;
  420. if (should_hash || (ctx->flags & IORING_SETUP_IOPOLL))
  421. io_wq_hash_work(&req->work, file_inode(req->file));
  422. } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
  423. if (def->unbound_nonreg_file)
  424. atomic_or(IO_WQ_WORK_UNBOUND, &req->work.flags);
  425. }
  426. }
  427. static void io_prep_async_link(struct io_kiocb *req)
  428. {
  429. struct io_kiocb *cur;
  430. if (req->flags & REQ_F_LINK_TIMEOUT) {
  431. struct io_ring_ctx *ctx = req->ctx;
  432. spin_lock_irq(&ctx->timeout_lock);
  433. io_for_each_link(cur, req)
  434. io_prep_async_work(cur);
  435. spin_unlock_irq(&ctx->timeout_lock);
  436. } else {
  437. io_for_each_link(cur, req)
  438. io_prep_async_work(cur);
  439. }
  440. }
  441. static void io_queue_iowq(struct io_kiocb *req)
  442. {
  443. struct io_kiocb *link = io_prep_linked_timeout(req);
  444. struct io_uring_task *tctx = req->task->io_uring;
  445. BUG_ON(!tctx);
  446. if ((current->flags & PF_KTHREAD) || !tctx->io_wq) {
  447. io_req_task_queue_fail(req, -ECANCELED);
  448. return;
  449. }
  450. /* init ->work of the whole link before punting */
  451. io_prep_async_link(req);
  452. /*
  453. * Not expected to happen, but if we do have a bug where this _can_
  454. * happen, catch it here and ensure the request is marked as
  455. * canceled. That will make io-wq go through the usual work cancel
  456. * procedure rather than attempt to run this request (or create a new
  457. * worker for it).
  458. */
  459. if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
  460. atomic_or(IO_WQ_WORK_CANCEL, &req->work.flags);
  461. trace_io_uring_queue_async_work(req, io_wq_is_hashed(&req->work));
  462. io_wq_enqueue(tctx->io_wq, &req->work);
  463. if (link)
  464. io_queue_linked_timeout(link);
  465. }
  466. static void io_req_queue_iowq_tw(struct io_kiocb *req, struct io_tw_state *ts)
  467. {
  468. io_queue_iowq(req);
  469. }
  470. void io_req_queue_iowq(struct io_kiocb *req)
  471. {
  472. req->io_task_work.func = io_req_queue_iowq_tw;
  473. io_req_task_work_add(req);
  474. }
  475. static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
  476. {
  477. while (!list_empty(&ctx->defer_list)) {
  478. struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
  479. struct io_defer_entry, list);
  480. if (req_need_defer(de->req, de->seq))
  481. break;
  482. list_del_init(&de->list);
  483. io_req_task_queue(de->req);
  484. kfree(de);
  485. }
  486. }
  487. void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
  488. {
  489. if (ctx->poll_activated)
  490. io_poll_wq_wake(ctx);
  491. if (ctx->off_timeout_used)
  492. io_flush_timeouts(ctx);
  493. if (ctx->drain_active) {
  494. spin_lock(&ctx->completion_lock);
  495. io_queue_deferred(ctx);
  496. spin_unlock(&ctx->completion_lock);
  497. }
  498. if (ctx->has_evfd)
  499. io_eventfd_flush_signal(ctx);
  500. }
  501. static inline void __io_cq_lock(struct io_ring_ctx *ctx)
  502. {
  503. if (!ctx->lockless_cq)
  504. spin_lock(&ctx->completion_lock);
  505. }
  506. static inline void io_cq_lock(struct io_ring_ctx *ctx)
  507. __acquires(ctx->completion_lock)
  508. {
  509. spin_lock(&ctx->completion_lock);
  510. }
  511. static inline void __io_cq_unlock_post(struct io_ring_ctx *ctx)
  512. {
  513. io_commit_cqring(ctx);
  514. if (!ctx->task_complete) {
  515. if (!ctx->lockless_cq)
  516. spin_unlock(&ctx->completion_lock);
  517. /* IOPOLL rings only need to wake up if it's also SQPOLL */
  518. if (!ctx->syscall_iopoll)
  519. io_cqring_wake(ctx);
  520. }
  521. io_commit_cqring_flush(ctx);
  522. }
  523. static void io_cq_unlock_post(struct io_ring_ctx *ctx)
  524. __releases(ctx->completion_lock)
  525. {
  526. io_commit_cqring(ctx);
  527. spin_unlock(&ctx->completion_lock);
  528. io_cqring_wake(ctx);
  529. io_commit_cqring_flush(ctx);
  530. }
  531. static void __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool dying)
  532. {
  533. size_t cqe_size = sizeof(struct io_uring_cqe);
  534. lockdep_assert_held(&ctx->uring_lock);
  535. /* don't abort if we're dying, entries must get freed */
  536. if (!dying && __io_cqring_events(ctx) == ctx->cq_entries)
  537. return;
  538. if (ctx->flags & IORING_SETUP_CQE32)
  539. cqe_size <<= 1;
  540. io_cq_lock(ctx);
  541. while (!list_empty(&ctx->cq_overflow_list)) {
  542. struct io_uring_cqe *cqe;
  543. struct io_overflow_cqe *ocqe;
  544. ocqe = list_first_entry(&ctx->cq_overflow_list,
  545. struct io_overflow_cqe, list);
  546. if (!dying) {
  547. if (!io_get_cqe_overflow(ctx, &cqe, true))
  548. break;
  549. memcpy(cqe, &ocqe->cqe, cqe_size);
  550. }
  551. list_del(&ocqe->list);
  552. kfree(ocqe);
  553. /*
  554. * For silly syzbot cases that deliberately overflow by huge
  555. * amounts, check if we need to resched and drop and
  556. * reacquire the locks if so. Nothing real would ever hit this.
  557. * Ideally we'd have a non-posting unlock for this, but hard
  558. * to care for a non-real case.
  559. */
  560. if (need_resched()) {
  561. io_cq_unlock_post(ctx);
  562. mutex_unlock(&ctx->uring_lock);
  563. cond_resched();
  564. mutex_lock(&ctx->uring_lock);
  565. io_cq_lock(ctx);
  566. }
  567. }
  568. if (list_empty(&ctx->cq_overflow_list)) {
  569. clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
  570. atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
  571. }
  572. io_cq_unlock_post(ctx);
  573. }
  574. static void io_cqring_overflow_kill(struct io_ring_ctx *ctx)
  575. {
  576. if (ctx->rings)
  577. __io_cqring_overflow_flush(ctx, true);
  578. }
  579. static void io_cqring_do_overflow_flush(struct io_ring_ctx *ctx)
  580. {
  581. mutex_lock(&ctx->uring_lock);
  582. __io_cqring_overflow_flush(ctx, false);
  583. mutex_unlock(&ctx->uring_lock);
  584. }
  585. /* can be called by any task */
  586. static void io_put_task_remote(struct task_struct *task)
  587. {
  588. struct io_uring_task *tctx = task->io_uring;
  589. percpu_counter_sub(&tctx->inflight, 1);
  590. if (unlikely(atomic_read(&tctx->in_cancel)))
  591. wake_up(&tctx->wait);
  592. put_task_struct(task);
  593. }
  594. /* used by a task to put its own references */
  595. static void io_put_task_local(struct task_struct *task)
  596. {
  597. task->io_uring->cached_refs++;
  598. }
  599. /* must to be called somewhat shortly after putting a request */
  600. static inline void io_put_task(struct task_struct *task)
  601. {
  602. if (likely(task == current))
  603. io_put_task_local(task);
  604. else
  605. io_put_task_remote(task);
  606. }
  607. void io_task_refs_refill(struct io_uring_task *tctx)
  608. {
  609. unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
  610. percpu_counter_add(&tctx->inflight, refill);
  611. refcount_add(refill, &current->usage);
  612. tctx->cached_refs += refill;
  613. }
  614. static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
  615. {
  616. struct io_uring_task *tctx = task->io_uring;
  617. unsigned int refs = tctx->cached_refs;
  618. if (refs) {
  619. tctx->cached_refs = 0;
  620. percpu_counter_sub(&tctx->inflight, refs);
  621. put_task_struct_many(task, refs);
  622. }
  623. }
  624. static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
  625. s32 res, u32 cflags, u64 extra1, u64 extra2)
  626. {
  627. struct io_overflow_cqe *ocqe;
  628. size_t ocq_size = sizeof(struct io_overflow_cqe);
  629. bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
  630. lockdep_assert_held(&ctx->completion_lock);
  631. if (is_cqe32)
  632. ocq_size += sizeof(struct io_uring_cqe);
  633. ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
  634. trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
  635. if (!ocqe) {
  636. /*
  637. * If we're in ring overflow flush mode, or in task cancel mode,
  638. * or cannot allocate an overflow entry, then we need to drop it
  639. * on the floor.
  640. */
  641. io_account_cq_overflow(ctx);
  642. set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
  643. return false;
  644. }
  645. if (list_empty(&ctx->cq_overflow_list)) {
  646. set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
  647. atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
  648. }
  649. ocqe->cqe.user_data = user_data;
  650. ocqe->cqe.res = res;
  651. ocqe->cqe.flags = cflags;
  652. if (is_cqe32) {
  653. ocqe->cqe.big_cqe[0] = extra1;
  654. ocqe->cqe.big_cqe[1] = extra2;
  655. }
  656. list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
  657. return true;
  658. }
  659. static void io_req_cqe_overflow(struct io_kiocb *req)
  660. {
  661. io_cqring_event_overflow(req->ctx, req->cqe.user_data,
  662. req->cqe.res, req->cqe.flags,
  663. req->big_cqe.extra1, req->big_cqe.extra2);
  664. memset(&req->big_cqe, 0, sizeof(req->big_cqe));
  665. }
  666. /*
  667. * writes to the cq entry need to come after reading head; the
  668. * control dependency is enough as we're using WRITE_ONCE to
  669. * fill the cq entry
  670. */
  671. bool io_cqe_cache_refill(struct io_ring_ctx *ctx, bool overflow)
  672. {
  673. struct io_rings *rings = ctx->rings;
  674. unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
  675. unsigned int free, queued, len;
  676. /*
  677. * Posting into the CQ when there are pending overflowed CQEs may break
  678. * ordering guarantees, which will affect links, F_MORE users and more.
  679. * Force overflow the completion.
  680. */
  681. if (!overflow && (ctx->check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT)))
  682. return false;
  683. /* userspace may cheat modifying the tail, be safe and do min */
  684. queued = min(__io_cqring_events(ctx), ctx->cq_entries);
  685. free = ctx->cq_entries - queued;
  686. /* we need a contiguous range, limit based on the current array offset */
  687. len = min(free, ctx->cq_entries - off);
  688. if (!len)
  689. return false;
  690. if (ctx->flags & IORING_SETUP_CQE32) {
  691. off <<= 1;
  692. len <<= 1;
  693. }
  694. ctx->cqe_cached = &rings->cqes[off];
  695. ctx->cqe_sentinel = ctx->cqe_cached + len;
  696. return true;
  697. }
  698. static bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res,
  699. u32 cflags)
  700. {
  701. struct io_uring_cqe *cqe;
  702. ctx->cq_extra++;
  703. /*
  704. * If we can't get a cq entry, userspace overflowed the
  705. * submission (by quite a lot). Increment the overflow count in
  706. * the ring.
  707. */
  708. if (likely(io_get_cqe(ctx, &cqe))) {
  709. trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
  710. WRITE_ONCE(cqe->user_data, user_data);
  711. WRITE_ONCE(cqe->res, res);
  712. WRITE_ONCE(cqe->flags, cflags);
  713. if (ctx->flags & IORING_SETUP_CQE32) {
  714. WRITE_ONCE(cqe->big_cqe[0], 0);
  715. WRITE_ONCE(cqe->big_cqe[1], 0);
  716. }
  717. return true;
  718. }
  719. return false;
  720. }
  721. static bool __io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res,
  722. u32 cflags)
  723. {
  724. bool filled;
  725. filled = io_fill_cqe_aux(ctx, user_data, res, cflags);
  726. if (!filled)
  727. filled = io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
  728. return filled;
  729. }
  730. bool io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
  731. {
  732. bool filled;
  733. io_cq_lock(ctx);
  734. filled = __io_post_aux_cqe(ctx, user_data, res, cflags);
  735. io_cq_unlock_post(ctx);
  736. return filled;
  737. }
  738. /*
  739. * Must be called from inline task_work so we now a flush will happen later,
  740. * and obviously with ctx->uring_lock held (tw always has that).
  741. */
  742. void io_add_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
  743. {
  744. if (!io_fill_cqe_aux(ctx, user_data, res, cflags)) {
  745. spin_lock(&ctx->completion_lock);
  746. io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
  747. spin_unlock(&ctx->completion_lock);
  748. }
  749. ctx->submit_state.cq_flush = true;
  750. }
  751. /*
  752. * A helper for multishot requests posting additional CQEs.
  753. * Should only be used from a task_work including IO_URING_F_MULTISHOT.
  754. */
  755. bool io_req_post_cqe(struct io_kiocb *req, s32 res, u32 cflags)
  756. {
  757. struct io_ring_ctx *ctx = req->ctx;
  758. bool posted;
  759. lockdep_assert(!io_wq_current_is_worker());
  760. lockdep_assert_held(&ctx->uring_lock);
  761. __io_cq_lock(ctx);
  762. posted = io_fill_cqe_aux(ctx, req->cqe.user_data, res, cflags);
  763. ctx->submit_state.cq_flush = true;
  764. __io_cq_unlock_post(ctx);
  765. return posted;
  766. }
  767. static void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
  768. {
  769. struct io_ring_ctx *ctx = req->ctx;
  770. /*
  771. * All execution paths but io-wq use the deferred completions by
  772. * passing IO_URING_F_COMPLETE_DEFER and thus should not end up here.
  773. */
  774. if (WARN_ON_ONCE(!(issue_flags & IO_URING_F_IOWQ)))
  775. return;
  776. /*
  777. * Handle special CQ sync cases via task_work. DEFER_TASKRUN requires
  778. * the submitter task context, IOPOLL protects with uring_lock.
  779. */
  780. if (ctx->task_complete || (ctx->flags & IORING_SETUP_IOPOLL)) {
  781. req->io_task_work.func = io_req_task_complete;
  782. io_req_task_work_add(req);
  783. return;
  784. }
  785. io_cq_lock(ctx);
  786. if (!(req->flags & REQ_F_CQE_SKIP)) {
  787. if (!io_fill_cqe_req(ctx, req))
  788. io_req_cqe_overflow(req);
  789. }
  790. io_cq_unlock_post(ctx);
  791. /*
  792. * We don't free the request here because we know it's called from
  793. * io-wq only, which holds a reference, so it cannot be the last put.
  794. */
  795. req_ref_put(req);
  796. }
  797. void io_req_defer_failed(struct io_kiocb *req, s32 res)
  798. __must_hold(&ctx->uring_lock)
  799. {
  800. const struct io_cold_def *def = &io_cold_defs[req->opcode];
  801. lockdep_assert_held(&req->ctx->uring_lock);
  802. req_set_fail(req);
  803. io_req_set_res(req, res, io_put_kbuf(req, res, IO_URING_F_UNLOCKED));
  804. if (def->fail)
  805. def->fail(req);
  806. io_req_complete_defer(req);
  807. }
  808. /*
  809. * Don't initialise the fields below on every allocation, but do that in
  810. * advance and keep them valid across allocations.
  811. */
  812. static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
  813. {
  814. req->ctx = ctx;
  815. req->link = NULL;
  816. req->async_data = NULL;
  817. /* not necessary, but safer to zero */
  818. memset(&req->cqe, 0, sizeof(req->cqe));
  819. memset(&req->big_cqe, 0, sizeof(req->big_cqe));
  820. }
  821. /*
  822. * A request might get retired back into the request caches even before opcode
  823. * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
  824. * Because of that, io_alloc_req() should be called only under ->uring_lock
  825. * and with extra caution to not get a request that is still worked on.
  826. */
  827. __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
  828. __must_hold(&ctx->uring_lock)
  829. {
  830. gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
  831. void *reqs[IO_REQ_ALLOC_BATCH];
  832. int ret;
  833. ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
  834. /*
  835. * Bulk alloc is all-or-nothing. If we fail to get a batch,
  836. * retry single alloc to be on the safe side.
  837. */
  838. if (unlikely(ret <= 0)) {
  839. reqs[0] = kmem_cache_alloc(req_cachep, gfp);
  840. if (!reqs[0])
  841. return false;
  842. ret = 1;
  843. }
  844. percpu_ref_get_many(&ctx->refs, ret);
  845. while (ret--) {
  846. struct io_kiocb *req = reqs[ret];
  847. io_preinit_req(req, ctx);
  848. io_req_add_to_cache(req, ctx);
  849. }
  850. return true;
  851. }
  852. __cold void io_free_req(struct io_kiocb *req)
  853. {
  854. /* refs were already put, restore them for io_req_task_complete() */
  855. req->flags &= ~REQ_F_REFCOUNT;
  856. /* we only want to free it, don't post CQEs */
  857. req->flags |= REQ_F_CQE_SKIP;
  858. req->io_task_work.func = io_req_task_complete;
  859. io_req_task_work_add(req);
  860. }
  861. static void __io_req_find_next_prep(struct io_kiocb *req)
  862. {
  863. struct io_ring_ctx *ctx = req->ctx;
  864. spin_lock(&ctx->completion_lock);
  865. io_disarm_next(req);
  866. spin_unlock(&ctx->completion_lock);
  867. }
  868. static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
  869. {
  870. struct io_kiocb *nxt;
  871. /*
  872. * If LINK is set, we have dependent requests in this chain. If we
  873. * didn't fail this request, queue the first one up, moving any other
  874. * dependencies to the next request. In case of failure, fail the rest
  875. * of the chain.
  876. */
  877. if (unlikely(req->flags & IO_DISARM_MASK))
  878. __io_req_find_next_prep(req);
  879. nxt = req->link;
  880. req->link = NULL;
  881. return nxt;
  882. }
  883. static void ctx_flush_and_put(struct io_ring_ctx *ctx, struct io_tw_state *ts)
  884. {
  885. if (!ctx)
  886. return;
  887. if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
  888. atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
  889. io_submit_flush_completions(ctx);
  890. mutex_unlock(&ctx->uring_lock);
  891. percpu_ref_put(&ctx->refs);
  892. }
  893. /*
  894. * Run queued task_work, returning the number of entries processed in *count.
  895. * If more entries than max_entries are available, stop processing once this
  896. * is reached and return the rest of the list.
  897. */
  898. struct llist_node *io_handle_tw_list(struct llist_node *node,
  899. unsigned int *count,
  900. unsigned int max_entries)
  901. {
  902. struct io_ring_ctx *ctx = NULL;
  903. struct io_tw_state ts = { };
  904. do {
  905. struct llist_node *next = node->next;
  906. struct io_kiocb *req = container_of(node, struct io_kiocb,
  907. io_task_work.node);
  908. if (req->ctx != ctx) {
  909. ctx_flush_and_put(ctx, &ts);
  910. ctx = req->ctx;
  911. mutex_lock(&ctx->uring_lock);
  912. percpu_ref_get(&ctx->refs);
  913. }
  914. INDIRECT_CALL_2(req->io_task_work.func,
  915. io_poll_task_func, io_req_rw_complete,
  916. req, &ts);
  917. node = next;
  918. (*count)++;
  919. if (unlikely(need_resched())) {
  920. ctx_flush_and_put(ctx, &ts);
  921. ctx = NULL;
  922. cond_resched();
  923. }
  924. } while (node && *count < max_entries);
  925. ctx_flush_and_put(ctx, &ts);
  926. return node;
  927. }
  928. /**
  929. * io_llist_xchg - swap all entries in a lock-less list
  930. * @head: the head of lock-less list to delete all entries
  931. * @new: new entry as the head of the list
  932. *
  933. * If list is empty, return NULL, otherwise, return the pointer to the first entry.
  934. * The order of entries returned is from the newest to the oldest added one.
  935. */
  936. static inline struct llist_node *io_llist_xchg(struct llist_head *head,
  937. struct llist_node *new)
  938. {
  939. return xchg(&head->first, new);
  940. }
  941. static __cold void io_fallback_tw(struct io_uring_task *tctx, bool sync)
  942. {
  943. struct llist_node *node = llist_del_all(&tctx->task_list);
  944. struct io_ring_ctx *last_ctx = NULL;
  945. struct io_kiocb *req;
  946. while (node) {
  947. req = container_of(node, struct io_kiocb, io_task_work.node);
  948. node = node->next;
  949. if (sync && last_ctx != req->ctx) {
  950. if (last_ctx) {
  951. flush_delayed_work(&last_ctx->fallback_work);
  952. percpu_ref_put(&last_ctx->refs);
  953. }
  954. last_ctx = req->ctx;
  955. percpu_ref_get(&last_ctx->refs);
  956. }
  957. if (llist_add(&req->io_task_work.node,
  958. &req->ctx->fallback_llist))
  959. schedule_delayed_work(&req->ctx->fallback_work, 1);
  960. }
  961. if (last_ctx) {
  962. flush_delayed_work(&last_ctx->fallback_work);
  963. percpu_ref_put(&last_ctx->refs);
  964. }
  965. }
  966. struct llist_node *tctx_task_work_run(struct io_uring_task *tctx,
  967. unsigned int max_entries,
  968. unsigned int *count)
  969. {
  970. struct llist_node *node;
  971. if (unlikely(current->flags & PF_EXITING)) {
  972. io_fallback_tw(tctx, true);
  973. return NULL;
  974. }
  975. node = llist_del_all(&tctx->task_list);
  976. if (node) {
  977. node = llist_reverse_order(node);
  978. node = io_handle_tw_list(node, count, max_entries);
  979. }
  980. /* relaxed read is enough as only the task itself sets ->in_cancel */
  981. if (unlikely(atomic_read(&tctx->in_cancel)))
  982. io_uring_drop_tctx_refs(current);
  983. trace_io_uring_task_work_run(tctx, *count);
  984. return node;
  985. }
  986. void tctx_task_work(struct callback_head *cb)
  987. {
  988. struct io_uring_task *tctx;
  989. struct llist_node *ret;
  990. unsigned int count = 0;
  991. tctx = container_of(cb, struct io_uring_task, task_work);
  992. ret = tctx_task_work_run(tctx, UINT_MAX, &count);
  993. /* can't happen */
  994. WARN_ON_ONCE(ret);
  995. }
  996. static inline void io_req_local_work_add(struct io_kiocb *req,
  997. struct io_ring_ctx *ctx,
  998. unsigned flags)
  999. {
  1000. unsigned nr_wait, nr_tw, nr_tw_prev;
  1001. struct llist_node *head;
  1002. /* See comment above IO_CQ_WAKE_INIT */
  1003. BUILD_BUG_ON(IO_CQ_WAKE_FORCE <= IORING_MAX_CQ_ENTRIES);
  1004. /*
  1005. * We don't know how many reuqests is there in the link and whether
  1006. * they can even be queued lazily, fall back to non-lazy.
  1007. */
  1008. if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
  1009. flags &= ~IOU_F_TWQ_LAZY_WAKE;
  1010. guard(rcu)();
  1011. head = READ_ONCE(ctx->work_llist.first);
  1012. do {
  1013. nr_tw_prev = 0;
  1014. if (head) {
  1015. struct io_kiocb *first_req = container_of(head,
  1016. struct io_kiocb,
  1017. io_task_work.node);
  1018. /*
  1019. * Might be executed at any moment, rely on
  1020. * SLAB_TYPESAFE_BY_RCU to keep it alive.
  1021. */
  1022. nr_tw_prev = READ_ONCE(first_req->nr_tw);
  1023. }
  1024. /*
  1025. * Theoretically, it can overflow, but that's fine as one of
  1026. * previous adds should've tried to wake the task.
  1027. */
  1028. nr_tw = nr_tw_prev + 1;
  1029. if (!(flags & IOU_F_TWQ_LAZY_WAKE))
  1030. nr_tw = IO_CQ_WAKE_FORCE;
  1031. req->nr_tw = nr_tw;
  1032. req->io_task_work.node.next = head;
  1033. } while (!try_cmpxchg(&ctx->work_llist.first, &head,
  1034. &req->io_task_work.node));
  1035. /*
  1036. * cmpxchg implies a full barrier, which pairs with the barrier
  1037. * in set_current_state() on the io_cqring_wait() side. It's used
  1038. * to ensure that either we see updated ->cq_wait_nr, or waiters
  1039. * going to sleep will observe the work added to the list, which
  1040. * is similar to the wait/wawke task state sync.
  1041. */
  1042. if (!head) {
  1043. if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
  1044. atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
  1045. if (ctx->has_evfd)
  1046. io_eventfd_signal(ctx);
  1047. }
  1048. nr_wait = atomic_read(&ctx->cq_wait_nr);
  1049. /* not enough or no one is waiting */
  1050. if (nr_tw < nr_wait)
  1051. return;
  1052. /* the previous add has already woken it up */
  1053. if (nr_tw_prev >= nr_wait)
  1054. return;
  1055. wake_up_state(ctx->submitter_task, TASK_INTERRUPTIBLE);
  1056. }
  1057. static void io_req_normal_work_add(struct io_kiocb *req)
  1058. {
  1059. struct io_uring_task *tctx = req->task->io_uring;
  1060. struct io_ring_ctx *ctx = req->ctx;
  1061. /* task_work already pending, we're done */
  1062. if (!llist_add(&req->io_task_work.node, &tctx->task_list))
  1063. return;
  1064. if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
  1065. atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
  1066. /* SQPOLL doesn't need the task_work added, it'll run it itself */
  1067. if (ctx->flags & IORING_SETUP_SQPOLL) {
  1068. __set_notify_signal(req->task);
  1069. return;
  1070. }
  1071. if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
  1072. return;
  1073. io_fallback_tw(tctx, false);
  1074. }
  1075. void __io_req_task_work_add(struct io_kiocb *req, unsigned flags)
  1076. {
  1077. if (req->ctx->flags & IORING_SETUP_DEFER_TASKRUN)
  1078. io_req_local_work_add(req, req->ctx, flags);
  1079. else
  1080. io_req_normal_work_add(req);
  1081. }
  1082. void io_req_task_work_add_remote(struct io_kiocb *req, struct io_ring_ctx *ctx,
  1083. unsigned flags)
  1084. {
  1085. if (WARN_ON_ONCE(!(ctx->flags & IORING_SETUP_DEFER_TASKRUN)))
  1086. return;
  1087. io_req_local_work_add(req, ctx, flags);
  1088. }
  1089. static void __cold io_move_task_work_from_local(struct io_ring_ctx *ctx)
  1090. {
  1091. struct llist_node *node;
  1092. node = llist_del_all(&ctx->work_llist);
  1093. while (node) {
  1094. struct io_kiocb *req = container_of(node, struct io_kiocb,
  1095. io_task_work.node);
  1096. node = node->next;
  1097. io_req_normal_work_add(req);
  1098. }
  1099. }
  1100. static bool io_run_local_work_continue(struct io_ring_ctx *ctx, int events,
  1101. int min_events)
  1102. {
  1103. if (llist_empty(&ctx->work_llist))
  1104. return false;
  1105. if (events < min_events)
  1106. return true;
  1107. if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
  1108. atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
  1109. return false;
  1110. }
  1111. static int __io_run_local_work(struct io_ring_ctx *ctx, struct io_tw_state *ts,
  1112. int min_events)
  1113. {
  1114. struct llist_node *node;
  1115. unsigned int loops = 0;
  1116. int ret = 0;
  1117. if (WARN_ON_ONCE(ctx->submitter_task != current))
  1118. return -EEXIST;
  1119. if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
  1120. atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
  1121. again:
  1122. /*
  1123. * llists are in reverse order, flip it back the right way before
  1124. * running the pending items.
  1125. */
  1126. node = llist_reverse_order(io_llist_xchg(&ctx->work_llist, NULL));
  1127. while (node) {
  1128. struct llist_node *next = node->next;
  1129. struct io_kiocb *req = container_of(node, struct io_kiocb,
  1130. io_task_work.node);
  1131. INDIRECT_CALL_2(req->io_task_work.func,
  1132. io_poll_task_func, io_req_rw_complete,
  1133. req, ts);
  1134. ret++;
  1135. node = next;
  1136. }
  1137. loops++;
  1138. if (io_run_local_work_continue(ctx, ret, min_events))
  1139. goto again;
  1140. io_submit_flush_completions(ctx);
  1141. if (io_run_local_work_continue(ctx, ret, min_events))
  1142. goto again;
  1143. trace_io_uring_local_work_run(ctx, ret, loops);
  1144. return ret;
  1145. }
  1146. static inline int io_run_local_work_locked(struct io_ring_ctx *ctx,
  1147. int min_events)
  1148. {
  1149. struct io_tw_state ts = {};
  1150. if (llist_empty(&ctx->work_llist))
  1151. return 0;
  1152. return __io_run_local_work(ctx, &ts, min_events);
  1153. }
  1154. static int io_run_local_work(struct io_ring_ctx *ctx, int min_events)
  1155. {
  1156. struct io_tw_state ts = {};
  1157. int ret;
  1158. mutex_lock(&ctx->uring_lock);
  1159. ret = __io_run_local_work(ctx, &ts, min_events);
  1160. mutex_unlock(&ctx->uring_lock);
  1161. return ret;
  1162. }
  1163. static void io_req_task_cancel(struct io_kiocb *req, struct io_tw_state *ts)
  1164. {
  1165. io_tw_lock(req->ctx, ts);
  1166. io_req_defer_failed(req, req->cqe.res);
  1167. }
  1168. void io_req_task_submit(struct io_kiocb *req, struct io_tw_state *ts)
  1169. {
  1170. io_tw_lock(req->ctx, ts);
  1171. /* req->task == current here, checking PF_EXITING is safe */
  1172. if (unlikely(req->task->flags & PF_EXITING))
  1173. io_req_defer_failed(req, -EFAULT);
  1174. else if (req->flags & REQ_F_FORCE_ASYNC)
  1175. io_queue_iowq(req);
  1176. else
  1177. io_queue_sqe(req);
  1178. }
  1179. void io_req_task_queue_fail(struct io_kiocb *req, int ret)
  1180. {
  1181. io_req_set_res(req, ret, 0);
  1182. req->io_task_work.func = io_req_task_cancel;
  1183. io_req_task_work_add(req);
  1184. }
  1185. void io_req_task_queue(struct io_kiocb *req)
  1186. {
  1187. req->io_task_work.func = io_req_task_submit;
  1188. io_req_task_work_add(req);
  1189. }
  1190. void io_queue_next(struct io_kiocb *req)
  1191. {
  1192. struct io_kiocb *nxt = io_req_find_next(req);
  1193. if (nxt)
  1194. io_req_task_queue(nxt);
  1195. }
  1196. static void io_free_batch_list(struct io_ring_ctx *ctx,
  1197. struct io_wq_work_node *node)
  1198. __must_hold(&ctx->uring_lock)
  1199. {
  1200. do {
  1201. struct io_kiocb *req = container_of(node, struct io_kiocb,
  1202. comp_list);
  1203. if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
  1204. if (req->flags & REQ_F_REFCOUNT) {
  1205. node = req->comp_list.next;
  1206. if (!req_ref_put_and_test(req))
  1207. continue;
  1208. }
  1209. if ((req->flags & REQ_F_POLLED) && req->apoll) {
  1210. struct async_poll *apoll = req->apoll;
  1211. if (apoll->double_poll)
  1212. kfree(apoll->double_poll);
  1213. if (!io_alloc_cache_put(&ctx->apoll_cache, apoll))
  1214. kfree(apoll);
  1215. req->flags &= ~REQ_F_POLLED;
  1216. }
  1217. if (req->flags & IO_REQ_LINK_FLAGS)
  1218. io_queue_next(req);
  1219. if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
  1220. io_clean_op(req);
  1221. }
  1222. io_put_file(req);
  1223. io_put_rsrc_node(ctx, req->rsrc_node);
  1224. io_put_task(req->task);
  1225. node = req->comp_list.next;
  1226. io_req_add_to_cache(req, ctx);
  1227. } while (node);
  1228. }
  1229. void __io_submit_flush_completions(struct io_ring_ctx *ctx)
  1230. __must_hold(&ctx->uring_lock)
  1231. {
  1232. struct io_submit_state *state = &ctx->submit_state;
  1233. struct io_wq_work_node *node;
  1234. __io_cq_lock(ctx);
  1235. __wq_list_for_each(node, &state->compl_reqs) {
  1236. struct io_kiocb *req = container_of(node, struct io_kiocb,
  1237. comp_list);
  1238. if (!(req->flags & REQ_F_CQE_SKIP) &&
  1239. unlikely(!io_fill_cqe_req(ctx, req))) {
  1240. if (ctx->lockless_cq) {
  1241. spin_lock(&ctx->completion_lock);
  1242. io_req_cqe_overflow(req);
  1243. spin_unlock(&ctx->completion_lock);
  1244. } else {
  1245. io_req_cqe_overflow(req);
  1246. }
  1247. }
  1248. }
  1249. __io_cq_unlock_post(ctx);
  1250. if (!wq_list_empty(&state->compl_reqs)) {
  1251. io_free_batch_list(ctx, state->compl_reqs.first);
  1252. INIT_WQ_LIST(&state->compl_reqs);
  1253. }
  1254. ctx->submit_state.cq_flush = false;
  1255. }
  1256. static unsigned io_cqring_events(struct io_ring_ctx *ctx)
  1257. {
  1258. /* See comment at the top of this file */
  1259. smp_rmb();
  1260. return __io_cqring_events(ctx);
  1261. }
  1262. /*
  1263. * We can't just wait for polled events to come to us, we have to actively
  1264. * find and complete them.
  1265. */
  1266. static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
  1267. {
  1268. if (!(ctx->flags & IORING_SETUP_IOPOLL))
  1269. return;
  1270. mutex_lock(&ctx->uring_lock);
  1271. while (!wq_list_empty(&ctx->iopoll_list)) {
  1272. /* let it sleep and repeat later if can't complete a request */
  1273. if (io_do_iopoll(ctx, true) == 0)
  1274. break;
  1275. /*
  1276. * Ensure we allow local-to-the-cpu processing to take place,
  1277. * in this case we need to ensure that we reap all events.
  1278. * Also let task_work, etc. to progress by releasing the mutex
  1279. */
  1280. if (need_resched()) {
  1281. mutex_unlock(&ctx->uring_lock);
  1282. cond_resched();
  1283. mutex_lock(&ctx->uring_lock);
  1284. }
  1285. }
  1286. mutex_unlock(&ctx->uring_lock);
  1287. }
  1288. static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
  1289. {
  1290. unsigned int nr_events = 0;
  1291. unsigned long check_cq;
  1292. lockdep_assert_held(&ctx->uring_lock);
  1293. if (!io_allowed_run_tw(ctx))
  1294. return -EEXIST;
  1295. check_cq = READ_ONCE(ctx->check_cq);
  1296. if (unlikely(check_cq)) {
  1297. if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
  1298. __io_cqring_overflow_flush(ctx, false);
  1299. /*
  1300. * Similarly do not spin if we have not informed the user of any
  1301. * dropped CQE.
  1302. */
  1303. if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT))
  1304. return -EBADR;
  1305. }
  1306. /*
  1307. * Don't enter poll loop if we already have events pending.
  1308. * If we do, we can potentially be spinning for commands that
  1309. * already triggered a CQE (eg in error).
  1310. */
  1311. if (io_cqring_events(ctx))
  1312. return 0;
  1313. do {
  1314. int ret = 0;
  1315. /*
  1316. * If a submit got punted to a workqueue, we can have the
  1317. * application entering polling for a command before it gets
  1318. * issued. That app will hold the uring_lock for the duration
  1319. * of the poll right here, so we need to take a breather every
  1320. * now and then to ensure that the issue has a chance to add
  1321. * the poll to the issued list. Otherwise we can spin here
  1322. * forever, while the workqueue is stuck trying to acquire the
  1323. * very same mutex.
  1324. */
  1325. if (wq_list_empty(&ctx->iopoll_list) ||
  1326. io_task_work_pending(ctx)) {
  1327. u32 tail = ctx->cached_cq_tail;
  1328. (void) io_run_local_work_locked(ctx, min);
  1329. if (task_work_pending(current) ||
  1330. wq_list_empty(&ctx->iopoll_list)) {
  1331. mutex_unlock(&ctx->uring_lock);
  1332. io_run_task_work();
  1333. mutex_lock(&ctx->uring_lock);
  1334. }
  1335. /* some requests don't go through iopoll_list */
  1336. if (tail != ctx->cached_cq_tail ||
  1337. wq_list_empty(&ctx->iopoll_list))
  1338. break;
  1339. }
  1340. ret = io_do_iopoll(ctx, !min);
  1341. if (unlikely(ret < 0))
  1342. return ret;
  1343. if (task_sigpending(current))
  1344. return -EINTR;
  1345. if (need_resched())
  1346. break;
  1347. nr_events += ret;
  1348. } while (nr_events < min);
  1349. return 0;
  1350. }
  1351. void io_req_task_complete(struct io_kiocb *req, struct io_tw_state *ts)
  1352. {
  1353. io_req_complete_defer(req);
  1354. }
  1355. /*
  1356. * After the iocb has been issued, it's safe to be found on the poll list.
  1357. * Adding the kiocb to the list AFTER submission ensures that we don't
  1358. * find it from a io_do_iopoll() thread before the issuer is done
  1359. * accessing the kiocb cookie.
  1360. */
  1361. static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
  1362. {
  1363. struct io_ring_ctx *ctx = req->ctx;
  1364. const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
  1365. /* workqueue context doesn't hold uring_lock, grab it now */
  1366. if (unlikely(needs_lock))
  1367. mutex_lock(&ctx->uring_lock);
  1368. /*
  1369. * Track whether we have multiple files in our lists. This will impact
  1370. * how we do polling eventually, not spinning if we're on potentially
  1371. * different devices.
  1372. */
  1373. if (wq_list_empty(&ctx->iopoll_list)) {
  1374. ctx->poll_multi_queue = false;
  1375. } else if (!ctx->poll_multi_queue) {
  1376. struct io_kiocb *list_req;
  1377. list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
  1378. comp_list);
  1379. if (list_req->file != req->file)
  1380. ctx->poll_multi_queue = true;
  1381. }
  1382. /*
  1383. * For fast devices, IO may have already completed. If it has, add
  1384. * it to the front so we find it first.
  1385. */
  1386. if (READ_ONCE(req->iopoll_completed))
  1387. wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
  1388. else
  1389. wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
  1390. if (unlikely(needs_lock)) {
  1391. /*
  1392. * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
  1393. * in sq thread task context or in io worker task context. If
  1394. * current task context is sq thread, we don't need to check
  1395. * whether should wake up sq thread.
  1396. */
  1397. if ((ctx->flags & IORING_SETUP_SQPOLL) &&
  1398. wq_has_sleeper(&ctx->sq_data->wait))
  1399. wake_up(&ctx->sq_data->wait);
  1400. mutex_unlock(&ctx->uring_lock);
  1401. }
  1402. }
  1403. io_req_flags_t io_file_get_flags(struct file *file)
  1404. {
  1405. io_req_flags_t res = 0;
  1406. if (S_ISREG(file_inode(file)->i_mode))
  1407. res |= REQ_F_ISREG;
  1408. if ((file->f_flags & O_NONBLOCK) || (file->f_mode & FMODE_NOWAIT))
  1409. res |= REQ_F_SUPPORT_NOWAIT;
  1410. return res;
  1411. }
  1412. bool io_alloc_async_data(struct io_kiocb *req)
  1413. {
  1414. const struct io_issue_def *def = &io_issue_defs[req->opcode];
  1415. WARN_ON_ONCE(!def->async_size);
  1416. req->async_data = kmalloc(def->async_size, GFP_KERNEL);
  1417. if (req->async_data) {
  1418. req->flags |= REQ_F_ASYNC_DATA;
  1419. return false;
  1420. }
  1421. return true;
  1422. }
  1423. static u32 io_get_sequence(struct io_kiocb *req)
  1424. {
  1425. u32 seq = req->ctx->cached_sq_head;
  1426. struct io_kiocb *cur;
  1427. /* need original cached_sq_head, but it was increased for each req */
  1428. io_for_each_link(cur, req)
  1429. seq--;
  1430. return seq;
  1431. }
  1432. static __cold void io_drain_req(struct io_kiocb *req)
  1433. __must_hold(&ctx->uring_lock)
  1434. {
  1435. struct io_ring_ctx *ctx = req->ctx;
  1436. struct io_defer_entry *de;
  1437. int ret;
  1438. u32 seq = io_get_sequence(req);
  1439. /* Still need defer if there is pending req in defer list. */
  1440. spin_lock(&ctx->completion_lock);
  1441. if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
  1442. spin_unlock(&ctx->completion_lock);
  1443. queue:
  1444. ctx->drain_active = false;
  1445. io_req_task_queue(req);
  1446. return;
  1447. }
  1448. spin_unlock(&ctx->completion_lock);
  1449. io_prep_async_link(req);
  1450. de = kmalloc(sizeof(*de), GFP_KERNEL);
  1451. if (!de) {
  1452. ret = -ENOMEM;
  1453. io_req_defer_failed(req, ret);
  1454. return;
  1455. }
  1456. spin_lock(&ctx->completion_lock);
  1457. if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
  1458. spin_unlock(&ctx->completion_lock);
  1459. kfree(de);
  1460. goto queue;
  1461. }
  1462. trace_io_uring_defer(req);
  1463. de->req = req;
  1464. de->seq = seq;
  1465. list_add_tail(&de->list, &ctx->defer_list);
  1466. spin_unlock(&ctx->completion_lock);
  1467. }
  1468. static bool io_assign_file(struct io_kiocb *req, const struct io_issue_def *def,
  1469. unsigned int issue_flags)
  1470. {
  1471. if (req->file || !def->needs_file)
  1472. return true;
  1473. if (req->flags & REQ_F_FIXED_FILE)
  1474. req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
  1475. else
  1476. req->file = io_file_get_normal(req, req->cqe.fd);
  1477. return !!req->file;
  1478. }
  1479. static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
  1480. {
  1481. const struct io_issue_def *def = &io_issue_defs[req->opcode];
  1482. const struct cred *creds = NULL;
  1483. int ret;
  1484. if (unlikely(!io_assign_file(req, def, issue_flags)))
  1485. return -EBADF;
  1486. if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
  1487. creds = override_creds(req->creds);
  1488. if (!def->audit_skip)
  1489. audit_uring_entry(req->opcode);
  1490. ret = def->issue(req, issue_flags);
  1491. if (!def->audit_skip)
  1492. audit_uring_exit(!ret, ret);
  1493. if (creds)
  1494. revert_creds(creds);
  1495. if (ret == IOU_OK) {
  1496. if (issue_flags & IO_URING_F_COMPLETE_DEFER)
  1497. io_req_complete_defer(req);
  1498. else
  1499. io_req_complete_post(req, issue_flags);
  1500. return 0;
  1501. }
  1502. if (ret == IOU_ISSUE_SKIP_COMPLETE) {
  1503. ret = 0;
  1504. io_arm_ltimeout(req);
  1505. /* If the op doesn't have a file, we're not polling for it */
  1506. if ((req->ctx->flags & IORING_SETUP_IOPOLL) && def->iopoll_queue)
  1507. io_iopoll_req_issued(req, issue_flags);
  1508. }
  1509. return ret;
  1510. }
  1511. int io_poll_issue(struct io_kiocb *req, struct io_tw_state *ts)
  1512. {
  1513. io_tw_lock(req->ctx, ts);
  1514. return io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_MULTISHOT|
  1515. IO_URING_F_COMPLETE_DEFER);
  1516. }
  1517. struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
  1518. {
  1519. struct io_kiocb *req = container_of(work, struct io_kiocb, work);
  1520. struct io_kiocb *nxt = NULL;
  1521. if (req_ref_put_and_test(req)) {
  1522. if (req->flags & IO_REQ_LINK_FLAGS)
  1523. nxt = io_req_find_next(req);
  1524. io_free_req(req);
  1525. }
  1526. return nxt ? &nxt->work : NULL;
  1527. }
  1528. void io_wq_submit_work(struct io_wq_work *work)
  1529. {
  1530. struct io_kiocb *req = container_of(work, struct io_kiocb, work);
  1531. const struct io_issue_def *def = &io_issue_defs[req->opcode];
  1532. unsigned int issue_flags = IO_URING_F_UNLOCKED | IO_URING_F_IOWQ;
  1533. bool needs_poll = false;
  1534. int ret = 0, err = -ECANCELED;
  1535. /* one will be dropped by ->io_wq_free_work() after returning to io-wq */
  1536. if (!(req->flags & REQ_F_REFCOUNT))
  1537. __io_req_set_refcount(req, 2);
  1538. else
  1539. req_ref_get(req);
  1540. io_arm_ltimeout(req);
  1541. /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
  1542. if (atomic_read(&work->flags) & IO_WQ_WORK_CANCEL) {
  1543. fail:
  1544. io_req_task_queue_fail(req, err);
  1545. return;
  1546. }
  1547. if (!io_assign_file(req, def, issue_flags)) {
  1548. err = -EBADF;
  1549. atomic_or(IO_WQ_WORK_CANCEL, &work->flags);
  1550. goto fail;
  1551. }
  1552. /*
  1553. * If DEFER_TASKRUN is set, it's only allowed to post CQEs from the
  1554. * submitter task context. Final request completions are handed to the
  1555. * right context, however this is not the case of auxiliary CQEs,
  1556. * which is the main mean of operation for multishot requests.
  1557. * Don't allow any multishot execution from io-wq. It's more restrictive
  1558. * than necessary and also cleaner.
  1559. */
  1560. if (req->flags & REQ_F_APOLL_MULTISHOT) {
  1561. err = -EBADFD;
  1562. if (!io_file_can_poll(req))
  1563. goto fail;
  1564. if (req->file->f_flags & O_NONBLOCK ||
  1565. req->file->f_mode & FMODE_NOWAIT) {
  1566. err = -ECANCELED;
  1567. if (io_arm_poll_handler(req, issue_flags) != IO_APOLL_OK)
  1568. goto fail;
  1569. return;
  1570. } else {
  1571. req->flags &= ~REQ_F_APOLL_MULTISHOT;
  1572. }
  1573. }
  1574. if (req->flags & REQ_F_FORCE_ASYNC) {
  1575. bool opcode_poll = def->pollin || def->pollout;
  1576. if (opcode_poll && io_file_can_poll(req)) {
  1577. needs_poll = true;
  1578. issue_flags |= IO_URING_F_NONBLOCK;
  1579. }
  1580. }
  1581. do {
  1582. ret = io_issue_sqe(req, issue_flags);
  1583. if (ret != -EAGAIN)
  1584. break;
  1585. /*
  1586. * If REQ_F_NOWAIT is set, then don't wait or retry with
  1587. * poll. -EAGAIN is final for that case.
  1588. */
  1589. if (req->flags & REQ_F_NOWAIT)
  1590. break;
  1591. /*
  1592. * We can get EAGAIN for iopolled IO even though we're
  1593. * forcing a sync submission from here, since we can't
  1594. * wait for request slots on the block side.
  1595. */
  1596. if (!needs_poll) {
  1597. if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
  1598. break;
  1599. if (io_wq_worker_stopped())
  1600. break;
  1601. cond_resched();
  1602. continue;
  1603. }
  1604. if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
  1605. return;
  1606. /* aborted or ready, in either case retry blocking */
  1607. needs_poll = false;
  1608. issue_flags &= ~IO_URING_F_NONBLOCK;
  1609. } while (1);
  1610. /* avoid locking problems by failing it from a clean context */
  1611. if (ret)
  1612. io_req_task_queue_fail(req, ret);
  1613. }
  1614. inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
  1615. unsigned int issue_flags)
  1616. {
  1617. struct io_ring_ctx *ctx = req->ctx;
  1618. struct io_fixed_file *slot;
  1619. struct file *file = NULL;
  1620. io_ring_submit_lock(ctx, issue_flags);
  1621. if (unlikely((unsigned int)fd >= ctx->nr_user_files))
  1622. goto out;
  1623. fd = array_index_nospec(fd, ctx->nr_user_files);
  1624. slot = io_fixed_file_slot(&ctx->file_table, fd);
  1625. if (!req->rsrc_node)
  1626. __io_req_set_rsrc_node(req, ctx);
  1627. req->flags |= io_slot_flags(slot);
  1628. file = io_slot_file(slot);
  1629. out:
  1630. io_ring_submit_unlock(ctx, issue_flags);
  1631. return file;
  1632. }
  1633. struct file *io_file_get_normal(struct io_kiocb *req, int fd)
  1634. {
  1635. struct file *file = fget(fd);
  1636. trace_io_uring_file_get(req, fd);
  1637. /* we don't allow fixed io_uring files */
  1638. if (file && io_is_uring_fops(file))
  1639. io_req_track_inflight(req);
  1640. return file;
  1641. }
  1642. static void io_queue_async(struct io_kiocb *req, int ret)
  1643. __must_hold(&req->ctx->uring_lock)
  1644. {
  1645. struct io_kiocb *linked_timeout;
  1646. if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
  1647. io_req_defer_failed(req, ret);
  1648. return;
  1649. }
  1650. linked_timeout = io_prep_linked_timeout(req);
  1651. switch (io_arm_poll_handler(req, 0)) {
  1652. case IO_APOLL_READY:
  1653. io_kbuf_recycle(req, 0);
  1654. io_req_task_queue(req);
  1655. break;
  1656. case IO_APOLL_ABORTED:
  1657. io_kbuf_recycle(req, 0);
  1658. io_queue_iowq(req);
  1659. break;
  1660. case IO_APOLL_OK:
  1661. break;
  1662. }
  1663. if (linked_timeout)
  1664. io_queue_linked_timeout(linked_timeout);
  1665. }
  1666. static inline void io_queue_sqe(struct io_kiocb *req)
  1667. __must_hold(&req->ctx->uring_lock)
  1668. {
  1669. int ret;
  1670. ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
  1671. /*
  1672. * We async punt it if the file wasn't marked NOWAIT, or if the file
  1673. * doesn't support non-blocking read/write attempts
  1674. */
  1675. if (unlikely(ret))
  1676. io_queue_async(req, ret);
  1677. }
  1678. static void io_queue_sqe_fallback(struct io_kiocb *req)
  1679. __must_hold(&req->ctx->uring_lock)
  1680. {
  1681. if (unlikely(req->flags & REQ_F_FAIL)) {
  1682. /*
  1683. * We don't submit, fail them all, for that replace hardlinks
  1684. * with normal links. Extra REQ_F_LINK is tolerated.
  1685. */
  1686. req->flags &= ~REQ_F_HARDLINK;
  1687. req->flags |= REQ_F_LINK;
  1688. io_req_defer_failed(req, req->cqe.res);
  1689. } else {
  1690. if (unlikely(req->ctx->drain_active))
  1691. io_drain_req(req);
  1692. else
  1693. io_queue_iowq(req);
  1694. }
  1695. }
  1696. /*
  1697. * Check SQE restrictions (opcode and flags).
  1698. *
  1699. * Returns 'true' if SQE is allowed, 'false' otherwise.
  1700. */
  1701. static inline bool io_check_restriction(struct io_ring_ctx *ctx,
  1702. struct io_kiocb *req,
  1703. unsigned int sqe_flags)
  1704. {
  1705. if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
  1706. return false;
  1707. if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
  1708. ctx->restrictions.sqe_flags_required)
  1709. return false;
  1710. if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
  1711. ctx->restrictions.sqe_flags_required))
  1712. return false;
  1713. return true;
  1714. }
  1715. static void io_init_req_drain(struct io_kiocb *req)
  1716. {
  1717. struct io_ring_ctx *ctx = req->ctx;
  1718. struct io_kiocb *head = ctx->submit_state.link.head;
  1719. ctx->drain_active = true;
  1720. if (head) {
  1721. /*
  1722. * If we need to drain a request in the middle of a link, drain
  1723. * the head request and the next request/link after the current
  1724. * link. Considering sequential execution of links,
  1725. * REQ_F_IO_DRAIN will be maintained for every request of our
  1726. * link.
  1727. */
  1728. head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
  1729. ctx->drain_next = true;
  1730. }
  1731. }
  1732. static __cold int io_init_fail_req(struct io_kiocb *req, int err)
  1733. {
  1734. /* ensure per-opcode data is cleared if we fail before prep */
  1735. memset(&req->cmd.data, 0, sizeof(req->cmd.data));
  1736. return err;
  1737. }
  1738. static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
  1739. const struct io_uring_sqe *sqe)
  1740. __must_hold(&ctx->uring_lock)
  1741. {
  1742. const struct io_issue_def *def;
  1743. unsigned int sqe_flags;
  1744. int personality;
  1745. u8 opcode;
  1746. /* req is partially pre-initialised, see io_preinit_req() */
  1747. req->opcode = opcode = READ_ONCE(sqe->opcode);
  1748. /* same numerical values with corresponding REQ_F_*, safe to copy */
  1749. sqe_flags = READ_ONCE(sqe->flags);
  1750. req->flags = (__force io_req_flags_t) sqe_flags;
  1751. req->cqe.user_data = READ_ONCE(sqe->user_data);
  1752. req->file = NULL;
  1753. req->rsrc_node = NULL;
  1754. req->task = current;
  1755. req->cancel_seq_set = false;
  1756. if (unlikely(opcode >= IORING_OP_LAST)) {
  1757. req->opcode = 0;
  1758. return io_init_fail_req(req, -EINVAL);
  1759. }
  1760. def = &io_issue_defs[opcode];
  1761. if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
  1762. /* enforce forwards compatibility on users */
  1763. if (sqe_flags & ~SQE_VALID_FLAGS)
  1764. return io_init_fail_req(req, -EINVAL);
  1765. if (sqe_flags & IOSQE_BUFFER_SELECT) {
  1766. if (!def->buffer_select)
  1767. return io_init_fail_req(req, -EOPNOTSUPP);
  1768. req->buf_index = READ_ONCE(sqe->buf_group);
  1769. }
  1770. if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
  1771. ctx->drain_disabled = true;
  1772. if (sqe_flags & IOSQE_IO_DRAIN) {
  1773. if (ctx->drain_disabled)
  1774. return io_init_fail_req(req, -EOPNOTSUPP);
  1775. io_init_req_drain(req);
  1776. }
  1777. }
  1778. if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
  1779. if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
  1780. return io_init_fail_req(req, -EACCES);
  1781. /* knock it to the slow queue path, will be drained there */
  1782. if (ctx->drain_active)
  1783. req->flags |= REQ_F_FORCE_ASYNC;
  1784. /* if there is no link, we're at "next" request and need to drain */
  1785. if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
  1786. ctx->drain_next = false;
  1787. ctx->drain_active = true;
  1788. req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
  1789. }
  1790. }
  1791. if (!def->ioprio && sqe->ioprio)
  1792. return io_init_fail_req(req, -EINVAL);
  1793. if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
  1794. return io_init_fail_req(req, -EINVAL);
  1795. if (def->needs_file) {
  1796. struct io_submit_state *state = &ctx->submit_state;
  1797. req->cqe.fd = READ_ONCE(sqe->fd);
  1798. /*
  1799. * Plug now if we have more than 2 IO left after this, and the
  1800. * target is potentially a read/write to block based storage.
  1801. */
  1802. if (state->need_plug && def->plug) {
  1803. state->plug_started = true;
  1804. state->need_plug = false;
  1805. blk_start_plug_nr_ios(&state->plug, state->submit_nr);
  1806. }
  1807. }
  1808. personality = READ_ONCE(sqe->personality);
  1809. if (personality) {
  1810. int ret;
  1811. req->creds = xa_load(&ctx->personalities, personality);
  1812. if (!req->creds)
  1813. return io_init_fail_req(req, -EINVAL);
  1814. get_cred(req->creds);
  1815. ret = security_uring_override_creds(req->creds);
  1816. if (ret) {
  1817. put_cred(req->creds);
  1818. return io_init_fail_req(req, ret);
  1819. }
  1820. req->flags |= REQ_F_CREDS;
  1821. }
  1822. return def->prep(req, sqe);
  1823. }
  1824. static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
  1825. struct io_kiocb *req, int ret)
  1826. {
  1827. struct io_ring_ctx *ctx = req->ctx;
  1828. struct io_submit_link *link = &ctx->submit_state.link;
  1829. struct io_kiocb *head = link->head;
  1830. trace_io_uring_req_failed(sqe, req, ret);
  1831. /*
  1832. * Avoid breaking links in the middle as it renders links with SQPOLL
  1833. * unusable. Instead of failing eagerly, continue assembling the link if
  1834. * applicable and mark the head with REQ_F_FAIL. The link flushing code
  1835. * should find the flag and handle the rest.
  1836. */
  1837. req_fail_link_node(req, ret);
  1838. if (head && !(head->flags & REQ_F_FAIL))
  1839. req_fail_link_node(head, -ECANCELED);
  1840. if (!(req->flags & IO_REQ_LINK_FLAGS)) {
  1841. if (head) {
  1842. link->last->link = req;
  1843. link->head = NULL;
  1844. req = head;
  1845. }
  1846. io_queue_sqe_fallback(req);
  1847. return ret;
  1848. }
  1849. if (head)
  1850. link->last->link = req;
  1851. else
  1852. link->head = req;
  1853. link->last = req;
  1854. return 0;
  1855. }
  1856. static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
  1857. const struct io_uring_sqe *sqe)
  1858. __must_hold(&ctx->uring_lock)
  1859. {
  1860. struct io_submit_link *link = &ctx->submit_state.link;
  1861. int ret;
  1862. ret = io_init_req(ctx, req, sqe);
  1863. if (unlikely(ret))
  1864. return io_submit_fail_init(sqe, req, ret);
  1865. trace_io_uring_submit_req(req);
  1866. /*
  1867. * If we already have a head request, queue this one for async
  1868. * submittal once the head completes. If we don't have a head but
  1869. * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
  1870. * submitted sync once the chain is complete. If none of those
  1871. * conditions are true (normal request), then just queue it.
  1872. */
  1873. if (unlikely(link->head)) {
  1874. trace_io_uring_link(req, link->last);
  1875. link->last->link = req;
  1876. link->last = req;
  1877. if (req->flags & IO_REQ_LINK_FLAGS)
  1878. return 0;
  1879. /* last request of the link, flush it */
  1880. req = link->head;
  1881. link->head = NULL;
  1882. if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
  1883. goto fallback;
  1884. } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
  1885. REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
  1886. if (req->flags & IO_REQ_LINK_FLAGS) {
  1887. link->head = req;
  1888. link->last = req;
  1889. } else {
  1890. fallback:
  1891. io_queue_sqe_fallback(req);
  1892. }
  1893. return 0;
  1894. }
  1895. io_queue_sqe(req);
  1896. return 0;
  1897. }
  1898. /*
  1899. * Batched submission is done, ensure local IO is flushed out.
  1900. */
  1901. static void io_submit_state_end(struct io_ring_ctx *ctx)
  1902. {
  1903. struct io_submit_state *state = &ctx->submit_state;
  1904. if (unlikely(state->link.head))
  1905. io_queue_sqe_fallback(state->link.head);
  1906. /* flush only after queuing links as they can generate completions */
  1907. io_submit_flush_completions(ctx);
  1908. if (state->plug_started)
  1909. blk_finish_plug(&state->plug);
  1910. }
  1911. /*
  1912. * Start submission side cache.
  1913. */
  1914. static void io_submit_state_start(struct io_submit_state *state,
  1915. unsigned int max_ios)
  1916. {
  1917. state->plug_started = false;
  1918. state->need_plug = max_ios > 2;
  1919. state->submit_nr = max_ios;
  1920. /* set only head, no need to init link_last in advance */
  1921. state->link.head = NULL;
  1922. }
  1923. static void io_commit_sqring(struct io_ring_ctx *ctx)
  1924. {
  1925. struct io_rings *rings = ctx->rings;
  1926. /*
  1927. * Ensure any loads from the SQEs are done at this point,
  1928. * since once we write the new head, the application could
  1929. * write new data to them.
  1930. */
  1931. smp_store_release(&rings->sq.head, ctx->cached_sq_head);
  1932. }
  1933. /*
  1934. * Fetch an sqe, if one is available. Note this returns a pointer to memory
  1935. * that is mapped by userspace. This means that care needs to be taken to
  1936. * ensure that reads are stable, as we cannot rely on userspace always
  1937. * being a good citizen. If members of the sqe are validated and then later
  1938. * used, it's important that those reads are done through READ_ONCE() to
  1939. * prevent a re-load down the line.
  1940. */
  1941. static bool io_get_sqe(struct io_ring_ctx *ctx, const struct io_uring_sqe **sqe)
  1942. {
  1943. unsigned mask = ctx->sq_entries - 1;
  1944. unsigned head = ctx->cached_sq_head++ & mask;
  1945. if (!(ctx->flags & IORING_SETUP_NO_SQARRAY)) {
  1946. head = READ_ONCE(ctx->sq_array[head]);
  1947. if (unlikely(head >= ctx->sq_entries)) {
  1948. /* drop invalid entries */
  1949. spin_lock(&ctx->completion_lock);
  1950. ctx->cq_extra--;
  1951. spin_unlock(&ctx->completion_lock);
  1952. WRITE_ONCE(ctx->rings->sq_dropped,
  1953. READ_ONCE(ctx->rings->sq_dropped) + 1);
  1954. return false;
  1955. }
  1956. }
  1957. /*
  1958. * The cached sq head (or cq tail) serves two purposes:
  1959. *
  1960. * 1) allows us to batch the cost of updating the user visible
  1961. * head updates.
  1962. * 2) allows the kernel side to track the head on its own, even
  1963. * though the application is the one updating it.
  1964. */
  1965. /* double index for 128-byte SQEs, twice as long */
  1966. if (ctx->flags & IORING_SETUP_SQE128)
  1967. head <<= 1;
  1968. *sqe = &ctx->sq_sqes[head];
  1969. return true;
  1970. }
  1971. int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
  1972. __must_hold(&ctx->uring_lock)
  1973. {
  1974. unsigned int entries = io_sqring_entries(ctx);
  1975. unsigned int left;
  1976. int ret;
  1977. if (unlikely(!entries))
  1978. return 0;
  1979. /* make sure SQ entry isn't read before tail */
  1980. ret = left = min(nr, entries);
  1981. io_get_task_refs(left);
  1982. io_submit_state_start(&ctx->submit_state, left);
  1983. do {
  1984. const struct io_uring_sqe *sqe;
  1985. struct io_kiocb *req;
  1986. if (unlikely(!io_alloc_req(ctx, &req)))
  1987. break;
  1988. if (unlikely(!io_get_sqe(ctx, &sqe))) {
  1989. io_req_add_to_cache(req, ctx);
  1990. break;
  1991. }
  1992. /*
  1993. * Continue submitting even for sqe failure if the
  1994. * ring was setup with IORING_SETUP_SUBMIT_ALL
  1995. */
  1996. if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
  1997. !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
  1998. left--;
  1999. break;
  2000. }
  2001. } while (--left);
  2002. if (unlikely(left)) {
  2003. ret -= left;
  2004. /* try again if it submitted nothing and can't allocate a req */
  2005. if (!ret && io_req_cache_empty(ctx))
  2006. ret = -EAGAIN;
  2007. current->io_uring->cached_refs += left;
  2008. }
  2009. io_submit_state_end(ctx);
  2010. /* Commit SQ ring head once we've consumed and submitted all SQEs */
  2011. io_commit_sqring(ctx);
  2012. return ret;
  2013. }
  2014. static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
  2015. int wake_flags, void *key)
  2016. {
  2017. struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue, wq);
  2018. /*
  2019. * Cannot safely flush overflowed CQEs from here, ensure we wake up
  2020. * the task, and the next invocation will do it.
  2021. */
  2022. if (io_should_wake(iowq) || io_has_work(iowq->ctx))
  2023. return autoremove_wake_function(curr, mode, wake_flags, key);
  2024. return -1;
  2025. }
  2026. int io_run_task_work_sig(struct io_ring_ctx *ctx)
  2027. {
  2028. if (!llist_empty(&ctx->work_llist)) {
  2029. __set_current_state(TASK_RUNNING);
  2030. if (io_run_local_work(ctx, INT_MAX) > 0)
  2031. return 0;
  2032. }
  2033. if (io_run_task_work() > 0)
  2034. return 0;
  2035. if (task_sigpending(current))
  2036. return -EINTR;
  2037. return 0;
  2038. }
  2039. static bool current_pending_io(void)
  2040. {
  2041. struct io_uring_task *tctx = current->io_uring;
  2042. if (!tctx)
  2043. return false;
  2044. return percpu_counter_read_positive(&tctx->inflight);
  2045. }
  2046. static enum hrtimer_restart io_cqring_timer_wakeup(struct hrtimer *timer)
  2047. {
  2048. struct io_wait_queue *iowq = container_of(timer, struct io_wait_queue, t);
  2049. WRITE_ONCE(iowq->hit_timeout, 1);
  2050. iowq->min_timeout = 0;
  2051. wake_up_process(iowq->wq.private);
  2052. return HRTIMER_NORESTART;
  2053. }
  2054. /*
  2055. * Doing min_timeout portion. If we saw any timeouts, events, or have work,
  2056. * wake up. If not, and we have a normal timeout, switch to that and keep
  2057. * sleeping.
  2058. */
  2059. static enum hrtimer_restart io_cqring_min_timer_wakeup(struct hrtimer *timer)
  2060. {
  2061. struct io_wait_queue *iowq = container_of(timer, struct io_wait_queue, t);
  2062. struct io_ring_ctx *ctx = iowq->ctx;
  2063. /* no general timeout, or shorter (or equal), we are done */
  2064. if (iowq->timeout == KTIME_MAX ||
  2065. ktime_compare(iowq->min_timeout, iowq->timeout) >= 0)
  2066. goto out_wake;
  2067. /* work we may need to run, wake function will see if we need to wake */
  2068. if (io_has_work(ctx))
  2069. goto out_wake;
  2070. /* got events since we started waiting, min timeout is done */
  2071. if (iowq->cq_min_tail != READ_ONCE(ctx->rings->cq.tail))
  2072. goto out_wake;
  2073. /* if we have any events and min timeout expired, we're done */
  2074. if (io_cqring_events(ctx))
  2075. goto out_wake;
  2076. /*
  2077. * If using deferred task_work running and application is waiting on
  2078. * more than one request, ensure we reset it now where we are switching
  2079. * to normal sleeps. Any request completion post min_wait should wake
  2080. * the task and return.
  2081. */
  2082. if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
  2083. atomic_set(&ctx->cq_wait_nr, 1);
  2084. smp_mb();
  2085. if (!llist_empty(&ctx->work_llist))
  2086. goto out_wake;
  2087. }
  2088. iowq->t.function = io_cqring_timer_wakeup;
  2089. hrtimer_set_expires(timer, iowq->timeout);
  2090. return HRTIMER_RESTART;
  2091. out_wake:
  2092. return io_cqring_timer_wakeup(timer);
  2093. }
  2094. static int io_cqring_schedule_timeout(struct io_wait_queue *iowq,
  2095. clockid_t clock_id, ktime_t start_time)
  2096. {
  2097. ktime_t timeout;
  2098. hrtimer_init_on_stack(&iowq->t, clock_id, HRTIMER_MODE_ABS);
  2099. if (iowq->min_timeout) {
  2100. timeout = ktime_add_ns(iowq->min_timeout, start_time);
  2101. iowq->t.function = io_cqring_min_timer_wakeup;
  2102. } else {
  2103. timeout = iowq->timeout;
  2104. iowq->t.function = io_cqring_timer_wakeup;
  2105. }
  2106. hrtimer_set_expires_range_ns(&iowq->t, timeout, 0);
  2107. hrtimer_start_expires(&iowq->t, HRTIMER_MODE_ABS);
  2108. if (!READ_ONCE(iowq->hit_timeout))
  2109. schedule();
  2110. hrtimer_cancel(&iowq->t);
  2111. destroy_hrtimer_on_stack(&iowq->t);
  2112. __set_current_state(TASK_RUNNING);
  2113. return READ_ONCE(iowq->hit_timeout) ? -ETIME : 0;
  2114. }
  2115. static int __io_cqring_wait_schedule(struct io_ring_ctx *ctx,
  2116. struct io_wait_queue *iowq,
  2117. ktime_t start_time)
  2118. {
  2119. int ret = 0;
  2120. /*
  2121. * Mark us as being in io_wait if we have pending requests, so cpufreq
  2122. * can take into account that the task is waiting for IO - turns out
  2123. * to be important for low QD IO.
  2124. */
  2125. if (current_pending_io())
  2126. current->in_iowait = 1;
  2127. if (iowq->timeout != KTIME_MAX || iowq->min_timeout)
  2128. ret = io_cqring_schedule_timeout(iowq, ctx->clockid, start_time);
  2129. else
  2130. schedule();
  2131. current->in_iowait = 0;
  2132. return ret;
  2133. }
  2134. /* If this returns > 0, the caller should retry */
  2135. static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
  2136. struct io_wait_queue *iowq,
  2137. ktime_t start_time)
  2138. {
  2139. if (unlikely(READ_ONCE(ctx->check_cq)))
  2140. return 1;
  2141. if (unlikely(!llist_empty(&ctx->work_llist)))
  2142. return 1;
  2143. if (unlikely(task_work_pending(current)))
  2144. return 1;
  2145. if (unlikely(task_sigpending(current)))
  2146. return -EINTR;
  2147. if (unlikely(io_should_wake(iowq)))
  2148. return 0;
  2149. return __io_cqring_wait_schedule(ctx, iowq, start_time);
  2150. }
  2151. struct ext_arg {
  2152. size_t argsz;
  2153. struct __kernel_timespec __user *ts;
  2154. const sigset_t __user *sig;
  2155. ktime_t min_time;
  2156. };
  2157. /*
  2158. * Wait until events become available, if we don't already have some. The
  2159. * application must reap them itself, as they reside on the shared cq ring.
  2160. */
  2161. static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events, u32 flags,
  2162. struct ext_arg *ext_arg)
  2163. {
  2164. struct io_wait_queue iowq;
  2165. struct io_rings *rings = ctx->rings;
  2166. ktime_t start_time;
  2167. int ret;
  2168. if (!io_allowed_run_tw(ctx))
  2169. return -EEXIST;
  2170. if (!llist_empty(&ctx->work_llist))
  2171. io_run_local_work(ctx, min_events);
  2172. io_run_task_work();
  2173. if (unlikely(test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)))
  2174. io_cqring_do_overflow_flush(ctx);
  2175. if (__io_cqring_events_user(ctx) >= min_events)
  2176. return 0;
  2177. init_waitqueue_func_entry(&iowq.wq, io_wake_function);
  2178. iowq.wq.private = current;
  2179. INIT_LIST_HEAD(&iowq.wq.entry);
  2180. iowq.ctx = ctx;
  2181. iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
  2182. iowq.cq_min_tail = READ_ONCE(ctx->rings->cq.tail);
  2183. iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
  2184. iowq.hit_timeout = 0;
  2185. iowq.min_timeout = ext_arg->min_time;
  2186. iowq.timeout = KTIME_MAX;
  2187. start_time = io_get_time(ctx);
  2188. if (ext_arg->ts) {
  2189. struct timespec64 ts;
  2190. if (get_timespec64(&ts, ext_arg->ts))
  2191. return -EFAULT;
  2192. iowq.timeout = timespec64_to_ktime(ts);
  2193. if (!(flags & IORING_ENTER_ABS_TIMER))
  2194. iowq.timeout = ktime_add(iowq.timeout, start_time);
  2195. }
  2196. if (ext_arg->sig) {
  2197. #ifdef CONFIG_COMPAT
  2198. if (in_compat_syscall())
  2199. ret = set_compat_user_sigmask((const compat_sigset_t __user *)ext_arg->sig,
  2200. ext_arg->argsz);
  2201. else
  2202. #endif
  2203. ret = set_user_sigmask(ext_arg->sig, ext_arg->argsz);
  2204. if (ret)
  2205. return ret;
  2206. }
  2207. io_napi_busy_loop(ctx, &iowq);
  2208. trace_io_uring_cqring_wait(ctx, min_events);
  2209. do {
  2210. unsigned long check_cq;
  2211. int nr_wait;
  2212. /* if min timeout has been hit, don't reset wait count */
  2213. if (!iowq.hit_timeout)
  2214. nr_wait = (int) iowq.cq_tail -
  2215. READ_ONCE(ctx->rings->cq.tail);
  2216. else
  2217. nr_wait = 1;
  2218. if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
  2219. atomic_set(&ctx->cq_wait_nr, nr_wait);
  2220. set_current_state(TASK_INTERRUPTIBLE);
  2221. } else {
  2222. prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
  2223. TASK_INTERRUPTIBLE);
  2224. }
  2225. ret = io_cqring_wait_schedule(ctx, &iowq, start_time);
  2226. __set_current_state(TASK_RUNNING);
  2227. atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT);
  2228. /*
  2229. * Run task_work after scheduling and before io_should_wake().
  2230. * If we got woken because of task_work being processed, run it
  2231. * now rather than let the caller do another wait loop.
  2232. */
  2233. if (!llist_empty(&ctx->work_llist))
  2234. io_run_local_work(ctx, nr_wait);
  2235. io_run_task_work();
  2236. /*
  2237. * Non-local task_work will be run on exit to userspace, but
  2238. * if we're using DEFER_TASKRUN, then we could have waited
  2239. * with a timeout for a number of requests. If the timeout
  2240. * hits, we could have some requests ready to process. Ensure
  2241. * this break is _after_ we have run task_work, to avoid
  2242. * deferring running potentially pending requests until the
  2243. * next time we wait for events.
  2244. */
  2245. if (ret < 0)
  2246. break;
  2247. check_cq = READ_ONCE(ctx->check_cq);
  2248. if (unlikely(check_cq)) {
  2249. /* let the caller flush overflows, retry */
  2250. if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
  2251. io_cqring_do_overflow_flush(ctx);
  2252. if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)) {
  2253. ret = -EBADR;
  2254. break;
  2255. }
  2256. }
  2257. if (io_should_wake(&iowq)) {
  2258. ret = 0;
  2259. break;
  2260. }
  2261. cond_resched();
  2262. } while (1);
  2263. if (!(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
  2264. finish_wait(&ctx->cq_wait, &iowq.wq);
  2265. restore_saved_sigmask_unless(ret == -EINTR);
  2266. return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
  2267. }
  2268. static void *io_rings_map(struct io_ring_ctx *ctx, unsigned long uaddr,
  2269. size_t size)
  2270. {
  2271. return __io_uaddr_map(&ctx->ring_pages, &ctx->n_ring_pages, uaddr,
  2272. size);
  2273. }
  2274. static void *io_sqes_map(struct io_ring_ctx *ctx, unsigned long uaddr,
  2275. size_t size)
  2276. {
  2277. return __io_uaddr_map(&ctx->sqe_pages, &ctx->n_sqe_pages, uaddr,
  2278. size);
  2279. }
  2280. static void io_rings_free(struct io_ring_ctx *ctx)
  2281. {
  2282. if (!(ctx->flags & IORING_SETUP_NO_MMAP)) {
  2283. io_pages_unmap(ctx->rings, &ctx->ring_pages, &ctx->n_ring_pages,
  2284. true);
  2285. io_pages_unmap(ctx->sq_sqes, &ctx->sqe_pages, &ctx->n_sqe_pages,
  2286. true);
  2287. } else {
  2288. io_pages_free(&ctx->ring_pages, ctx->n_ring_pages);
  2289. ctx->n_ring_pages = 0;
  2290. io_pages_free(&ctx->sqe_pages, ctx->n_sqe_pages);
  2291. ctx->n_sqe_pages = 0;
  2292. vunmap(ctx->rings);
  2293. vunmap(ctx->sq_sqes);
  2294. }
  2295. ctx->rings = NULL;
  2296. ctx->sq_sqes = NULL;
  2297. }
  2298. static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
  2299. unsigned int cq_entries, size_t *sq_offset)
  2300. {
  2301. struct io_rings *rings;
  2302. size_t off, sq_array_size;
  2303. off = struct_size(rings, cqes, cq_entries);
  2304. if (off == SIZE_MAX)
  2305. return SIZE_MAX;
  2306. if (ctx->flags & IORING_SETUP_CQE32) {
  2307. if (check_shl_overflow(off, 1, &off))
  2308. return SIZE_MAX;
  2309. }
  2310. #ifdef CONFIG_SMP
  2311. off = ALIGN(off, SMP_CACHE_BYTES);
  2312. if (off == 0)
  2313. return SIZE_MAX;
  2314. #endif
  2315. if (ctx->flags & IORING_SETUP_NO_SQARRAY) {
  2316. *sq_offset = SIZE_MAX;
  2317. return off;
  2318. }
  2319. *sq_offset = off;
  2320. sq_array_size = array_size(sizeof(u32), sq_entries);
  2321. if (sq_array_size == SIZE_MAX)
  2322. return SIZE_MAX;
  2323. if (check_add_overflow(off, sq_array_size, &off))
  2324. return SIZE_MAX;
  2325. return off;
  2326. }
  2327. static void io_req_caches_free(struct io_ring_ctx *ctx)
  2328. {
  2329. struct io_kiocb *req;
  2330. int nr = 0;
  2331. mutex_lock(&ctx->uring_lock);
  2332. while (!io_req_cache_empty(ctx)) {
  2333. req = io_extract_req(ctx);
  2334. kmem_cache_free(req_cachep, req);
  2335. nr++;
  2336. }
  2337. if (nr)
  2338. percpu_ref_put_many(&ctx->refs, nr);
  2339. mutex_unlock(&ctx->uring_lock);
  2340. }
  2341. static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
  2342. {
  2343. io_sq_thread_finish(ctx);
  2344. /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
  2345. if (WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list)))
  2346. return;
  2347. mutex_lock(&ctx->uring_lock);
  2348. if (ctx->buf_data)
  2349. __io_sqe_buffers_unregister(ctx);
  2350. if (ctx->file_data)
  2351. __io_sqe_files_unregister(ctx);
  2352. io_cqring_overflow_kill(ctx);
  2353. io_eventfd_unregister(ctx);
  2354. io_alloc_cache_free(&ctx->apoll_cache, kfree);
  2355. io_alloc_cache_free(&ctx->netmsg_cache, io_netmsg_cache_free);
  2356. io_alloc_cache_free(&ctx->rw_cache, io_rw_cache_free);
  2357. io_alloc_cache_free(&ctx->uring_cache, kfree);
  2358. io_alloc_cache_free(&ctx->msg_cache, io_msg_cache_free);
  2359. io_futex_cache_free(ctx);
  2360. io_destroy_buffers(ctx);
  2361. mutex_unlock(&ctx->uring_lock);
  2362. if (ctx->sq_creds)
  2363. put_cred(ctx->sq_creds);
  2364. if (ctx->submitter_task)
  2365. put_task_struct(ctx->submitter_task);
  2366. /* there are no registered resources left, nobody uses it */
  2367. if (ctx->rsrc_node)
  2368. io_rsrc_node_destroy(ctx, ctx->rsrc_node);
  2369. WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
  2370. WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
  2371. io_alloc_cache_free(&ctx->rsrc_node_cache, kfree);
  2372. if (ctx->mm_account) {
  2373. mmdrop(ctx->mm_account);
  2374. ctx->mm_account = NULL;
  2375. }
  2376. io_rings_free(ctx);
  2377. percpu_ref_exit(&ctx->refs);
  2378. free_uid(ctx->user);
  2379. io_req_caches_free(ctx);
  2380. if (ctx->hash_map)
  2381. io_wq_put_hash(ctx->hash_map);
  2382. io_napi_free(ctx);
  2383. kfree(ctx->cancel_table.hbs);
  2384. kfree(ctx->cancel_table_locked.hbs);
  2385. xa_destroy(&ctx->io_bl_xa);
  2386. kfree(ctx);
  2387. }
  2388. static __cold void io_activate_pollwq_cb(struct callback_head *cb)
  2389. {
  2390. struct io_ring_ctx *ctx = container_of(cb, struct io_ring_ctx,
  2391. poll_wq_task_work);
  2392. mutex_lock(&ctx->uring_lock);
  2393. ctx->poll_activated = true;
  2394. mutex_unlock(&ctx->uring_lock);
  2395. /*
  2396. * Wake ups for some events between start of polling and activation
  2397. * might've been lost due to loose synchronisation.
  2398. */
  2399. wake_up_all(&ctx->poll_wq);
  2400. percpu_ref_put(&ctx->refs);
  2401. }
  2402. __cold void io_activate_pollwq(struct io_ring_ctx *ctx)
  2403. {
  2404. spin_lock(&ctx->completion_lock);
  2405. /* already activated or in progress */
  2406. if (ctx->poll_activated || ctx->poll_wq_task_work.func)
  2407. goto out;
  2408. if (WARN_ON_ONCE(!ctx->task_complete))
  2409. goto out;
  2410. if (!ctx->submitter_task)
  2411. goto out;
  2412. /*
  2413. * with ->submitter_task only the submitter task completes requests, we
  2414. * only need to sync with it, which is done by injecting a tw
  2415. */
  2416. init_task_work(&ctx->poll_wq_task_work, io_activate_pollwq_cb);
  2417. percpu_ref_get(&ctx->refs);
  2418. if (task_work_add(ctx->submitter_task, &ctx->poll_wq_task_work, TWA_SIGNAL))
  2419. percpu_ref_put(&ctx->refs);
  2420. out:
  2421. spin_unlock(&ctx->completion_lock);
  2422. }
  2423. static __poll_t io_uring_poll(struct file *file, poll_table *wait)
  2424. {
  2425. struct io_ring_ctx *ctx = file->private_data;
  2426. __poll_t mask = 0;
  2427. if (unlikely(!ctx->poll_activated))
  2428. io_activate_pollwq(ctx);
  2429. poll_wait(file, &ctx->poll_wq, wait);
  2430. /*
  2431. * synchronizes with barrier from wq_has_sleeper call in
  2432. * io_commit_cqring
  2433. */
  2434. smp_rmb();
  2435. if (!io_sqring_full(ctx))
  2436. mask |= EPOLLOUT | EPOLLWRNORM;
  2437. /*
  2438. * Don't flush cqring overflow list here, just do a simple check.
  2439. * Otherwise there could possible be ABBA deadlock:
  2440. * CPU0 CPU1
  2441. * ---- ----
  2442. * lock(&ctx->uring_lock);
  2443. * lock(&ep->mtx);
  2444. * lock(&ctx->uring_lock);
  2445. * lock(&ep->mtx);
  2446. *
  2447. * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
  2448. * pushes them to do the flush.
  2449. */
  2450. if (__io_cqring_events_user(ctx) || io_has_work(ctx))
  2451. mask |= EPOLLIN | EPOLLRDNORM;
  2452. return mask;
  2453. }
  2454. struct io_tctx_exit {
  2455. struct callback_head task_work;
  2456. struct completion completion;
  2457. struct io_ring_ctx *ctx;
  2458. };
  2459. static __cold void io_tctx_exit_cb(struct callback_head *cb)
  2460. {
  2461. struct io_uring_task *tctx = current->io_uring;
  2462. struct io_tctx_exit *work;
  2463. work = container_of(cb, struct io_tctx_exit, task_work);
  2464. /*
  2465. * When @in_cancel, we're in cancellation and it's racy to remove the
  2466. * node. It'll be removed by the end of cancellation, just ignore it.
  2467. * tctx can be NULL if the queueing of this task_work raced with
  2468. * work cancelation off the exec path.
  2469. */
  2470. if (tctx && !atomic_read(&tctx->in_cancel))
  2471. io_uring_del_tctx_node((unsigned long)work->ctx);
  2472. complete(&work->completion);
  2473. }
  2474. static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
  2475. {
  2476. struct io_kiocb *req = container_of(work, struct io_kiocb, work);
  2477. return req->ctx == data;
  2478. }
  2479. static __cold void io_ring_exit_work(struct work_struct *work)
  2480. {
  2481. struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
  2482. unsigned long timeout = jiffies + HZ * 60 * 5;
  2483. unsigned long interval = HZ / 20;
  2484. struct io_tctx_exit exit;
  2485. struct io_tctx_node *node;
  2486. int ret;
  2487. /*
  2488. * If we're doing polled IO and end up having requests being
  2489. * submitted async (out-of-line), then completions can come in while
  2490. * we're waiting for refs to drop. We need to reap these manually,
  2491. * as nobody else will be looking for them.
  2492. */
  2493. do {
  2494. if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
  2495. mutex_lock(&ctx->uring_lock);
  2496. io_cqring_overflow_kill(ctx);
  2497. mutex_unlock(&ctx->uring_lock);
  2498. }
  2499. if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
  2500. io_move_task_work_from_local(ctx);
  2501. while (io_uring_try_cancel_requests(ctx, NULL, true))
  2502. cond_resched();
  2503. if (ctx->sq_data) {
  2504. struct io_sq_data *sqd = ctx->sq_data;
  2505. struct task_struct *tsk;
  2506. io_sq_thread_park(sqd);
  2507. tsk = sqd->thread;
  2508. if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
  2509. io_wq_cancel_cb(tsk->io_uring->io_wq,
  2510. io_cancel_ctx_cb, ctx, true);
  2511. io_sq_thread_unpark(sqd);
  2512. }
  2513. io_req_caches_free(ctx);
  2514. if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
  2515. /* there is little hope left, don't run it too often */
  2516. interval = HZ * 60;
  2517. }
  2518. /*
  2519. * This is really an uninterruptible wait, as it has to be
  2520. * complete. But it's also run from a kworker, which doesn't
  2521. * take signals, so it's fine to make it interruptible. This
  2522. * avoids scenarios where we knowingly can wait much longer
  2523. * on completions, for example if someone does a SIGSTOP on
  2524. * a task that needs to finish task_work to make this loop
  2525. * complete. That's a synthetic situation that should not
  2526. * cause a stuck task backtrace, and hence a potential panic
  2527. * on stuck tasks if that is enabled.
  2528. */
  2529. } while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval));
  2530. init_completion(&exit.completion);
  2531. init_task_work(&exit.task_work, io_tctx_exit_cb);
  2532. exit.ctx = ctx;
  2533. mutex_lock(&ctx->uring_lock);
  2534. while (!list_empty(&ctx->tctx_list)) {
  2535. WARN_ON_ONCE(time_after(jiffies, timeout));
  2536. node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
  2537. ctx_node);
  2538. /* don't spin on a single task if cancellation failed */
  2539. list_rotate_left(&ctx->tctx_list);
  2540. ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
  2541. if (WARN_ON_ONCE(ret))
  2542. continue;
  2543. mutex_unlock(&ctx->uring_lock);
  2544. /*
  2545. * See comment above for
  2546. * wait_for_completion_interruptible_timeout() on why this
  2547. * wait is marked as interruptible.
  2548. */
  2549. wait_for_completion_interruptible(&exit.completion);
  2550. mutex_lock(&ctx->uring_lock);
  2551. }
  2552. mutex_unlock(&ctx->uring_lock);
  2553. spin_lock(&ctx->completion_lock);
  2554. spin_unlock(&ctx->completion_lock);
  2555. /* pairs with RCU read section in io_req_local_work_add() */
  2556. if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
  2557. synchronize_rcu();
  2558. io_ring_ctx_free(ctx);
  2559. }
  2560. static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
  2561. {
  2562. unsigned long index;
  2563. struct creds *creds;
  2564. mutex_lock(&ctx->uring_lock);
  2565. percpu_ref_kill(&ctx->refs);
  2566. xa_for_each(&ctx->personalities, index, creds)
  2567. io_unregister_personality(ctx, index);
  2568. mutex_unlock(&ctx->uring_lock);
  2569. flush_delayed_work(&ctx->fallback_work);
  2570. INIT_WORK(&ctx->exit_work, io_ring_exit_work);
  2571. /*
  2572. * Use system_unbound_wq to avoid spawning tons of event kworkers
  2573. * if we're exiting a ton of rings at the same time. It just adds
  2574. * noise and overhead, there's no discernable change in runtime
  2575. * over using system_wq.
  2576. */
  2577. queue_work(iou_wq, &ctx->exit_work);
  2578. }
  2579. static int io_uring_release(struct inode *inode, struct file *file)
  2580. {
  2581. struct io_ring_ctx *ctx = file->private_data;
  2582. file->private_data = NULL;
  2583. io_ring_ctx_wait_and_kill(ctx);
  2584. return 0;
  2585. }
  2586. struct io_task_cancel {
  2587. struct task_struct *task;
  2588. bool all;
  2589. };
  2590. static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
  2591. {
  2592. struct io_kiocb *req = container_of(work, struct io_kiocb, work);
  2593. struct io_task_cancel *cancel = data;
  2594. return io_match_task_safe(req, cancel->task, cancel->all);
  2595. }
  2596. static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
  2597. struct task_struct *task,
  2598. bool cancel_all)
  2599. {
  2600. struct io_defer_entry *de;
  2601. LIST_HEAD(list);
  2602. spin_lock(&ctx->completion_lock);
  2603. list_for_each_entry_reverse(de, &ctx->defer_list, list) {
  2604. if (io_match_task_safe(de->req, task, cancel_all)) {
  2605. list_cut_position(&list, &ctx->defer_list, &de->list);
  2606. break;
  2607. }
  2608. }
  2609. spin_unlock(&ctx->completion_lock);
  2610. if (list_empty(&list))
  2611. return false;
  2612. while (!list_empty(&list)) {
  2613. de = list_first_entry(&list, struct io_defer_entry, list);
  2614. list_del_init(&de->list);
  2615. io_req_task_queue_fail(de->req, -ECANCELED);
  2616. kfree(de);
  2617. }
  2618. return true;
  2619. }
  2620. static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
  2621. {
  2622. struct io_tctx_node *node;
  2623. enum io_wq_cancel cret;
  2624. bool ret = false;
  2625. mutex_lock(&ctx->uring_lock);
  2626. list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
  2627. struct io_uring_task *tctx = node->task->io_uring;
  2628. /*
  2629. * io_wq will stay alive while we hold uring_lock, because it's
  2630. * killed after ctx nodes, which requires to take the lock.
  2631. */
  2632. if (!tctx || !tctx->io_wq)
  2633. continue;
  2634. cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
  2635. ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
  2636. }
  2637. mutex_unlock(&ctx->uring_lock);
  2638. return ret;
  2639. }
  2640. static __cold bool io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
  2641. struct task_struct *task,
  2642. bool cancel_all)
  2643. {
  2644. struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
  2645. struct io_uring_task *tctx = task ? task->io_uring : NULL;
  2646. enum io_wq_cancel cret;
  2647. bool ret = false;
  2648. /* set it so io_req_local_work_add() would wake us up */
  2649. if (ctx->flags & IORING_SETUP_DEFER_TASKRUN) {
  2650. atomic_set(&ctx->cq_wait_nr, 1);
  2651. smp_mb();
  2652. }
  2653. /* failed during ring init, it couldn't have issued any requests */
  2654. if (!ctx->rings)
  2655. return false;
  2656. if (!task) {
  2657. ret |= io_uring_try_cancel_iowq(ctx);
  2658. } else if (tctx && tctx->io_wq) {
  2659. /*
  2660. * Cancels requests of all rings, not only @ctx, but
  2661. * it's fine as the task is in exit/exec.
  2662. */
  2663. cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
  2664. &cancel, true);
  2665. ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
  2666. }
  2667. /* SQPOLL thread does its own polling */
  2668. if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
  2669. (ctx->sq_data && ctx->sq_data->thread == current)) {
  2670. while (!wq_list_empty(&ctx->iopoll_list)) {
  2671. io_iopoll_try_reap_events(ctx);
  2672. ret = true;
  2673. cond_resched();
  2674. }
  2675. }
  2676. if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
  2677. io_allowed_defer_tw_run(ctx))
  2678. ret |= io_run_local_work(ctx, INT_MAX) > 0;
  2679. ret |= io_cancel_defer_files(ctx, task, cancel_all);
  2680. mutex_lock(&ctx->uring_lock);
  2681. ret |= io_poll_remove_all(ctx, task, cancel_all);
  2682. ret |= io_waitid_remove_all(ctx, task, cancel_all);
  2683. ret |= io_futex_remove_all(ctx, task, cancel_all);
  2684. ret |= io_uring_try_cancel_uring_cmd(ctx, task, cancel_all);
  2685. mutex_unlock(&ctx->uring_lock);
  2686. ret |= io_kill_timeouts(ctx, task, cancel_all);
  2687. if (task)
  2688. ret |= io_run_task_work() > 0;
  2689. else
  2690. ret |= flush_delayed_work(&ctx->fallback_work);
  2691. return ret;
  2692. }
  2693. static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
  2694. {
  2695. if (tracked)
  2696. return atomic_read(&tctx->inflight_tracked);
  2697. return percpu_counter_sum(&tctx->inflight);
  2698. }
  2699. /*
  2700. * Find any io_uring ctx that this task has registered or done IO on, and cancel
  2701. * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
  2702. */
  2703. __cold void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd)
  2704. {
  2705. struct io_uring_task *tctx = current->io_uring;
  2706. struct io_ring_ctx *ctx;
  2707. struct io_tctx_node *node;
  2708. unsigned long index;
  2709. s64 inflight;
  2710. DEFINE_WAIT(wait);
  2711. WARN_ON_ONCE(sqd && sqd->thread != current);
  2712. if (!current->io_uring)
  2713. return;
  2714. if (tctx->io_wq)
  2715. io_wq_exit_start(tctx->io_wq);
  2716. atomic_inc(&tctx->in_cancel);
  2717. do {
  2718. bool loop = false;
  2719. io_uring_drop_tctx_refs(current);
  2720. if (!tctx_inflight(tctx, !cancel_all))
  2721. break;
  2722. /* read completions before cancelations */
  2723. inflight = tctx_inflight(tctx, false);
  2724. if (!inflight)
  2725. break;
  2726. if (!sqd) {
  2727. xa_for_each(&tctx->xa, index, node) {
  2728. /* sqpoll task will cancel all its requests */
  2729. if (node->ctx->sq_data)
  2730. continue;
  2731. loop |= io_uring_try_cancel_requests(node->ctx,
  2732. current, cancel_all);
  2733. }
  2734. } else {
  2735. list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
  2736. loop |= io_uring_try_cancel_requests(ctx,
  2737. current,
  2738. cancel_all);
  2739. }
  2740. if (loop) {
  2741. cond_resched();
  2742. continue;
  2743. }
  2744. prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
  2745. io_run_task_work();
  2746. io_uring_drop_tctx_refs(current);
  2747. xa_for_each(&tctx->xa, index, node) {
  2748. if (!llist_empty(&node->ctx->work_llist)) {
  2749. WARN_ON_ONCE(node->ctx->submitter_task &&
  2750. node->ctx->submitter_task != current);
  2751. goto end_wait;
  2752. }
  2753. }
  2754. /*
  2755. * If we've seen completions, retry without waiting. This
  2756. * avoids a race where a completion comes in before we did
  2757. * prepare_to_wait().
  2758. */
  2759. if (inflight == tctx_inflight(tctx, !cancel_all))
  2760. schedule();
  2761. end_wait:
  2762. finish_wait(&tctx->wait, &wait);
  2763. } while (1);
  2764. io_uring_clean_tctx(tctx);
  2765. if (cancel_all) {
  2766. /*
  2767. * We shouldn't run task_works after cancel, so just leave
  2768. * ->in_cancel set for normal exit.
  2769. */
  2770. atomic_dec(&tctx->in_cancel);
  2771. /* for exec all current's requests should be gone, kill tctx */
  2772. __io_uring_free(current);
  2773. }
  2774. }
  2775. void __io_uring_cancel(bool cancel_all)
  2776. {
  2777. io_uring_unreg_ringfd();
  2778. io_uring_cancel_generic(cancel_all, NULL);
  2779. }
  2780. static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
  2781. {
  2782. if (flags & IORING_ENTER_EXT_ARG) {
  2783. struct io_uring_getevents_arg arg;
  2784. if (argsz != sizeof(arg))
  2785. return -EINVAL;
  2786. if (copy_from_user(&arg, argp, sizeof(arg)))
  2787. return -EFAULT;
  2788. }
  2789. return 0;
  2790. }
  2791. static int io_get_ext_arg(unsigned flags, const void __user *argp,
  2792. struct ext_arg *ext_arg)
  2793. {
  2794. struct io_uring_getevents_arg arg;
  2795. /*
  2796. * If EXT_ARG isn't set, then we have no timespec and the argp pointer
  2797. * is just a pointer to the sigset_t.
  2798. */
  2799. if (!(flags & IORING_ENTER_EXT_ARG)) {
  2800. ext_arg->sig = (const sigset_t __user *) argp;
  2801. ext_arg->ts = NULL;
  2802. return 0;
  2803. }
  2804. /*
  2805. * EXT_ARG is set - ensure we agree on the size of it and copy in our
  2806. * timespec and sigset_t pointers if good.
  2807. */
  2808. if (ext_arg->argsz != sizeof(arg))
  2809. return -EINVAL;
  2810. if (copy_from_user(&arg, argp, sizeof(arg)))
  2811. return -EFAULT;
  2812. ext_arg->min_time = arg.min_wait_usec * NSEC_PER_USEC;
  2813. ext_arg->sig = u64_to_user_ptr(arg.sigmask);
  2814. ext_arg->argsz = arg.sigmask_sz;
  2815. ext_arg->ts = u64_to_user_ptr(arg.ts);
  2816. return 0;
  2817. }
  2818. SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
  2819. u32, min_complete, u32, flags, const void __user *, argp,
  2820. size_t, argsz)
  2821. {
  2822. struct io_ring_ctx *ctx;
  2823. struct file *file;
  2824. long ret;
  2825. if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
  2826. IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
  2827. IORING_ENTER_REGISTERED_RING |
  2828. IORING_ENTER_ABS_TIMER)))
  2829. return -EINVAL;
  2830. /*
  2831. * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
  2832. * need only dereference our task private array to find it.
  2833. */
  2834. if (flags & IORING_ENTER_REGISTERED_RING) {
  2835. struct io_uring_task *tctx = current->io_uring;
  2836. if (unlikely(!tctx || fd >= IO_RINGFD_REG_MAX))
  2837. return -EINVAL;
  2838. fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
  2839. file = tctx->registered_rings[fd];
  2840. if (unlikely(!file))
  2841. return -EBADF;
  2842. } else {
  2843. file = fget(fd);
  2844. if (unlikely(!file))
  2845. return -EBADF;
  2846. ret = -EOPNOTSUPP;
  2847. if (unlikely(!io_is_uring_fops(file)))
  2848. goto out;
  2849. }
  2850. ctx = file->private_data;
  2851. ret = -EBADFD;
  2852. if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
  2853. goto out;
  2854. /*
  2855. * For SQ polling, the thread will do all submissions and completions.
  2856. * Just return the requested submit count, and wake the thread if
  2857. * we were asked to.
  2858. */
  2859. ret = 0;
  2860. if (ctx->flags & IORING_SETUP_SQPOLL) {
  2861. if (unlikely(ctx->sq_data->thread == NULL)) {
  2862. ret = -EOWNERDEAD;
  2863. goto out;
  2864. }
  2865. if (flags & IORING_ENTER_SQ_WAKEUP)
  2866. wake_up(&ctx->sq_data->wait);
  2867. if (flags & IORING_ENTER_SQ_WAIT)
  2868. io_sqpoll_wait_sq(ctx);
  2869. ret = to_submit;
  2870. } else if (to_submit) {
  2871. ret = io_uring_add_tctx_node(ctx);
  2872. if (unlikely(ret))
  2873. goto out;
  2874. mutex_lock(&ctx->uring_lock);
  2875. ret = io_submit_sqes(ctx, to_submit);
  2876. if (ret != to_submit) {
  2877. mutex_unlock(&ctx->uring_lock);
  2878. goto out;
  2879. }
  2880. if (flags & IORING_ENTER_GETEVENTS) {
  2881. if (ctx->syscall_iopoll)
  2882. goto iopoll_locked;
  2883. /*
  2884. * Ignore errors, we'll soon call io_cqring_wait() and
  2885. * it should handle ownership problems if any.
  2886. */
  2887. if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
  2888. (void)io_run_local_work_locked(ctx, min_complete);
  2889. }
  2890. mutex_unlock(&ctx->uring_lock);
  2891. }
  2892. if (flags & IORING_ENTER_GETEVENTS) {
  2893. int ret2;
  2894. if (ctx->syscall_iopoll) {
  2895. /*
  2896. * We disallow the app entering submit/complete with
  2897. * polling, but we still need to lock the ring to
  2898. * prevent racing with polled issue that got punted to
  2899. * a workqueue.
  2900. */
  2901. mutex_lock(&ctx->uring_lock);
  2902. iopoll_locked:
  2903. ret2 = io_validate_ext_arg(flags, argp, argsz);
  2904. if (likely(!ret2)) {
  2905. min_complete = min(min_complete,
  2906. ctx->cq_entries);
  2907. ret2 = io_iopoll_check(ctx, min_complete);
  2908. }
  2909. mutex_unlock(&ctx->uring_lock);
  2910. } else {
  2911. struct ext_arg ext_arg = { .argsz = argsz };
  2912. ret2 = io_get_ext_arg(flags, argp, &ext_arg);
  2913. if (likely(!ret2)) {
  2914. min_complete = min(min_complete,
  2915. ctx->cq_entries);
  2916. ret2 = io_cqring_wait(ctx, min_complete, flags,
  2917. &ext_arg);
  2918. }
  2919. }
  2920. if (!ret) {
  2921. ret = ret2;
  2922. /*
  2923. * EBADR indicates that one or more CQE were dropped.
  2924. * Once the user has been informed we can clear the bit
  2925. * as they are obviously ok with those drops.
  2926. */
  2927. if (unlikely(ret2 == -EBADR))
  2928. clear_bit(IO_CHECK_CQ_DROPPED_BIT,
  2929. &ctx->check_cq);
  2930. }
  2931. }
  2932. out:
  2933. if (!(flags & IORING_ENTER_REGISTERED_RING))
  2934. fput(file);
  2935. return ret;
  2936. }
  2937. static const struct file_operations io_uring_fops = {
  2938. .release = io_uring_release,
  2939. .mmap = io_uring_mmap,
  2940. .get_unmapped_area = io_uring_get_unmapped_area,
  2941. #ifndef CONFIG_MMU
  2942. .mmap_capabilities = io_uring_nommu_mmap_capabilities,
  2943. #endif
  2944. .poll = io_uring_poll,
  2945. #ifdef CONFIG_PROC_FS
  2946. .show_fdinfo = io_uring_show_fdinfo,
  2947. #endif
  2948. };
  2949. bool io_is_uring_fops(struct file *file)
  2950. {
  2951. return file->f_op == &io_uring_fops;
  2952. }
  2953. static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
  2954. struct io_uring_params *p)
  2955. {
  2956. struct io_rings *rings;
  2957. size_t size, sq_array_offset;
  2958. void *ptr;
  2959. /* make sure these are sane, as we already accounted them */
  2960. ctx->sq_entries = p->sq_entries;
  2961. ctx->cq_entries = p->cq_entries;
  2962. size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
  2963. if (size == SIZE_MAX)
  2964. return -EOVERFLOW;
  2965. if (!(ctx->flags & IORING_SETUP_NO_MMAP))
  2966. rings = io_pages_map(&ctx->ring_pages, &ctx->n_ring_pages, size);
  2967. else
  2968. rings = io_rings_map(ctx, p->cq_off.user_addr, size);
  2969. if (IS_ERR(rings))
  2970. return PTR_ERR(rings);
  2971. ctx->rings = rings;
  2972. if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
  2973. ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
  2974. rings->sq_ring_mask = p->sq_entries - 1;
  2975. rings->cq_ring_mask = p->cq_entries - 1;
  2976. rings->sq_ring_entries = p->sq_entries;
  2977. rings->cq_ring_entries = p->cq_entries;
  2978. if (p->flags & IORING_SETUP_SQE128)
  2979. size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
  2980. else
  2981. size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
  2982. if (size == SIZE_MAX) {
  2983. io_rings_free(ctx);
  2984. return -EOVERFLOW;
  2985. }
  2986. if (!(ctx->flags & IORING_SETUP_NO_MMAP))
  2987. ptr = io_pages_map(&ctx->sqe_pages, &ctx->n_sqe_pages, size);
  2988. else
  2989. ptr = io_sqes_map(ctx, p->sq_off.user_addr, size);
  2990. if (IS_ERR(ptr)) {
  2991. io_rings_free(ctx);
  2992. return PTR_ERR(ptr);
  2993. }
  2994. ctx->sq_sqes = ptr;
  2995. return 0;
  2996. }
  2997. static int io_uring_install_fd(struct file *file)
  2998. {
  2999. int fd;
  3000. fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
  3001. if (fd < 0)
  3002. return fd;
  3003. fd_install(fd, file);
  3004. return fd;
  3005. }
  3006. /*
  3007. * Allocate an anonymous fd, this is what constitutes the application
  3008. * visible backing of an io_uring instance. The application mmaps this
  3009. * fd to gain access to the SQ/CQ ring details.
  3010. */
  3011. static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
  3012. {
  3013. /* Create a new inode so that the LSM can block the creation. */
  3014. return anon_inode_create_getfile("[io_uring]", &io_uring_fops, ctx,
  3015. O_RDWR | O_CLOEXEC, NULL);
  3016. }
  3017. static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
  3018. struct io_uring_params __user *params)
  3019. {
  3020. struct io_ring_ctx *ctx;
  3021. struct io_uring_task *tctx;
  3022. struct file *file;
  3023. int ret;
  3024. if (!entries)
  3025. return -EINVAL;
  3026. if (entries > IORING_MAX_ENTRIES) {
  3027. if (!(p->flags & IORING_SETUP_CLAMP))
  3028. return -EINVAL;
  3029. entries = IORING_MAX_ENTRIES;
  3030. }
  3031. if ((p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
  3032. && !(p->flags & IORING_SETUP_NO_MMAP))
  3033. return -EINVAL;
  3034. /*
  3035. * Use twice as many entries for the CQ ring. It's possible for the
  3036. * application to drive a higher depth than the size of the SQ ring,
  3037. * since the sqes are only used at submission time. This allows for
  3038. * some flexibility in overcommitting a bit. If the application has
  3039. * set IORING_SETUP_CQSIZE, it will have passed in the desired number
  3040. * of CQ ring entries manually.
  3041. */
  3042. p->sq_entries = roundup_pow_of_two(entries);
  3043. if (p->flags & IORING_SETUP_CQSIZE) {
  3044. /*
  3045. * If IORING_SETUP_CQSIZE is set, we do the same roundup
  3046. * to a power-of-two, if it isn't already. We do NOT impose
  3047. * any cq vs sq ring sizing.
  3048. */
  3049. if (!p->cq_entries)
  3050. return -EINVAL;
  3051. if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
  3052. if (!(p->flags & IORING_SETUP_CLAMP))
  3053. return -EINVAL;
  3054. p->cq_entries = IORING_MAX_CQ_ENTRIES;
  3055. }
  3056. p->cq_entries = roundup_pow_of_two(p->cq_entries);
  3057. if (p->cq_entries < p->sq_entries)
  3058. return -EINVAL;
  3059. } else {
  3060. p->cq_entries = 2 * p->sq_entries;
  3061. }
  3062. ctx = io_ring_ctx_alloc(p);
  3063. if (!ctx)
  3064. return -ENOMEM;
  3065. ctx->clockid = CLOCK_MONOTONIC;
  3066. ctx->clock_offset = 0;
  3067. if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
  3068. !(ctx->flags & IORING_SETUP_IOPOLL) &&
  3069. !(ctx->flags & IORING_SETUP_SQPOLL))
  3070. ctx->task_complete = true;
  3071. if (ctx->task_complete || (ctx->flags & IORING_SETUP_IOPOLL))
  3072. ctx->lockless_cq = true;
  3073. /*
  3074. * lazy poll_wq activation relies on ->task_complete for synchronisation
  3075. * purposes, see io_activate_pollwq()
  3076. */
  3077. if (!ctx->task_complete)
  3078. ctx->poll_activated = true;
  3079. /*
  3080. * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
  3081. * space applications don't need to do io completion events
  3082. * polling again, they can rely on io_sq_thread to do polling
  3083. * work, which can reduce cpu usage and uring_lock contention.
  3084. */
  3085. if (ctx->flags & IORING_SETUP_IOPOLL &&
  3086. !(ctx->flags & IORING_SETUP_SQPOLL))
  3087. ctx->syscall_iopoll = 1;
  3088. ctx->compat = in_compat_syscall();
  3089. if (!ns_capable_noaudit(&init_user_ns, CAP_IPC_LOCK))
  3090. ctx->user = get_uid(current_user());
  3091. /*
  3092. * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
  3093. * COOP_TASKRUN is set, then IPIs are never needed by the app.
  3094. */
  3095. ret = -EINVAL;
  3096. if (ctx->flags & IORING_SETUP_SQPOLL) {
  3097. /* IPI related flags don't make sense with SQPOLL */
  3098. if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
  3099. IORING_SETUP_TASKRUN_FLAG |
  3100. IORING_SETUP_DEFER_TASKRUN))
  3101. goto err;
  3102. ctx->notify_method = TWA_SIGNAL_NO_IPI;
  3103. } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
  3104. ctx->notify_method = TWA_SIGNAL_NO_IPI;
  3105. } else {
  3106. if (ctx->flags & IORING_SETUP_TASKRUN_FLAG &&
  3107. !(ctx->flags & IORING_SETUP_DEFER_TASKRUN))
  3108. goto err;
  3109. ctx->notify_method = TWA_SIGNAL;
  3110. }
  3111. /*
  3112. * For DEFER_TASKRUN we require the completion task to be the same as the
  3113. * submission task. This implies that there is only one submitter, so enforce
  3114. * that.
  3115. */
  3116. if (ctx->flags & IORING_SETUP_DEFER_TASKRUN &&
  3117. !(ctx->flags & IORING_SETUP_SINGLE_ISSUER)) {
  3118. goto err;
  3119. }
  3120. /*
  3121. * This is just grabbed for accounting purposes. When a process exits,
  3122. * the mm is exited and dropped before the files, hence we need to hang
  3123. * on to this mm purely for the purposes of being able to unaccount
  3124. * memory (locked/pinned vm). It's not used for anything else.
  3125. */
  3126. mmgrab(current->mm);
  3127. ctx->mm_account = current->mm;
  3128. ret = io_allocate_scq_urings(ctx, p);
  3129. if (ret)
  3130. goto err;
  3131. ret = io_sq_offload_create(ctx, p);
  3132. if (ret)
  3133. goto err;
  3134. ret = io_rsrc_init(ctx);
  3135. if (ret)
  3136. goto err;
  3137. p->sq_off.head = offsetof(struct io_rings, sq.head);
  3138. p->sq_off.tail = offsetof(struct io_rings, sq.tail);
  3139. p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
  3140. p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
  3141. p->sq_off.flags = offsetof(struct io_rings, sq_flags);
  3142. p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
  3143. if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
  3144. p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
  3145. p->sq_off.resv1 = 0;
  3146. if (!(ctx->flags & IORING_SETUP_NO_MMAP))
  3147. p->sq_off.user_addr = 0;
  3148. p->cq_off.head = offsetof(struct io_rings, cq.head);
  3149. p->cq_off.tail = offsetof(struct io_rings, cq.tail);
  3150. p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
  3151. p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
  3152. p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
  3153. p->cq_off.cqes = offsetof(struct io_rings, cqes);
  3154. p->cq_off.flags = offsetof(struct io_rings, cq_flags);
  3155. p->cq_off.resv1 = 0;
  3156. if (!(ctx->flags & IORING_SETUP_NO_MMAP))
  3157. p->cq_off.user_addr = 0;
  3158. p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
  3159. IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
  3160. IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
  3161. IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
  3162. IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
  3163. IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
  3164. IORING_FEAT_LINKED_FILE | IORING_FEAT_REG_REG_RING |
  3165. IORING_FEAT_RECVSEND_BUNDLE | IORING_FEAT_MIN_TIMEOUT;
  3166. if (copy_to_user(params, p, sizeof(*p))) {
  3167. ret = -EFAULT;
  3168. goto err;
  3169. }
  3170. if (ctx->flags & IORING_SETUP_SINGLE_ISSUER
  3171. && !(ctx->flags & IORING_SETUP_R_DISABLED))
  3172. WRITE_ONCE(ctx->submitter_task, get_task_struct(current));
  3173. file = io_uring_get_file(ctx);
  3174. if (IS_ERR(file)) {
  3175. ret = PTR_ERR(file);
  3176. goto err;
  3177. }
  3178. ret = __io_uring_add_tctx_node(ctx);
  3179. if (ret)
  3180. goto err_fput;
  3181. tctx = current->io_uring;
  3182. /*
  3183. * Install ring fd as the very last thing, so we don't risk someone
  3184. * having closed it before we finish setup
  3185. */
  3186. if (p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
  3187. ret = io_ring_add_registered_file(tctx, file, 0, IO_RINGFD_REG_MAX);
  3188. else
  3189. ret = io_uring_install_fd(file);
  3190. if (ret < 0)
  3191. goto err_fput;
  3192. trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
  3193. return ret;
  3194. err:
  3195. io_ring_ctx_wait_and_kill(ctx);
  3196. return ret;
  3197. err_fput:
  3198. fput(file);
  3199. return ret;
  3200. }
  3201. /*
  3202. * Sets up an aio uring context, and returns the fd. Applications asks for a
  3203. * ring size, we return the actual sq/cq ring sizes (among other things) in the
  3204. * params structure passed in.
  3205. */
  3206. static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
  3207. {
  3208. struct io_uring_params p;
  3209. int i;
  3210. if (copy_from_user(&p, params, sizeof(p)))
  3211. return -EFAULT;
  3212. for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
  3213. if (p.resv[i])
  3214. return -EINVAL;
  3215. }
  3216. if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
  3217. IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
  3218. IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
  3219. IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
  3220. IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
  3221. IORING_SETUP_SQE128 | IORING_SETUP_CQE32 |
  3222. IORING_SETUP_SINGLE_ISSUER | IORING_SETUP_DEFER_TASKRUN |
  3223. IORING_SETUP_NO_MMAP | IORING_SETUP_REGISTERED_FD_ONLY |
  3224. IORING_SETUP_NO_SQARRAY))
  3225. return -EINVAL;
  3226. return io_uring_create(entries, &p, params);
  3227. }
  3228. static inline bool io_uring_allowed(void)
  3229. {
  3230. int disabled = READ_ONCE(sysctl_io_uring_disabled);
  3231. kgid_t io_uring_group;
  3232. if (disabled == 2)
  3233. return false;
  3234. if (disabled == 0 || capable(CAP_SYS_ADMIN))
  3235. return true;
  3236. io_uring_group = make_kgid(&init_user_ns, sysctl_io_uring_group);
  3237. if (!gid_valid(io_uring_group))
  3238. return false;
  3239. return in_group_p(io_uring_group);
  3240. }
  3241. SYSCALL_DEFINE2(io_uring_setup, u32, entries,
  3242. struct io_uring_params __user *, params)
  3243. {
  3244. if (!io_uring_allowed())
  3245. return -EPERM;
  3246. return io_uring_setup(entries, params);
  3247. }
  3248. static int __init io_uring_init(void)
  3249. {
  3250. struct kmem_cache_args kmem_args = {
  3251. .useroffset = offsetof(struct io_kiocb, cmd.data),
  3252. .usersize = sizeof_field(struct io_kiocb, cmd.data),
  3253. };
  3254. #define __BUILD_BUG_VERIFY_OFFSET_SIZE(stype, eoffset, esize, ename) do { \
  3255. BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
  3256. BUILD_BUG_ON(sizeof_field(stype, ename) != esize); \
  3257. } while (0)
  3258. #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
  3259. __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, sizeof(etype), ename)
  3260. #define BUILD_BUG_SQE_ELEM_SIZE(eoffset, esize, ename) \
  3261. __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, esize, ename)
  3262. BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
  3263. BUILD_BUG_SQE_ELEM(0, __u8, opcode);
  3264. BUILD_BUG_SQE_ELEM(1, __u8, flags);
  3265. BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
  3266. BUILD_BUG_SQE_ELEM(4, __s32, fd);
  3267. BUILD_BUG_SQE_ELEM(8, __u64, off);
  3268. BUILD_BUG_SQE_ELEM(8, __u64, addr2);
  3269. BUILD_BUG_SQE_ELEM(8, __u32, cmd_op);
  3270. BUILD_BUG_SQE_ELEM(12, __u32, __pad1);
  3271. BUILD_BUG_SQE_ELEM(16, __u64, addr);
  3272. BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
  3273. BUILD_BUG_SQE_ELEM(24, __u32, len);
  3274. BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
  3275. BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
  3276. BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
  3277. BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
  3278. BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
  3279. BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
  3280. BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
  3281. BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
  3282. BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
  3283. BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
  3284. BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
  3285. BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
  3286. BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
  3287. BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
  3288. BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
  3289. BUILD_BUG_SQE_ELEM(28, __u32, rename_flags);
  3290. BUILD_BUG_SQE_ELEM(28, __u32, unlink_flags);
  3291. BUILD_BUG_SQE_ELEM(28, __u32, hardlink_flags);
  3292. BUILD_BUG_SQE_ELEM(28, __u32, xattr_flags);
  3293. BUILD_BUG_SQE_ELEM(28, __u32, msg_ring_flags);
  3294. BUILD_BUG_SQE_ELEM(32, __u64, user_data);
  3295. BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
  3296. BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
  3297. BUILD_BUG_SQE_ELEM(42, __u16, personality);
  3298. BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
  3299. BUILD_BUG_SQE_ELEM(44, __u32, file_index);
  3300. BUILD_BUG_SQE_ELEM(44, __u16, addr_len);
  3301. BUILD_BUG_SQE_ELEM(46, __u16, __pad3[0]);
  3302. BUILD_BUG_SQE_ELEM(48, __u64, addr3);
  3303. BUILD_BUG_SQE_ELEM_SIZE(48, 0, cmd);
  3304. BUILD_BUG_SQE_ELEM(56, __u64, __pad2);
  3305. BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
  3306. sizeof(struct io_uring_rsrc_update));
  3307. BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
  3308. sizeof(struct io_uring_rsrc_update2));
  3309. /* ->buf_index is u16 */
  3310. BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
  3311. BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
  3312. offsetof(struct io_uring_buf_ring, tail));
  3313. /* should fit into one byte */
  3314. BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
  3315. BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
  3316. BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
  3317. BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof_field(struct io_kiocb, flags));
  3318. BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
  3319. /* top 8bits are for internal use */
  3320. BUILD_BUG_ON((IORING_URING_CMD_MASK & 0xff000000) != 0);
  3321. io_uring_optable_init();
  3322. /*
  3323. * Allow user copy in the per-command field, which starts after the
  3324. * file in io_kiocb and until the opcode field. The openat2 handling
  3325. * requires copying in user memory into the io_kiocb object in that
  3326. * range, and HARDENED_USERCOPY will complain if we haven't
  3327. * correctly annotated this range.
  3328. */
  3329. req_cachep = kmem_cache_create("io_kiocb", sizeof(struct io_kiocb), &kmem_args,
  3330. SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT |
  3331. SLAB_TYPESAFE_BY_RCU);
  3332. io_buf_cachep = KMEM_CACHE(io_buffer,
  3333. SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT);
  3334. iou_wq = alloc_workqueue("iou_exit", WQ_UNBOUND, 64);
  3335. #ifdef CONFIG_SYSCTL
  3336. register_sysctl_init("kernel", kernel_io_uring_disabled_table);
  3337. #endif
  3338. return 0;
  3339. };
  3340. __initcall(io_uring_init);