aio.c 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224
  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. * Copyright 2018 Christoph Hellwig.
  9. *
  10. * See ../COPYING for licensing terms.
  11. */
  12. #define pr_fmt(fmt) "%s: " fmt, __func__
  13. #include <linux/kernel.h>
  14. #include <linux/init.h>
  15. #include <linux/errno.h>
  16. #include <linux/time.h>
  17. #include <linux/aio_abi.h>
  18. #include <linux/export.h>
  19. #include <linux/syscalls.h>
  20. #include <linux/backing-dev.h>
  21. #include <linux/refcount.h>
  22. #include <linux/uio.h>
  23. #include <linux/sched/signal.h>
  24. #include <linux/fs.h>
  25. #include <linux/file.h>
  26. #include <linux/mm.h>
  27. #include <linux/mman.h>
  28. #include <linux/mmu_context.h>
  29. #include <linux/percpu.h>
  30. #include <linux/slab.h>
  31. #include <linux/timer.h>
  32. #include <linux/aio.h>
  33. #include <linux/highmem.h>
  34. #include <linux/workqueue.h>
  35. #include <linux/security.h>
  36. #include <linux/eventfd.h>
  37. #include <linux/blkdev.h>
  38. #include <linux/compat.h>
  39. #include <linux/migrate.h>
  40. #include <linux/ramfs.h>
  41. #include <linux/percpu-refcount.h>
  42. #include <linux/mount.h>
  43. #include <asm/kmap_types.h>
  44. #include <linux/uaccess.h>
  45. #include <linux/nospec.h>
  46. #include "internal.h"
  47. #define KIOCB_KEY 0
  48. #define AIO_RING_MAGIC 0xa10a10a1
  49. #define AIO_RING_COMPAT_FEATURES 1
  50. #define AIO_RING_INCOMPAT_FEATURES 0
  51. struct aio_ring {
  52. unsigned id; /* kernel internal index number */
  53. unsigned nr; /* number of io_events */
  54. unsigned head; /* Written to by userland or under ring_lock
  55. * mutex by aio_read_events_ring(). */
  56. unsigned tail;
  57. unsigned magic;
  58. unsigned compat_features;
  59. unsigned incompat_features;
  60. unsigned header_length; /* size of aio_ring */
  61. struct io_event io_events[0];
  62. }; /* 128 bytes + ring size */
  63. #define AIO_RING_PAGES 8
  64. struct kioctx_table {
  65. struct rcu_head rcu;
  66. unsigned nr;
  67. struct kioctx __rcu *table[];
  68. };
  69. struct kioctx_cpu {
  70. unsigned reqs_available;
  71. };
  72. struct ctx_rq_wait {
  73. struct completion comp;
  74. atomic_t count;
  75. };
  76. struct kioctx {
  77. struct percpu_ref users;
  78. atomic_t dead;
  79. struct percpu_ref reqs;
  80. unsigned long user_id;
  81. struct __percpu kioctx_cpu *cpu;
  82. /*
  83. * For percpu reqs_available, number of slots we move to/from global
  84. * counter at a time:
  85. */
  86. unsigned req_batch;
  87. /*
  88. * This is what userspace passed to io_setup(), it's not used for
  89. * anything but counting against the global max_reqs quota.
  90. *
  91. * The real limit is nr_events - 1, which will be larger (see
  92. * aio_setup_ring())
  93. */
  94. unsigned max_reqs;
  95. /* Size of ringbuffer, in units of struct io_event */
  96. unsigned nr_events;
  97. unsigned long mmap_base;
  98. unsigned long mmap_size;
  99. struct page **ring_pages;
  100. long nr_pages;
  101. struct rcu_work free_rwork; /* see free_ioctx() */
  102. /*
  103. * signals when all in-flight requests are done
  104. */
  105. struct ctx_rq_wait *rq_wait;
  106. struct {
  107. /*
  108. * This counts the number of available slots in the ringbuffer,
  109. * so we avoid overflowing it: it's decremented (if positive)
  110. * when allocating a kiocb and incremented when the resulting
  111. * io_event is pulled off the ringbuffer.
  112. *
  113. * We batch accesses to it with a percpu version.
  114. */
  115. atomic_t reqs_available;
  116. } ____cacheline_aligned_in_smp;
  117. struct {
  118. spinlock_t ctx_lock;
  119. struct list_head active_reqs; /* used for cancellation */
  120. } ____cacheline_aligned_in_smp;
  121. struct {
  122. struct mutex ring_lock;
  123. wait_queue_head_t wait;
  124. } ____cacheline_aligned_in_smp;
  125. struct {
  126. unsigned tail;
  127. unsigned completed_events;
  128. spinlock_t completion_lock;
  129. } ____cacheline_aligned_in_smp;
  130. struct page *internal_pages[AIO_RING_PAGES];
  131. struct file *aio_ring_file;
  132. unsigned id;
  133. };
  134. /*
  135. * First field must be the file pointer in all the
  136. * iocb unions! See also 'struct kiocb' in <linux/fs.h>
  137. */
  138. struct fsync_iocb {
  139. struct file *file;
  140. struct work_struct work;
  141. bool datasync;
  142. struct cred *creds;
  143. };
  144. struct poll_iocb {
  145. struct file *file;
  146. struct wait_queue_head *head;
  147. __poll_t events;
  148. bool done;
  149. bool cancelled;
  150. struct wait_queue_entry wait;
  151. struct work_struct work;
  152. };
  153. /*
  154. * NOTE! Each of the iocb union members has the file pointer
  155. * as the first entry in their struct definition. So you can
  156. * access the file pointer through any of the sub-structs,
  157. * or directly as just 'ki_filp' in this struct.
  158. */
  159. struct aio_kiocb {
  160. union {
  161. struct file *ki_filp;
  162. struct kiocb rw;
  163. struct fsync_iocb fsync;
  164. struct poll_iocb poll;
  165. };
  166. struct kioctx *ki_ctx;
  167. kiocb_cancel_fn *ki_cancel;
  168. struct io_event ki_res;
  169. struct list_head ki_list; /* the aio core uses this
  170. * for cancellation */
  171. refcount_t ki_refcnt;
  172. /*
  173. * If the aio_resfd field of the userspace iocb is not zero,
  174. * this is the underlying eventfd context to deliver events to.
  175. */
  176. struct eventfd_ctx *ki_eventfd;
  177. };
  178. /*------ sysctl variables----*/
  179. static DEFINE_SPINLOCK(aio_nr_lock);
  180. unsigned long aio_nr; /* current system wide number of aio requests */
  181. unsigned long aio_max_nr = 0x10000; /* system wide maximum number of aio requests */
  182. /*----end sysctl variables---*/
  183. static struct kmem_cache *kiocb_cachep;
  184. static struct kmem_cache *kioctx_cachep;
  185. static struct vfsmount *aio_mnt;
  186. static const struct file_operations aio_ring_fops;
  187. static const struct address_space_operations aio_ctx_aops;
  188. static struct file *aio_private_file(struct kioctx *ctx, loff_t nr_pages)
  189. {
  190. struct file *file;
  191. struct inode *inode = alloc_anon_inode(aio_mnt->mnt_sb);
  192. if (IS_ERR(inode))
  193. return ERR_CAST(inode);
  194. inode->i_mapping->a_ops = &aio_ctx_aops;
  195. inode->i_mapping->private_data = ctx;
  196. inode->i_size = PAGE_SIZE * nr_pages;
  197. file = alloc_file_pseudo(inode, aio_mnt, "[aio]",
  198. O_RDWR, &aio_ring_fops);
  199. if (IS_ERR(file))
  200. iput(inode);
  201. return file;
  202. }
  203. static struct dentry *aio_mount(struct file_system_type *fs_type,
  204. int flags, const char *dev_name, void *data)
  205. {
  206. struct dentry *root = mount_pseudo(fs_type, "aio:", NULL, NULL,
  207. AIO_RING_MAGIC);
  208. if (!IS_ERR(root))
  209. root->d_sb->s_iflags |= SB_I_NOEXEC;
  210. return root;
  211. }
  212. /* aio_setup
  213. * Creates the slab caches used by the aio routines, panic on
  214. * failure as this is done early during the boot sequence.
  215. */
  216. static int __init aio_setup(void)
  217. {
  218. static struct file_system_type aio_fs = {
  219. .name = "aio",
  220. .mount = aio_mount,
  221. .kill_sb = kill_anon_super,
  222. };
  223. aio_mnt = kern_mount(&aio_fs);
  224. if (IS_ERR(aio_mnt))
  225. panic("Failed to create aio fs mount.");
  226. kiocb_cachep = KMEM_CACHE(aio_kiocb, SLAB_HWCACHE_ALIGN|SLAB_PANIC);
  227. kioctx_cachep = KMEM_CACHE(kioctx,SLAB_HWCACHE_ALIGN|SLAB_PANIC);
  228. return 0;
  229. }
  230. __initcall(aio_setup);
  231. static void put_aio_ring_file(struct kioctx *ctx)
  232. {
  233. struct file *aio_ring_file = ctx->aio_ring_file;
  234. struct address_space *i_mapping;
  235. if (aio_ring_file) {
  236. truncate_setsize(file_inode(aio_ring_file), 0);
  237. /* Prevent further access to the kioctx from migratepages */
  238. i_mapping = aio_ring_file->f_mapping;
  239. spin_lock(&i_mapping->private_lock);
  240. i_mapping->private_data = NULL;
  241. ctx->aio_ring_file = NULL;
  242. spin_unlock(&i_mapping->private_lock);
  243. fput(aio_ring_file);
  244. }
  245. }
  246. static void aio_free_ring(struct kioctx *ctx)
  247. {
  248. int i;
  249. /* Disconnect the kiotx from the ring file. This prevents future
  250. * accesses to the kioctx from page migration.
  251. */
  252. put_aio_ring_file(ctx);
  253. for (i = 0; i < ctx->nr_pages; i++) {
  254. struct page *page;
  255. pr_debug("pid(%d) [%d] page->count=%d\n", current->pid, i,
  256. page_count(ctx->ring_pages[i]));
  257. page = ctx->ring_pages[i];
  258. if (!page)
  259. continue;
  260. ctx->ring_pages[i] = NULL;
  261. put_page(page);
  262. }
  263. if (ctx->ring_pages && ctx->ring_pages != ctx->internal_pages) {
  264. kfree(ctx->ring_pages);
  265. ctx->ring_pages = NULL;
  266. }
  267. }
  268. static int aio_ring_mremap(struct vm_area_struct *vma)
  269. {
  270. struct file *file = vma->vm_file;
  271. struct mm_struct *mm = vma->vm_mm;
  272. struct kioctx_table *table;
  273. int i, res = -EINVAL;
  274. spin_lock(&mm->ioctx_lock);
  275. rcu_read_lock();
  276. table = rcu_dereference(mm->ioctx_table);
  277. for (i = 0; i < table->nr; i++) {
  278. struct kioctx *ctx;
  279. ctx = rcu_dereference(table->table[i]);
  280. if (ctx && ctx->aio_ring_file == file) {
  281. if (!atomic_read(&ctx->dead)) {
  282. ctx->user_id = ctx->mmap_base = vma->vm_start;
  283. res = 0;
  284. }
  285. break;
  286. }
  287. }
  288. rcu_read_unlock();
  289. spin_unlock(&mm->ioctx_lock);
  290. return res;
  291. }
  292. static const struct vm_operations_struct aio_ring_vm_ops = {
  293. .mremap = aio_ring_mremap,
  294. #if IS_ENABLED(CONFIG_MMU)
  295. .fault = filemap_fault,
  296. .map_pages = filemap_map_pages,
  297. .page_mkwrite = filemap_page_mkwrite,
  298. #endif
  299. };
  300. static int aio_ring_mmap(struct file *file, struct vm_area_struct *vma)
  301. {
  302. vma->vm_flags |= VM_DONTEXPAND;
  303. vma->vm_ops = &aio_ring_vm_ops;
  304. return 0;
  305. }
  306. static const struct file_operations aio_ring_fops = {
  307. .mmap = aio_ring_mmap,
  308. };
  309. #if IS_ENABLED(CONFIG_MIGRATION)
  310. static int aio_migratepage(struct address_space *mapping, struct page *new,
  311. struct page *old, enum migrate_mode mode)
  312. {
  313. struct kioctx *ctx;
  314. unsigned long flags;
  315. pgoff_t idx;
  316. int rc;
  317. /*
  318. * We cannot support the _NO_COPY case here, because copy needs to
  319. * happen under the ctx->completion_lock. That does not work with the
  320. * migration workflow of MIGRATE_SYNC_NO_COPY.
  321. */
  322. if (mode == MIGRATE_SYNC_NO_COPY)
  323. return -EINVAL;
  324. rc = 0;
  325. /* mapping->private_lock here protects against the kioctx teardown. */
  326. spin_lock(&mapping->private_lock);
  327. ctx = mapping->private_data;
  328. if (!ctx) {
  329. rc = -EINVAL;
  330. goto out;
  331. }
  332. /* The ring_lock mutex. The prevents aio_read_events() from writing
  333. * to the ring's head, and prevents page migration from mucking in
  334. * a partially initialized kiotx.
  335. */
  336. if (!mutex_trylock(&ctx->ring_lock)) {
  337. rc = -EAGAIN;
  338. goto out;
  339. }
  340. idx = old->index;
  341. if (idx < (pgoff_t)ctx->nr_pages) {
  342. /* Make sure the old page hasn't already been changed */
  343. if (ctx->ring_pages[idx] != old)
  344. rc = -EAGAIN;
  345. } else
  346. rc = -EINVAL;
  347. if (rc != 0)
  348. goto out_unlock;
  349. /* Writeback must be complete */
  350. BUG_ON(PageWriteback(old));
  351. get_page(new);
  352. rc = migrate_page_move_mapping(mapping, new, old, NULL, mode, 1);
  353. if (rc != MIGRATEPAGE_SUCCESS) {
  354. put_page(new);
  355. goto out_unlock;
  356. }
  357. /* Take completion_lock to prevent other writes to the ring buffer
  358. * while the old page is copied to the new. This prevents new
  359. * events from being lost.
  360. */
  361. spin_lock_irqsave(&ctx->completion_lock, flags);
  362. migrate_page_copy(new, old);
  363. BUG_ON(ctx->ring_pages[idx] != old);
  364. ctx->ring_pages[idx] = new;
  365. spin_unlock_irqrestore(&ctx->completion_lock, flags);
  366. /* The old page is no longer accessible. */
  367. put_page(old);
  368. out_unlock:
  369. mutex_unlock(&ctx->ring_lock);
  370. out:
  371. spin_unlock(&mapping->private_lock);
  372. return rc;
  373. }
  374. #endif
  375. static const struct address_space_operations aio_ctx_aops = {
  376. .set_page_dirty = __set_page_dirty_no_writeback,
  377. #if IS_ENABLED(CONFIG_MIGRATION)
  378. .migratepage = aio_migratepage,
  379. #endif
  380. };
  381. static int aio_setup_ring(struct kioctx *ctx, unsigned int nr_events)
  382. {
  383. struct aio_ring *ring;
  384. struct mm_struct *mm = current->mm;
  385. unsigned long size, unused;
  386. int nr_pages;
  387. int i;
  388. struct file *file;
  389. /* Compensate for the ring buffer's head/tail overlap entry */
  390. nr_events += 2; /* 1 is required, 2 for good luck */
  391. size = sizeof(struct aio_ring);
  392. size += sizeof(struct io_event) * nr_events;
  393. nr_pages = PFN_UP(size);
  394. if (nr_pages < 0)
  395. return -EINVAL;
  396. file = aio_private_file(ctx, nr_pages);
  397. if (IS_ERR(file)) {
  398. ctx->aio_ring_file = NULL;
  399. return -ENOMEM;
  400. }
  401. ctx->aio_ring_file = file;
  402. nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring))
  403. / sizeof(struct io_event);
  404. ctx->ring_pages = ctx->internal_pages;
  405. if (nr_pages > AIO_RING_PAGES) {
  406. ctx->ring_pages = kcalloc(nr_pages, sizeof(struct page *),
  407. GFP_KERNEL);
  408. if (!ctx->ring_pages) {
  409. put_aio_ring_file(ctx);
  410. return -ENOMEM;
  411. }
  412. }
  413. for (i = 0; i < nr_pages; i++) {
  414. struct page *page;
  415. page = find_or_create_page(file->f_mapping,
  416. i, GFP_HIGHUSER | __GFP_ZERO);
  417. if (!page)
  418. break;
  419. pr_debug("pid(%d) page[%d]->count=%d\n",
  420. current->pid, i, page_count(page));
  421. SetPageUptodate(page);
  422. unlock_page(page);
  423. ctx->ring_pages[i] = page;
  424. }
  425. ctx->nr_pages = i;
  426. if (unlikely(i != nr_pages)) {
  427. aio_free_ring(ctx);
  428. return -ENOMEM;
  429. }
  430. ctx->mmap_size = nr_pages * PAGE_SIZE;
  431. pr_debug("attempting mmap of %lu bytes\n", ctx->mmap_size);
  432. if (down_write_killable(&mm->mmap_sem)) {
  433. ctx->mmap_size = 0;
  434. aio_free_ring(ctx);
  435. return -EINTR;
  436. }
  437. ctx->mmap_base = do_mmap_pgoff(ctx->aio_ring_file, 0, ctx->mmap_size,
  438. PROT_READ | PROT_WRITE,
  439. MAP_SHARED, 0, &unused, NULL);
  440. up_write(&mm->mmap_sem);
  441. if (IS_ERR((void *)ctx->mmap_base)) {
  442. ctx->mmap_size = 0;
  443. aio_free_ring(ctx);
  444. return -ENOMEM;
  445. }
  446. pr_debug("mmap address: 0x%08lx\n", ctx->mmap_base);
  447. ctx->user_id = ctx->mmap_base;
  448. ctx->nr_events = nr_events; /* trusted copy */
  449. ring = kmap_atomic(ctx->ring_pages[0]);
  450. ring->nr = nr_events; /* user copy */
  451. ring->id = ~0U;
  452. ring->head = ring->tail = 0;
  453. ring->magic = AIO_RING_MAGIC;
  454. ring->compat_features = AIO_RING_COMPAT_FEATURES;
  455. ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
  456. ring->header_length = sizeof(struct aio_ring);
  457. kunmap_atomic(ring);
  458. flush_dcache_page(ctx->ring_pages[0]);
  459. return 0;
  460. }
  461. #define AIO_EVENTS_PER_PAGE (PAGE_SIZE / sizeof(struct io_event))
  462. #define AIO_EVENTS_FIRST_PAGE ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
  463. #define AIO_EVENTS_OFFSET (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
  464. void kiocb_set_cancel_fn(struct kiocb *iocb, kiocb_cancel_fn *cancel)
  465. {
  466. struct aio_kiocb *req = container_of(iocb, struct aio_kiocb, rw);
  467. struct kioctx *ctx = req->ki_ctx;
  468. unsigned long flags;
  469. if (WARN_ON_ONCE(!list_empty(&req->ki_list)))
  470. return;
  471. spin_lock_irqsave(&ctx->ctx_lock, flags);
  472. list_add_tail(&req->ki_list, &ctx->active_reqs);
  473. req->ki_cancel = cancel;
  474. spin_unlock_irqrestore(&ctx->ctx_lock, flags);
  475. }
  476. EXPORT_SYMBOL(kiocb_set_cancel_fn);
  477. /*
  478. * free_ioctx() should be RCU delayed to synchronize against the RCU
  479. * protected lookup_ioctx() and also needs process context to call
  480. * aio_free_ring(). Use rcu_work.
  481. */
  482. static void free_ioctx(struct work_struct *work)
  483. {
  484. struct kioctx *ctx = container_of(to_rcu_work(work), struct kioctx,
  485. free_rwork);
  486. pr_debug("freeing %p\n", ctx);
  487. aio_free_ring(ctx);
  488. free_percpu(ctx->cpu);
  489. percpu_ref_exit(&ctx->reqs);
  490. percpu_ref_exit(&ctx->users);
  491. kmem_cache_free(kioctx_cachep, ctx);
  492. }
  493. static void free_ioctx_reqs(struct percpu_ref *ref)
  494. {
  495. struct kioctx *ctx = container_of(ref, struct kioctx, reqs);
  496. /* At this point we know that there are no any in-flight requests */
  497. if (ctx->rq_wait && atomic_dec_and_test(&ctx->rq_wait->count))
  498. complete(&ctx->rq_wait->comp);
  499. /* Synchronize against RCU protected table->table[] dereferences */
  500. INIT_RCU_WORK(&ctx->free_rwork, free_ioctx);
  501. queue_rcu_work(system_wq, &ctx->free_rwork);
  502. }
  503. /*
  504. * When this function runs, the kioctx has been removed from the "hash table"
  505. * and ctx->users has dropped to 0, so we know no more kiocbs can be submitted -
  506. * now it's safe to cancel any that need to be.
  507. */
  508. static void free_ioctx_users(struct percpu_ref *ref)
  509. {
  510. struct kioctx *ctx = container_of(ref, struct kioctx, users);
  511. struct aio_kiocb *req;
  512. spin_lock_irq(&ctx->ctx_lock);
  513. while (!list_empty(&ctx->active_reqs)) {
  514. req = list_first_entry(&ctx->active_reqs,
  515. struct aio_kiocb, ki_list);
  516. req->ki_cancel(&req->rw);
  517. list_del_init(&req->ki_list);
  518. }
  519. spin_unlock_irq(&ctx->ctx_lock);
  520. percpu_ref_kill(&ctx->reqs);
  521. percpu_ref_put(&ctx->reqs);
  522. }
  523. static int ioctx_add_table(struct kioctx *ctx, struct mm_struct *mm)
  524. {
  525. unsigned i, new_nr;
  526. struct kioctx_table *table, *old;
  527. struct aio_ring *ring;
  528. spin_lock(&mm->ioctx_lock);
  529. table = rcu_dereference_raw(mm->ioctx_table);
  530. while (1) {
  531. if (table)
  532. for (i = 0; i < table->nr; i++)
  533. if (!rcu_access_pointer(table->table[i])) {
  534. ctx->id = i;
  535. rcu_assign_pointer(table->table[i], ctx);
  536. spin_unlock(&mm->ioctx_lock);
  537. /* While kioctx setup is in progress,
  538. * we are protected from page migration
  539. * changes ring_pages by ->ring_lock.
  540. */
  541. ring = kmap_atomic(ctx->ring_pages[0]);
  542. ring->id = ctx->id;
  543. kunmap_atomic(ring);
  544. return 0;
  545. }
  546. new_nr = (table ? table->nr : 1) * 4;
  547. spin_unlock(&mm->ioctx_lock);
  548. table = kzalloc(sizeof(*table) + sizeof(struct kioctx *) *
  549. new_nr, GFP_KERNEL);
  550. if (!table)
  551. return -ENOMEM;
  552. table->nr = new_nr;
  553. spin_lock(&mm->ioctx_lock);
  554. old = rcu_dereference_raw(mm->ioctx_table);
  555. if (!old) {
  556. rcu_assign_pointer(mm->ioctx_table, table);
  557. } else if (table->nr > old->nr) {
  558. memcpy(table->table, old->table,
  559. old->nr * sizeof(struct kioctx *));
  560. rcu_assign_pointer(mm->ioctx_table, table);
  561. kfree_rcu(old, rcu);
  562. } else {
  563. kfree(table);
  564. table = old;
  565. }
  566. }
  567. }
  568. static void aio_nr_sub(unsigned nr)
  569. {
  570. spin_lock(&aio_nr_lock);
  571. if (WARN_ON(aio_nr - nr > aio_nr))
  572. aio_nr = 0;
  573. else
  574. aio_nr -= nr;
  575. spin_unlock(&aio_nr_lock);
  576. }
  577. /* ioctx_alloc
  578. * Allocates and initializes an ioctx. Returns an ERR_PTR if it failed.
  579. */
  580. static struct kioctx *ioctx_alloc(unsigned nr_events)
  581. {
  582. struct mm_struct *mm = current->mm;
  583. struct kioctx *ctx;
  584. int err = -ENOMEM;
  585. /*
  586. * Store the original nr_events -- what userspace passed to io_setup(),
  587. * for counting against the global limit -- before it changes.
  588. */
  589. unsigned int max_reqs = nr_events;
  590. /*
  591. * We keep track of the number of available ringbuffer slots, to prevent
  592. * overflow (reqs_available), and we also use percpu counters for this.
  593. *
  594. * So since up to half the slots might be on other cpu's percpu counters
  595. * and unavailable, double nr_events so userspace sees what they
  596. * expected: additionally, we move req_batch slots to/from percpu
  597. * counters at a time, so make sure that isn't 0:
  598. */
  599. nr_events = max(nr_events, num_possible_cpus() * 4);
  600. nr_events *= 2;
  601. /* Prevent overflows */
  602. if (nr_events > (0x10000000U / sizeof(struct io_event))) {
  603. pr_debug("ENOMEM: nr_events too high\n");
  604. return ERR_PTR(-EINVAL);
  605. }
  606. if (!nr_events || (unsigned long)max_reqs > aio_max_nr)
  607. return ERR_PTR(-EAGAIN);
  608. ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
  609. if (!ctx)
  610. return ERR_PTR(-ENOMEM);
  611. ctx->max_reqs = max_reqs;
  612. spin_lock_init(&ctx->ctx_lock);
  613. spin_lock_init(&ctx->completion_lock);
  614. mutex_init(&ctx->ring_lock);
  615. /* Protect against page migration throughout kiotx setup by keeping
  616. * the ring_lock mutex held until setup is complete. */
  617. mutex_lock(&ctx->ring_lock);
  618. init_waitqueue_head(&ctx->wait);
  619. INIT_LIST_HEAD(&ctx->active_reqs);
  620. if (percpu_ref_init(&ctx->users, free_ioctx_users, 0, GFP_KERNEL))
  621. goto err;
  622. if (percpu_ref_init(&ctx->reqs, free_ioctx_reqs, 0, GFP_KERNEL))
  623. goto err;
  624. ctx->cpu = alloc_percpu(struct kioctx_cpu);
  625. if (!ctx->cpu)
  626. goto err;
  627. err = aio_setup_ring(ctx, nr_events);
  628. if (err < 0)
  629. goto err;
  630. atomic_set(&ctx->reqs_available, ctx->nr_events - 1);
  631. ctx->req_batch = (ctx->nr_events - 1) / (num_possible_cpus() * 4);
  632. if (ctx->req_batch < 1)
  633. ctx->req_batch = 1;
  634. /* limit the number of system wide aios */
  635. spin_lock(&aio_nr_lock);
  636. if (aio_nr + ctx->max_reqs > aio_max_nr ||
  637. aio_nr + ctx->max_reqs < aio_nr) {
  638. spin_unlock(&aio_nr_lock);
  639. err = -EAGAIN;
  640. goto err_ctx;
  641. }
  642. aio_nr += ctx->max_reqs;
  643. spin_unlock(&aio_nr_lock);
  644. percpu_ref_get(&ctx->users); /* io_setup() will drop this ref */
  645. percpu_ref_get(&ctx->reqs); /* free_ioctx_users() will drop this */
  646. err = ioctx_add_table(ctx, mm);
  647. if (err)
  648. goto err_cleanup;
  649. /* Release the ring_lock mutex now that all setup is complete. */
  650. mutex_unlock(&ctx->ring_lock);
  651. pr_debug("allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
  652. ctx, ctx->user_id, mm, ctx->nr_events);
  653. return ctx;
  654. err_cleanup:
  655. aio_nr_sub(ctx->max_reqs);
  656. err_ctx:
  657. atomic_set(&ctx->dead, 1);
  658. if (ctx->mmap_size)
  659. vm_munmap(ctx->mmap_base, ctx->mmap_size);
  660. aio_free_ring(ctx);
  661. err:
  662. mutex_unlock(&ctx->ring_lock);
  663. free_percpu(ctx->cpu);
  664. percpu_ref_exit(&ctx->reqs);
  665. percpu_ref_exit(&ctx->users);
  666. kmem_cache_free(kioctx_cachep, ctx);
  667. pr_debug("error allocating ioctx %d\n", err);
  668. return ERR_PTR(err);
  669. }
  670. /* kill_ioctx
  671. * Cancels all outstanding aio requests on an aio context. Used
  672. * when the processes owning a context have all exited to encourage
  673. * the rapid destruction of the kioctx.
  674. */
  675. static int kill_ioctx(struct mm_struct *mm, struct kioctx *ctx,
  676. struct ctx_rq_wait *wait)
  677. {
  678. struct kioctx_table *table;
  679. spin_lock(&mm->ioctx_lock);
  680. if (atomic_xchg(&ctx->dead, 1)) {
  681. spin_unlock(&mm->ioctx_lock);
  682. return -EINVAL;
  683. }
  684. table = rcu_dereference_raw(mm->ioctx_table);
  685. WARN_ON(ctx != rcu_access_pointer(table->table[ctx->id]));
  686. RCU_INIT_POINTER(table->table[ctx->id], NULL);
  687. spin_unlock(&mm->ioctx_lock);
  688. /* free_ioctx_reqs() will do the necessary RCU synchronization */
  689. wake_up_all(&ctx->wait);
  690. /*
  691. * It'd be more correct to do this in free_ioctx(), after all
  692. * the outstanding kiocbs have finished - but by then io_destroy
  693. * has already returned, so io_setup() could potentially return
  694. * -EAGAIN with no ioctxs actually in use (as far as userspace
  695. * could tell).
  696. */
  697. aio_nr_sub(ctx->max_reqs);
  698. if (ctx->mmap_size)
  699. vm_munmap(ctx->mmap_base, ctx->mmap_size);
  700. ctx->rq_wait = wait;
  701. percpu_ref_kill(&ctx->users);
  702. return 0;
  703. }
  704. /*
  705. * exit_aio: called when the last user of mm goes away. At this point, there is
  706. * no way for any new requests to be submited or any of the io_* syscalls to be
  707. * called on the context.
  708. *
  709. * There may be outstanding kiocbs, but free_ioctx() will explicitly wait on
  710. * them.
  711. */
  712. void exit_aio(struct mm_struct *mm)
  713. {
  714. struct kioctx_table *table = rcu_dereference_raw(mm->ioctx_table);
  715. struct ctx_rq_wait wait;
  716. int i, skipped;
  717. if (!table)
  718. return;
  719. atomic_set(&wait.count, table->nr);
  720. init_completion(&wait.comp);
  721. skipped = 0;
  722. for (i = 0; i < table->nr; ++i) {
  723. struct kioctx *ctx =
  724. rcu_dereference_protected(table->table[i], true);
  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. static bool get_reqs_available(struct kioctx *ctx)
  837. {
  838. if (__get_reqs_available(ctx))
  839. return true;
  840. user_refill_reqs_available(ctx);
  841. return __get_reqs_available(ctx);
  842. }
  843. /* aio_get_req
  844. * Allocate a slot for an aio request.
  845. * Returns NULL if no requests are free.
  846. *
  847. * The refcount is initialized to 2 - one for the async op completion,
  848. * one for the synchronous code that does this.
  849. */
  850. static inline struct aio_kiocb *aio_get_req(struct kioctx *ctx)
  851. {
  852. struct aio_kiocb *req;
  853. req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL);
  854. if (unlikely(!req))
  855. return NULL;
  856. percpu_ref_get(&ctx->reqs);
  857. req->ki_ctx = ctx;
  858. INIT_LIST_HEAD(&req->ki_list);
  859. refcount_set(&req->ki_refcnt, 2);
  860. req->ki_eventfd = NULL;
  861. return req;
  862. }
  863. static struct kioctx *lookup_ioctx(unsigned long ctx_id)
  864. {
  865. struct aio_ring __user *ring = (void __user *)ctx_id;
  866. struct mm_struct *mm = current->mm;
  867. struct kioctx *ctx, *ret = NULL;
  868. struct kioctx_table *table;
  869. unsigned id;
  870. if (get_user(id, &ring->id))
  871. return NULL;
  872. rcu_read_lock();
  873. table = rcu_dereference(mm->ioctx_table);
  874. if (!table || id >= table->nr)
  875. goto out;
  876. id = array_index_nospec(id, table->nr);
  877. ctx = rcu_dereference(table->table[id]);
  878. if (ctx && ctx->user_id == ctx_id) {
  879. if (percpu_ref_tryget_live(&ctx->users))
  880. ret = ctx;
  881. }
  882. out:
  883. rcu_read_unlock();
  884. return ret;
  885. }
  886. static inline void iocb_destroy(struct aio_kiocb *iocb)
  887. {
  888. if (iocb->ki_filp)
  889. fput(iocb->ki_filp);
  890. percpu_ref_put(&iocb->ki_ctx->reqs);
  891. kmem_cache_free(kiocb_cachep, iocb);
  892. }
  893. /* aio_complete
  894. * Called when the io request on the given iocb is complete.
  895. */
  896. static void aio_complete(struct aio_kiocb *iocb)
  897. {
  898. struct kioctx *ctx = iocb->ki_ctx;
  899. struct aio_ring *ring;
  900. struct io_event *ev_page, *event;
  901. unsigned tail, pos, head;
  902. unsigned long flags;
  903. /*
  904. * Add a completion event to the ring buffer. Must be done holding
  905. * ctx->completion_lock to prevent other code from messing with the tail
  906. * pointer since we might be called from irq context.
  907. */
  908. spin_lock_irqsave(&ctx->completion_lock, flags);
  909. tail = ctx->tail;
  910. pos = tail + AIO_EVENTS_OFFSET;
  911. if (++tail >= ctx->nr_events)
  912. tail = 0;
  913. ev_page = kmap_atomic(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
  914. event = ev_page + pos % AIO_EVENTS_PER_PAGE;
  915. *event = iocb->ki_res;
  916. kunmap_atomic(ev_page);
  917. flush_dcache_page(ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE]);
  918. pr_debug("%p[%u]: %p: %p %Lx %Lx %Lx\n", ctx, tail, iocb,
  919. (void __user *)(unsigned long)iocb->ki_res.obj,
  920. iocb->ki_res.data, iocb->ki_res.res, iocb->ki_res.res2);
  921. /* after flagging the request as done, we
  922. * must never even look at it again
  923. */
  924. smp_wmb(); /* make event visible before updating tail */
  925. ctx->tail = tail;
  926. ring = kmap_atomic(ctx->ring_pages[0]);
  927. head = ring->head;
  928. ring->tail = tail;
  929. kunmap_atomic(ring);
  930. flush_dcache_page(ctx->ring_pages[0]);
  931. ctx->completed_events++;
  932. if (ctx->completed_events > 1)
  933. refill_reqs_available(ctx, head, tail);
  934. spin_unlock_irqrestore(&ctx->completion_lock, flags);
  935. pr_debug("added to ring %p at [%u]\n", iocb, tail);
  936. /*
  937. * Check if the user asked us to deliver the result through an
  938. * eventfd. The eventfd_signal() function is safe to be called
  939. * from IRQ context.
  940. */
  941. if (iocb->ki_eventfd) {
  942. eventfd_signal(iocb->ki_eventfd, 1);
  943. eventfd_ctx_put(iocb->ki_eventfd);
  944. }
  945. /*
  946. * We have to order our ring_info tail store above and test
  947. * of the wait list below outside the wait lock. This is
  948. * like in wake_up_bit() where clearing a bit has to be
  949. * ordered with the unlocked test.
  950. */
  951. smp_mb();
  952. if (waitqueue_active(&ctx->wait))
  953. wake_up(&ctx->wait);
  954. }
  955. static inline void iocb_put(struct aio_kiocb *iocb)
  956. {
  957. if (refcount_dec_and_test(&iocb->ki_refcnt)) {
  958. aio_complete(iocb);
  959. iocb_destroy(iocb);
  960. }
  961. }
  962. /* aio_read_events_ring
  963. * Pull an event off of the ioctx's event ring. Returns the number of
  964. * events fetched
  965. */
  966. static long aio_read_events_ring(struct kioctx *ctx,
  967. struct io_event __user *event, long nr)
  968. {
  969. struct aio_ring *ring;
  970. unsigned head, tail, pos;
  971. long ret = 0;
  972. int copy_ret;
  973. /*
  974. * The mutex can block and wake us up and that will cause
  975. * wait_event_interruptible_hrtimeout() to schedule without sleeping
  976. * and repeat. This should be rare enough that it doesn't cause
  977. * peformance issues. See the comment in read_events() for more detail.
  978. */
  979. sched_annotate_sleep();
  980. mutex_lock(&ctx->ring_lock);
  981. /* Access to ->ring_pages here is protected by ctx->ring_lock. */
  982. ring = kmap_atomic(ctx->ring_pages[0]);
  983. head = ring->head;
  984. tail = ring->tail;
  985. kunmap_atomic(ring);
  986. /*
  987. * Ensure that once we've read the current tail pointer, that
  988. * we also see the events that were stored up to the tail.
  989. */
  990. smp_rmb();
  991. pr_debug("h%u t%u m%u\n", head, tail, ctx->nr_events);
  992. if (head == tail)
  993. goto out;
  994. head %= ctx->nr_events;
  995. tail %= ctx->nr_events;
  996. while (ret < nr) {
  997. long avail;
  998. struct io_event *ev;
  999. struct page *page;
  1000. avail = (head <= tail ? tail : ctx->nr_events) - head;
  1001. if (head == tail)
  1002. break;
  1003. pos = head + AIO_EVENTS_OFFSET;
  1004. page = ctx->ring_pages[pos / AIO_EVENTS_PER_PAGE];
  1005. pos %= AIO_EVENTS_PER_PAGE;
  1006. avail = min(avail, nr - ret);
  1007. avail = min_t(long, avail, AIO_EVENTS_PER_PAGE - pos);
  1008. ev = kmap(page);
  1009. copy_ret = copy_to_user(event + ret, ev + pos,
  1010. sizeof(*ev) * avail);
  1011. kunmap(page);
  1012. if (unlikely(copy_ret)) {
  1013. ret = -EFAULT;
  1014. goto out;
  1015. }
  1016. ret += avail;
  1017. head += avail;
  1018. head %= ctx->nr_events;
  1019. }
  1020. ring = kmap_atomic(ctx->ring_pages[0]);
  1021. ring->head = head;
  1022. kunmap_atomic(ring);
  1023. flush_dcache_page(ctx->ring_pages[0]);
  1024. pr_debug("%li h%u t%u\n", ret, head, tail);
  1025. out:
  1026. mutex_unlock(&ctx->ring_lock);
  1027. return ret;
  1028. }
  1029. static bool aio_read_events(struct kioctx *ctx, long min_nr, long nr,
  1030. struct io_event __user *event, long *i)
  1031. {
  1032. long ret = aio_read_events_ring(ctx, event + *i, nr - *i);
  1033. if (ret > 0)
  1034. *i += ret;
  1035. if (unlikely(atomic_read(&ctx->dead)))
  1036. ret = -EINVAL;
  1037. if (!*i)
  1038. *i = ret;
  1039. return ret < 0 || *i >= min_nr;
  1040. }
  1041. static long read_events(struct kioctx *ctx, long min_nr, long nr,
  1042. struct io_event __user *event,
  1043. ktime_t until)
  1044. {
  1045. long ret = 0;
  1046. /*
  1047. * Note that aio_read_events() is being called as the conditional - i.e.
  1048. * we're calling it after prepare_to_wait() has set task state to
  1049. * TASK_INTERRUPTIBLE.
  1050. *
  1051. * But aio_read_events() can block, and if it blocks it's going to flip
  1052. * the task state back to TASK_RUNNING.
  1053. *
  1054. * This should be ok, provided it doesn't flip the state back to
  1055. * TASK_RUNNING and return 0 too much - that causes us to spin. That
  1056. * will only happen if the mutex_lock() call blocks, and we then find
  1057. * the ringbuffer empty. So in practice we should be ok, but it's
  1058. * something to be aware of when touching this code.
  1059. */
  1060. if (until == 0)
  1061. aio_read_events(ctx, min_nr, nr, event, &ret);
  1062. else
  1063. wait_event_interruptible_hrtimeout(ctx->wait,
  1064. aio_read_events(ctx, min_nr, nr, event, &ret),
  1065. until);
  1066. return ret;
  1067. }
  1068. /* sys_io_setup:
  1069. * Create an aio_context capable of receiving at least nr_events.
  1070. * ctxp must not point to an aio_context that already exists, and
  1071. * must be initialized to 0 prior to the call. On successful
  1072. * creation of the aio_context, *ctxp is filled in with the resulting
  1073. * handle. May fail with -EINVAL if *ctxp is not initialized,
  1074. * if the specified nr_events exceeds internal limits. May fail
  1075. * with -EAGAIN if the specified nr_events exceeds the user's limit
  1076. * of available events. May fail with -ENOMEM if insufficient kernel
  1077. * resources are available. May fail with -EFAULT if an invalid
  1078. * pointer is passed for ctxp. Will fail with -ENOSYS if not
  1079. * implemented.
  1080. */
  1081. SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
  1082. {
  1083. struct kioctx *ioctx = NULL;
  1084. unsigned long ctx;
  1085. long ret;
  1086. ret = get_user(ctx, ctxp);
  1087. if (unlikely(ret))
  1088. goto out;
  1089. ret = -EINVAL;
  1090. if (unlikely(ctx || nr_events == 0)) {
  1091. pr_debug("EINVAL: ctx %lu nr_events %u\n",
  1092. ctx, nr_events);
  1093. goto out;
  1094. }
  1095. ioctx = ioctx_alloc(nr_events);
  1096. ret = PTR_ERR(ioctx);
  1097. if (!IS_ERR(ioctx)) {
  1098. ret = put_user(ioctx->user_id, ctxp);
  1099. if (ret)
  1100. kill_ioctx(current->mm, ioctx, NULL);
  1101. percpu_ref_put(&ioctx->users);
  1102. }
  1103. out:
  1104. return ret;
  1105. }
  1106. #ifdef CONFIG_COMPAT
  1107. COMPAT_SYSCALL_DEFINE2(io_setup, unsigned, nr_events, u32 __user *, ctx32p)
  1108. {
  1109. struct kioctx *ioctx = NULL;
  1110. unsigned long ctx;
  1111. long ret;
  1112. ret = get_user(ctx, ctx32p);
  1113. if (unlikely(ret))
  1114. goto out;
  1115. ret = -EINVAL;
  1116. if (unlikely(ctx || nr_events == 0)) {
  1117. pr_debug("EINVAL: ctx %lu nr_events %u\n",
  1118. ctx, nr_events);
  1119. goto out;
  1120. }
  1121. ioctx = ioctx_alloc(nr_events);
  1122. ret = PTR_ERR(ioctx);
  1123. if (!IS_ERR(ioctx)) {
  1124. /* truncating is ok because it's a user address */
  1125. ret = put_user((u32)ioctx->user_id, ctx32p);
  1126. if (ret)
  1127. kill_ioctx(current->mm, ioctx, NULL);
  1128. percpu_ref_put(&ioctx->users);
  1129. }
  1130. out:
  1131. return ret;
  1132. }
  1133. #endif
  1134. /* sys_io_destroy:
  1135. * Destroy the aio_context specified. May cancel any outstanding
  1136. * AIOs and block on completion. Will fail with -ENOSYS if not
  1137. * implemented. May fail with -EINVAL if the context pointed to
  1138. * is invalid.
  1139. */
  1140. SYSCALL_DEFINE1(io_destroy, aio_context_t, ctx)
  1141. {
  1142. struct kioctx *ioctx = lookup_ioctx(ctx);
  1143. if (likely(NULL != ioctx)) {
  1144. struct ctx_rq_wait wait;
  1145. int ret;
  1146. init_completion(&wait.comp);
  1147. atomic_set(&wait.count, 1);
  1148. /* Pass requests_done to kill_ioctx() where it can be set
  1149. * in a thread-safe way. If we try to set it here then we have
  1150. * a race condition if two io_destroy() called simultaneously.
  1151. */
  1152. ret = kill_ioctx(current->mm, ioctx, &wait);
  1153. percpu_ref_put(&ioctx->users);
  1154. /* Wait until all IO for the context are done. Otherwise kernel
  1155. * keep using user-space buffers even if user thinks the context
  1156. * is destroyed.
  1157. */
  1158. if (!ret)
  1159. wait_for_completion(&wait.comp);
  1160. return ret;
  1161. }
  1162. pr_debug("EINVAL: invalid context id\n");
  1163. return -EINVAL;
  1164. }
  1165. static void aio_remove_iocb(struct aio_kiocb *iocb)
  1166. {
  1167. struct kioctx *ctx = iocb->ki_ctx;
  1168. unsigned long flags;
  1169. spin_lock_irqsave(&ctx->ctx_lock, flags);
  1170. list_del(&iocb->ki_list);
  1171. spin_unlock_irqrestore(&ctx->ctx_lock, flags);
  1172. }
  1173. static void aio_complete_rw(struct kiocb *kiocb, long res, long res2)
  1174. {
  1175. struct aio_kiocb *iocb = container_of(kiocb, struct aio_kiocb, rw);
  1176. if (!list_empty_careful(&iocb->ki_list))
  1177. aio_remove_iocb(iocb);
  1178. if (kiocb->ki_flags & IOCB_WRITE) {
  1179. struct inode *inode = file_inode(kiocb->ki_filp);
  1180. /*
  1181. * Tell lockdep we inherited freeze protection from submission
  1182. * thread.
  1183. */
  1184. if (S_ISREG(inode->i_mode))
  1185. __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
  1186. file_end_write(kiocb->ki_filp);
  1187. }
  1188. iocb->ki_res.res = res;
  1189. iocb->ki_res.res2 = res2;
  1190. iocb_put(iocb);
  1191. }
  1192. static int aio_prep_rw(struct kiocb *req, const struct iocb *iocb)
  1193. {
  1194. int ret;
  1195. req->ki_complete = aio_complete_rw;
  1196. req->private = NULL;
  1197. req->ki_pos = iocb->aio_offset;
  1198. req->ki_flags = iocb_flags(req->ki_filp);
  1199. if (iocb->aio_flags & IOCB_FLAG_RESFD)
  1200. req->ki_flags |= IOCB_EVENTFD;
  1201. req->ki_hint = ki_hint_validate(file_write_hint(req->ki_filp));
  1202. if (iocb->aio_flags & IOCB_FLAG_IOPRIO) {
  1203. /*
  1204. * If the IOCB_FLAG_IOPRIO flag of aio_flags is set, then
  1205. * aio_reqprio is interpreted as an I/O scheduling
  1206. * class and priority.
  1207. */
  1208. ret = ioprio_check_cap(iocb->aio_reqprio);
  1209. if (ret) {
  1210. pr_debug("aio ioprio check cap error: %d\n", ret);
  1211. return ret;
  1212. }
  1213. req->ki_ioprio = iocb->aio_reqprio;
  1214. } else
  1215. req->ki_ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_NONE, 0);
  1216. ret = kiocb_set_rw_flags(req, iocb->aio_rw_flags);
  1217. if (unlikely(ret))
  1218. return ret;
  1219. req->ki_flags &= ~IOCB_HIPRI; /* no one is going to poll for this I/O */
  1220. return 0;
  1221. }
  1222. static int aio_setup_rw(int rw, const struct iocb *iocb, struct iovec **iovec,
  1223. bool vectored, bool compat, struct iov_iter *iter)
  1224. {
  1225. void __user *buf = (void __user *)(uintptr_t)iocb->aio_buf;
  1226. size_t len = iocb->aio_nbytes;
  1227. if (!vectored) {
  1228. ssize_t ret = import_single_range(rw, buf, len, *iovec, iter);
  1229. *iovec = NULL;
  1230. return ret;
  1231. }
  1232. #ifdef CONFIG_COMPAT
  1233. if (compat)
  1234. return compat_import_iovec(rw, buf, len, UIO_FASTIOV, iovec,
  1235. iter);
  1236. #endif
  1237. return import_iovec(rw, buf, len, UIO_FASTIOV, iovec, iter);
  1238. }
  1239. static inline void aio_rw_done(struct kiocb *req, ssize_t ret)
  1240. {
  1241. switch (ret) {
  1242. case -EIOCBQUEUED:
  1243. break;
  1244. case -ERESTARTSYS:
  1245. case -ERESTARTNOINTR:
  1246. case -ERESTARTNOHAND:
  1247. case -ERESTART_RESTARTBLOCK:
  1248. /*
  1249. * There's no easy way to restart the syscall since other AIO's
  1250. * may be already running. Just fail this IO with EINTR.
  1251. */
  1252. ret = -EINTR;
  1253. /*FALLTHRU*/
  1254. default:
  1255. req->ki_complete(req, ret, 0);
  1256. }
  1257. }
  1258. static ssize_t aio_read(struct kiocb *req, const struct iocb *iocb,
  1259. bool vectored, bool compat)
  1260. {
  1261. struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
  1262. struct iov_iter iter;
  1263. struct file *file;
  1264. ssize_t ret;
  1265. ret = aio_prep_rw(req, iocb);
  1266. if (ret)
  1267. return ret;
  1268. file = req->ki_filp;
  1269. if (unlikely(!(file->f_mode & FMODE_READ)))
  1270. return -EBADF;
  1271. ret = -EINVAL;
  1272. if (unlikely(!file->f_op->read_iter))
  1273. return -EINVAL;
  1274. ret = aio_setup_rw(READ, iocb, &iovec, vectored, compat, &iter);
  1275. if (ret)
  1276. return ret;
  1277. ret = rw_verify_area(READ, file, &req->ki_pos, iov_iter_count(&iter));
  1278. if (!ret)
  1279. aio_rw_done(req, call_read_iter(file, req, &iter));
  1280. kfree(iovec);
  1281. return ret;
  1282. }
  1283. static ssize_t aio_write(struct kiocb *req, const struct iocb *iocb,
  1284. bool vectored, bool compat)
  1285. {
  1286. struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
  1287. struct iov_iter iter;
  1288. struct file *file;
  1289. ssize_t ret;
  1290. ret = aio_prep_rw(req, iocb);
  1291. if (ret)
  1292. return ret;
  1293. file = req->ki_filp;
  1294. if (unlikely(!(file->f_mode & FMODE_WRITE)))
  1295. return -EBADF;
  1296. if (unlikely(!file->f_op->write_iter))
  1297. return -EINVAL;
  1298. ret = aio_setup_rw(WRITE, iocb, &iovec, vectored, compat, &iter);
  1299. if (ret)
  1300. return ret;
  1301. ret = rw_verify_area(WRITE, file, &req->ki_pos, iov_iter_count(&iter));
  1302. if (!ret) {
  1303. /*
  1304. * Open-code file_start_write here to grab freeze protection,
  1305. * which will be released by another thread in
  1306. * aio_complete_rw(). Fool lockdep by telling it the lock got
  1307. * released so that it doesn't complain about the held lock when
  1308. * we return to userspace.
  1309. */
  1310. if (S_ISREG(file_inode(file)->i_mode)) {
  1311. __sb_start_write(file_inode(file)->i_sb, SB_FREEZE_WRITE, true);
  1312. __sb_writers_release(file_inode(file)->i_sb, SB_FREEZE_WRITE);
  1313. }
  1314. req->ki_flags |= IOCB_WRITE;
  1315. aio_rw_done(req, call_write_iter(file, req, &iter));
  1316. }
  1317. kfree(iovec);
  1318. return ret;
  1319. }
  1320. static void aio_fsync_work(struct work_struct *work)
  1321. {
  1322. struct aio_kiocb *iocb = container_of(work, struct aio_kiocb, fsync.work);
  1323. const struct cred *old_cred = override_creds(iocb->fsync.creds);
  1324. iocb->ki_res.res = vfs_fsync(iocb->fsync.file, iocb->fsync.datasync);
  1325. revert_creds(old_cred);
  1326. put_cred(iocb->fsync.creds);
  1327. iocb_put(iocb);
  1328. }
  1329. static int aio_fsync(struct fsync_iocb *req, const struct iocb *iocb,
  1330. bool datasync)
  1331. {
  1332. if (unlikely(iocb->aio_buf || iocb->aio_offset || iocb->aio_nbytes ||
  1333. iocb->aio_rw_flags))
  1334. return -EINVAL;
  1335. if (unlikely(!req->file->f_op->fsync))
  1336. return -EINVAL;
  1337. req->creds = prepare_creds();
  1338. if (!req->creds)
  1339. return -ENOMEM;
  1340. req->datasync = datasync;
  1341. INIT_WORK(&req->work, aio_fsync_work);
  1342. schedule_work(&req->work);
  1343. return 0;
  1344. }
  1345. static void aio_poll_put_work(struct work_struct *work)
  1346. {
  1347. struct poll_iocb *req = container_of(work, struct poll_iocb, work);
  1348. struct aio_kiocb *iocb = container_of(req, struct aio_kiocb, poll);
  1349. iocb_put(iocb);
  1350. }
  1351. static void aio_poll_complete_work(struct work_struct *work)
  1352. {
  1353. struct poll_iocb *req = container_of(work, struct poll_iocb, work);
  1354. struct aio_kiocb *iocb = container_of(req, struct aio_kiocb, poll);
  1355. struct poll_table_struct pt = { ._key = req->events };
  1356. struct kioctx *ctx = iocb->ki_ctx;
  1357. __poll_t mask = 0;
  1358. if (!READ_ONCE(req->cancelled))
  1359. mask = vfs_poll(req->file, &pt) & req->events;
  1360. /*
  1361. * Note that ->ki_cancel callers also delete iocb from active_reqs after
  1362. * calling ->ki_cancel. We need the ctx_lock roundtrip here to
  1363. * synchronize with them. In the cancellation case the list_del_init
  1364. * itself is not actually needed, but harmless so we keep it in to
  1365. * avoid further branches in the fast path.
  1366. */
  1367. spin_lock_irq(&ctx->ctx_lock);
  1368. if (!mask && !READ_ONCE(req->cancelled)) {
  1369. add_wait_queue(req->head, &req->wait);
  1370. spin_unlock_irq(&ctx->ctx_lock);
  1371. return;
  1372. }
  1373. list_del_init(&iocb->ki_list);
  1374. iocb->ki_res.res = mangle_poll(mask);
  1375. req->done = true;
  1376. spin_unlock_irq(&ctx->ctx_lock);
  1377. iocb_put(iocb);
  1378. }
  1379. /* assumes we are called with irqs disabled */
  1380. static int aio_poll_cancel(struct kiocb *iocb)
  1381. {
  1382. struct aio_kiocb *aiocb = container_of(iocb, struct aio_kiocb, rw);
  1383. struct poll_iocb *req = &aiocb->poll;
  1384. spin_lock(&req->head->lock);
  1385. WRITE_ONCE(req->cancelled, true);
  1386. if (!list_empty(&req->wait.entry)) {
  1387. list_del_init(&req->wait.entry);
  1388. schedule_work(&aiocb->poll.work);
  1389. }
  1390. spin_unlock(&req->head->lock);
  1391. return 0;
  1392. }
  1393. static int aio_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
  1394. void *key)
  1395. {
  1396. struct poll_iocb *req = container_of(wait, struct poll_iocb, wait);
  1397. struct aio_kiocb *iocb = container_of(req, struct aio_kiocb, poll);
  1398. __poll_t mask = key_to_poll(key);
  1399. unsigned long flags;
  1400. /* for instances that support it check for an event match first: */
  1401. if (mask && !(mask & req->events))
  1402. return 0;
  1403. list_del_init(&req->wait.entry);
  1404. if (mask && spin_trylock_irqsave(&iocb->ki_ctx->ctx_lock, flags)) {
  1405. struct kioctx *ctx = iocb->ki_ctx;
  1406. /*
  1407. * Try to complete the iocb inline if we can. Use
  1408. * irqsave/irqrestore because not all filesystems (e.g. fuse)
  1409. * call this function with IRQs disabled and because IRQs
  1410. * have to be disabled before ctx_lock is obtained.
  1411. */
  1412. list_del(&iocb->ki_list);
  1413. iocb->ki_res.res = mangle_poll(mask);
  1414. req->done = true;
  1415. if (iocb->ki_eventfd && eventfd_signal_count()) {
  1416. iocb = NULL;
  1417. INIT_WORK(&req->work, aio_poll_put_work);
  1418. schedule_work(&req->work);
  1419. }
  1420. spin_unlock_irqrestore(&ctx->ctx_lock, flags);
  1421. if (iocb)
  1422. iocb_put(iocb);
  1423. } else {
  1424. schedule_work(&req->work);
  1425. }
  1426. return 1;
  1427. }
  1428. struct aio_poll_table {
  1429. struct poll_table_struct pt;
  1430. struct aio_kiocb *iocb;
  1431. int error;
  1432. };
  1433. static void
  1434. aio_poll_queue_proc(struct file *file, struct wait_queue_head *head,
  1435. struct poll_table_struct *p)
  1436. {
  1437. struct aio_poll_table *pt = container_of(p, struct aio_poll_table, pt);
  1438. /* multiple wait queues per file are not supported */
  1439. if (unlikely(pt->iocb->poll.head)) {
  1440. pt->error = -EINVAL;
  1441. return;
  1442. }
  1443. pt->error = 0;
  1444. pt->iocb->poll.head = head;
  1445. add_wait_queue(head, &pt->iocb->poll.wait);
  1446. }
  1447. static ssize_t aio_poll(struct aio_kiocb *aiocb, const struct iocb *iocb)
  1448. {
  1449. struct kioctx *ctx = aiocb->ki_ctx;
  1450. struct poll_iocb *req = &aiocb->poll;
  1451. struct aio_poll_table apt;
  1452. bool cancel = false;
  1453. __poll_t mask;
  1454. /* reject any unknown events outside the normal event mask. */
  1455. if ((u16)iocb->aio_buf != iocb->aio_buf)
  1456. return -EINVAL;
  1457. /* reject fields that are not defined for poll */
  1458. if (iocb->aio_offset || iocb->aio_nbytes || iocb->aio_rw_flags)
  1459. return -EINVAL;
  1460. INIT_WORK(&req->work, aio_poll_complete_work);
  1461. req->events = demangle_poll(iocb->aio_buf) | EPOLLERR | EPOLLHUP;
  1462. req->head = NULL;
  1463. req->done = false;
  1464. req->cancelled = false;
  1465. apt.pt._qproc = aio_poll_queue_proc;
  1466. apt.pt._key = req->events;
  1467. apt.iocb = aiocb;
  1468. apt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
  1469. /* initialized the list so that we can do list_empty checks */
  1470. INIT_LIST_HEAD(&req->wait.entry);
  1471. init_waitqueue_func_entry(&req->wait, aio_poll_wake);
  1472. mask = vfs_poll(req->file, &apt.pt) & req->events;
  1473. spin_lock_irq(&ctx->ctx_lock);
  1474. if (likely(req->head)) {
  1475. spin_lock(&req->head->lock);
  1476. if (unlikely(list_empty(&req->wait.entry))) {
  1477. if (apt.error)
  1478. cancel = true;
  1479. apt.error = 0;
  1480. mask = 0;
  1481. }
  1482. if (mask || apt.error) {
  1483. list_del_init(&req->wait.entry);
  1484. } else if (cancel) {
  1485. WRITE_ONCE(req->cancelled, true);
  1486. } else if (!req->done) { /* actually waiting for an event */
  1487. list_add_tail(&aiocb->ki_list, &ctx->active_reqs);
  1488. aiocb->ki_cancel = aio_poll_cancel;
  1489. }
  1490. spin_unlock(&req->head->lock);
  1491. }
  1492. if (mask) { /* no async, we'd stolen it */
  1493. aiocb->ki_res.res = mangle_poll(mask);
  1494. apt.error = 0;
  1495. }
  1496. spin_unlock_irq(&ctx->ctx_lock);
  1497. if (mask)
  1498. iocb_put(aiocb);
  1499. return apt.error;
  1500. }
  1501. static int __io_submit_one(struct kioctx *ctx, const struct iocb *iocb,
  1502. struct iocb __user *user_iocb, bool compat)
  1503. {
  1504. struct aio_kiocb *req;
  1505. ssize_t ret;
  1506. /* enforce forwards compatibility on users */
  1507. if (unlikely(iocb->aio_reserved2)) {
  1508. pr_debug("EINVAL: reserve field set\n");
  1509. return -EINVAL;
  1510. }
  1511. /* prevent overflows */
  1512. if (unlikely(
  1513. (iocb->aio_buf != (unsigned long)iocb->aio_buf) ||
  1514. (iocb->aio_nbytes != (size_t)iocb->aio_nbytes) ||
  1515. ((ssize_t)iocb->aio_nbytes < 0)
  1516. )) {
  1517. pr_debug("EINVAL: overflow check\n");
  1518. return -EINVAL;
  1519. }
  1520. if (!get_reqs_available(ctx))
  1521. return -EAGAIN;
  1522. ret = -EAGAIN;
  1523. req = aio_get_req(ctx);
  1524. if (unlikely(!req))
  1525. goto out_put_reqs_available;
  1526. req->ki_filp = fget(iocb->aio_fildes);
  1527. ret = -EBADF;
  1528. if (unlikely(!req->ki_filp))
  1529. goto out_put_req;
  1530. if (iocb->aio_flags & IOCB_FLAG_RESFD) {
  1531. /*
  1532. * If the IOCB_FLAG_RESFD flag of aio_flags is set, get an
  1533. * instance of the file* now. The file descriptor must be
  1534. * an eventfd() fd, and will be signaled for each completed
  1535. * event using the eventfd_signal() function.
  1536. */
  1537. req->ki_eventfd = eventfd_ctx_fdget((int) iocb->aio_resfd);
  1538. if (IS_ERR(req->ki_eventfd)) {
  1539. ret = PTR_ERR(req->ki_eventfd);
  1540. req->ki_eventfd = NULL;
  1541. goto out_put_req;
  1542. }
  1543. }
  1544. ret = put_user(KIOCB_KEY, &user_iocb->aio_key);
  1545. if (unlikely(ret)) {
  1546. pr_debug("EFAULT: aio_key\n");
  1547. goto out_put_req;
  1548. }
  1549. req->ki_res.obj = (u64)(unsigned long)user_iocb;
  1550. req->ki_res.data = iocb->aio_data;
  1551. req->ki_res.res = 0;
  1552. req->ki_res.res2 = 0;
  1553. switch (iocb->aio_lio_opcode) {
  1554. case IOCB_CMD_PREAD:
  1555. ret = aio_read(&req->rw, iocb, false, compat);
  1556. break;
  1557. case IOCB_CMD_PWRITE:
  1558. ret = aio_write(&req->rw, iocb, false, compat);
  1559. break;
  1560. case IOCB_CMD_PREADV:
  1561. ret = aio_read(&req->rw, iocb, true, compat);
  1562. break;
  1563. case IOCB_CMD_PWRITEV:
  1564. ret = aio_write(&req->rw, iocb, true, compat);
  1565. break;
  1566. case IOCB_CMD_FSYNC:
  1567. ret = aio_fsync(&req->fsync, iocb, false);
  1568. break;
  1569. case IOCB_CMD_FDSYNC:
  1570. ret = aio_fsync(&req->fsync, iocb, true);
  1571. break;
  1572. case IOCB_CMD_POLL:
  1573. ret = aio_poll(req, iocb);
  1574. break;
  1575. default:
  1576. pr_debug("invalid aio operation %d\n", iocb->aio_lio_opcode);
  1577. ret = -EINVAL;
  1578. break;
  1579. }
  1580. /* Done with the synchronous reference */
  1581. iocb_put(req);
  1582. /*
  1583. * If ret is 0, we'd either done aio_complete() ourselves or have
  1584. * arranged for that to be done asynchronously. Anything non-zero
  1585. * means that we need to destroy req ourselves.
  1586. */
  1587. if (!ret)
  1588. return 0;
  1589. out_put_req:
  1590. if (req->ki_eventfd)
  1591. eventfd_ctx_put(req->ki_eventfd);
  1592. iocb_destroy(req);
  1593. out_put_reqs_available:
  1594. put_reqs_available(ctx, 1);
  1595. return ret;
  1596. }
  1597. static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
  1598. bool compat)
  1599. {
  1600. struct iocb iocb;
  1601. if (unlikely(copy_from_user(&iocb, user_iocb, sizeof(iocb))))
  1602. return -EFAULT;
  1603. return __io_submit_one(ctx, &iocb, user_iocb, compat);
  1604. }
  1605. /* sys_io_submit:
  1606. * Queue the nr iocbs pointed to by iocbpp for processing. Returns
  1607. * the number of iocbs queued. May return -EINVAL if the aio_context
  1608. * specified by ctx_id is invalid, if nr is < 0, if the iocb at
  1609. * *iocbpp[0] is not properly initialized, if the operation specified
  1610. * is invalid for the file descriptor in the iocb. May fail with
  1611. * -EFAULT if any of the data structures point to invalid data. May
  1612. * fail with -EBADF if the file descriptor specified in the first
  1613. * iocb is invalid. May fail with -EAGAIN if insufficient resources
  1614. * are available to queue any iocbs. Will return 0 if nr is 0. Will
  1615. * fail with -ENOSYS if not implemented.
  1616. */
  1617. SYSCALL_DEFINE3(io_submit, aio_context_t, ctx_id, long, nr,
  1618. struct iocb __user * __user *, iocbpp)
  1619. {
  1620. struct kioctx *ctx;
  1621. long ret = 0;
  1622. int i = 0;
  1623. struct blk_plug plug;
  1624. if (unlikely(nr < 0))
  1625. return -EINVAL;
  1626. ctx = lookup_ioctx(ctx_id);
  1627. if (unlikely(!ctx)) {
  1628. pr_debug("EINVAL: invalid context id\n");
  1629. return -EINVAL;
  1630. }
  1631. if (nr > ctx->nr_events)
  1632. nr = ctx->nr_events;
  1633. blk_start_plug(&plug);
  1634. for (i = 0; i < nr; i++) {
  1635. struct iocb __user *user_iocb;
  1636. if (unlikely(get_user(user_iocb, iocbpp + i))) {
  1637. ret = -EFAULT;
  1638. break;
  1639. }
  1640. ret = io_submit_one(ctx, user_iocb, false);
  1641. if (ret)
  1642. break;
  1643. }
  1644. blk_finish_plug(&plug);
  1645. percpu_ref_put(&ctx->users);
  1646. return i ? i : ret;
  1647. }
  1648. #ifdef CONFIG_COMPAT
  1649. COMPAT_SYSCALL_DEFINE3(io_submit, compat_aio_context_t, ctx_id,
  1650. int, nr, compat_uptr_t __user *, iocbpp)
  1651. {
  1652. struct kioctx *ctx;
  1653. long ret = 0;
  1654. int i = 0;
  1655. struct blk_plug plug;
  1656. if (unlikely(nr < 0))
  1657. return -EINVAL;
  1658. ctx = lookup_ioctx(ctx_id);
  1659. if (unlikely(!ctx)) {
  1660. pr_debug("EINVAL: invalid context id\n");
  1661. return -EINVAL;
  1662. }
  1663. if (nr > ctx->nr_events)
  1664. nr = ctx->nr_events;
  1665. blk_start_plug(&plug);
  1666. for (i = 0; i < nr; i++) {
  1667. compat_uptr_t user_iocb;
  1668. if (unlikely(get_user(user_iocb, iocbpp + i))) {
  1669. ret = -EFAULT;
  1670. break;
  1671. }
  1672. ret = io_submit_one(ctx, compat_ptr(user_iocb), true);
  1673. if (ret)
  1674. break;
  1675. }
  1676. blk_finish_plug(&plug);
  1677. percpu_ref_put(&ctx->users);
  1678. return i ? i : ret;
  1679. }
  1680. #endif
  1681. /* sys_io_cancel:
  1682. * Attempts to cancel an iocb previously passed to io_submit. If
  1683. * the operation is successfully cancelled, the resulting event is
  1684. * copied into the memory pointed to by result without being placed
  1685. * into the completion queue and 0 is returned. May fail with
  1686. * -EFAULT if any of the data structures pointed to are invalid.
  1687. * May fail with -EINVAL if aio_context specified by ctx_id is
  1688. * invalid. May fail with -EAGAIN if the iocb specified was not
  1689. * cancelled. Will fail with -ENOSYS if not implemented.
  1690. */
  1691. SYSCALL_DEFINE3(io_cancel, aio_context_t, ctx_id, struct iocb __user *, iocb,
  1692. struct io_event __user *, result)
  1693. {
  1694. struct kioctx *ctx;
  1695. struct aio_kiocb *kiocb;
  1696. int ret = -EINVAL;
  1697. u32 key;
  1698. u64 obj = (u64)(unsigned long)iocb;
  1699. if (unlikely(get_user(key, &iocb->aio_key)))
  1700. return -EFAULT;
  1701. if (unlikely(key != KIOCB_KEY))
  1702. return -EINVAL;
  1703. ctx = lookup_ioctx(ctx_id);
  1704. if (unlikely(!ctx))
  1705. return -EINVAL;
  1706. spin_lock_irq(&ctx->ctx_lock);
  1707. /* TODO: use a hash or array, this sucks. */
  1708. list_for_each_entry(kiocb, &ctx->active_reqs, ki_list) {
  1709. if (kiocb->ki_res.obj == obj) {
  1710. ret = kiocb->ki_cancel(&kiocb->rw);
  1711. list_del_init(&kiocb->ki_list);
  1712. break;
  1713. }
  1714. }
  1715. spin_unlock_irq(&ctx->ctx_lock);
  1716. if (!ret) {
  1717. /*
  1718. * The result argument is no longer used - the io_event is
  1719. * always delivered via the ring buffer. -EINPROGRESS indicates
  1720. * cancellation is progress:
  1721. */
  1722. ret = -EINPROGRESS;
  1723. }
  1724. percpu_ref_put(&ctx->users);
  1725. return ret;
  1726. }
  1727. static long do_io_getevents(aio_context_t ctx_id,
  1728. long min_nr,
  1729. long nr,
  1730. struct io_event __user *events,
  1731. struct timespec64 *ts)
  1732. {
  1733. ktime_t until = ts ? timespec64_to_ktime(*ts) : KTIME_MAX;
  1734. struct kioctx *ioctx = lookup_ioctx(ctx_id);
  1735. long ret = -EINVAL;
  1736. if (likely(ioctx)) {
  1737. if (likely(min_nr <= nr && min_nr >= 0))
  1738. ret = read_events(ioctx, min_nr, nr, events, until);
  1739. percpu_ref_put(&ioctx->users);
  1740. }
  1741. return ret;
  1742. }
  1743. /* io_getevents:
  1744. * Attempts to read at least min_nr events and up to nr events from
  1745. * the completion queue for the aio_context specified by ctx_id. If
  1746. * it succeeds, the number of read events is returned. May fail with
  1747. * -EINVAL if ctx_id is invalid, if min_nr is out of range, if nr is
  1748. * out of range, if timeout is out of range. May fail with -EFAULT
  1749. * if any of the memory specified is invalid. May return 0 or
  1750. * < min_nr if the timeout specified by timeout has elapsed
  1751. * before sufficient events are available, where timeout == NULL
  1752. * specifies an infinite timeout. Note that the timeout pointed to by
  1753. * timeout is relative. Will fail with -ENOSYS if not implemented.
  1754. */
  1755. SYSCALL_DEFINE5(io_getevents, aio_context_t, ctx_id,
  1756. long, min_nr,
  1757. long, nr,
  1758. struct io_event __user *, events,
  1759. struct timespec __user *, timeout)
  1760. {
  1761. struct timespec64 ts;
  1762. int ret;
  1763. if (timeout && unlikely(get_timespec64(&ts, timeout)))
  1764. return -EFAULT;
  1765. ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &ts : NULL);
  1766. if (!ret && signal_pending(current))
  1767. ret = -EINTR;
  1768. return ret;
  1769. }
  1770. struct __aio_sigset {
  1771. const sigset_t __user *sigmask;
  1772. size_t sigsetsize;
  1773. };
  1774. SYSCALL_DEFINE6(io_pgetevents,
  1775. aio_context_t, ctx_id,
  1776. long, min_nr,
  1777. long, nr,
  1778. struct io_event __user *, events,
  1779. struct timespec __user *, timeout,
  1780. const struct __aio_sigset __user *, usig)
  1781. {
  1782. struct __aio_sigset ksig = { NULL, };
  1783. sigset_t ksigmask, sigsaved;
  1784. struct timespec64 ts;
  1785. int ret;
  1786. if (timeout && unlikely(get_timespec64(&ts, timeout)))
  1787. return -EFAULT;
  1788. if (usig && copy_from_user(&ksig, usig, sizeof(ksig)))
  1789. return -EFAULT;
  1790. if (ksig.sigmask) {
  1791. if (ksig.sigsetsize != sizeof(sigset_t))
  1792. return -EINVAL;
  1793. if (copy_from_user(&ksigmask, ksig.sigmask, sizeof(ksigmask)))
  1794. return -EFAULT;
  1795. sigdelsetmask(&ksigmask, sigmask(SIGKILL) | sigmask(SIGSTOP));
  1796. sigprocmask(SIG_SETMASK, &ksigmask, &sigsaved);
  1797. }
  1798. ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &ts : NULL);
  1799. if (signal_pending(current)) {
  1800. if (ksig.sigmask) {
  1801. current->saved_sigmask = sigsaved;
  1802. set_restore_sigmask();
  1803. }
  1804. if (!ret)
  1805. ret = -ERESTARTNOHAND;
  1806. } else {
  1807. if (ksig.sigmask)
  1808. sigprocmask(SIG_SETMASK, &sigsaved, NULL);
  1809. }
  1810. return ret;
  1811. }
  1812. #ifdef CONFIG_COMPAT
  1813. COMPAT_SYSCALL_DEFINE5(io_getevents, compat_aio_context_t, ctx_id,
  1814. compat_long_t, min_nr,
  1815. compat_long_t, nr,
  1816. struct io_event __user *, events,
  1817. struct compat_timespec __user *, timeout)
  1818. {
  1819. struct timespec64 t;
  1820. int ret;
  1821. if (timeout && compat_get_timespec64(&t, timeout))
  1822. return -EFAULT;
  1823. ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &t : NULL);
  1824. if (!ret && signal_pending(current))
  1825. ret = -EINTR;
  1826. return ret;
  1827. }
  1828. struct __compat_aio_sigset {
  1829. compat_sigset_t __user *sigmask;
  1830. compat_size_t sigsetsize;
  1831. };
  1832. COMPAT_SYSCALL_DEFINE6(io_pgetevents,
  1833. compat_aio_context_t, ctx_id,
  1834. compat_long_t, min_nr,
  1835. compat_long_t, nr,
  1836. struct io_event __user *, events,
  1837. struct compat_timespec __user *, timeout,
  1838. const struct __compat_aio_sigset __user *, usig)
  1839. {
  1840. struct __compat_aio_sigset ksig = { NULL, };
  1841. sigset_t ksigmask, sigsaved;
  1842. struct timespec64 t;
  1843. int ret;
  1844. if (timeout && compat_get_timespec64(&t, timeout))
  1845. return -EFAULT;
  1846. if (usig && copy_from_user(&ksig, usig, sizeof(ksig)))
  1847. return -EFAULT;
  1848. if (ksig.sigmask) {
  1849. if (ksig.sigsetsize != sizeof(compat_sigset_t))
  1850. return -EINVAL;
  1851. if (get_compat_sigset(&ksigmask, ksig.sigmask))
  1852. return -EFAULT;
  1853. sigdelsetmask(&ksigmask, sigmask(SIGKILL) | sigmask(SIGSTOP));
  1854. sigprocmask(SIG_SETMASK, &ksigmask, &sigsaved);
  1855. }
  1856. ret = do_io_getevents(ctx_id, min_nr, nr, events, timeout ? &t : NULL);
  1857. if (signal_pending(current)) {
  1858. if (ksig.sigmask) {
  1859. current->saved_sigmask = sigsaved;
  1860. set_restore_sigmask();
  1861. }
  1862. if (!ret)
  1863. ret = -ERESTARTNOHAND;
  1864. } else {
  1865. if (ksig.sigmask)
  1866. sigprocmask(SIG_SETMASK, &sigsaved, NULL);
  1867. }
  1868. return ret;
  1869. }
  1870. #endif