aio.c 46 KB

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