aio.c 44 KB

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