blob: 4cfddd7124521c9f34e614667fb592d8eacbe1ad [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001// SPDX-License-Identifier: GPL-2.0
2/*
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
5 *
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
8 *
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqring (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
16 * CQ entries.
17 *
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
23 * head will do).
24 *
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
28 * between.
29 *
30 * Also see the examples in the liburing library:
31 *
32 * git://git.kernel.dk/liburing
33 *
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
38 *
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
41 */
42#include <linux/kernel.h>
43#include <linux/init.h>
44#include <linux/errno.h>
45#include <linux/syscalls.h>
46#include <linux/compat.h>
47#include <linux/refcount.h>
48#include <linux/uio.h>
49
50#include <linux/sched/signal.h>
51#include <linux/fs.h>
52#include <linux/file.h>
53#include <linux/fdtable.h>
54#include <linux/mm.h>
55#include <linux/mman.h>
56#include <linux/mmu_context.h>
57#include <linux/percpu.h>
58#include <linux/slab.h>
59#include <linux/workqueue.h>
60#include <linux/kthread.h>
61#include <linux/blkdev.h>
62#include <linux/bvec.h>
63#include <linux/net.h>
64#include <net/sock.h>
65#include <net/af_unix.h>
66#include <linux/anon_inodes.h>
67#include <linux/sched/mm.h>
68#include <linux/uaccess.h>
69#include <linux/nospec.h>
70#include <linux/sizes.h>
71#include <linux/hugetlb.h>
72#include <linux/highmem.h>
73#include <linux/fs_struct.h>
74
75#include <uapi/linux/io_uring.h>
76
77#include "internal.h"
78
79#define IORING_MAX_ENTRIES 32768
80#define IORING_MAX_FIXED_FILES 1024
81
82struct io_uring {
83 u32 head ____cacheline_aligned_in_smp;
84 u32 tail ____cacheline_aligned_in_smp;
85};
86
87/*
88 * This data is shared with the application through the mmap at offsets
89 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
90 *
91 * The offsets to the member fields are published through struct
92 * io_sqring_offsets when calling io_uring_setup.
93 */
94struct io_rings {
95 /*
96 * Head and tail offsets into the ring; the offsets need to be
97 * masked to get valid indices.
98 *
99 * The kernel controls head of the sq ring and the tail of the cq ring,
100 * and the application controls tail of the sq ring and the head of the
101 * cq ring.
102 */
103 struct io_uring sq, cq;
104 /*
105 * Bitmasks to apply to head and tail offsets (constant, equals
106 * ring_entries - 1)
107 */
108 u32 sq_ring_mask, cq_ring_mask;
109 /* Ring sizes (constant, power of 2) */
110 u32 sq_ring_entries, cq_ring_entries;
111 /*
112 * Number of invalid entries dropped by the kernel due to
113 * invalid index stored in array
114 *
115 * Written by the kernel, shouldn't be modified by the
116 * application (i.e. get number of "new events" by comparing to
117 * cached value).
118 *
119 * After a new SQ head value was read by the application this
120 * counter includes all submissions that were dropped reaching
121 * the new SQ head (and possibly more).
122 */
123 u32 sq_dropped;
124 /*
125 * Runtime flags
126 *
127 * Written by the kernel, shouldn't be modified by the
128 * application.
129 *
130 * The application needs a full memory barrier before checking
131 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
132 */
133 u32 sq_flags;
134 /*
135 * Number of completion events lost because the queue was full;
136 * this should be avoided by the application by making sure
137 * there are not more requests pending thatn there is space in
138 * the completion queue.
139 *
140 * Written by the kernel, shouldn't be modified by the
141 * application (i.e. get number of "new events" by comparing to
142 * cached value).
143 *
144 * As completion events come in out of order this counter is not
145 * ordered with any other data.
146 */
147 u32 cq_overflow;
148 /*
149 * Ring buffer of completion events.
150 *
151 * The kernel writes completion events fresh every time they are
152 * produced, so the application is allowed to modify pending
153 * entries.
154 */
155 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
156};
157
158struct io_mapped_ubuf {
159 u64 ubuf;
160 size_t len;
161 struct bio_vec *bvec;
162 unsigned int nr_bvecs;
163};
164
165struct async_list {
166 spinlock_t lock;
167 atomic_t cnt;
168 struct list_head list;
169
170 struct file *file;
171 off_t io_start;
172 size_t io_len;
173};
174
175struct io_ring_ctx {
176 struct {
177 struct percpu_ref refs;
178 } ____cacheline_aligned_in_smp;
179
180 struct {
181 unsigned int flags;
182 bool compat;
183 bool account_mem;
184
185 /*
186 * Ring buffer of indices into array of io_uring_sqe, which is
187 * mmapped by the application using the IORING_OFF_SQES offset.
188 *
189 * This indirection could e.g. be used to assign fixed
190 * io_uring_sqe entries to operations and only submit them to
191 * the queue when needed.
192 *
193 * The kernel modifies neither the indices array nor the entries
194 * array.
195 */
196 u32 *sq_array;
197 unsigned cached_sq_head;
198 unsigned sq_entries;
199 unsigned sq_mask;
200 unsigned sq_thread_idle;
201 unsigned cached_sq_dropped;
202 struct io_uring_sqe *sq_sqes;
203
204 struct list_head defer_list;
205 struct list_head timeout_list;
206 } ____cacheline_aligned_in_smp;
207
208 /* IO offload */
209 struct workqueue_struct *sqo_wq[2];
210 struct task_struct *sqo_thread; /* if using sq thread polling */
211 struct mm_struct *sqo_mm;
212 wait_queue_head_t sqo_wait;
213 struct completion sqo_thread_started;
214
215 struct {
216 unsigned cached_cq_tail;
217 atomic_t cached_cq_overflow;
218 unsigned cq_entries;
219 unsigned cq_mask;
220 struct wait_queue_head cq_wait;
221 struct fasync_struct *cq_fasync;
222 struct eventfd_ctx *cq_ev_fd;
223 atomic_t cq_timeouts;
224 } ____cacheline_aligned_in_smp;
225
226 struct io_rings *rings;
227
228 /*
229 * If used, fixed file set. Writers must ensure that ->refs is dead,
230 * readers must ensure that ->refs is alive as long as the file* is
231 * used. Only updated through io_uring_register(2).
232 */
233 struct file **user_files;
234 unsigned nr_user_files;
235
236 /* if used, fixed mapped user buffers */
237 unsigned nr_user_bufs;
238 struct io_mapped_ubuf *user_bufs;
239
240 struct user_struct *user;
241
242 const struct cred *creds;
243
244 struct completion ctx_done;
245
246 struct {
247 struct mutex uring_lock;
248 wait_queue_head_t wait;
249 } ____cacheline_aligned_in_smp;
250
251 struct {
252 spinlock_t completion_lock;
253 bool poll_multi_file;
254 /*
255 * ->poll_list is protected by the ctx->uring_lock for
256 * io_uring instances that don't use IORING_SETUP_SQPOLL.
257 * For SQPOLL, only the single threaded io_sq_thread() will
258 * manipulate the list, hence no extra locking is needed there.
259 */
260 struct list_head poll_list;
261 struct list_head cancel_list;
262 } ____cacheline_aligned_in_smp;
263
264 struct async_list pending_async[2];
265
266 struct list_head task_list;
267 spinlock_t task_lock;
268};
269
270struct sqe_submit {
271 const struct io_uring_sqe *sqe;
272 unsigned short index;
273 u32 sequence;
274 bool has_user;
275 bool needs_lock;
276 bool needs_fixed_file;
277 u8 opcode;
278};
279
280/*
281 * First field must be the file pointer in all the
282 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
283 */
284struct io_poll_iocb {
285 struct file *file;
286 struct wait_queue_head *head;
287 __poll_t events;
288 bool done;
289 bool canceled;
290 struct wait_queue_entry wait;
291};
292
293struct io_timeout {
294 struct file *file;
295 struct hrtimer timer;
296};
297
298/*
299 * NOTE! Each of the iocb union members has the file pointer
300 * as the first entry in their struct definition. So you can
301 * access the file pointer through any of the sub-structs,
302 * or directly as just 'ki_filp' in this struct.
303 */
304struct io_kiocb {
305 union {
306 struct file *file;
307 struct kiocb rw;
308 struct io_poll_iocb poll;
309 struct io_timeout timeout;
310 };
311
312 struct sqe_submit submit;
313
314 struct io_ring_ctx *ctx;
315 struct list_head list;
316 struct list_head link_list;
317 unsigned int flags;
318 refcount_t refs;
319#define REQ_F_NOWAIT 1 /* must not punt to workers */
320#define REQ_F_IOPOLL_COMPLETED 2 /* polled IO has completed */
321#define REQ_F_FIXED_FILE 4 /* ctx owns file */
322#define REQ_F_SEQ_PREV 8 /* sequential with previous */
323#define REQ_F_IO_DRAIN 16 /* drain existing IO first */
324#define REQ_F_IO_DRAINED 32 /* drain done */
325#define REQ_F_LINK 64 /* linked sqes */
326#define REQ_F_LINK_DONE 128 /* linked sqes done */
327#define REQ_F_FAIL_LINK 256 /* fail rest of links */
328#define REQ_F_SHADOW_DRAIN 512 /* link-drain shadow req */
329#define REQ_F_TIMEOUT 1024 /* timeout request */
330#define REQ_F_ISREG 2048 /* regular file */
331#define REQ_F_MUST_PUNT 4096 /* must be punted even for NONBLOCK */
332#define REQ_F_TIMEOUT_NOSEQ 8192 /* no timeout sequence */
333#define REQ_F_CANCEL 16384 /* cancel request */
334 unsigned long fsize;
335 u64 user_data;
336 u32 result;
337 u32 sequence;
338 struct files_struct *files;
339
340 struct fs_struct *fs;
341
342 struct work_struct work;
343 struct task_struct *work_task;
344 struct list_head task_list;
345};
346
347#define IO_PLUG_THRESHOLD 2
348#define IO_IOPOLL_BATCH 8
349
350struct io_submit_state {
351 struct blk_plug plug;
352
353 /*
354 * io_kiocb alloc cache
355 */
356 void *reqs[IO_IOPOLL_BATCH];
357 unsigned int free_reqs;
358 unsigned int cur_req;
359
360 /*
361 * File reference cache
362 */
363 struct file *file;
364 unsigned int fd;
365 unsigned int has_refs;
366 unsigned int used_refs;
367 unsigned int ios_left;
368};
369
370static void io_sq_wq_submit_work(struct work_struct *work);
371static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
372 long res);
373static void __io_free_req(struct io_kiocb *req);
374
375static struct kmem_cache *req_cachep;
376
377static const struct file_operations io_uring_fops;
378
379static void io_ring_ctx_ref_free(struct percpu_ref *ref)
380{
381 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
382
383 complete(&ctx->ctx_done);
384}
385
386static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
387{
388 struct io_ring_ctx *ctx;
389 int i;
390
391 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
392 if (!ctx)
393 return NULL;
394
395 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
396 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
397 kfree(ctx);
398 return NULL;
399 }
400
401 ctx->flags = p->flags;
402 init_waitqueue_head(&ctx->sqo_wait);
403 init_waitqueue_head(&ctx->cq_wait);
404 init_completion(&ctx->ctx_done);
405 init_completion(&ctx->sqo_thread_started);
406 mutex_init(&ctx->uring_lock);
407 init_waitqueue_head(&ctx->wait);
408 for (i = 0; i < ARRAY_SIZE(ctx->pending_async); i++) {
409 spin_lock_init(&ctx->pending_async[i].lock);
410 INIT_LIST_HEAD(&ctx->pending_async[i].list);
411 atomic_set(&ctx->pending_async[i].cnt, 0);
412 }
413 spin_lock_init(&ctx->completion_lock);
414 INIT_LIST_HEAD(&ctx->poll_list);
415 INIT_LIST_HEAD(&ctx->cancel_list);
416 INIT_LIST_HEAD(&ctx->defer_list);
417 INIT_LIST_HEAD(&ctx->timeout_list);
418 INIT_LIST_HEAD(&ctx->task_list);
419 spin_lock_init(&ctx->task_lock);
420 return ctx;
421}
422
423static void io_req_put_fs(struct io_kiocb *req)
424{
425 struct fs_struct *fs = req->fs;
426
427 if (!fs)
428 return;
429
430 spin_lock(&req->fs->lock);
431 if (--fs->users)
432 fs = NULL;
433 spin_unlock(&req->fs->lock);
434 if (fs)
435 free_fs_struct(fs);
436 req->fs = NULL;
437}
438
439static inline bool __io_sequence_defer(struct io_ring_ctx *ctx,
440 struct io_kiocb *req)
441{
442 return req->sequence != ctx->cached_cq_tail + ctx->cached_sq_dropped
443 + atomic_read(&ctx->cached_cq_overflow);
444}
445
446static inline bool io_sequence_defer(struct io_ring_ctx *ctx,
447 struct io_kiocb *req)
448{
449 if ((req->flags & (REQ_F_IO_DRAIN|REQ_F_IO_DRAINED)) != REQ_F_IO_DRAIN)
450 return false;
451
452 return __io_sequence_defer(ctx, req);
453}
454
455static struct io_kiocb *io_get_deferred_req(struct io_ring_ctx *ctx)
456{
457 struct io_kiocb *req;
458
459 req = list_first_entry_or_null(&ctx->defer_list, struct io_kiocb, list);
460 if (req && !io_sequence_defer(ctx, req)) {
461 list_del_init(&req->list);
462 return req;
463 }
464
465 return NULL;
466}
467
468static struct io_kiocb *io_get_timeout_req(struct io_ring_ctx *ctx)
469{
470 struct io_kiocb *req;
471
472 req = list_first_entry_or_null(&ctx->timeout_list, struct io_kiocb, list);
473 if (req) {
474 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
475 return NULL;
476 if (!__io_sequence_defer(ctx, req)) {
477 list_del_init(&req->list);
478 return req;
479 }
480 }
481
482 return NULL;
483}
484
485static void __io_commit_cqring(struct io_ring_ctx *ctx)
486{
487 struct io_rings *rings = ctx->rings;
488
489 if (ctx->cached_cq_tail != READ_ONCE(rings->cq.tail)) {
490 /* order cqe stores with ring update */
491 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
492
493 if (wq_has_sleeper(&ctx->cq_wait)) {
494 wake_up_interruptible(&ctx->cq_wait);
495 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
496 }
497 }
498}
499
500static inline void io_queue_async_work(struct io_ring_ctx *ctx,
501 struct io_kiocb *req)
502{
503 unsigned long flags;
504 int rw = 0;
505
506 if (req->submit.sqe) {
507 switch (req->submit.opcode) {
508 case IORING_OP_WRITEV:
509 case IORING_OP_WRITE_FIXED:
510 rw = !(req->rw.ki_flags & IOCB_DIRECT);
511 break;
512 }
513 }
514
515 if (req->work.func == io_sq_wq_submit_work) {
516 req->files = current->files;
517
518 spin_lock_irqsave(&ctx->task_lock, flags);
519 list_add(&req->task_list, &ctx->task_list);
520 req->work_task = NULL;
521 spin_unlock_irqrestore(&ctx->task_lock, flags);
522 }
523
524 queue_work(ctx->sqo_wq[rw], &req->work);
525}
526
527static void io_kill_timeout(struct io_kiocb *req)
528{
529 int ret;
530
531 ret = hrtimer_try_to_cancel(&req->timeout.timer);
532 if (ret != -1) {
533 atomic_inc(&req->ctx->cq_timeouts);
534 list_del(&req->list);
535 io_cqring_fill_event(req->ctx, req->user_data, 0);
536 if (refcount_dec_and_test(&req->refs))
537 __io_free_req(req);
538 }
539}
540
541static void io_kill_timeouts(struct io_ring_ctx *ctx)
542{
543 struct io_kiocb *req, *tmp;
544
545 spin_lock_irq(&ctx->completion_lock);
546 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
547 io_kill_timeout(req);
548 spin_unlock_irq(&ctx->completion_lock);
549}
550
551static void io_commit_cqring(struct io_ring_ctx *ctx)
552{
553 struct io_kiocb *req;
554
555 while ((req = io_get_timeout_req(ctx)) != NULL)
556 io_kill_timeout(req);
557
558 __io_commit_cqring(ctx);
559
560 while ((req = io_get_deferred_req(ctx)) != NULL) {
561 if (req->flags & REQ_F_SHADOW_DRAIN) {
562 /* Just for drain, free it. */
563 __io_free_req(req);
564 continue;
565 }
566 req->flags |= REQ_F_IO_DRAINED;
567 io_queue_async_work(ctx, req);
568 }
569}
570
571static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
572{
573 struct io_rings *rings = ctx->rings;
574 unsigned tail;
575
576 tail = ctx->cached_cq_tail;
577 /*
578 * writes to the cq entry need to come after reading head; the
579 * control dependency is enough as we're using WRITE_ONCE to
580 * fill the cq entry
581 */
582 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
583 return NULL;
584
585 ctx->cached_cq_tail++;
586 return &rings->cqes[tail & ctx->cq_mask];
587}
588
589static void io_cqring_fill_event(struct io_ring_ctx *ctx, u64 ki_user_data,
590 long res)
591{
592 struct io_uring_cqe *cqe;
593
594 /*
595 * If we can't get a cq entry, userspace overflowed the
596 * submission (by quite a lot). Increment the overflow count in
597 * the ring.
598 */
599 cqe = io_get_cqring(ctx);
600 if (cqe) {
601 WRITE_ONCE(cqe->user_data, ki_user_data);
602 WRITE_ONCE(cqe->res, res);
603 WRITE_ONCE(cqe->flags, 0);
604 } else {
605 WRITE_ONCE(ctx->rings->cq_overflow,
606 atomic_inc_return(&ctx->cached_cq_overflow));
607 }
608}
609
610static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
611{
612 if (waitqueue_active(&ctx->wait))
613 wake_up(&ctx->wait);
614 if (waitqueue_active(&ctx->sqo_wait))
615 wake_up(&ctx->sqo_wait);
616 if (ctx->cq_ev_fd)
617 eventfd_signal(ctx->cq_ev_fd, 1);
618}
619
620static void io_cqring_add_event(struct io_ring_ctx *ctx, u64 user_data,
621 long res)
622{
623 unsigned long flags;
624
625 spin_lock_irqsave(&ctx->completion_lock, flags);
626 io_cqring_fill_event(ctx, user_data, res);
627 io_commit_cqring(ctx);
628 spin_unlock_irqrestore(&ctx->completion_lock, flags);
629
630 io_cqring_ev_posted(ctx);
631}
632
633static struct io_kiocb *io_get_req(struct io_ring_ctx *ctx,
634 struct io_submit_state *state)
635{
636 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
637 struct io_kiocb *req;
638
639 if (!percpu_ref_tryget(&ctx->refs))
640 return NULL;
641
642 if (!state) {
643 req = kmem_cache_alloc(req_cachep, gfp);
644 if (unlikely(!req))
645 goto out;
646 } else if (!state->free_reqs) {
647 size_t sz;
648 int ret;
649
650 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
651 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
652
653 /*
654 * Bulk alloc is all-or-nothing. If we fail to get a batch,
655 * retry single alloc to be on the safe side.
656 */
657 if (unlikely(ret <= 0)) {
658 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
659 if (!state->reqs[0])
660 goto out;
661 ret = 1;
662 }
663 state->free_reqs = ret - 1;
664 state->cur_req = 1;
665 req = state->reqs[0];
666 } else {
667 req = state->reqs[state->cur_req];
668 state->free_reqs--;
669 state->cur_req++;
670 }
671
672 INIT_LIST_HEAD(&req->task_list);
673 req->file = NULL;
674 req->ctx = ctx;
675 req->flags = 0;
676 /* one is dropped after submission, the other at completion */
677 refcount_set(&req->refs, 2);
678 req->result = 0;
679 req->fs = NULL;
680 return req;
681out:
682 percpu_ref_put(&ctx->refs);
683 return NULL;
684}
685
686static void io_free_req_many(struct io_ring_ctx *ctx, void **reqs, int *nr)
687{
688 if (*nr) {
689 kmem_cache_free_bulk(req_cachep, *nr, reqs);
690 percpu_ref_put_many(&ctx->refs, *nr);
691 *nr = 0;
692 }
693}
694
695static void __io_free_req(struct io_kiocb *req)
696{
697 io_req_put_fs(req);
698 if (req->file && !(req->flags & REQ_F_FIXED_FILE))
699 fput(req->file);
700 percpu_ref_put(&req->ctx->refs);
701 kmem_cache_free(req_cachep, req);
702}
703
704static void io_req_link_next(struct io_kiocb *req)
705{
706 struct io_kiocb *nxt;
707
708 /*
709 * The list should never be empty when we are called here. But could
710 * potentially happen if the chain is messed up, check to be on the
711 * safe side.
712 */
713 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb, list);
714 if (nxt) {
715 list_del(&nxt->list);
716 if (!list_empty(&req->link_list)) {
717 INIT_LIST_HEAD(&nxt->link_list);
718 list_splice(&req->link_list, &nxt->link_list);
719 nxt->flags |= REQ_F_LINK;
720 }
721
722 nxt->flags |= REQ_F_LINK_DONE;
723 INIT_WORK(&nxt->work, io_sq_wq_submit_work);
724 io_queue_async_work(req->ctx, nxt);
725 }
726}
727
728/*
729 * Called if REQ_F_LINK is set, and we fail the head request
730 */
731static void io_fail_links(struct io_kiocb *req)
732{
733 struct io_kiocb *link;
734
735 while (!list_empty(&req->link_list)) {
736 link = list_first_entry(&req->link_list, struct io_kiocb, list);
737 list_del(&link->list);
738
739 io_cqring_add_event(req->ctx, link->user_data, -ECANCELED);
740 __io_free_req(link);
741 }
742}
743
744static void io_free_req(struct io_kiocb *req)
745{
746 /*
747 * If LINK is set, we have dependent requests in this chain. If we
748 * didn't fail this request, queue the first one up, moving any other
749 * dependencies to the next request. In case of failure, fail the rest
750 * of the chain.
751 */
752 if (req->flags & REQ_F_LINK) {
753 if (req->flags & REQ_F_FAIL_LINK)
754 io_fail_links(req);
755 else
756 io_req_link_next(req);
757 }
758
759 __io_free_req(req);
760}
761
762static void io_put_req(struct io_kiocb *req)
763{
764 if (refcount_dec_and_test(&req->refs))
765 io_free_req(req);
766}
767
768static unsigned io_cqring_events(struct io_rings *rings)
769{
770 /* See comment at the top of this file */
771 smp_rmb();
772 return READ_ONCE(rings->cq.tail) - READ_ONCE(rings->cq.head);
773}
774
775static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
776{
777 struct io_rings *rings = ctx->rings;
778
779 /* make sure SQ entry isn't read before tail */
780 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
781}
782
783/*
784 * Find and free completed poll iocbs
785 */
786static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
787 struct list_head *done)
788{
789 void *reqs[IO_IOPOLL_BATCH];
790 struct io_kiocb *req;
791 int to_free;
792
793 to_free = 0;
794 while (!list_empty(done)) {
795 req = list_first_entry(done, struct io_kiocb, list);
796 list_del(&req->list);
797
798 io_cqring_fill_event(ctx, req->user_data, req->result);
799 (*nr_events)++;
800
801 if (refcount_dec_and_test(&req->refs)) {
802 /* If we're not using fixed files, we have to pair the
803 * completion part with the file put. Use regular
804 * completions for those, only batch free for fixed
805 * file and non-linked commands.
806 */
807 if ((req->flags & (REQ_F_FIXED_FILE|REQ_F_LINK)) ==
808 REQ_F_FIXED_FILE) {
809 reqs[to_free++] = req;
810 if (to_free == ARRAY_SIZE(reqs))
811 io_free_req_many(ctx, reqs, &to_free);
812 } else {
813 io_free_req(req);
814 }
815 }
816 }
817
818 io_commit_cqring(ctx);
819 io_free_req_many(ctx, reqs, &to_free);
820}
821
822static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
823 long min)
824{
825 struct io_kiocb *req, *tmp;
826 LIST_HEAD(done);
827 bool spin;
828 int ret;
829
830 /*
831 * Only spin for completions if we don't have multiple devices hanging
832 * off our complete list, and we're under the requested amount.
833 */
834 spin = !ctx->poll_multi_file && *nr_events < min;
835
836 ret = 0;
837 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
838 struct kiocb *kiocb = &req->rw;
839
840 /*
841 * Move completed entries to our local list. If we find a
842 * request that requires polling, break out and complete
843 * the done list first, if we have entries there.
844 */
845 if (req->flags & REQ_F_IOPOLL_COMPLETED) {
846 list_move_tail(&req->list, &done);
847 continue;
848 }
849 if (!list_empty(&done))
850 break;
851
852 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
853 if (ret < 0)
854 break;
855
856 if (ret && spin)
857 spin = false;
858 ret = 0;
859 }
860
861 if (!list_empty(&done))
862 io_iopoll_complete(ctx, nr_events, &done);
863
864 return ret;
865}
866
867/*
868 * Poll for a mininum of 'min' events. Note that if min == 0 we consider that a
869 * non-spinning poll check - we'll still enter the driver poll loop, but only
870 * as a non-spinning completion check.
871 */
872static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
873 long min)
874{
875 while (!list_empty(&ctx->poll_list) && !need_resched()) {
876 int ret;
877
878 ret = io_do_iopoll(ctx, nr_events, min);
879 if (ret < 0)
880 return ret;
881 if (!min || *nr_events >= min)
882 return 0;
883 }
884
885 return 1;
886}
887
888/*
889 * We can't just wait for polled events to come to us, we have to actively
890 * find and complete them.
891 */
892static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
893{
894 if (!(ctx->flags & IORING_SETUP_IOPOLL))
895 return;
896
897 mutex_lock(&ctx->uring_lock);
898 while (!list_empty(&ctx->poll_list)) {
899 unsigned int nr_events = 0;
900
901 io_iopoll_getevents(ctx, &nr_events, 1);
902
903 /*
904 * Ensure we allow local-to-the-cpu processing to take place,
905 * in this case we need to ensure that we reap all events.
906 */
907 cond_resched();
908 }
909 mutex_unlock(&ctx->uring_lock);
910}
911
912static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
913 long min)
914{
915 int iters = 0, ret = 0;
916
917 /*
918 * We disallow the app entering submit/complete with polling, but we
919 * still need to lock the ring to prevent racing with polled issue
920 * that got punted to a workqueue.
921 */
922 mutex_lock(&ctx->uring_lock);
923 do {
924 int tmin = 0;
925
926 /*
927 * Don't enter poll loop if we already have events pending.
928 * If we do, we can potentially be spinning for commands that
929 * already triggered a CQE (eg in error).
930 */
931 if (io_cqring_events(ctx->rings))
932 break;
933
934 /*
935 * If a submit got punted to a workqueue, we can have the
936 * application entering polling for a command before it gets
937 * issued. That app will hold the uring_lock for the duration
938 * of the poll right here, so we need to take a breather every
939 * now and then to ensure that the issue has a chance to add
940 * the poll to the issued list. Otherwise we can spin here
941 * forever, while the workqueue is stuck trying to acquire the
942 * very same mutex.
943 */
944 if (!(++iters & 7)) {
945 mutex_unlock(&ctx->uring_lock);
946 mutex_lock(&ctx->uring_lock);
947 }
948
949 if (*nr_events < min)
950 tmin = min - *nr_events;
951
952 ret = io_iopoll_getevents(ctx, nr_events, tmin);
953 if (ret <= 0)
954 break;
955 ret = 0;
956 } while (min && !*nr_events && !need_resched());
957
958 mutex_unlock(&ctx->uring_lock);
959 return ret;
960}
961
962static void kiocb_end_write(struct io_kiocb *req)
963{
964 /*
965 * Tell lockdep we inherited freeze protection from submission
966 * thread.
967 */
968 if (req->flags & REQ_F_ISREG) {
969 struct inode *inode = file_inode(req->file);
970
971 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
972 }
973 file_end_write(req->file);
974}
975
976static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
977{
978 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
979
980 if (kiocb->ki_flags & IOCB_WRITE)
981 kiocb_end_write(req);
982
983 if ((req->flags & REQ_F_LINK) && res != req->result)
984 req->flags |= REQ_F_FAIL_LINK;
985 io_cqring_add_event(req->ctx, req->user_data, res);
986 io_put_req(req);
987}
988
989static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
990{
991 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw);
992
993 if (kiocb->ki_flags & IOCB_WRITE)
994 kiocb_end_write(req);
995
996 if ((req->flags & REQ_F_LINK) && res != req->result)
997 req->flags |= REQ_F_FAIL_LINK;
998 req->result = res;
999 if (res != -EAGAIN)
1000 req->flags |= REQ_F_IOPOLL_COMPLETED;
1001}
1002
1003/*
1004 * After the iocb has been issued, it's safe to be found on the poll list.
1005 * Adding the kiocb to the list AFTER submission ensures that we don't
1006 * find it from a io_iopoll_getevents() thread before the issuer is done
1007 * accessing the kiocb cookie.
1008 */
1009static void io_iopoll_req_issued(struct io_kiocb *req)
1010{
1011 struct io_ring_ctx *ctx = req->ctx;
1012
1013 /*
1014 * Track whether we have multiple files in our lists. This will impact
1015 * how we do polling eventually, not spinning if we're on potentially
1016 * different devices.
1017 */
1018 if (list_empty(&ctx->poll_list)) {
1019 ctx->poll_multi_file = false;
1020 } else if (!ctx->poll_multi_file) {
1021 struct io_kiocb *list_req;
1022
1023 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
1024 list);
1025 if (list_req->rw.ki_filp != req->rw.ki_filp)
1026 ctx->poll_multi_file = true;
1027 }
1028
1029 /*
1030 * For fast devices, IO may have already completed. If it has, add
1031 * it to the front so we find it first.
1032 */
1033 if (req->flags & REQ_F_IOPOLL_COMPLETED)
1034 list_add(&req->list, &ctx->poll_list);
1035 else
1036 list_add_tail(&req->list, &ctx->poll_list);
1037}
1038
1039static void io_file_put(struct io_submit_state *state)
1040{
1041 if (state->file) {
1042 int diff = state->has_refs - state->used_refs;
1043
1044 if (diff)
1045 fput_many(state->file, diff);
1046 state->file = NULL;
1047 }
1048}
1049
1050/*
1051 * Get as many references to a file as we have IOs left in this submission,
1052 * assuming most submissions are for one file, or at least that each file
1053 * has more than one submission.
1054 */
1055static struct file *io_file_get(struct io_submit_state *state, int fd)
1056{
1057 if (!state)
1058 return fget(fd);
1059
1060 if (state->file) {
1061 if (state->fd == fd) {
1062 state->used_refs++;
1063 state->ios_left--;
1064 return state->file;
1065 }
1066 io_file_put(state);
1067 }
1068 state->file = fget_many(fd, state->ios_left);
1069 if (!state->file)
1070 return NULL;
1071
1072 state->fd = fd;
1073 state->has_refs = state->ios_left;
1074 state->used_refs = 1;
1075 state->ios_left--;
1076 return state->file;
1077}
1078
1079/*
1080 * If we tracked the file through the SCM inflight mechanism, we could support
1081 * any file. For now, just ensure that anything potentially problematic is done
1082 * inline.
1083 */
1084static bool io_file_supports_async(struct file *file)
1085{
1086 umode_t mode = file_inode(file)->i_mode;
1087
1088 if (S_ISBLK(mode) || S_ISCHR(mode))
1089 return true;
1090 if (S_ISREG(mode) && file->f_op != &io_uring_fops)
1091 return true;
1092
1093 return false;
1094}
1095
1096static int io_prep_rw(struct io_kiocb *req, const struct sqe_submit *s,
1097 bool force_nonblock)
1098{
1099 const struct io_uring_sqe *sqe = s->sqe;
1100 struct io_ring_ctx *ctx = req->ctx;
1101 struct kiocb *kiocb = &req->rw;
1102 unsigned ioprio;
1103 int ret;
1104
1105 if (!req->file)
1106 return -EBADF;
1107
1108 if (S_ISREG(file_inode(req->file)->i_mode))
1109 req->flags |= REQ_F_ISREG;
1110
1111 if (force_nonblock)
1112 req->fsize = rlimit(RLIMIT_FSIZE);
1113
1114 /*
1115 * If the file doesn't support async, mark it as REQ_F_MUST_PUNT so
1116 * we know to async punt it even if it was opened O_NONBLOCK
1117 */
1118 if (force_nonblock && !io_file_supports_async(req->file)) {
1119 req->flags |= REQ_F_MUST_PUNT;
1120 return -EAGAIN;
1121 }
1122
1123 kiocb->ki_pos = READ_ONCE(sqe->off);
1124 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
1125 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
1126
1127 ioprio = READ_ONCE(sqe->ioprio);
1128 if (ioprio) {
1129 ret = ioprio_check_cap(ioprio);
1130 if (ret)
1131 return ret;
1132
1133 kiocb->ki_ioprio = ioprio;
1134 } else
1135 kiocb->ki_ioprio = get_current_ioprio();
1136
1137 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
1138 if (unlikely(ret))
1139 return ret;
1140
1141 /* don't allow async punt if RWF_NOWAIT was requested */
1142 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
1143 (req->file->f_flags & O_NONBLOCK))
1144 req->flags |= REQ_F_NOWAIT;
1145
1146 if (force_nonblock)
1147 kiocb->ki_flags |= IOCB_NOWAIT;
1148
1149 if (ctx->flags & IORING_SETUP_IOPOLL) {
1150 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
1151 !kiocb->ki_filp->f_op->iopoll)
1152 return -EOPNOTSUPP;
1153
1154 kiocb->ki_flags |= IOCB_HIPRI;
1155 kiocb->ki_complete = io_complete_rw_iopoll;
1156 req->result = 0;
1157 } else {
1158 if (kiocb->ki_flags & IOCB_HIPRI)
1159 return -EINVAL;
1160 kiocb->ki_complete = io_complete_rw;
1161 }
1162 return 0;
1163}
1164
1165static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
1166{
1167 switch (ret) {
1168 case -EIOCBQUEUED:
1169 break;
1170 case -ERESTARTSYS:
1171 case -ERESTARTNOINTR:
1172 case -ERESTARTNOHAND:
1173 case -ERESTART_RESTARTBLOCK:
1174 /*
1175 * We can't just restart the syscall, since previously
1176 * submitted sqes may already be in progress. Just fail this
1177 * IO with EINTR.
1178 */
1179 ret = -EINTR;
1180 /* fall through */
1181 default:
1182 kiocb->ki_complete(kiocb, ret, 0);
1183 }
1184}
1185
1186static int io_import_fixed(struct io_ring_ctx *ctx, int rw,
1187 const struct io_uring_sqe *sqe,
1188 struct iov_iter *iter)
1189{
1190 size_t len = READ_ONCE(sqe->len);
1191 struct io_mapped_ubuf *imu;
1192 unsigned index, buf_index;
1193 size_t offset;
1194 u64 buf_addr;
1195
1196 /* attempt to use fixed buffers without having provided iovecs */
1197 if (unlikely(!ctx->user_bufs))
1198 return -EFAULT;
1199
1200 buf_index = READ_ONCE(sqe->buf_index);
1201 if (unlikely(buf_index >= ctx->nr_user_bufs))
1202 return -EFAULT;
1203
1204 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
1205 imu = &ctx->user_bufs[index];
1206 buf_addr = READ_ONCE(sqe->addr);
1207
1208 /* overflow */
1209 if (buf_addr + len < buf_addr)
1210 return -EFAULT;
1211 /* not inside the mapped region */
1212 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
1213 return -EFAULT;
1214
1215 /*
1216 * May not be a start of buffer, set size appropriately
1217 * and advance us to the beginning.
1218 */
1219 offset = buf_addr - imu->ubuf;
1220 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
1221
1222 if (offset) {
1223 /*
1224 * Don't use iov_iter_advance() here, as it's really slow for
1225 * using the latter parts of a big fixed buffer - it iterates
1226 * over each segment manually. We can cheat a bit here, because
1227 * we know that:
1228 *
1229 * 1) it's a BVEC iter, we set it up
1230 * 2) all bvecs are PAGE_SIZE in size, except potentially the
1231 * first and last bvec
1232 *
1233 * So just find our index, and adjust the iterator afterwards.
1234 * If the offset is within the first bvec (or the whole first
1235 * bvec, just use iov_iter_advance(). This makes it easier
1236 * since we can just skip the first segment, which may not
1237 * be PAGE_SIZE aligned.
1238 */
1239 const struct bio_vec *bvec = imu->bvec;
1240
1241 if (offset < bvec->bv_len) {
1242 iov_iter_advance(iter, offset);
1243 } else {
1244 unsigned long seg_skip;
1245
1246 /* skip first vec */
1247 offset -= bvec->bv_len;
1248 seg_skip = 1 + (offset >> PAGE_SHIFT);
1249
1250 iter->bvec = bvec + seg_skip;
1251 iter->nr_segs -= seg_skip;
1252 iter->count -= bvec->bv_len + offset;
1253 iter->iov_offset = offset & ~PAGE_MASK;
1254 }
1255 }
1256
1257 return len;
1258}
1259
1260static ssize_t io_import_iovec(struct io_ring_ctx *ctx, int rw,
1261 struct io_kiocb *req, struct iovec **iovec,
1262 struct iov_iter *iter)
1263{
1264 const struct io_uring_sqe *sqe = req->submit.sqe;
1265 void __user *buf = u64_to_user_ptr(READ_ONCE(sqe->addr));
1266 size_t sqe_len = READ_ONCE(sqe->len);
1267 u8 opcode;
1268
1269 opcode = req->submit.opcode;
1270 if (opcode == IORING_OP_READ_FIXED ||
1271 opcode == IORING_OP_WRITE_FIXED) {
1272 ssize_t ret = io_import_fixed(ctx, rw, sqe, iter);
1273 *iovec = NULL;
1274 return ret;
1275 }
1276
1277 if (!req->submit.has_user)
1278 return -EFAULT;
1279
1280#ifdef CONFIG_COMPAT
1281 if (ctx->compat)
1282 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
1283 iovec, iter);
1284#endif
1285
1286 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
1287}
1288
1289static inline bool io_should_merge(struct async_list *al, struct kiocb *kiocb)
1290{
1291 if (al->file == kiocb->ki_filp) {
1292 off_t start, end;
1293
1294 /*
1295 * Allow merging if we're anywhere in the range of the same
1296 * page. Generally this happens for sub-page reads or writes,
1297 * and it's beneficial to allow the first worker to bring the
1298 * page in and the piggy backed work can then work on the
1299 * cached page.
1300 */
1301 start = al->io_start & PAGE_MASK;
1302 end = (al->io_start + al->io_len + PAGE_SIZE - 1) & PAGE_MASK;
1303 if (kiocb->ki_pos >= start && kiocb->ki_pos <= end)
1304 return true;
1305 }
1306
1307 al->file = NULL;
1308 return false;
1309}
1310
1311/*
1312 * Make a note of the last file/offset/direction we punted to async
1313 * context. We'll use this information to see if we can piggy back a
1314 * sequential request onto the previous one, if it's still hasn't been
1315 * completed by the async worker.
1316 */
1317static void io_async_list_note(int rw, struct io_kiocb *req, size_t len)
1318{
1319 struct async_list *async_list = &req->ctx->pending_async[rw];
1320 struct kiocb *kiocb = &req->rw;
1321 struct file *filp = kiocb->ki_filp;
1322
1323 if (io_should_merge(async_list, kiocb)) {
1324 unsigned long max_bytes;
1325
1326 /* Use 8x RA size as a decent limiter for both reads/writes */
1327 max_bytes = filp->f_ra.ra_pages << (PAGE_SHIFT + 3);
1328 if (!max_bytes)
1329 max_bytes = VM_READAHEAD_PAGES << (PAGE_SHIFT + 3);
1330
1331 /* If max len are exceeded, reset the state */
1332 if (async_list->io_len + len <= max_bytes) {
1333 req->flags |= REQ_F_SEQ_PREV;
1334 async_list->io_len += len;
1335 } else {
1336 async_list->file = NULL;
1337 }
1338 }
1339
1340 /* New file? Reset state. */
1341 if (async_list->file != filp) {
1342 async_list->io_start = kiocb->ki_pos;
1343 async_list->io_len = len;
1344 async_list->file = filp;
1345 }
1346}
1347
1348/*
1349 * For files that don't have ->read_iter() and ->write_iter(), handle them
1350 * by looping over ->read() or ->write() manually.
1351 */
1352static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
1353 struct iov_iter *iter)
1354{
1355 ssize_t ret = 0;
1356
1357 /*
1358 * Don't support polled IO through this interface, and we can't
1359 * support non-blocking either. For the latter, this just causes
1360 * the kiocb to be handled from an async context.
1361 */
1362 if (kiocb->ki_flags & IOCB_HIPRI)
1363 return -EOPNOTSUPP;
1364 if (kiocb->ki_flags & IOCB_NOWAIT)
1365 return -EAGAIN;
1366
1367 while (iov_iter_count(iter)) {
1368 struct iovec iovec;
1369 ssize_t nr;
1370
1371 if (!iov_iter_is_bvec(iter)) {
1372 iovec = iov_iter_iovec(iter);
1373 } else {
1374 /* fixed buffers import bvec */
1375 iovec.iov_base = kmap(iter->bvec->bv_page)
1376 + iter->iov_offset;
1377 iovec.iov_len = min(iter->count,
1378 iter->bvec->bv_len - iter->iov_offset);
1379 }
1380
1381 if (rw == READ) {
1382 nr = file->f_op->read(file, iovec.iov_base,
1383 iovec.iov_len, &kiocb->ki_pos);
1384 } else {
1385 nr = file->f_op->write(file, iovec.iov_base,
1386 iovec.iov_len, &kiocb->ki_pos);
1387 }
1388
1389 if (iov_iter_is_bvec(iter))
1390 kunmap(iter->bvec->bv_page);
1391
1392 if (nr < 0) {
1393 if (!ret)
1394 ret = nr;
1395 break;
1396 }
1397 ret += nr;
1398 if (nr != iovec.iov_len)
1399 break;
1400 iov_iter_advance(iter, nr);
1401 }
1402
1403 return ret;
1404}
1405
1406static int io_read(struct io_kiocb *req, const struct sqe_submit *s,
1407 bool force_nonblock)
1408{
1409 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1410 struct kiocb *kiocb = &req->rw;
1411 struct iov_iter iter;
1412 struct file *file;
1413 size_t iov_count;
1414 ssize_t read_size, ret;
1415
1416 ret = io_prep_rw(req, s, force_nonblock);
1417 if (ret)
1418 return ret;
1419 file = kiocb->ki_filp;
1420
1421 if (unlikely(!(file->f_mode & FMODE_READ)))
1422 return -EBADF;
1423
1424 ret = io_import_iovec(req->ctx, READ, req, &iovec, &iter);
1425 if (ret < 0)
1426 return ret;
1427
1428 read_size = ret;
1429 if (req->flags & REQ_F_LINK)
1430 req->result = read_size;
1431
1432 iov_count = iov_iter_count(&iter);
1433 ret = rw_verify_area(READ, file, &kiocb->ki_pos, iov_count);
1434 if (!ret) {
1435 ssize_t ret2;
1436
1437 if (file->f_op->read_iter)
1438 ret2 = call_read_iter(file, kiocb, &iter);
1439 else if (req->file->f_op->read)
1440 ret2 = loop_rw_iter(READ, file, kiocb, &iter);
1441 else
1442 ret2 = -EINVAL;
1443
1444 /*
1445 * In case of a short read, punt to async. This can happen
1446 * if we have data partially cached. Alternatively we can
1447 * return the short read, in which case the application will
1448 * need to issue another SQE and wait for it. That SQE will
1449 * need async punt anyway, so it's more efficient to do it
1450 * here.
1451 */
1452 if (force_nonblock && !(req->flags & REQ_F_NOWAIT) &&
1453 (req->flags & REQ_F_ISREG) &&
1454 ret2 > 0 && ret2 < read_size)
1455 ret2 = -EAGAIN;
1456 /* Catch -EAGAIN return for forced non-blocking submission */
1457 if (!force_nonblock || ret2 != -EAGAIN) {
1458 io_rw_done(kiocb, ret2);
1459 } else {
1460 /*
1461 * If ->needs_lock is true, we're already in async
1462 * context.
1463 */
1464 if (!s->needs_lock)
1465 io_async_list_note(READ, req, iov_count);
1466 ret = -EAGAIN;
1467 }
1468 }
1469 kfree(iovec);
1470 return ret;
1471}
1472
1473static int io_write(struct io_kiocb *req, const struct sqe_submit *s,
1474 bool force_nonblock)
1475{
1476 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
1477 struct kiocb *kiocb = &req->rw;
1478 struct iov_iter iter;
1479 struct file *file;
1480 size_t iov_count;
1481 ssize_t ret;
1482
1483 ret = io_prep_rw(req, s, force_nonblock);
1484 if (ret)
1485 return ret;
1486
1487 file = kiocb->ki_filp;
1488 if (unlikely(!(file->f_mode & FMODE_WRITE)))
1489 return -EBADF;
1490
1491 ret = io_import_iovec(req->ctx, WRITE, req, &iovec, &iter);
1492 if (ret < 0)
1493 return ret;
1494
1495 if (req->flags & REQ_F_LINK)
1496 req->result = ret;
1497
1498 iov_count = iov_iter_count(&iter);
1499
1500 ret = -EAGAIN;
1501 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT)) {
1502 /* If ->needs_lock is true, we're already in async context. */
1503 if (!s->needs_lock)
1504 io_async_list_note(WRITE, req, iov_count);
1505 goto out_free;
1506 }
1507
1508 ret = rw_verify_area(WRITE, file, &kiocb->ki_pos, iov_count);
1509 if (!ret) {
1510 ssize_t ret2;
1511
1512 /*
1513 * Open-code file_start_write here to grab freeze protection,
1514 * which will be released by another thread in
1515 * io_complete_rw(). Fool lockdep by telling it the lock got
1516 * released so that it doesn't complain about the held lock when
1517 * we return to userspace.
1518 */
1519 if (req->flags & REQ_F_ISREG) {
1520 __sb_start_write(file_inode(file)->i_sb,
1521 SB_FREEZE_WRITE, true);
1522 __sb_writers_release(file_inode(file)->i_sb,
1523 SB_FREEZE_WRITE);
1524 }
1525 kiocb->ki_flags |= IOCB_WRITE;
1526
1527 if (!force_nonblock)
1528 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
1529
1530 if (file->f_op->write_iter)
1531 ret2 = call_write_iter(file, kiocb, &iter);
1532 else if (req->file->f_op->write)
1533 ret2 = loop_rw_iter(WRITE, file, kiocb, &iter);
1534 else
1535 ret2 = -EINVAL;
1536
1537 if (!force_nonblock)
1538 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
1539
1540 if (!force_nonblock || ret2 != -EAGAIN) {
1541 io_rw_done(kiocb, ret2);
1542 } else {
1543 /*
1544 * If ->needs_lock is true, we're already in async
1545 * context.
1546 */
1547 if (!s->needs_lock)
1548 io_async_list_note(WRITE, req, iov_count);
1549 ret = -EAGAIN;
1550 }
1551 }
1552out_free:
1553 kfree(iovec);
1554 return ret;
1555}
1556
1557/*
1558 * IORING_OP_NOP just posts a completion event, nothing else.
1559 */
1560static int io_nop(struct io_kiocb *req, u64 user_data)
1561{
1562 struct io_ring_ctx *ctx = req->ctx;
1563 long err = 0;
1564
1565 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1566 return -EINVAL;
1567
1568 io_cqring_add_event(ctx, user_data, err);
1569 io_put_req(req);
1570 return 0;
1571}
1572
1573static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1574{
1575 struct io_ring_ctx *ctx = req->ctx;
1576
1577 if (!req->file)
1578 return -EBADF;
1579
1580 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1581 return -EINVAL;
1582 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1583 return -EINVAL;
1584
1585 return 0;
1586}
1587
1588static int io_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1589 bool force_nonblock)
1590{
1591 loff_t sqe_off = READ_ONCE(sqe->off);
1592 loff_t sqe_len = READ_ONCE(sqe->len);
1593 loff_t end = sqe_off + sqe_len;
1594 unsigned fsync_flags;
1595 int ret;
1596
1597 fsync_flags = READ_ONCE(sqe->fsync_flags);
1598 if (unlikely(fsync_flags & ~IORING_FSYNC_DATASYNC))
1599 return -EINVAL;
1600
1601 ret = io_prep_fsync(req, sqe);
1602 if (ret)
1603 return ret;
1604
1605 /* fsync always requires a blocking context */
1606 if (force_nonblock)
1607 return -EAGAIN;
1608
1609 ret = vfs_fsync_range(req->rw.ki_filp, sqe_off,
1610 end > 0 ? end : LLONG_MAX,
1611 fsync_flags & IORING_FSYNC_DATASYNC);
1612
1613 if (ret < 0 && (req->flags & REQ_F_LINK))
1614 req->flags |= REQ_F_FAIL_LINK;
1615 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1616 io_put_req(req);
1617 return 0;
1618}
1619
1620static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1621{
1622 struct io_ring_ctx *ctx = req->ctx;
1623 int ret = 0;
1624
1625 if (!req->file)
1626 return -EBADF;
1627
1628 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1629 return -EINVAL;
1630 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
1631 return -EINVAL;
1632
1633 return ret;
1634}
1635
1636static int io_sync_file_range(struct io_kiocb *req,
1637 const struct io_uring_sqe *sqe,
1638 bool force_nonblock)
1639{
1640 loff_t sqe_off;
1641 loff_t sqe_len;
1642 unsigned flags;
1643 int ret;
1644
1645 ret = io_prep_sfr(req, sqe);
1646 if (ret)
1647 return ret;
1648
1649 /* sync_file_range always requires a blocking context */
1650 if (force_nonblock)
1651 return -EAGAIN;
1652
1653 sqe_off = READ_ONCE(sqe->off);
1654 sqe_len = READ_ONCE(sqe->len);
1655 flags = READ_ONCE(sqe->sync_range_flags);
1656
1657 ret = sync_file_range(req->rw.ki_filp, sqe_off, sqe_len, flags);
1658
1659 if (ret < 0 && (req->flags & REQ_F_LINK))
1660 req->flags |= REQ_F_FAIL_LINK;
1661 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1662 io_put_req(req);
1663 return 0;
1664}
1665
1666#if defined(CONFIG_NET)
1667static int io_send_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1668 bool force_nonblock,
1669 long (*fn)(struct socket *, struct user_msghdr __user *,
1670 unsigned int))
1671{
1672 struct socket *sock;
1673 int ret;
1674
1675 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1676 return -EINVAL;
1677
1678 sock = sock_from_file(req->file, &ret);
1679 if (sock) {
1680 struct user_msghdr __user *msg;
1681 unsigned flags;
1682
1683 flags = READ_ONCE(sqe->msg_flags);
1684 if (flags & MSG_DONTWAIT)
1685 req->flags |= REQ_F_NOWAIT;
1686 else if (force_nonblock)
1687 flags |= MSG_DONTWAIT;
1688
1689#ifdef CONFIG_COMPAT
1690 if (req->ctx->compat)
1691 flags |= MSG_CMSG_COMPAT;
1692#endif
1693
1694 msg = (struct user_msghdr __user *) (unsigned long)
1695 READ_ONCE(sqe->addr);
1696
1697 ret = fn(sock, msg, flags);
1698 if (force_nonblock && ret == -EAGAIN)
1699 return ret;
1700 if (ret == -ERESTARTSYS)
1701 ret = -EINTR;
1702 }
1703
1704 io_req_put_fs(req);
1705 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1706 io_put_req(req);
1707 return 0;
1708}
1709#endif
1710
1711static int io_sendmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1712 bool force_nonblock)
1713{
1714#if defined(CONFIG_NET)
1715 return io_send_recvmsg(req, sqe, force_nonblock, __sys_sendmsg_sock);
1716#else
1717 return -EOPNOTSUPP;
1718#endif
1719}
1720
1721static int io_recvmsg(struct io_kiocb *req, const struct io_uring_sqe *sqe,
1722 bool force_nonblock)
1723{
1724#if defined(CONFIG_NET)
1725 return io_send_recvmsg(req, sqe, force_nonblock, __sys_recvmsg_sock);
1726#else
1727 return -EOPNOTSUPP;
1728#endif
1729}
1730
1731static void io_poll_remove_one(struct io_kiocb *req)
1732{
1733 struct io_poll_iocb *poll = &req->poll;
1734
1735 spin_lock(&poll->head->lock);
1736 WRITE_ONCE(poll->canceled, true);
1737 if (!list_empty(&poll->wait.entry)) {
1738 list_del_init(&poll->wait.entry);
1739 io_queue_async_work(req->ctx, req);
1740 }
1741 spin_unlock(&poll->head->lock);
1742
1743 list_del_init(&req->list);
1744}
1745
1746static void io_poll_remove_all(struct io_ring_ctx *ctx)
1747{
1748 struct io_kiocb *req;
1749
1750 spin_lock_irq(&ctx->completion_lock);
1751 while (!list_empty(&ctx->cancel_list)) {
1752 req = list_first_entry(&ctx->cancel_list, struct io_kiocb,list);
1753 io_poll_remove_one(req);
1754 }
1755 spin_unlock_irq(&ctx->completion_lock);
1756}
1757
1758/*
1759 * Find a running poll command that matches one specified in sqe->addr,
1760 * and remove it if found.
1761 */
1762static int io_poll_remove(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1763{
1764 struct io_ring_ctx *ctx = req->ctx;
1765 struct io_kiocb *poll_req, *next;
1766 int ret = -ENOENT;
1767
1768 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1769 return -EINVAL;
1770 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
1771 sqe->poll_events)
1772 return -EINVAL;
1773
1774 spin_lock_irq(&ctx->completion_lock);
1775 list_for_each_entry_safe(poll_req, next, &ctx->cancel_list, list) {
1776 if (READ_ONCE(sqe->addr) == poll_req->user_data) {
1777 io_poll_remove_one(poll_req);
1778 ret = 0;
1779 break;
1780 }
1781 }
1782 spin_unlock_irq(&ctx->completion_lock);
1783
1784 io_cqring_add_event(req->ctx, sqe->user_data, ret);
1785 io_put_req(req);
1786 return 0;
1787}
1788
1789static void io_poll_complete(struct io_ring_ctx *ctx, struct io_kiocb *req,
1790 __poll_t mask)
1791{
1792 req->poll.done = true;
1793 io_cqring_fill_event(ctx, req->user_data, mangle_poll(mask));
1794 io_commit_cqring(ctx);
1795}
1796
1797static void io_poll_complete_work(struct work_struct *work)
1798{
1799 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
1800 struct io_poll_iocb *poll = &req->poll;
1801 struct poll_table_struct pt = { ._key = poll->events };
1802 struct io_ring_ctx *ctx = req->ctx;
1803 const struct cred *old_cred;
1804 __poll_t mask = 0;
1805
1806 old_cred = override_creds(ctx->creds);
1807
1808 if (!READ_ONCE(poll->canceled))
1809 mask = vfs_poll(poll->file, &pt) & poll->events;
1810
1811 /*
1812 * Note that ->ki_cancel callers also delete iocb from active_reqs after
1813 * calling ->ki_cancel. We need the ctx_lock roundtrip here to
1814 * synchronize with them. In the cancellation case the list_del_init
1815 * itself is not actually needed, but harmless so we keep it in to
1816 * avoid further branches in the fast path.
1817 */
1818 spin_lock_irq(&ctx->completion_lock);
1819 if (!mask && !READ_ONCE(poll->canceled)) {
1820 add_wait_queue(poll->head, &poll->wait);
1821 spin_unlock_irq(&ctx->completion_lock);
1822 goto out;
1823 }
1824 list_del_init(&req->list);
1825 io_poll_complete(ctx, req, mask);
1826 spin_unlock_irq(&ctx->completion_lock);
1827
1828 io_cqring_ev_posted(ctx);
1829 io_put_req(req);
1830out:
1831 revert_creds(old_cred);
1832}
1833
1834static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
1835 void *key)
1836{
1837 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
1838 wait);
1839 struct io_kiocb *req = container_of(poll, struct io_kiocb, poll);
1840 struct io_ring_ctx *ctx = req->ctx;
1841 __poll_t mask = key_to_poll(key);
1842 unsigned long flags;
1843
1844 /* for instances that support it check for an event match first: */
1845 if (mask && !(mask & poll->events))
1846 return 0;
1847
1848 list_del_init(&poll->wait.entry);
1849
1850 if (mask && spin_trylock_irqsave(&ctx->completion_lock, flags)) {
1851 list_del(&req->list);
1852 io_poll_complete(ctx, req, mask);
1853 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1854
1855 io_cqring_ev_posted(ctx);
1856 io_put_req(req);
1857 } else {
1858 io_queue_async_work(ctx, req);
1859 }
1860
1861 return 1;
1862}
1863
1864struct io_poll_table {
1865 struct poll_table_struct pt;
1866 struct io_kiocb *req;
1867 int error;
1868};
1869
1870static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
1871 struct poll_table_struct *p)
1872{
1873 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
1874
1875 if (unlikely(pt->req->poll.head)) {
1876 pt->error = -EINVAL;
1877 return;
1878 }
1879
1880 pt->error = 0;
1881 pt->req->poll.head = head;
1882 add_wait_queue(head, &pt->req->poll.wait);
1883}
1884
1885static int io_poll_add(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1886{
1887 struct io_poll_iocb *poll = &req->poll;
1888 struct io_ring_ctx *ctx = req->ctx;
1889 struct io_poll_table ipt;
1890 bool cancel = false;
1891 __poll_t mask;
1892 u16 events;
1893
1894 if (req->file->f_op->may_pollfree)
1895 return -EOPNOTSUPP;
1896
1897 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
1898 return -EINVAL;
1899 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
1900 return -EINVAL;
1901 if (!poll->file)
1902 return -EBADF;
1903
1904 req->submit.sqe = NULL;
1905 INIT_WORK(&req->work, io_poll_complete_work);
1906 events = READ_ONCE(sqe->poll_events);
1907 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP;
1908
1909 poll->head = NULL;
1910 poll->done = false;
1911 poll->canceled = false;
1912
1913 ipt.pt._qproc = io_poll_queue_proc;
1914 ipt.pt._key = poll->events;
1915 ipt.req = req;
1916 ipt.error = -EINVAL; /* same as no support for IOCB_CMD_POLL */
1917
1918 /* initialized the list so that we can do list_empty checks */
1919 INIT_LIST_HEAD(&poll->wait.entry);
1920 init_waitqueue_func_entry(&poll->wait, io_poll_wake);
1921
1922 INIT_LIST_HEAD(&req->list);
1923
1924 mask = vfs_poll(poll->file, &ipt.pt) & poll->events;
1925
1926 spin_lock_irq(&ctx->completion_lock);
1927 if (likely(poll->head)) {
1928 spin_lock(&poll->head->lock);
1929 if (unlikely(list_empty(&poll->wait.entry))) {
1930 if (ipt.error)
1931 cancel = true;
1932 ipt.error = 0;
1933 mask = 0;
1934 }
1935 if (mask || ipt.error)
1936 list_del_init(&poll->wait.entry);
1937 else if (cancel)
1938 WRITE_ONCE(poll->canceled, true);
1939 else if (!poll->done) /* actually waiting for an event */
1940 list_add_tail(&req->list, &ctx->cancel_list);
1941 spin_unlock(&poll->head->lock);
1942 }
1943 if (mask) { /* no async, we'd stolen it */
1944 ipt.error = 0;
1945 io_poll_complete(ctx, req, mask);
1946 }
1947 spin_unlock_irq(&ctx->completion_lock);
1948
1949 if (mask) {
1950 io_cqring_ev_posted(ctx);
1951 io_put_req(req);
1952 }
1953 return ipt.error;
1954}
1955
1956static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
1957{
1958 struct io_ring_ctx *ctx;
1959 struct io_kiocb *req, *prev;
1960 unsigned long flags;
1961
1962 req = container_of(timer, struct io_kiocb, timeout.timer);
1963 ctx = req->ctx;
1964 atomic_inc(&ctx->cq_timeouts);
1965
1966 spin_lock_irqsave(&ctx->completion_lock, flags);
1967 /*
1968 * Adjust the reqs sequence before the current one because it
1969 * will consume a slot in the cq_ring and the the cq_tail pointer
1970 * will be increased, otherwise other timeout reqs may return in
1971 * advance without waiting for enough wait_nr.
1972 */
1973 prev = req;
1974 list_for_each_entry_continue_reverse(prev, &ctx->timeout_list, list)
1975 prev->sequence++;
1976 list_del(&req->list);
1977
1978 io_cqring_fill_event(ctx, req->user_data, -ETIME);
1979 io_commit_cqring(ctx);
1980 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1981
1982 io_cqring_ev_posted(ctx);
1983
1984 io_put_req(req);
1985 return HRTIMER_NORESTART;
1986}
1987
1988static int io_timeout(struct io_kiocb *req, const struct io_uring_sqe *sqe)
1989{
1990 unsigned count;
1991 struct io_ring_ctx *ctx = req->ctx;
1992 struct list_head *entry;
1993 struct timespec64 ts;
1994 unsigned span = 0;
1995
1996 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
1997 return -EINVAL;
1998 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->timeout_flags ||
1999 sqe->len != 1)
2000 return -EINVAL;
2001
2002 if (get_timespec64(&ts, u64_to_user_ptr(sqe->addr)))
2003 return -EFAULT;
2004
2005 req->flags |= REQ_F_TIMEOUT;
2006
2007 /*
2008 * sqe->off holds how many events that need to occur for this
2009 * timeout event to be satisfied. If it isn't set, then this is
2010 * a pure timeout request, sequence isn't used.
2011 */
2012 count = READ_ONCE(sqe->off);
2013 if (!count) {
2014 req->flags |= REQ_F_TIMEOUT_NOSEQ;
2015 spin_lock_irq(&ctx->completion_lock);
2016 entry = ctx->timeout_list.prev;
2017 goto add;
2018 }
2019
2020 req->sequence = ctx->cached_sq_head + count - 1;
2021 /* reuse it to store the count */
2022 req->submit.sequence = count;
2023
2024 /*
2025 * Insertion sort, ensuring the first entry in the list is always
2026 * the one we need first.
2027 */
2028 spin_lock_irq(&ctx->completion_lock);
2029 list_for_each_prev(entry, &ctx->timeout_list) {
2030 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
2031 unsigned nxt_sq_head;
2032 long long tmp, tmp_nxt;
2033
2034 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
2035 continue;
2036
2037 /*
2038 * Since cached_sq_head + count - 1 can overflow, use type long
2039 * long to store it.
2040 */
2041 tmp = (long long)ctx->cached_sq_head + count - 1;
2042 nxt_sq_head = nxt->sequence - nxt->submit.sequence + 1;
2043 tmp_nxt = (long long)nxt_sq_head + nxt->submit.sequence - 1;
2044
2045 /*
2046 * cached_sq_head may overflow, and it will never overflow twice
2047 * once there is some timeout req still be valid.
2048 */
2049 if (ctx->cached_sq_head < nxt_sq_head)
2050 tmp += UINT_MAX;
2051
2052 if (tmp > tmp_nxt)
2053 break;
2054
2055 /*
2056 * Sequence of reqs after the insert one and itself should
2057 * be adjusted because each timeout req consumes a slot.
2058 */
2059 span++;
2060 nxt->sequence++;
2061 }
2062 req->sequence -= span;
2063add:
2064 list_add(&req->list, entry);
2065
2066 hrtimer_init(&req->timeout.timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2067 req->timeout.timer.function = io_timeout_fn;
2068 hrtimer_start(&req->timeout.timer, timespec64_to_ktime(ts),
2069 HRTIMER_MODE_REL);
2070 spin_unlock_irq(&ctx->completion_lock);
2071 return 0;
2072}
2073
2074static int io_req_defer(struct io_ring_ctx *ctx, struct io_kiocb *req,
2075 struct sqe_submit *s)
2076{
2077 struct io_uring_sqe *sqe_copy;
2078
2079 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list))
2080 return 0;
2081
2082 sqe_copy = kmalloc(sizeof(*sqe_copy), GFP_KERNEL);
2083 if (!sqe_copy)
2084 return -EAGAIN;
2085
2086 spin_lock_irq(&ctx->completion_lock);
2087 if (!io_sequence_defer(ctx, req) && list_empty(&ctx->defer_list)) {
2088 spin_unlock_irq(&ctx->completion_lock);
2089 kfree(sqe_copy);
2090 return 0;
2091 }
2092
2093 memcpy(&req->submit, s, sizeof(*s));
2094 memcpy(sqe_copy, s->sqe, sizeof(*sqe_copy));
2095 req->submit.sqe = sqe_copy;
2096
2097 INIT_WORK(&req->work, io_sq_wq_submit_work);
2098 list_add_tail(&req->list, &ctx->defer_list);
2099 spin_unlock_irq(&ctx->completion_lock);
2100 return -EIOCBQUEUED;
2101}
2102
2103static int __io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2104 const struct sqe_submit *s, bool force_nonblock)
2105{
2106 int ret;
2107
2108 req->user_data = READ_ONCE(s->sqe->user_data);
2109
2110 if (unlikely(s->index >= ctx->sq_entries))
2111 return -EINVAL;
2112
2113 switch (req->submit.opcode) {
2114 case IORING_OP_NOP:
2115 if (READ_ONCE(s->sqe->rw_flags))
2116 return -EINVAL;
2117 ret = io_nop(req, req->user_data);
2118 break;
2119 case IORING_OP_READV:
2120 if (unlikely(s->sqe->buf_index))
2121 return -EINVAL;
2122 ret = io_read(req, s, force_nonblock);
2123 break;
2124 case IORING_OP_WRITEV:
2125 if (unlikely(s->sqe->buf_index))
2126 return -EINVAL;
2127 ret = io_write(req, s, force_nonblock);
2128 break;
2129 case IORING_OP_READ_FIXED:
2130 ret = io_read(req, s, force_nonblock);
2131 break;
2132 case IORING_OP_WRITE_FIXED:
2133 ret = io_write(req, s, force_nonblock);
2134 break;
2135 case IORING_OP_FSYNC:
2136 ret = io_fsync(req, s->sqe, force_nonblock);
2137 break;
2138 case IORING_OP_POLL_ADD:
2139 ret = io_poll_add(req, s->sqe);
2140 break;
2141 case IORING_OP_POLL_REMOVE:
2142 ret = io_poll_remove(req, s->sqe);
2143 break;
2144 case IORING_OP_SYNC_FILE_RANGE:
2145 ret = io_sync_file_range(req, s->sqe, force_nonblock);
2146 break;
2147 case IORING_OP_SENDMSG:
2148 ret = io_sendmsg(req, s->sqe, force_nonblock);
2149 break;
2150 case IORING_OP_RECVMSG:
2151 ret = io_recvmsg(req, s->sqe, force_nonblock);
2152 break;
2153 case IORING_OP_TIMEOUT:
2154 ret = io_timeout(req, s->sqe);
2155 break;
2156 default:
2157 ret = -EINVAL;
2158 break;
2159 }
2160
2161 if (ret)
2162 return ret;
2163
2164 if (ctx->flags & IORING_SETUP_IOPOLL) {
2165 if (req->result == -EAGAIN)
2166 return -EAGAIN;
2167
2168 /* workqueue context doesn't hold uring_lock, grab it now */
2169 if (s->needs_lock)
2170 mutex_lock(&ctx->uring_lock);
2171 io_iopoll_req_issued(req);
2172 if (s->needs_lock)
2173 mutex_unlock(&ctx->uring_lock);
2174 }
2175
2176 return 0;
2177}
2178
2179static struct async_list *io_async_list_from_req(struct io_ring_ctx *ctx,
2180 struct io_kiocb *req)
2181{
2182 switch (req->submit.opcode) {
2183 case IORING_OP_READV:
2184 case IORING_OP_READ_FIXED:
2185 return &ctx->pending_async[READ];
2186 case IORING_OP_WRITEV:
2187 case IORING_OP_WRITE_FIXED:
2188 return &ctx->pending_async[WRITE];
2189 default:
2190 return NULL;
2191 }
2192}
2193
2194static inline bool io_req_needs_user(struct io_kiocb *req)
2195{
2196 return !(req->submit.opcode == IORING_OP_READ_FIXED ||
2197 req->submit.opcode == IORING_OP_WRITE_FIXED);
2198}
2199
2200static void io_sq_wq_submit_work(struct work_struct *work)
2201{
2202 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
2203 struct fs_struct *old_fs_struct = current->fs;
2204 struct io_ring_ctx *ctx = req->ctx;
2205 struct mm_struct *cur_mm = NULL;
2206 struct async_list *async_list;
2207 const struct cred *old_cred;
2208 LIST_HEAD(req_list);
2209 mm_segment_t old_fs;
2210 int ret;
2211
2212 old_cred = override_creds(ctx->creds);
2213 async_list = io_async_list_from_req(ctx, req);
2214
2215 allow_kernel_signal(SIGINT);
2216restart:
2217 do {
2218 struct sqe_submit *s = &req->submit;
2219 const struct io_uring_sqe *sqe = s->sqe;
2220 unsigned int flags = req->flags;
2221
2222 /* Ensure we clear previously set non-block flag */
2223 req->rw.ki_flags &= ~IOCB_NOWAIT;
2224
2225 if ((req->fs && req->fs != current->fs) ||
2226 (!req->fs && current->fs != old_fs_struct)) {
2227 task_lock(current);
2228 if (req->fs)
2229 current->fs = req->fs;
2230 else
2231 current->fs = old_fs_struct;
2232 task_unlock(current);
2233 }
2234
2235 ret = 0;
2236 if (io_req_needs_user(req) && !cur_mm) {
2237 if (!mmget_not_zero(ctx->sqo_mm)) {
2238 ret = -EFAULT;
2239 goto end_req;
2240 } else {
2241 cur_mm = ctx->sqo_mm;
2242 use_mm(cur_mm);
2243 old_fs = get_fs();
2244 set_fs(USER_DS);
2245 }
2246 }
2247
2248 if (!ret) {
2249 req->work_task = current;
2250
2251 /*
2252 * Pairs with the smp_store_mb() (B) in
2253 * io_cancel_async_work().
2254 */
2255 smp_mb(); /* A */
2256 if (req->flags & REQ_F_CANCEL) {
2257 ret = -ECANCELED;
2258 goto end_req;
2259 }
2260
2261 s->has_user = cur_mm != NULL;
2262 s->needs_lock = true;
2263 do {
2264 ret = __io_submit_sqe(ctx, req, s, false);
2265 /*
2266 * We can get EAGAIN for polled IO even though
2267 * we're forcing a sync submission from here,
2268 * since we can't wait for request slots on the
2269 * block side.
2270 */
2271 if (ret != -EAGAIN)
2272 break;
2273 cond_resched();
2274 } while (1);
2275 }
2276end_req:
2277 spin_lock_irq(&ctx->task_lock);
2278 list_del_init(&req->task_list);
2279 spin_unlock_irq(&ctx->task_lock);
2280
2281 /* drop submission reference */
2282 io_put_req(req);
2283
2284 if (ret) {
2285 io_cqring_add_event(ctx, sqe->user_data, ret);
2286 io_put_req(req);
2287 }
2288
2289 /* async context always use a copy of the sqe */
2290 kfree(sqe);
2291
2292 /* req from defer and link list needn't decrease async cnt */
2293 if (flags & (REQ_F_IO_DRAINED | REQ_F_LINK_DONE))
2294 goto out;
2295
2296 if (!async_list)
2297 break;
2298 if (!list_empty(&req_list)) {
2299 req = list_first_entry(&req_list, struct io_kiocb,
2300 list);
2301 list_del(&req->list);
2302 continue;
2303 }
2304 if (list_empty(&async_list->list))
2305 break;
2306
2307 req = NULL;
2308 spin_lock(&async_list->lock);
2309 if (list_empty(&async_list->list)) {
2310 spin_unlock(&async_list->lock);
2311 break;
2312 }
2313 list_splice_init(&async_list->list, &req_list);
2314 spin_unlock(&async_list->lock);
2315
2316 req = list_first_entry(&req_list, struct io_kiocb, list);
2317 list_del(&req->list);
2318 } while (req);
2319
2320 /*
2321 * Rare case of racing with a submitter. If we find the count has
2322 * dropped to zero AND we have pending work items, then restart
2323 * the processing. This is a tiny race window.
2324 */
2325 if (async_list) {
2326 ret = atomic_dec_return(&async_list->cnt);
2327 while (!ret && !list_empty(&async_list->list)) {
2328 spin_lock(&async_list->lock);
2329 atomic_inc(&async_list->cnt);
2330 list_splice_init(&async_list->list, &req_list);
2331 spin_unlock(&async_list->lock);
2332
2333 if (!list_empty(&req_list)) {
2334 req = list_first_entry(&req_list,
2335 struct io_kiocb, list);
2336 list_del(&req->list);
2337 goto restart;
2338 }
2339 ret = atomic_dec_return(&async_list->cnt);
2340 }
2341 }
2342
2343out:
2344 disallow_signal(SIGINT);
2345 if (cur_mm) {
2346 set_fs(old_fs);
2347 unuse_mm(cur_mm);
2348 mmput(cur_mm);
2349 }
2350 revert_creds(old_cred);
2351 if (old_fs_struct != current->fs) {
2352 task_lock(current);
2353 current->fs = old_fs_struct;
2354 task_unlock(current);
2355 }
2356}
2357
2358/*
2359 * See if we can piggy back onto previously submitted work, that is still
2360 * running. We currently only allow this if the new request is sequential
2361 * to the previous one we punted.
2362 */
2363static bool io_add_to_prev_work(struct async_list *list, struct io_kiocb *req)
2364{
2365 bool ret;
2366
2367 if (!list)
2368 return false;
2369 if (!(req->flags & REQ_F_SEQ_PREV))
2370 return false;
2371 if (!atomic_read(&list->cnt))
2372 return false;
2373
2374 ret = true;
2375 spin_lock(&list->lock);
2376 list_add_tail(&req->list, &list->list);
2377 /*
2378 * Ensure we see a simultaneous modification from io_sq_wq_submit_work()
2379 */
2380 smp_mb();
2381 if (!atomic_read(&list->cnt)) {
2382 list_del_init(&req->list);
2383 ret = false;
2384 }
2385
2386 if (ret) {
2387 struct io_ring_ctx *ctx = req->ctx;
2388
2389 req->files = current->files;
2390
2391 spin_lock_irq(&ctx->task_lock);
2392 list_add(&req->task_list, &ctx->task_list);
2393 req->work_task = NULL;
2394 spin_unlock_irq(&ctx->task_lock);
2395 }
2396 spin_unlock(&list->lock);
2397 return ret;
2398}
2399
2400static bool io_op_needs_file(struct io_kiocb *req)
2401{
2402 switch (req->submit.opcode) {
2403 case IORING_OP_NOP:
2404 case IORING_OP_POLL_REMOVE:
2405 case IORING_OP_TIMEOUT:
2406 return false;
2407 default:
2408 return true;
2409 }
2410}
2411
2412static int io_req_set_file(struct io_ring_ctx *ctx, const struct sqe_submit *s,
2413 struct io_submit_state *state, struct io_kiocb *req)
2414{
2415 unsigned flags;
2416 int fd;
2417
2418 flags = READ_ONCE(s->sqe->flags);
2419 fd = READ_ONCE(s->sqe->fd);
2420
2421 if (flags & IOSQE_IO_DRAIN)
2422 req->flags |= REQ_F_IO_DRAIN;
2423 /*
2424 * All io need record the previous position, if LINK vs DARIN,
2425 * it can be used to mark the position of the first IO in the
2426 * link list.
2427 */
2428 req->sequence = s->sequence;
2429
2430 if (!io_op_needs_file(req))
2431 return 0;
2432
2433 if (flags & IOSQE_FIXED_FILE) {
2434 if (unlikely(!ctx->user_files ||
2435 (unsigned) fd >= ctx->nr_user_files))
2436 return -EBADF;
2437 req->file = ctx->user_files[fd];
2438 req->flags |= REQ_F_FIXED_FILE;
2439 } else {
2440 if (s->needs_fixed_file)
2441 return -EBADF;
2442 req->file = io_file_get(state, fd);
2443 if (unlikely(!req->file))
2444 return -EBADF;
2445 }
2446
2447 return 0;
2448}
2449
2450static int __io_queue_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2451 struct sqe_submit *s)
2452{
2453 int ret;
2454
2455 ret = __io_submit_sqe(ctx, req, s, true);
2456
2457 /*
2458 * We async punt it if the file wasn't marked NOWAIT, or if the file
2459 * doesn't support non-blocking read/write attempts
2460 */
2461 if (ret == -EAGAIN && (!(req->flags & REQ_F_NOWAIT) ||
2462 (req->flags & REQ_F_MUST_PUNT))) {
2463 struct io_uring_sqe *sqe_copy;
2464
2465 sqe_copy = kmemdup(s->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2466 if (sqe_copy) {
2467 struct async_list *list;
2468
2469 s->sqe = sqe_copy;
2470 memcpy(&req->submit, s, sizeof(*s));
2471 list = io_async_list_from_req(ctx, req);
2472 if (!io_add_to_prev_work(list, req)) {
2473 if (list)
2474 atomic_inc(&list->cnt);
2475 INIT_WORK(&req->work, io_sq_wq_submit_work);
2476 io_queue_async_work(ctx, req);
2477 }
2478
2479 /*
2480 * Queued up for async execution, worker will release
2481 * submit reference when the iocb is actually submitted.
2482 */
2483 return 0;
2484 }
2485 }
2486
2487 /* drop submission reference */
2488 io_put_req(req);
2489
2490 /* and drop final reference, if we failed */
2491 if (ret) {
2492 io_cqring_add_event(ctx, req->user_data, ret);
2493 if (req->flags & REQ_F_LINK)
2494 req->flags |= REQ_F_FAIL_LINK;
2495 io_put_req(req);
2496 }
2497
2498 return ret;
2499}
2500
2501static int io_queue_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
2502 struct sqe_submit *s)
2503{
2504 int ret;
2505
2506 ret = io_req_defer(ctx, req, s);
2507 if (ret) {
2508 if (ret != -EIOCBQUEUED) {
2509 io_free_req(req);
2510 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2511 }
2512 return 0;
2513 }
2514
2515 return __io_queue_sqe(ctx, req, s);
2516}
2517
2518static int io_queue_link_head(struct io_ring_ctx *ctx, struct io_kiocb *req,
2519 struct sqe_submit *s, struct io_kiocb *shadow)
2520{
2521 int ret;
2522 int need_submit = false;
2523
2524 if (!shadow)
2525 return io_queue_sqe(ctx, req, s);
2526
2527 /*
2528 * Mark the first IO in link list as DRAIN, let all the following
2529 * IOs enter the defer list. all IO needs to be completed before link
2530 * list.
2531 */
2532 req->flags |= REQ_F_IO_DRAIN;
2533 ret = io_req_defer(ctx, req, s);
2534 if (ret) {
2535 if (ret != -EIOCBQUEUED) {
2536 io_free_req(req);
2537 __io_free_req(shadow);
2538 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2539 return 0;
2540 }
2541 } else {
2542 /*
2543 * If ret == 0 means that all IOs in front of link io are
2544 * running done. let's queue link head.
2545 */
2546 need_submit = true;
2547 }
2548
2549 /* Insert shadow req to defer_list, blocking next IOs */
2550 spin_lock_irq(&ctx->completion_lock);
2551 list_add_tail(&shadow->list, &ctx->defer_list);
2552 spin_unlock_irq(&ctx->completion_lock);
2553
2554 if (need_submit)
2555 return __io_queue_sqe(ctx, req, s);
2556
2557 return 0;
2558}
2559
2560#define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK)
2561
2562static void io_submit_sqe(struct io_ring_ctx *ctx, struct sqe_submit *s,
2563 struct io_submit_state *state, struct io_kiocb **link)
2564{
2565 struct io_uring_sqe *sqe_copy;
2566 struct io_kiocb *req;
2567 int ret;
2568
2569 /* enforce forwards compatibility on users */
2570 if (unlikely(s->sqe->flags & ~SQE_VALID_FLAGS)) {
2571 ret = -EINVAL;
2572 goto err;
2573 }
2574
2575 req = io_get_req(ctx, state);
2576 if (unlikely(!req)) {
2577 ret = -EAGAIN;
2578 goto err;
2579 }
2580
2581 memcpy(&req->submit, s, sizeof(*s));
2582 ret = io_req_set_file(ctx, s, state, req);
2583 if (unlikely(ret)) {
2584err_req:
2585 io_free_req(req);
2586err:
2587 io_cqring_add_event(ctx, s->sqe->user_data, ret);
2588 return;
2589 }
2590
2591 req->user_data = s->sqe->user_data;
2592
2593#if defined(CONFIG_NET)
2594 switch (req->submit.opcode) {
2595 case IORING_OP_SENDMSG:
2596 case IORING_OP_RECVMSG:
2597 spin_lock(&current->fs->lock);
2598 if (!current->fs->in_exec) {
2599 req->fs = current->fs;
2600 req->fs->users++;
2601 }
2602 spin_unlock(&current->fs->lock);
2603 if (!req->fs) {
2604 ret = -EAGAIN;
2605 goto err_req;
2606 }
2607 }
2608#endif
2609
2610 /*
2611 * If we already have a head request, queue this one for async
2612 * submittal once the head completes. If we don't have a head but
2613 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
2614 * submitted sync once the chain is complete. If none of those
2615 * conditions are true (normal request), then just queue it.
2616 */
2617 if (*link) {
2618 struct io_kiocb *prev = *link;
2619
2620 sqe_copy = kmemdup(s->sqe, sizeof(*sqe_copy), GFP_KERNEL);
2621 if (!sqe_copy) {
2622 ret = -EAGAIN;
2623 goto err_req;
2624 }
2625
2626 s->sqe = sqe_copy;
2627 memcpy(&req->submit, s, sizeof(*s));
2628 list_add_tail(&req->list, &prev->link_list);
2629 } else if (s->sqe->flags & IOSQE_IO_LINK) {
2630 req->flags |= REQ_F_LINK;
2631
2632 memcpy(&req->submit, s, sizeof(*s));
2633 INIT_LIST_HEAD(&req->link_list);
2634 *link = req;
2635 } else {
2636 io_queue_sqe(ctx, req, s);
2637 }
2638}
2639
2640/*
2641 * Batched submission is done, ensure local IO is flushed out.
2642 */
2643static void io_submit_state_end(struct io_submit_state *state)
2644{
2645 blk_finish_plug(&state->plug);
2646 io_file_put(state);
2647 if (state->free_reqs)
2648 kmem_cache_free_bulk(req_cachep, state->free_reqs,
2649 &state->reqs[state->cur_req]);
2650}
2651
2652/*
2653 * Start submission side cache.
2654 */
2655static void io_submit_state_start(struct io_submit_state *state,
2656 struct io_ring_ctx *ctx, unsigned max_ios)
2657{
2658 blk_start_plug(&state->plug);
2659 state->free_reqs = 0;
2660 state->file = NULL;
2661 state->ios_left = max_ios;
2662}
2663
2664static void io_commit_sqring(struct io_ring_ctx *ctx)
2665{
2666 struct io_rings *rings = ctx->rings;
2667
2668 if (ctx->cached_sq_head != READ_ONCE(rings->sq.head)) {
2669 /*
2670 * Ensure any loads from the SQEs are done at this point,
2671 * since once we write the new head, the application could
2672 * write new data to them.
2673 */
2674 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2675 }
2676}
2677
2678/*
2679 * Fetch an sqe, if one is available. Note that s->sqe will point to memory
2680 * that is mapped by userspace. This means that care needs to be taken to
2681 * ensure that reads are stable, as we cannot rely on userspace always
2682 * being a good citizen. If members of the sqe are validated and then later
2683 * used, it's important that those reads are done through READ_ONCE() to
2684 * prevent a re-load down the line.
2685 */
2686static bool io_get_sqring(struct io_ring_ctx *ctx, struct sqe_submit *s)
2687{
2688 struct io_rings *rings = ctx->rings;
2689 u32 *sq_array = ctx->sq_array;
2690 unsigned head;
2691
2692 /*
2693 * The cached sq head (or cq tail) serves two purposes:
2694 *
2695 * 1) allows us to batch the cost of updating the user visible
2696 * head updates.
2697 * 2) allows the kernel side to track the head on its own, even
2698 * though the application is the one updating it.
2699 */
2700 head = ctx->cached_sq_head;
2701 /* make sure SQ entry isn't read before tail */
2702 if (head == smp_load_acquire(&rings->sq.tail))
2703 return false;
2704
2705 head = READ_ONCE(sq_array[head & ctx->sq_mask]);
2706 if (head < ctx->sq_entries) {
2707 s->index = head;
2708 s->sqe = &ctx->sq_sqes[head];
2709 s->opcode = READ_ONCE(s->sqe->opcode);
2710 s->sequence = ctx->cached_sq_head;
2711 ctx->cached_sq_head++;
2712 return true;
2713 }
2714
2715 /* drop invalid entries */
2716 ctx->cached_sq_head++;
2717 ctx->cached_sq_dropped++;
2718 WRITE_ONCE(rings->sq_dropped, ctx->cached_sq_dropped);
2719 return false;
2720}
2721
2722static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
2723 bool has_user, bool mm_fault)
2724{
2725 struct io_submit_state state, *statep = NULL;
2726 struct io_kiocb *link = NULL;
2727 struct io_kiocb *shadow_req = NULL;
2728 bool prev_was_link = false;
2729 int i, submitted = 0;
2730
2731 if (nr > IO_PLUG_THRESHOLD) {
2732 io_submit_state_start(&state, ctx, nr);
2733 statep = &state;
2734 }
2735
2736 for (i = 0; i < nr; i++) {
2737 struct sqe_submit s;
2738
2739 if (!io_get_sqring(ctx, &s))
2740 break;
2741
2742 /*
2743 * If previous wasn't linked and we have a linked command,
2744 * that's the end of the chain. Submit the previous link.
2745 */
2746 if (!prev_was_link && link) {
2747 io_queue_link_head(ctx, link, &link->submit, shadow_req);
2748 link = NULL;
2749 shadow_req = NULL;
2750 }
2751 prev_was_link = (s.sqe->flags & IOSQE_IO_LINK) != 0;
2752
2753 if (link && (s.sqe->flags & IOSQE_IO_DRAIN)) {
2754 if (!shadow_req) {
2755 shadow_req = io_get_req(ctx, NULL);
2756 if (unlikely(!shadow_req))
2757 goto out;
2758 shadow_req->flags |= (REQ_F_IO_DRAIN | REQ_F_SHADOW_DRAIN);
2759 refcount_dec(&shadow_req->refs);
2760 }
2761 shadow_req->sequence = s.sequence;
2762 }
2763
2764out:
2765 if (unlikely(mm_fault)) {
2766 io_cqring_add_event(ctx, s.sqe->user_data,
2767 -EFAULT);
2768 } else {
2769 s.has_user = has_user;
2770 s.needs_lock = true;
2771 s.needs_fixed_file = true;
2772 io_submit_sqe(ctx, &s, statep, &link);
2773 submitted++;
2774 }
2775 }
2776
2777 if (link)
2778 io_queue_link_head(ctx, link, &link->submit, shadow_req);
2779 if (statep)
2780 io_submit_state_end(&state);
2781
2782 return submitted;
2783}
2784
2785static int io_sq_thread(void *data)
2786{
2787 struct io_ring_ctx *ctx = data;
2788 struct mm_struct *cur_mm = NULL;
2789 const struct cred *old_cred;
2790 mm_segment_t old_fs;
2791 DEFINE_WAIT(wait);
2792 unsigned inflight;
2793 unsigned long timeout;
2794
2795 complete(&ctx->sqo_thread_started);
2796
2797 old_fs = get_fs();
2798 set_fs(USER_DS);
2799 old_cred = override_creds(ctx->creds);
2800
2801 timeout = inflight = 0;
2802 while (!kthread_should_park()) {
2803 bool mm_fault = false;
2804 unsigned int to_submit;
2805
2806 if (inflight) {
2807 unsigned nr_events = 0;
2808
2809 if (ctx->flags & IORING_SETUP_IOPOLL) {
2810 /*
2811 * inflight is the count of the maximum possible
2812 * entries we submitted, but it can be smaller
2813 * if we dropped some of them. If we don't have
2814 * poll entries available, then we know that we
2815 * have nothing left to poll for. Reset the
2816 * inflight count to zero in that case.
2817 */
2818 mutex_lock(&ctx->uring_lock);
2819 if (!list_empty(&ctx->poll_list))
2820 io_iopoll_getevents(ctx, &nr_events, 0);
2821 else
2822 inflight = 0;
2823 mutex_unlock(&ctx->uring_lock);
2824 } else {
2825 /*
2826 * Normal IO, just pretend everything completed.
2827 * We don't have to poll completions for that.
2828 */
2829 nr_events = inflight;
2830 }
2831
2832 inflight -= nr_events;
2833 if (!inflight)
2834 timeout = jiffies + ctx->sq_thread_idle;
2835 }
2836
2837 to_submit = io_sqring_entries(ctx);
2838 if (!to_submit) {
2839 /*
2840 * Drop cur_mm before scheduling, we can't hold it for
2841 * long periods (or over schedule()). Do this before
2842 * adding ourselves to the waitqueue, as the unuse/drop
2843 * may sleep.
2844 */
2845 if (cur_mm) {
2846 unuse_mm(cur_mm);
2847 mmput(cur_mm);
2848 cur_mm = NULL;
2849 }
2850
2851 /*
2852 * We're polling. If we're within the defined idle
2853 * period, then let us spin without work before going
2854 * to sleep.
2855 */
2856 if (inflight || !time_after(jiffies, timeout)) {
2857 cond_resched();
2858 continue;
2859 }
2860
2861 prepare_to_wait(&ctx->sqo_wait, &wait,
2862 TASK_INTERRUPTIBLE);
2863
2864 /* Tell userspace we may need a wakeup call */
2865 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
2866 /* make sure to read SQ tail after writing flags */
2867 smp_mb();
2868
2869 to_submit = io_sqring_entries(ctx);
2870 if (!to_submit) {
2871 if (kthread_should_park()) {
2872 finish_wait(&ctx->sqo_wait, &wait);
2873 break;
2874 }
2875 if (signal_pending(current))
2876 flush_signals(current);
2877 schedule();
2878 finish_wait(&ctx->sqo_wait, &wait);
2879
2880 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
2881 continue;
2882 }
2883 finish_wait(&ctx->sqo_wait, &wait);
2884
2885 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
2886 }
2887
2888 /* Unless all new commands are FIXED regions, grab mm */
2889 if (!cur_mm) {
2890 mm_fault = !mmget_not_zero(ctx->sqo_mm);
2891 if (!mm_fault) {
2892 use_mm(ctx->sqo_mm);
2893 cur_mm = ctx->sqo_mm;
2894 }
2895 }
2896
2897 to_submit = min(to_submit, ctx->sq_entries);
2898 inflight += io_submit_sqes(ctx, to_submit, cur_mm != NULL,
2899 mm_fault);
2900
2901 /* Commit SQ ring head once we've consumed all SQEs */
2902 io_commit_sqring(ctx);
2903 }
2904
2905 set_fs(old_fs);
2906 if (cur_mm) {
2907 unuse_mm(cur_mm);
2908 mmput(cur_mm);
2909 }
2910 revert_creds(old_cred);
2911
2912 kthread_parkme();
2913
2914 return 0;
2915}
2916
2917static int io_ring_submit(struct io_ring_ctx *ctx, unsigned int to_submit)
2918{
2919 struct io_submit_state state, *statep = NULL;
2920 struct io_kiocb *link = NULL;
2921 struct io_kiocb *shadow_req = NULL;
2922 bool prev_was_link = false;
2923 int i, submit = 0;
2924
2925 if (to_submit > IO_PLUG_THRESHOLD) {
2926 io_submit_state_start(&state, ctx, to_submit);
2927 statep = &state;
2928 }
2929
2930 for (i = 0; i < to_submit; i++) {
2931 struct sqe_submit s;
2932
2933 if (!io_get_sqring(ctx, &s))
2934 break;
2935
2936 /*
2937 * If previous wasn't linked and we have a linked command,
2938 * that's the end of the chain. Submit the previous link.
2939 */
2940 if (!prev_was_link && link) {
2941 io_queue_link_head(ctx, link, &link->submit, shadow_req);
2942 link = NULL;
2943 shadow_req = NULL;
2944 }
2945 prev_was_link = (s.sqe->flags & IOSQE_IO_LINK) != 0;
2946
2947 if (link && (s.sqe->flags & IOSQE_IO_DRAIN)) {
2948 if (!shadow_req) {
2949 shadow_req = io_get_req(ctx, NULL);
2950 if (unlikely(!shadow_req))
2951 goto out;
2952 shadow_req->flags |= (REQ_F_IO_DRAIN | REQ_F_SHADOW_DRAIN);
2953 refcount_dec(&shadow_req->refs);
2954 }
2955 shadow_req->sequence = s.sequence;
2956 }
2957
2958out:
2959 s.has_user = true;
2960 s.needs_lock = false;
2961 s.needs_fixed_file = false;
2962 submit++;
2963 io_submit_sqe(ctx, &s, statep, &link);
2964 }
2965
2966 if (link)
2967 io_queue_link_head(ctx, link, &link->submit, shadow_req);
2968 if (statep)
2969 io_submit_state_end(statep);
2970
2971 io_commit_sqring(ctx);
2972
2973 return submit;
2974}
2975
2976struct io_wait_queue {
2977 struct wait_queue_entry wq;
2978 struct io_ring_ctx *ctx;
2979 unsigned to_wait;
2980 unsigned nr_timeouts;
2981};
2982
2983static inline bool io_should_wake(struct io_wait_queue *iowq)
2984{
2985 struct io_ring_ctx *ctx = iowq->ctx;
2986
2987 /*
2988 * Wake up if we have enough events, or if a timeout occured since we
2989 * started waiting. For timeouts, we always want to return to userspace,
2990 * regardless of event count.
2991 */
2992 return io_cqring_events(ctx->rings) >= iowq->to_wait ||
2993 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
2994}
2995
2996static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
2997 int wake_flags, void *key)
2998{
2999 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
3000 wq);
3001
3002 if (!io_should_wake(iowq))
3003 return -1;
3004
3005 return autoremove_wake_function(curr, mode, wake_flags, key);
3006}
3007
3008/*
3009 * Wait until events become available, if we don't already have some. The
3010 * application must reap them itself, as they reside on the shared cq ring.
3011 */
3012static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
3013 const sigset_t __user *sig, size_t sigsz)
3014{
3015 struct io_wait_queue iowq = {
3016 .wq = {
3017 .private = current,
3018 .func = io_wake_function,
3019 .entry = LIST_HEAD_INIT(iowq.wq.entry),
3020 },
3021 .ctx = ctx,
3022 .to_wait = min_events,
3023 };
3024 struct io_rings *rings = ctx->rings;
3025 int ret;
3026
3027 if (io_cqring_events(rings) >= min_events)
3028 return 0;
3029
3030 if (sig) {
3031#ifdef CONFIG_COMPAT
3032 if (in_compat_syscall())
3033 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
3034 sigsz);
3035 else
3036#endif
3037 ret = set_user_sigmask(sig, sigsz);
3038
3039 if (ret)
3040 return ret;
3041 }
3042
3043 ret = 0;
3044 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
3045 do {
3046 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
3047 TASK_INTERRUPTIBLE);
3048 if (io_should_wake(&iowq))
3049 break;
3050 schedule();
3051 if (signal_pending(current)) {
3052 ret = -ERESTARTSYS;
3053 break;
3054 }
3055 } while (1);
3056 finish_wait(&ctx->wait, &iowq.wq);
3057
3058 restore_saved_sigmask_unless(ret == -ERESTARTSYS);
3059 if (ret == -ERESTARTSYS)
3060 ret = -EINTR;
3061
3062 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
3063}
3064
3065static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
3066{
3067 int i;
3068
3069 for (i = 0; i < ctx->nr_user_files; i++)
3070 fput(ctx->user_files[i]);
3071}
3072
3073static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
3074{
3075 if (!ctx->user_files)
3076 return -ENXIO;
3077
3078 __io_sqe_files_unregister(ctx);
3079 kfree(ctx->user_files);
3080 ctx->user_files = NULL;
3081 ctx->nr_user_files = 0;
3082 return 0;
3083}
3084
3085static void io_sq_thread_stop(struct io_ring_ctx *ctx)
3086{
3087 if (ctx->sqo_thread) {
3088 wait_for_completion(&ctx->sqo_thread_started);
3089 /*
3090 * The park is a bit of a work-around, without it we get
3091 * warning spews on shutdown with SQPOLL set and affinity
3092 * set to a single CPU.
3093 */
3094 kthread_park(ctx->sqo_thread);
3095 kthread_stop(ctx->sqo_thread);
3096 ctx->sqo_thread = NULL;
3097 }
3098}
3099
3100static void io_finish_async(struct io_ring_ctx *ctx)
3101{
3102 int i;
3103
3104 io_sq_thread_stop(ctx);
3105
3106 for (i = 0; i < ARRAY_SIZE(ctx->sqo_wq); i++) {
3107 if (ctx->sqo_wq[i]) {
3108 destroy_workqueue(ctx->sqo_wq[i]);
3109 ctx->sqo_wq[i] = NULL;
3110 }
3111 }
3112}
3113
3114static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
3115 unsigned nr_args)
3116{
3117 __s32 __user *fds = (__s32 __user *) arg;
3118 int fd, ret = 0;
3119 unsigned i;
3120
3121 if (ctx->user_files)
3122 return -EBUSY;
3123 if (!nr_args)
3124 return -EINVAL;
3125 if (nr_args > IORING_MAX_FIXED_FILES)
3126 return -EMFILE;
3127
3128 ctx->user_files = kcalloc(nr_args, sizeof(struct file *), GFP_KERNEL);
3129 if (!ctx->user_files)
3130 return -ENOMEM;
3131
3132 for (i = 0; i < nr_args; i++) {
3133 ret = -EFAULT;
3134 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
3135 break;
3136
3137 ctx->user_files[i] = fget(fd);
3138
3139 ret = -EBADF;
3140 if (!ctx->user_files[i])
3141 break;
3142 /*
3143 * Don't allow io_uring instances to be registered. If UNIX
3144 * isn't enabled, then this causes a reference cycle and this
3145 * instance can never get freed. If UNIX is enabled we'll
3146 * handle it just fine, but there's still no point in allowing
3147 * a ring fd as it doesn't support regular read/write anyway.
3148 */
3149 if (ctx->user_files[i]->f_op == &io_uring_fops) {
3150 fput(ctx->user_files[i]);
3151 break;
3152 }
3153 ctx->nr_user_files++;
3154 ret = 0;
3155 }
3156
3157 if (ret) {
3158 for (i = 0; i < ctx->nr_user_files; i++)
3159 fput(ctx->user_files[i]);
3160
3161 kfree(ctx->user_files);
3162 ctx->user_files = NULL;
3163 ctx->nr_user_files = 0;
3164 return ret;
3165 }
3166
3167 return 0;
3168}
3169
3170static int io_sq_offload_start(struct io_ring_ctx *ctx,
3171 struct io_uring_params *p)
3172{
3173 int ret;
3174
3175 mmgrab(current->mm);
3176 ctx->sqo_mm = current->mm;
3177
3178 if (ctx->flags & IORING_SETUP_SQPOLL) {
3179 ret = -EPERM;
3180 if (!capable(CAP_SYS_ADMIN))
3181 goto err;
3182
3183 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
3184 if (!ctx->sq_thread_idle)
3185 ctx->sq_thread_idle = HZ;
3186
3187 if (p->flags & IORING_SETUP_SQ_AFF) {
3188 int cpu = p->sq_thread_cpu;
3189
3190 ret = -EINVAL;
3191 if (cpu >= nr_cpu_ids)
3192 goto err;
3193 if (!cpu_online(cpu))
3194 goto err;
3195
3196 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
3197 ctx, cpu,
3198 "io_uring-sq");
3199 } else {
3200 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
3201 "io_uring-sq");
3202 }
3203 if (IS_ERR(ctx->sqo_thread)) {
3204 ret = PTR_ERR(ctx->sqo_thread);
3205 ctx->sqo_thread = NULL;
3206 goto err;
3207 }
3208 wake_up_process(ctx->sqo_thread);
3209 } else if (p->flags & IORING_SETUP_SQ_AFF) {
3210 /* Can't have SQ_AFF without SQPOLL */
3211 ret = -EINVAL;
3212 goto err;
3213 }
3214
3215 /* Do QD, or 2 * CPUS, whatever is smallest */
3216 ctx->sqo_wq[0] = alloc_workqueue("io_ring-wq",
3217 WQ_UNBOUND | WQ_FREEZABLE,
3218 min(ctx->sq_entries - 1, 2 * num_online_cpus()));
3219 if (!ctx->sqo_wq[0]) {
3220 ret = -ENOMEM;
3221 goto err;
3222 }
3223
3224 /*
3225 * This is for buffered writes, where we want to limit the parallelism
3226 * due to file locking in file systems. As "normal" buffered writes
3227 * should parellelize on writeout quite nicely, limit us to having 2
3228 * pending. This avoids massive contention on the inode when doing
3229 * buffered async writes.
3230 */
3231 ctx->sqo_wq[1] = alloc_workqueue("io_ring-write-wq",
3232 WQ_UNBOUND | WQ_FREEZABLE, 2);
3233 if (!ctx->sqo_wq[1]) {
3234 ret = -ENOMEM;
3235 goto err;
3236 }
3237
3238 return 0;
3239err:
3240 io_finish_async(ctx);
3241 mmdrop(ctx->sqo_mm);
3242 ctx->sqo_mm = NULL;
3243 return ret;
3244}
3245
3246static void io_unaccount_mem(struct user_struct *user, unsigned long nr_pages)
3247{
3248 atomic_long_sub(nr_pages, &user->locked_vm);
3249}
3250
3251static int io_account_mem(struct user_struct *user, unsigned long nr_pages)
3252{
3253 unsigned long page_limit, cur_pages, new_pages;
3254
3255 /* Don't allow more pages than we can safely lock */
3256 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
3257
3258 do {
3259 cur_pages = atomic_long_read(&user->locked_vm);
3260 new_pages = cur_pages + nr_pages;
3261 if (new_pages > page_limit)
3262 return -ENOMEM;
3263 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
3264 new_pages) != cur_pages);
3265
3266 return 0;
3267}
3268
3269static void io_mem_free(void *ptr)
3270{
3271 struct page *page;
3272
3273 if (!ptr)
3274 return;
3275
3276 page = virt_to_head_page(ptr);
3277 if (put_page_testzero(page))
3278 free_compound_page(page);
3279}
3280
3281static void *io_mem_alloc(size_t size)
3282{
3283 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
3284 __GFP_NORETRY;
3285
3286 return (void *) __get_free_pages(gfp_flags, get_order(size));
3287}
3288
3289static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
3290 size_t *sq_offset)
3291{
3292 struct io_rings *rings;
3293 size_t off, sq_array_size;
3294
3295 off = struct_size(rings, cqes, cq_entries);
3296 if (off == SIZE_MAX)
3297 return SIZE_MAX;
3298
3299#ifdef CONFIG_SMP
3300 off = ALIGN(off, SMP_CACHE_BYTES);
3301 if (off == 0)
3302 return SIZE_MAX;
3303#endif
3304
3305 if (sq_offset)
3306 *sq_offset = off;
3307
3308 sq_array_size = array_size(sizeof(u32), sq_entries);
3309 if (sq_array_size == SIZE_MAX)
3310 return SIZE_MAX;
3311
3312 if (check_add_overflow(off, sq_array_size, &off))
3313 return SIZE_MAX;
3314
3315 return off;
3316}
3317
3318static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
3319{
3320 size_t pages;
3321
3322 pages = (size_t)1 << get_order(
3323 rings_size(sq_entries, cq_entries, NULL));
3324 pages += (size_t)1 << get_order(
3325 array_size(sizeof(struct io_uring_sqe), sq_entries));
3326
3327 return pages;
3328}
3329
3330static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
3331{
3332 int i, j;
3333
3334 if (!ctx->user_bufs)
3335 return -ENXIO;
3336
3337 for (i = 0; i < ctx->nr_user_bufs; i++) {
3338 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
3339
3340 for (j = 0; j < imu->nr_bvecs; j++)
3341 put_user_page(imu->bvec[j].bv_page);
3342
3343 if (ctx->account_mem)
3344 io_unaccount_mem(ctx->user, imu->nr_bvecs);
3345 kvfree(imu->bvec);
3346 imu->nr_bvecs = 0;
3347 }
3348
3349 kfree(ctx->user_bufs);
3350 ctx->user_bufs = NULL;
3351 ctx->nr_user_bufs = 0;
3352 return 0;
3353}
3354
3355static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
3356 void __user *arg, unsigned index)
3357{
3358 struct iovec __user *src;
3359
3360#ifdef CONFIG_COMPAT
3361 if (ctx->compat) {
3362 struct compat_iovec __user *ciovs;
3363 struct compat_iovec ciov;
3364
3365 ciovs = (struct compat_iovec __user *) arg;
3366 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
3367 return -EFAULT;
3368
3369 dst->iov_base = (void __user *) (unsigned long) ciov.iov_base;
3370 dst->iov_len = ciov.iov_len;
3371 return 0;
3372 }
3373#endif
3374 src = (struct iovec __user *) arg;
3375 if (copy_from_user(dst, &src[index], sizeof(*dst)))
3376 return -EFAULT;
3377 return 0;
3378}
3379
3380static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
3381 unsigned nr_args)
3382{
3383 struct vm_area_struct **vmas = NULL;
3384 struct page **pages = NULL;
3385 int i, j, got_pages = 0;
3386 int ret = -EINVAL;
3387
3388 if (ctx->user_bufs)
3389 return -EBUSY;
3390 if (!nr_args || nr_args > UIO_MAXIOV)
3391 return -EINVAL;
3392
3393 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
3394 GFP_KERNEL);
3395 if (!ctx->user_bufs)
3396 return -ENOMEM;
3397
3398 for (i = 0; i < nr_args; i++) {
3399 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
3400 unsigned long off, start, end, ubuf;
3401 int pret, nr_pages;
3402 struct iovec iov;
3403 size_t size;
3404
3405 ret = io_copy_iov(ctx, &iov, arg, i);
3406 if (ret)
3407 goto err;
3408
3409 /*
3410 * Don't impose further limits on the size and buffer
3411 * constraints here, we'll -EINVAL later when IO is
3412 * submitted if they are wrong.
3413 */
3414 ret = -EFAULT;
3415 if (!iov.iov_base || !iov.iov_len)
3416 goto err;
3417
3418 /* arbitrary limit, but we need something */
3419 if (iov.iov_len > SZ_1G)
3420 goto err;
3421
3422 ubuf = (unsigned long) iov.iov_base;
3423 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
3424 start = ubuf >> PAGE_SHIFT;
3425 nr_pages = end - start;
3426
3427 if (ctx->account_mem) {
3428 ret = io_account_mem(ctx->user, nr_pages);
3429 if (ret)
3430 goto err;
3431 }
3432
3433 ret = 0;
3434 if (!pages || nr_pages > got_pages) {
3435 kvfree(vmas);
3436 kvfree(pages);
3437 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
3438 GFP_KERNEL);
3439 vmas = kvmalloc_array(nr_pages,
3440 sizeof(struct vm_area_struct *),
3441 GFP_KERNEL);
3442 if (!pages || !vmas) {
3443 ret = -ENOMEM;
3444 if (ctx->account_mem)
3445 io_unaccount_mem(ctx->user, nr_pages);
3446 goto err;
3447 }
3448 got_pages = nr_pages;
3449 }
3450
3451 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
3452 GFP_KERNEL);
3453 ret = -ENOMEM;
3454 if (!imu->bvec) {
3455 if (ctx->account_mem)
3456 io_unaccount_mem(ctx->user, nr_pages);
3457 goto err;
3458 }
3459
3460 ret = 0;
3461 down_read(&current->mm->mmap_sem);
3462 pret = get_user_pages(ubuf, nr_pages,
3463 FOLL_WRITE | FOLL_LONGTERM,
3464 pages, vmas);
3465 if (pret == nr_pages) {
3466 /* don't support file backed memory */
3467 for (j = 0; j < nr_pages; j++) {
3468 struct vm_area_struct *vma = vmas[j];
3469
3470 if (vma->vm_file &&
3471 !is_file_hugepages(vma->vm_file)) {
3472 ret = -EOPNOTSUPP;
3473 break;
3474 }
3475 }
3476 } else {
3477 ret = pret < 0 ? pret : -EFAULT;
3478 }
3479 up_read(&current->mm->mmap_sem);
3480 if (ret) {
3481 /*
3482 * if we did partial map, or found file backed vmas,
3483 * release any pages we did get
3484 */
3485 if (pret > 0)
3486 put_user_pages(pages, pret);
3487 if (ctx->account_mem)
3488 io_unaccount_mem(ctx->user, nr_pages);
3489 kvfree(imu->bvec);
3490 goto err;
3491 }
3492
3493 off = ubuf & ~PAGE_MASK;
3494 size = iov.iov_len;
3495 for (j = 0; j < nr_pages; j++) {
3496 size_t vec_len;
3497
3498 vec_len = min_t(size_t, size, PAGE_SIZE - off);
3499 imu->bvec[j].bv_page = pages[j];
3500 imu->bvec[j].bv_len = vec_len;
3501 imu->bvec[j].bv_offset = off;
3502 off = 0;
3503 size -= vec_len;
3504 }
3505 /* store original address for later verification */
3506 imu->ubuf = ubuf;
3507 imu->len = iov.iov_len;
3508 imu->nr_bvecs = nr_pages;
3509
3510 ctx->nr_user_bufs++;
3511 }
3512 kvfree(pages);
3513 kvfree(vmas);
3514 return 0;
3515err:
3516 kvfree(pages);
3517 kvfree(vmas);
3518 io_sqe_buffer_unregister(ctx);
3519 return ret;
3520}
3521
3522static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
3523{
3524 __s32 __user *fds = arg;
3525 int fd;
3526
3527 if (ctx->cq_ev_fd)
3528 return -EBUSY;
3529
3530 if (copy_from_user(&fd, fds, sizeof(*fds)))
3531 return -EFAULT;
3532
3533 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
3534 if (IS_ERR(ctx->cq_ev_fd)) {
3535 int ret = PTR_ERR(ctx->cq_ev_fd);
3536 ctx->cq_ev_fd = NULL;
3537 return ret;
3538 }
3539
3540 return 0;
3541}
3542
3543static int io_eventfd_unregister(struct io_ring_ctx *ctx)
3544{
3545 if (ctx->cq_ev_fd) {
3546 eventfd_ctx_put(ctx->cq_ev_fd);
3547 ctx->cq_ev_fd = NULL;
3548 return 0;
3549 }
3550
3551 return -ENXIO;
3552}
3553
3554static void io_ring_ctx_free(struct io_ring_ctx *ctx)
3555{
3556 io_finish_async(ctx);
3557 if (ctx->sqo_mm)
3558 mmdrop(ctx->sqo_mm);
3559
3560 io_iopoll_reap_events(ctx);
3561 io_sqe_buffer_unregister(ctx);
3562 io_sqe_files_unregister(ctx);
3563 io_eventfd_unregister(ctx);
3564
3565 io_mem_free(ctx->rings);
3566 io_mem_free(ctx->sq_sqes);
3567
3568 percpu_ref_exit(&ctx->refs);
3569 if (ctx->account_mem)
3570 io_unaccount_mem(ctx->user,
3571 ring_pages(ctx->sq_entries, ctx->cq_entries));
3572 free_uid(ctx->user);
3573 if (ctx->creds)
3574 put_cred(ctx->creds);
3575 kfree(ctx);
3576}
3577
3578static __poll_t io_uring_poll(struct file *file, poll_table *wait)
3579{
3580 struct io_ring_ctx *ctx = file->private_data;
3581 __poll_t mask = 0;
3582
3583 poll_wait(file, &ctx->cq_wait, wait);
3584 /*
3585 * synchronizes with barrier from wq_has_sleeper call in
3586 * io_commit_cqring
3587 */
3588 smp_rmb();
3589 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
3590 ctx->rings->sq_ring_entries)
3591 mask |= EPOLLOUT | EPOLLWRNORM;
3592 if (READ_ONCE(ctx->rings->cq.head) != ctx->cached_cq_tail)
3593 mask |= EPOLLIN | EPOLLRDNORM;
3594
3595 return mask;
3596}
3597
3598static int io_uring_fasync(int fd, struct file *file, int on)
3599{
3600 struct io_ring_ctx *ctx = file->private_data;
3601
3602 return fasync_helper(fd, file, on, &ctx->cq_fasync);
3603}
3604
3605static void io_cancel_async_work(struct io_ring_ctx *ctx,
3606 struct files_struct *files)
3607{
3608 struct io_kiocb *req;
3609
3610 spin_lock_irq(&ctx->task_lock);
3611
3612 list_for_each_entry(req, &ctx->task_list, task_list) {
3613 if (files && req->files != files)
3614 continue;
3615
3616 /*
3617 * The below executes an smp_mb(), which matches with the
3618 * smp_mb() (A) in io_sq_wq_submit_work() such that either
3619 * we store REQ_F_CANCEL flag to req->flags or we see the
3620 * req->work_task setted in io_sq_wq_submit_work().
3621 */
3622 smp_store_mb(req->flags, req->flags | REQ_F_CANCEL); /* B */
3623
3624 if (req->work_task)
3625 send_sig(SIGINT, req->work_task, 1);
3626 }
3627 spin_unlock_irq(&ctx->task_lock);
3628}
3629
3630static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
3631{
3632 mutex_lock(&ctx->uring_lock);
3633 percpu_ref_kill(&ctx->refs);
3634 mutex_unlock(&ctx->uring_lock);
3635
3636 io_cancel_async_work(ctx, NULL);
3637 io_kill_timeouts(ctx);
3638 io_poll_remove_all(ctx);
3639 io_iopoll_reap_events(ctx);
3640 wait_for_completion(&ctx->ctx_done);
3641 io_ring_ctx_free(ctx);
3642}
3643
3644static int io_uring_flush(struct file *file, void *data)
3645{
3646 struct io_ring_ctx *ctx = file->private_data;
3647
3648 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
3649 io_cancel_async_work(ctx, data);
3650
3651 return 0;
3652}
3653
3654static int io_uring_release(struct inode *inode, struct file *file)
3655{
3656 struct io_ring_ctx *ctx = file->private_data;
3657
3658 file->private_data = NULL;
3659 io_ring_ctx_wait_and_kill(ctx);
3660 return 0;
3661}
3662
3663static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
3664{
3665 loff_t offset = (loff_t) vma->vm_pgoff << PAGE_SHIFT;
3666 unsigned long sz = vma->vm_end - vma->vm_start;
3667 struct io_ring_ctx *ctx = file->private_data;
3668 unsigned long pfn;
3669 struct page *page;
3670 void *ptr;
3671
3672 switch (offset) {
3673 case IORING_OFF_SQ_RING:
3674 case IORING_OFF_CQ_RING:
3675 ptr = ctx->rings;
3676 break;
3677 case IORING_OFF_SQES:
3678 ptr = ctx->sq_sqes;
3679 break;
3680 default:
3681 return -EINVAL;
3682 }
3683
3684 page = virt_to_head_page(ptr);
3685 if (sz > page_size(page))
3686 return -EINVAL;
3687
3688 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
3689 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
3690}
3691
3692SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
3693 u32, min_complete, u32, flags, const sigset_t __user *, sig,
3694 size_t, sigsz)
3695{
3696 struct io_ring_ctx *ctx;
3697 long ret = -EBADF;
3698 int submitted = 0;
3699 struct fd f;
3700
3701 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
3702 return -EINVAL;
3703
3704 f = fdget(fd);
3705 if (!f.file)
3706 return -EBADF;
3707
3708 ret = -EOPNOTSUPP;
3709 if (f.file->f_op != &io_uring_fops)
3710 goto out_fput;
3711
3712 ret = -ENXIO;
3713 ctx = f.file->private_data;
3714 if (!percpu_ref_tryget(&ctx->refs))
3715 goto out_fput;
3716
3717 /*
3718 * For SQ polling, the thread will do all submissions and completions.
3719 * Just return the requested submit count, and wake the thread if
3720 * we were asked to.
3721 */
3722 ret = 0;
3723 if (ctx->flags & IORING_SETUP_SQPOLL) {
3724 if (flags & IORING_ENTER_SQ_WAKEUP)
3725 wake_up(&ctx->sqo_wait);
3726 submitted = to_submit;
3727 } else if (to_submit) {
3728 to_submit = min(to_submit, ctx->sq_entries);
3729
3730 mutex_lock(&ctx->uring_lock);
3731 submitted = io_ring_submit(ctx, to_submit);
3732 mutex_unlock(&ctx->uring_lock);
3733
3734 if (submitted != to_submit)
3735 goto out;
3736 }
3737 if (flags & IORING_ENTER_GETEVENTS) {
3738 unsigned nr_events = 0;
3739
3740 min_complete = min(min_complete, ctx->cq_entries);
3741
3742 if (ctx->flags & IORING_SETUP_IOPOLL) {
3743 ret = io_iopoll_check(ctx, &nr_events, min_complete);
3744 } else {
3745 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
3746 }
3747 }
3748
3749out:
3750 percpu_ref_put(&ctx->refs);
3751out_fput:
3752 fdput(f);
3753 return submitted ? submitted : ret;
3754}
3755
3756static const struct file_operations io_uring_fops = {
3757 .release = io_uring_release,
3758 .flush = io_uring_flush,
3759 .mmap = io_uring_mmap,
3760 .poll = io_uring_poll,
3761 .fasync = io_uring_fasync,
3762};
3763
3764bool io_is_uring_fops(struct file *file)
3765{
3766 return file->f_op == &io_uring_fops;
3767}
3768
3769static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
3770 struct io_uring_params *p)
3771{
3772 struct io_rings *rings;
3773 size_t size, sq_array_offset;
3774
3775 /* make sure these are sane, as we already accounted them */
3776 ctx->sq_entries = p->sq_entries;
3777 ctx->cq_entries = p->cq_entries;
3778
3779 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
3780 if (size == SIZE_MAX)
3781 return -EOVERFLOW;
3782
3783 rings = io_mem_alloc(size);
3784 if (!rings)
3785 return -ENOMEM;
3786
3787 ctx->rings = rings;
3788 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
3789 rings->sq_ring_mask = p->sq_entries - 1;
3790 rings->cq_ring_mask = p->cq_entries - 1;
3791 rings->sq_ring_entries = p->sq_entries;
3792 rings->cq_ring_entries = p->cq_entries;
3793 ctx->sq_mask = rings->sq_ring_mask;
3794 ctx->cq_mask = rings->cq_ring_mask;
3795
3796 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
3797 if (size == SIZE_MAX) {
3798 io_mem_free(ctx->rings);
3799 ctx->rings = NULL;
3800 return -EOVERFLOW;
3801 }
3802
3803 ctx->sq_sqes = io_mem_alloc(size);
3804 if (!ctx->sq_sqes) {
3805 io_mem_free(ctx->rings);
3806 ctx->rings = NULL;
3807 return -ENOMEM;
3808 }
3809
3810 return 0;
3811}
3812
3813/*
3814 * Allocate an anonymous fd, this is what constitutes the application
3815 * visible backing of an io_uring instance. The application mmaps this
3816 * fd to gain access to the SQ/CQ ring details.
3817 */
3818static int io_uring_get_fd(struct io_ring_ctx *ctx)
3819{
3820 struct file *file;
3821 int ret;
3822
3823 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
3824 if (ret < 0)
3825 return ret;
3826
3827 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
3828 O_RDWR | O_CLOEXEC);
3829 if (IS_ERR(file)) {
3830 put_unused_fd(ret);
3831 return PTR_ERR(file);
3832 }
3833
3834 fd_install(ret, file);
3835 return ret;
3836}
3837
3838static int io_uring_create(unsigned entries, struct io_uring_params *p)
3839{
3840 struct user_struct *user = NULL;
3841 struct io_ring_ctx *ctx;
3842 bool account_mem;
3843 int ret;
3844
3845 if (!entries || entries > IORING_MAX_ENTRIES)
3846 return -EINVAL;
3847
3848 /*
3849 * Use twice as many entries for the CQ ring. It's possible for the
3850 * application to drive a higher depth than the size of the SQ ring,
3851 * since the sqes are only used at submission time. This allows for
3852 * some flexibility in overcommitting a bit.
3853 */
3854 p->sq_entries = roundup_pow_of_two(entries);
3855 p->cq_entries = 2 * p->sq_entries;
3856
3857 user = get_uid(current_user());
3858 account_mem = !capable(CAP_IPC_LOCK);
3859
3860 if (account_mem) {
3861 ret = io_account_mem(user,
3862 ring_pages(p->sq_entries, p->cq_entries));
3863 if (ret) {
3864 free_uid(user);
3865 return ret;
3866 }
3867 }
3868
3869 ctx = io_ring_ctx_alloc(p);
3870 if (!ctx) {
3871 if (account_mem)
3872 io_unaccount_mem(user, ring_pages(p->sq_entries,
3873 p->cq_entries));
3874 free_uid(user);
3875 return -ENOMEM;
3876 }
3877 ctx->compat = in_compat_syscall();
3878 ctx->account_mem = account_mem;
3879 ctx->user = user;
3880
3881 ctx->creds = get_current_cred();
3882 if (!ctx->creds) {
3883 ret = -ENOMEM;
3884 goto err;
3885 }
3886
3887 ret = io_allocate_scq_urings(ctx, p);
3888 if (ret)
3889 goto err;
3890
3891 ret = io_sq_offload_start(ctx, p);
3892 if (ret)
3893 goto err;
3894
3895 memset(&p->sq_off, 0, sizeof(p->sq_off));
3896 p->sq_off.head = offsetof(struct io_rings, sq.head);
3897 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
3898 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
3899 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
3900 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
3901 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
3902 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
3903
3904 memset(&p->cq_off, 0, sizeof(p->cq_off));
3905 p->cq_off.head = offsetof(struct io_rings, cq.head);
3906 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
3907 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
3908 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
3909 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
3910 p->cq_off.cqes = offsetof(struct io_rings, cqes);
3911
3912 /*
3913 * Install ring fd as the very last thing, so we don't risk someone
3914 * having closed it before we finish setup
3915 */
3916 ret = io_uring_get_fd(ctx);
3917 if (ret < 0)
3918 goto err;
3919
3920 p->features = IORING_FEAT_SINGLE_MMAP;
3921 return ret;
3922err:
3923 io_ring_ctx_wait_and_kill(ctx);
3924 return ret;
3925}
3926
3927/*
3928 * Sets up an aio uring context, and returns the fd. Applications asks for a
3929 * ring size, we return the actual sq/cq ring sizes (among other things) in the
3930 * params structure passed in.
3931 */
3932static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
3933{
3934 struct io_uring_params p;
3935 long ret;
3936 int i;
3937
3938 if (copy_from_user(&p, params, sizeof(p)))
3939 return -EFAULT;
3940 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
3941 if (p.resv[i])
3942 return -EINVAL;
3943 }
3944
3945 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
3946 IORING_SETUP_SQ_AFF))
3947 return -EINVAL;
3948
3949 ret = io_uring_create(entries, &p);
3950 if (ret < 0)
3951 return ret;
3952
3953 if (copy_to_user(params, &p, sizeof(p)))
3954 return -EFAULT;
3955
3956 return ret;
3957}
3958
3959SYSCALL_DEFINE2(io_uring_setup, u32, entries,
3960 struct io_uring_params __user *, params)
3961{
3962 return io_uring_setup(entries, params);
3963}
3964
3965static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
3966 void __user *arg, unsigned nr_args)
3967 __releases(ctx->uring_lock)
3968 __acquires(ctx->uring_lock)
3969{
3970 int ret;
3971
3972 /*
3973 * We're inside the ring mutex, if the ref is already dying, then
3974 * someone else killed the ctx or is already going through
3975 * io_uring_register().
3976 */
3977 if (percpu_ref_is_dying(&ctx->refs))
3978 return -ENXIO;
3979
3980 percpu_ref_kill(&ctx->refs);
3981
3982 /*
3983 * Drop uring mutex before waiting for references to exit. If another
3984 * thread is currently inside io_uring_enter() it might need to grab
3985 * the uring_lock to make progress. If we hold it here across the drain
3986 * wait, then we can deadlock. It's safe to drop the mutex here, since
3987 * no new references will come in after we've killed the percpu ref.
3988 */
3989 mutex_unlock(&ctx->uring_lock);
3990 wait_for_completion(&ctx->ctx_done);
3991 mutex_lock(&ctx->uring_lock);
3992
3993 switch (opcode) {
3994 case IORING_REGISTER_BUFFERS:
3995 ret = io_sqe_buffer_register(ctx, arg, nr_args);
3996 break;
3997 case IORING_UNREGISTER_BUFFERS:
3998 ret = -EINVAL;
3999 if (arg || nr_args)
4000 break;
4001 ret = io_sqe_buffer_unregister(ctx);
4002 break;
4003 case IORING_REGISTER_FILES:
4004 ret = io_sqe_files_register(ctx, arg, nr_args);
4005 break;
4006 case IORING_UNREGISTER_FILES:
4007 ret = -EINVAL;
4008 if (arg || nr_args)
4009 break;
4010 ret = io_sqe_files_unregister(ctx);
4011 break;
4012 case IORING_REGISTER_EVENTFD:
4013 ret = -EINVAL;
4014 if (nr_args != 1)
4015 break;
4016 ret = io_eventfd_register(ctx, arg);
4017 break;
4018 case IORING_UNREGISTER_EVENTFD:
4019 ret = -EINVAL;
4020 if (arg || nr_args)
4021 break;
4022 ret = io_eventfd_unregister(ctx);
4023 break;
4024 default:
4025 ret = -EINVAL;
4026 break;
4027 }
4028
4029 /* bring the ctx back to life */
4030 reinit_completion(&ctx->ctx_done);
4031 percpu_ref_reinit(&ctx->refs);
4032 return ret;
4033}
4034
4035SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
4036 void __user *, arg, unsigned int, nr_args)
4037{
4038 struct io_ring_ctx *ctx;
4039 long ret = -EBADF;
4040 struct fd f;
4041
4042 f = fdget(fd);
4043 if (!f.file)
4044 return -EBADF;
4045
4046 ret = -EOPNOTSUPP;
4047 if (f.file->f_op != &io_uring_fops)
4048 goto out_fput;
4049
4050 ctx = f.file->private_data;
4051
4052 mutex_lock(&ctx->uring_lock);
4053 ret = __io_uring_register(ctx, opcode, arg, nr_args);
4054 mutex_unlock(&ctx->uring_lock);
4055out_fput:
4056 fdput(f);
4057 return ret;
4058}
4059
4060static int __init io_uring_init(void)
4061{
4062 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
4063 return 0;
4064};
4065__initcall(io_uring_init);