aio.c 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635
  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. file->private_data = ctx;
  160. return file;
  161. }
  162. static struct dentry *aio_mount(struct file_system_type *fs_type,
  163. int flags, const char *dev_name, void *data)
  164. {
  165. static const struct dentry_operations ops = {
  166. .d_dname = simple_dname,
  167. };
  168. return mount_pseudo(fs_type, "aio:", NULL, &ops, 0xa10a10a1);
  169. }
  170. /* aio_setup
  171. * Creates the slab caches used by the aio routines, panic on
  172. * failure as this is done early during the boot sequence.
  173. */
  174. static int __init aio_setup(void)
  175. {
  176. static struct file_system_type aio_fs = {
  177. .name = "aio",
  178. .mount = aio_mount,
  179. .kill_sb = kill_anon_super,
  180. };
  181. aio_mnt = kern_mount(&aio_fs);
  182. if (IS_ERR(aio_mnt))
  183. panic("Failed to create aio fs mount.");
  184. kiocb_cachep = KMEM_CACHE(kiocb, SLAB_HWCACHE_ALIGN|SLAB_PANIC);
  185. kioctx_cachep = KMEM_CACHE(kioctx,SLAB_HWCACHE_ALIGN|SLAB_PANIC);
  186. pr_debug("sizeof(struct page) = %zu\n", sizeof(struct page));
  187. return 0;
  188. }
  189. __initcall(aio_setup);
  190. static void put_aio_ring_file(struct kioctx *ctx)
  191. {
  192. struct file *aio_ring_file = ctx->aio_ring_file;
  193. if (aio_ring_file) {
  194. truncate_setsize(aio_ring_file->f_inode, 0);
  195. /* Prevent further access to the kioctx from migratepages */
  196. spin_lock(&aio_ring_file->f_inode->i_mapping->private_lock);
  197. aio_ring_file->f_inode->i_mapping->private_data = NULL;
  198. ctx->aio_ring_file = NULL;
  199. spin_unlock(&aio_ring_file->f_inode->i_mapping->private_lock);
  200. fput(aio_ring_file);
  201. }
  202. }
  203. static void aio_free_ring(struct kioctx *ctx)
  204. {
  205. int i;
  206. /* Disconnect the kiotx from the ring file. This prevents future
  207. * accesses to the kioctx from page migration.
  208. */
  209. put_aio_ring_file(ctx);
  210. for (i = 0; i < ctx->nr_pages; i++) {
  211. struct page *page;
  212. pr_debug("pid(%d) [%d] page->count=%d\n", current->pid, i,
  213. page_count(ctx->ring_pages[i]));
  214. page = ctx->ring_pages[i];
  215. if (!page)
  216. continue;
  217. ctx->ring_pages[i] = NULL;
  218. put_page(page);
  219. }
  220. if (ctx->ring_pages && ctx->ring_pages != ctx->internal_pages) {
  221. kfree(ctx->ring_pages);
  222. ctx->ring_pages = NULL;
  223. }
  224. }
  225. static int aio_ring_mmap(struct file *file, struct vm_area_struct *vma)
  226. {
  227. vma->vm_ops = &generic_file_vm_ops;
  228. return 0;
  229. }
  230. static const struct file_operations aio_ring_fops = {
  231. .mmap = aio_ring_mmap,
  232. };
  233. static int aio_set_page_dirty(struct page *page)
  234. {
  235. return 0;
  236. }
  237. #if IS_ENABLED(CONFIG_MIGRATION)
  238. static int aio_migratepage(struct address_space *mapping, struct page *new,
  239. struct page *old, enum migrate_mode mode)
  240. {
  241. struct kioctx *ctx;
  242. unsigned long flags;
  243. pgoff_t idx;
  244. int rc;
  245. rc = 0;
  246. /* mapping->private_lock here protects against the kioctx teardown. */
  247. spin_lock(&mapping->private_lock);
  248. ctx = mapping->private_data;
  249. if (!ctx) {
  250. rc = -EINVAL;
  251. goto out;
  252. }
  253. /* The ring_lock mutex. The prevents aio_read_events() from writing
  254. * to the ring's head, and prevents page migration from mucking in
  255. * a partially initialized kiotx.
  256. */
  257. if (!mutex_trylock(&ctx->ring_lock)) {
  258. rc = -EAGAIN;
  259. goto out;
  260. }
  261. idx = old->index;
  262. if (idx < (pgoff_t)ctx->nr_pages) {
  263. /* Make sure the old page hasn't already been changed */
  264. if (ctx->ring_pages[idx] != old)
  265. rc = -EAGAIN;
  266. } else
  267. rc = -EINVAL;
  268. if (rc != 0)
  269. goto out_unlock;
  270. /* Writeback must be complete */
  271. BUG_ON(PageWriteback(old));
  272. get_page(new);
  273. rc = migrate_page_move_mapping(mapping, new, old, NULL, mode, 1);
  274. if (rc != MIGRATEPAGE_SUCCESS) {
  275. put_page(new);
  276. goto out_unlock;
  277. }
  278. /* Take completion_lock to prevent other writes to the ring buffer
  279. * while the old page is copied to the new. This prevents new
  280. * events from being lost.
  281. */
  282. spin_lock_irqsave(&ctx->completion_lock, flags);
  283. migrate_page_copy(new, old);
  284. BUG_ON(ctx->ring_pages[idx] != old);
  285. ctx->ring_pages[idx] = new;
  286. spin_unlock_irqrestore(&ctx->completion_lock, flags);
  287. /* The old page is no longer accessible. */
  288. put_page(old);
  289. out_unlock:
  290. mutex_unlock(&ctx->ring_lock);
  291. out:
  292. spin_unlock(&mapping->private_lock);
  293. return rc;
  294. }
  295. #endif
  296. static const struct address_space_operations aio_ctx_aops = {
  297. .set_page_dirty = aio_set_page_dirty,
  298. #if IS_ENABLED(CONFIG_MIGRATION)
  299. .migratepage = aio_migratepage,
  300. #endif
  301. };
  302. static int aio_setup_ring(struct kioctx *ctx)
  303. {
  304. struct aio_ring *ring;
  305. unsigned nr_events = ctx->max_reqs;
  306. struct mm_struct *mm = current->mm;
  307. unsigned long size, unused;
  308. int nr_pages;
  309. int i;
  310. struct file *file;
  311. /* Compensate for the ring buffer's head/tail overlap entry */
  312. nr_events += 2; /* 1 is required, 2 for good luck */
  313. size = sizeof(struct aio_ring);
  314. size += sizeof(struct io_event) * nr_events;
  315. nr_pages = PFN_UP(size);
  316. if (nr_pages < 0)
  317. return -EINVAL;
  318. file = aio_private_file(ctx, nr_pages);
  319. if (IS_ERR(file)) {
  320. ctx->aio_ring_file = NULL;
  321. return -ENOMEM;
  322. }
  323. ctx->aio_ring_file = file;
  324. nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring))
  325. / sizeof(struct io_event);
  326. ctx->ring_pages = ctx->internal_pages;
  327. if (nr_pages > AIO_RING_PAGES) {
  328. ctx->ring_pages = kcalloc(nr_pages, sizeof(struct page *),
  329. GFP_KERNEL);
  330. if (!ctx->ring_pages) {
  331. put_aio_ring_file(ctx);
  332. return -ENOMEM;
  333. }
  334. }
  335. for (i = 0; i < nr_pages; i++) {
  336. struct page *page;
  337. page = find_or_create_page(file->f_inode->i_mapping,
  338. i, GFP_HIGHUSER | __GFP_ZERO);
  339. if (!page)
  340. break;
  341. pr_debug("pid(%d) page[%d]->count=%d\n",
  342. current->pid, i, page_count(page));
  343. SetPageUptodate(page);
  344. SetPageDirty(page);
  345. unlock_page(page);
  346. ctx->ring_pages[i] = page;
  347. }
  348. ctx->nr_pages = i;
  349. if (unlikely(i != nr_pages)) {
  350. aio_free_ring(ctx);
  351. return -ENOMEM;
  352. }
  353. ctx->mmap_size = nr_pages * PAGE_SIZE;
  354. pr_debug("attempting mmap of %lu bytes\n", ctx->mmap_size);
  355. down_write(&mm->mmap_sem);
  356. ctx->mmap_base = do_mmap_pgoff(ctx->aio_ring_file, 0, ctx->mmap_size,
  357. PROT_READ | PROT_WRITE,
  358. MAP_SHARED, 0, &unused);
  359. up_write(&mm->mmap_sem);
  360. if (IS_ERR((void *)ctx->mmap_base)) {
  361. ctx->mmap_size = 0;
  362. aio_free_ring(ctx);
  363. return -ENOMEM;
  364. }
  365. pr_debug("mmap address: 0x%08lx\n", ctx->mmap_base);
  366. ctx->user_id = ctx->mmap_base;
  367. ctx->nr_events = nr_events; /* trusted copy */
  368. ring = kmap_atomic(ctx->ring_pages[0]);
  369. ring->nr = nr_events; /* user copy */
  370. ring->id = ~0U;
  371. ring->head = ring->tail = 0;
  372. ring->magic = AIO_RING_MAGIC;
  373. ring->compat_features = AIO_RING_COMPAT_FEATURES;
  374. ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
  375. ring->header_length = sizeof(struct aio_ring);
  376. kunmap_atomic(ring);
  377. flush_dcache_page(ctx->ring_pages[0]);
  378. return 0;
  379. }
  380. #define AIO_EVENTS_PER_PAGE (PAGE_SIZE / sizeof(struct io_event))
  381. #define AIO_EVENTS_FIRST_PAGE ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
  382. #define AIO_EVENTS_OFFSET (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
  383. void kiocb_set_cancel_fn(struct kiocb *req, kiocb_cancel_fn *cancel)
  384. {
  385. struct kioctx *ctx = req->ki_ctx;
  386. unsigned long flags;
  387. spin_lock_irqsave(&ctx->ctx_lock, flags);
  388. if (!req->ki_list.next)
  389. list_add(&req->ki_list, &ctx->active_reqs);
  390. req->ki_cancel = cancel;
  391. spin_unlock_irqrestore(&ctx->ctx_lock, flags);
  392. }
  393. EXPORT_SYMBOL(kiocb_set_cancel_fn);
  394. static int kiocb_cancel(struct kioctx *ctx, struct kiocb *kiocb)
  395. {
  396. kiocb_cancel_fn *old, *cancel;
  397. /*
  398. * Don't want to set kiocb->ki_cancel = KIOCB_CANCELLED unless it
  399. * actually has a cancel function, hence the cmpxchg()
  400. */
  401. cancel = ACCESS_ONCE(kiocb->ki_cancel);
  402. do {
  403. if (!cancel || cancel == KIOCB_CANCELLED)
  404. return -EINVAL;
  405. old = cancel;
  406. cancel = cmpxchg(&kiocb->ki_cancel, old, KIOCB_CANCELLED);
  407. } while (cancel != old);
  408. return cancel(kiocb);
  409. }
  410. static void free_ioctx(struct work_struct *work)
  411. {
  412. struct kioctx *ctx = container_of(work, struct kioctx, free_work);
  413. pr_debug("freeing %p\n", ctx);
  414. aio_free_ring(ctx);
  415. free_percpu(ctx->cpu);
  416. kmem_cache_free(kioctx_cachep, ctx);
  417. }
  418. static void free_ioctx_reqs(struct percpu_ref *ref)
  419. {
  420. struct kioctx *ctx = container_of(ref, struct kioctx, reqs);
  421. /* At this point we know that there are no any in-flight requests */
  422. if (ctx->requests_done)
  423. complete(ctx->requests_done);
  424. INIT_WORK(&ctx->free_work, free_ioctx);
  425. schedule_work(&ctx->free_work);
  426. }
  427. /*
  428. * When this function runs, the kioctx has been removed from the "hash table"
  429. * and ctx->users has dropped to 0, so we know no more kiocbs can be submitted -
  430. * now it's safe to cancel any that need to be.
  431. */
  432. static void free_ioctx_users(struct percpu_ref *ref)
  433. {
  434. struct kioctx *ctx = container_of(ref, struct kioctx, users);
  435. struct kiocb *req;
  436. spin_lock_irq(&ctx->ctx_lock);
  437. while (!list_empty(&ctx->active_reqs)) {
  438. req = list_first_entry(&ctx->active_reqs,
  439. struct kiocb, ki_list);
  440. list_del_init(&req->ki_list);
  441. kiocb_cancel(ctx, req);
  442. }
  443. spin_unlock_irq(&ctx->ctx_lock);
  444. percpu_ref_kill(&ctx->reqs);
  445. percpu_ref_put(&ctx->reqs);
  446. }
  447. static int ioctx_add_table(struct kioctx *ctx, struct mm_struct *mm)
  448. {
  449. unsigned i, new_nr;
  450. struct kioctx_table *table, *old;
  451. struct aio_ring *ring;
  452. spin_lock(&mm->ioctx_lock);
  453. rcu_read_lock();
  454. table = rcu_dereference(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. rcu_read_unlock();
  462. spin_unlock(&mm->ioctx_lock);
  463. /* While kioctx setup is in progress,
  464. * we are protected from page migration
  465. * changes ring_pages by ->ring_lock.
  466. */
  467. ring = kmap_atomic(ctx->ring_pages[0]);
  468. ring->id = ctx->id;
  469. kunmap_atomic(ring);
  470. return 0;
  471. }
  472. new_nr = (table ? table->nr : 1) * 4;
  473. rcu_read_unlock();
  474. spin_unlock(&mm->ioctx_lock);
  475. table = kzalloc(sizeof(*table) + sizeof(struct kioctx *) *
  476. new_nr, GFP_KERNEL);
  477. if (!table)
  478. return -ENOMEM;
  479. table->nr = new_nr;
  480. spin_lock(&mm->ioctx_lock);
  481. rcu_read_lock();
  482. old = rcu_dereference(mm->ioctx_table);
  483. if (!old) {
  484. rcu_assign_pointer(mm->ioctx_table, table);
  485. } else if (table->nr > old->nr) {
  486. memcpy(table->table, old->table,
  487. old->nr * sizeof(struct kioctx *));
  488. rcu_assign_pointer(mm->ioctx_table, table);
  489. kfree_rcu(old, rcu);
  490. } else {
  491. kfree(table);
  492. table = old;
  493. }
  494. }
  495. }
  496. static void aio_nr_sub(unsigned nr)
  497. {
  498. spin_lock(&aio_nr_lock);
  499. if (WARN_ON(aio_nr - nr > aio_nr))
  500. aio_nr = 0;
  501. else
  502. aio_nr -= nr;
  503. spin_unlock(&aio_nr_lock);
  504. }
  505. /* ioctx_alloc
  506. * Allocates and initializes an ioctx. Returns an ERR_PTR if it failed.
  507. */
  508. static struct kioctx *ioctx_alloc(unsigned nr_events)
  509. {
  510. struct mm_struct *mm = current->mm;
  511. struct kioctx *ctx;
  512. int err = -ENOMEM;
  513. /*
  514. * We keep track of the number of available ringbuffer slots, to prevent
  515. * overflow (reqs_available), and we also use percpu counters for this.
  516. *
  517. * So since up to half the slots might be on other cpu's percpu counters
  518. * and unavailable, double nr_events so userspace sees what they
  519. * expected: additionally, we move req_batch slots to/from percpu
  520. * counters at a time, so make sure that isn't 0:
  521. */
  522. nr_events = max(nr_events, num_possible_cpus() * 4);
  523. nr_events *= 2;
  524. /* Prevent overflows */
  525. if ((nr_events > (0x10000000U / sizeof(struct io_event))) ||
  526. (nr_events > (0x10000000U / sizeof(struct kiocb)))) {
  527. pr_debug("ENOMEM: nr_events too high\n");
  528. return ERR_PTR(-EINVAL);
  529. }
  530. if (!nr_events || (unsigned long)nr_events > (aio_max_nr * 2UL))
  531. return ERR_PTR(-EAGAIN);
  532. ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
  533. if (!ctx)
  534. return ERR_PTR(-ENOMEM);
  535. ctx->max_reqs = nr_events;
  536. spin_lock_init(&ctx->ctx_lock);
  537. spin_lock_init(&ctx->completion_lock);
  538. mutex_init(&ctx->ring_lock);
  539. /* Protect against page migration throughout kiotx setup by keeping
  540. * the ring_lock mutex held until setup is complete. */
  541. mutex_lock(&ctx->ring_lock);
  542. init_waitqueue_head(&ctx->wait);
  543. INIT_LIST_HEAD(&ctx->active_reqs);
  544. if (percpu_ref_init(&ctx->users, free_ioctx_users))
  545. goto err;
  546. if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs))
  547. goto err;
  548. ctx->cpu = alloc_percpu(struct kioctx_cpu);
  549. if (!ctx->cpu)
  550. goto err;
  551. err = aio_setup_ring(ctx);
  552. if (err < 0)
  553. goto err;
  554. atomic_set(&ctx->reqs_available, ctx->nr_events - 1);
  555. ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4);
  556. if (ctx->req_batch < 1)
  557. ctx->req_batch = 1;
  558. /* limit the number of system wide aios */
  559. spin_lock(&aio_nr_lock);
  560. if (aio_nr + nr_events > (aio_max_nr * 2UL) ||
  561. aio_nr + nr_events < aio_nr) {
  562. spin_unlock(&aio_nr_lock);
  563. err = -EAGAIN;
  564. goto err_ctx;
  565. }
  566. aio_nr += ctx->max_reqs;
  567. spin_unlock(&aio_nr_lock);
  568. percpu_ref_get(&ctx->users); /* io_setup() will drop this ref */
  569. percpu_ref_get(&ctx->reqs); /* free_ioctx_users() will drop this */
  570. err = ioctx_add_table(ctx, mm);
  571. if (err)
  572. goto err_cleanup;
  573. /* Release the ring_lock mutex now that all setup is complete. */
  574. mutex_unlock(&ctx->ring_lock);
  575. pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
  576. ctx, ctx->user_id, mm, ctx->nr_events);
  577. return ctx;
  578. err_cleanup:
  579. aio_nr_sub(ctx->max_reqs);
  580. err_ctx:
  581. aio_free_ring(ctx);
  582. err:
  583. mutex_unlock(&ctx->ring_lock);
  584. free_percpu(ctx->cpu);
  585. free_percpu(ctx->reqs.pcpu_count);
  586. free_percpu(ctx->users.pcpu_count);
  587. kmem_cache_free(kioctx_cachep, ctx);
  588. pr_debug("error allocating ioctx %d\n", err);
  589. return ERR_PTR(err);
  590. }
  591. /* kill_ioctx
  592. * Cancels all outstanding aio requests on an aio context. Used
  593. * when the processes owning a context have all exited to encourage
  594. * the rapid destruction of the kioctx.
  595. */
  596. static void kill_ioctx(struct mm_struct *mm, struct kioctx *ctx,
  597. struct completion *requests_done)
  598. {
  599. if (!atomic_xchg(&ctx->dead, 1)) {
  600. struct kioctx_table *table;
  601. spin_lock(&mm->ioctx_lock);
  602. rcu_read_lock();
  603. table = rcu_dereference(mm->ioctx_table);
  604. WARN_ON(ctx != table->table[ctx->id]);
  605. table->table[ctx->id] = NULL;
  606. rcu_read_unlock();
  607. spin_unlock(&mm->ioctx_lock);
  608. /* percpu_ref_kill() will do the necessary call_rcu() */
  609. wake_up_all(&ctx->wait);
  610. /*
  611. * It'd be more correct to do this in free_ioctx(), after all
  612. * the outstanding kiocbs have finished - but by then io_destroy
  613. * has already returned, so io_setup() could potentially return
  614. * -EAGAIN with no ioctxs actually in use (as far as userspace
  615. * could tell).
  616. */
  617. aio_nr_sub(ctx->max_reqs);
  618. if (ctx->mmap_size)
  619. vm_munmap(ctx->mmap_base, ctx->mmap_size);
  620. ctx->requests_done = requests_done;
  621. percpu_ref_kill(&ctx->users);
  622. } else {
  623. if (requests_done)
  624. complete(requests_done);
  625. }
  626. }
  627. /* wait_on_sync_kiocb:
  628. * Waits on the given sync kiocb to complete.
  629. */
  630. ssize_t wait_on_sync_kiocb(struct kiocb *req)
  631. {
  632. while (!req->ki_ctx) {
  633. set_current_state(TASK_UNINTERRUPTIBLE);
  634. if (req->ki_ctx)
  635. break;
  636. io_schedule();
  637. }
  638. __set_current_state(TASK_RUNNING);
  639. return req->ki_user_data;
  640. }
  641. EXPORT_SYMBOL(wait_on_sync_kiocb);
  642. /*
  643. * exit_aio: called when the last user of mm goes away. At this point, there is
  644. * no way for any new requests to be submited or any of the io_* syscalls to be
  645. * called on the context.
  646. *
  647. * There may be outstanding kiocbs, but free_ioctx() will explicitly wait on
  648. * them.
  649. */
  650. void exit_aio(struct mm_struct *mm)
  651. {
  652. struct kioctx_table *table;
  653. struct kioctx *ctx;
  654. unsigned i = 0;
  655. while (1) {
  656. rcu_read_lock();
  657. table = rcu_dereference(mm->ioctx_table);
  658. do {
  659. if (!table || i >= table->nr) {
  660. rcu_read_unlock();
  661. rcu_assign_pointer(mm->ioctx_table, NULL);
  662. if (table)
  663. kfree(table);
  664. return;
  665. }
  666. ctx = table->table[i++];
  667. } while (!ctx);
  668. rcu_read_unlock();
  669. /*
  670. * We don't need to bother with munmap() here -
  671. * exit_mmap(mm) is coming and it'll unmap everything.
  672. * Since aio_free_ring() uses non-zero ->mmap_size
  673. * as indicator that it needs to unmap the area,
  674. * just set it to 0; aio_free_ring() is the only
  675. * place that uses ->mmap_size, so it's safe.
  676. */
  677. ctx->mmap_size = 0;
  678. kill_ioctx(mm, ctx, NULL);
  679. }
  680. }
  681. static void put_reqs_available(struct kioctx *ctx, unsigned nr)
  682. {
  683. struct kioctx_cpu *kcpu;
  684. preempt_disable();
  685. kcpu = this_cpu_ptr(ctx->cpu);
  686. kcpu->reqs_available += nr;
  687. while (kcpu->reqs_available >= ctx->req_batch * 2) {
  688. kcpu->reqs_available -= ctx->req_batch;
  689. atomic_add(ctx->req_batch, &ctx->reqs_available);
  690. }
  691. preempt_enable();
  692. }
  693. static bool get_reqs_available(struct kioctx *ctx)
  694. {
  695. struct kioctx_cpu *kcpu;
  696. bool ret = false;
  697. preempt_disable();
  698. kcpu = this_cpu_ptr(ctx->cpu);
  699. if (!kcpu->reqs_available) {
  700. int old, avail = atomic_read(&ctx->reqs_available);
  701. do {
  702. if (avail < ctx->req_batch)
  703. goto out;
  704. old = avail;
  705. avail = atomic_cmpxchg(&ctx->reqs_available,
  706. avail, avail - ctx->req_batch);
  707. } while (avail != old);
  708. kcpu->reqs_available += ctx->req_batch;
  709. }
  710. ret = true;
  711. kcpu->reqs_available--;
  712. out:
  713. preempt_enable();
  714. return ret;
  715. }
  716. /* aio_get_req
  717. * Allocate a slot for an aio request.
  718. * Returns NULL if no requests are free.
  719. */
  720. static inline struct kiocb *aio_get_req(struct kioctx *ctx)
  721. {
  722. struct kiocb *req;
  723. if (!get_reqs_available(ctx))
  724. return NULL;
  725. req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL|__GFP_ZERO);
  726. if (unlikely(!req))
  727. goto out_put;
  728. percpu_ref_get(&ctx->reqs);
  729. req->ki_ctx = ctx;
  730. return req;
  731. out_put:
  732. put_reqs_available(ctx, 1);
  733. return NULL;
  734. }
  735. static void kiocb_free(struct kiocb *req)
  736. {
  737. if (req->ki_filp)
  738. fput(req->ki_filp);
  739. if (req->ki_eventfd != NULL)
  740. eventfd_ctx_put(req->ki_eventfd);
  741. kmem_cache_free(kiocb_cachep, req);
  742. }
  743. static struct kioctx *lookup_ioctx(unsigned long ctx_id)
  744. {
  745. struct aio_ring __user *ring = (void __user *)ctx_id;
  746. struct mm_struct *mm = current->mm;
  747. struct kioctx *ctx, *ret = NULL;
  748. struct kioctx_table *table;
  749. unsigned id;
  750. if (get_user(id, &ring->id))
  751. return NULL;
  752. rcu_read_lock();
  753. table = rcu_dereference(mm->ioctx_table);
  754. if (!table || id >= table->nr)
  755. goto out;
  756. ctx = table->table[id];
  757. if (ctx && ctx->user_id == ctx_id) {
  758. percpu_ref_get(&ctx->users);
  759. ret = ctx;
  760. }
  761. out:
  762. rcu_read_unlock();
  763. return ret;
  764. }
  765. /* aio_complete
  766. * Called when the io request on the given iocb is complete.
  767. */
  768. void aio_complete(struct kiocb *iocb, long res, long res2)
  769. {
  770. struct kioctx *ctx = iocb->ki_ctx;
  771. struct aio_ring *ring;
  772. struct io_event *ev_page, *event;
  773. unsigned long flags;
  774. unsigned tail, pos;
  775. /*
  776. * Special case handling for sync iocbs:
  777. * - events go directly into the iocb for fast handling
  778. * - the sync task with the iocb in its stack holds the single iocb
  779. * ref, no other paths have a way to get another ref
  780. * - the sync task helpfully left a reference to itself in the iocb
  781. */
  782. if (is_sync_kiocb(iocb)) {
  783. iocb->ki_user_data = res;
  784. smp_wmb();
  785. iocb->ki_ctx = ERR_PTR(-EXDEV);
  786. wake_up_process(iocb->ki_obj.tsk);
  787. return;
  788. }
  789. if (iocb->ki_list.next) {
  790. unsigned long flags;
  791. spin_lock_irqsave(&ctx->ctx_lock, flags);
  792. list_del(&iocb->ki_list);
  793. spin_unlock_irqrestore(&ctx->ctx_lock, flags);
  794. }
  795. /*
  796. * Add a completion event to the ring buffer. Must be done holding
  797. * ctx->completion_lock to prevent other code from messing with the tail
  798. * pointer since we might be called from irq context.
  799. */
  800. spin_lock_irqsave(&ctx->completion_lock, flags);
  801. tail = ctx->tail;
  802. pos = tail + AIO_EVENTS_OFFSET;
  803. if (++tail >= ctx->nr_events)
  804. tail = 0;
  805. ev_page = kmap_atomic(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
  806. event = ev_page + pos % AIO_EVENTS_PER_PAGE;
  807. event->obj = (u64)(unsigned long)iocb->ki_obj.user;
  808. event->data = iocb->ki_user_data;
  809. event->res = res;
  810. event->res2 = res2;
  811. kunmap_atomic(ev_page);
  812. flush_dcache_page(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
  813. pr_debug("%p[%u]: %p: %p %Lx %lx %lx\n",
  814. ctx, tail, iocb, iocb->ki_obj.user, iocb->ki_user_data,
  815. res, res2);
  816. /* after flagging the request as done, we
  817. * must never even look at it again
  818. */
  819. smp_wmb(); /* make event visible before updating tail */
  820. ctx->tail = tail;
  821. ring = kmap_atomic(ctx->ring_pages[0]);
  822. ring->tail = tail;
  823. kunmap_atomic(ring);
  824. flush_dcache_page(ctx->ring_pages[0]);
  825. spin_unlock_irqrestore(&ctx->completion_lock, flags);
  826. pr_debug("added to ring %p at [%u]\n", iocb, tail);
  827. /*
  828. * Check if the user asked us to deliver the result through an
  829. * eventfd. The eventfd_signal() function is safe to be called
  830. * from IRQ context.
  831. */
  832. if (iocb->ki_eventfd != NULL)
  833. eventfd_signal(iocb->ki_eventfd, 1);
  834. /* everything turned out well, dispose of the aiocb. */
  835. kiocb_free(iocb);
  836. /*
  837. * We have to order our ring_info tail store above and test
  838. * of the wait list below outside the wait lock. This is
  839. * like in wake_up_bit() where clearing a bit has to be
  840. * ordered with the unlocked test.
  841. */
  842. smp_mb();
  843. if (waitqueue_active(&ctx->wait))
  844. wake_up(&ctx->wait);
  845. percpu_ref_put(&ctx->reqs);
  846. }
  847. EXPORT_SYMBOL(aio_complete);
  848. /* aio_read_events
  849. * Pull an event off of the ioctx's event ring. Returns the number of
  850. * events fetched
  851. */
  852. static long aio_read_events_ring(struct kioctx *ctx,
  853. struct io_event __user *event, long nr)
  854. {
  855. struct aio_ring *ring;
  856. unsigned head, tail, pos;
  857. long ret = 0;
  858. int copy_ret;
  859. mutex_lock(&ctx->ring_lock);
  860. /* Access to ->ring_pages here is protected by ctx->ring_lock. */
  861. ring = kmap_atomic(ctx->ring_pages[0]);
  862. head = ring->head;
  863. tail = ring->tail;
  864. kunmap_atomic(ring);
  865. pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
  866. if (head == tail)
  867. goto out;
  868. while (ret < nr) {
  869. long avail;
  870. struct io_event *ev;
  871. struct page *page;
  872. avail = (head <= tail ? tail : ctx->nr_events) - head;
  873. if (head == tail)
  874. break;
  875. avail = min(avail, nr - ret);
  876. avail = min_t(long, avail, AIO_EVENTS_PER_PAGE -
  877. ((head + AIO_EVENTS_OFFSET) % AIO_EVENTS_PER_PAGE));
  878. pos = head + AIO_EVENTS_OFFSET;
  879. page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
  880. pos %= AIO_EVENTS_PER_PAGE;
  881. ev = kmap(page);
  882. copy_ret = copy_to_user(event + ret, ev + pos,
  883. sizeof(*ev) * avail);
  884. kunmap(page);
  885. if (unlikely(copy_ret)) {
  886. ret = -EFAULT;
  887. goto out;
  888. }
  889. ret += avail;
  890. head += avail;
  891. head %= ctx->nr_events;
  892. }
  893. ring = kmap_atomic(ctx->ring_pages[0]);
  894. ring->head = head;
  895. kunmap_atomic(ring);
  896. flush_dcache_page(ctx->ring_pages[0]);
  897. pr_debug("%li h%u t%u\n", ret, head, tail);
  898. put_reqs_available(ctx, ret);
  899. out:
  900. mutex_unlock(&ctx->ring_lock);
  901. return ret;
  902. }
  903. static bool aio_read_events(struct kioctx *ctx, long min_nr, long nr,
  904. struct io_event __user *event, long *i)
  905. {
  906. long ret = aio_read_events_ring(ctx, event + *i, nr - *i);
  907. if (ret > 0)
  908. *i += ret;
  909. if (unlikely(atomic_read(&ctx->dead)))
  910. ret = -EINVAL;
  911. if (!*i)
  912. *i = ret;
  913. return ret < 0 || *i >= min_nr;
  914. }
  915. static long read_events(struct kioctx *ctx, long min_nr, long nr,
  916. struct io_event __user *event,
  917. struct timespec __user *timeout)
  918. {
  919. ktime_t until = { .tv64 = KTIME_MAX };
  920. long ret = 0;
  921. if (timeout) {
  922. struct timespec ts;
  923. if (unlikely(copy_from_user(&ts, timeout, sizeof(ts))))
  924. return -EFAULT;
  925. until = timespec_to_ktime(ts);
  926. }
  927. /*
  928. * Note that aio_read_events() is being called as the conditional - i.e.
  929. * we're calling it after prepare_to_wait() has set task state to
  930. * TASK_INTERRUPTIBLE.
  931. *
  932. * But aio_read_events() can block, and if it blocks it's going to flip
  933. * the task state back to TASK_RUNNING.
  934. *
  935. * This should be ok, provided it doesn't flip the state back to
  936. * TASK_RUNNING and return 0 too much - that causes us to spin. That
  937. * will only happen if the mutex_lock() call blocks, and we then find
  938. * the ringbuffer empty. So in practice we should be ok, but it's
  939. * something to be aware of when touching this code.
  940. */
  941. wait_event_interruptible_hrtimeout(ctx->wait,
  942. aio_read_events(ctx, min_nr, nr, event, &ret), until);
  943. if (!ret && signal_pending(current))
  944. ret = -EINTR;
  945. return ret;
  946. }
  947. /* sys_io_setup:
  948. * Create an aio_context capable of receiving at least nr_events.
  949. * ctxp must not point to an aio_context that already exists, and
  950. * must be initialized to 0 prior to the call. On successful
  951. * creation of the aio_context, *ctxp is filled in with the resulting
  952. * handle. May fail with -EINVAL if *ctxp is not initialized,
  953. * if the specified nr_events exceeds internal limits. May fail
  954. * with -EAGAIN if the specified nr_events exceeds the user's limit
  955. * of available events. May fail with -ENOMEM if insufficient kernel
  956. * resources are available. May fail with -EFAULT if an invalid
  957. * pointer is passed for ctxp. Will fail with -ENOSYS if not
  958. * implemented.
  959. */
  960. SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
  961. {
  962. struct kioctx *ioctx = NULL;
  963. unsigned long ctx;
  964. long ret;
  965. ret = get_user(ctx, ctxp);
  966. if (unlikely(ret))
  967. goto out;
  968. ret = -EINVAL;
  969. if (unlikely(ctx || nr_events == 0)) {
  970. pr_debug("EINVAL: io_setup: ctx %lu nr_events %u\n",
  971. ctx, nr_events);
  972. goto out;
  973. }
  974. ioctx = ioctx_alloc(nr_events);
  975. ret = PTR_ERR(ioctx);
  976. if (!IS_ERR(ioctx)) {
  977. ret = put_user(ioctx->user_id, ctxp);
  978. if (ret)
  979. kill_ioctx(current->mm, ioctx, NULL);
  980. percpu_ref_put(&ioctx->users);
  981. }
  982. out:
  983. return ret;
  984. }
  985. /* sys_io_destroy:
  986. * Destroy the aio_context specified. May cancel any outstanding
  987. * AIOs and block on completion. Will fail with -ENOSYS if not
  988. * implemented. May fail with -EINVAL if the context pointed to
  989. * is invalid.
  990. */
  991. SYSCALL_DEFINE1(io_destroy, aio_context_t, ctx)
  992. {
  993. struct kioctx *ioctx = lookup_ioctx(ctx);
  994. if (likely(NULL != ioctx)) {
  995. struct completion requests_done =
  996. COMPLETION_INITIALIZER_ONSTACK(requests_done);
  997. /* Pass requests_done to kill_ioctx() where it can be set
  998. * in a thread-safe way. If we try to set it here then we have
  999. * a race condition if two io_destroy() called simultaneously.
  1000. */
  1001. kill_ioctx(current->mm, ioctx, &requests_done);
  1002. percpu_ref_put(&ioctx->users);
  1003. /* Wait until all IO for the context are done. Otherwise kernel
  1004. * keep using user-space buffers even if user thinks the context
  1005. * is destroyed.
  1006. */
  1007. wait_for_completion(&requests_done);
  1008. return 0;
  1009. }
  1010. pr_debug("EINVAL: io_destroy: invalid context id\n");
  1011. return -EINVAL;
  1012. }
  1013. typedef ssize_t (aio_rw_op)(struct kiocb *, const struct iovec *,
  1014. unsigned long, loff_t);
  1015. static ssize_t aio_setup_vectored_rw(struct kiocb *kiocb,
  1016. int rw, char __user *buf,
  1017. unsigned long *nr_segs,
  1018. struct iovec **iovec,
  1019. bool compat)
  1020. {
  1021. ssize_t ret;
  1022. *nr_segs = kiocb->ki_nbytes;
  1023. #ifdef CONFIG_COMPAT
  1024. if (compat)
  1025. ret = compat_rw_copy_check_uvector(rw,
  1026. (struct compat_iovec __user *)buf,
  1027. *nr_segs, 1, *iovec, iovec);
  1028. else
  1029. #endif
  1030. ret = rw_copy_check_uvector(rw,
  1031. (struct iovec __user *)buf,
  1032. *nr_segs, 1, *iovec, iovec);
  1033. if (ret < 0)
  1034. return ret;
  1035. /* ki_nbytes now reflect bytes instead of segs */
  1036. kiocb->ki_nbytes = ret;
  1037. return 0;
  1038. }
  1039. static ssize_t aio_setup_single_vector(struct kiocb *kiocb,
  1040. int rw, char __user *buf,
  1041. unsigned long *nr_segs,
  1042. struct iovec *iovec)
  1043. {
  1044. if (unlikely(!access_ok(!rw, buf, kiocb->ki_nbytes)))
  1045. return -EFAULT;
  1046. iovec->iov_base = buf;
  1047. iovec->iov_len = kiocb->ki_nbytes;
  1048. *nr_segs = 1;
  1049. return 0;
  1050. }
  1051. /*
  1052. * aio_setup_iocb:
  1053. * Performs the initial checks and aio retry method
  1054. * setup for the kiocb at the time of io submission.
  1055. */
  1056. static ssize_t aio_run_iocb(struct kiocb *req, unsigned opcode,
  1057. char __user *buf, bool compat)
  1058. {
  1059. struct file *file = req->ki_filp;
  1060. ssize_t ret;
  1061. unsigned long nr_segs;
  1062. int rw;
  1063. fmode_t mode;
  1064. aio_rw_op *rw_op;
  1065. struct iovec inline_vec, *iovec = &inline_vec;
  1066. switch (opcode) {
  1067. case IOCB_CMD_PREAD:
  1068. case IOCB_CMD_PREADV:
  1069. mode = FMODE_READ;
  1070. rw = READ;
  1071. rw_op = file->f_op->aio_read;
  1072. goto rw_common;
  1073. case IOCB_CMD_PWRITE:
  1074. case IOCB_CMD_PWRITEV:
  1075. mode = FMODE_WRITE;
  1076. rw = WRITE;
  1077. rw_op = file->f_op->aio_write;
  1078. goto rw_common;
  1079. rw_common:
  1080. if (unlikely(!(file->f_mode & mode)))
  1081. return -EBADF;
  1082. if (!rw_op)
  1083. return -EINVAL;
  1084. ret = (opcode == IOCB_CMD_PREADV ||
  1085. opcode == IOCB_CMD_PWRITEV)
  1086. ? aio_setup_vectored_rw(req, rw, buf, &nr_segs,
  1087. &iovec, compat)
  1088. : aio_setup_single_vector(req, rw, buf, &nr_segs,
  1089. iovec);
  1090. if (!ret)
  1091. ret = rw_verify_area(rw, file, &req->ki_pos, req->ki_nbytes);
  1092. if (ret < 0) {
  1093. if (iovec != &inline_vec)
  1094. kfree(iovec);
  1095. return ret;
  1096. }
  1097. req->ki_nbytes = ret;
  1098. /* XXX: move/kill - rw_verify_area()? */
  1099. /* This matches the pread()/pwrite() logic */
  1100. if (req->ki_pos < 0) {
  1101. ret = -EINVAL;
  1102. break;
  1103. }
  1104. if (rw == WRITE)
  1105. file_start_write(file);
  1106. ret = rw_op(req, iovec, nr_segs, req->ki_pos);
  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_vec)
  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(ctx, 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. }