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