aio.c 45 KB

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