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