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