aio.c 46 KB

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