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