aio.c 61 KB

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