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