aio.c 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445
  1. /*
  2. * An async IO implementation for Linux
  3. * Written by Benjamin LaHaise <bcrl@kvack.org>
  4. *
  5. * Implements an efficient asynchronous io interface.
  6. *
  7. * Copyright 2000, 2001, 2002 Red Hat, Inc. All Rights Reserved.
  8. * Copyright 2018 Christoph Hellwig.
  9. *
  10. * See ../COPYING for licensing terms.
  11. */
  12. #define pr_fmt(fmt) "%s: " fmt, __func__
  13. #include <linux/kernel.h>
  14. #include <linux/init.h>
  15. #include <linux/errno.h>
  16. #include <linux/time.h>
  17. #include <linux/aio_abi.h>
  18. #include <linux/export.h>
  19. #include <linux/syscalls.h>
  20. #include <linux/backing-dev.h>
  21. #include <linux/refcount.h>
  22. #include <linux/uio.h>
  23. #include <linux/sched/signal.h>
  24. #include <linux/fs.h>
  25. #include <linux/file.h>
  26. #include <linux/mm.h>
  27. #include <linux/mman.h>
  28. #include <linux/percpu.h>
  29. #include <linux/slab.h>
  30. #include <linux/timer.h>
  31. #include <linux/aio.h>
  32. #include <linux/highmem.h>
  33. #include <linux/workqueue.h>
  34. #include <linux/security.h>
  35. #include <linux/eventfd.h>
  36. #include <linux/blkdev.h>
  37. #include <linux/compat.h>
  38. #include <linux/migrate.h>
  39. #include <linux/ramfs.h>
  40. #include <linux/percpu-refcount.h>
  41. #include <linux/mount.h>
  42. #include <linux/pseudo_fs.h>
  43. #include <linux/uaccess.h>
  44. #include <linux/nospec.h>
  45. #include "internal.h"
  46. #define KIOCB_KEY 0
  47. #define AIO_RING_MAGIC 0xa10a10a1
  48. #define AIO_RING_COMPAT_FEATURES 1
  49. #define AIO_RING_INCOMPAT_FEATURES 0
  50. struct aio_ring {
  51. unsigned id; /* kernel internal index number */
  52. unsigned nr; /* number of io_events */
  53. unsigned head; /* Written to by userland or under ring_lock
  54. * mutex by aio_read_events_ring(). */
  55. unsigned tail;
  56. unsigned magic;
  57. unsigned compat_features;
  58. unsigned incompat_features;
  59. unsigned header_length; /* size of aio_ring */
  60. struct io_event io_events[];
  61. }; /* 128 bytes + ring size */
  62. /*
  63. * Plugging is meant to work with larger batches of IOs. If we don't
  64. * have more than the below, then don't bother setting up a plug.
  65. */
  66. #define AIO_PLUG_THRESHOLD 2
  67. #define AIO_RING_PAGES 8
  68. struct kioctx_table {
  69. struct rcu_head rcu;
  70. unsigned nr;
  71. struct kioctx __rcu *table[] __counted_by(nr);
  72. };
  73. struct kioctx_cpu {
  74. unsigned reqs_available;
  75. };
  76. struct ctx_rq_wait {
  77. struct completion comp;
  78. atomic_t count;
  79. };
  80. struct kioctx {
  81. struct percpu_ref users;
  82. atomic_t dead;
  83. struct percpu_ref reqs;
  84. unsigned long user_id;
  85. struct kioctx_cpu __percpu *cpu;
  86. /*
  87. * For percpu reqs_available, number of slots we move to/from global
  88. * counter at a time:
  89. */
  90. unsigned req_batch;
  91. /*
  92. * This is what userspace passed to io_setup(), it's not used for
  93. * anything but counting against the global max_reqs quota.
  94. *
  95. * The real limit is nr_events - 1, which will be larger (see
  96. * aio_setup_ring())
  97. */
  98. unsigned max_reqs;
  99. /* Size of ringbuffer, in units of struct io_event */
  100. unsigned nr_events;
  101. unsigned long mmap_base;
  102. unsigned long mmap_size;
  103. struct folio **ring_folios;
  104. long nr_pages;
  105. struct rcu_work free_rwork; /* see free_ioctx() */
  106. /*
  107. * signals when all in-flight requests are done
  108. */
  109. struct ctx_rq_wait *rq_wait;
  110. struct {
  111. /*
  112. * This counts the number of available slots in the ringbuffer,
  113. * so we avoid overflowing it: it's decremented (if positive)
  114. * when allocating a kiocb and incremented when the resulting
  115. * io_event is pulled off the ringbuffer.
  116. *
  117. * We batch accesses to it with a percpu version.
  118. */
  119. atomic_t reqs_available;
  120. } ____cacheline_aligned_in_smp;
  121. struct {
  122. spinlock_t ctx_lock;
  123. struct list_head active_reqs; /* used for cancellation */
  124. } ____cacheline_aligned_in_smp;
  125. struct {
  126. struct mutex ring_lock;
  127. wait_queue_head_t wait;
  128. } ____cacheline_aligned_in_smp;
  129. struct {
  130. unsigned tail;
  131. unsigned completed_events;
  132. spinlock_t completion_lock;
  133. } ____cacheline_aligned_in_smp;
  134. struct folio *internal_folios[AIO_RING_PAGES];
  135. struct file *aio_ring_file;
  136. unsigned id;
  137. };
  138. /*
  139. * First field must be the file pointer in all the
  140. * iocb unions! See also 'struct kiocb' in <linux/fs.h>
  141. */
  142. struct fsync_iocb {
  143. struct file *file;
  144. struct work_struct work;
  145. bool datasync;
  146. struct cred *creds;
  147. };
  148. struct poll_iocb {
  149. struct file *file;
  150. struct wait_queue_head *head;
  151. __poll_t events;
  152. bool cancelled;
  153. bool work_scheduled;
  154. bool work_need_resched;
  155. struct wait_queue_entry wait;
  156. struct work_struct work;
  157. };
  158. /*
  159. * NOTE! Each of the iocb union members has the file pointer
  160. * as the first entry in their struct definition. So you can
  161. * access the file pointer through any of the sub-structs,
  162. * or directly as just 'ki_filp' in this struct.
  163. */
  164. struct aio_kiocb {
  165. union {
  166. struct file *ki_filp;
  167. struct kiocb rw;
  168. struct fsync_iocb fsync;
  169. struct poll_iocb poll;
  170. };
  171. struct kioctx *ki_ctx;
  172. kiocb_cancel_fn *ki_cancel;
  173. struct io_event ki_res;
  174. struct list_head ki_list; /* the aio core uses this
  175. * for cancellation */
  176. refcount_t ki_refcnt;
  177. /*
  178. * If the aio_resfd field of the userspace iocb is not zero,
  179. * this is the underlying eventfd context to deliver events to.
  180. */
  181. struct eventfd_ctx *ki_eventfd;
  182. };
  183. /*------ sysctl variables----*/
  184. static DEFINE_SPINLOCK(aio_nr_lock);
  185. static unsigned long aio_nr; /* current system wide number of aio requests */
  186. static unsigned long aio_max_nr = 0x10000; /* system wide maximum number of aio requests */
  187. /*----end sysctl variables---*/
  188. #ifdef CONFIG_SYSCTL
  189. static struct ctl_table aio_sysctls[] = {
  190. {
  191. .procname = "aio-nr",
  192. .data = &aio_nr,
  193. .maxlen = sizeof(aio_nr),
  194. .mode = 0444,
  195. .proc_handler = proc_doulongvec_minmax,
  196. },
  197. {
  198. .procname = "aio-max-nr",
  199. .data = &aio_max_nr,
  200. .maxlen = sizeof(aio_max_nr),
  201. .mode = 0644,
  202. .proc_handler = proc_doulongvec_minmax,
  203. },
  204. };
  205. static void __init aio_sysctl_init(void)
  206. {
  207. register_sysctl_init("fs", aio_sysctls);
  208. }
  209. #else
  210. #define aio_sysctl_init() do { } while (0)
  211. #endif
  212. static struct kmem_cache *kiocb_cachep;
  213. static struct kmem_cache *kioctx_cachep;
  214. static struct vfsmount *aio_mnt;
  215. static const struct file_operations aio_ring_fops;
  216. static const struct address_space_operations aio_ctx_aops;
  217. static struct file *aio_private_file(struct kioctx *ctx, loff_t nr_pages)
  218. {
  219. struct file *file;
  220. struct inode *inode = alloc_anon_inode(aio_mnt->mnt_sb);
  221. if (IS_ERR(inode))
  222. return ERR_CAST(inode);
  223. inode->i_mapping->a_ops = &aio_ctx_aops;
  224. inode->i_mapping->i_private_data = ctx;
  225. inode->i_size = PAGE_SIZE * nr_pages;
  226. file = alloc_file_pseudo(inode, aio_mnt, "[aio]",
  227. O_RDWR, &aio_ring_fops);
  228. if (IS_ERR(file))
  229. iput(inode);
  230. return file;
  231. }
  232. static int aio_init_fs_context(struct fs_context *fc)
  233. {
  234. if (!init_pseudo(fc, AIO_RING_MAGIC))
  235. return -ENOMEM;
  236. fc->s_iflags |= SB_I_NOEXEC;
  237. return 0;
  238. }
  239. /* aio_setup
  240. * Creates the slab caches used by the aio routines, panic on
  241. * failure as this is done early during the boot sequence.
  242. */
  243. static int __init aio_setup(void)
  244. {
  245. static struct file_system_type aio_fs = {
  246. .name = "aio",
  247. .init_fs_context = aio_init_fs_context,
  248. .kill_sb = kill_anon_super,
  249. };
  250. aio_mnt = kern_mount(&aio_fs);
  251. if (IS_ERR(aio_mnt))
  252. panic("Failed to create aio fs mount.");
  253. kiocb_cachep = KMEM_CACHE(aio_kiocb, SLAB_HWCACHE_ALIGN|SLAB_PANIC);
  254. kioctx_cachep = KMEM_CACHE(kioctx,SLAB_HWCACHE_ALIGN|SLAB_PANIC);
  255. aio_sysctl_init();
  256. return 0;
  257. }
  258. __initcall(aio_setup);
  259. static void put_aio_ring_file(struct kioctx *ctx)
  260. {
  261. struct file *aio_ring_file = ctx->aio_ring_file;
  262. struct address_space *i_mapping;
  263. if (aio_ring_file) {
  264. truncate_setsize(file_inode(aio_ring_file), 0);
  265. /* Prevent further access to the kioctx from migratepages */
  266. i_mapping = aio_ring_file->f_mapping;
  267. spin_lock(&i_mapping->i_private_lock);
  268. i_mapping->i_private_data = NULL;
  269. ctx->aio_ring_file = NULL;
  270. spin_unlock(&i_mapping->i_private_lock);
  271. fput(aio_ring_file);
  272. }
  273. }
  274. static void aio_free_ring(struct kioctx *ctx)
  275. {
  276. int i;
  277. /* Disconnect the kiotx from the ring file. This prevents future
  278. * accesses to the kioctx from page migration.
  279. */
  280. put_aio_ring_file(ctx);
  281. for (i = 0; i < ctx->nr_pages; i++) {
  282. struct folio *folio = ctx->ring_folios[i];
  283. if (!folio)
  284. continue;
  285. pr_debug("pid(%d) [%d] folio->count=%d\n", current->pid, i,
  286. folio_ref_count(folio));
  287. ctx->ring_folios[i] = NULL;
  288. folio_put(folio);
  289. }
  290. if (ctx->ring_folios && ctx->ring_folios != ctx->internal_folios) {
  291. kfree(ctx->ring_folios);
  292. ctx->ring_folios = NULL;
  293. }
  294. }
  295. static int aio_ring_mremap(struct vm_area_struct *vma)
  296. {
  297. struct file *file = vma->vm_file;
  298. struct mm_struct *mm = vma->vm_mm;
  299. struct kioctx_table *table;
  300. int i, res = -EINVAL;
  301. spin_lock(&mm->ioctx_lock);
  302. rcu_read_lock();
  303. table = rcu_dereference(mm->ioctx_table);
  304. if (!table)
  305. goto out_unlock;
  306. for (i = 0; i < table->nr; i++) {
  307. struct kioctx *ctx;
  308. ctx = rcu_dereference(table->table[i]);
  309. if (ctx && ctx->aio_ring_file == file) {
  310. if (!atomic_read(&ctx->dead)) {
  311. ctx->user_id = ctx->mmap_base = vma->vm_start;
  312. res = 0;
  313. }
  314. break;
  315. }
  316. }
  317. out_unlock:
  318. rcu_read_unlock();
  319. spin_unlock(&mm->ioctx_lock);
  320. return res;
  321. }
  322. static const struct vm_operations_struct aio_ring_vm_ops = {
  323. .mremap = aio_ring_mremap,
  324. #if IS_ENABLED(CONFIG_MMU)
  325. .fault = filemap_fault,
  326. .map_pages = filemap_map_pages,
  327. .page_mkwrite = filemap_page_mkwrite,
  328. #endif
  329. };
  330. static int aio_ring_mmap(struct file *file, struct vm_area_struct *vma)
  331. {
  332. vm_flags_set(vma, VM_DONTEXPAND);
  333. vma->vm_ops = &aio_ring_vm_ops;
  334. return 0;
  335. }
  336. static const struct file_operations aio_ring_fops = {
  337. .mmap = aio_ring_mmap,
  338. };
  339. #if IS_ENABLED(CONFIG_MIGRATION)
  340. static int aio_migrate_folio(struct address_space *mapping, struct folio *dst,
  341. struct folio *src, enum migrate_mode mode)
  342. {
  343. struct kioctx *ctx;
  344. unsigned long flags;
  345. pgoff_t idx;
  346. int rc = 0;
  347. /* mapping->i_private_lock here protects against the kioctx teardown. */
  348. spin_lock(&mapping->i_private_lock);
  349. ctx = mapping->i_private_data;
  350. if (!ctx) {
  351. rc = -EINVAL;
  352. goto out;
  353. }
  354. /* The ring_lock mutex. The prevents aio_read_events() from writing
  355. * to the ring's head, and prevents page migration from mucking in
  356. * a partially initialized kiotx.
  357. */
  358. if (!mutex_trylock(&ctx->ring_lock)) {
  359. rc = -EAGAIN;
  360. goto out;
  361. }
  362. idx = src->index;
  363. if (idx < (pgoff_t)ctx->nr_pages) {
  364. /* Make sure the old folio hasn't already been changed */
  365. if (ctx->ring_folios[idx] != src)
  366. rc = -EAGAIN;
  367. } else
  368. rc = -EINVAL;
  369. if (rc != 0)
  370. goto out_unlock;
  371. /* Writeback must be complete */
  372. BUG_ON(folio_test_writeback(src));
  373. folio_get(dst);
  374. rc = folio_migrate_mapping(mapping, dst, src, 1);
  375. if (rc != MIGRATEPAGE_SUCCESS) {
  376. folio_put(dst);
  377. goto out_unlock;
  378. }
  379. /* Take completion_lock to prevent other writes to the ring buffer
  380. * while the old folio is copied to the new. This prevents new
  381. * events from being lost.
  382. */
  383. spin_lock_irqsave(&ctx->completion_lock, flags);
  384. folio_copy(dst, src);
  385. folio_migrate_flags(dst, src);
  386. BUG_ON(ctx->ring_folios[idx] != src);
  387. ctx->ring_folios[idx] = dst;
  388. spin_unlock_irqrestore(&ctx->completion_lock, flags);
  389. /* The old folio is no longer accessible. */
  390. folio_put(src);
  391. out_unlock:
  392. mutex_unlock(&ctx->ring_lock);
  393. out:
  394. spin_unlock(&mapping->i_private_lock);
  395. return rc;
  396. }
  397. #else
  398. #define aio_migrate_folio NULL
  399. #endif
  400. static const struct address_space_operations aio_ctx_aops = {
  401. .dirty_folio = noop_dirty_folio,
  402. .migrate_folio = aio_migrate_folio,
  403. };
  404. static int aio_setup_ring(struct kioctx *ctx, unsigned int nr_events)
  405. {
  406. struct aio_ring *ring;
  407. struct mm_struct *mm = current->mm;
  408. unsigned long size, unused;
  409. int nr_pages;
  410. int i;
  411. struct file *file;
  412. /* Compensate for the ring buffer's head/tail overlap entry */
  413. nr_events += 2; /* 1 is required, 2 for good luck */
  414. size = sizeof(struct aio_ring);
  415. size += sizeof(struct io_event) * nr_events;
  416. nr_pages = PFN_UP(size);
  417. if (nr_pages < 0)
  418. return -EINVAL;
  419. file = aio_private_file(ctx, nr_pages);
  420. if (IS_ERR(file)) {
  421. ctx->aio_ring_file = NULL;
  422. return -ENOMEM;
  423. }
  424. ctx->aio_ring_file = file;
  425. nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring))
  426. / sizeof(struct io_event);
  427. ctx->ring_folios = ctx->internal_folios;
  428. if (nr_pages > AIO_RING_PAGES) {
  429. ctx->ring_folios = kcalloc(nr_pages, sizeof(struct folio *),
  430. GFP_KERNEL);
  431. if (!ctx->ring_folios) {
  432. put_aio_ring_file(ctx);
  433. return -ENOMEM;
  434. }
  435. }
  436. for (i = 0; i < nr_pages; i++) {
  437. struct folio *folio;
  438. folio = __filemap_get_folio(file->f_mapping, i,
  439. FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
  440. GFP_USER | __GFP_ZERO);
  441. if (IS_ERR(folio))
  442. break;
  443. pr_debug("pid(%d) [%d] folio->count=%d\n", current->pid, i,
  444. folio_ref_count(folio));
  445. folio_end_read(folio, true);
  446. ctx->ring_folios[i] = folio;
  447. }
  448. ctx->nr_pages = i;
  449. if (unlikely(i != nr_pages)) {
  450. aio_free_ring(ctx);
  451. return -ENOMEM;
  452. }
  453. ctx->mmap_size = nr_pages * PAGE_SIZE;
  454. pr_debug("attempting mmap of %lu bytes\n", ctx->mmap_size);
  455. if (mmap_write_lock_killable(mm)) {
  456. ctx->mmap_size = 0;
  457. aio_free_ring(ctx);
  458. return -EINTR;
  459. }
  460. ctx->mmap_base = do_mmap(ctx->aio_ring_file, 0, ctx->mmap_size,
  461. PROT_READ | PROT_WRITE,
  462. MAP_SHARED, 0, 0, &unused, NULL);
  463. mmap_write_unlock(mm);
  464. if (IS_ERR((void *)ctx->mmap_base)) {
  465. ctx->mmap_size = 0;
  466. aio_free_ring(ctx);
  467. return -ENOMEM;
  468. }
  469. pr_debug("mmap address: 0x%08lx\n", ctx->mmap_base);
  470. ctx->user_id = ctx->mmap_base;
  471. ctx->nr_events = nr_events; /* trusted copy */
  472. ring = folio_address(ctx->ring_folios[0]);
  473. ring->nr = nr_events; /* user copy */
  474. ring->id = ~0U;
  475. ring->head = ring->tail = 0;
  476. ring->magic = AIO_RING_MAGIC;
  477. ring->compat_features = AIO_RING_COMPAT_FEATURES;
  478. ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
  479. ring->header_length = sizeof(struct aio_ring);
  480. flush_dcache_folio(ctx->ring_folios[0]);
  481. return 0;
  482. }
  483. #define AIO_EVENTS_PER_PAGE (PAGE_SIZE / sizeof(struct io_event))
  484. #define AIO_EVENTS_FIRST_PAGE ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
  485. #define AIO_EVENTS_OFFSET (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
  486. void kiocb_set_cancel_fn(struct kiocb *iocb, kiocb_cancel_fn *cancel)
  487. {
  488. struct aio_kiocb *req;
  489. struct kioctx *ctx;
  490. unsigned long flags;
  491. /*
  492. * kiocb didn't come from aio or is neither a read nor a write, hence
  493. * ignore it.
  494. */
  495. if (!(iocb->ki_flags & IOCB_AIO_RW))
  496. return;
  497. req = container_of(iocb, struct aio_kiocb, rw);
  498. if (WARN_ON_ONCE(!list_empty(&req->ki_list)))
  499. return;
  500. ctx = req->ki_ctx;
  501. spin_lock_irqsave(&ctx->ctx_lock, flags);
  502. list_add_tail(&req->ki_list, &ctx->active_reqs);
  503. req->ki_cancel = cancel;
  504. spin_unlock_irqrestore(&ctx->ctx_lock, flags);
  505. }
  506. EXPORT_SYMBOL(kiocb_set_cancel_fn);
  507. /*
  508. * free_ioctx() should be RCU delayed to synchronize against the RCU
  509. * protected lookup_ioctx() and also needs process context to call
  510. * aio_free_ring(). Use rcu_work.
  511. */
  512. static void free_ioctx(struct work_struct *work)
  513. {
  514. struct kioctx *ctx = container_of(to_rcu_work(work), struct kioctx,
  515. free_rwork);
  516. pr_debug("freeing %p\n", ctx);
  517. aio_free_ring(ctx);
  518. free_percpu(ctx->cpu);
  519. percpu_ref_exit(&ctx->reqs);
  520. percpu_ref_exit(&ctx->users);
  521. kmem_cache_free(kioctx_cachep, ctx);
  522. }
  523. static void free_ioctx_reqs(struct percpu_ref *ref)
  524. {
  525. struct kioctx *ctx = container_of(ref, struct kioctx, reqs);
  526. /* At this point we know that there are no any in-flight requests */
  527. if (ctx->rq_wait && atomic_dec_and_test(&ctx->rq_wait->count))
  528. complete(&ctx->rq_wait->comp);
  529. /* Synchronize against RCU protected table->table[] dereferences */
  530. INIT_RCU_WORK(&ctx->free_rwork, free_ioctx);
  531. queue_rcu_work(system_wq, &ctx->free_rwork);
  532. }
  533. /*
  534. * When this function runs, the kioctx has been removed from the "hash table"
  535. * and ctx->users has dropped to 0, so we know no more kiocbs can be submitted -
  536. * now it's safe to cancel any that need to be.
  537. */
  538. static void free_ioctx_users(struct percpu_ref *ref)
  539. {
  540. struct kioctx *ctx = container_of(ref, struct kioctx, users);
  541. struct aio_kiocb *req;
  542. spin_lock_irq(&ctx->ctx_lock);
  543. while (!list_empty(&ctx->active_reqs)) {
  544. req = list_first_entry(&ctx->active_reqs,
  545. struct aio_kiocb, ki_list);
  546. req->ki_cancel(&req->rw);
  547. list_del_init(&req->ki_list);
  548. }
  549. spin_unlock_irq(&ctx->ctx_lock);
  550. percpu_ref_kill(&ctx->reqs);
  551. percpu_ref_put(&ctx->reqs);
  552. }
  553. static int ioctx_add_table(struct kioctx *ctx, struct mm_struct *mm)
  554. {
  555. unsigned i, new_nr;
  556. struct kioctx_table *table, *old;
  557. struct aio_ring *ring;
  558. spin_lock(&mm->ioctx_lock);
  559. table = rcu_dereference_raw(mm->ioctx_table);
  560. while (1) {
  561. if (table)
  562. for (i = 0; i < table->nr; i++)
  563. if (!rcu_access_pointer(table->table[i])) {
  564. ctx->id = i;
  565. rcu_assign_pointer(table->table[i], ctx);
  566. spin_unlock(&mm->ioctx_lock);
  567. /* While kioctx setup is in progress,
  568. * we are protected from page migration
  569. * changes ring_folios by ->ring_lock.
  570. */
  571. ring = folio_address(ctx->ring_folios[0]);
  572. ring->id = ctx->id;
  573. return 0;
  574. }
  575. new_nr = (table ? table->nr : 1) * 4;
  576. spin_unlock(&mm->ioctx_lock);
  577. table = kzalloc(struct_size(table, table, new_nr), GFP_KERNEL);
  578. if (!table)
  579. return -ENOMEM;
  580. table->nr = new_nr;
  581. spin_lock(&mm->ioctx_lock);
  582. old = rcu_dereference_raw(mm->ioctx_table);
  583. if (!old) {
  584. rcu_assign_pointer(mm->ioctx_table, table);
  585. } else if (table->nr > old->nr) {
  586. memcpy(table->table, old->table,
  587. old->nr * sizeof(struct kioctx *));
  588. rcu_assign_pointer(mm->ioctx_table, table);
  589. kfree_rcu(old, rcu);
  590. } else {
  591. kfree(table);
  592. table = old;
  593. }
  594. }
  595. }
  596. static void aio_nr_sub(unsigned nr)
  597. {
  598. spin_lock(&aio_nr_lock);
  599. if (WARN_ON(aio_nr - nr > aio_nr))
  600. aio_nr = 0;
  601. else
  602. aio_nr -= nr;
  603. spin_unlock(&aio_nr_lock);
  604. }
  605. /* ioctx_alloc
  606. * Allocates and initializes an ioctx. Returns an ERR_PTR if it failed.
  607. */
  608. static struct kioctx *ioctx_alloc(unsigned nr_events)
  609. {
  610. struct mm_struct *mm = current->mm;
  611. struct kioctx *ctx;
  612. int err = -ENOMEM;
  613. /*
  614. * Store the original nr_events -- what userspace passed to io_setup(),
  615. * for counting against the global limit -- before it changes.
  616. */
  617. unsigned int max_reqs = nr_events;
  618. /*
  619. * We keep track of the number of available ringbuffer slots, to prevent
  620. * overflow (reqs_available), and we also use percpu counters for this.
  621. *
  622. * So since up to half the slots might be on other cpu's percpu counters
  623. * and unavailable, double nr_events so userspace sees what they
  624. * expected: additionally, we move req_batch slots to/from percpu
  625. * counters at a time, so make sure that isn't 0:
  626. */
  627. nr_events = max(nr_events, num_possible_cpus() * 4);
  628. nr_events *= 2;
  629. /* Prevent overflows */
  630. if (nr_events > (0x10000000U / sizeof(struct io_event))) {
  631. pr_debug("ENOMEM: nr_events too high\n");
  632. return ERR_PTR(-EINVAL);
  633. }
  634. if (!nr_events || (unsigned long)max_reqs > aio_max_nr)
  635. return ERR_PTR(-EAGAIN);
  636. ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
  637. if (!ctx)
  638. return ERR_PTR(-ENOMEM);
  639. ctx->max_reqs = max_reqs;
  640. spin_lock_init(&ctx->ctx_lock);
  641. spin_lock_init(&ctx->completion_lock);
  642. mutex_init(&ctx->ring_lock);
  643. /* Protect against page migration throughout kiotx setup by keeping
  644. * the ring_lock mutex held until setup is complete. */
  645. mutex_lock(&ctx->ring_lock);
  646. init_waitqueue_head(&ctx->wait);
  647. INIT_LIST_HEAD(&ctx->active_reqs);
  648. if (percpu_ref_init(&ctx->users, free_ioctx_users, 0, GFP_KERNEL))
  649. goto err;
  650. if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs, 0, GFP_KERNEL))
  651. goto err;
  652. ctx->cpu = alloc_percpu(struct kioctx_cpu);
  653. if (!ctx->cpu)
  654. goto err;
  655. err = aio_setup_ring(ctx, nr_events);
  656. if (err < 0)
  657. goto err;
  658. atomic_set(&ctx->reqs_available, ctx->nr_events - 1);
  659. ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4);
  660. if (ctx->req_batch < 1)
  661. ctx->req_batch = 1;
  662. /* limit the number of system wide aios */
  663. spin_lock(&aio_nr_lock);
  664. if (aio_nr + ctx->max_reqs > aio_max_nr ||
  665. aio_nr + ctx->max_reqs < aio_nr) {
  666. spin_unlock(&aio_nr_lock);
  667. err = -EAGAIN;
  668. goto err_ctx;
  669. }
  670. aio_nr += ctx->max_reqs;
  671. spin_unlock(&aio_nr_lock);
  672. percpu_ref_get(&ctx->users); /* io_setup() will drop this ref */
  673. percpu_ref_get(&ctx->reqs); /* free_ioctx_users() will drop this */
  674. err = ioctx_add_table(ctx, mm);
  675. if (err)
  676. goto err_cleanup;
  677. /* Release the ring_lock mutex now that all setup is complete. */
  678. mutex_unlock(&ctx->ring_lock);
  679. pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
  680. ctx, ctx->user_id, mm, ctx->nr_events);
  681. return ctx;
  682. err_cleanup:
  683. aio_nr_sub(ctx->max_reqs);
  684. err_ctx:
  685. atomic_set(&ctx->dead, 1);
  686. if (ctx->mmap_size)
  687. vm_munmap(ctx->mmap_base, ctx->mmap_size);
  688. aio_free_ring(ctx);
  689. err:
  690. mutex_unlock(&ctx->ring_lock);
  691. free_percpu(ctx->cpu);
  692. percpu_ref_exit(&ctx->reqs);
  693. percpu_ref_exit(&ctx->users);
  694. kmem_cache_free(kioctx_cachep, ctx);
  695. pr_debug("error allocating ioctx %d\n", err);
  696. return ERR_PTR(err);
  697. }
  698. /* kill_ioctx
  699. * Cancels all outstanding aio requests on an aio context. Used
  700. * when the processes owning a context have all exited to encourage
  701. * the rapid destruction of the kioctx.
  702. */
  703. static int kill_ioctx(struct mm_struct *mm, struct kioctx *ctx,
  704. struct ctx_rq_wait *wait)
  705. {
  706. struct kioctx_table *table;
  707. spin_lock(&mm->ioctx_lock);
  708. if (atomic_xchg(&ctx->dead, 1)) {
  709. spin_unlock(&mm->ioctx_lock);
  710. return -EINVAL;
  711. }
  712. table = rcu_dereference_raw(mm->ioctx_table);
  713. WARN_ON(ctx != rcu_access_pointer(table->table[ctx->id]));
  714. RCU_INIT_POINTER(table->table[ctx->id], NULL);
  715. spin_unlock(&mm->ioctx_lock);
  716. /* free_ioctx_reqs() will do the necessary RCU synchronization */
  717. wake_up_all(&ctx->wait);
  718. /*
  719. * It'd be more correct to do this in free_ioctx(), after all
  720. * the outstanding kiocbs have finished - but by then io_destroy
  721. * has already returned, so io_setup() could potentially return
  722. * -EAGAIN with no ioctxs actually in use (as far as userspace
  723. * could tell).
  724. */
  725. aio_nr_sub(ctx->max_reqs);
  726. if (ctx->mmap_size)
  727. vm_munmap(ctx->mmap_base, ctx->mmap_size);
  728. ctx->rq_wait = wait;
  729. percpu_ref_kill(&ctx->users);
  730. return 0;
  731. }
  732. /*
  733. * exit_aio: called when the last user of mm goes away. At this point, there is
  734. * no way for any new requests to be submited or any of the io_* syscalls to be
  735. * called on the context.
  736. *
  737. * There may be outstanding kiocbs, but free_ioctx() will explicitly wait on
  738. * them.
  739. */
  740. void exit_aio(struct mm_struct *mm)
  741. {
  742. struct kioctx_table *table = rcu_dereference_raw(mm->ioctx_table);
  743. struct ctx_rq_wait wait;
  744. int i, skipped;
  745. if (!table)
  746. return;
  747. atomic_set(&wait.count, table->nr);
  748. init_completion(&wait.comp);
  749. skipped = 0;
  750. for (i = 0; i < table->nr; ++i) {
  751. struct kioctx *ctx =
  752. rcu_dereference_protected(table->table[i], true);
  753. if (!ctx) {
  754. skipped++;
  755. continue;
  756. }
  757. /*
  758. * We don't need to bother with munmap() here - exit_mmap(mm)
  759. * is coming and it'll unmap everything. And we simply can't,
  760. * this is not necessarily our ->mm.
  761. * Since kill_ioctx() uses non-zero ->mmap_size as indicator
  762. * that it needs to unmap the area, just set it to 0.
  763. */
  764. ctx->mmap_size = 0;
  765. kill_ioctx(mm, ctx, &wait);
  766. }
  767. if (!atomic_sub_and_test(skipped, &wait.count)) {
  768. /* Wait until all IO for the context are done. */
  769. wait_for_completion(&wait.comp);
  770. }
  771. RCU_INIT_POINTER(mm->ioctx_table, NULL);
  772. kfree(table);
  773. }
  774. static void put_reqs_available(struct kioctx *ctx, unsigned nr)
  775. {
  776. struct kioctx_cpu *kcpu;
  777. unsigned long flags;
  778. local_irq_save(flags);
  779. kcpu = this_cpu_ptr(ctx->cpu);
  780. kcpu->reqs_available += nr;
  781. while (kcpu->reqs_available >= ctx->req_batch * 2) {
  782. kcpu->reqs_available -= ctx->req_batch;
  783. atomic_add(ctx->req_batch, &ctx->reqs_available);
  784. }
  785. local_irq_restore(flags);
  786. }
  787. static bool __get_reqs_available(struct kioctx *ctx)
  788. {
  789. struct kioctx_cpu *kcpu;
  790. bool ret = false;
  791. unsigned long flags;
  792. local_irq_save(flags);
  793. kcpu = this_cpu_ptr(ctx->cpu);
  794. if (!kcpu->reqs_available) {
  795. int avail = atomic_read(&ctx->reqs_available);
  796. do {
  797. if (avail < ctx->req_batch)
  798. goto out;
  799. } while (!atomic_try_cmpxchg(&ctx->reqs_available,
  800. &avail, avail - ctx->req_batch));
  801. kcpu->reqs_available += ctx->req_batch;
  802. }
  803. ret = true;
  804. kcpu->reqs_available--;
  805. out:
  806. local_irq_restore(flags);
  807. return ret;
  808. }
  809. /* refill_reqs_available
  810. * Updates the reqs_available reference counts used for tracking the
  811. * number of free slots in the completion ring. This can be called
  812. * from aio_complete() (to optimistically update reqs_available) or
  813. * from aio_get_req() (the we're out of events case). It must be
  814. * called holding ctx->completion_lock.
  815. */
  816. static void refill_reqs_available(struct kioctx *ctx, unsigned head,
  817. unsigned tail)
  818. {
  819. unsigned events_in_ring, completed;
  820. /* Clamp head since userland can write to it. */
  821. head %= ctx->nr_events;
  822. if (head <= tail)
  823. events_in_ring = tail - head;
  824. else
  825. events_in_ring = ctx->nr_events - (head - tail);
  826. completed = ctx->completed_events;
  827. if (events_in_ring < completed)
  828. completed -= events_in_ring;
  829. else
  830. completed = 0;
  831. if (!completed)
  832. return;
  833. ctx->completed_events -= completed;
  834. put_reqs_available(ctx, completed);
  835. }
  836. /* user_refill_reqs_available
  837. * Called to refill reqs_available when aio_get_req() encounters an
  838. * out of space in the completion ring.
  839. */
  840. static void user_refill_reqs_available(struct kioctx *ctx)
  841. {
  842. spin_lock_irq(&ctx->completion_lock);
  843. if (ctx->completed_events) {
  844. struct aio_ring *ring;
  845. unsigned head;
  846. /* Access of ring->head may race with aio_read_events_ring()
  847. * here, but that's okay since whether we read the old version
  848. * or the new version, and either will be valid. The important
  849. * part is that head cannot pass tail since we prevent
  850. * aio_complete() from updating tail by holding
  851. * ctx->completion_lock. Even if head is invalid, the check
  852. * against ctx->completed_events below will make sure we do the
  853. * safe/right thing.
  854. */
  855. ring = folio_address(ctx->ring_folios[0]);
  856. head = ring->head;
  857. refill_reqs_available(ctx, head, ctx->tail);
  858. }
  859. spin_unlock_irq(&ctx->completion_lock);
  860. }
  861. static bool get_reqs_available(struct kioctx *ctx)
  862. {
  863. if (__get_reqs_available(ctx))
  864. return true;
  865. user_refill_reqs_available(ctx);
  866. return __get_reqs_available(ctx);
  867. }
  868. /* aio_get_req
  869. * Allocate a slot for an aio request.
  870. * Returns NULL if no requests are free.
  871. *
  872. * The refcount is initialized to 2 - one for the async op completion,
  873. * one for the synchronous code that does this.
  874. */
  875. static inline struct aio_kiocb *aio_get_req(struct kioctx *ctx)
  876. {
  877. struct aio_kiocb *req;
  878. req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL);
  879. if (unlikely(!req))
  880. return NULL;
  881. if (unlikely(!get_reqs_available(ctx))) {
  882. kmem_cache_free(kiocb_cachep, req);
  883. return NULL;
  884. }
  885. percpu_ref_get(&ctx->reqs);
  886. req->ki_ctx = ctx;
  887. INIT_LIST_HEAD(&req->ki_list);
  888. refcount_set(&req->ki_refcnt, 2);
  889. req->ki_eventfd = NULL;
  890. return req;
  891. }
  892. static struct kioctx *lookup_ioctx(unsigned long ctx_id)
  893. {
  894. struct aio_ring __user *ring = (void __user *)ctx_id;
  895. struct mm_struct *mm = current->mm;
  896. struct kioctx *ctx, *ret = NULL;
  897. struct kioctx_table *table;
  898. unsigned id;
  899. if (get_user(id, &ring->id))
  900. return NULL;
  901. rcu_read_lock();
  902. table = rcu_dereference(mm->ioctx_table);
  903. if (!table || id >= table->nr)
  904. goto out;
  905. id = array_index_nospec(id, table->nr);
  906. ctx = rcu_dereference(table->table[id]);
  907. if (ctx && ctx->user_id == ctx_id) {
  908. if (percpu_ref_tryget_live(&ctx->users))
  909. ret = ctx;
  910. }
  911. out:
  912. rcu_read_unlock();
  913. return ret;
  914. }
  915. static inline void iocb_destroy(struct aio_kiocb *iocb)
  916. {
  917. if (iocb->ki_eventfd)
  918. eventfd_ctx_put(iocb->ki_eventfd);
  919. if (iocb->ki_filp)
  920. fput(iocb->ki_filp);
  921. percpu_ref_put(&iocb->ki_ctx->reqs);
  922. kmem_cache_free(kiocb_cachep, iocb);
  923. }
  924. struct aio_waiter {
  925. struct wait_queue_entry w;
  926. size_t min_nr;
  927. };
  928. /* aio_complete
  929. * Called when the io request on the given iocb is complete.
  930. */
  931. static void aio_complete(struct aio_kiocb *iocb)
  932. {
  933. struct kioctx *ctx = iocb->ki_ctx;
  934. struct aio_ring *ring;
  935. struct io_event *ev_page, *event;
  936. unsigned tail, pos, head, avail;
  937. unsigned long flags;
  938. /*
  939. * Add a completion event to the ring buffer. Must be done holding
  940. * ctx->completion_lock to prevent other code from messing with the tail
  941. * pointer since we might be called from irq context.
  942. */
  943. spin_lock_irqsave(&ctx->completion_lock, flags);
  944. tail = ctx->tail;
  945. pos = tail + AIO_EVENTS_OFFSET;
  946. if (++tail >= ctx->nr_events)
  947. tail = 0;
  948. ev_page = folio_address(ctx->ring_folios[pos / AIO_EVENTS_PER_PAGE]);
  949. event = ev_page + pos % AIO_EVENTS_PER_PAGE;
  950. *event = iocb->ki_res;
  951. flush_dcache_folio(ctx->ring_folios[pos / AIO_EVENTS_PER_PAGE]);
  952. pr_debug("%p[%u]: %p: %p %Lx %Lx %Lx\n", ctx, tail, iocb,
  953. (void __user *)(unsigned long)iocb->ki_res.obj,
  954. iocb->ki_res.data, iocb->ki_res.res, iocb->ki_res.res2);
  955. /* after flagging the request as done, we
  956. * must never even look at it again
  957. */
  958. smp_wmb(); /* make event visible before updating tail */
  959. ctx->tail = tail;
  960. ring = folio_address(ctx->ring_folios[0]);
  961. head = ring->head;
  962. ring->tail = tail;
  963. flush_dcache_folio(ctx->ring_folios[0]);
  964. ctx->completed_events++;
  965. if (ctx->completed_events > 1)
  966. refill_reqs_available(ctx, head, tail);
  967. avail = tail > head
  968. ? tail - head
  969. : tail + ctx->nr_events - head;
  970. spin_unlock_irqrestore(&ctx->completion_lock, flags);
  971. pr_debug("added to ring %p at [%u]\n", iocb, tail);
  972. /*
  973. * Check if the user asked us to deliver the result through an
  974. * eventfd. The eventfd_signal() function is safe to be called
  975. * from IRQ context.
  976. */
  977. if (iocb->ki_eventfd)
  978. eventfd_signal(iocb->ki_eventfd);
  979. /*
  980. * We have to order our ring_info tail store above and test
  981. * of the wait list below outside the wait lock. This is
  982. * like in wake_up_bit() where clearing a bit has to be
  983. * ordered with the unlocked test.
  984. */
  985. smp_mb();
  986. if (waitqueue_active(&ctx->wait)) {
  987. struct aio_waiter *curr, *next;
  988. unsigned long flags;
  989. spin_lock_irqsave(&ctx->wait.lock, flags);
  990. list_for_each_entry_safe(curr, next, &ctx->wait.head, w.entry)
  991. if (avail >= curr->min_nr) {
  992. wake_up_process(curr->w.private);
  993. list_del_init_careful(&curr->w.entry);
  994. }
  995. spin_unlock_irqrestore(&ctx->wait.lock, flags);
  996. }
  997. }
  998. static inline void iocb_put(struct aio_kiocb *iocb)
  999. {
  1000. if (refcount_dec_and_test(&iocb->ki_refcnt)) {
  1001. aio_complete(iocb);
  1002. iocb_destroy(iocb);
  1003. }
  1004. }
  1005. /* aio_read_events_ring
  1006. * Pull an event off of the ioctx's event ring. Returns the number of
  1007. * events fetched
  1008. */
  1009. static long aio_read_events_ring(struct kioctx *ctx,
  1010. struct io_event __user *event, long nr)
  1011. {
  1012. struct aio_ring *ring;
  1013. unsigned head, tail, pos;
  1014. long ret = 0;
  1015. int copy_ret;
  1016. /*
  1017. * The mutex can block and wake us up and that will cause
  1018. * wait_event_interruptible_hrtimeout() to schedule without sleeping
  1019. * and repeat. This should be rare enough that it doesn't cause
  1020. * peformance issues. See the comment in read_events() for more detail.
  1021. */
  1022. sched_annotate_sleep();
  1023. mutex_lock(&ctx->ring_lock);
  1024. /* Access to ->ring_folios here is protected by ctx->ring_lock. */
  1025. ring = folio_address(ctx->ring_folios[0]);
  1026. head = ring->head;
  1027. tail = ring->tail;
  1028. /*
  1029. * Ensure that once we've read the current tail pointer, that
  1030. * we also see the events that were stored up to the tail.
  1031. */
  1032. smp_rmb();
  1033. pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
  1034. if (head == tail)
  1035. goto out;
  1036. head %= ctx->nr_events;
  1037. tail %= ctx->nr_events;
  1038. while (ret < nr) {
  1039. long avail;
  1040. struct io_event *ev;
  1041. struct folio *folio;
  1042. avail = (head <= tail ? tail : ctx->nr_events) - head;
  1043. if (head == tail)
  1044. break;
  1045. pos = head + AIO_EVENTS_OFFSET;
  1046. folio = ctx->ring_folios[pos / AIO_EVENTS_PER_PAGE];
  1047. pos %= AIO_EVENTS_PER_PAGE;
  1048. avail = min(avail, nr - ret);
  1049. avail = min_t(long, avail, AIO_EVENTS_PER_PAGE - pos);
  1050. ev = folio_address(folio);
  1051. copy_ret = copy_to_user(event + ret, ev + pos,
  1052. sizeof(*ev) * avail);
  1053. if (unlikely(copy_ret)) {
  1054. ret = -EFAULT;
  1055. goto out;
  1056. }
  1057. ret += avail;
  1058. head += avail;
  1059. head %= ctx->nr_events;
  1060. }
  1061. ring = folio_address(ctx->ring_folios[0]);
  1062. ring->head = head;
  1063. flush_dcache_folio(ctx->ring_folios[0]);
  1064. pr_debug("%li h%u t%u\n", ret, head, tail);
  1065. out:
  1066. mutex_unlock(&ctx->ring_lock);
  1067. return ret;
  1068. }
  1069. static bool aio_read_events(struct kioctx *ctx, long min_nr, long nr,
  1070. struct io_event __user *event, long *i)
  1071. {
  1072. long ret = aio_read_events_ring(ctx, event + *i, nr - *i);
  1073. if (ret > 0)
  1074. *i += ret;
  1075. if (unlikely(atomic_read(&ctx->dead)))
  1076. ret = -EINVAL;
  1077. if (!*i)
  1078. *i = ret;
  1079. return ret < 0 || *i >= min_nr;
  1080. }
  1081. static long read_events(struct kioctx *ctx, long min_nr, long nr,
  1082. struct io_event __user *event,
  1083. ktime_t until)
  1084. {
  1085. struct hrtimer_sleeper t;
  1086. struct aio_waiter w;
  1087. long ret = 0, ret2 = 0;
  1088. /*
  1089. * Note that aio_read_events() is being called as the conditional - i.e.
  1090. * we're calling it after prepare_to_wait() has set task state to
  1091. * TASK_INTERRUPTIBLE.
  1092. *
  1093. * But aio_read_events() can block, and if it blocks it's going to flip
  1094. * the task state back to TASK_RUNNING.
  1095. *
  1096. * This should be ok, provided it doesn't flip the state back to
  1097. * TASK_RUNNING and return 0 too much - that causes us to spin. That
  1098. * will only happen if the mutex_lock() call blocks, and we then find
  1099. * the ringbuffer empty. So in practice we should be ok, but it's
  1100. * something to be aware of when touching this code.
  1101. */
  1102. aio_read_events(ctx, min_nr, nr, event, &ret);
  1103. if (until == 0 || ret < 0 || ret >= min_nr)
  1104. return ret;
  1105. hrtimer_init_sleeper_on_stack(&t, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  1106. if (until != KTIME_MAX) {
  1107. hrtimer_set_expires_range_ns(&t.timer, until, current->timer_slack_ns);
  1108. hrtimer_sleeper_start_expires(&t, HRTIMER_MODE_REL);
  1109. }
  1110. init_wait(&w.w);
  1111. while (1) {
  1112. unsigned long nr_got = ret;
  1113. w.min_nr = min_nr - ret;
  1114. ret2 = prepare_to_wait_event(&ctx->wait, &w.w, TASK_INTERRUPTIBLE);
  1115. if (!ret2 && !t.task)
  1116. ret2 = -ETIME;
  1117. if (aio_read_events(ctx, min_nr, nr, event, &ret) || ret2)
  1118. break;
  1119. if (nr_got == ret)
  1120. schedule();
  1121. }
  1122. finish_wait(&ctx->wait, &w.w);
  1123. hrtimer_cancel(&t.timer);
  1124. destroy_hrtimer_on_stack(&t.timer);
  1125. return ret;
  1126. }
  1127. /* sys_io_setup:
  1128. * Create an aio_context capable of receiving at least nr_events.
  1129. * ctxp must not point to an aio_context that already exists, and
  1130. * must be initialized to 0 prior to the call. On successful
  1131. * creation of the aio_context, *ctxp is filled in with the resulting
  1132. * handle. May fail with -EINVAL if *ctxp is not initialized,
  1133. * if the specified nr_events exceeds internal limits. May fail
  1134. * with -EAGAIN if the specified nr_events exceeds the user's limit
  1135. * of available events. May fail with -ENOMEM if insufficient kernel
  1136. * resources are available. May fail with -EFAULT if an invalid
  1137. * pointer is passed for ctxp. Will fail with -ENOSYS if not
  1138. * implemented.
  1139. */
  1140. SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
  1141. {
  1142. struct kioctx *ioctx = NULL;
  1143. unsigned long ctx;
  1144. long ret;
  1145. ret = get_user(ctx, ctxp);
  1146. if (unlikely(ret))
  1147. goto out;
  1148. ret = -EINVAL;
  1149. if (unlikely(ctx || nr_events == 0)) {
  1150. pr_debug("EINVAL: ctx %lu nr_events %u\n",
  1151. ctx, nr_events);
  1152. goto out;
  1153. }
  1154. ioctx = ioctx_alloc(nr_events);
  1155. ret = PTR_ERR(ioctx);
  1156. if (!IS_ERR(ioctx)) {
  1157. ret = put_user(ioctx->user_id, ctxp);
  1158. if (ret)
  1159. kill_ioctx(current->mm, ioctx, NULL);
  1160. percpu_ref_put(&ioctx->users);
  1161. }
  1162. out:
  1163. return ret;
  1164. }
  1165. #ifdef CONFIG_COMPAT
  1166. COMPAT_SYSCALL_DEFINE2(io_setup, unsigned, nr_events, u32 __user *, ctx32p)
  1167. {
  1168. struct kioctx *ioctx = NULL;
  1169. unsigned long ctx;
  1170. long ret;
  1171. ret = get_user(ctx, ctx32p);
  1172. if (unlikely(ret))
  1173. goto out;
  1174. ret = -EINVAL;
  1175. if (unlikely(ctx || nr_events == 0)) {
  1176. pr_debug("EINVAL: ctx %lu nr_events %u\n",
  1177. ctx, nr_events);
  1178. goto out;
  1179. }
  1180. ioctx = ioctx_alloc(nr_events);
  1181. ret = PTR_ERR(ioctx);
  1182. if (!IS_ERR(ioctx)) {
  1183. /* truncating is ok because it's a user address */
  1184. ret = put_user((u32)ioctx->user_id, ctx32p);
  1185. if (ret)
  1186. kill_ioctx(current->mm, ioctx, NULL);
  1187. percpu_ref_put(&ioctx->users);
  1188. }
  1189. out:
  1190. return ret;
  1191. }
  1192. #endif
  1193. /* sys_io_destroy:
  1194. * Destroy the aio_context specified. May cancel any outstanding
  1195. * AIOs and block on completion. Will fail with -ENOSYS if not
  1196. * implemented. May fail with -EINVAL if the context pointed to
  1197. * is invalid.
  1198. */
  1199. SYSCALL_DEFINE1(io_destroy, aio_context_t, ctx)
  1200. {
  1201. struct kioctx *ioctx = lookup_ioctx(ctx);
  1202. if (likely(NULL != ioctx)) {
  1203. struct ctx_rq_wait wait;
  1204. int ret;
  1205. init_completion(&wait.comp);
  1206. atomic_set(&wait.count, 1);
  1207. /* Pass requests_done to kill_ioctx() where it can be set
  1208. * in a thread-safe way. If we try to set it here then we have
  1209. * a race condition if two io_destroy() called simultaneously.
  1210. */
  1211. ret = kill_ioctx(current->mm, ioctx, &wait);
  1212. percpu_ref_put(&ioctx->users);
  1213. /* Wait until all IO for the context are done. Otherwise kernel
  1214. * keep using user-space buffers even if user thinks the context
  1215. * is destroyed.
  1216. */
  1217. if (!ret)
  1218. wait_for_completion(&wait.comp);
  1219. return ret;
  1220. }
  1221. pr_debug("EINVAL: invalid context id\n");
  1222. return -EINVAL;
  1223. }
  1224. static void aio_remove_iocb(struct aio_kiocb *iocb)
  1225. {
  1226. struct kioctx *ctx = iocb->ki_ctx;
  1227. unsigned long flags;
  1228. spin_lock_irqsave(&ctx->ctx_lock, flags);
  1229. list_del(&iocb->ki_list);
  1230. spin_unlock_irqrestore(&ctx->ctx_lock, flags);
  1231. }
  1232. static void aio_complete_rw(struct kiocb *kiocb, long res)
  1233. {
  1234. struct aio_kiocb *iocb = container_of(kiocb, struct aio_kiocb, rw);
  1235. if (!list_empty_careful(&iocb->ki_list))
  1236. aio_remove_iocb(iocb);
  1237. if (kiocb->ki_flags & IOCB_WRITE) {
  1238. struct inode *inode = file_inode(kiocb->ki_filp);
  1239. if (S_ISREG(inode->i_mode))
  1240. kiocb_end_write(kiocb);
  1241. }
  1242. iocb->ki_res.res = res;
  1243. iocb->ki_res.res2 = 0;
  1244. iocb_put(iocb);
  1245. }
  1246. static int aio_prep_rw(struct kiocb *req, const struct iocb *iocb, int rw_type)
  1247. {
  1248. int ret;
  1249. req->ki_complete = aio_complete_rw;
  1250. req->private = NULL;
  1251. req->ki_pos = iocb->aio_offset;
  1252. req->ki_flags = req->ki_filp->f_iocb_flags | IOCB_AIO_RW;
  1253. if (iocb->aio_flags & IOCB_FLAG_RESFD)
  1254. req->ki_flags |= IOCB_EVENTFD;
  1255. if (iocb->aio_flags & IOCB_FLAG_IOPRIO) {
  1256. /*
  1257. * If the IOCB_FLAG_IOPRIO flag of aio_flags is set, then
  1258. * aio_reqprio is interpreted as an I/O scheduling
  1259. * class and priority.
  1260. */
  1261. ret = ioprio_check_cap(iocb->aio_reqprio);
  1262. if (ret) {
  1263. pr_debug("aio ioprio check cap error: %d\n", ret);
  1264. return ret;
  1265. }
  1266. req->ki_ioprio = iocb->aio_reqprio;
  1267. } else
  1268. req->ki_ioprio = get_current_ioprio();
  1269. ret = kiocb_set_rw_flags(req, iocb->aio_rw_flags, rw_type);
  1270. if (unlikely(ret))
  1271. return ret;
  1272. req->ki_flags &= ~IOCB_HIPRI; /* no one is going to poll for this I/O */
  1273. return 0;
  1274. }
  1275. static ssize_t aio_setup_rw(int rw, const struct iocb *iocb,
  1276. struct iovec **iovec, bool vectored, bool compat,
  1277. struct iov_iter *iter)
  1278. {
  1279. void __user *buf = (void __user *)(uintptr_t)iocb->aio_buf;
  1280. size_t len = iocb->aio_nbytes;
  1281. if (!vectored) {
  1282. ssize_t ret = import_ubuf(rw, buf, len, iter);
  1283. *iovec = NULL;
  1284. return ret;
  1285. }
  1286. return __import_iovec(rw, buf, len, UIO_FASTIOV, iovec, iter, compat);
  1287. }
  1288. static inline void aio_rw_done(struct kiocb *req, ssize_t ret)
  1289. {
  1290. switch (ret) {
  1291. case -EIOCBQUEUED:
  1292. break;
  1293. case -ERESTARTSYS:
  1294. case -ERESTARTNOINTR:
  1295. case -ERESTARTNOHAND:
  1296. case -ERESTART_RESTARTBLOCK:
  1297. /*
  1298. * There's no easy way to restart the syscall since other AIO's
  1299. * may be already running. Just fail this IO with EINTR.
  1300. */
  1301. ret = -EINTR;
  1302. fallthrough;
  1303. default:
  1304. req->ki_complete(req, ret);
  1305. }
  1306. }
  1307. static int aio_read(struct kiocb *req, const struct iocb *iocb,
  1308. bool vectored, bool compat)
  1309. {
  1310. struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
  1311. struct iov_iter iter;
  1312. struct file *file;
  1313. int ret;
  1314. ret = aio_prep_rw(req, iocb, READ);
  1315. if (ret)
  1316. return ret;
  1317. file = req->ki_filp;
  1318. if (unlikely(!(file->f_mode & FMODE_READ)))
  1319. return -EBADF;
  1320. if (unlikely(!file->f_op->read_iter))
  1321. return -EINVAL;
  1322. ret = aio_setup_rw(ITER_DEST, iocb, &iovec, vectored, compat, &iter);
  1323. if (ret < 0)
  1324. return ret;
  1325. ret = rw_verify_area(READ, file, &req->ki_pos, iov_iter_count(&iter));
  1326. if (!ret)
  1327. aio_rw_done(req, file->f_op->read_iter(req, &iter));
  1328. kfree(iovec);
  1329. return ret;
  1330. }
  1331. static int aio_write(struct kiocb *req, const struct iocb *iocb,
  1332. bool vectored, bool compat)
  1333. {
  1334. struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
  1335. struct iov_iter iter;
  1336. struct file *file;
  1337. int ret;
  1338. ret = aio_prep_rw(req, iocb, WRITE);
  1339. if (ret)
  1340. return ret;
  1341. file = req->ki_filp;
  1342. if (unlikely(!(file->f_mode & FMODE_WRITE)))
  1343. return -EBADF;
  1344. if (unlikely(!file->f_op->write_iter))
  1345. return -EINVAL;
  1346. ret = aio_setup_rw(ITER_SOURCE, iocb, &iovec, vectored, compat, &iter);
  1347. if (ret < 0)
  1348. return ret;
  1349. ret = rw_verify_area(WRITE, file, &req->ki_pos, iov_iter_count(&iter));
  1350. if (!ret) {
  1351. if (S_ISREG(file_inode(file)->i_mode))
  1352. kiocb_start_write(req);
  1353. req->ki_flags |= IOCB_WRITE;
  1354. aio_rw_done(req, file->f_op->write_iter(req, &iter));
  1355. }
  1356. kfree(iovec);
  1357. return ret;
  1358. }
  1359. static void aio_fsync_work(struct work_struct *work)
  1360. {
  1361. struct aio_kiocb *iocb = container_of(work, struct aio_kiocb, fsync.work);
  1362. const struct cred *old_cred = override_creds(iocb->fsync.creds);
  1363. iocb->ki_res.res = vfs_fsync(iocb->fsync.file, iocb->fsync.datasync);
  1364. revert_creds(old_cred);
  1365. put_cred(iocb->fsync.creds);
  1366. iocb_put(iocb);
  1367. }
  1368. static int aio_fsync(struct fsync_iocb *req, const struct iocb *iocb,
  1369. bool datasync)
  1370. {
  1371. if (unlikely(iocb->aio_buf || iocb->aio_offset || iocb->aio_nbytes ||
  1372. iocb->aio_rw_flags))
  1373. return -EINVAL;
  1374. if (unlikely(!req->file->f_op->fsync))
  1375. return -EINVAL;
  1376. req->creds = prepare_creds();
  1377. if (!req->creds)
  1378. return -ENOMEM;
  1379. req->datasync = datasync;
  1380. INIT_WORK(&req->work, aio_fsync_work);
  1381. schedule_work(&req->work);
  1382. return 0;
  1383. }
  1384. static void aio_poll_put_work(struct work_struct *work)
  1385. {
  1386. struct poll_iocb *req = container_of(work, struct poll_iocb, work);
  1387. struct aio_kiocb *iocb = container_of(req, struct aio_kiocb, poll);
  1388. iocb_put(iocb);
  1389. }
  1390. /*
  1391. * Safely lock the waitqueue which the request is on, synchronizing with the
  1392. * case where the ->poll() provider decides to free its waitqueue early.
  1393. *
  1394. * Returns true on success, meaning that req->head->lock was locked, req->wait
  1395. * is on req->head, and an RCU read lock was taken. Returns false if the
  1396. * request was already removed from its waitqueue (which might no longer exist).
  1397. */
  1398. static bool poll_iocb_lock_wq(struct poll_iocb *req)
  1399. {
  1400. wait_queue_head_t *head;
  1401. /*
  1402. * While we hold the waitqueue lock and the waitqueue is nonempty,
  1403. * wake_up_pollfree() will wait for us. However, taking the waitqueue
  1404. * lock in the first place can race with the waitqueue being freed.
  1405. *
  1406. * We solve this as eventpoll does: by taking advantage of the fact that
  1407. * all users of wake_up_pollfree() will RCU-delay the actual free. If
  1408. * we enter rcu_read_lock() and see that the pointer to the queue is
  1409. * non-NULL, we can then lock it without the memory being freed out from
  1410. * under us, then check whether the request is still on the queue.
  1411. *
  1412. * Keep holding rcu_read_lock() as long as we hold the queue lock, in
  1413. * case the caller deletes the entry from the queue, leaving it empty.
  1414. * In that case, only RCU prevents the queue memory from being freed.
  1415. */
  1416. rcu_read_lock();
  1417. head = smp_load_acquire(&req->head);
  1418. if (head) {
  1419. spin_lock(&head->lock);
  1420. if (!list_empty(&req->wait.entry))
  1421. return true;
  1422. spin_unlock(&head->lock);
  1423. }
  1424. rcu_read_unlock();
  1425. return false;
  1426. }
  1427. static void poll_iocb_unlock_wq(struct poll_iocb *req)
  1428. {
  1429. spin_unlock(&req->head->lock);
  1430. rcu_read_unlock();
  1431. }
  1432. static void aio_poll_complete_work(struct work_struct *work)
  1433. {
  1434. struct poll_iocb *req = container_of(work, struct poll_iocb, work);
  1435. struct aio_kiocb *iocb = container_of(req, struct aio_kiocb, poll);
  1436. struct poll_table_struct pt = { ._key = req->events };
  1437. struct kioctx *ctx = iocb->ki_ctx;
  1438. __poll_t mask = 0;
  1439. if (!READ_ONCE(req->cancelled))
  1440. mask = vfs_poll(req->file, &pt) & req->events;
  1441. /*
  1442. * Note that ->ki_cancel callers also delete iocb from active_reqs after
  1443. * calling ->ki_cancel. We need the ctx_lock roundtrip here to
  1444. * synchronize with them. In the cancellation case the list_del_init
  1445. * itself is not actually needed, but harmless so we keep it in to
  1446. * avoid further branches in the fast path.
  1447. */
  1448. spin_lock_irq(&ctx->ctx_lock);
  1449. if (poll_iocb_lock_wq(req)) {
  1450. if (!mask && !READ_ONCE(req->cancelled)) {
  1451. /*
  1452. * The request isn't actually ready to be completed yet.
  1453. * Reschedule completion if another wakeup came in.
  1454. */
  1455. if (req->work_need_resched) {
  1456. schedule_work(&req->work);
  1457. req->work_need_resched = false;
  1458. } else {
  1459. req->work_scheduled = false;
  1460. }
  1461. poll_iocb_unlock_wq(req);
  1462. spin_unlock_irq(&ctx->ctx_lock);
  1463. return;
  1464. }
  1465. list_del_init(&req->wait.entry);
  1466. poll_iocb_unlock_wq(req);
  1467. } /* else, POLLFREE has freed the waitqueue, so we must complete */
  1468. list_del_init(&iocb->ki_list);
  1469. iocb->ki_res.res = mangle_poll(mask);
  1470. spin_unlock_irq(&ctx->ctx_lock);
  1471. iocb_put(iocb);
  1472. }
  1473. /* assumes we are called with irqs disabled */
  1474. static int aio_poll_cancel(struct kiocb *iocb)
  1475. {
  1476. struct aio_kiocb *aiocb = container_of(iocb, struct aio_kiocb, rw);
  1477. struct poll_iocb *req = &aiocb->poll;
  1478. if (poll_iocb_lock_wq(req)) {
  1479. WRITE_ONCE(req->cancelled, true);
  1480. if (!req->work_scheduled) {
  1481. schedule_work(&aiocb->poll.work);
  1482. req->work_scheduled = true;
  1483. }
  1484. poll_iocb_unlock_wq(req);
  1485. } /* else, the request was force-cancelled by POLLFREE already */
  1486. return 0;
  1487. }
  1488. static int aio_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
  1489. void *key)
  1490. {
  1491. struct poll_iocb *req = container_of(wait, struct poll_iocb, wait);
  1492. struct aio_kiocb *iocb = container_of(req, struct aio_kiocb, poll);
  1493. __poll_t mask = key_to_poll(key);
  1494. unsigned long flags;
  1495. /* for instances that support it check for an event match first: */
  1496. if (mask && !(mask & req->events))
  1497. return 0;
  1498. /*
  1499. * Complete the request inline if possible. This requires that three
  1500. * conditions be met:
  1501. * 1. An event mask must have been passed. If a plain wakeup was done
  1502. * instead, then mask == 0 and we have to call vfs_poll() to get
  1503. * the events, so inline completion isn't possible.
  1504. * 2. The completion work must not have already been scheduled.
  1505. * 3. ctx_lock must not be busy. We have to use trylock because we
  1506. * already hold the waitqueue lock, so this inverts the normal
  1507. * locking order. Use irqsave/irqrestore because not all
  1508. * filesystems (e.g. fuse) call this function with IRQs disabled,
  1509. * yet IRQs have to be disabled before ctx_lock is obtained.
  1510. */
  1511. if (mask && !req->work_scheduled &&
  1512. spin_trylock_irqsave(&iocb->ki_ctx->ctx_lock, flags)) {
  1513. struct kioctx *ctx = iocb->ki_ctx;
  1514. list_del_init(&req->wait.entry);
  1515. list_del(&iocb->ki_list);
  1516. iocb->ki_res.res = mangle_poll(mask);
  1517. if (iocb->ki_eventfd && !eventfd_signal_allowed()) {
  1518. iocb = NULL;
  1519. INIT_WORK(&req->work, aio_poll_put_work);
  1520. schedule_work(&req->work);
  1521. }
  1522. spin_unlock_irqrestore(&ctx->ctx_lock, flags);
  1523. if (iocb)
  1524. iocb_put(iocb);
  1525. } else {
  1526. /*
  1527. * Schedule the completion work if needed. If it was already
  1528. * scheduled, record that another wakeup came in.
  1529. *
  1530. * Don't remove the request from the waitqueue here, as it might
  1531. * not actually be complete yet (we won't know until vfs_poll()
  1532. * is called), and we must not miss any wakeups. POLLFREE is an
  1533. * exception to this; see below.
  1534. */
  1535. if (req->work_scheduled) {
  1536. req->work_need_resched = true;
  1537. } else {
  1538. schedule_work(&req->work);
  1539. req->work_scheduled = true;
  1540. }
  1541. /*
  1542. * If the waitqueue is being freed early but we can't complete
  1543. * the request inline, we have to tear down the request as best
  1544. * we can. That means immediately removing the request from its
  1545. * waitqueue and preventing all further accesses to the
  1546. * waitqueue via the request. We also need to schedule the
  1547. * completion work (done above). Also mark the request as
  1548. * cancelled, to potentially skip an unneeded call to ->poll().
  1549. */
  1550. if (mask & POLLFREE) {
  1551. WRITE_ONCE(req->cancelled, true);
  1552. list_del_init(&req->wait.entry);
  1553. /*
  1554. * Careful: this *must* be the last step, since as soon
  1555. * as req->head is NULL'ed out, the request can be
  1556. * completed and freed, since aio_poll_complete_work()
  1557. * will no longer need to take the waitqueue lock.
  1558. */
  1559. smp_store_release(&req->head, NULL);
  1560. }
  1561. }
  1562. return 1;
  1563. }
  1564. struct aio_poll_table {
  1565. struct poll_table_struct pt;
  1566. struct aio_kiocb *iocb;
  1567. bool queued;
  1568. int error;
  1569. };
  1570. static void
  1571. aio_poll_queue_proc(struct file *file, struct wait_queue_head *head,
  1572. struct poll_table_struct *p)
  1573. {
  1574. struct aio_poll_table *pt = container_of(p, struct aio_poll_table, pt);
  1575. /* multiple wait queues per file are not supported */
  1576. if (unlikely(pt->queued)) {
  1577. pt->error = -EINVAL;
  1578. return;
  1579. }
  1580. pt->queued = true;
  1581. pt->error = 0;
  1582. pt->iocb->poll.head = head;
  1583. add_wait_queue(head, &pt->iocb->poll.wait);
  1584. }
  1585. static int aio_poll(struct aio_kiocb *aiocb, const struct iocb *iocb)
  1586. {
  1587. struct kioctx *ctx = aiocb->ki_ctx;
  1588. struct poll_iocb *req = &aiocb->poll;
  1589. struct aio_poll_table apt;
  1590. bool cancel = false;
  1591. __poll_t mask;
  1592. /* reject any unknown events outside the normal event mask. */
  1593. if ((u16)iocb->aio_buf != iocb->aio_buf)
  1594. return -EINVAL;
  1595. /* reject fields that are not defined for poll */
  1596. if (iocb->aio_offset || iocb->aio_nbytes || iocb->aio_rw_flags)
  1597. return -EINVAL;
  1598. INIT_WORK(&req->work, aio_poll_complete_work);
  1599. req->events = demangle_poll(iocb->aio_buf) | EPOLLERR | EPOLLHUP;
  1600. req->head = NULL;
  1601. req->cancelled = false;
  1602. req->work_scheduled = false;
  1603. req->work_need_resched = false;
  1604. apt.pt._qproc = aio_poll_queue_proc;
  1605. apt.pt._key = req->events;
  1606. apt.iocb = aiocb;
  1607. apt.queued = false;
  1608. apt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
  1609. /* initialized the list so that we can do list_empty checks */
  1610. INIT_LIST_HEAD(&req->wait.entry);
  1611. init_waitqueue_func_entry(&req->wait, aio_poll_wake);
  1612. mask = vfs_poll(req->file, &apt.pt) & req->events;
  1613. spin_lock_irq(&ctx->ctx_lock);
  1614. if (likely(apt.queued)) {
  1615. bool on_queue = poll_iocb_lock_wq(req);
  1616. if (!on_queue || req->work_scheduled) {
  1617. /*
  1618. * aio_poll_wake() already either scheduled the async
  1619. * completion work, or completed the request inline.
  1620. */
  1621. if (apt.error) /* unsupported case: multiple queues */
  1622. cancel = true;
  1623. apt.error = 0;
  1624. mask = 0;
  1625. }
  1626. if (mask || apt.error) {
  1627. /* Steal to complete synchronously. */
  1628. list_del_init(&req->wait.entry);
  1629. } else if (cancel) {
  1630. /* Cancel if possible (may be too late though). */
  1631. WRITE_ONCE(req->cancelled, true);
  1632. } else if (on_queue) {
  1633. /*
  1634. * Actually waiting for an event, so add the request to
  1635. * active_reqs so that it can be cancelled if needed.
  1636. */
  1637. list_add_tail(&aiocb->ki_list, &ctx->active_reqs);
  1638. aiocb->ki_cancel = aio_poll_cancel;
  1639. }
  1640. if (on_queue)
  1641. poll_iocb_unlock_wq(req);
  1642. }
  1643. if (mask) { /* no async, we'd stolen it */
  1644. aiocb->ki_res.res = mangle_poll(mask);
  1645. apt.error = 0;
  1646. }
  1647. spin_unlock_irq(&ctx->ctx_lock);
  1648. if (mask)
  1649. iocb_put(aiocb);
  1650. return apt.error;
  1651. }
  1652. static int __io_submit_one(struct kioctx *ctx, const struct iocb *iocb,
  1653. struct iocb __user *user_iocb, struct aio_kiocb *req,
  1654. bool compat)
  1655. {
  1656. req->ki_filp = fget(iocb->aio_fildes);
  1657. if (unlikely(!req->ki_filp))
  1658. return -EBADF;
  1659. if (iocb->aio_flags & IOCB_FLAG_RESFD) {
  1660. struct eventfd_ctx *eventfd;
  1661. /*
  1662. * If the IOCB_FLAG_RESFD flag of aio_flags is set, get an
  1663. * instance of the file* now. The file descriptor must be
  1664. * an eventfd() fd, and will be signaled for each completed
  1665. * event using the eventfd_signal() function.
  1666. */
  1667. eventfd = eventfd_ctx_fdget(iocb->aio_resfd);
  1668. if (IS_ERR(eventfd))
  1669. return PTR_ERR(eventfd);
  1670. req->ki_eventfd = eventfd;
  1671. }
  1672. if (unlikely(put_user(KIOCB_KEY, &user_iocb->aio_key))) {
  1673. pr_debug("EFAULT: aio_key\n");
  1674. return -EFAULT;
  1675. }
  1676. req->ki_res.obj = (u64)(unsigned long)user_iocb;
  1677. req->ki_res.data = iocb->aio_data;
  1678. req->ki_res.res = 0;
  1679. req->ki_res.res2 = 0;
  1680. switch (iocb->aio_lio_opcode) {
  1681. case IOCB_CMD_PREAD:
  1682. return aio_read(&req->rw, iocb, false, compat);
  1683. case IOCB_CMD_PWRITE:
  1684. return aio_write(&req->rw, iocb, false, compat);
  1685. case IOCB_CMD_PREADV:
  1686. return aio_read(&req->rw, iocb, true, compat);
  1687. case IOCB_CMD_PWRITEV:
  1688. return aio_write(&req->rw, iocb, true, compat);
  1689. case IOCB_CMD_FSYNC:
  1690. return aio_fsync(&req->fsync, iocb, false);
  1691. case IOCB_CMD_FDSYNC:
  1692. return aio_fsync(&req->fsync, iocb, true);
  1693. case IOCB_CMD_POLL:
  1694. return aio_poll(req, iocb);
  1695. default:
  1696. pr_debug("invalid aio operation %d\n", iocb->aio_lio_opcode);
  1697. return -EINVAL;
  1698. }
  1699. }
  1700. static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
  1701. bool compat)
  1702. {
  1703. struct aio_kiocb *req;
  1704. struct iocb iocb;
  1705. int err;
  1706. if (unlikely(copy_from_user(&iocb, user_iocb, sizeof(iocb))))
  1707. return -EFAULT;
  1708. /* enforce forwards compatibility on users */
  1709. if (unlikely(iocb.aio_reserved2)) {
  1710. pr_debug("EINVAL: reserve field set\n");
  1711. return -EINVAL;
  1712. }
  1713. /* prevent overflows */
  1714. if (unlikely(
  1715. (iocb.aio_buf != (unsigned long)iocb.aio_buf) ||
  1716. (iocb.aio_nbytes != (size_t)iocb.aio_nbytes) ||
  1717. ((ssize_t)iocb.aio_nbytes < 0)
  1718. )) {
  1719. pr_debug("EINVAL: overflow check\n");
  1720. return -EINVAL;
  1721. }
  1722. req = aio_get_req(ctx);
  1723. if (unlikely(!req))
  1724. return -EAGAIN;
  1725. err = __io_submit_one(ctx, &iocb, user_iocb, req, compat);
  1726. /* Done with the synchronous reference */
  1727. iocb_put(req);
  1728. /*
  1729. * If err is 0, we'd either done aio_complete() ourselves or have
  1730. * arranged for that to be done asynchronously. Anything non-zero
  1731. * means that we need to destroy req ourselves.
  1732. */
  1733. if (unlikely(err)) {
  1734. iocb_destroy(req);
  1735. put_reqs_available(ctx, 1);
  1736. }
  1737. return err;
  1738. }
  1739. /* sys_io_submit:
  1740. * Queue the nr iocbs pointed to by iocbpp for processing. Returns
  1741. * the number of iocbs queued. May return -EINVAL if the aio_context
  1742. * specified by ctx_id is invalid, if nr is < 0, if the iocb at
  1743. * *iocbpp[0] is not properly initialized, if the operation specified
  1744. * is invalid for the file descriptor in the iocb. May fail with
  1745. * -EFAULT if any of the data structures point to invalid data. May
  1746. * fail with -EBADF if the file descriptor specified in the first
  1747. * iocb is invalid. May fail with -EAGAIN if insufficient resources
  1748. * are available to queue any iocbs. Will return 0 if nr is 0. Will
  1749. * fail with -ENOSYS if not implemented.
  1750. */
  1751. SYSCALL_DEFINE3(io_submit, aio_context_t, ctx_id, long, nr,
  1752. struct iocb __user * __user *, iocbpp)
  1753. {
  1754. struct kioctx *ctx;
  1755. long ret = 0;
  1756. int i = 0;
  1757. struct blk_plug plug;
  1758. if (unlikely(nr < 0))
  1759. return -EINVAL;
  1760. ctx = lookup_ioctx(ctx_id);
  1761. if (unlikely(!ctx)) {
  1762. pr_debug("EINVAL: invalid context id\n");
  1763. return -EINVAL;
  1764. }
  1765. if (nr > ctx->nr_events)
  1766. nr = ctx->nr_events;
  1767. if (nr > AIO_PLUG_THRESHOLD)
  1768. blk_start_plug(&plug);
  1769. for (i = 0; i < nr; i++) {
  1770. struct iocb __user *user_iocb;
  1771. if (unlikely(get_user(user_iocb, iocbpp + i))) {
  1772. ret = -EFAULT;
  1773. break;
  1774. }
  1775. ret = io_submit_one(ctx, user_iocb, false);
  1776. if (ret)
  1777. break;
  1778. }
  1779. if (nr > AIO_PLUG_THRESHOLD)
  1780. blk_finish_plug(&plug);
  1781. percpu_ref_put(&ctx->users);
  1782. return i ? i : ret;
  1783. }
  1784. #ifdef CONFIG_COMPAT
  1785. COMPAT_SYSCALL_DEFINE3(io_submit, compat_aio_context_t, ctx_id,
  1786. int, nr, compat_uptr_t __user *, iocbpp)
  1787. {
  1788. struct kioctx *ctx;
  1789. long ret = 0;
  1790. int i = 0;
  1791. struct blk_plug plug;
  1792. if (unlikely(nr < 0))
  1793. return -EINVAL;
  1794. ctx = lookup_ioctx(ctx_id);
  1795. if (unlikely(!ctx)) {
  1796. pr_debug("EINVAL: invalid context id\n");
  1797. return -EINVAL;
  1798. }
  1799. if (nr > ctx->nr_events)
  1800. nr = ctx->nr_events;
  1801. if (nr > AIO_PLUG_THRESHOLD)
  1802. blk_start_plug(&plug);
  1803. for (i = 0; i < nr; i++) {
  1804. compat_uptr_t user_iocb;
  1805. if (unlikely(get_user(user_iocb, iocbpp + i))) {
  1806. ret = -EFAULT;
  1807. break;
  1808. }
  1809. ret = io_submit_one(ctx, compat_ptr(user_iocb), true);
  1810. if (ret)
  1811. break;
  1812. }
  1813. if (nr > AIO_PLUG_THRESHOLD)
  1814. blk_finish_plug(&plug);
  1815. percpu_ref_put(&ctx->users);
  1816. return i ? i : ret;
  1817. }
  1818. #endif
  1819. /* sys_io_cancel:
  1820. * Attempts to cancel an iocb previously passed to io_submit. If
  1821. * the operation is successfully cancelled, the resulting event is
  1822. * copied into the memory pointed to by result without being placed
  1823. * into the completion queue and 0 is returned. May fail with
  1824. * -EFAULT if any of the data structures pointed to are invalid.
  1825. * May fail with -EINVAL if aio_context specified by ctx_id is
  1826. * invalid. May fail with -EAGAIN if the iocb specified was not
  1827. * cancelled. Will fail with -ENOSYS if not implemented.
  1828. */
  1829. SYSCALL_DEFINE3(io_cancel, aio_context_t, ctx_id, struct iocb __user *, iocb,
  1830. struct io_event __user *, result)
  1831. {
  1832. struct kioctx *ctx;
  1833. struct aio_kiocb *kiocb;
  1834. int ret = -EINVAL;
  1835. u32 key;
  1836. u64 obj = (u64)(unsigned long)iocb;
  1837. if (unlikely(get_user(key, &iocb->aio_key)))
  1838. return -EFAULT;
  1839. if (unlikely(key != KIOCB_KEY))
  1840. return -EINVAL;
  1841. ctx = lookup_ioctx(ctx_id);
  1842. if (unlikely(!ctx))
  1843. return -EINVAL;
  1844. spin_lock_irq(&ctx->ctx_lock);
  1845. /* TODO: use a hash or array, this sucks. */
  1846. list_for_each_entry(kiocb, &ctx->active_reqs, ki_list) {
  1847. if (kiocb->ki_res.obj == obj) {
  1848. ret = kiocb->ki_cancel(&kiocb->rw);
  1849. list_del_init(&kiocb->ki_list);
  1850. break;
  1851. }
  1852. }
  1853. spin_unlock_irq(&ctx->ctx_lock);
  1854. if (!ret) {
  1855. /*
  1856. * The result argument is no longer used - the io_event is
  1857. * always delivered via the ring buffer. -EINPROGRESS indicates
  1858. * cancellation is progress:
  1859. */
  1860. ret = -EINPROGRESS;
  1861. }
  1862. percpu_ref_put(&ctx->users);
  1863. return ret;
  1864. }
  1865. static long do_io_getevents(aio_context_t ctx_id,
  1866. long min_nr,
  1867. long nr,
  1868. struct io_event __user *events,
  1869. struct timespec64 *ts)
  1870. {
  1871. ktime_t until = ts ? timespec64_to_ktime(*ts) : KTIME_MAX;
  1872. struct kioctx *ioctx = lookup_ioctx(ctx_id);
  1873. long ret = -EINVAL;
  1874. if (likely(ioctx)) {
  1875. if (likely(min_nr <= nr && min_nr >= 0))
  1876. ret = read_events(ioctx, min_nr, nr, events, until);
  1877. percpu_ref_put(&ioctx->users);
  1878. }
  1879. return ret;
  1880. }
  1881. /* io_getevents:
  1882. * Attempts to read at least min_nr events and up to nr events from
  1883. * the completion queue for the aio_context specified by ctx_id. If
  1884. * it succeeds, the number of read events is returned. May fail with
  1885. * -EINVAL if ctx_id is invalid, if min_nr is out of range, if nr is
  1886. * out of range, if timeout is out of range. May fail with -EFAULT
  1887. * if any of the memory specified is invalid. May return 0 or
  1888. * < min_nr if the timeout specified by timeout has elapsed
  1889. * before sufficient events are available, where timeout == NULL
  1890. * specifies an infinite timeout. Note that the timeout pointed to by
  1891. * timeout is relative. Will fail with -ENOSYS if not implemented.
  1892. */
  1893. #ifdef CONFIG_64BIT
  1894. SYSCALL_DEFINE5(io_getevents, aio_context_t, ctx_id,
  1895. long, min_nr,
  1896. long, nr,
  1897. struct io_event __user *, events,
  1898. struct __kernel_timespec __user *, timeout)
  1899. {
  1900. struct timespec64 ts;
  1901. int ret;
  1902. if (timeout && unlikely(get_timespec64(&ts, timeout)))
  1903. return -EFAULT;
  1904. ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &ts : NULL);
  1905. if (!ret && signal_pending(current))
  1906. ret = -EINTR;
  1907. return ret;
  1908. }
  1909. #endif
  1910. struct __aio_sigset {
  1911. const sigset_t __user *sigmask;
  1912. size_t sigsetsize;
  1913. };
  1914. SYSCALL_DEFINE6(io_pgetevents,
  1915. aio_context_t, ctx_id,
  1916. long, min_nr,
  1917. long, nr,
  1918. struct io_event __user *, events,
  1919. struct __kernel_timespec __user *, timeout,
  1920. const struct __aio_sigset __user *, usig)
  1921. {
  1922. struct __aio_sigset ksig = { NULL, };
  1923. struct timespec64 ts;
  1924. bool interrupted;
  1925. int ret;
  1926. if (timeout && unlikely(get_timespec64(&ts, timeout)))
  1927. return -EFAULT;
  1928. if (usig && copy_from_user(&ksig, usig, sizeof(ksig)))
  1929. return -EFAULT;
  1930. ret = set_user_sigmask(ksig.sigmask, ksig.sigsetsize);
  1931. if (ret)
  1932. return ret;
  1933. ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &ts : NULL);
  1934. interrupted = signal_pending(current);
  1935. restore_saved_sigmask_unless(interrupted);
  1936. if (interrupted && !ret)
  1937. ret = -ERESTARTNOHAND;
  1938. return ret;
  1939. }
  1940. #if defined(CONFIG_COMPAT_32BIT_TIME) && !defined(CONFIG_64BIT)
  1941. SYSCALL_DEFINE6(io_pgetevents_time32,
  1942. aio_context_t, ctx_id,
  1943. long, min_nr,
  1944. long, nr,
  1945. struct io_event __user *, events,
  1946. struct old_timespec32 __user *, timeout,
  1947. const struct __aio_sigset __user *, usig)
  1948. {
  1949. struct __aio_sigset ksig = { NULL, };
  1950. struct timespec64 ts;
  1951. bool interrupted;
  1952. int ret;
  1953. if (timeout && unlikely(get_old_timespec32(&ts, timeout)))
  1954. return -EFAULT;
  1955. if (usig && copy_from_user(&ksig, usig, sizeof(ksig)))
  1956. return -EFAULT;
  1957. ret = set_user_sigmask(ksig.sigmask, ksig.sigsetsize);
  1958. if (ret)
  1959. return ret;
  1960. ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &ts : NULL);
  1961. interrupted = signal_pending(current);
  1962. restore_saved_sigmask_unless(interrupted);
  1963. if (interrupted && !ret)
  1964. ret = -ERESTARTNOHAND;
  1965. return ret;
  1966. }
  1967. #endif
  1968. #if defined(CONFIG_COMPAT_32BIT_TIME)
  1969. SYSCALL_DEFINE5(io_getevents_time32, __u32, ctx_id,
  1970. __s32, min_nr,
  1971. __s32, nr,
  1972. struct io_event __user *, events,
  1973. struct old_timespec32 __user *, timeout)
  1974. {
  1975. struct timespec64 t;
  1976. int ret;
  1977. if (timeout && get_old_timespec32(&t, timeout))
  1978. return -EFAULT;
  1979. ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &t : NULL);
  1980. if (!ret && signal_pending(current))
  1981. ret = -EINTR;
  1982. return ret;
  1983. }
  1984. #endif
  1985. #ifdef CONFIG_COMPAT
  1986. struct __compat_aio_sigset {
  1987. compat_uptr_t sigmask;
  1988. compat_size_t sigsetsize;
  1989. };
  1990. #if defined(CONFIG_COMPAT_32BIT_TIME)
  1991. COMPAT_SYSCALL_DEFINE6(io_pgetevents,
  1992. compat_aio_context_t, ctx_id,
  1993. compat_long_t, min_nr,
  1994. compat_long_t, nr,
  1995. struct io_event __user *, events,
  1996. struct old_timespec32 __user *, timeout,
  1997. const struct __compat_aio_sigset __user *, usig)
  1998. {
  1999. struct __compat_aio_sigset ksig = { 0, };
  2000. struct timespec64 t;
  2001. bool interrupted;
  2002. int ret;
  2003. if (timeout && get_old_timespec32(&t, timeout))
  2004. return -EFAULT;
  2005. if (usig && copy_from_user(&ksig, usig, sizeof(ksig)))
  2006. return -EFAULT;
  2007. ret = set_compat_user_sigmask(compat_ptr(ksig.sigmask), ksig.sigsetsize);
  2008. if (ret)
  2009. return ret;
  2010. ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &t : NULL);
  2011. interrupted = signal_pending(current);
  2012. restore_saved_sigmask_unless(interrupted);
  2013. if (interrupted && !ret)
  2014. ret = -ERESTARTNOHAND;
  2015. return ret;
  2016. }
  2017. #endif
  2018. COMPAT_SYSCALL_DEFINE6(io_pgetevents_time64,
  2019. compat_aio_context_t, ctx_id,
  2020. compat_long_t, min_nr,
  2021. compat_long_t, nr,
  2022. struct io_event __user *, events,
  2023. struct __kernel_timespec __user *, timeout,
  2024. const struct __compat_aio_sigset __user *, usig)
  2025. {
  2026. struct __compat_aio_sigset ksig = { 0, };
  2027. struct timespec64 t;
  2028. bool interrupted;
  2029. int ret;
  2030. if (timeout && get_timespec64(&t, timeout))
  2031. return -EFAULT;
  2032. if (usig && copy_from_user(&ksig, usig, sizeof(ksig)))
  2033. return -EFAULT;
  2034. ret = set_compat_user_sigmask(compat_ptr(ksig.sigmask), ksig.sigsetsize);
  2035. if (ret)
  2036. return ret;
  2037. ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &t : NULL);
  2038. interrupted = signal_pending(current);
  2039. restore_saved_sigmask_unless(interrupted);
  2040. if (interrupted && !ret)
  2041. ret = -ERESTARTNOHAND;
  2042. return ret;
  2043. }
  2044. #endif