aio.c 38 KB

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