aio.c 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723
  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. *
  9. * See ../COPYING for licensing terms.
  10. */
  11. #define pr_fmt(fmt) "%s: " fmt, __func__
  12. #include <linux/kernel.h>
  13. #include <linux/init.h>
  14. #include <linux/errno.h>
  15. #include <linux/time.h>
  16. #include <linux/aio_abi.h>
  17. #include <linux/export.h>
  18. #include <linux/syscalls.h>
  19. #include <linux/backing-dev.h>
  20. #include <linux/uio.h>
  21. #include <linux/sched.h>
  22. #include <linux/fs.h>
  23. #include <linux/file.h>
  24. #include <linux/mm.h>
  25. #include <linux/mman.h>
  26. #include <linux/mmu_context.h>
  27. #include <linux/percpu.h>
  28. #include <linux/slab.h>
  29. #include <linux/timer.h>
  30. #include <linux/aio.h>
  31. #include <linux/highmem.h>
  32. #include <linux/workqueue.h>
  33. #include <linux/security.h>
  34. #include <linux/eventfd.h>
  35. #include <linux/blkdev.h>
  36. #include <linux/compat.h>
  37. #include <linux/migrate.h>
  38. #include <linux/ramfs.h>
  39. #include <linux/percpu-refcount.h>
  40. #include <linux/mount.h>
  41. #include <asm/kmap_types.h>
  42. #include <asm/uaccess.h>
  43. #include "internal.h"
  44. #define AIO_RING_MAGIC 0xa10a10a1
  45. #define AIO_RING_COMPAT_FEATURES 1
  46. #define AIO_RING_INCOMPAT_FEATURES 0
  47. struct aio_ring {
  48. unsigned id; /* kernel internal index number */
  49. unsigned nr; /* number of io_events */
  50. unsigned head; /* Written to by userland or under ring_lock
  51. * mutex by aio_read_events_ring(). */
  52. unsigned tail;
  53. unsigned magic;
  54. unsigned compat_features;
  55. unsigned incompat_features;
  56. unsigned header_length; /* size of aio_ring */
  57. struct io_event io_events[0];
  58. }; /* 128 bytes + ring size */
  59. #define AIO_RING_PAGES 8
  60. struct kioctx_table {
  61. struct rcu_head rcu;
  62. unsigned nr;
  63. struct kioctx *table[];
  64. };
  65. struct kioctx_cpu {
  66. unsigned reqs_available;
  67. };
  68. struct kioctx {
  69. struct percpu_ref users;
  70. atomic_t dead;
  71. struct percpu_ref reqs;
  72. unsigned long user_id;
  73. struct __percpu kioctx_cpu *cpu;
  74. /*
  75. * For percpu reqs_available, number of slots we move to/from global
  76. * counter at a time:
  77. */
  78. unsigned req_batch;
  79. /*
  80. * This is what userspace passed to io_setup(), it's not used for
  81. * anything but counting against the global max_reqs quota.
  82. *
  83. * The real limit is nr_events - 1, which will be larger (see
  84. * aio_setup_ring())
  85. */
  86. unsigned max_reqs;
  87. /* Size of ringbuffer, in units of struct io_event */
  88. unsigned nr_events;
  89. unsigned long mmap_base;
  90. unsigned long mmap_size;
  91. struct page **ring_pages;
  92. long nr_pages;
  93. struct work_struct free_work;
  94. /*
  95. * signals when all in-flight requests are done
  96. */
  97. struct completion *requests_done;
  98. struct {
  99. /*
  100. * This counts the number of available slots in the ringbuffer,
  101. * so we avoid overflowing it: it's decremented (if positive)
  102. * when allocating a kiocb and incremented when the resulting
  103. * io_event is pulled off the ringbuffer.
  104. *
  105. * We batch accesses to it with a percpu version.
  106. */
  107. atomic_t reqs_available;
  108. } ____cacheline_aligned_in_smp;
  109. struct {
  110. spinlock_t ctx_lock;
  111. struct list_head active_reqs; /* used for cancellation */
  112. } ____cacheline_aligned_in_smp;
  113. struct {
  114. struct mutex ring_lock;
  115. wait_queue_head_t wait;
  116. } ____cacheline_aligned_in_smp;
  117. struct {
  118. unsigned tail;
  119. unsigned completed_events;
  120. spinlock_t completion_lock;
  121. } ____cacheline_aligned_in_smp;
  122. struct page *internal_pages[AIO_RING_PAGES];
  123. struct file *aio_ring_file;
  124. unsigned id;
  125. };
  126. /*------ sysctl variables----*/
  127. static DEFINE_SPINLOCK(aio_nr_lock);
  128. unsigned long aio_nr; /* current system wide number of aio requests */
  129. unsigned long aio_max_nr = 0x10000; /* system wide maximum number of aio requests */
  130. /*----end sysctl variables---*/
  131. static struct kmem_cache *kiocb_cachep;
  132. static struct kmem_cache *kioctx_cachep;
  133. static struct vfsmount *aio_mnt;
  134. static const struct file_operations aio_ring_fops;
  135. static const struct address_space_operations aio_ctx_aops;
  136. /* Backing dev info for aio fs.
  137. * -no dirty page accounting or writeback happens
  138. */
  139. static struct backing_dev_info aio_fs_backing_dev_info = {
  140. .name = "aiofs",
  141. .state = 0,
  142. .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK | BDI_CAP_MAP_COPY,
  143. };
  144. static struct file *aio_private_file(struct kioctx *ctx, loff_t nr_pages)
  145. {
  146. struct qstr this = QSTR_INIT("[aio]", 5);
  147. struct file *file;
  148. struct path path;
  149. struct inode *inode = alloc_anon_inode(aio_mnt->mnt_sb);
  150. if (IS_ERR(inode))
  151. return ERR_CAST(inode);
  152. inode->i_mapping->a_ops = &aio_ctx_aops;
  153. inode->i_mapping->private_data = ctx;
  154. inode->i_mapping->backing_dev_info = &aio_fs_backing_dev_info;
  155. inode->i_size = PAGE_SIZE * nr_pages;
  156. path.dentry = d_alloc_pseudo(aio_mnt->mnt_sb, &this);
  157. if (!path.dentry) {
  158. iput(inode);
  159. return ERR_PTR(-ENOMEM);
  160. }
  161. path.mnt = mntget(aio_mnt);
  162. d_instantiate(path.dentry, inode);
  163. file = alloc_file(&path, FMODE_READ | FMODE_WRITE, &aio_ring_fops);
  164. if (IS_ERR(file)) {
  165. path_put(&path);
  166. return file;
  167. }
  168. file->f_flags = O_RDWR;
  169. return file;
  170. }
  171. static struct dentry *aio_mount(struct file_system_type *fs_type,
  172. int flags, const char *dev_name, void *data)
  173. {
  174. static const struct dentry_operations ops = {
  175. .d_dname = simple_dname,
  176. };
  177. return mount_pseudo(fs_type, "aio:", NULL, &ops, AIO_RING_MAGIC);
  178. }
  179. /* aio_setup
  180. * Creates the slab caches used by the aio routines, panic on
  181. * failure as this is done early during the boot sequence.
  182. */
  183. static int __init aio_setup(void)
  184. {
  185. static struct file_system_type aio_fs = {
  186. .name = "aio",
  187. .mount = aio_mount,
  188. .kill_sb = kill_anon_super,
  189. };
  190. aio_mnt = kern_mount(&aio_fs);
  191. if (IS_ERR(aio_mnt))
  192. panic("Failed to create aio fs mount.");
  193. aio_mnt->mnt_flags |= MNT_NOEXEC;
  194. if (bdi_init(&aio_fs_backing_dev_info))
  195. panic("Failed to init aio fs backing dev info.");
  196. kiocb_cachep = KMEM_CACHE(kiocb, SLAB_HWCACHE_ALIGN|SLAB_PANIC);
  197. kioctx_cachep = KMEM_CACHE(kioctx,SLAB_HWCACHE_ALIGN|SLAB_PANIC);
  198. pr_debug("sizeof(struct page) = %zu\n", sizeof(struct page));
  199. return 0;
  200. }
  201. __initcall(aio_setup);
  202. static void put_aio_ring_file(struct kioctx *ctx)
  203. {
  204. struct file *aio_ring_file = ctx->aio_ring_file;
  205. if (aio_ring_file) {
  206. truncate_setsize(aio_ring_file->f_inode, 0);
  207. /* Prevent further access to the kioctx from migratepages */
  208. spin_lock(&aio_ring_file->f_inode->i_mapping->private_lock);
  209. aio_ring_file->f_inode->i_mapping->private_data = NULL;
  210. ctx->aio_ring_file = NULL;
  211. spin_unlock(&aio_ring_file->f_inode->i_mapping->private_lock);
  212. fput(aio_ring_file);
  213. }
  214. }
  215. static void aio_free_ring(struct kioctx *ctx)
  216. {
  217. int i;
  218. /* Disconnect the kiotx from the ring file. This prevents future
  219. * accesses to the kioctx from page migration.
  220. */
  221. put_aio_ring_file(ctx);
  222. for (i = 0; i < ctx->nr_pages; i++) {
  223. struct page *page;
  224. pr_debug("pid(%d) [%d] page->count=%d\n", current->pid, i,
  225. page_count(ctx->ring_pages[i]));
  226. page = ctx->ring_pages[i];
  227. if (!page)
  228. continue;
  229. ctx->ring_pages[i] = NULL;
  230. put_page(page);
  231. }
  232. if (ctx->ring_pages && ctx->ring_pages != ctx->internal_pages) {
  233. kfree(ctx->ring_pages);
  234. ctx->ring_pages = NULL;
  235. }
  236. }
  237. static int aio_ring_mmap(struct file *file, struct vm_area_struct *vma)
  238. {
  239. vma->vm_ops = &generic_file_vm_ops;
  240. return 0;
  241. }
  242. static const struct file_operations aio_ring_fops = {
  243. .mmap = aio_ring_mmap,
  244. };
  245. #if IS_ENABLED(CONFIG_MIGRATION)
  246. static int aio_migratepage(struct address_space *mapping, struct page *new,
  247. struct page *old, enum migrate_mode mode)
  248. {
  249. struct kioctx *ctx;
  250. unsigned long flags;
  251. pgoff_t idx;
  252. int rc;
  253. rc = 0;
  254. /* mapping->private_lock here protects against the kioctx teardown. */
  255. spin_lock(&mapping->private_lock);
  256. ctx = mapping->private_data;
  257. if (!ctx) {
  258. rc = -EINVAL;
  259. goto out;
  260. }
  261. /* The ring_lock mutex. The prevents aio_read_events() from writing
  262. * to the ring's head, and prevents page migration from mucking in
  263. * a partially initialized kiotx.
  264. */
  265. if (!mutex_trylock(&ctx->ring_lock)) {
  266. rc = -EAGAIN;
  267. goto out;
  268. }
  269. idx = old->index;
  270. if (idx < (pgoff_t)ctx->nr_pages) {
  271. /* Make sure the old page hasn't already been changed */
  272. if (ctx->ring_pages[idx] != old)
  273. rc = -EAGAIN;
  274. } else
  275. rc = -EINVAL;
  276. if (rc != 0)
  277. goto out_unlock;
  278. /* Writeback must be complete */
  279. BUG_ON(PageWriteback(old));
  280. get_page(new);
  281. rc = migrate_page_move_mapping(mapping, new, old, NULL, mode, 1);
  282. if (rc != MIGRATEPAGE_SUCCESS) {
  283. put_page(new);
  284. goto out_unlock;
  285. }
  286. /* Take completion_lock to prevent other writes to the ring buffer
  287. * while the old page is copied to the new. This prevents new
  288. * events from being lost.
  289. */
  290. spin_lock_irqsave(&ctx->completion_lock, flags);
  291. migrate_page_copy(new, old);
  292. BUG_ON(ctx->ring_pages[idx] != old);
  293. ctx->ring_pages[idx] = new;
  294. spin_unlock_irqrestore(&ctx->completion_lock, flags);
  295. /* The old page is no longer accessible. */
  296. put_page(old);
  297. out_unlock:
  298. mutex_unlock(&ctx->ring_lock);
  299. out:
  300. spin_unlock(&mapping->private_lock);
  301. return rc;
  302. }
  303. #endif
  304. static const struct address_space_operations aio_ctx_aops = {
  305. .set_page_dirty = __set_page_dirty_no_writeback,
  306. #if IS_ENABLED(CONFIG_MIGRATION)
  307. .migratepage = aio_migratepage,
  308. #endif
  309. };
  310. static int aio_setup_ring(struct kioctx *ctx)
  311. {
  312. struct aio_ring *ring;
  313. unsigned nr_events = ctx->max_reqs;
  314. struct mm_struct *mm = current->mm;
  315. unsigned long size, unused;
  316. int nr_pages;
  317. int i;
  318. struct file *file;
  319. /* Compensate for the ring buffer's head/tail overlap entry */
  320. nr_events += 2; /* 1 is required, 2 for good luck */
  321. size = sizeof(struct aio_ring);
  322. size += sizeof(struct io_event) * nr_events;
  323. nr_pages = PFN_UP(size);
  324. if (nr_pages < 0)
  325. return -EINVAL;
  326. file = aio_private_file(ctx, nr_pages);
  327. if (IS_ERR(file)) {
  328. ctx->aio_ring_file = NULL;
  329. return -ENOMEM;
  330. }
  331. ctx->aio_ring_file = file;
  332. nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring))
  333. / sizeof(struct io_event);
  334. ctx->ring_pages = ctx->internal_pages;
  335. if (nr_pages > AIO_RING_PAGES) {
  336. ctx->ring_pages = kcalloc(nr_pages, sizeof(struct page *),
  337. GFP_KERNEL);
  338. if (!ctx->ring_pages) {
  339. put_aio_ring_file(ctx);
  340. return -ENOMEM;
  341. }
  342. }
  343. for (i = 0; i < nr_pages; i++) {
  344. struct page *page;
  345. page = find_or_create_page(file->f_inode->i_mapping,
  346. i, GFP_HIGHUSER | __GFP_ZERO);
  347. if (!page)
  348. break;
  349. pr_debug("pid(%d) page[%d]->count=%d\n",
  350. current->pid, i, page_count(page));
  351. SetPageUptodate(page);
  352. unlock_page(page);
  353. ctx->ring_pages[i] = page;
  354. }
  355. ctx->nr_pages = i;
  356. if (unlikely(i != nr_pages)) {
  357. aio_free_ring(ctx);
  358. return -ENOMEM;
  359. }
  360. ctx->mmap_size = nr_pages * PAGE_SIZE;
  361. pr_debug("attempting mmap of %lu bytes\n", ctx->mmap_size);
  362. down_write(&mm->mmap_sem);
  363. ctx->mmap_base = do_mmap_pgoff(ctx->aio_ring_file, 0, ctx->mmap_size,
  364. PROT_READ | PROT_WRITE,
  365. MAP_SHARED, 0, &unused);
  366. up_write(&mm->mmap_sem);
  367. if (IS_ERR((void *)ctx->mmap_base)) {
  368. ctx->mmap_size = 0;
  369. aio_free_ring(ctx);
  370. return -ENOMEM;
  371. }
  372. pr_debug("mmap address: 0x%08lx\n", ctx->mmap_base);
  373. ctx->user_id = ctx->mmap_base;
  374. ctx->nr_events = nr_events; /* trusted copy */
  375. ring = kmap_atomic(ctx->ring_pages[0]);
  376. ring->nr = nr_events; /* user copy */
  377. ring->id = ~0U;
  378. ring->head = ring->tail = 0;
  379. ring->magic = AIO_RING_MAGIC;
  380. ring->compat_features = AIO_RING_COMPAT_FEATURES;
  381. ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
  382. ring->header_length = sizeof(struct aio_ring);
  383. kunmap_atomic(ring);
  384. flush_dcache_page(ctx->ring_pages[0]);
  385. return 0;
  386. }
  387. #define AIO_EVENTS_PER_PAGE (PAGE_SIZE / sizeof(struct io_event))
  388. #define AIO_EVENTS_FIRST_PAGE ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
  389. #define AIO_EVENTS_OFFSET (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
  390. void kiocb_set_cancel_fn(struct kiocb *req, kiocb_cancel_fn *cancel)
  391. {
  392. struct kioctx *ctx = req->ki_ctx;
  393. unsigned long flags;
  394. spin_lock_irqsave(&ctx->ctx_lock, flags);
  395. if (!req->ki_list.next)
  396. list_add(&req->ki_list, &ctx->active_reqs);
  397. req->ki_cancel = cancel;
  398. spin_unlock_irqrestore(&ctx->ctx_lock, flags);
  399. }
  400. EXPORT_SYMBOL(kiocb_set_cancel_fn);
  401. static int kiocb_cancel(struct kiocb *kiocb)
  402. {
  403. kiocb_cancel_fn *old, *cancel;
  404. /*
  405. * Don't want to set kiocb->ki_cancel = KIOCB_CANCELLED unless it
  406. * actually has a cancel function, hence the cmpxchg()
  407. */
  408. cancel = ACCESS_ONCE(kiocb->ki_cancel);
  409. do {
  410. if (!cancel || cancel == KIOCB_CANCELLED)
  411. return -EINVAL;
  412. old = cancel;
  413. cancel = cmpxchg(&kiocb->ki_cancel, old, KIOCB_CANCELLED);
  414. } while (cancel != old);
  415. return cancel(kiocb);
  416. }
  417. static void free_ioctx(struct work_struct *work)
  418. {
  419. struct kioctx *ctx = container_of(work, struct kioctx, free_work);
  420. pr_debug("freeing %p\n", ctx);
  421. aio_free_ring(ctx);
  422. free_percpu(ctx->cpu);
  423. percpu_ref_exit(&ctx->reqs);
  424. percpu_ref_exit(&ctx->users);
  425. kmem_cache_free(kioctx_cachep, ctx);
  426. }
  427. static void free_ioctx_reqs(struct percpu_ref *ref)
  428. {
  429. struct kioctx *ctx = container_of(ref, struct kioctx, reqs);
  430. /* At this point we know that there are no any in-flight requests */
  431. if (ctx->requests_done)
  432. complete(ctx->requests_done);
  433. INIT_WORK(&ctx->free_work, free_ioctx);
  434. schedule_work(&ctx->free_work);
  435. }
  436. /*
  437. * When this function runs, the kioctx has been removed from the "hash table"
  438. * and ctx->users has dropped to 0, so we know no more kiocbs can be submitted -
  439. * now it's safe to cancel any that need to be.
  440. */
  441. static void free_ioctx_users(struct percpu_ref *ref)
  442. {
  443. struct kioctx *ctx = container_of(ref, struct kioctx, users);
  444. struct kiocb *req;
  445. spin_lock_irq(&ctx->ctx_lock);
  446. while (!list_empty(&ctx->active_reqs)) {
  447. req = list_first_entry(&ctx->active_reqs,
  448. struct kiocb, ki_list);
  449. list_del_init(&req->ki_list);
  450. kiocb_cancel(req);
  451. }
  452. spin_unlock_irq(&ctx->ctx_lock);
  453. percpu_ref_kill(&ctx->reqs);
  454. percpu_ref_put(&ctx->reqs);
  455. }
  456. static int ioctx_add_table(struct kioctx *ctx, struct mm_struct *mm)
  457. {
  458. unsigned i, new_nr;
  459. struct kioctx_table *table, *old;
  460. struct aio_ring *ring;
  461. spin_lock(&mm->ioctx_lock);
  462. table = rcu_dereference_raw(mm->ioctx_table);
  463. while (1) {
  464. if (table)
  465. for (i = 0; i < table->nr; i++)
  466. if (!table->table[i]) {
  467. ctx->id = i;
  468. table->table[i] = ctx;
  469. spin_unlock(&mm->ioctx_lock);
  470. /* While kioctx setup is in progress,
  471. * we are protected from page migration
  472. * changes ring_pages by ->ring_lock.
  473. */
  474. ring = kmap_atomic(ctx->ring_pages[0]);
  475. ring->id = ctx->id;
  476. kunmap_atomic(ring);
  477. return 0;
  478. }
  479. new_nr = (table ? table->nr : 1) * 4;
  480. spin_unlock(&mm->ioctx_lock);
  481. table = kzalloc(sizeof(*table) + sizeof(struct kioctx *) *
  482. new_nr, GFP_KERNEL);
  483. if (!table)
  484. return -ENOMEM;
  485. table->nr = new_nr;
  486. spin_lock(&mm->ioctx_lock);
  487. old = rcu_dereference_raw(mm->ioctx_table);
  488. if (!old) {
  489. rcu_assign_pointer(mm->ioctx_table, table);
  490. } else if (table->nr > old->nr) {
  491. memcpy(table->table, old->table,
  492. old->nr * sizeof(struct kioctx *));
  493. rcu_assign_pointer(mm->ioctx_table, table);
  494. kfree_rcu(old, rcu);
  495. } else {
  496. kfree(table);
  497. table = old;
  498. }
  499. }
  500. }
  501. static void aio_nr_sub(unsigned nr)
  502. {
  503. spin_lock(&aio_nr_lock);
  504. if (WARN_ON(aio_nr - nr > aio_nr))
  505. aio_nr = 0;
  506. else
  507. aio_nr -= nr;
  508. spin_unlock(&aio_nr_lock);
  509. }
  510. /* ioctx_alloc
  511. * Allocates and initializes an ioctx. Returns an ERR_PTR if it failed.
  512. */
  513. static struct kioctx *ioctx_alloc(unsigned nr_events)
  514. {
  515. struct mm_struct *mm = current->mm;
  516. struct kioctx *ctx;
  517. int err = -ENOMEM;
  518. /*
  519. * We keep track of the number of available ringbuffer slots, to prevent
  520. * overflow (reqs_available), and we also use percpu counters for this.
  521. *
  522. * So since up to half the slots might be on other cpu's percpu counters
  523. * and unavailable, double nr_events so userspace sees what they
  524. * expected: additionally, we move req_batch slots to/from percpu
  525. * counters at a time, so make sure that isn't 0:
  526. */
  527. nr_events = max(nr_events, num_possible_cpus() * 4);
  528. nr_events *= 2;
  529. /* Prevent overflows */
  530. if ((nr_events > (0x10000000U / sizeof(struct io_event))) ||
  531. (nr_events > (0x10000000U / sizeof(struct kiocb)))) {
  532. pr_debug("ENOMEM: nr_events too high\n");
  533. return ERR_PTR(-EINVAL);
  534. }
  535. if (!nr_events || (unsigned long)nr_events > (aio_max_nr * 2UL))
  536. return ERR_PTR(-EAGAIN);
  537. ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
  538. if (!ctx)
  539. return ERR_PTR(-ENOMEM);
  540. ctx->max_reqs = nr_events;
  541. spin_lock_init(&ctx->ctx_lock);
  542. spin_lock_init(&ctx->completion_lock);
  543. mutex_init(&ctx->ring_lock);
  544. /* Protect against page migration throughout kiotx setup by keeping
  545. * the ring_lock mutex held until setup is complete. */
  546. mutex_lock(&ctx->ring_lock);
  547. init_waitqueue_head(&ctx->wait);
  548. INIT_LIST_HEAD(&ctx->active_reqs);
  549. if (percpu_ref_init(&ctx->users, free_ioctx_users, 0, GFP_KERNEL))
  550. goto err;
  551. if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs, 0, GFP_KERNEL))
  552. goto err;
  553. ctx->cpu = alloc_percpu(struct kioctx_cpu);
  554. if (!ctx->cpu)
  555. goto err;
  556. err = aio_setup_ring(ctx);
  557. if (err < 0)
  558. goto err;
  559. atomic_set(&ctx->reqs_available, ctx->nr_events - 1);
  560. ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4);
  561. if (ctx->req_batch < 1)
  562. ctx->req_batch = 1;
  563. /* limit the number of system wide aios */
  564. spin_lock(&aio_nr_lock);
  565. if (aio_nr + nr_events > (aio_max_nr * 2UL) ||
  566. aio_nr + nr_events < aio_nr) {
  567. spin_unlock(&aio_nr_lock);
  568. err = -EAGAIN;
  569. goto err_ctx;
  570. }
  571. aio_nr += ctx->max_reqs;
  572. spin_unlock(&aio_nr_lock);
  573. percpu_ref_get(&ctx->users); /* io_setup() will drop this ref */
  574. percpu_ref_get(&ctx->reqs); /* free_ioctx_users() will drop this */
  575. err = ioctx_add_table(ctx, mm);
  576. if (err)
  577. goto err_cleanup;
  578. /* Release the ring_lock mutex now that all setup is complete. */
  579. mutex_unlock(&ctx->ring_lock);
  580. pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
  581. ctx, ctx->user_id, mm, ctx->nr_events);
  582. return ctx;
  583. err_cleanup:
  584. aio_nr_sub(ctx->max_reqs);
  585. err_ctx:
  586. atomic_set(&ctx->dead, 1);
  587. if (ctx->mmap_size)
  588. vm_munmap(ctx->mmap_base, ctx->mmap_size);
  589. aio_free_ring(ctx);
  590. err:
  591. mutex_unlock(&ctx->ring_lock);
  592. free_percpu(ctx->cpu);
  593. percpu_ref_exit(&ctx->reqs);
  594. percpu_ref_exit(&ctx->users);
  595. kmem_cache_free(kioctx_cachep, ctx);
  596. pr_debug("error allocating ioctx %d\n", err);
  597. return ERR_PTR(err);
  598. }
  599. /* kill_ioctx
  600. * Cancels all outstanding aio requests on an aio context. Used
  601. * when the processes owning a context have all exited to encourage
  602. * the rapid destruction of the kioctx.
  603. */
  604. static int kill_ioctx(struct mm_struct *mm, struct kioctx *ctx,
  605. struct completion *requests_done)
  606. {
  607. struct kioctx_table *table;
  608. if (atomic_xchg(&ctx->dead, 1))
  609. return -EINVAL;
  610. spin_lock(&mm->ioctx_lock);
  611. table = rcu_dereference_raw(mm->ioctx_table);
  612. WARN_ON(ctx != table->table[ctx->id]);
  613. table->table[ctx->id] = NULL;
  614. spin_unlock(&mm->ioctx_lock);
  615. /* percpu_ref_kill() will do the necessary call_rcu() */
  616. wake_up_all(&ctx->wait);
  617. /*
  618. * It'd be more correct to do this in free_ioctx(), after all
  619. * the outstanding kiocbs have finished - but by then io_destroy
  620. * has already returned, so io_setup() could potentially return
  621. * -EAGAIN with no ioctxs actually in use (as far as userspace
  622. * could tell).
  623. */
  624. aio_nr_sub(ctx->max_reqs);
  625. if (ctx->mmap_size)
  626. vm_munmap(ctx->mmap_base, ctx->mmap_size);
  627. ctx->requests_done = requests_done;
  628. percpu_ref_kill(&ctx->users);
  629. return 0;
  630. }
  631. /* wait_on_sync_kiocb:
  632. * Waits on the given sync kiocb to complete.
  633. */
  634. ssize_t wait_on_sync_kiocb(struct kiocb *req)
  635. {
  636. while (!req->ki_ctx) {
  637. set_current_state(TASK_UNINTERRUPTIBLE);
  638. if (req->ki_ctx)
  639. break;
  640. io_schedule();
  641. }
  642. __set_current_state(TASK_RUNNING);
  643. return req->ki_user_data;
  644. }
  645. EXPORT_SYMBOL(wait_on_sync_kiocb);
  646. /*
  647. * exit_aio: called when the last user of mm goes away. At this point, there is
  648. * no way for any new requests to be submited or any of the io_* syscalls to be
  649. * called on the context.
  650. *
  651. * There may be outstanding kiocbs, but free_ioctx() will explicitly wait on
  652. * them.
  653. */
  654. void exit_aio(struct mm_struct *mm)
  655. {
  656. struct kioctx_table *table = rcu_dereference_raw(mm->ioctx_table);
  657. int i;
  658. if (!table)
  659. return;
  660. for (i = 0; i < table->nr; ++i) {
  661. struct kioctx *ctx = table->table[i];
  662. struct completion requests_done =
  663. COMPLETION_INITIALIZER_ONSTACK(requests_done);
  664. if (!ctx)
  665. continue;
  666. /*
  667. * We don't need to bother with munmap() here - exit_mmap(mm)
  668. * is coming and it'll unmap everything. And we simply can't,
  669. * this is not necessarily our ->mm.
  670. * Since kill_ioctx() uses non-zero ->mmap_size as indicator
  671. * that it needs to unmap the area, just set it to 0.
  672. */
  673. ctx->mmap_size = 0;
  674. kill_ioctx(mm, ctx, &requests_done);
  675. /* Wait until all IO for the context are done. */
  676. wait_for_completion(&requests_done);
  677. }
  678. RCU_INIT_POINTER(mm->ioctx_table, NULL);
  679. kfree(table);
  680. }
  681. static void put_reqs_available(struct kioctx *ctx, unsigned nr)
  682. {
  683. struct kioctx_cpu *kcpu;
  684. unsigned long flags;
  685. local_irq_save(flags);
  686. kcpu = this_cpu_ptr(ctx->cpu);
  687. kcpu->reqs_available += nr;
  688. while (kcpu->reqs_available >= ctx->req_batch * 2) {
  689. kcpu->reqs_available -= ctx->req_batch;
  690. atomic_add(ctx->req_batch, &ctx->reqs_available);
  691. }
  692. local_irq_restore(flags);
  693. }
  694. static bool get_reqs_available(struct kioctx *ctx)
  695. {
  696. struct kioctx_cpu *kcpu;
  697. bool ret = false;
  698. unsigned long flags;
  699. local_irq_save(flags);
  700. kcpu = this_cpu_ptr(ctx->cpu);
  701. if (!kcpu->reqs_available) {
  702. int old, avail = atomic_read(&ctx->reqs_available);
  703. do {
  704. if (avail < ctx->req_batch)
  705. goto out;
  706. old = avail;
  707. avail = atomic_cmpxchg(&ctx->reqs_available,
  708. avail, avail - ctx->req_batch);
  709. } while (avail != old);
  710. kcpu->reqs_available += ctx->req_batch;
  711. }
  712. ret = true;
  713. kcpu->reqs_available--;
  714. out:
  715. local_irq_restore(flags);
  716. return ret;
  717. }
  718. /* refill_reqs_available
  719. * Updates the reqs_available reference counts used for tracking the
  720. * number of free slots in the completion ring. This can be called
  721. * from aio_complete() (to optimistically update reqs_available) or
  722. * from aio_get_req() (the we're out of events case). It must be
  723. * called holding ctx->completion_lock.
  724. */
  725. static void refill_reqs_available(struct kioctx *ctx, unsigned head,
  726. unsigned tail)
  727. {
  728. unsigned events_in_ring, completed;
  729. /* Clamp head since userland can write to it. */
  730. head %= ctx->nr_events;
  731. if (head <= tail)
  732. events_in_ring = tail - head;
  733. else
  734. events_in_ring = ctx->nr_events - (head - tail);
  735. completed = ctx->completed_events;
  736. if (events_in_ring < completed)
  737. completed -= events_in_ring;
  738. else
  739. completed = 0;
  740. if (!completed)
  741. return;
  742. ctx->completed_events -= completed;
  743. put_reqs_available(ctx, completed);
  744. }
  745. /* user_refill_reqs_available
  746. * Called to refill reqs_available when aio_get_req() encounters an
  747. * out of space in the completion ring.
  748. */
  749. static void user_refill_reqs_available(struct kioctx *ctx)
  750. {
  751. spin_lock_irq(&ctx->completion_lock);
  752. if (ctx->completed_events) {
  753. struct aio_ring *ring;
  754. unsigned head;
  755. /* Access of ring->head may race with aio_read_events_ring()
  756. * here, but that's okay since whether we read the old version
  757. * or the new version, and either will be valid. The important
  758. * part is that head cannot pass tail since we prevent
  759. * aio_complete() from updating tail by holding
  760. * ctx->completion_lock. Even if head is invalid, the check
  761. * against ctx->completed_events below will make sure we do the
  762. * safe/right thing.
  763. */
  764. ring = kmap_atomic(ctx->ring_pages[0]);
  765. head = ring->head;
  766. kunmap_atomic(ring);
  767. refill_reqs_available(ctx, head, ctx->tail);
  768. }
  769. spin_unlock_irq(&ctx->completion_lock);
  770. }
  771. /* aio_get_req
  772. * Allocate a slot for an aio request.
  773. * Returns NULL if no requests are free.
  774. */
  775. static inline struct kiocb *aio_get_req(struct kioctx *ctx)
  776. {
  777. struct kiocb *req;
  778. if (!get_reqs_available(ctx)) {
  779. user_refill_reqs_available(ctx);
  780. if (!get_reqs_available(ctx))
  781. return NULL;
  782. }
  783. req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL|__GFP_ZERO);
  784. if (unlikely(!req))
  785. goto out_put;
  786. percpu_ref_get(&ctx->reqs);
  787. req->ki_ctx = ctx;
  788. return req;
  789. out_put:
  790. put_reqs_available(ctx, 1);
  791. return NULL;
  792. }
  793. static void kiocb_free(struct kiocb *req)
  794. {
  795. if (req->ki_filp)
  796. fput(req->ki_filp);
  797. if (req->ki_eventfd != NULL)
  798. eventfd_ctx_put(req->ki_eventfd);
  799. kmem_cache_free(kiocb_cachep, req);
  800. }
  801. static struct kioctx *lookup_ioctx(unsigned long ctx_id)
  802. {
  803. struct aio_ring __user *ring = (void __user *)ctx_id;
  804. struct mm_struct *mm = current->mm;
  805. struct kioctx *ctx, *ret = NULL;
  806. struct kioctx_table *table;
  807. unsigned id;
  808. if (get_user(id, &ring->id))
  809. return NULL;
  810. rcu_read_lock();
  811. table = rcu_dereference(mm->ioctx_table);
  812. if (!table || id >= table->nr)
  813. goto out;
  814. ctx = table->table[id];
  815. if (ctx && ctx->user_id == ctx_id) {
  816. percpu_ref_get(&ctx->users);
  817. ret = ctx;
  818. }
  819. out:
  820. rcu_read_unlock();
  821. return ret;
  822. }
  823. /* aio_complete
  824. * Called when the io request on the given iocb is complete.
  825. */
  826. void aio_complete(struct kiocb *iocb, long res, long res2)
  827. {
  828. struct kioctx *ctx = iocb->ki_ctx;
  829. struct aio_ring *ring;
  830. struct io_event *ev_page, *event;
  831. unsigned tail, pos, head;
  832. unsigned long flags;
  833. /*
  834. * Special case handling for sync iocbs:
  835. * - events go directly into the iocb for fast handling
  836. * - the sync task with the iocb in its stack holds the single iocb
  837. * ref, no other paths have a way to get another ref
  838. * - the sync task helpfully left a reference to itself in the iocb
  839. */
  840. if (is_sync_kiocb(iocb)) {
  841. iocb->ki_user_data = res;
  842. smp_wmb();
  843. iocb->ki_ctx = ERR_PTR(-EXDEV);
  844. wake_up_process(iocb->ki_obj.tsk);
  845. return;
  846. }
  847. if (iocb->ki_list.next) {
  848. unsigned long flags;
  849. spin_lock_irqsave(&ctx->ctx_lock, flags);
  850. list_del(&iocb->ki_list);
  851. spin_unlock_irqrestore(&ctx->ctx_lock, flags);
  852. }
  853. /*
  854. * Add a completion event to the ring buffer. Must be done holding
  855. * ctx->completion_lock to prevent other code from messing with the tail
  856. * pointer since we might be called from irq context.
  857. */
  858. spin_lock_irqsave(&ctx->completion_lock, flags);
  859. tail = ctx->tail;
  860. pos = tail + AIO_EVENTS_OFFSET;
  861. if (++tail >= ctx->nr_events)
  862. tail = 0;
  863. ev_page = kmap_atomic(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
  864. event = ev_page + pos % AIO_EVENTS_PER_PAGE;
  865. event->obj = (u64)(unsigned long)iocb->ki_obj.user;
  866. event->data = iocb->ki_user_data;
  867. event->res = res;
  868. event->res2 = res2;
  869. kunmap_atomic(ev_page);
  870. flush_dcache_page(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
  871. pr_debug("%p[%u]: %p: %p %Lx %lx %lx\n",
  872. ctx, tail, iocb, iocb->ki_obj.user, iocb->ki_user_data,
  873. res, res2);
  874. /* after flagging the request as done, we
  875. * must never even look at it again
  876. */
  877. smp_wmb(); /* make event visible before updating tail */
  878. ctx->tail = tail;
  879. ring = kmap_atomic(ctx->ring_pages[0]);
  880. head = ring->head;
  881. ring->tail = tail;
  882. kunmap_atomic(ring);
  883. flush_dcache_page(ctx->ring_pages[0]);
  884. ctx->completed_events++;
  885. if (ctx->completed_events > 1)
  886. refill_reqs_available(ctx, head, tail);
  887. spin_unlock_irqrestore(&ctx->completion_lock, flags);
  888. pr_debug("added to ring %p at [%u]\n", iocb, tail);
  889. /*
  890. * Check if the user asked us to deliver the result through an
  891. * eventfd. The eventfd_signal() function is safe to be called
  892. * from IRQ context.
  893. */
  894. if (iocb->ki_eventfd != NULL)
  895. eventfd_signal(iocb->ki_eventfd, 1);
  896. /* everything turned out well, dispose of the aiocb. */
  897. kiocb_free(iocb);
  898. /*
  899. * We have to order our ring_info tail store above and test
  900. * of the wait list below outside the wait lock. This is
  901. * like in wake_up_bit() where clearing a bit has to be
  902. * ordered with the unlocked test.
  903. */
  904. smp_mb();
  905. if (waitqueue_active(&ctx->wait))
  906. wake_up(&ctx->wait);
  907. percpu_ref_put(&ctx->reqs);
  908. }
  909. EXPORT_SYMBOL(aio_complete);
  910. /* aio_read_events_ring
  911. * Pull an event off of the ioctx's event ring. Returns the number of
  912. * events fetched
  913. */
  914. static long aio_read_events_ring(struct kioctx *ctx,
  915. struct io_event __user *event, long nr)
  916. {
  917. struct aio_ring *ring;
  918. unsigned head, tail, pos;
  919. long ret = 0;
  920. int copy_ret;
  921. mutex_lock(&ctx->ring_lock);
  922. /* Access to ->ring_pages here is protected by ctx->ring_lock. */
  923. ring = kmap_atomic(ctx->ring_pages[0]);
  924. head = ring->head;
  925. tail = ring->tail;
  926. kunmap_atomic(ring);
  927. /*
  928. * Ensure that once we've read the current tail pointer, that
  929. * we also see the events that were stored up to the tail.
  930. */
  931. smp_rmb();
  932. pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
  933. if (head == tail)
  934. goto out;
  935. head %= ctx->nr_events;
  936. tail %= ctx->nr_events;
  937. while (ret < nr) {
  938. long avail;
  939. struct io_event *ev;
  940. struct page *page;
  941. avail = (head <= tail ? tail : ctx->nr_events) - head;
  942. if (head == tail)
  943. break;
  944. avail = min(avail, nr - ret);
  945. avail = min_t(long, avail, AIO_EVENTS_PER_PAGE -
  946. ((head + AIO_EVENTS_OFFSET) % AIO_EVENTS_PER_PAGE));
  947. pos = head + AIO_EVENTS_OFFSET;
  948. page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
  949. pos %= AIO_EVENTS_PER_PAGE;
  950. ev = kmap(page);
  951. copy_ret = copy_to_user(event + ret, ev + pos,
  952. sizeof(*ev) * avail);
  953. kunmap(page);
  954. if (unlikely(copy_ret)) {
  955. ret = -EFAULT;
  956. goto out;
  957. }
  958. ret += avail;
  959. head += avail;
  960. head %= ctx->nr_events;
  961. }
  962. ring = kmap_atomic(ctx->ring_pages[0]);
  963. ring->head = head;
  964. kunmap_atomic(ring);
  965. flush_dcache_page(ctx->ring_pages[0]);
  966. pr_debug("%li h%u t%u\n", ret, head, tail);
  967. out:
  968. mutex_unlock(&ctx->ring_lock);
  969. return ret;
  970. }
  971. static bool aio_read_events(struct kioctx *ctx, long min_nr, long nr,
  972. struct io_event __user *event, long *i)
  973. {
  974. long ret = aio_read_events_ring(ctx, event + *i, nr - *i);
  975. if (ret > 0)
  976. *i += ret;
  977. if (unlikely(atomic_read(&ctx->dead)))
  978. ret = -EINVAL;
  979. if (!*i)
  980. *i = ret;
  981. return ret < 0 || *i >= min_nr;
  982. }
  983. static long read_events(struct kioctx *ctx, long min_nr, long nr,
  984. struct io_event __user *event,
  985. struct timespec __user *timeout)
  986. {
  987. ktime_t until = { .tv64 = KTIME_MAX };
  988. long ret = 0;
  989. if (timeout) {
  990. struct timespec ts;
  991. if (unlikely(copy_from_user(&ts, timeout, sizeof(ts))))
  992. return -EFAULT;
  993. until = timespec_to_ktime(ts);
  994. }
  995. /*
  996. * Note that aio_read_events() is being called as the conditional - i.e.
  997. * we're calling it after prepare_to_wait() has set task state to
  998. * TASK_INTERRUPTIBLE.
  999. *
  1000. * But aio_read_events() can block, and if it blocks it's going to flip
  1001. * the task state back to TASK_RUNNING.
  1002. *
  1003. * This should be ok, provided it doesn't flip the state back to
  1004. * TASK_RUNNING and return 0 too much - that causes us to spin. That
  1005. * will only happen if the mutex_lock() call blocks, and we then find
  1006. * the ringbuffer empty. So in practice we should be ok, but it's
  1007. * something to be aware of when touching this code.
  1008. */
  1009. wait_event_interruptible_hrtimeout(ctx->wait,
  1010. aio_read_events(ctx, min_nr, nr, event, &ret), until);
  1011. if (!ret && signal_pending(current))
  1012. ret = -EINTR;
  1013. return ret;
  1014. }
  1015. /* sys_io_setup:
  1016. * Create an aio_context capable of receiving at least nr_events.
  1017. * ctxp must not point to an aio_context that already exists, and
  1018. * must be initialized to 0 prior to the call. On successful
  1019. * creation of the aio_context, *ctxp is filled in with the resulting
  1020. * handle. May fail with -EINVAL if *ctxp is not initialized,
  1021. * if the specified nr_events exceeds internal limits. May fail
  1022. * with -EAGAIN if the specified nr_events exceeds the user's limit
  1023. * of available events. May fail with -ENOMEM if insufficient kernel
  1024. * resources are available. May fail with -EFAULT if an invalid
  1025. * pointer is passed for ctxp. Will fail with -ENOSYS if not
  1026. * implemented.
  1027. */
  1028. SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
  1029. {
  1030. struct kioctx *ioctx = NULL;
  1031. unsigned long ctx;
  1032. long ret;
  1033. ret = get_user(ctx, ctxp);
  1034. if (unlikely(ret))
  1035. goto out;
  1036. ret = -EINVAL;
  1037. if (unlikely(ctx || nr_events == 0)) {
  1038. pr_debug("EINVAL: io_setup: ctx %lu nr_events %u\n",
  1039. ctx, nr_events);
  1040. goto out;
  1041. }
  1042. ioctx = ioctx_alloc(nr_events);
  1043. ret = PTR_ERR(ioctx);
  1044. if (!IS_ERR(ioctx)) {
  1045. ret = put_user(ioctx->user_id, ctxp);
  1046. if (ret)
  1047. kill_ioctx(current->mm, ioctx, NULL);
  1048. percpu_ref_put(&ioctx->users);
  1049. }
  1050. out:
  1051. return ret;
  1052. }
  1053. /* sys_io_destroy:
  1054. * Destroy the aio_context specified. May cancel any outstanding
  1055. * AIOs and block on completion. Will fail with -ENOSYS if not
  1056. * implemented. May fail with -EINVAL if the context pointed to
  1057. * is invalid.
  1058. */
  1059. SYSCALL_DEFINE1(io_destroy, aio_context_t, ctx)
  1060. {
  1061. struct kioctx *ioctx = lookup_ioctx(ctx);
  1062. if (likely(NULL != ioctx)) {
  1063. struct completion requests_done =
  1064. COMPLETION_INITIALIZER_ONSTACK(requests_done);
  1065. int ret;
  1066. /* Pass requests_done to kill_ioctx() where it can be set
  1067. * in a thread-safe way. If we try to set it here then we have
  1068. * a race condition if two io_destroy() called simultaneously.
  1069. */
  1070. ret = kill_ioctx(current->mm, ioctx, &requests_done);
  1071. percpu_ref_put(&ioctx->users);
  1072. /* Wait until all IO for the context are done. Otherwise kernel
  1073. * keep using user-space buffers even if user thinks the context
  1074. * is destroyed.
  1075. */
  1076. if (!ret)
  1077. wait_for_completion(&requests_done);
  1078. return ret;
  1079. }
  1080. pr_debug("EINVAL: io_destroy: invalid context id\n");
  1081. return -EINVAL;
  1082. }
  1083. typedef ssize_t (aio_rw_op)(struct kiocb *, const struct iovec *,
  1084. unsigned long, loff_t);
  1085. typedef ssize_t (rw_iter_op)(struct kiocb *, struct iov_iter *);
  1086. static ssize_t aio_setup_vectored_rw(struct kiocb *kiocb,
  1087. int rw, char __user *buf,
  1088. unsigned long *nr_segs,
  1089. struct iovec **iovec,
  1090. bool compat)
  1091. {
  1092. ssize_t ret;
  1093. *nr_segs = kiocb->ki_nbytes;
  1094. #ifdef CONFIG_COMPAT
  1095. if (compat)
  1096. ret = compat_rw_copy_check_uvector(rw,
  1097. (struct compat_iovec __user *)buf,
  1098. *nr_segs, UIO_FASTIOV, *iovec, iovec);
  1099. else
  1100. #endif
  1101. ret = rw_copy_check_uvector(rw,
  1102. (struct iovec __user *)buf,
  1103. *nr_segs, UIO_FASTIOV, *iovec, iovec);
  1104. if (ret < 0)
  1105. return ret;
  1106. /* ki_nbytes now reflect bytes instead of segs */
  1107. kiocb->ki_nbytes = ret;
  1108. return 0;
  1109. }
  1110. static ssize_t aio_setup_single_vector(struct kiocb *kiocb,
  1111. int rw, char __user *buf,
  1112. unsigned long *nr_segs,
  1113. struct iovec *iovec)
  1114. {
  1115. if (unlikely(!access_ok(!rw, buf, kiocb->ki_nbytes)))
  1116. return -EFAULT;
  1117. iovec->iov_base = buf;
  1118. iovec->iov_len = kiocb->ki_nbytes;
  1119. *nr_segs = 1;
  1120. return 0;
  1121. }
  1122. /*
  1123. * aio_run_iocb:
  1124. * Performs the initial checks and io submission.
  1125. */
  1126. static ssize_t aio_run_iocb(struct kiocb *req, unsigned opcode,
  1127. char __user *buf, bool compat)
  1128. {
  1129. struct file *file = req->ki_filp;
  1130. ssize_t ret;
  1131. unsigned long nr_segs;
  1132. int rw;
  1133. fmode_t mode;
  1134. aio_rw_op *rw_op;
  1135. rw_iter_op *iter_op;
  1136. struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
  1137. struct iov_iter iter;
  1138. switch (opcode) {
  1139. case IOCB_CMD_PREAD:
  1140. case IOCB_CMD_PREADV:
  1141. mode = FMODE_READ;
  1142. rw = READ;
  1143. rw_op = file->f_op->aio_read;
  1144. iter_op = file->f_op->read_iter;
  1145. goto rw_common;
  1146. case IOCB_CMD_PWRITE:
  1147. case IOCB_CMD_PWRITEV:
  1148. mode = FMODE_WRITE;
  1149. rw = WRITE;
  1150. rw_op = file->f_op->aio_write;
  1151. iter_op = file->f_op->write_iter;
  1152. goto rw_common;
  1153. rw_common:
  1154. if (unlikely(!(file->f_mode & mode)))
  1155. return -EBADF;
  1156. if (!rw_op && !iter_op)
  1157. return -EINVAL;
  1158. ret = (opcode == IOCB_CMD_PREADV ||
  1159. opcode == IOCB_CMD_PWRITEV)
  1160. ? aio_setup_vectored_rw(req, rw, buf, &nr_segs,
  1161. &iovec, compat)
  1162. : aio_setup_single_vector(req, rw, buf, &nr_segs,
  1163. iovec);
  1164. if (!ret)
  1165. ret = rw_verify_area(rw, file, &req->ki_pos, req->ki_nbytes);
  1166. if (ret < 0) {
  1167. if (iovec != inline_vecs)
  1168. kfree(iovec);
  1169. return ret;
  1170. }
  1171. req->ki_nbytes = ret;
  1172. /* XXX: move/kill - rw_verify_area()? */
  1173. /* This matches the pread()/pwrite() logic */
  1174. if (req->ki_pos < 0) {
  1175. ret = -EINVAL;
  1176. break;
  1177. }
  1178. if (rw == WRITE)
  1179. file_start_write(file);
  1180. if (iter_op) {
  1181. iov_iter_init(&iter, rw, iovec, nr_segs, req->ki_nbytes);
  1182. ret = iter_op(req, &iter);
  1183. } else {
  1184. ret = rw_op(req, iovec, nr_segs, req->ki_pos);
  1185. }
  1186. if (rw == WRITE)
  1187. file_end_write(file);
  1188. break;
  1189. case IOCB_CMD_FDSYNC:
  1190. if (!file->f_op->aio_fsync)
  1191. return -EINVAL;
  1192. ret = file->f_op->aio_fsync(req, 1);
  1193. break;
  1194. case IOCB_CMD_FSYNC:
  1195. if (!file->f_op->aio_fsync)
  1196. return -EINVAL;
  1197. ret = file->f_op->aio_fsync(req, 0);
  1198. break;
  1199. default:
  1200. pr_debug("EINVAL: no operation provided\n");
  1201. return -EINVAL;
  1202. }
  1203. if (iovec != inline_vecs)
  1204. kfree(iovec);
  1205. if (ret != -EIOCBQUEUED) {
  1206. /*
  1207. * There's no easy way to restart the syscall since other AIO's
  1208. * may be already running. Just fail this IO with EINTR.
  1209. */
  1210. if (unlikely(ret == -ERESTARTSYS || ret == -ERESTARTNOINTR ||
  1211. ret == -ERESTARTNOHAND ||
  1212. ret == -ERESTART_RESTARTBLOCK))
  1213. ret = -EINTR;
  1214. aio_complete(req, ret, 0);
  1215. }
  1216. return 0;
  1217. }
  1218. static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
  1219. struct iocb *iocb, bool compat)
  1220. {
  1221. struct kiocb *req;
  1222. ssize_t ret;
  1223. /* enforce forwards compatibility on users */
  1224. if (unlikely(iocb->aio_reserved1 || iocb->aio_reserved2)) {
  1225. pr_debug("EINVAL: reserve field set\n");
  1226. return -EINVAL;
  1227. }
  1228. /* prevent overflows */
  1229. if (unlikely(
  1230. (iocb->aio_buf != (unsigned long)iocb->aio_buf) ||
  1231. (iocb->aio_nbytes != (size_t)iocb->aio_nbytes) ||
  1232. ((ssize_t)iocb->aio_nbytes < 0)
  1233. )) {
  1234. pr_debug("EINVAL: io_submit: overflow check\n");
  1235. return -EINVAL;
  1236. }
  1237. req = aio_get_req(ctx);
  1238. if (unlikely(!req))
  1239. return -EAGAIN;
  1240. req->ki_filp = fget(iocb->aio_fildes);
  1241. if (unlikely(!req->ki_filp)) {
  1242. ret = -EBADF;
  1243. goto out_put_req;
  1244. }
  1245. if (iocb->aio_flags & IOCB_FLAG_RESFD) {
  1246. /*
  1247. * If the IOCB_FLAG_RESFD flag of aio_flags is set, get an
  1248. * instance of the file* now. The file descriptor must be
  1249. * an eventfd() fd, and will be signaled for each completed
  1250. * event using the eventfd_signal() function.
  1251. */
  1252. req->ki_eventfd = eventfd_ctx_fdget((int) iocb->aio_resfd);
  1253. if (IS_ERR(req->ki_eventfd)) {
  1254. ret = PTR_ERR(req->ki_eventfd);
  1255. req->ki_eventfd = NULL;
  1256. goto out_put_req;
  1257. }
  1258. }
  1259. ret = put_user(KIOCB_KEY, &user_iocb->aio_key);
  1260. if (unlikely(ret)) {
  1261. pr_debug("EFAULT: aio_key\n");
  1262. goto out_put_req;
  1263. }
  1264. req->ki_obj.user = user_iocb;
  1265. req->ki_user_data = iocb->aio_data;
  1266. req->ki_pos = iocb->aio_offset;
  1267. req->ki_nbytes = iocb->aio_nbytes;
  1268. ret = aio_run_iocb(req, iocb->aio_lio_opcode,
  1269. (char __user *)(unsigned long)iocb->aio_buf,
  1270. compat);
  1271. if (ret)
  1272. goto out_put_req;
  1273. return 0;
  1274. out_put_req:
  1275. put_reqs_available(ctx, 1);
  1276. percpu_ref_put(&ctx->reqs);
  1277. kiocb_free(req);
  1278. return ret;
  1279. }
  1280. long do_io_submit(aio_context_t ctx_id, long nr,
  1281. struct iocb __user *__user *iocbpp, bool compat)
  1282. {
  1283. struct kioctx *ctx;
  1284. long ret = 0;
  1285. int i = 0;
  1286. struct blk_plug plug;
  1287. if (unlikely(nr < 0))
  1288. return -EINVAL;
  1289. if (unlikely(nr > LONG_MAX/sizeof(*iocbpp)))
  1290. nr = LONG_MAX/sizeof(*iocbpp);
  1291. if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
  1292. return -EFAULT;
  1293. ctx = lookup_ioctx(ctx_id);
  1294. if (unlikely(!ctx)) {
  1295. pr_debug("EINVAL: invalid context id\n");
  1296. return -EINVAL;
  1297. }
  1298. blk_start_plug(&plug);
  1299. /*
  1300. * AKPM: should this return a partial result if some of the IOs were
  1301. * successfully submitted?
  1302. */
  1303. for (i=0; i<nr; i++) {
  1304. struct iocb __user *user_iocb;
  1305. struct iocb tmp;
  1306. if (unlikely(__get_user(user_iocb, iocbpp + i))) {
  1307. ret = -EFAULT;
  1308. break;
  1309. }
  1310. if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
  1311. ret = -EFAULT;
  1312. break;
  1313. }
  1314. ret = io_submit_one(ctx, user_iocb, &tmp, compat);
  1315. if (ret)
  1316. break;
  1317. }
  1318. blk_finish_plug(&plug);
  1319. percpu_ref_put(&ctx->users);
  1320. return i ? i : ret;
  1321. }
  1322. /* sys_io_submit:
  1323. * Queue the nr iocbs pointed to by iocbpp for processing. Returns
  1324. * the number of iocbs queued. May return -EINVAL if the aio_context
  1325. * specified by ctx_id is invalid, if nr is < 0, if the iocb at
  1326. * *iocbpp[0] is not properly initialized, if the operation specified
  1327. * is invalid for the file descriptor in the iocb. May fail with
  1328. * -EFAULT if any of the data structures point to invalid data. May
  1329. * fail with -EBADF if the file descriptor specified in the first
  1330. * iocb is invalid. May fail with -EAGAIN if insufficient resources
  1331. * are available to queue any iocbs. Will return 0 if nr is 0. Will
  1332. * fail with -ENOSYS if not implemented.
  1333. */
  1334. SYSCALL_DEFINE3(io_submit, aio_context_t, ctx_id, long, nr,
  1335. struct iocb __user * __user *, iocbpp)
  1336. {
  1337. return do_io_submit(ctx_id, nr, iocbpp, 0);
  1338. }
  1339. /* lookup_kiocb
  1340. * Finds a given iocb for cancellation.
  1341. */
  1342. static struct kiocb *lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb,
  1343. u32 key)
  1344. {
  1345. struct list_head *pos;
  1346. assert_spin_locked(&ctx->ctx_lock);
  1347. if (key != KIOCB_KEY)
  1348. return NULL;
  1349. /* TODO: use a hash or array, this sucks. */
  1350. list_for_each(pos, &ctx->active_reqs) {
  1351. struct kiocb *kiocb = list_kiocb(pos);
  1352. if (kiocb->ki_obj.user == iocb)
  1353. return kiocb;
  1354. }
  1355. return NULL;
  1356. }
  1357. /* sys_io_cancel:
  1358. * Attempts to cancel an iocb previously passed to io_submit. If
  1359. * the operation is successfully cancelled, the resulting event is
  1360. * copied into the memory pointed to by result without being placed
  1361. * into the completion queue and 0 is returned. May fail with
  1362. * -EFAULT if any of the data structures pointed to are invalid.
  1363. * May fail with -EINVAL if aio_context specified by ctx_id is
  1364. * invalid. May fail with -EAGAIN if the iocb specified was not
  1365. * cancelled. Will fail with -ENOSYS if not implemented.
  1366. */
  1367. SYSCALL_DEFINE3(io_cancel, aio_context_t, ctx_id, struct iocb __user *, iocb,
  1368. struct io_event __user *, result)
  1369. {
  1370. struct kioctx *ctx;
  1371. struct kiocb *kiocb;
  1372. u32 key;
  1373. int ret;
  1374. ret = get_user(key, &iocb->aio_key);
  1375. if (unlikely(ret))
  1376. return -EFAULT;
  1377. ctx = lookup_ioctx(ctx_id);
  1378. if (unlikely(!ctx))
  1379. return -EINVAL;
  1380. spin_lock_irq(&ctx->ctx_lock);
  1381. kiocb = lookup_kiocb(ctx, iocb, key);
  1382. if (kiocb)
  1383. ret = kiocb_cancel(kiocb);
  1384. else
  1385. ret = -EINVAL;
  1386. spin_unlock_irq(&ctx->ctx_lock);
  1387. if (!ret) {
  1388. /*
  1389. * The result argument is no longer used - the io_event is
  1390. * always delivered via the ring buffer. -EINPROGRESS indicates
  1391. * cancellation is progress:
  1392. */
  1393. ret = -EINPROGRESS;
  1394. }
  1395. percpu_ref_put(&ctx->users);
  1396. return ret;
  1397. }
  1398. /* io_getevents:
  1399. * Attempts to read at least min_nr events and up to nr events from
  1400. * the completion queue for the aio_context specified by ctx_id. If
  1401. * it succeeds, the number of read events is returned. May fail with
  1402. * -EINVAL if ctx_id is invalid, if min_nr is out of range, if nr is
  1403. * out of range, if timeout is out of range. May fail with -EFAULT
  1404. * if any of the memory specified is invalid. May return 0 or
  1405. * < min_nr if the timeout specified by timeout has elapsed
  1406. * before sufficient events are available, where timeout == NULL
  1407. * specifies an infinite timeout. Note that the timeout pointed to by
  1408. * timeout is relative. Will fail with -ENOSYS if not implemented.
  1409. */
  1410. SYSCALL_DEFINE5(io_getevents, aio_context_t, ctx_id,
  1411. long, min_nr,
  1412. long, nr,
  1413. struct io_event __user *, events,
  1414. struct timespec __user *, timeout)
  1415. {
  1416. struct kioctx *ioctx = lookup_ioctx(ctx_id);
  1417. long ret = -EINVAL;
  1418. if (likely(ioctx)) {
  1419. if (likely(min_nr <= nr && min_nr >= 0))
  1420. ret = read_events(ioctx, min_nr, nr, events, timeout);
  1421. percpu_ref_put(&ioctx->users);
  1422. }
  1423. return ret;
  1424. }