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