aio.c 61 KB

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