aio.c 39 KB

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