aio.c 54 KB

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