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