aio.c 43 KB

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