aio.c 45 KB

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