aio.c 37 KB

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