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