io_uring.c 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229
  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.org/pub/scm/linux/kernel/git/axboe/liburing.git
  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/errno.h>
  44. #include <linux/syscalls.h>
  45. #include <linux/refcount.h>
  46. #include <linux/bits.h>
  47. #include <linux/sched/signal.h>
  48. #include <linux/fs.h>
  49. #include <linux/mm.h>
  50. #include <linux/percpu.h>
  51. #include <linux/slab.h>
  52. #include <linux/anon_inodes.h>
  53. #include <linux/uaccess.h>
  54. #include <linux/nospec.h>
  55. #include <linux/task_work.h>
  56. #include <linux/io_uring.h>
  57. #include <linux/io_uring/cmd.h>
  58. #include <linux/audit.h>
  59. #include <linux/security.h>
  60. #include <linux/jump_label.h>
  61. #define CREATE_TRACE_POINTS
  62. #include <trace/events/io_uring.h>
  63. #include <uapi/linux/io_uring.h>
  64. #include "io-wq.h"
  65. #include "filetable.h"
  66. #include "io_uring.h"
  67. #include "opdef.h"
  68. #include "refs.h"
  69. #include "tctx.h"
  70. #include "register.h"
  71. #include "sqpoll.h"
  72. #include "fdinfo.h"
  73. #include "kbuf.h"
  74. #include "rsrc.h"
  75. #include "cancel.h"
  76. #include "net.h"
  77. #include "notif.h"
  78. #include "waitid.h"
  79. #include "futex.h"
  80. #include "napi.h"
  81. #include "uring_cmd.h"
  82. #include "msg_ring.h"
  83. #include "memmap.h"
  84. #include "zcrx.h"
  85. #include "timeout.h"
  86. #include "poll.h"
  87. #include "rw.h"
  88. #include "alloc_cache.h"
  89. #include "eventfd.h"
  90. #include "wait.h"
  91. #include "bpf_filter.h"
  92. #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
  93. IOSQE_IO_HARDLINK | IOSQE_ASYNC)
  94. #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
  95. #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
  96. REQ_F_INFLIGHT | REQ_F_CREDS | REQ_F_ASYNC_DATA)
  97. #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | IO_REQ_LINK_FLAGS | \
  98. REQ_F_REISSUE | REQ_F_POLLED | \
  99. IO_REQ_CLEAN_FLAGS)
  100. #define IO_TCTX_REFS_CACHE_NR (1U << 10)
  101. #define IO_COMPL_BATCH 32
  102. #define IO_REQ_ALLOC_BATCH 8
  103. /* requests with any of those set should undergo io_disarm_next() */
  104. #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
  105. static void io_queue_sqe(struct io_kiocb *req, unsigned int extra_flags);
  106. static void __io_req_caches_free(struct io_ring_ctx *ctx);
  107. static __read_mostly DEFINE_STATIC_KEY_DEFERRED_FALSE(io_key_has_sqarray, HZ);
  108. struct kmem_cache *req_cachep;
  109. static struct workqueue_struct *iou_wq __ro_after_init;
  110. static int __read_mostly sysctl_io_uring_disabled;
  111. static int __read_mostly sysctl_io_uring_group = -1;
  112. #ifdef CONFIG_SYSCTL
  113. static const struct ctl_table kernel_io_uring_disabled_table[] = {
  114. {
  115. .procname = "io_uring_disabled",
  116. .data = &sysctl_io_uring_disabled,
  117. .maxlen = sizeof(sysctl_io_uring_disabled),
  118. .mode = 0644,
  119. .proc_handler = proc_dointvec_minmax,
  120. .extra1 = SYSCTL_ZERO,
  121. .extra2 = SYSCTL_TWO,
  122. },
  123. {
  124. .procname = "io_uring_group",
  125. .data = &sysctl_io_uring_group,
  126. .maxlen = sizeof(gid_t),
  127. .mode = 0644,
  128. .proc_handler = proc_dointvec,
  129. },
  130. };
  131. #endif
  132. static void io_poison_cached_req(struct io_kiocb *req)
  133. {
  134. req->ctx = IO_URING_PTR_POISON;
  135. req->tctx = IO_URING_PTR_POISON;
  136. req->file = IO_URING_PTR_POISON;
  137. req->creds = IO_URING_PTR_POISON;
  138. req->io_task_work.func = IO_URING_PTR_POISON;
  139. req->apoll = IO_URING_PTR_POISON;
  140. }
  141. static void io_poison_req(struct io_kiocb *req)
  142. {
  143. io_poison_cached_req(req);
  144. req->async_data = IO_URING_PTR_POISON;
  145. req->kbuf = IO_URING_PTR_POISON;
  146. req->comp_list.next = IO_URING_PTR_POISON;
  147. req->file_node = IO_URING_PTR_POISON;
  148. req->link = IO_URING_PTR_POISON;
  149. }
  150. static inline void req_fail_link_node(struct io_kiocb *req, int res)
  151. {
  152. req_set_fail(req);
  153. io_req_set_res(req, res, 0);
  154. }
  155. static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
  156. {
  157. if (IS_ENABLED(CONFIG_KASAN))
  158. io_poison_cached_req(req);
  159. wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
  160. }
  161. static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
  162. {
  163. struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
  164. complete(&ctx->ref_comp);
  165. }
  166. static int io_alloc_hash_table(struct io_hash_table *table, unsigned bits)
  167. {
  168. unsigned int hash_buckets;
  169. int i;
  170. do {
  171. hash_buckets = 1U << bits;
  172. table->hbs = kvmalloc_objs(table->hbs[0], hash_buckets,
  173. GFP_KERNEL_ACCOUNT);
  174. if (table->hbs)
  175. break;
  176. if (bits == 1)
  177. return -ENOMEM;
  178. bits--;
  179. } while (1);
  180. table->hash_bits = bits;
  181. for (i = 0; i < hash_buckets; i++)
  182. INIT_HLIST_HEAD(&table->hbs[i].list);
  183. return 0;
  184. }
  185. static void io_free_alloc_caches(struct io_ring_ctx *ctx)
  186. {
  187. io_alloc_cache_free(&ctx->apoll_cache, kfree);
  188. io_alloc_cache_free(&ctx->netmsg_cache, io_netmsg_cache_free);
  189. io_alloc_cache_free(&ctx->rw_cache, io_rw_cache_free);
  190. io_alloc_cache_free(&ctx->cmd_cache, io_cmd_cache_free);
  191. io_futex_cache_free(ctx);
  192. io_rsrc_cache_free(ctx);
  193. }
  194. static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
  195. {
  196. struct io_ring_ctx *ctx;
  197. int hash_bits;
  198. bool ret;
  199. ctx = kzalloc_obj(*ctx);
  200. if (!ctx)
  201. return NULL;
  202. xa_init(&ctx->io_bl_xa);
  203. /*
  204. * Use 5 bits less than the max cq entries, that should give us around
  205. * 32 entries per hash list if totally full and uniformly spread, but
  206. * don't keep too many buckets to not overconsume memory.
  207. */
  208. hash_bits = ilog2(p->cq_entries) - 5;
  209. hash_bits = clamp(hash_bits, 1, 8);
  210. if (io_alloc_hash_table(&ctx->cancel_table, hash_bits))
  211. goto err;
  212. if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
  213. 0, GFP_KERNEL))
  214. goto err;
  215. ctx->flags = p->flags;
  216. ctx->hybrid_poll_time = LLONG_MAX;
  217. atomic_set(&ctx->cq_wait_nr, IO_CQ_WAKE_INIT);
  218. init_waitqueue_head(&ctx->sqo_sq_wait);
  219. INIT_LIST_HEAD(&ctx->sqd_list);
  220. INIT_LIST_HEAD(&ctx->cq_overflow_list);
  221. ret = io_alloc_cache_init(&ctx->apoll_cache, IO_POLL_ALLOC_CACHE_MAX,
  222. sizeof(struct async_poll), 0);
  223. ret |= io_alloc_cache_init(&ctx->netmsg_cache, IO_ALLOC_CACHE_MAX,
  224. sizeof(struct io_async_msghdr),
  225. offsetof(struct io_async_msghdr, clear));
  226. ret |= io_alloc_cache_init(&ctx->rw_cache, IO_ALLOC_CACHE_MAX,
  227. sizeof(struct io_async_rw),
  228. offsetof(struct io_async_rw, clear));
  229. ret |= io_alloc_cache_init(&ctx->cmd_cache, IO_ALLOC_CACHE_MAX,
  230. sizeof(struct io_async_cmd),
  231. sizeof(struct io_async_cmd));
  232. ret |= io_futex_cache_init(ctx);
  233. ret |= io_rsrc_cache_init(ctx);
  234. if (ret)
  235. goto free_ref;
  236. init_completion(&ctx->ref_comp);
  237. xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
  238. mutex_init(&ctx->uring_lock);
  239. init_waitqueue_head(&ctx->cq_wait);
  240. init_waitqueue_head(&ctx->poll_wq);
  241. spin_lock_init(&ctx->completion_lock);
  242. raw_spin_lock_init(&ctx->timeout_lock);
  243. INIT_LIST_HEAD(&ctx->iopoll_list);
  244. INIT_LIST_HEAD(&ctx->defer_list);
  245. INIT_LIST_HEAD(&ctx->timeout_list);
  246. INIT_LIST_HEAD(&ctx->ltimeout_list);
  247. init_llist_head(&ctx->work_llist);
  248. INIT_LIST_HEAD(&ctx->tctx_list);
  249. mutex_init(&ctx->tctx_lock);
  250. ctx->submit_state.free_list.next = NULL;
  251. INIT_HLIST_HEAD(&ctx->waitid_list);
  252. xa_init_flags(&ctx->zcrx_ctxs, XA_FLAGS_ALLOC);
  253. #ifdef CONFIG_FUTEX
  254. INIT_HLIST_HEAD(&ctx->futex_list);
  255. #endif
  256. INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
  257. INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
  258. INIT_HLIST_HEAD(&ctx->cancelable_uring_cmd);
  259. io_napi_init(ctx);
  260. mutex_init(&ctx->mmap_lock);
  261. return ctx;
  262. free_ref:
  263. percpu_ref_exit(&ctx->refs);
  264. err:
  265. io_free_alloc_caches(ctx);
  266. kvfree(ctx->cancel_table.hbs);
  267. xa_destroy(&ctx->io_bl_xa);
  268. kfree(ctx);
  269. return NULL;
  270. }
  271. static void io_clean_op(struct io_kiocb *req)
  272. {
  273. if (unlikely(req->flags & REQ_F_BUFFER_SELECTED))
  274. io_kbuf_drop_legacy(req);
  275. if (req->flags & REQ_F_NEED_CLEANUP) {
  276. const struct io_cold_def *def = &io_cold_defs[req->opcode];
  277. if (def->cleanup)
  278. def->cleanup(req);
  279. }
  280. if (req->flags & REQ_F_INFLIGHT)
  281. atomic_dec(&req->tctx->inflight_tracked);
  282. if (req->flags & REQ_F_CREDS)
  283. put_cred(req->creds);
  284. if (req->flags & REQ_F_ASYNC_DATA) {
  285. kfree(req->async_data);
  286. req->async_data = NULL;
  287. }
  288. req->flags &= ~IO_REQ_CLEAN_FLAGS;
  289. }
  290. /*
  291. * Mark the request as inflight, so that file cancelation will find it.
  292. * Can be used if the file is an io_uring instance, or if the request itself
  293. * relies on ->mm being alive for the duration of the request.
  294. */
  295. inline void io_req_track_inflight(struct io_kiocb *req)
  296. {
  297. if (!(req->flags & REQ_F_INFLIGHT)) {
  298. req->flags |= REQ_F_INFLIGHT;
  299. atomic_inc(&req->tctx->inflight_tracked);
  300. }
  301. }
  302. static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
  303. {
  304. if (WARN_ON_ONCE(!req->link))
  305. return NULL;
  306. req->flags &= ~REQ_F_ARM_LTIMEOUT;
  307. req->flags |= REQ_F_LINK_TIMEOUT;
  308. /* linked timeouts should have two refs once prep'ed */
  309. io_req_set_refcount(req);
  310. __io_req_set_refcount(req->link, 2);
  311. return req->link;
  312. }
  313. static void io_prep_async_work(struct io_kiocb *req)
  314. {
  315. const struct io_issue_def *def = &io_issue_defs[req->opcode];
  316. struct io_ring_ctx *ctx = req->ctx;
  317. if (!(req->flags & REQ_F_CREDS)) {
  318. req->flags |= REQ_F_CREDS;
  319. req->creds = get_current_cred();
  320. }
  321. req->work.list.next = NULL;
  322. atomic_set(&req->work.flags, 0);
  323. if (req->flags & REQ_F_FORCE_ASYNC)
  324. atomic_or(IO_WQ_WORK_CONCURRENT, &req->work.flags);
  325. if (req->file && !(req->flags & REQ_F_FIXED_FILE))
  326. req->flags |= io_file_get_flags(req->file);
  327. if (req->file && (req->flags & REQ_F_ISREG)) {
  328. bool should_hash = def->hash_reg_file;
  329. /* don't serialize this request if the fs doesn't need it */
  330. if (should_hash && (req->file->f_flags & O_DIRECT) &&
  331. (req->file->f_op->fop_flags & FOP_DIO_PARALLEL_WRITE))
  332. should_hash = false;
  333. if (should_hash || (ctx->flags & IORING_SETUP_IOPOLL))
  334. io_wq_hash_work(&req->work, file_inode(req->file));
  335. } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
  336. if (def->unbound_nonreg_file)
  337. atomic_or(IO_WQ_WORK_UNBOUND, &req->work.flags);
  338. }
  339. }
  340. static void io_prep_async_link(struct io_kiocb *req)
  341. {
  342. struct io_kiocb *cur;
  343. if (req->flags & REQ_F_LINK_TIMEOUT) {
  344. struct io_ring_ctx *ctx = req->ctx;
  345. raw_spin_lock_irq(&ctx->timeout_lock);
  346. io_for_each_link(cur, req)
  347. io_prep_async_work(cur);
  348. raw_spin_unlock_irq(&ctx->timeout_lock);
  349. } else {
  350. io_for_each_link(cur, req)
  351. io_prep_async_work(cur);
  352. }
  353. }
  354. static void io_queue_iowq(struct io_kiocb *req)
  355. {
  356. struct io_uring_task *tctx = req->tctx;
  357. BUG_ON(!tctx);
  358. if ((current->flags & PF_KTHREAD) || !tctx->io_wq) {
  359. io_req_task_queue_fail(req, -ECANCELED);
  360. return;
  361. }
  362. /* init ->work of the whole link before punting */
  363. io_prep_async_link(req);
  364. /*
  365. * Not expected to happen, but if we do have a bug where this _can_
  366. * happen, catch it here and ensure the request is marked as
  367. * canceled. That will make io-wq go through the usual work cancel
  368. * procedure rather than attempt to run this request (or create a new
  369. * worker for it).
  370. */
  371. if (WARN_ON_ONCE(!same_thread_group(tctx->task, current)))
  372. atomic_or(IO_WQ_WORK_CANCEL, &req->work.flags);
  373. trace_io_uring_queue_async_work(req, io_wq_is_hashed(&req->work));
  374. io_wq_enqueue(tctx->io_wq, &req->work);
  375. }
  376. static void io_req_queue_iowq_tw(struct io_tw_req tw_req, io_tw_token_t tw)
  377. {
  378. io_queue_iowq(tw_req.req);
  379. }
  380. void io_req_queue_iowq(struct io_kiocb *req)
  381. {
  382. req->io_task_work.func = io_req_queue_iowq_tw;
  383. io_req_task_work_add(req);
  384. }
  385. unsigned io_linked_nr(struct io_kiocb *req)
  386. {
  387. struct io_kiocb *tmp;
  388. unsigned nr = 0;
  389. io_for_each_link(tmp, req)
  390. nr++;
  391. return nr;
  392. }
  393. static __cold noinline void io_queue_deferred(struct io_ring_ctx *ctx)
  394. {
  395. bool drain_seen = false, first = true;
  396. lockdep_assert_held(&ctx->uring_lock);
  397. __io_req_caches_free(ctx);
  398. while (!list_empty(&ctx->defer_list)) {
  399. struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
  400. struct io_defer_entry, list);
  401. drain_seen |= de->req->flags & REQ_F_IO_DRAIN;
  402. if ((drain_seen || first) && ctx->nr_req_allocated != ctx->nr_drained)
  403. return;
  404. list_del_init(&de->list);
  405. ctx->nr_drained -= io_linked_nr(de->req);
  406. io_req_task_queue(de->req);
  407. kfree(de);
  408. first = false;
  409. }
  410. }
  411. void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
  412. {
  413. if (ctx->poll_activated)
  414. io_poll_wq_wake(ctx);
  415. if (ctx->off_timeout_used)
  416. io_flush_timeouts(ctx);
  417. if (ctx->has_evfd)
  418. io_eventfd_signal(ctx, true);
  419. }
  420. static inline void __io_cq_lock(struct io_ring_ctx *ctx)
  421. {
  422. if (!ctx->lockless_cq)
  423. spin_lock(&ctx->completion_lock);
  424. }
  425. static inline void io_cq_lock(struct io_ring_ctx *ctx)
  426. __acquires(ctx->completion_lock)
  427. {
  428. spin_lock(&ctx->completion_lock);
  429. }
  430. static inline void __io_cq_unlock_post(struct io_ring_ctx *ctx)
  431. {
  432. io_commit_cqring(ctx);
  433. if (!ctx->task_complete) {
  434. if (!ctx->lockless_cq)
  435. spin_unlock(&ctx->completion_lock);
  436. /* IOPOLL rings only need to wake up if it's also SQPOLL */
  437. if (!ctx->syscall_iopoll)
  438. io_cqring_wake(ctx);
  439. }
  440. io_commit_cqring_flush(ctx);
  441. }
  442. static void io_cq_unlock_post(struct io_ring_ctx *ctx)
  443. __releases(ctx->completion_lock)
  444. {
  445. io_commit_cqring(ctx);
  446. spin_unlock(&ctx->completion_lock);
  447. io_cqring_wake(ctx);
  448. io_commit_cqring_flush(ctx);
  449. }
  450. static void __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool dying)
  451. {
  452. lockdep_assert_held(&ctx->uring_lock);
  453. /* don't abort if we're dying, entries must get freed */
  454. if (!dying && __io_cqring_events(ctx) == ctx->cq_entries)
  455. return;
  456. io_cq_lock(ctx);
  457. while (!list_empty(&ctx->cq_overflow_list)) {
  458. size_t cqe_size = sizeof(struct io_uring_cqe);
  459. struct io_uring_cqe *cqe;
  460. struct io_overflow_cqe *ocqe;
  461. bool is_cqe32 = false;
  462. ocqe = list_first_entry(&ctx->cq_overflow_list,
  463. struct io_overflow_cqe, list);
  464. if (ocqe->cqe.flags & IORING_CQE_F_32 ||
  465. ctx->flags & IORING_SETUP_CQE32) {
  466. is_cqe32 = true;
  467. cqe_size <<= 1;
  468. }
  469. if (ctx->flags & IORING_SETUP_CQE32)
  470. is_cqe32 = false;
  471. if (!dying) {
  472. if (!io_get_cqe_overflow(ctx, &cqe, true, is_cqe32))
  473. break;
  474. memcpy(cqe, &ocqe->cqe, cqe_size);
  475. }
  476. list_del(&ocqe->list);
  477. kfree(ocqe);
  478. /*
  479. * For silly syzbot cases that deliberately overflow by huge
  480. * amounts, check if we need to resched and drop and
  481. * reacquire the locks if so. Nothing real would ever hit this.
  482. * Ideally we'd have a non-posting unlock for this, but hard
  483. * to care for a non-real case.
  484. */
  485. if (need_resched()) {
  486. ctx->cqe_sentinel = ctx->cqe_cached;
  487. io_cq_unlock_post(ctx);
  488. mutex_unlock(&ctx->uring_lock);
  489. cond_resched();
  490. mutex_lock(&ctx->uring_lock);
  491. io_cq_lock(ctx);
  492. }
  493. }
  494. if (list_empty(&ctx->cq_overflow_list)) {
  495. clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
  496. atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
  497. }
  498. io_cq_unlock_post(ctx);
  499. }
  500. static void io_cqring_overflow_kill(struct io_ring_ctx *ctx)
  501. {
  502. if (ctx->rings)
  503. __io_cqring_overflow_flush(ctx, true);
  504. }
  505. void io_cqring_do_overflow_flush(struct io_ring_ctx *ctx)
  506. {
  507. mutex_lock(&ctx->uring_lock);
  508. __io_cqring_overflow_flush(ctx, false);
  509. mutex_unlock(&ctx->uring_lock);
  510. }
  511. /* must to be called somewhat shortly after putting a request */
  512. static inline void io_put_task(struct io_kiocb *req)
  513. {
  514. struct io_uring_task *tctx = req->tctx;
  515. if (likely(tctx->task == current)) {
  516. tctx->cached_refs++;
  517. } else {
  518. percpu_counter_sub(&tctx->inflight, 1);
  519. if (unlikely(atomic_read(&tctx->in_cancel)))
  520. wake_up(&tctx->wait);
  521. put_task_struct(tctx->task);
  522. }
  523. }
  524. void io_task_refs_refill(struct io_uring_task *tctx)
  525. {
  526. unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
  527. percpu_counter_add(&tctx->inflight, refill);
  528. refcount_add(refill, &current->usage);
  529. tctx->cached_refs += refill;
  530. }
  531. __cold void io_uring_drop_tctx_refs(struct task_struct *task)
  532. {
  533. struct io_uring_task *tctx = task->io_uring;
  534. unsigned int refs = tctx->cached_refs;
  535. if (refs) {
  536. tctx->cached_refs = 0;
  537. percpu_counter_sub(&tctx->inflight, refs);
  538. put_task_struct_many(task, refs);
  539. }
  540. }
  541. static __cold bool io_cqring_add_overflow(struct io_ring_ctx *ctx,
  542. struct io_overflow_cqe *ocqe)
  543. {
  544. lockdep_assert_held(&ctx->completion_lock);
  545. if (!ocqe) {
  546. struct io_rings *r = ctx->rings;
  547. /*
  548. * If we're in ring overflow flush mode, or in task cancel mode,
  549. * or cannot allocate an overflow entry, then we need to drop it
  550. * on the floor.
  551. */
  552. WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
  553. set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
  554. return false;
  555. }
  556. if (list_empty(&ctx->cq_overflow_list)) {
  557. set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
  558. atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
  559. }
  560. list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
  561. return true;
  562. }
  563. static struct io_overflow_cqe *io_alloc_ocqe(struct io_ring_ctx *ctx,
  564. struct io_cqe *cqe,
  565. struct io_big_cqe *big_cqe, gfp_t gfp)
  566. {
  567. struct io_overflow_cqe *ocqe;
  568. size_t ocq_size = sizeof(struct io_overflow_cqe);
  569. bool is_cqe32 = false;
  570. if (cqe->flags & IORING_CQE_F_32 || ctx->flags & IORING_SETUP_CQE32) {
  571. is_cqe32 = true;
  572. ocq_size += sizeof(struct io_uring_cqe);
  573. }
  574. ocqe = kzalloc(ocq_size, gfp | __GFP_ACCOUNT);
  575. trace_io_uring_cqe_overflow(ctx, cqe->user_data, cqe->res, cqe->flags, ocqe);
  576. if (ocqe) {
  577. ocqe->cqe.user_data = cqe->user_data;
  578. ocqe->cqe.res = cqe->res;
  579. ocqe->cqe.flags = cqe->flags;
  580. if (is_cqe32 && big_cqe) {
  581. ocqe->cqe.big_cqe[0] = big_cqe->extra1;
  582. ocqe->cqe.big_cqe[1] = big_cqe->extra2;
  583. }
  584. }
  585. if (big_cqe)
  586. big_cqe->extra1 = big_cqe->extra2 = 0;
  587. return ocqe;
  588. }
  589. /*
  590. * Fill an empty dummy CQE, in case alignment is off for posting a 32b CQE
  591. * because the ring is a single 16b entry away from wrapping.
  592. */
  593. static bool io_fill_nop_cqe(struct io_ring_ctx *ctx, unsigned int off)
  594. {
  595. if (__io_cqring_events(ctx) < ctx->cq_entries) {
  596. struct io_uring_cqe *cqe = &ctx->rings->cqes[off];
  597. cqe->user_data = 0;
  598. cqe->res = 0;
  599. cqe->flags = IORING_CQE_F_SKIP;
  600. ctx->cached_cq_tail++;
  601. return true;
  602. }
  603. return false;
  604. }
  605. /*
  606. * writes to the cq entry need to come after reading head; the
  607. * control dependency is enough as we're using WRITE_ONCE to
  608. * fill the cq entry
  609. */
  610. bool io_cqe_cache_refill(struct io_ring_ctx *ctx, bool overflow, bool cqe32)
  611. {
  612. struct io_rings *rings = ctx->rings;
  613. unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
  614. unsigned int free, queued, len;
  615. /*
  616. * Posting into the CQ when there are pending overflowed CQEs may break
  617. * ordering guarantees, which will affect links, F_MORE users and more.
  618. * Force overflow the completion.
  619. */
  620. if (!overflow && (ctx->check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT)))
  621. return false;
  622. /*
  623. * Post dummy CQE if a 32b CQE is needed and there's only room for a
  624. * 16b CQE before the ring wraps.
  625. */
  626. if (cqe32 && off + 1 == ctx->cq_entries) {
  627. if (!io_fill_nop_cqe(ctx, off))
  628. return false;
  629. off = 0;
  630. }
  631. /* userspace may cheat modifying the tail, be safe and do min */
  632. queued = min(__io_cqring_events(ctx), ctx->cq_entries);
  633. free = ctx->cq_entries - queued;
  634. /* we need a contiguous range, limit based on the current array offset */
  635. len = min(free, ctx->cq_entries - off);
  636. if (len < (cqe32 + 1))
  637. return false;
  638. if (ctx->flags & IORING_SETUP_CQE32) {
  639. off <<= 1;
  640. len <<= 1;
  641. }
  642. ctx->cqe_cached = &rings->cqes[off];
  643. ctx->cqe_sentinel = ctx->cqe_cached + len;
  644. return true;
  645. }
  646. static bool io_fill_cqe_aux32(struct io_ring_ctx *ctx,
  647. struct io_uring_cqe src_cqe[2])
  648. {
  649. struct io_uring_cqe *cqe;
  650. if (WARN_ON_ONCE(!(ctx->flags & (IORING_SETUP_CQE32|IORING_SETUP_CQE_MIXED))))
  651. return false;
  652. if (unlikely(!io_get_cqe(ctx, &cqe, true)))
  653. return false;
  654. memcpy(cqe, src_cqe, 2 * sizeof(*cqe));
  655. trace_io_uring_complete(ctx, NULL, cqe);
  656. return true;
  657. }
  658. static bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data, s32 res,
  659. u32 cflags)
  660. {
  661. bool cqe32 = cflags & IORING_CQE_F_32;
  662. struct io_uring_cqe *cqe;
  663. if (likely(io_get_cqe(ctx, &cqe, cqe32))) {
  664. WRITE_ONCE(cqe->user_data, user_data);
  665. WRITE_ONCE(cqe->res, res);
  666. WRITE_ONCE(cqe->flags, cflags);
  667. if (cqe32) {
  668. WRITE_ONCE(cqe->big_cqe[0], 0);
  669. WRITE_ONCE(cqe->big_cqe[1], 0);
  670. }
  671. trace_io_uring_complete(ctx, NULL, cqe);
  672. return true;
  673. }
  674. return false;
  675. }
  676. static inline struct io_cqe io_init_cqe(u64 user_data, s32 res, u32 cflags)
  677. {
  678. return (struct io_cqe) { .user_data = user_data, .res = res, .flags = cflags };
  679. }
  680. static __cold void io_cqe_overflow(struct io_ring_ctx *ctx, struct io_cqe *cqe,
  681. struct io_big_cqe *big_cqe)
  682. {
  683. struct io_overflow_cqe *ocqe;
  684. ocqe = io_alloc_ocqe(ctx, cqe, big_cqe, GFP_KERNEL);
  685. spin_lock(&ctx->completion_lock);
  686. io_cqring_add_overflow(ctx, ocqe);
  687. spin_unlock(&ctx->completion_lock);
  688. }
  689. static __cold bool io_cqe_overflow_locked(struct io_ring_ctx *ctx,
  690. struct io_cqe *cqe,
  691. struct io_big_cqe *big_cqe)
  692. {
  693. struct io_overflow_cqe *ocqe;
  694. ocqe = io_alloc_ocqe(ctx, cqe, big_cqe, GFP_NOWAIT);
  695. return io_cqring_add_overflow(ctx, ocqe);
  696. }
  697. bool io_post_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
  698. {
  699. bool filled;
  700. io_cq_lock(ctx);
  701. filled = io_fill_cqe_aux(ctx, user_data, res, cflags);
  702. if (unlikely(!filled)) {
  703. struct io_cqe cqe = io_init_cqe(user_data, res, cflags);
  704. filled = io_cqe_overflow_locked(ctx, &cqe, NULL);
  705. }
  706. io_cq_unlock_post(ctx);
  707. return filled;
  708. }
  709. /*
  710. * Must be called from inline task_work so we know a flush will happen later,
  711. * and obviously with ctx->uring_lock held (tw always has that).
  712. */
  713. void io_add_aux_cqe(struct io_ring_ctx *ctx, u64 user_data, s32 res, u32 cflags)
  714. {
  715. lockdep_assert_held(&ctx->uring_lock);
  716. lockdep_assert(ctx->lockless_cq);
  717. if (!io_fill_cqe_aux(ctx, user_data, res, cflags)) {
  718. struct io_cqe cqe = io_init_cqe(user_data, res, cflags);
  719. io_cqe_overflow(ctx, &cqe, NULL);
  720. }
  721. ctx->submit_state.cq_flush = true;
  722. }
  723. /*
  724. * A helper for multishot requests posting additional CQEs.
  725. * Should only be used from a task_work including IO_URING_F_MULTISHOT.
  726. */
  727. bool io_req_post_cqe(struct io_kiocb *req, s32 res, u32 cflags)
  728. {
  729. struct io_ring_ctx *ctx = req->ctx;
  730. bool posted;
  731. /*
  732. * If multishot has already posted deferred completions, ensure that
  733. * those are flushed first before posting this one. If not, CQEs
  734. * could get reordered.
  735. */
  736. if (!wq_list_empty(&ctx->submit_state.compl_reqs))
  737. __io_submit_flush_completions(ctx);
  738. lockdep_assert(!io_wq_current_is_worker());
  739. lockdep_assert_held(&ctx->uring_lock);
  740. if (!ctx->lockless_cq) {
  741. spin_lock(&ctx->completion_lock);
  742. posted = io_fill_cqe_aux(ctx, req->cqe.user_data, res, cflags);
  743. spin_unlock(&ctx->completion_lock);
  744. } else {
  745. posted = io_fill_cqe_aux(ctx, req->cqe.user_data, res, cflags);
  746. }
  747. ctx->submit_state.cq_flush = true;
  748. return posted;
  749. }
  750. /*
  751. * A helper for multishot requests posting additional CQEs.
  752. * Should only be used from a task_work including IO_URING_F_MULTISHOT.
  753. */
  754. bool io_req_post_cqe32(struct io_kiocb *req, struct io_uring_cqe cqe[2])
  755. {
  756. struct io_ring_ctx *ctx = req->ctx;
  757. bool posted;
  758. lockdep_assert(!io_wq_current_is_worker());
  759. lockdep_assert_held(&ctx->uring_lock);
  760. cqe[0].user_data = req->cqe.user_data;
  761. if (!ctx->lockless_cq) {
  762. spin_lock(&ctx->completion_lock);
  763. posted = io_fill_cqe_aux32(ctx, cqe);
  764. spin_unlock(&ctx->completion_lock);
  765. } else {
  766. posted = io_fill_cqe_aux32(ctx, cqe);
  767. }
  768. ctx->submit_state.cq_flush = true;
  769. return posted;
  770. }
  771. static void io_req_complete_post(struct io_kiocb *req, unsigned issue_flags)
  772. {
  773. struct io_ring_ctx *ctx = req->ctx;
  774. bool completed = true;
  775. /*
  776. * All execution paths but io-wq use the deferred completions by
  777. * passing IO_URING_F_COMPLETE_DEFER and thus should not end up here.
  778. */
  779. if (WARN_ON_ONCE(!(issue_flags & IO_URING_F_IOWQ)))
  780. return;
  781. /*
  782. * Handle special CQ sync cases via task_work. DEFER_TASKRUN requires
  783. * the submitter task context, IOPOLL protects with uring_lock.
  784. */
  785. if (ctx->lockless_cq || (req->flags & REQ_F_REISSUE)) {
  786. defer_complete:
  787. req->io_task_work.func = io_req_task_complete;
  788. io_req_task_work_add(req);
  789. return;
  790. }
  791. io_cq_lock(ctx);
  792. if (!(req->flags & REQ_F_CQE_SKIP))
  793. completed = io_fill_cqe_req(ctx, req);
  794. io_cq_unlock_post(ctx);
  795. if (!completed)
  796. goto defer_complete;
  797. /*
  798. * We don't free the request here because we know it's called from
  799. * io-wq only, which holds a reference, so it cannot be the last put.
  800. */
  801. req_ref_put(req);
  802. }
  803. void io_req_defer_failed(struct io_kiocb *req, s32 res)
  804. __must_hold(&ctx->uring_lock)
  805. {
  806. const struct io_cold_def *def = &io_cold_defs[req->opcode];
  807. lockdep_assert_held(&req->ctx->uring_lock);
  808. req_set_fail(req);
  809. io_req_set_res(req, res, io_put_kbuf(req, res, NULL));
  810. if (def->fail)
  811. def->fail(req);
  812. io_req_complete_defer(req);
  813. }
  814. /*
  815. * A request might get retired back into the request caches even before opcode
  816. * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
  817. * Because of that, io_alloc_req() should be called only under ->uring_lock
  818. * and with extra caution to not get a request that is still worked on.
  819. */
  820. __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
  821. __must_hold(&ctx->uring_lock)
  822. {
  823. gfp_t gfp = GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO;
  824. void *reqs[IO_REQ_ALLOC_BATCH];
  825. int ret;
  826. ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
  827. /*
  828. * Bulk alloc is all-or-nothing. If we fail to get a batch,
  829. * retry single alloc to be on the safe side.
  830. */
  831. if (unlikely(ret <= 0)) {
  832. reqs[0] = kmem_cache_alloc(req_cachep, gfp);
  833. if (!reqs[0])
  834. return false;
  835. ret = 1;
  836. }
  837. percpu_ref_get_many(&ctx->refs, ret);
  838. ctx->nr_req_allocated += ret;
  839. while (ret--) {
  840. struct io_kiocb *req = reqs[ret];
  841. io_req_add_to_cache(req, ctx);
  842. }
  843. return true;
  844. }
  845. __cold void io_free_req(struct io_kiocb *req)
  846. {
  847. /* refs were already put, restore them for io_req_task_complete() */
  848. req->flags &= ~REQ_F_REFCOUNT;
  849. /* we only want to free it, don't post CQEs */
  850. req->flags |= REQ_F_CQE_SKIP;
  851. req->io_task_work.func = io_req_task_complete;
  852. io_req_task_work_add(req);
  853. }
  854. static void __io_req_find_next_prep(struct io_kiocb *req)
  855. {
  856. struct io_ring_ctx *ctx = req->ctx;
  857. spin_lock(&ctx->completion_lock);
  858. io_disarm_next(req);
  859. spin_unlock(&ctx->completion_lock);
  860. }
  861. static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
  862. {
  863. struct io_kiocb *nxt;
  864. /*
  865. * If LINK is set, we have dependent requests in this chain. If we
  866. * didn't fail this request, queue the first one up, moving any other
  867. * dependencies to the next request. In case of failure, fail the rest
  868. * of the chain.
  869. */
  870. if (unlikely(req->flags & IO_DISARM_MASK))
  871. __io_req_find_next_prep(req);
  872. nxt = req->link;
  873. req->link = NULL;
  874. return nxt;
  875. }
  876. static void io_req_task_cancel(struct io_tw_req tw_req, io_tw_token_t tw)
  877. {
  878. struct io_kiocb *req = tw_req.req;
  879. io_tw_lock(req->ctx, tw);
  880. io_req_defer_failed(req, req->cqe.res);
  881. }
  882. void io_req_task_submit(struct io_tw_req tw_req, io_tw_token_t tw)
  883. {
  884. struct io_kiocb *req = tw_req.req;
  885. struct io_ring_ctx *ctx = req->ctx;
  886. io_tw_lock(ctx, tw);
  887. if (unlikely(tw.cancel))
  888. io_req_defer_failed(req, -EFAULT);
  889. else if (req->flags & REQ_F_FORCE_ASYNC)
  890. io_queue_iowq(req);
  891. else
  892. io_queue_sqe(req, 0);
  893. }
  894. void io_req_task_queue_fail(struct io_kiocb *req, int ret)
  895. {
  896. io_req_set_res(req, ret, 0);
  897. req->io_task_work.func = io_req_task_cancel;
  898. io_req_task_work_add(req);
  899. }
  900. void io_req_task_queue(struct io_kiocb *req)
  901. {
  902. req->io_task_work.func = io_req_task_submit;
  903. io_req_task_work_add(req);
  904. }
  905. void io_queue_next(struct io_kiocb *req)
  906. {
  907. struct io_kiocb *nxt = io_req_find_next(req);
  908. if (nxt)
  909. io_req_task_queue(nxt);
  910. }
  911. static inline void io_req_put_rsrc_nodes(struct io_kiocb *req)
  912. {
  913. if (req->file_node) {
  914. io_put_rsrc_node(req->ctx, req->file_node);
  915. req->file_node = NULL;
  916. }
  917. if (req->flags & REQ_F_BUF_NODE)
  918. io_put_rsrc_node(req->ctx, req->buf_node);
  919. }
  920. static void io_free_batch_list(struct io_ring_ctx *ctx,
  921. struct io_wq_work_node *node)
  922. __must_hold(&ctx->uring_lock)
  923. {
  924. do {
  925. struct io_kiocb *req = container_of(node, struct io_kiocb,
  926. comp_list);
  927. if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
  928. if (req->flags & REQ_F_REISSUE) {
  929. node = req->comp_list.next;
  930. req->flags &= ~REQ_F_REISSUE;
  931. io_queue_iowq(req);
  932. continue;
  933. }
  934. if (req->flags & REQ_F_REFCOUNT) {
  935. node = req->comp_list.next;
  936. if (!req_ref_put_and_test(req))
  937. continue;
  938. }
  939. if ((req->flags & REQ_F_POLLED) && req->apoll) {
  940. struct async_poll *apoll = req->apoll;
  941. if (apoll->double_poll)
  942. kfree(apoll->double_poll);
  943. io_cache_free(&ctx->apoll_cache, apoll);
  944. req->flags &= ~REQ_F_POLLED;
  945. }
  946. if (req->flags & IO_REQ_LINK_FLAGS)
  947. io_queue_next(req);
  948. if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
  949. io_clean_op(req);
  950. }
  951. io_put_file(req);
  952. io_req_put_rsrc_nodes(req);
  953. io_put_task(req);
  954. node = req->comp_list.next;
  955. io_req_add_to_cache(req, ctx);
  956. } while (node);
  957. }
  958. void __io_submit_flush_completions(struct io_ring_ctx *ctx)
  959. __must_hold(&ctx->uring_lock)
  960. {
  961. struct io_submit_state *state = &ctx->submit_state;
  962. struct io_wq_work_node *node;
  963. __io_cq_lock(ctx);
  964. __wq_list_for_each(node, &state->compl_reqs) {
  965. struct io_kiocb *req = container_of(node, struct io_kiocb,
  966. comp_list);
  967. /*
  968. * Requests marked with REQUEUE should not post a CQE, they
  969. * will go through the io-wq retry machinery and post one
  970. * later.
  971. */
  972. if (!(req->flags & (REQ_F_CQE_SKIP | REQ_F_REISSUE)) &&
  973. unlikely(!io_fill_cqe_req(ctx, req))) {
  974. if (ctx->lockless_cq)
  975. io_cqe_overflow(ctx, &req->cqe, &req->big_cqe);
  976. else
  977. io_cqe_overflow_locked(ctx, &req->cqe, &req->big_cqe);
  978. }
  979. }
  980. __io_cq_unlock_post(ctx);
  981. if (!wq_list_empty(&state->compl_reqs)) {
  982. io_free_batch_list(ctx, state->compl_reqs.first);
  983. INIT_WQ_LIST(&state->compl_reqs);
  984. }
  985. if (unlikely(ctx->drain_active))
  986. io_queue_deferred(ctx);
  987. ctx->submit_state.cq_flush = false;
  988. }
  989. /*
  990. * We can't just wait for polled events to come to us, we have to actively
  991. * find and complete them.
  992. */
  993. __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
  994. {
  995. if (!(ctx->flags & IORING_SETUP_IOPOLL))
  996. return;
  997. mutex_lock(&ctx->uring_lock);
  998. while (!list_empty(&ctx->iopoll_list)) {
  999. /* let it sleep and repeat later if can't complete a request */
  1000. if (io_do_iopoll(ctx, true) == 0)
  1001. break;
  1002. /*
  1003. * Ensure we allow local-to-the-cpu processing to take place,
  1004. * in this case we need to ensure that we reap all events.
  1005. * Also let task_work, etc. to progress by releasing the mutex
  1006. */
  1007. if (need_resched()) {
  1008. mutex_unlock(&ctx->uring_lock);
  1009. cond_resched();
  1010. mutex_lock(&ctx->uring_lock);
  1011. }
  1012. }
  1013. mutex_unlock(&ctx->uring_lock);
  1014. if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
  1015. io_move_task_work_from_local(ctx);
  1016. }
  1017. static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned int min_events)
  1018. {
  1019. unsigned int nr_events = 0;
  1020. unsigned long check_cq;
  1021. min_events = min(min_events, ctx->cq_entries);
  1022. lockdep_assert_held(&ctx->uring_lock);
  1023. if (!io_allowed_run_tw(ctx))
  1024. return -EEXIST;
  1025. check_cq = READ_ONCE(ctx->check_cq);
  1026. if (unlikely(check_cq)) {
  1027. if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
  1028. __io_cqring_overflow_flush(ctx, false);
  1029. /*
  1030. * Similarly do not spin if we have not informed the user of any
  1031. * dropped CQE.
  1032. */
  1033. if (check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT))
  1034. return -EBADR;
  1035. }
  1036. /*
  1037. * Don't enter poll loop if we already have events pending.
  1038. * If we do, we can potentially be spinning for commands that
  1039. * already triggered a CQE (eg in error).
  1040. */
  1041. if (io_cqring_events(ctx))
  1042. return 0;
  1043. do {
  1044. int ret = 0;
  1045. /*
  1046. * If a submit got punted to a workqueue, we can have the
  1047. * application entering polling for a command before it gets
  1048. * issued. That app will hold the uring_lock for the duration
  1049. * of the poll right here, so we need to take a breather every
  1050. * now and then to ensure that the issue has a chance to add
  1051. * the poll to the issued list. Otherwise we can spin here
  1052. * forever, while the workqueue is stuck trying to acquire the
  1053. * very same mutex.
  1054. */
  1055. if (list_empty(&ctx->iopoll_list) || io_task_work_pending(ctx)) {
  1056. u32 tail = ctx->cached_cq_tail;
  1057. (void) io_run_local_work_locked(ctx, min_events);
  1058. if (task_work_pending(current) || list_empty(&ctx->iopoll_list)) {
  1059. mutex_unlock(&ctx->uring_lock);
  1060. io_run_task_work();
  1061. mutex_lock(&ctx->uring_lock);
  1062. }
  1063. /* some requests don't go through iopoll_list */
  1064. if (tail != ctx->cached_cq_tail || list_empty(&ctx->iopoll_list))
  1065. break;
  1066. }
  1067. ret = io_do_iopoll(ctx, !min_events);
  1068. if (unlikely(ret < 0))
  1069. return ret;
  1070. if (task_sigpending(current))
  1071. return -EINTR;
  1072. if (need_resched())
  1073. break;
  1074. nr_events += ret;
  1075. } while (nr_events < min_events);
  1076. return 0;
  1077. }
  1078. void io_req_task_complete(struct io_tw_req tw_req, io_tw_token_t tw)
  1079. {
  1080. io_req_complete_defer(tw_req.req);
  1081. }
  1082. /*
  1083. * After the iocb has been issued, it's safe to be found on the poll list.
  1084. * Adding the kiocb to the list AFTER submission ensures that we don't
  1085. * find it from a io_do_iopoll() thread before the issuer is done
  1086. * accessing the kiocb cookie.
  1087. */
  1088. static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
  1089. {
  1090. struct io_ring_ctx *ctx = req->ctx;
  1091. const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
  1092. /* workqueue context doesn't hold uring_lock, grab it now */
  1093. if (unlikely(needs_lock))
  1094. mutex_lock(&ctx->uring_lock);
  1095. /*
  1096. * Track whether we have multiple files in our lists. This will impact
  1097. * how we do polling eventually, not spinning if we're on potentially
  1098. * different devices.
  1099. */
  1100. if (list_empty(&ctx->iopoll_list)) {
  1101. ctx->poll_multi_queue = false;
  1102. } else if (!ctx->poll_multi_queue) {
  1103. struct io_kiocb *list_req;
  1104. list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb, iopoll_node);
  1105. if (list_req->file != req->file)
  1106. ctx->poll_multi_queue = true;
  1107. }
  1108. list_add_tail(&req->iopoll_node, &ctx->iopoll_list);
  1109. if (unlikely(needs_lock)) {
  1110. /*
  1111. * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
  1112. * in sq thread task context or in io worker task context. If
  1113. * current task context is sq thread, we don't need to check
  1114. * whether should wake up sq thread.
  1115. */
  1116. if ((ctx->flags & IORING_SETUP_SQPOLL) &&
  1117. wq_has_sleeper(&ctx->sq_data->wait))
  1118. wake_up(&ctx->sq_data->wait);
  1119. mutex_unlock(&ctx->uring_lock);
  1120. }
  1121. }
  1122. io_req_flags_t io_file_get_flags(struct file *file)
  1123. {
  1124. io_req_flags_t res = 0;
  1125. BUILD_BUG_ON(REQ_F_ISREG_BIT != REQ_F_SUPPORT_NOWAIT_BIT + 1);
  1126. if (S_ISREG(file_inode(file)->i_mode))
  1127. res |= REQ_F_ISREG;
  1128. if ((file->f_flags & O_NONBLOCK) || (file->f_mode & FMODE_NOWAIT))
  1129. res |= REQ_F_SUPPORT_NOWAIT;
  1130. return res;
  1131. }
  1132. static __cold void io_drain_req(struct io_kiocb *req)
  1133. __must_hold(&ctx->uring_lock)
  1134. {
  1135. struct io_ring_ctx *ctx = req->ctx;
  1136. bool drain = req->flags & IOSQE_IO_DRAIN;
  1137. struct io_defer_entry *de;
  1138. de = kmalloc_obj(*de, GFP_KERNEL_ACCOUNT);
  1139. if (!de) {
  1140. io_req_defer_failed(req, -ENOMEM);
  1141. return;
  1142. }
  1143. io_prep_async_link(req);
  1144. trace_io_uring_defer(req);
  1145. de->req = req;
  1146. ctx->nr_drained += io_linked_nr(req);
  1147. list_add_tail(&de->list, &ctx->defer_list);
  1148. io_queue_deferred(ctx);
  1149. if (!drain && list_empty(&ctx->defer_list))
  1150. ctx->drain_active = false;
  1151. }
  1152. static bool io_assign_file(struct io_kiocb *req, const struct io_issue_def *def,
  1153. unsigned int issue_flags)
  1154. {
  1155. if (req->file || !def->needs_file)
  1156. return true;
  1157. if (req->flags & REQ_F_FIXED_FILE)
  1158. req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
  1159. else
  1160. req->file = io_file_get_normal(req, req->cqe.fd);
  1161. return !!req->file;
  1162. }
  1163. #define REQ_ISSUE_SLOW_FLAGS (REQ_F_CREDS | REQ_F_ARM_LTIMEOUT)
  1164. static inline int __io_issue_sqe(struct io_kiocb *req,
  1165. unsigned int issue_flags,
  1166. const struct io_issue_def *def)
  1167. {
  1168. const struct cred *creds = NULL;
  1169. struct io_kiocb *link = NULL;
  1170. int ret;
  1171. if (unlikely(req->flags & REQ_ISSUE_SLOW_FLAGS)) {
  1172. if ((req->flags & REQ_F_CREDS) && req->creds != current_cred())
  1173. creds = override_creds(req->creds);
  1174. if (req->flags & REQ_F_ARM_LTIMEOUT)
  1175. link = __io_prep_linked_timeout(req);
  1176. }
  1177. if (!def->audit_skip)
  1178. audit_uring_entry(req->opcode);
  1179. ret = def->issue(req, issue_flags);
  1180. if (!def->audit_skip)
  1181. audit_uring_exit(!ret, ret);
  1182. if (unlikely(creds || link)) {
  1183. if (creds)
  1184. revert_creds(creds);
  1185. if (link)
  1186. io_queue_linked_timeout(link);
  1187. }
  1188. return ret;
  1189. }
  1190. static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
  1191. {
  1192. const struct io_issue_def *def = &io_issue_defs[req->opcode];
  1193. int ret;
  1194. if (unlikely(!io_assign_file(req, def, issue_flags)))
  1195. return -EBADF;
  1196. ret = __io_issue_sqe(req, issue_flags, def);
  1197. if (ret == IOU_COMPLETE) {
  1198. if (issue_flags & IO_URING_F_COMPLETE_DEFER)
  1199. io_req_complete_defer(req);
  1200. else
  1201. io_req_complete_post(req, issue_flags);
  1202. return 0;
  1203. }
  1204. if (ret == IOU_ISSUE_SKIP_COMPLETE) {
  1205. ret = 0;
  1206. /* If the op doesn't have a file, we're not polling for it */
  1207. if ((req->ctx->flags & IORING_SETUP_IOPOLL) && def->iopoll_queue)
  1208. io_iopoll_req_issued(req, issue_flags);
  1209. }
  1210. return ret;
  1211. }
  1212. int io_poll_issue(struct io_kiocb *req, io_tw_token_t tw)
  1213. {
  1214. const unsigned int issue_flags = IO_URING_F_NONBLOCK |
  1215. IO_URING_F_MULTISHOT |
  1216. IO_URING_F_COMPLETE_DEFER;
  1217. int ret;
  1218. io_tw_lock(req->ctx, tw);
  1219. WARN_ON_ONCE(!req->file);
  1220. if (WARN_ON_ONCE(req->ctx->flags & IORING_SETUP_IOPOLL))
  1221. return -EFAULT;
  1222. ret = __io_issue_sqe(req, issue_flags, &io_issue_defs[req->opcode]);
  1223. WARN_ON_ONCE(ret == IOU_ISSUE_SKIP_COMPLETE);
  1224. return ret;
  1225. }
  1226. struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
  1227. {
  1228. struct io_kiocb *req = container_of(work, struct io_kiocb, work);
  1229. struct io_kiocb *nxt = NULL;
  1230. if (req_ref_put_and_test_atomic(req)) {
  1231. if (req->flags & IO_REQ_LINK_FLAGS)
  1232. nxt = io_req_find_next(req);
  1233. io_free_req(req);
  1234. }
  1235. return nxt ? &nxt->work : NULL;
  1236. }
  1237. void io_wq_submit_work(struct io_wq_work *work)
  1238. {
  1239. struct io_kiocb *req = container_of(work, struct io_kiocb, work);
  1240. const struct io_issue_def *def = &io_issue_defs[req->opcode];
  1241. unsigned int issue_flags = IO_URING_F_UNLOCKED | IO_URING_F_IOWQ;
  1242. bool needs_poll = false;
  1243. int ret = 0, err = -ECANCELED;
  1244. /* one will be dropped by io_wq_free_work() after returning to io-wq */
  1245. if (!(req->flags & REQ_F_REFCOUNT))
  1246. __io_req_set_refcount(req, 2);
  1247. else
  1248. req_ref_get(req);
  1249. /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
  1250. if (atomic_read(&work->flags) & IO_WQ_WORK_CANCEL) {
  1251. fail:
  1252. io_req_task_queue_fail(req, err);
  1253. return;
  1254. }
  1255. if (!io_assign_file(req, def, issue_flags)) {
  1256. err = -EBADF;
  1257. atomic_or(IO_WQ_WORK_CANCEL, &work->flags);
  1258. goto fail;
  1259. }
  1260. /*
  1261. * If DEFER_TASKRUN is set, it's only allowed to post CQEs from the
  1262. * submitter task context. Final request completions are handed to the
  1263. * right context, however this is not the case of auxiliary CQEs,
  1264. * which is the main mean of operation for multishot requests.
  1265. * Don't allow any multishot execution from io-wq. It's more restrictive
  1266. * than necessary and also cleaner.
  1267. */
  1268. if (req->flags & (REQ_F_MULTISHOT|REQ_F_APOLL_MULTISHOT)) {
  1269. err = -EBADFD;
  1270. if (!io_file_can_poll(req))
  1271. goto fail;
  1272. if (req->file->f_flags & O_NONBLOCK ||
  1273. req->file->f_mode & FMODE_NOWAIT) {
  1274. err = -ECANCELED;
  1275. if (io_arm_poll_handler(req, issue_flags) != IO_APOLL_OK)
  1276. goto fail;
  1277. return;
  1278. } else {
  1279. req->flags &= ~(REQ_F_APOLL_MULTISHOT|REQ_F_MULTISHOT);
  1280. }
  1281. }
  1282. if (req->flags & REQ_F_FORCE_ASYNC) {
  1283. bool opcode_poll = def->pollin || def->pollout;
  1284. if (opcode_poll && io_file_can_poll(req)) {
  1285. needs_poll = true;
  1286. issue_flags |= IO_URING_F_NONBLOCK;
  1287. }
  1288. }
  1289. do {
  1290. ret = io_issue_sqe(req, issue_flags);
  1291. if (ret != -EAGAIN)
  1292. break;
  1293. /*
  1294. * If REQ_F_NOWAIT is set, then don't wait or retry with
  1295. * poll. -EAGAIN is final for that case.
  1296. */
  1297. if (req->flags & REQ_F_NOWAIT)
  1298. break;
  1299. /*
  1300. * We can get EAGAIN for iopolled IO even though we're
  1301. * forcing a sync submission from here, since we can't
  1302. * wait for request slots on the block side.
  1303. */
  1304. if (!needs_poll) {
  1305. if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
  1306. break;
  1307. if (io_wq_worker_stopped())
  1308. break;
  1309. cond_resched();
  1310. continue;
  1311. }
  1312. if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
  1313. return;
  1314. /* aborted or ready, in either case retry blocking */
  1315. needs_poll = false;
  1316. issue_flags &= ~IO_URING_F_NONBLOCK;
  1317. } while (1);
  1318. /* avoid locking problems by failing it from a clean context */
  1319. if (ret)
  1320. io_req_task_queue_fail(req, ret);
  1321. }
  1322. inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
  1323. unsigned int issue_flags)
  1324. {
  1325. struct io_ring_ctx *ctx = req->ctx;
  1326. struct io_rsrc_node *node;
  1327. struct file *file = NULL;
  1328. io_ring_submit_lock(ctx, issue_flags);
  1329. node = io_rsrc_node_lookup(&ctx->file_table.data, fd);
  1330. if (node) {
  1331. node->refs++;
  1332. req->file_node = node;
  1333. req->flags |= io_slot_flags(node);
  1334. file = io_slot_file(node);
  1335. }
  1336. io_ring_submit_unlock(ctx, issue_flags);
  1337. return file;
  1338. }
  1339. struct file *io_file_get_normal(struct io_kiocb *req, int fd)
  1340. {
  1341. struct file *file = fget(fd);
  1342. trace_io_uring_file_get(req, fd);
  1343. /* we don't allow fixed io_uring files */
  1344. if (file && io_is_uring_fops(file))
  1345. io_req_track_inflight(req);
  1346. return file;
  1347. }
  1348. static int io_req_sqe_copy(struct io_kiocb *req, unsigned int issue_flags)
  1349. {
  1350. const struct io_cold_def *def = &io_cold_defs[req->opcode];
  1351. if (req->flags & REQ_F_SQE_COPIED)
  1352. return 0;
  1353. req->flags |= REQ_F_SQE_COPIED;
  1354. if (!def->sqe_copy)
  1355. return 0;
  1356. if (WARN_ON_ONCE(!(issue_flags & IO_URING_F_INLINE)))
  1357. return -EFAULT;
  1358. def->sqe_copy(req);
  1359. return 0;
  1360. }
  1361. static void io_queue_async(struct io_kiocb *req, unsigned int issue_flags, int ret)
  1362. __must_hold(&req->ctx->uring_lock)
  1363. {
  1364. if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
  1365. fail:
  1366. io_req_defer_failed(req, ret);
  1367. return;
  1368. }
  1369. ret = io_req_sqe_copy(req, issue_flags);
  1370. if (unlikely(ret))
  1371. goto fail;
  1372. switch (io_arm_poll_handler(req, 0)) {
  1373. case IO_APOLL_READY:
  1374. io_req_task_queue(req);
  1375. break;
  1376. case IO_APOLL_ABORTED:
  1377. io_queue_iowq(req);
  1378. break;
  1379. case IO_APOLL_OK:
  1380. break;
  1381. }
  1382. }
  1383. static inline void io_queue_sqe(struct io_kiocb *req, unsigned int extra_flags)
  1384. __must_hold(&req->ctx->uring_lock)
  1385. {
  1386. unsigned int issue_flags = IO_URING_F_NONBLOCK |
  1387. IO_URING_F_COMPLETE_DEFER | extra_flags;
  1388. int ret;
  1389. ret = io_issue_sqe(req, issue_flags);
  1390. /*
  1391. * We async punt it if the file wasn't marked NOWAIT, or if the file
  1392. * doesn't support non-blocking read/write attempts
  1393. */
  1394. if (unlikely(ret))
  1395. io_queue_async(req, issue_flags, ret);
  1396. }
  1397. static void io_queue_sqe_fallback(struct io_kiocb *req)
  1398. __must_hold(&req->ctx->uring_lock)
  1399. {
  1400. if (unlikely(req->flags & REQ_F_FAIL)) {
  1401. /*
  1402. * We don't submit, fail them all, for that replace hardlinks
  1403. * with normal links. Extra REQ_F_LINK is tolerated.
  1404. */
  1405. req->flags &= ~REQ_F_HARDLINK;
  1406. req->flags |= REQ_F_LINK;
  1407. io_req_defer_failed(req, req->cqe.res);
  1408. } else {
  1409. /* can't fail with IO_URING_F_INLINE */
  1410. io_req_sqe_copy(req, IO_URING_F_INLINE);
  1411. if (unlikely(req->ctx->drain_active))
  1412. io_drain_req(req);
  1413. else
  1414. io_queue_iowq(req);
  1415. }
  1416. }
  1417. /*
  1418. * Check SQE restrictions (opcode and flags).
  1419. *
  1420. * Returns 'true' if SQE is allowed, 'false' otherwise.
  1421. */
  1422. static inline bool io_check_restriction(struct io_ring_ctx *ctx,
  1423. struct io_kiocb *req,
  1424. unsigned int sqe_flags)
  1425. {
  1426. if (!ctx->op_restricted)
  1427. return true;
  1428. if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
  1429. return false;
  1430. if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
  1431. ctx->restrictions.sqe_flags_required)
  1432. return false;
  1433. if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
  1434. ctx->restrictions.sqe_flags_required))
  1435. return false;
  1436. return true;
  1437. }
  1438. static void io_init_drain(struct io_ring_ctx *ctx)
  1439. {
  1440. struct io_kiocb *head = ctx->submit_state.link.head;
  1441. ctx->drain_active = true;
  1442. if (head) {
  1443. /*
  1444. * If we need to drain a request in the middle of a link, drain
  1445. * the head request and the next request/link after the current
  1446. * link. Considering sequential execution of links,
  1447. * REQ_F_IO_DRAIN will be maintained for every request of our
  1448. * link.
  1449. */
  1450. head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
  1451. ctx->drain_next = true;
  1452. }
  1453. }
  1454. static __cold int io_init_fail_req(struct io_kiocb *req, int err)
  1455. {
  1456. /* ensure per-opcode data is cleared if we fail before prep */
  1457. memset(&req->cmd.data, 0, sizeof(req->cmd.data));
  1458. return err;
  1459. }
  1460. static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
  1461. const struct io_uring_sqe *sqe, unsigned int *left)
  1462. __must_hold(&ctx->uring_lock)
  1463. {
  1464. const struct io_issue_def *def;
  1465. unsigned int sqe_flags;
  1466. int personality;
  1467. u8 opcode;
  1468. req->ctx = ctx;
  1469. req->opcode = opcode = READ_ONCE(sqe->opcode);
  1470. /* same numerical values with corresponding REQ_F_*, safe to copy */
  1471. sqe_flags = READ_ONCE(sqe->flags);
  1472. req->flags = (__force io_req_flags_t) sqe_flags;
  1473. req->cqe.user_data = READ_ONCE(sqe->user_data);
  1474. req->file = NULL;
  1475. req->tctx = current->io_uring;
  1476. req->cancel_seq_set = false;
  1477. req->async_data = NULL;
  1478. if (unlikely(opcode >= IORING_OP_LAST)) {
  1479. req->opcode = 0;
  1480. return io_init_fail_req(req, -EINVAL);
  1481. }
  1482. opcode = array_index_nospec(opcode, IORING_OP_LAST);
  1483. def = &io_issue_defs[opcode];
  1484. if (def->is_128 && !(ctx->flags & IORING_SETUP_SQE128)) {
  1485. /*
  1486. * A 128b op on a non-128b SQ requires mixed SQE support as
  1487. * well as 2 contiguous entries.
  1488. */
  1489. if (!(ctx->flags & IORING_SETUP_SQE_MIXED) || *left < 2 ||
  1490. (unsigned)(sqe - ctx->sq_sqes) >= ctx->sq_entries - 1)
  1491. return io_init_fail_req(req, -EINVAL);
  1492. /*
  1493. * A 128b operation on a mixed SQ uses two entries, so we have
  1494. * to increment the head and cached refs, and decrement what's
  1495. * left.
  1496. */
  1497. current->io_uring->cached_refs++;
  1498. ctx->cached_sq_head++;
  1499. (*left)--;
  1500. }
  1501. if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
  1502. /* enforce forwards compatibility on users */
  1503. if (sqe_flags & ~SQE_VALID_FLAGS)
  1504. return io_init_fail_req(req, -EINVAL);
  1505. if (sqe_flags & IOSQE_BUFFER_SELECT) {
  1506. if (!def->buffer_select)
  1507. return io_init_fail_req(req, -EOPNOTSUPP);
  1508. req->buf_index = READ_ONCE(sqe->buf_group);
  1509. }
  1510. if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
  1511. ctx->drain_disabled = true;
  1512. if (sqe_flags & IOSQE_IO_DRAIN) {
  1513. if (ctx->drain_disabled)
  1514. return io_init_fail_req(req, -EOPNOTSUPP);
  1515. io_init_drain(ctx);
  1516. }
  1517. }
  1518. if (unlikely(ctx->op_restricted || ctx->drain_active || ctx->drain_next)) {
  1519. if (!io_check_restriction(ctx, req, sqe_flags))
  1520. return io_init_fail_req(req, -EACCES);
  1521. /* knock it to the slow queue path, will be drained there */
  1522. if (ctx->drain_active)
  1523. req->flags |= REQ_F_FORCE_ASYNC;
  1524. /* if there is no link, we're at "next" request and need to drain */
  1525. if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
  1526. ctx->drain_next = false;
  1527. ctx->drain_active = true;
  1528. req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
  1529. }
  1530. }
  1531. if (!def->ioprio && sqe->ioprio)
  1532. return io_init_fail_req(req, -EINVAL);
  1533. if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
  1534. return io_init_fail_req(req, -EINVAL);
  1535. if (def->needs_file) {
  1536. struct io_submit_state *state = &ctx->submit_state;
  1537. req->cqe.fd = READ_ONCE(sqe->fd);
  1538. /*
  1539. * Plug now if we have more than 2 IO left after this, and the
  1540. * target is potentially a read/write to block based storage.
  1541. */
  1542. if (state->need_plug && def->plug) {
  1543. state->plug_started = true;
  1544. state->need_plug = false;
  1545. blk_start_plug_nr_ios(&state->plug, state->submit_nr);
  1546. }
  1547. }
  1548. personality = READ_ONCE(sqe->personality);
  1549. if (personality) {
  1550. int ret;
  1551. req->creds = xa_load(&ctx->personalities, personality);
  1552. if (!req->creds)
  1553. return io_init_fail_req(req, -EINVAL);
  1554. get_cred(req->creds);
  1555. ret = security_uring_override_creds(req->creds);
  1556. if (ret) {
  1557. put_cred(req->creds);
  1558. return io_init_fail_req(req, ret);
  1559. }
  1560. req->flags |= REQ_F_CREDS;
  1561. }
  1562. return def->prep(req, sqe);
  1563. }
  1564. static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
  1565. struct io_kiocb *req, int ret)
  1566. {
  1567. struct io_ring_ctx *ctx = req->ctx;
  1568. struct io_submit_link *link = &ctx->submit_state.link;
  1569. struct io_kiocb *head = link->head;
  1570. trace_io_uring_req_failed(sqe, req, ret);
  1571. /*
  1572. * Avoid breaking links in the middle as it renders links with SQPOLL
  1573. * unusable. Instead of failing eagerly, continue assembling the link if
  1574. * applicable and mark the head with REQ_F_FAIL. The link flushing code
  1575. * should find the flag and handle the rest.
  1576. */
  1577. req_fail_link_node(req, ret);
  1578. if (head && !(head->flags & REQ_F_FAIL))
  1579. req_fail_link_node(head, -ECANCELED);
  1580. if (!(req->flags & IO_REQ_LINK_FLAGS)) {
  1581. if (head) {
  1582. link->last->link = req;
  1583. link->head = NULL;
  1584. req = head;
  1585. }
  1586. io_queue_sqe_fallback(req);
  1587. return ret;
  1588. }
  1589. if (head)
  1590. link->last->link = req;
  1591. else
  1592. link->head = req;
  1593. link->last = req;
  1594. return 0;
  1595. }
  1596. static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
  1597. const struct io_uring_sqe *sqe, unsigned int *left)
  1598. __must_hold(&ctx->uring_lock)
  1599. {
  1600. struct io_submit_link *link = &ctx->submit_state.link;
  1601. int ret;
  1602. ret = io_init_req(ctx, req, sqe, left);
  1603. if (unlikely(ret))
  1604. return io_submit_fail_init(sqe, req, ret);
  1605. if (unlikely(ctx->bpf_filters)) {
  1606. ret = io_uring_run_bpf_filters(ctx->bpf_filters, req);
  1607. if (ret)
  1608. return io_submit_fail_init(sqe, req, ret);
  1609. }
  1610. trace_io_uring_submit_req(req);
  1611. /*
  1612. * If we already have a head request, queue this one for async
  1613. * submittal once the head completes. If we don't have a head but
  1614. * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
  1615. * submitted sync once the chain is complete. If none of those
  1616. * conditions are true (normal request), then just queue it.
  1617. */
  1618. if (unlikely(link->head)) {
  1619. trace_io_uring_link(req, link->last);
  1620. io_req_sqe_copy(req, IO_URING_F_INLINE);
  1621. link->last->link = req;
  1622. link->last = req;
  1623. if (req->flags & IO_REQ_LINK_FLAGS)
  1624. return 0;
  1625. /* last request of the link, flush it */
  1626. req = link->head;
  1627. link->head = NULL;
  1628. if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
  1629. goto fallback;
  1630. } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
  1631. REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
  1632. if (req->flags & IO_REQ_LINK_FLAGS) {
  1633. link->head = req;
  1634. link->last = req;
  1635. } else {
  1636. fallback:
  1637. io_queue_sqe_fallback(req);
  1638. }
  1639. return 0;
  1640. }
  1641. io_queue_sqe(req, IO_URING_F_INLINE);
  1642. return 0;
  1643. }
  1644. /*
  1645. * Batched submission is done, ensure local IO is flushed out.
  1646. */
  1647. static void io_submit_state_end(struct io_ring_ctx *ctx)
  1648. {
  1649. struct io_submit_state *state = &ctx->submit_state;
  1650. if (unlikely(state->link.head))
  1651. io_queue_sqe_fallback(state->link.head);
  1652. /* flush only after queuing links as they can generate completions */
  1653. io_submit_flush_completions(ctx);
  1654. if (state->plug_started)
  1655. blk_finish_plug(&state->plug);
  1656. }
  1657. /*
  1658. * Start submission side cache.
  1659. */
  1660. static void io_submit_state_start(struct io_submit_state *state,
  1661. unsigned int max_ios)
  1662. {
  1663. state->plug_started = false;
  1664. state->need_plug = max_ios > 2;
  1665. state->submit_nr = max_ios;
  1666. /* set only head, no need to init link_last in advance */
  1667. state->link.head = NULL;
  1668. }
  1669. static void io_commit_sqring(struct io_ring_ctx *ctx)
  1670. {
  1671. struct io_rings *rings = ctx->rings;
  1672. if (ctx->flags & IORING_SETUP_SQ_REWIND) {
  1673. ctx->cached_sq_head = 0;
  1674. } else {
  1675. /*
  1676. * Ensure any loads from the SQEs are done at this point,
  1677. * since once we write the new head, the application could
  1678. * write new data to them.
  1679. */
  1680. smp_store_release(&rings->sq.head, ctx->cached_sq_head);
  1681. }
  1682. }
  1683. /*
  1684. * Fetch an sqe, if one is available. Note this returns a pointer to memory
  1685. * that is mapped by userspace. This means that care needs to be taken to
  1686. * ensure that reads are stable, as we cannot rely on userspace always
  1687. * being a good citizen. If members of the sqe are validated and then later
  1688. * used, it's important that those reads are done through READ_ONCE() to
  1689. * prevent a re-load down the line.
  1690. */
  1691. static bool io_get_sqe(struct io_ring_ctx *ctx, const struct io_uring_sqe **sqe)
  1692. {
  1693. unsigned mask = ctx->sq_entries - 1;
  1694. unsigned head = ctx->cached_sq_head++ & mask;
  1695. if (static_branch_unlikely(&io_key_has_sqarray.key) &&
  1696. (!(ctx->flags & IORING_SETUP_NO_SQARRAY))) {
  1697. head = READ_ONCE(ctx->sq_array[head]);
  1698. if (unlikely(head >= ctx->sq_entries)) {
  1699. WRITE_ONCE(ctx->rings->sq_dropped,
  1700. READ_ONCE(ctx->rings->sq_dropped) + 1);
  1701. return false;
  1702. }
  1703. head = array_index_nospec(head, ctx->sq_entries);
  1704. }
  1705. /*
  1706. * The cached sq head (or cq tail) serves two purposes:
  1707. *
  1708. * 1) allows us to batch the cost of updating the user visible
  1709. * head updates.
  1710. * 2) allows the kernel side to track the head on its own, even
  1711. * though the application is the one updating it.
  1712. */
  1713. /* double index for 128-byte SQEs, twice as long */
  1714. if (ctx->flags & IORING_SETUP_SQE128)
  1715. head <<= 1;
  1716. *sqe = &ctx->sq_sqes[head];
  1717. return true;
  1718. }
  1719. int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
  1720. __must_hold(&ctx->uring_lock)
  1721. {
  1722. unsigned int entries;
  1723. unsigned int left;
  1724. int ret;
  1725. if (ctx->flags & IORING_SETUP_SQ_REWIND)
  1726. entries = ctx->sq_entries;
  1727. else
  1728. entries = __io_sqring_entries(ctx);
  1729. entries = min(nr, entries);
  1730. if (unlikely(!entries))
  1731. return 0;
  1732. ret = left = entries;
  1733. io_get_task_refs(left);
  1734. io_submit_state_start(&ctx->submit_state, left);
  1735. do {
  1736. const struct io_uring_sqe *sqe;
  1737. struct io_kiocb *req;
  1738. if (unlikely(!io_alloc_req(ctx, &req)))
  1739. break;
  1740. if (unlikely(!io_get_sqe(ctx, &sqe))) {
  1741. io_req_add_to_cache(req, ctx);
  1742. break;
  1743. }
  1744. /*
  1745. * Continue submitting even for sqe failure if the
  1746. * ring was setup with IORING_SETUP_SUBMIT_ALL
  1747. */
  1748. if (unlikely(io_submit_sqe(ctx, req, sqe, &left)) &&
  1749. !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
  1750. left--;
  1751. break;
  1752. }
  1753. } while (--left);
  1754. if (unlikely(left)) {
  1755. ret -= left;
  1756. /* try again if it submitted nothing and can't allocate a req */
  1757. if (!ret && io_req_cache_empty(ctx))
  1758. ret = -EAGAIN;
  1759. current->io_uring->cached_refs += left;
  1760. }
  1761. io_submit_state_end(ctx);
  1762. /* Commit SQ ring head once we've consumed and submitted all SQEs */
  1763. io_commit_sqring(ctx);
  1764. return ret;
  1765. }
  1766. static void io_rings_free(struct io_ring_ctx *ctx)
  1767. {
  1768. io_free_region(ctx->user, &ctx->sq_region);
  1769. io_free_region(ctx->user, &ctx->ring_region);
  1770. ctx->rings = NULL;
  1771. RCU_INIT_POINTER(ctx->rings_rcu, NULL);
  1772. ctx->sq_sqes = NULL;
  1773. }
  1774. static int rings_size(unsigned int flags, unsigned int sq_entries,
  1775. unsigned int cq_entries, struct io_rings_layout *rl)
  1776. {
  1777. struct io_rings *rings;
  1778. size_t sqe_size;
  1779. size_t off;
  1780. if (flags & IORING_SETUP_CQE_MIXED) {
  1781. if (cq_entries < 2)
  1782. return -EOVERFLOW;
  1783. }
  1784. if (flags & IORING_SETUP_SQE_MIXED) {
  1785. if (sq_entries < 2)
  1786. return -EOVERFLOW;
  1787. }
  1788. rl->sq_array_offset = SIZE_MAX;
  1789. sqe_size = sizeof(struct io_uring_sqe);
  1790. if (flags & IORING_SETUP_SQE128)
  1791. sqe_size *= 2;
  1792. rl->sq_size = array_size(sqe_size, sq_entries);
  1793. if (rl->sq_size == SIZE_MAX)
  1794. return -EOVERFLOW;
  1795. off = struct_size(rings, cqes, cq_entries);
  1796. if (flags & IORING_SETUP_CQE32)
  1797. off = size_mul(off, 2);
  1798. if (off == SIZE_MAX)
  1799. return -EOVERFLOW;
  1800. #ifdef CONFIG_SMP
  1801. off = ALIGN(off, SMP_CACHE_BYTES);
  1802. if (off == 0)
  1803. return -EOVERFLOW;
  1804. #endif
  1805. if (!(flags & IORING_SETUP_NO_SQARRAY)) {
  1806. size_t sq_array_size;
  1807. rl->sq_array_offset = off;
  1808. sq_array_size = array_size(sizeof(u32), sq_entries);
  1809. off = size_add(off, sq_array_size);
  1810. if (off == SIZE_MAX)
  1811. return -EOVERFLOW;
  1812. }
  1813. rl->rings_size = off;
  1814. return 0;
  1815. }
  1816. static __cold void __io_req_caches_free(struct io_ring_ctx *ctx)
  1817. {
  1818. struct io_kiocb *req;
  1819. int nr = 0;
  1820. while (!io_req_cache_empty(ctx)) {
  1821. req = io_extract_req(ctx);
  1822. io_poison_req(req);
  1823. kmem_cache_free(req_cachep, req);
  1824. nr++;
  1825. }
  1826. if (nr) {
  1827. ctx->nr_req_allocated -= nr;
  1828. percpu_ref_put_many(&ctx->refs, nr);
  1829. }
  1830. }
  1831. static __cold void io_req_caches_free(struct io_ring_ctx *ctx)
  1832. {
  1833. guard(mutex)(&ctx->uring_lock);
  1834. __io_req_caches_free(ctx);
  1835. }
  1836. static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
  1837. {
  1838. io_sq_thread_finish(ctx);
  1839. mutex_lock(&ctx->uring_lock);
  1840. io_sqe_buffers_unregister(ctx);
  1841. io_sqe_files_unregister(ctx);
  1842. io_unregister_zcrx_ifqs(ctx);
  1843. io_cqring_overflow_kill(ctx);
  1844. io_eventfd_unregister(ctx);
  1845. io_free_alloc_caches(ctx);
  1846. io_destroy_buffers(ctx);
  1847. io_free_region(ctx->user, &ctx->param_region);
  1848. mutex_unlock(&ctx->uring_lock);
  1849. if (ctx->sq_creds)
  1850. put_cred(ctx->sq_creds);
  1851. if (ctx->submitter_task)
  1852. put_task_struct(ctx->submitter_task);
  1853. WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
  1854. if (ctx->mm_account) {
  1855. mmdrop(ctx->mm_account);
  1856. ctx->mm_account = NULL;
  1857. }
  1858. io_rings_free(ctx);
  1859. if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
  1860. static_branch_slow_dec_deferred(&io_key_has_sqarray);
  1861. percpu_ref_exit(&ctx->refs);
  1862. free_uid(ctx->user);
  1863. io_req_caches_free(ctx);
  1864. if (ctx->restrictions.bpf_filters) {
  1865. WARN_ON_ONCE(ctx->bpf_filters !=
  1866. ctx->restrictions.bpf_filters->filters);
  1867. } else {
  1868. WARN_ON_ONCE(ctx->bpf_filters);
  1869. }
  1870. io_put_bpf_filters(&ctx->restrictions);
  1871. WARN_ON_ONCE(ctx->nr_req_allocated);
  1872. if (ctx->hash_map)
  1873. io_wq_put_hash(ctx->hash_map);
  1874. io_napi_free(ctx);
  1875. kvfree(ctx->cancel_table.hbs);
  1876. xa_destroy(&ctx->io_bl_xa);
  1877. kfree(ctx);
  1878. }
  1879. static __cold void io_activate_pollwq_cb(struct callback_head *cb)
  1880. {
  1881. struct io_ring_ctx *ctx = container_of(cb, struct io_ring_ctx,
  1882. poll_wq_task_work);
  1883. mutex_lock(&ctx->uring_lock);
  1884. ctx->poll_activated = true;
  1885. mutex_unlock(&ctx->uring_lock);
  1886. /*
  1887. * Wake ups for some events between start of polling and activation
  1888. * might've been lost due to loose synchronisation.
  1889. */
  1890. wake_up_all(&ctx->poll_wq);
  1891. percpu_ref_put(&ctx->refs);
  1892. }
  1893. __cold void io_activate_pollwq(struct io_ring_ctx *ctx)
  1894. {
  1895. spin_lock(&ctx->completion_lock);
  1896. /* already activated or in progress */
  1897. if (ctx->poll_activated || ctx->poll_wq_task_work.func)
  1898. goto out;
  1899. if (WARN_ON_ONCE(!ctx->task_complete))
  1900. goto out;
  1901. if (!ctx->submitter_task)
  1902. goto out;
  1903. /*
  1904. * with ->submitter_task only the submitter task completes requests, we
  1905. * only need to sync with it, which is done by injecting a tw
  1906. */
  1907. init_task_work(&ctx->poll_wq_task_work, io_activate_pollwq_cb);
  1908. percpu_ref_get(&ctx->refs);
  1909. if (task_work_add(ctx->submitter_task, &ctx->poll_wq_task_work, TWA_SIGNAL))
  1910. percpu_ref_put(&ctx->refs);
  1911. out:
  1912. spin_unlock(&ctx->completion_lock);
  1913. }
  1914. static __poll_t io_uring_poll(struct file *file, poll_table *wait)
  1915. {
  1916. struct io_ring_ctx *ctx = file->private_data;
  1917. __poll_t mask = 0;
  1918. if (unlikely(!ctx->poll_activated))
  1919. io_activate_pollwq(ctx);
  1920. /*
  1921. * provides mb() which pairs with barrier from wq_has_sleeper
  1922. * call in io_commit_cqring
  1923. */
  1924. poll_wait(file, &ctx->poll_wq, wait);
  1925. rcu_read_lock();
  1926. if (!__io_sqring_full(ctx))
  1927. mask |= EPOLLOUT | EPOLLWRNORM;
  1928. /*
  1929. * Don't flush cqring overflow list here, just do a simple check.
  1930. * Otherwise there could possible be ABBA deadlock:
  1931. * CPU0 CPU1
  1932. * ---- ----
  1933. * lock(&ctx->uring_lock);
  1934. * lock(&ep->mtx);
  1935. * lock(&ctx->uring_lock);
  1936. * lock(&ep->mtx);
  1937. *
  1938. * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
  1939. * pushes them to do the flush.
  1940. */
  1941. if (__io_cqring_events_user(ctx) || io_has_work(ctx))
  1942. mask |= EPOLLIN | EPOLLRDNORM;
  1943. rcu_read_unlock();
  1944. return mask;
  1945. }
  1946. struct io_tctx_exit {
  1947. struct callback_head task_work;
  1948. struct completion completion;
  1949. struct io_ring_ctx *ctx;
  1950. };
  1951. static __cold void io_tctx_exit_cb(struct callback_head *cb)
  1952. {
  1953. struct io_uring_task *tctx = current->io_uring;
  1954. struct io_tctx_exit *work;
  1955. work = container_of(cb, struct io_tctx_exit, task_work);
  1956. /*
  1957. * When @in_cancel, we're in cancellation and it's racy to remove the
  1958. * node. It'll be removed by the end of cancellation, just ignore it.
  1959. * tctx can be NULL if the queueing of this task_work raced with
  1960. * work cancelation off the exec path.
  1961. */
  1962. if (tctx && !atomic_read(&tctx->in_cancel))
  1963. io_uring_del_tctx_node((unsigned long)work->ctx);
  1964. complete(&work->completion);
  1965. }
  1966. static __cold void io_ring_exit_work(struct work_struct *work)
  1967. {
  1968. struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
  1969. unsigned long timeout = jiffies + IO_URING_EXIT_WAIT_MAX;
  1970. unsigned long interval = HZ / 20;
  1971. struct io_tctx_exit exit;
  1972. struct io_tctx_node *node;
  1973. int ret;
  1974. /*
  1975. * If we're doing polled IO and end up having requests being
  1976. * submitted async (out-of-line), then completions can come in while
  1977. * we're waiting for refs to drop. We need to reap these manually,
  1978. * as nobody else will be looking for them.
  1979. */
  1980. do {
  1981. if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
  1982. mutex_lock(&ctx->uring_lock);
  1983. io_cqring_overflow_kill(ctx);
  1984. mutex_unlock(&ctx->uring_lock);
  1985. }
  1986. /* The SQPOLL thread never reaches this path */
  1987. do {
  1988. if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
  1989. io_move_task_work_from_local(ctx);
  1990. cond_resched();
  1991. } while (io_uring_try_cancel_requests(ctx, NULL, true, false));
  1992. if (ctx->sq_data) {
  1993. struct io_sq_data *sqd = ctx->sq_data;
  1994. struct task_struct *tsk;
  1995. io_sq_thread_park(sqd);
  1996. tsk = sqpoll_task_locked(sqd);
  1997. if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
  1998. io_wq_cancel_cb(tsk->io_uring->io_wq,
  1999. io_cancel_ctx_cb, ctx, true);
  2000. io_sq_thread_unpark(sqd);
  2001. }
  2002. io_req_caches_free(ctx);
  2003. if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
  2004. /* there is little hope left, don't run it too often */
  2005. interval = HZ * 60;
  2006. }
  2007. /*
  2008. * This is really an uninterruptible wait, as it has to be
  2009. * complete. But it's also run from a kworker, which doesn't
  2010. * take signals, so it's fine to make it interruptible. This
  2011. * avoids scenarios where we knowingly can wait much longer
  2012. * on completions, for example if someone does a SIGSTOP on
  2013. * a task that needs to finish task_work to make this loop
  2014. * complete. That's a synthetic situation that should not
  2015. * cause a stuck task backtrace, and hence a potential panic
  2016. * on stuck tasks if that is enabled.
  2017. */
  2018. } while (!wait_for_completion_interruptible_timeout(&ctx->ref_comp, interval));
  2019. init_completion(&exit.completion);
  2020. init_task_work(&exit.task_work, io_tctx_exit_cb);
  2021. exit.ctx = ctx;
  2022. mutex_lock(&ctx->uring_lock);
  2023. mutex_lock(&ctx->tctx_lock);
  2024. while (!list_empty(&ctx->tctx_list)) {
  2025. WARN_ON_ONCE(time_after(jiffies, timeout));
  2026. node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
  2027. ctx_node);
  2028. /* don't spin on a single task if cancellation failed */
  2029. list_rotate_left(&ctx->tctx_list);
  2030. ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
  2031. if (WARN_ON_ONCE(ret))
  2032. continue;
  2033. mutex_unlock(&ctx->tctx_lock);
  2034. mutex_unlock(&ctx->uring_lock);
  2035. /*
  2036. * See comment above for
  2037. * wait_for_completion_interruptible_timeout() on why this
  2038. * wait is marked as interruptible.
  2039. */
  2040. wait_for_completion_interruptible(&exit.completion);
  2041. mutex_lock(&ctx->uring_lock);
  2042. mutex_lock(&ctx->tctx_lock);
  2043. }
  2044. mutex_unlock(&ctx->tctx_lock);
  2045. mutex_unlock(&ctx->uring_lock);
  2046. spin_lock(&ctx->completion_lock);
  2047. spin_unlock(&ctx->completion_lock);
  2048. /* pairs with RCU read section in io_req_local_work_add() */
  2049. if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
  2050. synchronize_rcu();
  2051. io_ring_ctx_free(ctx);
  2052. }
  2053. static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
  2054. {
  2055. unsigned long index;
  2056. struct cred *creds;
  2057. mutex_lock(&ctx->uring_lock);
  2058. percpu_ref_kill(&ctx->refs);
  2059. xa_for_each(&ctx->personalities, index, creds)
  2060. io_unregister_personality(ctx, index);
  2061. mutex_unlock(&ctx->uring_lock);
  2062. flush_delayed_work(&ctx->fallback_work);
  2063. INIT_WORK(&ctx->exit_work, io_ring_exit_work);
  2064. /*
  2065. * Use system_dfl_wq to avoid spawning tons of event kworkers
  2066. * if we're exiting a ton of rings at the same time. It just adds
  2067. * noise and overhead, there's no discernable change in runtime
  2068. * over using system_percpu_wq.
  2069. */
  2070. queue_work(iou_wq, &ctx->exit_work);
  2071. }
  2072. static int io_uring_release(struct inode *inode, struct file *file)
  2073. {
  2074. struct io_ring_ctx *ctx = file->private_data;
  2075. file->private_data = NULL;
  2076. io_ring_ctx_wait_and_kill(ctx);
  2077. return 0;
  2078. }
  2079. static struct io_uring_reg_wait *io_get_ext_arg_reg(struct io_ring_ctx *ctx,
  2080. const struct io_uring_getevents_arg __user *uarg)
  2081. {
  2082. unsigned long size = sizeof(struct io_uring_reg_wait);
  2083. unsigned long offset = (uintptr_t)uarg;
  2084. unsigned long end;
  2085. if (unlikely(offset % sizeof(long)))
  2086. return ERR_PTR(-EFAULT);
  2087. /* also protects from NULL ->cq_wait_arg as the size would be 0 */
  2088. if (unlikely(check_add_overflow(offset, size, &end) ||
  2089. end > ctx->cq_wait_size))
  2090. return ERR_PTR(-EFAULT);
  2091. offset = array_index_nospec(offset, ctx->cq_wait_size - size);
  2092. return ctx->cq_wait_arg + offset;
  2093. }
  2094. static int io_validate_ext_arg(struct io_ring_ctx *ctx, unsigned flags,
  2095. const void __user *argp, size_t argsz)
  2096. {
  2097. struct io_uring_getevents_arg arg;
  2098. if (!(flags & IORING_ENTER_EXT_ARG))
  2099. return 0;
  2100. if (flags & IORING_ENTER_EXT_ARG_REG)
  2101. return -EINVAL;
  2102. if (argsz != sizeof(arg))
  2103. return -EINVAL;
  2104. if (copy_from_user(&arg, argp, sizeof(arg)))
  2105. return -EFAULT;
  2106. return 0;
  2107. }
  2108. static int io_get_ext_arg(struct io_ring_ctx *ctx, unsigned flags,
  2109. const void __user *argp, struct ext_arg *ext_arg)
  2110. {
  2111. const struct io_uring_getevents_arg __user *uarg = argp;
  2112. struct io_uring_getevents_arg arg;
  2113. ext_arg->iowait = !(flags & IORING_ENTER_NO_IOWAIT);
  2114. /*
  2115. * If EXT_ARG isn't set, then we have no timespec and the argp pointer
  2116. * is just a pointer to the sigset_t.
  2117. */
  2118. if (!(flags & IORING_ENTER_EXT_ARG)) {
  2119. ext_arg->sig = (const sigset_t __user *) argp;
  2120. return 0;
  2121. }
  2122. if (flags & IORING_ENTER_EXT_ARG_REG) {
  2123. struct io_uring_reg_wait *w;
  2124. if (ext_arg->argsz != sizeof(struct io_uring_reg_wait))
  2125. return -EINVAL;
  2126. w = io_get_ext_arg_reg(ctx, argp);
  2127. if (IS_ERR(w))
  2128. return PTR_ERR(w);
  2129. if (w->flags & ~IORING_REG_WAIT_TS)
  2130. return -EINVAL;
  2131. ext_arg->min_time = READ_ONCE(w->min_wait_usec) * NSEC_PER_USEC;
  2132. ext_arg->sig = u64_to_user_ptr(READ_ONCE(w->sigmask));
  2133. ext_arg->argsz = READ_ONCE(w->sigmask_sz);
  2134. if (w->flags & IORING_REG_WAIT_TS) {
  2135. ext_arg->ts.tv_sec = READ_ONCE(w->ts.tv_sec);
  2136. ext_arg->ts.tv_nsec = READ_ONCE(w->ts.tv_nsec);
  2137. ext_arg->ts_set = true;
  2138. }
  2139. return 0;
  2140. }
  2141. /*
  2142. * EXT_ARG is set - ensure we agree on the size of it and copy in our
  2143. * timespec and sigset_t pointers if good.
  2144. */
  2145. if (ext_arg->argsz != sizeof(arg))
  2146. return -EINVAL;
  2147. #ifdef CONFIG_64BIT
  2148. if (!user_access_begin(uarg, sizeof(*uarg)))
  2149. return -EFAULT;
  2150. unsafe_get_user(arg.sigmask, &uarg->sigmask, uaccess_end);
  2151. unsafe_get_user(arg.sigmask_sz, &uarg->sigmask_sz, uaccess_end);
  2152. unsafe_get_user(arg.min_wait_usec, &uarg->min_wait_usec, uaccess_end);
  2153. unsafe_get_user(arg.ts, &uarg->ts, uaccess_end);
  2154. user_access_end();
  2155. #else
  2156. if (copy_from_user(&arg, uarg, sizeof(arg)))
  2157. return -EFAULT;
  2158. #endif
  2159. ext_arg->min_time = arg.min_wait_usec * NSEC_PER_USEC;
  2160. ext_arg->sig = u64_to_user_ptr(arg.sigmask);
  2161. ext_arg->argsz = arg.sigmask_sz;
  2162. if (arg.ts) {
  2163. if (get_timespec64(&ext_arg->ts, u64_to_user_ptr(arg.ts)))
  2164. return -EFAULT;
  2165. ext_arg->ts_set = true;
  2166. }
  2167. return 0;
  2168. #ifdef CONFIG_64BIT
  2169. uaccess_end:
  2170. user_access_end();
  2171. return -EFAULT;
  2172. #endif
  2173. }
  2174. SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
  2175. u32, min_complete, u32, flags, const void __user *, argp,
  2176. size_t, argsz)
  2177. {
  2178. struct io_ring_ctx *ctx;
  2179. struct file *file;
  2180. long ret;
  2181. if (unlikely(flags & ~IORING_ENTER_FLAGS))
  2182. return -EINVAL;
  2183. /*
  2184. * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
  2185. * need only dereference our task private array to find it.
  2186. */
  2187. if (flags & IORING_ENTER_REGISTERED_RING) {
  2188. struct io_uring_task *tctx = current->io_uring;
  2189. if (unlikely(!tctx || fd >= IO_RINGFD_REG_MAX))
  2190. return -EINVAL;
  2191. fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
  2192. file = tctx->registered_rings[fd];
  2193. if (unlikely(!file))
  2194. return -EBADF;
  2195. } else {
  2196. file = fget(fd);
  2197. if (unlikely(!file))
  2198. return -EBADF;
  2199. ret = -EOPNOTSUPP;
  2200. if (unlikely(!io_is_uring_fops(file)))
  2201. goto out;
  2202. }
  2203. ctx = file->private_data;
  2204. ret = -EBADFD;
  2205. /*
  2206. * Keep IORING_SETUP_R_DISABLED check before submitter_task load
  2207. * in io_uring_add_tctx_node() -> __io_uring_add_tctx_node_from_submit()
  2208. */
  2209. if (unlikely(smp_load_acquire(&ctx->flags) & IORING_SETUP_R_DISABLED))
  2210. goto out;
  2211. /*
  2212. * For SQ polling, the thread will do all submissions and completions.
  2213. * Just return the requested submit count, and wake the thread if
  2214. * we were asked to.
  2215. */
  2216. ret = 0;
  2217. if (ctx->flags & IORING_SETUP_SQPOLL) {
  2218. if (unlikely(ctx->sq_data->thread == NULL)) {
  2219. ret = -EOWNERDEAD;
  2220. goto out;
  2221. }
  2222. if (flags & IORING_ENTER_SQ_WAKEUP)
  2223. wake_up(&ctx->sq_data->wait);
  2224. if (flags & IORING_ENTER_SQ_WAIT)
  2225. io_sqpoll_wait_sq(ctx);
  2226. ret = to_submit;
  2227. } else if (to_submit) {
  2228. ret = io_uring_add_tctx_node(ctx);
  2229. if (unlikely(ret))
  2230. goto out;
  2231. mutex_lock(&ctx->uring_lock);
  2232. ret = io_submit_sqes(ctx, to_submit);
  2233. if (ret != to_submit) {
  2234. mutex_unlock(&ctx->uring_lock);
  2235. goto out;
  2236. }
  2237. if (flags & IORING_ENTER_GETEVENTS) {
  2238. if (ctx->syscall_iopoll)
  2239. goto iopoll_locked;
  2240. /*
  2241. * Ignore errors, we'll soon call io_cqring_wait() and
  2242. * it should handle ownership problems if any.
  2243. */
  2244. if (ctx->flags & IORING_SETUP_DEFER_TASKRUN)
  2245. (void)io_run_local_work_locked(ctx, min_complete);
  2246. }
  2247. mutex_unlock(&ctx->uring_lock);
  2248. }
  2249. if (flags & IORING_ENTER_GETEVENTS) {
  2250. int ret2;
  2251. if (ctx->syscall_iopoll) {
  2252. /*
  2253. * We disallow the app entering submit/complete with
  2254. * polling, but we still need to lock the ring to
  2255. * prevent racing with polled issue that got punted to
  2256. * a workqueue.
  2257. */
  2258. mutex_lock(&ctx->uring_lock);
  2259. iopoll_locked:
  2260. ret2 = io_validate_ext_arg(ctx, flags, argp, argsz);
  2261. if (likely(!ret2))
  2262. ret2 = io_iopoll_check(ctx, min_complete);
  2263. mutex_unlock(&ctx->uring_lock);
  2264. } else {
  2265. struct ext_arg ext_arg = { .argsz = argsz };
  2266. ret2 = io_get_ext_arg(ctx, flags, argp, &ext_arg);
  2267. if (likely(!ret2))
  2268. ret2 = io_cqring_wait(ctx, min_complete, flags,
  2269. &ext_arg);
  2270. }
  2271. if (!ret) {
  2272. ret = ret2;
  2273. /*
  2274. * EBADR indicates that one or more CQE were dropped.
  2275. * Once the user has been informed we can clear the bit
  2276. * as they are obviously ok with those drops.
  2277. */
  2278. if (unlikely(ret2 == -EBADR))
  2279. clear_bit(IO_CHECK_CQ_DROPPED_BIT,
  2280. &ctx->check_cq);
  2281. }
  2282. }
  2283. out:
  2284. if (!(flags & IORING_ENTER_REGISTERED_RING))
  2285. fput(file);
  2286. return ret;
  2287. }
  2288. static const struct file_operations io_uring_fops = {
  2289. .release = io_uring_release,
  2290. .mmap = io_uring_mmap,
  2291. .get_unmapped_area = io_uring_get_unmapped_area,
  2292. #ifndef CONFIG_MMU
  2293. .mmap_capabilities = io_uring_nommu_mmap_capabilities,
  2294. #endif
  2295. .poll = io_uring_poll,
  2296. #ifdef CONFIG_PROC_FS
  2297. .show_fdinfo = io_uring_show_fdinfo,
  2298. #endif
  2299. };
  2300. bool io_is_uring_fops(struct file *file)
  2301. {
  2302. return file->f_op == &io_uring_fops;
  2303. }
  2304. static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
  2305. struct io_ctx_config *config)
  2306. {
  2307. struct io_uring_params *p = &config->p;
  2308. struct io_rings_layout *rl = &config->layout;
  2309. struct io_uring_region_desc rd;
  2310. struct io_rings *rings;
  2311. int ret;
  2312. /* make sure these are sane, as we already accounted them */
  2313. ctx->sq_entries = p->sq_entries;
  2314. ctx->cq_entries = p->cq_entries;
  2315. memset(&rd, 0, sizeof(rd));
  2316. rd.size = PAGE_ALIGN(rl->rings_size);
  2317. if (ctx->flags & IORING_SETUP_NO_MMAP) {
  2318. rd.user_addr = p->cq_off.user_addr;
  2319. rd.flags |= IORING_MEM_REGION_TYPE_USER;
  2320. }
  2321. ret = io_create_region(ctx, &ctx->ring_region, &rd, IORING_OFF_CQ_RING);
  2322. if (ret)
  2323. return ret;
  2324. ctx->rings = rings = io_region_get_ptr(&ctx->ring_region);
  2325. rcu_assign_pointer(ctx->rings_rcu, rings);
  2326. if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
  2327. ctx->sq_array = (u32 *)((char *)rings + rl->sq_array_offset);
  2328. memset(&rd, 0, sizeof(rd));
  2329. rd.size = PAGE_ALIGN(rl->sq_size);
  2330. if (ctx->flags & IORING_SETUP_NO_MMAP) {
  2331. rd.user_addr = p->sq_off.user_addr;
  2332. rd.flags |= IORING_MEM_REGION_TYPE_USER;
  2333. }
  2334. ret = io_create_region(ctx, &ctx->sq_region, &rd, IORING_OFF_SQES);
  2335. if (ret) {
  2336. io_rings_free(ctx);
  2337. return ret;
  2338. }
  2339. ctx->sq_sqes = io_region_get_ptr(&ctx->sq_region);
  2340. memset(rings, 0, sizeof(*rings));
  2341. WRITE_ONCE(rings->sq_ring_mask, ctx->sq_entries - 1);
  2342. WRITE_ONCE(rings->cq_ring_mask, ctx->cq_entries - 1);
  2343. WRITE_ONCE(rings->sq_ring_entries, ctx->sq_entries);
  2344. WRITE_ONCE(rings->cq_ring_entries, ctx->cq_entries);
  2345. return 0;
  2346. }
  2347. static int io_uring_install_fd(struct file *file)
  2348. {
  2349. int fd;
  2350. fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
  2351. if (fd < 0)
  2352. return fd;
  2353. fd_install(fd, file);
  2354. return fd;
  2355. }
  2356. /*
  2357. * Allocate an anonymous fd, this is what constitutes the application
  2358. * visible backing of an io_uring instance. The application mmaps this
  2359. * fd to gain access to the SQ/CQ ring details.
  2360. */
  2361. static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
  2362. {
  2363. /* Create a new inode so that the LSM can block the creation. */
  2364. return anon_inode_create_getfile("[io_uring]", &io_uring_fops, ctx,
  2365. O_RDWR | O_CLOEXEC, NULL);
  2366. }
  2367. static int io_uring_sanitise_params(struct io_uring_params *p)
  2368. {
  2369. unsigned flags = p->flags;
  2370. if (flags & ~IORING_SETUP_FLAGS)
  2371. return -EINVAL;
  2372. if (flags & IORING_SETUP_SQ_REWIND) {
  2373. if ((flags & IORING_SETUP_SQPOLL) ||
  2374. !(flags & IORING_SETUP_NO_SQARRAY))
  2375. return -EINVAL;
  2376. }
  2377. /* There is no way to mmap rings without a real fd */
  2378. if ((flags & IORING_SETUP_REGISTERED_FD_ONLY) &&
  2379. !(flags & IORING_SETUP_NO_MMAP))
  2380. return -EINVAL;
  2381. if (flags & IORING_SETUP_SQPOLL) {
  2382. /* IPI related flags don't make sense with SQPOLL */
  2383. if (flags & (IORING_SETUP_COOP_TASKRUN |
  2384. IORING_SETUP_TASKRUN_FLAG |
  2385. IORING_SETUP_DEFER_TASKRUN))
  2386. return -EINVAL;
  2387. }
  2388. if (flags & IORING_SETUP_TASKRUN_FLAG) {
  2389. if (!(flags & (IORING_SETUP_COOP_TASKRUN |
  2390. IORING_SETUP_DEFER_TASKRUN)))
  2391. return -EINVAL;
  2392. }
  2393. /* HYBRID_IOPOLL only valid with IOPOLL */
  2394. if ((flags & IORING_SETUP_HYBRID_IOPOLL) && !(flags & IORING_SETUP_IOPOLL))
  2395. return -EINVAL;
  2396. /*
  2397. * For DEFER_TASKRUN we require the completion task to be the same as
  2398. * the submission task. This implies that there is only one submitter.
  2399. */
  2400. if ((flags & IORING_SETUP_DEFER_TASKRUN) &&
  2401. !(flags & IORING_SETUP_SINGLE_ISSUER))
  2402. return -EINVAL;
  2403. /*
  2404. * Nonsensical to ask for CQE32 and mixed CQE support, it's not
  2405. * supported to post 16b CQEs on a ring setup with CQE32.
  2406. */
  2407. if ((flags & (IORING_SETUP_CQE32|IORING_SETUP_CQE_MIXED)) ==
  2408. (IORING_SETUP_CQE32|IORING_SETUP_CQE_MIXED))
  2409. return -EINVAL;
  2410. /*
  2411. * Nonsensical to ask for SQE128 and mixed SQE support, it's not
  2412. * supported to post 64b SQEs on a ring setup with SQE128.
  2413. */
  2414. if ((flags & (IORING_SETUP_SQE128|IORING_SETUP_SQE_MIXED)) ==
  2415. (IORING_SETUP_SQE128|IORING_SETUP_SQE_MIXED))
  2416. return -EINVAL;
  2417. return 0;
  2418. }
  2419. static int io_uring_fill_params(struct io_uring_params *p)
  2420. {
  2421. unsigned entries = p->sq_entries;
  2422. if (!entries)
  2423. return -EINVAL;
  2424. if (entries > IORING_MAX_ENTRIES) {
  2425. if (!(p->flags & IORING_SETUP_CLAMP))
  2426. return -EINVAL;
  2427. entries = IORING_MAX_ENTRIES;
  2428. }
  2429. /*
  2430. * Use twice as many entries for the CQ ring. It's possible for the
  2431. * application to drive a higher depth than the size of the SQ ring,
  2432. * since the sqes are only used at submission time. This allows for
  2433. * some flexibility in overcommitting a bit. If the application has
  2434. * set IORING_SETUP_CQSIZE, it will have passed in the desired number
  2435. * of CQ ring entries manually.
  2436. */
  2437. p->sq_entries = roundup_pow_of_two(entries);
  2438. if (p->flags & IORING_SETUP_CQSIZE) {
  2439. /*
  2440. * If IORING_SETUP_CQSIZE is set, we do the same roundup
  2441. * to a power-of-two, if it isn't already. We do NOT impose
  2442. * any cq vs sq ring sizing.
  2443. */
  2444. if (!p->cq_entries)
  2445. return -EINVAL;
  2446. if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
  2447. if (!(p->flags & IORING_SETUP_CLAMP))
  2448. return -EINVAL;
  2449. p->cq_entries = IORING_MAX_CQ_ENTRIES;
  2450. }
  2451. p->cq_entries = roundup_pow_of_two(p->cq_entries);
  2452. if (p->cq_entries < p->sq_entries)
  2453. return -EINVAL;
  2454. } else {
  2455. p->cq_entries = 2 * p->sq_entries;
  2456. }
  2457. return 0;
  2458. }
  2459. int io_prepare_config(struct io_ctx_config *config)
  2460. {
  2461. struct io_uring_params *p = &config->p;
  2462. int ret;
  2463. ret = io_uring_sanitise_params(p);
  2464. if (ret)
  2465. return ret;
  2466. ret = io_uring_fill_params(p);
  2467. if (ret)
  2468. return ret;
  2469. ret = rings_size(p->flags, p->sq_entries, p->cq_entries,
  2470. &config->layout);
  2471. if (ret)
  2472. return ret;
  2473. p->sq_off.head = offsetof(struct io_rings, sq.head);
  2474. p->sq_off.tail = offsetof(struct io_rings, sq.tail);
  2475. p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
  2476. p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
  2477. p->sq_off.flags = offsetof(struct io_rings, sq_flags);
  2478. p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
  2479. p->sq_off.resv1 = 0;
  2480. if (!(p->flags & IORING_SETUP_NO_MMAP))
  2481. p->sq_off.user_addr = 0;
  2482. p->cq_off.head = offsetof(struct io_rings, cq.head);
  2483. p->cq_off.tail = offsetof(struct io_rings, cq.tail);
  2484. p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
  2485. p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
  2486. p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
  2487. p->cq_off.cqes = offsetof(struct io_rings, cqes);
  2488. p->cq_off.flags = offsetof(struct io_rings, cq_flags);
  2489. p->cq_off.resv1 = 0;
  2490. if (!(p->flags & IORING_SETUP_NO_MMAP))
  2491. p->cq_off.user_addr = 0;
  2492. if (!(p->flags & IORING_SETUP_NO_SQARRAY))
  2493. p->sq_off.array = config->layout.sq_array_offset;
  2494. return 0;
  2495. }
  2496. void io_restriction_clone(struct io_restriction *dst, struct io_restriction *src)
  2497. {
  2498. memcpy(&dst->register_op, &src->register_op, sizeof(dst->register_op));
  2499. memcpy(&dst->sqe_op, &src->sqe_op, sizeof(dst->sqe_op));
  2500. dst->sqe_flags_allowed = src->sqe_flags_allowed;
  2501. dst->sqe_flags_required = src->sqe_flags_required;
  2502. dst->op_registered = src->op_registered;
  2503. dst->reg_registered = src->reg_registered;
  2504. io_bpf_filter_clone(dst, src);
  2505. }
  2506. static void io_ctx_restriction_clone(struct io_ring_ctx *ctx,
  2507. struct io_restriction *src)
  2508. {
  2509. struct io_restriction *dst = &ctx->restrictions;
  2510. io_restriction_clone(dst, src);
  2511. if (dst->bpf_filters)
  2512. WRITE_ONCE(ctx->bpf_filters, dst->bpf_filters->filters);
  2513. if (dst->op_registered)
  2514. ctx->op_restricted = 1;
  2515. if (dst->reg_registered)
  2516. ctx->reg_restricted = 1;
  2517. }
  2518. static __cold int io_uring_create(struct io_ctx_config *config)
  2519. {
  2520. struct io_uring_params *p = &config->p;
  2521. struct io_ring_ctx *ctx;
  2522. struct io_uring_task *tctx;
  2523. struct file *file;
  2524. int ret;
  2525. ret = io_prepare_config(config);
  2526. if (ret)
  2527. return ret;
  2528. ctx = io_ring_ctx_alloc(p);
  2529. if (!ctx)
  2530. return -ENOMEM;
  2531. ctx->clockid = CLOCK_MONOTONIC;
  2532. ctx->clock_offset = 0;
  2533. if (!(ctx->flags & IORING_SETUP_NO_SQARRAY))
  2534. static_branch_deferred_inc(&io_key_has_sqarray);
  2535. if ((ctx->flags & IORING_SETUP_DEFER_TASKRUN) &&
  2536. !(ctx->flags & IORING_SETUP_IOPOLL))
  2537. ctx->task_complete = true;
  2538. if (ctx->task_complete || (ctx->flags & IORING_SETUP_IOPOLL))
  2539. ctx->lockless_cq = true;
  2540. /*
  2541. * lazy poll_wq activation relies on ->task_complete for synchronisation
  2542. * purposes, see io_activate_pollwq()
  2543. */
  2544. if (!ctx->task_complete)
  2545. ctx->poll_activated = true;
  2546. /*
  2547. * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
  2548. * space applications don't need to do io completion events
  2549. * polling again, they can rely on io_sq_thread to do polling
  2550. * work, which can reduce cpu usage and uring_lock contention.
  2551. */
  2552. if (ctx->flags & IORING_SETUP_IOPOLL &&
  2553. !(ctx->flags & IORING_SETUP_SQPOLL))
  2554. ctx->syscall_iopoll = 1;
  2555. ctx->compat = in_compat_syscall();
  2556. if (!ns_capable_noaudit(&init_user_ns, CAP_IPC_LOCK))
  2557. ctx->user = get_uid(current_user());
  2558. /*
  2559. * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
  2560. * COOP_TASKRUN is set, then IPIs are never needed by the app.
  2561. */
  2562. if (ctx->flags & (IORING_SETUP_SQPOLL|IORING_SETUP_COOP_TASKRUN))
  2563. ctx->notify_method = TWA_SIGNAL_NO_IPI;
  2564. else
  2565. ctx->notify_method = TWA_SIGNAL;
  2566. /*
  2567. * If the current task has restrictions enabled, then copy them to
  2568. * our newly created ring and mark it as registered.
  2569. */
  2570. if (current->io_uring_restrict)
  2571. io_ctx_restriction_clone(ctx, current->io_uring_restrict);
  2572. /*
  2573. * This is just grabbed for accounting purposes. When a process exits,
  2574. * the mm is exited and dropped before the files, hence we need to hang
  2575. * on to this mm purely for the purposes of being able to unaccount
  2576. * memory (locked/pinned vm). It's not used for anything else.
  2577. */
  2578. mmgrab(current->mm);
  2579. ctx->mm_account = current->mm;
  2580. ret = io_allocate_scq_urings(ctx, config);
  2581. if (ret)
  2582. goto err;
  2583. ret = io_sq_offload_create(ctx, p);
  2584. if (ret)
  2585. goto err;
  2586. p->features = IORING_FEAT_FLAGS;
  2587. if (copy_to_user(config->uptr, p, sizeof(*p))) {
  2588. ret = -EFAULT;
  2589. goto err;
  2590. }
  2591. if (ctx->flags & IORING_SETUP_SINGLE_ISSUER
  2592. && !(ctx->flags & IORING_SETUP_R_DISABLED))
  2593. ctx->submitter_task = get_task_struct(current);
  2594. file = io_uring_get_file(ctx);
  2595. if (IS_ERR(file)) {
  2596. ret = PTR_ERR(file);
  2597. goto err;
  2598. }
  2599. ret = __io_uring_add_tctx_node(ctx);
  2600. if (ret)
  2601. goto err_fput;
  2602. tctx = current->io_uring;
  2603. /*
  2604. * Install ring fd as the very last thing, so we don't risk someone
  2605. * having closed it before we finish setup
  2606. */
  2607. if (p->flags & IORING_SETUP_REGISTERED_FD_ONLY)
  2608. ret = io_ring_add_registered_file(tctx, file, 0, IO_RINGFD_REG_MAX);
  2609. else
  2610. ret = io_uring_install_fd(file);
  2611. if (ret < 0)
  2612. goto err_fput;
  2613. trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
  2614. return ret;
  2615. err:
  2616. io_ring_ctx_wait_and_kill(ctx);
  2617. return ret;
  2618. err_fput:
  2619. fput(file);
  2620. return ret;
  2621. }
  2622. /*
  2623. * Sets up an aio uring context, and returns the fd. Applications asks for a
  2624. * ring size, we return the actual sq/cq ring sizes (among other things) in the
  2625. * params structure passed in.
  2626. */
  2627. static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
  2628. {
  2629. struct io_ctx_config config;
  2630. memset(&config, 0, sizeof(config));
  2631. if (copy_from_user(&config.p, params, sizeof(config.p)))
  2632. return -EFAULT;
  2633. if (!mem_is_zero(&config.p.resv, sizeof(config.p.resv)))
  2634. return -EINVAL;
  2635. config.p.sq_entries = entries;
  2636. config.uptr = params;
  2637. return io_uring_create(&config);
  2638. }
  2639. static inline int io_uring_allowed(void)
  2640. {
  2641. int disabled = READ_ONCE(sysctl_io_uring_disabled);
  2642. kgid_t io_uring_group;
  2643. if (disabled == 2)
  2644. return -EPERM;
  2645. if (disabled == 0 || capable(CAP_SYS_ADMIN))
  2646. goto allowed_lsm;
  2647. io_uring_group = make_kgid(&init_user_ns, sysctl_io_uring_group);
  2648. if (!gid_valid(io_uring_group))
  2649. return -EPERM;
  2650. if (!in_group_p(io_uring_group))
  2651. return -EPERM;
  2652. allowed_lsm:
  2653. return security_uring_allowed();
  2654. }
  2655. SYSCALL_DEFINE2(io_uring_setup, u32, entries,
  2656. struct io_uring_params __user *, params)
  2657. {
  2658. int ret;
  2659. ret = io_uring_allowed();
  2660. if (ret)
  2661. return ret;
  2662. return io_uring_setup(entries, params);
  2663. }
  2664. static int __init io_uring_init(void)
  2665. {
  2666. struct kmem_cache_args kmem_args = {
  2667. .useroffset = offsetof(struct io_kiocb, cmd.data),
  2668. .usersize = sizeof_field(struct io_kiocb, cmd.data),
  2669. .freeptr_offset = offsetof(struct io_kiocb, work),
  2670. .use_freeptr_offset = true,
  2671. };
  2672. #define __BUILD_BUG_VERIFY_OFFSET_SIZE(stype, eoffset, esize, ename) do { \
  2673. BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
  2674. BUILD_BUG_ON(sizeof_field(stype, ename) != esize); \
  2675. } while (0)
  2676. #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
  2677. __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, sizeof(etype), ename)
  2678. #define BUILD_BUG_SQE_ELEM_SIZE(eoffset, esize, ename) \
  2679. __BUILD_BUG_VERIFY_OFFSET_SIZE(struct io_uring_sqe, eoffset, esize, ename)
  2680. BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
  2681. BUILD_BUG_SQE_ELEM(0, __u8, opcode);
  2682. BUILD_BUG_SQE_ELEM(1, __u8, flags);
  2683. BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
  2684. BUILD_BUG_SQE_ELEM(4, __s32, fd);
  2685. BUILD_BUG_SQE_ELEM(8, __u64, off);
  2686. BUILD_BUG_SQE_ELEM(8, __u64, addr2);
  2687. BUILD_BUG_SQE_ELEM(8, __u32, cmd_op);
  2688. BUILD_BUG_SQE_ELEM(12, __u32, __pad1);
  2689. BUILD_BUG_SQE_ELEM(16, __u64, addr);
  2690. BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
  2691. BUILD_BUG_SQE_ELEM(24, __u32, len);
  2692. BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
  2693. BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
  2694. BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
  2695. BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
  2696. BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
  2697. BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
  2698. BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
  2699. BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
  2700. BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
  2701. BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
  2702. BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
  2703. BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
  2704. BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
  2705. BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
  2706. BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
  2707. BUILD_BUG_SQE_ELEM(28, __u32, rename_flags);
  2708. BUILD_BUG_SQE_ELEM(28, __u32, unlink_flags);
  2709. BUILD_BUG_SQE_ELEM(28, __u32, hardlink_flags);
  2710. BUILD_BUG_SQE_ELEM(28, __u32, xattr_flags);
  2711. BUILD_BUG_SQE_ELEM(28, __u32, msg_ring_flags);
  2712. BUILD_BUG_SQE_ELEM(32, __u64, user_data);
  2713. BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
  2714. BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
  2715. BUILD_BUG_SQE_ELEM(42, __u16, personality);
  2716. BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
  2717. BUILD_BUG_SQE_ELEM(44, __u32, file_index);
  2718. BUILD_BUG_SQE_ELEM(44, __u16, addr_len);
  2719. BUILD_BUG_SQE_ELEM(44, __u8, write_stream);
  2720. BUILD_BUG_SQE_ELEM(45, __u8, __pad4[0]);
  2721. BUILD_BUG_SQE_ELEM(46, __u16, __pad3[0]);
  2722. BUILD_BUG_SQE_ELEM(48, __u64, addr3);
  2723. BUILD_BUG_SQE_ELEM_SIZE(48, 0, cmd);
  2724. BUILD_BUG_SQE_ELEM(48, __u64, attr_ptr);
  2725. BUILD_BUG_SQE_ELEM(56, __u64, attr_type_mask);
  2726. BUILD_BUG_SQE_ELEM(56, __u64, __pad2);
  2727. BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
  2728. sizeof(struct io_uring_rsrc_update));
  2729. BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
  2730. sizeof(struct io_uring_rsrc_update2));
  2731. /* ->buf_index is u16 */
  2732. BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
  2733. BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
  2734. offsetof(struct io_uring_buf_ring, tail));
  2735. /* should fit into one byte */
  2736. BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
  2737. BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
  2738. BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
  2739. BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof_field(struct io_kiocb, flags));
  2740. BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
  2741. /* top 8bits are for internal use */
  2742. BUILD_BUG_ON((IORING_URING_CMD_MASK & 0xff000000) != 0);
  2743. io_uring_optable_init();
  2744. /* imu->dir is u8 */
  2745. BUILD_BUG_ON((IO_IMU_DEST | IO_IMU_SOURCE) > U8_MAX);
  2746. /*
  2747. * Allow user copy in the per-command field, which starts after the
  2748. * file in io_kiocb and until the opcode field. The openat2 handling
  2749. * requires copying in user memory into the io_kiocb object in that
  2750. * range, and HARDENED_USERCOPY will complain if we haven't
  2751. * correctly annotated this range.
  2752. */
  2753. req_cachep = kmem_cache_create("io_kiocb", sizeof(struct io_kiocb), &kmem_args,
  2754. SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT |
  2755. SLAB_TYPESAFE_BY_RCU);
  2756. iou_wq = alloc_workqueue("iou_exit", WQ_UNBOUND, 64);
  2757. BUG_ON(!iou_wq);
  2758. #ifdef CONFIG_SYSCTL
  2759. register_sysctl_init("kernel", kernel_io_uring_disabled_table);
  2760. #endif
  2761. return 0;
  2762. };
  2763. __initcall(io_uring_init);