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