aio.c 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832
  1. /*
  2. * An async IO implementation for Linux
  3. * Written by Benjamin LaHaise <bcrl@kvack.org>
  4. *
  5. * Implements an efficient asynchronous io interface.
  6. *
  7. * Copyright 2000, 2001, 2002 Red Hat, Inc. All Rights Reserved.
  8. *
  9. * See ../COPYING for licensing terms.
  10. */
  11. #include <linux/kernel.h>
  12. #include <linux/init.h>
  13. #include <linux/errno.h>
  14. #include <linux/time.h>
  15. #include <linux/aio_abi.h>
  16. #include <linux/module.h>
  17. #include <linux/syscalls.h>
  18. #include <linux/backing-dev.h>
  19. #include <linux/uio.h>
  20. #define DEBUG 0
  21. #include <linux/sched.h>
  22. #include <linux/fs.h>
  23. #include <linux/file.h>
  24. #include <linux/mm.h>
  25. #include <linux/mman.h>
  26. #include <linux/mmu_context.h>
  27. #include <linux/slab.h>
  28. #include <linux/timer.h>
  29. #include <linux/aio.h>
  30. #include <linux/highmem.h>
  31. #include <linux/workqueue.h>
  32. #include <linux/security.h>
  33. #include <linux/eventfd.h>
  34. #include <linux/blkdev.h>
  35. #include <linux/mempool.h>
  36. #include <linux/hash.h>
  37. #include <linux/compat.h>
  38. #include <asm/kmap_types.h>
  39. #include <asm/uaccess.h>
  40. #if DEBUG > 1
  41. #define dprintk printk
  42. #else
  43. #define dprintk(x...) do { ; } while (0)
  44. #endif
  45. /*------ sysctl variables----*/
  46. static DEFINE_SPINLOCK(aio_nr_lock);
  47. unsigned long aio_nr; /* current system wide number of aio requests */
  48. unsigned long aio_max_nr = 0x10000; /* system wide maximum number of aio requests */
  49. /*----end sysctl variables---*/
  50. static struct kmem_cache *kiocb_cachep;
  51. static struct kmem_cache *kioctx_cachep;
  52. static struct workqueue_struct *aio_wq;
  53. /* Used for rare fput completion. */
  54. static void aio_fput_routine(struct work_struct *);
  55. static DECLARE_WORK(fput_work, aio_fput_routine);
  56. static DEFINE_SPINLOCK(fput_lock);
  57. static LIST_HEAD(fput_head);
  58. #define AIO_BATCH_HASH_BITS 3 /* allocated on-stack, so don't go crazy */
  59. #define AIO_BATCH_HASH_SIZE (1 << AIO_BATCH_HASH_BITS)
  60. struct aio_batch_entry {
  61. struct hlist_node list;
  62. struct address_space *mapping;
  63. };
  64. mempool_t *abe_pool;
  65. static void aio_kick_handler(struct work_struct *);
  66. static void aio_queue_work(struct kioctx *);
  67. /* aio_setup
  68. * Creates the slab caches used by the aio routines, panic on
  69. * failure as this is done early during the boot sequence.
  70. */
  71. static int __init aio_setup(void)
  72. {
  73. kiocb_cachep = KMEM_CACHE(kiocb, SLAB_HWCACHE_ALIGN|SLAB_PANIC);
  74. kioctx_cachep = KMEM_CACHE(kioctx,SLAB_HWCACHE_ALIGN|SLAB_PANIC);
  75. aio_wq = create_workqueue("aio");
  76. abe_pool = mempool_create_kmalloc_pool(1, sizeof(struct aio_batch_entry));
  77. BUG_ON(!aio_wq || !abe_pool);
  78. pr_debug("aio_setup: sizeof(struct page) = %d\n", (int)sizeof(struct page));
  79. return 0;
  80. }
  81. __initcall(aio_setup);
  82. static void aio_free_ring(struct kioctx *ctx)
  83. {
  84. struct aio_ring_info *info = &ctx->ring_info;
  85. long i;
  86. for (i=0; i<info->nr_pages; i++)
  87. put_page(info->ring_pages[i]);
  88. if (info->mmap_size) {
  89. down_write(&ctx->mm->mmap_sem);
  90. do_munmap(ctx->mm, info->mmap_base, info->mmap_size);
  91. up_write(&ctx->mm->mmap_sem);
  92. }
  93. if (info->ring_pages && info->ring_pages != info->internal_pages)
  94. kfree(info->ring_pages);
  95. info->ring_pages = NULL;
  96. info->nr = 0;
  97. }
  98. static int aio_setup_ring(struct kioctx *ctx)
  99. {
  100. struct aio_ring *ring;
  101. struct aio_ring_info *info = &ctx->ring_info;
  102. unsigned nr_events = ctx->max_reqs;
  103. unsigned long size;
  104. int nr_pages;
  105. /* Compensate for the ring buffer's head/tail overlap entry */
  106. nr_events += 2; /* 1 is required, 2 for good luck */
  107. size = sizeof(struct aio_ring);
  108. size += sizeof(struct io_event) * nr_events;
  109. nr_pages = (size + PAGE_SIZE-1) >> PAGE_SHIFT;
  110. if (nr_pages < 0)
  111. return -EINVAL;
  112. nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring)) / sizeof(struct io_event);
  113. info->nr = 0;
  114. info->ring_pages = info->internal_pages;
  115. if (nr_pages > AIO_RING_PAGES) {
  116. info->ring_pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);
  117. if (!info->ring_pages)
  118. return -ENOMEM;
  119. }
  120. info->mmap_size = nr_pages * PAGE_SIZE;
  121. dprintk("attempting mmap of %lu bytes\n", info->mmap_size);
  122. down_write(&ctx->mm->mmap_sem);
  123. info->mmap_base = do_mmap(NULL, 0, info->mmap_size,
  124. PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE,
  125. 0);
  126. if (IS_ERR((void *)info->mmap_base)) {
  127. up_write(&ctx->mm->mmap_sem);
  128. info->mmap_size = 0;
  129. aio_free_ring(ctx);
  130. return -EAGAIN;
  131. }
  132. dprintk("mmap address: 0x%08lx\n", info->mmap_base);
  133. info->nr_pages = get_user_pages(current, ctx->mm,
  134. info->mmap_base, nr_pages,
  135. 1, 0, info->ring_pages, NULL);
  136. up_write(&ctx->mm->mmap_sem);
  137. if (unlikely(info->nr_pages != nr_pages)) {
  138. aio_free_ring(ctx);
  139. return -EAGAIN;
  140. }
  141. ctx->user_id = info->mmap_base;
  142. info->nr = nr_events; /* trusted copy */
  143. ring = kmap_atomic(info->ring_pages[0], KM_USER0);
  144. ring->nr = nr_events; /* user copy */
  145. ring->id = ctx->user_id;
  146. ring->head = ring->tail = 0;
  147. ring->magic = AIO_RING_MAGIC;
  148. ring->compat_features = AIO_RING_COMPAT_FEATURES;
  149. ring->incompat_features = AIO_RING_INCOMPAT_FEATURES;
  150. ring->header_length = sizeof(struct aio_ring);
  151. kunmap_atomic(ring, KM_USER0);
  152. return 0;
  153. }
  154. /* aio_ring_event: returns a pointer to the event at the given index from
  155. * kmap_atomic(, km). Release the pointer with put_aio_ring_event();
  156. */
  157. #define AIO_EVENTS_PER_PAGE (PAGE_SIZE / sizeof(struct io_event))
  158. #define AIO_EVENTS_FIRST_PAGE ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event))
  159. #define AIO_EVENTS_OFFSET (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE)
  160. #define aio_ring_event(info, nr, km) ({ \
  161. unsigned pos = (nr) + AIO_EVENTS_OFFSET; \
  162. struct io_event *__event; \
  163. __event = kmap_atomic( \
  164. (info)->ring_pages[pos / AIO_EVENTS_PER_PAGE], km); \
  165. __event += pos % AIO_EVENTS_PER_PAGE; \
  166. __event; \
  167. })
  168. #define put_aio_ring_event(event, km) do { \
  169. struct io_event *__event = (event); \
  170. (void)__event; \
  171. kunmap_atomic((void *)((unsigned long)__event & PAGE_MASK), km); \
  172. } while(0)
  173. static void ctx_rcu_free(struct rcu_head *head)
  174. {
  175. struct kioctx *ctx = container_of(head, struct kioctx, rcu_head);
  176. unsigned nr_events = ctx->max_reqs;
  177. kmem_cache_free(kioctx_cachep, ctx);
  178. if (nr_events) {
  179. spin_lock(&aio_nr_lock);
  180. BUG_ON(aio_nr - nr_events > aio_nr);
  181. aio_nr -= nr_events;
  182. spin_unlock(&aio_nr_lock);
  183. }
  184. }
  185. /* __put_ioctx
  186. * Called when the last user of an aio context has gone away,
  187. * and the struct needs to be freed.
  188. */
  189. static void __put_ioctx(struct kioctx *ctx)
  190. {
  191. BUG_ON(ctx->reqs_active);
  192. cancel_delayed_work(&ctx->wq);
  193. cancel_work_sync(&ctx->wq.work);
  194. aio_free_ring(ctx);
  195. mmdrop(ctx->mm);
  196. ctx->mm = NULL;
  197. pr_debug("__put_ioctx: freeing %p\n", ctx);
  198. call_rcu(&ctx->rcu_head, ctx_rcu_free);
  199. }
  200. #define get_ioctx(kioctx) do { \
  201. BUG_ON(atomic_read(&(kioctx)->users) <= 0); \
  202. atomic_inc(&(kioctx)->users); \
  203. } while (0)
  204. #define put_ioctx(kioctx) do { \
  205. BUG_ON(atomic_read(&(kioctx)->users) <= 0); \
  206. if (unlikely(atomic_dec_and_test(&(kioctx)->users))) \
  207. __put_ioctx(kioctx); \
  208. } while (0)
  209. /* ioctx_alloc
  210. * Allocates and initializes an ioctx. Returns an ERR_PTR if it failed.
  211. */
  212. static struct kioctx *ioctx_alloc(unsigned nr_events)
  213. {
  214. struct mm_struct *mm;
  215. struct kioctx *ctx;
  216. int did_sync = 0;
  217. /* Prevent overflows */
  218. if ((nr_events > (0x10000000U / sizeof(struct io_event))) ||
  219. (nr_events > (0x10000000U / sizeof(struct kiocb)))) {
  220. pr_debug("ENOMEM: nr_events too high\n");
  221. return ERR_PTR(-EINVAL);
  222. }
  223. if ((unsigned long)nr_events > aio_max_nr)
  224. return ERR_PTR(-EAGAIN);
  225. ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL);
  226. if (!ctx)
  227. return ERR_PTR(-ENOMEM);
  228. ctx->max_reqs = nr_events;
  229. mm = ctx->mm = current->mm;
  230. atomic_inc(&mm->mm_count);
  231. atomic_set(&ctx->users, 1);
  232. spin_lock_init(&ctx->ctx_lock);
  233. spin_lock_init(&ctx->ring_info.ring_lock);
  234. init_waitqueue_head(&ctx->wait);
  235. INIT_LIST_HEAD(&ctx->active_reqs);
  236. INIT_LIST_HEAD(&ctx->run_list);
  237. INIT_DELAYED_WORK(&ctx->wq, aio_kick_handler);
  238. if (aio_setup_ring(ctx) < 0)
  239. goto out_freectx;
  240. /* limit the number of system wide aios */
  241. do {
  242. spin_lock_bh(&aio_nr_lock);
  243. if (aio_nr + nr_events > aio_max_nr ||
  244. aio_nr + nr_events < aio_nr)
  245. ctx->max_reqs = 0;
  246. else
  247. aio_nr += ctx->max_reqs;
  248. spin_unlock_bh(&aio_nr_lock);
  249. if (ctx->max_reqs || did_sync)
  250. break;
  251. /* wait for rcu callbacks to have completed before giving up */
  252. synchronize_rcu();
  253. did_sync = 1;
  254. ctx->max_reqs = nr_events;
  255. } while (1);
  256. if (ctx->max_reqs == 0)
  257. goto out_cleanup;
  258. /* now link into global list. */
  259. spin_lock(&mm->ioctx_lock);
  260. hlist_add_head_rcu(&ctx->list, &mm->ioctx_list);
  261. spin_unlock(&mm->ioctx_lock);
  262. dprintk("aio: allocated ioctx %p[%ld]: mm=%p mask=0x%x\n",
  263. ctx, ctx->user_id, current->mm, ctx->ring_info.nr);
  264. return ctx;
  265. out_cleanup:
  266. __put_ioctx(ctx);
  267. return ERR_PTR(-EAGAIN);
  268. out_freectx:
  269. mmdrop(mm);
  270. kmem_cache_free(kioctx_cachep, ctx);
  271. ctx = ERR_PTR(-ENOMEM);
  272. dprintk("aio: error allocating ioctx %p\n", ctx);
  273. return ctx;
  274. }
  275. /* aio_cancel_all
  276. * Cancels all outstanding aio requests on an aio context. Used
  277. * when the processes owning a context have all exited to encourage
  278. * the rapid destruction of the kioctx.
  279. */
  280. static void aio_cancel_all(struct kioctx *ctx)
  281. {
  282. int (*cancel)(struct kiocb *, struct io_event *);
  283. struct io_event res;
  284. spin_lock_irq(&ctx->ctx_lock);
  285. ctx->dead = 1;
  286. while (!list_empty(&ctx->active_reqs)) {
  287. struct list_head *pos = ctx->active_reqs.next;
  288. struct kiocb *iocb = list_kiocb(pos);
  289. list_del_init(&iocb->ki_list);
  290. cancel = iocb->ki_cancel;
  291. kiocbSetCancelled(iocb);
  292. if (cancel) {
  293. iocb->ki_users++;
  294. spin_unlock_irq(&ctx->ctx_lock);
  295. cancel(iocb, &res);
  296. spin_lock_irq(&ctx->ctx_lock);
  297. }
  298. }
  299. spin_unlock_irq(&ctx->ctx_lock);
  300. }
  301. static void wait_for_all_aios(struct kioctx *ctx)
  302. {
  303. struct task_struct *tsk = current;
  304. DECLARE_WAITQUEUE(wait, tsk);
  305. spin_lock_irq(&ctx->ctx_lock);
  306. if (!ctx->reqs_active)
  307. goto out;
  308. add_wait_queue(&ctx->wait, &wait);
  309. set_task_state(tsk, TASK_UNINTERRUPTIBLE);
  310. while (ctx->reqs_active) {
  311. spin_unlock_irq(&ctx->ctx_lock);
  312. io_schedule();
  313. set_task_state(tsk, TASK_UNINTERRUPTIBLE);
  314. spin_lock_irq(&ctx->ctx_lock);
  315. }
  316. __set_task_state(tsk, TASK_RUNNING);
  317. remove_wait_queue(&ctx->wait, &wait);
  318. out:
  319. spin_unlock_irq(&ctx->ctx_lock);
  320. }
  321. /* wait_on_sync_kiocb:
  322. * Waits on the given sync kiocb to complete.
  323. */
  324. ssize_t wait_on_sync_kiocb(struct kiocb *iocb)
  325. {
  326. while (iocb->ki_users) {
  327. set_current_state(TASK_UNINTERRUPTIBLE);
  328. if (!iocb->ki_users)
  329. break;
  330. io_schedule();
  331. }
  332. __set_current_state(TASK_RUNNING);
  333. return iocb->ki_user_data;
  334. }
  335. EXPORT_SYMBOL(wait_on_sync_kiocb);
  336. /* exit_aio: called when the last user of mm goes away. At this point,
  337. * there is no way for any new requests to be submited or any of the
  338. * io_* syscalls to be called on the context. However, there may be
  339. * outstanding requests which hold references to the context; as they
  340. * go away, they will call put_ioctx and release any pinned memory
  341. * associated with the request (held via struct page * references).
  342. */
  343. void exit_aio(struct mm_struct *mm)
  344. {
  345. struct kioctx *ctx;
  346. while (!hlist_empty(&mm->ioctx_list)) {
  347. ctx = hlist_entry(mm->ioctx_list.first, struct kioctx, list);
  348. hlist_del_rcu(&ctx->list);
  349. aio_cancel_all(ctx);
  350. wait_for_all_aios(ctx);
  351. /*
  352. * Ensure we don't leave the ctx on the aio_wq
  353. */
  354. cancel_work_sync(&ctx->wq.work);
  355. if (1 != atomic_read(&ctx->users))
  356. printk(KERN_DEBUG
  357. "exit_aio:ioctx still alive: %d %d %d\n",
  358. atomic_read(&ctx->users), ctx->dead,
  359. ctx->reqs_active);
  360. put_ioctx(ctx);
  361. }
  362. }
  363. /* aio_get_req
  364. * Allocate a slot for an aio request. Increments the users count
  365. * of the kioctx so that the kioctx stays around until all requests are
  366. * complete. Returns NULL if no requests are free.
  367. *
  368. * Returns with kiocb->users set to 2. The io submit code path holds
  369. * an extra reference while submitting the i/o.
  370. * This prevents races between the aio code path referencing the
  371. * req (after submitting it) and aio_complete() freeing the req.
  372. */
  373. static struct kiocb *__aio_get_req(struct kioctx *ctx)
  374. {
  375. struct kiocb *req = NULL;
  376. struct aio_ring *ring;
  377. int okay = 0;
  378. req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL);
  379. if (unlikely(!req))
  380. return NULL;
  381. req->ki_flags = 0;
  382. req->ki_users = 2;
  383. req->ki_key = 0;
  384. req->ki_ctx = ctx;
  385. req->ki_cancel = NULL;
  386. req->ki_retry = NULL;
  387. req->ki_dtor = NULL;
  388. req->private = NULL;
  389. req->ki_iovec = NULL;
  390. INIT_LIST_HEAD(&req->ki_run_list);
  391. req->ki_eventfd = NULL;
  392. /* Check if the completion queue has enough free space to
  393. * accept an event from this io.
  394. */
  395. spin_lock_irq(&ctx->ctx_lock);
  396. ring = kmap_atomic(ctx->ring_info.ring_pages[0], KM_USER0);
  397. if (ctx->reqs_active < aio_ring_avail(&ctx->ring_info, ring)) {
  398. list_add(&req->ki_list, &ctx->active_reqs);
  399. ctx->reqs_active++;
  400. okay = 1;
  401. }
  402. kunmap_atomic(ring, KM_USER0);
  403. spin_unlock_irq(&ctx->ctx_lock);
  404. if (!okay) {
  405. kmem_cache_free(kiocb_cachep, req);
  406. req = NULL;
  407. }
  408. return req;
  409. }
  410. static inline struct kiocb *aio_get_req(struct kioctx *ctx)
  411. {
  412. struct kiocb *req;
  413. /* Handle a potential starvation case -- should be exceedingly rare as
  414. * requests will be stuck on fput_head only if the aio_fput_routine is
  415. * delayed and the requests were the last user of the struct file.
  416. */
  417. req = __aio_get_req(ctx);
  418. if (unlikely(NULL == req)) {
  419. aio_fput_routine(NULL);
  420. req = __aio_get_req(ctx);
  421. }
  422. return req;
  423. }
  424. static inline void really_put_req(struct kioctx *ctx, struct kiocb *req)
  425. {
  426. assert_spin_locked(&ctx->ctx_lock);
  427. if (req->ki_eventfd != NULL)
  428. eventfd_ctx_put(req->ki_eventfd);
  429. if (req->ki_dtor)
  430. req->ki_dtor(req);
  431. if (req->ki_iovec != &req->ki_inline_vec)
  432. kfree(req->ki_iovec);
  433. kmem_cache_free(kiocb_cachep, req);
  434. ctx->reqs_active--;
  435. if (unlikely(!ctx->reqs_active && ctx->dead))
  436. wake_up(&ctx->wait);
  437. }
  438. static void aio_fput_routine(struct work_struct *data)
  439. {
  440. spin_lock_irq(&fput_lock);
  441. while (likely(!list_empty(&fput_head))) {
  442. struct kiocb *req = list_kiocb(fput_head.next);
  443. struct kioctx *ctx = req->ki_ctx;
  444. list_del(&req->ki_list);
  445. spin_unlock_irq(&fput_lock);
  446. /* Complete the fput(s) */
  447. if (req->ki_filp != NULL)
  448. fput(req->ki_filp);
  449. /* Link the iocb into the context's free list */
  450. spin_lock_irq(&ctx->ctx_lock);
  451. really_put_req(ctx, req);
  452. spin_unlock_irq(&ctx->ctx_lock);
  453. put_ioctx(ctx);
  454. spin_lock_irq(&fput_lock);
  455. }
  456. spin_unlock_irq(&fput_lock);
  457. }
  458. /* __aio_put_req
  459. * Returns true if this put was the last user of the request.
  460. */
  461. static int __aio_put_req(struct kioctx *ctx, struct kiocb *req)
  462. {
  463. dprintk(KERN_DEBUG "aio_put(%p): f_count=%ld\n",
  464. req, atomic_long_read(&req->ki_filp->f_count));
  465. assert_spin_locked(&ctx->ctx_lock);
  466. req->ki_users--;
  467. BUG_ON(req->ki_users < 0);
  468. if (likely(req->ki_users))
  469. return 0;
  470. list_del(&req->ki_list); /* remove from active_reqs */
  471. req->ki_cancel = NULL;
  472. req->ki_retry = NULL;
  473. /*
  474. * Try to optimize the aio and eventfd file* puts, by avoiding to
  475. * schedule work in case it is not final fput() time. In normal cases,
  476. * we would not be holding the last reference to the file*, so
  477. * this function will be executed w/out any aio kthread wakeup.
  478. */
  479. if (unlikely(!fput_atomic(req->ki_filp))) {
  480. get_ioctx(ctx);
  481. spin_lock(&fput_lock);
  482. list_add(&req->ki_list, &fput_head);
  483. spin_unlock(&fput_lock);
  484. queue_work(aio_wq, &fput_work);
  485. } else {
  486. req->ki_filp = NULL;
  487. really_put_req(ctx, req);
  488. }
  489. return 1;
  490. }
  491. /* aio_put_req
  492. * Returns true if this put was the last user of the kiocb,
  493. * false if the request is still in use.
  494. */
  495. int aio_put_req(struct kiocb *req)
  496. {
  497. struct kioctx *ctx = req->ki_ctx;
  498. int ret;
  499. spin_lock_irq(&ctx->ctx_lock);
  500. ret = __aio_put_req(ctx, req);
  501. spin_unlock_irq(&ctx->ctx_lock);
  502. return ret;
  503. }
  504. EXPORT_SYMBOL(aio_put_req);
  505. static struct kioctx *lookup_ioctx(unsigned long ctx_id)
  506. {
  507. struct mm_struct *mm = current->mm;
  508. struct kioctx *ctx, *ret = NULL;
  509. struct hlist_node *n;
  510. rcu_read_lock();
  511. hlist_for_each_entry_rcu(ctx, n, &mm->ioctx_list, list) {
  512. if (ctx->user_id == ctx_id && !ctx->dead) {
  513. get_ioctx(ctx);
  514. ret = ctx;
  515. break;
  516. }
  517. }
  518. rcu_read_unlock();
  519. return ret;
  520. }
  521. /*
  522. * Queue up a kiocb to be retried. Assumes that the kiocb
  523. * has already been marked as kicked, and places it on
  524. * the retry run list for the corresponding ioctx, if it
  525. * isn't already queued. Returns 1 if it actually queued
  526. * the kiocb (to tell the caller to activate the work
  527. * queue to process it), or 0, if it found that it was
  528. * already queued.
  529. */
  530. static inline int __queue_kicked_iocb(struct kiocb *iocb)
  531. {
  532. struct kioctx *ctx = iocb->ki_ctx;
  533. assert_spin_locked(&ctx->ctx_lock);
  534. if (list_empty(&iocb->ki_run_list)) {
  535. list_add_tail(&iocb->ki_run_list,
  536. &ctx->run_list);
  537. return 1;
  538. }
  539. return 0;
  540. }
  541. /* aio_run_iocb
  542. * This is the core aio execution routine. It is
  543. * invoked both for initial i/o submission and
  544. * subsequent retries via the aio_kick_handler.
  545. * Expects to be invoked with iocb->ki_ctx->lock
  546. * already held. The lock is released and reacquired
  547. * as needed during processing.
  548. *
  549. * Calls the iocb retry method (already setup for the
  550. * iocb on initial submission) for operation specific
  551. * handling, but takes care of most of common retry
  552. * execution details for a given iocb. The retry method
  553. * needs to be non-blocking as far as possible, to avoid
  554. * holding up other iocbs waiting to be serviced by the
  555. * retry kernel thread.
  556. *
  557. * The trickier parts in this code have to do with
  558. * ensuring that only one retry instance is in progress
  559. * for a given iocb at any time. Providing that guarantee
  560. * simplifies the coding of individual aio operations as
  561. * it avoids various potential races.
  562. */
  563. static ssize_t aio_run_iocb(struct kiocb *iocb)
  564. {
  565. struct kioctx *ctx = iocb->ki_ctx;
  566. ssize_t (*retry)(struct kiocb *);
  567. ssize_t ret;
  568. if (!(retry = iocb->ki_retry)) {
  569. printk("aio_run_iocb: iocb->ki_retry = NULL\n");
  570. return 0;
  571. }
  572. /*
  573. * We don't want the next retry iteration for this
  574. * operation to start until this one has returned and
  575. * updated the iocb state. However, wait_queue functions
  576. * can trigger a kick_iocb from interrupt context in the
  577. * meantime, indicating that data is available for the next
  578. * iteration. We want to remember that and enable the
  579. * next retry iteration _after_ we are through with
  580. * this one.
  581. *
  582. * So, in order to be able to register a "kick", but
  583. * prevent it from being queued now, we clear the kick
  584. * flag, but make the kick code *think* that the iocb is
  585. * still on the run list until we are actually done.
  586. * When we are done with this iteration, we check if
  587. * the iocb was kicked in the meantime and if so, queue
  588. * it up afresh.
  589. */
  590. kiocbClearKicked(iocb);
  591. /*
  592. * This is so that aio_complete knows it doesn't need to
  593. * pull the iocb off the run list (We can't just call
  594. * INIT_LIST_HEAD because we don't want a kick_iocb to
  595. * queue this on the run list yet)
  596. */
  597. iocb->ki_run_list.next = iocb->ki_run_list.prev = NULL;
  598. spin_unlock_irq(&ctx->ctx_lock);
  599. /* Quit retrying if the i/o has been cancelled */
  600. if (kiocbIsCancelled(iocb)) {
  601. ret = -EINTR;
  602. aio_complete(iocb, ret, 0);
  603. /* must not access the iocb after this */
  604. goto out;
  605. }
  606. /*
  607. * Now we are all set to call the retry method in async
  608. * context.
  609. */
  610. ret = retry(iocb);
  611. if (ret != -EIOCBRETRY && ret != -EIOCBQUEUED) {
  612. /*
  613. * There's no easy way to restart the syscall since other AIO's
  614. * may be already running. Just fail this IO with EINTR.
  615. */
  616. if (unlikely(ret == -ERESTARTSYS || ret == -ERESTARTNOINTR ||
  617. ret == -ERESTARTNOHAND || ret == -ERESTART_RESTARTBLOCK))
  618. ret = -EINTR;
  619. aio_complete(iocb, ret, 0);
  620. }
  621. out:
  622. spin_lock_irq(&ctx->ctx_lock);
  623. if (-EIOCBRETRY == ret) {
  624. /*
  625. * OK, now that we are done with this iteration
  626. * and know that there is more left to go,
  627. * this is where we let go so that a subsequent
  628. * "kick" can start the next iteration
  629. */
  630. /* will make __queue_kicked_iocb succeed from here on */
  631. INIT_LIST_HEAD(&iocb->ki_run_list);
  632. /* we must queue the next iteration ourselves, if it
  633. * has already been kicked */
  634. if (kiocbIsKicked(iocb)) {
  635. __queue_kicked_iocb(iocb);
  636. /*
  637. * __queue_kicked_iocb will always return 1 here, because
  638. * iocb->ki_run_list is empty at this point so it should
  639. * be safe to unconditionally queue the context into the
  640. * work queue.
  641. */
  642. aio_queue_work(ctx);
  643. }
  644. }
  645. return ret;
  646. }
  647. /*
  648. * __aio_run_iocbs:
  649. * Process all pending retries queued on the ioctx
  650. * run list.
  651. * Assumes it is operating within the aio issuer's mm
  652. * context.
  653. */
  654. static int __aio_run_iocbs(struct kioctx *ctx)
  655. {
  656. struct kiocb *iocb;
  657. struct list_head run_list;
  658. assert_spin_locked(&ctx->ctx_lock);
  659. list_replace_init(&ctx->run_list, &run_list);
  660. while (!list_empty(&run_list)) {
  661. iocb = list_entry(run_list.next, struct kiocb,
  662. ki_run_list);
  663. list_del(&iocb->ki_run_list);
  664. /*
  665. * Hold an extra reference while retrying i/o.
  666. */
  667. iocb->ki_users++; /* grab extra reference */
  668. aio_run_iocb(iocb);
  669. __aio_put_req(ctx, iocb);
  670. }
  671. if (!list_empty(&ctx->run_list))
  672. return 1;
  673. return 0;
  674. }
  675. static void aio_queue_work(struct kioctx * ctx)
  676. {
  677. unsigned long timeout;
  678. /*
  679. * if someone is waiting, get the work started right
  680. * away, otherwise, use a longer delay
  681. */
  682. smp_mb();
  683. if (waitqueue_active(&ctx->wait))
  684. timeout = 1;
  685. else
  686. timeout = HZ/10;
  687. queue_delayed_work(aio_wq, &ctx->wq, timeout);
  688. }
  689. /*
  690. * aio_run_all_iocbs:
  691. * Process all pending retries queued on the ioctx
  692. * run list, and keep running them until the list
  693. * stays empty.
  694. * Assumes it is operating within the aio issuer's mm context.
  695. */
  696. static inline void aio_run_all_iocbs(struct kioctx *ctx)
  697. {
  698. spin_lock_irq(&ctx->ctx_lock);
  699. while (__aio_run_iocbs(ctx))
  700. ;
  701. spin_unlock_irq(&ctx->ctx_lock);
  702. }
  703. /*
  704. * aio_kick_handler:
  705. * Work queue handler triggered to process pending
  706. * retries on an ioctx. Takes on the aio issuer's
  707. * mm context before running the iocbs, so that
  708. * copy_xxx_user operates on the issuer's address
  709. * space.
  710. * Run on aiod's context.
  711. */
  712. static void aio_kick_handler(struct work_struct *work)
  713. {
  714. struct kioctx *ctx = container_of(work, struct kioctx, wq.work);
  715. mm_segment_t oldfs = get_fs();
  716. struct mm_struct *mm;
  717. int requeue;
  718. set_fs(USER_DS);
  719. use_mm(ctx->mm);
  720. spin_lock_irq(&ctx->ctx_lock);
  721. requeue =__aio_run_iocbs(ctx);
  722. mm = ctx->mm;
  723. spin_unlock_irq(&ctx->ctx_lock);
  724. unuse_mm(mm);
  725. set_fs(oldfs);
  726. /*
  727. * we're in a worker thread already, don't use queue_delayed_work,
  728. */
  729. if (requeue)
  730. queue_delayed_work(aio_wq, &ctx->wq, 0);
  731. }
  732. /*
  733. * Called by kick_iocb to queue the kiocb for retry
  734. * and if required activate the aio work queue to process
  735. * it
  736. */
  737. static void try_queue_kicked_iocb(struct kiocb *iocb)
  738. {
  739. struct kioctx *ctx = iocb->ki_ctx;
  740. unsigned long flags;
  741. int run = 0;
  742. spin_lock_irqsave(&ctx->ctx_lock, flags);
  743. /* set this inside the lock so that we can't race with aio_run_iocb()
  744. * testing it and putting the iocb on the run list under the lock */
  745. if (!kiocbTryKick(iocb))
  746. run = __queue_kicked_iocb(iocb);
  747. spin_unlock_irqrestore(&ctx->ctx_lock, flags);
  748. if (run)
  749. aio_queue_work(ctx);
  750. }
  751. /*
  752. * kick_iocb:
  753. * Called typically from a wait queue callback context
  754. * to trigger a retry of the iocb.
  755. * The retry is usually executed by aio workqueue
  756. * threads (See aio_kick_handler).
  757. */
  758. void kick_iocb(struct kiocb *iocb)
  759. {
  760. /* sync iocbs are easy: they can only ever be executing from a
  761. * single context. */
  762. if (is_sync_kiocb(iocb)) {
  763. kiocbSetKicked(iocb);
  764. wake_up_process(iocb->ki_obj.tsk);
  765. return;
  766. }
  767. try_queue_kicked_iocb(iocb);
  768. }
  769. EXPORT_SYMBOL(kick_iocb);
  770. /* aio_complete
  771. * Called when the io request on the given iocb is complete.
  772. * Returns true if this is the last user of the request. The
  773. * only other user of the request can be the cancellation code.
  774. */
  775. int aio_complete(struct kiocb *iocb, long res, long res2)
  776. {
  777. struct kioctx *ctx = iocb->ki_ctx;
  778. struct aio_ring_info *info;
  779. struct aio_ring *ring;
  780. struct io_event *event;
  781. unsigned long flags;
  782. unsigned long tail;
  783. int ret;
  784. /*
  785. * Special case handling for sync iocbs:
  786. * - events go directly into the iocb for fast handling
  787. * - the sync task with the iocb in its stack holds the single iocb
  788. * ref, no other paths have a way to get another ref
  789. * - the sync task helpfully left a reference to itself in the iocb
  790. */
  791. if (is_sync_kiocb(iocb)) {
  792. BUG_ON(iocb->ki_users != 1);
  793. iocb->ki_user_data = res;
  794. iocb->ki_users = 0;
  795. wake_up_process(iocb->ki_obj.tsk);
  796. return 1;
  797. }
  798. info = &ctx->ring_info;
  799. /* add a completion event to the ring buffer.
  800. * must be done holding ctx->ctx_lock to prevent
  801. * other code from messing with the tail
  802. * pointer since we might be called from irq
  803. * context.
  804. */
  805. spin_lock_irqsave(&ctx->ctx_lock, flags);
  806. if (iocb->ki_run_list.prev && !list_empty(&iocb->ki_run_list))
  807. list_del_init(&iocb->ki_run_list);
  808. /*
  809. * cancelled requests don't get events, userland was given one
  810. * when the event got cancelled.
  811. */
  812. if (kiocbIsCancelled(iocb))
  813. goto put_rq;
  814. ring = kmap_atomic(info->ring_pages[0], KM_IRQ1);
  815. tail = info->tail;
  816. event = aio_ring_event(info, tail, KM_IRQ0);
  817. if (++tail >= info->nr)
  818. tail = 0;
  819. event->obj = (u64)(unsigned long)iocb->ki_obj.user;
  820. event->data = iocb->ki_user_data;
  821. event->res = res;
  822. event->res2 = res2;
  823. dprintk("aio_complete: %p[%lu]: %p: %p %Lx %lx %lx\n",
  824. ctx, tail, iocb, iocb->ki_obj.user, iocb->ki_user_data,
  825. res, res2);
  826. /* after flagging the request as done, we
  827. * must never even look at it again
  828. */
  829. smp_wmb(); /* make event visible before updating tail */
  830. info->tail = tail;
  831. ring->tail = tail;
  832. put_aio_ring_event(event, KM_IRQ0);
  833. kunmap_atomic(ring, KM_IRQ1);
  834. pr_debug("added to ring %p at [%lu]\n", iocb, tail);
  835. /*
  836. * Check if the user asked us to deliver the result through an
  837. * eventfd. The eventfd_signal() function is safe to be called
  838. * from IRQ context.
  839. */
  840. if (iocb->ki_eventfd != NULL)
  841. eventfd_signal(iocb->ki_eventfd, 1);
  842. put_rq:
  843. /* everything turned out well, dispose of the aiocb. */
  844. ret = __aio_put_req(ctx, iocb);
  845. /*
  846. * We have to order our ring_info tail store above and test
  847. * of the wait list below outside the wait lock. This is
  848. * like in wake_up_bit() where clearing a bit has to be
  849. * ordered with the unlocked test.
  850. */
  851. smp_mb();
  852. if (waitqueue_active(&ctx->wait))
  853. wake_up(&ctx->wait);
  854. spin_unlock_irqrestore(&ctx->ctx_lock, flags);
  855. return ret;
  856. }
  857. EXPORT_SYMBOL(aio_complete);
  858. /* aio_read_evt
  859. * Pull an event off of the ioctx's event ring. Returns the number of
  860. * events fetched (0 or 1 ;-)
  861. * FIXME: make this use cmpxchg.
  862. * TODO: make the ringbuffer user mmap()able (requires FIXME).
  863. */
  864. static int aio_read_evt(struct kioctx *ioctx, struct io_event *ent)
  865. {
  866. struct aio_ring_info *info = &ioctx->ring_info;
  867. struct aio_ring *ring;
  868. unsigned long head;
  869. int ret = 0;
  870. ring = kmap_atomic(info->ring_pages[0], KM_USER0);
  871. dprintk("in aio_read_evt h%lu t%lu m%lu\n",
  872. (unsigned long)ring->head, (unsigned long)ring->tail,
  873. (unsigned long)ring->nr);
  874. if (ring->head == ring->tail)
  875. goto out;
  876. spin_lock(&info->ring_lock);
  877. head = ring->head % info->nr;
  878. if (head != ring->tail) {
  879. struct io_event *evp = aio_ring_event(info, head, KM_USER1);
  880. *ent = *evp;
  881. head = (head + 1) % info->nr;
  882. smp_mb(); /* finish reading the event before updatng the head */
  883. ring->head = head;
  884. ret = 1;
  885. put_aio_ring_event(evp, KM_USER1);
  886. }
  887. spin_unlock(&info->ring_lock);
  888. out:
  889. kunmap_atomic(ring, KM_USER0);
  890. dprintk("leaving aio_read_evt: %d h%lu t%lu\n", ret,
  891. (unsigned long)ring->head, (unsigned long)ring->tail);
  892. return ret;
  893. }
  894. struct aio_timeout {
  895. struct timer_list timer;
  896. int timed_out;
  897. struct task_struct *p;
  898. };
  899. static void timeout_func(unsigned long data)
  900. {
  901. struct aio_timeout *to = (struct aio_timeout *)data;
  902. to->timed_out = 1;
  903. wake_up_process(to->p);
  904. }
  905. static inline void init_timeout(struct aio_timeout *to)
  906. {
  907. setup_timer_on_stack(&to->timer, timeout_func, (unsigned long) to);
  908. to->timed_out = 0;
  909. to->p = current;
  910. }
  911. static inline void set_timeout(long start_jiffies, struct aio_timeout *to,
  912. const struct timespec *ts)
  913. {
  914. to->timer.expires = start_jiffies + timespec_to_jiffies(ts);
  915. if (time_after(to->timer.expires, jiffies))
  916. add_timer(&to->timer);
  917. else
  918. to->timed_out = 1;
  919. }
  920. static inline void clear_timeout(struct aio_timeout *to)
  921. {
  922. del_singleshot_timer_sync(&to->timer);
  923. }
  924. static int read_events(struct kioctx *ctx,
  925. long min_nr, long nr,
  926. struct io_event __user *event,
  927. struct timespec __user *timeout)
  928. {
  929. long start_jiffies = jiffies;
  930. struct task_struct *tsk = current;
  931. DECLARE_WAITQUEUE(wait, tsk);
  932. int ret;
  933. int i = 0;
  934. struct io_event ent;
  935. struct aio_timeout to;
  936. int retry = 0;
  937. /* needed to zero any padding within an entry (there shouldn't be
  938. * any, but C is fun!
  939. */
  940. memset(&ent, 0, sizeof(ent));
  941. retry:
  942. ret = 0;
  943. while (likely(i < nr)) {
  944. ret = aio_read_evt(ctx, &ent);
  945. if (unlikely(ret <= 0))
  946. break;
  947. dprintk("read event: %Lx %Lx %Lx %Lx\n",
  948. ent.data, ent.obj, ent.res, ent.res2);
  949. /* Could we split the check in two? */
  950. ret = -EFAULT;
  951. if (unlikely(copy_to_user(event, &ent, sizeof(ent)))) {
  952. dprintk("aio: lost an event due to EFAULT.\n");
  953. break;
  954. }
  955. ret = 0;
  956. /* Good, event copied to userland, update counts. */
  957. event ++;
  958. i ++;
  959. }
  960. if (min_nr <= i)
  961. return i;
  962. if (ret)
  963. return ret;
  964. /* End fast path */
  965. /* racey check, but it gets redone */
  966. if (!retry && unlikely(!list_empty(&ctx->run_list))) {
  967. retry = 1;
  968. aio_run_all_iocbs(ctx);
  969. goto retry;
  970. }
  971. init_timeout(&to);
  972. if (timeout) {
  973. struct timespec ts;
  974. ret = -EFAULT;
  975. if (unlikely(copy_from_user(&ts, timeout, sizeof(ts))))
  976. goto out;
  977. set_timeout(start_jiffies, &to, &ts);
  978. }
  979. while (likely(i < nr)) {
  980. add_wait_queue_exclusive(&ctx->wait, &wait);
  981. do {
  982. set_task_state(tsk, TASK_INTERRUPTIBLE);
  983. ret = aio_read_evt(ctx, &ent);
  984. if (ret)
  985. break;
  986. if (min_nr <= i)
  987. break;
  988. if (unlikely(ctx->dead)) {
  989. ret = -EINVAL;
  990. break;
  991. }
  992. if (to.timed_out) /* Only check after read evt */
  993. break;
  994. /* Try to only show up in io wait if there are ops
  995. * in flight */
  996. if (ctx->reqs_active)
  997. io_schedule();
  998. else
  999. schedule();
  1000. if (signal_pending(tsk)) {
  1001. ret = -EINTR;
  1002. break;
  1003. }
  1004. /*ret = aio_read_evt(ctx, &ent);*/
  1005. } while (1) ;
  1006. set_task_state(tsk, TASK_RUNNING);
  1007. remove_wait_queue(&ctx->wait, &wait);
  1008. if (unlikely(ret <= 0))
  1009. break;
  1010. ret = -EFAULT;
  1011. if (unlikely(copy_to_user(event, &ent, sizeof(ent)))) {
  1012. dprintk("aio: lost an event due to EFAULT.\n");
  1013. break;
  1014. }
  1015. /* Good, event copied to userland, update counts. */
  1016. event ++;
  1017. i ++;
  1018. }
  1019. if (timeout)
  1020. clear_timeout(&to);
  1021. out:
  1022. destroy_timer_on_stack(&to.timer);
  1023. return i ? i : ret;
  1024. }
  1025. /* Take an ioctx and remove it from the list of ioctx's. Protects
  1026. * against races with itself via ->dead.
  1027. */
  1028. static void io_destroy(struct kioctx *ioctx)
  1029. {
  1030. struct mm_struct *mm = current->mm;
  1031. int was_dead;
  1032. /* delete the entry from the list is someone else hasn't already */
  1033. spin_lock(&mm->ioctx_lock);
  1034. was_dead = ioctx->dead;
  1035. ioctx->dead = 1;
  1036. hlist_del_rcu(&ioctx->list);
  1037. spin_unlock(&mm->ioctx_lock);
  1038. dprintk("aio_release(%p)\n", ioctx);
  1039. if (likely(!was_dead))
  1040. put_ioctx(ioctx); /* twice for the list */
  1041. aio_cancel_all(ioctx);
  1042. wait_for_all_aios(ioctx);
  1043. /*
  1044. * Wake up any waiters. The setting of ctx->dead must be seen
  1045. * by other CPUs at this point. Right now, we rely on the
  1046. * locking done by the above calls to ensure this consistency.
  1047. */
  1048. wake_up(&ioctx->wait);
  1049. put_ioctx(ioctx); /* once for the lookup */
  1050. }
  1051. /* sys_io_setup:
  1052. * Create an aio_context capable of receiving at least nr_events.
  1053. * ctxp must not point to an aio_context that already exists, and
  1054. * must be initialized to 0 prior to the call. On successful
  1055. * creation of the aio_context, *ctxp is filled in with the resulting
  1056. * handle. May fail with -EINVAL if *ctxp is not initialized,
  1057. * if the specified nr_events exceeds internal limits. May fail
  1058. * with -EAGAIN if the specified nr_events exceeds the user's limit
  1059. * of available events. May fail with -ENOMEM if insufficient kernel
  1060. * resources are available. May fail with -EFAULT if an invalid
  1061. * pointer is passed for ctxp. Will fail with -ENOSYS if not
  1062. * implemented.
  1063. */
  1064. SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp)
  1065. {
  1066. struct kioctx *ioctx = NULL;
  1067. unsigned long ctx;
  1068. long ret;
  1069. ret = get_user(ctx, ctxp);
  1070. if (unlikely(ret))
  1071. goto out;
  1072. ret = -EINVAL;
  1073. if (unlikely(ctx || nr_events == 0)) {
  1074. pr_debug("EINVAL: io_setup: ctx %lu nr_events %u\n",
  1075. ctx, nr_events);
  1076. goto out;
  1077. }
  1078. ioctx = ioctx_alloc(nr_events);
  1079. ret = PTR_ERR(ioctx);
  1080. if (!IS_ERR(ioctx)) {
  1081. ret = put_user(ioctx->user_id, ctxp);
  1082. if (!ret)
  1083. return 0;
  1084. get_ioctx(ioctx); /* io_destroy() expects us to hold a ref */
  1085. io_destroy(ioctx);
  1086. }
  1087. out:
  1088. return ret;
  1089. }
  1090. /* sys_io_destroy:
  1091. * Destroy the aio_context specified. May cancel any outstanding
  1092. * AIOs and block on completion. Will fail with -ENOSYS if not
  1093. * implemented. May fail with -EINVAL if the context pointed to
  1094. * is invalid.
  1095. */
  1096. SYSCALL_DEFINE1(io_destroy, aio_context_t, ctx)
  1097. {
  1098. struct kioctx *ioctx = lookup_ioctx(ctx);
  1099. if (likely(NULL != ioctx)) {
  1100. io_destroy(ioctx);
  1101. return 0;
  1102. }
  1103. pr_debug("EINVAL: io_destroy: invalid context id\n");
  1104. return -EINVAL;
  1105. }
  1106. static void aio_advance_iovec(struct kiocb *iocb, ssize_t ret)
  1107. {
  1108. struct iovec *iov = &iocb->ki_iovec[iocb->ki_cur_seg];
  1109. BUG_ON(ret <= 0);
  1110. while (iocb->ki_cur_seg < iocb->ki_nr_segs && ret > 0) {
  1111. ssize_t this = min((ssize_t)iov->iov_len, ret);
  1112. iov->iov_base += this;
  1113. iov->iov_len -= this;
  1114. iocb->ki_left -= this;
  1115. ret -= this;
  1116. if (iov->iov_len == 0) {
  1117. iocb->ki_cur_seg++;
  1118. iov++;
  1119. }
  1120. }
  1121. /* the caller should not have done more io than what fit in
  1122. * the remaining iovecs */
  1123. BUG_ON(ret > 0 && iocb->ki_left == 0);
  1124. }
  1125. static ssize_t aio_rw_vect_retry(struct kiocb *iocb)
  1126. {
  1127. struct file *file = iocb->ki_filp;
  1128. struct address_space *mapping = file->f_mapping;
  1129. struct inode *inode = mapping->host;
  1130. ssize_t (*rw_op)(struct kiocb *, const struct iovec *,
  1131. unsigned long, loff_t);
  1132. ssize_t ret = 0;
  1133. unsigned short opcode;
  1134. if ((iocb->ki_opcode == IOCB_CMD_PREADV) ||
  1135. (iocb->ki_opcode == IOCB_CMD_PREAD)) {
  1136. rw_op = file->f_op->aio_read;
  1137. opcode = IOCB_CMD_PREADV;
  1138. } else {
  1139. rw_op = file->f_op->aio_write;
  1140. opcode = IOCB_CMD_PWRITEV;
  1141. }
  1142. /* This matches the pread()/pwrite() logic */
  1143. if (iocb->ki_pos < 0)
  1144. return -EINVAL;
  1145. do {
  1146. ret = rw_op(iocb, &iocb->ki_iovec[iocb->ki_cur_seg],
  1147. iocb->ki_nr_segs - iocb->ki_cur_seg,
  1148. iocb->ki_pos);
  1149. if (ret > 0)
  1150. aio_advance_iovec(iocb, ret);
  1151. /* retry all partial writes. retry partial reads as long as its a
  1152. * regular file. */
  1153. } while (ret > 0 && iocb->ki_left > 0 &&
  1154. (opcode == IOCB_CMD_PWRITEV ||
  1155. (!S_ISFIFO(inode->i_mode) && !S_ISSOCK(inode->i_mode))));
  1156. /* This means we must have transferred all that we could */
  1157. /* No need to retry anymore */
  1158. if ((ret == 0) || (iocb->ki_left == 0))
  1159. ret = iocb->ki_nbytes - iocb->ki_left;
  1160. /* If we managed to write some out we return that, rather than
  1161. * the eventual error. */
  1162. if (opcode == IOCB_CMD_PWRITEV
  1163. && ret < 0 && ret != -EIOCBQUEUED && ret != -EIOCBRETRY
  1164. && iocb->ki_nbytes - iocb->ki_left)
  1165. ret = iocb->ki_nbytes - iocb->ki_left;
  1166. return ret;
  1167. }
  1168. static ssize_t aio_fdsync(struct kiocb *iocb)
  1169. {
  1170. struct file *file = iocb->ki_filp;
  1171. ssize_t ret = -EINVAL;
  1172. if (file->f_op->aio_fsync)
  1173. ret = file->f_op->aio_fsync(iocb, 1);
  1174. return ret;
  1175. }
  1176. static ssize_t aio_fsync(struct kiocb *iocb)
  1177. {
  1178. struct file *file = iocb->ki_filp;
  1179. ssize_t ret = -EINVAL;
  1180. if (file->f_op->aio_fsync)
  1181. ret = file->f_op->aio_fsync(iocb, 0);
  1182. return ret;
  1183. }
  1184. static ssize_t aio_setup_vectored_rw(int type, struct kiocb *kiocb, bool compat)
  1185. {
  1186. ssize_t ret;
  1187. #ifdef CONFIG_COMPAT
  1188. if (compat)
  1189. ret = compat_rw_copy_check_uvector(type,
  1190. (struct compat_iovec __user *)kiocb->ki_buf,
  1191. kiocb->ki_nbytes, 1, &kiocb->ki_inline_vec,
  1192. &kiocb->ki_iovec);
  1193. else
  1194. #endif
  1195. ret = rw_copy_check_uvector(type,
  1196. (struct iovec __user *)kiocb->ki_buf,
  1197. kiocb->ki_nbytes, 1, &kiocb->ki_inline_vec,
  1198. &kiocb->ki_iovec);
  1199. if (ret < 0)
  1200. goto out;
  1201. kiocb->ki_nr_segs = kiocb->ki_nbytes;
  1202. kiocb->ki_cur_seg = 0;
  1203. /* ki_nbytes/left now reflect bytes instead of segs */
  1204. kiocb->ki_nbytes = ret;
  1205. kiocb->ki_left = ret;
  1206. ret = 0;
  1207. out:
  1208. return ret;
  1209. }
  1210. static ssize_t aio_setup_single_vector(struct kiocb *kiocb)
  1211. {
  1212. kiocb->ki_iovec = &kiocb->ki_inline_vec;
  1213. kiocb->ki_iovec->iov_base = kiocb->ki_buf;
  1214. kiocb->ki_iovec->iov_len = kiocb->ki_left;
  1215. kiocb->ki_nr_segs = 1;
  1216. kiocb->ki_cur_seg = 0;
  1217. return 0;
  1218. }
  1219. /*
  1220. * aio_setup_iocb:
  1221. * Performs the initial checks and aio retry method
  1222. * setup for the kiocb at the time of io submission.
  1223. */
  1224. static ssize_t aio_setup_iocb(struct kiocb *kiocb, bool compat)
  1225. {
  1226. struct file *file = kiocb->ki_filp;
  1227. ssize_t ret = 0;
  1228. switch (kiocb->ki_opcode) {
  1229. case IOCB_CMD_PREAD:
  1230. ret = -EBADF;
  1231. if (unlikely(!(file->f_mode & FMODE_READ)))
  1232. break;
  1233. ret = -EFAULT;
  1234. if (unlikely(!access_ok(VERIFY_WRITE, kiocb->ki_buf,
  1235. kiocb->ki_left)))
  1236. break;
  1237. ret = security_file_permission(file, MAY_READ);
  1238. if (unlikely(ret))
  1239. break;
  1240. ret = aio_setup_single_vector(kiocb);
  1241. if (ret)
  1242. break;
  1243. ret = -EINVAL;
  1244. if (file->f_op->aio_read)
  1245. kiocb->ki_retry = aio_rw_vect_retry;
  1246. break;
  1247. case IOCB_CMD_PWRITE:
  1248. ret = -EBADF;
  1249. if (unlikely(!(file->f_mode & FMODE_WRITE)))
  1250. break;
  1251. ret = -EFAULT;
  1252. if (unlikely(!access_ok(VERIFY_READ, kiocb->ki_buf,
  1253. kiocb->ki_left)))
  1254. break;
  1255. ret = security_file_permission(file, MAY_WRITE);
  1256. if (unlikely(ret))
  1257. break;
  1258. ret = aio_setup_single_vector(kiocb);
  1259. if (ret)
  1260. break;
  1261. ret = -EINVAL;
  1262. if (file->f_op->aio_write)
  1263. kiocb->ki_retry = aio_rw_vect_retry;
  1264. break;
  1265. case IOCB_CMD_PREADV:
  1266. ret = -EBADF;
  1267. if (unlikely(!(file->f_mode & FMODE_READ)))
  1268. break;
  1269. ret = security_file_permission(file, MAY_READ);
  1270. if (unlikely(ret))
  1271. break;
  1272. ret = aio_setup_vectored_rw(READ, kiocb, compat);
  1273. if (ret)
  1274. break;
  1275. ret = -EINVAL;
  1276. if (file->f_op->aio_read)
  1277. kiocb->ki_retry = aio_rw_vect_retry;
  1278. break;
  1279. case IOCB_CMD_PWRITEV:
  1280. ret = -EBADF;
  1281. if (unlikely(!(file->f_mode & FMODE_WRITE)))
  1282. break;
  1283. ret = security_file_permission(file, MAY_WRITE);
  1284. if (unlikely(ret))
  1285. break;
  1286. ret = aio_setup_vectored_rw(WRITE, kiocb, compat);
  1287. if (ret)
  1288. break;
  1289. ret = -EINVAL;
  1290. if (file->f_op->aio_write)
  1291. kiocb->ki_retry = aio_rw_vect_retry;
  1292. break;
  1293. case IOCB_CMD_FDSYNC:
  1294. ret = -EINVAL;
  1295. if (file->f_op->aio_fsync)
  1296. kiocb->ki_retry = aio_fdsync;
  1297. break;
  1298. case IOCB_CMD_FSYNC:
  1299. ret = -EINVAL;
  1300. if (file->f_op->aio_fsync)
  1301. kiocb->ki_retry = aio_fsync;
  1302. break;
  1303. default:
  1304. dprintk("EINVAL: io_submit: no operation provided\n");
  1305. ret = -EINVAL;
  1306. }
  1307. if (!kiocb->ki_retry)
  1308. return ret;
  1309. return 0;
  1310. }
  1311. static void aio_batch_add(struct address_space *mapping,
  1312. struct hlist_head *batch_hash)
  1313. {
  1314. struct aio_batch_entry *abe;
  1315. struct hlist_node *pos;
  1316. unsigned bucket;
  1317. bucket = hash_ptr(mapping, AIO_BATCH_HASH_BITS);
  1318. hlist_for_each_entry(abe, pos, &batch_hash[bucket], list) {
  1319. if (abe->mapping == mapping)
  1320. return;
  1321. }
  1322. abe = mempool_alloc(abe_pool, GFP_KERNEL);
  1323. /*
  1324. * we should be using igrab here, but
  1325. * we don't want to hammer on the global
  1326. * inode spinlock just to take an extra
  1327. * reference on a file that we must already
  1328. * have a reference to.
  1329. *
  1330. * When we're called, we always have a reference
  1331. * on the file, so we must always have a reference
  1332. * on the inode, so ihold() is safe here.
  1333. */
  1334. ihold(mapping->host);
  1335. abe->mapping = mapping;
  1336. hlist_add_head(&abe->list, &batch_hash[bucket]);
  1337. return;
  1338. }
  1339. static void aio_batch_free(struct hlist_head *batch_hash)
  1340. {
  1341. struct aio_batch_entry *abe;
  1342. struct hlist_node *pos, *n;
  1343. int i;
  1344. for (i = 0; i < AIO_BATCH_HASH_SIZE; i++) {
  1345. hlist_for_each_entry_safe(abe, pos, n, &batch_hash[i], list) {
  1346. blk_run_address_space(abe->mapping);
  1347. iput(abe->mapping->host);
  1348. hlist_del(&abe->list);
  1349. mempool_free(abe, abe_pool);
  1350. }
  1351. }
  1352. }
  1353. static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb,
  1354. struct iocb *iocb, struct hlist_head *batch_hash,
  1355. bool compat)
  1356. {
  1357. struct kiocb *req;
  1358. struct file *file;
  1359. ssize_t ret;
  1360. /* enforce forwards compatibility on users */
  1361. if (unlikely(iocb->aio_reserved1 || iocb->aio_reserved2)) {
  1362. pr_debug("EINVAL: io_submit: reserve field set\n");
  1363. return -EINVAL;
  1364. }
  1365. /* prevent overflows */
  1366. if (unlikely(
  1367. (iocb->aio_buf != (unsigned long)iocb->aio_buf) ||
  1368. (iocb->aio_nbytes != (size_t)iocb->aio_nbytes) ||
  1369. ((ssize_t)iocb->aio_nbytes < 0)
  1370. )) {
  1371. pr_debug("EINVAL: io_submit: overflow check\n");
  1372. return -EINVAL;
  1373. }
  1374. file = fget(iocb->aio_fildes);
  1375. if (unlikely(!file))
  1376. return -EBADF;
  1377. req = aio_get_req(ctx); /* returns with 2 references to req */
  1378. if (unlikely(!req)) {
  1379. fput(file);
  1380. return -EAGAIN;
  1381. }
  1382. req->ki_filp = file;
  1383. if (iocb->aio_flags & IOCB_FLAG_RESFD) {
  1384. /*
  1385. * If the IOCB_FLAG_RESFD flag of aio_flags is set, get an
  1386. * instance of the file* now. The file descriptor must be
  1387. * an eventfd() fd, and will be signaled for each completed
  1388. * event using the eventfd_signal() function.
  1389. */
  1390. req->ki_eventfd = eventfd_ctx_fdget((int) iocb->aio_resfd);
  1391. if (IS_ERR(req->ki_eventfd)) {
  1392. ret = PTR_ERR(req->ki_eventfd);
  1393. req->ki_eventfd = NULL;
  1394. goto out_put_req;
  1395. }
  1396. }
  1397. ret = put_user(req->ki_key, &user_iocb->aio_key);
  1398. if (unlikely(ret)) {
  1399. dprintk("EFAULT: aio_key\n");
  1400. goto out_put_req;
  1401. }
  1402. req->ki_obj.user = user_iocb;
  1403. req->ki_user_data = iocb->aio_data;
  1404. req->ki_pos = iocb->aio_offset;
  1405. req->ki_buf = (char __user *)(unsigned long)iocb->aio_buf;
  1406. req->ki_left = req->ki_nbytes = iocb->aio_nbytes;
  1407. req->ki_opcode = iocb->aio_lio_opcode;
  1408. ret = aio_setup_iocb(req, compat);
  1409. if (ret)
  1410. goto out_put_req;
  1411. spin_lock_irq(&ctx->ctx_lock);
  1412. aio_run_iocb(req);
  1413. if (!list_empty(&ctx->run_list)) {
  1414. /* drain the run list */
  1415. while (__aio_run_iocbs(ctx))
  1416. ;
  1417. }
  1418. spin_unlock_irq(&ctx->ctx_lock);
  1419. if (req->ki_opcode == IOCB_CMD_PREAD ||
  1420. req->ki_opcode == IOCB_CMD_PREADV ||
  1421. req->ki_opcode == IOCB_CMD_PWRITE ||
  1422. req->ki_opcode == IOCB_CMD_PWRITEV)
  1423. aio_batch_add(file->f_mapping, batch_hash);
  1424. aio_put_req(req); /* drop extra ref to req */
  1425. return 0;
  1426. out_put_req:
  1427. aio_put_req(req); /* drop extra ref to req */
  1428. aio_put_req(req); /* drop i/o ref to req */
  1429. return ret;
  1430. }
  1431. long do_io_submit(aio_context_t ctx_id, long nr,
  1432. struct iocb __user *__user *iocbpp, bool compat)
  1433. {
  1434. struct kioctx *ctx;
  1435. long ret = 0;
  1436. int i;
  1437. struct hlist_head batch_hash[AIO_BATCH_HASH_SIZE] = { { 0, }, };
  1438. if (unlikely(nr < 0))
  1439. return -EINVAL;
  1440. if (unlikely(nr > LONG_MAX/sizeof(*iocbpp)))
  1441. nr = LONG_MAX/sizeof(*iocbpp);
  1442. if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp)))))
  1443. return -EFAULT;
  1444. ctx = lookup_ioctx(ctx_id);
  1445. if (unlikely(!ctx)) {
  1446. pr_debug("EINVAL: io_submit: invalid context id\n");
  1447. return -EINVAL;
  1448. }
  1449. /*
  1450. * AKPM: should this return a partial result if some of the IOs were
  1451. * successfully submitted?
  1452. */
  1453. for (i=0; i<nr; i++) {
  1454. struct iocb __user *user_iocb;
  1455. struct iocb tmp;
  1456. if (unlikely(__get_user(user_iocb, iocbpp + i))) {
  1457. ret = -EFAULT;
  1458. break;
  1459. }
  1460. if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) {
  1461. ret = -EFAULT;
  1462. break;
  1463. }
  1464. ret = io_submit_one(ctx, user_iocb, &tmp, batch_hash, compat);
  1465. if (ret)
  1466. break;
  1467. }
  1468. aio_batch_free(batch_hash);
  1469. put_ioctx(ctx);
  1470. return i ? i : ret;
  1471. }
  1472. /* sys_io_submit:
  1473. * Queue the nr iocbs pointed to by iocbpp for processing. Returns
  1474. * the number of iocbs queued. May return -EINVAL if the aio_context
  1475. * specified by ctx_id is invalid, if nr is < 0, if the iocb at
  1476. * *iocbpp[0] is not properly initialized, if the operation specified
  1477. * is invalid for the file descriptor in the iocb. May fail with
  1478. * -EFAULT if any of the data structures point to invalid data. May
  1479. * fail with -EBADF if the file descriptor specified in the first
  1480. * iocb is invalid. May fail with -EAGAIN if insufficient resources
  1481. * are available to queue any iocbs. Will return 0 if nr is 0. Will
  1482. * fail with -ENOSYS if not implemented.
  1483. */
  1484. SYSCALL_DEFINE3(io_submit, aio_context_t, ctx_id, long, nr,
  1485. struct iocb __user * __user *, iocbpp)
  1486. {
  1487. return do_io_submit(ctx_id, nr, iocbpp, 0);
  1488. }
  1489. /* lookup_kiocb
  1490. * Finds a given iocb for cancellation.
  1491. */
  1492. static struct kiocb *lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb,
  1493. u32 key)
  1494. {
  1495. struct list_head *pos;
  1496. assert_spin_locked(&ctx->ctx_lock);
  1497. /* TODO: use a hash or array, this sucks. */
  1498. list_for_each(pos, &ctx->active_reqs) {
  1499. struct kiocb *kiocb = list_kiocb(pos);
  1500. if (kiocb->ki_obj.user == iocb && kiocb->ki_key == key)
  1501. return kiocb;
  1502. }
  1503. return NULL;
  1504. }
  1505. /* sys_io_cancel:
  1506. * Attempts to cancel an iocb previously passed to io_submit. If
  1507. * the operation is successfully cancelled, the resulting event is
  1508. * copied into the memory pointed to by result without being placed
  1509. * into the completion queue and 0 is returned. May fail with
  1510. * -EFAULT if any of the data structures pointed to are invalid.
  1511. * May fail with -EINVAL if aio_context specified by ctx_id is
  1512. * invalid. May fail with -EAGAIN if the iocb specified was not
  1513. * cancelled. Will fail with -ENOSYS if not implemented.
  1514. */
  1515. SYSCALL_DEFINE3(io_cancel, aio_context_t, ctx_id, struct iocb __user *, iocb,
  1516. struct io_event __user *, result)
  1517. {
  1518. int (*cancel)(struct kiocb *iocb, struct io_event *res);
  1519. struct kioctx *ctx;
  1520. struct kiocb *kiocb;
  1521. u32 key;
  1522. int ret;
  1523. ret = get_user(key, &iocb->aio_key);
  1524. if (unlikely(ret))
  1525. return -EFAULT;
  1526. ctx = lookup_ioctx(ctx_id);
  1527. if (unlikely(!ctx))
  1528. return -EINVAL;
  1529. spin_lock_irq(&ctx->ctx_lock);
  1530. ret = -EAGAIN;
  1531. kiocb = lookup_kiocb(ctx, iocb, key);
  1532. if (kiocb && kiocb->ki_cancel) {
  1533. cancel = kiocb->ki_cancel;
  1534. kiocb->ki_users ++;
  1535. kiocbSetCancelled(kiocb);
  1536. } else
  1537. cancel = NULL;
  1538. spin_unlock_irq(&ctx->ctx_lock);
  1539. if (NULL != cancel) {
  1540. struct io_event tmp;
  1541. pr_debug("calling cancel\n");
  1542. memset(&tmp, 0, sizeof(tmp));
  1543. tmp.obj = (u64)(unsigned long)kiocb->ki_obj.user;
  1544. tmp.data = kiocb->ki_user_data;
  1545. ret = cancel(kiocb, &tmp);
  1546. if (!ret) {
  1547. /* Cancellation succeeded -- copy the result
  1548. * into the user's buffer.
  1549. */
  1550. if (copy_to_user(result, &tmp, sizeof(tmp)))
  1551. ret = -EFAULT;
  1552. }
  1553. } else
  1554. ret = -EINVAL;
  1555. put_ioctx(ctx);
  1556. return ret;
  1557. }
  1558. /* io_getevents:
  1559. * Attempts to read at least min_nr events and up to nr events from
  1560. * the completion queue for the aio_context specified by ctx_id. If
  1561. * it succeeds, the number of read events is returned. May fail with
  1562. * -EINVAL if ctx_id is invalid, if min_nr is out of range, if nr is
  1563. * out of range, if timeout is out of range. May fail with -EFAULT
  1564. * if any of the memory specified is invalid. May return 0 or
  1565. * < min_nr if the timeout specified by timeout has elapsed
  1566. * before sufficient events are available, where timeout == NULL
  1567. * specifies an infinite timeout. Note that the timeout pointed to by
  1568. * timeout is relative and will be updated if not NULL and the
  1569. * operation blocks. Will fail with -ENOSYS if not implemented.
  1570. */
  1571. SYSCALL_DEFINE5(io_getevents, aio_context_t, ctx_id,
  1572. long, min_nr,
  1573. long, nr,
  1574. struct io_event __user *, events,
  1575. struct timespec __user *, timeout)
  1576. {
  1577. struct kioctx *ioctx = lookup_ioctx(ctx_id);
  1578. long ret = -EINVAL;
  1579. if (likely(ioctx)) {
  1580. if (likely(min_nr <= nr && min_nr >= 0))
  1581. ret = read_events(ioctx, min_nr, nr, events, timeout);
  1582. put_ioctx(ioctx);
  1583. }
  1584. asmlinkage_protect(5, ret, ctx_id, min_nr, nr, events, timeout);
  1585. return ret;
  1586. }