io_uring.c revision 89850fce
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
5 *
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
8 *
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqe (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
16 * CQ entries.
17 *
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
23 * head will do).
24 *
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
28 * between.
29 *
30 * Also see the examples in the liburing library:
31 *
32 *	git://git.kernel.dk/liburing
33 *
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
38 *
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
41 */
42#include <linux/kernel.h>
43#include <linux/init.h>
44#include <linux/errno.h>
45#include <linux/syscalls.h>
46#include <linux/compat.h>
47#include <net/compat.h>
48#include <linux/refcount.h>
49#include <linux/uio.h>
50#include <linux/bits.h>
51
52#include <linux/sched/signal.h>
53#include <linux/fs.h>
54#include <linux/file.h>
55#include <linux/fdtable.h>
56#include <linux/mm.h>
57#include <linux/mman.h>
58#include <linux/percpu.h>
59#include <linux/slab.h>
60#include <linux/blkdev.h>
61#include <linux/bvec.h>
62#include <linux/net.h>
63#include <net/sock.h>
64#include <net/af_unix.h>
65#include <net/scm.h>
66#include <linux/anon_inodes.h>
67#include <linux/sched/mm.h>
68#include <linux/uaccess.h>
69#include <linux/nospec.h>
70#include <linux/sizes.h>
71#include <linux/hugetlb.h>
72#include <linux/highmem.h>
73#include <linux/namei.h>
74#include <linux/fsnotify.h>
75#include <linux/fadvise.h>
76#include <linux/eventpoll.h>
77#include <linux/splice.h>
78#include <linux/task_work.h>
79#include <linux/pagemap.h>
80#include <linux/io_uring.h>
81#include <linux/tracehook.h>
82
83#define CREATE_TRACE_POINTS
84#include <trace/events/io_uring.h>
85
86#include <uapi/linux/io_uring.h>
87
88#include "internal.h"
89#include "io-wq.h"
90
91#define IORING_MAX_ENTRIES	32768
92#define IORING_MAX_CQ_ENTRIES	(2 * IORING_MAX_ENTRIES)
93#define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
94
95/* 512 entries per page on 64-bit archs, 64 pages max */
96#define IORING_MAX_FIXED_FILES	(1U << 15)
97#define IORING_MAX_RESTRICTIONS	(IORING_RESTRICTION_LAST + \
98				 IORING_REGISTER_LAST + IORING_OP_LAST)
99
100#define IO_RSRC_TAG_TABLE_SHIFT	9
101#define IO_RSRC_TAG_TABLE_MAX	(1U << IO_RSRC_TAG_TABLE_SHIFT)
102#define IO_RSRC_TAG_TABLE_MASK	(IO_RSRC_TAG_TABLE_MAX - 1)
103
104#define IORING_MAX_REG_BUFFERS	(1U << 14)
105
106#define SQE_VALID_FLAGS	(IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK|	\
107				IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
108				IOSQE_BUFFER_SELECT)
109#define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
110				REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS)
111
112#define IO_TCTX_REFS_CACHE_NR	(1U << 10)
113
114struct io_uring {
115	u32 head ____cacheline_aligned_in_smp;
116	u32 tail ____cacheline_aligned_in_smp;
117};
118
119/*
120 * This data is shared with the application through the mmap at offsets
121 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
122 *
123 * The offsets to the member fields are published through struct
124 * io_sqring_offsets when calling io_uring_setup.
125 */
126struct io_rings {
127	/*
128	 * Head and tail offsets into the ring; the offsets need to be
129	 * masked to get valid indices.
130	 *
131	 * The kernel controls head of the sq ring and the tail of the cq ring,
132	 * and the application controls tail of the sq ring and the head of the
133	 * cq ring.
134	 */
135	struct io_uring		sq, cq;
136	/*
137	 * Bitmasks to apply to head and tail offsets (constant, equals
138	 * ring_entries - 1)
139	 */
140	u32			sq_ring_mask, cq_ring_mask;
141	/* Ring sizes (constant, power of 2) */
142	u32			sq_ring_entries, cq_ring_entries;
143	/*
144	 * Number of invalid entries dropped by the kernel due to
145	 * invalid index stored in array
146	 *
147	 * Written by the kernel, shouldn't be modified by the
148	 * application (i.e. get number of "new events" by comparing to
149	 * cached value).
150	 *
151	 * After a new SQ head value was read by the application this
152	 * counter includes all submissions that were dropped reaching
153	 * the new SQ head (and possibly more).
154	 */
155	u32			sq_dropped;
156	/*
157	 * Runtime SQ flags
158	 *
159	 * Written by the kernel, shouldn't be modified by the
160	 * application.
161	 *
162	 * The application needs a full memory barrier before checking
163	 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
164	 */
165	u32			sq_flags;
166	/*
167	 * Runtime CQ flags
168	 *
169	 * Written by the application, shouldn't be modified by the
170	 * kernel.
171	 */
172	u32			cq_flags;
173	/*
174	 * Number of completion events lost because the queue was full;
175	 * this should be avoided by the application by making sure
176	 * there are not more requests pending than there is space in
177	 * the completion queue.
178	 *
179	 * Written by the kernel, shouldn't be modified by the
180	 * application (i.e. get number of "new events" by comparing to
181	 * cached value).
182	 *
183	 * As completion events come in out of order this counter is not
184	 * ordered with any other data.
185	 */
186	u32			cq_overflow;
187	/*
188	 * Ring buffer of completion events.
189	 *
190	 * The kernel writes completion events fresh every time they are
191	 * produced, so the application is allowed to modify pending
192	 * entries.
193	 */
194	struct io_uring_cqe	cqes[] ____cacheline_aligned_in_smp;
195};
196
197enum io_uring_cmd_flags {
198	IO_URING_F_NONBLOCK		= 1,
199	IO_URING_F_COMPLETE_DEFER	= 2,
200};
201
202struct io_mapped_ubuf {
203	u64		ubuf;
204	u64		ubuf_end;
205	unsigned int	nr_bvecs;
206	unsigned long	acct_pages;
207	struct bio_vec	bvec[];
208};
209
210struct io_ring_ctx;
211
212struct io_overflow_cqe {
213	struct io_uring_cqe cqe;
214	struct list_head list;
215};
216
217struct io_fixed_file {
218	/* file * with additional FFS_* flags */
219	unsigned long file_ptr;
220};
221
222struct io_rsrc_put {
223	struct list_head list;
224	u64 tag;
225	union {
226		void *rsrc;
227		struct file *file;
228		struct io_mapped_ubuf *buf;
229	};
230};
231
232struct io_file_table {
233	struct io_fixed_file *files;
234};
235
236struct io_rsrc_node {
237	struct percpu_ref		refs;
238	struct list_head		node;
239	struct list_head		rsrc_list;
240	struct io_rsrc_data		*rsrc_data;
241	struct llist_node		llist;
242	bool				done;
243};
244
245typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
246
247struct io_rsrc_data {
248	struct io_ring_ctx		*ctx;
249
250	u64				**tags;
251	unsigned int			nr;
252	rsrc_put_fn			*do_put;
253	atomic_t			refs;
254	struct completion		done;
255	bool				quiesce;
256};
257
258struct io_buffer {
259	struct list_head list;
260	__u64 addr;
261	__u32 len;
262	__u16 bid;
263};
264
265struct io_restriction {
266	DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
267	DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
268	u8 sqe_flags_allowed;
269	u8 sqe_flags_required;
270	bool registered;
271};
272
273enum {
274	IO_SQ_THREAD_SHOULD_STOP = 0,
275	IO_SQ_THREAD_SHOULD_PARK,
276};
277
278struct io_sq_data {
279	refcount_t		refs;
280	atomic_t		park_pending;
281	struct mutex		lock;
282
283	/* ctx's that are using this sqd */
284	struct list_head	ctx_list;
285
286	struct task_struct	*thread;
287	struct wait_queue_head	wait;
288
289	unsigned		sq_thread_idle;
290	int			sq_cpu;
291	pid_t			task_pid;
292	pid_t			task_tgid;
293
294	unsigned long		state;
295	struct completion	exited;
296};
297
298#define IO_COMPL_BATCH			32
299#define IO_REQ_CACHE_SIZE		32
300#define IO_REQ_ALLOC_BATCH		8
301
302struct io_submit_link {
303	struct io_kiocb		*head;
304	struct io_kiocb		*last;
305};
306
307struct io_submit_state {
308	struct blk_plug		plug;
309	struct io_submit_link	link;
310
311	/*
312	 * io_kiocb alloc cache
313	 */
314	void			*reqs[IO_REQ_CACHE_SIZE];
315	unsigned int		free_reqs;
316
317	bool			plug_started;
318
319	/*
320	 * Batch completion logic
321	 */
322	struct io_kiocb		*compl_reqs[IO_COMPL_BATCH];
323	unsigned int		compl_nr;
324	/* inline/task_work completion list, under ->uring_lock */
325	struct list_head	free_list;
326
327	unsigned int		ios_left;
328};
329
330struct io_ring_ctx {
331	/* const or read-mostly hot data */
332	struct {
333		struct percpu_ref	refs;
334
335		struct io_rings		*rings;
336		unsigned int		flags;
337		unsigned int		compat: 1;
338		unsigned int		drain_next: 1;
339		unsigned int		eventfd_async: 1;
340		unsigned int		restricted: 1;
341		unsigned int		off_timeout_used: 1;
342		unsigned int		drain_active: 1;
343	} ____cacheline_aligned_in_smp;
344
345	/* submission data */
346	struct {
347		struct mutex		uring_lock;
348
349		/*
350		 * Ring buffer of indices into array of io_uring_sqe, which is
351		 * mmapped by the application using the IORING_OFF_SQES offset.
352		 *
353		 * This indirection could e.g. be used to assign fixed
354		 * io_uring_sqe entries to operations and only submit them to
355		 * the queue when needed.
356		 *
357		 * The kernel modifies neither the indices array nor the entries
358		 * array.
359		 */
360		u32			*sq_array;
361		struct io_uring_sqe	*sq_sqes;
362		unsigned		cached_sq_head;
363		unsigned		sq_entries;
364		struct list_head	defer_list;
365
366		/*
367		 * Fixed resources fast path, should be accessed only under
368		 * uring_lock, and updated through io_uring_register(2)
369		 */
370		struct io_rsrc_node	*rsrc_node;
371		struct io_file_table	file_table;
372		unsigned		nr_user_files;
373		unsigned		nr_user_bufs;
374		struct io_mapped_ubuf	**user_bufs;
375
376		struct io_submit_state	submit_state;
377		struct list_head	timeout_list;
378		struct list_head	cq_overflow_list;
379		struct xarray		io_buffers;
380		struct xarray		personalities;
381		u32			pers_next;
382		unsigned		sq_thread_idle;
383	} ____cacheline_aligned_in_smp;
384
385	/* IRQ completion list, under ->completion_lock */
386	struct list_head	locked_free_list;
387	unsigned int		locked_free_nr;
388
389	const struct cred	*sq_creds;	/* cred used for __io_sq_thread() */
390	struct io_sq_data	*sq_data;	/* if using sq thread polling */
391
392	struct wait_queue_head	sqo_sq_wait;
393	struct list_head	sqd_list;
394
395	unsigned long		check_cq_overflow;
396
397	struct {
398		unsigned		cached_cq_tail;
399		unsigned		cq_entries;
400		struct eventfd_ctx	*cq_ev_fd;
401		struct wait_queue_head	poll_wait;
402		struct wait_queue_head	cq_wait;
403		unsigned		cq_extra;
404		atomic_t		cq_timeouts;
405		struct fasync_struct	*cq_fasync;
406		unsigned		cq_last_tm_flush;
407	} ____cacheline_aligned_in_smp;
408
409	struct {
410		spinlock_t		completion_lock;
411
412		spinlock_t		timeout_lock;
413
414		/*
415		 * ->iopoll_list is protected by the ctx->uring_lock for
416		 * io_uring instances that don't use IORING_SETUP_SQPOLL.
417		 * For SQPOLL, only the single threaded io_sq_thread() will
418		 * manipulate the list, hence no extra locking is needed there.
419		 */
420		struct list_head	iopoll_list;
421		struct hlist_head	*cancel_hash;
422		unsigned		cancel_hash_bits;
423		bool			poll_multi_queue;
424	} ____cacheline_aligned_in_smp;
425
426	struct io_restriction		restrictions;
427
428	/* slow path rsrc auxilary data, used by update/register */
429	struct {
430		struct io_rsrc_node		*rsrc_backup_node;
431		struct io_mapped_ubuf		*dummy_ubuf;
432		struct io_rsrc_data		*file_data;
433		struct io_rsrc_data		*buf_data;
434
435		struct delayed_work		rsrc_put_work;
436		struct llist_head		rsrc_put_llist;
437		struct list_head		rsrc_ref_list;
438		spinlock_t			rsrc_ref_lock;
439	};
440
441	/* Keep this last, we don't need it for the fast path */
442	struct {
443		#if defined(CONFIG_UNIX)
444			struct socket		*ring_sock;
445		#endif
446		/* hashed buffered write serialization */
447		struct io_wq_hash		*hash_map;
448
449		/* Only used for accounting purposes */
450		struct user_struct		*user;
451		struct mm_struct		*mm_account;
452
453		/* ctx exit and cancelation */
454		struct llist_head		fallback_llist;
455		struct delayed_work		fallback_work;
456		struct work_struct		exit_work;
457		struct list_head		tctx_list;
458		struct completion		ref_comp;
459	};
460};
461
462struct io_uring_task {
463	/* submission side */
464	int			cached_refs;
465	struct xarray		xa;
466	struct wait_queue_head	wait;
467	const struct io_ring_ctx *last;
468	struct io_wq		*io_wq;
469	struct percpu_counter	inflight;
470	atomic_t		inflight_tracked;
471	atomic_t		in_idle;
472
473	spinlock_t		task_lock;
474	struct io_wq_work_list	task_list;
475	struct callback_head	task_work;
476	bool			task_running;
477};
478
479/*
480 * First field must be the file pointer in all the
481 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
482 */
483struct io_poll_iocb {
484	struct file			*file;
485	struct wait_queue_head		*head;
486	__poll_t			events;
487	bool				done;
488	bool				canceled;
489	struct wait_queue_entry		wait;
490};
491
492struct io_poll_update {
493	struct file			*file;
494	u64				old_user_data;
495	u64				new_user_data;
496	__poll_t			events;
497	bool				update_events;
498	bool				update_user_data;
499};
500
501struct io_close {
502	struct file			*file;
503	int				fd;
504};
505
506struct io_timeout_data {
507	struct io_kiocb			*req;
508	struct hrtimer			timer;
509	struct timespec64		ts;
510	enum hrtimer_mode		mode;
511};
512
513struct io_accept {
514	struct file			*file;
515	struct sockaddr __user		*addr;
516	int __user			*addr_len;
517	int				flags;
518	unsigned long			nofile;
519};
520
521struct io_sync {
522	struct file			*file;
523	loff_t				len;
524	loff_t				off;
525	int				flags;
526	int				mode;
527};
528
529struct io_cancel {
530	struct file			*file;
531	u64				addr;
532};
533
534struct io_timeout {
535	struct file			*file;
536	u32				off;
537	u32				target_seq;
538	struct list_head		list;
539	/* head of the link, used by linked timeouts only */
540	struct io_kiocb			*head;
541};
542
543struct io_timeout_rem {
544	struct file			*file;
545	u64				addr;
546
547	/* timeout update */
548	struct timespec64		ts;
549	u32				flags;
550};
551
552struct io_rw {
553	/* NOTE: kiocb has the file as the first member, so don't do it here */
554	struct kiocb			kiocb;
555	u64				addr;
556	u64				len;
557};
558
559struct io_connect {
560	struct file			*file;
561	struct sockaddr __user		*addr;
562	int				addr_len;
563};
564
565struct io_sr_msg {
566	struct file			*file;
567	union {
568		struct compat_msghdr __user	*umsg_compat;
569		struct user_msghdr __user	*umsg;
570		void __user			*buf;
571	};
572	int				msg_flags;
573	int				bgid;
574	size_t				len;
575	struct io_buffer		*kbuf;
576};
577
578struct io_open {
579	struct file			*file;
580	int				dfd;
581	struct filename			*filename;
582	struct open_how			how;
583	unsigned long			nofile;
584};
585
586struct io_rsrc_update {
587	struct file			*file;
588	u64				arg;
589	u32				nr_args;
590	u32				offset;
591};
592
593struct io_fadvise {
594	struct file			*file;
595	u64				offset;
596	u32				len;
597	u32				advice;
598};
599
600struct io_madvise {
601	struct file			*file;
602	u64				addr;
603	u32				len;
604	u32				advice;
605};
606
607struct io_epoll {
608	struct file			*file;
609	int				epfd;
610	int				op;
611	int				fd;
612	struct epoll_event		event;
613};
614
615struct io_splice {
616	struct file			*file_out;
617	struct file			*file_in;
618	loff_t				off_out;
619	loff_t				off_in;
620	u64				len;
621	unsigned int			flags;
622};
623
624struct io_provide_buf {
625	struct file			*file;
626	__u64				addr;
627	__u32				len;
628	__u32				bgid;
629	__u16				nbufs;
630	__u16				bid;
631};
632
633struct io_statx {
634	struct file			*file;
635	int				dfd;
636	unsigned int			mask;
637	unsigned int			flags;
638	const char __user		*filename;
639	struct statx __user		*buffer;
640};
641
642struct io_shutdown {
643	struct file			*file;
644	int				how;
645};
646
647struct io_rename {
648	struct file			*file;
649	int				old_dfd;
650	int				new_dfd;
651	struct filename			*oldpath;
652	struct filename			*newpath;
653	int				flags;
654};
655
656struct io_unlink {
657	struct file			*file;
658	int				dfd;
659	int				flags;
660	struct filename			*filename;
661};
662
663struct io_completion {
664	struct file			*file;
665	u32				cflags;
666};
667
668struct io_async_connect {
669	struct sockaddr_storage		address;
670};
671
672struct io_async_msghdr {
673	struct iovec			fast_iov[UIO_FASTIOV];
674	/* points to an allocated iov, if NULL we use fast_iov instead */
675	struct iovec			*free_iov;
676	struct sockaddr __user		*uaddr;
677	struct msghdr			msg;
678	struct sockaddr_storage		addr;
679};
680
681struct io_async_rw {
682	struct iovec			fast_iov[UIO_FASTIOV];
683	const struct iovec		*free_iovec;
684	struct iov_iter			iter;
685	size_t				bytes_done;
686	struct wait_page_queue		wpq;
687};
688
689enum {
690	REQ_F_FIXED_FILE_BIT	= IOSQE_FIXED_FILE_BIT,
691	REQ_F_IO_DRAIN_BIT	= IOSQE_IO_DRAIN_BIT,
692	REQ_F_LINK_BIT		= IOSQE_IO_LINK_BIT,
693	REQ_F_HARDLINK_BIT	= IOSQE_IO_HARDLINK_BIT,
694	REQ_F_FORCE_ASYNC_BIT	= IOSQE_ASYNC_BIT,
695	REQ_F_BUFFER_SELECT_BIT	= IOSQE_BUFFER_SELECT_BIT,
696
697	/* first byte is taken by user flags, shift it to not overlap */
698	REQ_F_FAIL_BIT		= 8,
699	REQ_F_INFLIGHT_BIT,
700	REQ_F_CUR_POS_BIT,
701	REQ_F_NOWAIT_BIT,
702	REQ_F_LINK_TIMEOUT_BIT,
703	REQ_F_NEED_CLEANUP_BIT,
704	REQ_F_POLLED_BIT,
705	REQ_F_BUFFER_SELECTED_BIT,
706	REQ_F_LTIMEOUT_ACTIVE_BIT,
707	REQ_F_COMPLETE_INLINE_BIT,
708	REQ_F_REISSUE_BIT,
709	REQ_F_DONT_REISSUE_BIT,
710	REQ_F_CREDS_BIT,
711	/* keep async read/write and isreg together and in order */
712	REQ_F_NOWAIT_READ_BIT,
713	REQ_F_NOWAIT_WRITE_BIT,
714	REQ_F_ISREG_BIT,
715
716	/* not a real bit, just to check we're not overflowing the space */
717	__REQ_F_LAST_BIT,
718};
719
720enum {
721	/* ctx owns file */
722	REQ_F_FIXED_FILE	= BIT(REQ_F_FIXED_FILE_BIT),
723	/* drain existing IO first */
724	REQ_F_IO_DRAIN		= BIT(REQ_F_IO_DRAIN_BIT),
725	/* linked sqes */
726	REQ_F_LINK		= BIT(REQ_F_LINK_BIT),
727	/* doesn't sever on completion < 0 */
728	REQ_F_HARDLINK		= BIT(REQ_F_HARDLINK_BIT),
729	/* IOSQE_ASYNC */
730	REQ_F_FORCE_ASYNC	= BIT(REQ_F_FORCE_ASYNC_BIT),
731	/* IOSQE_BUFFER_SELECT */
732	REQ_F_BUFFER_SELECT	= BIT(REQ_F_BUFFER_SELECT_BIT),
733
734	/* fail rest of links */
735	REQ_F_FAIL		= BIT(REQ_F_FAIL_BIT),
736	/* on inflight list, should be cancelled and waited on exit reliably */
737	REQ_F_INFLIGHT		= BIT(REQ_F_INFLIGHT_BIT),
738	/* read/write uses file position */
739	REQ_F_CUR_POS		= BIT(REQ_F_CUR_POS_BIT),
740	/* must not punt to workers */
741	REQ_F_NOWAIT		= BIT(REQ_F_NOWAIT_BIT),
742	/* has or had linked timeout */
743	REQ_F_LINK_TIMEOUT	= BIT(REQ_F_LINK_TIMEOUT_BIT),
744	/* needs cleanup */
745	REQ_F_NEED_CLEANUP	= BIT(REQ_F_NEED_CLEANUP_BIT),
746	/* already went through poll handler */
747	REQ_F_POLLED		= BIT(REQ_F_POLLED_BIT),
748	/* buffer already selected */
749	REQ_F_BUFFER_SELECTED	= BIT(REQ_F_BUFFER_SELECTED_BIT),
750	/* linked timeout is active, i.e. prepared by link's head */
751	REQ_F_LTIMEOUT_ACTIVE	= BIT(REQ_F_LTIMEOUT_ACTIVE_BIT),
752	/* completion is deferred through io_comp_state */
753	REQ_F_COMPLETE_INLINE	= BIT(REQ_F_COMPLETE_INLINE_BIT),
754	/* caller should reissue async */
755	REQ_F_REISSUE		= BIT(REQ_F_REISSUE_BIT),
756	/* don't attempt request reissue, see io_rw_reissue() */
757	REQ_F_DONT_REISSUE	= BIT(REQ_F_DONT_REISSUE_BIT),
758	/* supports async reads */
759	REQ_F_NOWAIT_READ	= BIT(REQ_F_NOWAIT_READ_BIT),
760	/* supports async writes */
761	REQ_F_NOWAIT_WRITE	= BIT(REQ_F_NOWAIT_WRITE_BIT),
762	/* regular file */
763	REQ_F_ISREG		= BIT(REQ_F_ISREG_BIT),
764	/* has creds assigned */
765	REQ_F_CREDS		= BIT(REQ_F_CREDS_BIT),
766};
767
768struct async_poll {
769	struct io_poll_iocb	poll;
770	struct io_poll_iocb	*double_poll;
771};
772
773typedef void (*io_req_tw_func_t)(struct io_kiocb *req);
774
775struct io_task_work {
776	union {
777		struct io_wq_work_node	node;
778		struct llist_node	fallback_node;
779	};
780	io_req_tw_func_t		func;
781};
782
783enum {
784	IORING_RSRC_FILE		= 0,
785	IORING_RSRC_BUFFER		= 1,
786};
787
788/*
789 * NOTE! Each of the iocb union members has the file pointer
790 * as the first entry in their struct definition. So you can
791 * access the file pointer through any of the sub-structs,
792 * or directly as just 'ki_filp' in this struct.
793 */
794struct io_kiocb {
795	union {
796		struct file		*file;
797		struct io_rw		rw;
798		struct io_poll_iocb	poll;
799		struct io_poll_update	poll_update;
800		struct io_accept	accept;
801		struct io_sync		sync;
802		struct io_cancel	cancel;
803		struct io_timeout	timeout;
804		struct io_timeout_rem	timeout_rem;
805		struct io_connect	connect;
806		struct io_sr_msg	sr_msg;
807		struct io_open		open;
808		struct io_close		close;
809		struct io_rsrc_update	rsrc_update;
810		struct io_fadvise	fadvise;
811		struct io_madvise	madvise;
812		struct io_epoll		epoll;
813		struct io_splice	splice;
814		struct io_provide_buf	pbuf;
815		struct io_statx		statx;
816		struct io_shutdown	shutdown;
817		struct io_rename	rename;
818		struct io_unlink	unlink;
819		/* use only after cleaning per-op data, see io_clean_op() */
820		struct io_completion	compl;
821	};
822
823	/* opcode allocated if it needs to store data for async defer */
824	void				*async_data;
825	u8				opcode;
826	/* polled IO has completed */
827	u8				iopoll_completed;
828
829	u16				buf_index;
830	u32				result;
831
832	struct io_ring_ctx		*ctx;
833	unsigned int			flags;
834	atomic_t			refs;
835	struct task_struct		*task;
836	u64				user_data;
837
838	struct io_kiocb			*link;
839	struct percpu_ref		*fixed_rsrc_refs;
840
841	/* used with ctx->iopoll_list with reads/writes */
842	struct list_head		inflight_entry;
843	struct io_task_work		io_task_work;
844	/* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
845	struct hlist_node		hash_node;
846	struct async_poll		*apoll;
847	struct io_wq_work		work;
848	const struct cred		*creds;
849
850	/* store used ubuf, so we can prevent reloading */
851	struct io_mapped_ubuf		*imu;
852};
853
854struct io_tctx_node {
855	struct list_head	ctx_node;
856	struct task_struct	*task;
857	struct io_ring_ctx	*ctx;
858};
859
860struct io_defer_entry {
861	struct list_head	list;
862	struct io_kiocb		*req;
863	u32			seq;
864};
865
866struct io_op_def {
867	/* needs req->file assigned */
868	unsigned		needs_file : 1;
869	/* hash wq insertion if file is a regular file */
870	unsigned		hash_reg_file : 1;
871	/* unbound wq insertion if file is a non-regular file */
872	unsigned		unbound_nonreg_file : 1;
873	/* opcode is not supported by this kernel */
874	unsigned		not_supported : 1;
875	/* set if opcode supports polled "wait" */
876	unsigned		pollin : 1;
877	unsigned		pollout : 1;
878	/* op supports buffer selection */
879	unsigned		buffer_select : 1;
880	/* do prep async if is going to be punted */
881	unsigned		needs_async_setup : 1;
882	/* should block plug */
883	unsigned		plug : 1;
884	/* size of async data needed, if any */
885	unsigned short		async_size;
886};
887
888static const struct io_op_def io_op_defs[] = {
889	[IORING_OP_NOP] = {},
890	[IORING_OP_READV] = {
891		.needs_file		= 1,
892		.unbound_nonreg_file	= 1,
893		.pollin			= 1,
894		.buffer_select		= 1,
895		.needs_async_setup	= 1,
896		.plug			= 1,
897		.async_size		= sizeof(struct io_async_rw),
898	},
899	[IORING_OP_WRITEV] = {
900		.needs_file		= 1,
901		.hash_reg_file		= 1,
902		.unbound_nonreg_file	= 1,
903		.pollout		= 1,
904		.needs_async_setup	= 1,
905		.plug			= 1,
906		.async_size		= sizeof(struct io_async_rw),
907	},
908	[IORING_OP_FSYNC] = {
909		.needs_file		= 1,
910	},
911	[IORING_OP_READ_FIXED] = {
912		.needs_file		= 1,
913		.unbound_nonreg_file	= 1,
914		.pollin			= 1,
915		.plug			= 1,
916		.async_size		= sizeof(struct io_async_rw),
917	},
918	[IORING_OP_WRITE_FIXED] = {
919		.needs_file		= 1,
920		.hash_reg_file		= 1,
921		.unbound_nonreg_file	= 1,
922		.pollout		= 1,
923		.plug			= 1,
924		.async_size		= sizeof(struct io_async_rw),
925	},
926	[IORING_OP_POLL_ADD] = {
927		.needs_file		= 1,
928		.unbound_nonreg_file	= 1,
929	},
930	[IORING_OP_POLL_REMOVE] = {},
931	[IORING_OP_SYNC_FILE_RANGE] = {
932		.needs_file		= 1,
933	},
934	[IORING_OP_SENDMSG] = {
935		.needs_file		= 1,
936		.unbound_nonreg_file	= 1,
937		.pollout		= 1,
938		.needs_async_setup	= 1,
939		.async_size		= sizeof(struct io_async_msghdr),
940	},
941	[IORING_OP_RECVMSG] = {
942		.needs_file		= 1,
943		.unbound_nonreg_file	= 1,
944		.pollin			= 1,
945		.buffer_select		= 1,
946		.needs_async_setup	= 1,
947		.async_size		= sizeof(struct io_async_msghdr),
948	},
949	[IORING_OP_TIMEOUT] = {
950		.async_size		= sizeof(struct io_timeout_data),
951	},
952	[IORING_OP_TIMEOUT_REMOVE] = {
953		/* used by timeout updates' prep() */
954	},
955	[IORING_OP_ACCEPT] = {
956		.needs_file		= 1,
957		.unbound_nonreg_file	= 1,
958		.pollin			= 1,
959	},
960	[IORING_OP_ASYNC_CANCEL] = {},
961	[IORING_OP_LINK_TIMEOUT] = {
962		.async_size		= sizeof(struct io_timeout_data),
963	},
964	[IORING_OP_CONNECT] = {
965		.needs_file		= 1,
966		.unbound_nonreg_file	= 1,
967		.pollout		= 1,
968		.needs_async_setup	= 1,
969		.async_size		= sizeof(struct io_async_connect),
970	},
971	[IORING_OP_FALLOCATE] = {
972		.needs_file		= 1,
973	},
974	[IORING_OP_OPENAT] = {},
975	[IORING_OP_CLOSE] = {},
976	[IORING_OP_FILES_UPDATE] = {},
977	[IORING_OP_STATX] = {},
978	[IORING_OP_READ] = {
979		.needs_file		= 1,
980		.unbound_nonreg_file	= 1,
981		.pollin			= 1,
982		.buffer_select		= 1,
983		.plug			= 1,
984		.async_size		= sizeof(struct io_async_rw),
985	},
986	[IORING_OP_WRITE] = {
987		.needs_file		= 1,
988		.unbound_nonreg_file	= 1,
989		.pollout		= 1,
990		.plug			= 1,
991		.async_size		= sizeof(struct io_async_rw),
992	},
993	[IORING_OP_FADVISE] = {
994		.needs_file		= 1,
995	},
996	[IORING_OP_MADVISE] = {},
997	[IORING_OP_SEND] = {
998		.needs_file		= 1,
999		.unbound_nonreg_file	= 1,
1000		.pollout		= 1,
1001	},
1002	[IORING_OP_RECV] = {
1003		.needs_file		= 1,
1004		.unbound_nonreg_file	= 1,
1005		.pollin			= 1,
1006		.buffer_select		= 1,
1007	},
1008	[IORING_OP_OPENAT2] = {
1009	},
1010	[IORING_OP_EPOLL_CTL] = {
1011		.unbound_nonreg_file	= 1,
1012	},
1013	[IORING_OP_SPLICE] = {
1014		.needs_file		= 1,
1015		.hash_reg_file		= 1,
1016		.unbound_nonreg_file	= 1,
1017	},
1018	[IORING_OP_PROVIDE_BUFFERS] = {},
1019	[IORING_OP_REMOVE_BUFFERS] = {},
1020	[IORING_OP_TEE] = {
1021		.needs_file		= 1,
1022		.hash_reg_file		= 1,
1023		.unbound_nonreg_file	= 1,
1024	},
1025	[IORING_OP_SHUTDOWN] = {
1026		.needs_file		= 1,
1027	},
1028	[IORING_OP_RENAMEAT] = {},
1029	[IORING_OP_UNLINKAT] = {},
1030};
1031
1032static bool io_disarm_next(struct io_kiocb *req);
1033static void io_uring_del_tctx_node(unsigned long index);
1034static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1035					 struct task_struct *task,
1036					 bool cancel_all);
1037static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1038
1039static bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1040				 long res, unsigned int cflags);
1041static void io_put_req(struct io_kiocb *req);
1042static void io_put_req_deferred(struct io_kiocb *req, int nr);
1043static void io_dismantle_req(struct io_kiocb *req);
1044static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
1045static void io_queue_linked_timeout(struct io_kiocb *req);
1046static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
1047				     struct io_uring_rsrc_update2 *up,
1048				     unsigned nr_args);
1049static void io_clean_op(struct io_kiocb *req);
1050static struct file *io_file_get(struct io_ring_ctx *ctx,
1051				struct io_kiocb *req, int fd, bool fixed);
1052static void __io_queue_sqe(struct io_kiocb *req);
1053static void io_rsrc_put_work(struct work_struct *work);
1054
1055static void io_req_task_queue(struct io_kiocb *req);
1056static void io_submit_flush_completions(struct io_ring_ctx *ctx);
1057static int io_req_prep_async(struct io_kiocb *req);
1058
1059static struct kmem_cache *req_cachep;
1060
1061static const struct file_operations io_uring_fops;
1062
1063struct sock *io_uring_get_socket(struct file *file)
1064{
1065#if defined(CONFIG_UNIX)
1066	if (file->f_op == &io_uring_fops) {
1067		struct io_ring_ctx *ctx = file->private_data;
1068
1069		return ctx->ring_sock->sk;
1070	}
1071#endif
1072	return NULL;
1073}
1074EXPORT_SYMBOL(io_uring_get_socket);
1075
1076#define io_for_each_link(pos, head) \
1077	for (pos = (head); pos; pos = pos->link)
1078
1079static inline void io_req_set_rsrc_node(struct io_kiocb *req)
1080{
1081	struct io_ring_ctx *ctx = req->ctx;
1082
1083	if (!req->fixed_rsrc_refs) {
1084		req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
1085		percpu_ref_get(req->fixed_rsrc_refs);
1086	}
1087}
1088
1089static void io_refs_resurrect(struct percpu_ref *ref, struct completion *compl)
1090{
1091	bool got = percpu_ref_tryget(ref);
1092
1093	/* already at zero, wait for ->release() */
1094	if (!got)
1095		wait_for_completion(compl);
1096	percpu_ref_resurrect(ref);
1097	if (got)
1098		percpu_ref_put(ref);
1099}
1100
1101static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1102			  bool cancel_all)
1103{
1104	struct io_kiocb *req;
1105
1106	if (task && head->task != task)
1107		return false;
1108	if (cancel_all)
1109		return true;
1110
1111	io_for_each_link(req, head) {
1112		if (req->flags & REQ_F_INFLIGHT)
1113			return true;
1114	}
1115	return false;
1116}
1117
1118static inline void req_set_fail(struct io_kiocb *req)
1119{
1120	req->flags |= REQ_F_FAIL;
1121}
1122
1123static void io_ring_ctx_ref_free(struct percpu_ref *ref)
1124{
1125	struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1126
1127	complete(&ctx->ref_comp);
1128}
1129
1130static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1131{
1132	return !req->timeout.off;
1133}
1134
1135static void io_fallback_req_func(struct work_struct *work)
1136{
1137	struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1138						fallback_work.work);
1139	struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1140	struct io_kiocb *req, *tmp;
1141
1142	percpu_ref_get(&ctx->refs);
1143	llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
1144		req->io_task_work.func(req);
1145	percpu_ref_put(&ctx->refs);
1146}
1147
1148static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
1149{
1150	struct io_ring_ctx *ctx;
1151	int hash_bits;
1152
1153	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1154	if (!ctx)
1155		return NULL;
1156
1157	/*
1158	 * Use 5 bits less than the max cq entries, that should give us around
1159	 * 32 entries per hash list if totally full and uniformly spread.
1160	 */
1161	hash_bits = ilog2(p->cq_entries);
1162	hash_bits -= 5;
1163	if (hash_bits <= 0)
1164		hash_bits = 1;
1165	ctx->cancel_hash_bits = hash_bits;
1166	ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1167					GFP_KERNEL);
1168	if (!ctx->cancel_hash)
1169		goto err;
1170	__hash_init(ctx->cancel_hash, 1U << hash_bits);
1171
1172	ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1173	if (!ctx->dummy_ubuf)
1174		goto err;
1175	/* set invalid range, so io_import_fixed() fails meeting it */
1176	ctx->dummy_ubuf->ubuf = -1UL;
1177
1178	if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1179			    PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1180		goto err;
1181
1182	ctx->flags = p->flags;
1183	init_waitqueue_head(&ctx->sqo_sq_wait);
1184	INIT_LIST_HEAD(&ctx->sqd_list);
1185	init_waitqueue_head(&ctx->poll_wait);
1186	INIT_LIST_HEAD(&ctx->cq_overflow_list);
1187	init_completion(&ctx->ref_comp);
1188	xa_init_flags(&ctx->io_buffers, XA_FLAGS_ALLOC1);
1189	xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
1190	mutex_init(&ctx->uring_lock);
1191	init_waitqueue_head(&ctx->cq_wait);
1192	spin_lock_init(&ctx->completion_lock);
1193	spin_lock_init(&ctx->timeout_lock);
1194	INIT_LIST_HEAD(&ctx->iopoll_list);
1195	INIT_LIST_HEAD(&ctx->defer_list);
1196	INIT_LIST_HEAD(&ctx->timeout_list);
1197	spin_lock_init(&ctx->rsrc_ref_lock);
1198	INIT_LIST_HEAD(&ctx->rsrc_ref_list);
1199	INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1200	init_llist_head(&ctx->rsrc_put_llist);
1201	INIT_LIST_HEAD(&ctx->tctx_list);
1202	INIT_LIST_HEAD(&ctx->submit_state.free_list);
1203	INIT_LIST_HEAD(&ctx->locked_free_list);
1204	INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
1205	return ctx;
1206err:
1207	kfree(ctx->dummy_ubuf);
1208	kfree(ctx->cancel_hash);
1209	kfree(ctx);
1210	return NULL;
1211}
1212
1213static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1214{
1215	struct io_rings *r = ctx->rings;
1216
1217	WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1218	ctx->cq_extra--;
1219}
1220
1221static bool req_need_defer(struct io_kiocb *req, u32 seq)
1222{
1223	if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1224		struct io_ring_ctx *ctx = req->ctx;
1225
1226		return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
1227	}
1228
1229	return false;
1230}
1231
1232#define FFS_ASYNC_READ		0x1UL
1233#define FFS_ASYNC_WRITE		0x2UL
1234#ifdef CONFIG_64BIT
1235#define FFS_ISREG		0x4UL
1236#else
1237#define FFS_ISREG		0x0UL
1238#endif
1239#define FFS_MASK		~(FFS_ASYNC_READ|FFS_ASYNC_WRITE|FFS_ISREG)
1240
1241static inline bool io_req_ffs_set(struct io_kiocb *req)
1242{
1243	return IS_ENABLED(CONFIG_64BIT) && (req->flags & REQ_F_FIXED_FILE);
1244}
1245
1246static void io_req_track_inflight(struct io_kiocb *req)
1247{
1248	if (!(req->flags & REQ_F_INFLIGHT)) {
1249		req->flags |= REQ_F_INFLIGHT;
1250		atomic_inc(&current->io_uring->inflight_tracked);
1251	}
1252}
1253
1254static void io_prep_async_work(struct io_kiocb *req)
1255{
1256	const struct io_op_def *def = &io_op_defs[req->opcode];
1257	struct io_ring_ctx *ctx = req->ctx;
1258
1259	if (!(req->flags & REQ_F_CREDS)) {
1260		req->flags |= REQ_F_CREDS;
1261		req->creds = get_current_cred();
1262	}
1263
1264	req->work.list.next = NULL;
1265	req->work.flags = 0;
1266	if (req->flags & REQ_F_FORCE_ASYNC)
1267		req->work.flags |= IO_WQ_WORK_CONCURRENT;
1268
1269	if (req->flags & REQ_F_ISREG) {
1270		if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1271			io_wq_hash_work(&req->work, file_inode(req->file));
1272	} else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1273		if (def->unbound_nonreg_file)
1274			req->work.flags |= IO_WQ_WORK_UNBOUND;
1275	}
1276
1277	switch (req->opcode) {
1278	case IORING_OP_SPLICE:
1279	case IORING_OP_TEE:
1280		if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1281			req->work.flags |= IO_WQ_WORK_UNBOUND;
1282		break;
1283	}
1284}
1285
1286static void io_prep_async_link(struct io_kiocb *req)
1287{
1288	struct io_kiocb *cur;
1289
1290	if (req->flags & REQ_F_LINK_TIMEOUT) {
1291		struct io_ring_ctx *ctx = req->ctx;
1292
1293		spin_lock_irq(&ctx->completion_lock);
1294		io_for_each_link(cur, req)
1295			io_prep_async_work(cur);
1296		spin_unlock_irq(&ctx->completion_lock);
1297	} else {
1298		io_for_each_link(cur, req)
1299			io_prep_async_work(cur);
1300	}
1301}
1302
1303static void io_queue_async_work(struct io_kiocb *req)
1304{
1305	struct io_ring_ctx *ctx = req->ctx;
1306	struct io_kiocb *link = io_prep_linked_timeout(req);
1307	struct io_uring_task *tctx = req->task->io_uring;
1308
1309	BUG_ON(!tctx);
1310	BUG_ON(!tctx->io_wq);
1311
1312	/* init ->work of the whole link before punting */
1313	io_prep_async_link(req);
1314
1315	/*
1316	 * Not expected to happen, but if we do have a bug where this _can_
1317	 * happen, catch it here and ensure the request is marked as
1318	 * canceled. That will make io-wq go through the usual work cancel
1319	 * procedure rather than attempt to run this request (or create a new
1320	 * worker for it).
1321	 */
1322	if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1323		req->work.flags |= IO_WQ_WORK_CANCEL;
1324
1325	trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1326					&req->work, req->flags);
1327	io_wq_enqueue(tctx->io_wq, &req->work);
1328	if (link)
1329		io_queue_linked_timeout(link);
1330}
1331
1332static void io_kill_timeout(struct io_kiocb *req, int status)
1333	__must_hold(&req->ctx->completion_lock)
1334	__must_hold(&req->ctx->timeout_lock)
1335{
1336	struct io_timeout_data *io = req->async_data;
1337
1338	if (hrtimer_try_to_cancel(&io->timer) != -1) {
1339		atomic_set(&req->ctx->cq_timeouts,
1340			atomic_read(&req->ctx->cq_timeouts) + 1);
1341		list_del_init(&req->timeout.list);
1342		io_cqring_fill_event(req->ctx, req->user_data, status, 0);
1343		io_put_req_deferred(req, 1);
1344	}
1345}
1346
1347static void io_queue_deferred(struct io_ring_ctx *ctx)
1348{
1349	while (!list_empty(&ctx->defer_list)) {
1350		struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1351						struct io_defer_entry, list);
1352
1353		if (req_need_defer(de->req, de->seq))
1354			break;
1355		list_del_init(&de->list);
1356		io_req_task_queue(de->req);
1357		kfree(de);
1358	}
1359}
1360
1361static void io_flush_timeouts(struct io_ring_ctx *ctx)
1362	__must_hold(&ctx->completion_lock)
1363{
1364	u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
1365	unsigned long flags;
1366
1367	spin_lock_irqsave(&ctx->timeout_lock, flags);
1368	while (!list_empty(&ctx->timeout_list)) {
1369		u32 events_needed, events_got;
1370		struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1371						struct io_kiocb, timeout.list);
1372
1373		if (io_is_timeout_noseq(req))
1374			break;
1375
1376		/*
1377		 * Since seq can easily wrap around over time, subtract
1378		 * the last seq at which timeouts were flushed before comparing.
1379		 * Assuming not more than 2^31-1 events have happened since,
1380		 * these subtractions won't have wrapped, so we can check if
1381		 * target is in [last_seq, current_seq] by comparing the two.
1382		 */
1383		events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1384		events_got = seq - ctx->cq_last_tm_flush;
1385		if (events_got < events_needed)
1386			break;
1387
1388		list_del_init(&req->timeout.list);
1389		io_kill_timeout(req, 0);
1390	}
1391	ctx->cq_last_tm_flush = seq;
1392	spin_unlock_irqrestore(&ctx->timeout_lock, flags);
1393}
1394
1395static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
1396{
1397	if (ctx->off_timeout_used)
1398		io_flush_timeouts(ctx);
1399	if (ctx->drain_active)
1400		io_queue_deferred(ctx);
1401}
1402
1403static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1404{
1405	if (unlikely(ctx->off_timeout_used || ctx->drain_active))
1406		__io_commit_cqring_flush(ctx);
1407	/* order cqe stores with ring update */
1408	smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1409}
1410
1411static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1412{
1413	struct io_rings *r = ctx->rings;
1414
1415	return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
1416}
1417
1418static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1419{
1420	return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1421}
1422
1423static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
1424{
1425	struct io_rings *rings = ctx->rings;
1426	unsigned tail, mask = ctx->cq_entries - 1;
1427
1428	/*
1429	 * writes to the cq entry need to come after reading head; the
1430	 * control dependency is enough as we're using WRITE_ONCE to
1431	 * fill the cq entry
1432	 */
1433	if (__io_cqring_events(ctx) == ctx->cq_entries)
1434		return NULL;
1435
1436	tail = ctx->cached_cq_tail++;
1437	return &rings->cqes[tail & mask];
1438}
1439
1440static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1441{
1442	if (likely(!ctx->cq_ev_fd))
1443		return false;
1444	if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1445		return false;
1446	return !ctx->eventfd_async || io_wq_current_is_worker();
1447}
1448
1449static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1450{
1451	/*
1452	 * wake_up_all() may seem excessive, but io_wake_function() and
1453	 * io_should_wake() handle the termination of the loop and only
1454	 * wake as many waiters as we need to.
1455	 */
1456	if (wq_has_sleeper(&ctx->cq_wait))
1457		wake_up_all(&ctx->cq_wait);
1458	if (ctx->sq_data && waitqueue_active(&ctx->sq_data->wait))
1459		wake_up(&ctx->sq_data->wait);
1460	if (io_should_trigger_evfd(ctx))
1461		eventfd_signal(ctx->cq_ev_fd, 1);
1462	if (waitqueue_active(&ctx->poll_wait)) {
1463		wake_up_interruptible(&ctx->poll_wait);
1464		kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1465	}
1466}
1467
1468static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1469{
1470	if (ctx->flags & IORING_SETUP_SQPOLL) {
1471		if (wq_has_sleeper(&ctx->cq_wait))
1472			wake_up_all(&ctx->cq_wait);
1473	}
1474	if (io_should_trigger_evfd(ctx))
1475		eventfd_signal(ctx->cq_ev_fd, 1);
1476	if (waitqueue_active(&ctx->poll_wait)) {
1477		wake_up_interruptible(&ctx->poll_wait);
1478		kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1479	}
1480}
1481
1482/* Returns true if there are no backlogged entries after the flush */
1483static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1484{
1485	unsigned long flags;
1486	bool all_flushed, posted;
1487
1488	if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
1489		return false;
1490
1491	posted = false;
1492	spin_lock_irqsave(&ctx->completion_lock, flags);
1493	while (!list_empty(&ctx->cq_overflow_list)) {
1494		struct io_uring_cqe *cqe = io_get_cqe(ctx);
1495		struct io_overflow_cqe *ocqe;
1496
1497		if (!cqe && !force)
1498			break;
1499		ocqe = list_first_entry(&ctx->cq_overflow_list,
1500					struct io_overflow_cqe, list);
1501		if (cqe)
1502			memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1503		else
1504			io_account_cq_overflow(ctx);
1505
1506		posted = true;
1507		list_del(&ocqe->list);
1508		kfree(ocqe);
1509	}
1510
1511	all_flushed = list_empty(&ctx->cq_overflow_list);
1512	if (all_flushed) {
1513		clear_bit(0, &ctx->check_cq_overflow);
1514		WRITE_ONCE(ctx->rings->sq_flags,
1515			   ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
1516	}
1517
1518	if (posted)
1519		io_commit_cqring(ctx);
1520	spin_unlock_irqrestore(&ctx->completion_lock, flags);
1521	if (posted)
1522		io_cqring_ev_posted(ctx);
1523	return all_flushed;
1524}
1525
1526static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
1527{
1528	bool ret = true;
1529
1530	if (test_bit(0, &ctx->check_cq_overflow)) {
1531		/* iopoll syncs against uring_lock, not completion_lock */
1532		if (ctx->flags & IORING_SETUP_IOPOLL)
1533			mutex_lock(&ctx->uring_lock);
1534		ret = __io_cqring_overflow_flush(ctx, false);
1535		if (ctx->flags & IORING_SETUP_IOPOLL)
1536			mutex_unlock(&ctx->uring_lock);
1537	}
1538
1539	return ret;
1540}
1541
1542/*
1543 * Shamelessly stolen from the mm implementation of page reference checking,
1544 * see commit f958d7b528b1 for details.
1545 */
1546#define req_ref_zero_or_close_to_overflow(req)	\
1547	((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1548
1549static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1550{
1551	return atomic_inc_not_zero(&req->refs);
1552}
1553
1554static inline bool req_ref_sub_and_test(struct io_kiocb *req, int refs)
1555{
1556	WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1557	return atomic_sub_and_test(refs, &req->refs);
1558}
1559
1560static inline bool req_ref_put_and_test(struct io_kiocb *req)
1561{
1562	WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1563	return atomic_dec_and_test(&req->refs);
1564}
1565
1566static inline void req_ref_put(struct io_kiocb *req)
1567{
1568	WARN_ON_ONCE(req_ref_put_and_test(req));
1569}
1570
1571static inline void req_ref_get(struct io_kiocb *req)
1572{
1573	WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1574	atomic_inc(&req->refs);
1575}
1576
1577/* must to be called somewhat shortly after putting a request */
1578static inline void io_put_task(struct task_struct *task, int nr)
1579{
1580	struct io_uring_task *tctx = task->io_uring;
1581
1582	percpu_counter_sub(&tctx->inflight, nr);
1583	if (unlikely(atomic_read(&tctx->in_idle)))
1584		wake_up(&tctx->wait);
1585	put_task_struct_many(task, nr);
1586}
1587
1588static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
1589				     long res, unsigned int cflags)
1590{
1591	struct io_overflow_cqe *ocqe;
1592
1593	ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
1594	if (!ocqe) {
1595		/*
1596		 * If we're in ring overflow flush mode, or in task cancel mode,
1597		 * or cannot allocate an overflow entry, then we need to drop it
1598		 * on the floor.
1599		 */
1600		io_account_cq_overflow(ctx);
1601		return false;
1602	}
1603	if (list_empty(&ctx->cq_overflow_list)) {
1604		set_bit(0, &ctx->check_cq_overflow);
1605		WRITE_ONCE(ctx->rings->sq_flags,
1606			   ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
1607
1608	}
1609	ocqe->cqe.user_data = user_data;
1610	ocqe->cqe.res = res;
1611	ocqe->cqe.flags = cflags;
1612	list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
1613	return true;
1614}
1615
1616static inline bool __io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1617					  long res, unsigned int cflags)
1618{
1619	struct io_uring_cqe *cqe;
1620
1621	trace_io_uring_complete(ctx, user_data, res, cflags);
1622
1623	/*
1624	 * If we can't get a cq entry, userspace overflowed the
1625	 * submission (by quite a lot). Increment the overflow count in
1626	 * the ring.
1627	 */
1628	cqe = io_get_cqe(ctx);
1629	if (likely(cqe)) {
1630		WRITE_ONCE(cqe->user_data, user_data);
1631		WRITE_ONCE(cqe->res, res);
1632		WRITE_ONCE(cqe->flags, cflags);
1633		return true;
1634	}
1635	return io_cqring_event_overflow(ctx, user_data, res, cflags);
1636}
1637
1638/* not as hot to bloat with inlining */
1639static noinline bool io_cqring_fill_event(struct io_ring_ctx *ctx, u64 user_data,
1640					  long res, unsigned int cflags)
1641{
1642	return __io_cqring_fill_event(ctx, user_data, res, cflags);
1643}
1644
1645static void io_req_complete_post(struct io_kiocb *req, long res,
1646				 unsigned int cflags)
1647{
1648	struct io_ring_ctx *ctx = req->ctx;
1649	unsigned long flags;
1650
1651	spin_lock_irqsave(&ctx->completion_lock, flags);
1652	__io_cqring_fill_event(ctx, req->user_data, res, cflags);
1653	/*
1654	 * If we're the last reference to this request, add to our locked
1655	 * free_list cache.
1656	 */
1657	if (req_ref_put_and_test(req)) {
1658		if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
1659			if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL))
1660				io_disarm_next(req);
1661			if (req->link) {
1662				io_req_task_queue(req->link);
1663				req->link = NULL;
1664			}
1665		}
1666		io_dismantle_req(req);
1667		io_put_task(req->task, 1);
1668		list_add(&req->inflight_entry, &ctx->locked_free_list);
1669		ctx->locked_free_nr++;
1670	} else {
1671		if (!percpu_ref_tryget(&ctx->refs))
1672			req = NULL;
1673	}
1674	io_commit_cqring(ctx);
1675	spin_unlock_irqrestore(&ctx->completion_lock, flags);
1676
1677	if (req) {
1678		io_cqring_ev_posted(ctx);
1679		percpu_ref_put(&ctx->refs);
1680	}
1681}
1682
1683static inline bool io_req_needs_clean(struct io_kiocb *req)
1684{
1685	return req->flags & IO_REQ_CLEAN_FLAGS;
1686}
1687
1688static void io_req_complete_state(struct io_kiocb *req, long res,
1689				  unsigned int cflags)
1690{
1691	if (io_req_needs_clean(req))
1692		io_clean_op(req);
1693	req->result = res;
1694	req->compl.cflags = cflags;
1695	req->flags |= REQ_F_COMPLETE_INLINE;
1696}
1697
1698static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
1699				     long res, unsigned cflags)
1700{
1701	if (issue_flags & IO_URING_F_COMPLETE_DEFER)
1702		io_req_complete_state(req, res, cflags);
1703	else
1704		io_req_complete_post(req, res, cflags);
1705}
1706
1707static inline void io_req_complete(struct io_kiocb *req, long res)
1708{
1709	__io_req_complete(req, 0, res, 0);
1710}
1711
1712static void io_req_complete_failed(struct io_kiocb *req, long res)
1713{
1714	req_set_fail(req);
1715	io_put_req(req);
1716	io_req_complete_post(req, res, 0);
1717}
1718
1719/*
1720 * Don't initialise the fields below on every allocation, but do that in
1721 * advance and keep them valid across allocations.
1722 */
1723static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
1724{
1725	req->ctx = ctx;
1726	req->link = NULL;
1727	req->async_data = NULL;
1728	/* not necessary, but safer to zero */
1729	req->result = 0;
1730}
1731
1732static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
1733					struct io_submit_state *state)
1734{
1735	spin_lock_irq(&ctx->completion_lock);
1736	list_splice_init(&ctx->locked_free_list, &state->free_list);
1737	ctx->locked_free_nr = 0;
1738	spin_unlock_irq(&ctx->completion_lock);
1739}
1740
1741/* Returns true IFF there are requests in the cache */
1742static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
1743{
1744	struct io_submit_state *state = &ctx->submit_state;
1745	int nr;
1746
1747	/*
1748	 * If we have more than a batch's worth of requests in our IRQ side
1749	 * locked cache, grab the lock and move them over to our submission
1750	 * side cache.
1751	 */
1752	if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
1753		io_flush_cached_locked_reqs(ctx, state);
1754
1755	nr = state->free_reqs;
1756	while (!list_empty(&state->free_list)) {
1757		struct io_kiocb *req = list_first_entry(&state->free_list,
1758					struct io_kiocb, inflight_entry);
1759
1760		list_del(&req->inflight_entry);
1761		state->reqs[nr++] = req;
1762		if (nr == ARRAY_SIZE(state->reqs))
1763			break;
1764	}
1765
1766	state->free_reqs = nr;
1767	return nr != 0;
1768}
1769
1770static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
1771{
1772	struct io_submit_state *state = &ctx->submit_state;
1773	gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1774	int ret, i;
1775
1776	BUILD_BUG_ON(ARRAY_SIZE(state->reqs) < IO_REQ_ALLOC_BATCH);
1777
1778	if (likely(state->free_reqs || io_flush_cached_reqs(ctx)))
1779		goto got_req;
1780
1781	ret = kmem_cache_alloc_bulk(req_cachep, gfp, IO_REQ_ALLOC_BATCH,
1782				    state->reqs);
1783
1784	/*
1785	 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1786	 * retry single alloc to be on the safe side.
1787	 */
1788	if (unlikely(ret <= 0)) {
1789		state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1790		if (!state->reqs[0])
1791			return NULL;
1792		ret = 1;
1793	}
1794
1795	for (i = 0; i < ret; i++)
1796		io_preinit_req(state->reqs[i], ctx);
1797	state->free_reqs = ret;
1798got_req:
1799	state->free_reqs--;
1800	return state->reqs[state->free_reqs];
1801}
1802
1803static inline void io_put_file(struct file *file)
1804{
1805	if (file)
1806		fput(file);
1807}
1808
1809static void io_dismantle_req(struct io_kiocb *req)
1810{
1811	unsigned int flags = req->flags;
1812
1813	if (io_req_needs_clean(req))
1814		io_clean_op(req);
1815	if (!(flags & REQ_F_FIXED_FILE))
1816		io_put_file(req->file);
1817	if (req->fixed_rsrc_refs)
1818		percpu_ref_put(req->fixed_rsrc_refs);
1819	if (req->async_data) {
1820		kfree(req->async_data);
1821		req->async_data = NULL;
1822	}
1823}
1824
1825static void __io_free_req(struct io_kiocb *req)
1826{
1827	struct io_ring_ctx *ctx = req->ctx;
1828	unsigned long flags;
1829
1830	io_dismantle_req(req);
1831	io_put_task(req->task, 1);
1832
1833	spin_lock_irqsave(&ctx->completion_lock, flags);
1834	list_add(&req->inflight_entry, &ctx->locked_free_list);
1835	ctx->locked_free_nr++;
1836	spin_unlock_irqrestore(&ctx->completion_lock, flags);
1837
1838	percpu_ref_put(&ctx->refs);
1839}
1840
1841static inline void io_remove_next_linked(struct io_kiocb *req)
1842{
1843	struct io_kiocb *nxt = req->link;
1844
1845	req->link = nxt->link;
1846	nxt->link = NULL;
1847}
1848
1849static bool io_kill_linked_timeout(struct io_kiocb *req)
1850	__must_hold(&req->ctx->completion_lock)
1851{
1852	struct io_kiocb *link = req->link;
1853
1854	/*
1855	 * Can happen if a linked timeout fired and link had been like
1856	 * req -> link t-out -> link t-out [-> ...]
1857	 */
1858	if (link && (link->flags & REQ_F_LTIMEOUT_ACTIVE)) {
1859		struct io_timeout_data *io = link->async_data;
1860
1861		io_remove_next_linked(req);
1862		link->timeout.head = NULL;
1863		if (hrtimer_try_to_cancel(&io->timer) != -1) {
1864			io_cqring_fill_event(link->ctx, link->user_data,
1865					     -ECANCELED, 0);
1866			io_put_req_deferred(link, 1);
1867			return true;
1868		}
1869	}
1870	return false;
1871}
1872
1873static void io_fail_links(struct io_kiocb *req)
1874	__must_hold(&req->ctx->completion_lock)
1875{
1876	struct io_kiocb *nxt, *link = req->link;
1877
1878	req->link = NULL;
1879	while (link) {
1880		nxt = link->link;
1881		link->link = NULL;
1882
1883		trace_io_uring_fail_link(req, link);
1884		io_cqring_fill_event(link->ctx, link->user_data, -ECANCELED, 0);
1885		io_put_req_deferred(link, 2);
1886		link = nxt;
1887	}
1888}
1889
1890static bool io_disarm_next(struct io_kiocb *req)
1891	__must_hold(&req->ctx->completion_lock)
1892{
1893	bool posted = false;
1894
1895	if (likely(req->flags & REQ_F_LINK_TIMEOUT))
1896		posted = io_kill_linked_timeout(req);
1897	if (unlikely((req->flags & REQ_F_FAIL) &&
1898		     !(req->flags & REQ_F_HARDLINK))) {
1899		posted |= (req->link != NULL);
1900		io_fail_links(req);
1901	}
1902	return posted;
1903}
1904
1905static struct io_kiocb *__io_req_find_next(struct io_kiocb *req)
1906{
1907	struct io_kiocb *nxt;
1908
1909	/*
1910	 * If LINK is set, we have dependent requests in this chain. If we
1911	 * didn't fail this request, queue the first one up, moving any other
1912	 * dependencies to the next request. In case of failure, fail the rest
1913	 * of the chain.
1914	 */
1915	if (req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_FAIL)) {
1916		struct io_ring_ctx *ctx = req->ctx;
1917		unsigned long flags;
1918		bool posted;
1919
1920		spin_lock_irqsave(&ctx->completion_lock, flags);
1921		posted = io_disarm_next(req);
1922		if (posted)
1923			io_commit_cqring(req->ctx);
1924		spin_unlock_irqrestore(&ctx->completion_lock, flags);
1925		if (posted)
1926			io_cqring_ev_posted(ctx);
1927	}
1928	nxt = req->link;
1929	req->link = NULL;
1930	return nxt;
1931}
1932
1933static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
1934{
1935	if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
1936		return NULL;
1937	return __io_req_find_next(req);
1938}
1939
1940static void ctx_flush_and_put(struct io_ring_ctx *ctx)
1941{
1942	if (!ctx)
1943		return;
1944	if (ctx->submit_state.compl_nr) {
1945		mutex_lock(&ctx->uring_lock);
1946		io_submit_flush_completions(ctx);
1947		mutex_unlock(&ctx->uring_lock);
1948	}
1949	percpu_ref_put(&ctx->refs);
1950}
1951
1952static void tctx_task_work(struct callback_head *cb)
1953{
1954	struct io_ring_ctx *ctx = NULL;
1955	struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
1956						  task_work);
1957
1958	while (1) {
1959		struct io_wq_work_node *node;
1960
1961		spin_lock_irq(&tctx->task_lock);
1962		node = tctx->task_list.first;
1963		INIT_WQ_LIST(&tctx->task_list);
1964		if (!node)
1965			tctx->task_running = false;
1966		spin_unlock_irq(&tctx->task_lock);
1967		if (!node)
1968			break;
1969
1970		do {
1971			struct io_wq_work_node *next = node->next;
1972			struct io_kiocb *req = container_of(node, struct io_kiocb,
1973							    io_task_work.node);
1974
1975			if (req->ctx != ctx) {
1976				ctx_flush_and_put(ctx);
1977				ctx = req->ctx;
1978				percpu_ref_get(&ctx->refs);
1979			}
1980			req->io_task_work.func(req);
1981			node = next;
1982		} while (node);
1983
1984		cond_resched();
1985	}
1986
1987	ctx_flush_and_put(ctx);
1988}
1989
1990static void io_req_task_work_add(struct io_kiocb *req)
1991{
1992	struct task_struct *tsk = req->task;
1993	struct io_uring_task *tctx = tsk->io_uring;
1994	enum task_work_notify_mode notify;
1995	struct io_wq_work_node *node;
1996	unsigned long flags;
1997	bool running;
1998
1999	WARN_ON_ONCE(!tctx);
2000
2001	spin_lock_irqsave(&tctx->task_lock, flags);
2002	wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
2003	running = tctx->task_running;
2004	if (!running)
2005		tctx->task_running = true;
2006	spin_unlock_irqrestore(&tctx->task_lock, flags);
2007
2008	/* task_work already pending, we're done */
2009	if (running)
2010		return;
2011
2012	/*
2013	 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2014	 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2015	 * processing task_work. There's no reliable way to tell if TWA_RESUME
2016	 * will do the job.
2017	 */
2018	notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
2019	if (!task_work_add(tsk, &tctx->task_work, notify)) {
2020		wake_up_process(tsk);
2021		return;
2022	}
2023
2024	spin_lock_irqsave(&tctx->task_lock, flags);
2025	tctx->task_running = false;
2026	node = tctx->task_list.first;
2027	INIT_WQ_LIST(&tctx->task_list);
2028	spin_unlock_irqrestore(&tctx->task_lock, flags);
2029
2030	while (node) {
2031		req = container_of(node, struct io_kiocb, io_task_work.node);
2032		node = node->next;
2033		if (llist_add(&req->io_task_work.fallback_node,
2034			      &req->ctx->fallback_llist))
2035			schedule_delayed_work(&req->ctx->fallback_work, 1);
2036	}
2037}
2038
2039static void io_req_task_cancel(struct io_kiocb *req)
2040{
2041	struct io_ring_ctx *ctx = req->ctx;
2042
2043	/* ctx is guaranteed to stay alive while we hold uring_lock */
2044	mutex_lock(&ctx->uring_lock);
2045	io_req_complete_failed(req, req->result);
2046	mutex_unlock(&ctx->uring_lock);
2047}
2048
2049static void io_req_task_submit(struct io_kiocb *req)
2050{
2051	struct io_ring_ctx *ctx = req->ctx;
2052
2053	/* ctx stays valid until unlock, even if we drop all ours ctx->refs */
2054	mutex_lock(&ctx->uring_lock);
2055	if (likely(!(req->task->flags & PF_EXITING)))
2056		__io_queue_sqe(req);
2057	else
2058		io_req_complete_failed(req, -EFAULT);
2059	mutex_unlock(&ctx->uring_lock);
2060}
2061
2062static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
2063{
2064	req->result = ret;
2065	req->io_task_work.func = io_req_task_cancel;
2066	io_req_task_work_add(req);
2067}
2068
2069static void io_req_task_queue(struct io_kiocb *req)
2070{
2071	req->io_task_work.func = io_req_task_submit;
2072	io_req_task_work_add(req);
2073}
2074
2075static void io_req_task_queue_reissue(struct io_kiocb *req)
2076{
2077	req->io_task_work.func = io_queue_async_work;
2078	io_req_task_work_add(req);
2079}
2080
2081static inline void io_queue_next(struct io_kiocb *req)
2082{
2083	struct io_kiocb *nxt = io_req_find_next(req);
2084
2085	if (nxt)
2086		io_req_task_queue(nxt);
2087}
2088
2089static void io_free_req(struct io_kiocb *req)
2090{
2091	io_queue_next(req);
2092	__io_free_req(req);
2093}
2094
2095struct req_batch {
2096	struct task_struct	*task;
2097	int			task_refs;
2098	int			ctx_refs;
2099};
2100
2101static inline void io_init_req_batch(struct req_batch *rb)
2102{
2103	rb->task_refs = 0;
2104	rb->ctx_refs = 0;
2105	rb->task = NULL;
2106}
2107
2108static void io_req_free_batch_finish(struct io_ring_ctx *ctx,
2109				     struct req_batch *rb)
2110{
2111	if (rb->ctx_refs)
2112		percpu_ref_put_many(&ctx->refs, rb->ctx_refs);
2113	if (rb->task == current)
2114		current->io_uring->cached_refs += rb->task_refs;
2115	else if (rb->task)
2116		io_put_task(rb->task, rb->task_refs);
2117}
2118
2119static void io_req_free_batch(struct req_batch *rb, struct io_kiocb *req,
2120			      struct io_submit_state *state)
2121{
2122	io_queue_next(req);
2123	io_dismantle_req(req);
2124
2125	if (req->task != rb->task) {
2126		if (rb->task)
2127			io_put_task(rb->task, rb->task_refs);
2128		rb->task = req->task;
2129		rb->task_refs = 0;
2130	}
2131	rb->task_refs++;
2132	rb->ctx_refs++;
2133
2134	if (state->free_reqs != ARRAY_SIZE(state->reqs))
2135		state->reqs[state->free_reqs++] = req;
2136	else
2137		list_add(&req->inflight_entry, &state->free_list);
2138}
2139
2140static void io_submit_flush_completions(struct io_ring_ctx *ctx)
2141	__must_hold(&req->ctx->uring_lock)
2142{
2143	struct io_submit_state *state = &ctx->submit_state;
2144	int i, nr = state->compl_nr;
2145	struct req_batch rb;
2146
2147	spin_lock_irq(&ctx->completion_lock);
2148	for (i = 0; i < nr; i++) {
2149		struct io_kiocb *req = state->compl_reqs[i];
2150
2151		__io_cqring_fill_event(ctx, req->user_data, req->result,
2152					req->compl.cflags);
2153	}
2154	io_commit_cqring(ctx);
2155	spin_unlock_irq(&ctx->completion_lock);
2156	io_cqring_ev_posted(ctx);
2157
2158	io_init_req_batch(&rb);
2159	for (i = 0; i < nr; i++) {
2160		struct io_kiocb *req = state->compl_reqs[i];
2161
2162		/* submission and completion refs */
2163		if (req_ref_sub_and_test(req, 2))
2164			io_req_free_batch(&rb, req, &ctx->submit_state);
2165	}
2166
2167	io_req_free_batch_finish(ctx, &rb);
2168	state->compl_nr = 0;
2169}
2170
2171/*
2172 * Drop reference to request, return next in chain (if there is one) if this
2173 * was the last reference to this request.
2174 */
2175static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
2176{
2177	struct io_kiocb *nxt = NULL;
2178
2179	if (req_ref_put_and_test(req)) {
2180		nxt = io_req_find_next(req);
2181		__io_free_req(req);
2182	}
2183	return nxt;
2184}
2185
2186static inline void io_put_req(struct io_kiocb *req)
2187{
2188	if (req_ref_put_and_test(req))
2189		io_free_req(req);
2190}
2191
2192static inline void io_put_req_deferred(struct io_kiocb *req, int refs)
2193{
2194	if (req_ref_sub_and_test(req, refs)) {
2195		req->io_task_work.func = io_free_req;
2196		io_req_task_work_add(req);
2197	}
2198}
2199
2200static unsigned io_cqring_events(struct io_ring_ctx *ctx)
2201{
2202	/* See comment at the top of this file */
2203	smp_rmb();
2204	return __io_cqring_events(ctx);
2205}
2206
2207static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2208{
2209	struct io_rings *rings = ctx->rings;
2210
2211	/* make sure SQ entry isn't read before tail */
2212	return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2213}
2214
2215static unsigned int io_put_kbuf(struct io_kiocb *req, struct io_buffer *kbuf)
2216{
2217	unsigned int cflags;
2218
2219	cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
2220	cflags |= IORING_CQE_F_BUFFER;
2221	req->flags &= ~REQ_F_BUFFER_SELECTED;
2222	kfree(kbuf);
2223	return cflags;
2224}
2225
2226static inline unsigned int io_put_rw_kbuf(struct io_kiocb *req)
2227{
2228	struct io_buffer *kbuf;
2229
2230	kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2231	return io_put_kbuf(req, kbuf);
2232}
2233
2234static inline bool io_run_task_work(void)
2235{
2236	if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
2237		__set_current_state(TASK_RUNNING);
2238		tracehook_notify_signal();
2239		return true;
2240	}
2241
2242	return false;
2243}
2244
2245/*
2246 * Find and free completed poll iocbs
2247 */
2248static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
2249			       struct list_head *done, bool resubmit)
2250{
2251	struct req_batch rb;
2252	struct io_kiocb *req;
2253
2254	/* order with ->result store in io_complete_rw_iopoll() */
2255	smp_rmb();
2256
2257	io_init_req_batch(&rb);
2258	while (!list_empty(done)) {
2259		int cflags = 0;
2260
2261		req = list_first_entry(done, struct io_kiocb, inflight_entry);
2262		list_del(&req->inflight_entry);
2263
2264		if (READ_ONCE(req->result) == -EAGAIN && resubmit &&
2265		    !(req->flags & REQ_F_DONT_REISSUE)) {
2266			req->iopoll_completed = 0;
2267			req_ref_get(req);
2268			io_req_task_queue_reissue(req);
2269			continue;
2270		}
2271
2272		if (req->flags & REQ_F_BUFFER_SELECTED)
2273			cflags = io_put_rw_kbuf(req);
2274
2275		__io_cqring_fill_event(ctx, req->user_data, req->result, cflags);
2276		(*nr_events)++;
2277
2278		if (req_ref_put_and_test(req))
2279			io_req_free_batch(&rb, req, &ctx->submit_state);
2280	}
2281
2282	io_commit_cqring(ctx);
2283	io_cqring_ev_posted_iopoll(ctx);
2284	io_req_free_batch_finish(ctx, &rb);
2285}
2286
2287static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
2288			long min, bool resubmit)
2289{
2290	struct io_kiocb *req, *tmp;
2291	LIST_HEAD(done);
2292	bool spin;
2293
2294	/*
2295	 * Only spin for completions if we don't have multiple devices hanging
2296	 * off our complete list, and we're under the requested amount.
2297	 */
2298	spin = !ctx->poll_multi_queue && *nr_events < min;
2299
2300	list_for_each_entry_safe(req, tmp, &ctx->iopoll_list, inflight_entry) {
2301		struct kiocb *kiocb = &req->rw.kiocb;
2302		int ret;
2303
2304		/*
2305		 * Move completed and retryable entries to our local lists.
2306		 * If we find a request that requires polling, break out
2307		 * and complete those lists first, if we have entries there.
2308		 */
2309		if (READ_ONCE(req->iopoll_completed)) {
2310			list_move_tail(&req->inflight_entry, &done);
2311			continue;
2312		}
2313		if (!list_empty(&done))
2314			break;
2315
2316		ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
2317		if (unlikely(ret < 0))
2318			return ret;
2319		else if (ret)
2320			spin = false;
2321
2322		/* iopoll may have completed current req */
2323		if (READ_ONCE(req->iopoll_completed))
2324			list_move_tail(&req->inflight_entry, &done);
2325	}
2326
2327	if (!list_empty(&done))
2328		io_iopoll_complete(ctx, nr_events, &done, resubmit);
2329
2330	return 0;
2331}
2332
2333/*
2334 * We can't just wait for polled events to come to us, we have to actively
2335 * find and complete them.
2336 */
2337static void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
2338{
2339	if (!(ctx->flags & IORING_SETUP_IOPOLL))
2340		return;
2341
2342	mutex_lock(&ctx->uring_lock);
2343	while (!list_empty(&ctx->iopoll_list)) {
2344		unsigned int nr_events = 0;
2345
2346		io_do_iopoll(ctx, &nr_events, 0, false);
2347
2348		/* let it sleep and repeat later if can't complete a request */
2349		if (nr_events == 0)
2350			break;
2351		/*
2352		 * Ensure we allow local-to-the-cpu processing to take place,
2353		 * in this case we need to ensure that we reap all events.
2354		 * Also let task_work, etc. to progress by releasing the mutex
2355		 */
2356		if (need_resched()) {
2357			mutex_unlock(&ctx->uring_lock);
2358			cond_resched();
2359			mutex_lock(&ctx->uring_lock);
2360		}
2361	}
2362	mutex_unlock(&ctx->uring_lock);
2363}
2364
2365static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
2366{
2367	unsigned int nr_events = 0;
2368	int ret = 0;
2369
2370	/*
2371	 * We disallow the app entering submit/complete with polling, but we
2372	 * still need to lock the ring to prevent racing with polled issue
2373	 * that got punted to a workqueue.
2374	 */
2375	mutex_lock(&ctx->uring_lock);
2376	/*
2377	 * Don't enter poll loop if we already have events pending.
2378	 * If we do, we can potentially be spinning for commands that
2379	 * already triggered a CQE (eg in error).
2380	 */
2381	if (test_bit(0, &ctx->check_cq_overflow))
2382		__io_cqring_overflow_flush(ctx, false);
2383	if (io_cqring_events(ctx))
2384		goto out;
2385	do {
2386		/*
2387		 * If a submit got punted to a workqueue, we can have the
2388		 * application entering polling for a command before it gets
2389		 * issued. That app will hold the uring_lock for the duration
2390		 * of the poll right here, so we need to take a breather every
2391		 * now and then to ensure that the issue has a chance to add
2392		 * the poll to the issued list. Otherwise we can spin here
2393		 * forever, while the workqueue is stuck trying to acquire the
2394		 * very same mutex.
2395		 */
2396		if (list_empty(&ctx->iopoll_list)) {
2397			u32 tail = ctx->cached_cq_tail;
2398
2399			mutex_unlock(&ctx->uring_lock);
2400			io_run_task_work();
2401			mutex_lock(&ctx->uring_lock);
2402
2403			/* some requests don't go through iopoll_list */
2404			if (tail != ctx->cached_cq_tail ||
2405			    list_empty(&ctx->iopoll_list))
2406				break;
2407		}
2408		ret = io_do_iopoll(ctx, &nr_events, min, true);
2409	} while (!ret && nr_events < min && !need_resched());
2410out:
2411	mutex_unlock(&ctx->uring_lock);
2412	return ret;
2413}
2414
2415static void kiocb_end_write(struct io_kiocb *req)
2416{
2417	/*
2418	 * Tell lockdep we inherited freeze protection from submission
2419	 * thread.
2420	 */
2421	if (req->flags & REQ_F_ISREG) {
2422		struct super_block *sb = file_inode(req->file)->i_sb;
2423
2424		__sb_writers_acquired(sb, SB_FREEZE_WRITE);
2425		sb_end_write(sb);
2426	}
2427}
2428
2429#ifdef CONFIG_BLOCK
2430static bool io_resubmit_prep(struct io_kiocb *req)
2431{
2432	struct io_async_rw *rw = req->async_data;
2433
2434	if (!rw)
2435		return !io_req_prep_async(req);
2436	/* may have left rw->iter inconsistent on -EIOCBQUEUED */
2437	iov_iter_revert(&rw->iter, req->result - iov_iter_count(&rw->iter));
2438	return true;
2439}
2440
2441static bool io_rw_should_reissue(struct io_kiocb *req)
2442{
2443	umode_t mode = file_inode(req->file)->i_mode;
2444	struct io_ring_ctx *ctx = req->ctx;
2445
2446	if (!S_ISBLK(mode) && !S_ISREG(mode))
2447		return false;
2448	if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2449	    !(ctx->flags & IORING_SETUP_IOPOLL)))
2450		return false;
2451	/*
2452	 * If ref is dying, we might be running poll reap from the exit work.
2453	 * Don't attempt to reissue from that path, just let it fail with
2454	 * -EAGAIN.
2455	 */
2456	if (percpu_ref_is_dying(&ctx->refs))
2457		return false;
2458	/*
2459	 * Play it safe and assume not safe to re-import and reissue if we're
2460	 * not in the original thread group (or in task context).
2461	 */
2462	if (!same_thread_group(req->task, current) || !in_task())
2463		return false;
2464	return true;
2465}
2466#else
2467static bool io_resubmit_prep(struct io_kiocb *req)
2468{
2469	return false;
2470}
2471static bool io_rw_should_reissue(struct io_kiocb *req)
2472{
2473	return false;
2474}
2475#endif
2476
2477static void __io_complete_rw(struct io_kiocb *req, long res, long res2,
2478			     unsigned int issue_flags)
2479{
2480	int cflags = 0;
2481
2482	if (req->rw.kiocb.ki_flags & IOCB_WRITE)
2483		kiocb_end_write(req);
2484	if (res != req->result) {
2485		if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2486		    io_rw_should_reissue(req)) {
2487			req->flags |= REQ_F_REISSUE;
2488			return;
2489		}
2490		req_set_fail(req);
2491	}
2492	if (req->flags & REQ_F_BUFFER_SELECTED)
2493		cflags = io_put_rw_kbuf(req);
2494	__io_req_complete(req, issue_flags, res, cflags);
2495}
2496
2497static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2498{
2499	struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2500
2501	__io_complete_rw(req, res, res2, 0);
2502}
2503
2504static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2505{
2506	struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2507
2508	if (kiocb->ki_flags & IOCB_WRITE)
2509		kiocb_end_write(req);
2510	if (unlikely(res != req->result)) {
2511		if (!(res == -EAGAIN && io_rw_should_reissue(req) &&
2512		    io_resubmit_prep(req))) {
2513			req_set_fail(req);
2514			req->flags |= REQ_F_DONT_REISSUE;
2515		}
2516	}
2517
2518	WRITE_ONCE(req->result, res);
2519	/* order with io_iopoll_complete() checking ->result */
2520	smp_wmb();
2521	WRITE_ONCE(req->iopoll_completed, 1);
2522}
2523
2524/*
2525 * After the iocb has been issued, it's safe to be found on the poll list.
2526 * Adding the kiocb to the list AFTER submission ensures that we don't
2527 * find it from a io_do_iopoll() thread before the issuer is done
2528 * accessing the kiocb cookie.
2529 */
2530static void io_iopoll_req_issued(struct io_kiocb *req)
2531{
2532	struct io_ring_ctx *ctx = req->ctx;
2533	const bool in_async = io_wq_current_is_worker();
2534
2535	/* workqueue context doesn't hold uring_lock, grab it now */
2536	if (unlikely(in_async))
2537		mutex_lock(&ctx->uring_lock);
2538
2539	/*
2540	 * Track whether we have multiple files in our lists. This will impact
2541	 * how we do polling eventually, not spinning if we're on potentially
2542	 * different devices.
2543	 */
2544	if (list_empty(&ctx->iopoll_list)) {
2545		ctx->poll_multi_queue = false;
2546	} else if (!ctx->poll_multi_queue) {
2547		struct io_kiocb *list_req;
2548		unsigned int queue_num0, queue_num1;
2549
2550		list_req = list_first_entry(&ctx->iopoll_list, struct io_kiocb,
2551						inflight_entry);
2552
2553		if (list_req->file != req->file) {
2554			ctx->poll_multi_queue = true;
2555		} else {
2556			queue_num0 = blk_qc_t_to_queue_num(list_req->rw.kiocb.ki_cookie);
2557			queue_num1 = blk_qc_t_to_queue_num(req->rw.kiocb.ki_cookie);
2558			if (queue_num0 != queue_num1)
2559				ctx->poll_multi_queue = true;
2560		}
2561	}
2562
2563	/*
2564	 * For fast devices, IO may have already completed. If it has, add
2565	 * it to the front so we find it first.
2566	 */
2567	if (READ_ONCE(req->iopoll_completed))
2568		list_add(&req->inflight_entry, &ctx->iopoll_list);
2569	else
2570		list_add_tail(&req->inflight_entry, &ctx->iopoll_list);
2571
2572	if (unlikely(in_async)) {
2573		/*
2574		 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
2575		 * in sq thread task context or in io worker task context. If
2576		 * current task context is sq thread, we don't need to check
2577		 * whether should wake up sq thread.
2578		 */
2579		if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2580		    wq_has_sleeper(&ctx->sq_data->wait))
2581			wake_up(&ctx->sq_data->wait);
2582
2583		mutex_unlock(&ctx->uring_lock);
2584	}
2585}
2586
2587static bool io_bdev_nowait(struct block_device *bdev)
2588{
2589	return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
2590}
2591
2592/*
2593 * If we tracked the file through the SCM inflight mechanism, we could support
2594 * any file. For now, just ensure that anything potentially problematic is done
2595 * inline.
2596 */
2597static bool __io_file_supports_nowait(struct file *file, int rw)
2598{
2599	umode_t mode = file_inode(file)->i_mode;
2600
2601	if (S_ISBLK(mode)) {
2602		if (IS_ENABLED(CONFIG_BLOCK) &&
2603		    io_bdev_nowait(I_BDEV(file->f_mapping->host)))
2604			return true;
2605		return false;
2606	}
2607	if (S_ISSOCK(mode))
2608		return true;
2609	if (S_ISREG(mode)) {
2610		if (IS_ENABLED(CONFIG_BLOCK) &&
2611		    io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2612		    file->f_op != &io_uring_fops)
2613			return true;
2614		return false;
2615	}
2616
2617	/* any ->read/write should understand O_NONBLOCK */
2618	if (file->f_flags & O_NONBLOCK)
2619		return true;
2620
2621	if (!(file->f_mode & FMODE_NOWAIT))
2622		return false;
2623
2624	if (rw == READ)
2625		return file->f_op->read_iter != NULL;
2626
2627	return file->f_op->write_iter != NULL;
2628}
2629
2630static bool io_file_supports_nowait(struct io_kiocb *req, int rw)
2631{
2632	if (rw == READ && (req->flags & REQ_F_NOWAIT_READ))
2633		return true;
2634	else if (rw == WRITE && (req->flags & REQ_F_NOWAIT_WRITE))
2635		return true;
2636
2637	return __io_file_supports_nowait(req->file, rw);
2638}
2639
2640static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2641{
2642	struct io_ring_ctx *ctx = req->ctx;
2643	struct kiocb *kiocb = &req->rw.kiocb;
2644	struct file *file = req->file;
2645	unsigned ioprio;
2646	int ret;
2647
2648	if (!io_req_ffs_set(req) && S_ISREG(file_inode(file)->i_mode))
2649		req->flags |= REQ_F_ISREG;
2650
2651	kiocb->ki_pos = READ_ONCE(sqe->off);
2652	if (kiocb->ki_pos == -1 && !(file->f_mode & FMODE_STREAM)) {
2653		req->flags |= REQ_F_CUR_POS;
2654		kiocb->ki_pos = file->f_pos;
2655	}
2656	kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2657	kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2658	ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2659	if (unlikely(ret))
2660		return ret;
2661
2662	/* don't allow async punt for O_NONBLOCK or RWF_NOWAIT */
2663	if ((kiocb->ki_flags & IOCB_NOWAIT) || (file->f_flags & O_NONBLOCK))
2664		req->flags |= REQ_F_NOWAIT;
2665
2666	ioprio = READ_ONCE(sqe->ioprio);
2667	if (ioprio) {
2668		ret = ioprio_check_cap(ioprio);
2669		if (ret)
2670			return ret;
2671
2672		kiocb->ki_ioprio = ioprio;
2673	} else
2674		kiocb->ki_ioprio = get_current_ioprio();
2675
2676	if (ctx->flags & IORING_SETUP_IOPOLL) {
2677		if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2678		    !kiocb->ki_filp->f_op->iopoll)
2679			return -EOPNOTSUPP;
2680
2681		kiocb->ki_flags |= IOCB_HIPRI;
2682		kiocb->ki_complete = io_complete_rw_iopoll;
2683		req->iopoll_completed = 0;
2684	} else {
2685		if (kiocb->ki_flags & IOCB_HIPRI)
2686			return -EINVAL;
2687		kiocb->ki_complete = io_complete_rw;
2688	}
2689
2690	if (req->opcode == IORING_OP_READ_FIXED ||
2691	    req->opcode == IORING_OP_WRITE_FIXED) {
2692		req->imu = NULL;
2693		io_req_set_rsrc_node(req);
2694	}
2695
2696	req->rw.addr = READ_ONCE(sqe->addr);
2697	req->rw.len = READ_ONCE(sqe->len);
2698	req->buf_index = READ_ONCE(sqe->buf_index);
2699	return 0;
2700}
2701
2702static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2703{
2704	switch (ret) {
2705	case -EIOCBQUEUED:
2706		break;
2707	case -ERESTARTSYS:
2708	case -ERESTARTNOINTR:
2709	case -ERESTARTNOHAND:
2710	case -ERESTART_RESTARTBLOCK:
2711		/*
2712		 * We can't just restart the syscall, since previously
2713		 * submitted sqes may already be in progress. Just fail this
2714		 * IO with EINTR.
2715		 */
2716		ret = -EINTR;
2717		fallthrough;
2718	default:
2719		kiocb->ki_complete(kiocb, ret, 0);
2720	}
2721}
2722
2723static void kiocb_done(struct kiocb *kiocb, ssize_t ret,
2724		       unsigned int issue_flags)
2725{
2726	struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2727	struct io_async_rw *io = req->async_data;
2728	bool check_reissue = kiocb->ki_complete == io_complete_rw;
2729
2730	/* add previously done IO, if any */
2731	if (io && io->bytes_done > 0) {
2732		if (ret < 0)
2733			ret = io->bytes_done;
2734		else
2735			ret += io->bytes_done;
2736	}
2737
2738	if (req->flags & REQ_F_CUR_POS)
2739		req->file->f_pos = kiocb->ki_pos;
2740	if (ret >= 0 && check_reissue)
2741		__io_complete_rw(req, ret, 0, issue_flags);
2742	else
2743		io_rw_done(kiocb, ret);
2744
2745	if (check_reissue && (req->flags & REQ_F_REISSUE)) {
2746		req->flags &= ~REQ_F_REISSUE;
2747		if (io_resubmit_prep(req)) {
2748			req_ref_get(req);
2749			io_req_task_queue_reissue(req);
2750		} else {
2751			int cflags = 0;
2752
2753			req_set_fail(req);
2754			if (req->flags & REQ_F_BUFFER_SELECTED)
2755				cflags = io_put_rw_kbuf(req);
2756			__io_req_complete(req, issue_flags, ret, cflags);
2757		}
2758	}
2759}
2760
2761static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
2762			     struct io_mapped_ubuf *imu)
2763{
2764	size_t len = req->rw.len;
2765	u64 buf_end, buf_addr = req->rw.addr;
2766	size_t offset;
2767
2768	if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
2769		return -EFAULT;
2770	/* not inside the mapped region */
2771	if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
2772		return -EFAULT;
2773
2774	/*
2775	 * May not be a start of buffer, set size appropriately
2776	 * and advance us to the beginning.
2777	 */
2778	offset = buf_addr - imu->ubuf;
2779	iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2780
2781	if (offset) {
2782		/*
2783		 * Don't use iov_iter_advance() here, as it's really slow for
2784		 * using the latter parts of a big fixed buffer - it iterates
2785		 * over each segment manually. We can cheat a bit here, because
2786		 * we know that:
2787		 *
2788		 * 1) it's a BVEC iter, we set it up
2789		 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2790		 *    first and last bvec
2791		 *
2792		 * So just find our index, and adjust the iterator afterwards.
2793		 * If the offset is within the first bvec (or the whole first
2794		 * bvec, just use iov_iter_advance(). This makes it easier
2795		 * since we can just skip the first segment, which may not
2796		 * be PAGE_SIZE aligned.
2797		 */
2798		const struct bio_vec *bvec = imu->bvec;
2799
2800		if (offset <= bvec->bv_len) {
2801			iov_iter_advance(iter, offset);
2802		} else {
2803			unsigned long seg_skip;
2804
2805			/* skip first vec */
2806			offset -= bvec->bv_len;
2807			seg_skip = 1 + (offset >> PAGE_SHIFT);
2808
2809			iter->bvec = bvec + seg_skip;
2810			iter->nr_segs -= seg_skip;
2811			iter->count -= bvec->bv_len + offset;
2812			iter->iov_offset = offset & ~PAGE_MASK;
2813		}
2814	}
2815
2816	return 0;
2817}
2818
2819static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
2820{
2821	struct io_ring_ctx *ctx = req->ctx;
2822	struct io_mapped_ubuf *imu = req->imu;
2823	u16 index, buf_index = req->buf_index;
2824
2825	if (likely(!imu)) {
2826		if (unlikely(buf_index >= ctx->nr_user_bufs))
2827			return -EFAULT;
2828		index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2829		imu = READ_ONCE(ctx->user_bufs[index]);
2830		req->imu = imu;
2831	}
2832	return __io_import_fixed(req, rw, iter, imu);
2833}
2834
2835static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2836{
2837	if (needs_lock)
2838		mutex_unlock(&ctx->uring_lock);
2839}
2840
2841static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2842{
2843	/*
2844	 * "Normal" inline submissions always hold the uring_lock, since we
2845	 * grab it from the system call. Same is true for the SQPOLL offload.
2846	 * The only exception is when we've detached the request and issue it
2847	 * from an async worker thread, grab the lock for that case.
2848	 */
2849	if (needs_lock)
2850		mutex_lock(&ctx->uring_lock);
2851}
2852
2853static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2854					  int bgid, struct io_buffer *kbuf,
2855					  bool needs_lock)
2856{
2857	struct io_buffer *head;
2858
2859	if (req->flags & REQ_F_BUFFER_SELECTED)
2860		return kbuf;
2861
2862	io_ring_submit_lock(req->ctx, needs_lock);
2863
2864	lockdep_assert_held(&req->ctx->uring_lock);
2865
2866	head = xa_load(&req->ctx->io_buffers, bgid);
2867	if (head) {
2868		if (!list_empty(&head->list)) {
2869			kbuf = list_last_entry(&head->list, struct io_buffer,
2870							list);
2871			list_del(&kbuf->list);
2872		} else {
2873			kbuf = head;
2874			xa_erase(&req->ctx->io_buffers, bgid);
2875		}
2876		if (*len > kbuf->len)
2877			*len = kbuf->len;
2878	} else {
2879		kbuf = ERR_PTR(-ENOBUFS);
2880	}
2881
2882	io_ring_submit_unlock(req->ctx, needs_lock);
2883
2884	return kbuf;
2885}
2886
2887static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2888					bool needs_lock)
2889{
2890	struct io_buffer *kbuf;
2891	u16 bgid;
2892
2893	kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2894	bgid = req->buf_index;
2895	kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2896	if (IS_ERR(kbuf))
2897		return kbuf;
2898	req->rw.addr = (u64) (unsigned long) kbuf;
2899	req->flags |= REQ_F_BUFFER_SELECTED;
2900	return u64_to_user_ptr(kbuf->addr);
2901}
2902
2903#ifdef CONFIG_COMPAT
2904static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2905				bool needs_lock)
2906{
2907	struct compat_iovec __user *uiov;
2908	compat_ssize_t clen;
2909	void __user *buf;
2910	ssize_t len;
2911
2912	uiov = u64_to_user_ptr(req->rw.addr);
2913	if (!access_ok(uiov, sizeof(*uiov)))
2914		return -EFAULT;
2915	if (__get_user(clen, &uiov->iov_len))
2916		return -EFAULT;
2917	if (clen < 0)
2918		return -EINVAL;
2919
2920	len = clen;
2921	buf = io_rw_buffer_select(req, &len, needs_lock);
2922	if (IS_ERR(buf))
2923		return PTR_ERR(buf);
2924	iov[0].iov_base = buf;
2925	iov[0].iov_len = (compat_size_t) len;
2926	return 0;
2927}
2928#endif
2929
2930static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2931				      bool needs_lock)
2932{
2933	struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2934	void __user *buf;
2935	ssize_t len;
2936
2937	if (copy_from_user(iov, uiov, sizeof(*uiov)))
2938		return -EFAULT;
2939
2940	len = iov[0].iov_len;
2941	if (len < 0)
2942		return -EINVAL;
2943	buf = io_rw_buffer_select(req, &len, needs_lock);
2944	if (IS_ERR(buf))
2945		return PTR_ERR(buf);
2946	iov[0].iov_base = buf;
2947	iov[0].iov_len = len;
2948	return 0;
2949}
2950
2951static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2952				    bool needs_lock)
2953{
2954	if (req->flags & REQ_F_BUFFER_SELECTED) {
2955		struct io_buffer *kbuf;
2956
2957		kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2958		iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2959		iov[0].iov_len = kbuf->len;
2960		return 0;
2961	}
2962	if (req->rw.len != 1)
2963		return -EINVAL;
2964
2965#ifdef CONFIG_COMPAT
2966	if (req->ctx->compat)
2967		return io_compat_import(req, iov, needs_lock);
2968#endif
2969
2970	return __io_iov_buffer_select(req, iov, needs_lock);
2971}
2972
2973static int io_import_iovec(int rw, struct io_kiocb *req, struct iovec **iovec,
2974			   struct iov_iter *iter, bool needs_lock)
2975{
2976	void __user *buf = u64_to_user_ptr(req->rw.addr);
2977	size_t sqe_len = req->rw.len;
2978	u8 opcode = req->opcode;
2979	ssize_t ret;
2980
2981	if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2982		*iovec = NULL;
2983		return io_import_fixed(req, rw, iter);
2984	}
2985
2986	/* buffer index only valid with fixed read/write, or buffer select  */
2987	if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2988		return -EINVAL;
2989
2990	if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2991		if (req->flags & REQ_F_BUFFER_SELECT) {
2992			buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2993			if (IS_ERR(buf))
2994				return PTR_ERR(buf);
2995			req->rw.len = sqe_len;
2996		}
2997
2998		ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2999		*iovec = NULL;
3000		return ret;
3001	}
3002
3003	if (req->flags & REQ_F_BUFFER_SELECT) {
3004		ret = io_iov_buffer_select(req, *iovec, needs_lock);
3005		if (!ret)
3006			iov_iter_init(iter, rw, *iovec, 1, (*iovec)->iov_len);
3007		*iovec = NULL;
3008		return ret;
3009	}
3010
3011	return __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter,
3012			      req->ctx->compat);
3013}
3014
3015static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3016{
3017	return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
3018}
3019
3020/*
3021 * For files that don't have ->read_iter() and ->write_iter(), handle them
3022 * by looping over ->read() or ->write() manually.
3023 */
3024static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
3025{
3026	struct kiocb *kiocb = &req->rw.kiocb;
3027	struct file *file = req->file;
3028	ssize_t ret = 0;
3029
3030	/*
3031	 * Don't support polled IO through this interface, and we can't
3032	 * support non-blocking either. For the latter, this just causes
3033	 * the kiocb to be handled from an async context.
3034	 */
3035	if (kiocb->ki_flags & IOCB_HIPRI)
3036		return -EOPNOTSUPP;
3037	if (kiocb->ki_flags & IOCB_NOWAIT)
3038		return -EAGAIN;
3039
3040	while (iov_iter_count(iter)) {
3041		struct iovec iovec;
3042		ssize_t nr;
3043
3044		if (!iov_iter_is_bvec(iter)) {
3045			iovec = iov_iter_iovec(iter);
3046		} else {
3047			iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3048			iovec.iov_len = req->rw.len;
3049		}
3050
3051		if (rw == READ) {
3052			nr = file->f_op->read(file, iovec.iov_base,
3053					      iovec.iov_len, io_kiocb_ppos(kiocb));
3054		} else {
3055			nr = file->f_op->write(file, iovec.iov_base,
3056					       iovec.iov_len, io_kiocb_ppos(kiocb));
3057		}
3058
3059		if (nr < 0) {
3060			if (!ret)
3061				ret = nr;
3062			break;
3063		}
3064		ret += nr;
3065		if (nr != iovec.iov_len)
3066			break;
3067		req->rw.len -= nr;
3068		req->rw.addr += nr;
3069		iov_iter_advance(iter, nr);
3070	}
3071
3072	return ret;
3073}
3074
3075static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3076			  const struct iovec *fast_iov, struct iov_iter *iter)
3077{
3078	struct io_async_rw *rw = req->async_data;
3079
3080	memcpy(&rw->iter, iter, sizeof(*iter));
3081	rw->free_iovec = iovec;
3082	rw->bytes_done = 0;
3083	/* can only be fixed buffers, no need to do anything */
3084	if (iov_iter_is_bvec(iter))
3085		return;
3086	if (!iovec) {
3087		unsigned iov_off = 0;
3088
3089		rw->iter.iov = rw->fast_iov;
3090		if (iter->iov != fast_iov) {
3091			iov_off = iter->iov - fast_iov;
3092			rw->iter.iov += iov_off;
3093		}
3094		if (rw->fast_iov != fast_iov)
3095			memcpy(rw->fast_iov + iov_off, fast_iov + iov_off,
3096			       sizeof(struct iovec) * iter->nr_segs);
3097	} else {
3098		req->flags |= REQ_F_NEED_CLEANUP;
3099	}
3100}
3101
3102static inline int io_alloc_async_data(struct io_kiocb *req)
3103{
3104	WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3105	req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
3106	return req->async_data == NULL;
3107}
3108
3109static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
3110			     const struct iovec *fast_iov,
3111			     struct iov_iter *iter, bool force)
3112{
3113	if (!force && !io_op_defs[req->opcode].needs_async_setup)
3114		return 0;
3115	if (!req->async_data) {
3116		if (io_alloc_async_data(req)) {
3117			kfree(iovec);
3118			return -ENOMEM;
3119		}
3120
3121		io_req_map_rw(req, iovec, fast_iov, iter);
3122	}
3123	return 0;
3124}
3125
3126static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
3127{
3128	struct io_async_rw *iorw = req->async_data;
3129	struct iovec *iov = iorw->fast_iov;
3130	int ret;
3131
3132	ret = io_import_iovec(rw, req, &iov, &iorw->iter, false);
3133	if (unlikely(ret < 0))
3134		return ret;
3135
3136	iorw->bytes_done = 0;
3137	iorw->free_iovec = iov;
3138	if (iov)
3139		req->flags |= REQ_F_NEED_CLEANUP;
3140	return 0;
3141}
3142
3143static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3144{
3145	if (unlikely(!(req->file->f_mode & FMODE_READ)))
3146		return -EBADF;
3147	return io_prep_rw(req, sqe);
3148}
3149
3150/*
3151 * This is our waitqueue callback handler, registered through lock_page_async()
3152 * when we initially tried to do the IO with the iocb armed our waitqueue.
3153 * This gets called when the page is unlocked, and we generally expect that to
3154 * happen when the page IO is completed and the page is now uptodate. This will
3155 * queue a task_work based retry of the operation, attempting to copy the data
3156 * again. If the latter fails because the page was NOT uptodate, then we will
3157 * do a thread based blocking retry of the operation. That's the unexpected
3158 * slow path.
3159 */
3160static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3161			     int sync, void *arg)
3162{
3163	struct wait_page_queue *wpq;
3164	struct io_kiocb *req = wait->private;
3165	struct wait_page_key *key = arg;
3166
3167	wpq = container_of(wait, struct wait_page_queue, wait);
3168
3169	if (!wake_page_match(wpq, key))
3170		return 0;
3171
3172	req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
3173	list_del_init(&wait->entry);
3174
3175	/* submit ref gets dropped, acquire a new one */
3176	req_ref_get(req);
3177	io_req_task_queue(req);
3178	return 1;
3179}
3180
3181/*
3182 * This controls whether a given IO request should be armed for async page
3183 * based retry. If we return false here, the request is handed to the async
3184 * worker threads for retry. If we're doing buffered reads on a regular file,
3185 * we prepare a private wait_page_queue entry and retry the operation. This
3186 * will either succeed because the page is now uptodate and unlocked, or it
3187 * will register a callback when the page is unlocked at IO completion. Through
3188 * that callback, io_uring uses task_work to setup a retry of the operation.
3189 * That retry will attempt the buffered read again. The retry will generally
3190 * succeed, or in rare cases where it fails, we then fall back to using the
3191 * async worker threads for a blocking retry.
3192 */
3193static bool io_rw_should_retry(struct io_kiocb *req)
3194{
3195	struct io_async_rw *rw = req->async_data;
3196	struct wait_page_queue *wait = &rw->wpq;
3197	struct kiocb *kiocb = &req->rw.kiocb;
3198
3199	/* never retry for NOWAIT, we just complete with -EAGAIN */
3200	if (req->flags & REQ_F_NOWAIT)
3201		return false;
3202
3203	/* Only for buffered IO */
3204	if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
3205		return false;
3206
3207	/*
3208	 * just use poll if we can, and don't attempt if the fs doesn't
3209	 * support callback based unlocks
3210	 */
3211	if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3212		return false;
3213
3214	wait->wait.func = io_async_buf_func;
3215	wait->wait.private = req;
3216	wait->wait.flags = 0;
3217	INIT_LIST_HEAD(&wait->wait.entry);
3218	kiocb->ki_flags |= IOCB_WAITQ;
3219	kiocb->ki_flags &= ~IOCB_NOWAIT;
3220	kiocb->ki_waitq = wait;
3221	return true;
3222}
3223
3224static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
3225{
3226	if (req->file->f_op->read_iter)
3227		return call_read_iter(req->file, &req->rw.kiocb, iter);
3228	else if (req->file->f_op->read)
3229		return loop_rw_iter(READ, req, iter);
3230	else
3231		return -EINVAL;
3232}
3233
3234static int io_read(struct io_kiocb *req, unsigned int issue_flags)
3235{
3236	struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3237	struct kiocb *kiocb = &req->rw.kiocb;
3238	struct iov_iter __iter, *iter = &__iter;
3239	struct io_async_rw *rw = req->async_data;
3240	ssize_t io_size, ret, ret2;
3241	bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3242
3243	if (rw) {
3244		iter = &rw->iter;
3245		iovec = NULL;
3246	} else {
3247		ret = io_import_iovec(READ, req, &iovec, iter, !force_nonblock);
3248		if (ret < 0)
3249			return ret;
3250	}
3251	io_size = iov_iter_count(iter);
3252	req->result = io_size;
3253
3254	/* Ensure we clear previously set non-block flag */
3255	if (!force_nonblock)
3256		kiocb->ki_flags &= ~IOCB_NOWAIT;
3257	else
3258		kiocb->ki_flags |= IOCB_NOWAIT;
3259
3260	/* If the file doesn't support async, just async punt */
3261	if (force_nonblock && !io_file_supports_nowait(req, READ)) {
3262		ret = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3263		return ret ?: -EAGAIN;
3264	}
3265
3266	ret = rw_verify_area(READ, req->file, io_kiocb_ppos(kiocb), io_size);
3267	if (unlikely(ret)) {
3268		kfree(iovec);
3269		return ret;
3270	}
3271
3272	ret = io_iter_do_read(req, iter);
3273
3274	if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
3275		req->flags &= ~REQ_F_REISSUE;
3276		/* IOPOLL retry should happen for io-wq threads */
3277		if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
3278			goto done;
3279		/* no retry on NONBLOCK nor RWF_NOWAIT */
3280		if (req->flags & REQ_F_NOWAIT)
3281			goto done;
3282		/* some cases will consume bytes even on error returns */
3283		iov_iter_revert(iter, io_size - iov_iter_count(iter));
3284		ret = 0;
3285	} else if (ret == -EIOCBQUEUED) {
3286		goto out_free;
3287	} else if (ret <= 0 || ret == io_size || !force_nonblock ||
3288		   (req->flags & REQ_F_NOWAIT) || !(req->flags & REQ_F_ISREG)) {
3289		/* read all, failed, already did sync or don't want to retry */
3290		goto done;
3291	}
3292
3293	ret2 = io_setup_async_rw(req, iovec, inline_vecs, iter, true);
3294	if (ret2)
3295		return ret2;
3296
3297	iovec = NULL;
3298	rw = req->async_data;
3299	/* now use our persistent iterator, if we aren't already */
3300	iter = &rw->iter;
3301
3302	do {
3303		io_size -= ret;
3304		rw->bytes_done += ret;
3305		/* if we can retry, do so with the callbacks armed */
3306		if (!io_rw_should_retry(req)) {
3307			kiocb->ki_flags &= ~IOCB_WAITQ;
3308			return -EAGAIN;
3309		}
3310
3311		/*
3312		 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3313		 * we get -EIOCBQUEUED, then we'll get a notification when the
3314		 * desired page gets unlocked. We can also get a partial read
3315		 * here, and if we do, then just retry at the new offset.
3316		 */
3317		ret = io_iter_do_read(req, iter);
3318		if (ret == -EIOCBQUEUED)
3319			return 0;
3320		/* we got some bytes, but not all. retry. */
3321		kiocb->ki_flags &= ~IOCB_WAITQ;
3322	} while (ret > 0 && ret < io_size);
3323done:
3324	kiocb_done(kiocb, ret, issue_flags);
3325out_free:
3326	/* it's faster to check here then delegate to kfree */
3327	if (iovec)
3328		kfree(iovec);
3329	return 0;
3330}
3331
3332static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3333{
3334	if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3335		return -EBADF;
3336	return io_prep_rw(req, sqe);
3337}
3338
3339static int io_write(struct io_kiocb *req, unsigned int issue_flags)
3340{
3341	struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3342	struct kiocb *kiocb = &req->rw.kiocb;
3343	struct iov_iter __iter, *iter = &__iter;
3344	struct io_async_rw *rw = req->async_data;
3345	ssize_t ret, ret2, io_size;
3346	bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3347
3348	if (rw) {
3349		iter = &rw->iter;
3350		iovec = NULL;
3351	} else {
3352		ret = io_import_iovec(WRITE, req, &iovec, iter, !force_nonblock);
3353		if (ret < 0)
3354			return ret;
3355	}
3356	io_size = iov_iter_count(iter);
3357	req->result = io_size;
3358
3359	/* Ensure we clear previously set non-block flag */
3360	if (!force_nonblock)
3361		kiocb->ki_flags &= ~IOCB_NOWAIT;
3362	else
3363		kiocb->ki_flags |= IOCB_NOWAIT;
3364
3365	/* If the file doesn't support async, just async punt */
3366	if (force_nonblock && !io_file_supports_nowait(req, WRITE))
3367		goto copy_iov;
3368
3369	/* file path doesn't support NOWAIT for non-direct_IO */
3370	if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3371	    (req->flags & REQ_F_ISREG))
3372		goto copy_iov;
3373
3374	ret = rw_verify_area(WRITE, req->file, io_kiocb_ppos(kiocb), io_size);
3375	if (unlikely(ret))
3376		goto out_free;
3377
3378	/*
3379	 * Open-code file_start_write here to grab freeze protection,
3380	 * which will be released by another thread in
3381	 * io_complete_rw().  Fool lockdep by telling it the lock got
3382	 * released so that it doesn't complain about the held lock when
3383	 * we return to userspace.
3384	 */
3385	if (req->flags & REQ_F_ISREG) {
3386		sb_start_write(file_inode(req->file)->i_sb);
3387		__sb_writers_release(file_inode(req->file)->i_sb,
3388					SB_FREEZE_WRITE);
3389	}
3390	kiocb->ki_flags |= IOCB_WRITE;
3391
3392	if (req->file->f_op->write_iter)
3393		ret2 = call_write_iter(req->file, kiocb, iter);
3394	else if (req->file->f_op->write)
3395		ret2 = loop_rw_iter(WRITE, req, iter);
3396	else
3397		ret2 = -EINVAL;
3398
3399	if (req->flags & REQ_F_REISSUE) {
3400		req->flags &= ~REQ_F_REISSUE;
3401		ret2 = -EAGAIN;
3402	}
3403
3404	/*
3405	 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3406	 * retry them without IOCB_NOWAIT.
3407	 */
3408	if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3409		ret2 = -EAGAIN;
3410	/* no retry on NONBLOCK nor RWF_NOWAIT */
3411	if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
3412		goto done;
3413	if (!force_nonblock || ret2 != -EAGAIN) {
3414		/* IOPOLL retry should happen for io-wq threads */
3415		if ((req->ctx->flags & IORING_SETUP_IOPOLL) && ret2 == -EAGAIN)
3416			goto copy_iov;
3417done:
3418		kiocb_done(kiocb, ret2, issue_flags);
3419	} else {
3420copy_iov:
3421		/* some cases will consume bytes even on error returns */
3422		iov_iter_revert(iter, io_size - iov_iter_count(iter));
3423		ret = io_setup_async_rw(req, iovec, inline_vecs, iter, false);
3424		return ret ?: -EAGAIN;
3425	}
3426out_free:
3427	/* it's reportedly faster than delegating the null check to kfree() */
3428	if (iovec)
3429		kfree(iovec);
3430	return ret;
3431}
3432
3433static int io_renameat_prep(struct io_kiocb *req,
3434			    const struct io_uring_sqe *sqe)
3435{
3436	struct io_rename *ren = &req->rename;
3437	const char __user *oldf, *newf;
3438
3439	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3440		return -EINVAL;
3441	if (sqe->ioprio || sqe->buf_index)
3442		return -EINVAL;
3443	if (unlikely(req->flags & REQ_F_FIXED_FILE))
3444		return -EBADF;
3445
3446	ren->old_dfd = READ_ONCE(sqe->fd);
3447	oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
3448	newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3449	ren->new_dfd = READ_ONCE(sqe->len);
3450	ren->flags = READ_ONCE(sqe->rename_flags);
3451
3452	ren->oldpath = getname(oldf);
3453	if (IS_ERR(ren->oldpath))
3454		return PTR_ERR(ren->oldpath);
3455
3456	ren->newpath = getname(newf);
3457	if (IS_ERR(ren->newpath)) {
3458		putname(ren->oldpath);
3459		return PTR_ERR(ren->newpath);
3460	}
3461
3462	req->flags |= REQ_F_NEED_CLEANUP;
3463	return 0;
3464}
3465
3466static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
3467{
3468	struct io_rename *ren = &req->rename;
3469	int ret;
3470
3471	if (issue_flags & IO_URING_F_NONBLOCK)
3472		return -EAGAIN;
3473
3474	ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
3475				ren->newpath, ren->flags);
3476
3477	req->flags &= ~REQ_F_NEED_CLEANUP;
3478	if (ret < 0)
3479		req_set_fail(req);
3480	io_req_complete(req, ret);
3481	return 0;
3482}
3483
3484static int io_unlinkat_prep(struct io_kiocb *req,
3485			    const struct io_uring_sqe *sqe)
3486{
3487	struct io_unlink *un = &req->unlink;
3488	const char __user *fname;
3489
3490	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3491		return -EINVAL;
3492	if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
3493		return -EINVAL;
3494	if (unlikely(req->flags & REQ_F_FIXED_FILE))
3495		return -EBADF;
3496
3497	un->dfd = READ_ONCE(sqe->fd);
3498
3499	un->flags = READ_ONCE(sqe->unlink_flags);
3500	if (un->flags & ~AT_REMOVEDIR)
3501		return -EINVAL;
3502
3503	fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3504	un->filename = getname(fname);
3505	if (IS_ERR(un->filename))
3506		return PTR_ERR(un->filename);
3507
3508	req->flags |= REQ_F_NEED_CLEANUP;
3509	return 0;
3510}
3511
3512static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
3513{
3514	struct io_unlink *un = &req->unlink;
3515	int ret;
3516
3517	if (issue_flags & IO_URING_F_NONBLOCK)
3518		return -EAGAIN;
3519
3520	if (un->flags & AT_REMOVEDIR)
3521		ret = do_rmdir(un->dfd, un->filename);
3522	else
3523		ret = do_unlinkat(un->dfd, un->filename);
3524
3525	req->flags &= ~REQ_F_NEED_CLEANUP;
3526	if (ret < 0)
3527		req_set_fail(req);
3528	io_req_complete(req, ret);
3529	return 0;
3530}
3531
3532static int io_shutdown_prep(struct io_kiocb *req,
3533			    const struct io_uring_sqe *sqe)
3534{
3535#if defined(CONFIG_NET)
3536	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3537		return -EINVAL;
3538	if (sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
3539	    sqe->buf_index)
3540		return -EINVAL;
3541
3542	req->shutdown.how = READ_ONCE(sqe->len);
3543	return 0;
3544#else
3545	return -EOPNOTSUPP;
3546#endif
3547}
3548
3549static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
3550{
3551#if defined(CONFIG_NET)
3552	struct socket *sock;
3553	int ret;
3554
3555	if (issue_flags & IO_URING_F_NONBLOCK)
3556		return -EAGAIN;
3557
3558	sock = sock_from_file(req->file);
3559	if (unlikely(!sock))
3560		return -ENOTSOCK;
3561
3562	ret = __sys_shutdown_sock(sock, req->shutdown.how);
3563	if (ret < 0)
3564		req_set_fail(req);
3565	io_req_complete(req, ret);
3566	return 0;
3567#else
3568	return -EOPNOTSUPP;
3569#endif
3570}
3571
3572static int __io_splice_prep(struct io_kiocb *req,
3573			    const struct io_uring_sqe *sqe)
3574{
3575	struct io_splice *sp = &req->splice;
3576	unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3577
3578	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3579		return -EINVAL;
3580
3581	sp->file_in = NULL;
3582	sp->len = READ_ONCE(sqe->len);
3583	sp->flags = READ_ONCE(sqe->splice_flags);
3584
3585	if (unlikely(sp->flags & ~valid_flags))
3586		return -EINVAL;
3587
3588	sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
3589				  (sp->flags & SPLICE_F_FD_IN_FIXED));
3590	if (!sp->file_in)
3591		return -EBADF;
3592	req->flags |= REQ_F_NEED_CLEANUP;
3593	return 0;
3594}
3595
3596static int io_tee_prep(struct io_kiocb *req,
3597		       const struct io_uring_sqe *sqe)
3598{
3599	if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3600		return -EINVAL;
3601	return __io_splice_prep(req, sqe);
3602}
3603
3604static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
3605{
3606	struct io_splice *sp = &req->splice;
3607	struct file *in = sp->file_in;
3608	struct file *out = sp->file_out;
3609	unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3610	long ret = 0;
3611
3612	if (issue_flags & IO_URING_F_NONBLOCK)
3613		return -EAGAIN;
3614	if (sp->len)
3615		ret = do_tee(in, out, sp->len, flags);
3616
3617	if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3618		io_put_file(in);
3619	req->flags &= ~REQ_F_NEED_CLEANUP;
3620
3621	if (ret != sp->len)
3622		req_set_fail(req);
3623	io_req_complete(req, ret);
3624	return 0;
3625}
3626
3627static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3628{
3629	struct io_splice *sp = &req->splice;
3630
3631	sp->off_in = READ_ONCE(sqe->splice_off_in);
3632	sp->off_out = READ_ONCE(sqe->off);
3633	return __io_splice_prep(req, sqe);
3634}
3635
3636static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
3637{
3638	struct io_splice *sp = &req->splice;
3639	struct file *in = sp->file_in;
3640	struct file *out = sp->file_out;
3641	unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3642	loff_t *poff_in, *poff_out;
3643	long ret = 0;
3644
3645	if (issue_flags & IO_URING_F_NONBLOCK)
3646		return -EAGAIN;
3647
3648	poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3649	poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3650
3651	if (sp->len)
3652		ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3653
3654	if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
3655		io_put_file(in);
3656	req->flags &= ~REQ_F_NEED_CLEANUP;
3657
3658	if (ret != sp->len)
3659		req_set_fail(req);
3660	io_req_complete(req, ret);
3661	return 0;
3662}
3663
3664/*
3665 * IORING_OP_NOP just posts a completion event, nothing else.
3666 */
3667static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
3668{
3669	struct io_ring_ctx *ctx = req->ctx;
3670
3671	if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3672		return -EINVAL;
3673
3674	__io_req_complete(req, issue_flags, 0, 0);
3675	return 0;
3676}
3677
3678static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3679{
3680	struct io_ring_ctx *ctx = req->ctx;
3681
3682	if (!req->file)
3683		return -EBADF;
3684
3685	if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3686		return -EINVAL;
3687	if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3688		return -EINVAL;
3689
3690	req->sync.flags = READ_ONCE(sqe->fsync_flags);
3691	if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3692		return -EINVAL;
3693
3694	req->sync.off = READ_ONCE(sqe->off);
3695	req->sync.len = READ_ONCE(sqe->len);
3696	return 0;
3697}
3698
3699static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
3700{
3701	loff_t end = req->sync.off + req->sync.len;
3702	int ret;
3703
3704	/* fsync always requires a blocking context */
3705	if (issue_flags & IO_URING_F_NONBLOCK)
3706		return -EAGAIN;
3707
3708	ret = vfs_fsync_range(req->file, req->sync.off,
3709				end > 0 ? end : LLONG_MAX,
3710				req->sync.flags & IORING_FSYNC_DATASYNC);
3711	if (ret < 0)
3712		req_set_fail(req);
3713	io_req_complete(req, ret);
3714	return 0;
3715}
3716
3717static int io_fallocate_prep(struct io_kiocb *req,
3718			     const struct io_uring_sqe *sqe)
3719{
3720	if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3721		return -EINVAL;
3722	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3723		return -EINVAL;
3724
3725	req->sync.off = READ_ONCE(sqe->off);
3726	req->sync.len = READ_ONCE(sqe->addr);
3727	req->sync.mode = READ_ONCE(sqe->len);
3728	return 0;
3729}
3730
3731static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
3732{
3733	int ret;
3734
3735	/* fallocate always requiring blocking context */
3736	if (issue_flags & IO_URING_F_NONBLOCK)
3737		return -EAGAIN;
3738	ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3739				req->sync.len);
3740	if (ret < 0)
3741		req_set_fail(req);
3742	io_req_complete(req, ret);
3743	return 0;
3744}
3745
3746static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3747{
3748	const char __user *fname;
3749	int ret;
3750
3751	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3752		return -EINVAL;
3753	if (unlikely(sqe->ioprio || sqe->buf_index))
3754		return -EINVAL;
3755	if (unlikely(req->flags & REQ_F_FIXED_FILE))
3756		return -EBADF;
3757
3758	/* open.how should be already initialised */
3759	if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3760		req->open.how.flags |= O_LARGEFILE;
3761
3762	req->open.dfd = READ_ONCE(sqe->fd);
3763	fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3764	req->open.filename = getname(fname);
3765	if (IS_ERR(req->open.filename)) {
3766		ret = PTR_ERR(req->open.filename);
3767		req->open.filename = NULL;
3768		return ret;
3769	}
3770	req->open.nofile = rlimit(RLIMIT_NOFILE);
3771	req->flags |= REQ_F_NEED_CLEANUP;
3772	return 0;
3773}
3774
3775static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3776{
3777	u64 mode = READ_ONCE(sqe->len);
3778	u64 flags = READ_ONCE(sqe->open_flags);
3779
3780	req->open.how = build_open_how(flags, mode);
3781	return __io_openat_prep(req, sqe);
3782}
3783
3784static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3785{
3786	struct open_how __user *how;
3787	size_t len;
3788	int ret;
3789
3790	how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3791	len = READ_ONCE(sqe->len);
3792	if (len < OPEN_HOW_SIZE_VER0)
3793		return -EINVAL;
3794
3795	ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3796					len);
3797	if (ret)
3798		return ret;
3799
3800	return __io_openat_prep(req, sqe);
3801}
3802
3803static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
3804{
3805	struct open_flags op;
3806	struct file *file;
3807	bool nonblock_set;
3808	bool resolve_nonblock;
3809	int ret;
3810
3811	ret = build_open_flags(&req->open.how, &op);
3812	if (ret)
3813		goto err;
3814	nonblock_set = op.open_flag & O_NONBLOCK;
3815	resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
3816	if (issue_flags & IO_URING_F_NONBLOCK) {
3817		/*
3818		 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
3819		 * it'll always -EAGAIN
3820		 */
3821		if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
3822			return -EAGAIN;
3823		op.lookup_flags |= LOOKUP_CACHED;
3824		op.open_flag |= O_NONBLOCK;
3825	}
3826
3827	ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3828	if (ret < 0)
3829		goto err;
3830
3831	file = do_filp_open(req->open.dfd, req->open.filename, &op);
3832	if (IS_ERR(file)) {
3833		/*
3834		 * We could hang on to this 'fd' on retrying, but seems like
3835		 * marginal gain for something that is now known to be a slower
3836		 * path. So just put it, and we'll get a new one when we retry.
3837		 */
3838		put_unused_fd(ret);
3839
3840		ret = PTR_ERR(file);
3841		/* only retry if RESOLVE_CACHED wasn't already set by application */
3842		if (ret == -EAGAIN &&
3843		    (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
3844			return -EAGAIN;
3845		goto err;
3846	}
3847
3848	if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
3849		file->f_flags &= ~O_NONBLOCK;
3850	fsnotify_open(file);
3851	fd_install(ret, file);
3852err:
3853	putname(req->open.filename);
3854	req->flags &= ~REQ_F_NEED_CLEANUP;
3855	if (ret < 0)
3856		req_set_fail(req);
3857	__io_req_complete(req, issue_flags, ret, 0);
3858	return 0;
3859}
3860
3861static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
3862{
3863	return io_openat2(req, issue_flags);
3864}
3865
3866static int io_remove_buffers_prep(struct io_kiocb *req,
3867				  const struct io_uring_sqe *sqe)
3868{
3869	struct io_provide_buf *p = &req->pbuf;
3870	u64 tmp;
3871
3872	if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3873		return -EINVAL;
3874
3875	tmp = READ_ONCE(sqe->fd);
3876	if (!tmp || tmp > USHRT_MAX)
3877		return -EINVAL;
3878
3879	memset(p, 0, sizeof(*p));
3880	p->nbufs = tmp;
3881	p->bgid = READ_ONCE(sqe->buf_group);
3882	return 0;
3883}
3884
3885static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3886			       int bgid, unsigned nbufs)
3887{
3888	unsigned i = 0;
3889
3890	/* shouldn't happen */
3891	if (!nbufs)
3892		return 0;
3893
3894	/* the head kbuf is the list itself */
3895	while (!list_empty(&buf->list)) {
3896		struct io_buffer *nxt;
3897
3898		nxt = list_first_entry(&buf->list, struct io_buffer, list);
3899		list_del(&nxt->list);
3900		kfree(nxt);
3901		if (++i == nbufs)
3902			return i;
3903	}
3904	i++;
3905	kfree(buf);
3906	xa_erase(&ctx->io_buffers, bgid);
3907
3908	return i;
3909}
3910
3911static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
3912{
3913	struct io_provide_buf *p = &req->pbuf;
3914	struct io_ring_ctx *ctx = req->ctx;
3915	struct io_buffer *head;
3916	int ret = 0;
3917	bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3918
3919	io_ring_submit_lock(ctx, !force_nonblock);
3920
3921	lockdep_assert_held(&ctx->uring_lock);
3922
3923	ret = -ENOENT;
3924	head = xa_load(&ctx->io_buffers, p->bgid);
3925	if (head)
3926		ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3927	if (ret < 0)
3928		req_set_fail(req);
3929
3930	/* complete before unlock, IOPOLL may need the lock */
3931	__io_req_complete(req, issue_flags, ret, 0);
3932	io_ring_submit_unlock(ctx, !force_nonblock);
3933	return 0;
3934}
3935
3936static int io_provide_buffers_prep(struct io_kiocb *req,
3937				   const struct io_uring_sqe *sqe)
3938{
3939	unsigned long size, tmp_check;
3940	struct io_provide_buf *p = &req->pbuf;
3941	u64 tmp;
3942
3943	if (sqe->ioprio || sqe->rw_flags)
3944		return -EINVAL;
3945
3946	tmp = READ_ONCE(sqe->fd);
3947	if (!tmp || tmp > USHRT_MAX)
3948		return -E2BIG;
3949	p->nbufs = tmp;
3950	p->addr = READ_ONCE(sqe->addr);
3951	p->len = READ_ONCE(sqe->len);
3952
3953	if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
3954				&size))
3955		return -EOVERFLOW;
3956	if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
3957		return -EOVERFLOW;
3958
3959	size = (unsigned long)p->len * p->nbufs;
3960	if (!access_ok(u64_to_user_ptr(p->addr), size))
3961		return -EFAULT;
3962
3963	p->bgid = READ_ONCE(sqe->buf_group);
3964	tmp = READ_ONCE(sqe->off);
3965	if (tmp > USHRT_MAX)
3966		return -E2BIG;
3967	p->bid = tmp;
3968	return 0;
3969}
3970
3971static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3972{
3973	struct io_buffer *buf;
3974	u64 addr = pbuf->addr;
3975	int i, bid = pbuf->bid;
3976
3977	for (i = 0; i < pbuf->nbufs; i++) {
3978		buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3979		if (!buf)
3980			break;
3981
3982		buf->addr = addr;
3983		buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
3984		buf->bid = bid;
3985		addr += pbuf->len;
3986		bid++;
3987		if (!*head) {
3988			INIT_LIST_HEAD(&buf->list);
3989			*head = buf;
3990		} else {
3991			list_add_tail(&buf->list, &(*head)->list);
3992		}
3993	}
3994
3995	return i ? i : -ENOMEM;
3996}
3997
3998static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
3999{
4000	struct io_provide_buf *p = &req->pbuf;
4001	struct io_ring_ctx *ctx = req->ctx;
4002	struct io_buffer *head, *list;
4003	int ret = 0;
4004	bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4005
4006	io_ring_submit_lock(ctx, !force_nonblock);
4007
4008	lockdep_assert_held(&ctx->uring_lock);
4009
4010	list = head = xa_load(&ctx->io_buffers, p->bgid);
4011
4012	ret = io_add_buffers(p, &head);
4013	if (ret >= 0 && !list) {
4014		ret = xa_insert(&ctx->io_buffers, p->bgid, head, GFP_KERNEL);
4015		if (ret < 0)
4016			__io_remove_buffers(ctx, head, p->bgid, -1U);
4017	}
4018	if (ret < 0)
4019		req_set_fail(req);
4020	/* complete before unlock, IOPOLL may need the lock */
4021	__io_req_complete(req, issue_flags, ret, 0);
4022	io_ring_submit_unlock(ctx, !force_nonblock);
4023	return 0;
4024}
4025
4026static int io_epoll_ctl_prep(struct io_kiocb *req,
4027			     const struct io_uring_sqe *sqe)
4028{
4029#if defined(CONFIG_EPOLL)
4030	if (sqe->ioprio || sqe->buf_index)
4031		return -EINVAL;
4032	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4033		return -EINVAL;
4034
4035	req->epoll.epfd = READ_ONCE(sqe->fd);
4036	req->epoll.op = READ_ONCE(sqe->len);
4037	req->epoll.fd = READ_ONCE(sqe->off);
4038
4039	if (ep_op_has_event(req->epoll.op)) {
4040		struct epoll_event __user *ev;
4041
4042		ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4043		if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4044			return -EFAULT;
4045	}
4046
4047	return 0;
4048#else
4049	return -EOPNOTSUPP;
4050#endif
4051}
4052
4053static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
4054{
4055#if defined(CONFIG_EPOLL)
4056	struct io_epoll *ie = &req->epoll;
4057	int ret;
4058	bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4059
4060	ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4061	if (force_nonblock && ret == -EAGAIN)
4062		return -EAGAIN;
4063
4064	if (ret < 0)
4065		req_set_fail(req);
4066	__io_req_complete(req, issue_flags, ret, 0);
4067	return 0;
4068#else
4069	return -EOPNOTSUPP;
4070#endif
4071}
4072
4073static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4074{
4075#if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4076	if (sqe->ioprio || sqe->buf_index || sqe->off)
4077		return -EINVAL;
4078	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4079		return -EINVAL;
4080
4081	req->madvise.addr = READ_ONCE(sqe->addr);
4082	req->madvise.len = READ_ONCE(sqe->len);
4083	req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4084	return 0;
4085#else
4086	return -EOPNOTSUPP;
4087#endif
4088}
4089
4090static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
4091{
4092#if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4093	struct io_madvise *ma = &req->madvise;
4094	int ret;
4095
4096	if (issue_flags & IO_URING_F_NONBLOCK)
4097		return -EAGAIN;
4098
4099	ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
4100	if (ret < 0)
4101		req_set_fail(req);
4102	io_req_complete(req, ret);
4103	return 0;
4104#else
4105	return -EOPNOTSUPP;
4106#endif
4107}
4108
4109static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4110{
4111	if (sqe->ioprio || sqe->buf_index || sqe->addr)
4112		return -EINVAL;
4113	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4114		return -EINVAL;
4115
4116	req->fadvise.offset = READ_ONCE(sqe->off);
4117	req->fadvise.len = READ_ONCE(sqe->len);
4118	req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4119	return 0;
4120}
4121
4122static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4123{
4124	struct io_fadvise *fa = &req->fadvise;
4125	int ret;
4126
4127	if (issue_flags & IO_URING_F_NONBLOCK) {
4128		switch (fa->advice) {
4129		case POSIX_FADV_NORMAL:
4130		case POSIX_FADV_RANDOM:
4131		case POSIX_FADV_SEQUENTIAL:
4132			break;
4133		default:
4134			return -EAGAIN;
4135		}
4136	}
4137
4138	ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
4139	if (ret < 0)
4140		req_set_fail(req);
4141	__io_req_complete(req, issue_flags, ret, 0);
4142	return 0;
4143}
4144
4145static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4146{
4147	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4148		return -EINVAL;
4149	if (sqe->ioprio || sqe->buf_index)
4150		return -EINVAL;
4151	if (req->flags & REQ_F_FIXED_FILE)
4152		return -EBADF;
4153
4154	req->statx.dfd = READ_ONCE(sqe->fd);
4155	req->statx.mask = READ_ONCE(sqe->len);
4156	req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
4157	req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4158	req->statx.flags = READ_ONCE(sqe->statx_flags);
4159
4160	return 0;
4161}
4162
4163static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
4164{
4165	struct io_statx *ctx = &req->statx;
4166	int ret;
4167
4168	if (issue_flags & IO_URING_F_NONBLOCK)
4169		return -EAGAIN;
4170
4171	ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
4172		       ctx->buffer);
4173
4174	if (ret < 0)
4175		req_set_fail(req);
4176	io_req_complete(req, ret);
4177	return 0;
4178}
4179
4180static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4181{
4182	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4183		return -EINVAL;
4184	if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
4185	    sqe->rw_flags || sqe->buf_index)
4186		return -EINVAL;
4187	if (req->flags & REQ_F_FIXED_FILE)
4188		return -EBADF;
4189
4190	req->close.fd = READ_ONCE(sqe->fd);
4191	return 0;
4192}
4193
4194static int io_close(struct io_kiocb *req, unsigned int issue_flags)
4195{
4196	struct files_struct *files = current->files;
4197	struct io_close *close = &req->close;
4198	struct fdtable *fdt;
4199	struct file *file = NULL;
4200	int ret = -EBADF;
4201
4202	spin_lock(&files->file_lock);
4203	fdt = files_fdtable(files);
4204	if (close->fd >= fdt->max_fds) {
4205		spin_unlock(&files->file_lock);
4206		goto err;
4207	}
4208	file = fdt->fd[close->fd];
4209	if (!file || file->f_op == &io_uring_fops) {
4210		spin_unlock(&files->file_lock);
4211		file = NULL;
4212		goto err;
4213	}
4214
4215	/* if the file has a flush method, be safe and punt to async */
4216	if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
4217		spin_unlock(&files->file_lock);
4218		return -EAGAIN;
4219	}
4220
4221	ret = __close_fd_get_file(close->fd, &file);
4222	spin_unlock(&files->file_lock);
4223	if (ret < 0) {
4224		if (ret == -ENOENT)
4225			ret = -EBADF;
4226		goto err;
4227	}
4228
4229	/* No ->flush() or already async, safely close from here */
4230	ret = filp_close(file, current->files);
4231err:
4232	if (ret < 0)
4233		req_set_fail(req);
4234	if (file)
4235		fput(file);
4236	__io_req_complete(req, issue_flags, ret, 0);
4237	return 0;
4238}
4239
4240static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4241{
4242	struct io_ring_ctx *ctx = req->ctx;
4243
4244	if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4245		return -EINVAL;
4246	if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
4247		return -EINVAL;
4248
4249	req->sync.off = READ_ONCE(sqe->off);
4250	req->sync.len = READ_ONCE(sqe->len);
4251	req->sync.flags = READ_ONCE(sqe->sync_range_flags);
4252	return 0;
4253}
4254
4255static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
4256{
4257	int ret;
4258
4259	/* sync_file_range always requires a blocking context */
4260	if (issue_flags & IO_URING_F_NONBLOCK)
4261		return -EAGAIN;
4262
4263	ret = sync_file_range(req->file, req->sync.off, req->sync.len,
4264				req->sync.flags);
4265	if (ret < 0)
4266		req_set_fail(req);
4267	io_req_complete(req, ret);
4268	return 0;
4269}
4270
4271#if defined(CONFIG_NET)
4272static int io_setup_async_msg(struct io_kiocb *req,
4273			      struct io_async_msghdr *kmsg)
4274{
4275	struct io_async_msghdr *async_msg = req->async_data;
4276
4277	if (async_msg)
4278		return -EAGAIN;
4279	if (io_alloc_async_data(req)) {
4280		kfree(kmsg->free_iov);
4281		return -ENOMEM;
4282	}
4283	async_msg = req->async_data;
4284	req->flags |= REQ_F_NEED_CLEANUP;
4285	memcpy(async_msg, kmsg, sizeof(*kmsg));
4286	async_msg->msg.msg_name = &async_msg->addr;
4287	/* if were using fast_iov, set it to the new one */
4288	if (!async_msg->free_iov)
4289		async_msg->msg.msg_iter.iov = async_msg->fast_iov;
4290
4291	return -EAGAIN;
4292}
4293
4294static int io_sendmsg_copy_hdr(struct io_kiocb *req,
4295			       struct io_async_msghdr *iomsg)
4296{
4297	iomsg->msg.msg_name = &iomsg->addr;
4298	iomsg->free_iov = iomsg->fast_iov;
4299	return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
4300				   req->sr_msg.msg_flags, &iomsg->free_iov);
4301}
4302
4303static int io_sendmsg_prep_async(struct io_kiocb *req)
4304{
4305	int ret;
4306
4307	ret = io_sendmsg_copy_hdr(req, req->async_data);
4308	if (!ret)
4309		req->flags |= REQ_F_NEED_CLEANUP;
4310	return ret;
4311}
4312
4313static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4314{
4315	struct io_sr_msg *sr = &req->sr_msg;
4316
4317	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4318		return -EINVAL;
4319
4320	sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4321	sr->len = READ_ONCE(sqe->len);
4322	sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4323	if (sr->msg_flags & MSG_DONTWAIT)
4324		req->flags |= REQ_F_NOWAIT;
4325
4326#ifdef CONFIG_COMPAT
4327	if (req->ctx->compat)
4328		sr->msg_flags |= MSG_CMSG_COMPAT;
4329#endif
4330	return 0;
4331}
4332
4333static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
4334{
4335	struct io_async_msghdr iomsg, *kmsg;
4336	struct socket *sock;
4337	unsigned flags;
4338	int min_ret = 0;
4339	int ret;
4340
4341	sock = sock_from_file(req->file);
4342	if (unlikely(!sock))
4343		return -ENOTSOCK;
4344
4345	kmsg = req->async_data;
4346	if (!kmsg) {
4347		ret = io_sendmsg_copy_hdr(req, &iomsg);
4348		if (ret)
4349			return ret;
4350		kmsg = &iomsg;
4351	}
4352
4353	flags = req->sr_msg.msg_flags;
4354	if (issue_flags & IO_URING_F_NONBLOCK)
4355		flags |= MSG_DONTWAIT;
4356	if (flags & MSG_WAITALL)
4357		min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4358
4359	ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
4360	if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4361		return io_setup_async_msg(req, kmsg);
4362	if (ret == -ERESTARTSYS)
4363		ret = -EINTR;
4364
4365	/* fast path, check for non-NULL to avoid function call */
4366	if (kmsg->free_iov)
4367		kfree(kmsg->free_iov);
4368	req->flags &= ~REQ_F_NEED_CLEANUP;
4369	if (ret < min_ret)
4370		req_set_fail(req);
4371	__io_req_complete(req, issue_flags, ret, 0);
4372	return 0;
4373}
4374
4375static int io_send(struct io_kiocb *req, unsigned int issue_flags)
4376{
4377	struct io_sr_msg *sr = &req->sr_msg;
4378	struct msghdr msg;
4379	struct iovec iov;
4380	struct socket *sock;
4381	unsigned flags;
4382	int min_ret = 0;
4383	int ret;
4384
4385	sock = sock_from_file(req->file);
4386	if (unlikely(!sock))
4387		return -ENOTSOCK;
4388
4389	ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
4390	if (unlikely(ret))
4391		return ret;
4392
4393	msg.msg_name = NULL;
4394	msg.msg_control = NULL;
4395	msg.msg_controllen = 0;
4396	msg.msg_namelen = 0;
4397
4398	flags = req->sr_msg.msg_flags;
4399	if (issue_flags & IO_URING_F_NONBLOCK)
4400		flags |= MSG_DONTWAIT;
4401	if (flags & MSG_WAITALL)
4402		min_ret = iov_iter_count(&msg.msg_iter);
4403
4404	msg.msg_flags = flags;
4405	ret = sock_sendmsg(sock, &msg);
4406	if ((issue_flags & IO_URING_F_NONBLOCK) && ret == -EAGAIN)
4407		return -EAGAIN;
4408	if (ret == -ERESTARTSYS)
4409		ret = -EINTR;
4410
4411	if (ret < min_ret)
4412		req_set_fail(req);
4413	__io_req_complete(req, issue_flags, ret, 0);
4414	return 0;
4415}
4416
4417static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
4418				 struct io_async_msghdr *iomsg)
4419{
4420	struct io_sr_msg *sr = &req->sr_msg;
4421	struct iovec __user *uiov;
4422	size_t iov_len;
4423	int ret;
4424
4425	ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
4426					&iomsg->uaddr, &uiov, &iov_len);
4427	if (ret)
4428		return ret;
4429
4430	if (req->flags & REQ_F_BUFFER_SELECT) {
4431		if (iov_len > 1)
4432			return -EINVAL;
4433		if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
4434			return -EFAULT;
4435		sr->len = iomsg->fast_iov[0].iov_len;
4436		iomsg->free_iov = NULL;
4437	} else {
4438		iomsg->free_iov = iomsg->fast_iov;
4439		ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
4440				     &iomsg->free_iov, &iomsg->msg.msg_iter,
4441				     false);
4442		if (ret > 0)
4443			ret = 0;
4444	}
4445
4446	return ret;
4447}
4448
4449#ifdef CONFIG_COMPAT
4450static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
4451					struct io_async_msghdr *iomsg)
4452{
4453	struct io_sr_msg *sr = &req->sr_msg;
4454	struct compat_iovec __user *uiov;
4455	compat_uptr_t ptr;
4456	compat_size_t len;
4457	int ret;
4458
4459	ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
4460				  &ptr, &len);
4461	if (ret)
4462		return ret;
4463
4464	uiov = compat_ptr(ptr);
4465	if (req->flags & REQ_F_BUFFER_SELECT) {
4466		compat_ssize_t clen;
4467
4468		if (len > 1)
4469			return -EINVAL;
4470		if (!access_ok(uiov, sizeof(*uiov)))
4471			return -EFAULT;
4472		if (__get_user(clen, &uiov->iov_len))
4473			return -EFAULT;
4474		if (clen < 0)
4475			return -EINVAL;
4476		sr->len = clen;
4477		iomsg->free_iov = NULL;
4478	} else {
4479		iomsg->free_iov = iomsg->fast_iov;
4480		ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
4481				   UIO_FASTIOV, &iomsg->free_iov,
4482				   &iomsg->msg.msg_iter, true);
4483		if (ret < 0)
4484			return ret;
4485	}
4486
4487	return 0;
4488}
4489#endif
4490
4491static int io_recvmsg_copy_hdr(struct io_kiocb *req,
4492			       struct io_async_msghdr *iomsg)
4493{
4494	iomsg->msg.msg_name = &iomsg->addr;
4495
4496#ifdef CONFIG_COMPAT
4497	if (req->ctx->compat)
4498		return __io_compat_recvmsg_copy_hdr(req, iomsg);
4499#endif
4500
4501	return __io_recvmsg_copy_hdr(req, iomsg);
4502}
4503
4504static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4505					       bool needs_lock)
4506{
4507	struct io_sr_msg *sr = &req->sr_msg;
4508	struct io_buffer *kbuf;
4509
4510	kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4511	if (IS_ERR(kbuf))
4512		return kbuf;
4513
4514	sr->kbuf = kbuf;
4515	req->flags |= REQ_F_BUFFER_SELECTED;
4516	return kbuf;
4517}
4518
4519static inline unsigned int io_put_recv_kbuf(struct io_kiocb *req)
4520{
4521	return io_put_kbuf(req, req->sr_msg.kbuf);
4522}
4523
4524static int io_recvmsg_prep_async(struct io_kiocb *req)
4525{
4526	int ret;
4527
4528	ret = io_recvmsg_copy_hdr(req, req->async_data);
4529	if (!ret)
4530		req->flags |= REQ_F_NEED_CLEANUP;
4531	return ret;
4532}
4533
4534static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4535{
4536	struct io_sr_msg *sr = &req->sr_msg;
4537
4538	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4539		return -EINVAL;
4540
4541	sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4542	sr->len = READ_ONCE(sqe->len);
4543	sr->bgid = READ_ONCE(sqe->buf_group);
4544	sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
4545	if (sr->msg_flags & MSG_DONTWAIT)
4546		req->flags |= REQ_F_NOWAIT;
4547
4548#ifdef CONFIG_COMPAT
4549	if (req->ctx->compat)
4550		sr->msg_flags |= MSG_CMSG_COMPAT;
4551#endif
4552	return 0;
4553}
4554
4555static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
4556{
4557	struct io_async_msghdr iomsg, *kmsg;
4558	struct socket *sock;
4559	struct io_buffer *kbuf;
4560	unsigned flags;
4561	int min_ret = 0;
4562	int ret, cflags = 0;
4563	bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4564
4565	sock = sock_from_file(req->file);
4566	if (unlikely(!sock))
4567		return -ENOTSOCK;
4568
4569	kmsg = req->async_data;
4570	if (!kmsg) {
4571		ret = io_recvmsg_copy_hdr(req, &iomsg);
4572		if (ret)
4573			return ret;
4574		kmsg = &iomsg;
4575	}
4576
4577	if (req->flags & REQ_F_BUFFER_SELECT) {
4578		kbuf = io_recv_buffer_select(req, !force_nonblock);
4579		if (IS_ERR(kbuf))
4580			return PTR_ERR(kbuf);
4581		kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4582		kmsg->fast_iov[0].iov_len = req->sr_msg.len;
4583		iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
4584				1, req->sr_msg.len);
4585	}
4586
4587	flags = req->sr_msg.msg_flags;
4588	if (force_nonblock)
4589		flags |= MSG_DONTWAIT;
4590	if (flags & MSG_WAITALL)
4591		min_ret = iov_iter_count(&kmsg->msg.msg_iter);
4592
4593	ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
4594					kmsg->uaddr, flags);
4595	if (force_nonblock && ret == -EAGAIN)
4596		return io_setup_async_msg(req, kmsg);
4597	if (ret == -ERESTARTSYS)
4598		ret = -EINTR;
4599
4600	if (req->flags & REQ_F_BUFFER_SELECTED)
4601		cflags = io_put_recv_kbuf(req);
4602	/* fast path, check for non-NULL to avoid function call */
4603	if (kmsg->free_iov)
4604		kfree(kmsg->free_iov);
4605	req->flags &= ~REQ_F_NEED_CLEANUP;
4606	if (ret < min_ret || ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4607		req_set_fail(req);
4608	__io_req_complete(req, issue_flags, ret, cflags);
4609	return 0;
4610}
4611
4612static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
4613{
4614	struct io_buffer *kbuf;
4615	struct io_sr_msg *sr = &req->sr_msg;
4616	struct msghdr msg;
4617	void __user *buf = sr->buf;
4618	struct socket *sock;
4619	struct iovec iov;
4620	unsigned flags;
4621	int min_ret = 0;
4622	int ret, cflags = 0;
4623	bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4624
4625	sock = sock_from_file(req->file);
4626	if (unlikely(!sock))
4627		return -ENOTSOCK;
4628
4629	if (req->flags & REQ_F_BUFFER_SELECT) {
4630		kbuf = io_recv_buffer_select(req, !force_nonblock);
4631		if (IS_ERR(kbuf))
4632			return PTR_ERR(kbuf);
4633		buf = u64_to_user_ptr(kbuf->addr);
4634	}
4635
4636	ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
4637	if (unlikely(ret))
4638		goto out_free;
4639
4640	msg.msg_name = NULL;
4641	msg.msg_control = NULL;
4642	msg.msg_controllen = 0;
4643	msg.msg_namelen = 0;
4644	msg.msg_iocb = NULL;
4645	msg.msg_flags = 0;
4646
4647	flags = req->sr_msg.msg_flags;
4648	if (force_nonblock)
4649		flags |= MSG_DONTWAIT;
4650	if (flags & MSG_WAITALL)
4651		min_ret = iov_iter_count(&msg.msg_iter);
4652
4653	ret = sock_recvmsg(sock, &msg, flags);
4654	if (force_nonblock && ret == -EAGAIN)
4655		return -EAGAIN;
4656	if (ret == -ERESTARTSYS)
4657		ret = -EINTR;
4658out_free:
4659	if (req->flags & REQ_F_BUFFER_SELECTED)
4660		cflags = io_put_recv_kbuf(req);
4661	if (ret < min_ret || ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))))
4662		req_set_fail(req);
4663	__io_req_complete(req, issue_flags, ret, cflags);
4664	return 0;
4665}
4666
4667static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4668{
4669	struct io_accept *accept = &req->accept;
4670
4671	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4672		return -EINVAL;
4673	if (sqe->ioprio || sqe->len || sqe->buf_index)
4674		return -EINVAL;
4675
4676	accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4677	accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4678	accept->flags = READ_ONCE(sqe->accept_flags);
4679	accept->nofile = rlimit(RLIMIT_NOFILE);
4680	return 0;
4681}
4682
4683static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
4684{
4685	struct io_accept *accept = &req->accept;
4686	bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4687	unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4688	int ret;
4689
4690	if (req->file->f_flags & O_NONBLOCK)
4691		req->flags |= REQ_F_NOWAIT;
4692
4693	ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4694					accept->addr_len, accept->flags,
4695					accept->nofile);
4696	if (ret == -EAGAIN && force_nonblock)
4697		return -EAGAIN;
4698	if (ret < 0) {
4699		if (ret == -ERESTARTSYS)
4700			ret = -EINTR;
4701		req_set_fail(req);
4702	}
4703	__io_req_complete(req, issue_flags, ret, 0);
4704	return 0;
4705}
4706
4707static int io_connect_prep_async(struct io_kiocb *req)
4708{
4709	struct io_async_connect *io = req->async_data;
4710	struct io_connect *conn = &req->connect;
4711
4712	return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
4713}
4714
4715static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4716{
4717	struct io_connect *conn = &req->connect;
4718
4719	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4720		return -EINVAL;
4721	if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4722		return -EINVAL;
4723
4724	conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4725	conn->addr_len =  READ_ONCE(sqe->addr2);
4726	return 0;
4727}
4728
4729static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
4730{
4731	struct io_async_connect __io, *io;
4732	unsigned file_flags;
4733	int ret;
4734	bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
4735
4736	if (req->async_data) {
4737		io = req->async_data;
4738	} else {
4739		ret = move_addr_to_kernel(req->connect.addr,
4740						req->connect.addr_len,
4741						&__io.address);
4742		if (ret)
4743			goto out;
4744		io = &__io;
4745	}
4746
4747	file_flags = force_nonblock ? O_NONBLOCK : 0;
4748
4749	ret = __sys_connect_file(req->file, &io->address,
4750					req->connect.addr_len, file_flags);
4751	if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4752		if (req->async_data)
4753			return -EAGAIN;
4754		if (io_alloc_async_data(req)) {
4755			ret = -ENOMEM;
4756			goto out;
4757		}
4758		memcpy(req->async_data, &__io, sizeof(__io));
4759		return -EAGAIN;
4760	}
4761	if (ret == -ERESTARTSYS)
4762		ret = -EINTR;
4763out:
4764	if (ret < 0)
4765		req_set_fail(req);
4766	__io_req_complete(req, issue_flags, ret, 0);
4767	return 0;
4768}
4769#else /* !CONFIG_NET */
4770#define IO_NETOP_FN(op)							\
4771static int io_##op(struct io_kiocb *req, unsigned int issue_flags)	\
4772{									\
4773	return -EOPNOTSUPP;						\
4774}
4775
4776#define IO_NETOP_PREP(op)						\
4777IO_NETOP_FN(op)								\
4778static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
4779{									\
4780	return -EOPNOTSUPP;						\
4781}									\
4782
4783#define IO_NETOP_PREP_ASYNC(op)						\
4784IO_NETOP_PREP(op)							\
4785static int io_##op##_prep_async(struct io_kiocb *req)			\
4786{									\
4787	return -EOPNOTSUPP;						\
4788}
4789
4790IO_NETOP_PREP_ASYNC(sendmsg);
4791IO_NETOP_PREP_ASYNC(recvmsg);
4792IO_NETOP_PREP_ASYNC(connect);
4793IO_NETOP_PREP(accept);
4794IO_NETOP_FN(send);
4795IO_NETOP_FN(recv);
4796#endif /* CONFIG_NET */
4797
4798struct io_poll_table {
4799	struct poll_table_struct pt;
4800	struct io_kiocb *req;
4801	int nr_entries;
4802	int error;
4803};
4804
4805static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4806			   __poll_t mask, io_req_tw_func_t func)
4807{
4808	/* for instances that support it check for an event match first: */
4809	if (mask && !(mask & poll->events))
4810		return 0;
4811
4812	trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4813
4814	list_del_init(&poll->wait.entry);
4815
4816	req->result = mask;
4817	req->io_task_work.func = func;
4818
4819	/*
4820	 * If this fails, then the task is exiting. When a task exits, the
4821	 * work gets canceled, so just cancel this request as well instead
4822	 * of executing it. We can't safely execute it anyway, as we may not
4823	 * have the needed state needed for it anyway.
4824	 */
4825	io_req_task_work_add(req);
4826	return 1;
4827}
4828
4829static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4830	__acquires(&req->ctx->completion_lock)
4831{
4832	struct io_ring_ctx *ctx = req->ctx;
4833
4834	if (unlikely(req->task->flags & PF_EXITING))
4835		WRITE_ONCE(poll->canceled, true);
4836
4837	if (!req->result && !READ_ONCE(poll->canceled)) {
4838		struct poll_table_struct pt = { ._key = poll->events };
4839
4840		req->result = vfs_poll(req->file, &pt) & poll->events;
4841	}
4842
4843	spin_lock_irq(&ctx->completion_lock);
4844	if (!req->result && !READ_ONCE(poll->canceled)) {
4845		add_wait_queue(poll->head, &poll->wait);
4846		return true;
4847	}
4848
4849	return false;
4850}
4851
4852static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
4853{
4854	/* pure poll stashes this in ->async_data, poll driven retry elsewhere */
4855	if (req->opcode == IORING_OP_POLL_ADD)
4856		return req->async_data;
4857	return req->apoll->double_poll;
4858}
4859
4860static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
4861{
4862	if (req->opcode == IORING_OP_POLL_ADD)
4863		return &req->poll;
4864	return &req->apoll->poll;
4865}
4866
4867static void io_poll_remove_double(struct io_kiocb *req)
4868	__must_hold(&req->ctx->completion_lock)
4869{
4870	struct io_poll_iocb *poll = io_poll_get_double(req);
4871
4872	lockdep_assert_held(&req->ctx->completion_lock);
4873
4874	if (poll && poll->head) {
4875		struct wait_queue_head *head = poll->head;
4876
4877		spin_lock(&head->lock);
4878		list_del_init(&poll->wait.entry);
4879		if (poll->wait.private)
4880			req_ref_put(req);
4881		poll->head = NULL;
4882		spin_unlock(&head->lock);
4883	}
4884}
4885
4886static bool io_poll_complete(struct io_kiocb *req, __poll_t mask)
4887	__must_hold(&req->ctx->completion_lock)
4888{
4889	struct io_ring_ctx *ctx = req->ctx;
4890	unsigned flags = IORING_CQE_F_MORE;
4891	int error;
4892
4893	if (READ_ONCE(req->poll.canceled)) {
4894		error = -ECANCELED;
4895		req->poll.events |= EPOLLONESHOT;
4896	} else {
4897		error = mangle_poll(mask);
4898	}
4899	if (req->poll.events & EPOLLONESHOT)
4900		flags = 0;
4901	if (!io_cqring_fill_event(ctx, req->user_data, error, flags)) {
4902		req->poll.done = true;
4903		flags = 0;
4904	}
4905	if (flags & IORING_CQE_F_MORE)
4906		ctx->cq_extra++;
4907
4908	io_commit_cqring(ctx);
4909	return !(flags & IORING_CQE_F_MORE);
4910}
4911
4912static void io_poll_task_func(struct io_kiocb *req)
4913{
4914	struct io_ring_ctx *ctx = req->ctx;
4915	struct io_kiocb *nxt;
4916
4917	if (io_poll_rewait(req, &req->poll)) {
4918		spin_unlock_irq(&ctx->completion_lock);
4919	} else {
4920		bool done;
4921
4922		done = io_poll_complete(req, req->result);
4923		if (done) {
4924			io_poll_remove_double(req);
4925			hash_del(&req->hash_node);
4926		} else {
4927			req->result = 0;
4928			add_wait_queue(req->poll.head, &req->poll.wait);
4929		}
4930		spin_unlock_irq(&ctx->completion_lock);
4931		io_cqring_ev_posted(ctx);
4932
4933		if (done) {
4934			nxt = io_put_req_find_next(req);
4935			if (nxt)
4936				io_req_task_submit(nxt);
4937		}
4938	}
4939}
4940
4941static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4942			       int sync, void *key)
4943{
4944	struct io_kiocb *req = wait->private;
4945	struct io_poll_iocb *poll = io_poll_get_single(req);
4946	__poll_t mask = key_to_poll(key);
4947
4948	/* for instances that support it check for an event match first: */
4949	if (mask && !(mask & poll->events))
4950		return 0;
4951	if (!(poll->events & EPOLLONESHOT))
4952		return poll->wait.func(&poll->wait, mode, sync, key);
4953
4954	list_del_init(&wait->entry);
4955
4956	if (poll->head) {
4957		bool done;
4958
4959		spin_lock(&poll->head->lock);
4960		done = list_empty(&poll->wait.entry);
4961		if (!done)
4962			list_del_init(&poll->wait.entry);
4963		/* make sure double remove sees this as being gone */
4964		wait->private = NULL;
4965		spin_unlock(&poll->head->lock);
4966		if (!done) {
4967			/* use wait func handler, so it matches the rq type */
4968			poll->wait.func(&poll->wait, mode, sync, key);
4969		}
4970	}
4971	req_ref_put(req);
4972	return 1;
4973}
4974
4975static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4976			      wait_queue_func_t wake_func)
4977{
4978	poll->head = NULL;
4979	poll->done = false;
4980	poll->canceled = false;
4981#define IO_POLL_UNMASK	(EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
4982	/* mask in events that we always want/need */
4983	poll->events = events | IO_POLL_UNMASK;
4984	INIT_LIST_HEAD(&poll->wait.entry);
4985	init_waitqueue_func_entry(&poll->wait, wake_func);
4986}
4987
4988static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4989			    struct wait_queue_head *head,
4990			    struct io_poll_iocb **poll_ptr)
4991{
4992	struct io_kiocb *req = pt->req;
4993
4994	/*
4995	 * The file being polled uses multiple waitqueues for poll handling
4996	 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
4997	 * if this happens.
4998	 */
4999	if (unlikely(pt->nr_entries)) {
5000		struct io_poll_iocb *poll_one = poll;
5001
5002		/* already have a 2nd entry, fail a third attempt */
5003		if (*poll_ptr) {
5004			pt->error = -EINVAL;
5005			return;
5006		}
5007		/*
5008		 * Can't handle multishot for double wait for now, turn it
5009		 * into one-shot mode.
5010		 */
5011		if (!(poll_one->events & EPOLLONESHOT))
5012			poll_one->events |= EPOLLONESHOT;
5013		/* double add on the same waitqueue head, ignore */
5014		if (poll_one->head == head)
5015			return;
5016		poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
5017		if (!poll) {
5018			pt->error = -ENOMEM;
5019			return;
5020		}
5021		io_init_poll_iocb(poll, poll_one->events, io_poll_double_wake);
5022		req_ref_get(req);
5023		poll->wait.private = req;
5024		*poll_ptr = poll;
5025	}
5026
5027	pt->nr_entries++;
5028	poll->head = head;
5029
5030	if (poll->events & EPOLLEXCLUSIVE)
5031		add_wait_queue_exclusive(head, &poll->wait);
5032	else
5033		add_wait_queue(head, &poll->wait);
5034}
5035
5036static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
5037			       struct poll_table_struct *p)
5038{
5039	struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5040	struct async_poll *apoll = pt->req->apoll;
5041
5042	__io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
5043}
5044
5045static void io_async_task_func(struct io_kiocb *req)
5046{
5047	struct async_poll *apoll = req->apoll;
5048	struct io_ring_ctx *ctx = req->ctx;
5049
5050	trace_io_uring_task_run(req->ctx, req, req->opcode, req->user_data);
5051
5052	if (io_poll_rewait(req, &apoll->poll)) {
5053		spin_unlock_irq(&ctx->completion_lock);
5054		return;
5055	}
5056
5057	hash_del(&req->hash_node);
5058	io_poll_remove_double(req);
5059	spin_unlock_irq(&ctx->completion_lock);
5060
5061	if (!READ_ONCE(apoll->poll.canceled))
5062		io_req_task_submit(req);
5063	else
5064		io_req_complete_failed(req, -ECANCELED);
5065}
5066
5067static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5068			void *key)
5069{
5070	struct io_kiocb *req = wait->private;
5071	struct io_poll_iocb *poll = &req->apoll->poll;
5072
5073	trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
5074					key_to_poll(key));
5075
5076	return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
5077}
5078
5079static void io_poll_req_insert(struct io_kiocb *req)
5080{
5081	struct io_ring_ctx *ctx = req->ctx;
5082	struct hlist_head *list;
5083
5084	list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5085	hlist_add_head(&req->hash_node, list);
5086}
5087
5088static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
5089				      struct io_poll_iocb *poll,
5090				      struct io_poll_table *ipt, __poll_t mask,
5091				      wait_queue_func_t wake_func)
5092	__acquires(&ctx->completion_lock)
5093{
5094	struct io_ring_ctx *ctx = req->ctx;
5095	bool cancel = false;
5096
5097	INIT_HLIST_NODE(&req->hash_node);
5098	io_init_poll_iocb(poll, mask, wake_func);
5099	poll->file = req->file;
5100	poll->wait.private = req;
5101
5102	ipt->pt._key = mask;
5103	ipt->req = req;
5104	ipt->error = 0;
5105	ipt->nr_entries = 0;
5106
5107	mask = vfs_poll(req->file, &ipt->pt) & poll->events;
5108	if (unlikely(!ipt->nr_entries) && !ipt->error)
5109		ipt->error = -EINVAL;
5110
5111	spin_lock_irq(&ctx->completion_lock);
5112	if (ipt->error || (mask && (poll->events & EPOLLONESHOT)))
5113		io_poll_remove_double(req);
5114	if (likely(poll->head)) {
5115		spin_lock(&poll->head->lock);
5116		if (unlikely(list_empty(&poll->wait.entry))) {
5117			if (ipt->error)
5118				cancel = true;
5119			ipt->error = 0;
5120			mask = 0;
5121		}
5122		if ((mask && (poll->events & EPOLLONESHOT)) || ipt->error)
5123			list_del_init(&poll->wait.entry);
5124		else if (cancel)
5125			WRITE_ONCE(poll->canceled, true);
5126		else if (!poll->done) /* actually waiting for an event */
5127			io_poll_req_insert(req);
5128		spin_unlock(&poll->head->lock);
5129	}
5130
5131	return mask;
5132}
5133
5134enum {
5135	IO_APOLL_OK,
5136	IO_APOLL_ABORTED,
5137	IO_APOLL_READY
5138};
5139
5140static int io_arm_poll_handler(struct io_kiocb *req)
5141{
5142	const struct io_op_def *def = &io_op_defs[req->opcode];
5143	struct io_ring_ctx *ctx = req->ctx;
5144	struct async_poll *apoll;
5145	struct io_poll_table ipt;
5146	__poll_t ret, mask = EPOLLONESHOT | POLLERR | POLLPRI;
5147	int rw;
5148
5149	if (!req->file || !file_can_poll(req->file))
5150		return IO_APOLL_ABORTED;
5151	if (req->flags & REQ_F_POLLED)
5152		return IO_APOLL_ABORTED;
5153	if (!def->pollin && !def->pollout)
5154		return IO_APOLL_ABORTED;
5155
5156	if (def->pollin) {
5157		rw = READ;
5158		mask |= POLLIN | POLLRDNORM;
5159
5160		/* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
5161		if ((req->opcode == IORING_OP_RECVMSG) &&
5162		    (req->sr_msg.msg_flags & MSG_ERRQUEUE))
5163			mask &= ~POLLIN;
5164	} else {
5165		rw = WRITE;
5166		mask |= POLLOUT | POLLWRNORM;
5167	}
5168
5169	/* if we can't nonblock try, then no point in arming a poll handler */
5170	if (!io_file_supports_nowait(req, rw))
5171		return IO_APOLL_ABORTED;
5172
5173	apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
5174	if (unlikely(!apoll))
5175		return IO_APOLL_ABORTED;
5176	apoll->double_poll = NULL;
5177	req->apoll = apoll;
5178	req->flags |= REQ_F_POLLED;
5179	ipt.pt._qproc = io_async_queue_proc;
5180
5181	ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
5182					io_async_wake);
5183	if (ret || ipt.error) {
5184		spin_unlock_irq(&ctx->completion_lock);
5185		if (ret)
5186			return IO_APOLL_READY;
5187		return IO_APOLL_ABORTED;
5188	}
5189	spin_unlock_irq(&ctx->completion_lock);
5190	trace_io_uring_poll_arm(ctx, req, req->opcode, req->user_data,
5191				mask, apoll->poll.events);
5192	return IO_APOLL_OK;
5193}
5194
5195static bool __io_poll_remove_one(struct io_kiocb *req,
5196				 struct io_poll_iocb *poll, bool do_cancel)
5197	__must_hold(&req->ctx->completion_lock)
5198{
5199	bool do_complete = false;
5200
5201	if (!poll->head)
5202		return false;
5203	spin_lock(&poll->head->lock);
5204	if (do_cancel)
5205		WRITE_ONCE(poll->canceled, true);
5206	if (!list_empty(&poll->wait.entry)) {
5207		list_del_init(&poll->wait.entry);
5208		do_complete = true;
5209	}
5210	spin_unlock(&poll->head->lock);
5211	hash_del(&req->hash_node);
5212	return do_complete;
5213}
5214
5215static bool io_poll_remove_one(struct io_kiocb *req)
5216	__must_hold(&req->ctx->completion_lock)
5217{
5218	int refs;
5219	bool do_complete;
5220
5221	io_poll_remove_double(req);
5222	do_complete = __io_poll_remove_one(req, io_poll_get_single(req), true);
5223
5224	if (do_complete) {
5225		io_cqring_fill_event(req->ctx, req->user_data, -ECANCELED, 0);
5226		io_commit_cqring(req->ctx);
5227		req_set_fail(req);
5228
5229		/* non-poll requests have submit ref still */
5230		refs = 1 + (req->opcode != IORING_OP_POLL_ADD);
5231		io_put_req_deferred(req, refs);
5232	}
5233	return do_complete;
5234}
5235
5236/*
5237 * Returns true if we found and killed one or more poll requests
5238 */
5239static bool io_poll_remove_all(struct io_ring_ctx *ctx, struct task_struct *tsk,
5240			       bool cancel_all)
5241{
5242	struct hlist_node *tmp;
5243	struct io_kiocb *req;
5244	int posted = 0, i;
5245
5246	spin_lock_irq(&ctx->completion_lock);
5247	for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
5248		struct hlist_head *list;
5249
5250		list = &ctx->cancel_hash[i];
5251		hlist_for_each_entry_safe(req, tmp, list, hash_node) {
5252			if (io_match_task(req, tsk, cancel_all))
5253				posted += io_poll_remove_one(req);
5254		}
5255	}
5256	spin_unlock_irq(&ctx->completion_lock);
5257
5258	if (posted)
5259		io_cqring_ev_posted(ctx);
5260
5261	return posted != 0;
5262}
5263
5264static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
5265				     bool poll_only)
5266	__must_hold(&ctx->completion_lock)
5267{
5268	struct hlist_head *list;
5269	struct io_kiocb *req;
5270
5271	list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
5272	hlist_for_each_entry(req, list, hash_node) {
5273		if (sqe_addr != req->user_data)
5274			continue;
5275		if (poll_only && req->opcode != IORING_OP_POLL_ADD)
5276			continue;
5277		return req;
5278	}
5279	return NULL;
5280}
5281
5282static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
5283			  bool poll_only)
5284	__must_hold(&ctx->completion_lock)
5285{
5286	struct io_kiocb *req;
5287
5288	req = io_poll_find(ctx, sqe_addr, poll_only);
5289	if (!req)
5290		return -ENOENT;
5291	if (io_poll_remove_one(req))
5292		return 0;
5293
5294	return -EALREADY;
5295}
5296
5297static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
5298				     unsigned int flags)
5299{
5300	u32 events;
5301
5302	events = READ_ONCE(sqe->poll32_events);
5303#ifdef __BIG_ENDIAN
5304	events = swahw32(events);
5305#endif
5306	if (!(flags & IORING_POLL_ADD_MULTI))
5307		events |= EPOLLONESHOT;
5308	return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
5309}
5310
5311static int io_poll_update_prep(struct io_kiocb *req,
5312			       const struct io_uring_sqe *sqe)
5313{
5314	struct io_poll_update *upd = &req->poll_update;
5315	u32 flags;
5316
5317	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5318		return -EINVAL;
5319	if (sqe->ioprio || sqe->buf_index)
5320		return -EINVAL;
5321	flags = READ_ONCE(sqe->len);
5322	if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
5323		      IORING_POLL_ADD_MULTI))
5324		return -EINVAL;
5325	/* meaningless without update */
5326	if (flags == IORING_POLL_ADD_MULTI)
5327		return -EINVAL;
5328
5329	upd->old_user_data = READ_ONCE(sqe->addr);
5330	upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
5331	upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
5332
5333	upd->new_user_data = READ_ONCE(sqe->off);
5334	if (!upd->update_user_data && upd->new_user_data)
5335		return -EINVAL;
5336	if (upd->update_events)
5337		upd->events = io_poll_parse_events(sqe, flags);
5338	else if (sqe->poll32_events)
5339		return -EINVAL;
5340
5341	return 0;
5342}
5343
5344static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
5345			void *key)
5346{
5347	struct io_kiocb *req = wait->private;
5348	struct io_poll_iocb *poll = &req->poll;
5349
5350	return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
5351}
5352
5353static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
5354			       struct poll_table_struct *p)
5355{
5356	struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
5357
5358	__io_queue_proc(&pt->req->poll, pt, head, (struct io_poll_iocb **) &pt->req->async_data);
5359}
5360
5361static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5362{
5363	struct io_poll_iocb *poll = &req->poll;
5364	u32 flags;
5365
5366	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5367		return -EINVAL;
5368	if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
5369		return -EINVAL;
5370	flags = READ_ONCE(sqe->len);
5371	if (flags & ~IORING_POLL_ADD_MULTI)
5372		return -EINVAL;
5373
5374	poll->events = io_poll_parse_events(sqe, flags);
5375	return 0;
5376}
5377
5378static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
5379{
5380	struct io_poll_iocb *poll = &req->poll;
5381	struct io_ring_ctx *ctx = req->ctx;
5382	struct io_poll_table ipt;
5383	__poll_t mask;
5384
5385	ipt.pt._qproc = io_poll_queue_proc;
5386
5387	mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
5388					io_poll_wake);
5389
5390	if (mask) { /* no async, we'd stolen it */
5391		ipt.error = 0;
5392		io_poll_complete(req, mask);
5393	}
5394	spin_unlock_irq(&ctx->completion_lock);
5395
5396	if (mask) {
5397		io_cqring_ev_posted(ctx);
5398		if (poll->events & EPOLLONESHOT)
5399			io_put_req(req);
5400	}
5401	return ipt.error;
5402}
5403
5404static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
5405{
5406	struct io_ring_ctx *ctx = req->ctx;
5407	struct io_kiocb *preq;
5408	bool completing;
5409	int ret;
5410
5411	spin_lock_irq(&ctx->completion_lock);
5412	preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
5413	if (!preq) {
5414		ret = -ENOENT;
5415		goto err;
5416	}
5417
5418	if (!req->poll_update.update_events && !req->poll_update.update_user_data) {
5419		completing = true;
5420		ret = io_poll_remove_one(preq) ? 0 : -EALREADY;
5421		goto err;
5422	}
5423
5424	/*
5425	 * Don't allow racy completion with singleshot, as we cannot safely
5426	 * update those. For multishot, if we're racing with completion, just
5427	 * let completion re-add it.
5428	 */
5429	completing = !__io_poll_remove_one(preq, &preq->poll, false);
5430	if (completing && (preq->poll.events & EPOLLONESHOT)) {
5431		ret = -EALREADY;
5432		goto err;
5433	}
5434	/* we now have a detached poll request. reissue. */
5435	ret = 0;
5436err:
5437	if (ret < 0) {
5438		spin_unlock_irq(&ctx->completion_lock);
5439		req_set_fail(req);
5440		io_req_complete(req, ret);
5441		return 0;
5442	}
5443	/* only mask one event flags, keep behavior flags */
5444	if (req->poll_update.update_events) {
5445		preq->poll.events &= ~0xffff;
5446		preq->poll.events |= req->poll_update.events & 0xffff;
5447		preq->poll.events |= IO_POLL_UNMASK;
5448	}
5449	if (req->poll_update.update_user_data)
5450		preq->user_data = req->poll_update.new_user_data;
5451	spin_unlock_irq(&ctx->completion_lock);
5452
5453	/* complete update request, we're done with it */
5454	io_req_complete(req, ret);
5455
5456	if (!completing) {
5457		ret = io_poll_add(preq, issue_flags);
5458		if (ret < 0) {
5459			req_set_fail(preq);
5460			io_req_complete(preq, ret);
5461		}
5462	}
5463	return 0;
5464}
5465
5466static void io_req_task_timeout(struct io_kiocb *req)
5467{
5468	struct io_ring_ctx *ctx = req->ctx;
5469
5470	spin_lock_irq(&ctx->completion_lock);
5471	io_cqring_fill_event(ctx, req->user_data, -ETIME, 0);
5472	io_commit_cqring(ctx);
5473	spin_unlock_irq(&ctx->completion_lock);
5474
5475	io_cqring_ev_posted(ctx);
5476	req_set_fail(req);
5477	io_put_req(req);
5478}
5479
5480static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
5481{
5482	struct io_timeout_data *data = container_of(timer,
5483						struct io_timeout_data, timer);
5484	struct io_kiocb *req = data->req;
5485	struct io_ring_ctx *ctx = req->ctx;
5486	unsigned long flags;
5487
5488	spin_lock_irqsave(&ctx->timeout_lock, flags);
5489	list_del_init(&req->timeout.list);
5490	atomic_set(&req->ctx->cq_timeouts,
5491		atomic_read(&req->ctx->cq_timeouts) + 1);
5492	spin_unlock_irqrestore(&ctx->timeout_lock, flags);
5493
5494	req->io_task_work.func = io_req_task_timeout;
5495	io_req_task_work_add(req);
5496	return HRTIMER_NORESTART;
5497}
5498
5499static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
5500					   __u64 user_data)
5501	__must_hold(&ctx->timeout_lock)
5502{
5503	struct io_timeout_data *io;
5504	struct io_kiocb *req;
5505	bool found = false;
5506
5507	list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
5508		found = user_data == req->user_data;
5509		if (found)
5510			break;
5511	}
5512	if (!found)
5513		return ERR_PTR(-ENOENT);
5514
5515	io = req->async_data;
5516	if (hrtimer_try_to_cancel(&io->timer) == -1)
5517		return ERR_PTR(-EALREADY);
5518	list_del_init(&req->timeout.list);
5519	return req;
5520}
5521
5522static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
5523	__must_hold(&ctx->timeout_lock)
5524{
5525	struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5526
5527	if (IS_ERR(req))
5528		return PTR_ERR(req);
5529
5530	req_set_fail(req);
5531	io_cqring_fill_event(ctx, req->user_data, -ECANCELED, 0);
5532	io_put_req_deferred(req, 1);
5533	return 0;
5534}
5535
5536static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
5537			     struct timespec64 *ts, enum hrtimer_mode mode)
5538	__must_hold(&ctx->timeout_lock)
5539{
5540	struct io_kiocb *req = io_timeout_extract(ctx, user_data);
5541	struct io_timeout_data *data;
5542
5543	if (IS_ERR(req))
5544		return PTR_ERR(req);
5545
5546	req->timeout.off = 0; /* noseq */
5547	data = req->async_data;
5548	list_add_tail(&req->timeout.list, &ctx->timeout_list);
5549	hrtimer_init(&data->timer, CLOCK_MONOTONIC, mode);
5550	data->timer.function = io_timeout_fn;
5551	hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
5552	return 0;
5553}
5554
5555static int io_timeout_remove_prep(struct io_kiocb *req,
5556				  const struct io_uring_sqe *sqe)
5557{
5558	struct io_timeout_rem *tr = &req->timeout_rem;
5559
5560	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5561		return -EINVAL;
5562	if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
5563		return -EINVAL;
5564	if (sqe->ioprio || sqe->buf_index || sqe->len)
5565		return -EINVAL;
5566
5567	tr->addr = READ_ONCE(sqe->addr);
5568	tr->flags = READ_ONCE(sqe->timeout_flags);
5569	if (tr->flags & IORING_TIMEOUT_UPDATE) {
5570		if (tr->flags & ~(IORING_TIMEOUT_UPDATE|IORING_TIMEOUT_ABS))
5571			return -EINVAL;
5572		if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
5573			return -EFAULT;
5574	} else if (tr->flags) {
5575		/* timeout removal doesn't support flags */
5576		return -EINVAL;
5577	}
5578
5579	return 0;
5580}
5581
5582static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
5583{
5584	return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
5585					    : HRTIMER_MODE_REL;
5586}
5587
5588/*
5589 * Remove or update an existing timeout command
5590 */
5591static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
5592{
5593	struct io_timeout_rem *tr = &req->timeout_rem;
5594	struct io_ring_ctx *ctx = req->ctx;
5595	int ret;
5596
5597	spin_lock_irq(&ctx->timeout_lock);
5598	if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE))
5599		ret = io_timeout_cancel(ctx, tr->addr);
5600	else
5601		ret = io_timeout_update(ctx, tr->addr, &tr->ts,
5602					io_translate_timeout_mode(tr->flags));
5603	spin_unlock_irq(&ctx->timeout_lock);
5604
5605	spin_lock_irq(&ctx->completion_lock);
5606	io_cqring_fill_event(ctx, req->user_data, ret, 0);
5607	io_commit_cqring(ctx);
5608	spin_unlock_irq(&ctx->completion_lock);
5609	io_cqring_ev_posted(ctx);
5610	if (ret < 0)
5611		req_set_fail(req);
5612	io_put_req(req);
5613	return 0;
5614}
5615
5616static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5617			   bool is_timeout_link)
5618{
5619	struct io_timeout_data *data;
5620	unsigned flags;
5621	u32 off = READ_ONCE(sqe->off);
5622
5623	if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5624		return -EINVAL;
5625	if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5626		return -EINVAL;
5627	if (off && is_timeout_link)
5628		return -EINVAL;
5629	flags = READ_ONCE(sqe->timeout_flags);
5630	if (flags & ~IORING_TIMEOUT_ABS)
5631		return -EINVAL;
5632
5633	req->timeout.off = off;
5634	if (unlikely(off && !req->ctx->off_timeout_used))
5635		req->ctx->off_timeout_used = true;
5636
5637	if (!req->async_data && io_alloc_async_data(req))
5638		return -ENOMEM;
5639
5640	data = req->async_data;
5641	data->req = req;
5642
5643	if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5644		return -EFAULT;
5645
5646	data->mode = io_translate_timeout_mode(flags);
5647	hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5648	if (is_timeout_link)
5649		io_req_track_inflight(req);
5650	return 0;
5651}
5652
5653static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
5654{
5655	struct io_ring_ctx *ctx = req->ctx;
5656	struct io_timeout_data *data = req->async_data;
5657	struct list_head *entry;
5658	u32 tail, off = req->timeout.off;
5659
5660	spin_lock_irq(&ctx->timeout_lock);
5661
5662	/*
5663	 * sqe->off holds how many events that need to occur for this
5664	 * timeout event to be satisfied. If it isn't set, then this is
5665	 * a pure timeout request, sequence isn't used.
5666	 */
5667	if (io_is_timeout_noseq(req)) {
5668		entry = ctx->timeout_list.prev;
5669		goto add;
5670	}
5671
5672	tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5673	req->timeout.target_seq = tail + off;
5674
5675	/* Update the last seq here in case io_flush_timeouts() hasn't.
5676	 * This is safe because ->completion_lock is held, and submissions
5677	 * and completions are never mixed in the same ->completion_lock section.
5678	 */
5679	ctx->cq_last_tm_flush = tail;
5680
5681	/*
5682	 * Insertion sort, ensuring the first entry in the list is always
5683	 * the one we need first.
5684	 */
5685	list_for_each_prev(entry, &ctx->timeout_list) {
5686		struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
5687						  timeout.list);
5688
5689		if (io_is_timeout_noseq(nxt))
5690			continue;
5691		/* nxt.seq is behind @tail, otherwise would've been completed */
5692		if (off >= nxt->timeout.target_seq - tail)
5693			break;
5694	}
5695add:
5696	list_add(&req->timeout.list, entry);
5697	data->timer.function = io_timeout_fn;
5698	hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5699	spin_unlock_irq(&ctx->timeout_lock);
5700	return 0;
5701}
5702
5703struct io_cancel_data {
5704	struct io_ring_ctx *ctx;
5705	u64 user_data;
5706};
5707
5708static bool io_cancel_cb(struct io_wq_work *work, void *data)
5709{
5710	struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5711	struct io_cancel_data *cd = data;
5712
5713	return req->ctx == cd->ctx && req->user_data == cd->user_data;
5714}
5715
5716static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
5717			       struct io_ring_ctx *ctx)