aio.c 55 KB

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