1 // 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_cqe (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 <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
51
52 #include <linux/sched/signal.h>
53 #include <linux/fs.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
56 #include <linux/mm.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/blk-mq.h>
61 #include <linux/bvec.h>
62 #include <linux/net.h>
63 #include <net/sock.h>
64 #include <net/af_unix.h>
65 #include <net/scm.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/namei.h>
74 #include <linux/fsnotify.h>
75 #include <linux/fadvise.h>
76 #include <linux/eventpoll.h>
77 #include <linux/splice.h>
78 #include <linux/task_work.h>
79 #include <linux/pagemap.h>
80 #include <linux/io_uring.h>
81 #include <linux/audit.h>
82 #include <linux/security.h>
83 #include <linux/xattr.h>
84
85 #define CREATE_TRACE_POINTS
86 #include <trace/events/io_uring.h>
87
88 #include <uapi/linux/io_uring.h>
89
90 #include "../fs/internal.h"
91 #include "io-wq.h"
92
93 #define IORING_MAX_ENTRIES 32768
94 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
95 #define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
96
97 /* only define max */
98 #define IORING_MAX_FIXED_FILES (1U << 20)
99 #define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
100 IORING_REGISTER_LAST + IORING_OP_LAST)
101
102 #define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
103 #define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
104 #define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
105
106 #define IORING_MAX_REG_BUFFERS (1U << 14)
107
108 #define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
109 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
110
111 #define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
112 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
113
114 #define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
115 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
116 REQ_F_ASYNC_DATA)
117
118 #define IO_REQ_CLEAN_SLOW_FLAGS (REQ_F_REFCOUNT | REQ_F_LINK | REQ_F_HARDLINK |\
119 IO_REQ_CLEAN_FLAGS)
120
121 #define IO_APOLL_MULTI_POLLED (REQ_F_APOLL_MULTISHOT | REQ_F_POLLED)
122
123 #define IO_TCTX_REFS_CACHE_NR (1U << 10)
124
125 struct io_uring {
126 u32 head ____cacheline_aligned_in_smp;
127 u32 tail ____cacheline_aligned_in_smp;
128 };
129
130 /*
131 * This data is shared with the application through the mmap at offsets
132 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
133 *
134 * The offsets to the member fields are published through struct
135 * io_sqring_offsets when calling io_uring_setup.
136 */
137 struct io_rings {
138 /*
139 * Head and tail offsets into the ring; the offsets need to be
140 * masked to get valid indices.
141 *
142 * The kernel controls head of the sq ring and the tail of the cq ring,
143 * and the application controls tail of the sq ring and the head of the
144 * cq ring.
145 */
146 struct io_uring sq, cq;
147 /*
148 * Bitmasks to apply to head and tail offsets (constant, equals
149 * ring_entries - 1)
150 */
151 u32 sq_ring_mask, cq_ring_mask;
152 /* Ring sizes (constant, power of 2) */
153 u32 sq_ring_entries, cq_ring_entries;
154 /*
155 * Number of invalid entries dropped by the kernel due to
156 * invalid index stored in array
157 *
158 * Written by the kernel, shouldn't be modified by the
159 * application (i.e. get number of "new events" by comparing to
160 * cached value).
161 *
162 * After a new SQ head value was read by the application this
163 * counter includes all submissions that were dropped reaching
164 * the new SQ head (and possibly more).
165 */
166 u32 sq_dropped;
167 /*
168 * Runtime SQ flags
169 *
170 * Written by the kernel, shouldn't be modified by the
171 * application.
172 *
173 * The application needs a full memory barrier before checking
174 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
175 */
176 atomic_t sq_flags;
177 /*
178 * Runtime CQ flags
179 *
180 * Written by the application, shouldn't be modified by the
181 * kernel.
182 */
183 u32 cq_flags;
184 /*
185 * Number of completion events lost because the queue was full;
186 * this should be avoided by the application by making sure
187 * there are not more requests pending than there is space in
188 * the completion queue.
189 *
190 * Written by the kernel, shouldn't be modified by the
191 * application (i.e. get number of "new events" by comparing to
192 * cached value).
193 *
194 * As completion events come in out of order this counter is not
195 * ordered with any other data.
196 */
197 u32 cq_overflow;
198 /*
199 * Ring buffer of completion events.
200 *
201 * The kernel writes completion events fresh every time they are
202 * produced, so the application is allowed to modify pending
203 * entries.
204 */
205 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
206 };
207
208 struct io_mapped_ubuf {
209 u64 ubuf;
210 u64 ubuf_end;
211 unsigned int nr_bvecs;
212 unsigned long acct_pages;
213 struct bio_vec bvec[];
214 };
215
216 struct io_ring_ctx;
217
218 struct io_overflow_cqe {
219 struct list_head list;
220 struct io_uring_cqe cqe;
221 };
222
223 /*
224 * FFS_SCM is only available on 64-bit archs, for 32-bit we just define it as 0
225 * and define IO_URING_SCM_ALL. For this case, we use SCM for all files as we
226 * can't safely always dereference the file when the task has exited and ring
227 * cleanup is done. If a file is tracked and part of SCM, then unix gc on
228 * process exit may reap it before __io_sqe_files_unregister() is run.
229 */
230 #define FFS_NOWAIT 0x1UL
231 #define FFS_ISREG 0x2UL
232 #if defined(CONFIG_64BIT)
233 #define FFS_SCM 0x4UL
234 #else
235 #define IO_URING_SCM_ALL
236 #define FFS_SCM 0x0UL
237 #endif
238 #define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG|FFS_SCM)
239
240 struct io_fixed_file {
241 /* file * with additional FFS_* flags */
242 unsigned long file_ptr;
243 };
244
245 struct io_rsrc_put {
246 struct list_head list;
247 u64 tag;
248 union {
249 void *rsrc;
250 struct file *file;
251 struct io_mapped_ubuf *buf;
252 };
253 };
254
255 struct io_file_table {
256 struct io_fixed_file *files;
257 unsigned long *bitmap;
258 unsigned int alloc_hint;
259 };
260
261 struct io_rsrc_node {
262 struct percpu_ref refs;
263 struct list_head node;
264 struct list_head rsrc_list;
265 struct io_rsrc_data *rsrc_data;
266 struct llist_node llist;
267 bool done;
268 };
269
270 typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
271
272 struct io_rsrc_data {
273 struct io_ring_ctx *ctx;
274
275 u64 **tags;
276 unsigned int nr;
277 rsrc_put_fn *do_put;
278 atomic_t refs;
279 struct completion done;
280 bool quiesce;
281 };
282
283 #define IO_BUFFER_LIST_BUF_PER_PAGE (PAGE_SIZE / sizeof(struct io_uring_buf))
284 struct io_buffer_list {
285 /*
286 * If ->buf_nr_pages is set, then buf_pages/buf_ring are used. If not,
287 * then these are classic provided buffers and ->buf_list is used.
288 */
289 union {
290 struct list_head buf_list;
291 struct {
292 struct page **buf_pages;
293 struct io_uring_buf_ring *buf_ring;
294 };
295 };
296 __u16 bgid;
297
298 /* below is for ring provided buffers */
299 __u16 buf_nr_pages;
300 __u16 nr_entries;
301 __u16 head;
302 __u16 mask;
303 };
304
305 struct io_buffer {
306 struct list_head list;
307 __u64 addr;
308 __u32 len;
309 __u16 bid;
310 __u16 bgid;
311 };
312
313 struct io_restriction {
314 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
315 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
316 u8 sqe_flags_allowed;
317 u8 sqe_flags_required;
318 bool registered;
319 };
320
321 enum {
322 IO_SQ_THREAD_SHOULD_STOP = 0,
323 IO_SQ_THREAD_SHOULD_PARK,
324 };
325
326 struct io_sq_data {
327 refcount_t refs;
328 atomic_t park_pending;
329 struct mutex lock;
330
331 /* ctx's that are using this sqd */
332 struct list_head ctx_list;
333
334 struct task_struct *thread;
335 struct wait_queue_head wait;
336
337 unsigned sq_thread_idle;
338 int sq_cpu;
339 pid_t task_pid;
340 pid_t task_tgid;
341
342 unsigned long state;
343 struct completion exited;
344 };
345
346 #define IO_COMPL_BATCH 32
347 #define IO_REQ_CACHE_SIZE 32
348 #define IO_REQ_ALLOC_BATCH 8
349
350 struct io_submit_link {
351 struct io_kiocb *head;
352 struct io_kiocb *last;
353 };
354
355 struct io_submit_state {
356 /* inline/task_work completion list, under ->uring_lock */
357 struct io_wq_work_node free_list;
358 /* batch completion logic */
359 struct io_wq_work_list compl_reqs;
360 struct io_submit_link link;
361
362 bool plug_started;
363 bool need_plug;
364 bool flush_cqes;
365 unsigned short submit_nr;
366 struct blk_plug plug;
367 };
368
369 struct io_ev_fd {
370 struct eventfd_ctx *cq_ev_fd;
371 unsigned int eventfd_async: 1;
372 struct rcu_head rcu;
373 };
374
375 #define BGID_ARRAY 64
376
377 struct io_ring_ctx {
378 /* const or read-mostly hot data */
379 struct {
380 struct percpu_ref refs;
381
382 struct io_rings *rings;
383 unsigned int flags;
384 enum task_work_notify_mode notify_method;
385 unsigned int compat: 1;
386 unsigned int drain_next: 1;
387 unsigned int restricted: 1;
388 unsigned int off_timeout_used: 1;
389 unsigned int drain_active: 1;
390 unsigned int drain_disabled: 1;
391 unsigned int has_evfd: 1;
392 unsigned int syscall_iopoll: 1;
393 } ____cacheline_aligned_in_smp;
394
395 /* submission data */
396 struct {
397 struct mutex uring_lock;
398
399 /*
400 * Ring buffer of indices into array of io_uring_sqe, which is
401 * mmapped by the application using the IORING_OFF_SQES offset.
402 *
403 * This indirection could e.g. be used to assign fixed
404 * io_uring_sqe entries to operations and only submit them to
405 * the queue when needed.
406 *
407 * The kernel modifies neither the indices array nor the entries
408 * array.
409 */
410 u32 *sq_array;
411 struct io_uring_sqe *sq_sqes;
412 unsigned cached_sq_head;
413 unsigned sq_entries;
414 struct list_head defer_list;
415
416 /*
417 * Fixed resources fast path, should be accessed only under
418 * uring_lock, and updated through io_uring_register(2)
419 */
420 struct io_rsrc_node *rsrc_node;
421 int rsrc_cached_refs;
422 atomic_t cancel_seq;
423 struct io_file_table file_table;
424 unsigned nr_user_files;
425 unsigned nr_user_bufs;
426 struct io_mapped_ubuf **user_bufs;
427
428 struct io_submit_state submit_state;
429
430 struct io_buffer_list *io_bl;
431 struct xarray io_bl_xa;
432 struct list_head io_buffers_cache;
433
434 struct list_head timeout_list;
435 struct list_head ltimeout_list;
436 struct list_head cq_overflow_list;
437 struct list_head apoll_cache;
438 struct xarray personalities;
439 u32 pers_next;
440 unsigned sq_thread_idle;
441 } ____cacheline_aligned_in_smp;
442
443 /* IRQ completion list, under ->completion_lock */
444 struct io_wq_work_list locked_free_list;
445 unsigned int locked_free_nr;
446
447 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
448 struct io_sq_data *sq_data; /* if using sq thread polling */
449
450 struct wait_queue_head sqo_sq_wait;
451 struct list_head sqd_list;
452
453 unsigned long check_cq;
454
455 struct {
456 /*
457 * We cache a range of free CQEs we can use, once exhausted it
458 * should go through a slower range setup, see __io_get_cqe()
459 */
460 struct io_uring_cqe *cqe_cached;
461 struct io_uring_cqe *cqe_sentinel;
462
463 unsigned cached_cq_tail;
464 unsigned cq_entries;
465 struct io_ev_fd __rcu *io_ev_fd;
466 struct wait_queue_head cq_wait;
467 unsigned cq_extra;
468 atomic_t cq_timeouts;
469 unsigned cq_last_tm_flush;
470 } ____cacheline_aligned_in_smp;
471
472 struct {
473 spinlock_t completion_lock;
474
475 spinlock_t timeout_lock;
476
477 /*
478 * ->iopoll_list is protected by the ctx->uring_lock for
479 * io_uring instances that don't use IORING_SETUP_SQPOLL.
480 * For SQPOLL, only the single threaded io_sq_thread() will
481 * manipulate the list, hence no extra locking is needed there.
482 */
483 struct io_wq_work_list iopoll_list;
484 struct hlist_head *cancel_hash;
485 unsigned cancel_hash_bits;
486 bool poll_multi_queue;
487
488 struct list_head io_buffers_comp;
489 } ____cacheline_aligned_in_smp;
490
491 struct io_restriction restrictions;
492
493 /* slow path rsrc auxilary data, used by update/register */
494 struct {
495 struct io_rsrc_node *rsrc_backup_node;
496 struct io_mapped_ubuf *dummy_ubuf;
497 struct io_rsrc_data *file_data;
498 struct io_rsrc_data *buf_data;
499
500 struct delayed_work rsrc_put_work;
501 struct llist_head rsrc_put_llist;
502 struct list_head rsrc_ref_list;
503 spinlock_t rsrc_ref_lock;
504
505 struct list_head io_buffers_pages;
506 };
507
508 /* Keep this last, we don't need it for the fast path */
509 struct {
510 #if defined(CONFIG_UNIX)
511 struct socket *ring_sock;
512 #endif
513 /* hashed buffered write serialization */
514 struct io_wq_hash *hash_map;
515
516 /* Only used for accounting purposes */
517 struct user_struct *user;
518 struct mm_struct *mm_account;
519
520 /* ctx exit and cancelation */
521 struct llist_head fallback_llist;
522 struct delayed_work fallback_work;
523 struct work_struct exit_work;
524 struct list_head tctx_list;
525 struct completion ref_comp;
526 u32 iowq_limits[2];
527 bool iowq_limits_set;
528 };
529 };
530
531 /*
532 * Arbitrary limit, can be raised if need be
533 */
534 #define IO_RINGFD_REG_MAX 16
535
536 struct io_uring_task {
537 /* submission side */
538 int cached_refs;
539 struct xarray xa;
540 struct wait_queue_head wait;
541 const struct io_ring_ctx *last;
542 struct io_wq *io_wq;
543 struct percpu_counter inflight;
544 atomic_t inflight_tracked;
545 atomic_t in_idle;
546
547 spinlock_t task_lock;
548 struct io_wq_work_list task_list;
549 struct io_wq_work_list prio_task_list;
550 struct callback_head task_work;
551 struct file **registered_rings;
552 bool task_running;
553 };
554
555 /*
556 * First field must be the file pointer in all the
557 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
558 */
559 struct io_poll_iocb {
560 struct file *file;
561 struct wait_queue_head *head;
562 __poll_t events;
563 struct wait_queue_entry wait;
564 };
565
566 struct io_poll_update {
567 struct file *file;
568 u64 old_user_data;
569 u64 new_user_data;
570 __poll_t events;
571 bool update_events;
572 bool update_user_data;
573 };
574
575 struct io_close {
576 struct file *file;
577 int fd;
578 u32 file_slot;
579 };
580
581 struct io_timeout_data {
582 struct io_kiocb *req;
583 struct hrtimer timer;
584 struct timespec64 ts;
585 enum hrtimer_mode mode;
586 u32 flags;
587 };
588
589 struct io_accept {
590 struct file *file;
591 struct sockaddr __user *addr;
592 int __user *addr_len;
593 int flags;
594 u32 file_slot;
595 unsigned long nofile;
596 };
597
598 struct io_socket {
599 struct file *file;
600 int domain;
601 int type;
602 int protocol;
603 int flags;
604 u32 file_slot;
605 unsigned long nofile;
606 };
607
608 struct io_sync {
609 struct file *file;
610 loff_t len;
611 loff_t off;
612 int flags;
613 int mode;
614 };
615
616 struct io_cancel {
617 struct file *file;
618 u64 addr;
619 u32 flags;
620 s32 fd;
621 };
622
623 struct io_timeout {
624 struct file *file;
625 u32 off;
626 u32 target_seq;
627 struct list_head list;
628 /* head of the link, used by linked timeouts only */
629 struct io_kiocb *head;
630 /* for linked completions */
631 struct io_kiocb *prev;
632 };
633
634 struct io_timeout_rem {
635 struct file *file;
636 u64 addr;
637
638 /* timeout update */
639 struct timespec64 ts;
640 u32 flags;
641 bool ltimeout;
642 };
643
644 struct io_rw {
645 /* NOTE: kiocb has the file as the first member, so don't do it here */
646 struct kiocb kiocb;
647 u64 addr;
648 u32 len;
649 rwf_t flags;
650 };
651
652 struct io_connect {
653 struct file *file;
654 struct sockaddr __user *addr;
655 int addr_len;
656 };
657
658 struct io_sr_msg {
659 struct file *file;
660 union {
661 struct compat_msghdr __user *umsg_compat;
662 struct user_msghdr __user *umsg;
663 void __user *buf;
664 };
665 int msg_flags;
666 size_t len;
667 size_t done_io;
668 unsigned int flags;
669 };
670
671 struct io_open {
672 struct file *file;
673 int dfd;
674 u32 file_slot;
675 struct filename *filename;
676 struct open_how how;
677 unsigned long nofile;
678 };
679
680 struct io_rsrc_update {
681 struct file *file;
682 u64 arg;
683 u32 nr_args;
684 u32 offset;
685 };
686
687 struct io_fadvise {
688 struct file *file;
689 u64 offset;
690 u32 len;
691 u32 advice;
692 };
693
694 struct io_madvise {
695 struct file *file;
696 u64 addr;
697 u32 len;
698 u32 advice;
699 };
700
701 struct io_epoll {
702 struct file *file;
703 int epfd;
704 int op;
705 int fd;
706 struct epoll_event event;
707 };
708
709 struct io_splice {
710 struct file *file_out;
711 loff_t off_out;
712 loff_t off_in;
713 u64 len;
714 int splice_fd_in;
715 unsigned int flags;
716 };
717
718 struct io_provide_buf {
719 struct file *file;
720 __u64 addr;
721 __u32 len;
722 __u32 bgid;
723 __u16 nbufs;
724 __u16 bid;
725 };
726
727 struct io_statx {
728 struct file *file;
729 int dfd;
730 unsigned int mask;
731 unsigned int flags;
732 struct filename *filename;
733 struct statx __user *buffer;
734 };
735
736 struct io_shutdown {
737 struct file *file;
738 int how;
739 };
740
741 struct io_rename {
742 struct file *file;
743 int old_dfd;
744 int new_dfd;
745 struct filename *oldpath;
746 struct filename *newpath;
747 int flags;
748 };
749
750 struct io_unlink {
751 struct file *file;
752 int dfd;
753 int flags;
754 struct filename *filename;
755 };
756
757 struct io_mkdir {
758 struct file *file;
759 int dfd;
760 umode_t mode;
761 struct filename *filename;
762 };
763
764 struct io_symlink {
765 struct file *file;
766 int new_dfd;
767 struct filename *oldpath;
768 struct filename *newpath;
769 };
770
771 struct io_hardlink {
772 struct file *file;
773 int old_dfd;
774 int new_dfd;
775 struct filename *oldpath;
776 struct filename *newpath;
777 int flags;
778 };
779
780 struct io_msg {
781 struct file *file;
782 u64 user_data;
783 u32 len;
784 };
785
786 struct io_async_connect {
787 struct sockaddr_storage address;
788 };
789
790 struct io_async_msghdr {
791 struct iovec fast_iov[UIO_FASTIOV];
792 /* points to an allocated iov, if NULL we use fast_iov instead */
793 struct iovec *free_iov;
794 struct sockaddr __user *uaddr;
795 struct msghdr msg;
796 struct sockaddr_storage addr;
797 };
798
799 struct io_rw_state {
800 struct iov_iter iter;
801 struct iov_iter_state iter_state;
802 struct iovec fast_iov[UIO_FASTIOV];
803 };
804
805 struct io_async_rw {
806 struct io_rw_state s;
807 const struct iovec *free_iovec;
808 size_t bytes_done;
809 struct wait_page_queue wpq;
810 };
811
812 struct io_xattr {
813 struct file *file;
814 struct xattr_ctx ctx;
815 struct filename *filename;
816 };
817
818 enum {
819 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
820 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
821 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
822 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
823 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
824 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
825 REQ_F_CQE_SKIP_BIT = IOSQE_CQE_SKIP_SUCCESS_BIT,
826
827 /* first byte is taken by user flags, shift it to not overlap */
828 REQ_F_FAIL_BIT = 8,
829 REQ_F_INFLIGHT_BIT,
830 REQ_F_CUR_POS_BIT,
831 REQ_F_NOWAIT_BIT,
832 REQ_F_LINK_TIMEOUT_BIT,
833 REQ_F_NEED_CLEANUP_BIT,
834 REQ_F_POLLED_BIT,
835 REQ_F_BUFFER_SELECTED_BIT,
836 REQ_F_BUFFER_RING_BIT,
837 REQ_F_COMPLETE_INLINE_BIT,
838 REQ_F_REISSUE_BIT,
839 REQ_F_CREDS_BIT,
840 REQ_F_REFCOUNT_BIT,
841 REQ_F_ARM_LTIMEOUT_BIT,
842 REQ_F_ASYNC_DATA_BIT,
843 REQ_F_SKIP_LINK_CQES_BIT,
844 REQ_F_SINGLE_POLL_BIT,
845 REQ_F_DOUBLE_POLL_BIT,
846 REQ_F_PARTIAL_IO_BIT,
847 REQ_F_CQE32_INIT_BIT,
848 REQ_F_APOLL_MULTISHOT_BIT,
849 /* keep async read/write and isreg together and in order */
850 REQ_F_SUPPORT_NOWAIT_BIT,
851 REQ_F_ISREG_BIT,
852
853 /* not a real bit, just to check we're not overflowing the space */
854 __REQ_F_LAST_BIT,
855 };
856
857 enum {
858 /* ctx owns file */
859 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
860 /* drain existing IO first */
861 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
862 /* linked sqes */
863 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
864 /* doesn't sever on completion < 0 */
865 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
866 /* IOSQE_ASYNC */
867 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
868 /* IOSQE_BUFFER_SELECT */
869 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
870 /* IOSQE_CQE_SKIP_SUCCESS */
871 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
872
873 /* fail rest of links */
874 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
875 /* on inflight list, should be cancelled and waited on exit reliably */
876 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
877 /* read/write uses file position */
878 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
879 /* must not punt to workers */
880 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
881 /* has or had linked timeout */
882 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
883 /* needs cleanup */
884 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
885 /* already went through poll handler */
886 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
887 /* buffer already selected */
888 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
889 /* buffer selected from ring, needs commit */
890 REQ_F_BUFFER_RING = BIT(REQ_F_BUFFER_RING_BIT),
891 /* completion is deferred through io_comp_state */
892 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
893 /* caller should reissue async */
894 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
895 /* supports async reads/writes */
896 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
897 /* regular file */
898 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
899 /* has creds assigned */
900 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
901 /* skip refcounting if not set */
902 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
903 /* there is a linked timeout that has to be armed */
904 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
905 /* ->async_data allocated */
906 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
907 /* don't post CQEs while failing linked requests */
908 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
909 /* single poll may be active */
910 REQ_F_SINGLE_POLL = BIT(REQ_F_SINGLE_POLL_BIT),
911 /* double poll may active */
912 REQ_F_DOUBLE_POLL = BIT(REQ_F_DOUBLE_POLL_BIT),
913 /* request has already done partial IO */
914 REQ_F_PARTIAL_IO = BIT(REQ_F_PARTIAL_IO_BIT),
915 /* fast poll multishot mode */
916 REQ_F_APOLL_MULTISHOT = BIT(REQ_F_APOLL_MULTISHOT_BIT),
917 /* ->extra1 and ->extra2 are initialised */
918 REQ_F_CQE32_INIT = BIT(REQ_F_CQE32_INIT_BIT),
919 };
920
921 struct async_poll {
922 struct io_poll_iocb poll;
923 struct io_poll_iocb *double_poll;
924 };
925
926 typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
927
928 struct io_task_work {
929 union {
930 struct io_wq_work_node node;
931 struct llist_node fallback_node;
932 };
933 io_req_tw_func_t func;
934 };
935
936 enum {
937 IORING_RSRC_FILE = 0,
938 IORING_RSRC_BUFFER = 1,
939 };
940
941 struct io_cqe {
942 __u64 user_data;
943 __s32 res;
944 /* fd initially, then cflags for completion */
945 union {
946 __u32 flags;
947 int fd;
948 };
949 };
950
951 enum {
952 IO_CHECK_CQ_OVERFLOW_BIT,
953 IO_CHECK_CQ_DROPPED_BIT,
954 };
955
956 /*
957 * NOTE! Each of the iocb union members has the file pointer
958 * as the first entry in their struct definition. So you can
959 * access the file pointer through any of the sub-structs,
960 * or directly as just 'file' in this struct.
961 */
962 struct io_kiocb {
963 union {
964 struct file *file;
965 struct io_rw rw;
966 struct io_poll_iocb poll;
967 struct io_poll_update poll_update;
968 struct io_accept accept;
969 struct io_sync sync;
970 struct io_cancel cancel;
971 struct io_timeout timeout;
972 struct io_timeout_rem timeout_rem;
973 struct io_connect connect;
974 struct io_sr_msg sr_msg;
975 struct io_open open;
976 struct io_close close;
977 struct io_rsrc_update rsrc_update;
978 struct io_fadvise fadvise;
979 struct io_madvise madvise;
980 struct io_epoll epoll;
981 struct io_splice splice;
982 struct io_provide_buf pbuf;
983 struct io_statx statx;
984 struct io_shutdown shutdown;
985 struct io_rename rename;
986 struct io_unlink unlink;
987 struct io_mkdir mkdir;
988 struct io_symlink symlink;
989 struct io_hardlink hardlink;
990 struct io_msg msg;
991 struct io_xattr xattr;
992 struct io_socket sock;
993 struct io_uring_cmd uring_cmd;
994 };
995
996 u8 opcode;
997 /* polled IO has completed */
998 u8 iopoll_completed;
999 /*
1000 * Can be either a fixed buffer index, or used with provided buffers.
1001 * For the latter, before issue it points to the buffer group ID,
1002 * and after selection it points to the buffer ID itself.
1003 */
1004 u16 buf_index;
1005 unsigned int flags;
1006
1007 struct io_cqe cqe;
1008
1009 struct io_ring_ctx *ctx;
1010 struct task_struct *task;
1011
1012 struct io_rsrc_node *rsrc_node;
1013
1014 union {
1015 /* store used ubuf, so we can prevent reloading */
1016 struct io_mapped_ubuf *imu;
1017
1018 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
1019 struct io_buffer *kbuf;
1020
1021 /*
1022 * stores buffer ID for ring provided buffers, valid IFF
1023 * REQ_F_BUFFER_RING is set.
1024 */
1025 struct io_buffer_list *buf_list;
1026 };
1027
1028 union {
1029 /* used by request caches, completion batching and iopoll */
1030 struct io_wq_work_node comp_list;
1031 /* cache ->apoll->events */
1032 __poll_t apoll_events;
1033 };
1034 atomic_t refs;
1035 atomic_t poll_refs;
1036 struct io_task_work io_task_work;
1037 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
1038 union {
1039 struct hlist_node hash_node;
1040 struct {
1041 u64 extra1;
1042 u64 extra2;
1043 };
1044 };
1045 /* internal polling, see IORING_FEAT_FAST_POLL */
1046 struct async_poll *apoll;
1047 /* opcode allocated if it needs to store data for async defer */
1048 void *async_data;
1049 /* linked requests, IFF REQ_F_HARDLINK or REQ_F_LINK are set */
1050 struct io_kiocb *link;
1051 /* custom credentials, valid IFF REQ_F_CREDS is set */
1052 const struct cred *creds;
1053 struct io_wq_work work;
1054 };
1055
1056 struct io_tctx_node {
1057 struct list_head ctx_node;
1058 struct task_struct *task;
1059 struct io_ring_ctx *ctx;
1060 };
1061
1062 struct io_defer_entry {
1063 struct list_head list;
1064 struct io_kiocb *req;
1065 u32 seq;
1066 };
1067
1068 struct io_cancel_data {
1069 struct io_ring_ctx *ctx;
1070 union {
1071 u64 data;
1072 struct file *file;
1073 };
1074 u32 flags;
1075 int seq;
1076 };
1077
1078 /*
1079 * The URING_CMD payload starts at 'cmd' in the first sqe, and continues into
1080 * the following sqe if SQE128 is used.
1081 */
1082 #define uring_cmd_pdu_size(is_sqe128) \
1083 ((1 + !!(is_sqe128)) * sizeof(struct io_uring_sqe) - \
1084 offsetof(struct io_uring_sqe, cmd))
1085
1086 struct io_op_def {
1087 /* needs req->file assigned */
1088 unsigned needs_file : 1;
1089 /* should block plug */
1090 unsigned plug : 1;
1091 /* hash wq insertion if file is a regular file */
1092 unsigned hash_reg_file : 1;
1093 /* unbound wq insertion if file is a non-regular file */
1094 unsigned unbound_nonreg_file : 1;
1095 /* set if opcode supports polled "wait" */
1096 unsigned pollin : 1;
1097 unsigned pollout : 1;
1098 unsigned poll_exclusive : 1;
1099 /* op supports buffer selection */
1100 unsigned buffer_select : 1;
1101 /* do prep async if is going to be punted */
1102 unsigned needs_async_setup : 1;
1103 /* opcode is not supported by this kernel */
1104 unsigned not_supported : 1;
1105 /* skip auditing */
1106 unsigned audit_skip : 1;
1107 /* supports ioprio */
1108 unsigned ioprio : 1;
1109 /* supports iopoll */
1110 unsigned iopoll : 1;
1111 /* size of async data needed, if any */
1112 unsigned short async_size;
1113
1114 int (*prep)(struct io_kiocb *, const struct io_uring_sqe *);
1115 int (*issue)(struct io_kiocb *, unsigned int);
1116 };
1117
1118 static const struct io_op_def io_op_defs[];
1119
1120 /* requests with any of those set should undergo io_disarm_next() */
1121 #define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1122 #define IO_REQ_LINK_FLAGS (REQ_F_LINK | REQ_F_HARDLINK)
1123
1124 static bool io_disarm_next(struct io_kiocb *req);
1125 static void io_uring_del_tctx_node(unsigned long index);
1126 static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1127 struct task_struct *task,
1128 bool cancel_all);
1129 static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1130
1131 static void __io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags);
1132 static void io_dismantle_req(struct io_kiocb *req);
1133 static void io_queue_linked_timeout(struct io_kiocb *req);
1134 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1135 struct io_uring_rsrc_update2 *up,
1136 unsigned nr_args);
1137 static void io_clean_op(struct io_kiocb *req);
1138 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
1139 unsigned issue_flags);
1140 static struct file *io_file_get_normal(struct io_kiocb *req, int fd);
1141 static void io_queue_sqe(struct io_kiocb *req);
1142 static void io_rsrc_put_work(struct work_struct *work);
1143
1144 static void io_req_task_queue(struct io_kiocb *req);
1145 static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
1146 static int io_req_prep_async(struct io_kiocb *req);
1147
1148 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1149 unsigned int issue_flags, u32 slot_index);
1150 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
1151 unsigned int offset);
1152 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1153
1154 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
1155 static void io_eventfd_signal(struct io_ring_ctx *ctx);
1156 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags);
1157
1158 static struct kmem_cache *req_cachep;
1159
1160 static const struct file_operations io_uring_fops;
1161
io_uring_get_opcode(u8 opcode)1162 const char *io_uring_get_opcode(u8 opcode)
1163 {
1164 switch ((enum io_uring_op)opcode) {
1165 case IORING_OP_NOP:
1166 return "NOP";
1167 case IORING_OP_READV:
1168 return "READV";
1169 case IORING_OP_WRITEV:
1170 return "WRITEV";
1171 case IORING_OP_FSYNC:
1172 return "FSYNC";
1173 case IORING_OP_READ_FIXED:
1174 return "READ_FIXED";
1175 case IORING_OP_WRITE_FIXED:
1176 return "WRITE_FIXED";
1177 case IORING_OP_POLL_ADD:
1178 return "POLL_ADD";
1179 case IORING_OP_POLL_REMOVE:
1180 return "POLL_REMOVE";
1181 case IORING_OP_SYNC_FILE_RANGE:
1182 return "SYNC_FILE_RANGE";
1183 case IORING_OP_SENDMSG:
1184 return "SENDMSG";
1185 case IORING_OP_RECVMSG:
1186 return "RECVMSG";
1187 case IORING_OP_TIMEOUT:
1188 return "TIMEOUT";
1189 case IORING_OP_TIMEOUT_REMOVE:
1190 return "TIMEOUT_REMOVE";
1191 case IORING_OP_ACCEPT:
1192 return "ACCEPT";
1193 case IORING_OP_ASYNC_CANCEL:
1194 return "ASYNC_CANCEL";
1195 case IORING_OP_LINK_TIMEOUT:
1196 return "LINK_TIMEOUT";
1197 case IORING_OP_CONNECT:
1198 return "CONNECT";
1199 case IORING_OP_FALLOCATE:
1200 return "FALLOCATE";
1201 case IORING_OP_OPENAT:
1202 return "OPENAT";
1203 case IORING_OP_CLOSE:
1204 return "CLOSE";
1205 case IORING_OP_FILES_UPDATE:
1206 return "FILES_UPDATE";
1207 case IORING_OP_STATX:
1208 return "STATX";
1209 case IORING_OP_READ:
1210 return "READ";
1211 case IORING_OP_WRITE:
1212 return "WRITE";
1213 case IORING_OP_FADVISE:
1214 return "FADVISE";
1215 case IORING_OP_MADVISE:
1216 return "MADVISE";
1217 case IORING_OP_SEND:
1218 return "SEND";
1219 case IORING_OP_RECV:
1220 return "RECV";
1221 case IORING_OP_OPENAT2:
1222 return "OPENAT2";
1223 case IORING_OP_EPOLL_CTL:
1224 return "EPOLL_CTL";
1225 case IORING_OP_SPLICE:
1226 return "SPLICE";
1227 case IORING_OP_PROVIDE_BUFFERS:
1228 return "PROVIDE_BUFFERS";
1229 case IORING_OP_REMOVE_BUFFERS:
1230 return "REMOVE_BUFFERS";
1231 case IORING_OP_TEE:
1232 return "TEE";
1233 case IORING_OP_SHUTDOWN:
1234 return "SHUTDOWN";
1235 case IORING_OP_RENAMEAT:
1236 return "RENAMEAT";
1237 case IORING_OP_UNLINKAT:
1238 return "UNLINKAT";
1239 case IORING_OP_MKDIRAT:
1240 return "MKDIRAT";
1241 case IORING_OP_SYMLINKAT:
1242 return "SYMLINKAT";
1243 case IORING_OP_LINKAT:
1244 return "LINKAT";
1245 case IORING_OP_MSG_RING:
1246 return "MSG_RING";
1247 case IORING_OP_FSETXATTR:
1248 return "FSETXATTR";
1249 case IORING_OP_SETXATTR:
1250 return "SETXATTR";
1251 case IORING_OP_FGETXATTR:
1252 return "FGETXATTR";
1253 case IORING_OP_GETXATTR:
1254 return "GETXATTR";
1255 case IORING_OP_SOCKET:
1256 return "SOCKET";
1257 case IORING_OP_URING_CMD:
1258 return "URING_CMD";
1259 case IORING_OP_LAST:
1260 return "INVALID";
1261 }
1262 return "INVALID";
1263 }
1264
io_uring_get_socket(struct file * file)1265 struct sock *io_uring_get_socket(struct file *file)
1266 {
1267 #if defined(CONFIG_UNIX)
1268 if (file->f_op == &io_uring_fops) {
1269 struct io_ring_ctx *ctx = file->private_data;
1270
1271 return ctx->ring_sock->sk;
1272 }
1273 #endif
1274 return NULL;
1275 }
1276 EXPORT_SYMBOL(io_uring_get_socket);
1277
1278 #if defined(CONFIG_UNIX)
io_file_need_scm(struct file * filp)1279 static inline bool io_file_need_scm(struct file *filp)
1280 {
1281 #if defined(IO_URING_SCM_ALL)
1282 return true;
1283 #else
1284 return !!unix_get_socket(filp);
1285 #endif
1286 }
1287 #else
io_file_need_scm(struct file * filp)1288 static inline bool io_file_need_scm(struct file *filp)
1289 {
1290 return false;
1291 }
1292 #endif
1293
io_ring_submit_unlock(struct io_ring_ctx * ctx,unsigned issue_flags)1294 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, unsigned issue_flags)
1295 {
1296 lockdep_assert_held(&ctx->uring_lock);
1297 if (issue_flags & IO_URING_F_UNLOCKED)
1298 mutex_unlock(&ctx->uring_lock);
1299 }
1300
io_ring_submit_lock(struct io_ring_ctx * ctx,unsigned issue_flags)1301 static void io_ring_submit_lock(struct io_ring_ctx *ctx, unsigned issue_flags)
1302 {
1303 /*
1304 * "Normal" inline submissions always hold the uring_lock, since we
1305 * grab it from the system call. Same is true for the SQPOLL offload.
1306 * The only exception is when we've detached the request and issue it
1307 * from an async worker thread, grab the lock for that case.
1308 */
1309 if (issue_flags & IO_URING_F_UNLOCKED)
1310 mutex_lock(&ctx->uring_lock);
1311 lockdep_assert_held(&ctx->uring_lock);
1312 }
1313
io_tw_lock(struct io_ring_ctx * ctx,bool * locked)1314 static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1315 {
1316 if (!*locked) {
1317 mutex_lock(&ctx->uring_lock);
1318 *locked = true;
1319 }
1320 }
1321
1322 #define io_for_each_link(pos, head) \
1323 for (pos = (head); pos; pos = pos->link)
1324
1325 /*
1326 * Shamelessly stolen from the mm implementation of page reference checking,
1327 * see commit f958d7b528b1 for details.
1328 */
1329 #define req_ref_zero_or_close_to_overflow(req) \
1330 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1331
req_ref_inc_not_zero(struct io_kiocb * req)1332 static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1333 {
1334 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1335 return atomic_inc_not_zero(&req->refs);
1336 }
1337
req_ref_put_and_test(struct io_kiocb * req)1338 static inline bool req_ref_put_and_test(struct io_kiocb *req)
1339 {
1340 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1341 return true;
1342
1343 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1344 return atomic_dec_and_test(&req->refs);
1345 }
1346
req_ref_get(struct io_kiocb * req)1347 static inline void req_ref_get(struct io_kiocb *req)
1348 {
1349 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
1350 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1351 atomic_inc(&req->refs);
1352 }
1353
io_submit_flush_completions(struct io_ring_ctx * ctx)1354 static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1355 {
1356 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
1357 __io_submit_flush_completions(ctx);
1358 }
1359
__io_req_set_refcount(struct io_kiocb * req,int nr)1360 static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
1361 {
1362 if (!(req->flags & REQ_F_REFCOUNT)) {
1363 req->flags |= REQ_F_REFCOUNT;
1364 atomic_set(&req->refs, nr);
1365 }
1366 }
1367
io_req_set_refcount(struct io_kiocb * req)1368 static inline void io_req_set_refcount(struct io_kiocb *req)
1369 {
1370 __io_req_set_refcount(req, 1);
1371 }
1372
1373 #define IO_RSRC_REF_BATCH 100
1374
io_rsrc_put_node(struct io_rsrc_node * node,int nr)1375 static void io_rsrc_put_node(struct io_rsrc_node *node, int nr)
1376 {
1377 percpu_ref_put_many(&node->refs, nr);
1378 }
1379
io_req_put_rsrc_locked(struct io_kiocb * req,struct io_ring_ctx * ctx)1380 static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1381 struct io_ring_ctx *ctx)
1382 __must_hold(&ctx->uring_lock)
1383 {
1384 struct io_rsrc_node *node = req->rsrc_node;
1385
1386 if (node) {
1387 if (node == ctx->rsrc_node)
1388 ctx->rsrc_cached_refs++;
1389 else
1390 io_rsrc_put_node(node, 1);
1391 }
1392 }
1393
io_req_put_rsrc(struct io_kiocb * req)1394 static inline void io_req_put_rsrc(struct io_kiocb *req)
1395 {
1396 if (req->rsrc_node)
1397 io_rsrc_put_node(req->rsrc_node, 1);
1398 }
1399
io_rsrc_refs_drop(struct io_ring_ctx * ctx)1400 static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1401 __must_hold(&ctx->uring_lock)
1402 {
1403 if (ctx->rsrc_cached_refs) {
1404 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
1405 ctx->rsrc_cached_refs = 0;
1406 }
1407 }
1408
io_rsrc_refs_refill(struct io_ring_ctx * ctx)1409 static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1410 __must_hold(&ctx->uring_lock)
1411 {
1412 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1413 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1414 }
1415
io_req_set_rsrc_node(struct io_kiocb * req,struct io_ring_ctx * ctx,unsigned int issue_flags)1416 static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1417 struct io_ring_ctx *ctx,
1418 unsigned int issue_flags)
1419 {
1420 if (!req->rsrc_node) {
1421 req->rsrc_node = ctx->rsrc_node;
1422
1423 if (!(issue_flags & IO_URING_F_UNLOCKED)) {
1424 lockdep_assert_held(&ctx->uring_lock);
1425 ctx->rsrc_cached_refs--;
1426 if (unlikely(ctx->rsrc_cached_refs < 0))
1427 io_rsrc_refs_refill(ctx);
1428 } else {
1429 percpu_ref_get(&req->rsrc_node->refs);
1430 }
1431 }
1432 }
1433
__io_put_kbuf(struct io_kiocb * req,struct list_head * list)1434 static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
1435 {
1436 if (req->flags & REQ_F_BUFFER_RING) {
1437 if (req->buf_list)
1438 req->buf_list->head++;
1439 req->flags &= ~REQ_F_BUFFER_RING;
1440 } else {
1441 list_add(&req->kbuf->list, list);
1442 req->flags &= ~REQ_F_BUFFER_SELECTED;
1443 }
1444
1445 return IORING_CQE_F_BUFFER | (req->buf_index << IORING_CQE_BUFFER_SHIFT);
1446 }
1447
io_put_kbuf_comp(struct io_kiocb * req)1448 static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
1449 {
1450 lockdep_assert_held(&req->ctx->completion_lock);
1451
1452 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1453 return 0;
1454 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1455 }
1456
io_put_kbuf(struct io_kiocb * req,unsigned issue_flags)1457 static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1458 unsigned issue_flags)
1459 {
1460 unsigned int cflags;
1461
1462 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1463 return 0;
1464
1465 /*
1466 * We can add this buffer back to two lists:
1467 *
1468 * 1) The io_buffers_cache list. This one is protected by the
1469 * ctx->uring_lock. If we already hold this lock, add back to this
1470 * list as we can grab it from issue as well.
1471 * 2) The io_buffers_comp list. This one is protected by the
1472 * ctx->completion_lock.
1473 *
1474 * We migrate buffers from the comp_list to the issue cache list
1475 * when we need one.
1476 */
1477 if (req->flags & REQ_F_BUFFER_RING) {
1478 /* no buffers to recycle for this case */
1479 cflags = __io_put_kbuf(req, NULL);
1480 } else if (issue_flags & IO_URING_F_UNLOCKED) {
1481 struct io_ring_ctx *ctx = req->ctx;
1482
1483 spin_lock(&ctx->completion_lock);
1484 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1485 spin_unlock(&ctx->completion_lock);
1486 } else {
1487 lockdep_assert_held(&req->ctx->uring_lock);
1488
1489 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1490 }
1491
1492 return cflags;
1493 }
1494
io_buffer_get_list(struct io_ring_ctx * ctx,unsigned int bgid)1495 static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1496 unsigned int bgid)
1497 {
1498 if (ctx->io_bl && bgid < BGID_ARRAY)
1499 return &ctx->io_bl[bgid];
1500
1501 return xa_load(&ctx->io_bl_xa, bgid);
1502 }
1503
io_kbuf_recycle(struct io_kiocb * req,unsigned issue_flags)1504 static void io_kbuf_recycle(struct io_kiocb *req, unsigned issue_flags)
1505 {
1506 struct io_ring_ctx *ctx = req->ctx;
1507 struct io_buffer_list *bl;
1508 struct io_buffer *buf;
1509
1510 if (!(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)))
1511 return;
1512 /*
1513 * For legacy provided buffer mode, don't recycle if we already did
1514 * IO to this buffer. For ring-mapped provided buffer mode, we should
1515 * increment ring->head to explicitly monopolize the buffer to avoid
1516 * multiple use.
1517 */
1518 if ((req->flags & REQ_F_BUFFER_SELECTED) &&
1519 (req->flags & REQ_F_PARTIAL_IO))
1520 return;
1521
1522 /*
1523 * READV uses fields in `struct io_rw` (len/addr) to stash the selected
1524 * buffer data. However if that buffer is recycled the original request
1525 * data stored in addr is lost. Therefore forbid recycling for now.
1526 */
1527 if (req->opcode == IORING_OP_READV)
1528 return;
1529
1530 /*
1531 * We don't need to recycle for REQ_F_BUFFER_RING, we can just clear
1532 * the flag and hence ensure that bl->head doesn't get incremented.
1533 * If the tail has already been incremented, hang on to it.
1534 */
1535 if (req->flags & REQ_F_BUFFER_RING) {
1536 if (req->buf_list) {
1537 if (req->flags & REQ_F_PARTIAL_IO) {
1538 req->buf_list->head++;
1539 req->buf_list = NULL;
1540 } else {
1541 req->buf_index = req->buf_list->bgid;
1542 req->flags &= ~REQ_F_BUFFER_RING;
1543 }
1544 }
1545 return;
1546 }
1547
1548 io_ring_submit_lock(ctx, issue_flags);
1549
1550 buf = req->kbuf;
1551 bl = io_buffer_get_list(ctx, buf->bgid);
1552 list_add(&buf->list, &bl->buf_list);
1553 req->flags &= ~REQ_F_BUFFER_SELECTED;
1554 req->buf_index = buf->bgid;
1555
1556 io_ring_submit_unlock(ctx, issue_flags);
1557 }
1558
io_match_task(struct io_kiocb * head,struct task_struct * task,bool cancel_all)1559 static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1560 bool cancel_all)
1561 __must_hold(&req->ctx->timeout_lock)
1562 {
1563 struct io_kiocb *req;
1564
1565 if (task && head->task != task)
1566 return false;
1567 if (cancel_all)
1568 return true;
1569
1570 io_for_each_link(req, head) {
1571 if (req->flags & REQ_F_INFLIGHT)
1572 return true;
1573 }
1574 return false;
1575 }
1576
io_match_linked(struct io_kiocb * head)1577 static bool io_match_linked(struct io_kiocb *head)
1578 {
1579 struct io_kiocb *req;
1580
1581 io_for_each_link(req, head) {
1582 if (req->flags & REQ_F_INFLIGHT)
1583 return true;
1584 }
1585 return false;
1586 }
1587
1588 /*
1589 * As io_match_task() but protected against racing with linked timeouts.
1590 * User must not hold timeout_lock.
1591 */
io_match_task_safe(struct io_kiocb * head,struct task_struct * task,bool cancel_all)1592 static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1593 bool cancel_all)
1594 {
1595 bool matched;
1596
1597 if (task && head->task != task)
1598 return false;
1599 if (cancel_all)
1600 return true;
1601
1602 if (head->flags & REQ_F_LINK_TIMEOUT) {
1603 struct io_ring_ctx *ctx = head->ctx;
1604
1605 /* protect against races with linked timeouts */
1606 spin_lock_irq(&ctx->timeout_lock);
1607 matched = io_match_linked(head);
1608 spin_unlock_irq(&ctx->timeout_lock);
1609 } else {
1610 matched = io_match_linked(head);
1611 }
1612 return matched;
1613 }
1614
req_has_async_data(struct io_kiocb * req)1615 static inline bool req_has_async_data(struct io_kiocb *req)
1616 {
1617 return req->flags & REQ_F_ASYNC_DATA;
1618 }
1619
req_set_fail(struct io_kiocb * req)1620 static inline void req_set_fail(struct io_kiocb *req)
1621 {
1622 req->flags |= REQ_F_FAIL;
1623 if (req->flags & REQ_F_CQE_SKIP) {
1624 req->flags &= ~REQ_F_CQE_SKIP;
1625 req->flags |= REQ_F_SKIP_LINK_CQES;
1626 }
1627 }
1628
req_fail_link_node(struct io_kiocb * req,int res)1629 static inline void req_fail_link_node(struct io_kiocb *req, int res)
1630 {
1631 req_set_fail(req);
1632 req->cqe.res = res;
1633 }
1634
io_req_add_to_cache(struct io_kiocb * req,struct io_ring_ctx * ctx)1635 static inline void io_req_add_to_cache(struct io_kiocb *req, struct io_ring_ctx *ctx)
1636 {
1637 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
1638 }
1639
io_ring_ctx_ref_free(struct percpu_ref * ref)1640 static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
1641 {
1642 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1643
1644 complete(&ctx->ref_comp);
1645 }
1646
io_is_timeout_noseq(struct io_kiocb * req)1647 static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1648 {
1649 return !req->timeout.off;
1650 }
1651
io_fallback_req_func(struct work_struct * work)1652 static __cold void io_fallback_req_func(struct work_struct *work)
1653 {
1654 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1655 fallback_work.work);
1656 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1657 struct io_kiocb *req, *tmp;
1658 bool locked = false;
1659
1660 percpu_ref_get(&ctx->refs);
1661 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1662 req->io_task_work.func(req, &locked);
1663
1664 if (locked) {
1665 io_submit_flush_completions(ctx);
1666 mutex_unlock(&ctx->uring_lock);
1667 }
1668 percpu_ref_put(&ctx->refs);
1669 }
1670
io_ring_ctx_alloc(struct io_uring_params * p)1671 static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1672 {
1673 struct io_ring_ctx *ctx;
1674 int hash_bits;
1675
1676 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1677 if (!ctx)
1678 return NULL;
1679
1680 xa_init(&ctx->io_bl_xa);
1681
1682 /*
1683 * Use 5 bits less than the max cq entries, that should give us around
1684 * 32 entries per hash list if totally full and uniformly spread.
1685 */
1686 hash_bits = ilog2(p->cq_entries);
1687 hash_bits -= 5;
1688 if (hash_bits <= 0)
1689 hash_bits = 1;
1690 ctx->cancel_hash_bits = hash_bits;
1691 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1692 GFP_KERNEL);
1693 if (!ctx->cancel_hash)
1694 goto err;
1695 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1696
1697 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1698 if (!ctx->dummy_ubuf)
1699 goto err;
1700 /* set invalid range, so io_import_fixed() fails meeting it */
1701 ctx->dummy_ubuf->ubuf = -1UL;
1702
1703 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1704 0, GFP_KERNEL))
1705 goto err;
1706
1707 ctx->flags = p->flags;
1708 init_waitqueue_head(&ctx->sqo_sq_wait);
1709 INIT_LIST_HEAD(&ctx->sqd_list);
1710 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1711 INIT_LIST_HEAD(&ctx->io_buffers_cache);
1712 INIT_LIST_HEAD(&ctx->apoll_cache);
1713 init_completion(&ctx->ref_comp);
1714 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1715 mutex_init(&ctx->uring_lock);
1716 init_waitqueue_head(&ctx->cq_wait);
1717 spin_lock_init(&ctx->completion_lock);
1718 spin_lock_init(&ctx->timeout_lock);
1719 INIT_WQ_LIST(&ctx->iopoll_list);
1720 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1721 INIT_LIST_HEAD(&ctx->io_buffers_comp);
1722 INIT_LIST_HEAD(&ctx->defer_list);
1723 INIT_LIST_HEAD(&ctx->timeout_list);
1724 INIT_LIST_HEAD(&ctx->ltimeout_list);
1725 spin_lock_init(&ctx->rsrc_ref_lock);
1726 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1727 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1728 init_llist_head(&ctx->rsrc_put_llist);
1729 INIT_LIST_HEAD(&ctx->tctx_list);
1730 ctx->submit_state.free_list.next = NULL;
1731 INIT_WQ_LIST(&ctx->locked_free_list);
1732 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1733 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
1734 return ctx;
1735 err:
1736 kfree(ctx->dummy_ubuf);
1737 kfree(ctx->cancel_hash);
1738 kfree(ctx->io_bl);
1739 xa_destroy(&ctx->io_bl_xa);
1740 kfree(ctx);
1741 return NULL;
1742 }
1743
io_account_cq_overflow(struct io_ring_ctx * ctx)1744 static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1745 {
1746 struct io_rings *r = ctx->rings;
1747
1748 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1749 ctx->cq_extra--;
1750 }
1751
req_need_defer(struct io_kiocb * req,u32 seq)1752 static bool req_need_defer(struct io_kiocb *req, u32 seq)
1753 {
1754 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1755 struct io_ring_ctx *ctx = req->ctx;
1756
1757 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1758 }
1759
1760 return false;
1761 }
1762
io_req_ffs_set(struct io_kiocb * req)1763 static inline bool io_req_ffs_set(struct io_kiocb *req)
1764 {
1765 return req->flags & REQ_F_FIXED_FILE;
1766 }
1767
io_req_track_inflight(struct io_kiocb * req)1768 static inline void io_req_track_inflight(struct io_kiocb *req)
1769 {
1770 if (!(req->flags & REQ_F_INFLIGHT)) {
1771 req->flags |= REQ_F_INFLIGHT;
1772 atomic_inc(&req->task->io_uring->inflight_tracked);
1773 }
1774 }
1775
__io_prep_linked_timeout(struct io_kiocb * req)1776 static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1777 {
1778 if (WARN_ON_ONCE(!req->link))
1779 return NULL;
1780
1781 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1782 req->flags |= REQ_F_LINK_TIMEOUT;
1783
1784 /* linked timeouts should have two refs once prep'ed */
1785 io_req_set_refcount(req);
1786 __io_req_set_refcount(req->link, 2);
1787 return req->link;
1788 }
1789
io_prep_linked_timeout(struct io_kiocb * req)1790 static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1791 {
1792 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
1793 return NULL;
1794 return __io_prep_linked_timeout(req);
1795 }
1796
__io_arm_ltimeout(struct io_kiocb * req)1797 static noinline void __io_arm_ltimeout(struct io_kiocb *req)
1798 {
1799 io_queue_linked_timeout(__io_prep_linked_timeout(req));
1800 }
1801
io_arm_ltimeout(struct io_kiocb * req)1802 static inline void io_arm_ltimeout(struct io_kiocb *req)
1803 {
1804 if (unlikely(req->flags & REQ_F_ARM_LTIMEOUT))
1805 __io_arm_ltimeout(req);
1806 }
1807
io_prep_async_work(struct io_kiocb * req)1808 static void io_prep_async_work(struct io_kiocb *req)
1809 {
1810 const struct io_op_def *def = &io_op_defs[req->opcode];
1811 struct io_ring_ctx *ctx = req->ctx;
1812
1813 if (!(req->flags & REQ_F_CREDS)) {
1814 req->flags |= REQ_F_CREDS;
1815 req->creds = get_current_cred();
1816 }
1817
1818 req->work.list.next = NULL;
1819 req->work.flags = 0;
1820 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
1821 if (req->flags & REQ_F_FORCE_ASYNC)
1822 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1823
1824 if (req->flags & REQ_F_ISREG) {
1825 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1826 io_wq_hash_work(&req->work, file_inode(req->file));
1827 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1828 if (def->unbound_nonreg_file)
1829 req->work.flags |= IO_WQ_WORK_UNBOUND;
1830 }
1831 }
1832
io_prep_async_link(struct io_kiocb * req)1833 static void io_prep_async_link(struct io_kiocb *req)
1834 {
1835 struct io_kiocb *cur;
1836
1837 if (req->flags & REQ_F_LINK_TIMEOUT) {
1838 struct io_ring_ctx *ctx = req->ctx;
1839
1840 spin_lock_irq(&ctx->timeout_lock);
1841 io_for_each_link(cur, req)
1842 io_prep_async_work(cur);
1843 spin_unlock_irq(&ctx->timeout_lock);
1844 } else {
1845 io_for_each_link(cur, req)
1846 io_prep_async_work(cur);
1847 }
1848 }
1849
io_req_add_compl_list(struct io_kiocb * req)1850 static inline void io_req_add_compl_list(struct io_kiocb *req)
1851 {
1852 struct io_submit_state *state = &req->ctx->submit_state;
1853
1854 if (!(req->flags & REQ_F_CQE_SKIP))
1855 state->flush_cqes = true;
1856 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1857 }
1858
io_queue_iowq(struct io_kiocb * req,bool * dont_use)1859 static void io_queue_iowq(struct io_kiocb *req, bool *dont_use)
1860 {
1861 struct io_kiocb *link = io_prep_linked_timeout(req);
1862 struct io_uring_task *tctx = req->task->io_uring;
1863
1864 BUG_ON(!tctx);
1865 BUG_ON(!tctx->io_wq);
1866
1867 /* init ->work of the whole link before punting */
1868 io_prep_async_link(req);
1869
1870 /*
1871 * Not expected to happen, but if we do have a bug where this _can_
1872 * happen, catch it here and ensure the request is marked as
1873 * canceled. That will make io-wq go through the usual work cancel
1874 * procedure rather than attempt to run this request (or create a new
1875 * worker for it).
1876 */
1877 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1878 req->work.flags |= IO_WQ_WORK_CANCEL;
1879
1880 trace_io_uring_queue_async_work(req->ctx, req, req->cqe.user_data,
1881 req->opcode, req->flags, &req->work,
1882 io_wq_is_hashed(&req->work));
1883 io_wq_enqueue(tctx->io_wq, &req->work);
1884 if (link)
1885 io_queue_linked_timeout(link);
1886 }
1887
io_kill_timeout(struct io_kiocb * req,int status)1888 static void io_kill_timeout(struct io_kiocb *req, int status)
1889 __must_hold(&req->ctx->completion_lock)
1890 __must_hold(&req->ctx->timeout_lock)
1891 {
1892 struct io_timeout_data *io = req->async_data;
1893
1894 if (hrtimer_try_to_cancel(&io->timer) != -1) {
1895 if (status)
1896 req_set_fail(req);
1897 atomic_set(&req->ctx->cq_timeouts,
1898 atomic_read(&req->ctx->cq_timeouts) + 1);
1899 list_del_init(&req->timeout.list);
1900 io_req_tw_post_queue(req, status, 0);
1901 }
1902 }
1903
io_queue_deferred(struct io_ring_ctx * ctx)1904 static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
1905 {
1906 while (!list_empty(&ctx->defer_list)) {
1907 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1908 struct io_defer_entry, list);
1909
1910 if (req_need_defer(de->req, de->seq))
1911 break;
1912 list_del_init(&de->list);
1913 io_req_task_queue(de->req);
1914 kfree(de);
1915 }
1916 }
1917
io_flush_timeouts(struct io_ring_ctx * ctx)1918 static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
1919 __must_hold(&ctx->completion_lock)
1920 {
1921 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1922 struct io_kiocb *req, *tmp;
1923
1924 spin_lock_irq(&ctx->timeout_lock);
1925 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
1926 u32 events_needed, events_got;
1927
1928 if (io_is_timeout_noseq(req))
1929 break;
1930
1931 /*
1932 * Since seq can easily wrap around over time, subtract
1933 * the last seq at which timeouts were flushed before comparing.
1934 * Assuming not more than 2^31-1 events have happened since,
1935 * these subtractions won't have wrapped, so we can check if
1936 * target is in [last_seq, current_seq] by comparing the two.
1937 */
1938 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1939 events_got = seq - ctx->cq_last_tm_flush;
1940 if (events_got < events_needed)
1941 break;
1942
1943 io_kill_timeout(req, 0);
1944 }
1945 ctx->cq_last_tm_flush = seq;
1946 spin_unlock_irq(&ctx->timeout_lock);
1947 }
1948
io_commit_cqring(struct io_ring_ctx * ctx)1949 static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1950 {
1951 /* order cqe stores with ring update */
1952 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1953 }
1954
__io_commit_cqring_flush(struct io_ring_ctx * ctx)1955 static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1956 {
1957 if (ctx->off_timeout_used || ctx->drain_active) {
1958 spin_lock(&ctx->completion_lock);
1959 if (ctx->off_timeout_used)
1960 io_flush_timeouts(ctx);
1961 if (ctx->drain_active)
1962 io_queue_deferred(ctx);
1963 io_commit_cqring(ctx);
1964 spin_unlock(&ctx->completion_lock);
1965 }
1966 if (ctx->has_evfd)
1967 io_eventfd_signal(ctx);
1968 }
1969
io_sqring_full(struct io_ring_ctx * ctx)1970 static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1971 {
1972 struct io_rings *r = ctx->rings;
1973
1974 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1975 }
1976
__io_cqring_events(struct io_ring_ctx * ctx)1977 static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1978 {
1979 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1980 }
1981
1982 /*
1983 * writes to the cq entry need to come after reading head; the
1984 * control dependency is enough as we're using WRITE_ONCE to
1985 * fill the cq entry
1986 */
__io_get_cqe(struct io_ring_ctx * ctx)1987 static noinline struct io_uring_cqe *__io_get_cqe(struct io_ring_ctx *ctx)
1988 {
1989 struct io_rings *rings = ctx->rings;
1990 unsigned int off = ctx->cached_cq_tail & (ctx->cq_entries - 1);
1991 unsigned int shift = 0;
1992 unsigned int free, queued, len;
1993
1994 if (ctx->flags & IORING_SETUP_CQE32)
1995 shift = 1;
1996
1997 /* userspace may cheat modifying the tail, be safe and do min */
1998 queued = min(__io_cqring_events(ctx), ctx->cq_entries);
1999 free = ctx->cq_entries - queued;
2000 /* we need a contiguous range, limit based on the current array offset */
2001 len = min(free, ctx->cq_entries - off);
2002 if (!len)
2003 return NULL;
2004
2005 ctx->cached_cq_tail++;
2006 ctx->cqe_cached = &rings->cqes[off];
2007 ctx->cqe_sentinel = ctx->cqe_cached + len;
2008 ctx->cqe_cached++;
2009 return &rings->cqes[off << shift];
2010 }
2011
io_get_cqe(struct io_ring_ctx * ctx)2012 static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
2013 {
2014 if (likely(ctx->cqe_cached < ctx->cqe_sentinel)) {
2015 struct io_uring_cqe *cqe = ctx->cqe_cached;
2016
2017 if (ctx->flags & IORING_SETUP_CQE32) {
2018 unsigned int off = ctx->cqe_cached - ctx->rings->cqes;
2019
2020 cqe += off;
2021 }
2022
2023 ctx->cached_cq_tail++;
2024 ctx->cqe_cached++;
2025 return cqe;
2026 }
2027
2028 return __io_get_cqe(ctx);
2029 }
2030
io_eventfd_signal(struct io_ring_ctx * ctx)2031 static void io_eventfd_signal(struct io_ring_ctx *ctx)
2032 {
2033 struct io_ev_fd *ev_fd;
2034
2035 rcu_read_lock();
2036 /*
2037 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
2038 * and eventfd_signal
2039 */
2040 ev_fd = rcu_dereference(ctx->io_ev_fd);
2041
2042 /*
2043 * Check again if ev_fd exists incase an io_eventfd_unregister call
2044 * completed between the NULL check of ctx->io_ev_fd at the start of
2045 * the function and rcu_read_lock.
2046 */
2047 if (unlikely(!ev_fd))
2048 goto out;
2049 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
2050 goto out;
2051
2052 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
2053 eventfd_signal(ev_fd->cq_ev_fd, 1);
2054 out:
2055 rcu_read_unlock();
2056 }
2057
io_cqring_wake(struct io_ring_ctx * ctx)2058 static inline void io_cqring_wake(struct io_ring_ctx *ctx)
2059 {
2060 /*
2061 * wake_up_all() may seem excessive, but io_wake_function() and
2062 * io_should_wake() handle the termination of the loop and only
2063 * wake as many waiters as we need to.
2064 */
2065 if (wq_has_sleeper(&ctx->cq_wait))
2066 wake_up_all(&ctx->cq_wait);
2067 }
2068
2069 /*
2070 * This should only get called when at least one event has been posted.
2071 * Some applications rely on the eventfd notification count only changing
2072 * IFF a new CQE has been added to the CQ ring. There's no depedency on
2073 * 1:1 relationship between how many times this function is called (and
2074 * hence the eventfd count) and number of CQEs posted to the CQ ring.
2075 */
io_cqring_ev_posted(struct io_ring_ctx * ctx)2076 static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
2077 {
2078 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2079 ctx->has_evfd))
2080 __io_commit_cqring_flush(ctx);
2081
2082 io_cqring_wake(ctx);
2083 }
2084
io_cqring_ev_posted_iopoll(struct io_ring_ctx * ctx)2085 static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
2086 {
2087 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
2088 ctx->has_evfd))
2089 __io_commit_cqring_flush(ctx);
2090
2091 if (ctx->flags & IORING_SETUP_SQPOLL)
2092 io_cqring_wake(ctx);
2093 }
2094
2095 /* Returns true if there are no backlogged entries after the flush */
__io_cqring_overflow_flush(struct io_ring_ctx * ctx,bool force)2096 static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
2097 {
2098 bool all_flushed, posted;
2099 size_t cqe_size = sizeof(struct io_uring_cqe);
2100
2101 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
2102 return false;
2103
2104 if (ctx->flags & IORING_SETUP_CQE32)
2105 cqe_size <<= 1;
2106
2107 posted = false;
2108 spin_lock(&ctx->completion_lock);
2109 while (!list_empty(&ctx->cq_overflow_list)) {
2110 struct io_uring_cqe *cqe = io_get_cqe(ctx);
2111 struct io_overflow_cqe *ocqe;
2112
2113 if (!cqe && !force)
2114 break;
2115 ocqe = list_first_entry(&ctx->cq_overflow_list,
2116 struct io_overflow_cqe, list);
2117 if (cqe)
2118 memcpy(cqe, &ocqe->cqe, cqe_size);
2119 else
2120 io_account_cq_overflow(ctx);
2121
2122 posted = true;
2123 list_del(&ocqe->list);
2124 kfree(ocqe);
2125 }
2126
2127 all_flushed = list_empty(&ctx->cq_overflow_list);
2128 if (all_flushed) {
2129 clear_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2130 atomic_andnot(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2131 }
2132
2133 io_commit_cqring(ctx);
2134 spin_unlock(&ctx->completion_lock);
2135 if (posted)
2136 io_cqring_ev_posted(ctx);
2137 return all_flushed;
2138 }
2139
io_cqring_overflow_flush(struct io_ring_ctx * ctx)2140 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
2141 {
2142 bool ret = true;
2143
2144 if (test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq)) {
2145 /* iopoll syncs against uring_lock, not completion_lock */
2146 if (ctx->flags & IORING_SETUP_IOPOLL)
2147 mutex_lock(&ctx->uring_lock);
2148 ret = __io_cqring_overflow_flush(ctx, false);
2149 if (ctx->flags & IORING_SETUP_IOPOLL)
2150 mutex_unlock(&ctx->uring_lock);
2151 }
2152
2153 return ret;
2154 }
2155
__io_put_task(struct task_struct * task,int nr)2156 static void __io_put_task(struct task_struct *task, int nr)
2157 {
2158 struct io_uring_task *tctx = task->io_uring;
2159
2160 percpu_counter_sub(&tctx->inflight, nr);
2161 if (unlikely(atomic_read(&tctx->in_idle)))
2162 wake_up(&tctx->wait);
2163 put_task_struct_many(task, nr);
2164 }
2165
2166 /* must to be called somewhat shortly after putting a request */
io_put_task(struct task_struct * task,int nr)2167 static inline void io_put_task(struct task_struct *task, int nr)
2168 {
2169 if (likely(task == current))
2170 task->io_uring->cached_refs += nr;
2171 else
2172 __io_put_task(task, nr);
2173 }
2174
io_task_refs_refill(struct io_uring_task * tctx)2175 static void io_task_refs_refill(struct io_uring_task *tctx)
2176 {
2177 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
2178
2179 percpu_counter_add(&tctx->inflight, refill);
2180 refcount_add(refill, ¤t->usage);
2181 tctx->cached_refs += refill;
2182 }
2183
io_get_task_refs(int nr)2184 static inline void io_get_task_refs(int nr)
2185 {
2186 struct io_uring_task *tctx = current->io_uring;
2187
2188 tctx->cached_refs -= nr;
2189 if (unlikely(tctx->cached_refs < 0))
2190 io_task_refs_refill(tctx);
2191 }
2192
io_uring_drop_tctx_refs(struct task_struct * task)2193 static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
2194 {
2195 struct io_uring_task *tctx = task->io_uring;
2196 unsigned int refs = tctx->cached_refs;
2197
2198 if (refs) {
2199 tctx->cached_refs = 0;
2200 percpu_counter_sub(&tctx->inflight, refs);
2201 put_task_struct_many(task, refs);
2202 }
2203 }
2204
io_cqring_event_overflow(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags,u64 extra1,u64 extra2)2205 static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
2206 s32 res, u32 cflags, u64 extra1,
2207 u64 extra2)
2208 {
2209 struct io_overflow_cqe *ocqe;
2210 size_t ocq_size = sizeof(struct io_overflow_cqe);
2211 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
2212
2213 if (is_cqe32)
2214 ocq_size += sizeof(struct io_uring_cqe);
2215
2216 ocqe = kmalloc(ocq_size, GFP_ATOMIC | __GFP_ACCOUNT);
2217 trace_io_uring_cqe_overflow(ctx, user_data, res, cflags, ocqe);
2218 if (!ocqe) {
2219 /*
2220 * If we're in ring overflow flush mode, or in task cancel mode,
2221 * or cannot allocate an overflow entry, then we need to drop it
2222 * on the floor.
2223 */
2224 io_account_cq_overflow(ctx);
2225 set_bit(IO_CHECK_CQ_DROPPED_BIT, &ctx->check_cq);
2226 return false;
2227 }
2228 if (list_empty(&ctx->cq_overflow_list)) {
2229 set_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq);
2230 atomic_or(IORING_SQ_CQ_OVERFLOW, &ctx->rings->sq_flags);
2231
2232 }
2233 ocqe->cqe.user_data = user_data;
2234 ocqe->cqe.res = res;
2235 ocqe->cqe.flags = cflags;
2236 if (is_cqe32) {
2237 ocqe->cqe.big_cqe[0] = extra1;
2238 ocqe->cqe.big_cqe[1] = extra2;
2239 }
2240 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2241 return true;
2242 }
2243
__io_fill_cqe_req(struct io_ring_ctx * ctx,struct io_kiocb * req)2244 static inline bool __io_fill_cqe_req(struct io_ring_ctx *ctx,
2245 struct io_kiocb *req)
2246 {
2247 struct io_uring_cqe *cqe;
2248
2249 if (!(ctx->flags & IORING_SETUP_CQE32)) {
2250 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2251 req->cqe.res, req->cqe.flags, 0, 0);
2252
2253 /*
2254 * If we can't get a cq entry, userspace overflowed the
2255 * submission (by quite a lot). Increment the overflow count in
2256 * the ring.
2257 */
2258 cqe = io_get_cqe(ctx);
2259 if (likely(cqe)) {
2260 memcpy(cqe, &req->cqe, sizeof(*cqe));
2261 return true;
2262 }
2263
2264 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2265 req->cqe.res, req->cqe.flags,
2266 0, 0);
2267 } else {
2268 u64 extra1 = 0, extra2 = 0;
2269
2270 if (req->flags & REQ_F_CQE32_INIT) {
2271 extra1 = req->extra1;
2272 extra2 = req->extra2;
2273 }
2274
2275 trace_io_uring_complete(req->ctx, req, req->cqe.user_data,
2276 req->cqe.res, req->cqe.flags, extra1, extra2);
2277
2278 /*
2279 * If we can't get a cq entry, userspace overflowed the
2280 * submission (by quite a lot). Increment the overflow count in
2281 * the ring.
2282 */
2283 cqe = io_get_cqe(ctx);
2284 if (likely(cqe)) {
2285 memcpy(cqe, &req->cqe, sizeof(struct io_uring_cqe));
2286 WRITE_ONCE(cqe->big_cqe[0], extra1);
2287 WRITE_ONCE(cqe->big_cqe[1], extra2);
2288 return true;
2289 }
2290
2291 return io_cqring_event_overflow(ctx, req->cqe.user_data,
2292 req->cqe.res, req->cqe.flags,
2293 extra1, extra2);
2294 }
2295 }
2296
io_fill_cqe_aux(struct io_ring_ctx * ctx,u64 user_data,s32 res,u32 cflags)2297 static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2298 s32 res, u32 cflags)
2299 {
2300 struct io_uring_cqe *cqe;
2301
2302 ctx->cq_extra++;
2303 trace_io_uring_complete(ctx, NULL, user_data, res, cflags, 0, 0);
2304
2305 /*
2306 * If we can't get a cq entry, userspace overflowed the
2307 * submission (by quite a lot). Increment the overflow count in
2308 * the ring.
2309 */
2310 cqe = io_get_cqe(ctx);
2311 if (likely(cqe)) {
2312 WRITE_ONCE(cqe->user_data, user_data);
2313 WRITE_ONCE(cqe->res, res);
2314 WRITE_ONCE(cqe->flags, cflags);
2315
2316 if (ctx->flags & IORING_SETUP_CQE32) {
2317 WRITE_ONCE(cqe->big_cqe[0], 0);
2318 WRITE_ONCE(cqe->big_cqe[1], 0);
2319 }
2320 return true;
2321 }
2322 return io_cqring_event_overflow(ctx, user_data, res, cflags, 0, 0);
2323 }
2324
__io_req_complete_put(struct io_kiocb * req)2325 static void __io_req_complete_put(struct io_kiocb *req)
2326 {
2327 /*
2328 * If we're the last reference to this request, add to our locked
2329 * free_list cache.
2330 */
2331 if (req_ref_put_and_test(req)) {
2332 struct io_ring_ctx *ctx = req->ctx;
2333
2334 if (req->flags & IO_REQ_LINK_FLAGS) {
2335 if (req->flags & IO_DISARM_MASK)
2336 io_disarm_next(req);
2337 if (req->link) {
2338 io_req_task_queue(req->link);
2339 req->link = NULL;
2340 }
2341 }
2342 io_req_put_rsrc(req);
2343 /*
2344 * Selected buffer deallocation in io_clean_op() assumes that
2345 * we don't hold ->completion_lock. Clean them here to avoid
2346 * deadlocks.
2347 */
2348 io_put_kbuf_comp(req);
2349 io_dismantle_req(req);
2350 io_put_task(req->task, 1);
2351 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2352 ctx->locked_free_nr++;
2353 }
2354 }
2355
__io_req_complete_post(struct io_kiocb * req,s32 res,u32 cflags)2356 static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2357 u32 cflags)
2358 {
2359 if (!(req->flags & REQ_F_CQE_SKIP)) {
2360 req->cqe.res = res;
2361 req->cqe.flags = cflags;
2362 __io_fill_cqe_req(req->ctx, req);
2363 }
2364 __io_req_complete_put(req);
2365 }
2366
io_req_complete_post(struct io_kiocb * req,s32 res,u32 cflags)2367 static void io_req_complete_post(struct io_kiocb *req, s32 res, u32 cflags)
2368 {
2369 struct io_ring_ctx *ctx = req->ctx;
2370
2371 spin_lock(&ctx->completion_lock);
2372 __io_req_complete_post(req, res, cflags);
2373 io_commit_cqring(ctx);
2374 spin_unlock(&ctx->completion_lock);
2375 io_cqring_ev_posted(ctx);
2376 }
2377
io_req_complete_state(struct io_kiocb * req,s32 res,u32 cflags)2378 static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2379 u32 cflags)
2380 {
2381 req->cqe.res = res;
2382 req->cqe.flags = cflags;
2383 req->flags |= REQ_F_COMPLETE_INLINE;
2384 }
2385
__io_req_complete(struct io_kiocb * req,unsigned issue_flags,s32 res,u32 cflags)2386 static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
2387 s32 res, u32 cflags)
2388 {
2389 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2390 io_req_complete_state(req, res, cflags);
2391 else
2392 io_req_complete_post(req, res, cflags);
2393 }
2394
io_req_complete(struct io_kiocb * req,s32 res)2395 static inline void io_req_complete(struct io_kiocb *req, s32 res)
2396 {
2397 if (res < 0)
2398 req_set_fail(req);
2399 __io_req_complete(req, 0, res, 0);
2400 }
2401
io_req_complete_failed(struct io_kiocb * req,s32 res)2402 static void io_req_complete_failed(struct io_kiocb *req, s32 res)
2403 {
2404 req_set_fail(req);
2405 io_req_complete_post(req, res, io_put_kbuf(req, IO_URING_F_UNLOCKED));
2406 }
2407
2408 /*
2409 * Don't initialise the fields below on every allocation, but do that in
2410 * advance and keep them valid across allocations.
2411 */
io_preinit_req(struct io_kiocb * req,struct io_ring_ctx * ctx)2412 static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2413 {
2414 req->ctx = ctx;
2415 req->link = NULL;
2416 req->async_data = NULL;
2417 /* not necessary, but safer to zero */
2418 req->cqe.res = 0;
2419 }
2420
io_flush_cached_locked_reqs(struct io_ring_ctx * ctx,struct io_submit_state * state)2421 static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
2422 struct io_submit_state *state)
2423 {
2424 spin_lock(&ctx->completion_lock);
2425 wq_list_splice(&ctx->locked_free_list, &state->free_list);
2426 ctx->locked_free_nr = 0;
2427 spin_unlock(&ctx->completion_lock);
2428 }
2429
io_req_cache_empty(struct io_ring_ctx * ctx)2430 static inline bool io_req_cache_empty(struct io_ring_ctx *ctx)
2431 {
2432 return !ctx->submit_state.free_list.next;
2433 }
2434
2435 /*
2436 * A request might get retired back into the request caches even before opcode
2437 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2438 * Because of that, io_alloc_req() should be called only under ->uring_lock
2439 * and with extra caution to not get a request that is still worked on.
2440 */
__io_alloc_req_refill(struct io_ring_ctx * ctx)2441 static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
2442 __must_hold(&ctx->uring_lock)
2443 {
2444 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
2445 void *reqs[IO_REQ_ALLOC_BATCH];
2446 int ret, i;
2447
2448 /*
2449 * If we have more than a batch's worth of requests in our IRQ side
2450 * locked cache, grab the lock and move them over to our submission
2451 * side cache.
2452 */
2453 if (data_race(ctx->locked_free_nr) > IO_COMPL_BATCH) {
2454 io_flush_cached_locked_reqs(ctx, &ctx->submit_state);
2455 if (!io_req_cache_empty(ctx))
2456 return true;
2457 }
2458
2459 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
2460
2461 /*
2462 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2463 * retry single alloc to be on the safe side.
2464 */
2465 if (unlikely(ret <= 0)) {
2466 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2467 if (!reqs[0])
2468 return false;
2469 ret = 1;
2470 }
2471
2472 percpu_ref_get_many(&ctx->refs, ret);
2473 for (i = 0; i < ret; i++) {
2474 struct io_kiocb *req = reqs[i];
2475
2476 io_preinit_req(req, ctx);
2477 io_req_add_to_cache(req, ctx);
2478 }
2479 return true;
2480 }
2481
io_alloc_req_refill(struct io_ring_ctx * ctx)2482 static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2483 {
2484 if (unlikely(io_req_cache_empty(ctx)))
2485 return __io_alloc_req_refill(ctx);
2486 return true;
2487 }
2488
io_alloc_req(struct io_ring_ctx * ctx)2489 static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2490 {
2491 struct io_wq_work_node *node;
2492
2493 node = wq_stack_extract(&ctx->submit_state.free_list);
2494 return container_of(node, struct io_kiocb, comp_list);
2495 }
2496
io_put_file(struct file * file)2497 static inline void io_put_file(struct file *file)
2498 {
2499 if (file)
2500 fput(file);
2501 }
2502
io_dismantle_req(struct io_kiocb * req)2503 static inline void io_dismantle_req(struct io_kiocb *req)
2504 {
2505 unsigned int flags = req->flags;
2506
2507 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
2508 io_clean_op(req);
2509 if (!(flags & REQ_F_FIXED_FILE))
2510 io_put_file(req->file);
2511 }
2512
io_free_req(struct io_kiocb * req)2513 static __cold void io_free_req(struct io_kiocb *req)
2514 {
2515 struct io_ring_ctx *ctx = req->ctx;
2516
2517 io_req_put_rsrc(req);
2518 io_dismantle_req(req);
2519 io_put_task(req->task, 1);
2520
2521 spin_lock(&ctx->completion_lock);
2522 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
2523 ctx->locked_free_nr++;
2524 spin_unlock(&ctx->completion_lock);
2525 }
2526
io_remove_next_linked(struct io_kiocb * req)2527 static inline void io_remove_next_linked(struct io_kiocb *req)
2528 {
2529 struct io_kiocb *nxt = req->link;
2530
2531 req->link = nxt->link;
2532 nxt->link = NULL;
2533 }
2534
io_disarm_linked_timeout(struct io_kiocb * req)2535 static struct io_kiocb *io_disarm_linked_timeout(struct io_kiocb *req)
2536 __must_hold(&req->ctx->completion_lock)
2537 __must_hold(&req->ctx->timeout_lock)
2538 {
2539 struct io_kiocb *link = req->link;
2540
2541 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2542 struct io_timeout_data *io = link->async_data;
2543
2544 io_remove_next_linked(req);
2545 link->timeout.head = NULL;
2546 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2547 list_del(&link->timeout.list);
2548 return link;
2549 }
2550 }
2551 return NULL;
2552 }
2553
io_fail_links(struct io_kiocb * req)2554 static void io_fail_links(struct io_kiocb *req)
2555 __must_hold(&req->ctx->completion_lock)
2556 {
2557 struct io_kiocb *nxt, *link = req->link;
2558 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
2559
2560 req->link = NULL;
2561 while (link) {
2562 long res = -ECANCELED;
2563
2564 if (link->flags & REQ_F_FAIL)
2565 res = link->cqe.res;
2566
2567 nxt = link->link;
2568 link->link = NULL;
2569
2570 trace_io_uring_fail_link(req->ctx, req, req->cqe.user_data,
2571 req->opcode, link);
2572
2573 if (ignore_cqes)
2574 link->flags |= REQ_F_CQE_SKIP;
2575 else
2576 link->flags &= ~REQ_F_CQE_SKIP;
2577 __io_req_complete_post(link, res, 0);
2578 link = nxt;
2579 }
2580 }
2581
io_disarm_next(struct io_kiocb * req)2582 static bool io_disarm_next(struct io_kiocb *req)
2583 __must_hold(&req->ctx->completion_lock)
2584 {
2585 struct io_kiocb *link = NULL;
2586 bool posted = false;
2587
2588 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2589 link = req->link;
2590 req->flags &= ~REQ_F_ARM_LTIMEOUT;
2591 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2592 io_remove_next_linked(req);
2593 io_req_tw_post_queue(link, -ECANCELED, 0);
2594 posted = true;
2595 }
2596 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
2597 struct io_ring_ctx *ctx = req->ctx;
2598
2599 spin_lock_irq(&ctx->timeout_lock);
2600 link = io_disarm_linked_timeout(req);
2601 spin_unlock_irq(&ctx->timeout_lock);
2602 if (link) {
2603 posted = true;
2604 io_req_tw_post_queue(link, -ECANCELED, 0);
2605 }
2606 }
2607 if (unlikely((req->flags & REQ_F_FAIL) &&
2608 !(req->flags & REQ_F_HARDLINK))) {
2609 posted |= (req->link != NULL);
2610 io_fail_links(req);
2611 }
2612 return posted;
2613 }
2614
__io_req_find_next_prep(struct io_kiocb * req)2615 static void __io_req_find_next_prep(struct io_kiocb *req)
2616 {
2617 struct io_ring_ctx *ctx = req->ctx;
2618 bool posted;
2619
2620 spin_lock(&ctx->completion_lock);
2621 posted = io_disarm_next(req);
2622 io_commit_cqring(ctx);
2623 spin_unlock(&ctx->completion_lock);
2624 if (posted)
2625 io_cqring_ev_posted(ctx);
2626 }
2627
io_req_find_next(struct io_kiocb * req)2628 static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
2629 {
2630 struct io_kiocb *nxt;
2631
2632 /*
2633 * If LINK is set, we have dependent requests in this chain. If we
2634 * didn't fail this request, queue the first one up, moving any other
2635 * dependencies to the next request. In case of failure, fail the rest
2636 * of the chain.
2637 */
2638 if (unlikely(req->flags & IO_DISARM_MASK))
2639 __io_req_find_next_prep(req);
2640 nxt = req->link;
2641 req->link = NULL;
2642 return nxt;
2643 }
2644
ctx_flush_and_put(struct io_ring_ctx * ctx,bool * locked)2645 static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2646 {
2647 if (!ctx)
2648 return;
2649 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2650 atomic_andnot(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2651 if (*locked) {
2652 io_submit_flush_completions(ctx);
2653 mutex_unlock(&ctx->uring_lock);
2654 *locked = false;
2655 }
2656 percpu_ref_put(&ctx->refs);
2657 }
2658
ctx_commit_and_unlock(struct io_ring_ctx * ctx)2659 static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2660 {
2661 io_commit_cqring(ctx);
2662 spin_unlock(&ctx->completion_lock);
2663 io_cqring_ev_posted(ctx);
2664 }
2665
handle_prev_tw_list(struct io_wq_work_node * node,struct io_ring_ctx ** ctx,bool * uring_locked)2666 static void handle_prev_tw_list(struct io_wq_work_node *node,
2667 struct io_ring_ctx **ctx, bool *uring_locked)
2668 {
2669 if (*ctx && !*uring_locked)
2670 spin_lock(&(*ctx)->completion_lock);
2671
2672 do {
2673 struct io_wq_work_node *next = node->next;
2674 struct io_kiocb *req = container_of(node, struct io_kiocb,
2675 io_task_work.node);
2676
2677 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2678
2679 if (req->ctx != *ctx) {
2680 if (unlikely(!*uring_locked && *ctx))
2681 ctx_commit_and_unlock(*ctx);
2682
2683 ctx_flush_and_put(*ctx, uring_locked);
2684 *ctx = req->ctx;
2685 /* if not contended, grab and improve batching */
2686 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2687 percpu_ref_get(&(*ctx)->refs);
2688 if (unlikely(!*uring_locked))
2689 spin_lock(&(*ctx)->completion_lock);
2690 }
2691 if (likely(*uring_locked))
2692 req->io_task_work.func(req, uring_locked);
2693 else
2694 __io_req_complete_post(req, req->cqe.res,
2695 io_put_kbuf_comp(req));
2696 node = next;
2697 } while (node);
2698
2699 if (unlikely(!*uring_locked))
2700 ctx_commit_and_unlock(*ctx);
2701 }
2702
handle_tw_list(struct io_wq_work_node * node,struct io_ring_ctx ** ctx,bool * locked)2703 static void handle_tw_list(struct io_wq_work_node *node,
2704 struct io_ring_ctx **ctx, bool *locked)
2705 {
2706 do {
2707 struct io_wq_work_node *next = node->next;
2708 struct io_kiocb *req = container_of(node, struct io_kiocb,
2709 io_task_work.node);
2710
2711 prefetch(container_of(next, struct io_kiocb, io_task_work.node));
2712
2713 if (req->ctx != *ctx) {
2714 ctx_flush_and_put(*ctx, locked);
2715 *ctx = req->ctx;
2716 /* if not contended, grab and improve batching */
2717 *locked = mutex_trylock(&(*ctx)->uring_lock);
2718 percpu_ref_get(&(*ctx)->refs);
2719 }
2720 req->io_task_work.func(req, locked);
2721 node = next;
2722 } while (node);
2723 }
2724
tctx_task_work(struct callback_head * cb)2725 static void tctx_task_work(struct callback_head *cb)
2726 {
2727 bool uring_locked = false;
2728 struct io_ring_ctx *ctx = NULL;
2729 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2730 task_work);
2731
2732 while (1) {
2733 struct io_wq_work_node *node1, *node2;
2734
2735 spin_lock_irq(&tctx->task_lock);
2736 node1 = tctx->prio_task_list.first;
2737 node2 = tctx->task_list.first;
2738 INIT_WQ_LIST(&tctx->task_list);
2739 INIT_WQ_LIST(&tctx->prio_task_list);
2740 if (!node2 && !node1)
2741 tctx->task_running = false;
2742 spin_unlock_irq(&tctx->task_lock);
2743 if (!node2 && !node1)
2744 break;
2745
2746 if (node1)
2747 handle_prev_tw_list(node1, &ctx, &uring_locked);
2748 if (node2)
2749 handle_tw_list(node2, &ctx, &uring_locked);
2750 cond_resched();
2751
2752 if (data_race(!tctx->task_list.first) &&
2753 data_race(!tctx->prio_task_list.first) && uring_locked)
2754 io_submit_flush_completions(ctx);
2755 }
2756
2757 ctx_flush_and_put(ctx, &uring_locked);
2758
2759 /* relaxed read is enough as only the task itself sets ->in_idle */
2760 if (unlikely(atomic_read(&tctx->in_idle)))
2761 io_uring_drop_tctx_refs(current);
2762 }
2763
__io_req_task_work_add(struct io_kiocb * req,struct io_uring_task * tctx,struct io_wq_work_list * list)2764 static void __io_req_task_work_add(struct io_kiocb *req,
2765 struct io_uring_task *tctx,
2766 struct io_wq_work_list *list)
2767 {
2768 struct io_ring_ctx *ctx = req->ctx;
2769 struct io_wq_work_node *node;
2770 unsigned long flags;
2771 bool running;
2772
2773 spin_lock_irqsave(&tctx->task_lock, flags);
2774 wq_list_add_tail(&req->io_task_work.node, list);
2775 running = tctx->task_running;
2776 if (!running)
2777 tctx->task_running = true;
2778 spin_unlock_irqrestore(&tctx->task_lock, flags);
2779
2780 /* task_work already pending, we're done */
2781 if (running)
2782 return;
2783
2784 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
2785 atomic_or(IORING_SQ_TASKRUN, &ctx->rings->sq_flags);
2786
2787 if (likely(!task_work_add(req->task, &tctx->task_work, ctx->notify_method)))
2788 return;
2789
2790 spin_lock_irqsave(&tctx->task_lock, flags);
2791 tctx->task_running = false;
2792 node = wq_list_merge(&tctx->prio_task_list, &tctx->task_list);
2793 spin_unlock_irqrestore(&tctx->task_lock, flags);
2794
2795 while (node) {
2796 req = container_of(node, struct io_kiocb, io_task_work.node);
2797 node = node->next;
2798 if (llist_add(&req->io_task_work.fallback_node,
2799 &req->ctx->fallback_llist))
2800 schedule_delayed_work(&req->ctx->fallback_work, 1);
2801 }
2802 }
2803
io_req_task_work_add(struct io_kiocb * req)2804 static void io_req_task_work_add(struct io_kiocb *req)
2805 {
2806 struct io_uring_task *tctx = req->task->io_uring;
2807
2808 __io_req_task_work_add(req, tctx, &tctx->task_list);
2809 }
2810
io_req_task_prio_work_add(struct io_kiocb * req)2811 static void io_req_task_prio_work_add(struct io_kiocb *req)
2812 {
2813 struct io_uring_task *tctx = req->task->io_uring;
2814
2815 if (req->ctx->flags & IORING_SETUP_SQPOLL)
2816 __io_req_task_work_add(req, tctx, &tctx->prio_task_list);
2817 else
2818 __io_req_task_work_add(req, tctx, &tctx->task_list);
2819 }
2820
io_req_tw_post(struct io_kiocb * req,bool * locked)2821 static void io_req_tw_post(struct io_kiocb *req, bool *locked)
2822 {
2823 io_req_complete_post(req, req->cqe.res, req->cqe.flags);
2824 }
2825
io_req_tw_post_queue(struct io_kiocb * req,s32 res,u32 cflags)2826 static void io_req_tw_post_queue(struct io_kiocb *req, s32 res, u32 cflags)
2827 {
2828 req->cqe.res = res;
2829 req->cqe.flags = cflags;
2830 req->io_task_work.func = io_req_tw_post;
2831 io_req_task_work_add(req);
2832 }
2833
io_req_task_cancel(struct io_kiocb * req,bool * locked)2834 static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
2835 {
2836 /* not needed for normal modes, but SQPOLL depends on it */
2837 io_tw_lock(req->ctx, locked);
2838 io_req_complete_failed(req, req->cqe.res);
2839 }
2840
io_req_task_submit(struct io_kiocb * req,bool * locked)2841 static void io_req_task_submit(struct io_kiocb *req, bool *locked)
2842 {
2843 io_tw_lock(req->ctx, locked);
2844 /* req->task == current here, checking PF_EXITING is safe */
2845 if (likely(!(req->task->flags & PF_EXITING)))
2846 io_queue_sqe(req);
2847 else
2848 io_req_complete_failed(req, -EFAULT);
2849 }
2850
io_req_task_queue_fail(struct io_kiocb * req,int ret)2851 static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2852 {
2853 req->cqe.res = ret;
2854 req->io_task_work.func = io_req_task_cancel;
2855 io_req_task_work_add(req);
2856 }
2857
io_req_task_queue(struct io_kiocb * req)2858 static void io_req_task_queue(struct io_kiocb *req)
2859 {
2860 req->io_task_work.func = io_req_task_submit;
2861 io_req_task_work_add(req);
2862 }
2863
io_req_task_queue_reissue(struct io_kiocb * req)2864 static void io_req_task_queue_reissue(struct io_kiocb *req)
2865 {
2866 req->io_task_work.func = io_queue_iowq;
2867 io_req_task_work_add(req);
2868 }
2869
io_queue_next(struct io_kiocb * req)2870 static void io_queue_next(struct io_kiocb *req)
2871 {
2872 struct io_kiocb *nxt = io_req_find_next(req);
2873
2874 if (nxt)
2875 io_req_task_queue(nxt);
2876 }
2877
io_free_batch_list(struct io_ring_ctx * ctx,struct io_wq_work_node * node)2878 static void io_free_batch_list(struct io_ring_ctx *ctx,
2879 struct io_wq_work_node *node)
2880 __must_hold(&ctx->uring_lock)
2881 {
2882 struct task_struct *task = NULL;
2883 int task_refs = 0;
2884
2885 do {
2886 struct io_kiocb *req = container_of(node, struct io_kiocb,
2887 comp_list);
2888
2889 if (unlikely(req->flags & IO_REQ_CLEAN_SLOW_FLAGS)) {
2890 if (req->flags & REQ_F_REFCOUNT) {
2891 node = req->comp_list.next;
2892 if (!req_ref_put_and_test(req))
2893 continue;
2894 }
2895 if ((req->flags & REQ_F_POLLED) && req->apoll) {
2896 struct async_poll *apoll = req->apoll;
2897
2898 if (apoll->double_poll)
2899 kfree(apoll->double_poll);
2900 list_add(&apoll->poll.wait.entry,
2901 &ctx->apoll_cache);
2902 req->flags &= ~REQ_F_POLLED;
2903 }
2904 if (req->flags & IO_REQ_LINK_FLAGS)
2905 io_queue_next(req);
2906 if (unlikely(req->flags & IO_REQ_CLEAN_FLAGS))
2907 io_clean_op(req);
2908 }
2909 if (!(req->flags & REQ_F_FIXED_FILE))
2910 io_put_file(req->file);
2911
2912 io_req_put_rsrc_locked(req, ctx);
2913
2914 if (req->task != task) {
2915 if (task)
2916 io_put_task(task, task_refs);
2917 task = req->task;
2918 task_refs = 0;
2919 }
2920 task_refs++;
2921 node = req->comp_list.next;
2922 io_req_add_to_cache(req, ctx);
2923 } while (node);
2924
2925 if (task)
2926 io_put_task(task, task_refs);
2927 }
2928
__io_submit_flush_completions(struct io_ring_ctx * ctx)2929 static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
2930 __must_hold(&ctx->uring_lock)
2931 {
2932 struct io_wq_work_node *node, *prev;
2933 struct io_submit_state *state = &ctx->submit_state;
2934
2935 if (state->flush_cqes) {
2936 spin_lock(&ctx->completion_lock);
2937 wq_list_for_each(node, prev, &state->compl_reqs) {
2938 struct io_kiocb *req = container_of(node, struct io_kiocb,
2939 comp_list);
2940
2941 if (!(req->flags & REQ_F_CQE_SKIP))
2942 __io_fill_cqe_req(ctx, req);
2943 }
2944
2945 io_commit_cqring(ctx);
2946 spin_unlock(&ctx->completion_lock);
2947 io_cqring_ev_posted(ctx);
2948 state->flush_cqes = false;
2949 }
2950
2951 io_free_batch_list(ctx, state->compl_reqs.first);
2952 INIT_WQ_LIST(&state->compl_reqs);
2953 }
2954
2955 /*
2956 * Drop reference to request, return next in chain (if there is one) if this
2957 * was the last reference to this request.
2958 */
io_put_req_find_next(struct io_kiocb * req)2959 static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2960 {
2961 struct io_kiocb *nxt = NULL;
2962
2963 if (req_ref_put_and_test(req)) {
2964 if (unlikely(req->flags & IO_REQ_LINK_FLAGS))
2965 nxt = io_req_find_next(req);
2966 io_free_req(req);
2967 }
2968 return nxt;
2969 }
2970
io_put_req(struct io_kiocb * req)2971 static inline void io_put_req(struct io_kiocb *req)
2972 {
2973 if (req_ref_put_and_test(req)) {
2974 io_queue_next(req);
2975 io_free_req(req);
2976 }
2977 }
2978
io_cqring_events(struct io_ring_ctx * ctx)2979 static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2980 {
2981 /* See comment at the top of this file */
2982 smp_rmb();
2983 return __io_cqring_events(ctx);
2984 }
2985
io_sqring_entries(struct io_ring_ctx * ctx)2986 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2987 {
2988 struct io_rings *rings = ctx->rings;
2989
2990 /* make sure SQ entry isn't read before tail */
2991 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2992 }
2993
io_run_task_work(void)2994 static inline bool io_run_task_work(void)
2995 {
2996 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || task_work_pending(current)) {
2997 __set_current_state(TASK_RUNNING);
2998 clear_notify_signal();
2999 if (task_work_pending(current))
3000 task_work_run();
3001 return true;
3002 }
3003
3004 return false;
3005 }
3006
io_do_iopoll(struct io_ring_ctx * ctx,bool force_nonspin)3007 static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
3008 {
3009 struct io_wq_work_node *pos, *start, *prev;
3010 unsigned int poll_flags = BLK_POLL_NOSLEEP;
3011 DEFINE_IO_COMP_BATCH(iob);
3012 int nr_events = 0;
3013
3014 /*
3015 * Only spin for completions if we don't have multiple devices hanging
3016 * off our complete list.
3017 */
3018 if (ctx->poll_multi_queue || force_nonspin)
3019 poll_flags |= BLK_POLL_ONESHOT;
3020
3021 wq_list_for_each(pos, start, &ctx->iopoll_list) {
3022 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3023 struct kiocb *kiocb = &req->rw.kiocb;
3024 int ret;
3025
3026 /*
3027 * Move completed and retryable entries to our local lists.
3028 * If we find a request that requires polling, break out
3029 * and complete those lists first, if we have entries there.
3030 */
3031 if (READ_ONCE(req->iopoll_completed))
3032 break;
3033
3034 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
3035 if (unlikely(ret < 0))
3036 return ret;
3037 else if (ret)
3038 poll_flags |= BLK_POLL_ONESHOT;
3039
3040 /* iopoll may have completed current req */
3041 if (!rq_list_empty(iob.req_list) ||
3042 READ_ONCE(req->iopoll_completed))
3043 break;
3044 }
3045
3046 if (!rq_list_empty(iob.req_list))
3047 iob.complete(&iob);
3048 else if (!pos)
3049 return 0;
3050
3051 prev = start;
3052 wq_list_for_each_resume(pos, prev) {
3053 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
3054
3055 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
3056 if (!smp_load_acquire(&req->iopoll_completed))
3057 break;
3058 nr_events++;
3059 if (unlikely(req->flags & REQ_F_CQE_SKIP))
3060 continue;
3061
3062 req->cqe.flags = io_put_kbuf(req, 0);
3063 __io_fill_cqe_req(req->ctx, req);
3064 }
3065
3066 if (unlikely(!nr_events))
3067 return 0;
3068
3069 io_commit_cqring(ctx);
3070 io_cqring_ev_posted_iopoll(ctx);
3071 pos = start ? start->next : ctx->iopoll_list.first;
3072 wq_list_cut(&ctx->iopoll_list, prev, start);
3073 io_free_batch_list(ctx, pos);
3074 return nr_events;
3075 }
3076
3077 /*
3078 * We can't just wait for polled events to come to us, we have to actively
3079 * find and complete them.
3080 */
io_iopoll_try_reap_events(struct io_ring_ctx * ctx)3081 static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
3082 {
3083 if (!(ctx->flags & IORING_SETUP_IOPOLL))
3084 return;
3085
3086 mutex_lock(&ctx->uring_lock);
3087 while (!wq_list_empty(&ctx->iopoll_list)) {
3088 /* let it sleep and repeat later if can't complete a request */
3089 if (io_do_iopoll(ctx, true) == 0)
3090 break;
3091 /*
3092 * Ensure we allow local-to-the-cpu processing to take place,
3093 * in this case we need to ensure that we reap all events.
3094 * Also let task_work, etc. to progress by releasing the mutex
3095 */
3096 if (need_resched()) {
3097 mutex_unlock(&ctx->uring_lock);
3098 cond_resched();
3099 mutex_lock(&ctx->uring_lock);
3100 }
3101 }
3102 mutex_unlock(&ctx->uring_lock);
3103 }
3104
io_iopoll_check(struct io_ring_ctx * ctx,long min)3105 static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
3106 {
3107 unsigned int nr_events = 0;
3108 int ret = 0;
3109 unsigned long check_cq;
3110
3111 /*
3112 * Don't enter poll loop if we already have events pending.
3113 * If we do, we can potentially be spinning for commands that
3114 * already triggered a CQE (eg in error).
3115 */
3116 check_cq = READ_ONCE(ctx->check_cq);
3117 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
3118 __io_cqring_overflow_flush(ctx, false);
3119 if (io_cqring_events(ctx))
3120 return 0;
3121
3122 /*
3123 * Similarly do not spin if we have not informed the user of any
3124 * dropped CQE.
3125 */
3126 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
3127 return -EBADR;
3128
3129 do {
3130 /*
3131 * If a submit got punted to a workqueue, we can have the
3132 * application entering polling for a command before it gets
3133 * issued. That app will hold the uring_lock for the duration
3134 * of the poll right here, so we need to take a breather every
3135 * now and then to ensure that the issue has a chance to add
3136 * the poll to the issued list. Otherwise we can spin here
3137 * forever, while the workqueue is stuck trying to acquire the
3138 * very same mutex.
3139 */
3140 if (wq_list_empty(&ctx->iopoll_list)) {
3141 u32 tail = ctx->cached_cq_tail;
3142
3143 mutex_unlock(&ctx->uring_lock);
3144 io_run_task_work();
3145 mutex_lock(&ctx->uring_lock);
3146
3147 /* some requests don't go through iopoll_list */
3148 if (tail != ctx->cached_cq_tail ||
3149 wq_list_empty(&ctx->iopoll_list))
3150 break;
3151 }
3152 ret = io_do_iopoll(ctx, !min);
3153 if (ret < 0)
3154 break;
3155 nr_events += ret;
3156 ret = 0;
3157 } while (nr_events < min && !need_resched());
3158
3159 return ret;
3160 }
3161
kiocb_end_write(struct io_kiocb * req)3162 static void kiocb_end_write(struct io_kiocb *req)
3163 {
3164 /*
3165 * Tell lockdep we inherited freeze protection from submission
3166 * thread.
3167 */
3168 if (req->flags & REQ_F_ISREG) {
3169 struct super_block *sb = file_inode(req->file)->i_sb;
3170
3171 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
3172 sb_end_write(sb);
3173 }
3174 }
3175
3176 #ifdef CONFIG_BLOCK
io_resubmit_prep(struct io_kiocb * req)3177 static bool io_resubmit_prep(struct io_kiocb *req)
3178 {
3179 struct io_async_rw *rw = req->async_data;
3180
3181 if (!req_has_async_data(req))
3182 return !io_req_prep_async(req);
3183 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
3184 return true;
3185 }
3186
io_rw_should_reissue(struct io_kiocb * req)3187 static bool io_rw_should_reissue(struct io_kiocb *req)
3188 {
3189 umode_t mode = file_inode(req->file)->i_mode;
3190 struct io_ring_ctx *ctx = req->ctx;
3191
3192 if (!S_ISBLK(mode) && !S_ISREG(mode))
3193 return false;
3194 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
3195 !(ctx->flags & IORING_SETUP_IOPOLL)))
3196 return false;
3197 /*
3198 * If ref is dying, we might be running poll reap from the exit work.
3199 * Don't attempt to reissue from that path, just let it fail with
3200 * -EAGAIN.
3201 */
3202 if (percpu_ref_is_dying(&ctx->refs))
3203 return false;
3204 /*
3205 * Play it safe and assume not safe to re-import and reissue if we're
3206 * not in the original thread group (or in task context).
3207 */
3208 if (!same_thread_group(req->task, current) || !in_task())
3209 return false;
3210 return true;
3211 }
3212 #else
io_resubmit_prep(struct io_kiocb * req)3213 static bool io_resubmit_prep(struct io_kiocb *req)
3214 {
3215 return false;
3216 }
io_rw_should_reissue(struct io_kiocb * req)3217 static bool io_rw_should_reissue(struct io_kiocb *req)
3218 {
3219 return false;
3220 }
3221 #endif
3222
__io_complete_rw_common(struct io_kiocb * req,long res)3223 static bool __io_complete_rw_common(struct io_kiocb *req, long res)
3224 {
3225 if (req->rw.kiocb.ki_flags & IOCB_WRITE) {
3226 kiocb_end_write(req);
3227 fsnotify_modify(req->file);
3228 } else {
3229 fsnotify_access(req->file);
3230 }
3231 if (unlikely(res != req->cqe.res)) {
3232 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
3233 io_rw_should_reissue(req)) {
3234 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
3235 return true;
3236 }
3237 req_set_fail(req);
3238 req->cqe.res = res;
3239 }
3240 return false;
3241 }
3242
io_req_task_complete(struct io_kiocb * req,bool * locked)3243 static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
3244 {
3245 int res = req->cqe.res;
3246
3247 if (*locked) {
3248 io_req_complete_state(req, res, io_put_kbuf(req, 0));
3249 io_req_add_compl_list(req);
3250 } else {
3251 io_req_complete_post(req, res,
3252 io_put_kbuf(req, IO_URING_F_UNLOCKED));
3253 }
3254 }
3255
__io_complete_rw(struct io_kiocb * req,long res,unsigned int issue_flags)3256 static void __io_complete_rw(struct io_kiocb *req, long res,
3257 unsigned int issue_flags)
3258 {
3259 if (__io_complete_rw_common(req, res))
3260 return;
3261 __io_req_complete(req, issue_flags, req->cqe.res,
3262 io_put_kbuf(req, issue_flags));
3263 }
3264
io_complete_rw(struct kiocb * kiocb,long res)3265 static void io_complete_rw(struct kiocb *kiocb, long res)
3266 {
3267 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3268
3269 if (__io_complete_rw_common(req, res))
3270 return;
3271 req->cqe.res = res;
3272 req->io_task_work.func = io_req_task_complete;
3273 io_req_task_prio_work_add(req);
3274 }
3275
io_complete_rw_iopoll(struct kiocb * kiocb,long res)3276 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
3277 {
3278 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
3279
3280 if (kiocb->ki_flags & IOCB_WRITE)
3281 kiocb_end_write(req);
3282 if (unlikely(res != req->cqe.res)) {
3283 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3284 req->flags |= REQ_F_REISSUE | REQ_F_PARTIAL_IO;
3285 return;
3286 }
3287 req->cqe.res = res;
3288 }
3289
3290 /* order with io_iopoll_complete() checking ->iopoll_completed */
3291 smp_store_release(&req->iopoll_completed, 1);
3292 }
3293
3294 /*
3295 * After the iocb has been issued, it's safe to be found on the poll list.
3296 * Adding the kiocb to the list AFTER submission ensures that we don't
3297 * find it from a io_do_iopoll() thread before the issuer is done
3298 * accessing the kiocb cookie.
3299 */
io_iopoll_req_issued(struct io_kiocb * req,unsigned int issue_flags)3300 static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
3301 {
3302 struct io_ring_ctx *ctx = req->ctx;
3303 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
3304
3305 /* workqueue context doesn't hold uring_lock, grab it now */
3306 if (unlikely(needs_lock))
3307 mutex_lock(&ctx->uring_lock);
3308
3309 /*
3310 * Track whether we have multiple files in our lists. This will impact
3311 * how we do polling eventually, not spinning if we're on potentially
3312 * different devices.
3313 */
3314 if (wq_list_empty(&ctx->iopoll_list)) {
3315 ctx->poll_multi_queue = false;
3316 } else if (!ctx->poll_multi_queue) {
3317 struct io_kiocb *list_req;
3318
3319 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3320 comp_list);
3321 if (list_req->file != req->file)
3322 ctx->poll_multi_queue = true;
3323 }
3324
3325 /*
3326 * For fast devices, IO may have already completed. If it has, add
3327 * it to the front so we find it first.
3328 */
3329 if (READ_ONCE(req->iopoll_completed))
3330 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
3331 else
3332 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
3333
3334 if (unlikely(needs_lock)) {
3335 /*
3336 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3337 * in sq thread task context or in io worker task context. If
3338 * current task context is sq thread, we don't need to check
3339 * whether should wake up sq thread.
3340 */
3341 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3342 wq_has_sleeper(&ctx->sq_data->wait))
3343 wake_up(&ctx->sq_data->wait);
3344
3345 mutex_unlock(&ctx->uring_lock);
3346 }
3347 }
3348
io_bdev_nowait(struct block_device * bdev)3349 static bool io_bdev_nowait(struct block_device *bdev)
3350 {
3351 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
3352 }
3353
3354 /*
3355 * If we tracked the file through the SCM inflight mechanism, we could support
3356 * any file. For now, just ensure that anything potentially problematic is done
3357 * inline.
3358 */
__io_file_supports_nowait(struct file * file,umode_t mode)3359 static bool __io_file_supports_nowait(struct file *file, umode_t mode)
3360 {
3361 if (S_ISBLK(mode)) {
3362 if (IS_ENABLED(CONFIG_BLOCK) &&
3363 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
3364 return true;
3365 return false;
3366 }
3367 if (S_ISSOCK(mode))
3368 return true;
3369 if (S_ISREG(mode)) {
3370 if (IS_ENABLED(CONFIG_BLOCK) &&
3371 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
3372 file->f_op != &io_uring_fops)
3373 return true;
3374 return false;
3375 }
3376
3377 /* any ->read/write should understand O_NONBLOCK */
3378 if (file->f_flags & O_NONBLOCK)
3379 return true;
3380 return file->f_mode & FMODE_NOWAIT;
3381 }
3382
3383 /*
3384 * If we tracked the file through the SCM inflight mechanism, we could support
3385 * any file. For now, just ensure that anything potentially problematic is done
3386 * inline.
3387 */
io_file_get_flags(struct file * file)3388 static unsigned int io_file_get_flags(struct file *file)
3389 {
3390 umode_t mode = file_inode(file)->i_mode;
3391 unsigned int res = 0;
3392
3393 if (S_ISREG(mode))
3394 res |= FFS_ISREG;
3395 if (__io_file_supports_nowait(file, mode))
3396 res |= FFS_NOWAIT;
3397 if (io_file_need_scm(file))
3398 res |= FFS_SCM;
3399 return res;
3400 }
3401
io_file_supports_nowait(struct io_kiocb * req)3402 static inline bool io_file_supports_nowait(struct io_kiocb *req)
3403 {
3404 return req->flags & REQ_F_SUPPORT_NOWAIT;
3405 }
3406
io_prep_rw(struct io_kiocb * req,const struct io_uring_sqe * sqe)3407 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3408 {
3409 struct kiocb *kiocb = &req->rw.kiocb;
3410 unsigned ioprio;
3411 int ret;
3412
3413 kiocb->ki_pos = READ_ONCE(sqe->off);
3414 /* used for fixed read/write too - just read unconditionally */
3415 req->buf_index = READ_ONCE(sqe->buf_index);
3416
3417 if (req->opcode == IORING_OP_READ_FIXED ||
3418 req->opcode == IORING_OP_WRITE_FIXED) {
3419 struct io_ring_ctx *ctx = req->ctx;
3420 u16 index;
3421
3422 if (unlikely(req->buf_index >= ctx->nr_user_bufs))
3423 return -EFAULT;
3424 index = array_index_nospec(req->buf_index, ctx->nr_user_bufs);
3425 req->imu = ctx->user_bufs[index];
3426 io_req_set_rsrc_node(req, ctx, 0);
3427 }
3428
3429 ioprio = READ_ONCE(sqe->ioprio);
3430 if (ioprio) {
3431 ret = ioprio_check_cap(ioprio);
3432 if (ret)
3433 return ret;
3434
3435 kiocb->ki_ioprio = ioprio;
3436 } else {
3437 kiocb->ki_ioprio = get_current_ioprio();
3438 }
3439
3440 req->rw.addr = READ_ONCE(sqe->addr);
3441 req->rw.len = READ_ONCE(sqe->len);
3442 req->rw.flags = READ_ONCE(sqe->rw_flags);
3443 return 0;
3444 }
3445
io_rw_done(struct kiocb * kiocb,ssize_t ret)3446 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3447 {
3448 switch (ret) {
3449 case -EIOCBQUEUED:
3450 break;
3451 case -ERESTARTSYS:
3452 case -ERESTARTNOINTR:
3453 case -ERESTARTNOHAND:
3454 case -ERESTART_RESTARTBLOCK:
3455 /*
3456 * We can't just restart the syscall, since previously
3457 * submitted sqes may already be in progress. Just fail this
3458 * IO with EINTR.
3459 */
3460 ret = -EINTR;
3461 fallthrough;
3462 default:
3463 kiocb->ki_complete(kiocb, ret);
3464 }
3465 }
3466
io_kiocb_update_pos(struct io_kiocb * req)3467 static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
3468 {
3469 struct kiocb *kiocb = &req->rw.kiocb;
3470
3471 if (kiocb->ki_pos != -1)
3472 return &kiocb->ki_pos;
3473
3474 if (!(req->file->f_mode & FMODE_STREAM)) {
3475 req->flags |= REQ_F_CUR_POS;
3476 kiocb->ki_pos = req->file->f_pos;
3477 return &kiocb->ki_pos;
3478 }
3479
3480 kiocb->ki_pos = 0;
3481 return NULL;
3482 }
3483
kiocb_done(struct io_kiocb * req,ssize_t ret,unsigned int issue_flags)3484 static void kiocb_done(struct io_kiocb *req, ssize_t ret,
3485 unsigned int issue_flags)
3486 {
3487 struct io_async_rw *io = req->async_data;
3488
3489 /* add previously done IO, if any */
3490 if (req_has_async_data(req) && io->bytes_done > 0) {
3491 if (ret < 0)
3492 ret = io->bytes_done;
3493 else
3494 ret += io->bytes_done;
3495 }
3496
3497 if (req->flags & REQ_F_CUR_POS)
3498 req->file->f_pos = req->rw.kiocb.ki_pos;
3499 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
3500 __io_complete_rw(req, ret, issue_flags);
3501 else
3502 io_rw_done(&req->rw.kiocb, ret);
3503
3504 if (req->flags & REQ_F_REISSUE) {
3505 req->flags &= ~REQ_F_REISSUE;
3506 if (io_resubmit_prep(req))
3507 io_req_task_queue_reissue(req);
3508 else
3509 io_req_task_queue_fail(req, ret);
3510 }
3511 }
3512
__io_import_fixed(struct io_kiocb * req,int rw,struct iov_iter * iter,struct io_mapped_ubuf * imu)3513 static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3514 struct io_mapped_ubuf *imu)
3515 {
3516 size_t len = req->rw.len;
3517 u64 buf_end, buf_addr = req->rw.addr;
3518 size_t offset;
3519
3520 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
3521 return -EFAULT;
3522 /* not inside the mapped region */
3523 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
3524 return -EFAULT;
3525
3526 /*
3527 * May not be a start of buffer, set size appropriately
3528 * and advance us to the beginning.
3529 */
3530 offset = buf_addr - imu->ubuf;
3531 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
3532
3533 if (offset) {
3534 /*
3535 * Don't use iov_iter_advance() here, as it's really slow for
3536 * using the latter parts of a big fixed buffer - it iterates
3537 * over each segment manually. We can cheat a bit here, because
3538 * we know that:
3539 *
3540 * 1) it's a BVEC iter, we set it up
3541 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3542 * first and last bvec
3543 *
3544 * So just find our index, and adjust the iterator afterwards.
3545 * If the offset is within the first bvec (or the whole first
3546 * bvec, just use iov_iter_advance(). This makes it easier
3547 * since we can just skip the first segment, which may not
3548 * be PAGE_SIZE aligned.
3549 */
3550 const struct bio_vec *bvec = imu->bvec;
3551
3552 if (offset <= bvec->bv_len) {
3553 iov_iter_advance(iter, offset);
3554 } else {
3555 unsigned long seg_skip;
3556
3557 /* skip first vec */
3558 offset -= bvec->bv_len;
3559 seg_skip = 1 + (offset >> PAGE_SHIFT);
3560
3561 iter->bvec = bvec + seg_skip;
3562 iter->nr_segs -= seg_skip;
3563 iter->count -= bvec->bv_len + offset;
3564 iter->iov_offset = offset & ~PAGE_MASK;
3565 }
3566 }
3567
3568 return 0;
3569 }
3570
io_import_fixed(struct io_kiocb * req,int rw,struct iov_iter * iter,unsigned int issue_flags)3571 static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3572 unsigned int issue_flags)
3573 {
3574 if (WARN_ON_ONCE(!req->imu))
3575 return -EFAULT;
3576 return __io_import_fixed(req, rw, iter, req->imu);
3577 }
3578
io_buffer_add_list(struct io_ring_ctx * ctx,struct io_buffer_list * bl,unsigned int bgid)3579 static int io_buffer_add_list(struct io_ring_ctx *ctx,
3580 struct io_buffer_list *bl, unsigned int bgid)
3581 {
3582 bl->bgid = bgid;
3583 if (bgid < BGID_ARRAY)
3584 return 0;
3585
3586 return xa_err(xa_store(&ctx->io_bl_xa, bgid, bl, GFP_KERNEL));
3587 }
3588
io_provided_buffer_select(struct io_kiocb * req,size_t * len,struct io_buffer_list * bl)3589 static void __user *io_provided_buffer_select(struct io_kiocb *req, size_t *len,
3590 struct io_buffer_list *bl)
3591 {
3592 if (!list_empty(&bl->buf_list)) {
3593 struct io_buffer *kbuf;
3594
3595 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3596 list_del(&kbuf->list);
3597 if (*len > kbuf->len)
3598 *len = kbuf->len;
3599 req->flags |= REQ_F_BUFFER_SELECTED;
3600 req->kbuf = kbuf;
3601 req->buf_index = kbuf->bid;
3602 return u64_to_user_ptr(kbuf->addr);
3603 }
3604 return NULL;
3605 }
3606
io_ring_buffer_select(struct io_kiocb * req,size_t * len,struct io_buffer_list * bl,unsigned int issue_flags)3607 static void __user *io_ring_buffer_select(struct io_kiocb *req, size_t *len,
3608 struct io_buffer_list *bl,
3609 unsigned int issue_flags)
3610 {
3611 struct io_uring_buf_ring *br = bl->buf_ring;
3612 struct io_uring_buf *buf;
3613 __u16 head = bl->head;
3614
3615 if (unlikely(smp_load_acquire(&br->tail) == head))
3616 return NULL;
3617
3618 head &= bl->mask;
3619 if (head < IO_BUFFER_LIST_BUF_PER_PAGE) {
3620 buf = &br->bufs[head];
3621 } else {
3622 int off = head & (IO_BUFFER_LIST_BUF_PER_PAGE - 1);
3623 int index = head / IO_BUFFER_LIST_BUF_PER_PAGE;
3624 buf = page_address(bl->buf_pages[index]);
3625 buf += off;
3626 }
3627 if (*len > buf->len)
3628 *len = buf->len;
3629 req->flags |= REQ_F_BUFFER_RING;
3630 req->buf_list = bl;
3631 req->buf_index = buf->bid;
3632
3633 if (issue_flags & IO_URING_F_UNLOCKED || !file_can_poll(req->file)) {
3634 /*
3635 * If we came in unlocked, we have no choice but to consume the
3636 * buffer here. This does mean it'll be pinned until the IO
3637 * completes. But coming in unlocked means we're in io-wq
3638 * context, hence there should be no further retry. For the
3639 * locked case, the caller must ensure to call the commit when
3640 * the transfer completes (or if we get -EAGAIN and must poll
3641 * or retry).
3642 */
3643 req->buf_list = NULL;
3644 bl->head++;
3645 }
3646 return u64_to_user_ptr(buf->addr);
3647 }
3648
io_buffer_select(struct io_kiocb * req,size_t * len,unsigned int issue_flags)3649 static void __user *io_buffer_select(struct io_kiocb *req, size_t *len,
3650 unsigned int issue_flags)
3651 {
3652 struct io_ring_ctx *ctx = req->ctx;
3653 struct io_buffer_list *bl;
3654 void __user *ret = NULL;
3655
3656 io_ring_submit_lock(req->ctx, issue_flags);
3657
3658 bl = io_buffer_get_list(ctx, req->buf_index);
3659 if (likely(bl)) {
3660 if (bl->buf_nr_pages)
3661 ret = io_ring_buffer_select(req, len, bl, issue_flags);
3662 else
3663 ret = io_provided_buffer_select(req, len, bl);
3664 }
3665 io_ring_submit_unlock(req->ctx, issue_flags);
3666 return ret;
3667 }
3668
3669 #ifdef CONFIG_COMPAT
io_compat_import(struct io_kiocb * req,struct iovec * iov,unsigned int issue_flags)3670 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
3671 unsigned int issue_flags)
3672 {
3673 struct compat_iovec __user *uiov;
3674 compat_ssize_t clen;
3675 void __user *buf;
3676 size_t len;
3677
3678 uiov = u64_to_user_ptr(req->rw.addr);
3679 if (!access_ok(uiov, sizeof(*uiov)))
3680 return -EFAULT;
3681 if (__get_user(clen, &uiov->iov_len))
3682 return -EFAULT;
3683 if (clen < 0)
3684 return -EINVAL;
3685
3686 len = clen;
3687 buf = io_buffer_select(req, &len, issue_flags);
3688 if (!buf)
3689 return -ENOBUFS;
3690 req->rw.addr = (unsigned long) buf;
3691 iov[0].iov_base = buf;
3692 req->rw.len = iov[0].iov_len = (compat_size_t) len;
3693 return 0;
3694 }
3695 #endif
3696
__io_iov_buffer_select(struct io_kiocb * req,struct iovec * iov,unsigned int issue_flags)3697 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3698 unsigned int issue_flags)
3699 {
3700 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3701 void __user *buf;
3702 ssize_t len;
3703
3704 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3705 return -EFAULT;
3706
3707 len = iov[0].iov_len;
3708 if (len < 0)
3709 return -EINVAL;
3710 buf = io_buffer_select(req, &len, issue_flags);
3711 if (!buf)
3712 return -ENOBUFS;
3713 req->rw.addr = (unsigned long) buf;
3714 iov[0].iov_base = buf;
3715 req->rw.len = iov[0].iov_len = len;
3716 return 0;
3717 }
3718
io_iov_buffer_select(struct io_kiocb * req,struct iovec * iov,unsigned int issue_flags)3719 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
3720 unsigned int issue_flags)
3721 {
3722 if (req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING)) {
3723 iov[0].iov_base = u64_to_user_ptr(req->rw.addr);
3724 iov[0].iov_len = req->rw.len;
3725 return 0;
3726 }
3727 if (req->rw.len != 1)
3728 return -EINVAL;
3729
3730 #ifdef CONFIG_COMPAT
3731 if (req->ctx->compat)
3732 return io_compat_import(req, iov, issue_flags);
3733 #endif
3734
3735 return __io_iov_buffer_select(req, iov, issue_flags);
3736 }
3737
io_do_buffer_select(struct io_kiocb * req)3738 static inline bool io_do_buffer_select(struct io_kiocb *req)
3739 {
3740 if (!(req->flags & REQ_F_BUFFER_SELECT))
3741 return false;
3742 return !(req->flags & (REQ_F_BUFFER_SELECTED|REQ_F_BUFFER_RING));
3743 }
3744
__io_import_iovec(int rw,struct io_kiocb * req,struct io_rw_state * s,unsigned int issue_flags)3745 static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3746 struct io_rw_state *s,
3747 unsigned int issue_flags)
3748 {
3749 struct iov_iter *iter = &s->iter;
3750 u8 opcode = req->opcode;
3751 struct iovec *iovec;
3752 void __user *buf;
3753 size_t sqe_len;
3754 ssize_t ret;
3755
3756 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3757 ret = io_import_fixed(req, rw, iter, issue_flags);
3758 if (ret)
3759 return ERR_PTR(ret);
3760 return NULL;
3761 }
3762
3763 buf = u64_to_user_ptr(req->rw.addr);
3764 sqe_len = req->rw.len;
3765
3766 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
3767 if (io_do_buffer_select(req)) {
3768 buf = io_buffer_select(req, &sqe_len, issue_flags);
3769 if (!buf)
3770 return ERR_PTR(-ENOBUFS);
3771 req->rw.addr = (unsigned long) buf;
3772 req->rw.len = sqe_len;
3773 }
3774
3775 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
3776 if (ret)
3777 return ERR_PTR(ret);
3778 return NULL;
3779 }
3780
3781 iovec = s->fast_iov;
3782 if (req->flags & REQ_F_BUFFER_SELECT) {
3783 ret = io_iov_buffer_select(req, iovec, issue_flags);
3784 if (ret)
3785 return ERR_PTR(ret);
3786 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3787 return NULL;
3788 }
3789
3790 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
3791 req->ctx->compat);
3792 if (unlikely(ret < 0))
3793 return ERR_PTR(ret);
3794 return iovec;
3795 }
3796
io_import_iovec(int rw,struct io_kiocb * req,struct iovec ** iovec,struct io_rw_state * s,unsigned int issue_flags)3797 static inline int io_import_iovec(int rw, struct io_kiocb *req,
3798 struct iovec **iovec, struct io_rw_state *s,
3799 unsigned int issue_flags)
3800 {
3801 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3802 if (unlikely(IS_ERR(*iovec)))
3803 return PTR_ERR(*iovec);
3804
3805 iov_iter_save_state(&s->iter, &s->iter_state);
3806 return 0;
3807 }
3808
io_kiocb_ppos(struct kiocb * kiocb)3809 static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3810 {
3811 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3812 }
3813
3814 /*
3815 * For files that don't have ->read_iter() and ->write_iter(), handle them
3816 * by looping over ->read() or ->write() manually.
3817 */
loop_rw_iter(int rw,struct io_kiocb * req,struct iov_iter * iter)3818 static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3819 {
3820 struct kiocb *kiocb = &req->rw.kiocb;
3821 struct file *file = req->file;
3822 ssize_t ret = 0;
3823 loff_t *ppos;
3824
3825 /*
3826 * Don't support polled IO through this interface, and we can't
3827 * support non-blocking either. For the latter, this just causes
3828 * the kiocb to be handled from an async context.
3829 */
3830 if (kiocb->ki_flags & IOCB_HIPRI)
3831 return -EOPNOTSUPP;
3832 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3833 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
3834 return -EAGAIN;
3835
3836 ppos = io_kiocb_ppos(kiocb);
3837
3838 while (iov_iter_count(iter)) {
3839 struct iovec iovec;
3840 ssize_t nr;
3841
3842 if (!iov_iter_is_bvec(iter)) {
3843 iovec = iov_iter_iovec(iter);
3844 } else {
3845 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3846 iovec.iov_len = req->rw.len;
3847 }
3848
3849 if (rw == READ) {
3850 nr = file->f_op->read(file, iovec.iov_base,
3851 iovec.iov_len, ppos);
3852 } else {
3853 nr = file->f_op->write(file, iovec.iov_base,
3854 iovec.iov_len, ppos);
3855 }
3856
3857 if (nr < 0) {
3858 if (!ret)
3859 ret = nr;
3860 break;
3861 }
3862 ret += nr;
3863 if (!iov_iter_is_bvec(iter)) {
3864 iov_iter_advance(iter, nr);
3865 } else {
3866 req->rw.addr += nr;
3867 req->rw.len -= nr;
3868 if (!req->rw.len)
3869 break;
3870 }
3871 if (nr != iovec.iov_len)
3872 break;
3873 }
3874
3875 return ret;
3876 }
3877
io_req_map_rw(struct io_kiocb * req,const struct iovec * iovec,const struct iovec * fast_iov,struct iov_iter * iter)3878 static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3879 const struct iovec *fast_iov, struct iov_iter *iter)
3880 {
3881 struct io_async_rw *rw = req->async_data;
3882
3883 memcpy(&rw->s.iter, iter, sizeof(*iter));
3884 rw->free_iovec = iovec;
3885 rw->bytes_done = 0;
3886 /* can only be fixed buffers, no need to do anything */
3887 if (iov_iter_is_bvec(iter))
3888 return;
3889 if (!iovec) {
3890 unsigned iov_off = 0;
3891
3892 rw->s.iter.iov = rw->s.fast_iov;
3893 if (iter->iov != fast_iov) {
3894 iov_off = iter->iov - fast_iov;
3895 rw->s.iter.iov += iov_off;
3896 }
3897 if (rw->s.fast_iov != fast_iov)
3898 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
3899 sizeof(struct iovec) * iter->nr_segs);
3900 } else {
3901 req->flags |= REQ_F_NEED_CLEANUP;
3902 }
3903 }
3904
io_alloc_async_data(struct io_kiocb * req)3905 static inline bool io_alloc_async_data(struct io_kiocb *req)
3906 {
3907 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3908 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3909 if (req->async_data) {
3910 req->flags |= REQ_F_ASYNC_DATA;
3911 return false;
3912 }
3913 return true;
3914 }
3915
io_setup_async_rw(struct io_kiocb * req,const struct iovec * iovec,struct io_rw_state * s,bool force)3916 static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3917 struct io_rw_state *s, bool force)
3918 {
3919 if (!force && !io_op_defs[req->opcode].needs_async_setup)
3920 return 0;
3921 if (!req_has_async_data(req)) {
3922 struct io_async_rw *iorw;
3923
3924 if (io_alloc_async_data(req)) {
3925 kfree(iovec);
3926 return -ENOMEM;
3927 }
3928
3929 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
3930 iorw = req->async_data;
3931 /* we've copied and mapped the iter, ensure state is saved */
3932 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
3933 }
3934 return 0;
3935 }
3936
io_rw_prep_async(struct io_kiocb * req,int rw)3937 static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3938 {
3939 struct io_async_rw *iorw = req->async_data;
3940 struct iovec *iov;
3941 int ret;
3942
3943 /* submission path, ->uring_lock should already be taken */
3944 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
3945 if (unlikely(ret < 0))
3946 return ret;
3947
3948 iorw->bytes_done = 0;
3949 iorw->free_iovec = iov;
3950 if (iov)
3951 req->flags |= REQ_F_NEED_CLEANUP;
3952 return 0;
3953 }
3954
io_readv_prep_async(struct io_kiocb * req)3955 static int io_readv_prep_async(struct io_kiocb *req)
3956 {
3957 return io_rw_prep_async(req, READ);
3958 }
3959
io_writev_prep_async(struct io_kiocb * req)3960 static int io_writev_prep_async(struct io_kiocb *req)
3961 {
3962 return io_rw_prep_async(req, WRITE);
3963 }
3964
3965 /*
3966 * This is our waitqueue callback handler, registered through __folio_lock_async()
3967 * when we initially tried to do the IO with the iocb armed our waitqueue.
3968 * This gets called when the page is unlocked, and we generally expect that to
3969 * happen when the page IO is completed and the page is now uptodate. This will
3970 * queue a task_work based retry of the operation, attempting to copy the data
3971 * again. If the latter fails because the page was NOT uptodate, then we will
3972 * do a thread based blocking retry of the operation. That's the unexpected
3973 * slow path.
3974 */
io_async_buf_func(struct wait_queue_entry * wait,unsigned mode,int sync,void * arg)3975 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3976 int sync, void *arg)
3977 {
3978 struct wait_page_queue *wpq;
3979 struct io_kiocb *req = wait->private;
3980 struct wait_page_key *key = arg;
3981
3982 wpq = container_of(wait, struct wait_page_queue, wait);
3983
3984 if (!wake_page_match(wpq, key))
3985 return 0;
3986
3987 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3988 list_del_init(&wait->entry);
3989 io_req_task_queue(req);
3990 return 1;
3991 }
3992
3993 /*
3994 * This controls whether a given IO request should be armed for async page
3995 * based retry. If we return false here, the request is handed to the async
3996 * worker threads for retry. If we're doing buffered reads on a regular file,
3997 * we prepare a private wait_page_queue entry and retry the operation. This
3998 * will either succeed because the page is now uptodate and unlocked, or it
3999 * will register a callback when the page is unlocked at IO completion. Through
4000 * that callback, io_uring uses task_work to setup a retry of the operation.
4001 * That retry will attempt the buffered read again. The retry will generally
4002 * succeed, or in rare cases where it fails, we then fall back to using the
4003 * async worker threads for a blocking retry.
4004 */
io_rw_should_retry(struct io_kiocb * req)4005 static bool io_rw_should_retry(struct io_kiocb *req)
4006 {
4007 struct io_async_rw *rw = req->async_data;
4008 struct wait_page_queue *wait = &rw->wpq;
4009 struct kiocb *kiocb = &req->rw.kiocb;
4010
4011 /* never retry for NOWAIT, we just complete with -EAGAIN */
4012 if (req->flags & REQ_F_NOWAIT)
4013 return false;
4014
4015 /* Only for buffered IO */
4016 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
4017 return false;
4018
4019 /*
4020 * just use poll if we can, and don't attempt if the fs doesn't
4021 * support callback based unlocks
4022 */
4023 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
4024 return false;
4025
4026 wait->wait.func = io_async_buf_func;
4027 wait->wait.private = req;
4028 wait->wait.flags = 0;
4029 INIT_LIST_HEAD(&wait->wait.entry);
4030 kiocb->ki_flags |= IOCB_WAITQ;
4031 kiocb->ki_flags &= ~IOCB_NOWAIT;
4032 kiocb->ki_waitq = wait;
4033 return true;
4034 }
4035
io_iter_do_read(struct io_kiocb * req,struct iov_iter * iter)4036 static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
4037 {
4038 if (likely(req->file->f_op->read_iter))
4039 return call_read_iter(req->file, &req->rw.kiocb, iter);
4040 else if (req->file->f_op->read)
4041 return loop_rw_iter(READ, req, iter);
4042 else
4043 return -EINVAL;
4044 }
4045
need_read_all(struct io_kiocb * req)4046 static bool need_read_all(struct io_kiocb *req)
4047 {
4048 return req->flags & REQ_F_ISREG ||
4049 S_ISBLK(file_inode(req->file)->i_mode);
4050 }
4051
io_rw_init_file(struct io_kiocb * req,fmode_t mode)4052 static int io_rw_init_file(struct io_kiocb *req, fmode_t mode)
4053 {
4054 struct kiocb *kiocb = &req->rw.kiocb;
4055 struct io_ring_ctx *ctx = req->ctx;
4056 struct file *file = req->file;
4057 int ret;
4058
4059 if (unlikely(!file || !(file->f_mode & mode)))
4060 return -EBADF;
4061
4062 if (!io_req_ffs_set(req))
4063 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
4064
4065 kiocb->ki_flags = iocb_flags(file);
4066 ret = kiocb_set_rw_flags(kiocb, req->rw.flags);
4067 if (unlikely(ret))
4068 return ret;
4069
4070 /*
4071 * If the file is marked O_NONBLOCK, still allow retry for it if it
4072 * supports async. Otherwise it's impossible to use O_NONBLOCK files
4073 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
4074 */
4075 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
4076 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
4077 req->flags |= REQ_F_NOWAIT;
4078
4079 if (ctx->flags & IORING_SETUP_IOPOLL) {
4080 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
4081 return -EOPNOTSUPP;
4082
4083 kiocb->private = NULL;
4084 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
4085 kiocb->ki_complete = io_complete_rw_iopoll;
4086 req->iopoll_completed = 0;
4087 } else {
4088 if (kiocb->ki_flags & IOCB_HIPRI)
4089 return -EINVAL;
4090 kiocb->ki_complete = io_complete_rw;
4091 }
4092
4093 return 0;
4094 }
4095
io_read(struct io_kiocb * req,unsigned int issue_flags)4096 static int io_read(struct io_kiocb *req, unsigned int issue_flags)
4097 {
4098 struct io_rw_state __s, *s = &__s;
4099 struct iovec *iovec;
4100 struct kiocb *kiocb = &req->rw.kiocb;
4101 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4102 struct io_async_rw *rw;
4103 ssize_t ret, ret2;
4104 loff_t *ppos;
4105
4106 if (!req_has_async_data(req)) {
4107 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4108 if (unlikely(ret < 0))
4109 return ret;
4110 } else {
4111 rw = req->async_data;
4112 s = &rw->s;
4113
4114 /*
4115 * Safe and required to re-import if we're using provided
4116 * buffers, as we dropped the selected one before retry.
4117 */
4118 if (io_do_buffer_select(req)) {
4119 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
4120 if (unlikely(ret < 0))
4121 return ret;
4122 }
4123
4124 /*
4125 * We come here from an earlier attempt, restore our state to
4126 * match in case it doesn't. It's cheap enough that we don't
4127 * need to make this conditional.
4128 */
4129 iov_iter_restore(&s->iter, &s->iter_state);
4130 iovec = NULL;
4131 }
4132 ret = io_rw_init_file(req, FMODE_READ);
4133 if (unlikely(ret)) {
4134 kfree(iovec);
4135 return ret;
4136 }
4137 req->cqe.res = iov_iter_count(&s->iter);
4138
4139 if (force_nonblock) {
4140 /* If the file doesn't support async, just async punt */
4141 if (unlikely(!io_file_supports_nowait(req))) {
4142 ret = io_setup_async_rw(req, iovec, s, true);
4143 return ret ?: -EAGAIN;
4144 }
4145 kiocb->ki_flags |= IOCB_NOWAIT;
4146 } else {
4147 /* Ensure we clear previously set non-block flag */
4148 kiocb->ki_flags &= ~IOCB_NOWAIT;
4149 }
4150
4151 ppos = io_kiocb_update_pos(req);
4152
4153 ret = rw_verify_area(READ, req->file, ppos, req->cqe.res);
4154 if (unlikely(ret)) {
4155 kfree(iovec);
4156 return ret;
4157 }
4158
4159 ret = io_iter_do_read(req, &s->iter);
4160
4161 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
4162 req->flags &= ~REQ_F_REISSUE;
4163 /* if we can poll, just do that */
4164 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
4165 return -EAGAIN;
4166 /* IOPOLL retry should happen for io-wq threads */
4167 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
4168 goto done;
4169 /* no retry on NONBLOCK nor RWF_NOWAIT */
4170 if (req->flags & REQ_F_NOWAIT)
4171 goto done;
4172 ret = 0;
4173 } else if (ret == -EIOCBQUEUED) {
4174 goto out_free;
4175 } else if (ret == req->cqe.res || ret <= 0 || !force_nonblock ||
4176 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
4177 /* read all, failed, already did sync or don't want to retry */
4178 goto done;
4179 }
4180
4181 /*
4182 * Don't depend on the iter state matching what was consumed, or being
4183 * untouched in case of error. Restore it and we'll advance it
4184 * manually if we need to.
4185 */
4186 iov_iter_restore(&s->iter, &s->iter_state);
4187
4188 ret2 = io_setup_async_rw(req, iovec, s, true);
4189 if (ret2)
4190 return ret2;
4191
4192 iovec = NULL;
4193 rw = req->async_data;
4194 s = &rw->s;
4195 /*
4196 * Now use our persistent iterator and state, if we aren't already.
4197 * We've restored and mapped the iter to match.
4198 */
4199
4200 do {
4201 /*
4202 * We end up here because of a partial read, either from
4203 * above or inside this loop. Advance the iter by the bytes
4204 * that were consumed.
4205 */
4206 iov_iter_advance(&s->iter, ret);
4207 if (!iov_iter_count(&s->iter))
4208 break;
4209 rw->bytes_done += ret;
4210 iov_iter_save_state(&s->iter, &s->iter_state);
4211
4212 /* if we can retry, do so with the callbacks armed */
4213 if (!io_rw_should_retry(req)) {
4214 kiocb->ki_flags &= ~IOCB_WAITQ;
4215 return -EAGAIN;
4216 }
4217
4218 /*
4219 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
4220 * we get -EIOCBQUEUED, then we'll get a notification when the
4221 * desired page gets unlocked. We can also get a partial read
4222 * here, and if we do, then just retry at the new offset.
4223 */
4224 ret = io_iter_do_read(req, &s->iter);
4225 if (ret == -EIOCBQUEUED)
4226 return 0;
4227 /* we got some bytes, but not all. retry. */
4228 kiocb->ki_flags &= ~IOCB_WAITQ;
4229 iov_iter_restore(&s->iter, &s->iter_state);
4230 } while (ret > 0);
4231 done:
4232 kiocb_done(req, ret, issue_flags);
4233 out_free:
4234 /* it's faster to check here then delegate to kfree */
4235 if (iovec)
4236 kfree(iovec);
4237 return 0;
4238 }
4239
io_write(struct io_kiocb * req,unsigned int issue_flags)4240 static int io_write(struct io_kiocb *req, unsigned int issue_flags)
4241 {
4242 struct io_rw_state __s, *s = &__s;
4243 struct iovec *iovec;
4244 struct kiocb *kiocb = &req->rw.kiocb;
4245 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4246 ssize_t ret, ret2;
4247 loff_t *ppos;
4248
4249 if (!req_has_async_data(req)) {
4250 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
4251 if (unlikely(ret < 0))
4252 return ret;
4253 } else {
4254 struct io_async_rw *rw = req->async_data;
4255
4256 s = &rw->s;
4257 iov_iter_restore(&s->iter, &s->iter_state);
4258 iovec = NULL;
4259 }
4260 ret = io_rw_init_file(req, FMODE_WRITE);
4261 if (unlikely(ret)) {
4262 kfree(iovec);
4263 return ret;
4264 }
4265 req->cqe.res = iov_iter_count(&s->iter);
4266
4267 if (force_nonblock) {
4268 /* If the file doesn't support async, just async punt */
4269 if (unlikely(!io_file_supports_nowait(req)))
4270 goto copy_iov;
4271
4272 /* file path doesn't support NOWAIT for non-direct_IO */
4273 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
4274 (req->flags & REQ_F_ISREG))
4275 goto copy_iov;
4276
4277 kiocb->ki_flags |= IOCB_NOWAIT;
4278 } else {
4279 /* Ensure we clear previously set non-block flag */
4280 kiocb->ki_flags &= ~IOCB_NOWAIT;
4281 }
4282
4283 ppos = io_kiocb_update_pos(req);
4284
4285 ret = rw_verify_area(WRITE, req->file, ppos, req->cqe.res);
4286 if (unlikely(ret))
4287 goto out_free;
4288
4289 /*
4290 * Open-code file_start_write here to grab freeze protection,
4291 * which will be released by another thread in
4292 * io_complete_rw(). Fool lockdep by telling it the lock got
4293 * released so that it doesn't complain about the held lock when
4294 * we return to userspace.
4295 */
4296 if (req->flags & REQ_F_ISREG) {
4297 sb_start_write(file_inode(req->file)->i_sb);
4298 __sb_writers_release(file_inode(req->file)->i_sb,
4299 SB_FREEZE_WRITE);
4300 }
4301 kiocb->ki_flags |= IOCB_WRITE;
4302
4303 if (likely(req->file->f_op->write_iter))
4304 ret2 = call_write_iter(req->file, kiocb, &s->iter);
4305 else if (req->file->f_op->write)
4306 ret2 = loop_rw_iter(WRITE, req, &s->iter);
4307 else
4308 ret2 = -EINVAL;
4309
4310 if (req->flags & REQ_F_REISSUE) {
4311 req->flags &= ~REQ_F_REISSUE;
4312 ret2 = -EAGAIN;
4313 }
4314
4315 /*
4316 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4317 * retry them without IOCB_NOWAIT.
4318 */
4319 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4320 ret2 = -EAGAIN;
4321 /* no retry on NONBLOCK nor RWF_NOWAIT */
4322 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
4323 goto done;
4324 if (!force_nonblock || ret2 != -EAGAIN) {
4325 /* IOPOLL retry should happen for io-wq threads */
4326 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
4327 goto copy_iov;
4328 done:
4329 kiocb_done(req, ret2, issue_flags);
4330 } else {
4331 copy_iov:
4332 iov_iter_restore(&s->iter, &s->iter_state);
4333 ret = io_setup_async_rw(req, iovec, s, false);
4334 if (!ret) {
4335 if (kiocb->ki_flags & IOCB_WRITE)
4336 kiocb_end_write(req);
4337 return -EAGAIN;
4338 }
4339 return ret;
4340 }
4341 out_free:
4342 /* it's reportedly faster than delegating the null check to kfree() */
4343 if (iovec)
4344 kfree(iovec);
4345 return ret;
4346 }
4347
io_renameat_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)4348 static int io_renameat_prep(struct io_kiocb *req,
4349 const struct io_uring_sqe *sqe)
4350 {
4351 struct io_rename *ren = &req->rename;
4352 const char __user *oldf, *newf;
4353
4354 if (sqe->buf_index || sqe->splice_fd_in)
4355 return -EINVAL;
4356 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4357 return -EBADF;
4358
4359 ren->old_dfd = READ_ONCE(sqe->fd);
4360 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4361 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4362 ren->new_dfd = READ_ONCE(sqe->len);
4363 ren->flags = READ_ONCE(sqe->rename_flags);
4364
4365 ren->oldpath = getname(oldf);
4366 if (IS_ERR(ren->oldpath))
4367 return PTR_ERR(ren->oldpath);
4368
4369 ren->newpath = getname(newf);
4370 if (IS_ERR(ren->newpath)) {
4371 putname(ren->oldpath);
4372 return PTR_ERR(ren->newpath);
4373 }
4374
4375 req->flags |= REQ_F_NEED_CLEANUP;
4376 return 0;
4377 }
4378
io_renameat(struct io_kiocb * req,unsigned int issue_flags)4379 static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
4380 {
4381 struct io_rename *ren = &req->rename;
4382 int ret;
4383
4384 if (issue_flags & IO_URING_F_NONBLOCK)
4385 return -EAGAIN;
4386
4387 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4388 ren->newpath, ren->flags);
4389
4390 req->flags &= ~REQ_F_NEED_CLEANUP;
4391 io_req_complete(req, ret);
4392 return 0;
4393 }
4394
__io_xattr_finish(struct io_kiocb * req)4395 static inline void __io_xattr_finish(struct io_kiocb *req)
4396 {
4397 struct io_xattr *ix = &req->xattr;
4398
4399 if (ix->filename)
4400 putname(ix->filename);
4401
4402 kfree(ix->ctx.kname);
4403 kvfree(ix->ctx.kvalue);
4404 }
4405
io_xattr_finish(struct io_kiocb * req,int ret)4406 static void io_xattr_finish(struct io_kiocb *req, int ret)
4407 {
4408 req->flags &= ~REQ_F_NEED_CLEANUP;
4409
4410 __io_xattr_finish(req);
4411 io_req_complete(req, ret);
4412 }
4413
__io_getxattr_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)4414 static int __io_getxattr_prep(struct io_kiocb *req,
4415 const struct io_uring_sqe *sqe)
4416 {
4417 struct io_xattr *ix = &req->xattr;
4418 const char __user *name;
4419 int ret;
4420
4421 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4422 return -EBADF;
4423
4424 ix->filename = NULL;
4425 ix->ctx.kvalue = NULL;
4426 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4427 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4428 ix->ctx.size = READ_ONCE(sqe->len);
4429 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4430
4431 if (ix->ctx.flags)
4432 return -EINVAL;
4433
4434 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4435 if (!ix->ctx.kname)
4436 return -ENOMEM;
4437
4438 ret = strncpy_from_user(ix->ctx.kname->name, name,
4439 sizeof(ix->ctx.kname->name));
4440 if (!ret || ret == sizeof(ix->ctx.kname->name))
4441 ret = -ERANGE;
4442 if (ret < 0) {
4443 kfree(ix->ctx.kname);
4444 return ret;
4445 }
4446
4447 req->flags |= REQ_F_NEED_CLEANUP;
4448 return 0;
4449 }
4450
io_fgetxattr_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)4451 static int io_fgetxattr_prep(struct io_kiocb *req,
4452 const struct io_uring_sqe *sqe)
4453 {
4454 return __io_getxattr_prep(req, sqe);
4455 }
4456
io_getxattr_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)4457 static int io_getxattr_prep(struct io_kiocb *req,
4458 const struct io_uring_sqe *sqe)
4459 {
4460 struct io_xattr *ix = &req->xattr;
4461 const char __user *path;
4462 int ret;
4463
4464 ret = __io_getxattr_prep(req, sqe);
4465 if (ret)
4466 return ret;
4467
4468 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4469
4470 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4471 if (IS_ERR(ix->filename)) {
4472 ret = PTR_ERR(ix->filename);
4473 ix->filename = NULL;
4474 }
4475
4476 return ret;
4477 }
4478
io_fgetxattr(struct io_kiocb * req,unsigned int issue_flags)4479 static int io_fgetxattr(struct io_kiocb *req, unsigned int issue_flags)
4480 {
4481 struct io_xattr *ix = &req->xattr;
4482 int ret;
4483
4484 if (issue_flags & IO_URING_F_NONBLOCK)
4485 return -EAGAIN;
4486
4487 ret = do_getxattr(mnt_user_ns(req->file->f_path.mnt),
4488 req->file->f_path.dentry,
4489 &ix->ctx);
4490
4491 io_xattr_finish(req, ret);
4492 return 0;
4493 }
4494
io_getxattr(struct io_kiocb * req,unsigned int issue_flags)4495 static int io_getxattr(struct io_kiocb *req, unsigned int issue_flags)
4496 {
4497 struct io_xattr *ix = &req->xattr;
4498 unsigned int lookup_flags = LOOKUP_FOLLOW;
4499 struct path path;
4500 int ret;
4501
4502 if (issue_flags & IO_URING_F_NONBLOCK)
4503 return -EAGAIN;
4504
4505 retry:
4506 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4507 if (!ret) {
4508 ret = do_getxattr(mnt_user_ns(path.mnt),
4509 path.dentry,
4510 &ix->ctx);
4511
4512 path_put(&path);
4513 if (retry_estale(ret, lookup_flags)) {
4514 lookup_flags |= LOOKUP_REVAL;
4515 goto retry;
4516 }
4517 }
4518
4519 io_xattr_finish(req, ret);
4520 return 0;
4521 }
4522
__io_setxattr_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)4523 static int __io_setxattr_prep(struct io_kiocb *req,
4524 const struct io_uring_sqe *sqe)
4525 {
4526 struct io_xattr *ix = &req->xattr;
4527 const char __user *name;
4528 int ret;
4529
4530 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4531 return -EBADF;
4532
4533 ix->filename = NULL;
4534 name = u64_to_user_ptr(READ_ONCE(sqe->addr));
4535 ix->ctx.cvalue = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4536 ix->ctx.kvalue = NULL;
4537 ix->ctx.size = READ_ONCE(sqe->len);
4538 ix->ctx.flags = READ_ONCE(sqe->xattr_flags);
4539
4540 ix->ctx.kname = kmalloc(sizeof(*ix->ctx.kname), GFP_KERNEL);
4541 if (!ix->ctx.kname)
4542 return -ENOMEM;
4543
4544 ret = setxattr_copy(name, &ix->ctx);
4545 if (ret) {
4546 kfree(ix->ctx.kname);
4547 return ret;
4548 }
4549
4550 req->flags |= REQ_F_NEED_CLEANUP;
4551 return 0;
4552 }
4553
io_setxattr_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)4554 static int io_setxattr_prep(struct io_kiocb *req,
4555 const struct io_uring_sqe *sqe)
4556 {
4557 struct io_xattr *ix = &req->xattr;
4558 const char __user *path;
4559 int ret;
4560
4561 ret = __io_setxattr_prep(req, sqe);
4562 if (ret)
4563 return ret;
4564
4565 path = u64_to_user_ptr(READ_ONCE(sqe->addr3));
4566
4567 ix->filename = getname_flags(path, LOOKUP_FOLLOW, NULL);
4568 if (IS_ERR(ix->filename)) {
4569 ret = PTR_ERR(ix->filename);
4570 ix->filename = NULL;
4571 }
4572
4573 return ret;
4574 }
4575
io_fsetxattr_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)4576 static int io_fsetxattr_prep(struct io_kiocb *req,
4577 const struct io_uring_sqe *sqe)
4578 {
4579 return __io_setxattr_prep(req, sqe);
4580 }
4581
__io_setxattr(struct io_kiocb * req,unsigned int issue_flags,struct path * path)4582 static int __io_setxattr(struct io_kiocb *req, unsigned int issue_flags,
4583 struct path *path)
4584 {
4585 struct io_xattr *ix = &req->xattr;
4586 int ret;
4587
4588 ret = mnt_want_write(path->mnt);
4589 if (!ret) {
4590 ret = do_setxattr(mnt_user_ns(path->mnt), path->dentry, &ix->ctx);
4591 mnt_drop_write(path->mnt);
4592 }
4593
4594 return ret;
4595 }
4596
io_fsetxattr(struct io_kiocb * req,unsigned int issue_flags)4597 static int io_fsetxattr(struct io_kiocb *req, unsigned int issue_flags)
4598 {
4599 int ret;
4600
4601 if (issue_flags & IO_URING_F_NONBLOCK)
4602 return -EAGAIN;
4603
4604 ret = __io_setxattr(req, issue_flags, &req->file->f_path);
4605 io_xattr_finish(req, ret);
4606
4607 return 0;
4608 }
4609
io_setxattr(struct io_kiocb * req,unsigned int issue_flags)4610 static int io_setxattr(struct io_kiocb *req, unsigned int issue_flags)
4611 {
4612 struct io_xattr *ix = &req->xattr;
4613 unsigned int lookup_flags = LOOKUP_FOLLOW;
4614 struct path path;
4615 int ret;
4616
4617 if (issue_flags & IO_URING_F_NONBLOCK)
4618 return -EAGAIN;
4619
4620 retry:
4621 ret = filename_lookup(AT_FDCWD, ix->filename, lookup_flags, &path, NULL);
4622 if (!ret) {
4623 ret = __io_setxattr(req, issue_flags, &path);
4624 path_put(&path);
4625 if (retry_estale(ret, lookup_flags)) {
4626 lookup_flags |= LOOKUP_REVAL;
4627 goto retry;
4628 }
4629 }
4630
4631 io_xattr_finish(req, ret);
4632 return 0;
4633 }
4634
io_unlinkat_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)4635 static int io_unlinkat_prep(struct io_kiocb *req,
4636 const struct io_uring_sqe *sqe)
4637 {
4638 struct io_unlink *un = &req->unlink;
4639 const char __user *fname;
4640
4641 if (sqe->off || sqe->len || sqe->buf_index || sqe->splice_fd_in)
4642 return -EINVAL;
4643 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4644 return -EBADF;
4645
4646 un->dfd = READ_ONCE(sqe->fd);
4647
4648 un->flags = READ_ONCE(sqe->unlink_flags);
4649 if (un->flags & ~AT_REMOVEDIR)
4650 return -EINVAL;
4651
4652 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4653 un->filename = getname(fname);
4654 if (IS_ERR(un->filename))
4655 return PTR_ERR(un->filename);
4656
4657 req->flags |= REQ_F_NEED_CLEANUP;
4658 return 0;
4659 }
4660
io_unlinkat(struct io_kiocb * req,unsigned int issue_flags)4661 static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
4662 {
4663 struct io_unlink *un = &req->unlink;
4664 int ret;
4665
4666 if (issue_flags & IO_URING_F_NONBLOCK)
4667 return -EAGAIN;
4668
4669 if (un->flags & AT_REMOVEDIR)
4670 ret = do_rmdir(un->dfd, un->filename);
4671 else
4672 ret = do_unlinkat(un->dfd, un->filename);
4673
4674 req->flags &= ~REQ_F_NEED_CLEANUP;
4675 io_req_complete(req, ret);
4676 return 0;
4677 }
4678
io_mkdirat_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)4679 static int io_mkdirat_prep(struct io_kiocb *req,
4680 const struct io_uring_sqe *sqe)
4681 {
4682 struct io_mkdir *mkd = &req->mkdir;
4683 const char __user *fname;
4684
4685 if (sqe->off || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4686 return -EINVAL;
4687 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4688 return -EBADF;
4689
4690 mkd->dfd = READ_ONCE(sqe->fd);
4691 mkd->mode = READ_ONCE(sqe->len);
4692
4693 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4694 mkd->filename = getname(fname);
4695 if (IS_ERR(mkd->filename))
4696 return PTR_ERR(mkd->filename);
4697
4698 req->flags |= REQ_F_NEED_CLEANUP;
4699 return 0;
4700 }
4701
io_mkdirat(struct io_kiocb * req,unsigned int issue_flags)4702 static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
4703 {
4704 struct io_mkdir *mkd = &req->mkdir;
4705 int ret;
4706
4707 if (issue_flags & IO_URING_F_NONBLOCK)
4708 return -EAGAIN;
4709
4710 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4711
4712 req->flags &= ~REQ_F_NEED_CLEANUP;
4713 io_req_complete(req, ret);
4714 return 0;
4715 }
4716
io_symlinkat_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)4717 static int io_symlinkat_prep(struct io_kiocb *req,
4718 const struct io_uring_sqe *sqe)
4719 {
4720 struct io_symlink *sl = &req->symlink;
4721 const char __user *oldpath, *newpath;
4722
4723 if (sqe->len || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4724 return -EINVAL;
4725 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4726 return -EBADF;
4727
4728 sl->new_dfd = READ_ONCE(sqe->fd);
4729 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4730 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4731
4732 sl->oldpath = getname(oldpath);
4733 if (IS_ERR(sl->oldpath))
4734 return PTR_ERR(sl->oldpath);
4735
4736 sl->newpath = getname(newpath);
4737 if (IS_ERR(sl->newpath)) {
4738 putname(sl->oldpath);
4739 return PTR_ERR(sl->newpath);
4740 }
4741
4742 req->flags |= REQ_F_NEED_CLEANUP;
4743 return 0;
4744 }
4745
io_symlinkat(struct io_kiocb * req,unsigned int issue_flags)4746 static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
4747 {
4748 struct io_symlink *sl = &req->symlink;
4749 int ret;
4750
4751 if (issue_flags & IO_URING_F_NONBLOCK)
4752 return -EAGAIN;
4753
4754 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4755
4756 req->flags &= ~REQ_F_NEED_CLEANUP;
4757 io_req_complete(req, ret);
4758 return 0;
4759 }
4760
io_linkat_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)4761 static int io_linkat_prep(struct io_kiocb *req,
4762 const struct io_uring_sqe *sqe)
4763 {
4764 struct io_hardlink *lnk = &req->hardlink;
4765 const char __user *oldf, *newf;
4766
4767 if (sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4768 return -EINVAL;
4769 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4770 return -EBADF;
4771
4772 lnk->old_dfd = READ_ONCE(sqe->fd);
4773 lnk->new_dfd = READ_ONCE(sqe->len);
4774 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4775 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4776 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4777
4778 lnk->oldpath = getname(oldf);
4779 if (IS_ERR(lnk->oldpath))
4780 return PTR_ERR(lnk->oldpath);
4781
4782 lnk->newpath = getname(newf);
4783 if (IS_ERR(lnk->newpath)) {
4784 putname(lnk->oldpath);
4785 return PTR_ERR(lnk->newpath);
4786 }
4787
4788 req->flags |= REQ_F_NEED_CLEANUP;
4789 return 0;
4790 }
4791
io_linkat(struct io_kiocb * req,unsigned int issue_flags)4792 static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
4793 {
4794 struct io_hardlink *lnk = &req->hardlink;
4795 int ret;
4796
4797 if (issue_flags & IO_URING_F_NONBLOCK)
4798 return -EAGAIN;
4799
4800 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4801 lnk->newpath, lnk->flags);
4802
4803 req->flags &= ~REQ_F_NEED_CLEANUP;
4804 io_req_complete(req, ret);
4805 return 0;
4806 }
4807
io_uring_cmd_work(struct io_kiocb * req,bool * locked)4808 static void io_uring_cmd_work(struct io_kiocb *req, bool *locked)
4809 {
4810 req->uring_cmd.task_work_cb(&req->uring_cmd);
4811 }
4812
io_uring_cmd_complete_in_task(struct io_uring_cmd * ioucmd,void (* task_work_cb)(struct io_uring_cmd *))4813 void io_uring_cmd_complete_in_task(struct io_uring_cmd *ioucmd,
4814 void (*task_work_cb)(struct io_uring_cmd *))
4815 {
4816 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
4817
4818 req->uring_cmd.task_work_cb = task_work_cb;
4819 req->io_task_work.func = io_uring_cmd_work;
4820 io_req_task_work_add(req);
4821 }
4822 EXPORT_SYMBOL_GPL(io_uring_cmd_complete_in_task);
4823
io_req_set_cqe32_extra(struct io_kiocb * req,u64 extra1,u64 extra2)4824 static inline void io_req_set_cqe32_extra(struct io_kiocb *req,
4825 u64 extra1, u64 extra2)
4826 {
4827 req->extra1 = extra1;
4828 req->extra2 = extra2;
4829 req->flags |= REQ_F_CQE32_INIT;
4830 }
4831
4832 /*
4833 * Called by consumers of io_uring_cmd, if they originally returned
4834 * -EIOCBQUEUED upon receiving the command.
4835 */
io_uring_cmd_done(struct io_uring_cmd * ioucmd,ssize_t ret,ssize_t res2)4836 void io_uring_cmd_done(struct io_uring_cmd *ioucmd, ssize_t ret, ssize_t res2)
4837 {
4838 struct io_kiocb *req = container_of(ioucmd, struct io_kiocb, uring_cmd);
4839
4840 if (ret < 0)
4841 req_set_fail(req);
4842
4843 if (req->ctx->flags & IORING_SETUP_CQE32)
4844 io_req_set_cqe32_extra(req, res2, 0);
4845 io_req_complete(req, ret);
4846 }
4847 EXPORT_SYMBOL_GPL(io_uring_cmd_done);
4848
io_uring_cmd_prep_async(struct io_kiocb * req)4849 static int io_uring_cmd_prep_async(struct io_kiocb *req)
4850 {
4851 size_t cmd_size;
4852
4853 cmd_size = uring_cmd_pdu_size(req->ctx->flags & IORING_SETUP_SQE128);
4854
4855 memcpy(req->async_data, req->uring_cmd.cmd, cmd_size);
4856 return 0;
4857 }
4858
io_uring_cmd_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)4859 static int io_uring_cmd_prep(struct io_kiocb *req,
4860 const struct io_uring_sqe *sqe)
4861 {
4862 struct io_uring_cmd *ioucmd = &req->uring_cmd;
4863
4864 if (sqe->rw_flags || sqe->__pad1)
4865 return -EINVAL;
4866 ioucmd->cmd = sqe->cmd;
4867 ioucmd->cmd_op = READ_ONCE(sqe->cmd_op);
4868 return 0;
4869 }
4870
io_uring_cmd(struct io_kiocb * req,unsigned int issue_flags)4871 static int io_uring_cmd(struct io_kiocb *req, unsigned int issue_flags)
4872 {
4873 struct io_uring_cmd *ioucmd = &req->uring_cmd;
4874 struct io_ring_ctx *ctx = req->ctx;
4875 struct file *file = req->file;
4876 int ret;
4877
4878 if (!req->file->f_op->uring_cmd)
4879 return -EOPNOTSUPP;
4880
4881 ret = security_uring_cmd(ioucmd);
4882 if (ret)
4883 return ret;
4884
4885 if (ctx->flags & IORING_SETUP_SQE128)
4886 issue_flags |= IO_URING_F_SQE128;
4887 if (ctx->flags & IORING_SETUP_CQE32)
4888 issue_flags |= IO_URING_F_CQE32;
4889 if (ctx->flags & IORING_SETUP_IOPOLL)
4890 issue_flags |= IO_URING_F_IOPOLL;
4891
4892 if (req_has_async_data(req))
4893 ioucmd->cmd = req->async_data;
4894
4895 ret = file->f_op->uring_cmd(ioucmd, issue_flags);
4896 if (ret == -EAGAIN) {
4897 if (!req_has_async_data(req)) {
4898 if (io_alloc_async_data(req))
4899 return -ENOMEM;
4900 io_uring_cmd_prep_async(req);
4901 }
4902 return -EAGAIN;
4903 }
4904
4905 if (ret != -EIOCBQUEUED)
4906 io_uring_cmd_done(ioucmd, ret, 0);
4907 return 0;
4908 }
4909
__io_splice_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)4910 static int __io_splice_prep(struct io_kiocb *req,
4911 const struct io_uring_sqe *sqe)
4912 {
4913 struct io_splice *sp = &req->splice;
4914 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
4915
4916 sp->len = READ_ONCE(sqe->len);
4917 sp->flags = READ_ONCE(sqe->splice_flags);
4918 if (unlikely(sp->flags & ~valid_flags))
4919 return -EINVAL;
4920 sp->splice_fd_in = READ_ONCE(sqe->splice_fd_in);
4921 return 0;
4922 }
4923
io_tee_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)4924 static int io_tee_prep(struct io_kiocb *req,
4925 const struct io_uring_sqe *sqe)
4926 {
4927 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4928 return -EINVAL;
4929 return __io_splice_prep(req, sqe);
4930 }
4931
io_tee(struct io_kiocb * req,unsigned int issue_flags)4932 static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
4933 {
4934 struct io_splice *sp = &req->splice;
4935 struct file *out = sp->file_out;
4936 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4937 struct file *in;
4938 long ret = 0;
4939
4940 if (issue_flags & IO_URING_F_NONBLOCK)
4941 return -EAGAIN;
4942
4943 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4944 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
4945 else
4946 in = io_file_get_normal(req, sp->splice_fd_in);
4947 if (!in) {
4948 ret = -EBADF;
4949 goto done;
4950 }
4951
4952 if (sp->len)
4953 ret = do_tee(in, out, sp->len, flags);
4954
4955 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4956 io_put_file(in);
4957 done:
4958 if (ret != sp->len)
4959 req_set_fail(req);
4960 __io_req_complete(req, 0, ret, 0);
4961 return 0;
4962 }
4963
io_splice_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)4964 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4965 {
4966 struct io_splice *sp = &req->splice;
4967
4968 sp->off_in = READ_ONCE(sqe->splice_off_in);
4969 sp->off_out = READ_ONCE(sqe->off);
4970 return __io_splice_prep(req, sqe);
4971 }
4972
io_splice(struct io_kiocb * req,unsigned int issue_flags)4973 static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
4974 {
4975 struct io_splice *sp = &req->splice;
4976 struct file *out = sp->file_out;
4977 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4978 loff_t *poff_in, *poff_out;
4979 struct file *in;
4980 long ret = 0;
4981
4982 if (issue_flags & IO_URING_F_NONBLOCK)
4983 return -EAGAIN;
4984
4985 if (sp->flags & SPLICE_F_FD_IN_FIXED)
4986 in = io_file_get_fixed(req, sp->splice_fd_in, issue_flags);
4987 else
4988 in = io_file_get_normal(req, sp->splice_fd_in);
4989 if (!in) {
4990 ret = -EBADF;
4991 goto done;
4992 }
4993
4994 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4995 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
4996
4997 if (sp->len)
4998 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
4999
5000 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
5001 io_put_file(in);
5002 done:
5003 if (ret != sp->len)
5004 req_set_fail(req);
5005 __io_req_complete(req, 0, ret, 0);
5006 return 0;
5007 }
5008
io_nop_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)5009 static int io_nop_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5010 {
5011 return 0;
5012 }
5013
5014 /*
5015 * IORING_OP_NOP just posts a completion event, nothing else.
5016 */
io_nop(struct io_kiocb * req,unsigned int issue_flags)5017 static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
5018 {
5019 __io_req_complete(req, issue_flags, 0, 0);
5020 return 0;
5021 }
5022
io_msg_ring_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)5023 static int io_msg_ring_prep(struct io_kiocb *req,
5024 const struct io_uring_sqe *sqe)
5025 {
5026 if (unlikely(sqe->addr || sqe->rw_flags || sqe->splice_fd_in ||
5027 sqe->buf_index || sqe->personality))
5028 return -EINVAL;
5029
5030 req->msg.user_data = READ_ONCE(sqe->off);
5031 req->msg.len = READ_ONCE(sqe->len);
5032 return 0;
5033 }
5034
io_msg_ring(struct io_kiocb * req,unsigned int issue_flags)5035 static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
5036 {
5037 struct io_ring_ctx *target_ctx;
5038 struct io_msg *msg = &req->msg;
5039 bool filled;
5040 int ret;
5041
5042 ret = -EBADFD;
5043 if (req->file->f_op != &io_uring_fops)
5044 goto done;
5045
5046 ret = -EOVERFLOW;
5047 target_ctx = req->file->private_data;
5048
5049 spin_lock(&target_ctx->completion_lock);
5050 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len, 0);
5051 io_commit_cqring(target_ctx);
5052 spin_unlock(&target_ctx->completion_lock);
5053
5054 if (filled) {
5055 io_cqring_ev_posted(target_ctx);
5056 ret = 0;
5057 }
5058
5059 done:
5060 if (ret < 0)
5061 req_set_fail(req);
5062 __io_req_complete(req, issue_flags, ret, 0);
5063 /* put file to avoid an attempt to IOPOLL the req */
5064 io_put_file(req->file);
5065 req->file = NULL;
5066 return 0;
5067 }
5068
io_fsync_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)5069 static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5070 {
5071 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5072 return -EINVAL;
5073
5074 req->sync.flags = READ_ONCE(sqe->fsync_flags);
5075 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
5076 return -EINVAL;
5077
5078 req->sync.off = READ_ONCE(sqe->off);
5079 req->sync.len = READ_ONCE(sqe->len);
5080 return 0;
5081 }
5082
io_fsync(struct io_kiocb * req,unsigned int issue_flags)5083 static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
5084 {
5085 loff_t end = req->sync.off + req->sync.len;
5086 int ret;
5087
5088 /* fsync always requires a blocking context */
5089 if (issue_flags & IO_URING_F_NONBLOCK)
5090 return -EAGAIN;
5091
5092 ret = vfs_fsync_range(req->file, req->sync.off,
5093 end > 0 ? end : LLONG_MAX,
5094 req->sync.flags & IORING_FSYNC_DATASYNC);
5095 io_req_complete(req, ret);
5096 return 0;
5097 }
5098
io_fallocate_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)5099 static int io_fallocate_prep(struct io_kiocb *req,
5100 const struct io_uring_sqe *sqe)
5101 {
5102 if (sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
5103 return -EINVAL;
5104
5105 req->sync.off = READ_ONCE(sqe->off);
5106 req->sync.len = READ_ONCE(sqe->addr);
5107 req->sync.mode = READ_ONCE(sqe->len);
5108 return 0;
5109 }
5110
io_fallocate(struct io_kiocb * req,unsigned int issue_flags)5111 static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
5112 {
5113 int ret;
5114
5115 /* fallocate always requiring blocking context */
5116 if (issue_flags & IO_URING_F_NONBLOCK)
5117 return -EAGAIN;
5118 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
5119 req->sync.len);
5120 if (ret >= 0)
5121 fsnotify_modify(req->file);
5122 io_req_complete(req, ret);
5123 return 0;
5124 }
5125
__io_openat_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)5126 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5127 {
5128 const char __user *fname;
5129 int ret;
5130
5131 if (unlikely(sqe->buf_index))
5132 return -EINVAL;
5133 if (unlikely(req->flags & REQ_F_FIXED_FILE))
5134 return -EBADF;
5135
5136 /* open.how should be already initialised */
5137 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
5138 req->open.how.flags |= O_LARGEFILE;
5139
5140 req->open.dfd = READ_ONCE(sqe->fd);
5141 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
5142 req->open.filename = getname(fname);
5143 if (IS_ERR(req->open.filename)) {
5144 ret = PTR_ERR(req->open.filename);
5145 req->open.filename = NULL;
5146 return ret;
5147 }
5148
5149 req->open.file_slot = READ_ONCE(sqe->file_index);
5150 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
5151 return -EINVAL;
5152
5153 req->open.nofile = rlimit(RLIMIT_NOFILE);
5154 req->flags |= REQ_F_NEED_CLEANUP;
5155 return 0;
5156 }
5157
io_openat_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)5158 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5159 {
5160 u64 mode = READ_ONCE(sqe->len);
5161 u64 flags = READ_ONCE(sqe->open_flags);
5162
5163 req->open.how = build_open_how(flags, mode);
5164 return __io_openat_prep(req, sqe);
5165 }
5166
io_openat2_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)5167 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5168 {
5169 struct open_how __user *how;
5170 size_t len;
5171 int ret;
5172
5173 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5174 len = READ_ONCE(sqe->len);
5175 if (len < OPEN_HOW_SIZE_VER0)
5176 return -EINVAL;
5177
5178 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
5179 len);
5180 if (ret)
5181 return ret;
5182
5183 return __io_openat_prep(req, sqe);
5184 }
5185
io_file_bitmap_get(struct io_ring_ctx * ctx)5186 static int io_file_bitmap_get(struct io_ring_ctx *ctx)
5187 {
5188 struct io_file_table *table = &ctx->file_table;
5189 unsigned long nr = ctx->nr_user_files;
5190 int ret;
5191
5192 do {
5193 ret = find_next_zero_bit(table->bitmap, nr, table->alloc_hint);
5194 if (ret != nr)
5195 return ret;
5196
5197 if (!table->alloc_hint)
5198 break;
5199
5200 nr = table->alloc_hint;
5201 table->alloc_hint = 0;
5202 } while (1);
5203
5204 return -ENFILE;
5205 }
5206
5207 /*
5208 * Note when io_fixed_fd_install() returns error value, it will ensure
5209 * fput() is called correspondingly.
5210 */
io_fixed_fd_install(struct io_kiocb * req,unsigned int issue_flags,struct file * file,unsigned int file_slot)5211 static int io_fixed_fd_install(struct io_kiocb *req, unsigned int issue_flags,
5212 struct file *file, unsigned int file_slot)
5213 {
5214 bool alloc_slot = file_slot == IORING_FILE_INDEX_ALLOC;
5215 struct io_ring_ctx *ctx = req->ctx;
5216 int ret;
5217
5218 io_ring_submit_lock(ctx, issue_flags);
5219
5220 if (alloc_slot) {
5221 ret = io_file_bitmap_get(ctx);
5222 if (unlikely(ret < 0))
5223 goto err;
5224 file_slot = ret;
5225 } else {
5226 file_slot--;
5227 }
5228
5229 ret = io_install_fixed_file(req, file, issue_flags, file_slot);
5230 if (!ret && alloc_slot)
5231 ret = file_slot;
5232 err:
5233 io_ring_submit_unlock(ctx, issue_flags);
5234 if (unlikely(ret < 0))
5235 fput(file);
5236 return ret;
5237 }
5238
io_openat2(struct io_kiocb * req,unsigned int issue_flags)5239 static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
5240 {
5241 struct open_flags op;
5242 struct file *file;
5243 bool resolve_nonblock, nonblock_set;
5244 bool fixed = !!req->open.file_slot;
5245 int ret;
5246
5247 ret = build_open_flags(&req->open.how, &op);
5248 if (ret)
5249 goto err;
5250 nonblock_set = op.open_flag & O_NONBLOCK;
5251 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
5252 if (issue_flags & IO_URING_F_NONBLOCK) {
5253 /*
5254 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
5255 * it'll always -EAGAIN
5256 */
5257 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
5258 return -EAGAIN;
5259 op.lookup_flags |= LOOKUP_CACHED;
5260 op.open_flag |= O_NONBLOCK;
5261 }
5262
5263 if (!fixed) {
5264 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
5265 if (ret < 0)
5266 goto err;
5267 }
5268
5269 file = do_filp_open(req->open.dfd, req->open.filename, &op);
5270 if (IS_ERR(file)) {
5271 /*
5272 * We could hang on to this 'fd' on retrying, but seems like
5273 * marginal gain for something that is now known to be a slower
5274 * path. So just put it, and we'll get a new one when we retry.
5275 */
5276 if (!fixed)
5277 put_unused_fd(ret);
5278
5279 ret = PTR_ERR(file);
5280 /* only retry if RESOLVE_CACHED wasn't already set by application */
5281 if (ret == -EAGAIN &&
5282 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
5283 return -EAGAIN;
5284 goto err;
5285 }
5286
5287 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
5288 file->f_flags &= ~O_NONBLOCK;
5289 fsnotify_open(file);
5290
5291 if (!fixed)
5292 fd_install(ret, file);
5293 else
5294 ret = io_fixed_fd_install(req, issue_flags, file,
5295 req->open.file_slot);
5296 err:
5297 putname(req->open.filename);
5298 req->flags &= ~REQ_F_NEED_CLEANUP;
5299 if (ret < 0)
5300 req_set_fail(req);
5301 __io_req_complete(req, issue_flags, ret, 0);
5302 return 0;
5303 }
5304
io_openat(struct io_kiocb * req,unsigned int issue_flags)5305 static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
5306 {
5307 return io_openat2(req, issue_flags);
5308 }
5309
io_remove_buffers_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)5310 static int io_remove_buffers_prep(struct io_kiocb *req,
5311 const struct io_uring_sqe *sqe)
5312 {
5313 struct io_provide_buf *p = &req->pbuf;
5314 u64 tmp;
5315
5316 if (sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
5317 sqe->splice_fd_in)
5318 return -EINVAL;
5319
5320 tmp = READ_ONCE(sqe->fd);
5321 if (!tmp || tmp > USHRT_MAX)
5322 return -EINVAL;
5323
5324 memset(p, 0, sizeof(*p));
5325 p->nbufs = tmp;
5326 p->bgid = READ_ONCE(sqe->buf_group);
5327 return 0;
5328 }
5329
__io_remove_buffers(struct io_ring_ctx * ctx,struct io_buffer_list * bl,unsigned nbufs)5330 static int __io_remove_buffers(struct io_ring_ctx *ctx,
5331 struct io_buffer_list *bl, unsigned nbufs)
5332 {
5333 unsigned i = 0;
5334
5335 /* shouldn't happen */
5336 if (!nbufs)
5337 return 0;
5338
5339 if (bl->buf_nr_pages) {
5340 int j;
5341
5342 i = bl->buf_ring->tail - bl->head;
5343 for (j = 0; j < bl->buf_nr_pages; j++)
5344 unpin_user_page(bl->buf_pages[j]);
5345 kvfree(bl->buf_pages);
5346 bl->buf_pages = NULL;
5347 bl->buf_nr_pages = 0;
5348 /* make sure it's seen as empty */
5349 INIT_LIST_HEAD(&bl->buf_list);
5350 return i;
5351 }
5352
5353 /* the head kbuf is the list itself */
5354 while (!list_empty(&bl->buf_list)) {
5355 struct io_buffer *nxt;
5356
5357 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
5358 list_del(&nxt->list);
5359 if (++i == nbufs)
5360 return i;
5361 cond_resched();
5362 }
5363 i++;
5364
5365 return i;
5366 }
5367
io_remove_buffers(struct io_kiocb * req,unsigned int issue_flags)5368 static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
5369 {
5370 struct io_provide_buf *p = &req->pbuf;
5371 struct io_ring_ctx *ctx = req->ctx;
5372 struct io_buffer_list *bl;
5373 int ret = 0;
5374
5375 io_ring_submit_lock(ctx, issue_flags);
5376
5377 ret = -ENOENT;
5378 bl = io_buffer_get_list(ctx, p->bgid);
5379 if (bl) {
5380 ret = -EINVAL;
5381 /* can't use provide/remove buffers command on mapped buffers */
5382 if (!bl->buf_nr_pages)
5383 ret = __io_remove_buffers(ctx, bl, p->nbufs);
5384 }
5385 if (ret < 0)
5386 req_set_fail(req);
5387
5388 /* complete before unlock, IOPOLL may need the lock */
5389 __io_req_complete(req, issue_flags, ret, 0);
5390 io_ring_submit_unlock(ctx, issue_flags);
5391 return 0;
5392 }
5393
io_provide_buffers_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)5394 static int io_provide_buffers_prep(struct io_kiocb *req,
5395 const struct io_uring_sqe *sqe)
5396 {
5397 unsigned long size, tmp_check;
5398 struct io_provide_buf *p = &req->pbuf;
5399 u64 tmp;
5400
5401 if (sqe->rw_flags || sqe->splice_fd_in)
5402 return -EINVAL;
5403
5404 tmp = READ_ONCE(sqe->fd);
5405 if (!tmp || tmp > USHRT_MAX)
5406 return -E2BIG;
5407 p->nbufs = tmp;
5408 p->addr = READ_ONCE(sqe->addr);
5409 p->len = READ_ONCE(sqe->len);
5410
5411 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
5412 &size))
5413 return -EOVERFLOW;
5414 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
5415 return -EOVERFLOW;
5416
5417 size = (unsigned long)p->len * p->nbufs;
5418 if (!access_ok(u64_to_user_ptr(p->addr), size))
5419 return -EFAULT;
5420
5421 p->bgid = READ_ONCE(sqe->buf_group);
5422 tmp = READ_ONCE(sqe->off);
5423 if (tmp > USHRT_MAX)
5424 return -E2BIG;
5425 p->bid = tmp;
5426 return 0;
5427 }
5428
io_refill_buffer_cache(struct io_ring_ctx * ctx)5429 static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
5430 {
5431 struct io_buffer *buf;
5432 struct page *page;
5433 int bufs_in_page;
5434
5435 /*
5436 * Completions that don't happen inline (eg not under uring_lock) will
5437 * add to ->io_buffers_comp. If we don't have any free buffers, check
5438 * the completion list and splice those entries first.
5439 */
5440 if (!list_empty_careful(&ctx->io_buffers_comp)) {
5441 spin_lock(&ctx->completion_lock);
5442 if (!list_empty(&ctx->io_buffers_comp)) {
5443 list_splice_init(&ctx->io_buffers_comp,
5444 &ctx->io_buffers_cache);
5445 spin_unlock(&ctx->completion_lock);
5446 return 0;
5447 }
5448 spin_unlock(&ctx->completion_lock);
5449 }
5450
5451 /*
5452 * No free buffers and no completion entries either. Allocate a new
5453 * page worth of buffer entries and add those to our freelist.
5454 */
5455 page = alloc_page(GFP_KERNEL_ACCOUNT);
5456 if (!page)
5457 return -ENOMEM;
5458
5459 list_add(&page->lru, &ctx->io_buffers_pages);
5460
5461 buf = page_address(page);
5462 bufs_in_page = PAGE_SIZE / sizeof(*buf);
5463 while (bufs_in_page) {
5464 list_add_tail(&buf->list, &ctx->io_buffers_cache);
5465 buf++;
5466 bufs_in_page--;
5467 }
5468
5469 return 0;
5470 }
5471
io_add_buffers(struct io_ring_ctx * ctx,struct io_provide_buf * pbuf,struct io_buffer_list * bl)5472 static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
5473 struct io_buffer_list *bl)
5474 {
5475 struct io_buffer *buf;
5476 u64 addr = pbuf->addr;
5477 int i, bid = pbuf->bid;
5478
5479 for (i = 0; i < pbuf->nbufs; i++) {
5480 if (list_empty(&ctx->io_buffers_cache) &&
5481 io_refill_buffer_cache(ctx))
5482 break;
5483 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
5484 list);
5485 list_move_tail(&buf->list, &bl->buf_list);
5486 buf->addr = addr;
5487 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
5488 buf->bid = bid;
5489 buf->bgid = pbuf->bgid;
5490 addr += pbuf->len;
5491 bid++;
5492 cond_resched();
5493 }
5494
5495 return i ? 0 : -ENOMEM;
5496 }
5497
io_init_bl_list(struct io_ring_ctx * ctx)5498 static __cold int io_init_bl_list(struct io_ring_ctx *ctx)
5499 {
5500 int i;
5501
5502 ctx->io_bl = kcalloc(BGID_ARRAY, sizeof(struct io_buffer_list),
5503 GFP_KERNEL);
5504 if (!ctx->io_bl)
5505 return -ENOMEM;
5506
5507 for (i = 0; i < BGID_ARRAY; i++) {
5508 INIT_LIST_HEAD(&ctx->io_bl[i].buf_list);
5509 ctx->io_bl[i].bgid = i;
5510 }
5511
5512 return 0;
5513 }
5514
io_provide_buffers(struct io_kiocb * req,unsigned int issue_flags)5515 static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
5516 {
5517 struct io_provide_buf *p = &req->pbuf;
5518 struct io_ring_ctx *ctx = req->ctx;
5519 struct io_buffer_list *bl;
5520 int ret = 0;
5521
5522 io_ring_submit_lock(ctx, issue_flags);
5523
5524 if (unlikely(p->bgid < BGID_ARRAY && !ctx->io_bl)) {
5525 ret = io_init_bl_list(ctx);
5526 if (ret)
5527 goto err;
5528 }
5529
5530 bl = io_buffer_get_list(ctx, p->bgid);
5531 if (unlikely(!bl)) {
5532 bl = kzalloc(sizeof(*bl), GFP_KERNEL_ACCOUNT);
5533 if (!bl) {
5534 ret = -ENOMEM;
5535 goto err;
5536 }
5537 INIT_LIST_HEAD(&bl->buf_list);
5538 ret = io_buffer_add_list(ctx, bl, p->bgid);
5539 if (ret) {
5540 kfree(bl);
5541 goto err;
5542 }
5543 }
5544 /* can't add buffers via this command for a mapped buffer ring */
5545 if (bl->buf_nr_pages) {
5546 ret = -EINVAL;
5547 goto err;
5548 }
5549
5550 ret = io_add_buffers(ctx, p, bl);
5551 err:
5552 if (ret < 0)
5553 req_set_fail(req);
5554 /* complete before unlock, IOPOLL may need the lock */
5555 __io_req_complete(req, issue_flags, ret, 0);
5556 io_ring_submit_unlock(ctx, issue_flags);
5557 return 0;
5558 }
5559
io_epoll_ctl_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)5560 static int io_epoll_ctl_prep(struct io_kiocb *req,
5561 const struct io_uring_sqe *sqe)
5562 {
5563 #if defined(CONFIG_EPOLL)
5564 if (sqe->buf_index || sqe->splice_fd_in)
5565 return -EINVAL;
5566
5567 req->epoll.epfd = READ_ONCE(sqe->fd);
5568 req->epoll.op = READ_ONCE(sqe->len);
5569 req->epoll.fd = READ_ONCE(sqe->off);
5570
5571 if (ep_op_has_event(req->epoll.op)) {
5572 struct epoll_event __user *ev;
5573
5574 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
5575 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
5576 return -EFAULT;
5577 }
5578
5579 return 0;
5580 #else
5581 return -EOPNOTSUPP;
5582 #endif
5583 }
5584
io_epoll_ctl(struct io_kiocb * req,unsigned int issue_flags)5585 static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
5586 {
5587 #if defined(CONFIG_EPOLL)
5588 struct io_epoll *ie = &req->epoll;
5589 int ret;
5590 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
5591
5592 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
5593 if (force_nonblock && ret == -EAGAIN)
5594 return -EAGAIN;
5595
5596 if (ret < 0)
5597 req_set_fail(req);
5598 __io_req_complete(req, issue_flags, ret, 0);
5599 return 0;
5600 #else
5601 return -EOPNOTSUPP;
5602 #endif
5603 }
5604
io_madvise_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)5605 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5606 {
5607 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5608 if (sqe->buf_index || sqe->off || sqe->splice_fd_in)
5609 return -EINVAL;
5610
5611 req->madvise.addr = READ_ONCE(sqe->addr);
5612 req->madvise.len = READ_ONCE(sqe->len);
5613 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
5614 return 0;
5615 #else
5616 return -EOPNOTSUPP;
5617 #endif
5618 }
5619
io_madvise(struct io_kiocb * req,unsigned int issue_flags)5620 static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
5621 {
5622 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
5623 struct io_madvise *ma = &req->madvise;
5624 int ret;
5625
5626 if (issue_flags & IO_URING_F_NONBLOCK)
5627 return -EAGAIN;
5628
5629 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
5630 io_req_complete(req, ret);
5631 return 0;
5632 #else
5633 return -EOPNOTSUPP;
5634 #endif
5635 }
5636
io_fadvise_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)5637 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5638 {
5639 if (sqe->buf_index || sqe->addr || sqe->splice_fd_in)
5640 return -EINVAL;
5641
5642 req->fadvise.offset = READ_ONCE(sqe->off);
5643 req->fadvise.len = READ_ONCE(sqe->len);
5644 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
5645 return 0;
5646 }
5647
io_fadvise(struct io_kiocb * req,unsigned int issue_flags)5648 static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
5649 {
5650 struct io_fadvise *fa = &req->fadvise;
5651 int ret;
5652
5653 if (issue_flags & IO_URING_F_NONBLOCK) {
5654 switch (fa->advice) {
5655 case POSIX_FADV_NORMAL:
5656 case POSIX_FADV_RANDOM:
5657 case POSIX_FADV_SEQUENTIAL:
5658 break;
5659 default:
5660 return -EAGAIN;
5661 }
5662 }
5663
5664 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5665 if (ret < 0)
5666 req_set_fail(req);
5667 __io_req_complete(req, issue_flags, ret, 0);
5668 return 0;
5669 }
5670
io_statx_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)5671 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5672 {
5673 const char __user *path;
5674
5675 if (sqe->buf_index || sqe->splice_fd_in)
5676 return -EINVAL;
5677 if (req->flags & REQ_F_FIXED_FILE)
5678 return -EBADF;
5679
5680 req->statx.dfd = READ_ONCE(sqe->fd);
5681 req->statx.mask = READ_ONCE(sqe->len);
5682 path = u64_to_user_ptr(READ_ONCE(sqe->addr));
5683 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5684 req->statx.flags = READ_ONCE(sqe->statx_flags);
5685
5686 req->statx.filename = getname_flags(path,
5687 getname_statx_lookup_flags(req->statx.flags),
5688 NULL);
5689
5690 if (IS_ERR(req->statx.filename)) {
5691 int ret = PTR_ERR(req->statx.filename);
5692
5693 req->statx.filename = NULL;
5694 return ret;
5695 }
5696
5697 req->flags |= REQ_F_NEED_CLEANUP;
5698 return 0;
5699 }
5700
io_statx(struct io_kiocb * req,unsigned int issue_flags)5701 static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
5702 {
5703 struct io_statx *ctx = &req->statx;
5704 int ret;
5705
5706 if (issue_flags & IO_URING_F_NONBLOCK)
5707 return -EAGAIN;
5708
5709 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5710 ctx->buffer);
5711 io_req_complete(req, ret);
5712 return 0;
5713 }
5714
io_close_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)5715 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5716 {
5717 if (sqe->off || sqe->addr || sqe->len || sqe->rw_flags || sqe->buf_index)
5718 return -EINVAL;
5719 if (req->flags & REQ_F_FIXED_FILE)
5720 return -EBADF;
5721
5722 req->close.fd = READ_ONCE(sqe->fd);
5723 req->close.file_slot = READ_ONCE(sqe->file_index);
5724 if (req->close.file_slot && req->close.fd)
5725 return -EINVAL;
5726
5727 return 0;
5728 }
5729
io_close(struct io_kiocb * req,unsigned int issue_flags)5730 static int io_close(struct io_kiocb *req, unsigned int issue_flags)
5731 {
5732 struct files_struct *files = current->files;
5733 struct io_close *close = &req->close;
5734 struct fdtable *fdt;
5735 struct file *file;
5736 int ret = -EBADF;
5737
5738 if (req->close.file_slot) {
5739 ret = io_close_fixed(req, issue_flags);
5740 goto err;
5741 }
5742
5743 spin_lock(&files->file_lock);
5744 fdt = files_fdtable(files);
5745 if (close->fd >= fdt->max_fds) {
5746 spin_unlock(&files->file_lock);
5747 goto err;
5748 }
5749 file = rcu_dereference_protected(fdt->fd[close->fd],
5750 lockdep_is_held(&files->file_lock));
5751 if (!file || file->f_op == &io_uring_fops) {
5752 spin_unlock(&files->file_lock);
5753 goto err;
5754 }
5755
5756 /* if the file has a flush method, be safe and punt to async */
5757 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
5758 spin_unlock(&files->file_lock);
5759 return -EAGAIN;
5760 }
5761
5762 file = __close_fd_get_file(close->fd);
5763 spin_unlock(&files->file_lock);
5764 if (!file)
5765 goto err;
5766
5767 /* No ->flush() or already async, safely close from here */
5768 ret = filp_close(file, current->files);
5769 err:
5770 if (ret < 0)
5771 req_set_fail(req);
5772 __io_req_complete(req, issue_flags, ret, 0);
5773 return 0;
5774 }
5775
io_sfr_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)5776 static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5777 {
5778 if (unlikely(sqe->addr || sqe->buf_index || sqe->splice_fd_in))
5779 return -EINVAL;
5780
5781 req->sync.off = READ_ONCE(sqe->off);
5782 req->sync.len = READ_ONCE(sqe->len);
5783 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
5784 return 0;
5785 }
5786
io_sync_file_range(struct io_kiocb * req,unsigned int issue_flags)5787 static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
5788 {
5789 int ret;
5790
5791 /* sync_file_range always requires a blocking context */
5792 if (issue_flags & IO_URING_F_NONBLOCK)
5793 return -EAGAIN;
5794
5795 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
5796 req->sync.flags);
5797 io_req_complete(req, ret);
5798 return 0;
5799 }
5800
5801 #if defined(CONFIG_NET)
io_shutdown_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)5802 static int io_shutdown_prep(struct io_kiocb *req,
5803 const struct io_uring_sqe *sqe)
5804 {
5805 if (unlikely(sqe->off || sqe->addr || sqe->rw_flags ||
5806 sqe->buf_index || sqe->splice_fd_in))
5807 return -EINVAL;
5808
5809 req->shutdown.how = READ_ONCE(sqe->len);
5810 return 0;
5811 }
5812
io_shutdown(struct io_kiocb * req,unsigned int issue_flags)5813 static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
5814 {
5815 struct socket *sock;
5816 int ret;
5817
5818 if (issue_flags & IO_URING_F_NONBLOCK)
5819 return -EAGAIN;
5820
5821 sock = sock_from_file(req->file);
5822 if (unlikely(!sock))
5823 return -ENOTSOCK;
5824
5825 ret = __sys_shutdown_sock(sock, req->shutdown.how);
5826 io_req_complete(req, ret);
5827 return 0;
5828 }
5829
io_net_retry(struct socket * sock,int flags)5830 static bool io_net_retry(struct socket *sock, int flags)
5831 {
5832 if (!(flags & MSG_WAITALL))
5833 return false;
5834 return sock->type == SOCK_STREAM || sock->type == SOCK_SEQPACKET;
5835 }
5836
io_setup_async_msg(struct io_kiocb * req,struct io_async_msghdr * kmsg)5837 static int io_setup_async_msg(struct io_kiocb *req,
5838 struct io_async_msghdr *kmsg)
5839 {
5840 struct io_async_msghdr *async_msg = req->async_data;
5841
5842 if (async_msg)
5843 return -EAGAIN;
5844 if (io_alloc_async_data(req)) {
5845 kfree(kmsg->free_iov);
5846 return -ENOMEM;
5847 }
5848 async_msg = req->async_data;
5849 req->flags |= REQ_F_NEED_CLEANUP;
5850 memcpy(async_msg, kmsg, sizeof(*kmsg));
5851 async_msg->msg.msg_name = &async_msg->addr;
5852 /* if were using fast_iov, set it to the new one */
5853 if (!async_msg->free_iov)
5854 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
5855
5856 return -EAGAIN;
5857 }
5858
io_sendmsg_copy_hdr(struct io_kiocb * req,struct io_async_msghdr * iomsg)5859 static int io_sendmsg_copy_hdr(struct io_kiocb *req,
5860 struct io_async_msghdr *iomsg)
5861 {
5862 iomsg->msg.msg_name = &iomsg->addr;
5863 iomsg->free_iov = iomsg->fast_iov;
5864 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
5865 req->sr_msg.msg_flags, &iomsg->free_iov);
5866 }
5867
io_sendmsg_prep_async(struct io_kiocb * req)5868 static int io_sendmsg_prep_async(struct io_kiocb *req)
5869 {
5870 int ret;
5871
5872 ret = io_sendmsg_copy_hdr(req, req->async_data);
5873 if (!ret)
5874 req->flags |= REQ_F_NEED_CLEANUP;
5875 return ret;
5876 }
5877
io_sendmsg_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)5878 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5879 {
5880 struct io_sr_msg *sr = &req->sr_msg;
5881
5882 if (unlikely(sqe->file_index || sqe->addr2))
5883 return -EINVAL;
5884
5885 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
5886 sr->len = READ_ONCE(sqe->len);
5887 sr->flags = READ_ONCE(sqe->ioprio);
5888 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
5889 return -EINVAL;
5890 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5891 if (sr->msg_flags & MSG_DONTWAIT)
5892 req->flags |= REQ_F_NOWAIT;
5893
5894 #ifdef CONFIG_COMPAT
5895 if (req->ctx->compat)
5896 sr->msg_flags |= MSG_CMSG_COMPAT;
5897 #endif
5898 sr->done_io = 0;
5899 return 0;
5900 }
5901
io_sendmsg(struct io_kiocb * req,unsigned int issue_flags)5902 static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
5903 {
5904 struct io_async_msghdr iomsg, *kmsg;
5905 struct io_sr_msg *sr = &req->sr_msg;
5906 struct socket *sock;
5907 unsigned flags;
5908 int min_ret = 0;
5909 int ret;
5910
5911 sock = sock_from_file(req->file);
5912 if (unlikely(!sock))
5913 return -ENOTSOCK;
5914
5915 if (req_has_async_data(req)) {
5916 kmsg = req->async_data;
5917 } else {
5918 ret = io_sendmsg_copy_hdr(req, &iomsg);
5919 if (ret)
5920 return ret;
5921 kmsg = &iomsg;
5922 }
5923
5924 if (!(req->flags & REQ_F_POLLED) &&
5925 (sr->flags & IORING_RECVSEND_POLL_FIRST))
5926 return io_setup_async_msg(req, kmsg);
5927
5928 flags = sr->msg_flags;
5929 if (issue_flags & IO_URING_F_NONBLOCK)
5930 flags |= MSG_DONTWAIT;
5931 if (flags & MSG_WAITALL)
5932 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5933
5934 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
5935
5936 if (ret < min_ret) {
5937 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5938 return io_setup_async_msg(req, kmsg);
5939 if (ret == -ERESTARTSYS)
5940 ret = -EINTR;
5941 if (ret > 0 && io_net_retry(sock, flags)) {
5942 sr->done_io += ret;
5943 req->flags |= REQ_F_PARTIAL_IO;
5944 return io_setup_async_msg(req, kmsg);
5945 }
5946 req_set_fail(req);
5947 }
5948 /* fast path, check for non-NULL to avoid function call */
5949 if (kmsg->free_iov)
5950 kfree(kmsg->free_iov);
5951 req->flags &= ~REQ_F_NEED_CLEANUP;
5952 if (ret >= 0)
5953 ret += sr->done_io;
5954 else if (sr->done_io)
5955 ret = sr->done_io;
5956 __io_req_complete(req, issue_flags, ret, 0);
5957 return 0;
5958 }
5959
io_send(struct io_kiocb * req,unsigned int issue_flags)5960 static int io_send(struct io_kiocb *req, unsigned int issue_flags)
5961 {
5962 struct io_sr_msg *sr = &req->sr_msg;
5963 struct msghdr msg;
5964 struct iovec iov;
5965 struct socket *sock;
5966 unsigned flags;
5967 int min_ret = 0;
5968 int ret;
5969
5970 if (!(req->flags & REQ_F_POLLED) &&
5971 (sr->flags & IORING_RECVSEND_POLL_FIRST))
5972 return -EAGAIN;
5973
5974 sock = sock_from_file(req->file);
5975 if (unlikely(!sock))
5976 return -ENOTSOCK;
5977
5978 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
5979 if (unlikely(ret))
5980 return ret;
5981
5982 msg.msg_name = NULL;
5983 msg.msg_control = NULL;
5984 msg.msg_controllen = 0;
5985 msg.msg_namelen = 0;
5986
5987 flags = sr->msg_flags;
5988 if (issue_flags & IO_URING_F_NONBLOCK)
5989 flags |= MSG_DONTWAIT;
5990 if (flags & MSG_WAITALL)
5991 min_ret = iov_iter_count(&msg.msg_iter);
5992
5993 msg.msg_flags = flags;
5994 ret = sock_sendmsg(sock, &msg);
5995 if (ret < min_ret) {
5996 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5997 return -EAGAIN;
5998 if (ret == -ERESTARTSYS)
5999 ret = -EINTR;
6000 if (ret > 0 && io_net_retry(sock, flags)) {
6001 sr->len -= ret;
6002 sr->buf += ret;
6003 sr->done_io += ret;
6004 req->flags |= REQ_F_PARTIAL_IO;
6005 return -EAGAIN;
6006 }
6007 req_set_fail(req);
6008 }
6009 if (ret >= 0)
6010 ret += sr->done_io;
6011 else if (sr->done_io)
6012 ret = sr->done_io;
6013 __io_req_complete(req, issue_flags, ret, 0);
6014 return 0;
6015 }
6016
__io_recvmsg_copy_hdr(struct io_kiocb * req,struct io_async_msghdr * iomsg)6017 static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
6018 struct io_async_msghdr *iomsg)
6019 {
6020 struct io_sr_msg *sr = &req->sr_msg;
6021 struct iovec __user *uiov;
6022 size_t iov_len;
6023 int ret;
6024
6025 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
6026 &iomsg->uaddr, &uiov, &iov_len);
6027 if (ret)
6028 return ret;
6029
6030 if (req->flags & REQ_F_BUFFER_SELECT) {
6031 if (iov_len > 1)
6032 return -EINVAL;
6033 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
6034 return -EFAULT;
6035 sr->len = iomsg->fast_iov[0].iov_len;
6036 iomsg->free_iov = NULL;
6037 } else {
6038 iomsg->free_iov = iomsg->fast_iov;
6039 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
6040 &iomsg->free_iov, &iomsg->msg.msg_iter,
6041 false);
6042 if (ret > 0)
6043 ret = 0;
6044 }
6045
6046 return ret;
6047 }
6048
6049 #ifdef CONFIG_COMPAT
__io_compat_recvmsg_copy_hdr(struct io_kiocb * req,struct io_async_msghdr * iomsg)6050 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
6051 struct io_async_msghdr *iomsg)
6052 {
6053 struct io_sr_msg *sr = &req->sr_msg;
6054 struct compat_iovec __user *uiov;
6055 compat_uptr_t ptr;
6056 compat_size_t len;
6057 int ret;
6058
6059 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
6060 &ptr, &len);
6061 if (ret)
6062 return ret;
6063
6064 uiov = compat_ptr(ptr);
6065 if (req->flags & REQ_F_BUFFER_SELECT) {
6066 compat_ssize_t clen;
6067
6068 if (len > 1)
6069 return -EINVAL;
6070 if (!access_ok(uiov, sizeof(*uiov)))
6071 return -EFAULT;
6072 if (__get_user(clen, &uiov->iov_len))
6073 return -EFAULT;
6074 if (clen < 0)
6075 return -EINVAL;
6076 sr->len = clen;
6077 iomsg->free_iov = NULL;
6078 } else {
6079 iomsg->free_iov = iomsg->fast_iov;
6080 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
6081 UIO_FASTIOV, &iomsg->free_iov,
6082 &iomsg->msg.msg_iter, true);
6083 if (ret < 0)
6084 return ret;
6085 }
6086
6087 return 0;
6088 }
6089 #endif
6090
io_recvmsg_copy_hdr(struct io_kiocb * req,struct io_async_msghdr * iomsg)6091 static int io_recvmsg_copy_hdr(struct io_kiocb *req,
6092 struct io_async_msghdr *iomsg)
6093 {
6094 iomsg->msg.msg_name = &iomsg->addr;
6095
6096 #ifdef CONFIG_COMPAT
6097 if (req->ctx->compat)
6098 return __io_compat_recvmsg_copy_hdr(req, iomsg);
6099 #endif
6100
6101 return __io_recvmsg_copy_hdr(req, iomsg);
6102 }
6103
io_recvmsg_prep_async(struct io_kiocb * req)6104 static int io_recvmsg_prep_async(struct io_kiocb *req)
6105 {
6106 int ret;
6107
6108 ret = io_recvmsg_copy_hdr(req, req->async_data);
6109 if (!ret)
6110 req->flags |= REQ_F_NEED_CLEANUP;
6111 return ret;
6112 }
6113
io_recvmsg_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)6114 static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6115 {
6116 struct io_sr_msg *sr = &req->sr_msg;
6117
6118 if (unlikely(sqe->file_index || sqe->addr2))
6119 return -EINVAL;
6120
6121 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
6122 sr->len = READ_ONCE(sqe->len);
6123 sr->flags = READ_ONCE(sqe->ioprio);
6124 if (sr->flags & ~IORING_RECVSEND_POLL_FIRST)
6125 return -EINVAL;
6126 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
6127 if (sr->msg_flags & MSG_DONTWAIT)
6128 req->flags |= REQ_F_NOWAIT;
6129
6130 #ifdef CONFIG_COMPAT
6131 if (req->ctx->compat)
6132 sr->msg_flags |= MSG_CMSG_COMPAT;
6133 #endif
6134 sr->done_io = 0;
6135 return 0;
6136 }
6137
io_recvmsg(struct io_kiocb * req,unsigned int issue_flags)6138 static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
6139 {
6140 struct io_async_msghdr iomsg, *kmsg;
6141 struct io_sr_msg *sr = &req->sr_msg;
6142 struct socket *sock;
6143 unsigned int cflags;
6144 unsigned flags;
6145 int ret, min_ret = 0;
6146 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6147
6148 sock = sock_from_file(req->file);
6149 if (unlikely(!sock))
6150 return -ENOTSOCK;
6151
6152 if (req_has_async_data(req)) {
6153 kmsg = req->async_data;
6154 } else {
6155 ret = io_recvmsg_copy_hdr(req, &iomsg);
6156 if (ret)
6157 return ret;
6158 kmsg = &iomsg;
6159 }
6160
6161 if (!(req->flags & REQ_F_POLLED) &&
6162 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6163 return io_setup_async_msg(req, kmsg);
6164
6165 if (io_do_buffer_select(req)) {
6166 void __user *buf;
6167
6168 buf = io_buffer_select(req, &sr->len, issue_flags);
6169 if (!buf)
6170 return -ENOBUFS;
6171 kmsg->fast_iov[0].iov_base = buf;
6172 kmsg->fast_iov[0].iov_len = sr->len;
6173 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov, 1,
6174 sr->len);
6175 }
6176
6177 flags = sr->msg_flags;
6178 if (force_nonblock)
6179 flags |= MSG_DONTWAIT;
6180 if (flags & MSG_WAITALL)
6181 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
6182
6183 kmsg->msg.msg_get_inq = 1;
6184 ret = __sys_recvmsg_sock(sock, &kmsg->msg, sr->umsg, kmsg->uaddr, flags);
6185 if (ret < min_ret) {
6186 if (ret == -EAGAIN && force_nonblock)
6187 return io_setup_async_msg(req, kmsg);
6188 if (ret == -ERESTARTSYS)
6189 ret = -EINTR;
6190 if (ret > 0 && io_net_retry(sock, flags)) {
6191 sr->done_io += ret;
6192 req->flags |= REQ_F_PARTIAL_IO;
6193 return io_setup_async_msg(req, kmsg);
6194 }
6195 req_set_fail(req);
6196 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6197 req_set_fail(req);
6198 }
6199
6200 /* fast path, check for non-NULL to avoid function call */
6201 if (kmsg->free_iov)
6202 kfree(kmsg->free_iov);
6203 req->flags &= ~REQ_F_NEED_CLEANUP;
6204 if (ret >= 0)
6205 ret += sr->done_io;
6206 else if (sr->done_io)
6207 ret = sr->done_io;
6208 cflags = io_put_kbuf(req, issue_flags);
6209 if (kmsg->msg.msg_inq)
6210 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6211 __io_req_complete(req, issue_flags, ret, cflags);
6212 return 0;
6213 }
6214
io_recv(struct io_kiocb * req,unsigned int issue_flags)6215 static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
6216 {
6217 struct io_sr_msg *sr = &req->sr_msg;
6218 struct msghdr msg;
6219 struct socket *sock;
6220 struct iovec iov;
6221 unsigned int cflags;
6222 unsigned flags;
6223 int ret, min_ret = 0;
6224 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6225
6226 if (!(req->flags & REQ_F_POLLED) &&
6227 (sr->flags & IORING_RECVSEND_POLL_FIRST))
6228 return -EAGAIN;
6229
6230 sock = sock_from_file(req->file);
6231 if (unlikely(!sock))
6232 return -ENOTSOCK;
6233
6234 if (io_do_buffer_select(req)) {
6235 void __user *buf;
6236
6237 buf = io_buffer_select(req, &sr->len, issue_flags);
6238 if (!buf)
6239 return -ENOBUFS;
6240 sr->buf = buf;
6241 }
6242
6243 ret = import_single_range(READ, sr->buf, sr->len, &iov, &msg.msg_iter);
6244 if (unlikely(ret))
6245 goto out_free;
6246
6247 msg.msg_name = NULL;
6248 msg.msg_namelen = 0;
6249 msg.msg_control = NULL;
6250 msg.msg_get_inq = 1;
6251 msg.msg_flags = 0;
6252 msg.msg_controllen = 0;
6253 msg.msg_iocb = NULL;
6254
6255 flags = sr->msg_flags;
6256 if (force_nonblock)
6257 flags |= MSG_DONTWAIT;
6258 if (flags & MSG_WAITALL)
6259 min_ret = iov_iter_count(&msg.msg_iter);
6260
6261 ret = sock_recvmsg(sock, &msg, flags);
6262 if (ret < min_ret) {
6263 if (ret == -EAGAIN && force_nonblock)
6264 return -EAGAIN;
6265 if (ret == -ERESTARTSYS)
6266 ret = -EINTR;
6267 if (ret > 0 && io_net_retry(sock, flags)) {
6268 sr->len -= ret;
6269 sr->buf += ret;
6270 sr->done_io += ret;
6271 req->flags |= REQ_F_PARTIAL_IO;
6272 return -EAGAIN;
6273 }
6274 req_set_fail(req);
6275 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
6276 out_free:
6277 req_set_fail(req);
6278 }
6279
6280 if (ret >= 0)
6281 ret += sr->done_io;
6282 else if (sr->done_io)
6283 ret = sr->done_io;
6284 cflags = io_put_kbuf(req, issue_flags);
6285 if (msg.msg_inq)
6286 cflags |= IORING_CQE_F_SOCK_NONEMPTY;
6287 __io_req_complete(req, issue_flags, ret, cflags);
6288 return 0;
6289 }
6290
io_accept_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)6291 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6292 {
6293 struct io_accept *accept = &req->accept;
6294 unsigned flags;
6295
6296 if (sqe->len || sqe->buf_index)
6297 return -EINVAL;
6298
6299 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6300 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
6301 accept->flags = READ_ONCE(sqe->accept_flags);
6302 accept->nofile = rlimit(RLIMIT_NOFILE);
6303 flags = READ_ONCE(sqe->ioprio);
6304 if (flags & ~IORING_ACCEPT_MULTISHOT)
6305 return -EINVAL;
6306
6307 accept->file_slot = READ_ONCE(sqe->file_index);
6308 if (accept->file_slot) {
6309 if (accept->flags & SOCK_CLOEXEC)
6310 return -EINVAL;
6311 if (flags & IORING_ACCEPT_MULTISHOT &&
6312 accept->file_slot != IORING_FILE_INDEX_ALLOC)
6313 return -EINVAL;
6314 }
6315 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6316 return -EINVAL;
6317 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
6318 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
6319 if (flags & IORING_ACCEPT_MULTISHOT)
6320 req->flags |= REQ_F_APOLL_MULTISHOT;
6321 return 0;
6322 }
6323
io_accept(struct io_kiocb * req,unsigned int issue_flags)6324 static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
6325 {
6326 struct io_ring_ctx *ctx = req->ctx;
6327 struct io_accept *accept = &req->accept;
6328 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6329 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
6330 bool fixed = !!accept->file_slot;
6331 struct file *file;
6332 int ret, fd;
6333
6334 retry:
6335 if (!fixed) {
6336 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
6337 if (unlikely(fd < 0))
6338 return fd;
6339 }
6340 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
6341 accept->flags);
6342 if (IS_ERR(file)) {
6343 if (!fixed)
6344 put_unused_fd(fd);
6345 ret = PTR_ERR(file);
6346 if (ret == -EAGAIN && force_nonblock) {
6347 /*
6348 * if it's multishot and polled, we don't need to
6349 * return EAGAIN to arm the poll infra since it
6350 * has already been done
6351 */
6352 if ((req->flags & IO_APOLL_MULTI_POLLED) ==
6353 IO_APOLL_MULTI_POLLED)
6354 ret = 0;
6355 return ret;
6356 }
6357 if (ret == -ERESTARTSYS)
6358 ret = -EINTR;
6359 req_set_fail(req);
6360 } else if (!fixed) {
6361 fd_install(fd, file);
6362 ret = fd;
6363 } else {
6364 ret = io_fixed_fd_install(req, issue_flags, file,
6365 accept->file_slot);
6366 }
6367
6368 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6369 __io_req_complete(req, issue_flags, ret, 0);
6370 return 0;
6371 }
6372 if (ret >= 0) {
6373 bool filled;
6374
6375 spin_lock(&ctx->completion_lock);
6376 filled = io_fill_cqe_aux(ctx, req->cqe.user_data, ret,
6377 IORING_CQE_F_MORE);
6378 io_commit_cqring(ctx);
6379 spin_unlock(&ctx->completion_lock);
6380 if (filled) {
6381 io_cqring_ev_posted(ctx);
6382 goto retry;
6383 }
6384 ret = -ECANCELED;
6385 }
6386
6387 return ret;
6388 }
6389
io_socket_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)6390 static int io_socket_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6391 {
6392 struct io_socket *sock = &req->sock;
6393
6394 if (sqe->addr || sqe->rw_flags || sqe->buf_index)
6395 return -EINVAL;
6396
6397 sock->domain = READ_ONCE(sqe->fd);
6398 sock->type = READ_ONCE(sqe->off);
6399 sock->protocol = READ_ONCE(sqe->len);
6400 sock->file_slot = READ_ONCE(sqe->file_index);
6401 sock->nofile = rlimit(RLIMIT_NOFILE);
6402
6403 sock->flags = sock->type & ~SOCK_TYPE_MASK;
6404 if (sock->file_slot && (sock->flags & SOCK_CLOEXEC))
6405 return -EINVAL;
6406 if (sock->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
6407 return -EINVAL;
6408 return 0;
6409 }
6410
io_socket(struct io_kiocb * req,unsigned int issue_flags)6411 static int io_socket(struct io_kiocb *req, unsigned int issue_flags)
6412 {
6413 struct io_socket *sock = &req->sock;
6414 bool fixed = !!sock->file_slot;
6415 struct file *file;
6416 int ret, fd;
6417
6418 if (!fixed) {
6419 fd = __get_unused_fd_flags(sock->flags, sock->nofile);
6420 if (unlikely(fd < 0))
6421 return fd;
6422 }
6423 file = __sys_socket_file(sock->domain, sock->type, sock->protocol);
6424 if (IS_ERR(file)) {
6425 if (!fixed)
6426 put_unused_fd(fd);
6427 ret = PTR_ERR(file);
6428 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
6429 return -EAGAIN;
6430 if (ret == -ERESTARTSYS)
6431 ret = -EINTR;
6432 req_set_fail(req);
6433 } else if (!fixed) {
6434 fd_install(fd, file);
6435 ret = fd;
6436 } else {
6437 ret = io_fixed_fd_install(req, issue_flags, file,
6438 sock->file_slot);
6439 }
6440 __io_req_complete(req, issue_flags, ret, 0);
6441 return 0;
6442 }
6443
io_connect_prep_async(struct io_kiocb * req)6444 static int io_connect_prep_async(struct io_kiocb *req)
6445 {
6446 struct io_async_connect *io = req->async_data;
6447 struct io_connect *conn = &req->connect;
6448
6449 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
6450 }
6451
io_connect_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)6452 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
6453 {
6454 struct io_connect *conn = &req->connect;
6455
6456 if (sqe->len || sqe->buf_index || sqe->rw_flags || sqe->splice_fd_in)
6457 return -EINVAL;
6458
6459 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
6460 conn->addr_len = READ_ONCE(sqe->addr2);
6461 return 0;
6462 }
6463
io_connect(struct io_kiocb * req,unsigned int issue_flags)6464 static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
6465 {
6466 struct io_async_connect __io, *io;
6467 unsigned file_flags;
6468 int ret;
6469 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
6470
6471 if (req_has_async_data(req)) {
6472 io = req->async_data;
6473 } else {
6474 ret = move_addr_to_kernel(req->connect.addr,
6475 req->connect.addr_len,
6476 &__io.address);
6477 if (ret)
6478 goto out;
6479 io = &__io;
6480 }
6481
6482 file_flags = force_nonblock ? O_NONBLOCK : 0;
6483
6484 ret = __sys_connect_file(req->file, &io->address,
6485 req->connect.addr_len, file_flags);
6486 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
6487 if (req_has_async_data(req))
6488 return -EAGAIN;
6489 if (io_alloc_async_data(req)) {
6490 ret = -ENOMEM;
6491 goto out;
6492 }
6493 memcpy(req->async_data, &__io, sizeof(__io));
6494 return -EAGAIN;
6495 }
6496 if (ret == -ERESTARTSYS)
6497 ret = -EINTR;
6498 out:
6499 if (ret < 0)
6500 req_set_fail(req);
6501 __io_req_complete(req, issue_flags, ret, 0);
6502 return 0;
6503 }
6504 #else /* !CONFIG_NET */
6505 #define IO_NETOP_FN(op) \
6506 static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
6507 { \
6508 return -EOPNOTSUPP; \
6509 }
6510
6511 #define IO_NETOP_PREP(op) \
6512 IO_NETOP_FN(op) \
6513 static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
6514 { \
6515 return -EOPNOTSUPP; \
6516 } \
6517
6518 #define IO_NETOP_PREP_ASYNC(op) \
6519 IO_NETOP_PREP(op) \
6520 static int io_##op##_prep_async(struct io_kiocb *req) \
6521 { \
6522 return -EOPNOTSUPP; \
6523 }
6524
6525 IO_NETOP_PREP_ASYNC(sendmsg);
6526 IO_NETOP_PREP_ASYNC(recvmsg);
6527 IO_NETOP_PREP_ASYNC(connect);
6528 IO_NETOP_PREP(accept);
6529 IO_NETOP_PREP(socket);
6530 IO_NETOP_PREP(shutdown);
6531 IO_NETOP_FN(send);
6532 IO_NETOP_FN(recv);
6533 #endif /* CONFIG_NET */
6534
6535 struct io_poll_table {
6536 struct poll_table_struct pt;
6537 struct io_kiocb *req;
6538 int nr_entries;
6539 int error;
6540 };
6541
6542 #define IO_POLL_CANCEL_FLAG BIT(31)
6543 #define IO_POLL_REF_MASK GENMASK(30, 0)
6544
6545 /*
6546 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
6547 * bump it and acquire ownership. It's disallowed to modify requests while not
6548 * owning it, that prevents from races for enqueueing task_work's and b/w
6549 * arming poll and wakeups.
6550 */
io_poll_get_ownership(struct io_kiocb * req)6551 static inline bool io_poll_get_ownership(struct io_kiocb *req)
6552 {
6553 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
6554 }
6555
io_poll_mark_cancelled(struct io_kiocb * req)6556 static void io_poll_mark_cancelled(struct io_kiocb *req)
6557 {
6558 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
6559 }
6560
io_poll_get_double(struct io_kiocb * req)6561 static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
6562 {
6563 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
6564 if (req->opcode == IORING_OP_POLL_ADD)
6565 return req->async_data;
6566 return req->apoll->double_poll;
6567 }
6568
io_poll_get_single(struct io_kiocb * req)6569 static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
6570 {
6571 if (req->opcode == IORING_OP_POLL_ADD)
6572 return &req->poll;
6573 return &req->apoll->poll;
6574 }
6575
io_poll_req_insert(struct io_kiocb * req)6576 static void io_poll_req_insert(struct io_kiocb *req)
6577 {
6578 struct io_ring_ctx *ctx = req->ctx;
6579 struct hlist_head *list;
6580
6581 list = &ctx->cancel_hash[hash_long(req->cqe.user_data, ctx->cancel_hash_bits)];
6582 hlist_add_head(&req->hash_node, list);
6583 }
6584
io_init_poll_iocb(struct io_poll_iocb * poll,__poll_t events,wait_queue_func_t wake_func)6585 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
6586 wait_queue_func_t wake_func)
6587 {
6588 poll->head = NULL;
6589 #define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
6590 /* mask in events that we always want/need */
6591 poll->events = events | IO_POLL_UNMASK;
6592 INIT_LIST_HEAD(&poll->wait.entry);
6593 init_waitqueue_func_entry(&poll->wait, wake_func);
6594 }
6595
io_poll_remove_entry(struct io_poll_iocb * poll)6596 static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
6597 {
6598 struct wait_queue_head *head = smp_load_acquire(&poll->head);
6599
6600 if (head) {
6601 spin_lock_irq(&head->lock);
6602 list_del_init(&poll->wait.entry);
6603 poll->head = NULL;
6604 spin_unlock_irq(&head->lock);
6605 }
6606 }
6607
io_poll_remove_entries(struct io_kiocb * req)6608 static void io_poll_remove_entries(struct io_kiocb *req)
6609 {
6610 /*
6611 * Nothing to do if neither of those flags are set. Avoid dipping
6612 * into the poll/apoll/double cachelines if we can.
6613 */
6614 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
6615 return;
6616
6617 /*
6618 * While we hold the waitqueue lock and the waitqueue is nonempty,
6619 * wake_up_pollfree() will wait for us. However, taking the waitqueue
6620 * lock in the first place can race with the waitqueue being freed.
6621 *
6622 * We solve this as eventpoll does: by taking advantage of the fact that
6623 * all users of wake_up_pollfree() will RCU-delay the actual free. If
6624 * we enter rcu_read_lock() and see that the pointer to the queue is
6625 * non-NULL, we can then lock it without the memory being freed out from
6626 * under us.
6627 *
6628 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
6629 * case the caller deletes the entry from the queue, leaving it empty.
6630 * In that case, only RCU prevents the queue memory from being freed.
6631 */
6632 rcu_read_lock();
6633 if (req->flags & REQ_F_SINGLE_POLL)
6634 io_poll_remove_entry(io_poll_get_single(req));
6635 if (req->flags & REQ_F_DOUBLE_POLL)
6636 io_poll_remove_entry(io_poll_get_double(req));
6637 rcu_read_unlock();
6638 }
6639
6640 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags);
6641 /*
6642 * All poll tw should go through this. Checks for poll events, manages
6643 * references, does rewait, etc.
6644 *
6645 * Returns a negative error on failure. >0 when no action require, which is
6646 * either spurious wakeup or multishot CQE is served. 0 when it's done with
6647 * the request, then the mask is stored in req->cqe.res.
6648 */
io_poll_check_events(struct io_kiocb * req,bool * locked)6649 static int io_poll_check_events(struct io_kiocb *req, bool *locked)
6650 {
6651 struct io_ring_ctx *ctx = req->ctx;
6652 int v, ret;
6653
6654 /* req->task == current here, checking PF_EXITING is safe */
6655 if (unlikely(req->task->flags & PF_EXITING))
6656 return -ECANCELED;
6657
6658 do {
6659 v = atomic_read(&req->poll_refs);
6660
6661 /* tw handler should be the owner, and so have some references */
6662 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
6663 return 0;
6664 if (v & IO_POLL_CANCEL_FLAG)
6665 return -ECANCELED;
6666
6667 if (!req->cqe.res) {
6668 struct poll_table_struct pt = { ._key = req->apoll_events };
6669 req->cqe.res = vfs_poll(req->file, &pt) & req->apoll_events;
6670 }
6671
6672 if ((unlikely(!req->cqe.res)))
6673 continue;
6674 if (req->apoll_events & EPOLLONESHOT)
6675 return 0;
6676
6677 /* multishot, just fill a CQE and proceed */
6678 if (!(req->flags & REQ_F_APOLL_MULTISHOT)) {
6679 __poll_t mask = mangle_poll(req->cqe.res &
6680 req->apoll_events);
6681 bool filled;
6682
6683 spin_lock(&ctx->completion_lock);
6684 filled = io_fill_cqe_aux(ctx, req->cqe.user_data,
6685 mask, IORING_CQE_F_MORE);
6686 io_commit_cqring(ctx);
6687 spin_unlock(&ctx->completion_lock);
6688 if (filled) {
6689 io_cqring_ev_posted(ctx);
6690 continue;
6691 }
6692 return -ECANCELED;
6693 }
6694
6695 io_tw_lock(req->ctx, locked);
6696 if (unlikely(req->task->flags & PF_EXITING))
6697 return -EFAULT;
6698 ret = io_issue_sqe(req,
6699 IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
6700 if (ret)
6701 return ret;
6702
6703 /*
6704 * Release all references, retry if someone tried to restart
6705 * task_work while we were executing it.
6706 */
6707 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
6708
6709 return 1;
6710 }
6711
io_poll_task_func(struct io_kiocb * req,bool * locked)6712 static void io_poll_task_func(struct io_kiocb *req, bool *locked)
6713 {
6714 struct io_ring_ctx *ctx = req->ctx;
6715 int ret;
6716
6717 ret = io_poll_check_events(req, locked);
6718 if (ret > 0)
6719 return;
6720
6721 if (!ret) {
6722 req->cqe.res = mangle_poll(req->cqe.res & req->poll.events);
6723 } else {
6724 req->cqe.res = ret;
6725 req_set_fail(req);
6726 }
6727
6728 io_poll_remove_entries(req);
6729 spin_lock(&ctx->completion_lock);
6730 hash_del(&req->hash_node);
6731 __io_req_complete_post(req, req->cqe.res, 0);
6732 io_commit_cqring(ctx);
6733 spin_unlock(&ctx->completion_lock);
6734 io_cqring_ev_posted(ctx);
6735 }
6736
io_apoll_task_func(struct io_kiocb * req,bool * locked)6737 static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
6738 {
6739 struct io_ring_ctx *ctx = req->ctx;
6740 int ret;
6741
6742 ret = io_poll_check_events(req, locked);
6743 if (ret > 0)
6744 return;
6745
6746 io_poll_remove_entries(req);
6747 spin_lock(&ctx->completion_lock);
6748 hash_del(&req->hash_node);
6749 spin_unlock(&ctx->completion_lock);
6750
6751 if (!ret)
6752 io_req_task_submit(req, locked);
6753 else
6754 io_req_complete_failed(req, ret);
6755 }
6756
__io_poll_execute(struct io_kiocb * req,int mask,__poll_t __maybe_unused events)6757 static void __io_poll_execute(struct io_kiocb *req, int mask,
6758 __poll_t __maybe_unused events)
6759 {
6760 req->cqe.res = mask;
6761 /*
6762 * This is useful for poll that is armed on behalf of another
6763 * request, and where the wakeup path could be on a different
6764 * CPU. We want to avoid pulling in req->apoll->events for that
6765 * case.
6766 */
6767 if (req->opcode == IORING_OP_POLL_ADD)
6768 req->io_task_work.func = io_poll_task_func;
6769 else
6770 req->io_task_work.func = io_apoll_task_func;
6771
6772 trace_io_uring_task_add(req->ctx, req, req->cqe.user_data, req->opcode, mask);
6773 io_req_task_work_add(req);
6774 }
6775
io_poll_execute(struct io_kiocb * req,int res,__poll_t events)6776 static inline void io_poll_execute(struct io_kiocb *req, int res,
6777 __poll_t events)
6778 {
6779 if (io_poll_get_ownership(req))
6780 __io_poll_execute(req, res, events);
6781 }
6782
io_poll_cancel_req(struct io_kiocb * req)6783 static void io_poll_cancel_req(struct io_kiocb *req)
6784 {
6785 io_poll_mark_cancelled(req);
6786 /* kick tw, which should complete the request */
6787 io_poll_execute(req, 0, 0);
6788 }
6789
6790 #define wqe_to_req(wait) ((void *)((unsigned long) (wait)->private & ~1))
6791 #define wqe_is_double(wait) ((unsigned long) (wait)->private & 1)
6792 #define IO_ASYNC_POLL_COMMON (EPOLLONESHOT | EPOLLPRI)
6793
io_poll_wake(struct wait_queue_entry * wait,unsigned mode,int sync,void * key)6794 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
6795 void *key)
6796 {
6797 struct io_kiocb *req = wqe_to_req(wait);
6798 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
6799 wait);
6800 __poll_t mask = key_to_poll(key);
6801
6802 if (unlikely(mask & POLLFREE)) {
6803 io_poll_mark_cancelled(req);
6804 /* we have to kick tw in case it's not already */
6805 io_poll_execute(req, 0, poll->events);
6806
6807 /*
6808 * If the waitqueue is being freed early but someone is already
6809 * holds ownership over it, we have to tear down the request as
6810 * best we can. That means immediately removing the request from
6811 * its waitqueue and preventing all further accesses to the
6812 * waitqueue via the request.
6813 */
6814 list_del_init(&poll->wait.entry);
6815
6816 /*
6817 * Careful: this *must* be the last step, since as soon
6818 * as req->head is NULL'ed out, the request can be
6819 * completed and freed, since aio_poll_complete_work()
6820 * will no longer need to take the waitqueue lock.
6821 */
6822 smp_store_release(&poll->head, NULL);
6823 return 1;
6824 }
6825
6826 /* for instances that support it check for an event match first */
6827 if (mask && !(mask & (poll->events & ~IO_ASYNC_POLL_COMMON)))
6828 return 0;
6829
6830 if (io_poll_get_ownership(req)) {
6831 /* optional, saves extra locking for removal in tw handler */
6832 if (mask && poll->events & EPOLLONESHOT) {
6833 list_del_init(&poll->wait.entry);
6834 poll->head = NULL;
6835 if (wqe_is_double(wait))
6836 req->flags &= ~REQ_F_DOUBLE_POLL;
6837 else
6838 req->flags &= ~REQ_F_SINGLE_POLL;
6839 }
6840 __io_poll_execute(req, mask, poll->events);
6841 }
6842 return 1;
6843 }
6844
__io_queue_proc(struct io_poll_iocb * poll,struct io_poll_table * pt,struct wait_queue_head * head,struct io_poll_iocb ** poll_ptr)6845 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
6846 struct wait_queue_head *head,
6847 struct io_poll_iocb **poll_ptr)
6848 {
6849 struct io_kiocb *req = pt->req;
6850 unsigned long wqe_private = (unsigned long) req;
6851
6852 /*
6853 * The file being polled uses multiple waitqueues for poll handling
6854 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
6855 * if this happens.
6856 */
6857 if (unlikely(pt->nr_entries)) {
6858 struct io_poll_iocb *first = poll;
6859
6860 /* double add on the same waitqueue head, ignore */
6861 if (first->head == head)
6862 return;
6863 /* already have a 2nd entry, fail a third attempt */
6864 if (*poll_ptr) {
6865 if ((*poll_ptr)->head == head)
6866 return;
6867 pt->error = -EINVAL;
6868 return;
6869 }
6870
6871 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
6872 if (!poll) {
6873 pt->error = -ENOMEM;
6874 return;
6875 }
6876 /* mark as double wq entry */
6877 wqe_private |= 1;
6878 req->flags |= REQ_F_DOUBLE_POLL;
6879 io_init_poll_iocb(poll, first->events, first->wait.func);
6880 *poll_ptr = poll;
6881 if (req->opcode == IORING_OP_POLL_ADD)
6882 req->flags |= REQ_F_ASYNC_DATA;
6883 }
6884
6885 req->flags |= REQ_F_SINGLE_POLL;
6886 pt->nr_entries++;
6887 poll->head = head;
6888 poll->wait.private = (void *) wqe_private;
6889
6890 if (poll->events & EPOLLEXCLUSIVE)
6891 add_wait_queue_exclusive(head, &poll->wait);
6892 else
6893 add_wait_queue(head, &poll->wait);
6894 }
6895
io_poll_queue_proc(struct file * file,struct wait_queue_head * head,struct poll_table_struct * p)6896 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
6897 struct poll_table_struct *p)
6898 {
6899 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6900
6901 __io_queue_proc(&pt->req->poll, pt, head,
6902 (struct io_poll_iocb **) &pt->req->async_data);
6903 }
6904
__io_arm_poll_handler(struct io_kiocb * req,struct io_poll_iocb * poll,struct io_poll_table * ipt,__poll_t mask)6905 static int __io_arm_poll_handler(struct io_kiocb *req,
6906 struct io_poll_iocb *poll,
6907 struct io_poll_table *ipt, __poll_t mask)
6908 {
6909 struct io_ring_ctx *ctx = req->ctx;
6910 int v;
6911
6912 INIT_HLIST_NODE(&req->hash_node);
6913 req->work.cancel_seq = atomic_read(&ctx->cancel_seq);
6914 io_init_poll_iocb(poll, mask, io_poll_wake);
6915 poll->file = req->file;
6916
6917 req->apoll_events = poll->events;
6918
6919 ipt->pt._key = mask;
6920 ipt->req = req;
6921 ipt->error = 0;
6922 ipt->nr_entries = 0;
6923
6924 /*
6925 * Take the ownership to delay any tw execution up until we're done
6926 * with poll arming. see io_poll_get_ownership().
6927 */
6928 atomic_set(&req->poll_refs, 1);
6929 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
6930
6931 if (mask && (poll->events & EPOLLONESHOT)) {
6932 io_poll_remove_entries(req);
6933 /* no one else has access to the req, forget about the ref */
6934 return mask;
6935 }
6936 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
6937 io_poll_remove_entries(req);
6938 if (!ipt->error)
6939 ipt->error = -EINVAL;
6940 return 0;
6941 }
6942
6943 spin_lock(&ctx->completion_lock);
6944 io_poll_req_insert(req);
6945 spin_unlock(&ctx->completion_lock);
6946
6947 if (mask) {
6948 /* can't multishot if failed, just queue the event we've got */
6949 if (unlikely(ipt->error || !ipt->nr_entries)) {
6950 poll->events |= EPOLLONESHOT;
6951 req->apoll_events |= EPOLLONESHOT;
6952 ipt->error = 0;
6953 }
6954 __io_poll_execute(req, mask, poll->events);
6955 return 0;
6956 }
6957
6958 /*
6959 * Release ownership. If someone tried to queue a tw while it was
6960 * locked, kick it off for them.
6961 */
6962 v = atomic_dec_return(&req->poll_refs);
6963 if (unlikely(v & IO_POLL_REF_MASK))
6964 __io_poll_execute(req, 0, poll->events);
6965 return 0;
6966 }
6967
io_async_queue_proc(struct file * file,struct wait_queue_head * head,struct poll_table_struct * p)6968 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
6969 struct poll_table_struct *p)
6970 {
6971 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6972 struct async_poll *apoll = pt->req->apoll;
6973
6974 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
6975 }
6976
6977 enum {
6978 IO_APOLL_OK,
6979 IO_APOLL_ABORTED,
6980 IO_APOLL_READY
6981 };
6982
io_arm_poll_handler(struct io_kiocb * req,unsigned issue_flags)6983 static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
6984 {
6985 const struct io_op_def *def = &io_op_defs[req->opcode];
6986 struct io_ring_ctx *ctx = req->ctx;
6987 struct async_poll *apoll;
6988 struct io_poll_table ipt;
6989 __poll_t mask = POLLPRI | POLLERR;
6990 int ret;
6991
6992 if (!def->pollin && !def->pollout)
6993 return IO_APOLL_ABORTED;
6994 if (!file_can_poll(req->file))
6995 return IO_APOLL_ABORTED;
6996 if ((req->flags & (REQ_F_POLLED|REQ_F_PARTIAL_IO)) == REQ_F_POLLED)
6997 return IO_APOLL_ABORTED;
6998 if (!(req->flags & REQ_F_APOLL_MULTISHOT))
6999 mask |= EPOLLONESHOT;
7000
7001 if (def->pollin) {
7002 mask |= EPOLLIN | EPOLLRDNORM;
7003
7004 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
7005 if ((req->opcode == IORING_OP_RECVMSG) &&
7006 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
7007 mask &= ~EPOLLIN;
7008 } else {
7009 mask |= EPOLLOUT | EPOLLWRNORM;
7010 }
7011 if (def->poll_exclusive)
7012 mask |= EPOLLEXCLUSIVE;
7013 if (req->flags & REQ_F_POLLED) {
7014 apoll = req->apoll;
7015 kfree(apoll->double_poll);
7016 } else if (!(issue_flags & IO_URING_F_UNLOCKED) &&
7017 !list_empty(&ctx->apoll_cache)) {
7018 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
7019 poll.wait.entry);
7020 list_del_init(&apoll->poll.wait.entry);
7021 } else {
7022 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
7023 if (unlikely(!apoll))
7024 return IO_APOLL_ABORTED;
7025 }
7026 apoll->double_poll = NULL;
7027 req->apoll = apoll;
7028 req->flags |= REQ_F_POLLED;
7029 ipt.pt._qproc = io_async_queue_proc;
7030
7031 io_kbuf_recycle(req, issue_flags);
7032
7033 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
7034 if (ret || ipt.error)
7035 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
7036
7037 trace_io_uring_poll_arm(ctx, req, req->cqe.user_data, req->opcode,
7038 mask, apoll->poll.events);
7039 return IO_APOLL_OK;
7040 }
7041
7042 /*
7043 * Returns true if we found and killed one or more poll requests
7044 */
io_poll_remove_all(struct io_ring_ctx * ctx,struct task_struct * tsk,bool cancel_all)7045 static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
7046 struct task_struct *tsk, bool cancel_all)
7047 {
7048 struct hlist_node *tmp;
7049 struct io_kiocb *req;
7050 bool found = false;
7051 int i;
7052
7053 spin_lock(&ctx->completion_lock);
7054 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7055 struct hlist_head *list;
7056
7057 list = &ctx->cancel_hash[i];
7058 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
7059 if (io_match_task_safe(req, tsk, cancel_all)) {
7060 hlist_del_init(&req->hash_node);
7061 io_poll_cancel_req(req);
7062 found = true;
7063 }
7064 }
7065 }
7066 spin_unlock(&ctx->completion_lock);
7067 return found;
7068 }
7069
io_poll_find(struct io_ring_ctx * ctx,bool poll_only,struct io_cancel_data * cd)7070 static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, bool poll_only,
7071 struct io_cancel_data *cd)
7072 __must_hold(&ctx->completion_lock)
7073 {
7074 struct hlist_head *list;
7075 struct io_kiocb *req;
7076
7077 list = &ctx->cancel_hash[hash_long(cd->data, ctx->cancel_hash_bits)];
7078 hlist_for_each_entry(req, list, hash_node) {
7079 if (cd->data != req->cqe.user_data)
7080 continue;
7081 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
7082 continue;
7083 if (cd->flags & IORING_ASYNC_CANCEL_ALL) {
7084 if (cd->seq == req->work.cancel_seq)
7085 continue;
7086 req->work.cancel_seq = cd->seq;
7087 }
7088 return req;
7089 }
7090 return NULL;
7091 }
7092
io_poll_file_find(struct io_ring_ctx * ctx,struct io_cancel_data * cd)7093 static struct io_kiocb *io_poll_file_find(struct io_ring_ctx *ctx,
7094 struct io_cancel_data *cd)
7095 __must_hold(&ctx->completion_lock)
7096 {
7097 struct io_kiocb *req;
7098 int i;
7099
7100 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
7101 struct hlist_head *list;
7102
7103 list = &ctx->cancel_hash[i];
7104 hlist_for_each_entry(req, list, hash_node) {
7105 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7106 req->file != cd->file)
7107 continue;
7108 if (cd->seq == req->work.cancel_seq)
7109 continue;
7110 req->work.cancel_seq = cd->seq;
7111 return req;
7112 }
7113 }
7114 return NULL;
7115 }
7116
io_poll_disarm(struct io_kiocb * req)7117 static bool io_poll_disarm(struct io_kiocb *req)
7118 __must_hold(&ctx->completion_lock)
7119 {
7120 if (!io_poll_get_ownership(req))
7121 return false;
7122 io_poll_remove_entries(req);
7123 hash_del(&req->hash_node);
7124 return true;
7125 }
7126
io_poll_cancel(struct io_ring_ctx * ctx,struct io_cancel_data * cd)7127 static int io_poll_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7128 __must_hold(&ctx->completion_lock)
7129 {
7130 struct io_kiocb *req;
7131
7132 if (cd->flags & (IORING_ASYNC_CANCEL_FD|IORING_ASYNC_CANCEL_ANY))
7133 req = io_poll_file_find(ctx, cd);
7134 else
7135 req = io_poll_find(ctx, false, cd);
7136 if (!req)
7137 return -ENOENT;
7138 io_poll_cancel_req(req);
7139 return 0;
7140 }
7141
io_poll_parse_events(const struct io_uring_sqe * sqe,unsigned int flags)7142 static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
7143 unsigned int flags)
7144 {
7145 u32 events;
7146
7147 events = READ_ONCE(sqe->poll32_events);
7148 #ifdef __BIG_ENDIAN
7149 events = swahw32(events);
7150 #endif
7151 if (!(flags & IORING_POLL_ADD_MULTI))
7152 events |= EPOLLONESHOT;
7153 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
7154 }
7155
io_poll_remove_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)7156 static int io_poll_remove_prep(struct io_kiocb *req,
7157 const struct io_uring_sqe *sqe)
7158 {
7159 struct io_poll_update *upd = &req->poll_update;
7160 u32 flags;
7161
7162 if (sqe->buf_index || sqe->splice_fd_in)
7163 return -EINVAL;
7164 flags = READ_ONCE(sqe->len);
7165 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
7166 IORING_POLL_ADD_MULTI))
7167 return -EINVAL;
7168 /* meaningless without update */
7169 if (flags == IORING_POLL_ADD_MULTI)
7170 return -EINVAL;
7171
7172 upd->old_user_data = READ_ONCE(sqe->addr);
7173 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
7174 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
7175
7176 upd->new_user_data = READ_ONCE(sqe->off);
7177 if (!upd->update_user_data && upd->new_user_data)
7178 return -EINVAL;
7179 if (upd->update_events)
7180 upd->events = io_poll_parse_events(sqe, flags);
7181 else if (sqe->poll32_events)
7182 return -EINVAL;
7183
7184 return 0;
7185 }
7186
io_poll_add_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)7187 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
7188 {
7189 struct io_poll_iocb *poll = &req->poll;
7190 u32 flags;
7191
7192 if (sqe->buf_index || sqe->off || sqe->addr)
7193 return -EINVAL;
7194 flags = READ_ONCE(sqe->len);
7195 if (flags & ~IORING_POLL_ADD_MULTI)
7196 return -EINVAL;
7197 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
7198 return -EINVAL;
7199
7200 io_req_set_refcount(req);
7201 poll->events = io_poll_parse_events(sqe, flags);
7202 return 0;
7203 }
7204
io_poll_add(struct io_kiocb * req,unsigned int issue_flags)7205 static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
7206 {
7207 struct io_poll_iocb *poll = &req->poll;
7208 struct io_poll_table ipt;
7209 int ret;
7210
7211 ipt.pt._qproc = io_poll_queue_proc;
7212
7213 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
7214 if (!ret && ipt.error)
7215 req_set_fail(req);
7216 ret = ret ?: ipt.error;
7217 if (ret)
7218 __io_req_complete(req, issue_flags, ret, 0);
7219 return 0;
7220 }
7221
io_poll_remove(struct io_kiocb * req,unsigned int issue_flags)7222 static int io_poll_remove(struct io_kiocb *req, unsigned int issue_flags)
7223 {
7224 struct io_cancel_data cd = { .data = req->poll_update.old_user_data, };
7225 struct io_ring_ctx *ctx = req->ctx;
7226 struct io_kiocb *preq;
7227 int ret2, ret = 0;
7228 bool locked;
7229
7230 spin_lock(&ctx->completion_lock);
7231 preq = io_poll_find(ctx, true, &cd);
7232 if (!preq || !io_poll_disarm(preq)) {
7233 spin_unlock(&ctx->completion_lock);
7234 ret = preq ? -EALREADY : -ENOENT;
7235 goto out;
7236 }
7237 spin_unlock(&ctx->completion_lock);
7238
7239 if (req->poll_update.update_events || req->poll_update.update_user_data) {
7240 /* only mask one event flags, keep behavior flags */
7241 if (req->poll_update.update_events) {
7242 preq->poll.events &= ~0xffff;
7243 preq->poll.events |= req->poll_update.events & 0xffff;
7244 preq->poll.events |= IO_POLL_UNMASK;
7245 }
7246 if (req->poll_update.update_user_data)
7247 preq->cqe.user_data = req->poll_update.new_user_data;
7248
7249 ret2 = io_poll_add(preq, issue_flags);
7250 /* successfully updated, don't complete poll request */
7251 if (!ret2)
7252 goto out;
7253 }
7254
7255 req_set_fail(preq);
7256 preq->cqe.res = -ECANCELED;
7257 locked = !(issue_flags & IO_URING_F_UNLOCKED);
7258 io_req_task_complete(preq, &locked);
7259 out:
7260 if (ret < 0)
7261 req_set_fail(req);
7262 /* complete update request, we're done with it */
7263 __io_req_complete(req, issue_flags, ret, 0);
7264 return 0;
7265 }
7266
io_timeout_fn(struct hrtimer * timer)7267 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
7268 {
7269 struct io_timeout_data *data = container_of(timer,
7270 struct io_timeout_data, timer);
7271 struct io_kiocb *req = data->req;
7272 struct io_ring_ctx *ctx = req->ctx;
7273 unsigned long flags;
7274
7275 spin_lock_irqsave(&ctx->timeout_lock, flags);
7276 list_del_init(&req->timeout.list);
7277 atomic_set(&req->ctx->cq_timeouts,
7278 atomic_read(&req->ctx->cq_timeouts) + 1);
7279 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
7280
7281 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
7282 req_set_fail(req);
7283
7284 req->cqe.res = -ETIME;
7285 req->io_task_work.func = io_req_task_complete;
7286 io_req_task_work_add(req);
7287 return HRTIMER_NORESTART;
7288 }
7289
io_timeout_extract(struct io_ring_ctx * ctx,struct io_cancel_data * cd)7290 static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
7291 struct io_cancel_data *cd)
7292 __must_hold(&ctx->timeout_lock)
7293 {
7294 struct io_timeout_data *io;
7295 struct io_kiocb *req;
7296 bool found = false;
7297
7298 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
7299 if (!(cd->flags & IORING_ASYNC_CANCEL_ANY) &&
7300 cd->data != req->cqe.user_data)
7301 continue;
7302 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7303 if (cd->seq == req->work.cancel_seq)
7304 continue;
7305 req->work.cancel_seq = cd->seq;
7306 }
7307 found = true;
7308 break;
7309 }
7310 if (!found)
7311 return ERR_PTR(-ENOENT);
7312
7313 io = req->async_data;
7314 if (hrtimer_try_to_cancel(&io->timer) == -1)
7315 return ERR_PTR(-EALREADY);
7316 list_del_init(&req->timeout.list);
7317 return req;
7318 }
7319
io_timeout_cancel(struct io_ring_ctx * ctx,struct io_cancel_data * cd)7320 static int io_timeout_cancel(struct io_ring_ctx *ctx, struct io_cancel_data *cd)
7321 __must_hold(&ctx->completion_lock)
7322 {
7323 struct io_kiocb *req;
7324
7325 spin_lock_irq(&ctx->timeout_lock);
7326 req = io_timeout_extract(ctx, cd);
7327 spin_unlock_irq(&ctx->timeout_lock);
7328
7329 if (IS_ERR(req))
7330 return PTR_ERR(req);
7331 io_req_task_queue_fail(req, -ECANCELED);
7332 return 0;
7333 }
7334
io_timeout_get_clock(struct io_timeout_data * data)7335 static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
7336 {
7337 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
7338 case IORING_TIMEOUT_BOOTTIME:
7339 return CLOCK_BOOTTIME;
7340 case IORING_TIMEOUT_REALTIME:
7341 return CLOCK_REALTIME;
7342 default:
7343 /* can't happen, vetted at prep time */
7344 WARN_ON_ONCE(1);
7345 fallthrough;
7346 case 0:
7347 return CLOCK_MONOTONIC;
7348 }
7349 }
7350
io_linked_timeout_update(struct io_ring_ctx * ctx,__u64 user_data,struct timespec64 * ts,enum hrtimer_mode mode)7351 static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7352 struct timespec64 *ts, enum hrtimer_mode mode)
7353 __must_hold(&ctx->timeout_lock)
7354 {
7355 struct io_timeout_data *io;
7356 struct io_kiocb *req;
7357 bool found = false;
7358
7359 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
7360 found = user_data == req->cqe.user_data;
7361 if (found)
7362 break;
7363 }
7364 if (!found)
7365 return -ENOENT;
7366
7367 io = req->async_data;
7368 if (hrtimer_try_to_cancel(&io->timer) == -1)
7369 return -EALREADY;
7370 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
7371 io->timer.function = io_link_timeout_fn;
7372 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
7373 return 0;
7374 }
7375
io_timeout_update(struct io_ring_ctx * ctx,__u64 user_data,struct timespec64 * ts,enum hrtimer_mode mode)7376 static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
7377 struct timespec64 *ts, enum hrtimer_mode mode)
7378 __must_hold(&ctx->timeout_lock)
7379 {
7380 struct io_cancel_data cd = { .data = user_data, };
7381 struct io_kiocb *req = io_timeout_extract(ctx, &cd);
7382 struct io_timeout_data *data;
7383
7384 if (IS_ERR(req))
7385 return PTR_ERR(req);
7386
7387 req->timeout.off = 0; /* noseq */
7388 data = req->async_data;
7389 list_add_tail(&req->timeout.list, &ctx->timeout_list);
7390 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
7391 data->timer.function = io_timeout_fn;
7392 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
7393 return 0;
7394 }
7395
io_timeout_remove_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)7396 static int io_timeout_remove_prep(struct io_kiocb *req,
7397 const struct io_uring_sqe *sqe)
7398 {
7399 struct io_timeout_rem *tr = &req->timeout_rem;
7400
7401 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7402 return -EINVAL;
7403 if (sqe->buf_index || sqe->len || sqe->splice_fd_in)
7404 return -EINVAL;
7405
7406 tr->ltimeout = false;
7407 tr->addr = READ_ONCE(sqe->addr);
7408 tr->flags = READ_ONCE(sqe->timeout_flags);
7409 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
7410 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7411 return -EINVAL;
7412 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
7413 tr->ltimeout = true;
7414 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
7415 return -EINVAL;
7416 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
7417 return -EFAULT;
7418 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
7419 return -EINVAL;
7420 } else if (tr->flags) {
7421 /* timeout removal doesn't support flags */
7422 return -EINVAL;
7423 }
7424
7425 return 0;
7426 }
7427
io_translate_timeout_mode(unsigned int flags)7428 static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
7429 {
7430 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
7431 : HRTIMER_MODE_REL;
7432 }
7433
7434 /*
7435 * Remove or update an existing timeout command
7436 */
io_timeout_remove(struct io_kiocb * req,unsigned int issue_flags)7437 static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
7438 {
7439 struct io_timeout_rem *tr = &req->timeout_rem;
7440 struct io_ring_ctx *ctx = req->ctx;
7441 int ret;
7442
7443 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
7444 struct io_cancel_data cd = { .data = tr->addr, };
7445
7446 spin_lock(&ctx->completion_lock);
7447 ret = io_timeout_cancel(ctx, &cd);
7448 spin_unlock(&ctx->completion_lock);
7449 } else {
7450 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
7451
7452 spin_lock_irq(&ctx->timeout_lock);
7453 if (tr->ltimeout)
7454 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
7455 else
7456 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
7457 spin_unlock_irq(&ctx->timeout_lock);
7458 }
7459
7460 if (ret < 0)
7461 req_set_fail(req);
7462 io_req_complete_post(req, ret, 0);
7463 return 0;
7464 }
7465
__io_timeout_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe,bool is_timeout_link)7466 static int __io_timeout_prep(struct io_kiocb *req,
7467 const struct io_uring_sqe *sqe,
7468 bool is_timeout_link)
7469 {
7470 struct io_timeout_data *data;
7471 unsigned flags;
7472 u32 off = READ_ONCE(sqe->off);
7473
7474 if (sqe->buf_index || sqe->len != 1 || sqe->splice_fd_in)
7475 return -EINVAL;
7476 if (off && is_timeout_link)
7477 return -EINVAL;
7478 flags = READ_ONCE(sqe->timeout_flags);
7479 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
7480 IORING_TIMEOUT_ETIME_SUCCESS))
7481 return -EINVAL;
7482 /* more than one clock specified is invalid, obviously */
7483 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
7484 return -EINVAL;
7485
7486 INIT_LIST_HEAD(&req->timeout.list);
7487 req->timeout.off = off;
7488 if (unlikely(off && !req->ctx->off_timeout_used))
7489 req->ctx->off_timeout_used = true;
7490
7491 if (WARN_ON_ONCE(req_has_async_data(req)))
7492 return -EFAULT;
7493 if (io_alloc_async_data(req))
7494 return -ENOMEM;
7495
7496 data = req->async_data;
7497 data->req = req;
7498 data->flags = flags;
7499
7500 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
7501 return -EFAULT;
7502
7503 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
7504 return -EINVAL;
7505
7506 INIT_LIST_HEAD(&req->timeout.list);
7507 data->mode = io_translate_timeout_mode(flags);
7508 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
7509
7510 if (is_timeout_link) {
7511 struct io_submit_link *link = &req->ctx->submit_state.link;
7512
7513 if (!link->head)
7514 return -EINVAL;
7515 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
7516 return -EINVAL;
7517 req->timeout.head = link->last;
7518 link->last->flags |= REQ_F_ARM_LTIMEOUT;
7519 }
7520 return 0;
7521 }
7522
io_timeout_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)7523 static int io_timeout_prep(struct io_kiocb *req,
7524 const struct io_uring_sqe *sqe)
7525 {
7526 return __io_timeout_prep(req, sqe, false);
7527 }
7528
io_link_timeout_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)7529 static int io_link_timeout_prep(struct io_kiocb *req,
7530 const struct io_uring_sqe *sqe)
7531 {
7532 return __io_timeout_prep(req, sqe, true);
7533 }
7534
io_timeout(struct io_kiocb * req,unsigned int issue_flags)7535 static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
7536 {
7537 struct io_ring_ctx *ctx = req->ctx;
7538 struct io_timeout_data *data = req->async_data;
7539 struct list_head *entry;
7540 u32 tail, off = req->timeout.off;
7541
7542 spin_lock_irq(&ctx->timeout_lock);
7543
7544 /*
7545 * sqe->off holds how many events that need to occur for this
7546 * timeout event to be satisfied. If it isn't set, then this is
7547 * a pure timeout request, sequence isn't used.
7548 */
7549 if (io_is_timeout_noseq(req)) {
7550 entry = ctx->timeout_list.prev;
7551 goto add;
7552 }
7553
7554 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
7555 req->timeout.target_seq = tail + off;
7556
7557 /* Update the last seq here in case io_flush_timeouts() hasn't.
7558 * This is safe because ->completion_lock is held, and submissions
7559 * and completions are never mixed in the same ->completion_lock section.
7560 */
7561 ctx->cq_last_tm_flush = tail;
7562
7563 /*
7564 * Insertion sort, ensuring the first entry in the list is always
7565 * the one we need first.
7566 */
7567 list_for_each_prev(entry, &ctx->timeout_list) {
7568 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
7569 timeout.list);
7570
7571 if (io_is_timeout_noseq(nxt))
7572 continue;
7573 /* nxt.seq is behind @tail, otherwise would've been completed */
7574 if (off >= nxt->timeout.target_seq - tail)
7575 break;
7576 }
7577 add:
7578 list_add(&req->timeout.list, entry);
7579 data->timer.function = io_timeout_fn;
7580 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
7581 spin_unlock_irq(&ctx->timeout_lock);
7582 return 0;
7583 }
7584
io_cancel_cb(struct io_wq_work * work,void * data)7585 static bool io_cancel_cb(struct io_wq_work *work, void *data)
7586 {
7587 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7588 struct io_cancel_data *cd = data;
7589
7590 if (req->ctx != cd->ctx)
7591 return false;
7592 if (cd->flags & IORING_ASYNC_CANCEL_ANY) {
7593 ;
7594 } else if (cd->flags & IORING_ASYNC_CANCEL_FD) {
7595 if (req->file != cd->file)
7596 return false;
7597 } else {
7598 if (req->cqe.user_data != cd->data)
7599 return false;
7600 }
7601 if (cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY)) {
7602 if (cd->seq == req->work.cancel_seq)
7603 return false;
7604 req->work.cancel_seq = cd->seq;
7605 }
7606 return true;
7607 }
7608
io_async_cancel_one(struct io_uring_task * tctx,struct io_cancel_data * cd)7609 static int io_async_cancel_one(struct io_uring_task *tctx,
7610 struct io_cancel_data *cd)
7611 {
7612 enum io_wq_cancel cancel_ret;
7613 int ret = 0;
7614 bool all;
7615
7616 if (!tctx || !tctx->io_wq)
7617 return -ENOENT;
7618
7619 all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7620 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, cd, all);
7621 switch (cancel_ret) {
7622 case IO_WQ_CANCEL_OK:
7623 ret = 0;
7624 break;
7625 case IO_WQ_CANCEL_RUNNING:
7626 ret = -EALREADY;
7627 break;
7628 case IO_WQ_CANCEL_NOTFOUND:
7629 ret = -ENOENT;
7630 break;
7631 }
7632
7633 return ret;
7634 }
7635
io_try_cancel(struct io_kiocb * req,struct io_cancel_data * cd)7636 static int io_try_cancel(struct io_kiocb *req, struct io_cancel_data *cd)
7637 {
7638 struct io_ring_ctx *ctx = req->ctx;
7639 int ret;
7640
7641 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
7642
7643 ret = io_async_cancel_one(req->task->io_uring, cd);
7644 /*
7645 * Fall-through even for -EALREADY, as we may have poll armed
7646 * that need unarming.
7647 */
7648 if (!ret)
7649 return 0;
7650
7651 spin_lock(&ctx->completion_lock);
7652 ret = io_poll_cancel(ctx, cd);
7653 if (ret != -ENOENT)
7654 goto out;
7655 if (!(cd->flags & IORING_ASYNC_CANCEL_FD))
7656 ret = io_timeout_cancel(ctx, cd);
7657 out:
7658 spin_unlock(&ctx->completion_lock);
7659 return ret;
7660 }
7661
7662 #define CANCEL_FLAGS (IORING_ASYNC_CANCEL_ALL | IORING_ASYNC_CANCEL_FD | \
7663 IORING_ASYNC_CANCEL_ANY)
7664
io_async_cancel_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)7665 static int io_async_cancel_prep(struct io_kiocb *req,
7666 const struct io_uring_sqe *sqe)
7667 {
7668 if (unlikely(req->flags & REQ_F_BUFFER_SELECT))
7669 return -EINVAL;
7670 if (sqe->off || sqe->len || sqe->splice_fd_in)
7671 return -EINVAL;
7672
7673 req->cancel.addr = READ_ONCE(sqe->addr);
7674 req->cancel.flags = READ_ONCE(sqe->cancel_flags);
7675 if (req->cancel.flags & ~CANCEL_FLAGS)
7676 return -EINVAL;
7677 if (req->cancel.flags & IORING_ASYNC_CANCEL_FD) {
7678 if (req->cancel.flags & IORING_ASYNC_CANCEL_ANY)
7679 return -EINVAL;
7680 req->cancel.fd = READ_ONCE(sqe->fd);
7681 }
7682
7683 return 0;
7684 }
7685
__io_async_cancel(struct io_cancel_data * cd,struct io_kiocb * req,unsigned int issue_flags)7686 static int __io_async_cancel(struct io_cancel_data *cd, struct io_kiocb *req,
7687 unsigned int issue_flags)
7688 {
7689 bool all = cd->flags & (IORING_ASYNC_CANCEL_ALL|IORING_ASYNC_CANCEL_ANY);
7690 struct io_ring_ctx *ctx = cd->ctx;
7691 struct io_tctx_node *node;
7692 int ret, nr = 0;
7693
7694 do {
7695 ret = io_try_cancel(req, cd);
7696 if (ret == -ENOENT)
7697 break;
7698 if (!all)
7699 return ret;
7700 nr++;
7701 } while (1);
7702
7703 /* slow path, try all io-wq's */
7704 io_ring_submit_lock(ctx, issue_flags);
7705 ret = -ENOENT;
7706 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
7707 struct io_uring_task *tctx = node->task->io_uring;
7708
7709 ret = io_async_cancel_one(tctx, cd);
7710 if (ret != -ENOENT) {
7711 if (!all)
7712 break;
7713 nr++;
7714 }
7715 }
7716 io_ring_submit_unlock(ctx, issue_flags);
7717 return all ? nr : ret;
7718 }
7719
io_async_cancel(struct io_kiocb * req,unsigned int issue_flags)7720 static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
7721 {
7722 struct io_cancel_data cd = {
7723 .ctx = req->ctx,
7724 .data = req->cancel.addr,
7725 .flags = req->cancel.flags,
7726 .seq = atomic_inc_return(&req->ctx->cancel_seq),
7727 };
7728 int ret;
7729
7730 if (cd.flags & IORING_ASYNC_CANCEL_FD) {
7731 if (req->flags & REQ_F_FIXED_FILE)
7732 req->file = io_file_get_fixed(req, req->cancel.fd,
7733 issue_flags);
7734 else
7735 req->file = io_file_get_normal(req, req->cancel.fd);
7736 if (!req->file) {
7737 ret = -EBADF;
7738 goto done;
7739 }
7740 cd.file = req->file;
7741 }
7742
7743 ret = __io_async_cancel(&cd, req, issue_flags);
7744 done:
7745 if (ret < 0)
7746 req_set_fail(req);
7747 io_req_complete_post(req, ret, 0);
7748 return 0;
7749 }
7750
io_files_update_prep(struct io_kiocb * req,const struct io_uring_sqe * sqe)7751 static int io_files_update_prep(struct io_kiocb *req,
7752 const struct io_uring_sqe *sqe)
7753 {
7754 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
7755 return -EINVAL;
7756 if (sqe->rw_flags || sqe->splice_fd_in)
7757 return -EINVAL;
7758
7759 req->rsrc_update.offset = READ_ONCE(sqe->off);
7760 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
7761 if (!req->rsrc_update.nr_args)
7762 return -EINVAL;
7763 req->rsrc_update.arg = READ_ONCE(sqe->addr);
7764 return 0;
7765 }
7766
io_files_update_with_index_alloc(struct io_kiocb * req,unsigned int issue_flags)7767 static int io_files_update_with_index_alloc(struct io_kiocb *req,
7768 unsigned int issue_flags)
7769 {
7770 __s32 __user *fds = u64_to_user_ptr(req->rsrc_update.arg);
7771 unsigned int done;
7772 struct file *file;
7773 int ret, fd;
7774
7775 if (!req->ctx->file_data)
7776 return -ENXIO;
7777
7778 for (done = 0; done < req->rsrc_update.nr_args; done++) {
7779 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7780 ret = -EFAULT;
7781 break;
7782 }
7783
7784 file = fget(fd);
7785 if (!file) {
7786 ret = -EBADF;
7787 break;
7788 }
7789 ret = io_fixed_fd_install(req, issue_flags, file,
7790 IORING_FILE_INDEX_ALLOC);
7791 if (ret < 0)
7792 break;
7793 if (copy_to_user(&fds[done], &ret, sizeof(ret))) {
7794 __io_close_fixed(req, issue_flags, ret);
7795 ret = -EFAULT;
7796 break;
7797 }
7798 }
7799
7800 if (done)
7801 return done;
7802 return ret;
7803 }
7804
io_files_update(struct io_kiocb * req,unsigned int issue_flags)7805 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
7806 {
7807 struct io_ring_ctx *ctx = req->ctx;
7808 struct io_uring_rsrc_update2 up;
7809 int ret;
7810
7811 up.offset = req->rsrc_update.offset;
7812 up.data = req->rsrc_update.arg;
7813 up.nr = 0;
7814 up.tags = 0;
7815 up.resv = 0;
7816 up.resv2 = 0;
7817
7818 if (req->rsrc_update.offset == IORING_FILE_INDEX_ALLOC) {
7819 ret = io_files_update_with_index_alloc(req, issue_flags);
7820 } else {
7821 io_ring_submit_lock(ctx, issue_flags);
7822 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
7823 &up, req->rsrc_update.nr_args);
7824 io_ring_submit_unlock(ctx, issue_flags);
7825 }
7826
7827 if (ret < 0)
7828 req_set_fail(req);
7829 __io_req_complete(req, issue_flags, ret, 0);
7830 return 0;
7831 }
7832
io_req_prep_async(struct io_kiocb * req)7833 static int io_req_prep_async(struct io_kiocb *req)
7834 {
7835 const struct io_op_def *def = &io_op_defs[req->opcode];
7836
7837 /* assign early for deferred execution for non-fixed file */
7838 if (def->needs_file && !(req->flags & REQ_F_FIXED_FILE))
7839 req->file = io_file_get_normal(req, req->cqe.fd);
7840 if (!def->needs_async_setup)
7841 return 0;
7842 if (WARN_ON_ONCE(req_has_async_data(req)))
7843 return -EFAULT;
7844 if (io_alloc_async_data(req))
7845 return -EAGAIN;
7846
7847 switch (req->opcode) {
7848 case IORING_OP_READV:
7849 return io_readv_prep_async(req);
7850 case IORING_OP_WRITEV:
7851 return io_writev_prep_async(req);
7852 case IORING_OP_SENDMSG:
7853 return io_sendmsg_prep_async(req);
7854 case IORING_OP_RECVMSG:
7855 return io_recvmsg_prep_async(req);
7856 case IORING_OP_CONNECT:
7857 return io_connect_prep_async(req);
7858 case IORING_OP_URING_CMD:
7859 return io_uring_cmd_prep_async(req);
7860 }
7861
7862 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
7863 req->opcode);
7864 return -EINVAL;
7865 }
7866
io_get_sequence(struct io_kiocb * req)7867 static u32 io_get_sequence(struct io_kiocb *req)
7868 {
7869 u32 seq = req->ctx->cached_sq_head;
7870 struct io_kiocb *cur;
7871
7872 /* need original cached_sq_head, but it was increased for each req */
7873 io_for_each_link(cur, req)
7874 seq--;
7875 return seq;
7876 }
7877
io_drain_req(struct io_kiocb * req)7878 static __cold void io_drain_req(struct io_kiocb *req)
7879 {
7880 struct io_ring_ctx *ctx = req->ctx;
7881 struct io_defer_entry *de;
7882 int ret;
7883 u32 seq = io_get_sequence(req);
7884
7885 /* Still need defer if there is pending req in defer list. */
7886 spin_lock(&ctx->completion_lock);
7887 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
7888 spin_unlock(&ctx->completion_lock);
7889 queue:
7890 ctx->drain_active = false;
7891 io_req_task_queue(req);
7892 return;
7893 }
7894 spin_unlock(&ctx->completion_lock);
7895
7896 ret = io_req_prep_async(req);
7897 if (ret) {
7898 fail:
7899 io_req_complete_failed(req, ret);
7900 return;
7901 }
7902 io_prep_async_link(req);
7903 de = kmalloc(sizeof(*de), GFP_KERNEL);
7904 if (!de) {
7905 ret = -ENOMEM;
7906 goto fail;
7907 }
7908
7909 spin_lock(&ctx->completion_lock);
7910 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
7911 spin_unlock(&ctx->completion_lock);
7912 kfree(de);
7913 goto queue;
7914 }
7915
7916 trace_io_uring_defer(ctx, req, req->cqe.user_data, req->opcode);
7917 de->req = req;
7918 de->seq = seq;
7919 list_add_tail(&de->list, &ctx->defer_list);
7920 spin_unlock(&ctx->completion_lock);
7921 }
7922
io_clean_op(struct io_kiocb * req)7923 static void io_clean_op(struct io_kiocb *req)
7924 {
7925 if (req->flags & REQ_F_BUFFER_SELECTED) {
7926 spin_lock(&req->ctx->completion_lock);
7927 io_put_kbuf_comp(req);
7928 spin_unlock(&req->ctx->completion_lock);
7929 }
7930
7931 if (req->flags & REQ_F_NEED_CLEANUP) {
7932 switch (req->opcode) {
7933 case IORING_OP_READV:
7934 case IORING_OP_READ_FIXED:
7935 case IORING_OP_READ:
7936 case IORING_OP_WRITEV:
7937 case IORING_OP_WRITE_FIXED:
7938 case IORING_OP_WRITE: {
7939 struct io_async_rw *io = req->async_data;
7940
7941 kfree(io->free_iovec);
7942 break;
7943 }
7944 case IORING_OP_RECVMSG:
7945 case IORING_OP_SENDMSG: {
7946 struct io_async_msghdr *io = req->async_data;
7947
7948 kfree(io->free_iov);
7949 break;
7950 }
7951 case IORING_OP_OPENAT:
7952 case IORING_OP_OPENAT2:
7953 if (req->open.filename)
7954 putname(req->open.filename);
7955 break;
7956 case IORING_OP_RENAMEAT:
7957 putname(req->rename.oldpath);
7958 putname(req->rename.newpath);
7959 break;
7960 case IORING_OP_UNLINKAT:
7961 putname(req->unlink.filename);
7962 break;
7963 case IORING_OP_MKDIRAT:
7964 putname(req->mkdir.filename);
7965 break;
7966 case IORING_OP_SYMLINKAT:
7967 putname(req->symlink.oldpath);
7968 putname(req->symlink.newpath);
7969 break;
7970 case IORING_OP_LINKAT:
7971 putname(req->hardlink.oldpath);
7972 putname(req->hardlink.newpath);
7973 break;
7974 case IORING_OP_STATX:
7975 if (req->statx.filename)
7976 putname(req->statx.filename);
7977 break;
7978 case IORING_OP_SETXATTR:
7979 case IORING_OP_FSETXATTR:
7980 case IORING_OP_GETXATTR:
7981 case IORING_OP_FGETXATTR:
7982 __io_xattr_finish(req);
7983 break;
7984 }
7985 }
7986 if ((req->flags & REQ_F_POLLED) && req->apoll) {
7987 kfree(req->apoll->double_poll);
7988 kfree(req->apoll);
7989 req->apoll = NULL;
7990 }
7991 if (req->flags & REQ_F_INFLIGHT) {
7992 struct io_uring_task *tctx = req->task->io_uring;
7993
7994 atomic_dec(&tctx->inflight_tracked);
7995 }
7996 if (req->flags & REQ_F_CREDS)
7997 put_cred(req->creds);
7998 if (req->flags & REQ_F_ASYNC_DATA) {
7999 kfree(req->async_data);
8000 req->async_data = NULL;
8001 }
8002 req->flags &= ~IO_REQ_CLEAN_FLAGS;
8003 }
8004
io_assign_file(struct io_kiocb * req,unsigned int issue_flags)8005 static bool io_assign_file(struct io_kiocb *req, unsigned int issue_flags)
8006 {
8007 if (req->file || !io_op_defs[req->opcode].needs_file)
8008 return true;
8009
8010 if (req->flags & REQ_F_FIXED_FILE)
8011 req->file = io_file_get_fixed(req, req->cqe.fd, issue_flags);
8012 else
8013 req->file = io_file_get_normal(req, req->cqe.fd);
8014
8015 return !!req->file;
8016 }
8017
io_issue_sqe(struct io_kiocb * req,unsigned int issue_flags)8018 static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
8019 {
8020 const struct io_op_def *def = &io_op_defs[req->opcode];
8021 const struct cred *creds = NULL;
8022 int ret;
8023
8024 if (unlikely(!io_assign_file(req, issue_flags)))
8025 return -EBADF;
8026
8027 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
8028 creds = override_creds(req->creds);
8029
8030 if (!def->audit_skip)
8031 audit_uring_entry(req->opcode);
8032
8033 ret = def->issue(req, issue_flags);
8034
8035 if (!def->audit_skip)
8036 audit_uring_exit(!ret, ret);
8037
8038 if (creds)
8039 revert_creds(creds);
8040 if (ret)
8041 return ret;
8042 /* If the op doesn't have a file, we're not polling for it */
8043 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
8044 io_iopoll_req_issued(req, issue_flags);
8045
8046 return 0;
8047 }
8048
io_wq_free_work(struct io_wq_work * work)8049 static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
8050 {
8051 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8052
8053 req = io_put_req_find_next(req);
8054 return req ? &req->work : NULL;
8055 }
8056
io_wq_submit_work(struct io_wq_work * work)8057 static void io_wq_submit_work(struct io_wq_work *work)
8058 {
8059 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
8060 const struct io_op_def *def = &io_op_defs[req->opcode];
8061 unsigned int issue_flags = IO_URING_F_UNLOCKED;
8062 bool needs_poll = false;
8063 int ret = 0, err = -ECANCELED;
8064
8065 /* one will be dropped by ->io_free_work() after returning to io-wq */
8066 if (!(req->flags & REQ_F_REFCOUNT))
8067 __io_req_set_refcount(req, 2);
8068 else
8069 req_ref_get(req);
8070
8071 io_arm_ltimeout(req);
8072
8073 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
8074 if (work->flags & IO_WQ_WORK_CANCEL) {
8075 fail:
8076 io_req_task_queue_fail(req, err);
8077 return;
8078 }
8079 if (!io_assign_file(req, issue_flags)) {
8080 err = -EBADF;
8081 work->flags |= IO_WQ_WORK_CANCEL;
8082 goto fail;
8083 }
8084
8085 if (req->flags & REQ_F_FORCE_ASYNC) {
8086 bool opcode_poll = def->pollin || def->pollout;
8087
8088 if (opcode_poll && file_can_poll(req->file)) {
8089 needs_poll = true;
8090 issue_flags |= IO_URING_F_NONBLOCK;
8091 }
8092 }
8093
8094 do {
8095 ret = io_issue_sqe(req, issue_flags);
8096 if (ret != -EAGAIN)
8097 break;
8098 /*
8099 * We can get EAGAIN for iopolled IO even though we're
8100 * forcing a sync submission from here, since we can't
8101 * wait for request slots on the block side.
8102 */
8103 if (!needs_poll) {
8104 if (!(req->ctx->flags & IORING_SETUP_IOPOLL))
8105 break;
8106 cond_resched();
8107 continue;
8108 }
8109
8110 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
8111 return;
8112 /* aborted or ready, in either case retry blocking */
8113 needs_poll = false;
8114 issue_flags &= ~IO_URING_F_NONBLOCK;
8115 } while (1);
8116
8117 /* avoid locking problems by failing it from a clean context */
8118 if (ret)
8119 io_req_task_queue_fail(req, ret);
8120 }
8121
io_fixed_file_slot(struct io_file_table * table,unsigned i)8122 static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
8123 unsigned i)
8124 {
8125 return &table->files[i];
8126 }
8127
io_file_from_index(struct io_ring_ctx * ctx,int index)8128 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
8129 int index)
8130 {
8131 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
8132
8133 return (struct file *) (slot->file_ptr & FFS_MASK);
8134 }
8135
io_fixed_file_set(struct io_fixed_file * file_slot,struct file * file)8136 static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
8137 {
8138 unsigned long file_ptr = (unsigned long) file;
8139
8140 file_ptr |= io_file_get_flags(file);
8141 file_slot->file_ptr = file_ptr;
8142 }
8143
io_file_get_fixed(struct io_kiocb * req,int fd,unsigned int issue_flags)8144 static inline struct file *io_file_get_fixed(struct io_kiocb *req, int fd,
8145 unsigned int issue_flags)
8146 {
8147 struct io_ring_ctx *ctx = req->ctx;
8148 struct file *file = NULL;
8149 unsigned long file_ptr;
8150
8151 io_ring_submit_lock(ctx, issue_flags);
8152
8153 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
8154 goto out;
8155 fd = array_index_nospec(fd, ctx->nr_user_files);
8156 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
8157 file = (struct file *) (file_ptr & FFS_MASK);
8158 file_ptr &= ~FFS_MASK;
8159 /* mask in overlapping REQ_F and FFS bits */
8160 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
8161 io_req_set_rsrc_node(req, ctx, 0);
8162 WARN_ON_ONCE(file && !test_bit(fd, ctx->file_table.bitmap));
8163 out:
8164 io_ring_submit_unlock(ctx, issue_flags);
8165 return file;
8166 }
8167
io_file_get_normal(struct io_kiocb * req,int fd)8168 static struct file *io_file_get_normal(struct io_kiocb *req, int fd)
8169 {
8170 struct file *file = fget(fd);
8171
8172 trace_io_uring_file_get(req->ctx, req, req->cqe.user_data, fd);
8173
8174 /* we don't allow fixed io_uring files */
8175 if (file && file->f_op == &io_uring_fops)
8176 io_req_track_inflight(req);
8177 return file;
8178 }
8179
io_req_task_link_timeout(struct io_kiocb * req,bool * locked)8180 static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
8181 {
8182 struct io_kiocb *prev = req->timeout.prev;
8183 int ret = -ENOENT;
8184
8185 if (prev) {
8186 if (!(req->task->flags & PF_EXITING)) {
8187 struct io_cancel_data cd = {
8188 .ctx = req->ctx,
8189 .data = prev->cqe.user_data,
8190 };
8191
8192 ret = io_try_cancel(req, &cd);
8193 }
8194 io_req_complete_post(req, ret ?: -ETIME, 0);
8195 io_put_req(prev);
8196 } else {
8197 io_req_complete_post(req, -ETIME, 0);
8198 }
8199 }
8200
io_link_timeout_fn(struct hrtimer * timer)8201 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
8202 {
8203 struct io_timeout_data *data = container_of(timer,
8204 struct io_timeout_data, timer);
8205 struct io_kiocb *prev, *req = data->req;
8206 struct io_ring_ctx *ctx = req->ctx;
8207 unsigned long flags;
8208
8209 spin_lock_irqsave(&ctx->timeout_lock, flags);
8210 prev = req->timeout.head;
8211 req->timeout.head = NULL;
8212
8213 /*
8214 * We don't expect the list to be empty, that will only happen if we
8215 * race with the completion of the linked work.
8216 */
8217 if (prev) {
8218 io_remove_next_linked(prev);
8219 if (!req_ref_inc_not_zero(prev))
8220 prev = NULL;
8221 }
8222 list_del(&req->timeout.list);
8223 req->timeout.prev = prev;
8224 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
8225
8226 req->io_task_work.func = io_req_task_link_timeout;
8227 io_req_task_work_add(req);
8228 return HRTIMER_NORESTART;
8229 }
8230
io_queue_linked_timeout(struct io_kiocb * req)8231 static void io_queue_linked_timeout(struct io_kiocb *req)
8232 {
8233 struct io_ring_ctx *ctx = req->ctx;
8234
8235 spin_lock_irq(&ctx->timeout_lock);
8236 /*
8237 * If the back reference is NULL, then our linked request finished
8238 * before we got a chance to setup the timer
8239 */
8240 if (req->timeout.head) {
8241 struct io_timeout_data *data = req->async_data;
8242
8243 data->timer.function = io_link_timeout_fn;
8244 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
8245 data->mode);
8246 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
8247 }
8248 spin_unlock_irq(&ctx->timeout_lock);
8249 /* drop submission reference */
8250 io_put_req(req);
8251 }
8252
io_queue_async(struct io_kiocb * req,int ret)8253 static void io_queue_async(struct io_kiocb *req, int ret)
8254 __must_hold(&req->ctx->uring_lock)
8255 {
8256 struct io_kiocb *linked_timeout;
8257
8258 if (ret != -EAGAIN || (req->flags & REQ_F_NOWAIT)) {
8259 io_req_complete_failed(req, ret);
8260 return;
8261 }
8262
8263 linked_timeout = io_prep_linked_timeout(req);
8264
8265 switch (io_arm_poll_handler(req, 0)) {
8266 case IO_APOLL_READY:
8267 io_kbuf_recycle(req, 0);
8268 io_req_task_queue(req);
8269 break;
8270 case IO_APOLL_ABORTED:
8271 /*
8272 * Queued up for async execution, worker will release
8273 * submit reference when the iocb is actually submitted.
8274 */
8275 io_kbuf_recycle(req, 0);
8276 io_queue_iowq(req, NULL);
8277 break;
8278 case IO_APOLL_OK:
8279 break;
8280 }
8281
8282 if (linked_timeout)
8283 io_queue_linked_timeout(linked_timeout);
8284 }
8285
io_queue_sqe(struct io_kiocb * req)8286 static inline void io_queue_sqe(struct io_kiocb *req)
8287 __must_hold(&req->ctx->uring_lock)
8288 {
8289 int ret;
8290
8291 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
8292
8293 if (req->flags & REQ_F_COMPLETE_INLINE) {
8294 io_req_add_compl_list(req);
8295 return;
8296 }
8297 /*
8298 * We async punt it if the file wasn't marked NOWAIT, or if the file
8299 * doesn't support non-blocking read/write attempts
8300 */
8301 if (likely(!ret))
8302 io_arm_ltimeout(req);
8303 else
8304 io_queue_async(req, ret);
8305 }
8306
io_queue_sqe_fallback(struct io_kiocb * req)8307 static void io_queue_sqe_fallback(struct io_kiocb *req)
8308 __must_hold(&req->ctx->uring_lock)
8309 {
8310 if (unlikely(req->flags & REQ_F_FAIL)) {
8311 /*
8312 * We don't submit, fail them all, for that replace hardlinks
8313 * with normal links. Extra REQ_F_LINK is tolerated.
8314 */
8315 req->flags &= ~REQ_F_HARDLINK;
8316 req->flags |= REQ_F_LINK;
8317 io_req_complete_failed(req, req->cqe.res);
8318 } else if (unlikely(req->ctx->drain_active)) {
8319 io_drain_req(req);
8320 } else {
8321 int ret = io_req_prep_async(req);
8322
8323 if (unlikely(ret))
8324 io_req_complete_failed(req, ret);
8325 else
8326 io_queue_iowq(req, NULL);
8327 }
8328 }
8329
8330 /*
8331 * Check SQE restrictions (opcode and flags).
8332 *
8333 * Returns 'true' if SQE is allowed, 'false' otherwise.
8334 */
io_check_restriction(struct io_ring_ctx * ctx,struct io_kiocb * req,unsigned int sqe_flags)8335 static inline bool io_check_restriction(struct io_ring_ctx *ctx,
8336 struct io_kiocb *req,
8337 unsigned int sqe_flags)
8338 {
8339 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
8340 return false;
8341
8342 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
8343 ctx->restrictions.sqe_flags_required)
8344 return false;
8345
8346 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
8347 ctx->restrictions.sqe_flags_required))
8348 return false;
8349
8350 return true;
8351 }
8352
io_init_req_drain(struct io_kiocb * req)8353 static void io_init_req_drain(struct io_kiocb *req)
8354 {
8355 struct io_ring_ctx *ctx = req->ctx;
8356 struct io_kiocb *head = ctx->submit_state.link.head;
8357
8358 ctx->drain_active = true;
8359 if (head) {
8360 /*
8361 * If we need to drain a request in the middle of a link, drain
8362 * the head request and the next request/link after the current
8363 * link. Considering sequential execution of links,
8364 * REQ_F_IO_DRAIN will be maintained for every request of our
8365 * link.
8366 */
8367 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8368 ctx->drain_next = true;
8369 }
8370 }
8371
io_init_req(struct io_ring_ctx * ctx,struct io_kiocb * req,const struct io_uring_sqe * sqe)8372 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
8373 const struct io_uring_sqe *sqe)
8374 __must_hold(&ctx->uring_lock)
8375 {
8376 const struct io_op_def *def;
8377 unsigned int sqe_flags;
8378 int personality;
8379 u8 opcode;
8380
8381 /* req is partially pre-initialised, see io_preinit_req() */
8382 req->opcode = opcode = READ_ONCE(sqe->opcode);
8383 /* same numerical values with corresponding REQ_F_*, safe to copy */
8384 req->flags = sqe_flags = READ_ONCE(sqe->flags);
8385 req->cqe.user_data = READ_ONCE(sqe->user_data);
8386 req->file = NULL;
8387 req->rsrc_node = NULL;
8388 req->task = current;
8389
8390 if (unlikely(opcode >= IORING_OP_LAST)) {
8391 req->opcode = 0;
8392 return -EINVAL;
8393 }
8394 def = &io_op_defs[opcode];
8395 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
8396 /* enforce forwards compatibility on users */
8397 if (sqe_flags & ~SQE_VALID_FLAGS)
8398 return -EINVAL;
8399 if (sqe_flags & IOSQE_BUFFER_SELECT) {
8400 if (!def->buffer_select)
8401 return -EOPNOTSUPP;
8402 req->buf_index = READ_ONCE(sqe->buf_group);
8403 }
8404 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
8405 ctx->drain_disabled = true;
8406 if (sqe_flags & IOSQE_IO_DRAIN) {
8407 if (ctx->drain_disabled)
8408 return -EOPNOTSUPP;
8409 io_init_req_drain(req);
8410 }
8411 }
8412 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
8413 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
8414 return -EACCES;
8415 /* knock it to the slow queue path, will be drained there */
8416 if (ctx->drain_active)
8417 req->flags |= REQ_F_FORCE_ASYNC;
8418 /* if there is no link, we're at "next" request and need to drain */
8419 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
8420 ctx->drain_next = false;
8421 ctx->drain_active = true;
8422 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
8423 }
8424 }
8425
8426 if (!def->ioprio && sqe->ioprio)
8427 return -EINVAL;
8428 if (!def->iopoll && (ctx->flags & IORING_SETUP_IOPOLL))
8429 return -EINVAL;
8430
8431 if (def->needs_file) {
8432 struct io_submit_state *state = &ctx->submit_state;
8433
8434 req->cqe.fd = READ_ONCE(sqe->fd);
8435
8436 /*
8437 * Plug now if we have more than 2 IO left after this, and the
8438 * target is potentially a read/write to block based storage.
8439 */
8440 if (state->need_plug && def->plug) {
8441 state->plug_started = true;
8442 state->need_plug = false;
8443 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
8444 }
8445 }
8446
8447 personality = READ_ONCE(sqe->personality);
8448 if (personality) {
8449 int ret;
8450
8451 req->creds = xa_load(&ctx->personalities, personality);
8452 if (!req->creds)
8453 return -EINVAL;
8454 get_cred(req->creds);
8455 ret = security_uring_override_creds(req->creds);
8456 if (ret) {
8457 put_cred(req->creds);
8458 return ret;
8459 }
8460 req->flags |= REQ_F_CREDS;
8461 }
8462
8463 return def->prep(req, sqe);
8464 }
8465
io_submit_fail_init(const struct io_uring_sqe * sqe,struct io_kiocb * req,int ret)8466 static __cold int io_submit_fail_init(const struct io_uring_sqe *sqe,
8467 struct io_kiocb *req, int ret)
8468 {
8469 struct io_ring_ctx *ctx = req->ctx;
8470 struct io_submit_link *link = &ctx->submit_state.link;
8471 struct io_kiocb *head = link->head;
8472
8473 trace_io_uring_req_failed(sqe, ctx, req, ret);
8474
8475 /*
8476 * Avoid breaking links in the middle as it renders links with SQPOLL
8477 * unusable. Instead of failing eagerly, continue assembling the link if
8478 * applicable and mark the head with REQ_F_FAIL. The link flushing code
8479 * should find the flag and handle the rest.
8480 */
8481 req_fail_link_node(req, ret);
8482 if (head && !(head->flags & REQ_F_FAIL))
8483 req_fail_link_node(head, -ECANCELED);
8484
8485 if (!(req->flags & IO_REQ_LINK_FLAGS)) {
8486 if (head) {
8487 link->last->link = req;
8488 link->head = NULL;
8489 req = head;
8490 }
8491 io_queue_sqe_fallback(req);
8492 return ret;
8493 }
8494
8495 if (head)
8496 link->last->link = req;
8497 else
8498 link->head = req;
8499 link->last = req;
8500 return 0;
8501 }
8502
io_submit_sqe(struct io_ring_ctx * ctx,struct io_kiocb * req,const struct io_uring_sqe * sqe)8503 static inline int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
8504 const struct io_uring_sqe *sqe)
8505 __must_hold(&ctx->uring_lock)
8506 {
8507 struct io_submit_link *link = &ctx->submit_state.link;
8508 int ret;
8509
8510 ret = io_init_req(ctx, req, sqe);
8511 if (unlikely(ret))
8512 return io_submit_fail_init(sqe, req, ret);
8513
8514 /* don't need @sqe from now on */
8515 trace_io_uring_submit_sqe(ctx, req, req->cqe.user_data, req->opcode,
8516 req->flags, true,
8517 ctx->flags & IORING_SETUP_SQPOLL);
8518
8519 /*
8520 * If we already have a head request, queue this one for async
8521 * submittal once the head completes. If we don't have a head but
8522 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
8523 * submitted sync once the chain is complete. If none of those
8524 * conditions are true (normal request), then just queue it.
8525 */
8526 if (unlikely(link->head)) {
8527 ret = io_req_prep_async(req);
8528 if (unlikely(ret))
8529 return io_submit_fail_init(sqe, req, ret);
8530
8531 trace_io_uring_link(ctx, req, link->head);
8532 link->last->link = req;
8533 link->last = req;
8534
8535 if (req->flags & IO_REQ_LINK_FLAGS)
8536 return 0;
8537 /* last request of the link, flush it */
8538 req = link->head;
8539 link->head = NULL;
8540 if (req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))
8541 goto fallback;
8542
8543 } else if (unlikely(req->flags & (IO_REQ_LINK_FLAGS |
8544 REQ_F_FORCE_ASYNC | REQ_F_FAIL))) {
8545 if (req->flags & IO_REQ_LINK_FLAGS) {
8546 link->head = req;
8547 link->last = req;
8548 } else {
8549 fallback:
8550 io_queue_sqe_fallback(req);
8551 }
8552 return 0;
8553 }
8554
8555 io_queue_sqe(req);
8556 return 0;
8557 }
8558
8559 /*
8560 * Batched submission is done, ensure local IO is flushed out.
8561 */
io_submit_state_end(struct io_ring_ctx * ctx)8562 static void io_submit_state_end(struct io_ring_ctx *ctx)
8563 {
8564 struct io_submit_state *state = &ctx->submit_state;
8565
8566 if (unlikely(state->link.head))
8567 io_queue_sqe_fallback(state->link.head);
8568 /* flush only after queuing links as they can generate completions */
8569 io_submit_flush_completions(ctx);
8570 if (state->plug_started)
8571 blk_finish_plug(&state->plug);
8572 }
8573
8574 /*
8575 * Start submission side cache.
8576 */
io_submit_state_start(struct io_submit_state * state,unsigned int max_ios)8577 static void io_submit_state_start(struct io_submit_state *state,
8578 unsigned int max_ios)
8579 {
8580 state->plug_started = false;
8581 state->need_plug = max_ios > 2;
8582 state->submit_nr = max_ios;
8583 /* set only head, no need to init link_last in advance */
8584 state->link.head = NULL;
8585 }
8586
io_commit_sqring(struct io_ring_ctx * ctx)8587 static void io_commit_sqring(struct io_ring_ctx *ctx)
8588 {
8589 struct io_rings *rings = ctx->rings;
8590
8591 /*
8592 * Ensure any loads from the SQEs are done at this point,
8593 * since once we write the new head, the application could
8594 * write new data to them.
8595 */
8596 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
8597 }
8598
8599 /*
8600 * Fetch an sqe, if one is available. Note this returns a pointer to memory
8601 * that is mapped by userspace. This means that care needs to be taken to
8602 * ensure that reads are stable, as we cannot rely on userspace always
8603 * being a good citizen. If members of the sqe are validated and then later
8604 * used, it's important that those reads are done through READ_ONCE() to
8605 * prevent a re-load down the line.
8606 */
io_get_sqe(struct io_ring_ctx * ctx)8607 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
8608 {
8609 unsigned head, mask = ctx->sq_entries - 1;
8610 unsigned sq_idx = ctx->cached_sq_head++ & mask;
8611
8612 /*
8613 * The cached sq head (or cq tail) serves two purposes:
8614 *
8615 * 1) allows us to batch the cost of updating the user visible
8616 * head updates.
8617 * 2) allows the kernel side to track the head on its own, even
8618 * though the application is the one updating it.
8619 */
8620 head = READ_ONCE(ctx->sq_array[sq_idx]);
8621 if (likely(head < ctx->sq_entries)) {
8622 /* double index for 128-byte SQEs, twice as long */
8623 if (ctx->flags & IORING_SETUP_SQE128)
8624 head <<= 1;
8625 return &ctx->sq_sqes[head];
8626 }
8627
8628 /* drop invalid entries */
8629 ctx->cq_extra--;
8630 WRITE_ONCE(ctx->rings->sq_dropped,
8631 READ_ONCE(ctx->rings->sq_dropped) + 1);
8632 return NULL;
8633 }
8634
io_submit_sqes(struct io_ring_ctx * ctx,unsigned int nr)8635 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
8636 __must_hold(&ctx->uring_lock)
8637 {
8638 unsigned int entries = io_sqring_entries(ctx);
8639 unsigned int left;
8640 int ret;
8641
8642 if (unlikely(!entries))
8643 return 0;
8644 /* make sure SQ entry isn't read before tail */
8645 ret = left = min3(nr, ctx->sq_entries, entries);
8646 io_get_task_refs(left);
8647 io_submit_state_start(&ctx->submit_state, left);
8648
8649 do {
8650 const struct io_uring_sqe *sqe;
8651 struct io_kiocb *req;
8652
8653 if (unlikely(!io_alloc_req_refill(ctx)))
8654 break;
8655 req = io_alloc_req(ctx);
8656 sqe = io_get_sqe(ctx);
8657 if (unlikely(!sqe)) {
8658 io_req_add_to_cache(req, ctx);
8659 break;
8660 }
8661
8662 /*
8663 * Continue submitting even for sqe failure if the
8664 * ring was setup with IORING_SETUP_SUBMIT_ALL
8665 */
8666 if (unlikely(io_submit_sqe(ctx, req, sqe)) &&
8667 !(ctx->flags & IORING_SETUP_SUBMIT_ALL)) {
8668 left--;
8669 break;
8670 }
8671 } while (--left);
8672
8673 if (unlikely(left)) {
8674 ret -= left;
8675 /* try again if it submitted nothing and can't allocate a req */
8676 if (!ret && io_req_cache_empty(ctx))
8677 ret = -EAGAIN;
8678 current->io_uring->cached_refs += left;
8679 }
8680
8681 io_submit_state_end(ctx);
8682 /* Commit SQ ring head once we've consumed and submitted all SQEs */
8683 io_commit_sqring(ctx);
8684 return ret;
8685 }
8686
io_sqd_events_pending(struct io_sq_data * sqd)8687 static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
8688 {
8689 return READ_ONCE(sqd->state);
8690 }
8691
__io_sq_thread(struct io_ring_ctx * ctx,bool cap_entries)8692 static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
8693 {
8694 unsigned int to_submit;
8695 int ret = 0;
8696
8697 to_submit = io_sqring_entries(ctx);
8698 /* if we're handling multiple rings, cap submit size for fairness */
8699 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
8700 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
8701
8702 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
8703 const struct cred *creds = NULL;
8704
8705 if (ctx->sq_creds != current_cred())
8706 creds = override_creds(ctx->sq_creds);
8707
8708 mutex_lock(&ctx->uring_lock);
8709 if (!wq_list_empty(&ctx->iopoll_list))
8710 io_do_iopoll(ctx, true);
8711
8712 /*
8713 * Don't submit if refs are dying, good for io_uring_register(),
8714 * but also it is relied upon by io_ring_exit_work()
8715 */
8716 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
8717 !(ctx->flags & IORING_SETUP_R_DISABLED))
8718 ret = io_submit_sqes(ctx, to_submit);
8719 mutex_unlock(&ctx->uring_lock);
8720
8721 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
8722 wake_up(&ctx->sqo_sq_wait);
8723 if (creds)
8724 revert_creds(creds);
8725 }
8726
8727 return ret;
8728 }
8729
io_sqd_update_thread_idle(struct io_sq_data * sqd)8730 static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
8731 {
8732 struct io_ring_ctx *ctx;
8733 unsigned sq_thread_idle = 0;
8734
8735 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8736 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
8737 sqd->sq_thread_idle = sq_thread_idle;
8738 }
8739
io_sqd_handle_event(struct io_sq_data * sqd)8740 static bool io_sqd_handle_event(struct io_sq_data *sqd)
8741 {
8742 bool did_sig = false;
8743 struct ksignal ksig;
8744
8745 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
8746 signal_pending(current)) {
8747 mutex_unlock(&sqd->lock);
8748 if (signal_pending(current))
8749 did_sig = get_signal(&ksig);
8750 cond_resched();
8751 mutex_lock(&sqd->lock);
8752 }
8753 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
8754 }
8755
io_sq_thread(void * data)8756 static int io_sq_thread(void *data)
8757 {
8758 struct io_sq_data *sqd = data;
8759 struct io_ring_ctx *ctx;
8760 unsigned long timeout = 0;
8761 char buf[TASK_COMM_LEN];
8762 DEFINE_WAIT(wait);
8763
8764 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
8765 set_task_comm(current, buf);
8766
8767 if (sqd->sq_cpu != -1)
8768 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
8769 else
8770 set_cpus_allowed_ptr(current, cpu_online_mask);
8771 current->flags |= PF_NO_SETAFFINITY;
8772
8773 audit_alloc_kernel(current);
8774
8775 mutex_lock(&sqd->lock);
8776 while (1) {
8777 bool cap_entries, sqt_spin = false;
8778
8779 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
8780 if (io_sqd_handle_event(sqd))
8781 break;
8782 timeout = jiffies + sqd->sq_thread_idle;
8783 }
8784
8785 cap_entries = !list_is_singular(&sqd->ctx_list);
8786 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8787 int ret = __io_sq_thread(ctx, cap_entries);
8788
8789 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
8790 sqt_spin = true;
8791 }
8792 if (io_run_task_work())
8793 sqt_spin = true;
8794
8795 if (sqt_spin || !time_after(jiffies, timeout)) {
8796 cond_resched();
8797 if (sqt_spin)
8798 timeout = jiffies + sqd->sq_thread_idle;
8799 continue;
8800 }
8801
8802 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
8803 if (!io_sqd_events_pending(sqd) && !task_work_pending(current)) {
8804 bool needs_sched = true;
8805
8806 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
8807 atomic_or(IORING_SQ_NEED_WAKEUP,
8808 &ctx->rings->sq_flags);
8809 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
8810 !wq_list_empty(&ctx->iopoll_list)) {
8811 needs_sched = false;
8812 break;
8813 }
8814
8815 /*
8816 * Ensure the store of the wakeup flag is not
8817 * reordered with the load of the SQ tail
8818 */
8819 smp_mb__after_atomic();
8820
8821 if (io_sqring_entries(ctx)) {
8822 needs_sched = false;
8823 break;
8824 }
8825 }
8826
8827 if (needs_sched) {
8828 mutex_unlock(&sqd->lock);
8829 schedule();
8830 mutex_lock(&sqd->lock);
8831 }
8832 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8833 atomic_andnot(IORING_SQ_NEED_WAKEUP,
8834 &ctx->rings->sq_flags);
8835 }
8836
8837 finish_wait(&sqd->wait, &wait);
8838 timeout = jiffies + sqd->sq_thread_idle;
8839 }
8840
8841 io_uring_cancel_generic(true, sqd);
8842 sqd->thread = NULL;
8843 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8844 atomic_or(IORING_SQ_NEED_WAKEUP, &ctx->rings->sq_flags);
8845 io_run_task_work();
8846 mutex_unlock(&sqd->lock);
8847
8848 audit_free(current);
8849
8850 complete(&sqd->exited);
8851 do_exit(0);
8852 }
8853
8854 struct io_wait_queue {
8855 struct wait_queue_entry wq;
8856 struct io_ring_ctx *ctx;
8857 unsigned cq_tail;
8858 unsigned nr_timeouts;
8859 };
8860
io_should_wake(struct io_wait_queue * iowq)8861 static inline bool io_should_wake(struct io_wait_queue *iowq)
8862 {
8863 struct io_ring_ctx *ctx = iowq->ctx;
8864 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
8865
8866 /*
8867 * Wake up if we have enough events, or if a timeout occurred since we
8868 * started waiting. For timeouts, we always want to return to userspace,
8869 * regardless of event count.
8870 */
8871 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
8872 }
8873
io_wake_function(struct wait_queue_entry * curr,unsigned int mode,int wake_flags,void * key)8874 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
8875 int wake_flags, void *key)
8876 {
8877 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
8878 wq);
8879
8880 /*
8881 * Cannot safely flush overflowed CQEs from here, ensure we wake up
8882 * the task, and the next invocation will do it.
8883 */
8884 if (io_should_wake(iowq) ||
8885 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &iowq->ctx->check_cq))
8886 return autoremove_wake_function(curr, mode, wake_flags, key);
8887 return -1;
8888 }
8889
io_run_task_work_sig(void)8890 static int io_run_task_work_sig(void)
8891 {
8892 if (io_run_task_work())
8893 return 1;
8894 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
8895 return -ERESTARTSYS;
8896 if (task_sigpending(current))
8897 return -EINTR;
8898 return 0;
8899 }
8900
8901 /* when returns >0, the caller should retry */
io_cqring_wait_schedule(struct io_ring_ctx * ctx,struct io_wait_queue * iowq,ktime_t timeout)8902 static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
8903 struct io_wait_queue *iowq,
8904 ktime_t timeout)
8905 {
8906 int ret;
8907 unsigned long check_cq;
8908
8909 /* make sure we run task_work before checking for signals */
8910 ret = io_run_task_work_sig();
8911 if (ret || io_should_wake(iowq))
8912 return ret;
8913 check_cq = READ_ONCE(ctx->check_cq);
8914 /* let the caller flush overflows, retry */
8915 if (check_cq & BIT(IO_CHECK_CQ_OVERFLOW_BIT))
8916 return 1;
8917 if (unlikely(check_cq & BIT(IO_CHECK_CQ_DROPPED_BIT)))
8918 return -EBADR;
8919 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
8920 return -ETIME;
8921 return 1;
8922 }
8923
8924 /*
8925 * Wait until events become available, if we don't already have some. The
8926 * application must reap them itself, as they reside on the shared cq ring.
8927 */
io_cqring_wait(struct io_ring_ctx * ctx,int min_events,const sigset_t __user * sig,size_t sigsz,struct __kernel_timespec __user * uts)8928 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
8929 const sigset_t __user *sig, size_t sigsz,
8930 struct __kernel_timespec __user *uts)
8931 {
8932 struct io_wait_queue iowq;
8933 struct io_rings *rings = ctx->rings;
8934 ktime_t timeout = KTIME_MAX;
8935 int ret;
8936
8937 do {
8938 io_cqring_overflow_flush(ctx);
8939 if (io_cqring_events(ctx) >= min_events)
8940 return 0;
8941 if (!io_run_task_work())
8942 break;
8943 } while (1);
8944
8945 if (sig) {
8946 #ifdef CONFIG_COMPAT
8947 if (in_compat_syscall())
8948 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
8949 sigsz);
8950 else
8951 #endif
8952 ret = set_user_sigmask(sig, sigsz);
8953
8954 if (ret)
8955 return ret;
8956 }
8957
8958 if (uts) {
8959 struct timespec64 ts;
8960
8961 if (get_timespec64(&ts, uts))
8962 return -EFAULT;
8963 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
8964 }
8965
8966 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
8967 iowq.wq.private = current;
8968 INIT_LIST_HEAD(&iowq.wq.entry);
8969 iowq.ctx = ctx;
8970 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
8971 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
8972
8973 trace_io_uring_cqring_wait(ctx, min_events);
8974 do {
8975 /* if we can't even flush overflow, don't wait for more */
8976 if (!io_cqring_overflow_flush(ctx)) {
8977 ret = -EBUSY;
8978 break;
8979 }
8980 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
8981 TASK_INTERRUPTIBLE);
8982 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
8983 cond_resched();
8984 } while (ret > 0);
8985
8986 finish_wait(&ctx->cq_wait, &iowq.wq);
8987 restore_saved_sigmask_unless(ret == -EINTR);
8988
8989 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
8990 }
8991
io_free_page_table(void ** table,size_t size)8992 static void io_free_page_table(void **table, size_t size)
8993 {
8994 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8995
8996 for (i = 0; i < nr_tables; i++)
8997 kfree(table[i]);
8998 kfree(table);
8999 }
9000
io_alloc_page_table(size_t size)9001 static __cold void **io_alloc_page_table(size_t size)
9002 {
9003 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
9004 size_t init_size = size;
9005 void **table;
9006
9007 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
9008 if (!table)
9009 return NULL;
9010
9011 for (i = 0; i < nr_tables; i++) {
9012 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
9013
9014 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
9015 if (!table[i]) {
9016 io_free_page_table(table, init_size);
9017 return NULL;
9018 }
9019 size -= this_size;
9020 }
9021 return table;
9022 }
9023
io_rsrc_node_destroy(struct io_rsrc_node * ref_node)9024 static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
9025 {
9026 percpu_ref_exit(&ref_node->refs);
9027 kfree(ref_node);
9028 }
9029
io_rsrc_node_ref_zero(struct percpu_ref * ref)9030 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
9031 {
9032 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
9033 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
9034 unsigned long flags;
9035 bool first_add = false;
9036 unsigned long delay = HZ;
9037
9038 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
9039 node->done = true;
9040
9041 /* if we are mid-quiesce then do not delay */
9042 if (node->rsrc_data->quiesce)
9043 delay = 0;
9044
9045 while (!list_empty(&ctx->rsrc_ref_list)) {
9046 node = list_first_entry(&ctx->rsrc_ref_list,
9047 struct io_rsrc_node, node);
9048 /* recycle ref nodes in order */
9049 if (!node->done)
9050 break;
9051 list_del(&node->node);
9052 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
9053 }
9054 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
9055
9056 if (first_add)
9057 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
9058 }
9059
io_rsrc_node_alloc(void)9060 static struct io_rsrc_node *io_rsrc_node_alloc(void)
9061 {
9062 struct io_rsrc_node *ref_node;
9063
9064 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
9065 if (!ref_node)
9066 return NULL;
9067
9068 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
9069 0, GFP_KERNEL)) {
9070 kfree(ref_node);
9071 return NULL;
9072 }
9073 INIT_LIST_HEAD(&ref_node->node);
9074 INIT_LIST_HEAD(&ref_node->rsrc_list);
9075 ref_node->done = false;
9076 return ref_node;
9077 }
9078
io_rsrc_node_switch(struct io_ring_ctx * ctx,struct io_rsrc_data * data_to_kill)9079 static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
9080 struct io_rsrc_data *data_to_kill)
9081 __must_hold(&ctx->uring_lock)
9082 {
9083 WARN_ON_ONCE(!ctx->rsrc_backup_node);
9084 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
9085
9086 io_rsrc_refs_drop(ctx);
9087
9088 if (data_to_kill) {
9089 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
9090
9091 rsrc_node->rsrc_data = data_to_kill;
9092 spin_lock_irq(&ctx->rsrc_ref_lock);
9093 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
9094 spin_unlock_irq(&ctx->rsrc_ref_lock);
9095
9096 atomic_inc(&data_to_kill->refs);
9097 percpu_ref_kill(&rsrc_node->refs);
9098 ctx->rsrc_node = NULL;
9099 }
9100
9101 if (!ctx->rsrc_node) {
9102 ctx->rsrc_node = ctx->rsrc_backup_node;
9103 ctx->rsrc_backup_node = NULL;
9104 }
9105 }
9106
io_rsrc_node_switch_start(struct io_ring_ctx * ctx)9107 static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
9108 {
9109 if (ctx->rsrc_backup_node)
9110 return 0;
9111 ctx->rsrc_backup_node = io_rsrc_node_alloc();
9112 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
9113 }
9114
io_rsrc_ref_quiesce(struct io_rsrc_data * data,struct io_ring_ctx * ctx)9115 static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
9116 struct io_ring_ctx *ctx)
9117 {
9118 int ret;
9119
9120 /* As we may drop ->uring_lock, other task may have started quiesce */
9121 if (data->quiesce)
9122 return -ENXIO;
9123
9124 data->quiesce = true;
9125 do {
9126 ret = io_rsrc_node_switch_start(ctx);
9127 if (ret)
9128 break;
9129 io_rsrc_node_switch(ctx, data);
9130
9131 /* kill initial ref, already quiesced if zero */
9132 if (atomic_dec_and_test(&data->refs))
9133 break;
9134 mutex_unlock(&ctx->uring_lock);
9135 flush_delayed_work(&ctx->rsrc_put_work);
9136 ret = wait_for_completion_interruptible(&data->done);
9137 if (!ret) {
9138 mutex_lock(&ctx->uring_lock);
9139 if (atomic_read(&data->refs) > 0) {
9140 /*
9141 * it has been revived by another thread while
9142 * we were unlocked
9143 */
9144 mutex_unlock(&ctx->uring_lock);
9145 } else {
9146 break;
9147 }
9148 }
9149
9150 atomic_inc(&data->refs);
9151 /* wait for all works potentially completing data->done */
9152 flush_delayed_work(&ctx->rsrc_put_work);
9153 reinit_completion(&data->done);
9154
9155 ret = io_run_task_work_sig();
9156 mutex_lock(&ctx->uring_lock);
9157 } while (ret >= 0);
9158 data->quiesce = false;
9159
9160 return ret;
9161 }
9162
io_get_tag_slot(struct io_rsrc_data * data,unsigned int idx)9163 static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
9164 {
9165 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
9166 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
9167
9168 return &data->tags[table_idx][off];
9169 }
9170
io_rsrc_data_free(struct io_rsrc_data * data)9171 static void io_rsrc_data_free(struct io_rsrc_data *data)
9172 {
9173 size_t size = data->nr * sizeof(data->tags[0][0]);
9174
9175 if (data->tags)
9176 io_free_page_table((void **)data->tags, size);
9177 kfree(data);
9178 }
9179
io_rsrc_data_alloc(struct io_ring_ctx * ctx,rsrc_put_fn * do_put,u64 __user * utags,unsigned nr,struct io_rsrc_data ** pdata)9180 static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
9181 u64 __user *utags, unsigned nr,
9182 struct io_rsrc_data **pdata)
9183 {
9184 struct io_rsrc_data *data;
9185 int ret = -ENOMEM;
9186 unsigned i;
9187
9188 data = kzalloc(sizeof(*data), GFP_KERNEL);
9189 if (!data)
9190 return -ENOMEM;
9191 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
9192 if (!data->tags) {
9193 kfree(data);
9194 return -ENOMEM;
9195 }
9196
9197 data->nr = nr;
9198 data->ctx = ctx;
9199 data->do_put = do_put;
9200 if (utags) {
9201 ret = -EFAULT;
9202 for (i = 0; i < nr; i++) {
9203 u64 *tag_slot = io_get_tag_slot(data, i);
9204
9205 if (copy_from_user(tag_slot, &utags[i],
9206 sizeof(*tag_slot)))
9207 goto fail;
9208 }
9209 }
9210
9211 atomic_set(&data->refs, 1);
9212 init_completion(&data->done);
9213 *pdata = data;
9214 return 0;
9215 fail:
9216 io_rsrc_data_free(data);
9217 return ret;
9218 }
9219
io_alloc_file_tables(struct io_file_table * table,unsigned nr_files)9220 static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
9221 {
9222 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
9223 GFP_KERNEL_ACCOUNT);
9224 if (unlikely(!table->files))
9225 return false;
9226
9227 table->bitmap = bitmap_zalloc(nr_files, GFP_KERNEL_ACCOUNT);
9228 if (unlikely(!table->bitmap)) {
9229 kvfree(table->files);
9230 return false;
9231 }
9232
9233 return true;
9234 }
9235
io_free_file_tables(struct io_file_table * table)9236 static void io_free_file_tables(struct io_file_table *table)
9237 {
9238 kvfree(table->files);
9239 bitmap_free(table->bitmap);
9240 table->files = NULL;
9241 table->bitmap = NULL;
9242 }
9243
io_file_bitmap_set(struct io_file_table * table,int bit)9244 static inline void io_file_bitmap_set(struct io_file_table *table, int bit)
9245 {
9246 WARN_ON_ONCE(test_bit(bit, table->bitmap));
9247 __set_bit(bit, table->bitmap);
9248 table->alloc_hint = bit + 1;
9249 }
9250
io_file_bitmap_clear(struct io_file_table * table,int bit)9251 static inline void io_file_bitmap_clear(struct io_file_table *table, int bit)
9252 {
9253 __clear_bit(bit, table->bitmap);
9254 table->alloc_hint = bit;
9255 }
9256
__io_sqe_files_unregister(struct io_ring_ctx * ctx)9257 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
9258 {
9259 #if !defined(IO_URING_SCM_ALL)
9260 int i;
9261
9262 for (i = 0; i < ctx->nr_user_files; i++) {
9263 struct file *file = io_file_from_index(ctx, i);
9264
9265 if (!file)
9266 continue;
9267 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
9268 continue;
9269 io_file_bitmap_clear(&ctx->file_table, i);
9270 fput(file);
9271 }
9272 #endif
9273
9274 #if defined(CONFIG_UNIX)
9275 if (ctx->ring_sock) {
9276 struct sock *sock = ctx->ring_sock->sk;
9277 struct sk_buff *skb;
9278
9279 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
9280 kfree_skb(skb);
9281 }
9282 #endif
9283 io_free_file_tables(&ctx->file_table);
9284 io_rsrc_data_free(ctx->file_data);
9285 ctx->file_data = NULL;
9286 ctx->nr_user_files = 0;
9287 }
9288
io_sqe_files_unregister(struct io_ring_ctx * ctx)9289 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
9290 {
9291 unsigned nr = ctx->nr_user_files;
9292 int ret;
9293
9294 if (!ctx->file_data)
9295 return -ENXIO;
9296
9297 /*
9298 * Quiesce may unlock ->uring_lock, and while it's not held
9299 * prevent new requests using the table.
9300 */
9301 ctx->nr_user_files = 0;
9302 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
9303 ctx->nr_user_files = nr;
9304 if (!ret)
9305 __io_sqe_files_unregister(ctx);
9306 return ret;
9307 }
9308
io_sq_thread_unpark(struct io_sq_data * sqd)9309 static void io_sq_thread_unpark(struct io_sq_data *sqd)
9310 __releases(&sqd->lock)
9311 {
9312 WARN_ON_ONCE(sqd->thread == current);
9313
9314 /*
9315 * Do the dance but not conditional clear_bit() because it'd race with
9316 * other threads incrementing park_pending and setting the bit.
9317 */
9318 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9319 if (atomic_dec_return(&sqd->park_pending))
9320 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9321 mutex_unlock(&sqd->lock);
9322 }
9323
io_sq_thread_park(struct io_sq_data * sqd)9324 static void io_sq_thread_park(struct io_sq_data *sqd)
9325 __acquires(&sqd->lock)
9326 {
9327 WARN_ON_ONCE(sqd->thread == current);
9328
9329 atomic_inc(&sqd->park_pending);
9330 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9331 mutex_lock(&sqd->lock);
9332 if (sqd->thread)
9333 wake_up_process(sqd->thread);
9334 }
9335
io_sq_thread_stop(struct io_sq_data * sqd)9336 static void io_sq_thread_stop(struct io_sq_data *sqd)
9337 {
9338 WARN_ON_ONCE(sqd->thread == current);
9339 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
9340
9341 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
9342 mutex_lock(&sqd->lock);
9343 if (sqd->thread)
9344 wake_up_process(sqd->thread);
9345 mutex_unlock(&sqd->lock);
9346 wait_for_completion(&sqd->exited);
9347 }
9348
io_put_sq_data(struct io_sq_data * sqd)9349 static void io_put_sq_data(struct io_sq_data *sqd)
9350 {
9351 if (refcount_dec_and_test(&sqd->refs)) {
9352 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
9353
9354 io_sq_thread_stop(sqd);
9355 kfree(sqd);
9356 }
9357 }
9358
io_sq_thread_finish(struct io_ring_ctx * ctx)9359 static void io_sq_thread_finish(struct io_ring_ctx *ctx)
9360 {
9361 struct io_sq_data *sqd = ctx->sq_data;
9362
9363 if (sqd) {
9364 io_sq_thread_park(sqd);
9365 list_del_init(&ctx->sqd_list);
9366 io_sqd_update_thread_idle(sqd);
9367 io_sq_thread_unpark(sqd);
9368
9369 io_put_sq_data(sqd);
9370 ctx->sq_data = NULL;
9371 }
9372 }
9373
io_attach_sq_data(struct io_uring_params * p)9374 static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
9375 {
9376 struct io_ring_ctx *ctx_attach;
9377 struct io_sq_data *sqd;
9378 struct fd f;
9379
9380 f = fdget(p->wq_fd);
9381 if (!f.file)
9382 return ERR_PTR(-ENXIO);
9383 if (f.file->f_op != &io_uring_fops) {
9384 fdput(f);
9385 return ERR_PTR(-EINVAL);
9386 }
9387
9388 ctx_attach = f.file->private_data;
9389 sqd = ctx_attach->sq_data;
9390 if (!sqd) {
9391 fdput(f);
9392 return ERR_PTR(-EINVAL);
9393 }
9394 if (sqd->task_tgid != current->tgid) {
9395 fdput(f);
9396 return ERR_PTR(-EPERM);
9397 }
9398
9399 refcount_inc(&sqd->refs);
9400 fdput(f);
9401 return sqd;
9402 }
9403
io_get_sq_data(struct io_uring_params * p,bool * attached)9404 static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
9405 bool *attached)
9406 {
9407 struct io_sq_data *sqd;
9408
9409 *attached = false;
9410 if (p->flags & IORING_SETUP_ATTACH_WQ) {
9411 sqd = io_attach_sq_data(p);
9412 if (!IS_ERR(sqd)) {
9413 *attached = true;
9414 return sqd;
9415 }
9416 /* fall through for EPERM case, setup new sqd/task */
9417 if (PTR_ERR(sqd) != -EPERM)
9418 return sqd;
9419 }
9420
9421 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
9422 if (!sqd)
9423 return ERR_PTR(-ENOMEM);
9424
9425 atomic_set(&sqd->park_pending, 0);
9426 refcount_set(&sqd->refs, 1);
9427 INIT_LIST_HEAD(&sqd->ctx_list);
9428 mutex_init(&sqd->lock);
9429 init_waitqueue_head(&sqd->wait);
9430 init_completion(&sqd->exited);
9431 return sqd;
9432 }
9433
9434 /*
9435 * Ensure the UNIX gc is aware of our file set, so we are certain that
9436 * the io_uring can be safely unregistered on process exit, even if we have
9437 * loops in the file referencing. We account only files that can hold other
9438 * files because otherwise they can't form a loop and so are not interesting
9439 * for GC.
9440 */
io_scm_file_account(struct io_ring_ctx * ctx,struct file * file)9441 static int io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
9442 {
9443 #if defined(CONFIG_UNIX)
9444 struct sock *sk = ctx->ring_sock->sk;
9445 struct sk_buff_head *head = &sk->sk_receive_queue;
9446 struct scm_fp_list *fpl;
9447 struct sk_buff *skb;
9448
9449 if (likely(!io_file_need_scm(file)))
9450 return 0;
9451
9452 /*
9453 * See if we can merge this file into an existing skb SCM_RIGHTS
9454 * file set. If there's no room, fall back to allocating a new skb
9455 * and filling it in.
9456 */
9457 spin_lock_irq(&head->lock);
9458 skb = skb_peek(head);
9459 if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
9460 __skb_unlink(skb, head);
9461 else
9462 skb = NULL;
9463 spin_unlock_irq(&head->lock);
9464
9465 if (!skb) {
9466 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
9467 if (!fpl)
9468 return -ENOMEM;
9469
9470 skb = alloc_skb(0, GFP_KERNEL);
9471 if (!skb) {
9472 kfree(fpl);
9473 return -ENOMEM;
9474 }
9475
9476 fpl->user = get_uid(current_user());
9477 fpl->max = SCM_MAX_FD;
9478 fpl->count = 0;
9479
9480 UNIXCB(skb).fp = fpl;
9481 skb->sk = sk;
9482 skb->destructor = unix_destruct_scm;
9483 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
9484 }
9485
9486 fpl = UNIXCB(skb).fp;
9487 fpl->fp[fpl->count++] = get_file(file);
9488 unix_inflight(fpl->user, file);
9489 skb_queue_head(head, skb);
9490 fput(file);
9491 #endif
9492 return 0;
9493 }
9494
io_rsrc_file_put(struct io_ring_ctx * ctx,struct io_rsrc_put * prsrc)9495 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
9496 {
9497 struct file *file = prsrc->file;
9498 #if defined(CONFIG_UNIX)
9499 struct sock *sock = ctx->ring_sock->sk;
9500 struct sk_buff_head list, *head = &sock->sk_receive_queue;
9501 struct sk_buff *skb;
9502 int i;
9503
9504 if (!io_file_need_scm(file)) {
9505 fput(file);
9506 return;
9507 }
9508
9509 __skb_queue_head_init(&list);
9510
9511 /*
9512 * Find the skb that holds this file in its SCM_RIGHTS. When found,
9513 * remove this entry and rearrange the file array.
9514 */
9515 skb = skb_dequeue(head);
9516 while (skb) {
9517 struct scm_fp_list *fp;
9518
9519 fp = UNIXCB(skb).fp;
9520 for (i = 0; i < fp->count; i++) {
9521 int left;
9522
9523 if (fp->fp[i] != file)
9524 continue;
9525
9526 unix_notinflight(fp->user, fp->fp[i]);
9527 left = fp->count - 1 - i;
9528 if (left) {
9529 memmove(&fp->fp[i], &fp->fp[i + 1],
9530 left * sizeof(struct file *));
9531 }
9532 fp->count--;
9533 if (!fp->count) {
9534 kfree_skb(skb);
9535 skb = NULL;
9536 } else {
9537 __skb_queue_tail(&list, skb);
9538 }
9539 fput(file);
9540 file = NULL;
9541 break;
9542 }
9543
9544 if (!file)
9545 break;
9546
9547 __skb_queue_tail(&list, skb);
9548
9549 skb = skb_dequeue(head);
9550 }
9551
9552 if (skb_peek(&list)) {
9553 spin_lock_irq(&head->lock);
9554 while ((skb = __skb_dequeue(&list)) != NULL)
9555 __skb_queue_tail(head, skb);
9556 spin_unlock_irq(&head->lock);
9557 }
9558 #else
9559 fput(file);
9560 #endif
9561 }
9562
__io_rsrc_put_work(struct io_rsrc_node * ref_node)9563 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
9564 {
9565 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
9566 struct io_ring_ctx *ctx = rsrc_data->ctx;
9567 struct io_rsrc_put *prsrc, *tmp;
9568
9569 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
9570 list_del(&prsrc->list);
9571
9572 if (prsrc->tag) {
9573 if (ctx->flags & IORING_SETUP_IOPOLL)
9574 mutex_lock(&ctx->uring_lock);
9575
9576 spin_lock(&ctx->completion_lock);
9577 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
9578 io_commit_cqring(ctx);
9579 spin_unlock(&ctx->completion_lock);
9580 io_cqring_ev_posted(ctx);
9581
9582 if (ctx->flags & IORING_SETUP_IOPOLL)
9583 mutex_unlock(&ctx->uring_lock);
9584 }
9585
9586 rsrc_data->do_put(ctx, prsrc);
9587 kfree(prsrc);
9588 }
9589
9590 io_rsrc_node_destroy(ref_node);
9591 if (atomic_dec_and_test(&rsrc_data->refs))
9592 complete(&rsrc_data->done);
9593 }
9594
io_rsrc_put_work(struct work_struct * work)9595 static void io_rsrc_put_work(struct work_struct *work)
9596 {
9597 struct io_ring_ctx *ctx;
9598 struct llist_node *node;
9599
9600 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
9601 node = llist_del_all(&ctx->rsrc_put_llist);
9602
9603 while (node) {
9604 struct io_rsrc_node *ref_node;
9605 struct llist_node *next = node->next;
9606
9607 ref_node = llist_entry(node, struct io_rsrc_node, llist);
9608 __io_rsrc_put_work(ref_node);
9609 node = next;
9610 }
9611 }
9612
io_sqe_files_register(struct io_ring_ctx * ctx,void __user * arg,unsigned nr_args,u64 __user * tags)9613 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
9614 unsigned nr_args, u64 __user *tags)
9615 {
9616 __s32 __user *fds = (__s32 __user *) arg;
9617 struct file *file;
9618 int fd, ret;
9619 unsigned i;
9620
9621 if (ctx->file_data)
9622 return -EBUSY;
9623 if (!nr_args)
9624 return -EINVAL;
9625 if (nr_args > IORING_MAX_FIXED_FILES)
9626 return -EMFILE;
9627 if (nr_args > rlimit(RLIMIT_NOFILE))
9628 return -EMFILE;
9629 ret = io_rsrc_node_switch_start(ctx);
9630 if (ret)
9631 return ret;
9632 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
9633 &ctx->file_data);
9634 if (ret)
9635 return ret;
9636
9637 if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
9638 io_rsrc_data_free(ctx->file_data);
9639 ctx->file_data = NULL;
9640 return -ENOMEM;
9641 }
9642
9643 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
9644 struct io_fixed_file *file_slot;
9645
9646 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
9647 ret = -EFAULT;
9648 goto fail;
9649 }
9650 /* allow sparse sets */
9651 if (!fds || fd == -1) {
9652 ret = -EINVAL;
9653 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
9654 goto fail;
9655 continue;
9656 }
9657
9658 file = fget(fd);
9659 ret = -EBADF;
9660 if (unlikely(!file))
9661 goto fail;
9662
9663 /*
9664 * Don't allow io_uring instances to be registered. If UNIX
9665 * isn't enabled, then this causes a reference cycle and this
9666 * instance can never get freed. If UNIX is enabled we'll
9667 * handle it just fine, but there's still no point in allowing
9668 * a ring fd as it doesn't support regular read/write anyway.
9669 */
9670 if (file->f_op == &io_uring_fops) {
9671 fput(file);
9672 goto fail;
9673 }
9674 ret = io_scm_file_account(ctx, file);
9675 if (ret) {
9676 fput(file);
9677 goto fail;
9678 }
9679 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9680 io_fixed_file_set(file_slot, file);
9681 io_file_bitmap_set(&ctx->file_table, i);
9682 }
9683
9684 io_rsrc_node_switch(ctx, NULL);
9685 return 0;
9686 fail:
9687 __io_sqe_files_unregister(ctx);
9688 return ret;
9689 }
9690
io_queue_rsrc_removal(struct io_rsrc_data * data,unsigned idx,struct io_rsrc_node * node,void * rsrc)9691 static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
9692 struct io_rsrc_node *node, void *rsrc)
9693 {
9694 u64 *tag_slot = io_get_tag_slot(data, idx);
9695 struct io_rsrc_put *prsrc;
9696
9697 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
9698 if (!prsrc)
9699 return -ENOMEM;
9700
9701 prsrc->tag = *tag_slot;
9702 *tag_slot = 0;
9703 prsrc->rsrc = rsrc;
9704 list_add(&prsrc->list, &node->rsrc_list);
9705 return 0;
9706 }
9707
io_install_fixed_file(struct io_kiocb * req,struct file * file,unsigned int issue_flags,u32 slot_index)9708 static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
9709 unsigned int issue_flags, u32 slot_index)
9710 __must_hold(&req->ctx->uring_lock)
9711 {
9712 struct io_ring_ctx *ctx = req->ctx;
9713 bool needs_switch = false;
9714 struct io_fixed_file *file_slot;
9715 int ret;
9716
9717 if (file->f_op == &io_uring_fops)
9718 return -EBADF;
9719 if (!ctx->file_data)
9720 return -ENXIO;
9721 if (slot_index >= ctx->nr_user_files)
9722 return -EINVAL;
9723
9724 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
9725 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
9726
9727 if (file_slot->file_ptr) {
9728 struct file *old_file;
9729
9730 ret = io_rsrc_node_switch_start(ctx);
9731 if (ret)
9732 goto err;
9733
9734 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9735 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
9736 ctx->rsrc_node, old_file);
9737 if (ret)
9738 goto err;
9739 file_slot->file_ptr = 0;
9740 io_file_bitmap_clear(&ctx->file_table, slot_index);
9741 needs_switch = true;
9742 }
9743
9744 ret = io_scm_file_account(ctx, file);
9745 if (!ret) {
9746 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
9747 io_fixed_file_set(file_slot, file);
9748 io_file_bitmap_set(&ctx->file_table, slot_index);
9749 }
9750 err:
9751 if (needs_switch)
9752 io_rsrc_node_switch(ctx, ctx->file_data);
9753 if (ret)
9754 fput(file);
9755 return ret;
9756 }
9757
__io_close_fixed(struct io_kiocb * req,unsigned int issue_flags,unsigned int offset)9758 static int __io_close_fixed(struct io_kiocb *req, unsigned int issue_flags,
9759 unsigned int offset)
9760 {
9761 struct io_ring_ctx *ctx = req->ctx;
9762 struct io_fixed_file *file_slot;
9763 struct file *file;
9764 int ret;
9765
9766 io_ring_submit_lock(ctx, issue_flags);
9767 ret = -ENXIO;
9768 if (unlikely(!ctx->file_data))
9769 goto out;
9770 ret = -EINVAL;
9771 if (offset >= ctx->nr_user_files)
9772 goto out;
9773 ret = io_rsrc_node_switch_start(ctx);
9774 if (ret)
9775 goto out;
9776
9777 offset = array_index_nospec(offset, ctx->nr_user_files);
9778 file_slot = io_fixed_file_slot(&ctx->file_table, offset);
9779 ret = -EBADF;
9780 if (!file_slot->file_ptr)
9781 goto out;
9782
9783 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9784 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
9785 if (ret)
9786 goto out;
9787
9788 file_slot->file_ptr = 0;
9789 io_file_bitmap_clear(&ctx->file_table, offset);
9790 io_rsrc_node_switch(ctx, ctx->file_data);
9791 ret = 0;
9792 out:
9793 io_ring_submit_unlock(ctx, issue_flags);
9794 return ret;
9795 }
9796
io_close_fixed(struct io_kiocb * req,unsigned int issue_flags)9797 static inline int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
9798 {
9799 return __io_close_fixed(req, issue_flags, req->close.file_slot - 1);
9800 }
9801
__io_sqe_files_update(struct io_ring_ctx * ctx,struct io_uring_rsrc_update2 * up,unsigned nr_args)9802 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
9803 struct io_uring_rsrc_update2 *up,
9804 unsigned nr_args)
9805 {
9806 u64 __user *tags = u64_to_user_ptr(up->tags);
9807 __s32 __user *fds = u64_to_user_ptr(up->data);
9808 struct io_rsrc_data *data = ctx->file_data;
9809 struct io_fixed_file *file_slot;
9810 struct file *file;
9811 int fd, i, err = 0;
9812 unsigned int done;
9813 bool needs_switch = false;
9814
9815 if (!ctx->file_data)
9816 return -ENXIO;
9817 if (up->offset + nr_args > ctx->nr_user_files)
9818 return -EINVAL;
9819
9820 for (done = 0; done < nr_args; done++) {
9821 u64 tag = 0;
9822
9823 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
9824 copy_from_user(&fd, &fds[done], sizeof(fd))) {
9825 err = -EFAULT;
9826 break;
9827 }
9828 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
9829 err = -EINVAL;
9830 break;
9831 }
9832 if (fd == IORING_REGISTER_FILES_SKIP)
9833 continue;
9834
9835 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
9836 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9837
9838 if (file_slot->file_ptr) {
9839 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9840 err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
9841 if (err)
9842 break;
9843 file_slot->file_ptr = 0;
9844 io_file_bitmap_clear(&ctx->file_table, i);
9845 needs_switch = true;
9846 }
9847 if (fd != -1) {
9848 file = fget(fd);
9849 if (!file) {
9850 err = -EBADF;
9851 break;
9852 }
9853 /*
9854 * Don't allow io_uring instances to be registered. If
9855 * UNIX isn't enabled, then this causes a reference
9856 * cycle and this instance can never get freed. If UNIX
9857 * is enabled we'll handle it just fine, but there's
9858 * still no point in allowing a ring fd as it doesn't
9859 * support regular read/write anyway.
9860 */
9861 if (file->f_op == &io_uring_fops) {
9862 fput(file);
9863 err = -EBADF;
9864 break;
9865 }
9866 err = io_scm_file_account(ctx, file);
9867 if (err) {
9868 fput(file);
9869 break;
9870 }
9871 *io_get_tag_slot(data, i) = tag;
9872 io_fixed_file_set(file_slot, file);
9873 io_file_bitmap_set(&ctx->file_table, i);
9874 }
9875 }
9876
9877 if (needs_switch)
9878 io_rsrc_node_switch(ctx, data);
9879 return done ? done : err;
9880 }
9881
io_init_wq_offload(struct io_ring_ctx * ctx,struct task_struct * task)9882 static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
9883 struct task_struct *task)
9884 {
9885 struct io_wq_hash *hash;
9886 struct io_wq_data data;
9887 unsigned int concurrency;
9888
9889 mutex_lock(&ctx->uring_lock);
9890 hash = ctx->hash_map;
9891 if (!hash) {
9892 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
9893 if (!hash) {
9894 mutex_unlock(&ctx->uring_lock);
9895 return ERR_PTR(-ENOMEM);
9896 }
9897 refcount_set(&hash->refs, 1);
9898 init_waitqueue_head(&hash->wait);
9899 ctx->hash_map = hash;
9900 }
9901 mutex_unlock(&ctx->uring_lock);
9902
9903 data.hash = hash;
9904 data.task = task;
9905 data.free_work = io_wq_free_work;
9906 data.do_work = io_wq_submit_work;
9907
9908 /* Do QD, or 4 * CPUS, whatever is smallest */
9909 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
9910
9911 return io_wq_create(concurrency, &data);
9912 }
9913
io_uring_alloc_task_context(struct task_struct * task,struct io_ring_ctx * ctx)9914 static __cold int io_uring_alloc_task_context(struct task_struct *task,
9915 struct io_ring_ctx *ctx)
9916 {
9917 struct io_uring_task *tctx;
9918 int ret;
9919
9920 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
9921 if (unlikely(!tctx))
9922 return -ENOMEM;
9923
9924 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
9925 sizeof(struct file *), GFP_KERNEL);
9926 if (unlikely(!tctx->registered_rings)) {
9927 kfree(tctx);
9928 return -ENOMEM;
9929 }
9930
9931 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
9932 if (unlikely(ret)) {
9933 kfree(tctx->registered_rings);
9934 kfree(tctx);
9935 return ret;
9936 }
9937
9938 tctx->io_wq = io_init_wq_offload(ctx, task);
9939 if (IS_ERR(tctx->io_wq)) {
9940 ret = PTR_ERR(tctx->io_wq);
9941 percpu_counter_destroy(&tctx->inflight);
9942 kfree(tctx->registered_rings);
9943 kfree(tctx);
9944 return ret;
9945 }
9946
9947 xa_init(&tctx->xa);
9948 init_waitqueue_head(&tctx->wait);
9949 atomic_set(&tctx->in_idle, 0);
9950 atomic_set(&tctx->inflight_tracked, 0);
9951 task->io_uring = tctx;
9952 spin_lock_init(&tctx->task_lock);
9953 INIT_WQ_LIST(&tctx->task_list);
9954 INIT_WQ_LIST(&tctx->prio_task_list);
9955 init_task_work(&tctx->task_work, tctx_task_work);
9956 return 0;
9957 }
9958
__io_uring_free(struct task_struct * tsk)9959 void __io_uring_free(struct task_struct *tsk)
9960 {
9961 struct io_uring_task *tctx = tsk->io_uring;
9962
9963 WARN_ON_ONCE(!xa_empty(&tctx->xa));
9964 WARN_ON_ONCE(tctx->io_wq);
9965 WARN_ON_ONCE(tctx->cached_refs);
9966
9967 kfree(tctx->registered_rings);
9968 percpu_counter_destroy(&tctx->inflight);
9969 kfree(tctx);
9970 tsk->io_uring = NULL;
9971 }
9972
io_sq_offload_create(struct io_ring_ctx * ctx,struct io_uring_params * p)9973 static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
9974 struct io_uring_params *p)
9975 {
9976 int ret;
9977
9978 /* Retain compatibility with failing for an invalid attach attempt */
9979 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
9980 IORING_SETUP_ATTACH_WQ) {
9981 struct fd f;
9982
9983 f = fdget(p->wq_fd);
9984 if (!f.file)
9985 return -ENXIO;
9986 if (f.file->f_op != &io_uring_fops) {
9987 fdput(f);
9988 return -EINVAL;
9989 }
9990 fdput(f);
9991 }
9992 if (ctx->flags & IORING_SETUP_SQPOLL) {
9993 struct task_struct *tsk;
9994 struct io_sq_data *sqd;
9995 bool attached;
9996
9997 ret = security_uring_sqpoll();
9998 if (ret)
9999 return ret;
10000
10001 sqd = io_get_sq_data(p, &attached);
10002 if (IS_ERR(sqd)) {
10003 ret = PTR_ERR(sqd);
10004 goto err;
10005 }
10006
10007 ctx->sq_creds = get_current_cred();
10008 ctx->sq_data = sqd;
10009 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
10010 if (!ctx->sq_thread_idle)
10011 ctx->sq_thread_idle = HZ;
10012
10013 io_sq_thread_park(sqd);
10014 list_add(&ctx->sqd_list, &sqd->ctx_list);
10015 io_sqd_update_thread_idle(sqd);
10016 /* don't attach to a dying SQPOLL thread, would be racy */
10017 ret = (attached && !sqd->thread) ? -ENXIO : 0;
10018 io_sq_thread_unpark(sqd);
10019
10020 if (ret < 0)
10021 goto err;
10022 if (attached)
10023 return 0;
10024
10025 if (p->flags & IORING_SETUP_SQ_AFF) {
10026 int cpu = p->sq_thread_cpu;
10027
10028 ret = -EINVAL;
10029 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
10030 goto err_sqpoll;
10031 sqd->sq_cpu = cpu;
10032 } else {
10033 sqd->sq_cpu = -1;
10034 }
10035
10036 sqd->task_pid = current->pid;
10037 sqd->task_tgid = current->tgid;
10038 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
10039 if (IS_ERR(tsk)) {
10040 ret = PTR_ERR(tsk);
10041 goto err_sqpoll;
10042 }
10043
10044 sqd->thread = tsk;
10045 ret = io_uring_alloc_task_context(tsk, ctx);
10046 wake_up_new_task(tsk);
10047 if (ret)
10048 goto err;
10049 } else if (p->flags & IORING_SETUP_SQ_AFF) {
10050 /* Can't have SQ_AFF without SQPOLL */
10051 ret = -EINVAL;
10052 goto err;
10053 }
10054
10055 return 0;
10056 err_sqpoll:
10057 complete(&ctx->sq_data->exited);
10058 err:
10059 io_sq_thread_finish(ctx);
10060 return ret;
10061 }
10062
__io_unaccount_mem(struct user_struct * user,unsigned long nr_pages)10063 static inline void __io_unaccount_mem(struct user_struct *user,
10064 unsigned long nr_pages)
10065 {
10066 atomic_long_sub(nr_pages, &user->locked_vm);
10067 }
10068
__io_account_mem(struct user_struct * user,unsigned long nr_pages)10069 static inline int __io_account_mem(struct user_struct *user,
10070 unsigned long nr_pages)
10071 {
10072 unsigned long page_limit, cur_pages, new_pages;
10073
10074 /* Don't allow more pages than we can safely lock */
10075 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
10076
10077 do {
10078 cur_pages = atomic_long_read(&user->locked_vm);
10079 new_pages = cur_pages + nr_pages;
10080 if (new_pages > page_limit)
10081 return -ENOMEM;
10082 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
10083 new_pages) != cur_pages);
10084
10085 return 0;
10086 }
10087
io_unaccount_mem(struct io_ring_ctx * ctx,unsigned long nr_pages)10088 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10089 {
10090 if (ctx->user)
10091 __io_unaccount_mem(ctx->user, nr_pages);
10092
10093 if (ctx->mm_account)
10094 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
10095 }
10096
io_account_mem(struct io_ring_ctx * ctx,unsigned long nr_pages)10097 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
10098 {
10099 int ret;
10100
10101 if (ctx->user) {
10102 ret = __io_account_mem(ctx->user, nr_pages);
10103 if (ret)
10104 return ret;
10105 }
10106
10107 if (ctx->mm_account)
10108 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
10109
10110 return 0;
10111 }
10112
io_mem_free(void * ptr)10113 static void io_mem_free(void *ptr)
10114 {
10115 struct page *page;
10116
10117 if (!ptr)
10118 return;
10119
10120 page = virt_to_head_page(ptr);
10121 if (put_page_testzero(page))
10122 free_compound_page(page);
10123 }
10124
io_mem_alloc(size_t size)10125 static void *io_mem_alloc(size_t size)
10126 {
10127 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
10128
10129 return (void *) __get_free_pages(gfp, get_order(size));
10130 }
10131
rings_size(struct io_ring_ctx * ctx,unsigned int sq_entries,unsigned int cq_entries,size_t * sq_offset)10132 static unsigned long rings_size(struct io_ring_ctx *ctx, unsigned int sq_entries,
10133 unsigned int cq_entries, size_t *sq_offset)
10134 {
10135 struct io_rings *rings;
10136 size_t off, sq_array_size;
10137
10138 off = struct_size(rings, cqes, cq_entries);
10139 if (off == SIZE_MAX)
10140 return SIZE_MAX;
10141 if (ctx->flags & IORING_SETUP_CQE32) {
10142 if (check_shl_overflow(off, 1, &off))
10143 return SIZE_MAX;
10144 }
10145
10146 #ifdef CONFIG_SMP
10147 off = ALIGN(off, SMP_CACHE_BYTES);
10148 if (off == 0)
10149 return SIZE_MAX;
10150 #endif
10151
10152 if (sq_offset)
10153 *sq_offset = off;
10154
10155 sq_array_size = array_size(sizeof(u32), sq_entries);
10156 if (sq_array_size == SIZE_MAX)
10157 return SIZE_MAX;
10158
10159 if (check_add_overflow(off, sq_array_size, &off))
10160 return SIZE_MAX;
10161
10162 return off;
10163 }
10164
io_buffer_unmap(struct io_ring_ctx * ctx,struct io_mapped_ubuf ** slot)10165 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
10166 {
10167 struct io_mapped_ubuf *imu = *slot;
10168 unsigned int i;
10169
10170 if (imu != ctx->dummy_ubuf) {
10171 for (i = 0; i < imu->nr_bvecs; i++)
10172 unpin_user_page(imu->bvec[i].bv_page);
10173 if (imu->acct_pages)
10174 io_unaccount_mem(ctx, imu->acct_pages);
10175 kvfree(imu);
10176 }
10177 *slot = NULL;
10178 }
10179
io_rsrc_buf_put(struct io_ring_ctx * ctx,struct io_rsrc_put * prsrc)10180 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
10181 {
10182 io_buffer_unmap(ctx, &prsrc->buf);
10183 prsrc->buf = NULL;
10184 }
10185
__io_sqe_buffers_unregister(struct io_ring_ctx * ctx)10186 static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10187 {
10188 unsigned int i;
10189
10190 for (i = 0; i < ctx->nr_user_bufs; i++)
10191 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
10192 kfree(ctx->user_bufs);
10193 io_rsrc_data_free(ctx->buf_data);
10194 ctx->user_bufs = NULL;
10195 ctx->buf_data = NULL;
10196 ctx->nr_user_bufs = 0;
10197 }
10198
io_sqe_buffers_unregister(struct io_ring_ctx * ctx)10199 static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
10200 {
10201 unsigned nr = ctx->nr_user_bufs;
10202 int ret;
10203
10204 if (!ctx->buf_data)
10205 return -ENXIO;
10206
10207 /*
10208 * Quiesce may unlock ->uring_lock, and while it's not held
10209 * prevent new requests using the table.
10210 */
10211 ctx->nr_user_bufs = 0;
10212 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
10213 ctx->nr_user_bufs = nr;
10214 if (!ret)
10215 __io_sqe_buffers_unregister(ctx);
10216 return ret;
10217 }
10218
io_copy_iov(struct io_ring_ctx * ctx,struct iovec * dst,void __user * arg,unsigned index)10219 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
10220 void __user *arg, unsigned index)
10221 {
10222 struct iovec __user *src;
10223
10224 #ifdef CONFIG_COMPAT
10225 if (ctx->compat) {
10226 struct compat_iovec __user *ciovs;
10227 struct compat_iovec ciov;
10228
10229 ciovs = (struct compat_iovec __user *) arg;
10230 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
10231 return -EFAULT;
10232
10233 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
10234 dst->iov_len = ciov.iov_len;
10235 return 0;
10236 }
10237 #endif
10238 src = (struct iovec __user *) arg;
10239 if (copy_from_user(dst, &src[index], sizeof(*dst)))
10240 return -EFAULT;
10241 return 0;
10242 }
10243
10244 /*
10245 * Not super efficient, but this is just a registration time. And we do cache
10246 * the last compound head, so generally we'll only do a full search if we don't
10247 * match that one.
10248 *
10249 * We check if the given compound head page has already been accounted, to
10250 * avoid double accounting it. This allows us to account the full size of the
10251 * page, not just the constituent pages of a huge page.
10252 */
headpage_already_acct(struct io_ring_ctx * ctx,struct page ** pages,int nr_pages,struct page * hpage)10253 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
10254 int nr_pages, struct page *hpage)
10255 {
10256 int i, j;
10257
10258 /* check current page array */
10259 for (i = 0; i < nr_pages; i++) {
10260 if (!PageCompound(pages[i]))
10261 continue;
10262 if (compound_head(pages[i]) == hpage)
10263 return true;
10264 }
10265
10266 /* check previously registered pages */
10267 for (i = 0; i < ctx->nr_user_bufs; i++) {
10268 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
10269
10270 for (j = 0; j < imu->nr_bvecs; j++) {
10271 if (!PageCompound(imu->bvec[j].bv_page))
10272 continue;
10273 if (compound_head(imu->bvec[j].bv_page) == hpage)
10274 return true;
10275 }
10276 }
10277
10278 return false;
10279 }
10280
io_buffer_account_pin(struct io_ring_ctx * ctx,struct page ** pages,int nr_pages,struct io_mapped_ubuf * imu,struct page ** last_hpage)10281 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
10282 int nr_pages, struct io_mapped_ubuf *imu,
10283 struct page **last_hpage)
10284 {
10285 int i, ret;
10286
10287 imu->acct_pages = 0;
10288 for (i = 0; i < nr_pages; i++) {
10289 if (!PageCompound(pages[i])) {
10290 imu->acct_pages++;
10291 } else {
10292 struct page *hpage;
10293
10294 hpage = compound_head(pages[i]);
10295 if (hpage == *last_hpage)
10296 continue;
10297 *last_hpage = hpage;
10298 if (headpage_already_acct(ctx, pages, i, hpage))
10299 continue;
10300 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
10301 }
10302 }
10303
10304 if (!imu->acct_pages)
10305 return 0;
10306
10307 ret = io_account_mem(ctx, imu->acct_pages);
10308 if (ret)
10309 imu->acct_pages = 0;
10310 return ret;
10311 }
10312
io_pin_pages(unsigned long ubuf,unsigned long len,int * npages)10313 static struct page **io_pin_pages(unsigned long ubuf, unsigned long len,
10314 int *npages)
10315 {
10316 unsigned long start, end, nr_pages;
10317 struct vm_area_struct **vmas = NULL;
10318 struct page **pages = NULL;
10319 int i, pret, ret = -ENOMEM;
10320
10321 end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
10322 start = ubuf >> PAGE_SHIFT;
10323 nr_pages = end - start;
10324
10325 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
10326 if (!pages)
10327 goto done;
10328
10329 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
10330 GFP_KERNEL);
10331 if (!vmas)
10332 goto done;
10333
10334 ret = 0;
10335 mmap_read_lock(current->mm);
10336 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
10337 pages, vmas);
10338 if (pret == nr_pages) {
10339 /* don't support file backed memory */
10340 for (i = 0; i < nr_pages; i++) {
10341 struct vm_area_struct *vma = vmas[i];
10342
10343 if (vma_is_shmem(vma))
10344 continue;
10345 if (vma->vm_file &&
10346 !is_file_hugepages(vma->vm_file)) {
10347 ret = -EOPNOTSUPP;
10348 break;
10349 }
10350 }
10351 *npages = nr_pages;
10352 } else {
10353 ret = pret < 0 ? pret : -EFAULT;
10354 }
10355 mmap_read_unlock(current->mm);
10356 if (ret) {
10357 /*
10358 * if we did partial map, or found file backed vmas,
10359 * release any pages we did get
10360 */
10361 if (pret > 0)
10362 unpin_user_pages(pages, pret);
10363 goto done;
10364 }
10365 ret = 0;
10366 done:
10367 kvfree(vmas);
10368 if (ret < 0) {
10369 kvfree(pages);
10370 pages = ERR_PTR(ret);
10371 }
10372 return pages;
10373 }
10374
io_sqe_buffer_register(struct io_ring_ctx * ctx,struct iovec * iov,struct io_mapped_ubuf ** pimu,struct page ** last_hpage)10375 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
10376 struct io_mapped_ubuf **pimu,
10377 struct page **last_hpage)
10378 {
10379 struct io_mapped_ubuf *imu = NULL;
10380 struct page **pages = NULL;
10381 unsigned long off;
10382 size_t size;
10383 int ret, nr_pages, i;
10384
10385 if (!iov->iov_base) {
10386 *pimu = ctx->dummy_ubuf;
10387 return 0;
10388 }
10389
10390 *pimu = NULL;
10391 ret = -ENOMEM;
10392
10393 pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
10394 &nr_pages);
10395 if (IS_ERR(pages)) {
10396 ret = PTR_ERR(pages);
10397 pages = NULL;
10398 goto done;
10399 }
10400
10401 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
10402 if (!imu)
10403 goto done;
10404
10405 ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
10406 if (ret) {
10407 unpin_user_pages(pages, nr_pages);
10408 goto done;
10409 }
10410
10411 off = (unsigned long) iov->iov_base & ~PAGE_MASK;
10412 size = iov->iov_len;
10413 for (i = 0; i < nr_pages; i++) {
10414 size_t vec_len;
10415
10416 vec_len = min_t(size_t, size, PAGE_SIZE - off);
10417 imu->bvec[i].bv_page = pages[i];
10418 imu->bvec[i].bv_len = vec_len;
10419 imu->bvec[i].bv_offset = off;
10420 off = 0;
10421 size -= vec_len;
10422 }
10423 /* store original address for later verification */
10424 imu->ubuf = (unsigned long) iov->iov_base;
10425 imu->ubuf_end = imu->ubuf + iov->iov_len;
10426 imu->nr_bvecs = nr_pages;
10427 *pimu = imu;
10428 ret = 0;
10429 done:
10430 if (ret)
10431 kvfree(imu);
10432 kvfree(pages);
10433 return ret;
10434 }
10435
io_buffers_map_alloc(struct io_ring_ctx * ctx,unsigned int nr_args)10436 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
10437 {
10438 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
10439 return ctx->user_bufs ? 0 : -ENOMEM;
10440 }
10441
io_buffer_validate(struct iovec * iov)10442 static int io_buffer_validate(struct iovec *iov)
10443 {
10444 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
10445
10446 /*
10447 * Don't impose further limits on the size and buffer
10448 * constraints here, we'll -EINVAL later when IO is
10449 * submitted if they are wrong.
10450 */
10451 if (!iov->iov_base)
10452 return iov->iov_len ? -EFAULT : 0;
10453 if (!iov->iov_len)
10454 return -EFAULT;
10455
10456 /* arbitrary limit, but we need something */
10457 if (iov->iov_len > SZ_1G)
10458 return -EFAULT;
10459
10460 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
10461 return -EOVERFLOW;
10462
10463 return 0;
10464 }
10465
io_sqe_buffers_register(struct io_ring_ctx * ctx,void __user * arg,unsigned int nr_args,u64 __user * tags)10466 static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
10467 unsigned int nr_args, u64 __user *tags)
10468 {
10469 struct page *last_hpage = NULL;
10470 struct io_rsrc_data *data;
10471 int i, ret;
10472 struct iovec iov;
10473
10474 if (ctx->user_bufs)
10475 return -EBUSY;
10476 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
10477 return -EINVAL;
10478 ret = io_rsrc_node_switch_start(ctx);
10479 if (ret)
10480 return ret;
10481 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
10482 if (ret)
10483 return ret;
10484 ret = io_buffers_map_alloc(ctx, nr_args);
10485 if (ret) {
10486 io_rsrc_data_free(data);
10487 return ret;
10488 }
10489
10490 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
10491 if (arg) {
10492 ret = io_copy_iov(ctx, &iov, arg, i);
10493 if (ret)
10494 break;
10495 ret = io_buffer_validate(&iov);
10496 if (ret)
10497 break;
10498 } else {
10499 memset(&iov, 0, sizeof(iov));
10500 }
10501
10502 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
10503 ret = -EINVAL;
10504 break;
10505 }
10506
10507 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
10508 &last_hpage);
10509 if (ret)
10510 break;
10511 }
10512
10513 WARN_ON_ONCE(ctx->buf_data);
10514
10515 ctx->buf_data = data;
10516 if (ret)
10517 __io_sqe_buffers_unregister(ctx);
10518 else
10519 io_rsrc_node_switch(ctx, NULL);
10520 return ret;
10521 }
10522
__io_sqe_buffers_update(struct io_ring_ctx * ctx,struct io_uring_rsrc_update2 * up,unsigned int nr_args)10523 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
10524 struct io_uring_rsrc_update2 *up,
10525 unsigned int nr_args)
10526 {
10527 u64 __user *tags = u64_to_user_ptr(up->tags);
10528 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
10529 struct page *last_hpage = NULL;
10530 bool needs_switch = false;
10531 __u32 done;
10532 int i, err;
10533
10534 if (!ctx->buf_data)
10535 return -ENXIO;
10536 if (up->offset + nr_args > ctx->nr_user_bufs)
10537 return -EINVAL;
10538
10539 for (done = 0; done < nr_args; done++) {
10540 struct io_mapped_ubuf *imu;
10541 int offset = up->offset + done;
10542 u64 tag = 0;
10543
10544 err = io_copy_iov(ctx, &iov, iovs, done);
10545 if (err)
10546 break;
10547 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
10548 err = -EFAULT;
10549 break;
10550 }
10551 err = io_buffer_validate(&iov);
10552 if (err)
10553 break;
10554 if (!iov.iov_base && tag) {
10555 err = -EINVAL;
10556 break;
10557 }
10558 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
10559 if (err)
10560 break;
10561
10562 i = array_index_nospec(offset, ctx->nr_user_bufs);
10563 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
10564 err = io_queue_rsrc_removal(ctx->buf_data, i,
10565 ctx->rsrc_node, ctx->user_bufs[i]);
10566 if (unlikely(err)) {
10567 io_buffer_unmap(ctx, &imu);
10568 break;
10569 }
10570 ctx->user_bufs[i] = NULL;
10571 needs_switch = true;
10572 }
10573
10574 ctx->user_bufs[i] = imu;
10575 *io_get_tag_slot(ctx->buf_data, offset) = tag;
10576 }
10577
10578 if (needs_switch)
10579 io_rsrc_node_switch(ctx, ctx->buf_data);
10580 return done ? done : err;
10581 }
10582
io_eventfd_register(struct io_ring_ctx * ctx,void __user * arg,unsigned int eventfd_async)10583 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
10584 unsigned int eventfd_async)
10585 {
10586 struct io_ev_fd *ev_fd;
10587 __s32 __user *fds = arg;
10588 int fd;
10589
10590 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
10591 lockdep_is_held(&ctx->uring_lock));
10592 if (ev_fd)
10593 return -EBUSY;
10594
10595 if (copy_from_user(&fd, fds, sizeof(*fds)))
10596 return -EFAULT;
10597
10598 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
10599 if (!ev_fd)
10600 return -ENOMEM;
10601
10602 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
10603 if (IS_ERR(ev_fd->cq_ev_fd)) {
10604 int ret = PTR_ERR(ev_fd->cq_ev_fd);
10605 kfree(ev_fd);
10606 return ret;
10607 }
10608 ev_fd->eventfd_async = eventfd_async;
10609 ctx->has_evfd = true;
10610 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
10611 return 0;
10612 }
10613
io_eventfd_put(struct rcu_head * rcu)10614 static void io_eventfd_put(struct rcu_head *rcu)
10615 {
10616 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
10617
10618 eventfd_ctx_put(ev_fd->cq_ev_fd);
10619 kfree(ev_fd);
10620 }
10621
io_eventfd_unregister(struct io_ring_ctx * ctx)10622 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
10623 {
10624 struct io_ev_fd *ev_fd;
10625
10626 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
10627 lockdep_is_held(&ctx->uring_lock));
10628 if (ev_fd) {
10629 ctx->has_evfd = false;
10630 rcu_assign_pointer(ctx->io_ev_fd, NULL);
10631 call_rcu(&ev_fd->rcu, io_eventfd_put);
10632 return 0;
10633 }
10634
10635 return -ENXIO;
10636 }
10637
io_destroy_buffers(struct io_ring_ctx * ctx)10638 static void io_destroy_buffers(struct io_ring_ctx *ctx)
10639 {
10640 struct io_buffer_list *bl;
10641 unsigned long index;
10642 int i;
10643
10644 for (i = 0; i < BGID_ARRAY; i++) {
10645 if (!ctx->io_bl)
10646 break;
10647 __io_remove_buffers(ctx, &ctx->io_bl[i], -1U);
10648 }
10649
10650 xa_for_each(&ctx->io_bl_xa, index, bl) {
10651 xa_erase(&ctx->io_bl_xa, bl->bgid);
10652 __io_remove_buffers(ctx, bl, -1U);
10653 kfree(bl);
10654 }
10655
10656 while (!list_empty(&ctx->io_buffers_pages)) {
10657 struct page *page;
10658
10659 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
10660 list_del_init(&page->lru);
10661 __free_page(page);
10662 }
10663 }
10664
io_req_caches_free(struct io_ring_ctx * ctx)10665 static void io_req_caches_free(struct io_ring_ctx *ctx)
10666 {
10667 struct io_submit_state *state = &ctx->submit_state;
10668 int nr = 0;
10669
10670 mutex_lock(&ctx->uring_lock);
10671 io_flush_cached_locked_reqs(ctx, state);
10672
10673 while (!io_req_cache_empty(ctx)) {
10674 struct io_wq_work_node *node;
10675 struct io_kiocb *req;
10676
10677 node = wq_stack_extract(&state->free_list);
10678 req = container_of(node, struct io_kiocb, comp_list);
10679 kmem_cache_free(req_cachep, req);
10680 nr++;
10681 }
10682 if (nr)
10683 percpu_ref_put_many(&ctx->refs, nr);
10684 mutex_unlock(&ctx->uring_lock);
10685 }
10686
io_wait_rsrc_data(struct io_rsrc_data * data)10687 static void io_wait_rsrc_data(struct io_rsrc_data *data)
10688 {
10689 if (data && !atomic_dec_and_test(&data->refs))
10690 wait_for_completion(&data->done);
10691 }
10692
io_flush_apoll_cache(struct io_ring_ctx * ctx)10693 static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
10694 {
10695 struct async_poll *apoll;
10696
10697 while (!list_empty(&ctx->apoll_cache)) {
10698 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
10699 poll.wait.entry);
10700 list_del(&apoll->poll.wait.entry);
10701 kfree(apoll);
10702 }
10703 }
10704
io_ring_ctx_free(struct io_ring_ctx * ctx)10705 static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
10706 {
10707 io_sq_thread_finish(ctx);
10708
10709 if (ctx->mm_account) {
10710 mmdrop(ctx->mm_account);
10711 ctx->mm_account = NULL;
10712 }
10713
10714 io_rsrc_refs_drop(ctx);
10715 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
10716 io_wait_rsrc_data(ctx->buf_data);
10717 io_wait_rsrc_data(ctx->file_data);
10718
10719 mutex_lock(&ctx->uring_lock);
10720 if (ctx->buf_data)
10721 __io_sqe_buffers_unregister(ctx);
10722 if (ctx->file_data)
10723 __io_sqe_files_unregister(ctx);
10724 if (ctx->rings)
10725 __io_cqring_overflow_flush(ctx, true);
10726 io_eventfd_unregister(ctx);
10727 io_flush_apoll_cache(ctx);
10728 mutex_unlock(&ctx->uring_lock);
10729 io_destroy_buffers(ctx);
10730 if (ctx->sq_creds)
10731 put_cred(ctx->sq_creds);
10732
10733 /* there are no registered resources left, nobody uses it */
10734 if (ctx->rsrc_node)
10735 io_rsrc_node_destroy(ctx->rsrc_node);
10736 if (ctx->rsrc_backup_node)
10737 io_rsrc_node_destroy(ctx->rsrc_backup_node);
10738 flush_delayed_work(&ctx->rsrc_put_work);
10739 flush_delayed_work(&ctx->fallback_work);
10740
10741 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
10742 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
10743
10744 #if defined(CONFIG_UNIX)
10745 if (ctx->ring_sock) {
10746 ctx->ring_sock->file = NULL; /* so that iput() is called */
10747 sock_release(ctx->ring_sock);
10748 }
10749 #endif
10750 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
10751
10752 io_mem_free(ctx->rings);
10753 io_mem_free(ctx->sq_sqes);
10754
10755 percpu_ref_exit(&ctx->refs);
10756 free_uid(ctx->user);
10757 io_req_caches_free(ctx);
10758 if (ctx->hash_map)
10759 io_wq_put_hash(ctx->hash_map);
10760 kfree(ctx->cancel_hash);
10761 kfree(ctx->dummy_ubuf);
10762 kfree(ctx->io_bl);
10763 xa_destroy(&ctx->io_bl_xa);
10764 kfree(ctx);
10765 }
10766
io_uring_poll(struct file * file,poll_table * wait)10767 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
10768 {
10769 struct io_ring_ctx *ctx = file->private_data;
10770 __poll_t mask = 0;
10771
10772 poll_wait(file, &ctx->cq_wait, wait);
10773 /*
10774 * synchronizes with barrier from wq_has_sleeper call in
10775 * io_commit_cqring
10776 */
10777 smp_rmb();
10778 if (!io_sqring_full(ctx))
10779 mask |= EPOLLOUT | EPOLLWRNORM;
10780
10781 /*
10782 * Don't flush cqring overflow list here, just do a simple check.
10783 * Otherwise there could possible be ABBA deadlock:
10784 * CPU0 CPU1
10785 * ---- ----
10786 * lock(&ctx->uring_lock);
10787 * lock(&ep->mtx);
10788 * lock(&ctx->uring_lock);
10789 * lock(&ep->mtx);
10790 *
10791 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
10792 * pushs them to do the flush.
10793 */
10794 if (io_cqring_events(ctx) ||
10795 test_bit(IO_CHECK_CQ_OVERFLOW_BIT, &ctx->check_cq))
10796 mask |= EPOLLIN | EPOLLRDNORM;
10797
10798 return mask;
10799 }
10800
io_unregister_personality(struct io_ring_ctx * ctx,unsigned id)10801 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
10802 {
10803 const struct cred *creds;
10804
10805 creds = xa_erase(&ctx->personalities, id);
10806 if (creds) {
10807 put_cred(creds);
10808 return 0;
10809 }
10810
10811 return -EINVAL;
10812 }
10813
10814 struct io_tctx_exit {
10815 struct callback_head task_work;
10816 struct completion completion;
10817 struct io_ring_ctx *ctx;
10818 };
10819
io_tctx_exit_cb(struct callback_head * cb)10820 static __cold void io_tctx_exit_cb(struct callback_head *cb)
10821 {
10822 struct io_uring_task *tctx = current->io_uring;
10823 struct io_tctx_exit *work;
10824
10825 work = container_of(cb, struct io_tctx_exit, task_work);
10826 /*
10827 * When @in_idle, we're in cancellation and it's racy to remove the
10828 * node. It'll be removed by the end of cancellation, just ignore it.
10829 */
10830 if (!atomic_read(&tctx->in_idle))
10831 io_uring_del_tctx_node((unsigned long)work->ctx);
10832 complete(&work->completion);
10833 }
10834
io_cancel_ctx_cb(struct io_wq_work * work,void * data)10835 static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
10836 {
10837 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10838
10839 return req->ctx == data;
10840 }
10841
io_ring_exit_work(struct work_struct * work)10842 static __cold void io_ring_exit_work(struct work_struct *work)
10843 {
10844 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
10845 unsigned long timeout = jiffies + HZ * 60 * 5;
10846 unsigned long interval = HZ / 20;
10847 struct io_tctx_exit exit;
10848 struct io_tctx_node *node;
10849 int ret;
10850
10851 /*
10852 * If we're doing polled IO and end up having requests being
10853 * submitted async (out-of-line), then completions can come in while
10854 * we're waiting for refs to drop. We need to reap these manually,
10855 * as nobody else will be looking for them.
10856 */
10857 do {
10858 io_uring_try_cancel_requests(ctx, NULL, true);
10859 if (ctx->sq_data) {
10860 struct io_sq_data *sqd = ctx->sq_data;
10861 struct task_struct *tsk;
10862
10863 io_sq_thread_park(sqd);
10864 tsk = sqd->thread;
10865 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
10866 io_wq_cancel_cb(tsk->io_uring->io_wq,
10867 io_cancel_ctx_cb, ctx, true);
10868 io_sq_thread_unpark(sqd);
10869 }
10870
10871 io_req_caches_free(ctx);
10872
10873 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
10874 /* there is little hope left, don't run it too often */
10875 interval = HZ * 60;
10876 }
10877 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
10878
10879 init_completion(&exit.completion);
10880 init_task_work(&exit.task_work, io_tctx_exit_cb);
10881 exit.ctx = ctx;
10882 /*
10883 * Some may use context even when all refs and requests have been put,
10884 * and they are free to do so while still holding uring_lock or
10885 * completion_lock, see io_req_task_submit(). Apart from other work,
10886 * this lock/unlock section also waits them to finish.
10887 */
10888 mutex_lock(&ctx->uring_lock);
10889 while (!list_empty(&ctx->tctx_list)) {
10890 WARN_ON_ONCE(time_after(jiffies, timeout));
10891
10892 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
10893 ctx_node);
10894 /* don't spin on a single task if cancellation failed */
10895 list_rotate_left(&ctx->tctx_list);
10896 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
10897 if (WARN_ON_ONCE(ret))
10898 continue;
10899
10900 mutex_unlock(&ctx->uring_lock);
10901 wait_for_completion(&exit.completion);
10902 mutex_lock(&ctx->uring_lock);
10903 }
10904 mutex_unlock(&ctx->uring_lock);
10905 spin_lock(&ctx->completion_lock);
10906 spin_unlock(&ctx->completion_lock);
10907
10908 io_ring_ctx_free(ctx);
10909 }
10910
10911 /* Returns true if we found and killed one or more timeouts */
io_kill_timeouts(struct io_ring_ctx * ctx,struct task_struct * tsk,bool cancel_all)10912 static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
10913 struct task_struct *tsk, bool cancel_all)
10914 {
10915 struct io_kiocb *req, *tmp;
10916 int canceled = 0;
10917
10918 spin_lock(&ctx->completion_lock);
10919 spin_lock_irq(&ctx->timeout_lock);
10920 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
10921 if (io_match_task(req, tsk, cancel_all)) {
10922 io_kill_timeout(req, -ECANCELED);
10923 canceled++;
10924 }
10925 }
10926 spin_unlock_irq(&ctx->timeout_lock);
10927 io_commit_cqring(ctx);
10928 spin_unlock(&ctx->completion_lock);
10929 if (canceled != 0)
10930 io_cqring_ev_posted(ctx);
10931 return canceled != 0;
10932 }
10933
io_ring_ctx_wait_and_kill(struct io_ring_ctx * ctx)10934 static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
10935 {
10936 unsigned long index;
10937 struct creds *creds;
10938
10939 mutex_lock(&ctx->uring_lock);
10940 percpu_ref_kill(&ctx->refs);
10941 if (ctx->rings)
10942 __io_cqring_overflow_flush(ctx, true);
10943 xa_for_each(&ctx->personalities, index, creds)
10944 io_unregister_personality(ctx, index);
10945 mutex_unlock(&ctx->uring_lock);
10946
10947 /* failed during ring init, it couldn't have issued any requests */
10948 if (ctx->rings) {
10949 io_kill_timeouts(ctx, NULL, true);
10950 io_poll_remove_all(ctx, NULL, true);
10951 /* if we failed setting up the ctx, we might not have any rings */
10952 io_iopoll_try_reap_events(ctx);
10953 }
10954
10955 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
10956 /*
10957 * Use system_unbound_wq to avoid spawning tons of event kworkers
10958 * if we're exiting a ton of rings at the same time. It just adds
10959 * noise and overhead, there's no discernable change in runtime
10960 * over using system_wq.
10961 */
10962 queue_work(system_unbound_wq, &ctx->exit_work);
10963 }
10964
io_uring_release(struct inode * inode,struct file * file)10965 static int io_uring_release(struct inode *inode, struct file *file)
10966 {
10967 struct io_ring_ctx *ctx = file->private_data;
10968
10969 file->private_data = NULL;
10970 io_ring_ctx_wait_and_kill(ctx);
10971 return 0;
10972 }
10973
10974 struct io_task_cancel {
10975 struct task_struct *task;
10976 bool all;
10977 };
10978
io_cancel_task_cb(struct io_wq_work * work,void * data)10979 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
10980 {
10981 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10982 struct io_task_cancel *cancel = data;
10983
10984 return io_match_task_safe(req, cancel->task, cancel->all);
10985 }
10986
io_cancel_defer_files(struct io_ring_ctx * ctx,struct task_struct * task,bool cancel_all)10987 static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
10988 struct task_struct *task,
10989 bool cancel_all)
10990 {
10991 struct io_defer_entry *de;
10992 LIST_HEAD(list);
10993
10994 spin_lock(&ctx->completion_lock);
10995 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
10996 if (io_match_task_safe(de->req, task, cancel_all)) {
10997 list_cut_position(&list, &ctx->defer_list, &de->list);
10998 break;
10999 }
11000 }
11001 spin_unlock(&ctx->completion_lock);
11002 if (list_empty(&list))
11003 return false;
11004
11005 while (!list_empty(&list)) {
11006 de = list_first_entry(&list, struct io_defer_entry, list);
11007 list_del_init(&de->list);
11008 io_req_complete_failed(de->req, -ECANCELED);
11009 kfree(de);
11010 }
11011 return true;
11012 }
11013
io_uring_try_cancel_iowq(struct io_ring_ctx * ctx)11014 static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
11015 {
11016 struct io_tctx_node *node;
11017 enum io_wq_cancel cret;
11018 bool ret = false;
11019
11020 mutex_lock(&ctx->uring_lock);
11021 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11022 struct io_uring_task *tctx = node->task->io_uring;
11023
11024 /*
11025 * io_wq will stay alive while we hold uring_lock, because it's
11026 * killed after ctx nodes, which requires to take the lock.
11027 */
11028 if (!tctx || !tctx->io_wq)
11029 continue;
11030 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
11031 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11032 }
11033 mutex_unlock(&ctx->uring_lock);
11034
11035 return ret;
11036 }
11037
io_uring_try_cancel_requests(struct io_ring_ctx * ctx,struct task_struct * task,bool cancel_all)11038 static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
11039 struct task_struct *task,
11040 bool cancel_all)
11041 {
11042 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
11043 struct io_uring_task *tctx = task ? task->io_uring : NULL;
11044
11045 /* failed during ring init, it couldn't have issued any requests */
11046 if (!ctx->rings)
11047 return;
11048
11049 while (1) {
11050 enum io_wq_cancel cret;
11051 bool ret = false;
11052
11053 if (!task) {
11054 ret |= io_uring_try_cancel_iowq(ctx);
11055 } else if (tctx && tctx->io_wq) {
11056 /*
11057 * Cancels requests of all rings, not only @ctx, but
11058 * it's fine as the task is in exit/exec.
11059 */
11060 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
11061 &cancel, true);
11062 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
11063 }
11064
11065 /* SQPOLL thread does its own polling */
11066 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
11067 (ctx->sq_data && ctx->sq_data->thread == current)) {
11068 while (!wq_list_empty(&ctx->iopoll_list)) {
11069 io_iopoll_try_reap_events(ctx);
11070 ret = true;
11071 }
11072 }
11073
11074 ret |= io_cancel_defer_files(ctx, task, cancel_all);
11075 ret |= io_poll_remove_all(ctx, task, cancel_all);
11076 ret |= io_kill_timeouts(ctx, task, cancel_all);
11077 if (task)
11078 ret |= io_run_task_work();
11079 if (!ret)
11080 break;
11081 cond_resched();
11082 }
11083 }
11084
__io_uring_add_tctx_node(struct io_ring_ctx * ctx)11085 static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11086 {
11087 struct io_uring_task *tctx = current->io_uring;
11088 struct io_tctx_node *node;
11089 int ret;
11090
11091 if (unlikely(!tctx)) {
11092 ret = io_uring_alloc_task_context(current, ctx);
11093 if (unlikely(ret))
11094 return ret;
11095
11096 tctx = current->io_uring;
11097 if (ctx->iowq_limits_set) {
11098 unsigned int limits[2] = { ctx->iowq_limits[0],
11099 ctx->iowq_limits[1], };
11100
11101 ret = io_wq_max_workers(tctx->io_wq, limits);
11102 if (ret)
11103 return ret;
11104 }
11105 }
11106 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
11107 node = kmalloc(sizeof(*node), GFP_KERNEL);
11108 if (!node)
11109 return -ENOMEM;
11110 node->ctx = ctx;
11111 node->task = current;
11112
11113 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
11114 node, GFP_KERNEL));
11115 if (ret) {
11116 kfree(node);
11117 return ret;
11118 }
11119
11120 mutex_lock(&ctx->uring_lock);
11121 list_add(&node->ctx_node, &ctx->tctx_list);
11122 mutex_unlock(&ctx->uring_lock);
11123 }
11124 tctx->last = ctx;
11125 return 0;
11126 }
11127
11128 /*
11129 * Note that this task has used io_uring. We use it for cancelation purposes.
11130 */
io_uring_add_tctx_node(struct io_ring_ctx * ctx)11131 static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
11132 {
11133 struct io_uring_task *tctx = current->io_uring;
11134
11135 if (likely(tctx && tctx->last == ctx))
11136 return 0;
11137 return __io_uring_add_tctx_node(ctx);
11138 }
11139
11140 /*
11141 * Remove this io_uring_file -> task mapping.
11142 */
io_uring_del_tctx_node(unsigned long index)11143 static __cold void io_uring_del_tctx_node(unsigned long index)
11144 {
11145 struct io_uring_task *tctx = current->io_uring;
11146 struct io_tctx_node *node;
11147
11148 if (!tctx)
11149 return;
11150 node = xa_erase(&tctx->xa, index);
11151 if (!node)
11152 return;
11153
11154 WARN_ON_ONCE(current != node->task);
11155 WARN_ON_ONCE(list_empty(&node->ctx_node));
11156
11157 mutex_lock(&node->ctx->uring_lock);
11158 list_del(&node->ctx_node);
11159 mutex_unlock(&node->ctx->uring_lock);
11160
11161 if (tctx->last == node->ctx)
11162 tctx->last = NULL;
11163 kfree(node);
11164 }
11165
io_uring_clean_tctx(struct io_uring_task * tctx)11166 static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
11167 {
11168 struct io_wq *wq = tctx->io_wq;
11169 struct io_tctx_node *node;
11170 unsigned long index;
11171
11172 xa_for_each(&tctx->xa, index, node) {
11173 io_uring_del_tctx_node(index);
11174 cond_resched();
11175 }
11176 if (wq) {
11177 /*
11178 * Must be after io_uring_del_tctx_node() (removes nodes under
11179 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
11180 */
11181 io_wq_put_and_exit(wq);
11182 tctx->io_wq = NULL;
11183 }
11184 }
11185
tctx_inflight(struct io_uring_task * tctx,bool tracked)11186 static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
11187 {
11188 if (tracked)
11189 return atomic_read(&tctx->inflight_tracked);
11190 return percpu_counter_sum(&tctx->inflight);
11191 }
11192
11193 /*
11194 * Find any io_uring ctx that this task has registered or done IO on, and cancel
11195 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
11196 */
io_uring_cancel_generic(bool cancel_all,struct io_sq_data * sqd)11197 static __cold void io_uring_cancel_generic(bool cancel_all,
11198 struct io_sq_data *sqd)
11199 {
11200 struct io_uring_task *tctx = current->io_uring;
11201 struct io_ring_ctx *ctx;
11202 s64 inflight;
11203 DEFINE_WAIT(wait);
11204
11205 WARN_ON_ONCE(sqd && sqd->thread != current);
11206
11207 if (!current->io_uring)
11208 return;
11209 if (tctx->io_wq)
11210 io_wq_exit_start(tctx->io_wq);
11211
11212 atomic_inc(&tctx->in_idle);
11213 do {
11214 io_uring_drop_tctx_refs(current);
11215 /* read completions before cancelations */
11216 inflight = tctx_inflight(tctx, !cancel_all);
11217 if (!inflight)
11218 break;
11219
11220 if (!sqd) {
11221 struct io_tctx_node *node;
11222 unsigned long index;
11223
11224 xa_for_each(&tctx->xa, index, node) {
11225 /* sqpoll task will cancel all its requests */
11226 if (node->ctx->sq_data)
11227 continue;
11228 io_uring_try_cancel_requests(node->ctx, current,
11229 cancel_all);
11230 }
11231 } else {
11232 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
11233 io_uring_try_cancel_requests(ctx, current,
11234 cancel_all);
11235 }
11236
11237 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
11238 io_run_task_work();
11239 io_uring_drop_tctx_refs(current);
11240
11241 /*
11242 * If we've seen completions, retry without waiting. This
11243 * avoids a race where a completion comes in before we did
11244 * prepare_to_wait().
11245 */
11246 if (inflight == tctx_inflight(tctx, !cancel_all))
11247 schedule();
11248 finish_wait(&tctx->wait, &wait);
11249 } while (1);
11250
11251 io_uring_clean_tctx(tctx);
11252 if (cancel_all) {
11253 /*
11254 * We shouldn't run task_works after cancel, so just leave
11255 * ->in_idle set for normal exit.
11256 */
11257 atomic_dec(&tctx->in_idle);
11258 /* for exec all current's requests should be gone, kill tctx */
11259 __io_uring_free(current);
11260 }
11261 }
11262
__io_uring_cancel(bool cancel_all)11263 void __io_uring_cancel(bool cancel_all)
11264 {
11265 io_uring_cancel_generic(cancel_all, NULL);
11266 }
11267
io_uring_unreg_ringfd(void)11268 void io_uring_unreg_ringfd(void)
11269 {
11270 struct io_uring_task *tctx = current->io_uring;
11271 int i;
11272
11273 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
11274 if (tctx->registered_rings[i]) {
11275 fput(tctx->registered_rings[i]);
11276 tctx->registered_rings[i] = NULL;
11277 }
11278 }
11279 }
11280
io_ring_add_registered_fd(struct io_uring_task * tctx,int fd,int start,int end)11281 static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
11282 int start, int end)
11283 {
11284 struct file *file;
11285 int offset;
11286
11287 for (offset = start; offset < end; offset++) {
11288 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
11289 if (tctx->registered_rings[offset])
11290 continue;
11291
11292 file = fget(fd);
11293 if (!file) {
11294 return -EBADF;
11295 } else if (file->f_op != &io_uring_fops) {
11296 fput(file);
11297 return -EOPNOTSUPP;
11298 }
11299 tctx->registered_rings[offset] = file;
11300 return offset;
11301 }
11302
11303 return -EBUSY;
11304 }
11305
11306 /*
11307 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
11308 * invocation. User passes in an array of struct io_uring_rsrc_update
11309 * with ->data set to the ring_fd, and ->offset given for the desired
11310 * index. If no index is desired, application may set ->offset == -1U
11311 * and we'll find an available index. Returns number of entries
11312 * successfully processed, or < 0 on error if none were processed.
11313 */
io_ringfd_register(struct io_ring_ctx * ctx,void __user * __arg,unsigned nr_args)11314 static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
11315 unsigned nr_args)
11316 {
11317 struct io_uring_rsrc_update __user *arg = __arg;
11318 struct io_uring_rsrc_update reg;
11319 struct io_uring_task *tctx;
11320 int ret, i;
11321
11322 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11323 return -EINVAL;
11324
11325 mutex_unlock(&ctx->uring_lock);
11326 ret = io_uring_add_tctx_node(ctx);
11327 mutex_lock(&ctx->uring_lock);
11328 if (ret)
11329 return ret;
11330
11331 tctx = current->io_uring;
11332 for (i = 0; i < nr_args; i++) {
11333 int start, end;
11334
11335 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11336 ret = -EFAULT;
11337 break;
11338 }
11339
11340 if (reg.resv) {
11341 ret = -EINVAL;
11342 break;
11343 }
11344
11345 if (reg.offset == -1U) {
11346 start = 0;
11347 end = IO_RINGFD_REG_MAX;
11348 } else {
11349 if (reg.offset >= IO_RINGFD_REG_MAX) {
11350 ret = -EINVAL;
11351 break;
11352 }
11353 start = reg.offset;
11354 end = start + 1;
11355 }
11356
11357 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
11358 if (ret < 0)
11359 break;
11360
11361 reg.offset = ret;
11362 if (copy_to_user(&arg[i], ®, sizeof(reg))) {
11363 fput(tctx->registered_rings[reg.offset]);
11364 tctx->registered_rings[reg.offset] = NULL;
11365 ret = -EFAULT;
11366 break;
11367 }
11368 }
11369
11370 return i ? i : ret;
11371 }
11372
io_ringfd_unregister(struct io_ring_ctx * ctx,void __user * __arg,unsigned nr_args)11373 static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
11374 unsigned nr_args)
11375 {
11376 struct io_uring_rsrc_update __user *arg = __arg;
11377 struct io_uring_task *tctx = current->io_uring;
11378 struct io_uring_rsrc_update reg;
11379 int ret = 0, i;
11380
11381 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
11382 return -EINVAL;
11383 if (!tctx)
11384 return 0;
11385
11386 for (i = 0; i < nr_args; i++) {
11387 if (copy_from_user(®, &arg[i], sizeof(reg))) {
11388 ret = -EFAULT;
11389 break;
11390 }
11391 if (reg.resv || reg.data || reg.offset >= IO_RINGFD_REG_MAX) {
11392 ret = -EINVAL;
11393 break;
11394 }
11395
11396 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
11397 if (tctx->registered_rings[reg.offset]) {
11398 fput(tctx->registered_rings[reg.offset]);
11399 tctx->registered_rings[reg.offset] = NULL;
11400 }
11401 }
11402
11403 return i ? i : ret;
11404 }
11405
io_uring_validate_mmap_request(struct file * file,loff_t pgoff,size_t sz)11406 static void *io_uring_validate_mmap_request(struct file *file,
11407 loff_t pgoff, size_t sz)
11408 {
11409 struct io_ring_ctx *ctx = file->private_data;
11410 loff_t offset = pgoff << PAGE_SHIFT;
11411 struct page *page;
11412 void *ptr;
11413
11414 switch (offset) {
11415 case IORING_OFF_SQ_RING:
11416 case IORING_OFF_CQ_RING:
11417 ptr = ctx->rings;
11418 break;
11419 case IORING_OFF_SQES:
11420 ptr = ctx->sq_sqes;
11421 break;
11422 default:
11423 return ERR_PTR(-EINVAL);
11424 }
11425
11426 page = virt_to_head_page(ptr);
11427 if (sz > page_size(page))
11428 return ERR_PTR(-EINVAL);
11429
11430 return ptr;
11431 }
11432
11433 #ifdef CONFIG_MMU
11434
io_uring_mmap(struct file * file,struct vm_area_struct * vma)11435 static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11436 {
11437 size_t sz = vma->vm_end - vma->vm_start;
11438 unsigned long pfn;
11439 void *ptr;
11440
11441 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
11442 if (IS_ERR(ptr))
11443 return PTR_ERR(ptr);
11444
11445 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
11446 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
11447 }
11448
11449 #else /* !CONFIG_MMU */
11450
io_uring_mmap(struct file * file,struct vm_area_struct * vma)11451 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
11452 {
11453 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
11454 }
11455
io_uring_nommu_mmap_capabilities(struct file * file)11456 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
11457 {
11458 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
11459 }
11460
io_uring_nommu_get_unmapped_area(struct file * file,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags)11461 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
11462 unsigned long addr, unsigned long len,
11463 unsigned long pgoff, unsigned long flags)
11464 {
11465 void *ptr;
11466
11467 ptr = io_uring_validate_mmap_request(file, pgoff, len);
11468 if (IS_ERR(ptr))
11469 return PTR_ERR(ptr);
11470
11471 return (unsigned long) ptr;
11472 }
11473
11474 #endif /* !CONFIG_MMU */
11475
io_sqpoll_wait_sq(struct io_ring_ctx * ctx)11476 static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
11477 {
11478 DEFINE_WAIT(wait);
11479
11480 do {
11481 if (!io_sqring_full(ctx))
11482 break;
11483 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
11484
11485 if (!io_sqring_full(ctx))
11486 break;
11487 schedule();
11488 } while (!signal_pending(current));
11489
11490 finish_wait(&ctx->sqo_sq_wait, &wait);
11491 return 0;
11492 }
11493
io_validate_ext_arg(unsigned flags,const void __user * argp,size_t argsz)11494 static int io_validate_ext_arg(unsigned flags, const void __user *argp, size_t argsz)
11495 {
11496 if (flags & IORING_ENTER_EXT_ARG) {
11497 struct io_uring_getevents_arg arg;
11498
11499 if (argsz != sizeof(arg))
11500 return -EINVAL;
11501 if (copy_from_user(&arg, argp, sizeof(arg)))
11502 return -EFAULT;
11503 }
11504 return 0;
11505 }
11506
io_get_ext_arg(unsigned flags,const void __user * argp,size_t * argsz,struct __kernel_timespec __user ** ts,const sigset_t __user ** sig)11507 static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
11508 struct __kernel_timespec __user **ts,
11509 const sigset_t __user **sig)
11510 {
11511 struct io_uring_getevents_arg arg;
11512
11513 /*
11514 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
11515 * is just a pointer to the sigset_t.
11516 */
11517 if (!(flags & IORING_ENTER_EXT_ARG)) {
11518 *sig = (const sigset_t __user *) argp;
11519 *ts = NULL;
11520 return 0;
11521 }
11522
11523 /*
11524 * EXT_ARG is set - ensure we agree on the size of it and copy in our
11525 * timespec and sigset_t pointers if good.
11526 */
11527 if (*argsz != sizeof(arg))
11528 return -EINVAL;
11529 if (copy_from_user(&arg, argp, sizeof(arg)))
11530 return -EFAULT;
11531 if (arg.pad)
11532 return -EINVAL;
11533 *sig = u64_to_user_ptr(arg.sigmask);
11534 *argsz = arg.sigmask_sz;
11535 *ts = u64_to_user_ptr(arg.ts);
11536 return 0;
11537 }
11538
SYSCALL_DEFINE6(io_uring_enter,unsigned int,fd,u32,to_submit,u32,min_complete,u32,flags,const void __user *,argp,size_t,argsz)11539 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
11540 u32, min_complete, u32, flags, const void __user *, argp,
11541 size_t, argsz)
11542 {
11543 struct io_ring_ctx *ctx;
11544 struct fd f;
11545 long ret;
11546
11547 io_run_task_work();
11548
11549 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
11550 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
11551 IORING_ENTER_REGISTERED_RING)))
11552 return -EINVAL;
11553
11554 /*
11555 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
11556 * need only dereference our task private array to find it.
11557 */
11558 if (flags & IORING_ENTER_REGISTERED_RING) {
11559 struct io_uring_task *tctx = current->io_uring;
11560
11561 if (!tctx || fd >= IO_RINGFD_REG_MAX)
11562 return -EINVAL;
11563 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
11564 f.file = tctx->registered_rings[fd];
11565 f.flags = 0;
11566 } else {
11567 f = fdget(fd);
11568 }
11569
11570 if (unlikely(!f.file))
11571 return -EBADF;
11572
11573 ret = -EOPNOTSUPP;
11574 if (unlikely(f.file->f_op != &io_uring_fops))
11575 goto out_fput;
11576
11577 ret = -ENXIO;
11578 ctx = f.file->private_data;
11579 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
11580 goto out_fput;
11581
11582 ret = -EBADFD;
11583 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
11584 goto out;
11585
11586 /*
11587 * For SQ polling, the thread will do all submissions and completions.
11588 * Just return the requested submit count, and wake the thread if
11589 * we were asked to.
11590 */
11591 ret = 0;
11592 if (ctx->flags & IORING_SETUP_SQPOLL) {
11593 io_cqring_overflow_flush(ctx);
11594
11595 if (unlikely(ctx->sq_data->thread == NULL)) {
11596 ret = -EOWNERDEAD;
11597 goto out;
11598 }
11599 if (flags & IORING_ENTER_SQ_WAKEUP)
11600 wake_up(&ctx->sq_data->wait);
11601 if (flags & IORING_ENTER_SQ_WAIT) {
11602 ret = io_sqpoll_wait_sq(ctx);
11603 if (ret)
11604 goto out;
11605 }
11606 ret = to_submit;
11607 } else if (to_submit) {
11608 ret = io_uring_add_tctx_node(ctx);
11609 if (unlikely(ret))
11610 goto out;
11611
11612 mutex_lock(&ctx->uring_lock);
11613 ret = io_submit_sqes(ctx, to_submit);
11614 if (ret != to_submit) {
11615 mutex_unlock(&ctx->uring_lock);
11616 goto out;
11617 }
11618 if ((flags & IORING_ENTER_GETEVENTS) && ctx->syscall_iopoll)
11619 goto iopoll_locked;
11620 mutex_unlock(&ctx->uring_lock);
11621 }
11622 if (flags & IORING_ENTER_GETEVENTS) {
11623 int ret2;
11624 if (ctx->syscall_iopoll) {
11625 /*
11626 * We disallow the app entering submit/complete with
11627 * polling, but we still need to lock the ring to
11628 * prevent racing with polled issue that got punted to
11629 * a workqueue.
11630 */
11631 mutex_lock(&ctx->uring_lock);
11632 iopoll_locked:
11633 ret2 = io_validate_ext_arg(flags, argp, argsz);
11634 if (likely(!ret2)) {
11635 min_complete = min(min_complete,
11636 ctx->cq_entries);
11637 ret2 = io_iopoll_check(ctx, min_complete);
11638 }
11639 mutex_unlock(&ctx->uring_lock);
11640 } else {
11641 const sigset_t __user *sig;
11642 struct __kernel_timespec __user *ts;
11643
11644 ret2 = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
11645 if (likely(!ret2)) {
11646 min_complete = min(min_complete,
11647 ctx->cq_entries);
11648 ret2 = io_cqring_wait(ctx, min_complete, sig,
11649 argsz, ts);
11650 }
11651 }
11652
11653 if (!ret) {
11654 ret = ret2;
11655
11656 /*
11657 * EBADR indicates that one or more CQE were dropped.
11658 * Once the user has been informed we can clear the bit
11659 * as they are obviously ok with those drops.
11660 */
11661 if (unlikely(ret2 == -EBADR))
11662 clear_bit(IO_CHECK_CQ_DROPPED_BIT,
11663 &ctx->check_cq);
11664 }
11665 }
11666
11667 out:
11668 percpu_ref_put(&ctx->refs);
11669 out_fput:
11670 fdput(f);
11671 return ret;
11672 }
11673
11674 #ifdef CONFIG_PROC_FS
io_uring_show_cred(struct seq_file * m,unsigned int id,const struct cred * cred)11675 static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
11676 const struct cred *cred)
11677 {
11678 struct user_namespace *uns = seq_user_ns(m);
11679 struct group_info *gi;
11680 kernel_cap_t cap;
11681 unsigned __capi;
11682 int g;
11683
11684 seq_printf(m, "%5d\n", id);
11685 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
11686 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
11687 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
11688 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
11689 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
11690 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
11691 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
11692 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
11693 seq_puts(m, "\n\tGroups:\t");
11694 gi = cred->group_info;
11695 for (g = 0; g < gi->ngroups; g++) {
11696 seq_put_decimal_ull(m, g ? " " : "",
11697 from_kgid_munged(uns, gi->gid[g]));
11698 }
11699 seq_puts(m, "\n\tCapEff:\t");
11700 cap = cred->cap_effective;
11701 CAP_FOR_EACH_U32(__capi)
11702 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
11703 seq_putc(m, '\n');
11704 return 0;
11705 }
11706
__io_uring_show_fdinfo(struct io_ring_ctx * ctx,struct seq_file * m)11707 static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
11708 struct seq_file *m)
11709 {
11710 struct io_sq_data *sq = NULL;
11711 struct io_overflow_cqe *ocqe;
11712 struct io_rings *r = ctx->rings;
11713 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
11714 unsigned int sq_head = READ_ONCE(r->sq.head);
11715 unsigned int sq_tail = READ_ONCE(r->sq.tail);
11716 unsigned int cq_head = READ_ONCE(r->cq.head);
11717 unsigned int cq_tail = READ_ONCE(r->cq.tail);
11718 unsigned int cq_shift = 0;
11719 unsigned int sq_entries, cq_entries;
11720 bool has_lock;
11721 bool is_cqe32 = (ctx->flags & IORING_SETUP_CQE32);
11722 unsigned int i;
11723
11724 if (is_cqe32)
11725 cq_shift = 1;
11726
11727 /*
11728 * we may get imprecise sqe and cqe info if uring is actively running
11729 * since we get cached_sq_head and cached_cq_tail without uring_lock
11730 * and sq_tail and cq_head are changed by userspace. But it's ok since
11731 * we usually use these info when it is stuck.
11732 */
11733 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
11734 seq_printf(m, "SqHead:\t%u\n", sq_head);
11735 seq_printf(m, "SqTail:\t%u\n", sq_tail);
11736 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
11737 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
11738 seq_printf(m, "CqHead:\t%u\n", cq_head);
11739 seq_printf(m, "CqTail:\t%u\n", cq_tail);
11740 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
11741 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
11742 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
11743 for (i = 0; i < sq_entries; i++) {
11744 unsigned int entry = i + sq_head;
11745 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
11746 struct io_uring_sqe *sqe;
11747
11748 if (sq_idx > sq_mask)
11749 continue;
11750 sqe = &ctx->sq_sqes[sq_idx];
11751 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
11752 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
11753 sqe->user_data);
11754 }
11755 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
11756 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
11757 for (i = 0; i < cq_entries; i++) {
11758 unsigned int entry = i + cq_head;
11759 struct io_uring_cqe *cqe = &r->cqes[(entry & cq_mask) << cq_shift];
11760
11761 if (!is_cqe32) {
11762 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
11763 entry & cq_mask, cqe->user_data, cqe->res,
11764 cqe->flags);
11765 } else {
11766 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x, "
11767 "extra1:%llu, extra2:%llu\n",
11768 entry & cq_mask, cqe->user_data, cqe->res,
11769 cqe->flags, cqe->big_cqe[0], cqe->big_cqe[1]);
11770 }
11771 }
11772
11773 /*
11774 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
11775 * since fdinfo case grabs it in the opposite direction of normal use
11776 * cases. If we fail to get the lock, we just don't iterate any
11777 * structures that could be going away outside the io_uring mutex.
11778 */
11779 has_lock = mutex_trylock(&ctx->uring_lock);
11780
11781 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
11782 sq = ctx->sq_data;
11783 if (!sq->thread)
11784 sq = NULL;
11785 }
11786
11787 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
11788 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
11789 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
11790 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
11791 struct file *f = io_file_from_index(ctx, i);
11792
11793 if (f)
11794 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
11795 else
11796 seq_printf(m, "%5u: <none>\n", i);
11797 }
11798 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
11799 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
11800 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
11801 unsigned int len = buf->ubuf_end - buf->ubuf;
11802
11803 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
11804 }
11805 if (has_lock && !xa_empty(&ctx->personalities)) {
11806 unsigned long index;
11807 const struct cred *cred;
11808
11809 seq_printf(m, "Personalities:\n");
11810 xa_for_each(&ctx->personalities, index, cred)
11811 io_uring_show_cred(m, index, cred);
11812 }
11813 if (has_lock)
11814 mutex_unlock(&ctx->uring_lock);
11815
11816 seq_puts(m, "PollList:\n");
11817 spin_lock(&ctx->completion_lock);
11818 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
11819 struct hlist_head *list = &ctx->cancel_hash[i];
11820 struct io_kiocb *req;
11821
11822 hlist_for_each_entry(req, list, hash_node)
11823 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
11824 task_work_pending(req->task));
11825 }
11826
11827 seq_puts(m, "CqOverflowList:\n");
11828 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
11829 struct io_uring_cqe *cqe = &ocqe->cqe;
11830
11831 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
11832 cqe->user_data, cqe->res, cqe->flags);
11833
11834 }
11835
11836 spin_unlock(&ctx->completion_lock);
11837 }
11838
io_uring_show_fdinfo(struct seq_file * m,struct file * f)11839 static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
11840 {
11841 struct io_ring_ctx *ctx = f->private_data;
11842
11843 if (percpu_ref_tryget(&ctx->refs)) {
11844 __io_uring_show_fdinfo(ctx, m);
11845 percpu_ref_put(&ctx->refs);
11846 }
11847 }
11848 #endif
11849
11850 static const struct file_operations io_uring_fops = {
11851 .release = io_uring_release,
11852 .mmap = io_uring_mmap,
11853 #ifndef CONFIG_MMU
11854 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
11855 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
11856 #endif
11857 .poll = io_uring_poll,
11858 #ifdef CONFIG_PROC_FS
11859 .show_fdinfo = io_uring_show_fdinfo,
11860 #endif
11861 };
11862
io_allocate_scq_urings(struct io_ring_ctx * ctx,struct io_uring_params * p)11863 static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
11864 struct io_uring_params *p)
11865 {
11866 struct io_rings *rings;
11867 size_t size, sq_array_offset;
11868
11869 /* make sure these are sane, as we already accounted them */
11870 ctx->sq_entries = p->sq_entries;
11871 ctx->cq_entries = p->cq_entries;
11872
11873 size = rings_size(ctx, p->sq_entries, p->cq_entries, &sq_array_offset);
11874 if (size == SIZE_MAX)
11875 return -EOVERFLOW;
11876
11877 rings = io_mem_alloc(size);
11878 if (!rings)
11879 return -ENOMEM;
11880
11881 ctx->rings = rings;
11882 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
11883 rings->sq_ring_mask = p->sq_entries - 1;
11884 rings->cq_ring_mask = p->cq_entries - 1;
11885 rings->sq_ring_entries = p->sq_entries;
11886 rings->cq_ring_entries = p->cq_entries;
11887
11888 if (p->flags & IORING_SETUP_SQE128)
11889 size = array_size(2 * sizeof(struct io_uring_sqe), p->sq_entries);
11890 else
11891 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
11892 if (size == SIZE_MAX) {
11893 io_mem_free(ctx->rings);
11894 ctx->rings = NULL;
11895 return -EOVERFLOW;
11896 }
11897
11898 ctx->sq_sqes = io_mem_alloc(size);
11899 if (!ctx->sq_sqes) {
11900 io_mem_free(ctx->rings);
11901 ctx->rings = NULL;
11902 return -ENOMEM;
11903 }
11904
11905 return 0;
11906 }
11907
io_uring_install_fd(struct io_ring_ctx * ctx,struct file * file)11908 static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
11909 {
11910 int ret, fd;
11911
11912 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
11913 if (fd < 0)
11914 return fd;
11915
11916 ret = io_uring_add_tctx_node(ctx);
11917 if (ret) {
11918 put_unused_fd(fd);
11919 return ret;
11920 }
11921 fd_install(fd, file);
11922 return fd;
11923 }
11924
11925 /*
11926 * Allocate an anonymous fd, this is what constitutes the application
11927 * visible backing of an io_uring instance. The application mmaps this
11928 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
11929 * we have to tie this fd to a socket for file garbage collection purposes.
11930 */
io_uring_get_file(struct io_ring_ctx * ctx)11931 static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
11932 {
11933 struct file *file;
11934 #if defined(CONFIG_UNIX)
11935 int ret;
11936
11937 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
11938 &ctx->ring_sock);
11939 if (ret)
11940 return ERR_PTR(ret);
11941 #endif
11942
11943 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
11944 O_RDWR | O_CLOEXEC, NULL);
11945 #if defined(CONFIG_UNIX)
11946 if (IS_ERR(file)) {
11947 sock_release(ctx->ring_sock);
11948 ctx->ring_sock = NULL;
11949 } else {
11950 ctx->ring_sock->file = file;
11951 }
11952 #endif
11953 return file;
11954 }
11955
io_uring_create(unsigned entries,struct io_uring_params * p,struct io_uring_params __user * params)11956 static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
11957 struct io_uring_params __user *params)
11958 {
11959 struct io_ring_ctx *ctx;
11960 struct file *file;
11961 int ret;
11962
11963 if (!entries)
11964 return -EINVAL;
11965 if (entries > IORING_MAX_ENTRIES) {
11966 if (!(p->flags & IORING_SETUP_CLAMP))
11967 return -EINVAL;
11968 entries = IORING_MAX_ENTRIES;
11969 }
11970
11971 /*
11972 * Use twice as many entries for the CQ ring. It's possible for the
11973 * application to drive a higher depth than the size of the SQ ring,
11974 * since the sqes are only used at submission time. This allows for
11975 * some flexibility in overcommitting a bit. If the application has
11976 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
11977 * of CQ ring entries manually.
11978 */
11979 p->sq_entries = roundup_pow_of_two(entries);
11980 if (p->flags & IORING_SETUP_CQSIZE) {
11981 /*
11982 * If IORING_SETUP_CQSIZE is set, we do the same roundup
11983 * to a power-of-two, if it isn't already. We do NOT impose
11984 * any cq vs sq ring sizing.
11985 */
11986 if (!p->cq_entries)
11987 return -EINVAL;
11988 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
11989 if (!(p->flags & IORING_SETUP_CLAMP))
11990 return -EINVAL;
11991 p->cq_entries = IORING_MAX_CQ_ENTRIES;
11992 }
11993 p->cq_entries = roundup_pow_of_two(p->cq_entries);
11994 if (p->cq_entries < p->sq_entries)
11995 return -EINVAL;
11996 } else {
11997 p->cq_entries = 2 * p->sq_entries;
11998 }
11999
12000 ctx = io_ring_ctx_alloc(p);
12001 if (!ctx)
12002 return -ENOMEM;
12003
12004 /*
12005 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
12006 * space applications don't need to do io completion events
12007 * polling again, they can rely on io_sq_thread to do polling
12008 * work, which can reduce cpu usage and uring_lock contention.
12009 */
12010 if (ctx->flags & IORING_SETUP_IOPOLL &&
12011 !(ctx->flags & IORING_SETUP_SQPOLL))
12012 ctx->syscall_iopoll = 1;
12013
12014 ctx->compat = in_compat_syscall();
12015 if (!capable(CAP_IPC_LOCK))
12016 ctx->user = get_uid(current_user());
12017
12018 /*
12019 * For SQPOLL, we just need a wakeup, always. For !SQPOLL, if
12020 * COOP_TASKRUN is set, then IPIs are never needed by the app.
12021 */
12022 ret = -EINVAL;
12023 if (ctx->flags & IORING_SETUP_SQPOLL) {
12024 /* IPI related flags don't make sense with SQPOLL */
12025 if (ctx->flags & (IORING_SETUP_COOP_TASKRUN |
12026 IORING_SETUP_TASKRUN_FLAG))
12027 goto err;
12028 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12029 } else if (ctx->flags & IORING_SETUP_COOP_TASKRUN) {
12030 ctx->notify_method = TWA_SIGNAL_NO_IPI;
12031 } else {
12032 if (ctx->flags & IORING_SETUP_TASKRUN_FLAG)
12033 goto err;
12034 ctx->notify_method = TWA_SIGNAL;
12035 }
12036
12037 /*
12038 * This is just grabbed for accounting purposes. When a process exits,
12039 * the mm is exited and dropped before the files, hence we need to hang
12040 * on to this mm purely for the purposes of being able to unaccount
12041 * memory (locked/pinned vm). It's not used for anything else.
12042 */
12043 mmgrab(current->mm);
12044 ctx->mm_account = current->mm;
12045
12046 ret = io_allocate_scq_urings(ctx, p);
12047 if (ret)
12048 goto err;
12049
12050 ret = io_sq_offload_create(ctx, p);
12051 if (ret)
12052 goto err;
12053 /* always set a rsrc node */
12054 ret = io_rsrc_node_switch_start(ctx);
12055 if (ret)
12056 goto err;
12057 io_rsrc_node_switch(ctx, NULL);
12058
12059 memset(&p->sq_off, 0, sizeof(p->sq_off));
12060 p->sq_off.head = offsetof(struct io_rings, sq.head);
12061 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
12062 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
12063 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
12064 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
12065 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
12066 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
12067
12068 memset(&p->cq_off, 0, sizeof(p->cq_off));
12069 p->cq_off.head = offsetof(struct io_rings, cq.head);
12070 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
12071 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
12072 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
12073 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
12074 p->cq_off.cqes = offsetof(struct io_rings, cqes);
12075 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
12076
12077 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
12078 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
12079 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
12080 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
12081 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
12082 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP |
12083 IORING_FEAT_LINKED_FILE;
12084
12085 if (copy_to_user(params, p, sizeof(*p))) {
12086 ret = -EFAULT;
12087 goto err;
12088 }
12089
12090 file = io_uring_get_file(ctx);
12091 if (IS_ERR(file)) {
12092 ret = PTR_ERR(file);
12093 goto err;
12094 }
12095
12096 /*
12097 * Install ring fd as the very last thing, so we don't risk someone
12098 * having closed it before we finish setup
12099 */
12100 ret = io_uring_install_fd(ctx, file);
12101 if (ret < 0) {
12102 /* fput will clean it up */
12103 fput(file);
12104 return ret;
12105 }
12106
12107 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
12108 return ret;
12109 err:
12110 io_ring_ctx_wait_and_kill(ctx);
12111 return ret;
12112 }
12113
12114 /*
12115 * Sets up an aio uring context, and returns the fd. Applications asks for a
12116 * ring size, we return the actual sq/cq ring sizes (among other things) in the
12117 * params structure passed in.
12118 */
io_uring_setup(u32 entries,struct io_uring_params __user * params)12119 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
12120 {
12121 struct io_uring_params p;
12122 int i;
12123
12124 if (copy_from_user(&p, params, sizeof(p)))
12125 return -EFAULT;
12126 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
12127 if (p.resv[i])
12128 return -EINVAL;
12129 }
12130
12131 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
12132 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
12133 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
12134 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL |
12135 IORING_SETUP_COOP_TASKRUN | IORING_SETUP_TASKRUN_FLAG |
12136 IORING_SETUP_SQE128 | IORING_SETUP_CQE32))
12137 return -EINVAL;
12138
12139 return io_uring_create(entries, &p, params);
12140 }
12141
SYSCALL_DEFINE2(io_uring_setup,u32,entries,struct io_uring_params __user *,params)12142 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
12143 struct io_uring_params __user *, params)
12144 {
12145 return io_uring_setup(entries, params);
12146 }
12147
io_probe(struct io_ring_ctx * ctx,void __user * arg,unsigned nr_args)12148 static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
12149 unsigned nr_args)
12150 {
12151 struct io_uring_probe *p;
12152 size_t size;
12153 int i, ret;
12154
12155 size = struct_size(p, ops, nr_args);
12156 if (size == SIZE_MAX)
12157 return -EOVERFLOW;
12158 p = kzalloc(size, GFP_KERNEL);
12159 if (!p)
12160 return -ENOMEM;
12161
12162 ret = -EFAULT;
12163 if (copy_from_user(p, arg, size))
12164 goto out;
12165 ret = -EINVAL;
12166 if (memchr_inv(p, 0, size))
12167 goto out;
12168
12169 p->last_op = IORING_OP_LAST - 1;
12170 if (nr_args > IORING_OP_LAST)
12171 nr_args = IORING_OP_LAST;
12172
12173 for (i = 0; i < nr_args; i++) {
12174 p->ops[i].op = i;
12175 if (!io_op_defs[i].not_supported)
12176 p->ops[i].flags = IO_URING_OP_SUPPORTED;
12177 }
12178 p->ops_len = i;
12179
12180 ret = 0;
12181 if (copy_to_user(arg, p, size))
12182 ret = -EFAULT;
12183 out:
12184 kfree(p);
12185 return ret;
12186 }
12187
io_register_personality(struct io_ring_ctx * ctx)12188 static int io_register_personality(struct io_ring_ctx *ctx)
12189 {
12190 const struct cred *creds;
12191 u32 id;
12192 int ret;
12193
12194 creds = get_current_cred();
12195
12196 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
12197 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
12198 if (ret < 0) {
12199 put_cred(creds);
12200 return ret;
12201 }
12202 return id;
12203 }
12204
io_register_restrictions(struct io_ring_ctx * ctx,void __user * arg,unsigned int nr_args)12205 static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
12206 void __user *arg, unsigned int nr_args)
12207 {
12208 struct io_uring_restriction *res;
12209 size_t size;
12210 int i, ret;
12211
12212 /* Restrictions allowed only if rings started disabled */
12213 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12214 return -EBADFD;
12215
12216 /* We allow only a single restrictions registration */
12217 if (ctx->restrictions.registered)
12218 return -EBUSY;
12219
12220 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
12221 return -EINVAL;
12222
12223 size = array_size(nr_args, sizeof(*res));
12224 if (size == SIZE_MAX)
12225 return -EOVERFLOW;
12226
12227 res = memdup_user(arg, size);
12228 if (IS_ERR(res))
12229 return PTR_ERR(res);
12230
12231 ret = 0;
12232
12233 for (i = 0; i < nr_args; i++) {
12234 switch (res[i].opcode) {
12235 case IORING_RESTRICTION_REGISTER_OP:
12236 if (res[i].register_op >= IORING_REGISTER_LAST) {
12237 ret = -EINVAL;
12238 goto out;
12239 }
12240
12241 __set_bit(res[i].register_op,
12242 ctx->restrictions.register_op);
12243 break;
12244 case IORING_RESTRICTION_SQE_OP:
12245 if (res[i].sqe_op >= IORING_OP_LAST) {
12246 ret = -EINVAL;
12247 goto out;
12248 }
12249
12250 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
12251 break;
12252 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
12253 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
12254 break;
12255 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
12256 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
12257 break;
12258 default:
12259 ret = -EINVAL;
12260 goto out;
12261 }
12262 }
12263
12264 out:
12265 /* Reset all restrictions if an error happened */
12266 if (ret != 0)
12267 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
12268 else
12269 ctx->restrictions.registered = true;
12270
12271 kfree(res);
12272 return ret;
12273 }
12274
io_register_enable_rings(struct io_ring_ctx * ctx)12275 static int io_register_enable_rings(struct io_ring_ctx *ctx)
12276 {
12277 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
12278 return -EBADFD;
12279
12280 if (ctx->restrictions.registered)
12281 ctx->restricted = 1;
12282
12283 ctx->flags &= ~IORING_SETUP_R_DISABLED;
12284 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
12285 wake_up(&ctx->sq_data->wait);
12286 return 0;
12287 }
12288
__io_register_rsrc_update(struct io_ring_ctx * ctx,unsigned type,struct io_uring_rsrc_update2 * up,unsigned nr_args)12289 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
12290 struct io_uring_rsrc_update2 *up,
12291 unsigned nr_args)
12292 {
12293 __u32 tmp;
12294 int err;
12295
12296 if (check_add_overflow(up->offset, nr_args, &tmp))
12297 return -EOVERFLOW;
12298 err = io_rsrc_node_switch_start(ctx);
12299 if (err)
12300 return err;
12301
12302 switch (type) {
12303 case IORING_RSRC_FILE:
12304 return __io_sqe_files_update(ctx, up, nr_args);
12305 case IORING_RSRC_BUFFER:
12306 return __io_sqe_buffers_update(ctx, up, nr_args);
12307 }
12308 return -EINVAL;
12309 }
12310
io_register_files_update(struct io_ring_ctx * ctx,void __user * arg,unsigned nr_args)12311 static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
12312 unsigned nr_args)
12313 {
12314 struct io_uring_rsrc_update2 up;
12315
12316 if (!nr_args)
12317 return -EINVAL;
12318 memset(&up, 0, sizeof(up));
12319 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
12320 return -EFAULT;
12321 if (up.resv || up.resv2)
12322 return -EINVAL;
12323 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
12324 }
12325
io_register_rsrc_update(struct io_ring_ctx * ctx,void __user * arg,unsigned size,unsigned type)12326 static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
12327 unsigned size, unsigned type)
12328 {
12329 struct io_uring_rsrc_update2 up;
12330
12331 if (size != sizeof(up))
12332 return -EINVAL;
12333 if (copy_from_user(&up, arg, sizeof(up)))
12334 return -EFAULT;
12335 if (!up.nr || up.resv || up.resv2)
12336 return -EINVAL;
12337 return __io_register_rsrc_update(ctx, type, &up, up.nr);
12338 }
12339
io_register_rsrc(struct io_ring_ctx * ctx,void __user * arg,unsigned int size,unsigned int type)12340 static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
12341 unsigned int size, unsigned int type)
12342 {
12343 struct io_uring_rsrc_register rr;
12344
12345 /* keep it extendible */
12346 if (size != sizeof(rr))
12347 return -EINVAL;
12348
12349 memset(&rr, 0, sizeof(rr));
12350 if (copy_from_user(&rr, arg, size))
12351 return -EFAULT;
12352 if (!rr.nr || rr.resv2)
12353 return -EINVAL;
12354 if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
12355 return -EINVAL;
12356
12357 switch (type) {
12358 case IORING_RSRC_FILE:
12359 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12360 break;
12361 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
12362 rr.nr, u64_to_user_ptr(rr.tags));
12363 case IORING_RSRC_BUFFER:
12364 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
12365 break;
12366 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
12367 rr.nr, u64_to_user_ptr(rr.tags));
12368 }
12369 return -EINVAL;
12370 }
12371
io_register_iowq_aff(struct io_ring_ctx * ctx,void __user * arg,unsigned len)12372 static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
12373 void __user *arg, unsigned len)
12374 {
12375 struct io_uring_task *tctx = current->io_uring;
12376 cpumask_var_t new_mask;
12377 int ret;
12378
12379 if (!tctx || !tctx->io_wq)
12380 return -EINVAL;
12381
12382 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
12383 return -ENOMEM;
12384
12385 cpumask_clear(new_mask);
12386 if (len > cpumask_size())
12387 len = cpumask_size();
12388
12389 if (in_compat_syscall()) {
12390 ret = compat_get_bitmap(cpumask_bits(new_mask),
12391 (const compat_ulong_t __user *)arg,
12392 len * 8 /* CHAR_BIT */);
12393 } else {
12394 ret = copy_from_user(new_mask, arg, len);
12395 }
12396
12397 if (ret) {
12398 free_cpumask_var(new_mask);
12399 return -EFAULT;
12400 }
12401
12402 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
12403 free_cpumask_var(new_mask);
12404 return ret;
12405 }
12406
io_unregister_iowq_aff(struct io_ring_ctx * ctx)12407 static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
12408 {
12409 struct io_uring_task *tctx = current->io_uring;
12410
12411 if (!tctx || !tctx->io_wq)
12412 return -EINVAL;
12413
12414 return io_wq_cpu_affinity(tctx->io_wq, NULL);
12415 }
12416
io_register_iowq_max_workers(struct io_ring_ctx * ctx,void __user * arg)12417 static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
12418 void __user *arg)
12419 __must_hold(&ctx->uring_lock)
12420 {
12421 struct io_tctx_node *node;
12422 struct io_uring_task *tctx = NULL;
12423 struct io_sq_data *sqd = NULL;
12424 __u32 new_count[2];
12425 int i, ret;
12426
12427 if (copy_from_user(new_count, arg, sizeof(new_count)))
12428 return -EFAULT;
12429 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12430 if (new_count[i] > INT_MAX)
12431 return -EINVAL;
12432
12433 if (ctx->flags & IORING_SETUP_SQPOLL) {
12434 sqd = ctx->sq_data;
12435 if (sqd) {
12436 /*
12437 * Observe the correct sqd->lock -> ctx->uring_lock
12438 * ordering. Fine to drop uring_lock here, we hold
12439 * a ref to the ctx.
12440 */
12441 refcount_inc(&sqd->refs);
12442 mutex_unlock(&ctx->uring_lock);
12443 mutex_lock(&sqd->lock);
12444 mutex_lock(&ctx->uring_lock);
12445 if (sqd->thread)
12446 tctx = sqd->thread->io_uring;
12447 }
12448 } else {
12449 tctx = current->io_uring;
12450 }
12451
12452 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
12453
12454 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12455 if (new_count[i])
12456 ctx->iowq_limits[i] = new_count[i];
12457 ctx->iowq_limits_set = true;
12458
12459 if (tctx && tctx->io_wq) {
12460 ret = io_wq_max_workers(tctx->io_wq, new_count);
12461 if (ret)
12462 goto err;
12463 } else {
12464 memset(new_count, 0, sizeof(new_count));
12465 }
12466
12467 if (sqd) {
12468 mutex_unlock(&sqd->lock);
12469 io_put_sq_data(sqd);
12470 }
12471
12472 if (copy_to_user(arg, new_count, sizeof(new_count)))
12473 return -EFAULT;
12474
12475 /* that's it for SQPOLL, only the SQPOLL task creates requests */
12476 if (sqd)
12477 return 0;
12478
12479 /* now propagate the restriction to all registered users */
12480 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
12481 struct io_uring_task *tctx = node->task->io_uring;
12482
12483 if (WARN_ON_ONCE(!tctx->io_wq))
12484 continue;
12485
12486 for (i = 0; i < ARRAY_SIZE(new_count); i++)
12487 new_count[i] = ctx->iowq_limits[i];
12488 /* ignore errors, it always returns zero anyway */
12489 (void)io_wq_max_workers(tctx->io_wq, new_count);
12490 }
12491 return 0;
12492 err:
12493 if (sqd) {
12494 mutex_unlock(&sqd->lock);
12495 io_put_sq_data(sqd);
12496 }
12497 return ret;
12498 }
12499
io_register_pbuf_ring(struct io_ring_ctx * ctx,void __user * arg)12500 static int io_register_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12501 {
12502 struct io_uring_buf_ring *br;
12503 struct io_uring_buf_reg reg;
12504 struct io_buffer_list *bl, *free_bl = NULL;
12505 struct page **pages;
12506 int nr_pages;
12507
12508 if (copy_from_user(®, arg, sizeof(reg)))
12509 return -EFAULT;
12510
12511 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12512 return -EINVAL;
12513 if (!reg.ring_addr)
12514 return -EFAULT;
12515 if (reg.ring_addr & ~PAGE_MASK)
12516 return -EINVAL;
12517 if (!is_power_of_2(reg.ring_entries))
12518 return -EINVAL;
12519
12520 /* cannot disambiguate full vs empty due to head/tail size */
12521 if (reg.ring_entries >= 65536)
12522 return -EINVAL;
12523
12524 if (unlikely(reg.bgid < BGID_ARRAY && !ctx->io_bl)) {
12525 int ret = io_init_bl_list(ctx);
12526 if (ret)
12527 return ret;
12528 }
12529
12530 bl = io_buffer_get_list(ctx, reg.bgid);
12531 if (bl) {
12532 /* if mapped buffer ring OR classic exists, don't allow */
12533 if (bl->buf_nr_pages || !list_empty(&bl->buf_list))
12534 return -EEXIST;
12535 } else {
12536 free_bl = bl = kzalloc(sizeof(*bl), GFP_KERNEL);
12537 if (!bl)
12538 return -ENOMEM;
12539 }
12540
12541 pages = io_pin_pages(reg.ring_addr,
12542 struct_size(br, bufs, reg.ring_entries),
12543 &nr_pages);
12544 if (IS_ERR(pages)) {
12545 kfree(free_bl);
12546 return PTR_ERR(pages);
12547 }
12548
12549 br = page_address(pages[0]);
12550 bl->buf_pages = pages;
12551 bl->buf_nr_pages = nr_pages;
12552 bl->nr_entries = reg.ring_entries;
12553 bl->buf_ring = br;
12554 bl->mask = reg.ring_entries - 1;
12555 io_buffer_add_list(ctx, bl, reg.bgid);
12556 return 0;
12557 }
12558
io_unregister_pbuf_ring(struct io_ring_ctx * ctx,void __user * arg)12559 static int io_unregister_pbuf_ring(struct io_ring_ctx *ctx, void __user *arg)
12560 {
12561 struct io_uring_buf_reg reg;
12562 struct io_buffer_list *bl;
12563
12564 if (copy_from_user(®, arg, sizeof(reg)))
12565 return -EFAULT;
12566 if (reg.pad || reg.resv[0] || reg.resv[1] || reg.resv[2])
12567 return -EINVAL;
12568
12569 bl = io_buffer_get_list(ctx, reg.bgid);
12570 if (!bl)
12571 return -ENOENT;
12572 if (!bl->buf_nr_pages)
12573 return -EINVAL;
12574
12575 __io_remove_buffers(ctx, bl, -1U);
12576 if (bl->bgid >= BGID_ARRAY) {
12577 xa_erase(&ctx->io_bl_xa, bl->bgid);
12578 kfree(bl);
12579 }
12580 return 0;
12581 }
12582
__io_uring_register(struct io_ring_ctx * ctx,unsigned opcode,void __user * arg,unsigned nr_args)12583 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
12584 void __user *arg, unsigned nr_args)
12585 __releases(ctx->uring_lock)
12586 __acquires(ctx->uring_lock)
12587 {
12588 int ret;
12589
12590 /*
12591 * We're inside the ring mutex, if the ref is already dying, then
12592 * someone else killed the ctx or is already going through
12593 * io_uring_register().
12594 */
12595 if (percpu_ref_is_dying(&ctx->refs))
12596 return -ENXIO;
12597
12598 if (ctx->restricted) {
12599 if (opcode >= IORING_REGISTER_LAST)
12600 return -EINVAL;
12601 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
12602 if (!test_bit(opcode, ctx->restrictions.register_op))
12603 return -EACCES;
12604 }
12605
12606 switch (opcode) {
12607 case IORING_REGISTER_BUFFERS:
12608 ret = -EFAULT;
12609 if (!arg)
12610 break;
12611 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
12612 break;
12613 case IORING_UNREGISTER_BUFFERS:
12614 ret = -EINVAL;
12615 if (arg || nr_args)
12616 break;
12617 ret = io_sqe_buffers_unregister(ctx);
12618 break;
12619 case IORING_REGISTER_FILES:
12620 ret = -EFAULT;
12621 if (!arg)
12622 break;
12623 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
12624 break;
12625 case IORING_UNREGISTER_FILES:
12626 ret = -EINVAL;
12627 if (arg || nr_args)
12628 break;
12629 ret = io_sqe_files_unregister(ctx);
12630 break;
12631 case IORING_REGISTER_FILES_UPDATE:
12632 ret = io_register_files_update(ctx, arg, nr_args);
12633 break;
12634 case IORING_REGISTER_EVENTFD:
12635 ret = -EINVAL;
12636 if (nr_args != 1)
12637 break;
12638 ret = io_eventfd_register(ctx, arg, 0);
12639 break;
12640 case IORING_REGISTER_EVENTFD_ASYNC:
12641 ret = -EINVAL;
12642 if (nr_args != 1)
12643 break;
12644 ret = io_eventfd_register(ctx, arg, 1);
12645 break;
12646 case IORING_UNREGISTER_EVENTFD:
12647 ret = -EINVAL;
12648 if (arg || nr_args)
12649 break;
12650 ret = io_eventfd_unregister(ctx);
12651 break;
12652 case IORING_REGISTER_PROBE:
12653 ret = -EINVAL;
12654 if (!arg || nr_args > 256)
12655 break;
12656 ret = io_probe(ctx, arg, nr_args);
12657 break;
12658 case IORING_REGISTER_PERSONALITY:
12659 ret = -EINVAL;
12660 if (arg || nr_args)
12661 break;
12662 ret = io_register_personality(ctx);
12663 break;
12664 case IORING_UNREGISTER_PERSONALITY:
12665 ret = -EINVAL;
12666 if (arg)
12667 break;
12668 ret = io_unregister_personality(ctx, nr_args);
12669 break;
12670 case IORING_REGISTER_ENABLE_RINGS:
12671 ret = -EINVAL;
12672 if (arg || nr_args)
12673 break;
12674 ret = io_register_enable_rings(ctx);
12675 break;
12676 case IORING_REGISTER_RESTRICTIONS:
12677 ret = io_register_restrictions(ctx, arg, nr_args);
12678 break;
12679 case IORING_REGISTER_FILES2:
12680 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
12681 break;
12682 case IORING_REGISTER_FILES_UPDATE2:
12683 ret = io_register_rsrc_update(ctx, arg, nr_args,
12684 IORING_RSRC_FILE);
12685 break;
12686 case IORING_REGISTER_BUFFERS2:
12687 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
12688 break;
12689 case IORING_REGISTER_BUFFERS_UPDATE:
12690 ret = io_register_rsrc_update(ctx, arg, nr_args,
12691 IORING_RSRC_BUFFER);
12692 break;
12693 case IORING_REGISTER_IOWQ_AFF:
12694 ret = -EINVAL;
12695 if (!arg || !nr_args)
12696 break;
12697 ret = io_register_iowq_aff(ctx, arg, nr_args);
12698 break;
12699 case IORING_UNREGISTER_IOWQ_AFF:
12700 ret = -EINVAL;
12701 if (arg || nr_args)
12702 break;
12703 ret = io_unregister_iowq_aff(ctx);
12704 break;
12705 case IORING_REGISTER_IOWQ_MAX_WORKERS:
12706 ret = -EINVAL;
12707 if (!arg || nr_args != 2)
12708 break;
12709 ret = io_register_iowq_max_workers(ctx, arg);
12710 break;
12711 case IORING_REGISTER_RING_FDS:
12712 ret = io_ringfd_register(ctx, arg, nr_args);
12713 break;
12714 case IORING_UNREGISTER_RING_FDS:
12715 ret = io_ringfd_unregister(ctx, arg, nr_args);
12716 break;
12717 case IORING_REGISTER_PBUF_RING:
12718 ret = -EINVAL;
12719 if (!arg || nr_args != 1)
12720 break;
12721 ret = io_register_pbuf_ring(ctx, arg);
12722 break;
12723 case IORING_UNREGISTER_PBUF_RING:
12724 ret = -EINVAL;
12725 if (!arg || nr_args != 1)
12726 break;
12727 ret = io_unregister_pbuf_ring(ctx, arg);
12728 break;
12729 default:
12730 ret = -EINVAL;
12731 break;
12732 }
12733
12734 return ret;
12735 }
12736
SYSCALL_DEFINE4(io_uring_register,unsigned int,fd,unsigned int,opcode,void __user *,arg,unsigned int,nr_args)12737 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
12738 void __user *, arg, unsigned int, nr_args)
12739 {
12740 struct io_ring_ctx *ctx;
12741 long ret = -EBADF;
12742 struct fd f;
12743
12744 f = fdget(fd);
12745 if (!f.file)
12746 return -EBADF;
12747
12748 ret = -EOPNOTSUPP;
12749 if (f.file->f_op != &io_uring_fops)
12750 goto out_fput;
12751
12752 ctx = f.file->private_data;
12753
12754 io_run_task_work();
12755
12756 mutex_lock(&ctx->uring_lock);
12757 ret = __io_uring_register(ctx, opcode, arg, nr_args);
12758 mutex_unlock(&ctx->uring_lock);
12759 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
12760 out_fput:
12761 fdput(f);
12762 return ret;
12763 }
12764
io_no_issue(struct io_kiocb * req,unsigned int issue_flags)12765 static int io_no_issue(struct io_kiocb *req, unsigned int issue_flags)
12766 {
12767 WARN_ON_ONCE(1);
12768 return -ECANCELED;
12769 }
12770
12771 static const struct io_op_def io_op_defs[] = {
12772 [IORING_OP_NOP] = {
12773 .audit_skip = 1,
12774 .iopoll = 1,
12775 .prep = io_nop_prep,
12776 .issue = io_nop,
12777 },
12778 [IORING_OP_READV] = {
12779 .needs_file = 1,
12780 .unbound_nonreg_file = 1,
12781 .pollin = 1,
12782 .buffer_select = 1,
12783 .needs_async_setup = 1,
12784 .plug = 1,
12785 .audit_skip = 1,
12786 .ioprio = 1,
12787 .iopoll = 1,
12788 .async_size = sizeof(struct io_async_rw),
12789 .prep = io_prep_rw,
12790 .issue = io_read,
12791 },
12792 [IORING_OP_WRITEV] = {
12793 .needs_file = 1,
12794 .hash_reg_file = 1,
12795 .unbound_nonreg_file = 1,
12796 .pollout = 1,
12797 .needs_async_setup = 1,
12798 .plug = 1,
12799 .audit_skip = 1,
12800 .ioprio = 1,
12801 .iopoll = 1,
12802 .async_size = sizeof(struct io_async_rw),
12803 .prep = io_prep_rw,
12804 .issue = io_write,
12805 },
12806 [IORING_OP_FSYNC] = {
12807 .needs_file = 1,
12808 .audit_skip = 1,
12809 .prep = io_fsync_prep,
12810 .issue = io_fsync,
12811 },
12812 [IORING_OP_READ_FIXED] = {
12813 .needs_file = 1,
12814 .unbound_nonreg_file = 1,
12815 .pollin = 1,
12816 .plug = 1,
12817 .audit_skip = 1,
12818 .ioprio = 1,
12819 .iopoll = 1,
12820 .async_size = sizeof(struct io_async_rw),
12821 .prep = io_prep_rw,
12822 .issue = io_read,
12823 },
12824 [IORING_OP_WRITE_FIXED] = {
12825 .needs_file = 1,
12826 .hash_reg_file = 1,
12827 .unbound_nonreg_file = 1,
12828 .pollout = 1,
12829 .plug = 1,
12830 .audit_skip = 1,
12831 .ioprio = 1,
12832 .iopoll = 1,
12833 .async_size = sizeof(struct io_async_rw),
12834 .prep = io_prep_rw,
12835 .issue = io_write,
12836 },
12837 [IORING_OP_POLL_ADD] = {
12838 .needs_file = 1,
12839 .unbound_nonreg_file = 1,
12840 .audit_skip = 1,
12841 .prep = io_poll_add_prep,
12842 .issue = io_poll_add,
12843 },
12844 [IORING_OP_POLL_REMOVE] = {
12845 .audit_skip = 1,
12846 .prep = io_poll_remove_prep,
12847 .issue = io_poll_remove,
12848 },
12849 [IORING_OP_SYNC_FILE_RANGE] = {
12850 .needs_file = 1,
12851 .audit_skip = 1,
12852 .prep = io_sfr_prep,
12853 .issue = io_sync_file_range,
12854 },
12855 [IORING_OP_SENDMSG] = {
12856 .needs_file = 1,
12857 .unbound_nonreg_file = 1,
12858 .pollout = 1,
12859 .needs_async_setup = 1,
12860 .ioprio = 1,
12861 .async_size = sizeof(struct io_async_msghdr),
12862 .prep = io_sendmsg_prep,
12863 .issue = io_sendmsg,
12864 },
12865 [IORING_OP_RECVMSG] = {
12866 .needs_file = 1,
12867 .unbound_nonreg_file = 1,
12868 .pollin = 1,
12869 .buffer_select = 1,
12870 .needs_async_setup = 1,
12871 .ioprio = 1,
12872 .async_size = sizeof(struct io_async_msghdr),
12873 .prep = io_recvmsg_prep,
12874 .issue = io_recvmsg,
12875 },
12876 [IORING_OP_TIMEOUT] = {
12877 .audit_skip = 1,
12878 .async_size = sizeof(struct io_timeout_data),
12879 .prep = io_timeout_prep,
12880 .issue = io_timeout,
12881 },
12882 [IORING_OP_TIMEOUT_REMOVE] = {
12883 /* used by timeout updates' prep() */
12884 .audit_skip = 1,
12885 .prep = io_timeout_remove_prep,
12886 .issue = io_timeout_remove,
12887 },
12888 [IORING_OP_ACCEPT] = {
12889 .needs_file = 1,
12890 .unbound_nonreg_file = 1,
12891 .pollin = 1,
12892 .poll_exclusive = 1,
12893 .ioprio = 1, /* used for flags */
12894 .prep = io_accept_prep,
12895 .issue = io_accept,
12896 },
12897 [IORING_OP_ASYNC_CANCEL] = {
12898 .audit_skip = 1,
12899 .prep = io_async_cancel_prep,
12900 .issue = io_async_cancel,
12901 },
12902 [IORING_OP_LINK_TIMEOUT] = {
12903 .audit_skip = 1,
12904 .async_size = sizeof(struct io_timeout_data),
12905 .prep = io_link_timeout_prep,
12906 .issue = io_no_issue,
12907 },
12908 [IORING_OP_CONNECT] = {
12909 .needs_file = 1,
12910 .unbound_nonreg_file = 1,
12911 .pollout = 1,
12912 .needs_async_setup = 1,
12913 .async_size = sizeof(struct io_async_connect),
12914 .prep = io_connect_prep,
12915 .issue = io_connect,
12916 },
12917 [IORING_OP_FALLOCATE] = {
12918 .needs_file = 1,
12919 .prep = io_fallocate_prep,
12920 .issue = io_fallocate,
12921 },
12922 [IORING_OP_OPENAT] = {
12923 .prep = io_openat_prep,
12924 .issue = io_openat,
12925 },
12926 [IORING_OP_CLOSE] = {
12927 .prep = io_close_prep,
12928 .issue = io_close,
12929 },
12930 [IORING_OP_FILES_UPDATE] = {
12931 .audit_skip = 1,
12932 .iopoll = 1,
12933 .prep = io_files_update_prep,
12934 .issue = io_files_update,
12935 },
12936 [IORING_OP_STATX] = {
12937 .audit_skip = 1,
12938 .prep = io_statx_prep,
12939 .issue = io_statx,
12940 },
12941 [IORING_OP_READ] = {
12942 .needs_file = 1,
12943 .unbound_nonreg_file = 1,
12944 .pollin = 1,
12945 .buffer_select = 1,
12946 .plug = 1,
12947 .audit_skip = 1,
12948 .ioprio = 1,
12949 .iopoll = 1,
12950 .async_size = sizeof(struct io_async_rw),
12951 .prep = io_prep_rw,
12952 .issue = io_read,
12953 },
12954 [IORING_OP_WRITE] = {
12955 .needs_file = 1,
12956 .hash_reg_file = 1,
12957 .unbound_nonreg_file = 1,
12958 .pollout = 1,
12959 .plug = 1,
12960 .audit_skip = 1,
12961 .ioprio = 1,
12962 .iopoll = 1,
12963 .async_size = sizeof(struct io_async_rw),
12964 .prep = io_prep_rw,
12965 .issue = io_write,
12966 },
12967 [IORING_OP_FADVISE] = {
12968 .needs_file = 1,
12969 .audit_skip = 1,
12970 .prep = io_fadvise_prep,
12971 .issue = io_fadvise,
12972 },
12973 [IORING_OP_MADVISE] = {
12974 .prep = io_madvise_prep,
12975 .issue = io_madvise,
12976 },
12977 [IORING_OP_SEND] = {
12978 .needs_file = 1,
12979 .unbound_nonreg_file = 1,
12980 .pollout = 1,
12981 .audit_skip = 1,
12982 .ioprio = 1,
12983 .prep = io_sendmsg_prep,
12984 .issue = io_send,
12985 },
12986 [IORING_OP_RECV] = {
12987 .needs_file = 1,
12988 .unbound_nonreg_file = 1,
12989 .pollin = 1,
12990 .buffer_select = 1,
12991 .audit_skip = 1,
12992 .ioprio = 1,
12993 .prep = io_recvmsg_prep,
12994 .issue = io_recv,
12995 },
12996 [IORING_OP_OPENAT2] = {
12997 .prep = io_openat2_prep,
12998 .issue = io_openat2,
12999 },
13000 [IORING_OP_EPOLL_CTL] = {
13001 .unbound_nonreg_file = 1,
13002 .audit_skip = 1,
13003 .prep = io_epoll_ctl_prep,
13004 .issue = io_epoll_ctl,
13005 },
13006 [IORING_OP_SPLICE] = {
13007 .needs_file = 1,
13008 .hash_reg_file = 1,
13009 .unbound_nonreg_file = 1,
13010 .audit_skip = 1,
13011 .prep = io_splice_prep,
13012 .issue = io_splice,
13013 },
13014 [IORING_OP_PROVIDE_BUFFERS] = {
13015 .audit_skip = 1,
13016 .iopoll = 1,
13017 .prep = io_provide_buffers_prep,
13018 .issue = io_provide_buffers,
13019 },
13020 [IORING_OP_REMOVE_BUFFERS] = {
13021 .audit_skip = 1,
13022 .iopoll = 1,
13023 .prep = io_remove_buffers_prep,
13024 .issue = io_remove_buffers,
13025 },
13026 [IORING_OP_TEE] = {
13027 .needs_file = 1,
13028 .hash_reg_file = 1,
13029 .unbound_nonreg_file = 1,
13030 .audit_skip = 1,
13031 .prep = io_tee_prep,
13032 .issue = io_tee,
13033 },
13034 [IORING_OP_SHUTDOWN] = {
13035 .needs_file = 1,
13036 .prep = io_shutdown_prep,
13037 .issue = io_shutdown,
13038 },
13039 [IORING_OP_RENAMEAT] = {
13040 .prep = io_renameat_prep,
13041 .issue = io_renameat,
13042 },
13043 [IORING_OP_UNLINKAT] = {
13044 .prep = io_unlinkat_prep,
13045 .issue = io_unlinkat,
13046 },
13047 [IORING_OP_MKDIRAT] = {
13048 .prep = io_mkdirat_prep,
13049 .issue = io_mkdirat,
13050 },
13051 [IORING_OP_SYMLINKAT] = {
13052 .prep = io_symlinkat_prep,
13053 .issue = io_symlinkat,
13054 },
13055 [IORING_OP_LINKAT] = {
13056 .prep = io_linkat_prep,
13057 .issue = io_linkat,
13058 },
13059 [IORING_OP_MSG_RING] = {
13060 .needs_file = 1,
13061 .iopoll = 1,
13062 .prep = io_msg_ring_prep,
13063 .issue = io_msg_ring,
13064 },
13065 [IORING_OP_FSETXATTR] = {
13066 .needs_file = 1,
13067 .prep = io_fsetxattr_prep,
13068 .issue = io_fsetxattr,
13069 },
13070 [IORING_OP_SETXATTR] = {
13071 .prep = io_setxattr_prep,
13072 .issue = io_setxattr,
13073 },
13074 [IORING_OP_FGETXATTR] = {
13075 .needs_file = 1,
13076 .prep = io_fgetxattr_prep,
13077 .issue = io_fgetxattr,
13078 },
13079 [IORING_OP_GETXATTR] = {
13080 .prep = io_getxattr_prep,
13081 .issue = io_getxattr,
13082 },
13083 [IORING_OP_SOCKET] = {
13084 .audit_skip = 1,
13085 .prep = io_socket_prep,
13086 .issue = io_socket,
13087 },
13088 [IORING_OP_URING_CMD] = {
13089 .needs_file = 1,
13090 .plug = 1,
13091 .needs_async_setup = 1,
13092 .async_size = uring_cmd_pdu_size(1),
13093 .prep = io_uring_cmd_prep,
13094 .issue = io_uring_cmd,
13095 },
13096 };
13097
io_uring_init(void)13098 static int __init io_uring_init(void)
13099 {
13100 int i;
13101
13102 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
13103 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
13104 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
13105 } while (0)
13106
13107 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
13108 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
13109 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
13110 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
13111 BUILD_BUG_SQE_ELEM(1, __u8, flags);
13112 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
13113 BUILD_BUG_SQE_ELEM(4, __s32, fd);
13114 BUILD_BUG_SQE_ELEM(8, __u64, off);
13115 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
13116 BUILD_BUG_SQE_ELEM(16, __u64, addr);
13117 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
13118 BUILD_BUG_SQE_ELEM(24, __u32, len);
13119 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
13120 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
13121 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
13122 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
13123 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
13124 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
13125 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
13126 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
13127 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
13128 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
13129 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
13130 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
13131 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
13132 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
13133 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
13134 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
13135 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
13136 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
13137 BUILD_BUG_SQE_ELEM(42, __u16, personality);
13138 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
13139 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
13140 BUILD_BUG_SQE_ELEM(48, __u64, addr3);
13141
13142 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
13143 sizeof(struct io_uring_rsrc_update));
13144 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
13145 sizeof(struct io_uring_rsrc_update2));
13146
13147 /* ->buf_index is u16 */
13148 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
13149 BUILD_BUG_ON(BGID_ARRAY * sizeof(struct io_buffer_list) > PAGE_SIZE);
13150 BUILD_BUG_ON(offsetof(struct io_uring_buf_ring, bufs) != 0);
13151 BUILD_BUG_ON(offsetof(struct io_uring_buf, resv) !=
13152 offsetof(struct io_uring_buf_ring, tail));
13153
13154 /* should fit into one byte */
13155 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
13156 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
13157 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
13158
13159 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
13160 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
13161
13162 BUILD_BUG_ON(sizeof(atomic_t) != sizeof(u32));
13163
13164 BUILD_BUG_ON(sizeof(struct io_uring_cmd) > 64);
13165
13166 for (i = 0; i < ARRAY_SIZE(io_op_defs); i++) {
13167 BUG_ON(!io_op_defs[i].prep);
13168 BUG_ON(!io_op_defs[i].issue);
13169 }
13170
13171 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
13172 SLAB_ACCOUNT);
13173 return 0;
13174 };
13175 __initcall(io_uring_init);
13176