aio.c 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878
  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 *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 work_struct free_work;
  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 = 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 = ACCESS_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. static void free_ioctx(struct work_struct *work)
  486. {
  487. struct kioctx *ctx = container_of(work, struct kioctx, free_work);
  488. pr_debug("freeing %p\n", ctx);
  489. aio_free_ring(ctx);
  490. free_percpu(ctx->cpu);
  491. percpu_ref_exit(&ctx->reqs);
  492. percpu_ref_exit(&ctx->users);
  493. kmem_cache_free(kioctx_cachep, ctx);
  494. }
  495. static void free_ioctx_reqs(struct percpu_ref *ref)
  496. {
  497. struct kioctx *ctx = container_of(ref, struct kioctx, reqs);
  498. /* At this point we know that there are no any in-flight requests */
  499. if (ctx->rq_wait && atomic_dec_and_test(&ctx->rq_wait->count))
  500. complete(&ctx->rq_wait->comp);
  501. INIT_WORK(&ctx->free_work, free_ioctx);
  502. schedule_work(&ctx->free_work);
  503. }
  504. /*
  505. * When this function runs, the kioctx has been removed from the "hash table"
  506. * and ctx->users has dropped to 0, so we know no more kiocbs can be submitted -
  507. * now it's safe to cancel any that need to be.
  508. */
  509. static void free_ioctx_users(struct percpu_ref *ref)
  510. {
  511. struct kioctx *ctx = container_of(ref, struct kioctx, users);
  512. struct aio_kiocb *req;
  513. spin_lock_irq(&ctx->ctx_lock);
  514. while (!list_empty(&ctx->active_reqs)) {
  515. req = list_first_entry(&ctx->active_reqs,
  516. struct aio_kiocb, ki_list);
  517. list_del_init(&req->ki_list);
  518. kiocb_cancel(req);
  519. }
  520. spin_unlock_irq(&ctx->ctx_lock);
  521. percpu_ref_kill(&ctx->reqs);
  522. percpu_ref_put(&ctx->reqs);
  523. }
  524. static int ioctx_add_table(struct kioctx *ctx, struct mm_struct *mm)
  525. {
  526. unsigned i, new_nr;
  527. struct kioctx_table *table, *old;
  528. struct aio_ring *ring;
  529. spin_lock(&mm->ioctx_lock);
  530. table = rcu_dereference_raw(mm->ioctx_table);
  531. while (1) {
  532. if (table)
  533. for (i = 0; i < table->nr; i++)
  534. if (!table->table[i]) {
  535. ctx->id = i;
  536. table->table[i] = ctx;
  537. spin_unlock(&mm->ioctx_lock);
  538. /* While kioctx setup is in progress,
  539. * we are protected from page migration
  540. * changes ring_pages by ->ring_lock.
  541. */
  542. ring = kmap_atomic(ctx->ring_pages[0]);
  543. ring->id = ctx->id;
  544. kunmap_atomic(ring);
  545. return 0;
  546. }
  547. new_nr = (table ? table->nr : 1) * 4;
  548. spin_unlock(&mm->ioctx_lock);
  549. table = kzalloc(sizeof(*table) + sizeof(struct kioctx *) *
  550. new_nr, GFP_KERNEL);
  551. if (!table)
  552. return -ENOMEM;
  553. table->nr = new_nr;
  554. spin_lock(&mm->ioctx_lock);
  555. old = rcu_dereference_raw(mm->ioctx_table);
  556. if (!old) {
  557. rcu_assign_pointer(mm->ioctx_table, table);
  558. } else if (table->nr > old->nr) {
  559. memcpy(table->table, old->table,
  560. old->nr * sizeof(struct kioctx *));
  561. rcu_assign_pointer(mm->ioctx_table, table);
  562. kfree_rcu(old, rcu);
  563. } else {
  564. kfree(table);
  565. table = old;
  566. }
  567. }
  568. }
  569. static void aio_nr_sub(unsigned nr)
  570. {
  571. spin_lock(&aio_nr_lock);
  572. if (WARN_ON(aio_nr - nr > aio_nr))
  573. aio_nr = 0;
  574. else
  575. aio_nr -= nr;
  576. spin_unlock(&aio_nr_lock);
  577. }
  578. /* ioctx_alloc
  579. * Allocates and initializes an ioctx. Returns an ERR_PTR if it failed.
  580. */
  581. static struct kioctx *ioctx_alloc(unsigned nr_events)
  582. {
  583. struct mm_struct *mm = current->mm;
  584. struct kioctx *ctx;
  585. int err = -ENOMEM;
  586. /*
  587. * Store the original nr_events -- what userspace passed to io_setup(),
  588. * for counting against the global limit -- before it changes.
  589. */
  590. unsigned int max_reqs = nr_events;
  591. /*
  592. * We keep track of the number of available ringbuffer slots, to prevent
  593. * overflow (reqs_available), and we also use percpu counters for this.
  594. *
  595. * So since up to half the slots might be on other cpu's percpu counters
  596. * and unavailable, double nr_events so userspace sees what they
  597. * expected: additionally, we move req_batch slots to/from percpu
  598. * counters at a time, so make sure that isn't 0:
  599. */
  600. nr_events = max(nr_events, num_possible_cpus() * 4);
  601. nr_events *= 2;
  602. /* Prevent overflows */
  603. if (nr_events > (0x10000000U / sizeof(struct io_event))) {
  604. pr_debug("ENOMEM: nr_events too high\n");
  605. return ERR_PTR(-EINVAL);
  606. }
  607. if (!nr_events || (unsigned long)max_reqs > aio_max_nr)
  608. return ERR_PTR(-EAGAIN);
  609. ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
  610. if (!ctx)
  611. return ERR_PTR(-ENOMEM);
  612. ctx->max_reqs = max_reqs;
  613. spin_lock_init(&ctx->ctx_lock);
  614. spin_lock_init(&ctx->completion_lock);
  615. mutex_init(&ctx->ring_lock);
  616. /* Protect against page migration throughout kiotx setup by keeping
  617. * the ring_lock mutex held until setup is complete. */
  618. mutex_lock(&ctx->ring_lock);
  619. init_waitqueue_head(&ctx->wait);
  620. INIT_LIST_HEAD(&ctx->active_reqs);
  621. if (percpu_ref_init(&ctx->users, free_ioctx_users, 0, GFP_KERNEL))
  622. goto err;
  623. if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs, 0, GFP_KERNEL))
  624. goto err;
  625. ctx->cpu = alloc_percpu(struct kioctx_cpu);
  626. if (!ctx->cpu)
  627. goto err;
  628. err = aio_setup_ring(ctx, nr_events);
  629. if (err < 0)
  630. goto err;
  631. atomic_set(&ctx->reqs_available, ctx->nr_events - 1);
  632. ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4);
  633. if (ctx->req_batch < 1)
  634. ctx->req_batch = 1;
  635. /* limit the number of system wide aios */
  636. spin_lock(&aio_nr_lock);
  637. if (aio_nr + ctx->max_reqs > aio_max_nr ||
  638. aio_nr + ctx->max_reqs < aio_nr) {
  639. spin_unlock(&aio_nr_lock);
  640. err = -EAGAIN;
  641. goto err_ctx;
  642. }
  643. aio_nr += ctx->max_reqs;
  644. spin_unlock(&aio_nr_lock);
  645. percpu_ref_get(&ctx->users); /* io_setup() will drop this ref */
  646. percpu_ref_get(&ctx->reqs); /* free_ioctx_users() will drop this */
  647. err = ioctx_add_table(ctx, mm);
  648. if (err)
  649. goto err_cleanup;
  650. /* Release the ring_lock mutex now that all setup is complete. */
  651. mutex_unlock(&ctx->ring_lock);
  652. pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
  653. ctx, ctx->user_id, mm, ctx->nr_events);
  654. return ctx;
  655. err_cleanup:
  656. aio_nr_sub(ctx->max_reqs);
  657. err_ctx:
  658. atomic_set(&ctx->dead, 1);
  659. if (ctx->mmap_size)
  660. vm_munmap(ctx->mmap_base, ctx->mmap_size);
  661. aio_free_ring(ctx);
  662. err:
  663. mutex_unlock(&ctx->ring_lock);
  664. free_percpu(ctx->cpu);
  665. percpu_ref_exit(&ctx->reqs);
  666. percpu_ref_exit(&ctx->users);
  667. kmem_cache_free(kioctx_cachep, ctx);
  668. pr_debug("error allocating ioctx %d\n", err);
  669. return ERR_PTR(err);
  670. }
  671. /* kill_ioctx
  672. * Cancels all outstanding aio requests on an aio context. Used
  673. * when the processes owning a context have all exited to encourage
  674. * the rapid destruction of the kioctx.
  675. */
  676. static int kill_ioctx(struct mm_struct *mm, struct kioctx *ctx,
  677. struct ctx_rq_wait *wait)
  678. {
  679. struct kioctx_table *table;
  680. spin_lock(&mm->ioctx_lock);
  681. if (atomic_xchg(&ctx->dead, 1)) {
  682. spin_unlock(&mm->ioctx_lock);
  683. return -EINVAL;
  684. }
  685. table = rcu_dereference_raw(mm->ioctx_table);
  686. WARN_ON(ctx != table->table[ctx->id]);
  687. table->table[ctx->id] = NULL;
  688. spin_unlock(&mm->ioctx_lock);
  689. /* percpu_ref_kill() will do the necessary call_rcu() */
  690. wake_up_all(&ctx->wait);
  691. /*
  692. * It'd be more correct to do this in free_ioctx(), after all
  693. * the outstanding kiocbs have finished - but by then io_destroy
  694. * has already returned, so io_setup() could potentially return
  695. * -EAGAIN with no ioctxs actually in use (as far as userspace
  696. * could tell).
  697. */
  698. aio_nr_sub(ctx->max_reqs);
  699. if (ctx->mmap_size)
  700. vm_munmap(ctx->mmap_base, ctx->mmap_size);
  701. ctx->rq_wait = wait;
  702. percpu_ref_kill(&ctx->users);
  703. return 0;
  704. }
  705. /*
  706. * exit_aio: called when the last user of mm goes away. At this point, there is
  707. * no way for any new requests to be submited or any of the io_* syscalls to be
  708. * called on the context.
  709. *
  710. * There may be outstanding kiocbs, but free_ioctx() will explicitly wait on
  711. * them.
  712. */
  713. void exit_aio(struct mm_struct *mm)
  714. {
  715. struct kioctx_table *table = rcu_dereference_raw(mm->ioctx_table);
  716. struct ctx_rq_wait wait;
  717. int i, skipped;
  718. if (!table)
  719. return;
  720. atomic_set(&wait.count, table->nr);
  721. init_completion(&wait.comp);
  722. skipped = 0;
  723. for (i = 0; i < table->nr; ++i) {
  724. struct kioctx *ctx = table->table[i];
  725. if (!ctx) {
  726. skipped++;
  727. continue;
  728. }
  729. /*
  730. * We don't need to bother with munmap() here - exit_mmap(mm)
  731. * is coming and it'll unmap everything. And we simply can't,
  732. * this is not necessarily our ->mm.
  733. * Since kill_ioctx() uses non-zero ->mmap_size as indicator
  734. * that it needs to unmap the area, just set it to 0.
  735. */
  736. ctx->mmap_size = 0;
  737. kill_ioctx(mm, ctx, &wait);
  738. }
  739. if (!atomic_sub_and_test(skipped, &wait.count)) {
  740. /* Wait until all IO for the context are done. */
  741. wait_for_completion(&wait.comp);
  742. }
  743. RCU_INIT_POINTER(mm->ioctx_table, NULL);
  744. kfree(table);
  745. }
  746. static void put_reqs_available(struct kioctx *ctx, unsigned nr)
  747. {
  748. struct kioctx_cpu *kcpu;
  749. unsigned long flags;
  750. local_irq_save(flags);
  751. kcpu = this_cpu_ptr(ctx->cpu);
  752. kcpu->reqs_available += nr;
  753. while (kcpu->reqs_available >= ctx->req_batch * 2) {
  754. kcpu->reqs_available -= ctx->req_batch;
  755. atomic_add(ctx->req_batch, &ctx->reqs_available);
  756. }
  757. local_irq_restore(flags);
  758. }
  759. static bool get_reqs_available(struct kioctx *ctx)
  760. {
  761. struct kioctx_cpu *kcpu;
  762. bool ret = false;
  763. unsigned long flags;
  764. local_irq_save(flags);
  765. kcpu = this_cpu_ptr(ctx->cpu);
  766. if (!kcpu->reqs_available) {
  767. int old, avail = atomic_read(&ctx->reqs_available);
  768. do {
  769. if (avail < ctx->req_batch)
  770. goto out;
  771. old = avail;
  772. avail = atomic_cmpxchg(&ctx->reqs_available,
  773. avail, avail - ctx->req_batch);
  774. } while (avail != old);
  775. kcpu->reqs_available += ctx->req_batch;
  776. }
  777. ret = true;
  778. kcpu->reqs_available--;
  779. out:
  780. local_irq_restore(flags);
  781. return ret;
  782. }
  783. /* refill_reqs_available
  784. * Updates the reqs_available reference counts used for tracking the
  785. * number of free slots in the completion ring. This can be called
  786. * from aio_complete() (to optimistically update reqs_available) or
  787. * from aio_get_req() (the we're out of events case). It must be
  788. * called holding ctx->completion_lock.
  789. */
  790. static void refill_reqs_available(struct kioctx *ctx, unsigned head,
  791. unsigned tail)
  792. {
  793. unsigned events_in_ring, completed;
  794. /* Clamp head since userland can write to it. */
  795. head %= ctx->nr_events;
  796. if (head <= tail)
  797. events_in_ring = tail - head;
  798. else
  799. events_in_ring = ctx->nr_events - (head - tail);
  800. completed = ctx->completed_events;
  801. if (events_in_ring < completed)
  802. completed -= events_in_ring;
  803. else
  804. completed = 0;
  805. if (!completed)
  806. return;
  807. ctx->completed_events -= completed;
  808. put_reqs_available(ctx, completed);
  809. }
  810. /* user_refill_reqs_available
  811. * Called to refill reqs_available when aio_get_req() encounters an
  812. * out of space in the completion ring.
  813. */
  814. static void user_refill_reqs_available(struct kioctx *ctx)
  815. {
  816. spin_lock_irq(&ctx->completion_lock);
  817. if (ctx->completed_events) {
  818. struct aio_ring *ring;
  819. unsigned head;
  820. /* Access of ring->head may race with aio_read_events_ring()
  821. * here, but that's okay since whether we read the old version
  822. * or the new version, and either will be valid. The important
  823. * part is that head cannot pass tail since we prevent
  824. * aio_complete() from updating tail by holding
  825. * ctx->completion_lock. Even if head is invalid, the check
  826. * against ctx->completed_events below will make sure we do the
  827. * safe/right thing.
  828. */
  829. ring = kmap_atomic(ctx->ring_pages[0]);
  830. head = ring->head;
  831. kunmap_atomic(ring);
  832. refill_reqs_available(ctx, head, ctx->tail);
  833. }
  834. spin_unlock_irq(&ctx->completion_lock);
  835. }
  836. /* aio_get_req
  837. * Allocate a slot for an aio request.
  838. * Returns NULL if no requests are free.
  839. */
  840. static inline struct aio_kiocb *aio_get_req(struct kioctx *ctx)
  841. {
  842. struct aio_kiocb *req;
  843. if (!get_reqs_available(ctx)) {
  844. user_refill_reqs_available(ctx);
  845. if (!get_reqs_available(ctx))
  846. return NULL;
  847. }
  848. req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL|__GFP_ZERO);
  849. if (unlikely(!req))
  850. goto out_put;
  851. percpu_ref_get(&ctx->reqs);
  852. req->ki_ctx = ctx;
  853. return req;
  854. out_put:
  855. put_reqs_available(ctx, 1);
  856. return NULL;
  857. }
  858. static void kiocb_free(struct aio_kiocb *req)
  859. {
  860. if (req->common.ki_filp)
  861. fput(req->common.ki_filp);
  862. if (req->ki_eventfd != NULL)
  863. eventfd_ctx_put(req->ki_eventfd);
  864. kmem_cache_free(kiocb_cachep, req);
  865. }
  866. static struct kioctx *lookup_ioctx(unsigned long ctx_id)
  867. {
  868. struct aio_ring __user *ring = (void __user *)ctx_id;
  869. struct mm_struct *mm = current->mm;
  870. struct kioctx *ctx, *ret = NULL;
  871. struct kioctx_table *table;
  872. unsigned id;
  873. if (get_user(id, &ring->id))
  874. return NULL;
  875. rcu_read_lock();
  876. table = rcu_dereference(mm->ioctx_table);
  877. if (!table || id >= table->nr)
  878. goto out;
  879. ctx = table->table[id];
  880. if (ctx && ctx->user_id == ctx_id) {
  881. percpu_ref_get(&ctx->users);
  882. ret = ctx;
  883. }
  884. out:
  885. rcu_read_unlock();
  886. return ret;
  887. }
  888. /* aio_complete
  889. * Called when the io request on the given iocb is complete.
  890. */
  891. static void aio_complete(struct kiocb *kiocb, long res, long res2)
  892. {
  893. struct aio_kiocb *iocb = container_of(kiocb, struct aio_kiocb, common);
  894. struct kioctx *ctx = iocb->ki_ctx;
  895. struct aio_ring *ring;
  896. struct io_event *ev_page, *event;
  897. unsigned tail, pos, head;
  898. unsigned long flags;
  899. if (kiocb->ki_flags & IOCB_WRITE) {
  900. struct file *file = kiocb->ki_filp;
  901. /*
  902. * Tell lockdep we inherited freeze protection from submission
  903. * thread.
  904. */
  905. if (S_ISREG(file_inode(file)->i_mode))
  906. __sb_writers_acquired(file_inode(file)->i_sb, SB_FREEZE_WRITE);
  907. file_end_write(file);
  908. }
  909. /*
  910. * Special case handling for sync iocbs:
  911. * - events go directly into the iocb for fast handling
  912. * - the sync task with the iocb in its stack holds the single iocb
  913. * ref, no other paths have a way to get another ref
  914. * - the sync task helpfully left a reference to itself in the iocb
  915. */
  916. BUG_ON(is_sync_kiocb(kiocb));
  917. if (iocb->ki_list.next) {
  918. unsigned long flags;
  919. spin_lock_irqsave(&ctx->ctx_lock, flags);
  920. list_del(&iocb->ki_list);
  921. spin_unlock_irqrestore(&ctx->ctx_lock, flags);
  922. }
  923. /*
  924. * Add a completion event to the ring buffer. Must be done holding
  925. * ctx->completion_lock to prevent other code from messing with the tail
  926. * pointer since we might be called from irq context.
  927. */
  928. spin_lock_irqsave(&ctx->completion_lock, flags);
  929. tail = ctx->tail;
  930. pos = tail + AIO_EVENTS_OFFSET;
  931. if (++tail >= ctx->nr_events)
  932. tail = 0;
  933. ev_page = kmap_atomic(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
  934. event = ev_page + pos % AIO_EVENTS_PER_PAGE;
  935. event->obj = (u64)(unsigned long)iocb->ki_user_iocb;
  936. event->data = iocb->ki_user_data;
  937. event->res = res;
  938. event->res2 = res2;
  939. kunmap_atomic(ev_page);
  940. flush_dcache_page(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
  941. pr_debug("%p[%u]: %p: %p %Lx %lx %lx\n",
  942. ctx, tail, iocb, iocb->ki_user_iocb, iocb->ki_user_data,
  943. res, res2);
  944. /* after flagging the request as done, we
  945. * must never even look at it again
  946. */
  947. smp_wmb(); /* make event visible before updating tail */
  948. ctx->tail = tail;
  949. ring = kmap_atomic(ctx->ring_pages[0]);
  950. head = ring->head;
  951. ring->tail = tail;
  952. kunmap_atomic(ring);
  953. flush_dcache_page(ctx->ring_pages[0]);
  954. ctx->completed_events++;
  955. if (ctx->completed_events > 1)
  956. refill_reqs_available(ctx, head, tail);
  957. spin_unlock_irqrestore(&ctx->completion_lock, flags);
  958. pr_debug("added to ring %p at [%u]\n", iocb, tail);
  959. /*
  960. * Check if the user asked us to deliver the result through an
  961. * eventfd. The eventfd_signal() function is safe to be called
  962. * from IRQ context.
  963. */
  964. if (iocb->ki_eventfd != NULL)
  965. eventfd_signal(iocb->ki_eventfd, 1);
  966. /* everything turned out well, dispose of the aiocb. */
  967. kiocb_free(iocb);
  968. /*
  969. * We have to order our ring_info tail store above and test
  970. * of the wait list below outside the wait lock. This is
  971. * like in wake_up_bit() where clearing a bit has to be
  972. * ordered with the unlocked test.
  973. */
  974. smp_mb();
  975. if (waitqueue_active(&ctx->wait))
  976. wake_up(&ctx->wait);
  977. percpu_ref_put(&ctx->reqs);
  978. }
  979. /* aio_read_events_ring
  980. * Pull an event off of the ioctx's event ring. Returns the number of
  981. * events fetched
  982. */
  983. static long aio_read_events_ring(struct kioctx *ctx,
  984. struct io_event __user *event, long nr)
  985. {
  986. struct aio_ring *ring;
  987. unsigned head, tail, pos;
  988. long ret = 0;
  989. int copy_ret;
  990. /*
  991. * The mutex can block and wake us up and that will cause
  992. * wait_event_interruptible_hrtimeout() to schedule without sleeping
  993. * and repeat. This should be rare enough that it doesn't cause
  994. * peformance issues. See the comment in read_events() for more detail.
  995. */
  996. sched_annotate_sleep();
  997. mutex_lock(&ctx->ring_lock);
  998. /* Access to ->ring_pages here is protected by ctx->ring_lock. */
  999. ring = kmap_atomic(ctx->ring_pages[0]);
  1000. head = ring->head;
  1001. tail = ring->tail;
  1002. kunmap_atomic(ring);
  1003. /*
  1004. * Ensure that once we've read the current tail pointer, that
  1005. * we also see the events that were stored up to the tail.
  1006. */
  1007. smp_rmb();
  1008. pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
  1009. if (head == tail)
  1010. goto out;
  1011. head %= ctx->nr_events;
  1012. tail %= ctx->nr_events;
  1013. while (ret < nr) {
  1014. long avail;
  1015. struct io_event *ev;
  1016. struct page *page;
  1017. avail = (head <= tail ? tail : ctx->nr_events) - head;
  1018. if (head == tail)
  1019. break;
  1020. avail = min(avail, nr - ret);
  1021. avail = min_t(long, avail, AIO_EVENTS_PER_PAGE -
  1022. ((head + AIO_EVENTS_OFFSET) % AIO_EVENTS_PER_PAGE));
  1023. pos = head + AIO_EVENTS_OFFSET;
  1024. page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
  1025. pos %= AIO_EVENTS_PER_PAGE;
  1026. ev = kmap(page);
  1027. copy_ret = copy_to_user(event + ret, ev + pos,
  1028. sizeof(*ev) * avail);
  1029. kunmap(page);
  1030. if (unlikely(copy_ret)) {
  1031. ret = -EFAULT;
  1032. goto out;
  1033. }
  1034. ret += avail;
  1035. head += avail;
  1036. head %= ctx->nr_events;
  1037. }
  1038. ring = kmap_atomic(ctx->ring_pages[0]);
  1039. ring->head = head;
  1040. kunmap_atomic(ring);
  1041. flush_dcache_page(ctx->ring_pages[0]);
  1042. pr_debug("%li h%u t%u\n", ret, head, tail);
  1043. out:
  1044. mutex_unlock(&ctx->ring_lock);
  1045. return ret;
  1046. }
  1047. static bool aio_read_events(struct kioctx *ctx, long min_nr, long nr,
  1048. struct io_event __user *event, long *i)
  1049. {
  1050. long ret = aio_read_events_ring(ctx, event + *i, nr - *i);
  1051. if (ret > 0)
  1052. *i += ret;
  1053. if (unlikely(atomic_read(&ctx->dead)))
  1054. ret = -EINVAL;
  1055. if (!*i)
  1056. *i = ret;
  1057. return ret < 0 || *i >= min_nr;
  1058. }
  1059. static long read_events(struct kioctx *ctx, long min_nr, long nr,
  1060. struct io_event __user *event,
  1061. struct timespec __user *timeout)
  1062. {
  1063. ktime_t until = KTIME_MAX;
  1064. long ret = 0;
  1065. if (timeout) {
  1066. struct timespec ts;
  1067. if (unlikely(copy_from_user(&ts, timeout, sizeof(ts))))
  1068. return -EFAULT;
  1069. until = timespec_to_ktime(ts);
  1070. }
  1071. /*
  1072. * Note that aio_read_events() is being called as the conditional - i.e.
  1073. * we're calling it after prepare_to_wait() has set task state to
  1074. * TASK_INTERRUPTIBLE.
  1075. *
  1076. * But aio_read_events() can block, and if it blocks it's going to flip
  1077. * the task state back to TASK_RUNNING.
  1078. *
  1079. * This should be ok, provided it doesn't flip the state back to
  1080. * TASK_RUNNING and return 0 too much - that causes us to spin. That
  1081. * will only happen if the mutex_lock() call blocks, and we then find
  1082. * the ringbuffer empty. So in practice we should be ok, but it's
  1083. * something to be aware of when touching this code.
  1084. */
  1085. if (until == 0)
  1086. aio_read_events(ctx, min_nr, nr, event, &ret);
  1087. else
  1088. wait_event_interruptible_hrtimeout(ctx->wait,
  1089. aio_read_events(ctx, min_nr, nr, event, &ret),
  1090. until);
  1091. if (!ret && signal_pending(current))
  1092. ret = -EINTR;
  1093. return ret;
  1094. }
  1095. /* sys_io_setup:
  1096. * Create an aio_context capable of receiving at least nr_events.
  1097. * ctxp must not point to an aio_context that already exists, and
  1098. * must be initialized to 0 prior to the call. On successful
  1099. * creation of the aio_context, *ctxp is filled in with the resulting
  1100. * handle. May fail with -EINVAL if *ctxp is not initialized,
  1101. * if the specified nr_events exceeds internal limits. May fail
  1102. * with -EAGAIN if the specified nr_events exceeds the user's limit
  1103. * of available events. May fail with -ENOMEM if insufficient kernel
  1104. * resources are available. May fail with -EFAULT if an invalid
  1105. * pointer is passed for ctxp. Will fail with -ENOSYS if not
  1106. * implemented.
  1107. */
  1108. SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
  1109. {
  1110. struct kioctx *ioctx = NULL;
  1111. unsigned long ctx;
  1112. long ret;
  1113. ret = get_user(ctx, ctxp);
  1114. if (unlikely(ret))
  1115. goto out;
  1116. ret = -EINVAL;
  1117. if (unlikely(ctx || nr_events == 0)) {
  1118. pr_debug("EINVAL: ctx %lu nr_events %u\n",
  1119. ctx, nr_events);
  1120. goto out;
  1121. }
  1122. ioctx = ioctx_alloc(nr_events);
  1123. ret = PTR_ERR(ioctx);
  1124. if (!IS_ERR(ioctx)) {
  1125. ret = put_user(ioctx->user_id, ctxp);
  1126. if (ret)
  1127. kill_ioctx(current->mm, ioctx, NULL);
  1128. percpu_ref_put(&ioctx->users);
  1129. }
  1130. out:
  1131. return ret;
  1132. }
  1133. #ifdef CONFIG_COMPAT
  1134. COMPAT_SYSCALL_DEFINE2(io_setup, unsigned, nr_events, u32 __user *, ctx32p)
  1135. {
  1136. struct kioctx *ioctx = NULL;
  1137. unsigned long ctx;
  1138. long ret;
  1139. ret = get_user(ctx, ctx32p);
  1140. if (unlikely(ret))
  1141. goto out;
  1142. ret = -EINVAL;
  1143. if (unlikely(ctx || nr_events == 0)) {
  1144. pr_debug("EINVAL: ctx %lu nr_events %u\n",
  1145. ctx, nr_events);
  1146. goto out;
  1147. }
  1148. ioctx = ioctx_alloc(nr_events);
  1149. ret = PTR_ERR(ioctx);
  1150. if (!IS_ERR(ioctx)) {
  1151. /* truncating is ok because it's a user address */
  1152. ret = put_user((u32)ioctx->user_id, ctx32p);
  1153. if (ret)
  1154. kill_ioctx(current->mm, ioctx, NULL);
  1155. percpu_ref_put(&ioctx->users);
  1156. }
  1157. out:
  1158. return ret;
  1159. }
  1160. #endif
  1161. /* sys_io_destroy:
  1162. * Destroy the aio_context specified. May cancel any outstanding
  1163. * AIOs and block on completion. Will fail with -ENOSYS if not
  1164. * implemented. May fail with -EINVAL if the context pointed to
  1165. * is invalid.
  1166. */
  1167. SYSCALL_DEFINE1(io_destroy, aio_context_t, ctx)
  1168. {
  1169. struct kioctx *ioctx = lookup_ioctx(ctx);
  1170. if (likely(NULL != ioctx)) {
  1171. struct ctx_rq_wait wait;
  1172. int ret;
  1173. init_completion(&wait.comp);
  1174. atomic_set(&wait.count, 1);
  1175. /* Pass requests_done to kill_ioctx() where it can be set
  1176. * in a thread-safe way. If we try to set it here then we have
  1177. * a race condition if two io_destroy() called simultaneously.
  1178. */
  1179. ret = kill_ioctx(current->mm, ioctx, &wait);
  1180. percpu_ref_put(&ioctx->users);
  1181. /* Wait until all IO for the context are done. Otherwise kernel
  1182. * keep using user-space buffers even if user thinks the context
  1183. * is destroyed.
  1184. */
  1185. if (!ret)
  1186. wait_for_completion(&wait.comp);
  1187. return ret;
  1188. }
  1189. pr_debug("EINVAL: invalid context id\n");
  1190. return -EINVAL;
  1191. }
  1192. static int aio_setup_rw(int rw, struct iocb *iocb, struct iovec **iovec,
  1193. bool vectored, bool compat, struct iov_iter *iter)
  1194. {
  1195. void __user *buf = (void __user *)(uintptr_t)iocb->aio_buf;
  1196. size_t len = iocb->aio_nbytes;
  1197. if (!vectored) {
  1198. ssize_t ret = import_single_range(rw, buf, len, *iovec, iter);
  1199. *iovec = NULL;
  1200. return ret;
  1201. }
  1202. #ifdef CONFIG_COMPAT
  1203. if (compat)
  1204. return compat_import_iovec(rw, buf, len, UIO_FASTIOV, iovec,
  1205. iter);
  1206. #endif
  1207. return import_iovec(rw, buf, len, UIO_FASTIOV, iovec, iter);
  1208. }
  1209. static inline ssize_t aio_ret(struct kiocb *req, ssize_t ret)
  1210. {
  1211. switch (ret) {
  1212. case -EIOCBQUEUED:
  1213. return ret;
  1214. case -ERESTARTSYS:
  1215. case -ERESTARTNOINTR:
  1216. case -ERESTARTNOHAND:
  1217. case -ERESTART_RESTARTBLOCK:
  1218. /*
  1219. * There's no easy way to restart the syscall since other AIO's
  1220. * may be already running. Just fail this IO with EINTR.
  1221. */
  1222. ret = -EINTR;
  1223. /*FALLTHRU*/
  1224. default:
  1225. aio_complete(req, ret, 0);
  1226. return 0;
  1227. }
  1228. }
  1229. static ssize_t aio_read(struct kiocb *req, struct iocb *iocb, bool vectored,
  1230. bool compat)
  1231. {
  1232. struct file *file = req->ki_filp;
  1233. struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
  1234. struct iov_iter iter;
  1235. ssize_t ret;
  1236. if (unlikely(!(file->f_mode & FMODE_READ)))
  1237. return -EBADF;
  1238. if (unlikely(!file->f_op->read_iter))
  1239. return -EINVAL;
  1240. ret = aio_setup_rw(READ, iocb, &iovec, vectored, compat, &iter);
  1241. if (ret)
  1242. return ret;
  1243. ret = rw_verify_area(READ, file, &req->ki_pos, iov_iter_count(&iter));
  1244. if (!ret)
  1245. ret = aio_ret(req, call_read_iter(file, req, &iter));
  1246. kfree(iovec);
  1247. return ret;
  1248. }
  1249. static ssize_t aio_write(struct kiocb *req, struct iocb *iocb, bool vectored,
  1250. bool compat)
  1251. {
  1252. struct file *file = req->ki_filp;
  1253. struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
  1254. struct iov_iter iter;
  1255. ssize_t ret;
  1256. if (unlikely(!(file->f_mode & FMODE_WRITE)))
  1257. return -EBADF;
  1258. if (unlikely(!file->f_op->write_iter))
  1259. return -EINVAL;
  1260. ret = aio_setup_rw(WRITE, iocb, &iovec, vectored, compat, &iter);
  1261. if (ret)
  1262. return ret;
  1263. ret = rw_verify_area(WRITE, file, &req->ki_pos, iov_iter_count(&iter));
  1264. if (!ret) {
  1265. req->ki_flags |= IOCB_WRITE;
  1266. file_start_write(file);
  1267. ret = aio_ret(req, call_write_iter(file, req, &iter));
  1268. /*
  1269. * We release freeze protection in aio_complete(). Fool lockdep
  1270. * by telling it the lock got released so that it doesn't
  1271. * complain about held lock when we return to userspace.
  1272. */
  1273. if (S_ISREG(file_inode(file)->i_mode))
  1274. __sb_writers_release(file_inode(file)->i_sb, SB_FREEZE_WRITE);
  1275. }
  1276. kfree(iovec);
  1277. return ret;
  1278. }
  1279. static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
  1280. struct iocb *iocb, bool compat)
  1281. {
  1282. struct aio_kiocb *req;
  1283. struct file *file;
  1284. ssize_t ret;
  1285. /* enforce forwards compatibility on users */
  1286. if (unlikely(iocb->aio_reserved2)) {
  1287. pr_debug("EINVAL: reserve field set\n");
  1288. return -EINVAL;
  1289. }
  1290. /* prevent overflows */
  1291. if (unlikely(
  1292. (iocb->aio_buf != (unsigned long)iocb->aio_buf) ||
  1293. (iocb->aio_nbytes != (size_t)iocb->aio_nbytes) ||
  1294. ((ssize_t)iocb->aio_nbytes < 0)
  1295. )) {
  1296. pr_debug("EINVAL: overflow check\n");
  1297. return -EINVAL;
  1298. }
  1299. req = aio_get_req(ctx);
  1300. if (unlikely(!req))
  1301. return -EAGAIN;
  1302. req->common.ki_filp = file = fget(iocb->aio_fildes);
  1303. if (unlikely(!req->common.ki_filp)) {
  1304. ret = -EBADF;
  1305. goto out_put_req;
  1306. }
  1307. req->common.ki_pos = iocb->aio_offset;
  1308. req->common.ki_complete = aio_complete;
  1309. req->common.ki_flags = iocb_flags(req->common.ki_filp);
  1310. req->common.ki_hint = file_write_hint(file);
  1311. if (iocb->aio_flags & IOCB_FLAG_RESFD) {
  1312. /*
  1313. * If the IOCB_FLAG_RESFD flag of aio_flags is set, get an
  1314. * instance of the file* now. The file descriptor must be
  1315. * an eventfd() fd, and will be signaled for each completed
  1316. * event using the eventfd_signal() function.
  1317. */
  1318. req->ki_eventfd = eventfd_ctx_fdget((int) iocb->aio_resfd);
  1319. if (IS_ERR(req->ki_eventfd)) {
  1320. ret = PTR_ERR(req->ki_eventfd);
  1321. req->ki_eventfd = NULL;
  1322. goto out_put_req;
  1323. }
  1324. req->common.ki_flags |= IOCB_EVENTFD;
  1325. }
  1326. ret = kiocb_set_rw_flags(&req->common, iocb->aio_rw_flags);
  1327. if (unlikely(ret)) {
  1328. pr_debug("EINVAL: aio_rw_flags\n");
  1329. goto out_put_req;
  1330. }
  1331. ret = put_user(KIOCB_KEY, &user_iocb->aio_key);
  1332. if (unlikely(ret)) {
  1333. pr_debug("EFAULT: aio_key\n");
  1334. goto out_put_req;
  1335. }
  1336. req->ki_user_iocb = user_iocb;
  1337. req->ki_user_data = iocb->aio_data;
  1338. get_file(file);
  1339. switch (iocb->aio_lio_opcode) {
  1340. case IOCB_CMD_PREAD:
  1341. ret = aio_read(&req->common, iocb, false, compat);
  1342. break;
  1343. case IOCB_CMD_PWRITE:
  1344. ret = aio_write(&req->common, iocb, false, compat);
  1345. break;
  1346. case IOCB_CMD_PREADV:
  1347. ret = aio_read(&req->common, iocb, true, compat);
  1348. break;
  1349. case IOCB_CMD_PWRITEV:
  1350. ret = aio_write(&req->common, iocb, true, compat);
  1351. break;
  1352. default:
  1353. pr_debug("invalid aio operation %d\n", iocb->aio_lio_opcode);
  1354. ret = -EINVAL;
  1355. break;
  1356. }
  1357. fput(file);
  1358. if (ret && ret != -EIOCBQUEUED)
  1359. goto out_put_req;
  1360. return 0;
  1361. out_put_req:
  1362. put_reqs_available(ctx, 1);
  1363. percpu_ref_put(&ctx->reqs);
  1364. kiocb_free(req);
  1365. return ret;
  1366. }
  1367. static long do_io_submit(aio_context_t ctx_id, long nr,
  1368. struct iocb __user *__user *iocbpp, bool compat)
  1369. {
  1370. struct kioctx *ctx;
  1371. long ret = 0;
  1372. int i = 0;
  1373. struct blk_plug plug;
  1374. if (unlikely(nr < 0))
  1375. return -EINVAL;
  1376. if (unlikely(nr > LONG_MAX/sizeof(*iocbpp)))
  1377. nr = LONG_MAX/sizeof(*iocbpp);
  1378. if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
  1379. return -EFAULT;
  1380. ctx = lookup_ioctx(ctx_id);
  1381. if (unlikely(!ctx)) {
  1382. pr_debug("EINVAL: invalid context id\n");
  1383. return -EINVAL;
  1384. }
  1385. blk_start_plug(&plug);
  1386. /*
  1387. * AKPM: should this return a partial result if some of the IOs were
  1388. * successfully submitted?
  1389. */
  1390. for (i=0; i<nr; i++) {
  1391. struct iocb __user *user_iocb;
  1392. struct iocb tmp;
  1393. if (unlikely(__get_user(user_iocb, iocbpp + i))) {
  1394. ret = -EFAULT;
  1395. break;
  1396. }
  1397. if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
  1398. ret = -EFAULT;
  1399. break;
  1400. }
  1401. ret = io_submit_one(ctx, user_iocb, &tmp, compat);
  1402. if (ret)
  1403. break;
  1404. }
  1405. blk_finish_plug(&plug);
  1406. percpu_ref_put(&ctx->users);
  1407. return i ? i : ret;
  1408. }
  1409. /* sys_io_submit:
  1410. * Queue the nr iocbs pointed to by iocbpp for processing. Returns
  1411. * the number of iocbs queued. May return -EINVAL if the aio_context
  1412. * specified by ctx_id is invalid, if nr is < 0, if the iocb at
  1413. * *iocbpp[0] is not properly initialized, if the operation specified
  1414. * is invalid for the file descriptor in the iocb. May fail with
  1415. * -EFAULT if any of the data structures point to invalid data. May
  1416. * fail with -EBADF if the file descriptor specified in the first
  1417. * iocb is invalid. May fail with -EAGAIN if insufficient resources
  1418. * are available to queue any iocbs. Will return 0 if nr is 0. Will
  1419. * fail with -ENOSYS if not implemented.
  1420. */
  1421. SYSCALL_DEFINE3(io_submit, aio_context_t, ctx_id, long, nr,
  1422. struct iocb __user * __user *, iocbpp)
  1423. {
  1424. return do_io_submit(ctx_id, nr, iocbpp, 0);
  1425. }
  1426. #ifdef CONFIG_COMPAT
  1427. static inline long
  1428. copy_iocb(long nr, u32 __user *ptr32, struct iocb __user * __user *ptr64)
  1429. {
  1430. compat_uptr_t uptr;
  1431. int i;
  1432. for (i = 0; i < nr; ++i) {
  1433. if (get_user(uptr, ptr32 + i))
  1434. return -EFAULT;
  1435. if (put_user(compat_ptr(uptr), ptr64 + i))
  1436. return -EFAULT;
  1437. }
  1438. return 0;
  1439. }
  1440. #define MAX_AIO_SUBMITS (PAGE_SIZE/sizeof(struct iocb *))
  1441. COMPAT_SYSCALL_DEFINE3(io_submit, compat_aio_context_t, ctx_id,
  1442. int, nr, u32 __user *, iocb)
  1443. {
  1444. struct iocb __user * __user *iocb64;
  1445. long ret;
  1446. if (unlikely(nr < 0))
  1447. return -EINVAL;
  1448. if (nr > MAX_AIO_SUBMITS)
  1449. nr = MAX_AIO_SUBMITS;
  1450. iocb64 = compat_alloc_user_space(nr * sizeof(*iocb64));
  1451. ret = copy_iocb(nr, iocb, iocb64);
  1452. if (!ret)
  1453. ret = do_io_submit(ctx_id, nr, iocb64, 1);
  1454. return ret;
  1455. }
  1456. #endif
  1457. /* lookup_kiocb
  1458. * Finds a given iocb for cancellation.
  1459. */
  1460. static struct aio_kiocb *
  1461. lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb, u32 key)
  1462. {
  1463. struct aio_kiocb *kiocb;
  1464. assert_spin_locked(&ctx->ctx_lock);
  1465. if (key != KIOCB_KEY)
  1466. return NULL;
  1467. /* TODO: use a hash or array, this sucks. */
  1468. list_for_each_entry(kiocb, &ctx->active_reqs, ki_list) {
  1469. if (kiocb->ki_user_iocb == iocb)
  1470. return kiocb;
  1471. }
  1472. return NULL;
  1473. }
  1474. /* sys_io_cancel:
  1475. * Attempts to cancel an iocb previously passed to io_submit. If
  1476. * the operation is successfully cancelled, the resulting event is
  1477. * copied into the memory pointed to by result without being placed
  1478. * into the completion queue and 0 is returned. May fail with
  1479. * -EFAULT if any of the data structures pointed to are invalid.
  1480. * May fail with -EINVAL if aio_context specified by ctx_id is
  1481. * invalid. May fail with -EAGAIN if the iocb specified was not
  1482. * cancelled. Will fail with -ENOSYS if not implemented.
  1483. */
  1484. SYSCALL_DEFINE3(io_cancel, aio_context_t, ctx_id, struct iocb __user *, iocb,
  1485. struct io_event __user *, result)
  1486. {
  1487. struct kioctx *ctx;
  1488. struct aio_kiocb *kiocb;
  1489. u32 key;
  1490. int ret;
  1491. ret = get_user(key, &iocb->aio_key);
  1492. if (unlikely(ret))
  1493. return -EFAULT;
  1494. ctx = lookup_ioctx(ctx_id);
  1495. if (unlikely(!ctx))
  1496. return -EINVAL;
  1497. spin_lock_irq(&ctx->ctx_lock);
  1498. kiocb = lookup_kiocb(ctx, iocb, key);
  1499. if (kiocb)
  1500. ret = kiocb_cancel(kiocb);
  1501. else
  1502. ret = -EINVAL;
  1503. spin_unlock_irq(&ctx->ctx_lock);
  1504. if (!ret) {
  1505. /*
  1506. * The result argument is no longer used - the io_event is
  1507. * always delivered via the ring buffer. -EINPROGRESS indicates
  1508. * cancellation is progress:
  1509. */
  1510. ret = -EINPROGRESS;
  1511. }
  1512. percpu_ref_put(&ctx->users);
  1513. return ret;
  1514. }
  1515. /* io_getevents:
  1516. * Attempts to read at least min_nr events and up to nr events from
  1517. * the completion queue for the aio_context specified by ctx_id. If
  1518. * it succeeds, the number of read events is returned. May fail with
  1519. * -EINVAL if ctx_id is invalid, if min_nr is out of range, if nr is
  1520. * out of range, if timeout is out of range. May fail with -EFAULT
  1521. * if any of the memory specified is invalid. May return 0 or
  1522. * < min_nr if the timeout specified by timeout has elapsed
  1523. * before sufficient events are available, where timeout == NULL
  1524. * specifies an infinite timeout. Note that the timeout pointed to by
  1525. * timeout is relative. Will fail with -ENOSYS if not implemented.
  1526. */
  1527. SYSCALL_DEFINE5(io_getevents, aio_context_t, ctx_id,
  1528. long, min_nr,
  1529. long, nr,
  1530. struct io_event __user *, events,
  1531. struct timespec __user *, timeout)
  1532. {
  1533. struct kioctx *ioctx = lookup_ioctx(ctx_id);
  1534. long ret = -EINVAL;
  1535. if (likely(ioctx)) {
  1536. if (likely(min_nr <= nr && min_nr >= 0))
  1537. ret = read_events(ioctx, min_nr, nr, events, timeout);
  1538. percpu_ref_put(&ioctx->users);
  1539. }
  1540. return ret;
  1541. }
  1542. #ifdef CONFIG_COMPAT
  1543. COMPAT_SYSCALL_DEFINE5(io_getevents, compat_aio_context_t, ctx_id,
  1544. compat_long_t, min_nr,
  1545. compat_long_t, nr,
  1546. struct io_event __user *, events,
  1547. struct compat_timespec __user *, timeout)
  1548. {
  1549. struct timespec t;
  1550. struct timespec __user *ut = NULL;
  1551. if (timeout) {
  1552. if (compat_get_timespec(&t, timeout))
  1553. return -EFAULT;
  1554. ut = compat_alloc_user_space(sizeof(*ut));
  1555. if (copy_to_user(ut, &t, sizeof(t)))
  1556. return -EFAULT;
  1557. }
  1558. return sys_io_getevents(ctx_id, min_nr, nr, events, ut);
  1559. }
  1560. #endif