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