aio.c 44 KB

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