aio.c 47 KB

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