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