io_uring: ensure that fsnotify is always called
[linux-2.6-block.git] / fs / io_uring.c
CommitLineData
2b188cc1
JA
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
5 *
6 * A note on the read/write ordering memory barriers that are matched between
1e84b97b
SB
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
d068b506 14 * through a control-dependency in io_get_cqe (smp_store_release to
1e84b97b
SB
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.
2b188cc1
JA
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
c992fe29 40 * Copyright (c) 2018-2019 Christoph Hellwig
2b188cc1
JA
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>
52de1fe1 47#include <net/compat.h>
2b188cc1
JA
48#include <linux/refcount.h>
49#include <linux/uio.h>
6b47ee6e 50#include <linux/bits.h>
2b188cc1
JA
51
52#include <linux/sched/signal.h>
53#include <linux/fs.h>
54#include <linux/file.h>
55#include <linux/fdtable.h>
56#include <linux/mm.h>
57#include <linux/mman.h>
2b188cc1
JA
58#include <linux/percpu.h>
59#include <linux/slab.h>
edce22e1 60#include <linux/blk-mq.h>
edafccee 61#include <linux/bvec.h>
2b188cc1
JA
62#include <linux/net.h>
63#include <net/sock.h>
64#include <net/af_unix.h>
6b06314c 65#include <net/scm.h>
adc8682e 66#include <net/busy_poll.h>
2b188cc1
JA
67#include <linux/anon_inodes.h>
68#include <linux/sched/mm.h>
69#include <linux/uaccess.h>
70#include <linux/nospec.h>
edafccee
JA
71#include <linux/sizes.h>
72#include <linux/hugetlb.h>
aa4c3967 73#include <linux/highmem.h>
15b71abe
JA
74#include <linux/namei.h>
75#include <linux/fsnotify.h>
4840e418 76#include <linux/fadvise.h>
3e4827b0 77#include <linux/eventpoll.h>
7d67af2c 78#include <linux/splice.h>
b41e9852 79#include <linux/task_work.h>
bcf5a063 80#include <linux/pagemap.h>
0f212204 81#include <linux/io_uring.h>
ef98eb04 82#include <linux/tracehook.h>
5bd2182d 83#include <linux/audit.h>
cdc1404a 84#include <linux/security.h>
2b188cc1 85
c826bd7a
DD
86#define CREATE_TRACE_POINTS
87#include <trace/events/io_uring.h>
88
2b188cc1
JA
89#include <uapi/linux/io_uring.h>
90
91#include "internal.h"
561fb04a 92#include "io-wq.h"
2b188cc1 93
5277deaa 94#define IORING_MAX_ENTRIES 32768
33a107f0 95#define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
4ce8ad95 96#define IORING_SQPOLL_CAP_ENTRIES_VALUE 8
65e19f54 97
187f08c1 98/* only define max */
042b0d85 99#define IORING_MAX_FIXED_FILES (1U << 15)
21b55dbc
SG
100#define IORING_MAX_RESTRICTIONS (IORING_RESTRICTION_LAST + \
101 IORING_REGISTER_LAST + IORING_OP_LAST)
2b188cc1 102
187f08c1 103#define IO_RSRC_TAG_TABLE_SHIFT (PAGE_SHIFT - 3)
2d091d62
PB
104#define IO_RSRC_TAG_TABLE_MAX (1U << IO_RSRC_TAG_TABLE_SHIFT)
105#define IO_RSRC_TAG_TABLE_MASK (IO_RSRC_TAG_TABLE_MAX - 1)
106
489809e2
PB
107#define IORING_MAX_REG_BUFFERS (1U << 14)
108
68fe256a
PB
109#define SQE_COMMON_FLAGS (IOSQE_FIXED_FILE | IOSQE_IO_LINK | \
110 IOSQE_IO_HARDLINK | IOSQE_ASYNC)
111
5562a8d7
PB
112#define SQE_VALID_FLAGS (SQE_COMMON_FLAGS | IOSQE_BUFFER_SELECT | \
113 IOSQE_IO_DRAIN | IOSQE_CQE_SKIP_SUCCESS)
68fe256a 114
c854357b 115#define IO_REQ_CLEAN_FLAGS (REQ_F_BUFFER_SELECTED | REQ_F_NEED_CLEANUP | \
d886e185
PB
116 REQ_F_POLLED | REQ_F_INFLIGHT | REQ_F_CREDS | \
117 REQ_F_ASYNC_DATA)
b16fed66 118
09899b19
PB
119#define IO_TCTX_REFS_CACHE_NR (1U << 10)
120
2b188cc1
JA
121struct io_uring {
122 u32 head ____cacheline_aligned_in_smp;
123 u32 tail ____cacheline_aligned_in_smp;
124};
125
1e84b97b 126/*
75b28aff
HV
127 * This data is shared with the application through the mmap at offsets
128 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
1e84b97b
SB
129 *
130 * The offsets to the member fields are published through struct
131 * io_sqring_offsets when calling io_uring_setup.
132 */
75b28aff 133struct io_rings {
1e84b97b
SB
134 /*
135 * Head and tail offsets into the ring; the offsets need to be
136 * masked to get valid indices.
137 *
75b28aff
HV
138 * The kernel controls head of the sq ring and the tail of the cq ring,
139 * and the application controls tail of the sq ring and the head of the
140 * cq ring.
1e84b97b 141 */
75b28aff 142 struct io_uring sq, cq;
1e84b97b 143 /*
75b28aff 144 * Bitmasks to apply to head and tail offsets (constant, equals
1e84b97b
SB
145 * ring_entries - 1)
146 */
75b28aff
HV
147 u32 sq_ring_mask, cq_ring_mask;
148 /* Ring sizes (constant, power of 2) */
149 u32 sq_ring_entries, cq_ring_entries;
1e84b97b
SB
150 /*
151 * Number of invalid entries dropped by the kernel due to
152 * invalid index stored in array
153 *
154 * Written by the kernel, shouldn't be modified by the
155 * application (i.e. get number of "new events" by comparing to
156 * cached value).
157 *
158 * After a new SQ head value was read by the application this
159 * counter includes all submissions that were dropped reaching
160 * the new SQ head (and possibly more).
161 */
75b28aff 162 u32 sq_dropped;
1e84b97b 163 /*
0d9b5b3a 164 * Runtime SQ flags
1e84b97b
SB
165 *
166 * Written by the kernel, shouldn't be modified by the
167 * application.
168 *
169 * The application needs a full memory barrier before checking
170 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
171 */
75b28aff 172 u32 sq_flags;
0d9b5b3a
SG
173 /*
174 * Runtime CQ flags
175 *
176 * Written by the application, shouldn't be modified by the
177 * kernel.
178 */
fe7e3257 179 u32 cq_flags;
1e84b97b
SB
180 /*
181 * Number of completion events lost because the queue was full;
182 * this should be avoided by the application by making sure
0b4295b5 183 * there are not more requests pending than there is space in
1e84b97b
SB
184 * the completion queue.
185 *
186 * Written by the kernel, shouldn't be modified by the
187 * application (i.e. get number of "new events" by comparing to
188 * cached value).
189 *
190 * As completion events come in out of order this counter is not
191 * ordered with any other data.
192 */
75b28aff 193 u32 cq_overflow;
1e84b97b
SB
194 /*
195 * Ring buffer of completion events.
196 *
197 * The kernel writes completion events fresh every time they are
198 * produced, so the application is allowed to modify pending
199 * entries.
200 */
75b28aff 201 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
2b188cc1
JA
202};
203
45d189c6 204enum io_uring_cmd_flags {
51aac424 205 IO_URING_F_COMPLETE_DEFER = 1,
3b44b371 206 IO_URING_F_UNLOCKED = 2,
51aac424
PB
207 /* int's last bit, sign checks are usually faster than a bit test */
208 IO_URING_F_NONBLOCK = INT_MIN,
45d189c6
PB
209};
210
edafccee
JA
211struct io_mapped_ubuf {
212 u64 ubuf;
4751f53d 213 u64 ubuf_end;
edafccee 214 unsigned int nr_bvecs;
de293938 215 unsigned long acct_pages;
41edf1a5 216 struct bio_vec bvec[];
edafccee
JA
217};
218
50238531
BM
219struct io_ring_ctx;
220
6c2450ae
PB
221struct io_overflow_cqe {
222 struct io_uring_cqe cqe;
223 struct list_head list;
224};
225
a04b0ac0
PB
226struct io_fixed_file {
227 /* file * with additional FFS_* flags */
228 unsigned long file_ptr;
229};
230
269bbe5f
BM
231struct io_rsrc_put {
232 struct list_head list;
b60c8dce 233 u64 tag;
50238531
BM
234 union {
235 void *rsrc;
236 struct file *file;
bd54b6fe 237 struct io_mapped_ubuf *buf;
50238531 238 };
269bbe5f
BM
239};
240
aeca241b 241struct io_file_table {
042b0d85 242 struct io_fixed_file *files;
31b51510
JA
243};
244
b895c9a6 245struct io_rsrc_node {
05589553
XW
246 struct percpu_ref refs;
247 struct list_head node;
269bbe5f 248 struct list_head rsrc_list;
b895c9a6 249 struct io_rsrc_data *rsrc_data;
4a38aed2 250 struct llist_node llist;
e297822b 251 bool done;
05589553
XW
252};
253
40ae0ff7
PB
254typedef void (rsrc_put_fn)(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc);
255
b895c9a6 256struct io_rsrc_data {
05f3fb3c
JA
257 struct io_ring_ctx *ctx;
258
2d091d62
PB
259 u64 **tags;
260 unsigned int nr;
40ae0ff7 261 rsrc_put_fn *do_put;
3e942498 262 atomic_t refs;
05f3fb3c 263 struct completion done;
8bad28d8 264 bool quiesce;
05f3fb3c
JA
265};
266
dbc7d452
JA
267struct io_buffer_list {
268 struct list_head list;
269 struct list_head buf_list;
270 __u16 bgid;
271};
272
5a2e745d
JA
273struct io_buffer {
274 struct list_head list;
275 __u64 addr;
d1f82808 276 __u32 len;
5a2e745d 277 __u16 bid;
b1c62645 278 __u16 bgid;
5a2e745d
JA
279};
280
21b55dbc
SG
281struct io_restriction {
282 DECLARE_BITMAP(register_op, IORING_REGISTER_LAST);
283 DECLARE_BITMAP(sqe_op, IORING_OP_LAST);
284 u8 sqe_flags_allowed;
285 u8 sqe_flags_required;
7e84e1c7 286 bool registered;
21b55dbc
SG
287};
288
37d1e2e3
JA
289enum {
290 IO_SQ_THREAD_SHOULD_STOP = 0,
291 IO_SQ_THREAD_SHOULD_PARK,
292};
293
534ca6d6
JA
294struct io_sq_data {
295 refcount_t refs;
9e138a48 296 atomic_t park_pending;
09a6f4ef 297 struct mutex lock;
69fb2131
JA
298
299 /* ctx's that are using this sqd */
300 struct list_head ctx_list;
69fb2131 301
534ca6d6
JA
302 struct task_struct *thread;
303 struct wait_queue_head wait;
08369246
XW
304
305 unsigned sq_thread_idle;
37d1e2e3
JA
306 int sq_cpu;
307 pid_t task_pid;
5c2469e0 308 pid_t task_tgid;
37d1e2e3
JA
309
310 unsigned long state;
37d1e2e3 311 struct completion exited;
534ca6d6
JA
312};
313
6dd0be1e 314#define IO_COMPL_BATCH 32
6ff119a6 315#define IO_REQ_CACHE_SIZE 32
bf019da7 316#define IO_REQ_ALLOC_BATCH 8
258b29a9 317
a1ab7b35
PB
318struct io_submit_link {
319 struct io_kiocb *head;
320 struct io_kiocb *last;
321};
322
258b29a9 323struct io_submit_state {
5a158c6b
PB
324 /* inline/task_work completion list, under ->uring_lock */
325 struct io_wq_work_node free_list;
326 /* batch completion logic */
327 struct io_wq_work_list compl_reqs;
a1ab7b35 328 struct io_submit_link link;
258b29a9 329
258b29a9 330 bool plug_started;
4b628aeb 331 bool need_plug;
3d4aeb9f 332 bool flush_cqes;
5ca7a8b3 333 unsigned short submit_nr;
5a158c6b 334 struct blk_plug plug;
258b29a9
PB
335};
336
77bc59b4
UA
337struct io_ev_fd {
338 struct eventfd_ctx *cq_ev_fd;
c75312dd 339 unsigned int eventfd_async: 1;
77bc59b4
UA
340 struct rcu_head rcu;
341};
342
dbc7d452
JA
343#define IO_BUFFERS_HASH_BITS 5
344
2b188cc1 345struct io_ring_ctx {
b52ecf8c 346 /* const or read-mostly hot data */
2b188cc1
JA
347 struct {
348 struct percpu_ref refs;
2b188cc1 349
b52ecf8c 350 struct io_rings *rings;
2b188cc1 351 unsigned int flags;
e1d85334 352 unsigned int compat: 1;
e1d85334 353 unsigned int drain_next: 1;
21b55dbc 354 unsigned int restricted: 1;
f18ee4cf 355 unsigned int off_timeout_used: 1;
10c66904 356 unsigned int drain_active: 1;
5562a8d7 357 unsigned int drain_disabled: 1;
9aa8dfde 358 unsigned int has_evfd: 1;
b52ecf8c 359 } ____cacheline_aligned_in_smp;
2b188cc1 360
7f1129d2 361 /* submission data */
b52ecf8c 362 struct {
0499e582
PB
363 struct mutex uring_lock;
364
75b28aff
HV
365 /*
366 * Ring buffer of indices into array of io_uring_sqe, which is
367 * mmapped by the application using the IORING_OFF_SQES offset.
368 *
369 * This indirection could e.g. be used to assign fixed
370 * io_uring_sqe entries to operations and only submit them to
371 * the queue when needed.
372 *
373 * The kernel modifies neither the indices array nor the entries
374 * array.
375 */
376 u32 *sq_array;
c7af47cf 377 struct io_uring_sqe *sq_sqes;
2b188cc1
JA
378 unsigned cached_sq_head;
379 unsigned sq_entries;
de0617e4 380 struct list_head defer_list;
7f1129d2
PB
381
382 /*
383 * Fixed resources fast path, should be accessed only under
384 * uring_lock, and updated through io_uring_register(2)
385 */
386 struct io_rsrc_node *rsrc_node;
ab409402 387 int rsrc_cached_refs;
7f1129d2
PB
388 struct io_file_table file_table;
389 unsigned nr_user_files;
390 unsigned nr_user_bufs;
391 struct io_mapped_ubuf **user_bufs;
392
393 struct io_submit_state submit_state;
5262f567 394 struct list_head timeout_list;
ef9dd637 395 struct list_head ltimeout_list;
1d7bb1d5 396 struct list_head cq_overflow_list;
dbc7d452 397 struct list_head *io_buffers;
cc3cec83 398 struct list_head io_buffers_cache;
4d9237e3 399 struct list_head apoll_cache;
7f1129d2
PB
400 struct xarray personalities;
401 u32 pers_next;
402 unsigned sq_thread_idle;
2b188cc1
JA
403 } ____cacheline_aligned_in_smp;
404
d0acdee2 405 /* IRQ completion list, under ->completion_lock */
c2b6c6bc 406 struct io_wq_work_list locked_free_list;
d0acdee2 407 unsigned int locked_free_nr;
3c1a2ead 408
7c30f36a 409 const struct cred *sq_creds; /* cred used for __io_sq_thread() */
534ca6d6
JA
410 struct io_sq_data *sq_data; /* if using sq thread polling */
411
90554200 412 struct wait_queue_head sqo_sq_wait;
69fb2131 413 struct list_head sqd_list;
75b28aff 414
5ed7a37d 415 unsigned long check_cq_overflow;
adc8682e
OL
416#ifdef CONFIG_NET_RX_BUSY_POLL
417 /* used to track busy poll napi_id */
418 struct list_head napi_list;
419 spinlock_t napi_lock; /* napi_list lock */
420#endif
5ed7a37d 421
206aefde
JA
422 struct {
423 unsigned cached_cq_tail;
424 unsigned cq_entries;
77bc59b4 425 struct io_ev_fd __rcu *io_ev_fd;
0499e582
PB
426 struct wait_queue_head cq_wait;
427 unsigned cq_extra;
428 atomic_t cq_timeouts;
0499e582 429 unsigned cq_last_tm_flush;
206aefde 430 } ____cacheline_aligned_in_smp;
2b188cc1 431
2b188cc1
JA
432 struct {
433 spinlock_t completion_lock;
e94f141b 434
89850fce
JA
435 spinlock_t timeout_lock;
436
def596e9 437 /*
540e32a0 438 * ->iopoll_list is protected by the ctx->uring_lock for
def596e9
JA
439 * io_uring instances that don't use IORING_SETUP_SQPOLL.
440 * For SQPOLL, only the single threaded io_sq_thread() will
441 * manipulate the list, hence no extra locking is needed there.
442 */
5eef4e87 443 struct io_wq_work_list iopoll_list;
78076bb6
JA
444 struct hlist_head *cancel_hash;
445 unsigned cancel_hash_bits;
915b3dde 446 bool poll_multi_queue;
cc3cec83
JA
447
448 struct list_head io_buffers_comp;
2b188cc1 449 } ____cacheline_aligned_in_smp;
85faa7b8 450
21b55dbc 451 struct io_restriction restrictions;
3c1a2ead 452
b13a8918
PB
453 /* slow path rsrc auxilary data, used by update/register */
454 struct {
455 struct io_rsrc_node *rsrc_backup_node;
456 struct io_mapped_ubuf *dummy_ubuf;
457 struct io_rsrc_data *file_data;
458 struct io_rsrc_data *buf_data;
459
460 struct delayed_work rsrc_put_work;
461 struct llist_head rsrc_put_llist;
462 struct list_head rsrc_ref_list;
463 spinlock_t rsrc_ref_lock;
cc3cec83
JA
464
465 struct list_head io_buffers_pages;
b13a8918
PB
466 };
467
3c1a2ead 468 /* Keep this last, we don't need it for the fast path */
b986af7e
PB
469 struct {
470 #if defined(CONFIG_UNIX)
471 struct socket *ring_sock;
472 #endif
473 /* hashed buffered write serialization */
474 struct io_wq_hash *hash_map;
475
476 /* Only used for accounting purposes */
477 struct user_struct *user;
478 struct mm_struct *mm_account;
479
480 /* ctx exit and cancelation */
9011bf9a
PB
481 struct llist_head fallback_llist;
482 struct delayed_work fallback_work;
b986af7e
PB
483 struct work_struct exit_work;
484 struct list_head tctx_list;
485 struct completion ref_comp;
e139a1ec
PB
486 u32 iowq_limits[2];
487 bool iowq_limits_set;
b986af7e 488 };
2b188cc1
JA
489};
490
e7a6c00d
JA
491/*
492 * Arbitrary limit, can be raised if need be
493 */
494#define IO_RINGFD_REG_MAX 16
495
53e043b2
SM
496struct io_uring_task {
497 /* submission side */
09899b19 498 int cached_refs;
53e043b2
SM
499 struct xarray xa;
500 struct wait_queue_head wait;
ee53fb2b
SM
501 const struct io_ring_ctx *last;
502 struct io_wq *io_wq;
53e043b2 503 struct percpu_counter inflight;
b303fe2e 504 atomic_t inflight_tracked;
53e043b2 505 atomic_t in_idle;
53e043b2
SM
506
507 spinlock_t task_lock;
508 struct io_wq_work_list task_list;
4813c377 509 struct io_wq_work_list prior_task_list;
53e043b2 510 struct callback_head task_work;
e7a6c00d 511 struct file **registered_rings;
6294f368 512 bool task_running;
53e043b2
SM
513};
514
09bb8394
JA
515/*
516 * First field must be the file pointer in all the
517 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
518 */
221c5eb2
JA
519struct io_poll_iocb {
520 struct file *file;
018043be 521 struct wait_queue_head *head;
221c5eb2 522 __poll_t events;
392edb45 523 struct wait_queue_entry wait;
221c5eb2
JA
524};
525
9d805892 526struct io_poll_update {
018043be 527 struct file *file;
9d805892
PB
528 u64 old_user_data;
529 u64 new_user_data;
530 __poll_t events;
b69de288
JA
531 bool update_events;
532 bool update_user_data;
018043be
PB
533};
534
b5dba59e
JA
535struct io_close {
536 struct file *file;
b5dba59e 537 int fd;
7df778be 538 u32 file_slot;
b5dba59e
JA
539};
540
ad8a48ac
JA
541struct io_timeout_data {
542 struct io_kiocb *req;
543 struct hrtimer timer;
544 struct timespec64 ts;
545 enum hrtimer_mode mode;
50c1df2b 546 u32 flags;
ad8a48ac
JA
547};
548
8ed8d3c3
JA
549struct io_accept {
550 struct file *file;
551 struct sockaddr __user *addr;
552 int __user *addr_len;
553 int flags;
aaa4db12 554 u32 file_slot;
09952e3e 555 unsigned long nofile;
8ed8d3c3
JA
556};
557
558struct io_sync {
559 struct file *file;
560 loff_t len;
561 loff_t off;
562 int flags;
d63d1b5e 563 int mode;
8ed8d3c3
JA
564};
565
fbf23849
JA
566struct io_cancel {
567 struct file *file;
568 u64 addr;
569};
570
b29472ee
JA
571struct io_timeout {
572 struct file *file;
bfe68a22
PB
573 u32 off;
574 u32 target_seq;
135fcde8 575 struct list_head list;
90cd7e42
PB
576 /* head of the link, used by linked timeouts only */
577 struct io_kiocb *head;
89b263f6
JA
578 /* for linked completions */
579 struct io_kiocb *prev;
b29472ee
JA
580};
581
0bdf7a2d
PB
582struct io_timeout_rem {
583 struct file *file;
584 u64 addr;
9c8e11b3
PB
585
586 /* timeout update */
587 struct timespec64 ts;
588 u32 flags;
f1042b6c 589 bool ltimeout;
0bdf7a2d
PB
590};
591
9adbd45d
JA
592struct io_rw {
593 /* NOTE: kiocb has the file as the first member, so don't do it here */
594 struct kiocb kiocb;
595 u64 addr;
596 u64 len;
597};
598
3fbb51c1
JA
599struct io_connect {
600 struct file *file;
601 struct sockaddr __user *addr;
602 int addr_len;
603};
604
e47293fd
JA
605struct io_sr_msg {
606 struct file *file;
fddaface 607 union {
4af3417a
PB
608 struct compat_msghdr __user *umsg_compat;
609 struct user_msghdr __user *umsg;
610 void __user *buf;
fddaface 611 };
e47293fd 612 int msg_flags;
bcda7baa 613 int bgid;
fddaface 614 size_t len;
e47293fd
JA
615};
616
15b71abe
JA
617struct io_open {
618 struct file *file;
619 int dfd;
b9445598 620 u32 file_slot;
15b71abe 621 struct filename *filename;
c12cedf2 622 struct open_how how;
4022e7af 623 unsigned long nofile;
15b71abe
JA
624};
625
269bbe5f 626struct io_rsrc_update {
05f3fb3c
JA
627 struct file *file;
628 u64 arg;
629 u32 nr_args;
630 u32 offset;
631};
632
4840e418
JA
633struct io_fadvise {
634 struct file *file;
635 u64 offset;
636 u32 len;
637 u32 advice;
638};
639
c1ca757b
JA
640struct io_madvise {
641 struct file *file;
642 u64 addr;
643 u32 len;
644 u32 advice;
645};
646
3e4827b0
JA
647struct io_epoll {
648 struct file *file;
649 int epfd;
650 int op;
651 int fd;
652 struct epoll_event event;
e47293fd
JA
653};
654
7d67af2c
PB
655struct io_splice {
656 struct file *file_out;
657 struct file *file_in;
658 loff_t off_out;
659 loff_t off_in;
660 u64 len;
661 unsigned int flags;
662};
663
ddf0322d
JA
664struct io_provide_buf {
665 struct file *file;
666 __u64 addr;
38134ada 667 __u32 len;
ddf0322d
JA
668 __u32 bgid;
669 __u16 nbufs;
670 __u16 bid;
671};
672
1d9e1288
BM
673struct io_statx {
674 struct file *file;
675 int dfd;
676 unsigned int mask;
677 unsigned int flags;
e62753e4 678 const char __user *filename;
1d9e1288
BM
679 struct statx __user *buffer;
680};
681
36f4fa68
JA
682struct io_shutdown {
683 struct file *file;
684 int how;
685};
686
80a261fd
JA
687struct io_rename {
688 struct file *file;
689 int old_dfd;
690 int new_dfd;
691 struct filename *oldpath;
692 struct filename *newpath;
693 int flags;
694};
695
14a1143b
JA
696struct io_unlink {
697 struct file *file;
698 int dfd;
699 int flags;
700 struct filename *filename;
701};
702
e34a02dc
DK
703struct io_mkdir {
704 struct file *file;
705 int dfd;
706 umode_t mode;
707 struct filename *filename;
708};
709
7a8721f8
DK
710struct io_symlink {
711 struct file *file;
712 int new_dfd;
713 struct filename *oldpath;
714 struct filename *newpath;
715};
716
cf30da90
DK
717struct io_hardlink {
718 struct file *file;
719 int old_dfd;
720 int new_dfd;
721 struct filename *oldpath;
722 struct filename *newpath;
723 int flags;
724};
725
4f57f06c
JA
726struct io_msg {
727 struct file *file;
728 u64 user_data;
729 u32 len;
730};
731
f499a021
JA
732struct io_async_connect {
733 struct sockaddr_storage address;
734};
735
03b1230c
JA
736struct io_async_msghdr {
737 struct iovec fast_iov[UIO_FASTIOV];
257e84a5
PB
738 /* points to an allocated iov, if NULL we use fast_iov instead */
739 struct iovec *free_iov;
03b1230c
JA
740 struct sockaddr __user *uaddr;
741 struct msghdr msg;
b537916c 742 struct sockaddr_storage addr;
03b1230c
JA
743};
744
538941e2 745struct io_rw_state {
ff6165b2 746 struct iov_iter iter;
cd658695 747 struct iov_iter_state iter_state;
c88598a9 748 struct iovec fast_iov[UIO_FASTIOV];
538941e2
PB
749};
750
751struct io_async_rw {
752 struct io_rw_state s;
753 const struct iovec *free_iovec;
227c0c96 754 size_t bytes_done;
bcf5a063 755 struct wait_page_queue wpq;
f67676d1
JA
756};
757
6b47ee6e
PB
758enum {
759 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
760 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
761 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
762 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
763 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
bcda7baa 764 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
04c76b41 765 REQ_F_CQE_SKIP_BIT = IOSQE_CQE_SKIP_SUCCESS_BIT,
6b47ee6e 766
dddca226 767 /* first byte is taken by user flags, shift it to not overlap */
93d2bcd2 768 REQ_F_FAIL_BIT = 8,
6b47ee6e
PB
769 REQ_F_INFLIGHT_BIT,
770 REQ_F_CUR_POS_BIT,
771 REQ_F_NOWAIT_BIT,
6b47ee6e 772 REQ_F_LINK_TIMEOUT_BIT,
99bc4c38 773 REQ_F_NEED_CLEANUP_BIT,
d7718a9d 774 REQ_F_POLLED_BIT,
bcda7baa 775 REQ_F_BUFFER_SELECTED_BIT,
e342c807 776 REQ_F_COMPLETE_INLINE_BIT,
230d50d4 777 REQ_F_REISSUE_BIT,
b8e64b53 778 REQ_F_CREDS_BIT,
20e60a38 779 REQ_F_REFCOUNT_BIT,
4d13d1a4 780 REQ_F_ARM_LTIMEOUT_BIT,
d886e185 781 REQ_F_ASYNC_DATA_BIT,
04c76b41 782 REQ_F_SKIP_LINK_CQES_BIT,
91eac1c6
JA
783 REQ_F_SINGLE_POLL_BIT,
784 REQ_F_DOUBLE_POLL_BIT,
7b29f92d 785 /* keep async read/write and isreg together and in order */
35645ac3 786 REQ_F_SUPPORT_NOWAIT_BIT,
7b29f92d 787 REQ_F_ISREG_BIT,
84557871
JA
788
789 /* not a real bit, just to check we're not overflowing the space */
790 __REQ_F_LAST_BIT,
6b47ee6e
PB
791};
792
793enum {
794 /* ctx owns file */
795 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
796 /* drain existing IO first */
797 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
798 /* linked sqes */
799 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
800 /* doesn't sever on completion < 0 */
801 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
802 /* IOSQE_ASYNC */
803 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
bcda7baa
JA
804 /* IOSQE_BUFFER_SELECT */
805 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
04c76b41
PB
806 /* IOSQE_CQE_SKIP_SUCCESS */
807 REQ_F_CQE_SKIP = BIT(REQ_F_CQE_SKIP_BIT),
6b47ee6e 808
6b47ee6e 809 /* fail rest of links */
93d2bcd2 810 REQ_F_FAIL = BIT(REQ_F_FAIL_BIT),
b05a1bcd 811 /* on inflight list, should be cancelled and waited on exit reliably */
6b47ee6e
PB
812 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
813 /* read/write uses file position */
814 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
815 /* must not punt to workers */
816 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
900fad45 817 /* has or had linked timeout */
6b47ee6e 818 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
99bc4c38
PB
819 /* needs cleanup */
820 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
d7718a9d
JA
821 /* already went through poll handler */
822 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
bcda7baa
JA
823 /* buffer already selected */
824 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
e342c807
PB
825 /* completion is deferred through io_comp_state */
826 REQ_F_COMPLETE_INLINE = BIT(REQ_F_COMPLETE_INLINE_BIT),
230d50d4
JA
827 /* caller should reissue async */
828 REQ_F_REISSUE = BIT(REQ_F_REISSUE_BIT),
35645ac3
PB
829 /* supports async reads/writes */
830 REQ_F_SUPPORT_NOWAIT = BIT(REQ_F_SUPPORT_NOWAIT_BIT),
7b29f92d
JA
831 /* regular file */
832 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
b8e64b53
PB
833 /* has creds assigned */
834 REQ_F_CREDS = BIT(REQ_F_CREDS_BIT),
20e60a38
PB
835 /* skip refcounting if not set */
836 REQ_F_REFCOUNT = BIT(REQ_F_REFCOUNT_BIT),
4d13d1a4
PB
837 /* there is a linked timeout that has to be armed */
838 REQ_F_ARM_LTIMEOUT = BIT(REQ_F_ARM_LTIMEOUT_BIT),
d886e185
PB
839 /* ->async_data allocated */
840 REQ_F_ASYNC_DATA = BIT(REQ_F_ASYNC_DATA_BIT),
04c76b41
PB
841 /* don't post CQEs while failing linked requests */
842 REQ_F_SKIP_LINK_CQES = BIT(REQ_F_SKIP_LINK_CQES_BIT),
91eac1c6
JA
843 /* single poll may be active */
844 REQ_F_SINGLE_POLL = BIT(REQ_F_SINGLE_POLL_BIT),
845 /* double poll may active */
846 REQ_F_DOUBLE_POLL = BIT(REQ_F_DOUBLE_POLL_BIT),
d7718a9d
JA
847};
848
849struct async_poll {
850 struct io_poll_iocb poll;
807abcb0 851 struct io_poll_iocb *double_poll;
6b47ee6e
PB
852};
853
f237c30a 854typedef void (*io_req_tw_func_t)(struct io_kiocb *req, bool *locked);
5b0a6acc 855
7cbf1722 856struct io_task_work {
5b0a6acc
PB
857 union {
858 struct io_wq_work_node node;
859 struct llist_node fallback_node;
860 };
861 io_req_tw_func_t func;
7cbf1722
JA
862};
863
992da01a
PB
864enum {
865 IORING_RSRC_FILE = 0,
866 IORING_RSRC_BUFFER = 1,
867};
868
09bb8394
JA
869/*
870 * NOTE! Each of the iocb union members has the file pointer
871 * as the first entry in their struct definition. So you can
872 * access the file pointer through any of the sub-structs,
63c36549 873 * or directly as just 'file' in this struct.
09bb8394 874 */
2b188cc1 875struct io_kiocb {
221c5eb2 876 union {
09bb8394 877 struct file *file;
9adbd45d 878 struct io_rw rw;
221c5eb2 879 struct io_poll_iocb poll;
9d805892 880 struct io_poll_update poll_update;
8ed8d3c3
JA
881 struct io_accept accept;
882 struct io_sync sync;
fbf23849 883 struct io_cancel cancel;
b29472ee 884 struct io_timeout timeout;
0bdf7a2d 885 struct io_timeout_rem timeout_rem;
3fbb51c1 886 struct io_connect connect;
e47293fd 887 struct io_sr_msg sr_msg;
15b71abe 888 struct io_open open;
b5dba59e 889 struct io_close close;
269bbe5f 890 struct io_rsrc_update rsrc_update;
4840e418 891 struct io_fadvise fadvise;
c1ca757b 892 struct io_madvise madvise;
3e4827b0 893 struct io_epoll epoll;
7d67af2c 894 struct io_splice splice;
ddf0322d 895 struct io_provide_buf pbuf;
1d9e1288 896 struct io_statx statx;
36f4fa68 897 struct io_shutdown shutdown;
80a261fd 898 struct io_rename rename;
14a1143b 899 struct io_unlink unlink;
e34a02dc 900 struct io_mkdir mkdir;
7a8721f8 901 struct io_symlink symlink;
cf30da90 902 struct io_hardlink hardlink;
4f57f06c 903 struct io_msg msg;
221c5eb2 904 };
2b188cc1 905
d625c6ee 906 u8 opcode;
65a6543d
XW
907 /* polled IO has completed */
908 u8 iopoll_completed;
4f4eeba8 909 u16 buf_index;
d17e56eb
PB
910 unsigned int flags;
911
912 u64 user_data;
9cf7c104 913 u32 result;
d17e56eb 914 u32 cflags;
4f4eeba8 915
010e8e6b 916 struct io_ring_ctx *ctx;
010e8e6b 917 struct task_struct *task;
d7718a9d 918
269bbe5f 919 struct percpu_ref *fixed_rsrc_refs;
d886e185
PB
920 /* store used ubuf, so we can prevent reloading */
921 struct io_mapped_ubuf *imu;
fcb323cc 922
7e3709d5 923 /* used by request caches, completion batching and iopoll */
ef05d9eb 924 struct io_wq_work_node comp_list;
d17e56eb 925 atomic_t refs;
521d61fc 926 atomic_t poll_refs;
7e3709d5 927 struct io_kiocb *link;
5b0a6acc 928 struct io_task_work io_task_work;
010e8e6b
PB
929 /* for polled requests, i.e. IORING_OP_POLL_ADD and async armed poll */
930 struct hlist_node hash_node;
7e3709d5 931 /* internal polling, see IORING_FEAT_FAST_POLL */
010e8e6b 932 struct async_poll *apoll;
d886e185
PB
933 /* opcode allocated if it needs to store data for async defer */
934 void *async_data;
7e3709d5 935 /* custom credentials, valid IFF REQ_F_CREDS is set */
7e3709d5 936 /* stores selected buf, valid IFF REQ_F_BUFFER_SELECTED is set */
30d51dd4 937 struct io_buffer *kbuf;
521d61fc
JA
938 const struct cred *creds;
939 struct io_wq_work work;
2b188cc1 940};
05589553 941
13bf43f5
PB
942struct io_tctx_node {
943 struct list_head ctx_node;
944 struct task_struct *task;
13bf43f5
PB
945 struct io_ring_ctx *ctx;
946};
947
27dc8338
PB
948struct io_defer_entry {
949 struct list_head list;
950 struct io_kiocb *req;
9cf7c104 951 u32 seq;
2b188cc1
JA
952};
953
d3656344 954struct io_op_def {
d3656344
JA
955 /* needs req->file assigned */
956 unsigned needs_file : 1;
6d63416d
PB
957 /* should block plug */
958 unsigned plug : 1;
d3656344
JA
959 /* hash wq insertion if file is a regular file */
960 unsigned hash_reg_file : 1;
961 /* unbound wq insertion if file is a non-regular file */
962 unsigned unbound_nonreg_file : 1;
8a72758c
JA
963 /* set if opcode supports polled "wait" */
964 unsigned pollin : 1;
965 unsigned pollout : 1;
bcda7baa
JA
966 /* op supports buffer selection */
967 unsigned buffer_select : 1;
26f0505a
PB
968 /* do prep async if is going to be punted */
969 unsigned needs_async_setup : 1;
6d63416d
PB
970 /* opcode is not supported by this kernel */
971 unsigned not_supported : 1;
5bd2182d
PM
972 /* skip auditing */
973 unsigned audit_skip : 1;
e8c2bc1f
JA
974 /* size of async data needed, if any */
975 unsigned short async_size;
d3656344
JA
976};
977
0918682b 978static const struct io_op_def io_op_defs[] = {
0463b6c5
PB
979 [IORING_OP_NOP] = {},
980 [IORING_OP_READV] = {
d3656344
JA
981 .needs_file = 1,
982 .unbound_nonreg_file = 1,
8a72758c 983 .pollin = 1,
4d954c25 984 .buffer_select = 1,
26f0505a 985 .needs_async_setup = 1,
27926b68 986 .plug = 1,
5bd2182d 987 .audit_skip = 1,
e8c2bc1f 988 .async_size = sizeof(struct io_async_rw),
d3656344 989 },
0463b6c5 990 [IORING_OP_WRITEV] = {
d3656344
JA
991 .needs_file = 1,
992 .hash_reg_file = 1,
993 .unbound_nonreg_file = 1,
8a72758c 994 .pollout = 1,
26f0505a 995 .needs_async_setup = 1,
27926b68 996 .plug = 1,
5bd2182d 997 .audit_skip = 1,
e8c2bc1f 998 .async_size = sizeof(struct io_async_rw),
d3656344 999 },
0463b6c5 1000 [IORING_OP_FSYNC] = {
d3656344 1001 .needs_file = 1,
5bd2182d 1002 .audit_skip = 1,
d3656344 1003 },
0463b6c5 1004 [IORING_OP_READ_FIXED] = {
d3656344
JA
1005 .needs_file = 1,
1006 .unbound_nonreg_file = 1,
8a72758c 1007 .pollin = 1,
27926b68 1008 .plug = 1,
5bd2182d 1009 .audit_skip = 1,
e8c2bc1f 1010 .async_size = sizeof(struct io_async_rw),
d3656344 1011 },
0463b6c5 1012 [IORING_OP_WRITE_FIXED] = {
d3656344
JA
1013 .needs_file = 1,
1014 .hash_reg_file = 1,
1015 .unbound_nonreg_file = 1,
8a72758c 1016 .pollout = 1,
27926b68 1017 .plug = 1,
5bd2182d 1018 .audit_skip = 1,
e8c2bc1f 1019 .async_size = sizeof(struct io_async_rw),
d3656344 1020 },
0463b6c5 1021 [IORING_OP_POLL_ADD] = {
d3656344
JA
1022 .needs_file = 1,
1023 .unbound_nonreg_file = 1,
5bd2182d
PM
1024 .audit_skip = 1,
1025 },
1026 [IORING_OP_POLL_REMOVE] = {
1027 .audit_skip = 1,
d3656344 1028 },
0463b6c5 1029 [IORING_OP_SYNC_FILE_RANGE] = {
d3656344 1030 .needs_file = 1,
5bd2182d 1031 .audit_skip = 1,
d3656344 1032 },
0463b6c5 1033 [IORING_OP_SENDMSG] = {
d3656344
JA
1034 .needs_file = 1,
1035 .unbound_nonreg_file = 1,
8a72758c 1036 .pollout = 1,
26f0505a 1037 .needs_async_setup = 1,
e8c2bc1f 1038 .async_size = sizeof(struct io_async_msghdr),
d3656344 1039 },
0463b6c5 1040 [IORING_OP_RECVMSG] = {
d3656344
JA
1041 .needs_file = 1,
1042 .unbound_nonreg_file = 1,
8a72758c 1043 .pollin = 1,
52de1fe1 1044 .buffer_select = 1,
26f0505a 1045 .needs_async_setup = 1,
e8c2bc1f 1046 .async_size = sizeof(struct io_async_msghdr),
d3656344 1047 },
0463b6c5 1048 [IORING_OP_TIMEOUT] = {
5bd2182d 1049 .audit_skip = 1,
e8c2bc1f 1050 .async_size = sizeof(struct io_timeout_data),
d3656344 1051 },
9c8e11b3
PB
1052 [IORING_OP_TIMEOUT_REMOVE] = {
1053 /* used by timeout updates' prep() */
5bd2182d 1054 .audit_skip = 1,
9c8e11b3 1055 },
0463b6c5 1056 [IORING_OP_ACCEPT] = {
d3656344
JA
1057 .needs_file = 1,
1058 .unbound_nonreg_file = 1,
8a72758c 1059 .pollin = 1,
d3656344 1060 },
5bd2182d
PM
1061 [IORING_OP_ASYNC_CANCEL] = {
1062 .audit_skip = 1,
1063 },
0463b6c5 1064 [IORING_OP_LINK_TIMEOUT] = {
5bd2182d 1065 .audit_skip = 1,
e8c2bc1f 1066 .async_size = sizeof(struct io_timeout_data),
d3656344 1067 },
0463b6c5 1068 [IORING_OP_CONNECT] = {
d3656344
JA
1069 .needs_file = 1,
1070 .unbound_nonreg_file = 1,
8a72758c 1071 .pollout = 1,
26f0505a 1072 .needs_async_setup = 1,
e8c2bc1f 1073 .async_size = sizeof(struct io_async_connect),
d3656344 1074 },
0463b6c5 1075 [IORING_OP_FALLOCATE] = {
d3656344 1076 .needs_file = 1,
d3656344 1077 },
44526bed
JA
1078 [IORING_OP_OPENAT] = {},
1079 [IORING_OP_CLOSE] = {},
5bd2182d
PM
1080 [IORING_OP_FILES_UPDATE] = {
1081 .audit_skip = 1,
1082 },
1083 [IORING_OP_STATX] = {
1084 .audit_skip = 1,
1085 },
0463b6c5 1086 [IORING_OP_READ] = {
3a6820f2
JA
1087 .needs_file = 1,
1088 .unbound_nonreg_file = 1,
8a72758c 1089 .pollin = 1,
bcda7baa 1090 .buffer_select = 1,
27926b68 1091 .plug = 1,
5bd2182d 1092 .audit_skip = 1,
e8c2bc1f 1093 .async_size = sizeof(struct io_async_rw),
3a6820f2 1094 },
0463b6c5 1095 [IORING_OP_WRITE] = {
3a6820f2 1096 .needs_file = 1,
7b3188e7 1097 .hash_reg_file = 1,
3a6820f2 1098 .unbound_nonreg_file = 1,
8a72758c 1099 .pollout = 1,
27926b68 1100 .plug = 1,
5bd2182d 1101 .audit_skip = 1,
e8c2bc1f 1102 .async_size = sizeof(struct io_async_rw),
3a6820f2 1103 },
0463b6c5 1104 [IORING_OP_FADVISE] = {
4840e418 1105 .needs_file = 1,
5bd2182d 1106 .audit_skip = 1,
c1ca757b 1107 },
44526bed 1108 [IORING_OP_MADVISE] = {},
0463b6c5 1109 [IORING_OP_SEND] = {
fddaface
JA
1110 .needs_file = 1,
1111 .unbound_nonreg_file = 1,
8a72758c 1112 .pollout = 1,
5bd2182d 1113 .audit_skip = 1,
fddaface 1114 },
0463b6c5 1115 [IORING_OP_RECV] = {
fddaface
JA
1116 .needs_file = 1,
1117 .unbound_nonreg_file = 1,
8a72758c 1118 .pollin = 1,
bcda7baa 1119 .buffer_select = 1,
5bd2182d 1120 .audit_skip = 1,
fddaface 1121 },
0463b6c5 1122 [IORING_OP_OPENAT2] = {
cebdb986 1123 },
3e4827b0
JA
1124 [IORING_OP_EPOLL_CTL] = {
1125 .unbound_nonreg_file = 1,
5bd2182d 1126 .audit_skip = 1,
3e4827b0 1127 },
7d67af2c
PB
1128 [IORING_OP_SPLICE] = {
1129 .needs_file = 1,
1130 .hash_reg_file = 1,
1131 .unbound_nonreg_file = 1,
5bd2182d
PM
1132 .audit_skip = 1,
1133 },
1134 [IORING_OP_PROVIDE_BUFFERS] = {
1135 .audit_skip = 1,
1136 },
1137 [IORING_OP_REMOVE_BUFFERS] = {
1138 .audit_skip = 1,
ddf0322d 1139 },
f2a8d5c7
PB
1140 [IORING_OP_TEE] = {
1141 .needs_file = 1,
1142 .hash_reg_file = 1,
1143 .unbound_nonreg_file = 1,
5bd2182d 1144 .audit_skip = 1,
f2a8d5c7 1145 },
36f4fa68
JA
1146 [IORING_OP_SHUTDOWN] = {
1147 .needs_file = 1,
1148 },
44526bed
JA
1149 [IORING_OP_RENAMEAT] = {},
1150 [IORING_OP_UNLINKAT] = {},
e34a02dc 1151 [IORING_OP_MKDIRAT] = {},
7a8721f8 1152 [IORING_OP_SYMLINKAT] = {},
cf30da90 1153 [IORING_OP_LINKAT] = {},
4f57f06c
JA
1154 [IORING_OP_MSG_RING] = {
1155 .needs_file = 1,
1156 },
d3656344
JA
1157};
1158
0756a869
PB
1159/* requests with any of those set should undergo io_disarm_next() */
1160#define IO_DISARM_MASK (REQ_F_ARM_LTIMEOUT | REQ_F_LINK_TIMEOUT | REQ_F_FAIL)
1161
7a612350 1162static bool io_disarm_next(struct io_kiocb *req);
eef51daa 1163static void io_uring_del_tctx_node(unsigned long index);
9936c7c2
PB
1164static void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
1165 struct task_struct *task,
3dd0c97a 1166 bool cancel_all);
78cc687b 1167static void io_uring_cancel_generic(bool cancel_all, struct io_sq_data *sqd);
1ffc5422 1168
913a571a
PB
1169static void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags);
1170
ec9c02ad 1171static void io_put_req(struct io_kiocb *req);
91c2f697 1172static void io_put_req_deferred(struct io_kiocb *req);
c7dae4ba 1173static void io_dismantle_req(struct io_kiocb *req);
94ae5e77 1174static void io_queue_linked_timeout(struct io_kiocb *req);
fdecb662 1175static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
c3bdad02 1176 struct io_uring_rsrc_update2 *up,
98f0b3b4 1177 unsigned nr_args);
68fb8979 1178static void io_clean_op(struct io_kiocb *req);
ac177053 1179static struct file *io_file_get(struct io_ring_ctx *ctx,
8371adf5 1180 struct io_kiocb *req, int fd, bool fixed);
c5eef2b9 1181static void __io_queue_sqe(struct io_kiocb *req);
269bbe5f 1182static void io_rsrc_put_work(struct work_struct *work);
de0617e4 1183
907d1df3 1184static void io_req_task_queue(struct io_kiocb *req);
c450178d 1185static void __io_submit_flush_completions(struct io_ring_ctx *ctx);
179ae0d1 1186static int io_req_prep_async(struct io_kiocb *req);
de0617e4 1187
b9445598
PB
1188static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
1189 unsigned int issue_flags, u32 slot_index);
7df778be
PB
1190static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags);
1191
f1042b6c 1192static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer);
9aa8dfde 1193static void io_eventfd_signal(struct io_ring_ctx *ctx);
b9445598 1194
2b188cc1
JA
1195static struct kmem_cache *req_cachep;
1196
0918682b 1197static const struct file_operations io_uring_fops;
2b188cc1
JA
1198
1199struct sock *io_uring_get_socket(struct file *file)
1200{
1201#if defined(CONFIG_UNIX)
1202 if (file->f_op == &io_uring_fops) {
1203 struct io_ring_ctx *ctx = file->private_data;
1204
1205 return ctx->ring_sock->sk;
1206 }
1207#endif
1208 return NULL;
1209}
1210EXPORT_SYMBOL(io_uring_get_socket);
1211
f237c30a
PB
1212static inline void io_tw_lock(struct io_ring_ctx *ctx, bool *locked)
1213{
1214 if (!*locked) {
1215 mutex_lock(&ctx->uring_lock);
1216 *locked = true;
1217 }
1218}
1219
f2f87370
PB
1220#define io_for_each_link(pos, head) \
1221 for (pos = (head); pos; pos = pos->link)
1222
21c843d5
PB
1223/*
1224 * Shamelessly stolen from the mm implementation of page reference checking,
1225 * see commit f958d7b528b1 for details.
1226 */
1227#define req_ref_zero_or_close_to_overflow(req) \
1228 ((unsigned int) atomic_read(&(req->refs)) + 127u <= 127u)
1229
1230static inline bool req_ref_inc_not_zero(struct io_kiocb *req)
1231{
20e60a38 1232 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
21c843d5
PB
1233 return atomic_inc_not_zero(&req->refs);
1234}
1235
21c843d5
PB
1236static inline bool req_ref_put_and_test(struct io_kiocb *req)
1237{
20e60a38
PB
1238 if (likely(!(req->flags & REQ_F_REFCOUNT)))
1239 return true;
1240
21c843d5
PB
1241 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1242 return atomic_dec_and_test(&req->refs);
1243}
1244
21c843d5
PB
1245static inline void req_ref_get(struct io_kiocb *req)
1246{
20e60a38 1247 WARN_ON_ONCE(!(req->flags & REQ_F_REFCOUNT));
21c843d5
PB
1248 WARN_ON_ONCE(req_ref_zero_or_close_to_overflow(req));
1249 atomic_inc(&req->refs);
1250}
1251
c450178d
PB
1252static inline void io_submit_flush_completions(struct io_ring_ctx *ctx)
1253{
6f33b0bc 1254 if (!wq_list_empty(&ctx->submit_state.compl_reqs))
c450178d
PB
1255 __io_submit_flush_completions(ctx);
1256}
1257
48dcd38d 1258static inline void __io_req_set_refcount(struct io_kiocb *req, int nr)
20e60a38
PB
1259{
1260 if (!(req->flags & REQ_F_REFCOUNT)) {
1261 req->flags |= REQ_F_REFCOUNT;
48dcd38d 1262 atomic_set(&req->refs, nr);
20e60a38
PB
1263 }
1264}
1265
48dcd38d
PB
1266static inline void io_req_set_refcount(struct io_kiocb *req)
1267{
1268 __io_req_set_refcount(req, 1);
1269}
1270
ab409402
PB
1271#define IO_RSRC_REF_BATCH 100
1272
1273static inline void io_req_put_rsrc_locked(struct io_kiocb *req,
1274 struct io_ring_ctx *ctx)
1275 __must_hold(&ctx->uring_lock)
36f72fe2 1276{
ab409402
PB
1277 struct percpu_ref *ref = req->fixed_rsrc_refs;
1278
1279 if (ref) {
1280 if (ref == &ctx->rsrc_node->refs)
1281 ctx->rsrc_cached_refs++;
1282 else
1283 percpu_ref_put(ref);
1284 }
1285}
1286
1287static inline void io_req_put_rsrc(struct io_kiocb *req, struct io_ring_ctx *ctx)
1288{
1289 if (req->fixed_rsrc_refs)
1290 percpu_ref_put(req->fixed_rsrc_refs);
1291}
1292
1293static __cold void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
1294 __must_hold(&ctx->uring_lock)
1295{
1296 if (ctx->rsrc_cached_refs) {
1297 percpu_ref_put_many(&ctx->rsrc_node->refs, ctx->rsrc_cached_refs);
1298 ctx->rsrc_cached_refs = 0;
1299 }
1300}
1301
1302static void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
1303 __must_hold(&ctx->uring_lock)
1304{
1305 ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
1306 percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
1307}
36f72fe2 1308
a46be971
PB
1309static inline void io_req_set_rsrc_node(struct io_kiocb *req,
1310 struct io_ring_ctx *ctx)
36f72fe2 1311{
269bbe5f 1312 if (!req->fixed_rsrc_refs) {
a7f0ed5a 1313 req->fixed_rsrc_refs = &ctx->rsrc_node->refs;
ab409402
PB
1314 ctx->rsrc_cached_refs--;
1315 if (unlikely(ctx->rsrc_cached_refs < 0))
1316 io_rsrc_refs_refill(ctx);
36f72fe2
PB
1317 }
1318}
1319
cc3cec83 1320static unsigned int __io_put_kbuf(struct io_kiocb *req, struct list_head *list)
3648e526 1321{
d1fd1c20 1322 struct io_buffer *kbuf = req->kbuf;
3648e526
HX
1323 unsigned int cflags;
1324
cc3cec83 1325 cflags = IORING_CQE_F_BUFFER | (kbuf->bid << IORING_CQE_BUFFER_SHIFT);
3648e526 1326 req->flags &= ~REQ_F_BUFFER_SELECTED;
cc3cec83 1327 list_add(&kbuf->list, list);
d1fd1c20 1328 req->kbuf = NULL;
3648e526
HX
1329 return cflags;
1330}
1331
cc3cec83 1332static inline unsigned int io_put_kbuf_comp(struct io_kiocb *req)
3648e526
HX
1333{
1334 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1335 return 0;
cc3cec83
JA
1336 return __io_put_kbuf(req, &req->ctx->io_buffers_comp);
1337}
1338
1339static inline unsigned int io_put_kbuf(struct io_kiocb *req,
1340 unsigned issue_flags)
1341{
1342 unsigned int cflags;
1343
1344 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1345 return 0;
1346
1347 /*
1348 * We can add this buffer back to two lists:
1349 *
1350 * 1) The io_buffers_cache list. This one is protected by the
1351 * ctx->uring_lock. If we already hold this lock, add back to this
1352 * list as we can grab it from issue as well.
1353 * 2) The io_buffers_comp list. This one is protected by the
1354 * ctx->completion_lock.
1355 *
1356 * We migrate buffers from the comp_list to the issue cache list
1357 * when we need one.
1358 */
1359 if (issue_flags & IO_URING_F_UNLOCKED) {
1360 struct io_ring_ctx *ctx = req->ctx;
1361
1362 spin_lock(&ctx->completion_lock);
1363 cflags = __io_put_kbuf(req, &ctx->io_buffers_comp);
1364 spin_unlock(&ctx->completion_lock);
1365 } else {
1366 cflags = __io_put_kbuf(req, &req->ctx->io_buffers_cache);
1367 }
1368
1369 return cflags;
3648e526
HX
1370}
1371
dbc7d452
JA
1372static struct io_buffer_list *io_buffer_get_list(struct io_ring_ctx *ctx,
1373 unsigned int bgid)
1374{
1375 struct list_head *hash_list;
1376 struct io_buffer_list *bl;
1377
1378 hash_list = &ctx->io_buffers[hash_32(bgid, IO_BUFFERS_HASH_BITS)];
1379 list_for_each_entry(bl, hash_list, list)
1380 if (bl->bgid == bgid || bgid == -1U)
1381 return bl;
1382
1383 return NULL;
1384}
1385
b1c62645
JA
1386static void io_kbuf_recycle(struct io_kiocb *req)
1387{
1388 struct io_ring_ctx *ctx = req->ctx;
dbc7d452
JA
1389 struct io_buffer_list *bl;
1390 struct io_buffer *buf;
b1c62645
JA
1391
1392 if (likely(!(req->flags & REQ_F_BUFFER_SELECTED)))
1393 return;
1394
1395 lockdep_assert_held(&ctx->uring_lock);
1396
1397 buf = req->kbuf;
dbc7d452
JA
1398 bl = io_buffer_get_list(ctx, buf->bgid);
1399 list_add(&buf->list, &bl->buf_list);
b1c62645
JA
1400 req->flags &= ~REQ_F_BUFFER_SELECTED;
1401 req->kbuf = NULL;
1402}
1403
3dd0c97a
PB
1404static bool io_match_task(struct io_kiocb *head, struct task_struct *task,
1405 bool cancel_all)
6af3f48b 1406 __must_hold(&req->ctx->timeout_lock)
08d23634
PB
1407{
1408 struct io_kiocb *req;
1409
68207680 1410 if (task && head->task != task)
08d23634 1411 return false;
3dd0c97a 1412 if (cancel_all)
08d23634
PB
1413 return true;
1414
1415 io_for_each_link(req, head) {
b05a1bcd 1416 if (req->flags & REQ_F_INFLIGHT)
02a13674 1417 return true;
08d23634
PB
1418 }
1419 return false;
1420}
1421
6af3f48b
PB
1422static bool io_match_linked(struct io_kiocb *head)
1423{
1424 struct io_kiocb *req;
1425
1426 io_for_each_link(req, head) {
1427 if (req->flags & REQ_F_INFLIGHT)
1428 return true;
1429 }
1430 return false;
1431}
1432
1433/*
1434 * As io_match_task() but protected against racing with linked timeouts.
1435 * User must not hold timeout_lock.
1436 */
1437static bool io_match_task_safe(struct io_kiocb *head, struct task_struct *task,
1438 bool cancel_all)
1439{
1440 bool matched;
1441
1442 if (task && head->task != task)
1443 return false;
1444 if (cancel_all)
1445 return true;
1446
1447 if (head->flags & REQ_F_LINK_TIMEOUT) {
1448 struct io_ring_ctx *ctx = head->ctx;
1449
1450 /* protect against races with linked timeouts */
1451 spin_lock_irq(&ctx->timeout_lock);
1452 matched = io_match_linked(head);
1453 spin_unlock_irq(&ctx->timeout_lock);
1454 } else {
1455 matched = io_match_linked(head);
1456 }
1457 return matched;
1458}
1459
d886e185
PB
1460static inline bool req_has_async_data(struct io_kiocb *req)
1461{
1462 return req->flags & REQ_F_ASYNC_DATA;
1463}
1464
93d2bcd2 1465static inline void req_set_fail(struct io_kiocb *req)
c40f6379 1466{
93d2bcd2 1467 req->flags |= REQ_F_FAIL;
04c76b41
PB
1468 if (req->flags & REQ_F_CQE_SKIP) {
1469 req->flags &= ~REQ_F_CQE_SKIP;
1470 req->flags |= REQ_F_SKIP_LINK_CQES;
1471 }
c40f6379 1472}
4a38aed2 1473
a8295b98
HX
1474static inline void req_fail_link_node(struct io_kiocb *req, int res)
1475{
1476 req_set_fail(req);
1477 req->result = res;
1478}
1479
c072481d 1480static __cold void io_ring_ctx_ref_free(struct percpu_ref *ref)
2b188cc1
JA
1481{
1482 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
1483
0f158b4c 1484 complete(&ctx->ref_comp);
2b188cc1
JA
1485}
1486
8eb7e2d0
PB
1487static inline bool io_is_timeout_noseq(struct io_kiocb *req)
1488{
1489 return !req->timeout.off;
1490}
1491
c072481d 1492static __cold void io_fallback_req_func(struct work_struct *work)
f56165e6
PB
1493{
1494 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx,
1495 fallback_work.work);
1496 struct llist_node *node = llist_del_all(&ctx->fallback_llist);
1497 struct io_kiocb *req, *tmp;
f237c30a 1498 bool locked = false;
f56165e6
PB
1499
1500 percpu_ref_get(&ctx->refs);
1501 llist_for_each_entry_safe(req, tmp, node, io_task_work.fallback_node)
f237c30a 1502 req->io_task_work.func(req, &locked);
5636c00d 1503
f237c30a 1504 if (locked) {
c450178d 1505 io_submit_flush_completions(ctx);
f237c30a
PB
1506 mutex_unlock(&ctx->uring_lock);
1507 }
f56165e6
PB
1508 percpu_ref_put(&ctx->refs);
1509}
1510
c072481d 1511static __cold struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
2b188cc1
JA
1512{
1513 struct io_ring_ctx *ctx;
dbc7d452 1514 int i, hash_bits;
2b188cc1
JA
1515
1516 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
1517 if (!ctx)
1518 return NULL;
1519
78076bb6
JA
1520 /*
1521 * Use 5 bits less than the max cq entries, that should give us around
1522 * 32 entries per hash list if totally full and uniformly spread.
1523 */
1524 hash_bits = ilog2(p->cq_entries);
1525 hash_bits -= 5;
1526 if (hash_bits <= 0)
1527 hash_bits = 1;
1528 ctx->cancel_hash_bits = hash_bits;
1529 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1530 GFP_KERNEL);
1531 if (!ctx->cancel_hash)
1532 goto err;
1533 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1534
6224843d
PB
1535 ctx->dummy_ubuf = kzalloc(sizeof(*ctx->dummy_ubuf), GFP_KERNEL);
1536 if (!ctx->dummy_ubuf)
1537 goto err;
1538 /* set invalid range, so io_import_fixed() fails meeting it */
1539 ctx->dummy_ubuf->ubuf = -1UL;
1540
dbc7d452
JA
1541 ctx->io_buffers = kcalloc(1U << IO_BUFFERS_HASH_BITS,
1542 sizeof(struct list_head), GFP_KERNEL);
1543 if (!ctx->io_buffers)
1544 goto err;
1545 for (i = 0; i < (1U << IO_BUFFERS_HASH_BITS); i++)
1546 INIT_LIST_HEAD(&ctx->io_buffers[i]);
1547
21482896 1548 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
206aefde
JA
1549 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1550 goto err;
2b188cc1
JA
1551
1552 ctx->flags = p->flags;
90554200 1553 init_waitqueue_head(&ctx->sqo_sq_wait);
69fb2131 1554 INIT_LIST_HEAD(&ctx->sqd_list);
1d7bb1d5 1555 INIT_LIST_HEAD(&ctx->cq_overflow_list);
cc3cec83 1556 INIT_LIST_HEAD(&ctx->io_buffers_cache);
4d9237e3 1557 INIT_LIST_HEAD(&ctx->apoll_cache);
0f158b4c 1558 init_completion(&ctx->ref_comp);
61cf9370 1559 xa_init_flags(&ctx->personalities, XA_FLAGS_ALLOC1);
2b188cc1 1560 mutex_init(&ctx->uring_lock);
311997b3 1561 init_waitqueue_head(&ctx->cq_wait);
2b188cc1 1562 spin_lock_init(&ctx->completion_lock);
89850fce 1563 spin_lock_init(&ctx->timeout_lock);
5eef4e87 1564 INIT_WQ_LIST(&ctx->iopoll_list);
cc3cec83
JA
1565 INIT_LIST_HEAD(&ctx->io_buffers_pages);
1566 INIT_LIST_HEAD(&ctx->io_buffers_comp);
de0617e4 1567 INIT_LIST_HEAD(&ctx->defer_list);
5262f567 1568 INIT_LIST_HEAD(&ctx->timeout_list);
ef9dd637 1569 INIT_LIST_HEAD(&ctx->ltimeout_list);
d67d2263
BM
1570 spin_lock_init(&ctx->rsrc_ref_lock);
1571 INIT_LIST_HEAD(&ctx->rsrc_ref_list);
269bbe5f
BM
1572 INIT_DELAYED_WORK(&ctx->rsrc_put_work, io_rsrc_put_work);
1573 init_llist_head(&ctx->rsrc_put_llist);
13bf43f5 1574 INIT_LIST_HEAD(&ctx->tctx_list);
c2b6c6bc
PB
1575 ctx->submit_state.free_list.next = NULL;
1576 INIT_WQ_LIST(&ctx->locked_free_list);
9011bf9a 1577 INIT_DELAYED_WORK(&ctx->fallback_work, io_fallback_req_func);
6f33b0bc 1578 INIT_WQ_LIST(&ctx->submit_state.compl_reqs);
adc8682e
OL
1579#ifdef CONFIG_NET_RX_BUSY_POLL
1580 INIT_LIST_HEAD(&ctx->napi_list);
1581 spin_lock_init(&ctx->napi_lock);
1582#endif
2b188cc1 1583 return ctx;
206aefde 1584err:
6224843d 1585 kfree(ctx->dummy_ubuf);
78076bb6 1586 kfree(ctx->cancel_hash);
dbc7d452 1587 kfree(ctx->io_buffers);
206aefde
JA
1588 kfree(ctx);
1589 return NULL;
2b188cc1
JA
1590}
1591
8f6ed49a
PB
1592static void io_account_cq_overflow(struct io_ring_ctx *ctx)
1593{
1594 struct io_rings *r = ctx->rings;
1595
1596 WRITE_ONCE(r->cq_overflow, READ_ONCE(r->cq_overflow) + 1);
1597 ctx->cq_extra--;
1598}
1599
9cf7c104 1600static bool req_need_defer(struct io_kiocb *req, u32 seq)
7adf4eaf 1601{
2bc9930e
JA
1602 if (unlikely(req->flags & REQ_F_IO_DRAIN)) {
1603 struct io_ring_ctx *ctx = req->ctx;
a197f664 1604
8f6ed49a 1605 return seq + READ_ONCE(ctx->cq_extra) != ctx->cached_cq_tail;
2bc9930e 1606 }
de0617e4 1607
9d858b21 1608 return false;
de0617e4
JA
1609}
1610
35645ac3
PB
1611#define FFS_NOWAIT 0x1UL
1612#define FFS_ISREG 0x2UL
1613#define FFS_MASK ~(FFS_NOWAIT|FFS_ISREG)
c97d8a0f
PB
1614
1615static inline bool io_req_ffs_set(struct io_kiocb *req)
1616{
35645ac3 1617 return req->flags & REQ_F_FIXED_FILE;
c97d8a0f
PB
1618}
1619
c072481d 1620static inline void io_req_track_inflight(struct io_kiocb *req)
ce3d5aae 1621{
ce3d5aae 1622 if (!(req->flags & REQ_F_INFLIGHT)) {
ce3d5aae 1623 req->flags |= REQ_F_INFLIGHT;
b303fe2e 1624 atomic_inc(&current->io_uring->inflight_tracked);
ce3d5aae
PB
1625 }
1626}
1627
fd08e530
PB
1628static struct io_kiocb *__io_prep_linked_timeout(struct io_kiocb *req)
1629{
906c6caa
PB
1630 if (WARN_ON_ONCE(!req->link))
1631 return NULL;
1632
4d13d1a4
PB
1633 req->flags &= ~REQ_F_ARM_LTIMEOUT;
1634 req->flags |= REQ_F_LINK_TIMEOUT;
fd08e530
PB
1635
1636 /* linked timeouts should have two refs once prep'ed */
48dcd38d 1637 io_req_set_refcount(req);
4d13d1a4
PB
1638 __io_req_set_refcount(req->link, 2);
1639 return req->link;
fd08e530
PB
1640}
1641
1642static inline struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
1643{
4d13d1a4 1644 if (likely(!(req->flags & REQ_F_ARM_LTIMEOUT)))
fd08e530
PB
1645 return NULL;
1646 return __io_prep_linked_timeout(req);
1647}
1648
1e6fa521
JA
1649static void io_prep_async_work(struct io_kiocb *req)
1650{
1651 const struct io_op_def *def = &io_op_defs[req->opcode];
1e6fa521
JA
1652 struct io_ring_ctx *ctx = req->ctx;
1653
b8e64b53
PB
1654 if (!(req->flags & REQ_F_CREDS)) {
1655 req->flags |= REQ_F_CREDS;
c10d1f98 1656 req->creds = get_current_cred();
b8e64b53 1657 }
003e8dcc 1658
e1d675df
PB
1659 req->work.list.next = NULL;
1660 req->work.flags = 0;
feaadc4f
PB
1661 if (req->flags & REQ_F_FORCE_ASYNC)
1662 req->work.flags |= IO_WQ_WORK_CONCURRENT;
1663
1e6fa521
JA
1664 if (req->flags & REQ_F_ISREG) {
1665 if (def->hash_reg_file || (ctx->flags & IORING_SETUP_IOPOLL))
1666 io_wq_hash_work(&req->work, file_inode(req->file));
4b982bd0 1667 } else if (!req->file || !S_ISBLK(file_inode(req->file)->i_mode)) {
1e6fa521
JA
1668 if (def->unbound_nonreg_file)
1669 req->work.flags |= IO_WQ_WORK_UNBOUND;
1670 }
e1d675df
PB
1671
1672 switch (req->opcode) {
1673 case IORING_OP_SPLICE:
1674 case IORING_OP_TEE:
e1d675df
PB
1675 if (!S_ISREG(file_inode(req->splice.file_in)->i_mode))
1676 req->work.flags |= IO_WQ_WORK_UNBOUND;
1677 break;
1678 }
561fb04a 1679}
cccf0ee8 1680
cbdcb435 1681static void io_prep_async_link(struct io_kiocb *req)
561fb04a 1682{
cbdcb435 1683 struct io_kiocb *cur;
54a91f3b 1684
44eff40a
PB
1685 if (req->flags & REQ_F_LINK_TIMEOUT) {
1686 struct io_ring_ctx *ctx = req->ctx;
1687
674ee8e1 1688 spin_lock_irq(&ctx->timeout_lock);
44eff40a
PB
1689 io_for_each_link(cur, req)
1690 io_prep_async_work(cur);
674ee8e1 1691 spin_unlock_irq(&ctx->timeout_lock);
44eff40a
PB
1692 } else {
1693 io_for_each_link(cur, req)
1694 io_prep_async_work(cur);
1695 }
561fb04a
JA
1696}
1697
fff4e40e
PB
1698static inline void io_req_add_compl_list(struct io_kiocb *req)
1699{
3d4aeb9f 1700 struct io_ring_ctx *ctx = req->ctx;
33ce2aff 1701 struct io_submit_state *state = &ctx->submit_state;
fff4e40e 1702
3d4aeb9f
PB
1703 if (!(req->flags & REQ_F_CQE_SKIP))
1704 ctx->submit_state.flush_cqes = true;
fff4e40e
PB
1705 wq_list_add_tail(&req->comp_list, &state->compl_reqs);
1706}
1707
00169246 1708static void io_queue_async_work(struct io_kiocb *req, bool *dont_use)
561fb04a 1709{
a197f664 1710 struct io_ring_ctx *ctx = req->ctx;
cbdcb435 1711 struct io_kiocb *link = io_prep_linked_timeout(req);
5aa75ed5 1712 struct io_uring_task *tctx = req->task->io_uring;
561fb04a 1713
3bfe6106
JA
1714 BUG_ON(!tctx);
1715 BUG_ON(!tctx->io_wq);
561fb04a 1716
cbdcb435
PB
1717 /* init ->work of the whole link before punting */
1718 io_prep_async_link(req);
991468dc
JA
1719
1720 /*
1721 * Not expected to happen, but if we do have a bug where this _can_
1722 * happen, catch it here and ensure the request is marked as
1723 * canceled. That will make io-wq go through the usual work cancel
1724 * procedure rather than attempt to run this request (or create a new
1725 * worker for it).
1726 */
1727 if (WARN_ON_ONCE(!same_thread_group(req->task, current)))
1728 req->work.flags |= IO_WQ_WORK_CANCEL;
1729
502c87d6
SR
1730 trace_io_uring_queue_async_work(ctx, req, req->user_data, req->opcode, req->flags,
1731 &req->work, io_wq_is_hashed(&req->work));
ebf93667 1732 io_wq_enqueue(tctx->io_wq, &req->work);
7271ef3a
JA
1733 if (link)
1734 io_queue_linked_timeout(link);
cbdcb435
PB
1735}
1736
1ee4160c 1737static void io_kill_timeout(struct io_kiocb *req, int status)
8c855885 1738 __must_hold(&req->ctx->completion_lock)
89850fce 1739 __must_hold(&req->ctx->timeout_lock)
5262f567 1740{
e8c2bc1f 1741 struct io_timeout_data *io = req->async_data;
5262f567 1742
fd9c7bc5 1743 if (hrtimer_try_to_cancel(&io->timer) != -1) {
2ae2eb9d
PB
1744 if (status)
1745 req_set_fail(req);
01cec8c1
PB
1746 atomic_set(&req->ctx->cq_timeouts,
1747 atomic_read(&req->ctx->cq_timeouts) + 1);
135fcde8 1748 list_del_init(&req->timeout.list);
913a571a 1749 io_fill_cqe_req(req, status, 0);
91c2f697 1750 io_put_req_deferred(req);
5262f567
JA
1751 }
1752}
1753
c072481d 1754static __cold void io_queue_deferred(struct io_ring_ctx *ctx)
de0617e4 1755{
441b8a78 1756 while (!list_empty(&ctx->defer_list)) {
27dc8338
PB
1757 struct io_defer_entry *de = list_first_entry(&ctx->defer_list,
1758 struct io_defer_entry, list);
de0617e4 1759
9cf7c104 1760 if (req_need_defer(de->req, de->seq))
04518945 1761 break;
27dc8338 1762 list_del_init(&de->list);
907d1df3 1763 io_req_task_queue(de->req);
27dc8338 1764 kfree(de);
441b8a78 1765 }
04518945
PB
1766}
1767
c072481d 1768static __cold void io_flush_timeouts(struct io_ring_ctx *ctx)
89850fce 1769 __must_hold(&ctx->completion_lock)
de0617e4 1770{
441b8a78 1771 u32 seq = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
f010505b 1772
79ebeaee 1773 spin_lock_irq(&ctx->timeout_lock);
f18ee4cf 1774 while (!list_empty(&ctx->timeout_list)) {
f010505b 1775 u32 events_needed, events_got;
360428f8 1776 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
135fcde8 1777 struct io_kiocb, timeout.list);
de0617e4 1778
8eb7e2d0 1779 if (io_is_timeout_noseq(req))
360428f8 1780 break;
f010505b
MDG
1781
1782 /*
1783 * Since seq can easily wrap around over time, subtract
1784 * the last seq at which timeouts were flushed before comparing.
1785 * Assuming not more than 2^31-1 events have happened since,
1786 * these subtractions won't have wrapped, so we can check if
1787 * target is in [last_seq, current_seq] by comparing the two.
1788 */
1789 events_needed = req->timeout.target_seq - ctx->cq_last_tm_flush;
1790 events_got = seq - ctx->cq_last_tm_flush;
1791 if (events_got < events_needed)
360428f8 1792 break;
bfe68a22 1793
135fcde8 1794 list_del_init(&req->timeout.list);
1ee4160c 1795 io_kill_timeout(req, 0);
f18ee4cf 1796 }
f010505b 1797 ctx->cq_last_tm_flush = seq;
79ebeaee 1798 spin_unlock_irq(&ctx->timeout_lock);
360428f8 1799}
5262f567 1800
9333f6b4
PB
1801static inline void io_commit_cqring(struct io_ring_ctx *ctx)
1802{
1803 /* order cqe stores with ring update */
1804 smp_store_release(&ctx->rings->cq.tail, ctx->cached_cq_tail);
1805}
1806
9aa8dfde 1807static void __io_commit_cqring_flush(struct io_ring_ctx *ctx)
360428f8 1808{
9aa8dfde
PB
1809 if (ctx->off_timeout_used || ctx->drain_active) {
1810 spin_lock(&ctx->completion_lock);
1811 if (ctx->off_timeout_used)
1812 io_flush_timeouts(ctx);
1813 if (ctx->drain_active)
1814 io_queue_deferred(ctx);
1815 io_commit_cqring(ctx);
1816 spin_unlock(&ctx->completion_lock);
1817 }
1818 if (ctx->has_evfd)
1819 io_eventfd_signal(ctx);
de0617e4
JA
1820}
1821
90554200
JA
1822static inline bool io_sqring_full(struct io_ring_ctx *ctx)
1823{
1824 struct io_rings *r = ctx->rings;
1825
a566c556 1826 return READ_ONCE(r->sq.tail) - ctx->cached_sq_head == ctx->sq_entries;
90554200
JA
1827}
1828
888aae2e
PB
1829static inline unsigned int __io_cqring_events(struct io_ring_ctx *ctx)
1830{
1831 return ctx->cached_cq_tail - READ_ONCE(ctx->rings->cq.head);
1832}
1833
d068b506 1834static inline struct io_uring_cqe *io_get_cqe(struct io_ring_ctx *ctx)
2b188cc1 1835{
75b28aff 1836 struct io_rings *rings = ctx->rings;
ea5ab3b5 1837 unsigned tail, mask = ctx->cq_entries - 1;
2b188cc1 1838
115e12e5
SB
1839 /*
1840 * writes to the cq entry need to come after reading head; the
1841 * control dependency is enough as we're using WRITE_ONCE to
1842 * fill the cq entry
1843 */
a566c556 1844 if (__io_cqring_events(ctx) == ctx->cq_entries)
2b188cc1
JA
1845 return NULL;
1846
888aae2e 1847 tail = ctx->cached_cq_tail++;
ea5ab3b5 1848 return &rings->cqes[tail & mask];
2b188cc1
JA
1849}
1850
77bc59b4 1851static void io_eventfd_signal(struct io_ring_ctx *ctx)
f2842ab5 1852{
77bc59b4
UA
1853 struct io_ev_fd *ev_fd;
1854
77bc59b4
UA
1855 rcu_read_lock();
1856 /*
1857 * rcu_dereference ctx->io_ev_fd once and use it for both for checking
1858 * and eventfd_signal
1859 */
1860 ev_fd = rcu_dereference(ctx->io_ev_fd);
1861
1862 /*
1863 * Check again if ev_fd exists incase an io_eventfd_unregister call
1864 * completed between the NULL check of ctx->io_ev_fd at the start of
1865 * the function and rcu_read_lock.
1866 */
1867 if (unlikely(!ev_fd))
1868 goto out;
7e55a19c 1869 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
77bc59b4
UA
1870 goto out;
1871
c75312dd 1872 if (!ev_fd->eventfd_async || io_wq_current_is_worker())
77bc59b4 1873 eventfd_signal(ev_fd->cq_ev_fd, 1);
77bc59b4
UA
1874out:
1875 rcu_read_unlock();
f2842ab5
JA
1876}
1877
9aa8dfde
PB
1878static inline void io_cqring_wake(struct io_ring_ctx *ctx)
1879{
1880 /*
1881 * wake_up_all() may seem excessive, but io_wake_function() and
1882 * io_should_wake() handle the termination of the loop and only
1883 * wake as many waiters as we need to.
1884 */
1885 if (wq_has_sleeper(&ctx->cq_wait))
1886 wake_up_all(&ctx->cq_wait);
1887}
1888
2c5d763c
JA
1889/*
1890 * This should only get called when at least one event has been posted.
1891 * Some applications rely on the eventfd notification count only changing
1892 * IFF a new CQE has been added to the CQ ring. There's no depedency on
1893 * 1:1 relationship between how many times this function is called (and
1894 * hence the eventfd count) and number of CQEs posted to the CQ ring.
1895 */
66fc25ca 1896static inline void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1d7bb1d5 1897{
9aa8dfde
PB
1898 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1899 ctx->has_evfd))
9333f6b4
PB
1900 __io_commit_cqring_flush(ctx);
1901
9aa8dfde 1902 io_cqring_wake(ctx);
1d7bb1d5
JA
1903}
1904
80c18e4a
PB
1905static void io_cqring_ev_posted_iopoll(struct io_ring_ctx *ctx)
1906{
9aa8dfde
PB
1907 if (unlikely(ctx->off_timeout_used || ctx->drain_active ||
1908 ctx->has_evfd))
9333f6b4
PB
1909 __io_commit_cqring_flush(ctx);
1910
9aa8dfde
PB
1911 if (ctx->flags & IORING_SETUP_SQPOLL)
1912 io_cqring_wake(ctx);
80c18e4a
PB
1913}
1914
c4a2ed72 1915/* Returns true if there are no backlogged entries after the flush */
6c2450ae 1916static bool __io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1d7bb1d5 1917{
b18032bb 1918 bool all_flushed, posted;
1d7bb1d5 1919
a566c556 1920 if (!force && __io_cqring_events(ctx) == ctx->cq_entries)
e23de15f 1921 return false;
1d7bb1d5 1922
b18032bb 1923 posted = false;
79ebeaee 1924 spin_lock(&ctx->completion_lock);
6c2450ae 1925 while (!list_empty(&ctx->cq_overflow_list)) {
d068b506 1926 struct io_uring_cqe *cqe = io_get_cqe(ctx);
6c2450ae 1927 struct io_overflow_cqe *ocqe;
e6c8aa9a 1928
1d7bb1d5
JA
1929 if (!cqe && !force)
1930 break;
6c2450ae
PB
1931 ocqe = list_first_entry(&ctx->cq_overflow_list,
1932 struct io_overflow_cqe, list);
1933 if (cqe)
1934 memcpy(cqe, &ocqe->cqe, sizeof(*cqe));
1935 else
8f6ed49a
PB
1936 io_account_cq_overflow(ctx);
1937
b18032bb 1938 posted = true;
6c2450ae
PB
1939 list_del(&ocqe->list);
1940 kfree(ocqe);
1d7bb1d5
JA
1941 }
1942
09e88404
PB
1943 all_flushed = list_empty(&ctx->cq_overflow_list);
1944 if (all_flushed) {
5ed7a37d 1945 clear_bit(0, &ctx->check_cq_overflow);
20c0b380
NA
1946 WRITE_ONCE(ctx->rings->sq_flags,
1947 ctx->rings->sq_flags & ~IORING_SQ_CQ_OVERFLOW);
09e88404 1948 }
46930143 1949
b18032bb
JA
1950 if (posted)
1951 io_commit_cqring(ctx);
79ebeaee 1952 spin_unlock(&ctx->completion_lock);
b18032bb
JA
1953 if (posted)
1954 io_cqring_ev_posted(ctx);
09e88404 1955 return all_flushed;
1d7bb1d5
JA
1956}
1957
90f67366 1958static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx)
6c503150 1959{
ca0a2651
JA
1960 bool ret = true;
1961
5ed7a37d 1962 if (test_bit(0, &ctx->check_cq_overflow)) {
6c503150
PB
1963 /* iopoll syncs against uring_lock, not completion_lock */
1964 if (ctx->flags & IORING_SETUP_IOPOLL)
1965 mutex_lock(&ctx->uring_lock);
90f67366 1966 ret = __io_cqring_overflow_flush(ctx, false);
6c503150
PB
1967 if (ctx->flags & IORING_SETUP_IOPOLL)
1968 mutex_unlock(&ctx->uring_lock);
1969 }
ca0a2651
JA
1970
1971 return ret;
6c503150
PB
1972}
1973
6a290a14
PB
1974/* must to be called somewhat shortly after putting a request */
1975static inline void io_put_task(struct task_struct *task, int nr)
1976{
1977 struct io_uring_task *tctx = task->io_uring;
1978
e98e49b2
PB
1979 if (likely(task == current)) {
1980 tctx->cached_refs += nr;
1981 } else {
1982 percpu_counter_sub(&tctx->inflight, nr);
1983 if (unlikely(atomic_read(&tctx->in_idle)))
1984 wake_up(&tctx->wait);
1985 put_task_struct_many(task, nr);
1986 }
6a290a14
PB
1987}
1988
9a10867a
PB
1989static void io_task_refs_refill(struct io_uring_task *tctx)
1990{
1991 unsigned int refill = -tctx->cached_refs + IO_TCTX_REFS_CACHE_NR;
1992
1993 percpu_counter_add(&tctx->inflight, refill);
1994 refcount_add(refill, &current->usage);
1995 tctx->cached_refs += refill;
1996}
1997
1998static inline void io_get_task_refs(int nr)
1999{
2000 struct io_uring_task *tctx = current->io_uring;
2001
2002 tctx->cached_refs -= nr;
2003 if (unlikely(tctx->cached_refs < 0))
2004 io_task_refs_refill(tctx);
2005}
2006
3cc7fdb9
PB
2007static __cold void io_uring_drop_tctx_refs(struct task_struct *task)
2008{
2009 struct io_uring_task *tctx = task->io_uring;
2010 unsigned int refs = tctx->cached_refs;
2011
2012 if (refs) {
2013 tctx->cached_refs = 0;
2014 percpu_counter_sub(&tctx->inflight, refs);
2015 put_task_struct_many(task, refs);
2016 }
2017}
2018
d4d19c19 2019static bool io_cqring_event_overflow(struct io_ring_ctx *ctx, u64 user_data,
54daa9b2 2020 s32 res, u32 cflags)
2b188cc1 2021{
cce4b8b0 2022 struct io_overflow_cqe *ocqe;
2b188cc1 2023
cce4b8b0
PB
2024 ocqe = kmalloc(sizeof(*ocqe), GFP_ATOMIC | __GFP_ACCOUNT);
2025 if (!ocqe) {
2026 /*
2027 * If we're in ring overflow flush mode, or in task cancel mode,
2028 * or cannot allocate an overflow entry, then we need to drop it
2029 * on the floor.
2030 */
8f6ed49a 2031 io_account_cq_overflow(ctx);
cce4b8b0 2032 return false;
2b188cc1 2033 }
cce4b8b0 2034 if (list_empty(&ctx->cq_overflow_list)) {
5ed7a37d 2035 set_bit(0, &ctx->check_cq_overflow);
20c0b380
NA
2036 WRITE_ONCE(ctx->rings->sq_flags,
2037 ctx->rings->sq_flags | IORING_SQ_CQ_OVERFLOW);
2038
cce4b8b0 2039 }
d4d19c19 2040 ocqe->cqe.user_data = user_data;
cce4b8b0
PB
2041 ocqe->cqe.res = res;
2042 ocqe->cqe.flags = cflags;
2043 list_add_tail(&ocqe->list, &ctx->cq_overflow_list);
2044 return true;
2b188cc1
JA
2045}
2046
ae4da189 2047static inline bool __io_fill_cqe(struct io_ring_ctx *ctx, u64 user_data,
913a571a 2048 s32 res, u32 cflags)
2b188cc1
JA
2049{
2050 struct io_uring_cqe *cqe;
2051
2052 /*
2053 * If we can't get a cq entry, userspace overflowed the
2054 * submission (by quite a lot). Increment the overflow count in
2055 * the ring.
2056 */
d068b506 2057 cqe = io_get_cqe(ctx);
1d7bb1d5 2058 if (likely(cqe)) {
d4d19c19 2059 WRITE_ONCE(cqe->user_data, user_data);
2b188cc1 2060 WRITE_ONCE(cqe->res, res);
bcda7baa 2061 WRITE_ONCE(cqe->flags, cflags);
8d13326e 2062 return true;
2b188cc1 2063 }
d4d19c19 2064 return io_cqring_event_overflow(ctx, user_data, res, cflags);
2b188cc1
JA
2065}
2066
ae4da189 2067static inline bool __io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
d5ec1dfa 2068{
502c87d6 2069 trace_io_uring_complete(req->ctx, req, req->user_data, res, cflags);
ae4da189 2070 return __io_fill_cqe(req->ctx, req->user_data, res, cflags);
d5ec1dfa
SR
2071}
2072
913a571a 2073static noinline void io_fill_cqe_req(struct io_kiocb *req, s32 res, u32 cflags)
bcda7baa 2074{
04c76b41 2075 if (!(req->flags & REQ_F_CQE_SKIP))
ae4da189 2076 __io_fill_cqe_req(req, res, cflags);
bcda7baa
JA
2077}
2078
913a571a
PB
2079static noinline bool io_fill_cqe_aux(struct io_ring_ctx *ctx, u64 user_data,
2080 s32 res, u32 cflags)
bcda7baa 2081{
913a571a 2082 ctx->cq_extra++;
502c87d6 2083 trace_io_uring_complete(ctx, NULL, user_data, res, cflags);
ae4da189 2084 return __io_fill_cqe(ctx, user_data, res, cflags);
bcda7baa
JA
2085}
2086
a37fae8a
HX
2087static void __io_req_complete_post(struct io_kiocb *req, s32 res,
2088 u32 cflags)
2b188cc1 2089{
78e19bbe 2090 struct io_ring_ctx *ctx = req->ctx;
2b188cc1 2091
04c76b41 2092 if (!(req->flags & REQ_F_CQE_SKIP))
ae4da189 2093 __io_fill_cqe_req(req, res, cflags);
c7dae4ba
JA
2094 /*
2095 * If we're the last reference to this request, add to our locked
2096 * free_list cache.
2097 */
de9b4cca 2098 if (req_ref_put_and_test(req)) {
7a612350 2099 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
0756a869 2100 if (req->flags & IO_DISARM_MASK)
7a612350
PB
2101 io_disarm_next(req);
2102 if (req->link) {
2103 io_req_task_queue(req->link);
2104 req->link = NULL;
2105 }
2106 }
ab409402 2107 io_req_put_rsrc(req, ctx);
c7dae4ba
JA
2108 io_dismantle_req(req);
2109 io_put_task(req->task, 1);
c2b6c6bc 2110 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
d0acdee2 2111 ctx->locked_free_nr++;
180f829f 2112 }
a37fae8a
HX
2113}
2114
2115static void io_req_complete_post(struct io_kiocb *req, s32 res,
2116 u32 cflags)
2117{
2118 struct io_ring_ctx *ctx = req->ctx;
2119
2120 spin_lock(&ctx->completion_lock);
2121 __io_req_complete_post(req, res, cflags);
7a612350 2122 io_commit_cqring(ctx);
79ebeaee 2123 spin_unlock(&ctx->completion_lock);
a3f34907 2124 io_cqring_ev_posted(ctx);
4e3d9ff9
JA
2125}
2126
54daa9b2
PB
2127static inline void io_req_complete_state(struct io_kiocb *req, s32 res,
2128 u32 cflags)
229a7b63 2129{
a38d68db 2130 req->result = res;
d17e56eb 2131 req->cflags = cflags;
e342c807 2132 req->flags |= REQ_F_COMPLETE_INLINE;
e1e16097
JA
2133}
2134
889fca73 2135static inline void __io_req_complete(struct io_kiocb *req, unsigned issue_flags,
54daa9b2 2136 s32 res, u32 cflags)
bcda7baa 2137{
889fca73
PB
2138 if (issue_flags & IO_URING_F_COMPLETE_DEFER)
2139 io_req_complete_state(req, res, cflags);
a38d68db 2140 else
c7dae4ba 2141 io_req_complete_post(req, res, cflags);
bcda7baa
JA
2142}
2143
54daa9b2 2144static inline void io_req_complete(struct io_kiocb *req, s32 res)
0ddf92e8 2145{
889fca73 2146 __io_req_complete(req, 0, res, 0);
0ddf92e8
JA
2147}
2148
54daa9b2 2149static void io_req_complete_failed(struct io_kiocb *req, s32 res)
f41db273 2150{
93d2bcd2 2151 req_set_fail(req);
3b2b78a8 2152 io_req_complete_post(req, res, io_put_kbuf(req, 0));
f41db273
PB
2153}
2154
c6d3d9cb
PB
2155static void io_req_complete_fail_submit(struct io_kiocb *req)
2156{
2157 /*
2158 * We don't submit, fail them all, for that replace hardlinks with
2159 * normal links. Extra REQ_F_LINK is tolerated.
2160 */
2161 req->flags &= ~REQ_F_HARDLINK;
2162 req->flags |= REQ_F_LINK;
2163 io_req_complete_failed(req, req->result);
2164}
2165
864ea921
PB
2166/*
2167 * Don't initialise the fields below on every allocation, but do that in
2168 * advance and keep them valid across allocations.
2169 */
2170static void io_preinit_req(struct io_kiocb *req, struct io_ring_ctx *ctx)
2171{
2172 req->ctx = ctx;
2173 req->link = NULL;
2174 req->async_data = NULL;
2175 /* not necessary, but safer to zero */
2176 req->result = 0;
2177}
2178
dac7a098 2179static void io_flush_cached_locked_reqs(struct io_ring_ctx *ctx,
cd0ca2e0 2180 struct io_submit_state *state)
dac7a098 2181{
79ebeaee 2182 spin_lock(&ctx->completion_lock);
c2b6c6bc 2183 wq_list_splice(&ctx->locked_free_list, &state->free_list);
d0acdee2 2184 ctx->locked_free_nr = 0;
79ebeaee 2185 spin_unlock(&ctx->completion_lock);
dac7a098
PB
2186}
2187
dd78f492 2188/* Returns true IFF there are requests in the cache */
c7dae4ba 2189static bool io_flush_cached_reqs(struct io_ring_ctx *ctx)
0ddf92e8 2190{
c7dae4ba 2191 struct io_submit_state *state = &ctx->submit_state;
0ddf92e8 2192
c7dae4ba
JA
2193 /*
2194 * If we have more than a batch's worth of requests in our IRQ side
2195 * locked cache, grab the lock and move them over to our submission
2196 * side cache.
2197 */
d0acdee2 2198 if (READ_ONCE(ctx->locked_free_nr) > IO_COMPL_BATCH)
cd0ca2e0 2199 io_flush_cached_locked_reqs(ctx, state);
c2b6c6bc 2200 return !!state->free_list.next;
0ddf92e8
JA
2201}
2202
5d5901a3
PB
2203/*
2204 * A request might get retired back into the request caches even before opcode
2205 * handlers and io_issue_sqe() are done with it, e.g. inline completion path.
2206 * Because of that, io_alloc_req() should be called only under ->uring_lock
2207 * and with extra caution to not get a request that is still worked on.
2208 */
c072481d 2209static __cold bool __io_alloc_req_refill(struct io_ring_ctx *ctx)
5d5901a3 2210 __must_hold(&ctx->uring_lock)
2b188cc1 2211{
e5d1bc0a 2212 struct io_submit_state *state = &ctx->submit_state;
864ea921 2213 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
3ab665b7
PB
2214 void *reqs[IO_REQ_ALLOC_BATCH];
2215 struct io_kiocb *req;
864ea921 2216 int ret, i;
e5d1bc0a 2217
c2b6c6bc 2218 if (likely(state->free_list.next || io_flush_cached_reqs(ctx)))
a33ae9ce 2219 return true;
e5d1bc0a 2220
3ab665b7 2221 ret = kmem_cache_alloc_bulk(req_cachep, gfp, ARRAY_SIZE(reqs), reqs);
fd6fab2c 2222
864ea921
PB
2223 /*
2224 * Bulk alloc is all-or-nothing. If we fail to get a batch,
2225 * retry single alloc to be on the safe side.
2226 */
2227 if (unlikely(ret <= 0)) {
3ab665b7
PB
2228 reqs[0] = kmem_cache_alloc(req_cachep, gfp);
2229 if (!reqs[0])
a33ae9ce 2230 return false;
864ea921 2231 ret = 1;
2b188cc1 2232 }
864ea921 2233
37f0e767 2234 percpu_ref_get_many(&ctx->refs, ret);
3ab665b7
PB
2235 for (i = 0; i < ret; i++) {
2236 req = reqs[i];
2237
2238 io_preinit_req(req, ctx);
c2b6c6bc 2239 wq_stack_add_head(&req->comp_list, &state->free_list);
3ab665b7 2240 }
a33ae9ce
PB
2241 return true;
2242}
2243
2244static inline bool io_alloc_req_refill(struct io_ring_ctx *ctx)
2245{
2246 if (unlikely(!ctx->submit_state.free_list.next))
2247 return __io_alloc_req_refill(ctx);
2248 return true;
2249}
2250
2251static inline struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx)
2252{
2253 struct io_wq_work_node *node;
2254
2255 node = wq_stack_extract(&ctx->submit_state.free_list);
c2b6c6bc 2256 return container_of(node, struct io_kiocb, comp_list);
2b188cc1
JA
2257}
2258
e1d767f0 2259static inline void io_put_file(struct file *file)
8da11c19 2260{
e1d767f0 2261 if (file)
8da11c19
PB
2262 fput(file);
2263}
2264
6b639522 2265static inline void io_dismantle_req(struct io_kiocb *req)
2b188cc1 2266{
094bae49 2267 unsigned int flags = req->flags;
929a3af9 2268
867f8fa5 2269 if (unlikely(flags & IO_REQ_CLEAN_FLAGS))
3a0a6902 2270 io_clean_op(req);
e1d767f0
PB
2271 if (!(flags & REQ_F_FIXED_FILE))
2272 io_put_file(req->file);
e65ef56d
JA
2273}
2274
c072481d 2275static __cold void __io_free_req(struct io_kiocb *req)
c6ca97b3 2276{
51a4cc11 2277 struct io_ring_ctx *ctx = req->ctx;
c6ca97b3 2278
ab409402 2279 io_req_put_rsrc(req, ctx);
216578e5 2280 io_dismantle_req(req);
7c660731 2281 io_put_task(req->task, 1);
c6ca97b3 2282
79ebeaee 2283 spin_lock(&ctx->completion_lock);
c2b6c6bc 2284 wq_list_add_head(&req->comp_list, &ctx->locked_free_list);
c34b025f 2285 ctx->locked_free_nr++;
79ebeaee 2286 spin_unlock(&ctx->completion_lock);
e65ef56d
JA
2287}
2288
f2f87370
PB
2289static inline void io_remove_next_linked(struct io_kiocb *req)
2290{
2291 struct io_kiocb *nxt = req->link;
2292
2293 req->link = nxt->link;
2294 nxt->link = NULL;
2295}
2296
33cc89a9
PB
2297static bool io_kill_linked_timeout(struct io_kiocb *req)
2298 __must_hold(&req->ctx->completion_lock)
89b263f6 2299 __must_hold(&req->ctx->timeout_lock)
2665abfd 2300{
33cc89a9 2301 struct io_kiocb *link = req->link;
f2f87370 2302
b97e736a 2303 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
c9abd7ad 2304 struct io_timeout_data *io = link->async_data;
7c86ffee 2305
f2f87370 2306 io_remove_next_linked(req);
90cd7e42 2307 link->timeout.head = NULL;
fd9c7bc5 2308 if (hrtimer_try_to_cancel(&io->timer) != -1) {
ef9dd637 2309 list_del(&link->timeout.list);
04c76b41 2310 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
913a571a 2311 io_fill_cqe_req(link, -ECANCELED, 0);
91c2f697 2312 io_put_req_deferred(link);
d4729fbd 2313 return true;
c9abd7ad
PB
2314 }
2315 }
d4729fbd 2316 return false;
7c86ffee
PB
2317}
2318
d148ca4b 2319static void io_fail_links(struct io_kiocb *req)
33cc89a9 2320 __must_hold(&req->ctx->completion_lock)
9e645e11 2321{
33cc89a9 2322 struct io_kiocb *nxt, *link = req->link;
04c76b41 2323 bool ignore_cqes = req->flags & REQ_F_SKIP_LINK_CQES;
9e645e11 2324
f2f87370 2325 req->link = NULL;
f2f87370 2326 while (link) {
a8295b98
HX
2327 long res = -ECANCELED;
2328
2329 if (link->flags & REQ_F_FAIL)
2330 res = link->result;
2331
f2f87370
PB
2332 nxt = link->link;
2333 link->link = NULL;
2665abfd 2334
502c87d6
SR
2335 trace_io_uring_fail_link(req->ctx, req, req->user_data,
2336 req->opcode, link);
2337
04c76b41
PB
2338 if (!ignore_cqes) {
2339 link->flags &= ~REQ_F_CQE_SKIP;
2340 io_fill_cqe_req(link, res, 0);
2341 }
91c2f697 2342 io_put_req_deferred(link);
f2f87370 2343 link = nxt;
9e645e11 2344 }
33cc89a9 2345}
9e645e11 2346
33cc89a9
PB
2347static bool io_disarm_next(struct io_kiocb *req)
2348 __must_hold(&req->ctx->completion_lock)
2349{
2350 bool posted = false;
2351
0756a869
PB
2352 if (req->flags & REQ_F_ARM_LTIMEOUT) {
2353 struct io_kiocb *link = req->link;
2354
906c6caa 2355 req->flags &= ~REQ_F_ARM_LTIMEOUT;
0756a869
PB
2356 if (link && link->opcode == IORING_OP_LINK_TIMEOUT) {
2357 io_remove_next_linked(req);
04c76b41 2358 /* leave REQ_F_CQE_SKIP to io_fill_cqe_req */
913a571a 2359 io_fill_cqe_req(link, -ECANCELED, 0);
0756a869
PB
2360 io_put_req_deferred(link);
2361 posted = true;
2362 }
2363 } else if (req->flags & REQ_F_LINK_TIMEOUT) {
89b263f6
JA
2364 struct io_ring_ctx *ctx = req->ctx;
2365
2366 spin_lock_irq(&ctx->timeout_lock);
33cc89a9 2367 posted = io_kill_linked_timeout(req);
89b263f6
JA
2368 spin_unlock_irq(&ctx->timeout_lock);
2369 }
93d2bcd2 2370 if (unlikely((req->flags & REQ_F_FAIL) &&
e4335ed3 2371 !(req->flags & REQ_F_HARDLINK))) {
33cc89a9
PB
2372 posted |= (req->link != NULL);
2373 io_fail_links(req);
2374 }
2375 return posted;
9e645e11
JA
2376}
2377
d81499bf
PB
2378static void __io_req_find_next_prep(struct io_kiocb *req)
2379{
2380 struct io_ring_ctx *ctx = req->ctx;
2381 bool posted;
2382
2383 spin_lock(&ctx->completion_lock);
2384 posted = io_disarm_next(req);
2385 if (posted)
33ce2aff 2386 io_commit_cqring(ctx);
d81499bf
PB
2387 spin_unlock(&ctx->completion_lock);
2388 if (posted)
2389 io_cqring_ev_posted(ctx);
2390}
2391
2392static inline struct io_kiocb *io_req_find_next(struct io_kiocb *req)
c69f8dbe 2393{
33cc89a9 2394 struct io_kiocb *nxt;
944e58bf 2395
d81499bf
PB
2396 if (likely(!(req->flags & (REQ_F_LINK|REQ_F_HARDLINK))))
2397 return NULL;
9e645e11
JA
2398 /*
2399 * If LINK is set, we have dependent requests in this chain. If we
2400 * didn't fail this request, queue the first one up, moving any other
2401 * dependencies to the next request. In case of failure, fail the rest
2402 * of the chain.
2403 */
d81499bf
PB
2404 if (unlikely(req->flags & IO_DISARM_MASK))
2405 __io_req_find_next_prep(req);
33cc89a9
PB
2406 nxt = req->link;
2407 req->link = NULL;
2408 return nxt;
4d7dd462 2409}
9e645e11 2410
f237c30a 2411static void ctx_flush_and_put(struct io_ring_ctx *ctx, bool *locked)
2c32395d
PB
2412{
2413 if (!ctx)
2414 return;
f237c30a 2415 if (*locked) {
c450178d 2416 io_submit_flush_completions(ctx);
2c32395d 2417 mutex_unlock(&ctx->uring_lock);
f237c30a 2418 *locked = false;
2c32395d
PB
2419 }
2420 percpu_ref_put(&ctx->refs);
2421}
2422
f28c240e
HX
2423static inline void ctx_commit_and_unlock(struct io_ring_ctx *ctx)
2424{
2425 io_commit_cqring(ctx);
2426 spin_unlock(&ctx->completion_lock);
2427 io_cqring_ev_posted(ctx);
2428}
2429
2430static void handle_prev_tw_list(struct io_wq_work_node *node,
2431 struct io_ring_ctx **ctx, bool *uring_locked)
2432{
2433 if (*ctx && !*uring_locked)
2434 spin_lock(&(*ctx)->completion_lock);
2435
2436 do {
2437 struct io_wq_work_node *next = node->next;
2438 struct io_kiocb *req = container_of(node, struct io_kiocb,
2439 io_task_work.node);
2440
2441 if (req->ctx != *ctx) {
2442 if (unlikely(!*uring_locked && *ctx))
2443 ctx_commit_and_unlock(*ctx);
2444
2445 ctx_flush_and_put(*ctx, uring_locked);
2446 *ctx = req->ctx;
2447 /* if not contended, grab and improve batching */
2448 *uring_locked = mutex_trylock(&(*ctx)->uring_lock);
2449 percpu_ref_get(&(*ctx)->refs);
2450 if (unlikely(!*uring_locked))
2451 spin_lock(&(*ctx)->completion_lock);
2452 }
2453 if (likely(*uring_locked))
2454 req->io_task_work.func(req, uring_locked);
2455 else
cc3cec83
JA
2456 __io_req_complete_post(req, req->result,
2457 io_put_kbuf_comp(req));
f28c240e
HX
2458 node = next;
2459 } while (node);
2460
2461 if (unlikely(!*uring_locked))
2462 ctx_commit_and_unlock(*ctx);
2463}
2464
2465static void handle_tw_list(struct io_wq_work_node *node,
2466 struct io_ring_ctx **ctx, bool *locked)
9f8d032a
HX
2467{
2468 do {
2469 struct io_wq_work_node *next = node->next;
2470 struct io_kiocb *req = container_of(node, struct io_kiocb,
2471 io_task_work.node);
2472
2473 if (req->ctx != *ctx) {
2474 ctx_flush_and_put(*ctx, locked);
2475 *ctx = req->ctx;
2476 /* if not contended, grab and improve batching */
2477 *locked = mutex_trylock(&(*ctx)->uring_lock);
2478 percpu_ref_get(&(*ctx)->refs);
2479 }
2480 req->io_task_work.func(req, locked);
2481 node = next;
2482 } while (node);
2483}
2484
7cbf1722 2485static void tctx_task_work(struct callback_head *cb)
c40f6379 2486{
f28c240e 2487 bool uring_locked = false;
ebd0df2e 2488 struct io_ring_ctx *ctx = NULL;
3f18407d
PB
2489 struct io_uring_task *tctx = container_of(cb, struct io_uring_task,
2490 task_work);
c40f6379 2491
16f72070 2492 while (1) {
f28c240e 2493 struct io_wq_work_node *node1, *node2;
3f18407d 2494
f28c240e
HX
2495 if (!tctx->task_list.first &&
2496 !tctx->prior_task_list.first && uring_locked)
8d4ad41e
PB
2497 io_submit_flush_completions(ctx);
2498
3f18407d 2499 spin_lock_irq(&tctx->task_lock);
f28c240e
HX
2500 node1 = tctx->prior_task_list.first;
2501 node2 = tctx->task_list.first;
3f18407d 2502 INIT_WQ_LIST(&tctx->task_list);
f28c240e
HX
2503 INIT_WQ_LIST(&tctx->prior_task_list);
2504 if (!node2 && !node1)
6294f368 2505 tctx->task_running = false;
3f18407d 2506 spin_unlock_irq(&tctx->task_lock);
f28c240e 2507 if (!node2 && !node1)
6294f368 2508 break;
3f18407d 2509
f28c240e
HX
2510 if (node1)
2511 handle_prev_tw_list(node1, &ctx, &uring_locked);
6294f368 2512
f28c240e
HX
2513 if (node2)
2514 handle_tw_list(node2, &ctx, &uring_locked);
7cbf1722 2515 cond_resched();
3f18407d 2516 }
ebd0df2e 2517
f28c240e 2518 ctx_flush_and_put(ctx, &uring_locked);
3cc7fdb9
PB
2519
2520 /* relaxed read is enough as only the task itself sets ->in_idle */
2521 if (unlikely(atomic_read(&tctx->in_idle)))
2522 io_uring_drop_tctx_refs(current);
7cbf1722
JA
2523}
2524
4813c377 2525static void io_req_task_work_add(struct io_kiocb *req, bool priority)
7cbf1722 2526{
c15b79de 2527 struct task_struct *tsk = req->task;
7cbf1722 2528 struct io_uring_task *tctx = tsk->io_uring;
c15b79de 2529 enum task_work_notify_mode notify;
e09ee510 2530 struct io_wq_work_node *node;
0b81e80c 2531 unsigned long flags;
6294f368 2532 bool running;
7cbf1722
JA
2533
2534 WARN_ON_ONCE(!tctx);
2535
0b81e80c 2536 spin_lock_irqsave(&tctx->task_lock, flags);
4813c377
HX
2537 if (priority)
2538 wq_list_add_tail(&req->io_task_work.node, &tctx->prior_task_list);
2539 else
2540 wq_list_add_tail(&req->io_task_work.node, &tctx->task_list);
6294f368
PB
2541 running = tctx->task_running;
2542 if (!running)
2543 tctx->task_running = true;
0b81e80c 2544 spin_unlock_irqrestore(&tctx->task_lock, flags);
7cbf1722
JA
2545
2546 /* task_work already pending, we're done */
6294f368 2547 if (running)
e09ee510 2548 return;
7cbf1722 2549
c15b79de
PB
2550 /*
2551 * SQPOLL kernel thread doesn't need notification, just a wakeup. For
2552 * all other cases, use TWA_SIGNAL unconditionally to ensure we're
2553 * processing task_work. There's no reliable way to tell if TWA_RESUME
2554 * will do the job.
2555 */
2556 notify = (req->ctx->flags & IORING_SETUP_SQPOLL) ? TWA_NONE : TWA_SIGNAL;
d97ec623
PB
2557 if (likely(!task_work_add(tsk, &tctx->task_work, notify))) {
2558 if (notify == TWA_NONE)
2559 wake_up_process(tsk);
e09ee510 2560 return;
c15b79de 2561 }
2215bed9 2562
0b81e80c 2563 spin_lock_irqsave(&tctx->task_lock, flags);
6294f368 2564 tctx->task_running = false;
4813c377 2565 node = wq_list_merge(&tctx->prior_task_list, &tctx->task_list);
0b81e80c 2566 spin_unlock_irqrestore(&tctx->task_lock, flags);
7cbf1722 2567
e09ee510
PB
2568 while (node) {
2569 req = container_of(node, struct io_kiocb, io_task_work.node);
2570 node = node->next;
2571 if (llist_add(&req->io_task_work.fallback_node,
2572 &req->ctx->fallback_llist))
2573 schedule_delayed_work(&req->ctx->fallback_work, 1);
2574 }
eab30c4d
PB
2575}
2576
f237c30a 2577static void io_req_task_cancel(struct io_kiocb *req, bool *locked)
c40f6379 2578{
87ceb6a6 2579 struct io_ring_ctx *ctx = req->ctx;
c40f6379 2580
b18a1a45 2581 /* not needed for normal modes, but SQPOLL depends on it */
f237c30a 2582 io_tw_lock(ctx, locked);
2593553a 2583 io_req_complete_failed(req, req->result);
c40f6379
JA
2584}
2585
f237c30a 2586static void io_req_task_submit(struct io_kiocb *req, bool *locked)
c40f6379
JA
2587{
2588 struct io_ring_ctx *ctx = req->ctx;
2589
f237c30a 2590 io_tw_lock(ctx, locked);
316319e8 2591 /* req->task == current here, checking PF_EXITING is safe */
af066f31 2592 if (likely(!(req->task->flags & PF_EXITING)))
c5eef2b9 2593 __io_queue_sqe(req);
81b6d05c 2594 else
2593553a 2595 io_req_complete_failed(req, -EFAULT);
c40f6379
JA
2596}
2597
2c4b8eb6 2598static void io_req_task_queue_fail(struct io_kiocb *req, int ret)
c40f6379 2599{
2c4b8eb6 2600 req->result = ret;
5b0a6acc 2601 req->io_task_work.func = io_req_task_cancel;
4813c377 2602 io_req_task_work_add(req, false);
c40f6379
JA
2603}
2604
2c4b8eb6 2605static void io_req_task_queue(struct io_kiocb *req)
a3df7698 2606{
5b0a6acc 2607 req->io_task_work.func = io_req_task_submit;
4813c377 2608 io_req_task_work_add(req, false);
a3df7698
PB
2609}
2610
773af691
JA
2611static void io_req_task_queue_reissue(struct io_kiocb *req)
2612{
2613 req->io_task_work.func = io_queue_async_work;
4813c377 2614 io_req_task_work_add(req, false);
773af691
JA
2615}
2616
f2f87370 2617static inline void io_queue_next(struct io_kiocb *req)
c69f8dbe 2618{
9b5f7bd9 2619 struct io_kiocb *nxt = io_req_find_next(req);
944e58bf
PB
2620
2621 if (nxt)
906a8c3f 2622 io_req_task_queue(nxt);
c69f8dbe
JL
2623}
2624
c3524383 2625static void io_free_req(struct io_kiocb *req)
7a743e22 2626{
c3524383
PB
2627 io_queue_next(req);
2628 __io_free_req(req);
2629}
8766dd51 2630
f237c30a
PB
2631static void io_free_req_work(struct io_kiocb *req, bool *locked)
2632{
2633 io_free_req(req);
2634}
2635
3aa83bfb 2636static void io_free_batch_list(struct io_ring_ctx *ctx,
1cce17ac 2637 struct io_wq_work_node *node)
3aa83bfb 2638 __must_hold(&ctx->uring_lock)
5af1d13e 2639{
d4b7a5ef 2640 struct task_struct *task = NULL;
37f0e767 2641 int task_refs = 0;
5af1d13e 2642
3aa83bfb
PB
2643 do {
2644 struct io_kiocb *req = container_of(node, struct io_kiocb,
2645 comp_list);
2d6500d4 2646
def77acf 2647 if (unlikely(req->flags & REQ_F_REFCOUNT)) {
c1e53a69 2648 node = req->comp_list.next;
def77acf
PB
2649 if (!req_ref_put_and_test(req))
2650 continue;
c1e53a69 2651 }
2d6500d4 2652
ab409402 2653 io_req_put_rsrc_locked(req, ctx);
d4b7a5ef
PB
2654 io_queue_next(req);
2655 io_dismantle_req(req);
5af1d13e 2656
d4b7a5ef
PB
2657 if (req->task != task) {
2658 if (task)
2659 io_put_task(task, task_refs);
2660 task = req->task;
2661 task_refs = 0;
2662 }
2663 task_refs++;
c1e53a69 2664 node = req->comp_list.next;
d4b7a5ef 2665 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
3aa83bfb 2666 } while (node);
d4b7a5ef 2667
d4b7a5ef
PB
2668 if (task)
2669 io_put_task(task, task_refs);
7a743e22
PB
2670}
2671
c450178d 2672static void __io_submit_flush_completions(struct io_ring_ctx *ctx)
a141dd89 2673 __must_hold(&ctx->uring_lock)
905c172f 2674{
6f33b0bc 2675 struct io_wq_work_node *node, *prev;
cd0ca2e0 2676 struct io_submit_state *state = &ctx->submit_state;
905c172f 2677
3d4aeb9f
PB
2678 if (state->flush_cqes) {
2679 spin_lock(&ctx->completion_lock);
2680 wq_list_for_each(node, prev, &state->compl_reqs) {
2681 struct io_kiocb *req = container_of(node, struct io_kiocb,
6f33b0bc 2682 comp_list);
5182ed2e 2683
3d4aeb9f 2684 if (!(req->flags & REQ_F_CQE_SKIP))
ae4da189 2685 __io_fill_cqe_req(req, req->result, req->cflags);
4d9237e3
JA
2686 if ((req->flags & REQ_F_POLLED) && req->apoll) {
2687 struct async_poll *apoll = req->apoll;
2688
2689 if (apoll->double_poll)
2690 kfree(apoll->double_poll);
2691 list_add(&apoll->poll.wait.entry,
2692 &ctx->apoll_cache);
2693 req->flags &= ~REQ_F_POLLED;
2694 }
3d4aeb9f
PB
2695 }
2696
2697 io_commit_cqring(ctx);
2698 spin_unlock(&ctx->completion_lock);
2699 io_cqring_ev_posted(ctx);
2700 state->flush_cqes = false;
905c172f 2701 }
5182ed2e 2702
1cce17ac 2703 io_free_batch_list(ctx, state->compl_reqs.first);
6f33b0bc 2704 INIT_WQ_LIST(&state->compl_reqs);
7a743e22
PB
2705}
2706
ba816ad6
JA
2707/*
2708 * Drop reference to request, return next in chain (if there is one) if this
2709 * was the last reference to this request.
2710 */
0d85035a 2711static inline struct io_kiocb *io_put_req_find_next(struct io_kiocb *req)
e65ef56d 2712{
9b5f7bd9
PB
2713 struct io_kiocb *nxt = NULL;
2714
de9b4cca 2715 if (req_ref_put_and_test(req)) {
9b5f7bd9 2716 nxt = io_req_find_next(req);
4d7dd462 2717 __io_free_req(req);
2a44f467 2718 }
9b5f7bd9 2719 return nxt;
2b188cc1
JA
2720}
2721
0d85035a 2722static inline void io_put_req(struct io_kiocb *req)
e65ef56d 2723{
de9b4cca 2724 if (req_ref_put_and_test(req))
e65ef56d 2725 io_free_req(req);
2b188cc1
JA
2726}
2727
91c2f697 2728static inline void io_put_req_deferred(struct io_kiocb *req)
216578e5 2729{
91c2f697 2730 if (req_ref_put_and_test(req)) {
f237c30a 2731 req->io_task_work.func = io_free_req_work;
4813c377 2732 io_req_task_work_add(req, false);
543af3a1 2733 }
216578e5
PB
2734}
2735
6c503150 2736static unsigned io_cqring_events(struct io_ring_ctx *ctx)
a3a0e43f
JA
2737{
2738 /* See comment at the top of this file */
2739 smp_rmb();
e23de15f 2740 return __io_cqring_events(ctx);
a3a0e43f
JA
2741}
2742
fb5ccc98
PB
2743static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
2744{
2745 struct io_rings *rings = ctx->rings;
2746
2747 /* make sure SQ entry isn't read before tail */
2748 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
2749}
2750
4c6e277c
JA
2751static inline bool io_run_task_work(void)
2752{
ef98eb04 2753 if (test_thread_flag(TIF_NOTIFY_SIGNAL) || current->task_works) {
4c6e277c 2754 __set_current_state(TASK_RUNNING);
ef98eb04 2755 tracehook_notify_signal();
4c6e277c
JA
2756 return true;
2757 }
2758
2759 return false;
bcda7baa
JA
2760}
2761
5ba3c874 2762static int io_do_iopoll(struct io_ring_ctx *ctx, bool force_nonspin)
def596e9 2763{
5eef4e87 2764 struct io_wq_work_node *pos, *start, *prev;
d729cf9a 2765 unsigned int poll_flags = BLK_POLL_NOSLEEP;
b688f11e 2766 DEFINE_IO_COMP_BATCH(iob);
5ba3c874 2767 int nr_events = 0;
def596e9
JA
2768
2769 /*
2770 * Only spin for completions if we don't have multiple devices hanging
87a115fb 2771 * off our complete list.
def596e9 2772 */
87a115fb 2773 if (ctx->poll_multi_queue || force_nonspin)
ef99b2d3 2774 poll_flags |= BLK_POLL_ONESHOT;
def596e9 2775
5eef4e87
PB
2776 wq_list_for_each(pos, start, &ctx->iopoll_list) {
2777 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
9adbd45d 2778 struct kiocb *kiocb = &req->rw.kiocb;
a2416e1e 2779 int ret;
def596e9
JA
2780
2781 /*
581f9810
BM
2782 * Move completed and retryable entries to our local lists.
2783 * If we find a request that requires polling, break out
2784 * and complete those lists first, if we have entries there.
def596e9 2785 */
e3f721e6 2786 if (READ_ONCE(req->iopoll_completed))
def596e9
JA
2787 break;
2788
b688f11e 2789 ret = kiocb->ki_filp->f_op->iopoll(kiocb, &iob, poll_flags);
a2416e1e
PB
2790 if (unlikely(ret < 0))
2791 return ret;
2792 else if (ret)
ef99b2d3 2793 poll_flags |= BLK_POLL_ONESHOT;
def596e9 2794
3aadc23e 2795 /* iopoll may have completed current req */
b688f11e
JA
2796 if (!rq_list_empty(iob.req_list) ||
2797 READ_ONCE(req->iopoll_completed))
e3f721e6 2798 break;
def596e9
JA
2799 }
2800
b688f11e
JA
2801 if (!rq_list_empty(iob.req_list))
2802 iob.complete(&iob);
5eef4e87
PB
2803 else if (!pos)
2804 return 0;
def596e9 2805
5eef4e87
PB
2806 prev = start;
2807 wq_list_for_each_resume(pos, prev) {
2808 struct io_kiocb *req = container_of(pos, struct io_kiocb, comp_list);
2809
b3fa03fd
PB
2810 /* order with io_complete_rw_iopoll(), e.g. ->result updates */
2811 if (!smp_load_acquire(&req->iopoll_completed))
e3f721e6 2812 break;
83a13a41
PB
2813 if (unlikely(req->flags & REQ_F_CQE_SKIP))
2814 continue;
d1fd1c20 2815
ae4da189 2816 __io_fill_cqe_req(req, req->result, io_put_kbuf(req, 0));
e3f721e6
PB
2817 nr_events++;
2818 }
def596e9 2819
f5ed3bcd
PB
2820 if (unlikely(!nr_events))
2821 return 0;
2822
2823 io_commit_cqring(ctx);
2824 io_cqring_ev_posted_iopoll(ctx);
1cce17ac 2825 pos = start ? start->next : ctx->iopoll_list.first;
5eef4e87 2826 wq_list_cut(&ctx->iopoll_list, prev, start);
1cce17ac 2827 io_free_batch_list(ctx, pos);
5ba3c874 2828 return nr_events;
def596e9
JA
2829}
2830
def596e9
JA
2831/*
2832 * We can't just wait for polled events to come to us, we have to actively
2833 * find and complete them.
2834 */
c072481d 2835static __cold void io_iopoll_try_reap_events(struct io_ring_ctx *ctx)
def596e9
JA
2836{
2837 if (!(ctx->flags & IORING_SETUP_IOPOLL))
2838 return;
2839
2840 mutex_lock(&ctx->uring_lock);
5eef4e87 2841 while (!wq_list_empty(&ctx->iopoll_list)) {
b2edc0a7 2842 /* let it sleep and repeat later if can't complete a request */
5ba3c874 2843 if (io_do_iopoll(ctx, true) == 0)
b2edc0a7 2844 break;
08f5439f
JA
2845 /*
2846 * Ensure we allow local-to-the-cpu processing to take place,
2847 * in this case we need to ensure that we reap all events.
3fcee5a6 2848 * Also let task_work, etc. to progress by releasing the mutex
08f5439f 2849 */
3fcee5a6
PB
2850 if (need_resched()) {
2851 mutex_unlock(&ctx->uring_lock);
2852 cond_resched();
2853 mutex_lock(&ctx->uring_lock);
2854 }
def596e9
JA
2855 }
2856 mutex_unlock(&ctx->uring_lock);
2857}
2858
7668b92a 2859static int io_iopoll_check(struct io_ring_ctx *ctx, long min)
def596e9 2860{
7668b92a 2861 unsigned int nr_events = 0;
e9979b36 2862 int ret = 0;
500f9fba 2863
c7849be9
XW
2864 /*
2865 * We disallow the app entering submit/complete with polling, but we
2866 * still need to lock the ring to prevent racing with polled issue
2867 * that got punted to a workqueue.
2868 */
2869 mutex_lock(&ctx->uring_lock);
f39c8a5b
PB
2870 /*
2871 * Don't enter poll loop if we already have events pending.
2872 * If we do, we can potentially be spinning for commands that
2873 * already triggered a CQE (eg in error).
2874 */
5ed7a37d 2875 if (test_bit(0, &ctx->check_cq_overflow))
f39c8a5b
PB
2876 __io_cqring_overflow_flush(ctx, false);
2877 if (io_cqring_events(ctx))
2878 goto out;
def596e9 2879 do {
500f9fba
JA
2880 /*
2881 * If a submit got punted to a workqueue, we can have the
2882 * application entering polling for a command before it gets
2883 * issued. That app will hold the uring_lock for the duration
2884 * of the poll right here, so we need to take a breather every
2885 * now and then to ensure that the issue has a chance to add
2886 * the poll to the issued list. Otherwise we can spin here
2887 * forever, while the workqueue is stuck trying to acquire the
2888 * very same mutex.
2889 */
5eef4e87 2890 if (wq_list_empty(&ctx->iopoll_list)) {
8f487ef2
PB
2891 u32 tail = ctx->cached_cq_tail;
2892
500f9fba 2893 mutex_unlock(&ctx->uring_lock);
4c6e277c 2894 io_run_task_work();
500f9fba 2895 mutex_lock(&ctx->uring_lock);
def596e9 2896
8f487ef2
PB
2897 /* some requests don't go through iopoll_list */
2898 if (tail != ctx->cached_cq_tail ||
5eef4e87 2899 wq_list_empty(&ctx->iopoll_list))
e9979b36 2900 break;
500f9fba 2901 }
5ba3c874
PB
2902 ret = io_do_iopoll(ctx, !min);
2903 if (ret < 0)
2904 break;
2905 nr_events += ret;
2906 ret = 0;
2907 } while (nr_events < min && !need_resched());
f39c8a5b 2908out:
500f9fba 2909 mutex_unlock(&ctx->uring_lock);
def596e9
JA
2910 return ret;
2911}
2912
491381ce 2913static void kiocb_end_write(struct io_kiocb *req)
2b188cc1 2914{
491381ce
JA
2915 /*
2916 * Tell lockdep we inherited freeze protection from submission
2917 * thread.
2918 */
2919 if (req->flags & REQ_F_ISREG) {
1c98679d 2920 struct super_block *sb = file_inode(req->file)->i_sb;
2b188cc1 2921
1c98679d
PB
2922 __sb_writers_acquired(sb, SB_FREEZE_WRITE);
2923 sb_end_write(sb);
2b188cc1
JA
2924 }
2925}
2926
b63534c4 2927#ifdef CONFIG_BLOCK
dc2a6e9a 2928static bool io_resubmit_prep(struct io_kiocb *req)
b63534c4 2929{
ab454438 2930 struct io_async_rw *rw = req->async_data;
b63534c4 2931
d886e185 2932 if (!req_has_async_data(req))
ab454438 2933 return !io_req_prep_async(req);
538941e2 2934 iov_iter_restore(&rw->s.iter, &rw->s.iter_state);
ab454438 2935 return true;
b63534c4 2936}
b63534c4 2937
3e6a0d3c 2938static bool io_rw_should_reissue(struct io_kiocb *req)
b63534c4 2939{
355afaeb 2940 umode_t mode = file_inode(req->file)->i_mode;
3e6a0d3c 2941 struct io_ring_ctx *ctx = req->ctx;
b63534c4 2942
355afaeb
JA
2943 if (!S_ISBLK(mode) && !S_ISREG(mode))
2944 return false;
3e6a0d3c
JA
2945 if ((req->flags & REQ_F_NOWAIT) || (io_wq_current_is_worker() &&
2946 !(ctx->flags & IORING_SETUP_IOPOLL)))
b63534c4 2947 return false;
7c977a58
JA
2948 /*
2949 * If ref is dying, we might be running poll reap from the exit work.
2950 * Don't attempt to reissue from that path, just let it fail with
2951 * -EAGAIN.
2952 */
3e6a0d3c
JA
2953 if (percpu_ref_is_dying(&ctx->refs))
2954 return false;
ef046888
JA
2955 /*
2956 * Play it safe and assume not safe to re-import and reissue if we're
2957 * not in the original thread group (or in task context).
2958 */
2959 if (!same_thread_group(req->task, current) || !in_task())
2960 return false;
3e6a0d3c
JA
2961 return true;
2962}
e82ad485 2963#else
a1ff1e3f 2964static bool io_resubmit_prep(struct io_kiocb *req)
e82ad485
JA
2965{
2966 return false;
2967}
e82ad485 2968static bool io_rw_should_reissue(struct io_kiocb *req)
3e6a0d3c 2969{
b63534c4
JA
2970 return false;
2971}
3e6a0d3c 2972#endif
b63534c4 2973
8ef12efe 2974static bool __io_complete_rw_common(struct io_kiocb *req, long res)
a1d7c393 2975{
f63cf519 2976 if (req->rw.kiocb.ki_flags & IOCB_WRITE) {
b65c128f 2977 kiocb_end_write(req);
f63cf519
JA
2978 fsnotify_modify(req->file);
2979 } else {
2980 fsnotify_access(req->file);
2981 }
258f3a7f 2982 if (unlikely(res != req->result)) {
9532b99b
PB
2983 if ((res == -EAGAIN || res == -EOPNOTSUPP) &&
2984 io_rw_should_reissue(req)) {
2985 req->flags |= REQ_F_REISSUE;
8ef12efe 2986 return true;
9532b99b 2987 }
93d2bcd2 2988 req_set_fail(req);
8ef12efe 2989 req->result = res;
9532b99b 2990 }
8ef12efe
JA
2991 return false;
2992}
2993
cc8e9ba7 2994static inline void io_req_task_complete(struct io_kiocb *req, bool *locked)
8ef12efe 2995{
54daa9b2 2996 int res = req->result;
126180b9
PB
2997
2998 if (*locked) {
cc3cec83 2999 io_req_complete_state(req, res, io_put_kbuf(req, 0));
fff4e40e 3000 io_req_add_compl_list(req);
126180b9 3001 } else {
cc3cec83
JA
3002 io_req_complete_post(req, res,
3003 io_put_kbuf(req, IO_URING_F_UNLOCKED));
126180b9 3004 }
8ef12efe
JA
3005}
3006
00f6e68b 3007static void __io_complete_rw(struct io_kiocb *req, long res,
8ef12efe
JA
3008 unsigned int issue_flags)
3009{
3010 if (__io_complete_rw_common(req, res))
3011 return;
cc3cec83
JA
3012 __io_req_complete(req, issue_flags, req->result,
3013 io_put_kbuf(req, issue_flags));
ba816ad6
JA
3014}
3015
6b19b766 3016static void io_complete_rw(struct kiocb *kiocb, long res)
ba816ad6 3017{
9adbd45d 3018 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
ba816ad6 3019
8ef12efe
JA
3020 if (__io_complete_rw_common(req, res))
3021 return;
3022 req->result = res;
3023 req->io_task_work.func = io_req_task_complete;
f28c240e 3024 io_req_task_work_add(req, !!(req->ctx->flags & IORING_SETUP_SQPOLL));
2b188cc1
JA
3025}
3026
6b19b766 3027static void io_complete_rw_iopoll(struct kiocb *kiocb, long res)
def596e9 3028{
9adbd45d 3029 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
def596e9 3030
491381ce
JA
3031 if (kiocb->ki_flags & IOCB_WRITE)
3032 kiocb_end_write(req);
9532b99b 3033 if (unlikely(res != req->result)) {
b66ceaf3
PB
3034 if (res == -EAGAIN && io_rw_should_reissue(req)) {
3035 req->flags |= REQ_F_REISSUE;
3036 return;
9532b99b 3037 }
258f3a7f 3038 req->result = res;
8c130827 3039 }
bbde017a 3040
b3fa03fd
PB
3041 /* order with io_iopoll_complete() checking ->iopoll_completed */
3042 smp_store_release(&req->iopoll_completed, 1);
def596e9
JA
3043}
3044
3045/*
3046 * After the iocb has been issued, it's safe to be found on the poll list.
3047 * Adding the kiocb to the list AFTER submission ensures that we don't
f39c8a5b 3048 * find it from a io_do_iopoll() thread before the issuer is done
def596e9
JA
3049 * accessing the kiocb cookie.
3050 */
9882131c 3051static void io_iopoll_req_issued(struct io_kiocb *req, unsigned int issue_flags)
def596e9
JA
3052{
3053 struct io_ring_ctx *ctx = req->ctx;
3b44b371 3054 const bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
cb3d8972
PB
3055
3056 /* workqueue context doesn't hold uring_lock, grab it now */
3b44b371 3057 if (unlikely(needs_lock))
cb3d8972 3058 mutex_lock(&ctx->uring_lock);
def596e9
JA
3059
3060 /*
3061 * Track whether we have multiple files in our lists. This will impact
3062 * how we do polling eventually, not spinning if we're on potentially
3063 * different devices.
3064 */
5eef4e87 3065 if (wq_list_empty(&ctx->iopoll_list)) {
915b3dde
HX
3066 ctx->poll_multi_queue = false;
3067 } else if (!ctx->poll_multi_queue) {
def596e9
JA
3068 struct io_kiocb *list_req;
3069
5eef4e87
PB
3070 list_req = container_of(ctx->iopoll_list.first, struct io_kiocb,
3071 comp_list);
30da1b45 3072 if (list_req->file != req->file)
915b3dde 3073 ctx->poll_multi_queue = true;
def596e9
JA
3074 }
3075
3076 /*
3077 * For fast devices, IO may have already completed. If it has, add
3078 * it to the front so we find it first.
3079 */
65a6543d 3080 if (READ_ONCE(req->iopoll_completed))
5eef4e87 3081 wq_list_add_head(&req->comp_list, &ctx->iopoll_list);
def596e9 3082 else
5eef4e87 3083 wq_list_add_tail(&req->comp_list, &ctx->iopoll_list);
bdcd3eab 3084
3b44b371 3085 if (unlikely(needs_lock)) {
cb3d8972
PB
3086 /*
3087 * If IORING_SETUP_SQPOLL is enabled, sqes are either handle
3088 * in sq thread task context or in io worker task context. If
3089 * current task context is sq thread, we don't need to check
3090 * whether should wake up sq thread.
3091 */
3092 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
3093 wq_has_sleeper(&ctx->sq_data->wait))
3094 wake_up(&ctx->sq_data->wait);
3095
3096 mutex_unlock(&ctx->uring_lock);
3097 }
def596e9
JA
3098}
3099
4503b767
JA
3100static bool io_bdev_nowait(struct block_device *bdev)
3101{
9ba0d0c8 3102 return !bdev || blk_queue_nowait(bdev_get_queue(bdev));
4503b767
JA
3103}
3104
2b188cc1
JA
3105/*
3106 * If we tracked the file through the SCM inflight mechanism, we could support
3107 * any file. For now, just ensure that anything potentially problematic is done
3108 * inline.
3109 */
88459b50 3110static bool __io_file_supports_nowait(struct file *file, umode_t mode)
2b188cc1 3111{
4503b767 3112 if (S_ISBLK(mode)) {
4e7b5671
CH
3113 if (IS_ENABLED(CONFIG_BLOCK) &&
3114 io_bdev_nowait(I_BDEV(file->f_mapping->host)))
4503b767
JA
3115 return true;
3116 return false;
3117 }
976517f1 3118 if (S_ISSOCK(mode))
2b188cc1 3119 return true;
4503b767 3120 if (S_ISREG(mode)) {
4e7b5671
CH
3121 if (IS_ENABLED(CONFIG_BLOCK) &&
3122 io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
4503b767
JA
3123 file->f_op != &io_uring_fops)
3124 return true;
3125 return false;
3126 }
2b188cc1 3127
c5b85625
JA
3128 /* any ->read/write should understand O_NONBLOCK */
3129 if (file->f_flags & O_NONBLOCK)
3130 return true;
35645ac3 3131 return file->f_mode & FMODE_NOWAIT;
2b188cc1 3132}
c5b85625 3133
88459b50
PB
3134/*
3135 * If we tracked the file through the SCM inflight mechanism, we could support
3136 * any file. For now, just ensure that anything potentially problematic is done
3137 * inline.
3138 */
3139static unsigned int io_file_get_flags(struct file *file)
3140{
3141 umode_t mode = file_inode(file)->i_mode;
3142 unsigned int res = 0;
af197f50 3143
88459b50
PB
3144 if (S_ISREG(mode))
3145 res |= FFS_ISREG;
3146 if (__io_file_supports_nowait(file, mode))
3147 res |= FFS_NOWAIT;
3148 return res;
2b188cc1
JA
3149}
3150
35645ac3 3151static inline bool io_file_supports_nowait(struct io_kiocb *req)
7b29f92d 3152{
88459b50 3153 return req->flags & REQ_F_SUPPORT_NOWAIT;
7b29f92d
JA
3154}
3155
b9a6b8f9 3156static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe)
2b188cc1 3157{
def596e9 3158 struct io_ring_ctx *ctx = req->ctx;
9adbd45d 3159 struct kiocb *kiocb = &req->rw.kiocb;
75c668cd 3160 struct file *file = req->file;
09bb8394
JA
3161 unsigned ioprio;
3162 int ret;
2b188cc1 3163
88459b50
PB
3164 if (!io_req_ffs_set(req))
3165 req->flags |= io_file_get_flags(file) << REQ_F_SUPPORT_NOWAIT_BIT;
491381ce 3166
2b188cc1 3167 kiocb->ki_pos = READ_ONCE(sqe->off);
5cb03d63 3168 kiocb->ki_flags = iocb_flags(file);
3e577dcd
PB
3169 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
3170 if (unlikely(ret))
3171 return ret;
2b188cc1 3172
5d329e12
JA
3173 /*
3174 * If the file is marked O_NONBLOCK, still allow retry for it if it
3175 * supports async. Otherwise it's impossible to use O_NONBLOCK files
3176 * reliably. If not, or it IOCB_NOWAIT is set, don't retry.
3177 */
3178 if ((kiocb->ki_flags & IOCB_NOWAIT) ||
35645ac3 3179 ((file->f_flags & O_NONBLOCK) && !io_file_supports_nowait(req)))
75c668cd
PB
3180 req->flags |= REQ_F_NOWAIT;
3181
def596e9 3182 if (ctx->flags & IORING_SETUP_IOPOLL) {
5cb03d63 3183 if (!(kiocb->ki_flags & IOCB_DIRECT) || !file->f_op->iopoll)
09bb8394 3184 return -EOPNOTSUPP;
2b188cc1 3185
394918eb 3186 kiocb->ki_flags |= IOCB_HIPRI | IOCB_ALLOC_CACHE;
def596e9 3187 kiocb->ki_complete = io_complete_rw_iopoll;
65a6543d 3188 req->iopoll_completed = 0;
def596e9 3189 } else {
09bb8394
JA
3190 if (kiocb->ki_flags & IOCB_HIPRI)
3191 return -EINVAL;
def596e9
JA
3192 kiocb->ki_complete = io_complete_rw;
3193 }
9adbd45d 3194
fb27274a
PB
3195 ioprio = READ_ONCE(sqe->ioprio);
3196 if (ioprio) {
3197 ret = ioprio_check_cap(ioprio);
3198 if (ret)
3199 return ret;
3200
3201 kiocb->ki_ioprio = ioprio;
3202 } else {
3203 kiocb->ki_ioprio = get_current_ioprio();
eae071c9
PB
3204 }
3205
578c0ee2 3206 req->imu = NULL;
3529d8c2
JA
3207 req->rw.addr = READ_ONCE(sqe->addr);
3208 req->rw.len = READ_ONCE(sqe->len);
4f4eeba8 3209 req->buf_index = READ_ONCE(sqe->buf_index);
2b188cc1 3210 return 0;
2b188cc1
JA
3211}
3212
3213static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
3214{
3215 switch (ret) {
3216 case -EIOCBQUEUED:
3217 break;
3218 case -ERESTARTSYS:
3219 case -ERESTARTNOINTR:
3220 case -ERESTARTNOHAND:
3221 case -ERESTART_RESTARTBLOCK:
3222 /*
3223 * We can't just restart the syscall, since previously
3224 * submitted sqes may already be in progress. Just fail this
3225 * IO with EINTR.
3226 */
3227 ret = -EINTR;
df561f66 3228 fallthrough;
2b188cc1 3229 default:
6b19b766 3230 kiocb->ki_complete(kiocb, ret);
2b188cc1
JA
3231 }
3232}
3233
b4aec400 3234static inline loff_t *io_kiocb_update_pos(struct io_kiocb *req)
d34e1e5b
DY
3235{
3236 struct kiocb *kiocb = &req->rw.kiocb;
b4aec400 3237 bool is_stream = req->file->f_mode & FMODE_STREAM;
d34e1e5b
DY
3238
3239 if (kiocb->ki_pos == -1) {
b4aec400 3240 if (!is_stream) {
d34e1e5b
DY
3241 req->flags |= REQ_F_CUR_POS;
3242 kiocb->ki_pos = req->file->f_pos;
b4aec400 3243 return &kiocb->ki_pos;
d34e1e5b
DY
3244 } else {
3245 kiocb->ki_pos = 0;
b4aec400 3246 return NULL;
d34e1e5b
DY
3247 }
3248 }
b4aec400 3249 return is_stream ? NULL : &kiocb->ki_pos;
d34e1e5b
DY
3250}
3251
2ea537ca 3252static void kiocb_done(struct io_kiocb *req, ssize_t ret,
889fca73 3253 unsigned int issue_flags)
ba816ad6 3254{
e8c2bc1f 3255 struct io_async_rw *io = req->async_data;
ba04291e 3256
227c0c96 3257 /* add previously done IO, if any */
d886e185 3258 if (req_has_async_data(req) && io->bytes_done > 0) {
227c0c96 3259 if (ret < 0)
e8c2bc1f 3260 ret = io->bytes_done;
227c0c96 3261 else
e8c2bc1f 3262 ret += io->bytes_done;
227c0c96
JA
3263 }
3264
ba04291e 3265 if (req->flags & REQ_F_CUR_POS)
2ea537ca
PB
3266 req->file->f_pos = req->rw.kiocb.ki_pos;
3267 if (ret >= 0 && (req->rw.kiocb.ki_complete == io_complete_rw))
00f6e68b 3268 __io_complete_rw(req, ret, issue_flags);
ba816ad6 3269 else
2ea537ca 3270 io_rw_done(&req->rw.kiocb, ret);
97284637 3271
b66ceaf3 3272 if (req->flags & REQ_F_REISSUE) {
97284637 3273 req->flags &= ~REQ_F_REISSUE;
b91ef187 3274 if (io_resubmit_prep(req))
773af691 3275 io_req_task_queue_reissue(req);
b91ef187
PB
3276 else
3277 io_req_task_queue_fail(req, ret);
97284637 3278 }
ba816ad6
JA
3279}
3280
eae071c9
PB
3281static int __io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter,
3282 struct io_mapped_ubuf *imu)
edafccee 3283{
9adbd45d 3284 size_t len = req->rw.len;
75769e3f 3285 u64 buf_end, buf_addr = req->rw.addr;
edafccee 3286 size_t offset;
edafccee 3287
75769e3f 3288 if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
edafccee
JA
3289 return -EFAULT;
3290 /* not inside the mapped region */
4751f53d 3291 if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
edafccee
JA
3292 return -EFAULT;
3293
3294 /*
3295 * May not be a start of buffer, set size appropriately
3296 * and advance us to the beginning.
3297 */
3298 offset = buf_addr - imu->ubuf;
3299 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
bd11b3a3
JA
3300
3301 if (offset) {
3302 /*
3303 * Don't use iov_iter_advance() here, as it's really slow for
3304 * using the latter parts of a big fixed buffer - it iterates
3305 * over each segment manually. We can cheat a bit here, because
3306 * we know that:
3307 *
3308 * 1) it's a BVEC iter, we set it up
3309 * 2) all bvecs are PAGE_SIZE in size, except potentially the
3310 * first and last bvec
3311 *
3312 * So just find our index, and adjust the iterator afterwards.
3313 * If the offset is within the first bvec (or the whole first
3314 * bvec, just use iov_iter_advance(). This makes it easier
3315 * since we can just skip the first segment, which may not
3316 * be PAGE_SIZE aligned.
3317 */
3318 const struct bio_vec *bvec = imu->bvec;
3319
3320 if (offset <= bvec->bv_len) {
3321 iov_iter_advance(iter, offset);
3322 } else {
3323 unsigned long seg_skip;
3324
3325 /* skip first vec */
3326 offset -= bvec->bv_len;
3327 seg_skip = 1 + (offset >> PAGE_SHIFT);
3328
3329 iter->bvec = bvec + seg_skip;
3330 iter->nr_segs -= seg_skip;
99c79f66 3331 iter->count -= bvec->bv_len + offset;
bd11b3a3 3332 iter->iov_offset = offset & ~PAGE_MASK;
bd11b3a3
JA
3333 }
3334 }
3335
847595de 3336 return 0;
edafccee
JA
3337}
3338
eae071c9
PB
3339static int io_import_fixed(struct io_kiocb *req, int rw, struct iov_iter *iter)
3340{
eae071c9
PB
3341 struct io_mapped_ubuf *imu = req->imu;
3342 u16 index, buf_index = req->buf_index;
3343
3344 if (likely(!imu)) {
578c0ee2
PB
3345 struct io_ring_ctx *ctx = req->ctx;
3346
eae071c9
PB
3347 if (unlikely(buf_index >= ctx->nr_user_bufs))
3348 return -EFAULT;
578c0ee2 3349 io_req_set_rsrc_node(req, ctx);
eae071c9
PB
3350 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
3351 imu = READ_ONCE(ctx->user_bufs[index]);
3352 req->imu = imu;
3353 }
3354 return __io_import_fixed(req, rw, iter, imu);
3355}
3356
bcda7baa
JA
3357static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
3358{
3359 if (needs_lock)
3360 mutex_unlock(&ctx->uring_lock);
3361}
3362
3363static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
3364{
3365 /*
3366 * "Normal" inline submissions always hold the uring_lock, since we
3367 * grab it from the system call. Same is true for the SQPOLL offload.
3368 * The only exception is when we've detached the request and issue it
3369 * from an async worker thread, grab the lock for that case.
3370 */
3371 if (needs_lock)
3372 mutex_lock(&ctx->uring_lock);
3373}
3374
dbc7d452
JA
3375static void io_buffer_add_list(struct io_ring_ctx *ctx,
3376 struct io_buffer_list *bl, unsigned int bgid)
3377{
3378 struct list_head *list;
3379
3380 list = &ctx->io_buffers[hash_32(bgid, IO_BUFFERS_HASH_BITS)];
3381 INIT_LIST_HEAD(&bl->buf_list);
3382 bl->bgid = bgid;
3383 list_add(&bl->list, list);
3384}
3385
bcda7baa 3386static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
51aac424 3387 int bgid, unsigned int issue_flags)
bcda7baa 3388{
30d51dd4 3389 struct io_buffer *kbuf = req->kbuf;
3b44b371 3390 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
dbc7d452
JA
3391 struct io_ring_ctx *ctx = req->ctx;
3392 struct io_buffer_list *bl;
bcda7baa
JA
3393
3394 if (req->flags & REQ_F_BUFFER_SELECTED)
3395 return kbuf;
3396
dbc7d452 3397 io_ring_submit_lock(ctx, needs_lock);
bcda7baa 3398
dbc7d452 3399 lockdep_assert_held(&ctx->uring_lock);
bcda7baa 3400
dbc7d452
JA
3401 bl = io_buffer_get_list(ctx, bgid);
3402 if (bl && !list_empty(&bl->buf_list)) {
3403 kbuf = list_first_entry(&bl->buf_list, struct io_buffer, list);
3404 list_del(&kbuf->list);
bcda7baa
JA
3405 if (*len > kbuf->len)
3406 *len = kbuf->len;
30d51dd4
PB
3407 req->flags |= REQ_F_BUFFER_SELECTED;
3408 req->kbuf = kbuf;
bcda7baa
JA
3409 } else {
3410 kbuf = ERR_PTR(-ENOBUFS);
3411 }
3412
3413 io_ring_submit_unlock(req->ctx, needs_lock);
bcda7baa
JA
3414 return kbuf;
3415}
3416
4d954c25 3417static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
51aac424 3418 unsigned int issue_flags)
4d954c25
JA
3419{
3420 struct io_buffer *kbuf;
4f4eeba8 3421 u16 bgid;
4d954c25 3422
4f4eeba8 3423 bgid = req->buf_index;
51aac424 3424 kbuf = io_buffer_select(req, len, bgid, issue_flags);
4d954c25
JA
3425 if (IS_ERR(kbuf))
3426 return kbuf;
4d954c25
JA
3427 return u64_to_user_ptr(kbuf->addr);
3428}
3429
3430#ifdef CONFIG_COMPAT
3431static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
51aac424 3432 unsigned int issue_flags)
4d954c25
JA
3433{
3434 struct compat_iovec __user *uiov;
3435 compat_ssize_t clen;
3436 void __user *buf;
3437 ssize_t len;
3438
3439 uiov = u64_to_user_ptr(req->rw.addr);
3440 if (!access_ok(uiov, sizeof(*uiov)))
3441 return -EFAULT;
3442 if (__get_user(clen, &uiov->iov_len))
3443 return -EFAULT;
3444 if (clen < 0)
3445 return -EINVAL;
3446
3447 len = clen;
51aac424 3448 buf = io_rw_buffer_select(req, &len, issue_flags);
4d954c25
JA
3449 if (IS_ERR(buf))
3450 return PTR_ERR(buf);
3451 iov[0].iov_base = buf;
3452 iov[0].iov_len = (compat_size_t) len;
3453 return 0;
3454}
3455#endif
3456
3457static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
51aac424 3458 unsigned int issue_flags)
4d954c25
JA
3459{
3460 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
3461 void __user *buf;
3462 ssize_t len;
3463
3464 if (copy_from_user(iov, uiov, sizeof(*uiov)))
3465 return -EFAULT;
3466
3467 len = iov[0].iov_len;
3468 if (len < 0)
3469 return -EINVAL;
51aac424 3470 buf = io_rw_buffer_select(req, &len, issue_flags);
4d954c25
JA
3471 if (IS_ERR(buf))
3472 return PTR_ERR(buf);
3473 iov[0].iov_base = buf;
3474 iov[0].iov_len = len;
3475 return 0;
3476}
3477
3478static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
51aac424 3479 unsigned int issue_flags)
4d954c25 3480{
dddb3e26 3481 if (req->flags & REQ_F_BUFFER_SELECTED) {
30d51dd4 3482 struct io_buffer *kbuf = req->kbuf;
dddb3e26 3483
dddb3e26
JA
3484 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
3485 iov[0].iov_len = kbuf->len;
4d954c25 3486 return 0;
dddb3e26 3487 }
dd201662 3488 if (req->rw.len != 1)
4d954c25
JA
3489 return -EINVAL;
3490
3491#ifdef CONFIG_COMPAT
3492 if (req->ctx->compat)
51aac424 3493 return io_compat_import(req, iov, issue_flags);
4d954c25
JA
3494#endif
3495
51aac424 3496 return __io_iov_buffer_select(req, iov, issue_flags);
4d954c25
JA
3497}
3498
caa8fe6e
PB
3499static struct iovec *__io_import_iovec(int rw, struct io_kiocb *req,
3500 struct io_rw_state *s,
3501 unsigned int issue_flags)
2b188cc1 3502{
5e49c973 3503 struct iov_iter *iter = &s->iter;
847595de 3504 u8 opcode = req->opcode;
caa8fe6e 3505 struct iovec *iovec;
d1d681b0
PB
3506 void __user *buf;
3507 size_t sqe_len;
4d954c25 3508 ssize_t ret;
edafccee 3509
f3251183
PB
3510 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
3511 ret = io_import_fixed(req, rw, iter);
3512 if (ret)
3513 return ERR_PTR(ret);
3514 return NULL;
3515 }
2b188cc1 3516
bcda7baa 3517 /* buffer index only valid with fixed read/write, or buffer select */
d1d681b0 3518 if (unlikely(req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT)))
caa8fe6e 3519 return ERR_PTR(-EINVAL);
9adbd45d 3520
d1d681b0
PB
3521 buf = u64_to_user_ptr(req->rw.addr);
3522 sqe_len = req->rw.len;
9adbd45d 3523
3a6820f2 3524 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
bcda7baa 3525 if (req->flags & REQ_F_BUFFER_SELECT) {
51aac424 3526 buf = io_rw_buffer_select(req, &sqe_len, issue_flags);
867a23ea 3527 if (IS_ERR(buf))
898df244 3528 return ERR_CAST(buf);
3f9d6441 3529 req->rw.len = sqe_len;
bcda7baa
JA
3530 }
3531
5e49c973 3532 ret = import_single_range(rw, buf, sqe_len, s->fast_iov, iter);
f3251183
PB
3533 if (ret)
3534 return ERR_PTR(ret);
3535 return NULL;
3a6820f2
JA
3536 }
3537
caa8fe6e 3538 iovec = s->fast_iov;
4d954c25 3539 if (req->flags & REQ_F_BUFFER_SELECT) {
caa8fe6e 3540 ret = io_iov_buffer_select(req, iovec, issue_flags);
f3251183
PB
3541 if (ret)
3542 return ERR_PTR(ret);
3543 iov_iter_init(iter, rw, iovec, 1, iovec->iov_len);
3544 return NULL;
4d954c25
JA
3545 }
3546
caa8fe6e 3547 ret = __import_iovec(rw, buf, sqe_len, UIO_FASTIOV, &iovec, iter,
89cd35c5 3548 req->ctx->compat);
caa8fe6e
PB
3549 if (unlikely(ret < 0))
3550 return ERR_PTR(ret);
3551 return iovec;
2b188cc1
JA
3552}
3553
5e49c973
PB
3554static inline int io_import_iovec(int rw, struct io_kiocb *req,
3555 struct iovec **iovec, struct io_rw_state *s,
3556 unsigned int issue_flags)
3557{
caa8fe6e
PB
3558 *iovec = __io_import_iovec(rw, req, s, issue_flags);
3559 if (unlikely(IS_ERR(*iovec)))
3560 return PTR_ERR(*iovec);
5e49c973 3561
5e49c973 3562 iov_iter_save_state(&s->iter, &s->iter_state);
caa8fe6e 3563 return 0;
2b188cc1
JA
3564}
3565
0fef9483
JA
3566static inline loff_t *io_kiocb_ppos(struct kiocb *kiocb)
3567{
5b09e37e 3568 return (kiocb->ki_filp->f_mode & FMODE_STREAM) ? NULL : &kiocb->ki_pos;
0fef9483
JA
3569}
3570
31b51510 3571/*
32960613
JA
3572 * For files that don't have ->read_iter() and ->write_iter(), handle them
3573 * by looping over ->read() or ->write() manually.
31b51510 3574 */
4017eb91 3575static ssize_t loop_rw_iter(int rw, struct io_kiocb *req, struct iov_iter *iter)
32960613 3576{
4017eb91
JA
3577 struct kiocb *kiocb = &req->rw.kiocb;
3578 struct file *file = req->file;
32960613 3579 ssize_t ret = 0;
af9c45ec 3580 loff_t *ppos;
32960613
JA
3581
3582 /*
3583 * Don't support polled IO through this interface, and we can't
3584 * support non-blocking either. For the latter, this just causes
3585 * the kiocb to be handled from an async context.
3586 */
3587 if (kiocb->ki_flags & IOCB_HIPRI)
3588 return -EOPNOTSUPP;
35645ac3
PB
3589 if ((kiocb->ki_flags & IOCB_NOWAIT) &&
3590 !(kiocb->ki_filp->f_flags & O_NONBLOCK))
32960613
JA
3591 return -EAGAIN;
3592
af9c45ec
DY
3593 ppos = io_kiocb_ppos(kiocb);
3594
32960613 3595 while (iov_iter_count(iter)) {
311ae9e1 3596 struct iovec iovec;
32960613
JA
3597 ssize_t nr;
3598
311ae9e1
PB
3599 if (!iov_iter_is_bvec(iter)) {
3600 iovec = iov_iter_iovec(iter);
3601 } else {
4017eb91
JA
3602 iovec.iov_base = u64_to_user_ptr(req->rw.addr);
3603 iovec.iov_len = req->rw.len;
311ae9e1
PB
3604 }
3605
32960613
JA
3606 if (rw == READ) {
3607 nr = file->f_op->read(file, iovec.iov_base,
af9c45ec 3608 iovec.iov_len, ppos);
32960613
JA
3609 } else {
3610 nr = file->f_op->write(file, iovec.iov_base,
af9c45ec 3611 iovec.iov_len, ppos);
32960613
JA
3612 }
3613
3614 if (nr < 0) {
3615 if (!ret)
3616 ret = nr;
3617 break;
3618 }
5e929367 3619 ret += nr;
16c8d2df
JA
3620 if (!iov_iter_is_bvec(iter)) {
3621 iov_iter_advance(iter, nr);
3622 } else {
16c8d2df 3623 req->rw.addr += nr;
5e929367
JA
3624 req->rw.len -= nr;
3625 if (!req->rw.len)
3626 break;
16c8d2df 3627 }
32960613
JA
3628 if (nr != iovec.iov_len)
3629 break;
32960613
JA
3630 }
3631
3632 return ret;
3633}
3634
ff6165b2
JA
3635static void io_req_map_rw(struct io_kiocb *req, const struct iovec *iovec,
3636 const struct iovec *fast_iov, struct iov_iter *iter)
f67676d1 3637{
e8c2bc1f 3638 struct io_async_rw *rw = req->async_data;
b64e3444 3639
538941e2 3640 memcpy(&rw->s.iter, iter, sizeof(*iter));
afb87658 3641 rw->free_iovec = iovec;
227c0c96 3642 rw->bytes_done = 0;
ff6165b2 3643 /* can only be fixed buffers, no need to do anything */
9c3a205c 3644 if (iov_iter_is_bvec(iter))
ff6165b2 3645 return;
b64e3444 3646 if (!iovec) {
ff6165b2
JA
3647 unsigned iov_off = 0;
3648
538941e2 3649 rw->s.iter.iov = rw->s.fast_iov;
ff6165b2
JA
3650 if (iter->iov != fast_iov) {
3651 iov_off = iter->iov - fast_iov;
538941e2 3652 rw->s.iter.iov += iov_off;
ff6165b2 3653 }
538941e2
PB
3654 if (rw->s.fast_iov != fast_iov)
3655 memcpy(rw->s.fast_iov + iov_off, fast_iov + iov_off,
45097dae 3656 sizeof(struct iovec) * iter->nr_segs);
99bc4c38
PB
3657 } else {
3658 req->flags |= REQ_F_NEED_CLEANUP;
f67676d1
JA
3659 }
3660}
3661
8d4af685 3662static inline bool io_alloc_async_data(struct io_kiocb *req)
3d9932a8 3663{
e8c2bc1f
JA
3664 WARN_ON_ONCE(!io_op_defs[req->opcode].async_size);
3665 req->async_data = kmalloc(io_op_defs[req->opcode].async_size, GFP_KERNEL);
d886e185
PB
3666 if (req->async_data) {
3667 req->flags |= REQ_F_ASYNC_DATA;
3668 return false;
3669 }
3670 return true;
3d9932a8
XW
3671}
3672
ff6165b2 3673static int io_setup_async_rw(struct io_kiocb *req, const struct iovec *iovec,
c88598a9 3674 struct io_rw_state *s, bool force)
b7bb4f7d 3675{
26f0505a 3676 if (!force && !io_op_defs[req->opcode].needs_async_setup)
74566df3 3677 return 0;
d886e185 3678 if (!req_has_async_data(req)) {
cd658695
JA
3679 struct io_async_rw *iorw;
3680
6cb78689 3681 if (io_alloc_async_data(req)) {
6bf985dc 3682 kfree(iovec);
5d204bcf 3683 return -ENOMEM;
6bf985dc 3684 }
b7bb4f7d 3685
c88598a9 3686 io_req_map_rw(req, iovec, s->fast_iov, &s->iter);
cd658695
JA
3687 iorw = req->async_data;
3688 /* we've copied and mapped the iter, ensure state is saved */
538941e2 3689 iov_iter_save_state(&iorw->s.iter, &iorw->s.iter_state);
5d204bcf 3690 }
b7bb4f7d 3691 return 0;
f67676d1
JA
3692}
3693
73debe68 3694static inline int io_rw_prep_async(struct io_kiocb *req, int rw)
c3e330a4 3695{
e8c2bc1f 3696 struct io_async_rw *iorw = req->async_data;
5e49c973 3697 struct iovec *iov;
847595de 3698 int ret;
c3e330a4 3699
51aac424 3700 /* submission path, ->uring_lock should already be taken */
3b44b371 3701 ret = io_import_iovec(rw, req, &iov, &iorw->s, 0);
c3e330a4
PB
3702 if (unlikely(ret < 0))
3703 return ret;
3704
ab0b196c
PB
3705 iorw->bytes_done = 0;
3706 iorw->free_iovec = iov;
3707 if (iov)
3708 req->flags |= REQ_F_NEED_CLEANUP;
c3e330a4
PB
3709 return 0;
3710}
3711
73debe68 3712static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
f67676d1 3713{
3529d8c2
JA
3714 if (unlikely(!(req->file->f_mode & FMODE_READ)))
3715 return -EBADF;
b9a6b8f9 3716 return io_prep_rw(req, sqe);
f67676d1
JA
3717}
3718
c1dd91d1 3719/*
ffdc8dab 3720 * This is our waitqueue callback handler, registered through __folio_lock_async()
c1dd91d1
JA
3721 * when we initially tried to do the IO with the iocb armed our waitqueue.
3722 * This gets called when the page is unlocked, and we generally expect that to
3723 * happen when the page IO is completed and the page is now uptodate. This will
3724 * queue a task_work based retry of the operation, attempting to copy the data
3725 * again. If the latter fails because the page was NOT uptodate, then we will
3726 * do a thread based blocking retry of the operation. That's the unexpected
3727 * slow path.
3728 */
bcf5a063
JA
3729static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
3730 int sync, void *arg)
3731{
3732 struct wait_page_queue *wpq;
3733 struct io_kiocb *req = wait->private;
bcf5a063 3734 struct wait_page_key *key = arg;
bcf5a063
JA
3735
3736 wpq = container_of(wait, struct wait_page_queue, wait);
3737
cdc8fcb4
LT
3738 if (!wake_page_match(wpq, key))
3739 return 0;
3740
c8d317aa 3741 req->rw.kiocb.ki_flags &= ~IOCB_WAITQ;
bcf5a063 3742 list_del_init(&wait->entry);
921b9054 3743 io_req_task_queue(req);
bcf5a063
JA
3744 return 1;
3745}
3746
c1dd91d1
JA
3747/*
3748 * This controls whether a given IO request should be armed for async page
3749 * based retry. If we return false here, the request is handed to the async
3750 * worker threads for retry. If we're doing buffered reads on a regular file,
3751 * we prepare a private wait_page_queue entry and retry the operation. This
3752 * will either succeed because the page is now uptodate and unlocked, or it
3753 * will register a callback when the page is unlocked at IO completion. Through
3754 * that callback, io_uring uses task_work to setup a retry of the operation.
3755 * That retry will attempt the buffered read again. The retry will generally
3756 * succeed, or in rare cases where it fails, we then fall back to using the
3757 * async worker threads for a blocking retry.
3758 */
227c0c96 3759static bool io_rw_should_retry(struct io_kiocb *req)
f67676d1 3760{
e8c2bc1f
JA
3761 struct io_async_rw *rw = req->async_data;
3762 struct wait_page_queue *wait = &rw->wpq;
bcf5a063 3763 struct kiocb *kiocb = &req->rw.kiocb;
f67676d1 3764
bcf5a063
JA
3765 /* never retry for NOWAIT, we just complete with -EAGAIN */
3766 if (req->flags & REQ_F_NOWAIT)
3767 return false;
f67676d1 3768
227c0c96 3769 /* Only for buffered IO */
3b2a4439 3770 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_HIPRI))
bcf5a063 3771 return false;
3b2a4439 3772
bcf5a063
JA
3773 /*
3774 * just use poll if we can, and don't attempt if the fs doesn't
3775 * support callback based unlocks
3776 */
3777 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
3778 return false;
f67676d1 3779
3b2a4439
JA
3780 wait->wait.func = io_async_buf_func;
3781 wait->wait.private = req;
3782 wait->wait.flags = 0;
3783 INIT_LIST_HEAD(&wait->wait.entry);
3784 kiocb->ki_flags |= IOCB_WAITQ;
c8d317aa 3785 kiocb->ki_flags &= ~IOCB_NOWAIT;
3b2a4439 3786 kiocb->ki_waitq = wait;
3b2a4439 3787 return true;
bcf5a063
JA
3788}
3789
aeab9506 3790static inline int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
bcf5a063 3791{
607b6fb8 3792 if (likely(req->file->f_op->read_iter))
bcf5a063 3793 return call_read_iter(req->file, &req->rw.kiocb, iter);
2dd2111d 3794 else if (req->file->f_op->read)
4017eb91 3795 return loop_rw_iter(READ, req, iter);
2dd2111d
GH
3796 else
3797 return -EINVAL;
f67676d1
JA
3798}
3799
7db30437
ML
3800static bool need_read_all(struct io_kiocb *req)
3801{
3802 return req->flags & REQ_F_ISREG ||
3803 S_ISBLK(file_inode(req->file)->i_mode);
3804}
3805
889fca73 3806static int io_read(struct io_kiocb *req, unsigned int issue_flags)
2b188cc1 3807{
607b6fb8 3808 struct io_rw_state __s, *s = &__s;
c88598a9 3809 struct iovec *iovec;
9adbd45d 3810 struct kiocb *kiocb = &req->rw.kiocb;
45d189c6 3811 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
d886e185 3812 struct io_async_rw *rw;
cd658695 3813 ssize_t ret, ret2;
b4aec400 3814 loff_t *ppos;
ff6165b2 3815
607b6fb8
PB
3816 if (!req_has_async_data(req)) {
3817 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3818 if (unlikely(ret < 0))
3819 return ret;
3820 } else {
2be2eb02
JA
3821 /*
3822 * Safe and required to re-import if we're using provided
3823 * buffers, as we dropped the selected one before retry.
3824 */
3825 if (req->flags & REQ_F_BUFFER_SELECT) {
3826 ret = io_import_iovec(READ, req, &iovec, s, issue_flags);
3827 if (unlikely(ret < 0))
3828 return ret;
3829 }
3830
d886e185 3831 rw = req->async_data;
c88598a9 3832 s = &rw->s;
cd658695
JA
3833 /*
3834 * We come here from an earlier attempt, restore our state to
3835 * match in case it doesn't. It's cheap enough that we don't
3836 * need to make this conditional.
3837 */
c88598a9 3838 iov_iter_restore(&s->iter, &s->iter_state);
2846c481 3839 iovec = NULL;
2846c481 3840 }
c88598a9 3841 req->result = iov_iter_count(&s->iter);
2b188cc1 3842
607b6fb8
PB
3843 if (force_nonblock) {
3844 /* If the file doesn't support async, just async punt */
35645ac3 3845 if (unlikely(!io_file_supports_nowait(req))) {
607b6fb8
PB
3846 ret = io_setup_async_rw(req, iovec, s, true);
3847 return ret ?: -EAGAIN;
3848 }
a88fc400 3849 kiocb->ki_flags |= IOCB_NOWAIT;
607b6fb8
PB
3850 } else {
3851 /* Ensure we clear previously set non-block flag */
3852 kiocb->ki_flags &= ~IOCB_NOWAIT;
6713e7a6 3853 }
9e645e11 3854
b4aec400 3855 ppos = io_kiocb_update_pos(req);
d34e1e5b 3856
b4aec400 3857 ret = rw_verify_area(READ, req->file, ppos, req->result);
5ea5dd45
PB
3858 if (unlikely(ret)) {
3859 kfree(iovec);
3860 return ret;
3861 }
2b188cc1 3862
c88598a9 3863 ret = io_iter_do_read(req, &s->iter);
32960613 3864
230d50d4 3865 if (ret == -EAGAIN || (req->flags & REQ_F_REISSUE)) {
6ad7f233 3866 req->flags &= ~REQ_F_REISSUE;
9af177ee
JA
3867 /* if we can poll, just do that */
3868 if (req->opcode == IORING_OP_READ && file_can_poll(req->file))
3869 return -EAGAIN;
eefdf30f
JA
3870 /* IOPOLL retry should happen for io-wq threads */
3871 if (!force_nonblock && !(req->ctx->flags & IORING_SETUP_IOPOLL))
f91daf56 3872 goto done;
75c668cd
PB
3873 /* no retry on NONBLOCK nor RWF_NOWAIT */
3874 if (req->flags & REQ_F_NOWAIT)
355afaeb 3875 goto done;
f38c7e3a 3876 ret = 0;
230d50d4
JA
3877 } else if (ret == -EIOCBQUEUED) {
3878 goto out_free;
f80a50a6 3879 } else if (ret == req->result || ret <= 0 || !force_nonblock ||
7db30437 3880 (req->flags & REQ_F_NOWAIT) || !need_read_all(req)) {
7335e3bf 3881 /* read all, failed, already did sync or don't want to retry */
00d23d51 3882 goto done;
227c0c96
JA
3883 }
3884
cd658695
JA
3885 /*
3886 * Don't depend on the iter state matching what was consumed, or being
3887 * untouched in case of error. Restore it and we'll advance it
3888 * manually if we need to.
3889 */
c88598a9 3890 iov_iter_restore(&s->iter, &s->iter_state);
cd658695 3891
c88598a9 3892 ret2 = io_setup_async_rw(req, iovec, s, true);
6bf985dc
PB
3893 if (ret2)
3894 return ret2;
3895
fe1cdd55 3896 iovec = NULL;
e8c2bc1f 3897 rw = req->async_data;
c88598a9 3898 s = &rw->s;
cd658695
JA
3899 /*
3900 * Now use our persistent iterator and state, if we aren't already.
3901 * We've restored and mapped the iter to match.
3902 */
227c0c96 3903
b23df91b 3904 do {
cd658695
JA
3905 /*
3906 * We end up here because of a partial read, either from
3907 * above or inside this loop. Advance the iter by the bytes
3908 * that were consumed.
3909 */
c88598a9
PB
3910 iov_iter_advance(&s->iter, ret);
3911 if (!iov_iter_count(&s->iter))
cd658695 3912 break;
b23df91b 3913 rw->bytes_done += ret;
c88598a9 3914 iov_iter_save_state(&s->iter, &s->iter_state);
cd658695 3915
b23df91b
PB
3916 /* if we can retry, do so with the callbacks armed */
3917 if (!io_rw_should_retry(req)) {
3918 kiocb->ki_flags &= ~IOCB_WAITQ;
3919 return -EAGAIN;
3920 }
3921
3922 /*
3923 * Now retry read with the IOCB_WAITQ parts set in the iocb. If
3924 * we get -EIOCBQUEUED, then we'll get a notification when the
3925 * desired page gets unlocked. We can also get a partial read
3926 * here, and if we do, then just retry at the new offset.
3927 */
c88598a9 3928 ret = io_iter_do_read(req, &s->iter);
b23df91b
PB
3929 if (ret == -EIOCBQUEUED)
3930 return 0;
227c0c96 3931 /* we got some bytes, but not all. retry. */
b5b0ecb7 3932 kiocb->ki_flags &= ~IOCB_WAITQ;
c88598a9 3933 iov_iter_restore(&s->iter, &s->iter_state);
cd658695 3934 } while (ret > 0);
227c0c96 3935done:
2ea537ca 3936 kiocb_done(req, ret, issue_flags);
fe1cdd55
PB
3937out_free:
3938 /* it's faster to check here then delegate to kfree */
3939 if (iovec)
3940 kfree(iovec);
5ea5dd45 3941 return 0;
2b188cc1
JA
3942}
3943
73debe68 3944static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
f67676d1 3945{
3529d8c2
JA
3946 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3947 return -EBADF;
3884b83d 3948 req->rw.kiocb.ki_hint = ki_hint_validate(file_write_hint(req->file));
b9a6b8f9 3949 return io_prep_rw(req, sqe);
f67676d1
JA
3950}
3951
889fca73 3952static int io_write(struct io_kiocb *req, unsigned int issue_flags)
2b188cc1 3953{
607b6fb8 3954 struct io_rw_state __s, *s = &__s;
c88598a9 3955 struct iovec *iovec;
9adbd45d 3956 struct kiocb *kiocb = &req->rw.kiocb;
45d189c6 3957 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
cd658695 3958 ssize_t ret, ret2;
b4aec400 3959 loff_t *ppos;
2b188cc1 3960
607b6fb8 3961 if (!req_has_async_data(req)) {
5e49c973
PB
3962 ret = io_import_iovec(WRITE, req, &iovec, s, issue_flags);
3963 if (unlikely(ret < 0))
2846c481 3964 return ret;
607b6fb8
PB
3965 } else {
3966 struct io_async_rw *rw = req->async_data;
3967
3968 s = &rw->s;
3969 iov_iter_restore(&s->iter, &s->iter_state);
2846c481 3970 iovec = NULL;
2846c481 3971 }
c88598a9 3972 req->result = iov_iter_count(&s->iter);
2b188cc1 3973
607b6fb8
PB
3974 if (force_nonblock) {
3975 /* If the file doesn't support async, just async punt */
35645ac3 3976 if (unlikely(!io_file_supports_nowait(req)))
607b6fb8 3977 goto copy_iov;
fd6c2e4c 3978
607b6fb8
PB
3979 /* file path doesn't support NOWAIT for non-direct_IO */
3980 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3981 (req->flags & REQ_F_ISREG))
3982 goto copy_iov;
31b51510 3983
607b6fb8
PB
3984 kiocb->ki_flags |= IOCB_NOWAIT;
3985 } else {
3986 /* Ensure we clear previously set non-block flag */
3987 kiocb->ki_flags &= ~IOCB_NOWAIT;
3988 }
31b51510 3989
b4aec400 3990 ppos = io_kiocb_update_pos(req);
d34e1e5b 3991
b4aec400 3992 ret = rw_verify_area(WRITE, req->file, ppos, req->result);
fa15bafb
PB
3993 if (unlikely(ret))
3994 goto out_free;
4ed734b0 3995
fa15bafb
PB
3996 /*
3997 * Open-code file_start_write here to grab freeze protection,
3998 * which will be released by another thread in
3999 * io_complete_rw(). Fool lockdep by telling it the lock got
4000 * released so that it doesn't complain about the held lock when
4001 * we return to userspace.
4002 */
4003 if (req->flags & REQ_F_ISREG) {
8a3c84b6 4004 sb_start_write(file_inode(req->file)->i_sb);
fa15bafb
PB
4005 __sb_writers_release(file_inode(req->file)->i_sb,
4006 SB_FREEZE_WRITE);
4007 }
4008 kiocb->ki_flags |= IOCB_WRITE;
4ed734b0 4009
35645ac3 4010 if (likely(req->file->f_op->write_iter))
c88598a9 4011 ret2 = call_write_iter(req->file, kiocb, &s->iter);
2dd2111d 4012 else if (req->file->f_op->write)
c88598a9 4013 ret2 = loop_rw_iter(WRITE, req, &s->iter);
2dd2111d
GH
4014 else
4015 ret2 = -EINVAL;
4ed734b0 4016
6ad7f233
PB
4017 if (req->flags & REQ_F_REISSUE) {
4018 req->flags &= ~REQ_F_REISSUE;
230d50d4 4019 ret2 = -EAGAIN;
6ad7f233 4020 }
230d50d4 4021
fa15bafb
PB
4022 /*
4023 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
4024 * retry them without IOCB_NOWAIT.
4025 */
4026 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
4027 ret2 = -EAGAIN;
75c668cd
PB
4028 /* no retry on NONBLOCK nor RWF_NOWAIT */
4029 if (ret2 == -EAGAIN && (req->flags & REQ_F_NOWAIT))
355afaeb 4030 goto done;
fa15bafb 4031 if (!force_nonblock || ret2 != -EAGAIN) {
eefdf30f 4032 /* IOPOLL retry should happen for io-wq threads */
b10841c9 4033 if (ret2 == -EAGAIN && (req->ctx->flags & IORING_SETUP_IOPOLL))
eefdf30f 4034 goto copy_iov;
355afaeb 4035done:
2ea537ca 4036 kiocb_done(req, ret2, issue_flags);
fa15bafb 4037 } else {
f67676d1 4038copy_iov:
c88598a9
PB
4039 iov_iter_restore(&s->iter, &s->iter_state);
4040 ret = io_setup_async_rw(req, iovec, s, false);
6bf985dc 4041 return ret ?: -EAGAIN;
2b188cc1 4042 }
31b51510 4043out_free:
f261c168 4044 /* it's reportedly faster than delegating the null check to kfree() */
252917c3 4045 if (iovec)
6f2cc166 4046 kfree(iovec);
2b188cc1
JA
4047 return ret;
4048}
4049
80a261fd
JA
4050static int io_renameat_prep(struct io_kiocb *req,
4051 const struct io_uring_sqe *sqe)
4052{
4053 struct io_rename *ren = &req->rename;
4054 const char __user *oldf, *newf;
4055
ed7eb259
JA
4056 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4057 return -EINVAL;
26578cda 4058 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
ed7eb259 4059 return -EINVAL;
80a261fd
JA
4060 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4061 return -EBADF;
4062
4063 ren->old_dfd = READ_ONCE(sqe->fd);
4064 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4065 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4066 ren->new_dfd = READ_ONCE(sqe->len);
4067 ren->flags = READ_ONCE(sqe->rename_flags);
4068
4069 ren->oldpath = getname(oldf);
4070 if (IS_ERR(ren->oldpath))
4071 return PTR_ERR(ren->oldpath);
4072
4073 ren->newpath = getname(newf);
4074 if (IS_ERR(ren->newpath)) {
4075 putname(ren->oldpath);
4076 return PTR_ERR(ren->newpath);
4077 }
4078
4079 req->flags |= REQ_F_NEED_CLEANUP;
4080 return 0;
4081}
4082
45d189c6 4083static int io_renameat(struct io_kiocb *req, unsigned int issue_flags)
80a261fd
JA
4084{
4085 struct io_rename *ren = &req->rename;
4086 int ret;
4087
45d189c6 4088 if (issue_flags & IO_URING_F_NONBLOCK)
80a261fd
JA
4089 return -EAGAIN;
4090
4091 ret = do_renameat2(ren->old_dfd, ren->oldpath, ren->new_dfd,
4092 ren->newpath, ren->flags);
4093
4094 req->flags &= ~REQ_F_NEED_CLEANUP;
4095 if (ret < 0)
93d2bcd2 4096 req_set_fail(req);
80a261fd
JA
4097 io_req_complete(req, ret);
4098 return 0;
4099}
4100
14a1143b
JA
4101static int io_unlinkat_prep(struct io_kiocb *req,
4102 const struct io_uring_sqe *sqe)
4103{
4104 struct io_unlink *un = &req->unlink;
4105 const char __user *fname;
4106
22634bc5
JA
4107 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4108 return -EINVAL;
26578cda
PB
4109 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4110 sqe->splice_fd_in)
22634bc5 4111 return -EINVAL;
14a1143b
JA
4112 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4113 return -EBADF;
4114
4115 un->dfd = READ_ONCE(sqe->fd);
4116
4117 un->flags = READ_ONCE(sqe->unlink_flags);
4118 if (un->flags & ~AT_REMOVEDIR)
4119 return -EINVAL;
4120
4121 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4122 un->filename = getname(fname);
4123 if (IS_ERR(un->filename))
4124 return PTR_ERR(un->filename);
4125
4126 req->flags |= REQ_F_NEED_CLEANUP;
4127 return 0;
4128}
4129
45d189c6 4130static int io_unlinkat(struct io_kiocb *req, unsigned int issue_flags)
14a1143b
JA
4131{
4132 struct io_unlink *un = &req->unlink;
4133 int ret;
4134
45d189c6 4135 if (issue_flags & IO_URING_F_NONBLOCK)
14a1143b
JA
4136 return -EAGAIN;
4137
4138 if (un->flags & AT_REMOVEDIR)
4139 ret = do_rmdir(un->dfd, un->filename);
4140 else
4141 ret = do_unlinkat(un->dfd, un->filename);
4142
4143 req->flags &= ~REQ_F_NEED_CLEANUP;
4144 if (ret < 0)
93d2bcd2 4145 req_set_fail(req);
14a1143b
JA
4146 io_req_complete(req, ret);
4147 return 0;
4148}
4149
e34a02dc
DK
4150static int io_mkdirat_prep(struct io_kiocb *req,
4151 const struct io_uring_sqe *sqe)
4152{
4153 struct io_mkdir *mkd = &req->mkdir;
4154 const char __user *fname;
4155
4156 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4157 return -EINVAL;
4158 if (sqe->ioprio || sqe->off || sqe->rw_flags || sqe->buf_index ||
4159 sqe->splice_fd_in)
4160 return -EINVAL;
4161 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4162 return -EBADF;
4163
4164 mkd->dfd = READ_ONCE(sqe->fd);
4165 mkd->mode = READ_ONCE(sqe->len);
4166
4167 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
4168 mkd->filename = getname(fname);
4169 if (IS_ERR(mkd->filename))
4170 return PTR_ERR(mkd->filename);
4171
4172 req->flags |= REQ_F_NEED_CLEANUP;
4173 return 0;
4174}
4175
04f34081 4176static int io_mkdirat(struct io_kiocb *req, unsigned int issue_flags)
e34a02dc
DK
4177{
4178 struct io_mkdir *mkd = &req->mkdir;
4179 int ret;
4180
4181 if (issue_flags & IO_URING_F_NONBLOCK)
4182 return -EAGAIN;
4183
4184 ret = do_mkdirat(mkd->dfd, mkd->filename, mkd->mode);
4185
4186 req->flags &= ~REQ_F_NEED_CLEANUP;
4187 if (ret < 0)
4188 req_set_fail(req);
4189 io_req_complete(req, ret);
4190 return 0;
4191}
4192
7a8721f8
DK
4193static int io_symlinkat_prep(struct io_kiocb *req,
4194 const struct io_uring_sqe *sqe)
4195{
4196 struct io_symlink *sl = &req->symlink;
4197 const char __user *oldpath, *newpath;
4198
4199 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4200 return -EINVAL;
4201 if (sqe->ioprio || sqe->len || sqe->rw_flags || sqe->buf_index ||
4202 sqe->splice_fd_in)
4203 return -EINVAL;
4204 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4205 return -EBADF;
4206
4207 sl->new_dfd = READ_ONCE(sqe->fd);
4208 oldpath = u64_to_user_ptr(READ_ONCE(sqe->addr));
4209 newpath = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4210
4211 sl->oldpath = getname(oldpath);
4212 if (IS_ERR(sl->oldpath))
4213 return PTR_ERR(sl->oldpath);
4214
4215 sl->newpath = getname(newpath);
4216 if (IS_ERR(sl->newpath)) {
4217 putname(sl->oldpath);
4218 return PTR_ERR(sl->newpath);
4219 }
4220
4221 req->flags |= REQ_F_NEED_CLEANUP;
4222 return 0;
4223}
4224
04f34081 4225static int io_symlinkat(struct io_kiocb *req, unsigned int issue_flags)
7a8721f8
DK
4226{
4227 struct io_symlink *sl = &req->symlink;
4228 int ret;
4229
4230 if (issue_flags & IO_URING_F_NONBLOCK)
4231 return -EAGAIN;
4232
4233 ret = do_symlinkat(sl->oldpath, sl->new_dfd, sl->newpath);
4234
4235 req->flags &= ~REQ_F_NEED_CLEANUP;
4236 if (ret < 0)
4237 req_set_fail(req);
4238 io_req_complete(req, ret);
4239 return 0;
4240}
4241
cf30da90
DK
4242static int io_linkat_prep(struct io_kiocb *req,
4243 const struct io_uring_sqe *sqe)
4244{
4245 struct io_hardlink *lnk = &req->hardlink;
4246 const char __user *oldf, *newf;
4247
4248 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4249 return -EINVAL;
4250 if (sqe->ioprio || sqe->rw_flags || sqe->buf_index || sqe->splice_fd_in)
4251 return -EINVAL;
4252 if (unlikely(req->flags & REQ_F_FIXED_FILE))
4253 return -EBADF;
4254
4255 lnk->old_dfd = READ_ONCE(sqe->fd);
4256 lnk->new_dfd = READ_ONCE(sqe->len);
4257 oldf = u64_to_user_ptr(READ_ONCE(sqe->addr));
4258 newf = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4259 lnk->flags = READ_ONCE(sqe->hardlink_flags);
4260
4261 lnk->oldpath = getname(oldf);
4262 if (IS_ERR(lnk->oldpath))
4263 return PTR_ERR(lnk->oldpath);
4264
4265 lnk->newpath = getname(newf);
4266 if (IS_ERR(lnk->newpath)) {
4267 putname(lnk->oldpath);
4268 return PTR_ERR(lnk->newpath);
4269 }
4270
4271 req->flags |= REQ_F_NEED_CLEANUP;
4272 return 0;
4273}
4274
04f34081 4275static int io_linkat(struct io_kiocb *req, unsigned int issue_flags)
cf30da90
DK
4276{
4277 struct io_hardlink *lnk = &req->hardlink;
4278 int ret;
4279
4280 if (issue_flags & IO_URING_F_NONBLOCK)
4281 return -EAGAIN;
4282
4283 ret = do_linkat(lnk->old_dfd, lnk->oldpath, lnk->new_dfd,
4284 lnk->newpath, lnk->flags);
4285
4286 req->flags &= ~REQ_F_NEED_CLEANUP;
4287 if (ret < 0)
4288 req_set_fail(req);
4289 io_req_complete(req, ret);
4290 return 0;
4291}
4292
36f4fa68
JA
4293static int io_shutdown_prep(struct io_kiocb *req,
4294 const struct io_uring_sqe *sqe)
4295{
4296#if defined(CONFIG_NET)
4297 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4298 return -EINVAL;
26578cda
PB
4299 if (unlikely(sqe->ioprio || sqe->off || sqe->addr || sqe->rw_flags ||
4300 sqe->buf_index || sqe->splice_fd_in))
36f4fa68
JA
4301 return -EINVAL;
4302
4303 req->shutdown.how = READ_ONCE(sqe->len);
4304 return 0;
4305#else
4306 return -EOPNOTSUPP;
4307#endif
4308}
4309
45d189c6 4310static int io_shutdown(struct io_kiocb *req, unsigned int issue_flags)
36f4fa68
JA
4311{
4312#if defined(CONFIG_NET)
4313 struct socket *sock;
4314 int ret;
4315
45d189c6 4316 if (issue_flags & IO_URING_F_NONBLOCK)
36f4fa68
JA
4317 return -EAGAIN;
4318
48aba79b 4319 sock = sock_from_file(req->file);
36f4fa68 4320 if (unlikely(!sock))
48aba79b 4321 return -ENOTSOCK;
36f4fa68
JA
4322
4323 ret = __sys_shutdown_sock(sock, req->shutdown.how);
a146468d 4324 if (ret < 0)
93d2bcd2 4325 req_set_fail(req);
36f4fa68
JA
4326 io_req_complete(req, ret);
4327 return 0;
4328#else
4329 return -EOPNOTSUPP;
4330#endif
4331}
4332
f2a8d5c7
PB
4333static int __io_splice_prep(struct io_kiocb *req,
4334 const struct io_uring_sqe *sqe)
7d67af2c 4335{
fe7e3257 4336 struct io_splice *sp = &req->splice;
7d67af2c 4337 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
7d67af2c 4338
3232dd02
PB
4339 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4340 return -EINVAL;
7d67af2c
PB
4341
4342 sp->file_in = NULL;
7d67af2c
PB
4343 sp->len = READ_ONCE(sqe->len);
4344 sp->flags = READ_ONCE(sqe->splice_flags);
4345
4346 if (unlikely(sp->flags & ~valid_flags))
4347 return -EINVAL;
4348
62906e89 4349 sp->file_in = io_file_get(req->ctx, req, READ_ONCE(sqe->splice_fd_in),
8371adf5
PB
4350 (sp->flags & SPLICE_F_FD_IN_FIXED));
4351 if (!sp->file_in)
4352 return -EBADF;
7d67af2c 4353 req->flags |= REQ_F_NEED_CLEANUP;
7d67af2c
PB
4354 return 0;
4355}
4356
f2a8d5c7
PB
4357static int io_tee_prep(struct io_kiocb *req,
4358 const struct io_uring_sqe *sqe)
4359{
4360 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
4361 return -EINVAL;
4362 return __io_splice_prep(req, sqe);
4363}
4364
45d189c6 4365static int io_tee(struct io_kiocb *req, unsigned int issue_flags)
f2a8d5c7
PB
4366{
4367 struct io_splice *sp = &req->splice;
4368 struct file *in = sp->file_in;
4369 struct file *out = sp->file_out;
4370 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4371 long ret = 0;
4372
45d189c6 4373 if (issue_flags & IO_URING_F_NONBLOCK)
f2a8d5c7
PB
4374 return -EAGAIN;
4375 if (sp->len)
4376 ret = do_tee(in, out, sp->len, flags);
4377
e1d767f0
PB
4378 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4379 io_put_file(in);
f2a8d5c7
PB
4380 req->flags &= ~REQ_F_NEED_CLEANUP;
4381
f2a8d5c7 4382 if (ret != sp->len)
93d2bcd2 4383 req_set_fail(req);
e1e16097 4384 io_req_complete(req, ret);
f2a8d5c7
PB
4385 return 0;
4386}
4387
4388static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4389{
fe7e3257 4390 struct io_splice *sp = &req->splice;
f2a8d5c7
PB
4391
4392 sp->off_in = READ_ONCE(sqe->splice_off_in);
4393 sp->off_out = READ_ONCE(sqe->off);
4394 return __io_splice_prep(req, sqe);
4395}
4396
45d189c6 4397static int io_splice(struct io_kiocb *req, unsigned int issue_flags)
7d67af2c
PB
4398{
4399 struct io_splice *sp = &req->splice;
4400 struct file *in = sp->file_in;
4401 struct file *out = sp->file_out;
4402 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
4403 loff_t *poff_in, *poff_out;
c9687426 4404 long ret = 0;
7d67af2c 4405
45d189c6 4406 if (issue_flags & IO_URING_F_NONBLOCK)
2fb3e822 4407 return -EAGAIN;
7d67af2c
PB
4408
4409 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
4410 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
c9687426 4411
948a7749 4412 if (sp->len)
c9687426 4413 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
7d67af2c 4414
e1d767f0
PB
4415 if (!(sp->flags & SPLICE_F_FD_IN_FIXED))
4416 io_put_file(in);
7d67af2c
PB
4417 req->flags &= ~REQ_F_NEED_CLEANUP;
4418
7d67af2c 4419 if (ret != sp->len)
93d2bcd2 4420 req_set_fail(req);
e1e16097 4421 io_req_complete(req, ret);
7d67af2c
PB
4422 return 0;
4423}
4424
2b188cc1
JA
4425/*
4426 * IORING_OP_NOP just posts a completion event, nothing else.
4427 */
889fca73 4428static int io_nop(struct io_kiocb *req, unsigned int issue_flags)
2b188cc1
JA
4429{
4430 struct io_ring_ctx *ctx = req->ctx;
2b188cc1 4431
def596e9
JA
4432 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
4433 return -EINVAL;
4434
889fca73 4435 __io_req_complete(req, issue_flags, 0, 0);
2b188cc1
JA
4436 return 0;
4437}
4438
4f57f06c
JA
4439static int io_msg_ring_prep(struct io_kiocb *req,
4440 const struct io_uring_sqe *sqe)
4441{
f3b6a41e
JA
4442 if (unlikely(sqe->addr || sqe->ioprio || sqe->rw_flags ||
4443 sqe->splice_fd_in || sqe->buf_index || sqe->personality))
4f57f06c
JA
4444 return -EINVAL;
4445
4446 if (req->file->f_op != &io_uring_fops)
4447 return -EBADFD;
4448
4449 req->msg.user_data = READ_ONCE(sqe->off);
4450 req->msg.len = READ_ONCE(sqe->len);
4451 return 0;
4452}
4453
4454static int io_msg_ring(struct io_kiocb *req, unsigned int issue_flags)
4455{
4456 struct io_ring_ctx *target_ctx;
4457 struct io_msg *msg = &req->msg;
4458 int ret = -EOVERFLOW;
4459 bool filled;
4460
4461 target_ctx = req->file->private_data;
4462
4463 spin_lock(&target_ctx->completion_lock);
4464 filled = io_fill_cqe_aux(target_ctx, msg->user_data, msg->len,
4465 IORING_CQE_F_MSG);
4466 io_commit_cqring(target_ctx);
4467 spin_unlock(&target_ctx->completion_lock);
4468
4469 if (filled) {
4470 io_cqring_ev_posted(target_ctx);
4471 ret = 0;
4472 }
4473
4474 __io_req_complete(req, issue_flags, ret, 0);
4475 return 0;
4476}
4477
1155c76a 4478static int io_fsync_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
c992fe29 4479{
6b06314c 4480 struct io_ring_ctx *ctx = req->ctx;
c992fe29 4481
09bb8394
JA
4482 if (!req->file)
4483 return -EBADF;
c992fe29 4484
6b06314c 4485 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
def596e9 4486 return -EINVAL;
26578cda
PB
4487 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
4488 sqe->splice_fd_in))
c992fe29
CH
4489 return -EINVAL;
4490
8ed8d3c3
JA
4491 req->sync.flags = READ_ONCE(sqe->fsync_flags);
4492 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
4493 return -EINVAL;
4494
4495 req->sync.off = READ_ONCE(sqe->off);
4496 req->sync.len = READ_ONCE(sqe->len);
c992fe29
CH
4497 return 0;
4498}
4499
45d189c6 4500static int io_fsync(struct io_kiocb *req, unsigned int issue_flags)
8ed8d3c3 4501{
8ed8d3c3 4502 loff_t end = req->sync.off + req->sync.len;
8ed8d3c3
JA
4503 int ret;
4504
ac45abc0 4505 /* fsync always requires a blocking context */
45d189c6 4506 if (issue_flags & IO_URING_F_NONBLOCK)
ac45abc0
PB
4507 return -EAGAIN;
4508
9adbd45d 4509 ret = vfs_fsync_range(req->file, req->sync.off,
8ed8d3c3
JA
4510 end > 0 ? end : LLONG_MAX,
4511 req->sync.flags & IORING_FSYNC_DATASYNC);
4512 if (ret < 0)
93d2bcd2 4513 req_set_fail(req);
e1e16097 4514 io_req_complete(req, ret);
c992fe29
CH
4515 return 0;
4516}
4517
d63d1b5e
JA
4518static int io_fallocate_prep(struct io_kiocb *req,
4519 const struct io_uring_sqe *sqe)
4520{
26578cda
PB
4521 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags ||
4522 sqe->splice_fd_in)
d63d1b5e 4523 return -EINVAL;
3232dd02
PB
4524 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4525 return -EINVAL;
d63d1b5e
JA
4526
4527 req->sync.off = READ_ONCE(sqe->off);
4528 req->sync.len = READ_ONCE(sqe->addr);
4529 req->sync.mode = READ_ONCE(sqe->len);
4530 return 0;
4531}
4532
45d189c6 4533static int io_fallocate(struct io_kiocb *req, unsigned int issue_flags)
5d17b4a4 4534{
ac45abc0
PB
4535 int ret;
4536
d63d1b5e 4537 /* fallocate always requiring blocking context */
45d189c6 4538 if (issue_flags & IO_URING_F_NONBLOCK)
5d17b4a4 4539 return -EAGAIN;
ac45abc0
PB
4540 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
4541 req->sync.len);
ac45abc0 4542 if (ret < 0)
93d2bcd2 4543 req_set_fail(req);
f63cf519
JA
4544 else
4545 fsnotify_modify(req->file);
e1e16097 4546 io_req_complete(req, ret);
5d17b4a4
JA
4547 return 0;
4548}
4549
ec65fea5 4550static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
b7bb4f7d 4551{
f8748881 4552 const char __user *fname;
15b71abe 4553 int ret;
b7bb4f7d 4554
d3fddf6d
PB
4555 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4556 return -EINVAL;
b9445598 4557 if (unlikely(sqe->ioprio || sqe->buf_index))
15b71abe 4558 return -EINVAL;
ec65fea5 4559 if (unlikely(req->flags & REQ_F_FIXED_FILE))
cf3040ca 4560 return -EBADF;
03b1230c 4561
ec65fea5
PB
4562 /* open.how should be already initialised */
4563 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
08a1d26e 4564 req->open.how.flags |= O_LARGEFILE;
3529d8c2 4565
25e72d10
PB
4566 req->open.dfd = READ_ONCE(sqe->fd);
4567 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
f8748881 4568 req->open.filename = getname(fname);
15b71abe
JA
4569 if (IS_ERR(req->open.filename)) {
4570 ret = PTR_ERR(req->open.filename);
4571 req->open.filename = NULL;
4572 return ret;
4573 }
b9445598
PB
4574
4575 req->open.file_slot = READ_ONCE(sqe->file_index);
4576 if (req->open.file_slot && (req->open.how.flags & O_CLOEXEC))
4577 return -EINVAL;
4578
4022e7af 4579 req->open.nofile = rlimit(RLIMIT_NOFILE);
8fef80bf 4580 req->flags |= REQ_F_NEED_CLEANUP;
15b71abe 4581 return 0;
03b1230c
JA
4582}
4583
ec65fea5
PB
4584static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4585{
d3fddf6d
PB
4586 u64 mode = READ_ONCE(sqe->len);
4587 u64 flags = READ_ONCE(sqe->open_flags);
ec65fea5 4588
ec65fea5
PB
4589 req->open.how = build_open_how(flags, mode);
4590 return __io_openat_prep(req, sqe);
4591}
4592
cebdb986 4593static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
aa1fa28f 4594{
cebdb986 4595 struct open_how __user *how;
cebdb986 4596 size_t len;
0fa03c62
JA
4597 int ret;
4598
cebdb986
JA
4599 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4600 len = READ_ONCE(sqe->len);
cebdb986
JA
4601 if (len < OPEN_HOW_SIZE_VER0)
4602 return -EINVAL;
3529d8c2 4603
cebdb986
JA
4604 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
4605 len);
4606 if (ret)
4607 return ret;
3529d8c2 4608
ec65fea5 4609 return __io_openat_prep(req, sqe);
cebdb986
JA
4610}
4611
45d189c6 4612static int io_openat2(struct io_kiocb *req, unsigned int issue_flags)
15b71abe
JA
4613{
4614 struct open_flags op;
15b71abe 4615 struct file *file;
b9445598
PB
4616 bool resolve_nonblock, nonblock_set;
4617 bool fixed = !!req->open.file_slot;
15b71abe
JA
4618 int ret;
4619
cebdb986 4620 ret = build_open_flags(&req->open.how, &op);
15b71abe
JA
4621 if (ret)
4622 goto err;
3a81fd02
JA
4623 nonblock_set = op.open_flag & O_NONBLOCK;
4624 resolve_nonblock = req->open.how.resolve & RESOLVE_CACHED;
45d189c6 4625 if (issue_flags & IO_URING_F_NONBLOCK) {
3a81fd02
JA
4626 /*
4627 * Don't bother trying for O_TRUNC, O_CREAT, or O_TMPFILE open,
4628 * it'll always -EAGAIN
4629 */
4630 if (req->open.how.flags & (O_TRUNC | O_CREAT | O_TMPFILE))
4631 return -EAGAIN;
4632 op.lookup_flags |= LOOKUP_CACHED;
4633 op.open_flag |= O_NONBLOCK;
4634 }
15b71abe 4635
b9445598
PB
4636 if (!fixed) {
4637 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
4638 if (ret < 0)
4639 goto err;
4640 }
15b71abe
JA
4641
4642 file = do_filp_open(req->open.dfd, req->open.filename, &op);
12dcb58a 4643 if (IS_ERR(file)) {
944d1444 4644 /*
12dcb58a
PB
4645 * We could hang on to this 'fd' on retrying, but seems like
4646 * marginal gain for something that is now known to be a slower
4647 * path. So just put it, and we'll get a new one when we retry.
944d1444 4648 */
b9445598
PB
4649 if (!fixed)
4650 put_unused_fd(ret);
3a81fd02 4651
15b71abe 4652 ret = PTR_ERR(file);
12dcb58a
PB
4653 /* only retry if RESOLVE_CACHED wasn't already set by application */
4654 if (ret == -EAGAIN &&
4655 (!resolve_nonblock && (issue_flags & IO_URING_F_NONBLOCK)))
4656 return -EAGAIN;
4657 goto err;
15b71abe 4658 }
12dcb58a
PB
4659
4660 if ((issue_flags & IO_URING_F_NONBLOCK) && !nonblock_set)
4661 file->f_flags &= ~O_NONBLOCK;
4662 fsnotify_open(file);
b9445598
PB
4663
4664 if (!fixed)
4665 fd_install(ret, file);
4666 else
4667 ret = io_install_fixed_file(req, file, issue_flags,
4668 req->open.file_slot - 1);
15b71abe
JA
4669err:
4670 putname(req->open.filename);
8fef80bf 4671 req->flags &= ~REQ_F_NEED_CLEANUP;
15b71abe 4672 if (ret < 0)
93d2bcd2 4673 req_set_fail(req);
0bdf3398 4674 __io_req_complete(req, issue_flags, ret, 0);
15b71abe
JA
4675 return 0;
4676}
4677
45d189c6 4678static int io_openat(struct io_kiocb *req, unsigned int issue_flags)
cebdb986 4679{
e45cff58 4680 return io_openat2(req, issue_flags);
cebdb986
JA
4681}
4682
067524e9
JA
4683static int io_remove_buffers_prep(struct io_kiocb *req,
4684 const struct io_uring_sqe *sqe)
4685{
4686 struct io_provide_buf *p = &req->pbuf;
4687 u64 tmp;
4688
26578cda
PB
4689 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off ||
4690 sqe->splice_fd_in)
067524e9
JA
4691 return -EINVAL;
4692
4693 tmp = READ_ONCE(sqe->fd);
4694 if (!tmp || tmp > USHRT_MAX)
4695 return -EINVAL;
4696
4697 memset(p, 0, sizeof(*p));
4698 p->nbufs = tmp;
4699 p->bgid = READ_ONCE(sqe->buf_group);
4700 return 0;
4701}
4702
dbc7d452
JA
4703static int __io_remove_buffers(struct io_ring_ctx *ctx,
4704 struct io_buffer_list *bl, unsigned nbufs)
067524e9
JA
4705{
4706 unsigned i = 0;
4707
4708 /* shouldn't happen */
4709 if (!nbufs)
4710 return 0;
4711
4712 /* the head kbuf is the list itself */
dbc7d452 4713 while (!list_empty(&bl->buf_list)) {
067524e9
JA
4714 struct io_buffer *nxt;
4715
dbc7d452 4716 nxt = list_first_entry(&bl->buf_list, struct io_buffer, list);
067524e9 4717 list_del(&nxt->list);
067524e9
JA
4718 if (++i == nbufs)
4719 return i;
1d0254e6 4720 cond_resched();
067524e9
JA
4721 }
4722 i++;
067524e9
JA
4723
4724 return i;
4725}
4726
889fca73 4727static int io_remove_buffers(struct io_kiocb *req, unsigned int issue_flags)
067524e9
JA
4728{
4729 struct io_provide_buf *p = &req->pbuf;
4730 struct io_ring_ctx *ctx = req->ctx;
dbc7d452 4731 struct io_buffer_list *bl;
067524e9 4732 int ret = 0;
3b44b371 4733 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
067524e9 4734
3b44b371 4735 io_ring_submit_lock(ctx, needs_lock);
067524e9
JA
4736
4737 lockdep_assert_held(&ctx->uring_lock);
4738
4739 ret = -ENOENT;
dbc7d452
JA
4740 bl = io_buffer_get_list(ctx, p->bgid);
4741 if (bl)
4742 ret = __io_remove_buffers(ctx, bl, p->nbufs);
067524e9 4743 if (ret < 0)
93d2bcd2 4744 req_set_fail(req);
067524e9 4745
9fb8cb49
PB
4746 /* complete before unlock, IOPOLL may need the lock */
4747 __io_req_complete(req, issue_flags, ret, 0);
3b44b371 4748 io_ring_submit_unlock(ctx, needs_lock);
067524e9
JA
4749 return 0;
4750}
4751
ddf0322d
JA
4752static int io_provide_buffers_prep(struct io_kiocb *req,
4753 const struct io_uring_sqe *sqe)
4754{
38134ada 4755 unsigned long size, tmp_check;
ddf0322d
JA
4756 struct io_provide_buf *p = &req->pbuf;
4757 u64 tmp;
4758
26578cda 4759 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
ddf0322d
JA
4760 return -EINVAL;
4761
4762 tmp = READ_ONCE(sqe->fd);
4763 if (!tmp || tmp > USHRT_MAX)
4764 return -E2BIG;
4765 p->nbufs = tmp;
4766 p->addr = READ_ONCE(sqe->addr);
4767 p->len = READ_ONCE(sqe->len);
4768
38134ada
PB
4769 if (check_mul_overflow((unsigned long)p->len, (unsigned long)p->nbufs,
4770 &size))
4771 return -EOVERFLOW;
4772 if (check_add_overflow((unsigned long)p->addr, size, &tmp_check))
4773 return -EOVERFLOW;
4774
d81269fe
PB
4775 size = (unsigned long)p->len * p->nbufs;
4776 if (!access_ok(u64_to_user_ptr(p->addr), size))
ddf0322d
JA
4777 return -EFAULT;
4778
4779 p->bgid = READ_ONCE(sqe->buf_group);
4780 tmp = READ_ONCE(sqe->off);
4781 if (tmp > USHRT_MAX)
4782 return -E2BIG;
4783 p->bid = tmp;
4784 return 0;
4785}
4786
cc3cec83
JA
4787static int io_refill_buffer_cache(struct io_ring_ctx *ctx)
4788{
4789 struct io_buffer *buf;
4790 struct page *page;
4791 int bufs_in_page;
4792
4793 /*
4794 * Completions that don't happen inline (eg not under uring_lock) will
4795 * add to ->io_buffers_comp. If we don't have any free buffers, check
4796 * the completion list and splice those entries first.
4797 */
4798 if (!list_empty_careful(&ctx->io_buffers_comp)) {
4799 spin_lock(&ctx->completion_lock);
4800 if (!list_empty(&ctx->io_buffers_comp)) {
4801 list_splice_init(&ctx->io_buffers_comp,
4802 &ctx->io_buffers_cache);
4803 spin_unlock(&ctx->completion_lock);
4804 return 0;
4805 }
4806 spin_unlock(&ctx->completion_lock);
4807 }
4808
4809 /*
4810 * No free buffers and no completion entries either. Allocate a new
4811 * page worth of buffer entries and add those to our freelist.
4812 */
4813 page = alloc_page(GFP_KERNEL_ACCOUNT);
4814 if (!page)
4815 return -ENOMEM;
4816
4817 list_add(&page->lru, &ctx->io_buffers_pages);
4818
4819 buf = page_address(page);
4820 bufs_in_page = PAGE_SIZE / sizeof(*buf);
4821 while (bufs_in_page) {
4822 list_add_tail(&buf->list, &ctx->io_buffers_cache);
4823 buf++;
4824 bufs_in_page--;
4825 }
4826
4827 return 0;
4828}
4829
4830static int io_add_buffers(struct io_ring_ctx *ctx, struct io_provide_buf *pbuf,
dbc7d452 4831 struct io_buffer_list *bl)
ddf0322d
JA
4832{
4833 struct io_buffer *buf;
4834 u64 addr = pbuf->addr;
4835 int i, bid = pbuf->bid;
4836
4837 for (i = 0; i < pbuf->nbufs; i++) {
cc3cec83
JA
4838 if (list_empty(&ctx->io_buffers_cache) &&
4839 io_refill_buffer_cache(ctx))
ddf0322d 4840 break;
cc3cec83
JA
4841 buf = list_first_entry(&ctx->io_buffers_cache, struct io_buffer,
4842 list);
dbc7d452 4843 list_move_tail(&buf->list, &bl->buf_list);
ddf0322d 4844 buf->addr = addr;
d1f82808 4845 buf->len = min_t(__u32, pbuf->len, MAX_RW_COUNT);
ddf0322d 4846 buf->bid = bid;
b1c62645 4847 buf->bgid = pbuf->bgid;
ddf0322d
JA
4848 addr += pbuf->len;
4849 bid++;
f240762f 4850 cond_resched();
ddf0322d
JA
4851 }
4852
dbc7d452 4853 return i ? 0 : -ENOMEM;
ddf0322d
JA
4854}
4855
889fca73 4856static int io_provide_buffers(struct io_kiocb *req, unsigned int issue_flags)
ddf0322d
JA
4857{
4858 struct io_provide_buf *p = &req->pbuf;
4859 struct io_ring_ctx *ctx = req->ctx;
dbc7d452 4860 struct io_buffer_list *bl;
ddf0322d 4861 int ret = 0;
3b44b371 4862 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
ddf0322d 4863
3b44b371 4864 io_ring_submit_lock(ctx, needs_lock);
ddf0322d
JA
4865
4866 lockdep_assert_held(&ctx->uring_lock);
4867
dbc7d452
JA
4868 bl = io_buffer_get_list(ctx, p->bgid);
4869 if (unlikely(!bl)) {
4870 bl = kmalloc(sizeof(*bl), GFP_KERNEL);
4871 if (!bl) {
4872 ret = -ENOMEM;
4873 goto err;
4874 }
4875 io_buffer_add_list(ctx, bl, p->bgid);
ddf0322d 4876 }
dbc7d452
JA
4877
4878 ret = io_add_buffers(ctx, p, bl);
4879err:
ddf0322d 4880 if (ret < 0)
93d2bcd2 4881 req_set_fail(req);
9fb8cb49
PB
4882 /* complete before unlock, IOPOLL may need the lock */
4883 __io_req_complete(req, issue_flags, ret, 0);
3b44b371 4884 io_ring_submit_unlock(ctx, needs_lock);
ddf0322d 4885 return 0;
cebdb986
JA
4886}
4887
3e4827b0
JA
4888static int io_epoll_ctl_prep(struct io_kiocb *req,
4889 const struct io_uring_sqe *sqe)
4890{
4891#if defined(CONFIG_EPOLL)
26578cda 4892 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
3e4827b0 4893 return -EINVAL;
2d74d042 4894 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3232dd02 4895 return -EINVAL;
3e4827b0
JA
4896
4897 req->epoll.epfd = READ_ONCE(sqe->fd);
4898 req->epoll.op = READ_ONCE(sqe->len);
4899 req->epoll.fd = READ_ONCE(sqe->off);
4900
4901 if (ep_op_has_event(req->epoll.op)) {
4902 struct epoll_event __user *ev;
4903
4904 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
4905 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
4906 return -EFAULT;
4907 }
4908
4909 return 0;
4910#else
4911 return -EOPNOTSUPP;
4912#endif
4913}
4914
889fca73 4915static int io_epoll_ctl(struct io_kiocb *req, unsigned int issue_flags)
3e4827b0
JA
4916{
4917#if defined(CONFIG_EPOLL)
4918 struct io_epoll *ie = &req->epoll;
4919 int ret;
45d189c6 4920 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
3e4827b0
JA
4921
4922 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
4923 if (force_nonblock && ret == -EAGAIN)
4924 return -EAGAIN;
4925
4926 if (ret < 0)
93d2bcd2 4927 req_set_fail(req);
889fca73 4928 __io_req_complete(req, issue_flags, ret, 0);
3e4827b0
JA
4929 return 0;
4930#else
4931 return -EOPNOTSUPP;
4932#endif
4933}
4934
c1ca757b
JA
4935static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4936{
4937#if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
26578cda 4938 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->splice_fd_in)
c1ca757b 4939 return -EINVAL;
3232dd02
PB
4940 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4941 return -EINVAL;
c1ca757b
JA
4942
4943 req->madvise.addr = READ_ONCE(sqe->addr);
4944 req->madvise.len = READ_ONCE(sqe->len);
4945 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
4946 return 0;
4947#else
4948 return -EOPNOTSUPP;
4949#endif
4950}
4951
45d189c6 4952static int io_madvise(struct io_kiocb *req, unsigned int issue_flags)
c1ca757b
JA
4953{
4954#if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
4955 struct io_madvise *ma = &req->madvise;
4956 int ret;
4957
45d189c6 4958 if (issue_flags & IO_URING_F_NONBLOCK)
c1ca757b
JA
4959 return -EAGAIN;
4960
0726b01e 4961 ret = do_madvise(current->mm, ma->addr, ma->len, ma->advice);
c1ca757b 4962 if (ret < 0)
93d2bcd2 4963 req_set_fail(req);
e1e16097 4964 io_req_complete(req, ret);
c1ca757b
JA
4965 return 0;
4966#else
4967 return -EOPNOTSUPP;
4968#endif
4969}
4970
4840e418
JA
4971static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4972{
26578cda 4973 if (sqe->ioprio || sqe->buf_index || sqe->addr || sqe->splice_fd_in)
4840e418 4974 return -EINVAL;
3232dd02
PB
4975 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4976 return -EINVAL;
4840e418
JA
4977
4978 req->fadvise.offset = READ_ONCE(sqe->off);
4979 req->fadvise.len = READ_ONCE(sqe->len);
4980 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
4981 return 0;
4982}
4983
45d189c6 4984static int io_fadvise(struct io_kiocb *req, unsigned int issue_flags)
4840e418
JA
4985{
4986 struct io_fadvise *fa = &req->fadvise;
4987 int ret;
4988
45d189c6 4989 if (issue_flags & IO_URING_F_NONBLOCK) {
3e69426d
JA
4990 switch (fa->advice) {
4991 case POSIX_FADV_NORMAL:
4992 case POSIX_FADV_RANDOM:
4993 case POSIX_FADV_SEQUENTIAL:
4994 break;
4995 default:
4996 return -EAGAIN;
4997 }
4998 }
4840e418
JA
4999
5000 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
5001 if (ret < 0)
93d2bcd2 5002 req_set_fail(req);
0bdf3398 5003 __io_req_complete(req, issue_flags, ret, 0);
4840e418
JA
5004 return 0;
5005}
5006
eddc7ef5
JA
5007static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5008{
2d74d042 5009 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3232dd02 5010 return -EINVAL;
26578cda 5011 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
eddc7ef5 5012 return -EINVAL;
9c280f90 5013 if (req->flags & REQ_F_FIXED_FILE)
cf3040ca 5014 return -EBADF;
eddc7ef5 5015
1d9e1288
BM
5016 req->statx.dfd = READ_ONCE(sqe->fd);
5017 req->statx.mask = READ_ONCE(sqe->len);
e62753e4 5018 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
1d9e1288
BM
5019 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
5020 req->statx.flags = READ_ONCE(sqe->statx_flags);
eddc7ef5
JA
5021
5022 return 0;
5023}
5024
45d189c6 5025static int io_statx(struct io_kiocb *req, unsigned int issue_flags)
eddc7ef5 5026{
1d9e1288 5027 struct io_statx *ctx = &req->statx;
eddc7ef5
JA
5028 int ret;
5029
59d70013 5030 if (issue_flags & IO_URING_F_NONBLOCK)
eddc7ef5
JA
5031 return -EAGAIN;
5032
e62753e4
BM
5033 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
5034 ctx->buffer);
eddc7ef5 5035
eddc7ef5 5036 if (ret < 0)
93d2bcd2 5037 req_set_fail(req);
e1e16097 5038 io_req_complete(req, ret);
eddc7ef5
JA
5039 return 0;
5040}
5041
b5dba59e
JA
5042static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5043{
14587a46 5044 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3232dd02 5045 return -EINVAL;
b5dba59e 5046 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
7df778be 5047 sqe->rw_flags || sqe->buf_index)
b5dba59e 5048 return -EINVAL;
9c280f90 5049 if (req->flags & REQ_F_FIXED_FILE)
cf3040ca 5050 return -EBADF;
b5dba59e
JA
5051
5052 req->close.fd = READ_ONCE(sqe->fd);
7df778be
PB
5053 req->close.file_slot = READ_ONCE(sqe->file_index);
5054 if (req->close.file_slot && req->close.fd)
5055 return -EINVAL;
5056
b5dba59e 5057 return 0;
b5dba59e
JA
5058}
5059
889fca73 5060static int io_close(struct io_kiocb *req, unsigned int issue_flags)
b5dba59e 5061{
9eac1904 5062 struct files_struct *files = current->files;
3af73b28 5063 struct io_close *close = &req->close;
9eac1904 5064 struct fdtable *fdt;
a1fde923
PB
5065 struct file *file = NULL;
5066 int ret = -EBADF;
b5dba59e 5067
7df778be
PB
5068 if (req->close.file_slot) {
5069 ret = io_close_fixed(req, issue_flags);
5070 goto err;
5071 }
5072
9eac1904
JA
5073 spin_lock(&files->file_lock);
5074 fdt = files_fdtable(files);
5075 if (close->fd >= fdt->max_fds) {
5076 spin_unlock(&files->file_lock);
5077 goto err;
5078 }
5079 file = fdt->fd[close->fd];
a1fde923 5080 if (!file || file->f_op == &io_uring_fops) {
9eac1904
JA
5081 spin_unlock(&files->file_lock);
5082 file = NULL;
5083 goto err;
3af73b28 5084 }
b5dba59e
JA
5085
5086 /* if the file has a flush method, be safe and punt to async */
45d189c6 5087 if (file->f_op->flush && (issue_flags & IO_URING_F_NONBLOCK)) {
9eac1904 5088 spin_unlock(&files->file_lock);
0bf0eefd 5089 return -EAGAIN;
a2100672 5090 }
b5dba59e 5091
9eac1904
JA
5092 ret = __close_fd_get_file(close->fd, &file);
5093 spin_unlock(&files->file_lock);
5094 if (ret < 0) {
5095 if (ret == -ENOENT)
5096 ret = -EBADF;
5097 goto err;
5098 }
5099
3af73b28 5100 /* No ->flush() or already async, safely close from here */
9eac1904
JA
5101 ret = filp_close(file, current->files);
5102err:
3af73b28 5103 if (ret < 0)
93d2bcd2 5104 req_set_fail(req);
9eac1904
JA
5105 if (file)
5106 fput(file);
889fca73 5107 __io_req_complete(req, issue_flags, ret, 0);
1a417f4e 5108 return 0;
b5dba59e
JA
5109}
5110
1155c76a 5111static int io_sfr_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5d17b4a4
JA
5112{
5113 struct io_ring_ctx *ctx = req->ctx;
5d17b4a4 5114
5d17b4a4
JA
5115 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
5116 return -EINVAL;
26578cda
PB
5117 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index ||
5118 sqe->splice_fd_in))
5d17b4a4
JA
5119 return -EINVAL;
5120
8ed8d3c3
JA
5121 req->sync.off = READ_ONCE(sqe->off);
5122 req->sync.len = READ_ONCE(sqe->len);
5123 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
8ed8d3c3
JA
5124 return 0;
5125}
5126
45d189c6 5127static int io_sync_file_range(struct io_kiocb *req, unsigned int issue_flags)
8ed8d3c3 5128{
8ed8d3c3
JA
5129 int ret;
5130
ac45abc0 5131 /* sync_file_range always requires a blocking context */
45d189c6 5132 if (issue_flags & IO_URING_F_NONBLOCK)
ac45abc0
PB
5133 return -EAGAIN;
5134
9adbd45d 5135 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
8ed8d3c3
JA
5136 req->sync.flags);
5137 if (ret < 0)
93d2bcd2 5138 req_set_fail(req);
e1e16097 5139 io_req_complete(req, ret);
5d17b4a4
JA
5140 return 0;
5141}
5142
469956e8 5143#if defined(CONFIG_NET)
02d27d89
PB
5144static int io_setup_async_msg(struct io_kiocb *req,
5145 struct io_async_msghdr *kmsg)
5146{
e8c2bc1f
JA
5147 struct io_async_msghdr *async_msg = req->async_data;
5148
5149 if (async_msg)
02d27d89 5150 return -EAGAIN;
e8c2bc1f 5151 if (io_alloc_async_data(req)) {
257e84a5 5152 kfree(kmsg->free_iov);
02d27d89
PB
5153 return -ENOMEM;
5154 }
e8c2bc1f 5155 async_msg = req->async_data;
02d27d89 5156 req->flags |= REQ_F_NEED_CLEANUP;
e8c2bc1f 5157 memcpy(async_msg, kmsg, sizeof(*kmsg));
2a780802 5158 async_msg->msg.msg_name = &async_msg->addr;
257e84a5
PB
5159 /* if were using fast_iov, set it to the new one */
5160 if (!async_msg->free_iov)
5161 async_msg->msg.msg_iter.iov = async_msg->fast_iov;
5162
02d27d89
PB
5163 return -EAGAIN;
5164}
5165
2ae523ed
PB
5166static int io_sendmsg_copy_hdr(struct io_kiocb *req,
5167 struct io_async_msghdr *iomsg)
5168{
2ae523ed 5169 iomsg->msg.msg_name = &iomsg->addr;
257e84a5 5170 iomsg->free_iov = iomsg->fast_iov;
2ae523ed 5171 return sendmsg_copy_msghdr(&iomsg->msg, req->sr_msg.umsg,
257e84a5 5172 req->sr_msg.msg_flags, &iomsg->free_iov);
2ae523ed
PB
5173}
5174
93642ef8
PB
5175static int io_sendmsg_prep_async(struct io_kiocb *req)
5176{
5177 int ret;
5178
93642ef8
PB
5179 ret = io_sendmsg_copy_hdr(req, req->async_data);
5180 if (!ret)
5181 req->flags |= REQ_F_NEED_CLEANUP;
5182 return ret;
5183}
5184
3529d8c2 5185static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
03b1230c 5186{
e47293fd 5187 struct io_sr_msg *sr = &req->sr_msg;
03b1230c 5188
d2b6f48b
PB
5189 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5190 return -EINVAL;
5191
270a5940 5192 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
fddaface 5193 sr->len = READ_ONCE(sqe->len);
04411806
PB
5194 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5195 if (sr->msg_flags & MSG_DONTWAIT)
5196 req->flags |= REQ_F_NOWAIT;
3529d8c2 5197
d8768362
JA
5198#ifdef CONFIG_COMPAT
5199 if (req->ctx->compat)
5200 sr->msg_flags |= MSG_CMSG_COMPAT;
5201#endif
93642ef8 5202 return 0;
03b1230c
JA
5203}
5204
889fca73 5205static int io_sendmsg(struct io_kiocb *req, unsigned int issue_flags)
aa1fa28f 5206{
6b754c8b 5207 struct io_async_msghdr iomsg, *kmsg;
0fa03c62 5208 struct socket *sock;
7a7cacba 5209 unsigned flags;
0031275d 5210 int min_ret = 0;
0fa03c62
JA
5211 int ret;
5212
dba4a925 5213 sock = sock_from_file(req->file);
7a7cacba 5214 if (unlikely(!sock))
dba4a925 5215 return -ENOTSOCK;
3529d8c2 5216
d886e185
PB
5217 if (req_has_async_data(req)) {
5218 kmsg = req->async_data;
5219 } else {
7a7cacba
PB
5220 ret = io_sendmsg_copy_hdr(req, &iomsg);
5221 if (ret)
5222 return ret;
5223 kmsg = &iomsg;
0fa03c62 5224 }
0fa03c62 5225
04411806
PB
5226 flags = req->sr_msg.msg_flags;
5227 if (issue_flags & IO_URING_F_NONBLOCK)
7a7cacba 5228 flags |= MSG_DONTWAIT;
0031275d
SM
5229 if (flags & MSG_WAITALL)
5230 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5231
7a7cacba 5232 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
0fa03c62 5233
7297ce3d
PB
5234 if (ret < min_ret) {
5235 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5236 return io_setup_async_msg(req, kmsg);
5237 if (ret == -ERESTARTSYS)
5238 ret = -EINTR;
5239 req_set_fail(req);
5240 }
257e84a5
PB
5241 /* fast path, check for non-NULL to avoid function call */
5242 if (kmsg->free_iov)
5243 kfree(kmsg->free_iov);
99bc4c38 5244 req->flags &= ~REQ_F_NEED_CLEANUP;
889fca73 5245 __io_req_complete(req, issue_flags, ret, 0);
5d17b4a4 5246 return 0;
03b1230c 5247}
aa1fa28f 5248
889fca73 5249static int io_send(struct io_kiocb *req, unsigned int issue_flags)
fddaface 5250{
7a7cacba
PB
5251 struct io_sr_msg *sr = &req->sr_msg;
5252 struct msghdr msg;
5253 struct iovec iov;
fddaface 5254 struct socket *sock;
7a7cacba 5255 unsigned flags;
0031275d 5256 int min_ret = 0;
fddaface
JA
5257 int ret;
5258
dba4a925 5259 sock = sock_from_file(req->file);
7a7cacba 5260 if (unlikely(!sock))
dba4a925 5261 return -ENOTSOCK;
fddaface 5262
7a7cacba
PB
5263 ret = import_single_range(WRITE, sr->buf, sr->len, &iov, &msg.msg_iter);
5264 if (unlikely(ret))
14db8411 5265 return ret;
fddaface 5266
7a7cacba
PB
5267 msg.msg_name = NULL;
5268 msg.msg_control = NULL;
5269 msg.msg_controllen = 0;
5270 msg.msg_namelen = 0;
fddaface 5271
04411806
PB
5272 flags = req->sr_msg.msg_flags;
5273 if (issue_flags & IO_URING_F_NONBLOCK)
7a7cacba 5274 flags |= MSG_DONTWAIT;
0031275d
SM
5275 if (flags & MSG_WAITALL)
5276 min_ret = iov_iter_count(&msg.msg_iter);
5277
7a7cacba
PB
5278 msg.msg_flags = flags;
5279 ret = sock_sendmsg(sock, &msg);
7297ce3d
PB
5280 if (ret < min_ret) {
5281 if (ret == -EAGAIN && (issue_flags & IO_URING_F_NONBLOCK))
5282 return -EAGAIN;
5283 if (ret == -ERESTARTSYS)
5284 ret = -EINTR;
93d2bcd2 5285 req_set_fail(req);
7297ce3d 5286 }
889fca73 5287 __io_req_complete(req, issue_flags, ret, 0);
fddaface 5288 return 0;
fddaface
JA
5289}
5290
1400e697
PB
5291static int __io_recvmsg_copy_hdr(struct io_kiocb *req,
5292 struct io_async_msghdr *iomsg)
52de1fe1
JA
5293{
5294 struct io_sr_msg *sr = &req->sr_msg;
5295 struct iovec __user *uiov;
5296 size_t iov_len;
5297 int ret;
5298
1400e697
PB
5299 ret = __copy_msghdr_from_user(&iomsg->msg, sr->umsg,
5300 &iomsg->uaddr, &uiov, &iov_len);
52de1fe1
JA
5301 if (ret)
5302 return ret;
5303
5304 if (req->flags & REQ_F_BUFFER_SELECT) {
5305 if (iov_len > 1)
5306 return -EINVAL;
5476dfed 5307 if (copy_from_user(iomsg->fast_iov, uiov, sizeof(*uiov)))
52de1fe1 5308 return -EFAULT;
5476dfed 5309 sr->len = iomsg->fast_iov[0].iov_len;
257e84a5 5310 iomsg->free_iov = NULL;
52de1fe1 5311 } else {
257e84a5 5312 iomsg->free_iov = iomsg->fast_iov;
89cd35c5 5313 ret = __import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
257e84a5 5314 &iomsg->free_iov, &iomsg->msg.msg_iter,
89cd35c5 5315 false);
52de1fe1
JA
5316 if (ret > 0)
5317 ret = 0;
5318 }
5319
5320 return ret;
5321}
5322
5323#ifdef CONFIG_COMPAT
5324static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
1400e697 5325 struct io_async_msghdr *iomsg)
52de1fe1 5326{
52de1fe1
JA
5327 struct io_sr_msg *sr = &req->sr_msg;
5328 struct compat_iovec __user *uiov;
5329 compat_uptr_t ptr;
5330 compat_size_t len;
5331 int ret;
5332
4af3417a
PB
5333 ret = __get_compat_msghdr(&iomsg->msg, sr->umsg_compat, &iomsg->uaddr,
5334 &ptr, &len);
52de1fe1
JA
5335 if (ret)
5336 return ret;
5337
5338 uiov = compat_ptr(ptr);
5339 if (req->flags & REQ_F_BUFFER_SELECT) {
5340 compat_ssize_t clen;
5341
5342 if (len > 1)
5343 return -EINVAL;
5344 if (!access_ok(uiov, sizeof(*uiov)))
5345 return -EFAULT;
5346 if (__get_user(clen, &uiov->iov_len))
5347 return -EFAULT;
5348 if (clen < 0)
5349 return -EINVAL;
2d280bc8 5350 sr->len = clen;
257e84a5 5351 iomsg->free_iov = NULL;
52de1fe1 5352 } else {
257e84a5 5353 iomsg->free_iov = iomsg->fast_iov;
89cd35c5 5354 ret = __import_iovec(READ, (struct iovec __user *)uiov, len,
257e84a5 5355 UIO_FASTIOV, &iomsg->free_iov,
89cd35c5 5356 &iomsg->msg.msg_iter, true);
52de1fe1
JA
5357 if (ret < 0)
5358 return ret;
5359 }
5360
5361 return 0;
5362}
5363#endif
5364
1400e697
PB
5365static int io_recvmsg_copy_hdr(struct io_kiocb *req,
5366 struct io_async_msghdr *iomsg)
52de1fe1 5367{
1400e697 5368 iomsg->msg.msg_name = &iomsg->addr;
52de1fe1
JA
5369
5370#ifdef CONFIG_COMPAT
5371 if (req->ctx->compat)
1400e697 5372 return __io_compat_recvmsg_copy_hdr(req, iomsg);
fddaface 5373#endif
52de1fe1 5374
1400e697 5375 return __io_recvmsg_copy_hdr(req, iomsg);
52de1fe1
JA
5376}
5377
bcda7baa 5378static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
51aac424 5379 unsigned int issue_flags)
bcda7baa
JA
5380{
5381 struct io_sr_msg *sr = &req->sr_msg;
bcda7baa 5382
51aac424 5383 return io_buffer_select(req, &sr->len, sr->bgid, issue_flags);
fddaface
JA
5384}
5385
93642ef8 5386static int io_recvmsg_prep_async(struct io_kiocb *req)
aa1fa28f 5387{
99bc4c38 5388 int ret;
3529d8c2 5389
93642ef8
PB
5390 ret = io_recvmsg_copy_hdr(req, req->async_data);
5391 if (!ret)
5392 req->flags |= REQ_F_NEED_CLEANUP;
5393 return ret;
5394}
5395
5396static int io_recvmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5397{
5398 struct io_sr_msg *sr = &req->sr_msg;
5399
d2b6f48b
PB
5400 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5401 return -EINVAL;
5402
270a5940 5403 sr->umsg = u64_to_user_ptr(READ_ONCE(sqe->addr));
0b7b21e4 5404 sr->len = READ_ONCE(sqe->len);
bcda7baa 5405 sr->bgid = READ_ONCE(sqe->buf_group);
04411806
PB
5406 sr->msg_flags = READ_ONCE(sqe->msg_flags) | MSG_NOSIGNAL;
5407 if (sr->msg_flags & MSG_DONTWAIT)
5408 req->flags |= REQ_F_NOWAIT;
06b76d44 5409
d8768362
JA
5410#ifdef CONFIG_COMPAT
5411 if (req->ctx->compat)
5412 sr->msg_flags |= MSG_CMSG_COMPAT;
5413#endif
93642ef8 5414 return 0;
aa1fa28f
JA
5415}
5416
889fca73 5417static int io_recvmsg(struct io_kiocb *req, unsigned int issue_flags)
aa1fa28f 5418{
6b754c8b 5419 struct io_async_msghdr iomsg, *kmsg;
03b1230c 5420 struct socket *sock;
7fbb1b54 5421 struct io_buffer *kbuf;
7a7cacba 5422 unsigned flags;
d1fd1c20 5423 int ret, min_ret = 0;
45d189c6 5424 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
03b1230c 5425
dba4a925 5426 sock = sock_from_file(req->file);
7a7cacba 5427 if (unlikely(!sock))
dba4a925 5428 return -ENOTSOCK;
3529d8c2 5429
d886e185
PB
5430 if (req_has_async_data(req)) {
5431 kmsg = req->async_data;
5432 } else {
7a7cacba
PB
5433 ret = io_recvmsg_copy_hdr(req, &iomsg);
5434 if (ret)
681fda8d 5435 return ret;
7a7cacba
PB
5436 kmsg = &iomsg;
5437 }
03b1230c 5438
bc02ef33 5439 if (req->flags & REQ_F_BUFFER_SELECT) {
51aac424 5440 kbuf = io_recv_buffer_select(req, issue_flags);
bc02ef33 5441 if (IS_ERR(kbuf))
52de1fe1 5442 return PTR_ERR(kbuf);
7a7cacba 5443 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
5476dfed
PB
5444 kmsg->fast_iov[0].iov_len = req->sr_msg.len;
5445 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->fast_iov,
7a7cacba
PB
5446 1, req->sr_msg.len);
5447 }
52de1fe1 5448
04411806
PB
5449 flags = req->sr_msg.msg_flags;
5450 if (force_nonblock)
7a7cacba 5451 flags |= MSG_DONTWAIT;
0031275d
SM
5452 if (flags & MSG_WAITALL)
5453 min_ret = iov_iter_count(&kmsg->msg.msg_iter);
5454
7a7cacba
PB
5455 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.umsg,
5456 kmsg->uaddr, flags);
7297ce3d
PB
5457 if (ret < min_ret) {
5458 if (ret == -EAGAIN && force_nonblock)
5459 return io_setup_async_msg(req, kmsg);
5460 if (ret == -ERESTARTSYS)
5461 ret = -EINTR;
5462 req_set_fail(req);
5463 } else if ((flags & MSG_WAITALL) && (kmsg->msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
5464 req_set_fail(req);
5465 }
03b1230c 5466
257e84a5
PB
5467 /* fast path, check for non-NULL to avoid function call */
5468 if (kmsg->free_iov)
5469 kfree(kmsg->free_iov);
99bc4c38 5470 req->flags &= ~REQ_F_NEED_CLEANUP;
cc3cec83 5471 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
03b1230c 5472 return 0;
0fa03c62 5473}
5d17b4a4 5474
889fca73 5475static int io_recv(struct io_kiocb *req, unsigned int issue_flags)
fddaface 5476{
6b754c8b 5477 struct io_buffer *kbuf;
7a7cacba
PB
5478 struct io_sr_msg *sr = &req->sr_msg;
5479 struct msghdr msg;
5480 void __user *buf = sr->buf;
fddaface 5481 struct socket *sock;
7a7cacba
PB
5482 struct iovec iov;
5483 unsigned flags;
d1fd1c20 5484 int ret, min_ret = 0;
45d189c6 5485 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
fddaface 5486
dba4a925 5487 sock = sock_from_file(req->file);
7a7cacba 5488 if (unlikely(!sock))
dba4a925 5489 return -ENOTSOCK;
fddaface 5490
bc02ef33 5491 if (req->flags & REQ_F_BUFFER_SELECT) {
51aac424 5492 kbuf = io_recv_buffer_select(req, issue_flags);
bcda7baa
JA
5493 if (IS_ERR(kbuf))
5494 return PTR_ERR(kbuf);
7a7cacba 5495 buf = u64_to_user_ptr(kbuf->addr);
bc02ef33 5496 }
bcda7baa 5497
7a7cacba 5498 ret = import_single_range(READ, buf, sr->len, &iov, &msg.msg_iter);
14c32eee
PB
5499 if (unlikely(ret))
5500 goto out_free;
fddaface 5501
7a7cacba
PB
5502 msg.msg_name = NULL;
5503 msg.msg_control = NULL;
5504 msg.msg_controllen = 0;
5505 msg.msg_namelen = 0;
5506 msg.msg_iocb = NULL;
5507 msg.msg_flags = 0;
fddaface 5508
04411806
PB
5509 flags = req->sr_msg.msg_flags;
5510 if (force_nonblock)
7a7cacba 5511 flags |= MSG_DONTWAIT;
0031275d
SM
5512 if (flags & MSG_WAITALL)
5513 min_ret = iov_iter_count(&msg.msg_iter);
5514
7a7cacba 5515 ret = sock_recvmsg(sock, &msg, flags);
7297ce3d
PB
5516 if (ret < min_ret) {
5517 if (ret == -EAGAIN && force_nonblock)
5518 return -EAGAIN;
5519 if (ret == -ERESTARTSYS)
5520 ret = -EINTR;
5521 req_set_fail(req);
5522 } else if ((flags & MSG_WAITALL) && (msg.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
0d7c1153 5523out_free:
93d2bcd2 5524 req_set_fail(req);
7297ce3d 5525 }
cc3cec83
JA
5526
5527 __io_req_complete(req, issue_flags, ret, io_put_kbuf(req, issue_flags));
fddaface 5528 return 0;
fddaface
JA
5529}
5530
3529d8c2 5531static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
17f2fe35 5532{
8ed8d3c3
JA
5533 struct io_accept *accept = &req->accept;
5534
14587a46 5535 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
17f2fe35 5536 return -EINVAL;
aaa4db12 5537 if (sqe->ioprio || sqe->len || sqe->buf_index)
17f2fe35
JA
5538 return -EINVAL;
5539
d55e5f5b
JA
5540 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5541 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
8ed8d3c3 5542 accept->flags = READ_ONCE(sqe->accept_flags);
09952e3e 5543 accept->nofile = rlimit(RLIMIT_NOFILE);
a7083ad5 5544
aaa4db12 5545 accept->file_slot = READ_ONCE(sqe->file_index);
adf3a9e9 5546 if (accept->file_slot && (accept->flags & SOCK_CLOEXEC))
aaa4db12 5547 return -EINVAL;
a7083ad5
PB
5548 if (accept->flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
5549 return -EINVAL;
5550 if (SOCK_NONBLOCK != O_NONBLOCK && (accept->flags & SOCK_NONBLOCK))
5551 accept->flags = (accept->flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
8ed8d3c3 5552 return 0;
8ed8d3c3 5553}
17f2fe35 5554
889fca73 5555static int io_accept(struct io_kiocb *req, unsigned int issue_flags)
8ed8d3c3
JA
5556{
5557 struct io_accept *accept = &req->accept;
45d189c6 5558 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
ac45abc0 5559 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
aaa4db12 5560 bool fixed = !!accept->file_slot;
a7083ad5
PB
5561 struct file *file;
5562 int ret, fd;
8ed8d3c3 5563
e697deed
JX
5564 if (req->file->f_flags & O_NONBLOCK)
5565 req->flags |= REQ_F_NOWAIT;
5566
aaa4db12
PB
5567 if (!fixed) {
5568 fd = __get_unused_fd_flags(accept->flags, accept->nofile);
5569 if (unlikely(fd < 0))
5570 return fd;
5571 }
a7083ad5
PB
5572 file = do_accept(req->file, file_flags, accept->addr, accept->addr_len,
5573 accept->flags);
5574 if (IS_ERR(file)) {
aaa4db12
PB
5575 if (!fixed)
5576 put_unused_fd(fd);
a7083ad5
PB
5577 ret = PTR_ERR(file);
5578 if (ret == -EAGAIN && force_nonblock)
5579 return -EAGAIN;
ac45abc0
PB
5580 if (ret == -ERESTARTSYS)
5581 ret = -EINTR;
93d2bcd2 5582 req_set_fail(req);
aaa4db12 5583 } else if (!fixed) {
a7083ad5
PB
5584 fd_install(fd, file);
5585 ret = fd;
aaa4db12
PB
5586 } else {
5587 ret = io_install_fixed_file(req, file, issue_flags,
5588 accept->file_slot - 1);
ac45abc0 5589 }
889fca73 5590 __io_req_complete(req, issue_flags, ret, 0);
17f2fe35 5591 return 0;
8ed8d3c3
JA
5592}
5593
93642ef8
PB
5594static int io_connect_prep_async(struct io_kiocb *req)
5595{
5596 struct io_async_connect *io = req->async_data;
5597 struct io_connect *conn = &req->connect;
5598
5599 return move_addr_to_kernel(conn->addr, conn->addr_len, &io->address);
5600}
5601
3529d8c2 5602static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
f499a021 5603{
3529d8c2 5604 struct io_connect *conn = &req->connect;
f499a021 5605
14587a46 5606 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3fbb51c1 5607 return -EINVAL;
26578cda
PB
5608 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags ||
5609 sqe->splice_fd_in)
3fbb51c1
JA
5610 return -EINVAL;
5611
3529d8c2
JA
5612 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
5613 conn->addr_len = READ_ONCE(sqe->addr2);
93642ef8 5614 return 0;
f499a021
JA
5615}
5616
889fca73 5617static int io_connect(struct io_kiocb *req, unsigned int issue_flags)
f8e85cf2 5618{
e8c2bc1f 5619 struct io_async_connect __io, *io;
f8e85cf2 5620 unsigned file_flags;
3fbb51c1 5621 int ret;
45d189c6 5622 bool force_nonblock = issue_flags & IO_URING_F_NONBLOCK;
f8e85cf2 5623
d886e185 5624 if (req_has_async_data(req)) {
e8c2bc1f 5625 io = req->async_data;
f499a021 5626 } else {
3529d8c2
JA
5627 ret = move_addr_to_kernel(req->connect.addr,
5628 req->connect.addr_len,
e8c2bc1f 5629 &__io.address);
f499a021
JA
5630 if (ret)
5631 goto out;
5632 io = &__io;
5633 }
5634
3fbb51c1
JA
5635 file_flags = force_nonblock ? O_NONBLOCK : 0;
5636
e8c2bc1f 5637 ret = __sys_connect_file(req->file, &io->address,
3fbb51c1 5638 req->connect.addr_len, file_flags);
87f80d62 5639 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
d886e185 5640 if (req_has_async_data(req))
b7bb4f7d 5641 return -EAGAIN;
e8c2bc1f 5642 if (io_alloc_async_data(req)) {
f499a021
JA
5643 ret = -ENOMEM;
5644 goto out;
5645 }
e8c2bc1f 5646 memcpy(req->async_data, &__io, sizeof(__io));
f8e85cf2 5647 return -EAGAIN;
f499a021 5648 }
f8e85cf2
JA
5649 if (ret == -ERESTARTSYS)
5650 ret = -EINTR;
f499a021 5651out:
4e88d6e7 5652 if (ret < 0)
93d2bcd2 5653 req_set_fail(req);
889fca73 5654 __io_req_complete(req, issue_flags, ret, 0);
f8e85cf2 5655 return 0;
469956e8
Y
5656}
5657#else /* !CONFIG_NET */
99a10081
JA
5658#define IO_NETOP_FN(op) \
5659static int io_##op(struct io_kiocb *req, unsigned int issue_flags) \
5660{ \
5661 return -EOPNOTSUPP; \
5662}
5663
5664#define IO_NETOP_PREP(op) \
5665IO_NETOP_FN(op) \
5666static int io_##op##_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe) \
5667{ \
5668 return -EOPNOTSUPP; \
5669} \
5670
5671#define IO_NETOP_PREP_ASYNC(op) \
5672IO_NETOP_PREP(op) \
5673static int io_##op##_prep_async(struct io_kiocb *req) \
5674{ \
5675 return -EOPNOTSUPP; \
5676}
5677
5678IO_NETOP_PREP_ASYNC(sendmsg);
5679IO_NETOP_PREP_ASYNC(recvmsg);
5680IO_NETOP_PREP_ASYNC(connect);
5681IO_NETOP_PREP(accept);
5682IO_NETOP_FN(send);
5683IO_NETOP_FN(recv);
469956e8 5684#endif /* CONFIG_NET */
f8e85cf2 5685
adc8682e
OL
5686#ifdef CONFIG_NET_RX_BUSY_POLL
5687
5688#define NAPI_TIMEOUT (60 * SEC_CONVERSION)
5689
5690struct napi_entry {
5691 struct list_head list;
5692 unsigned int napi_id;
5693 unsigned long timeout;
5694};
5695
5696/*
5697 * Add busy poll NAPI ID from sk.
5698 */
5699static void io_add_napi(struct file *file, struct io_ring_ctx *ctx)
5700{
5701 unsigned int napi_id;
5702 struct socket *sock;
5703 struct sock *sk;
5704 struct napi_entry *ne;
5705
5706 if (!net_busy_loop_on())
5707 return;
5708
5709 sock = sock_from_file(file);
5710 if (!sock)
5711 return;
5712
5713 sk = sock->sk;
5714 if (!sk)
5715 return;
5716
5717 napi_id = READ_ONCE(sk->sk_napi_id);
5718
5719 /* Non-NAPI IDs can be rejected */
5720 if (napi_id < MIN_NAPI_ID)
5721 return;
5722
5723 spin_lock(&ctx->napi_lock);
5724 list_for_each_entry(ne, &ctx->napi_list, list) {
5725 if (ne->napi_id == napi_id) {
5726 ne->timeout = jiffies + NAPI_TIMEOUT;
5727 goto out;
5728 }
5729 }
5730
5731 ne = kmalloc(sizeof(*ne), GFP_NOWAIT);
5732 if (!ne)
5733 goto out;
5734
5735 ne->napi_id = napi_id;
5736 ne->timeout = jiffies + NAPI_TIMEOUT;
5737 list_add_tail(&ne->list, &ctx->napi_list);
5738out:
5739 spin_unlock(&ctx->napi_lock);
5740}
5741
5742static inline void io_check_napi_entry_timeout(struct napi_entry *ne)
5743{
5744 if (time_after(jiffies, ne->timeout)) {
5745 list_del(&ne->list);
5746 kfree(ne);
5747 }
5748}
5749
5750/*
5751 * Busy poll if globally on and supporting sockets found
5752 */
5753static bool io_napi_busy_loop(struct list_head *napi_list)
5754{
5755 struct napi_entry *ne, *n;
5756
5757 list_for_each_entry_safe(ne, n, napi_list, list) {
5758 napi_busy_loop(ne->napi_id, NULL, NULL, true,
5759 BUSY_POLL_BUDGET);
5760 io_check_napi_entry_timeout(ne);
5761 }
5762 return !list_empty(napi_list);
5763}
5764
5765static void io_free_napi_list(struct io_ring_ctx *ctx)
5766{
5767 spin_lock(&ctx->napi_lock);
5768 while (!list_empty(&ctx->napi_list)) {
5769 struct napi_entry *ne =
5770 list_first_entry(&ctx->napi_list, struct napi_entry,
5771 list);
5772
5773 list_del(&ne->list);
5774 kfree(ne);
5775 }
5776 spin_unlock(&ctx->napi_lock);
5777}
5778#else
5779static inline void io_add_napi(struct file *file, struct io_ring_ctx *ctx)
5780{
5781}
5782
5783static inline void io_free_napi_list(struct io_ring_ctx *ctx)
5784{
5785}
5786#endif /* CONFIG_NET_RX_BUSY_POLL */
5787
d7718a9d
JA
5788struct io_poll_table {
5789 struct poll_table_struct pt;
5790 struct io_kiocb *req;
68b11e8b 5791 int nr_entries;
d7718a9d
JA
5792 int error;
5793};
ce593a6c 5794
aa43477b
PB
5795#define IO_POLL_CANCEL_FLAG BIT(31)
5796#define IO_POLL_REF_MASK ((1u << 20)-1)
6d816e08 5797
aa43477b
PB
5798/*
5799 * If refs part of ->poll_refs (see IO_POLL_REF_MASK) is 0, it's free. We can
5800 * bump it and acquire ownership. It's disallowed to modify requests while not
5801 * owning it, that prevents from races for enqueueing task_work's and b/w
5802 * arming poll and wakeups.
5803 */
5804static inline bool io_poll_get_ownership(struct io_kiocb *req)
5805{
5806 return !(atomic_fetch_inc(&req->poll_refs) & IO_POLL_REF_MASK);
d7718a9d
JA
5807}
5808
aa43477b 5809static void io_poll_mark_cancelled(struct io_kiocb *req)
74ce6ce4 5810{
aa43477b 5811 atomic_or(IO_POLL_CANCEL_FLAG, &req->poll_refs);
74ce6ce4
JA
5812}
5813
d4e7cd36 5814static struct io_poll_iocb *io_poll_get_double(struct io_kiocb *req)
18bceab1 5815{
e8c2bc1f 5816 /* pure poll stashes this in ->async_data, poll driven retry elsewhere */
d4e7cd36 5817 if (req->opcode == IORING_OP_POLL_ADD)
e8c2bc1f 5818 return req->async_data;
d4e7cd36
JA
5819 return req->apoll->double_poll;
5820}
5821
5822static struct io_poll_iocb *io_poll_get_single(struct io_kiocb *req)
5823{
5824 if (req->opcode == IORING_OP_POLL_ADD)
5825 return &req->poll;
5826 return &req->apoll->poll;
5827}
5828
5641897a 5829static void io_poll_req_insert(struct io_kiocb *req)
d4e7cd36 5830{
5641897a
PB
5831 struct io_ring_ctx *ctx = req->ctx;
5832 struct hlist_head *list;
18bceab1 5833
5641897a
PB
5834 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
5835 hlist_add_head(&req->hash_node, list);
18bceab1
JA
5836}
5837
5641897a
PB
5838static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
5839 wait_queue_func_t wake_func)
18bceab1 5840{
5641897a 5841 poll->head = NULL;
5641897a
PB
5842#define IO_POLL_UNMASK (EPOLLERR|EPOLLHUP|EPOLLNVAL|EPOLLRDHUP)
5843 /* mask in events that we always want/need */
5844 poll->events = events | IO_POLL_UNMASK;
5845 INIT_LIST_HEAD(&poll->wait.entry);
5846 init_waitqueue_func_entry(&poll->wait, wake_func);
18bceab1
JA
5847}
5848
aa43477b 5849static inline void io_poll_remove_entry(struct io_poll_iocb *poll)
18bceab1 5850{
791f3465 5851 struct wait_queue_head *head = smp_load_acquire(&poll->head);
18bceab1 5852
791f3465
PB
5853 if (head) {
5854 spin_lock_irq(&head->lock);
5855 list_del_init(&poll->wait.entry);
5856 poll->head = NULL;
5857 spin_unlock_irq(&head->lock);
5858 }
aa43477b 5859}
18bceab1 5860
aa43477b
PB
5861static void io_poll_remove_entries(struct io_kiocb *req)
5862{
91eac1c6
JA
5863 /*
5864 * Nothing to do if neither of those flags are set. Avoid dipping
5865 * into the poll/apoll/double cachelines if we can.
5866 */
5867 if (!(req->flags & (REQ_F_SINGLE_POLL | REQ_F_DOUBLE_POLL)))
5868 return;
18bceab1 5869
791f3465
PB
5870 /*
5871 * While we hold the waitqueue lock and the waitqueue is nonempty,
5872 * wake_up_pollfree() will wait for us. However, taking the waitqueue
5873 * lock in the first place can race with the waitqueue being freed.
5874 *
5875 * We solve this as eventpoll does: by taking advantage of the fact that
5876 * all users of wake_up_pollfree() will RCU-delay the actual free. If
5877 * we enter rcu_read_lock() and see that the pointer to the queue is
5878 * non-NULL, we can then lock it without the memory being freed out from
5879 * under us.
5880 *
5881 * Keep holding rcu_read_lock() as long as we hold the queue lock, in
5882 * case the caller deletes the entry from the queue, leaving it empty.
5883 * In that case, only RCU prevents the queue memory from being freed.
5884 */
5885 rcu_read_lock();
91eac1c6
JA
5886 if (req->flags & REQ_F_SINGLE_POLL)
5887 io_poll_remove_entry(io_poll_get_single(req));
5888 if (req->flags & REQ_F_DOUBLE_POLL)
5889 io_poll_remove_entry(io_poll_get_double(req));
791f3465 5890 rcu_read_unlock();
18bceab1
JA
5891}
5892
aa43477b
PB
5893/*
5894 * All poll tw should go through this. Checks for poll events, manages
5895 * references, does rewait, etc.
5896 *
5897 * Returns a negative error on failure. >0 when no action require, which is
5898 * either spurious wakeup or multishot CQE is served. 0 when it's done with
5899 * the request, then the mask is stored in req->result.
5900 */
5901static int io_poll_check_events(struct io_kiocb *req)
18bceab1 5902{
74ce6ce4 5903 struct io_ring_ctx *ctx = req->ctx;
d4e7cd36 5904 struct io_poll_iocb *poll = io_poll_get_single(req);
aa43477b 5905 int v;
18bceab1 5906
316319e8 5907 /* req->task == current here, checking PF_EXITING is safe */
e09ee510 5908 if (unlikely(req->task->flags & PF_EXITING))
aa43477b 5909 io_poll_mark_cancelled(req);
18bceab1 5910
aa43477b
PB
5911 do {
5912 v = atomic_read(&req->poll_refs);
74ce6ce4 5913
aa43477b
PB
5914 /* tw handler should be the owner, and so have some references */
5915 if (WARN_ON_ONCE(!(v & IO_POLL_REF_MASK)))
5916 return 0;
5917 if (v & IO_POLL_CANCEL_FLAG)
5918 return -ECANCELED;
8706e04e 5919
aa43477b 5920 if (!req->result) {
81459350 5921 struct poll_table_struct pt = { ._key = req->cflags };
18bceab1 5922
81459350 5923 req->result = vfs_poll(req->file, &pt) & req->cflags;
c8b5e260 5924 }
74ce6ce4 5925
aa43477b 5926 /* multishot, just fill an CQE and proceed */
81459350 5927 if (req->result && !(req->cflags & EPOLLONESHOT)) {
aa43477b
PB
5928 __poll_t mask = mangle_poll(req->result & poll->events);
5929 bool filled;
18bceab1 5930
aa43477b
PB
5931 spin_lock(&ctx->completion_lock);
5932 filled = io_fill_cqe_aux(ctx, req->user_data, mask,
5933 IORING_CQE_F_MORE);
5934 io_commit_cqring(ctx);
5935 spin_unlock(&ctx->completion_lock);
5936 if (unlikely(!filled))
5937 return -ECANCELED;
5938 io_cqring_ev_posted(ctx);
adc8682e 5939 io_add_napi(req->file, ctx);
aa43477b
PB
5940 } else if (req->result) {
5941 return 0;
5942 }
18bceab1 5943
aa43477b
PB
5944 /*
5945 * Release all references, retry if someone tried to restart
5946 * task_work while we were executing it.
5947 */
5948 } while (atomic_sub_return(v & IO_POLL_REF_MASK, &req->poll_refs));
18bceab1 5949
18bceab1
JA
5950 return 1;
5951}
5952
aa43477b 5953static void io_poll_task_func(struct io_kiocb *req, bool *locked)
18bceab1 5954{
18bceab1 5955 struct io_ring_ctx *ctx = req->ctx;
aa43477b 5956 int ret;
18bceab1 5957
aa43477b
PB
5958 ret = io_poll_check_events(req);
5959 if (ret > 0)
5960 return;
5961
5962 if (!ret) {
5963 req->result = mangle_poll(req->result & req->poll.events);
e27414be 5964 } else {
aa43477b
PB
5965 req->result = ret;
5966 req_set_fail(req);
a62682f9 5967 }
aa43477b
PB
5968
5969 io_poll_remove_entries(req);
5970 spin_lock(&ctx->completion_lock);
5971 hash_del(&req->hash_node);
5972 __io_req_complete_post(req, req->result, 0);
5973 io_commit_cqring(ctx);
5974 spin_unlock(&ctx->completion_lock);
5975 io_cqring_ev_posted(ctx);
18bceab1
JA
5976}
5977
aa43477b 5978static void io_apoll_task_func(struct io_kiocb *req, bool *locked)
18bceab1
JA
5979{
5980 struct io_ring_ctx *ctx = req->ctx;
aa43477b 5981 int ret;
18bceab1 5982
aa43477b
PB
5983 ret = io_poll_check_events(req);
5984 if (ret > 0)
5985 return;
18bceab1 5986
aa43477b
PB
5987 io_poll_remove_entries(req);
5988 spin_lock(&ctx->completion_lock);
5989 hash_del(&req->hash_node);
5990 spin_unlock(&ctx->completion_lock);
18bceab1 5991
aa43477b
PB
5992 if (!ret)
5993 io_req_task_submit(req, locked);
5994 else
5995 io_req_complete_failed(req, ret);
18bceab1
JA
5996}
5997
81459350 5998static void __io_poll_execute(struct io_kiocb *req, int mask, int events)
aa43477b
PB
5999{
6000 req->result = mask;
81459350
JA
6001 /*
6002 * This is useful for poll that is armed on behalf of another
6003 * request, and where the wakeup path could be on a different
6004 * CPU. We want to avoid pulling in req->apoll->events for that
6005 * case.
6006 */
6007 req->cflags = events;
aa43477b
PB
6008 if (req->opcode == IORING_OP_POLL_ADD)
6009 req->io_task_work.func = io_poll_task_func;
6010 else
6011 req->io_task_work.func = io_apoll_task_func;
6012
502c87d6 6013 trace_io_uring_task_add(req->ctx, req, req->user_data, req->opcode, mask);
aa43477b
PB
6014 io_req_task_work_add(req, false);
6015}
6016
81459350 6017static inline void io_poll_execute(struct io_kiocb *req, int res, int events)
aa43477b
PB
6018{
6019 if (io_poll_get_ownership(req))
81459350 6020 __io_poll_execute(req, res, events);
aa43477b
PB
6021}
6022
6023static void io_poll_cancel_req(struct io_kiocb *req)
6024{
6025 io_poll_mark_cancelled(req);
6026 /* kick tw, which should complete the request */
81459350 6027 io_poll_execute(req, 0, 0);
aa43477b
PB
6028}
6029
6030static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
6031 void *key)
18bceab1
JA
6032{
6033 struct io_kiocb *req = wait->private;
aa43477b
PB
6034 struct io_poll_iocb *poll = container_of(wait, struct io_poll_iocb,
6035 wait);
18bceab1
JA
6036 __poll_t mask = key_to_poll(key);
6037
791f3465
PB
6038 if (unlikely(mask & POLLFREE)) {
6039 io_poll_mark_cancelled(req);
6040 /* we have to kick tw in case it's not already */
81459350 6041 io_poll_execute(req, 0, poll->events);
791f3465
PB
6042
6043 /*
6044 * If the waitqueue is being freed early but someone is already
6045 * holds ownership over it, we have to tear down the request as
6046 * best we can. That means immediately removing the request from
6047 * its waitqueue and preventing all further accesses to the
6048 * waitqueue via the request.
6049 */
6050 list_del_init(&poll->wait.entry);
6051
6052 /*
6053 * Careful: this *must* be the last step, since as soon
6054 * as req->head is NULL'ed out, the request can be
6055 * completed and freed, since aio_poll_complete_work()
6056 * will no longer need to take the waitqueue lock.
6057 */
6058 smp_store_release(&poll->head, NULL);
6059 return 1;
6060 }
6061
aa43477b 6062 /* for instances that support it check for an event match first */
18bceab1
JA
6063 if (mask && !(mask & poll->events))
6064 return 0;
6065
eb0089d6
PB
6066 if (io_poll_get_ownership(req)) {
6067 /* optional, saves extra locking for removal in tw handler */
6068 if (mask && poll->events & EPOLLONESHOT) {
6069 list_del_init(&poll->wait.entry);
6070 poll->head = NULL;
91eac1c6 6071 req->flags &= ~REQ_F_SINGLE_POLL;
eb0089d6 6072 }
81459350 6073 __io_poll_execute(req, mask, poll->events);
eb0089d6 6074 }
18bceab1 6075 return 1;
18bceab1
JA
6076}
6077
6078static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
807abcb0
JA
6079 struct wait_queue_head *head,
6080 struct io_poll_iocb **poll_ptr)
18bceab1
JA
6081{
6082 struct io_kiocb *req = pt->req;
6083
6084 /*
68b11e8b
PB
6085 * The file being polled uses multiple waitqueues for poll handling
6086 * (e.g. one for read, one for write). Setup a separate io_poll_iocb
6087 * if this happens.
18bceab1 6088 */
68b11e8b 6089 if (unlikely(pt->nr_entries)) {
aa43477b 6090 struct io_poll_iocb *first = poll;
58852d4d 6091
23a65db8 6092 /* double add on the same waitqueue head, ignore */
aa43477b 6093 if (first->head == head)
23a65db8 6094 return;
18bceab1 6095 /* already have a 2nd entry, fail a third attempt */
807abcb0 6096 if (*poll_ptr) {
23a65db8
PB
6097 if ((*poll_ptr)->head == head)
6098 return;
18bceab1
JA
6099 pt->error = -EINVAL;
6100 return;
6101 }
aa43477b 6102
18bceab1
JA
6103 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
6104 if (!poll) {
6105 pt->error = -ENOMEM;
6106 return;
6107 }
91eac1c6 6108 req->flags |= REQ_F_DOUBLE_POLL;
aa43477b 6109 io_init_poll_iocb(poll, first->events, first->wait.func);
807abcb0 6110 *poll_ptr = poll;
d886e185
PB
6111 if (req->opcode == IORING_OP_POLL_ADD)
6112 req->flags |= REQ_F_ASYNC_DATA;
18bceab1
JA
6113 }
6114
91eac1c6 6115 req->flags |= REQ_F_SINGLE_POLL;
68b11e8b 6116 pt->nr_entries++;
18bceab1 6117 poll->head = head;
aa43477b 6118 poll->wait.private = req;
a31eb4a2
JX
6119
6120 if (poll->events & EPOLLEXCLUSIVE)
6121 add_wait_queue_exclusive(head, &poll->wait);
6122 else
6123 add_wait_queue(head, &poll->wait);
18bceab1
JA
6124}
6125
aa43477b 6126static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
18bceab1
JA
6127 struct poll_table_struct *p)
6128{
6129 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
d7718a9d 6130
aa43477b
PB
6131 __io_queue_proc(&pt->req->poll, pt, head,
6132 (struct io_poll_iocb **) &pt->req->async_data);
d7718a9d
JA
6133}
6134
aa43477b
PB
6135static int __io_arm_poll_handler(struct io_kiocb *req,
6136 struct io_poll_iocb *poll,
6137 struct io_poll_table *ipt, __poll_t mask)
d7718a9d
JA
6138{
6139 struct io_ring_ctx *ctx = req->ctx;
aa43477b 6140 int v;
d7718a9d 6141
4d52f338 6142 INIT_HLIST_NODE(&req->hash_node);
aa43477b 6143 io_init_poll_iocb(poll, mask, io_poll_wake);
b90cd197 6144 poll->file = req->file;
18bceab1 6145 poll->wait.private = req;
d7718a9d
JA
6146
6147 ipt->pt._key = mask;
6148 ipt->req = req;
68b11e8b
PB
6149 ipt->error = 0;
6150 ipt->nr_entries = 0;
d7718a9d 6151
aa43477b
PB
6152 /*
6153 * Take the ownership to delay any tw execution up until we're done
6154 * with poll arming. see io_poll_get_ownership().
6155 */
6156 atomic_set(&req->poll_refs, 1);
d7718a9d 6157 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
aa43477b
PB
6158
6159 if (mask && (poll->events & EPOLLONESHOT)) {
6160 io_poll_remove_entries(req);
6161 /* no one else has access to the req, forget about the ref */
6162 return mask;
6163 }
6164 if (!mask && unlikely(ipt->error || !ipt->nr_entries)) {
6165 io_poll_remove_entries(req);
6166 if (!ipt->error)
6167 ipt->error = -EINVAL;
6168 return 0;
6169 }
d7718a9d 6170
79ebeaee 6171 spin_lock(&ctx->completion_lock);
aa43477b
PB
6172 io_poll_req_insert(req);
6173 spin_unlock(&ctx->completion_lock);
6174
6175 if (mask) {
6176 /* can't multishot if failed, just queue the event we've got */
6177 if (unlikely(ipt->error || !ipt->nr_entries))
6178 poll->events |= EPOLLONESHOT;
81459350 6179 __io_poll_execute(req, mask, poll->events);
aa43477b 6180 return 0;
d7718a9d 6181 }
adc8682e 6182 io_add_napi(req->file, req->ctx);
d7718a9d 6183
aa43477b
PB
6184 /*
6185 * Release ownership. If someone tried to queue a tw while it was
6186 * locked, kick it off for them.
6187 */
6188 v = atomic_dec_return(&req->poll_refs);
6189 if (unlikely(v & IO_POLL_REF_MASK))
81459350 6190 __io_poll_execute(req, 0, poll->events);
aa43477b
PB
6191 return 0;
6192}
6193
6194static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
6195 struct poll_table_struct *p)
6196{
6197 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
6198 struct async_poll *apoll = pt->req->apoll;
6199
6200 __io_queue_proc(&apoll->poll, pt, head, &apoll->double_poll);
d7718a9d
JA
6201}
6202
59b735ae
OL
6203enum {
6204 IO_APOLL_OK,
6205 IO_APOLL_ABORTED,
6206 IO_APOLL_READY
6207};
6208
4d9237e3 6209static int io_arm_poll_handler(struct io_kiocb *req, unsigned issue_flags)
d7718a9d
JA
6210{
6211 const struct io_op_def *def = &io_op_defs[req->opcode];
6212 struct io_ring_ctx *ctx = req->ctx;
6213 struct async_poll *apoll;
6214 struct io_poll_table ipt;
aa43477b
PB
6215 __poll_t mask = EPOLLONESHOT | POLLERR | POLLPRI;
6216 int ret;
d7718a9d 6217
b2d9c3da
PB
6218 if (!def->pollin && !def->pollout)
6219 return IO_APOLL_ABORTED;
658d0a40
PB
6220 if (!file_can_poll(req->file) || (req->flags & REQ_F_POLLED))
6221 return IO_APOLL_ABORTED;
b2d9c3da
PB
6222
6223 if (def->pollin) {
b2d9c3da
PB
6224 mask |= POLLIN | POLLRDNORM;
6225
6226 /* If reading from MSG_ERRQUEUE using recvmsg, ignore POLLIN */
6227 if ((req->opcode == IORING_OP_RECVMSG) &&
6228 (req->sr_msg.msg_flags & MSG_ERRQUEUE))
6229 mask &= ~POLLIN;
6230 } else {
b2d9c3da
PB
6231 mask |= POLLOUT | POLLWRNORM;
6232 }
6233
4d9237e3
JA
6234 if (!(issue_flags & IO_URING_F_UNLOCKED) &&
6235 !list_empty(&ctx->apoll_cache)) {
6236 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
6237 poll.wait.entry);
6238 list_del_init(&apoll->poll.wait.entry);
6239 } else {
6240 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
6241 if (unlikely(!apoll))
6242 return IO_APOLL_ABORTED;
6243 }
807abcb0 6244 apoll->double_poll = NULL;
d7718a9d 6245 req->apoll = apoll;
b2d9c3da 6246 req->flags |= REQ_F_POLLED;
d7718a9d
JA
6247 ipt.pt._qproc = io_async_queue_proc;
6248
abdad709
JA
6249 io_kbuf_recycle(req);
6250
aa43477b 6251 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask);
41a5169c
HX
6252 if (ret || ipt.error)
6253 return ret ? IO_APOLL_READY : IO_APOLL_ABORTED;
6254
502c87d6 6255 trace_io_uring_poll_arm(ctx, req, req->user_data, req->opcode,
236daeae 6256 mask, apoll->poll.events);
59b735ae 6257 return IO_APOLL_OK;
d7718a9d
JA
6258}
6259
76e1b642
JA
6260/*
6261 * Returns true if we found and killed one or more poll requests
6262 */
c072481d
PB
6263static __cold bool io_poll_remove_all(struct io_ring_ctx *ctx,
6264 struct task_struct *tsk, bool cancel_all)
221c5eb2 6265{
78076bb6 6266 struct hlist_node *tmp;
221c5eb2 6267 struct io_kiocb *req;
aa43477b
PB
6268 bool found = false;
6269 int i;
221c5eb2 6270
79ebeaee 6271 spin_lock(&ctx->completion_lock);
78076bb6
JA
6272 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
6273 struct hlist_head *list;
6274
6275 list = &ctx->cancel_hash[i];
f3606e3a 6276 hlist_for_each_entry_safe(req, tmp, list, hash_node) {
42a7b4ed 6277 if (io_match_task_safe(req, tsk, cancel_all)) {
aa43477b
PB
6278 io_poll_cancel_req(req);
6279 found = true;
6280 }
f3606e3a 6281 }
221c5eb2 6282 }
79ebeaee 6283 spin_unlock(&ctx->completion_lock);
aa43477b 6284 return found;
221c5eb2
JA
6285}
6286
9ba5fac8
PB
6287static struct io_kiocb *io_poll_find(struct io_ring_ctx *ctx, __u64 sqe_addr,
6288 bool poll_only)
e07785b0 6289 __must_hold(&ctx->completion_lock)
47f46768 6290{
78076bb6 6291 struct hlist_head *list;
47f46768
JA
6292 struct io_kiocb *req;
6293
78076bb6
JA
6294 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
6295 hlist_for_each_entry(req, list, hash_node) {
b41e9852
JA
6296 if (sqe_addr != req->user_data)
6297 continue;
9ba5fac8
PB
6298 if (poll_only && req->opcode != IORING_OP_POLL_ADD)
6299 continue;
b2cb805f 6300 return req;
47f46768 6301 }
b2cb805f
JA
6302 return NULL;
6303}
6304
aa43477b
PB
6305static bool io_poll_disarm(struct io_kiocb *req)
6306 __must_hold(&ctx->completion_lock)
6307{
6308 if (!io_poll_get_ownership(req))
6309 return false;
6310 io_poll_remove_entries(req);
6311 hash_del(&req->hash_node);
6312 return true;
6313}
6314
9ba5fac8
PB
6315static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr,
6316 bool poll_only)
e07785b0 6317 __must_hold(&ctx->completion_lock)
b2cb805f 6318{
aa43477b 6319 struct io_kiocb *req = io_poll_find(ctx, sqe_addr, poll_only);
b2cb805f 6320
b2cb805f
JA
6321 if (!req)
6322 return -ENOENT;
aa43477b
PB
6323 io_poll_cancel_req(req);
6324 return 0;
47f46768
JA
6325}
6326
9096af3e
PB
6327static __poll_t io_poll_parse_events(const struct io_uring_sqe *sqe,
6328 unsigned int flags)
6329{
6330 u32 events;
47f46768 6331
9096af3e
PB
6332 events = READ_ONCE(sqe->poll32_events);
6333#ifdef __BIG_ENDIAN
6334 events = swahw32(events);
6335#endif
6336 if (!(flags & IORING_POLL_ADD_MULTI))
6337 events |= EPOLLONESHOT;
6338 return demangle_poll(events) | (events & (EPOLLEXCLUSIVE|EPOLLONESHOT));
47f46768
JA
6339}
6340
c5de0036 6341static int io_poll_update_prep(struct io_kiocb *req,
3529d8c2 6342 const struct io_uring_sqe *sqe)
0969e783 6343{
c5de0036
PB
6344 struct io_poll_update *upd = &req->poll_update;
6345 u32 flags;
6346
0969e783
JA
6347 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6348 return -EINVAL;
26578cda 6349 if (sqe->ioprio || sqe->buf_index || sqe->splice_fd_in)
c5de0036
PB
6350 return -EINVAL;
6351 flags = READ_ONCE(sqe->len);
6352 if (flags & ~(IORING_POLL_UPDATE_EVENTS | IORING_POLL_UPDATE_USER_DATA |
6353 IORING_POLL_ADD_MULTI))
6354 return -EINVAL;
6355 /* meaningless without update */
6356 if (flags == IORING_POLL_ADD_MULTI)
0969e783
JA
6357 return -EINVAL;
6358
c5de0036
PB
6359 upd->old_user_data = READ_ONCE(sqe->addr);
6360 upd->update_events = flags & IORING_POLL_UPDATE_EVENTS;
6361 upd->update_user_data = flags & IORING_POLL_UPDATE_USER_DATA;
221c5eb2 6362
c5de0036
PB
6363 upd->new_user_data = READ_ONCE(sqe->off);
6364 if (!upd->update_user_data && upd->new_user_data)
6365 return -EINVAL;
6366 if (upd->update_events)
6367 upd->events = io_poll_parse_events(sqe, flags);
6368 else if (sqe->poll32_events)
6369 return -EINVAL;
221c5eb2 6370
221c5eb2
JA
6371 return 0;
6372}
6373
3529d8c2 6374static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
221c5eb2
JA
6375{
6376 struct io_poll_iocb *poll = &req->poll;
c5de0036 6377 u32 flags;
221c5eb2
JA
6378
6379 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6380 return -EINVAL;
c5de0036 6381 if (sqe->ioprio || sqe->buf_index || sqe->off || sqe->addr)
88e41cf9
JA
6382 return -EINVAL;
6383 flags = READ_ONCE(sqe->len);
c5de0036 6384 if (flags & ~IORING_POLL_ADD_MULTI)
221c5eb2 6385 return -EINVAL;
04c76b41
PB
6386 if ((flags & IORING_POLL_ADD_MULTI) && (req->flags & REQ_F_CQE_SKIP))
6387 return -EINVAL;
221c5eb2 6388
48dcd38d 6389 io_req_set_refcount(req);
81459350 6390 req->cflags = poll->events = io_poll_parse_events(sqe, flags);
0969e783
JA
6391 return 0;
6392}
6393
61e98203 6394static int io_poll_add(struct io_kiocb *req, unsigned int issue_flags)
0969e783
JA
6395{
6396 struct io_poll_iocb *poll = &req->poll;
0969e783 6397 struct io_poll_table ipt;
aa43477b 6398 int ret;
0969e783 6399
d7718a9d 6400 ipt.pt._qproc = io_poll_queue_proc;
36703247 6401
aa43477b
PB
6402 ret = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events);
6403 ret = ret ?: ipt.error;
6404 if (ret)
6405 __io_req_complete(req, issue_flags, ret, 0);
6406 return 0;
221c5eb2
JA
6407}
6408
c5de0036 6409static int io_poll_update(struct io_kiocb *req, unsigned int issue_flags)
b69de288
JA
6410{
6411 struct io_ring_ctx *ctx = req->ctx;
6412 struct io_kiocb *preq;
2bbb146d 6413 int ret2, ret = 0;
cc8e9ba7 6414 bool locked;
b69de288 6415
79ebeaee 6416 spin_lock(&ctx->completion_lock);
9ba5fac8 6417 preq = io_poll_find(ctx, req->poll_update.old_user_data, true);
aa43477b 6418 if (!preq || !io_poll_disarm(preq)) {
79ebeaee 6419 spin_unlock(&ctx->completion_lock);
aa43477b 6420 ret = preq ? -EALREADY : -ENOENT;
2bbb146d 6421 goto out;
b69de288 6422 }
79ebeaee 6423 spin_unlock(&ctx->completion_lock);
cb3b200e 6424
2bbb146d
PB
6425 if (req->poll_update.update_events || req->poll_update.update_user_data) {
6426 /* only mask one event flags, keep behavior flags */
6427 if (req->poll_update.update_events) {
6428 preq->poll.events &= ~0xffff;
6429 preq->poll.events |= req->poll_update.events & 0xffff;
6430 preq->poll.events |= IO_POLL_UNMASK;
cb3b200e 6431 }
2bbb146d
PB
6432 if (req->poll_update.update_user_data)
6433 preq->user_data = req->poll_update.new_user_data;
b69de288 6434
2bbb146d
PB
6435 ret2 = io_poll_add(preq, issue_flags);
6436 /* successfully updated, don't complete poll request */
6437 if (!ret2)
6438 goto out;
b69de288 6439 }
6224590d 6440
2bbb146d 6441 req_set_fail(preq);
cc8e9ba7
PB
6442 preq->result = -ECANCELED;
6443 locked = !(issue_flags & IO_URING_F_UNLOCKED);
6444 io_req_task_complete(preq, &locked);
2bbb146d
PB
6445out:
6446 if (ret < 0)
6224590d 6447 req_set_fail(req);
2bbb146d 6448 /* complete update request, we're done with it */
cc8e9ba7 6449 __io_req_complete(req, issue_flags, ret, 0);
b69de288 6450 return 0;
89850fce
JA
6451}
6452
5262f567
JA
6453static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
6454{
ad8a48ac
JA
6455 struct io_timeout_data *data = container_of(timer,
6456 struct io_timeout_data, timer);
6457 struct io_kiocb *req = data->req;
6458 struct io_ring_ctx *ctx = req->ctx;
5262f567
JA
6459 unsigned long flags;
6460
89850fce 6461 spin_lock_irqsave(&ctx->timeout_lock, flags);
a71976f3 6462 list_del_init(&req->timeout.list);
01cec8c1
PB
6463 atomic_set(&req->ctx->cq_timeouts,
6464 atomic_read(&req->ctx->cq_timeouts) + 1);
89850fce 6465 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
01cec8c1 6466
a90c8bf6
PB
6467 if (!(data->flags & IORING_TIMEOUT_ETIME_SUCCESS))
6468 req_set_fail(req);
6469
6470 req->result = -ETIME;
6471 req->io_task_work.func = io_req_task_complete;
4813c377 6472 io_req_task_work_add(req, false);
5262f567
JA
6473 return HRTIMER_NORESTART;
6474}
6475
fbd15848
PB
6476static struct io_kiocb *io_timeout_extract(struct io_ring_ctx *ctx,
6477 __u64 user_data)
89850fce 6478 __must_hold(&ctx->timeout_lock)
f254ac04 6479{
fbd15848 6480 struct io_timeout_data *io;
47f46768 6481 struct io_kiocb *req;
fd9c7bc5 6482 bool found = false;
f254ac04 6483
135fcde8 6484 list_for_each_entry(req, &ctx->timeout_list, timeout.list) {
fd9c7bc5
PB
6485 found = user_data == req->user_data;
6486 if (found)
47f46768 6487 break;
47f46768 6488 }
fd9c7bc5
PB
6489 if (!found)
6490 return ERR_PTR(-ENOENT);
fbd15848
PB
6491
6492 io = req->async_data;
fd9c7bc5 6493 if (hrtimer_try_to_cancel(&io->timer) == -1)
fbd15848 6494 return ERR_PTR(-EALREADY);
a71976f3 6495 list_del_init(&req->timeout.list);
fbd15848
PB
6496 return req;
6497}
47f46768 6498
fbd15848 6499static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
ec3c3d0f 6500 __must_hold(&ctx->completion_lock)
89850fce 6501 __must_hold(&ctx->timeout_lock)
fbd15848
PB
6502{
6503 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6504
6505 if (IS_ERR(req))
6506 return PTR_ERR(req);
6695490d 6507 io_req_task_queue_fail(req, -ECANCELED);
f254ac04
JA
6508 return 0;
6509}
6510
50c1df2b
JA
6511static clockid_t io_timeout_get_clock(struct io_timeout_data *data)
6512{
6513 switch (data->flags & IORING_TIMEOUT_CLOCK_MASK) {
6514 case IORING_TIMEOUT_BOOTTIME:
6515 return CLOCK_BOOTTIME;
6516 case IORING_TIMEOUT_REALTIME:
6517 return CLOCK_REALTIME;
6518 default:
6519 /* can't happen, vetted at prep time */
6520 WARN_ON_ONCE(1);
6521 fallthrough;
6522 case 0:
6523 return CLOCK_MONOTONIC;
6524 }
6525}
6526
f1042b6c
PB
6527static int io_linked_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6528 struct timespec64 *ts, enum hrtimer_mode mode)
6529 __must_hold(&ctx->timeout_lock)
6530{
6531 struct io_timeout_data *io;
6532 struct io_kiocb *req;
6533 bool found = false;
6534
6535 list_for_each_entry(req, &ctx->ltimeout_list, timeout.list) {
6536 found = user_data == req->user_data;
6537 if (found)
6538 break;
6539 }
6540 if (!found)
6541 return -ENOENT;
6542
6543 io = req->async_data;
6544 if (hrtimer_try_to_cancel(&io->timer) == -1)
6545 return -EALREADY;
6546 hrtimer_init(&io->timer, io_timeout_get_clock(io), mode);
6547 io->timer.function = io_link_timeout_fn;
6548 hrtimer_start(&io->timer, timespec64_to_ktime(*ts), mode);
6549 return 0;
6550}
6551
9c8e11b3
PB
6552static int io_timeout_update(struct io_ring_ctx *ctx, __u64 user_data,
6553 struct timespec64 *ts, enum hrtimer_mode mode)
89850fce 6554 __must_hold(&ctx->timeout_lock)
47f46768 6555{
9c8e11b3
PB
6556 struct io_kiocb *req = io_timeout_extract(ctx, user_data);
6557 struct io_timeout_data *data;
47f46768 6558
9c8e11b3
PB
6559 if (IS_ERR(req))
6560 return PTR_ERR(req);
47f46768 6561
9c8e11b3
PB
6562 req->timeout.off = 0; /* noseq */
6563 data = req->async_data;
6564 list_add_tail(&req->timeout.list, &ctx->timeout_list);
50c1df2b 6565 hrtimer_init(&data->timer, io_timeout_get_clock(data), mode);
9c8e11b3
PB
6566 data->timer.function = io_timeout_fn;
6567 hrtimer_start(&data->timer, timespec64_to_ktime(*ts), mode);
6568 return 0;
47f46768
JA
6569}
6570
3529d8c2
JA
6571static int io_timeout_remove_prep(struct io_kiocb *req,
6572 const struct io_uring_sqe *sqe)
b29472ee 6573{
9c8e11b3
PB
6574 struct io_timeout_rem *tr = &req->timeout_rem;
6575
b29472ee
JA
6576 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
6577 return -EINVAL;
61710e43
DA
6578 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6579 return -EINVAL;
26578cda 6580 if (sqe->ioprio || sqe->buf_index || sqe->len || sqe->splice_fd_in)
b29472ee
JA
6581 return -EINVAL;
6582
f1042b6c 6583 tr->ltimeout = false;
9c8e11b3
PB
6584 tr->addr = READ_ONCE(sqe->addr);
6585 tr->flags = READ_ONCE(sqe->timeout_flags);
f1042b6c
PB
6586 if (tr->flags & IORING_TIMEOUT_UPDATE_MASK) {
6587 if (hweight32(tr->flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
6588 return -EINVAL;
6589 if (tr->flags & IORING_LINK_TIMEOUT_UPDATE)
6590 tr->ltimeout = true;
6591 if (tr->flags & ~(IORING_TIMEOUT_UPDATE_MASK|IORING_TIMEOUT_ABS))
9c8e11b3
PB
6592 return -EINVAL;
6593 if (get_timespec64(&tr->ts, u64_to_user_ptr(sqe->addr2)))
6594 return -EFAULT;
2087009c
YB
6595 if (tr->ts.tv_sec < 0 || tr->ts.tv_nsec < 0)
6596 return -EINVAL;
9c8e11b3
PB
6597 } else if (tr->flags) {
6598 /* timeout removal doesn't support flags */
b29472ee 6599 return -EINVAL;
9c8e11b3 6600 }
b29472ee 6601
b29472ee
JA
6602 return 0;
6603}
6604
8662daec
PB
6605static inline enum hrtimer_mode io_translate_timeout_mode(unsigned int flags)
6606{
6607 return (flags & IORING_TIMEOUT_ABS) ? HRTIMER_MODE_ABS
6608 : HRTIMER_MODE_REL;
6609}
6610
11365043
JA
6611/*
6612 * Remove or update an existing timeout command
6613 */
61e98203 6614static int io_timeout_remove(struct io_kiocb *req, unsigned int issue_flags)
11365043 6615{
9c8e11b3 6616 struct io_timeout_rem *tr = &req->timeout_rem;
11365043 6617 struct io_ring_ctx *ctx = req->ctx;
47f46768 6618 int ret;
11365043 6619
ec3c3d0f
PB
6620 if (!(req->timeout_rem.flags & IORING_TIMEOUT_UPDATE)) {
6621 spin_lock(&ctx->completion_lock);
6622 spin_lock_irq(&ctx->timeout_lock);
9c8e11b3 6623 ret = io_timeout_cancel(ctx, tr->addr);
ec3c3d0f
PB
6624 spin_unlock_irq(&ctx->timeout_lock);
6625 spin_unlock(&ctx->completion_lock);
6626 } else {
f1042b6c
PB
6627 enum hrtimer_mode mode = io_translate_timeout_mode(tr->flags);
6628
ec3c3d0f 6629 spin_lock_irq(&ctx->timeout_lock);
f1042b6c
PB
6630 if (tr->ltimeout)
6631 ret = io_linked_timeout_update(ctx, tr->addr, &tr->ts, mode);
6632 else
6633 ret = io_timeout_update(ctx, tr->addr, &tr->ts, mode);
ec3c3d0f
PB
6634 spin_unlock_irq(&ctx->timeout_lock);
6635 }
11365043 6636
4e88d6e7 6637 if (ret < 0)
93d2bcd2 6638 req_set_fail(req);
505657bc 6639 io_req_complete_post(req, ret, 0);
11365043 6640 return 0;
5262f567
JA
6641}
6642
3529d8c2 6643static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2d28390a 6644 bool is_timeout_link)
5262f567 6645{
ad8a48ac 6646 struct io_timeout_data *data;
a41525ab 6647 unsigned flags;
56080b02 6648 u32 off = READ_ONCE(sqe->off);
5262f567 6649
ad8a48ac 6650 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5262f567 6651 return -EINVAL;
26578cda
PB
6652 if (sqe->ioprio || sqe->buf_index || sqe->len != 1 ||
6653 sqe->splice_fd_in)
a41525ab 6654 return -EINVAL;
56080b02 6655 if (off && is_timeout_link)
2d28390a 6656 return -EINVAL;
a41525ab 6657 flags = READ_ONCE(sqe->timeout_flags);
6224590d
PB
6658 if (flags & ~(IORING_TIMEOUT_ABS | IORING_TIMEOUT_CLOCK_MASK |
6659 IORING_TIMEOUT_ETIME_SUCCESS))
50c1df2b
JA
6660 return -EINVAL;
6661 /* more than one clock specified is invalid, obviously */
6662 if (hweight32(flags & IORING_TIMEOUT_CLOCK_MASK) > 1)
5262f567 6663 return -EINVAL;
bdf20073 6664
ef9dd637 6665 INIT_LIST_HEAD(&req->timeout.list);
bfe68a22 6666 req->timeout.off = off;
f18ee4cf
PB
6667 if (unlikely(off && !req->ctx->off_timeout_used))
6668 req->ctx->off_timeout_used = true;
26a61679 6669
d6a644a7
PB
6670 if (WARN_ON_ONCE(req_has_async_data(req)))
6671 return -EFAULT;
6672 if (io_alloc_async_data(req))
26a61679
JA
6673 return -ENOMEM;
6674
e8c2bc1f 6675 data = req->async_data;
ad8a48ac 6676 data->req = req;
50c1df2b 6677 data->flags = flags;
ad8a48ac
JA
6678
6679 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5262f567
JA
6680 return -EFAULT;
6681
f6223ff7
YB
6682 if (data->ts.tv_sec < 0 || data->ts.tv_nsec < 0)
6683 return -EINVAL;
6684
8662daec 6685 data->mode = io_translate_timeout_mode(flags);
50c1df2b 6686 hrtimer_init(&data->timer, io_timeout_get_clock(data), data->mode);
b97e736a
PB
6687
6688 if (is_timeout_link) {
6689 struct io_submit_link *link = &req->ctx->submit_state.link;
6690
6691 if (!link->head)
6692 return -EINVAL;
6693 if (link->last->opcode == IORING_OP_LINK_TIMEOUT)
6694 return -EINVAL;
4d13d1a4
PB
6695 req->timeout.head = link->last;
6696 link->last->flags |= REQ_F_ARM_LTIMEOUT;
b97e736a 6697 }
ad8a48ac
JA
6698 return 0;
6699}
6700
61e98203 6701static int io_timeout(struct io_kiocb *req, unsigned int issue_flags)
ad8a48ac 6702{
ad8a48ac 6703 struct io_ring_ctx *ctx = req->ctx;
e8c2bc1f 6704 struct io_timeout_data *data = req->async_data;
ad8a48ac 6705 struct list_head *entry;
bfe68a22 6706 u32 tail, off = req->timeout.off;
ad8a48ac 6707
89850fce 6708 spin_lock_irq(&ctx->timeout_lock);
93bd25bb 6709
5262f567
JA
6710 /*
6711 * sqe->off holds how many events that need to occur for this
93bd25bb
JA
6712 * timeout event to be satisfied. If it isn't set, then this is
6713 * a pure timeout request, sequence isn't used.
5262f567 6714 */
8eb7e2d0 6715 if (io_is_timeout_noseq(req)) {
93bd25bb
JA
6716 entry = ctx->timeout_list.prev;
6717 goto add;
6718 }
5262f567 6719
bfe68a22
PB
6720 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
6721 req->timeout.target_seq = tail + off;
5262f567 6722
f010505b
MDG
6723 /* Update the last seq here in case io_flush_timeouts() hasn't.
6724 * This is safe because ->completion_lock is held, and submissions
6725 * and completions are never mixed in the same ->completion_lock section.
6726 */
6727 ctx->cq_last_tm_flush = tail;
6728
5262f567
JA
6729 /*
6730 * Insertion sort, ensuring the first entry in the list is always
6731 * the one we need first.
6732 */
5262f567 6733 list_for_each_prev(entry, &ctx->timeout_list) {
135fcde8
PB
6734 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb,
6735 timeout.list);
5262f567 6736
8eb7e2d0 6737 if (io_is_timeout_noseq(nxt))
93bd25bb 6738 continue;
bfe68a22
PB
6739 /* nxt.seq is behind @tail, otherwise would've been completed */
6740 if (off >= nxt->timeout.target_seq - tail)
5262f567
JA
6741 break;
6742 }
93bd25bb 6743add:
135fcde8 6744 list_add(&req->timeout.list, entry);
ad8a48ac
JA
6745 data->timer.function = io_timeout_fn;
6746 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
89850fce 6747 spin_unlock_irq(&ctx->timeout_lock);
5262f567
JA
6748 return 0;
6749}
5262f567 6750
f458dd84
PB
6751struct io_cancel_data {
6752 struct io_ring_ctx *ctx;
6753 u64 user_data;
6754};
6755
62755e35
JA
6756static bool io_cancel_cb(struct io_wq_work *work, void *data)
6757{
6758 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
f458dd84 6759 struct io_cancel_data *cd = data;
62755e35 6760
f458dd84 6761 return req->ctx == cd->ctx && req->user_data == cd->user_data;
62755e35
JA
6762}
6763
f458dd84
PB
6764static int io_async_cancel_one(struct io_uring_task *tctx, u64 user_data,
6765 struct io_ring_ctx *ctx)
62755e35 6766{
f458dd84 6767 struct io_cancel_data data = { .ctx = ctx, .user_data = user_data, };
62755e35 6768 enum io_wq_cancel cancel_ret;
62755e35
JA
6769 int ret = 0;
6770
f458dd84 6771 if (!tctx || !tctx->io_wq)
5aa75ed5
JA
6772 return -ENOENT;
6773
f458dd84 6774 cancel_ret = io_wq_cancel_cb(tctx->io_wq, io_cancel_cb, &data, false);
62755e35
JA
6775 switch (cancel_ret) {
6776 case IO_WQ_CANCEL_OK:
6777 ret = 0;
6778 break;
6779 case IO_WQ_CANCEL_RUNNING:
6780 ret = -EALREADY;
6781 break;
6782 case IO_WQ_CANCEL_NOTFOUND:
6783 ret = -ENOENT;
6784 break;
6785 }
6786
e977d6d3
JA
6787 return ret;
6788}
6789
8cb01fac 6790static int io_try_cancel_userdata(struct io_kiocb *req, u64 sqe_addr)
47f46768 6791{
8cb01fac 6792 struct io_ring_ctx *ctx = req->ctx;
47f46768
JA
6793 int ret;
6794
dadebc35 6795 WARN_ON_ONCE(!io_wq_current_is_worker() && req->task != current);
8cb01fac 6796
f458dd84 6797 ret = io_async_cancel_one(req->task->io_uring, sqe_addr, ctx);
ccbf7261
JA
6798 /*
6799 * Fall-through even for -EALREADY, as we may have poll armed
6800 * that need unarming.
6801 */
6802 if (!ret)
6803 return 0;
505657bc
PB
6804
6805 spin_lock(&ctx->completion_lock);
ccbf7261
JA
6806 ret = io_poll_cancel(ctx, sqe_addr, false);
6807 if (ret != -ENOENT)
6808 goto out;
6809
79ebeaee 6810 spin_lock_irq(&ctx->timeout_lock);
47f46768 6811 ret = io_timeout_cancel(ctx, sqe_addr);
79ebeaee 6812 spin_unlock_irq(&ctx->timeout_lock);
505657bc
PB
6813out:
6814 spin_unlock(&ctx->completion_lock);
6815 return ret;
47f46768
JA
6816}
6817
3529d8c2
JA
6818static int io_async_cancel_prep(struct io_kiocb *req,
6819 const struct io_uring_sqe *sqe)
e977d6d3 6820{
fbf23849 6821 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
e977d6d3 6822 return -EINVAL;
61710e43
DA
6823 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6824 return -EINVAL;
26578cda
PB
6825 if (sqe->ioprio || sqe->off || sqe->len || sqe->cancel_flags ||
6826 sqe->splice_fd_in)
e977d6d3
JA
6827 return -EINVAL;
6828
fbf23849
JA
6829 req->cancel.addr = READ_ONCE(sqe->addr);
6830 return 0;
6831}
6832
61e98203 6833static int io_async_cancel(struct io_kiocb *req, unsigned int issue_flags)
fbf23849
JA
6834{
6835 struct io_ring_ctx *ctx = req->ctx;
58f99373 6836 u64 sqe_addr = req->cancel.addr;
3b44b371 6837 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
58f99373
PB
6838 struct io_tctx_node *node;
6839 int ret;
6840
8cb01fac 6841 ret = io_try_cancel_userdata(req, sqe_addr);
58f99373
PB
6842 if (ret != -ENOENT)
6843 goto done;
58f99373
PB
6844
6845 /* slow path, try all io-wq's */
3b44b371 6846 io_ring_submit_lock(ctx, needs_lock);
58f99373
PB
6847 ret = -ENOENT;
6848 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
6849 struct io_uring_task *tctx = node->task->io_uring;
fbf23849 6850
58f99373
PB
6851 ret = io_async_cancel_one(tctx, req->cancel.addr, ctx);
6852 if (ret != -ENOENT)
6853 break;
6854 }
3b44b371 6855 io_ring_submit_unlock(ctx, needs_lock);
58f99373 6856done:
58f99373 6857 if (ret < 0)
93d2bcd2 6858 req_set_fail(req);
505657bc 6859 io_req_complete_post(req, ret, 0);
5262f567
JA
6860 return 0;
6861}
6862
269bbe5f 6863static int io_rsrc_update_prep(struct io_kiocb *req,
05f3fb3c
JA
6864 const struct io_uring_sqe *sqe)
6865{
61710e43
DA
6866 if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
6867 return -EINVAL;
26578cda 6868 if (sqe->ioprio || sqe->rw_flags || sqe->splice_fd_in)
05f3fb3c
JA
6869 return -EINVAL;
6870
269bbe5f
BM
6871 req->rsrc_update.offset = READ_ONCE(sqe->off);
6872 req->rsrc_update.nr_args = READ_ONCE(sqe->len);
6873 if (!req->rsrc_update.nr_args)
05f3fb3c 6874 return -EINVAL;
269bbe5f 6875 req->rsrc_update.arg = READ_ONCE(sqe->addr);
05f3fb3c
JA
6876 return 0;
6877}
6878
889fca73 6879static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
fbf23849
JA
6880{
6881 struct io_ring_ctx *ctx = req->ctx;
3b44b371 6882 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
c3bdad02 6883 struct io_uring_rsrc_update2 up;
05f3fb3c 6884 int ret;
fbf23849 6885
269bbe5f
BM
6886 up.offset = req->rsrc_update.offset;
6887 up.data = req->rsrc_update.arg;
c3bdad02
PB
6888 up.nr = 0;
6889 up.tags = 0;
615cee49 6890 up.resv = 0;
05f3fb3c 6891
3b44b371 6892 io_ring_submit_lock(ctx, needs_lock);
fdecb662 6893 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
98f0b3b4 6894 &up, req->rsrc_update.nr_args);
3b44b371 6895 io_ring_submit_unlock(ctx, needs_lock);
05f3fb3c
JA
6896
6897 if (ret < 0)
93d2bcd2 6898 req_set_fail(req);
889fca73 6899 __io_req_complete(req, issue_flags, ret, 0);
5262f567
JA
6900 return 0;
6901}
6902
bfe76559 6903static int io_req_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
f67676d1 6904{
d625c6ee 6905 switch (req->opcode) {
e781573e 6906 case IORING_OP_NOP:
bfe76559 6907 return 0;
f67676d1
JA
6908 case IORING_OP_READV:
6909 case IORING_OP_READ_FIXED:
3a6820f2 6910 case IORING_OP_READ:
bfe76559 6911 return io_read_prep(req, sqe);
f67676d1
JA
6912 case IORING_OP_WRITEV:
6913 case IORING_OP_WRITE_FIXED:
3a6820f2 6914 case IORING_OP_WRITE:
bfe76559 6915 return io_write_prep(req, sqe);
0969e783 6916 case IORING_OP_POLL_ADD:
bfe76559 6917 return io_poll_add_prep(req, sqe);
0969e783 6918 case IORING_OP_POLL_REMOVE:
c5de0036 6919 return io_poll_update_prep(req, sqe);
8ed8d3c3 6920 case IORING_OP_FSYNC:
1155c76a 6921 return io_fsync_prep(req, sqe);
8ed8d3c3 6922 case IORING_OP_SYNC_FILE_RANGE:
1155c76a 6923 return io_sfr_prep(req, sqe);
03b1230c 6924 case IORING_OP_SENDMSG:
fddaface 6925 case IORING_OP_SEND:
bfe76559 6926 return io_sendmsg_prep(req, sqe);
03b1230c 6927 case IORING_OP_RECVMSG:
fddaface 6928 case IORING_OP_RECV:
bfe76559 6929 return io_recvmsg_prep(req, sqe);
f499a021 6930 case IORING_OP_CONNECT:
bfe76559 6931 return io_connect_prep(req, sqe);
2d28390a 6932 case IORING_OP_TIMEOUT:
bfe76559 6933 return io_timeout_prep(req, sqe, false);
b29472ee 6934 case IORING_OP_TIMEOUT_REMOVE:
bfe76559 6935 return io_timeout_remove_prep(req, sqe);
fbf23849 6936 case IORING_OP_ASYNC_CANCEL:
bfe76559 6937 return io_async_cancel_prep(req, sqe);
2d28390a 6938 case IORING_OP_LINK_TIMEOUT:
bfe76559 6939 return io_timeout_prep(req, sqe, true);
8ed8d3c3 6940 case IORING_OP_ACCEPT:
bfe76559 6941 return io_accept_prep(req, sqe);
d63d1b5e 6942 case IORING_OP_FALLOCATE:
bfe76559 6943 return io_fallocate_prep(req, sqe);
15b71abe 6944 case IORING_OP_OPENAT:
bfe76559 6945 return io_openat_prep(req, sqe);
b5dba59e 6946 case IORING_OP_CLOSE:
bfe76559 6947 return io_close_prep(req, sqe);
05f3fb3c 6948 case IORING_OP_FILES_UPDATE:
269bbe5f 6949 return io_rsrc_update_prep(req, sqe);
eddc7ef5 6950 case IORING_OP_STATX:
bfe76559 6951 return io_statx_prep(req, sqe);
4840e418 6952 case IORING_OP_FADVISE:
bfe76559 6953 return io_fadvise_prep(req, sqe);
c1ca757b 6954 case IORING_OP_MADVISE:
bfe76559 6955 return io_madvise_prep(req, sqe);
cebdb986 6956 case IORING_OP_OPENAT2:
bfe76559 6957 return io_openat2_prep(req, sqe);
3e4827b0 6958 case IORING_OP_EPOLL_CTL:
bfe76559 6959 return io_epoll_ctl_prep(req, sqe);
7d67af2c 6960 case IORING_OP_SPLICE:
bfe76559 6961 return io_splice_prep(req, sqe);
ddf0322d 6962 case IORING_OP_PROVIDE_BUFFERS:
bfe76559 6963 return io_provide_buffers_prep(req, sqe);
067524e9 6964 case IORING_OP_REMOVE_BUFFERS:
bfe76559 6965 return io_remove_buffers_prep(req, sqe);
f2a8d5c7 6966 case IORING_OP_TEE:
bfe76559 6967 return io_tee_prep(req, sqe);
36f4fa68
JA
6968 case IORING_OP_SHUTDOWN:
6969 return io_shutdown_prep(req, sqe);
80a261fd
JA
6970 case IORING_OP_RENAMEAT:
6971 return io_renameat_prep(req, sqe);
14a1143b
JA
6972 case IORING_OP_UNLINKAT:
6973 return io_unlinkat_prep(req, sqe);
e34a02dc
DK
6974 case IORING_OP_MKDIRAT:
6975 return io_mkdirat_prep(req, sqe);
7a8721f8
DK
6976 case IORING_OP_SYMLINKAT:
6977 return io_symlinkat_prep(req, sqe);
cf30da90
DK
6978 case IORING_OP_LINKAT:
6979 return io_linkat_prep(req, sqe);
4f57f06c
JA
6980 case IORING_OP_MSG_RING:
6981 return io_msg_ring_prep(req, sqe);
f67676d1
JA
6982 }
6983
bfe76559
PB
6984 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
6985 req->opcode);
bd54b6fe 6986 return -EINVAL;
bfe76559
PB
6987}
6988
93642ef8 6989static int io_req_prep_async(struct io_kiocb *req)
bfe76559 6990{
b7e298d2
PB
6991 if (!io_op_defs[req->opcode].needs_async_setup)
6992 return 0;
d886e185 6993 if (WARN_ON_ONCE(req_has_async_data(req)))
b7e298d2
PB
6994 return -EFAULT;
6995 if (io_alloc_async_data(req))
6996 return -EAGAIN;
6997
93642ef8
PB
6998 switch (req->opcode) {
6999 case IORING_OP_READV:
93642ef8
PB
7000 return io_rw_prep_async(req, READ);
7001 case IORING_OP_WRITEV:
93642ef8
PB
7002 return io_rw_prep_async(req, WRITE);
7003 case IORING_OP_SENDMSG:
93642ef8
PB
7004 return io_sendmsg_prep_async(req);
7005 case IORING_OP_RECVMSG:
93642ef8
PB
7006 return io_recvmsg_prep_async(req);
7007 case IORING_OP_CONNECT:
7008 return io_connect_prep_async(req);
7009 }
b7e298d2
PB
7010 printk_once(KERN_WARNING "io_uring: prep_async() bad opcode %d\n",
7011 req->opcode);
7012 return -EFAULT;
f67676d1
JA
7013}
7014
9cf7c104
PB
7015static u32 io_get_sequence(struct io_kiocb *req)
7016{
a3dbdf54 7017 u32 seq = req->ctx->cached_sq_head;
9cf7c104 7018
a3dbdf54
PB
7019 /* need original cached_sq_head, but it was increased for each req */
7020 io_for_each_link(req, req)
7021 seq--;
7022 return seq;
9cf7c104
PB
7023}
7024
c072481d 7025static __cold void io_drain_req(struct io_kiocb *req)
de0617e4 7026{
a197f664 7027 struct io_ring_ctx *ctx = req->ctx;
27dc8338 7028 struct io_defer_entry *de;
f67676d1 7029 int ret;
e0eb71dc 7030 u32 seq = io_get_sequence(req);
3c19966d 7031
9d858b21 7032 /* Still need defer if there is pending req in defer list. */
e302f104 7033 spin_lock(&ctx->completion_lock);
5e371265 7034 if (!req_need_defer(req, seq) && list_empty_careful(&ctx->defer_list)) {
e302f104 7035 spin_unlock(&ctx->completion_lock);
e0eb71dc 7036queue:
10c66904 7037 ctx->drain_active = false;
e0eb71dc
PB
7038 io_req_task_queue(req);
7039 return;
10c66904 7040 }
e302f104 7041 spin_unlock(&ctx->completion_lock);
9cf7c104 7042
b7e298d2 7043 ret = io_req_prep_async(req);
e0eb71dc
PB
7044 if (ret) {
7045fail:
7046 io_req_complete_failed(req, ret);
7047 return;
7048 }
cbdcb435 7049 io_prep_async_link(req);
27dc8338 7050 de = kmalloc(sizeof(*de), GFP_KERNEL);
76cc33d7 7051 if (!de) {
1b48773f 7052 ret = -ENOMEM;
e0eb71dc 7053 goto fail;
76cc33d7 7054 }
2d28390a 7055
79ebeaee 7056 spin_lock(&ctx->completion_lock);
9cf7c104 7057 if (!req_need_defer(req, seq) && list_empty(&ctx->defer_list)) {
79ebeaee 7058 spin_unlock(&ctx->completion_lock);
27dc8338 7059 kfree(de);
e0eb71dc 7060 goto queue;
de0617e4
JA
7061 }
7062
502c87d6 7063 trace_io_uring_defer(ctx, req, req->user_data, req->opcode);
27dc8338 7064 de->req = req;
9cf7c104 7065 de->seq = seq;
27dc8338 7066 list_add_tail(&de->list, &ctx->defer_list);
79ebeaee 7067 spin_unlock(&ctx->completion_lock);
de0617e4
JA
7068}
7069
68fb8979 7070static void io_clean_op(struct io_kiocb *req)
99bc4c38 7071{
d1fd1c20 7072 if (req->flags & REQ_F_BUFFER_SELECTED)
cc3cec83 7073 io_put_kbuf_comp(req);
99bc4c38 7074
0e1b6fe3
PB
7075 if (req->flags & REQ_F_NEED_CLEANUP) {
7076 switch (req->opcode) {
7077 case IORING_OP_READV:
7078 case IORING_OP_READ_FIXED:
7079 case IORING_OP_READ:
7080 case IORING_OP_WRITEV:
7081 case IORING_OP_WRITE_FIXED:
e8c2bc1f
JA
7082 case IORING_OP_WRITE: {
7083 struct io_async_rw *io = req->async_data;
1dacb4df
PB
7084
7085 kfree(io->free_iovec);
0e1b6fe3 7086 break;
e8c2bc1f 7087 }
0e1b6fe3 7088 case IORING_OP_RECVMSG:
e8c2bc1f
JA
7089 case IORING_OP_SENDMSG: {
7090 struct io_async_msghdr *io = req->async_data;
257e84a5
PB
7091
7092 kfree(io->free_iov);
0e1b6fe3 7093 break;
e8c2bc1f 7094 }
0e1b6fe3
PB
7095 case IORING_OP_SPLICE:
7096 case IORING_OP_TEE:
e1d767f0
PB
7097 if (!(req->splice.flags & SPLICE_F_FD_IN_FIXED))
7098 io_put_file(req->splice.file_in);
0e1b6fe3 7099 break;
f3cd4850
JA
7100 case IORING_OP_OPENAT:
7101 case IORING_OP_OPENAT2:
7102 if (req->open.filename)
7103 putname(req->open.filename);
7104 break;
80a261fd
JA
7105 case IORING_OP_RENAMEAT:
7106 putname(req->rename.oldpath);
7107 putname(req->rename.newpath);
7108 break;
14a1143b
JA
7109 case IORING_OP_UNLINKAT:
7110 putname(req->unlink.filename);
7111 break;
e34a02dc
DK
7112 case IORING_OP_MKDIRAT:
7113 putname(req->mkdir.filename);
7114 break;
7a8721f8
DK
7115 case IORING_OP_SYMLINKAT:
7116 putname(req->symlink.oldpath);
7117 putname(req->symlink.newpath);
7118 break;
cf30da90
DK
7119 case IORING_OP_LINKAT:
7120 putname(req->hardlink.oldpath);
7121 putname(req->hardlink.newpath);
7122 break;
0e1b6fe3 7123 }
99bc4c38 7124 }
75652a30
JA
7125 if ((req->flags & REQ_F_POLLED) && req->apoll) {
7126 kfree(req->apoll->double_poll);
7127 kfree(req->apoll);
7128 req->apoll = NULL;
7129 }
3a0a6902
PB
7130 if (req->flags & REQ_F_INFLIGHT) {
7131 struct io_uring_task *tctx = req->task->io_uring;
7132
7133 atomic_dec(&tctx->inflight_tracked);
3a0a6902 7134 }
c854357b 7135 if (req->flags & REQ_F_CREDS)
b8e64b53 7136 put_cred(req->creds);
d886e185
PB
7137 if (req->flags & REQ_F_ASYNC_DATA) {
7138 kfree(req->async_data);
7139 req->async_data = NULL;
7140 }
c854357b 7141 req->flags &= ~IO_REQ_CLEAN_FLAGS;
99bc4c38
PB
7142}
7143
889fca73 7144static int io_issue_sqe(struct io_kiocb *req, unsigned int issue_flags)
2b188cc1 7145{
5730b27e 7146 const struct cred *creds = NULL;
d625c6ee 7147 int ret;
2b188cc1 7148
6878b40e 7149 if (unlikely((req->flags & REQ_F_CREDS) && req->creds != current_cred()))
c10d1f98 7150 creds = override_creds(req->creds);
5730b27e 7151
5bd2182d
PM
7152 if (!io_op_defs[req->opcode].audit_skip)
7153 audit_uring_entry(req->opcode);
7154
d625c6ee 7155 switch (req->opcode) {
2b188cc1 7156 case IORING_OP_NOP:
889fca73 7157 ret = io_nop(req, issue_flags);
2b188cc1
JA
7158 break;
7159 case IORING_OP_READV:
edafccee 7160 case IORING_OP_READ_FIXED:
3a6820f2 7161 case IORING_OP_READ:
889fca73 7162 ret = io_read(req, issue_flags);
edafccee 7163 break;
3529d8c2 7164 case IORING_OP_WRITEV:
edafccee 7165 case IORING_OP_WRITE_FIXED:
3a6820f2 7166 case IORING_OP_WRITE:
889fca73 7167 ret = io_write(req, issue_flags);
2b188cc1 7168 break;
c992fe29 7169 case IORING_OP_FSYNC:
45d189c6 7170 ret = io_fsync(req, issue_flags);
c992fe29 7171 break;
221c5eb2 7172 case IORING_OP_POLL_ADD:
61e98203 7173 ret = io_poll_add(req, issue_flags);
221c5eb2
JA
7174 break;
7175 case IORING_OP_POLL_REMOVE:
c5de0036 7176 ret = io_poll_update(req, issue_flags);
221c5eb2 7177 break;
5d17b4a4 7178 case IORING_OP_SYNC_FILE_RANGE:
45d189c6 7179 ret = io_sync_file_range(req, issue_flags);
5d17b4a4 7180 break;
0fa03c62 7181 case IORING_OP_SENDMSG:
889fca73 7182 ret = io_sendmsg(req, issue_flags);
062d04d7 7183 break;
fddaface 7184 case IORING_OP_SEND:
889fca73 7185 ret = io_send(req, issue_flags);
0fa03c62 7186 break;
aa1fa28f 7187 case IORING_OP_RECVMSG:
889fca73 7188 ret = io_recvmsg(req, issue_flags);
062d04d7 7189 break;
fddaface 7190 case IORING_OP_RECV:
889fca73 7191 ret = io_recv(req, issue_flags);
aa1fa28f 7192 break;
5262f567 7193 case IORING_OP_TIMEOUT:
61e98203 7194 ret = io_timeout(req, issue_flags);
5262f567 7195 break;
11365043 7196 case IORING_OP_TIMEOUT_REMOVE:
61e98203 7197 ret = io_timeout_remove(req, issue_flags);
11365043 7198 break;
17f2fe35 7199 case IORING_OP_ACCEPT:
889fca73 7200 ret = io_accept(req, issue_flags);
17f2fe35 7201 break;
f8e85cf2 7202 case IORING_OP_CONNECT:
889fca73 7203 ret = io_connect(req, issue_flags);
f8e85cf2 7204 break;
62755e35 7205 case IORING_OP_ASYNC_CANCEL:
61e98203 7206 ret = io_async_cancel(req, issue_flags);
62755e35 7207 break;
d63d1b5e 7208 case IORING_OP_FALLOCATE:
45d189c6 7209 ret = io_fallocate(req, issue_flags);
d63d1b5e 7210 break;
15b71abe 7211 case IORING_OP_OPENAT:
45d189c6 7212 ret = io_openat(req, issue_flags);
15b71abe 7213 break;
b5dba59e 7214 case IORING_OP_CLOSE:
889fca73 7215 ret = io_close(req, issue_flags);
b5dba59e 7216 break;
05f3fb3c 7217 case IORING_OP_FILES_UPDATE:
889fca73 7218 ret = io_files_update(req, issue_flags);
05f3fb3c 7219 break;
eddc7ef5 7220 case IORING_OP_STATX:
45d189c6 7221 ret = io_statx(req, issue_flags);
eddc7ef5 7222 break;
4840e418 7223 case IORING_OP_FADVISE:
45d189c6 7224 ret = io_fadvise(req, issue_flags);
4840e418 7225 break;
c1ca757b 7226 case IORING_OP_MADVISE:
45d189c6 7227 ret = io_madvise(req, issue_flags);
c1ca757b 7228 break;
cebdb986 7229 case IORING_OP_OPENAT2:
45d189c6 7230 ret = io_openat2(req, issue_flags);
cebdb986 7231 break;
3e4827b0 7232 case IORING_OP_EPOLL_CTL:
889fca73 7233 ret = io_epoll_ctl(req, issue_flags);
3e4827b0 7234 break;
7d67af2c 7235 case IORING_OP_SPLICE:
45d189c6 7236 ret = io_splice(req, issue_flags);
7d67af2c 7237 break;
ddf0322d 7238 case IORING_OP_PROVIDE_BUFFERS:
889fca73 7239 ret = io_provide_buffers(req, issue_flags);
ddf0322d 7240 break;
067524e9 7241 case IORING_OP_REMOVE_BUFFERS:
889fca73 7242 ret = io_remove_buffers(req, issue_flags);
3e4827b0 7243 break;
f2a8d5c7 7244 case IORING_OP_TEE:
45d189c6 7245 ret = io_tee(req, issue_flags);
f2a8d5c7 7246 break;
36f4fa68 7247 case IORING_OP_SHUTDOWN:
45d189c6 7248 ret = io_shutdown(req, issue_flags);
36f4fa68 7249 break;
80a261fd 7250 case IORING_OP_RENAMEAT:
45d189c6 7251 ret = io_renameat(req, issue_flags);
80a261fd 7252 break;
14a1143b 7253 case IORING_OP_UNLINKAT:
45d189c6 7254 ret = io_unlinkat(req, issue_flags);
14a1143b 7255 break;
e34a02dc
DK
7256 case IORING_OP_MKDIRAT:
7257 ret = io_mkdirat(req, issue_flags);
7258 break;
7a8721f8
DK
7259 case IORING_OP_SYMLINKAT:
7260 ret = io_symlinkat(req, issue_flags);
7261 break;
cf30da90
DK
7262 case IORING_OP_LINKAT:
7263 ret = io_linkat(req, issue_flags);
7264 break;
4f57f06c
JA
7265 case IORING_OP_MSG_RING:
7266 ret = io_msg_ring(req, issue_flags);
7267 break;
2b188cc1
JA
7268 default:
7269 ret = -EINVAL;
7270 break;
7271 }
7272
5bd2182d
PM
7273 if (!io_op_defs[req->opcode].audit_skip)
7274 audit_uring_exit(!ret, ret);
7275
5730b27e
JA
7276 if (creds)
7277 revert_creds(creds);
def596e9
JA
7278 if (ret)
7279 return ret;
b532576e 7280 /* If the op doesn't have a file, we're not polling for it */
9983028e 7281 if ((req->ctx->flags & IORING_SETUP_IOPOLL) && req->file)
9882131c 7282 io_iopoll_req_issued(req, issue_flags);
def596e9
JA
7283
7284 return 0;
2b188cc1
JA
7285}
7286
ebc11b6c
PB
7287static struct io_wq_work *io_wq_free_work(struct io_wq_work *work)
7288{
7289 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7290
7291 req = io_put_req_find_next(req);
7292 return req ? &req->work : NULL;
7293}
7294
5280f7e5 7295static void io_wq_submit_work(struct io_wq_work *work)
2b188cc1
JA
7296{
7297 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
d01905db
PB
7298 unsigned int issue_flags = IO_URING_F_UNLOCKED;
7299 bool needs_poll = false;
6df1db6b 7300 struct io_kiocb *timeout;
561fb04a 7301 int ret = 0;
2b188cc1 7302
48dcd38d
PB
7303 /* one will be dropped by ->io_free_work() after returning to io-wq */
7304 if (!(req->flags & REQ_F_REFCOUNT))
7305 __io_req_set_refcount(req, 2);
7306 else
7307 req_ref_get(req);
5d5901a3 7308
6df1db6b
PB
7309 timeout = io_prep_linked_timeout(req);
7310 if (timeout)
7311 io_queue_linked_timeout(timeout);
d4c81f38 7312
dadebc35 7313 /* either cancelled or io-wq is dying, so don't touch tctx->iowq */
d01905db
PB
7314 if (work->flags & IO_WQ_WORK_CANCEL) {
7315 io_req_task_queue_fail(req, -ECANCELED);
7316 return;
7317 }
31b51510 7318
d01905db 7319 if (req->flags & REQ_F_FORCE_ASYNC) {
afb7f56f
PB
7320 const struct io_op_def *def = &io_op_defs[req->opcode];
7321 bool opcode_poll = def->pollin || def->pollout;
7322
7323 if (opcode_poll && file_can_poll(req->file)) {
7324 needs_poll = true;
d01905db 7325 issue_flags |= IO_URING_F_NONBLOCK;
afb7f56f 7326 }
561fb04a 7327 }
31b51510 7328
d01905db
PB
7329 do {
7330 ret = io_issue_sqe(req, issue_flags);
7331 if (ret != -EAGAIN)
7332 break;
7333 /*
7334 * We can get EAGAIN for iopolled IO even though we're
7335 * forcing a sync submission from here, since we can't
7336 * wait for request slots on the block side.
7337 */
7338 if (!needs_poll) {
7339 cond_resched();
7340 continue;
90fa0288
HX
7341 }
7342
4d9237e3 7343 if (io_arm_poll_handler(req, issue_flags) == IO_APOLL_OK)
d01905db
PB
7344 return;
7345 /* aborted or ready, in either case retry blocking */
7346 needs_poll = false;
7347 issue_flags &= ~IO_URING_F_NONBLOCK;
7348 } while (1);
31b51510 7349
a3df7698 7350 /* avoid locking problems by failing it from a clean context */
5d5901a3 7351 if (ret)
a3df7698 7352 io_req_task_queue_fail(req, ret);
2b188cc1
JA
7353}
7354
aeca241b 7355static inline struct io_fixed_file *io_fixed_file_slot(struct io_file_table *table,
042b0d85 7356 unsigned i)
65e19f54 7357{
042b0d85 7358 return &table->files[i];
dafecf19
PB
7359}
7360
65e19f54
JA
7361static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
7362 int index)
7363{
aeca241b 7364 struct io_fixed_file *slot = io_fixed_file_slot(&ctx->file_table, index);
65e19f54 7365
a04b0ac0 7366 return (struct file *) (slot->file_ptr & FFS_MASK);
65e19f54
JA
7367}
7368
a04b0ac0 7369static void io_fixed_file_set(struct io_fixed_file *file_slot, struct file *file)
9a321c98
PB
7370{
7371 unsigned long file_ptr = (unsigned long) file;
7372
88459b50 7373 file_ptr |= io_file_get_flags(file);
a04b0ac0 7374 file_slot->file_ptr = file_ptr;
65e19f54
JA
7375}
7376
ac177053
PB
7377static inline struct file *io_file_get_fixed(struct io_ring_ctx *ctx,
7378 struct io_kiocb *req, int fd)
09bb8394 7379{
8da11c19 7380 struct file *file;
ac177053 7381 unsigned long file_ptr;
09bb8394 7382
ac177053
PB
7383 if (unlikely((unsigned int)fd >= ctx->nr_user_files))
7384 return NULL;
7385 fd = array_index_nospec(fd, ctx->nr_user_files);
7386 file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
7387 file = (struct file *) (file_ptr & FFS_MASK);
7388 file_ptr &= ~FFS_MASK;
7389 /* mask in overlapping REQ_F and FFS bits */
35645ac3 7390 req->flags |= (file_ptr << REQ_F_SUPPORT_NOWAIT_BIT);
a46be971 7391 io_req_set_rsrc_node(req, ctx);
ac177053
PB
7392 return file;
7393}
d44f554e 7394
ac177053 7395static struct file *io_file_get_normal(struct io_ring_ctx *ctx,
ac177053
PB
7396 struct io_kiocb *req, int fd)
7397{
62906e89 7398 struct file *file = fget(fd);
ac177053 7399
502c87d6 7400 trace_io_uring_file_get(ctx, req, req->user_data, fd);
09bb8394 7401
ac177053
PB
7402 /* we don't allow fixed io_uring files */
7403 if (file && unlikely(file->f_op == &io_uring_fops))
7404 io_req_track_inflight(req);
8371adf5 7405 return file;
09bb8394
JA
7406}
7407
ac177053 7408static inline struct file *io_file_get(struct io_ring_ctx *ctx,
ac177053
PB
7409 struct io_kiocb *req, int fd, bool fixed)
7410{
7411 if (fixed)
7412 return io_file_get_fixed(ctx, req, fd);
7413 else
62906e89 7414 return io_file_get_normal(ctx, req, fd);
ac177053
PB
7415}
7416
f237c30a 7417static void io_req_task_link_timeout(struct io_kiocb *req, bool *locked)
89b263f6
JA
7418{
7419 struct io_kiocb *prev = req->timeout.prev;
617a8948 7420 int ret = -ENOENT;
89b263f6
JA
7421
7422 if (prev) {
617a8948
PB
7423 if (!(req->task->flags & PF_EXITING))
7424 ret = io_try_cancel_userdata(req, prev->user_data);
505657bc 7425 io_req_complete_post(req, ret ?: -ETIME, 0);
89b263f6 7426 io_put_req(prev);
89b263f6
JA
7427 } else {
7428 io_req_complete_post(req, -ETIME, 0);
7429 }
7430}
7431
2665abfd 7432static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
2b188cc1 7433{
ad8a48ac
JA
7434 struct io_timeout_data *data = container_of(timer,
7435 struct io_timeout_data, timer);
90cd7e42 7436 struct io_kiocb *prev, *req = data->req;
2665abfd 7437 struct io_ring_ctx *ctx = req->ctx;
2665abfd 7438 unsigned long flags;
2665abfd 7439
89b263f6 7440 spin_lock_irqsave(&ctx->timeout_lock, flags);
90cd7e42
PB
7441 prev = req->timeout.head;
7442 req->timeout.head = NULL;
2665abfd
JA
7443
7444 /*
7445 * We don't expect the list to be empty, that will only happen if we
7446 * race with the completion of the linked work.
7447 */
447c19f3 7448 if (prev) {
f2f87370 7449 io_remove_next_linked(prev);
447c19f3
PB
7450 if (!req_ref_inc_not_zero(prev))
7451 prev = NULL;
7452 }
ef9dd637 7453 list_del(&req->timeout.list);
89b263f6
JA
7454 req->timeout.prev = prev;
7455 spin_unlock_irqrestore(&ctx->timeout_lock, flags);
2665abfd 7456
89b263f6 7457 req->io_task_work.func = io_req_task_link_timeout;
4813c377 7458 io_req_task_work_add(req, false);
2665abfd
JA
7459 return HRTIMER_NORESTART;
7460}
7461
de968c18 7462static void io_queue_linked_timeout(struct io_kiocb *req)
2665abfd 7463{
de968c18
PB
7464 struct io_ring_ctx *ctx = req->ctx;
7465
89b263f6 7466 spin_lock_irq(&ctx->timeout_lock);
76a46e06 7467 /*
f2f87370
PB
7468 * If the back reference is NULL, then our linked request finished
7469 * before we got a chance to setup the timer
76a46e06 7470 */
90cd7e42 7471 if (req->timeout.head) {
e8c2bc1f 7472 struct io_timeout_data *data = req->async_data;
94ae5e77 7473
ad8a48ac
JA
7474 data->timer.function = io_link_timeout_fn;
7475 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
7476 data->mode);
ef9dd637 7477 list_add_tail(&req->timeout.list, &ctx->ltimeout_list);
2665abfd 7478 }
89b263f6 7479 spin_unlock_irq(&ctx->timeout_lock);
2665abfd 7480 /* drop submission reference */
76a46e06
JA
7481 io_put_req(req);
7482}
2665abfd 7483
d475a9a6
PB
7484static void io_queue_sqe_arm_apoll(struct io_kiocb *req)
7485 __must_hold(&req->ctx->uring_lock)
7486{
7487 struct io_kiocb *linked_timeout = io_prep_linked_timeout(req);
7488
4d9237e3 7489 switch (io_arm_poll_handler(req, 0)) {
d475a9a6 7490 case IO_APOLL_READY:
d475a9a6
PB
7491 io_req_task_queue(req);
7492 break;
7493 case IO_APOLL_ABORTED:
7494 /*
7495 * Queued up for async execution, worker will release
7496 * submit reference when the iocb is actually submitted.
7497 */
b1c62645 7498 io_kbuf_recycle(req);
d475a9a6
PB
7499 io_queue_async_work(req, NULL);
7500 break;
b1c62645 7501 case IO_APOLL_OK:
b1c62645 7502 break;
d475a9a6
PB
7503 }
7504
7505 if (linked_timeout)
7506 io_queue_linked_timeout(linked_timeout);
7507}
7508
7509static inline void __io_queue_sqe(struct io_kiocb *req)
282cdc86 7510 __must_hold(&req->ctx->uring_lock)
2b188cc1 7511{
906c6caa 7512 struct io_kiocb *linked_timeout;
e0c5c576 7513 int ret;
2b188cc1 7514
c5eef2b9 7515 ret = io_issue_sqe(req, IO_URING_F_NONBLOCK|IO_URING_F_COMPLETE_DEFER);
193155c8 7516
fff4e40e
PB
7517 if (req->flags & REQ_F_COMPLETE_INLINE) {
7518 io_req_add_compl_list(req);
d9f9d284 7519 return;
fff4e40e 7520 }
491381ce
JA
7521 /*
7522 * We async punt it if the file wasn't marked NOWAIT, or if the file
7523 * doesn't support non-blocking read/write attempts
7524 */
1840038e 7525 if (likely(!ret)) {
906c6caa
PB
7526 linked_timeout = io_prep_linked_timeout(req);
7527 if (linked_timeout)
7528 io_queue_linked_timeout(linked_timeout);
1840038e 7529 } else if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
d475a9a6 7530 io_queue_sqe_arm_apoll(req);
0d63c148 7531 } else {
f41db273 7532 io_req_complete_failed(req, ret);
9e645e11 7533 }
2b188cc1
JA
7534}
7535
4652fe3f 7536static void io_queue_sqe_fallback(struct io_kiocb *req)
282cdc86 7537 __must_hold(&req->ctx->uring_lock)
4fe2c963 7538{
4652fe3f 7539 if (req->flags & REQ_F_FAIL) {
c6d3d9cb 7540 io_req_complete_fail_submit(req);
e0eb71dc
PB
7541 } else if (unlikely(req->ctx->drain_active)) {
7542 io_drain_req(req);
76cc33d7
PB
7543 } else {
7544 int ret = io_req_prep_async(req);
7545
7546 if (unlikely(ret))
7547 io_req_complete_failed(req, ret);
7548 else
f237c30a 7549 io_queue_async_work(req, NULL);
ce35a47a 7550 }
4fe2c963
JL
7551}
7552
4652fe3f
PB
7553static inline void io_queue_sqe(struct io_kiocb *req)
7554 __must_hold(&req->ctx->uring_lock)
7555{
7556 if (likely(!(req->flags & (REQ_F_FORCE_ASYNC | REQ_F_FAIL))))
7557 __io_queue_sqe(req);
7558 else
7559 io_queue_sqe_fallback(req);
7560}
7561
b16fed66
PB
7562/*
7563 * Check SQE restrictions (opcode and flags).
7564 *
7565 * Returns 'true' if SQE is allowed, 'false' otherwise.
7566 */
7567static inline bool io_check_restriction(struct io_ring_ctx *ctx,
7568 struct io_kiocb *req,
7569 unsigned int sqe_flags)
4fe2c963 7570{
b16fed66
PB
7571 if (!test_bit(req->opcode, ctx->restrictions.sqe_op))
7572 return false;
7573
7574 if ((sqe_flags & ctx->restrictions.sqe_flags_required) !=
7575 ctx->restrictions.sqe_flags_required)
7576 return false;
7577
7578 if (sqe_flags & ~(ctx->restrictions.sqe_flags_allowed |
7579 ctx->restrictions.sqe_flags_required))
7580 return false;
7581
7582 return true;
4fe2c963
JL
7583}
7584
22b2ca31
PB
7585static void io_init_req_drain(struct io_kiocb *req)
7586{
7587 struct io_ring_ctx *ctx = req->ctx;
7588 struct io_kiocb *head = ctx->submit_state.link.head;
7589
7590 ctx->drain_active = true;
7591 if (head) {
7592 /*
7593 * If we need to drain a request in the middle of a link, drain
7594 * the head request and the next request/link after the current
7595 * link. Considering sequential execution of links,
b6c7db32 7596 * REQ_F_IO_DRAIN will be maintained for every request of our
22b2ca31
PB
7597 * link.
7598 */
b6c7db32 7599 head->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
22b2ca31
PB
7600 ctx->drain_next = true;
7601 }
7602}
7603
b16fed66
PB
7604static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
7605 const struct io_uring_sqe *sqe)
282cdc86 7606 __must_hold(&ctx->uring_lock)
b16fed66 7607{
b16fed66 7608 unsigned int sqe_flags;
fc0ae024 7609 int personality;
4a04d1d1 7610 u8 opcode;
b16fed66 7611
864ea921 7612 /* req is partially pre-initialised, see io_preinit_req() */
4a04d1d1 7613 req->opcode = opcode = READ_ONCE(sqe->opcode);
b16fed66
PB
7614 /* same numerical values with corresponding REQ_F_*, safe to copy */
7615 req->flags = sqe_flags = READ_ONCE(sqe->flags);
7616 req->user_data = READ_ONCE(sqe->user_data);
b16fed66 7617 req->file = NULL;
b16fed66 7618 req->fixed_rsrc_refs = NULL;
b16fed66 7619 req->task = current;
b16fed66 7620
4a04d1d1
PB
7621 if (unlikely(opcode >= IORING_OP_LAST)) {
7622 req->opcode = 0;
b16fed66 7623 return -EINVAL;
4a04d1d1 7624 }
68fe256a
PB
7625 if (unlikely(sqe_flags & ~SQE_COMMON_FLAGS)) {
7626 /* enforce forwards compatibility on users */
7627 if (sqe_flags & ~SQE_VALID_FLAGS)
7628 return -EINVAL;
7629 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
4a04d1d1 7630 !io_op_defs[opcode].buffer_select)
68fe256a 7631 return -EOPNOTSUPP;
5562a8d7
PB
7632 if (sqe_flags & IOSQE_CQE_SKIP_SUCCESS)
7633 ctx->drain_disabled = true;
7634 if (sqe_flags & IOSQE_IO_DRAIN) {
7635 if (ctx->drain_disabled)
7636 return -EOPNOTSUPP;
22b2ca31 7637 io_init_req_drain(req);
5562a8d7 7638 }
2a56a9bd
PB
7639 }
7640 if (unlikely(ctx->restricted || ctx->drain_active || ctx->drain_next)) {
7641 if (ctx->restricted && !io_check_restriction(ctx, req, sqe_flags))
7642 return -EACCES;
7643 /* knock it to the slow queue path, will be drained there */
7644 if (ctx->drain_active)
7645 req->flags |= REQ_F_FORCE_ASYNC;
7646 /* if there is no link, we're at "next" request and need to drain */
7647 if (unlikely(ctx->drain_next) && !ctx->submit_state.link.head) {
7648 ctx->drain_next = false;
7649 ctx->drain_active = true;
b6c7db32 7650 req->flags |= REQ_F_IO_DRAIN | REQ_F_FORCE_ASYNC;
2a56a9bd 7651 }
68fe256a 7652 }
b16fed66 7653
4a04d1d1 7654 if (io_op_defs[opcode].needs_file) {
6d63416d
PB
7655 struct io_submit_state *state = &ctx->submit_state;
7656
7657 /*
7658 * Plug now if we have more than 2 IO left after this, and the
7659 * target is potentially a read/write to block based storage.
7660 */
4a04d1d1 7661 if (state->need_plug && io_op_defs[opcode].plug) {
6d63416d
PB
7662 state->plug_started = true;
7663 state->need_plug = false;
5ca7a8b3 7664 blk_start_plug_nr_ios(&state->plug, state->submit_nr);
6d63416d
PB
7665 }
7666
62906e89 7667 req->file = io_file_get(ctx, req, READ_ONCE(sqe->fd),
ac177053 7668 (sqe_flags & IOSQE_FIXED_FILE));
b16fed66 7669 if (unlikely(!req->file))
fc0ae024 7670 return -EBADF;
b16fed66 7671 }
863e0560 7672
003e8dcc
JA
7673 personality = READ_ONCE(sqe->personality);
7674 if (personality) {
cdab10bf
LT
7675 int ret;
7676
c10d1f98
PB
7677 req->creds = xa_load(&ctx->personalities, personality);
7678 if (!req->creds)
003e8dcc 7679 return -EINVAL;
c10d1f98 7680 get_cred(req->creds);
cdc1404a
PM
7681 ret = security_uring_override_creds(req->creds);
7682 if (ret) {
7683 put_cred(req->creds);
7684 return ret;
7685 }
b8e64b53 7686 req->flags |= REQ_F_CREDS;
003e8dcc 7687 }
b16fed66 7688
fc0ae024 7689 return io_req_prep(req, sqe);
b16fed66
PB
7690}
7691
a6b8cadc 7692static int io_submit_sqe(struct io_ring_ctx *ctx, struct io_kiocb *req,
a1ab7b35 7693 const struct io_uring_sqe *sqe)
282cdc86 7694 __must_hold(&ctx->uring_lock)
9e645e11 7695{
a1ab7b35 7696 struct io_submit_link *link = &ctx->submit_state.link;
ef4ff581 7697 int ret;
9e645e11 7698
a6b8cadc
PB
7699 ret = io_init_req(ctx, req, sqe);
7700 if (unlikely(ret)) {
502c87d6 7701 trace_io_uring_req_failed(sqe, ctx, req, ret);
a87acfde 7702
a8295b98 7703 /* fail even hard links since we don't submit */
de59bc10 7704 if (link->head) {
a8295b98
HX
7705 /*
7706 * we can judge a link req is failed or cancelled by if
7707 * REQ_F_FAIL is set, but the head is an exception since
7708 * it may be set REQ_F_FAIL because of other req's failure
7709 * so let's leverage req->result to distinguish if a head
7710 * is set REQ_F_FAIL because of its failure or other req's
7711 * failure so that we can set the correct ret code for it.
7712 * init result here to avoid affecting the normal path.
7713 */
7714 if (!(link->head->flags & REQ_F_FAIL))
7715 req_fail_link_node(link->head, -ECANCELED);
7716 } else if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
7717 /*
7718 * the current req is a normal req, we should return
7719 * error and thus break the submittion loop.
7720 */
7721 io_req_complete_failed(req, ret);
7722 return ret;
de59bc10 7723 }
a8295b98 7724 req_fail_link_node(req, ret);
a6b8cadc 7725 }
441b8a78 7726
be7053b7 7727 /* don't need @sqe from now on */
502c87d6 7728 trace_io_uring_submit_sqe(ctx, req, req->user_data, req->opcode,
236daeae
OL
7729 req->flags, true,
7730 ctx->flags & IORING_SETUP_SQPOLL);
a6b8cadc 7731
9e645e11
JA
7732 /*
7733 * If we already have a head request, queue this one for async
7734 * submittal once the head completes. If we don't have a head but
7735 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
7736 * submitted sync once the chain is complete. If none of those
7737 * conditions are true (normal request), then just queue it.
7738 */
863e0560
PB
7739 if (link->head) {
7740 struct io_kiocb *head = link->head;
4e88d6e7 7741
a8295b98
HX
7742 if (!(req->flags & REQ_F_FAIL)) {
7743 ret = io_req_prep_async(req);
7744 if (unlikely(ret)) {
7745 req_fail_link_node(req, ret);
7746 if (!(head->flags & REQ_F_FAIL))
7747 req_fail_link_node(head, -ECANCELED);
7748 }
7749 }
9d76377f 7750 trace_io_uring_link(ctx, req, head);
f2f87370 7751 link->last->link = req;
863e0560 7752 link->last = req;
32fe525b 7753
f15a3431
PB
7754 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK))
7755 return 0;
32fe525b 7756 /* last request of a link, enqueue the link */
f15a3431
PB
7757 link->head = NULL;
7758 req = head;
7759 } else if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
7760 link->head = req;
7761 link->last = req;
7762 return 0;
9e645e11 7763 }
2e6e1fde 7764
f15a3431 7765 io_queue_sqe(req);
1d4240cc 7766 return 0;
9e645e11
JA
7767}
7768
9a56a232
JA
7769/*
7770 * Batched submission is done, ensure local IO is flushed out.
7771 */
553deffd 7772static void io_submit_state_end(struct io_ring_ctx *ctx)
9a56a232 7773{
553deffd
PB
7774 struct io_submit_state *state = &ctx->submit_state;
7775
a1ab7b35 7776 if (state->link.head)
de59bc10 7777 io_queue_sqe(state->link.head);
553deffd 7778 /* flush only after queuing links as they can generate completions */
c450178d 7779 io_submit_flush_completions(ctx);
27926b68
JA
7780 if (state->plug_started)
7781 blk_finish_plug(&state->plug);
9a56a232
JA
7782}
7783
7784/*
7785 * Start submission side cache.
7786 */
7787static void io_submit_state_start(struct io_submit_state *state,
ba88ff11 7788 unsigned int max_ios)
9a56a232 7789{
27926b68 7790 state->plug_started = false;
4b628aeb 7791 state->need_plug = max_ios > 2;
5ca7a8b3 7792 state->submit_nr = max_ios;
a1ab7b35
PB
7793 /* set only head, no need to init link_last in advance */
7794 state->link.head = NULL;
9a56a232
JA
7795}
7796
2b188cc1
JA
7797static void io_commit_sqring(struct io_ring_ctx *ctx)
7798{
75b28aff 7799 struct io_rings *rings = ctx->rings;
2b188cc1 7800
caf582c6
PB
7801 /*
7802 * Ensure any loads from the SQEs are done at this point,
7803 * since once we write the new head, the application could
7804 * write new data to them.
7805 */
7806 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
2b188cc1
JA
7807}
7808
2b188cc1 7809/*
dd9ae8a0 7810 * Fetch an sqe, if one is available. Note this returns a pointer to memory
2b188cc1
JA
7811 * that is mapped by userspace. This means that care needs to be taken to
7812 * ensure that reads are stable, as we cannot rely on userspace always
7813 * being a good citizen. If members of the sqe are validated and then later
7814 * used, it's important that those reads are done through READ_ONCE() to
7815 * prevent a re-load down the line.
7816 */
709b302f 7817static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
2b188cc1 7818{
ea5ab3b5 7819 unsigned head, mask = ctx->sq_entries - 1;
17d3aeb3 7820 unsigned sq_idx = ctx->cached_sq_head++ & mask;
2b188cc1
JA
7821
7822 /*
7823 * The cached sq head (or cq tail) serves two purposes:
7824 *
7825 * 1) allows us to batch the cost of updating the user visible
7826 * head updates.
7827 * 2) allows the kernel side to track the head on its own, even
7828 * though the application is the one updating it.
7829 */
17d3aeb3 7830 head = READ_ONCE(ctx->sq_array[sq_idx]);
709b302f
PB
7831 if (likely(head < ctx->sq_entries))
7832 return &ctx->sq_sqes[head];
2b188cc1
JA
7833
7834 /* drop invalid entries */
15641e42
PB
7835 ctx->cq_extra--;
7836 WRITE_ONCE(ctx->rings->sq_dropped,
7837 READ_ONCE(ctx->rings->sq_dropped) + 1);
709b302f
PB
7838 return NULL;
7839}
7840
0f212204 7841static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr)
282cdc86 7842 __must_hold(&ctx->uring_lock)
6c271ce2 7843{
69629809 7844 unsigned int entries = io_sqring_entries(ctx);
46c4e16a 7845 int submitted = 0;
6c271ce2 7846
51d48dab 7847 if (unlikely(!entries))
69629809 7848 return 0;
ee7d46d9 7849 /* make sure SQ entry isn't read before tail */
69629809 7850 nr = min3(nr, ctx->sq_entries, entries);
9a10867a 7851 io_get_task_refs(nr);
6c271ce2 7852
ba88ff11 7853 io_submit_state_start(&ctx->submit_state, nr);
69629809 7854 do {
3529d8c2 7855 const struct io_uring_sqe *sqe;
196be95c 7856 struct io_kiocb *req;
fb5ccc98 7857
a33ae9ce 7858 if (unlikely(!io_alloc_req_refill(ctx))) {
196be95c
PB
7859 if (!submitted)
7860 submitted = -EAGAIN;
fb5ccc98 7861 break;
196be95c 7862 }
a33ae9ce 7863 req = io_alloc_req(ctx);
4fccfcbb
PB
7864 sqe = io_get_sqe(ctx);
7865 if (unlikely(!sqe)) {
c2b6c6bc 7866 wq_stack_add_head(&req->comp_list, &ctx->submit_state.free_list);
4fccfcbb
PB
7867 break;
7868 }
d3656344
JA
7869 /* will complete beyond this point, count as submitted */
7870 submitted++;
bcbb7bf6
JA
7871 if (io_submit_sqe(ctx, req, sqe)) {
7872 /*
7873 * Continue submitting even for sqe failure if the
7874 * ring was setup with IORING_SETUP_SUBMIT_ALL
7875 */
7876 if (!(ctx->flags & IORING_SETUP_SUBMIT_ALL))
7877 break;
7878 }
69629809 7879 } while (submitted < nr);
6c271ce2 7880
9466f437
PB
7881 if (unlikely(submitted != nr)) {
7882 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
d8a6df10 7883 int unused = nr - ref_used;
9466f437 7884
09899b19 7885 current->io_uring->cached_refs += unused;
9466f437 7886 }
6c271ce2 7887
553deffd 7888 io_submit_state_end(ctx);
ae9428ca
PB
7889 /* Commit SQ ring head once we've consumed and submitted all SQEs */
7890 io_commit_sqring(ctx);
7891
6c271ce2
JA
7892 return submitted;
7893}
7894
e4b6d902
PB
7895static inline bool io_sqd_events_pending(struct io_sq_data *sqd)
7896{
7897 return READ_ONCE(sqd->state);
7898}
7899
23b3628e
XW
7900static inline void io_ring_set_wakeup_flag(struct io_ring_ctx *ctx)
7901{
7902 /* Tell userspace we may need a wakeup call */
79ebeaee 7903 spin_lock(&ctx->completion_lock);
20c0b380
NA
7904 WRITE_ONCE(ctx->rings->sq_flags,
7905 ctx->rings->sq_flags | IORING_SQ_NEED_WAKEUP);
79ebeaee 7906 spin_unlock(&ctx->completion_lock);
23b3628e
XW
7907}
7908
7909static inline void io_ring_clear_wakeup_flag(struct io_ring_ctx *ctx)
7910{
79ebeaee 7911 spin_lock(&ctx->completion_lock);
20c0b380
NA
7912 WRITE_ONCE(ctx->rings->sq_flags,
7913 ctx->rings->sq_flags & ~IORING_SQ_NEED_WAKEUP);
79ebeaee 7914 spin_unlock(&ctx->completion_lock);
23b3628e
XW
7915}
7916
08369246 7917static int __io_sq_thread(struct io_ring_ctx *ctx, bool cap_entries)
6c271ce2 7918{
c8d1ba58 7919 unsigned int to_submit;
bdcd3eab 7920 int ret = 0;
6c271ce2 7921
c8d1ba58 7922 to_submit = io_sqring_entries(ctx);
e95eee2d 7923 /* if we're handling multiple rings, cap submit size for fairness */
4ce8ad95
OL
7924 if (cap_entries && to_submit > IORING_SQPOLL_CAP_ENTRIES_VALUE)
7925 to_submit = IORING_SQPOLL_CAP_ENTRIES_VALUE;
e95eee2d 7926
5eef4e87 7927 if (!wq_list_empty(&ctx->iopoll_list) || to_submit) {
948e1947
PB
7928 const struct cred *creds = NULL;
7929
7930 if (ctx->sq_creds != current_cred())
7931 creds = override_creds(ctx->sq_creds);
a4c0b3de 7932
c8d1ba58 7933 mutex_lock(&ctx->uring_lock);
5eef4e87 7934 if (!wq_list_empty(&ctx->iopoll_list))
5ba3c874 7935 io_do_iopoll(ctx, true);
906a3c6f 7936
3b763ba1
PB
7937 /*
7938 * Don't submit if refs are dying, good for io_uring_register(),
7939 * but also it is relied upon by io_ring_exit_work()
7940 */
0298ef96
PB
7941 if (to_submit && likely(!percpu_ref_is_dying(&ctx->refs)) &&
7942 !(ctx->flags & IORING_SETUP_R_DISABLED))
08369246 7943 ret = io_submit_sqes(ctx, to_submit);
c8d1ba58 7944 mutex_unlock(&ctx->uring_lock);
adc8682e
OL
7945#ifdef CONFIG_NET_RX_BUSY_POLL
7946 spin_lock(&ctx->napi_lock);
7947 if (!list_empty(&ctx->napi_list) &&
7948 io_napi_busy_loop(&ctx->napi_list))
7949 ++ret;
7950 spin_unlock(&ctx->napi_lock);
7951#endif
acfb381d
PB
7952 if (to_submit && wq_has_sleeper(&ctx->sqo_sq_wait))
7953 wake_up(&ctx->sqo_sq_wait);
948e1947
PB
7954 if (creds)
7955 revert_creds(creds);
acfb381d 7956 }
6c271ce2 7957
08369246
XW
7958 return ret;
7959}
6c271ce2 7960
c072481d 7961static __cold void io_sqd_update_thread_idle(struct io_sq_data *sqd)
08369246
XW
7962{
7963 struct io_ring_ctx *ctx;
7964 unsigned sq_thread_idle = 0;
6c271ce2 7965
c9dca27d
PB
7966 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
7967 sq_thread_idle = max(sq_thread_idle, ctx->sq_thread_idle);
08369246 7968 sqd->sq_thread_idle = sq_thread_idle;
c8d1ba58 7969}
6c271ce2 7970
e4b6d902
PB
7971static bool io_sqd_handle_event(struct io_sq_data *sqd)
7972{
7973 bool did_sig = false;
7974 struct ksignal ksig;
7975
7976 if (test_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state) ||
7977 signal_pending(current)) {
7978 mutex_unlock(&sqd->lock);
7979 if (signal_pending(current))
7980 did_sig = get_signal(&ksig);
7981 cond_resched();
7982 mutex_lock(&sqd->lock);
7983 }
e4b6d902
PB
7984 return did_sig || test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
7985}
7986
c8d1ba58
JA
7987static int io_sq_thread(void *data)
7988{
69fb2131
JA
7989 struct io_sq_data *sqd = data;
7990 struct io_ring_ctx *ctx;
a0d9205f 7991 unsigned long timeout = 0;
37d1e2e3 7992 char buf[TASK_COMM_LEN];
08369246 7993 DEFINE_WAIT(wait);
6c271ce2 7994
696ee88a 7995 snprintf(buf, sizeof(buf), "iou-sqp-%d", sqd->task_pid);
37d1e2e3 7996 set_task_comm(current, buf);
37d1e2e3
JA
7997
7998 if (sqd->sq_cpu != -1)
7999 set_cpus_allowed_ptr(current, cpumask_of(sqd->sq_cpu));
8000 else
8001 set_cpus_allowed_ptr(current, cpu_online_mask);
8002 current->flags |= PF_NO_SETAFFINITY;
8003
5bd2182d
PM
8004 audit_alloc_kernel(current);
8005
09a6f4ef 8006 mutex_lock(&sqd->lock);
e4b6d902 8007 while (1) {
1a924a80 8008 bool cap_entries, sqt_spin = false;
c1edbf5f 8009
e4b6d902
PB
8010 if (io_sqd_events_pending(sqd) || signal_pending(current)) {
8011 if (io_sqd_handle_event(sqd))
c7d95613 8012 break;
08369246
XW
8013 timeout = jiffies + sqd->sq_thread_idle;
8014 }
e4b6d902 8015
e95eee2d 8016 cap_entries = !list_is_singular(&sqd->ctx_list);
69fb2131 8017 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
948e1947 8018 int ret = __io_sq_thread(ctx, cap_entries);
7c30f36a 8019
5eef4e87 8020 if (!sqt_spin && (ret > 0 || !wq_list_empty(&ctx->iopoll_list)))
08369246 8021 sqt_spin = true;
69fb2131 8022 }
dd432ea5
PB
8023 if (io_run_task_work())
8024 sqt_spin = true;
6c271ce2 8025
08369246 8026 if (sqt_spin || !time_after(jiffies, timeout)) {
c8d1ba58 8027 cond_resched();
08369246
XW
8028 if (sqt_spin)
8029 timeout = jiffies + sqd->sq_thread_idle;
8030 continue;
8031 }
8032
08369246 8033 prepare_to_wait(&sqd->wait, &wait, TASK_INTERRUPTIBLE);
dd432ea5 8034 if (!io_sqd_events_pending(sqd) && !current->task_works) {
1a924a80
PB
8035 bool needs_sched = true;
8036
724cb4f9 8037 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list) {
aaa9f0f4
PB
8038 io_ring_set_wakeup_flag(ctx);
8039
724cb4f9 8040 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
5eef4e87 8041 !wq_list_empty(&ctx->iopoll_list)) {
724cb4f9
HX
8042 needs_sched = false;
8043 break;
8044 }
8045 if (io_sqring_entries(ctx)) {
8046 needs_sched = false;
8047 break;
8048 }
8049 }
8050
8051 if (needs_sched) {
8052 mutex_unlock(&sqd->lock);
8053 schedule();
8054 mutex_lock(&sqd->lock);
8055 }
69fb2131
JA
8056 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
8057 io_ring_clear_wakeup_flag(ctx);
6c271ce2 8058 }
08369246
XW
8059
8060 finish_wait(&sqd->wait, &wait);
8061 timeout = jiffies + sqd->sq_thread_idle;
6c271ce2 8062 }
28cea78a 8063
78cc687b 8064 io_uring_cancel_generic(true, sqd);
37d1e2e3 8065 sqd->thread = NULL;
05962f95 8066 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
5f3f26f9 8067 io_ring_set_wakeup_flag(ctx);
521d6a73 8068 io_run_task_work();
734551df
PB
8069 mutex_unlock(&sqd->lock);
8070
5bd2182d
PM
8071 audit_free(current);
8072
37d1e2e3
JA
8073 complete(&sqd->exited);
8074 do_exit(0);
6c271ce2
JA
8075}
8076
bda52162
JA
8077struct io_wait_queue {
8078 struct wait_queue_entry wq;
8079 struct io_ring_ctx *ctx;
5fd46178 8080 unsigned cq_tail;
bda52162 8081 unsigned nr_timeouts;
adc8682e
OL
8082#ifdef CONFIG_NET_RX_BUSY_POLL
8083 unsigned busy_poll_to;
8084#endif
bda52162
JA
8085};
8086
6c503150 8087static inline bool io_should_wake(struct io_wait_queue *iowq)
bda52162
JA
8088{
8089 struct io_ring_ctx *ctx = iowq->ctx;
5fd46178 8090 int dist = ctx->cached_cq_tail - (int) iowq->cq_tail;
bda52162
JA
8091
8092 /*
d195a66e 8093 * Wake up if we have enough events, or if a timeout occurred since we
bda52162
JA
8094 * started waiting. For timeouts, we always want to return to userspace,
8095 * regardless of event count.
8096 */
5fd46178 8097 return dist >= 0 || atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
bda52162
JA
8098}
8099
8100static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
8101 int wake_flags, void *key)
8102{
8103 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
8104 wq);
8105
6c503150
PB
8106 /*
8107 * Cannot safely flush overflowed CQEs from here, ensure we wake up
8108 * the task, and the next invocation will do it.
8109 */
5ed7a37d 8110 if (io_should_wake(iowq) || test_bit(0, &iowq->ctx->check_cq_overflow))
6c503150
PB
8111 return autoremove_wake_function(curr, mode, wake_flags, key);
8112 return -1;
bda52162
JA
8113}
8114
af9c1a44
JA
8115static int io_run_task_work_sig(void)
8116{
8117 if (io_run_task_work())
8118 return 1;
0b8cfa97 8119 if (test_thread_flag(TIF_NOTIFY_SIGNAL))
792ee0f6 8120 return -ERESTARTSYS;
c5020bc8
OL
8121 if (task_sigpending(current))
8122 return -EINTR;
8123 return 0;
af9c1a44
JA
8124}
8125
eeb60b9a
PB
8126/* when returns >0, the caller should retry */
8127static inline int io_cqring_wait_schedule(struct io_ring_ctx *ctx,
8128 struct io_wait_queue *iowq,
22833966 8129 ktime_t timeout)
eeb60b9a
PB
8130{
8131 int ret;
8132
8133 /* make sure we run task_work before checking for signals */
8134 ret = io_run_task_work_sig();
8135 if (ret || io_should_wake(iowq))
8136 return ret;
8137 /* let the caller flush overflows, retry */
5ed7a37d 8138 if (test_bit(0, &ctx->check_cq_overflow))
eeb60b9a
PB
8139 return 1;
8140
22833966
JA
8141 if (!schedule_hrtimeout(&timeout, HRTIMER_MODE_ABS))
8142 return -ETIME;
8143 return 1;
eeb60b9a
PB
8144}
8145
adc8682e
OL
8146#ifdef CONFIG_NET_RX_BUSY_POLL
8147static void io_adjust_busy_loop_timeout(struct timespec64 *ts,
8148 struct io_wait_queue *iowq)
8149{
8150 unsigned busy_poll_to = READ_ONCE(sysctl_net_busy_poll);
8151 struct timespec64 pollto = ns_to_timespec64(1000 * (s64)busy_poll_to);
8152
8153 if (timespec64_compare(ts, &pollto) > 0) {
8154 *ts = timespec64_sub(*ts, pollto);
8155 iowq->busy_poll_to = busy_poll_to;
8156 } else {
8157 u64 to = timespec64_to_ns(ts);
8158
8159 do_div(to, 1000);
8160 iowq->busy_poll_to = to;
8161 ts->tv_sec = 0;
8162 ts->tv_nsec = 0;
8163 }
8164}
8165
8166static inline bool io_busy_loop_timeout(unsigned long start_time,
8167 unsigned long bp_usec)
8168{
8169 if (bp_usec) {
8170 unsigned long end_time = start_time + bp_usec;
8171 unsigned long now = busy_loop_current_time();
8172
8173 return time_after(now, end_time);
8174 }
8175 return true;
8176}
8177
8178static bool io_busy_loop_end(void *p, unsigned long start_time)
8179{
8180 struct io_wait_queue *iowq = p;
8181
8182 return signal_pending(current) ||
8183 io_should_wake(iowq) ||
8184 io_busy_loop_timeout(start_time, iowq->busy_poll_to);
8185}
8186
8187static void io_blocking_napi_busy_loop(struct list_head *napi_list,
8188 struct io_wait_queue *iowq)
8189{
8190 unsigned long start_time =
8191 list_is_singular(napi_list) ? 0 :
8192 busy_loop_current_time();
8193
8194 do {
8195 if (list_is_singular(napi_list)) {
8196 struct napi_entry *ne =
8197 list_first_entry(napi_list,
8198 struct napi_entry, list);
8199
8200 napi_busy_loop(ne->napi_id, io_busy_loop_end, iowq,
8201 true, BUSY_POLL_BUDGET);
8202 io_check_napi_entry_timeout(ne);
8203 break;
8204 }
8205 } while (io_napi_busy_loop(napi_list) &&
8206 !io_busy_loop_end(iowq, start_time));
8207}
8208
8209static void io_putback_napi_list(struct io_ring_ctx *ctx,
8210 struct list_head *napi_list)
8211{
8212 struct napi_entry *cne, *lne;
8213
8214 spin_lock(&ctx->napi_lock);
8215 list_for_each_entry(cne, &ctx->napi_list, list)
8216 list_for_each_entry(lne, napi_list, list)
8217 if (cne->napi_id == lne->napi_id) {
8218 list_del(&lne->list);
8219 kfree(lne);
8220 break;
8221 }
8222 list_splice(napi_list, &ctx->napi_list);
8223 spin_unlock(&ctx->napi_lock);
8224}
8225#endif /* CONFIG_NET_RX_BUSY_POLL */
8226
2b188cc1
JA
8227/*
8228 * Wait until events become available, if we don't already have some. The
8229 * application must reap them itself, as they reside on the shared cq ring.
8230 */
8231static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
c73ebb68
HX
8232 const sigset_t __user *sig, size_t sigsz,
8233 struct __kernel_timespec __user *uts)
2b188cc1 8234{
90291099 8235 struct io_wait_queue iowq;
75b28aff 8236 struct io_rings *rings = ctx->rings;
22833966 8237 ktime_t timeout = KTIME_MAX;
c1d5a224 8238 int ret;
adc8682e
OL
8239#ifdef CONFIG_NET_RX_BUSY_POLL
8240 LIST_HEAD(local_napi_list);
8241#endif
2b188cc1 8242
b41e9852 8243 do {
90f67366 8244 io_cqring_overflow_flush(ctx);
6c503150 8245 if (io_cqring_events(ctx) >= min_events)
b41e9852 8246 return 0;
4c6e277c 8247 if (!io_run_task_work())
b41e9852 8248 break;
b41e9852 8249 } while (1);
2b188cc1
JA
8250
8251 if (sig) {
9e75ad5d
AB
8252#ifdef CONFIG_COMPAT
8253 if (in_compat_syscall())
8254 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
b772434b 8255 sigsz);
9e75ad5d
AB
8256 else
8257#endif
b772434b 8258 ret = set_user_sigmask(sig, sigsz);
9e75ad5d 8259
2b188cc1
JA
8260 if (ret)
8261 return ret;
8262 }
8263
adc8682e
OL
8264#ifdef CONFIG_NET_RX_BUSY_POLL
8265 iowq.busy_poll_to = 0;
8266 if (!(ctx->flags & IORING_SETUP_SQPOLL)) {
8267 spin_lock(&ctx->napi_lock);
8268 list_splice_init(&ctx->napi_list, &local_napi_list);
8269 spin_unlock(&ctx->napi_lock);
8270 }
8271#endif
950e79dd
OL
8272 if (uts) {
8273 struct timespec64 ts;
8274
8275 if (get_timespec64(&ts, uts))
8276 return -EFAULT;
adc8682e
OL
8277#ifdef CONFIG_NET_RX_BUSY_POLL
8278 if (!list_empty(&local_napi_list))
8279 io_adjust_busy_loop_timeout(&ts, &iowq);
8280#endif
950e79dd
OL
8281 timeout = ktime_add_ns(timespec64_to_ktime(ts), ktime_get_ns());
8282 }
adc8682e
OL
8283#ifdef CONFIG_NET_RX_BUSY_POLL
8284 else if (!list_empty(&local_napi_list))
8285 iowq.busy_poll_to = READ_ONCE(sysctl_net_busy_poll);
8286#endif
950e79dd 8287
90291099
PB
8288 init_waitqueue_func_entry(&iowq.wq, io_wake_function);
8289 iowq.wq.private = current;
8290 INIT_LIST_HEAD(&iowq.wq.entry);
8291 iowq.ctx = ctx;
bda52162 8292 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
5fd46178 8293 iowq.cq_tail = READ_ONCE(ctx->rings->cq.head) + min_events;
90291099 8294
c826bd7a 8295 trace_io_uring_cqring_wait(ctx, min_events);
adc8682e
OL
8296#ifdef CONFIG_NET_RX_BUSY_POLL
8297 if (iowq.busy_poll_to)
8298 io_blocking_napi_busy_loop(&local_napi_list, &iowq);
8299 if (!list_empty(&local_napi_list))
8300 io_putback_napi_list(ctx, &local_napi_list);
8301#endif
bda52162 8302 do {
ca0a2651 8303 /* if we can't even flush overflow, don't wait for more */
90f67366 8304 if (!io_cqring_overflow_flush(ctx)) {
ca0a2651
JA
8305 ret = -EBUSY;
8306 break;
8307 }
311997b3 8308 prepare_to_wait_exclusive(&ctx->cq_wait, &iowq.wq,
bda52162 8309 TASK_INTERRUPTIBLE);
22833966 8310 ret = io_cqring_wait_schedule(ctx, &iowq, timeout);
311997b3 8311 finish_wait(&ctx->cq_wait, &iowq.wq);
ca0a2651 8312 cond_resched();
eeb60b9a 8313 } while (ret > 0);
bda52162 8314
b7db41c9 8315 restore_saved_sigmask_unless(ret == -EINTR);
2b188cc1 8316
75b28aff 8317 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
2b188cc1
JA
8318}
8319
9123c8ff 8320static void io_free_page_table(void **table, size_t size)
05f3fb3c 8321{
9123c8ff 8322 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
05f3fb3c 8323
846a4ef2 8324 for (i = 0; i < nr_tables; i++)
9123c8ff
PB
8325 kfree(table[i]);
8326 kfree(table);
8327}
8328
c072481d 8329static __cold void **io_alloc_page_table(size_t size)
9123c8ff
PB
8330{
8331 unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
8332 size_t init_size = size;
8333 void **table;
8334
0bea96f5 8335 table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
9123c8ff
PB
8336 if (!table)
8337 return NULL;
8338
8339 for (i = 0; i < nr_tables; i++) {
27f6b318 8340 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
9123c8ff 8341
0bea96f5 8342 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
9123c8ff
PB
8343 if (!table[i]) {
8344 io_free_page_table(table, init_size);
8345 return NULL;
8346 }
8347 size -= this_size;
8348 }
8349 return table;
05f3fb3c
JA
8350}
8351
28a9fe25 8352static void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
1642b445 8353{
28a9fe25
PB
8354 percpu_ref_exit(&ref_node->refs);
8355 kfree(ref_node);
1642b445
PB
8356}
8357
c072481d 8358static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
b9bd2bea
PB
8359{
8360 struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
8361 struct io_ring_ctx *ctx = node->rsrc_data->ctx;
8362 unsigned long flags;
8363 bool first_add = false;
b36a2050 8364 unsigned long delay = HZ;
b9bd2bea
PB
8365
8366 spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
8367 node->done = true;
8368
b36a2050
DY
8369 /* if we are mid-quiesce then do not delay */
8370 if (node->rsrc_data->quiesce)
8371 delay = 0;
8372
b9bd2bea
PB
8373 while (!list_empty(&ctx->rsrc_ref_list)) {
8374 node = list_first_entry(&ctx->rsrc_ref_list,
8375 struct io_rsrc_node, node);
8376 /* recycle ref nodes in order */
8377 if (!node->done)
8378 break;
8379 list_del(&node->node);
8380 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
8381 }
8382 spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
8383
8384 if (first_add)
b36a2050 8385 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
b9bd2bea
PB
8386}
8387
f6133fbd 8388static struct io_rsrc_node *io_rsrc_node_alloc(void)
b9bd2bea
PB
8389{
8390 struct io_rsrc_node *ref_node;
8391
8392 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
8393 if (!ref_node)
8394 return NULL;
8395
8396 if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
8397 0, GFP_KERNEL)) {
8398 kfree(ref_node);
8399 return NULL;
8400 }
8401 INIT_LIST_HEAD(&ref_node->node);
8402 INIT_LIST_HEAD(&ref_node->rsrc_list);
8403 ref_node->done = false;
8404 return ref_node;
8405}
8406
a7f0ed5a
PB
8407static void io_rsrc_node_switch(struct io_ring_ctx *ctx,
8408 struct io_rsrc_data *data_to_kill)
ab409402 8409 __must_hold(&ctx->uring_lock)
6b06314c 8410{
a7f0ed5a
PB
8411 WARN_ON_ONCE(!ctx->rsrc_backup_node);
8412 WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
6b06314c 8413
ab409402
PB
8414 io_rsrc_refs_drop(ctx);
8415
a7f0ed5a
PB
8416 if (data_to_kill) {
8417 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
82fbcfa9 8418
a7f0ed5a 8419 rsrc_node->rsrc_data = data_to_kill;
4956b9ea 8420 spin_lock_irq(&ctx->rsrc_ref_lock);
a7f0ed5a 8421 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
4956b9ea 8422 spin_unlock_irq(&ctx->rsrc_ref_lock);
82fbcfa9 8423
3e942498 8424 atomic_inc(&data_to_kill->refs);
a7f0ed5a
PB
8425 percpu_ref_kill(&rsrc_node->refs);
8426 ctx->rsrc_node = NULL;
8427 }
6b06314c 8428
a7f0ed5a
PB
8429 if (!ctx->rsrc_node) {
8430 ctx->rsrc_node = ctx->rsrc_backup_node;
8431 ctx->rsrc_backup_node = NULL;
8432 }
8bad28d8
HX
8433}
8434
a7f0ed5a 8435static int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
8dd03afe
PB
8436{
8437 if (ctx->rsrc_backup_node)
8438 return 0;
f6133fbd 8439 ctx->rsrc_backup_node = io_rsrc_node_alloc();
8dd03afe 8440 return ctx->rsrc_backup_node ? 0 : -ENOMEM;
8bad28d8
HX
8441}
8442
c072481d
PB
8443static __cold int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
8444 struct io_ring_ctx *ctx)
8bad28d8
HX
8445{
8446 int ret;
05589553 8447
215c3902 8448 /* As we may drop ->uring_lock, other task may have started quiesce */
8bad28d8
HX
8449 if (data->quiesce)
8450 return -ENXIO;
05589553 8451
8bad28d8 8452 data->quiesce = true;
1ffc5422 8453 do {
a7f0ed5a 8454 ret = io_rsrc_node_switch_start(ctx);
8dd03afe 8455 if (ret)
f2303b1f 8456 break;
a7f0ed5a 8457 io_rsrc_node_switch(ctx, data);
f2303b1f 8458
3e942498
PB
8459 /* kill initial ref, already quiesced if zero */
8460 if (atomic_dec_and_test(&data->refs))
8461 break;
c018db4a 8462 mutex_unlock(&ctx->uring_lock);
8bad28d8 8463 flush_delayed_work(&ctx->rsrc_put_work);
1ffc5422 8464 ret = wait_for_completion_interruptible(&data->done);
c018db4a
JA
8465 if (!ret) {
8466 mutex_lock(&ctx->uring_lock);
80912cef
DY
8467 if (atomic_read(&data->refs) > 0) {
8468 /*
8469 * it has been revived by another thread while
8470 * we were unlocked
8471 */
8472 mutex_unlock(&ctx->uring_lock);
8473 } else {
8474 break;
8475 }
c018db4a 8476 }
8bad28d8 8477
3e942498
PB
8478 atomic_inc(&data->refs);
8479 /* wait for all works potentially completing data->done */
8480 flush_delayed_work(&ctx->rsrc_put_work);
cb5e1b81 8481 reinit_completion(&data->done);
8dd03afe 8482
1ffc5422 8483 ret = io_run_task_work_sig();
8bad28d8 8484 mutex_lock(&ctx->uring_lock);
f2303b1f 8485 } while (ret >= 0);
8bad28d8 8486 data->quiesce = false;
05f3fb3c 8487
8bad28d8 8488 return ret;
d7954b2b
BM
8489}
8490
2d091d62
PB
8491static u64 *io_get_tag_slot(struct io_rsrc_data *data, unsigned int idx)
8492{
8493 unsigned int off = idx & IO_RSRC_TAG_TABLE_MASK;
8494 unsigned int table_idx = idx >> IO_RSRC_TAG_TABLE_SHIFT;
8495
8496 return &data->tags[table_idx][off];
8497}
8498
44b31f2f 8499static void io_rsrc_data_free(struct io_rsrc_data *data)
1ad555c6 8500{
2d091d62
PB
8501 size_t size = data->nr * sizeof(data->tags[0][0]);
8502
8503 if (data->tags)
8504 io_free_page_table((void **)data->tags, size);
44b31f2f
PB
8505 kfree(data);
8506}
8507
c072481d
PB
8508static __cold int io_rsrc_data_alloc(struct io_ring_ctx *ctx, rsrc_put_fn *do_put,
8509 u64 __user *utags, unsigned nr,
8510 struct io_rsrc_data **pdata)
1ad555c6 8511{
b895c9a6 8512 struct io_rsrc_data *data;
2d091d62 8513 int ret = -ENOMEM;
d878c816 8514 unsigned i;
1ad555c6
BM
8515
8516 data = kzalloc(sizeof(*data), GFP_KERNEL);
8517 if (!data)
d878c816 8518 return -ENOMEM;
2d091d62 8519 data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
b60c8dce 8520 if (!data->tags) {
1ad555c6 8521 kfree(data);
d878c816
PB
8522 return -ENOMEM;
8523 }
2d091d62
PB
8524
8525 data->nr = nr;
8526 data->ctx = ctx;
8527 data->do_put = do_put;
d878c816 8528 if (utags) {
2d091d62 8529 ret = -EFAULT;
d878c816 8530 for (i = 0; i < nr; i++) {
fdd1dc31
CIK
8531 u64 *tag_slot = io_get_tag_slot(data, i);
8532
8533 if (copy_from_user(tag_slot, &utags[i],
8534 sizeof(*tag_slot)))
2d091d62 8535 goto fail;
d878c816 8536 }
1ad555c6 8537 }
b60c8dce 8538
3e942498 8539 atomic_set(&data->refs, 1);
1ad555c6 8540 init_completion(&data->done);
d878c816
PB
8541 *pdata = data;
8542 return 0;
2d091d62
PB
8543fail:
8544 io_rsrc_data_free(data);
8545 return ret;
1ad555c6
BM
8546}
8547
9123c8ff
PB
8548static bool io_alloc_file_tables(struct io_file_table *table, unsigned nr_files)
8549{
0bea96f5
PB
8550 table->files = kvcalloc(nr_files, sizeof(table->files[0]),
8551 GFP_KERNEL_ACCOUNT);
9123c8ff
PB
8552 return !!table->files;
8553}
8554
042b0d85 8555static void io_free_file_tables(struct io_file_table *table)
9123c8ff 8556{
042b0d85 8557 kvfree(table->files);
9123c8ff
PB
8558 table->files = NULL;
8559}
8560
fff4db76 8561static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
1ad555c6 8562{
fff4db76
PB
8563#if defined(CONFIG_UNIX)
8564 if (ctx->ring_sock) {
8565 struct sock *sock = ctx->ring_sock->sk;
8566 struct sk_buff *skb;
8567
8568 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
8569 kfree_skb(skb);
8570 }
8571#else
8572 int i;
8573
8574 for (i = 0; i < ctx->nr_user_files; i++) {
8575 struct file *file;
8576
8577 file = io_file_from_index(ctx, i);
8578 if (file)
8579 fput(file);
8580 }
8581#endif
042b0d85 8582 io_free_file_tables(&ctx->file_table);
44b31f2f 8583 io_rsrc_data_free(ctx->file_data);
fff4db76
PB
8584 ctx->file_data = NULL;
8585 ctx->nr_user_files = 0;
1ad555c6
BM
8586}
8587
d7954b2b
BM
8588static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
8589{
d7954b2b
BM
8590 int ret;
8591
08480400 8592 if (!ctx->file_data)
d7954b2b 8593 return -ENXIO;
08480400
PB
8594 ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
8595 if (!ret)
8596 __io_sqe_files_unregister(ctx);
8597 return ret;
6b06314c
JA
8598}
8599
37d1e2e3 8600static void io_sq_thread_unpark(struct io_sq_data *sqd)
09a6f4ef 8601 __releases(&sqd->lock)
37d1e2e3 8602{
521d6a73
PB
8603 WARN_ON_ONCE(sqd->thread == current);
8604
9e138a48
PB
8605 /*
8606 * Do the dance but not conditional clear_bit() because it'd race with
8607 * other threads incrementing park_pending and setting the bit.
8608 */
37d1e2e3 8609 clear_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
9e138a48
PB
8610 if (atomic_dec_return(&sqd->park_pending))
8611 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
09a6f4ef 8612 mutex_unlock(&sqd->lock);
37d1e2e3
JA
8613}
8614
86e0d676 8615static void io_sq_thread_park(struct io_sq_data *sqd)
09a6f4ef 8616 __acquires(&sqd->lock)
37d1e2e3 8617{
521d6a73
PB
8618 WARN_ON_ONCE(sqd->thread == current);
8619
9e138a48 8620 atomic_inc(&sqd->park_pending);
86e0d676 8621 set_bit(IO_SQ_THREAD_SHOULD_PARK, &sqd->state);
09a6f4ef 8622 mutex_lock(&sqd->lock);
05962f95 8623 if (sqd->thread)
86e0d676 8624 wake_up_process(sqd->thread);
37d1e2e3
JA
8625}
8626
8627static void io_sq_thread_stop(struct io_sq_data *sqd)
8628{
521d6a73 8629 WARN_ON_ONCE(sqd->thread == current);
88885f66 8630 WARN_ON_ONCE(test_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state));
521d6a73 8631
05962f95 8632 set_bit(IO_SQ_THREAD_SHOULD_STOP, &sqd->state);
88885f66 8633 mutex_lock(&sqd->lock);
e8f98f24
JA
8634 if (sqd->thread)
8635 wake_up_process(sqd->thread);
09a6f4ef 8636 mutex_unlock(&sqd->lock);
05962f95 8637 wait_for_completion(&sqd->exited);
37d1e2e3
JA
8638}
8639
534ca6d6 8640static void io_put_sq_data(struct io_sq_data *sqd)
6c271ce2 8641{
534ca6d6 8642 if (refcount_dec_and_test(&sqd->refs)) {
9e138a48
PB
8643 WARN_ON_ONCE(atomic_read(&sqd->park_pending));
8644
37d1e2e3
JA
8645 io_sq_thread_stop(sqd);
8646 kfree(sqd);
8647 }
8648}
8649
8650static void io_sq_thread_finish(struct io_ring_ctx *ctx)
8651{
8652 struct io_sq_data *sqd = ctx->sq_data;
8653
8654 if (sqd) {
05962f95 8655 io_sq_thread_park(sqd);
521d6a73 8656 list_del_init(&ctx->sqd_list);
37d1e2e3 8657 io_sqd_update_thread_idle(sqd);
05962f95 8658 io_sq_thread_unpark(sqd);
37d1e2e3
JA
8659
8660 io_put_sq_data(sqd);
8661 ctx->sq_data = NULL;
534ca6d6
JA
8662 }
8663}
8664
aa06165d
JA
8665static struct io_sq_data *io_attach_sq_data(struct io_uring_params *p)
8666{
8667 struct io_ring_ctx *ctx_attach;
8668 struct io_sq_data *sqd;
8669 struct fd f;
8670
8671 f = fdget(p->wq_fd);
8672 if (!f.file)
8673 return ERR_PTR(-ENXIO);
8674 if (f.file->f_op != &io_uring_fops) {
8675 fdput(f);
8676 return ERR_PTR(-EINVAL);
8677 }
8678
8679 ctx_attach = f.file->private_data;
8680 sqd = ctx_attach->sq_data;
8681 if (!sqd) {
8682 fdput(f);
8683 return ERR_PTR(-EINVAL);
8684 }
5c2469e0
JA
8685 if (sqd->task_tgid != current->tgid) {
8686 fdput(f);
8687 return ERR_PTR(-EPERM);
8688 }
aa06165d
JA
8689
8690 refcount_inc(&sqd->refs);
8691 fdput(f);
8692 return sqd;
8693}
8694
26984fbf
PB
8695static struct io_sq_data *io_get_sq_data(struct io_uring_params *p,
8696 bool *attached)
534ca6d6
JA
8697{
8698 struct io_sq_data *sqd;
8699
26984fbf 8700 *attached = false;
5c2469e0
JA
8701 if (p->flags & IORING_SETUP_ATTACH_WQ) {
8702 sqd = io_attach_sq_data(p);
26984fbf
PB
8703 if (!IS_ERR(sqd)) {
8704 *attached = true;
5c2469e0 8705 return sqd;
26984fbf 8706 }
5c2469e0
JA
8707 /* fall through for EPERM case, setup new sqd/task */
8708 if (PTR_ERR(sqd) != -EPERM)
8709 return sqd;
8710 }
aa06165d 8711
534ca6d6
JA
8712 sqd = kzalloc(sizeof(*sqd), GFP_KERNEL);
8713 if (!sqd)
8714 return ERR_PTR(-ENOMEM);
8715
9e138a48 8716 atomic_set(&sqd->park_pending, 0);
534ca6d6 8717 refcount_set(&sqd->refs, 1);
69fb2131 8718 INIT_LIST_HEAD(&sqd->ctx_list);
09a6f4ef 8719 mutex_init(&sqd->lock);
534ca6d6 8720 init_waitqueue_head(&sqd->wait);
37d1e2e3 8721 init_completion(&sqd->exited);
534ca6d6
JA
8722 return sqd;
8723}
8724
6b06314c 8725#if defined(CONFIG_UNIX)
6b06314c
JA
8726/*
8727 * Ensure the UNIX gc is aware of our file set, so we are certain that
8728 * the io_uring can be safely unregistered on process exit, even if we have
8729 * loops in the file referencing.
8730 */
8731static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
8732{
8733 struct sock *sk = ctx->ring_sock->sk;
8734 struct scm_fp_list *fpl;
8735 struct sk_buff *skb;
08a45173 8736 int i, nr_files;
6b06314c 8737
6b06314c
JA
8738 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
8739 if (!fpl)
8740 return -ENOMEM;
8741
8742 skb = alloc_skb(0, GFP_KERNEL);
8743 if (!skb) {
8744 kfree(fpl);
8745 return -ENOMEM;
8746 }
8747
8748 skb->sk = sk;
6b06314c 8749
08a45173 8750 nr_files = 0;
62e398be 8751 fpl->user = get_uid(current_user());
6b06314c 8752 for (i = 0; i < nr; i++) {
65e19f54
JA
8753 struct file *file = io_file_from_index(ctx, i + offset);
8754
8755 if (!file)
08a45173 8756 continue;
65e19f54 8757 fpl->fp[nr_files] = get_file(file);
08a45173
JA
8758 unix_inflight(fpl->user, fpl->fp[nr_files]);
8759 nr_files++;
6b06314c
JA
8760 }
8761
08a45173
JA
8762 if (nr_files) {
8763 fpl->max = SCM_MAX_FD;
8764 fpl->count = nr_files;
8765 UNIXCB(skb).fp = fpl;
05f3fb3c 8766 skb->destructor = unix_destruct_scm;
08a45173
JA
8767 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
8768 skb_queue_head(&sk->sk_receive_queue, skb);
6b06314c 8769
08a45173
JA
8770 for (i = 0; i < nr_files; i++)
8771 fput(fpl->fp[i]);
8772 } else {
8773 kfree_skb(skb);
8774 kfree(fpl);
8775 }
6b06314c
JA
8776
8777 return 0;
8778}
8779
8780/*
8781 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
8782 * causes regular reference counting to break down. We rely on the UNIX
8783 * garbage collection to take care of this problem for us.
8784 */
8785static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8786{
8787 unsigned left, total;
8788 int ret = 0;
8789
8790 total = 0;
8791 left = ctx->nr_user_files;
8792 while (left) {
8793 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
6b06314c
JA
8794
8795 ret = __io_sqe_files_scm(ctx, this_files, total);
8796 if (ret)
8797 break;
8798 left -= this_files;
8799 total += this_files;
8800 }
8801
8802 if (!ret)
8803 return 0;
8804
8805 while (total < ctx->nr_user_files) {
65e19f54
JA
8806 struct file *file = io_file_from_index(ctx, total);
8807
8808 if (file)
8809 fput(file);
6b06314c
JA
8810 total++;
8811 }
8812
8813 return ret;
8814}
8815#else
8816static int io_sqe_files_scm(struct io_ring_ctx *ctx)
8817{
8818 return 0;
8819}
8820#endif
8821
47e90392 8822static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
05f3fb3c 8823{
50238531 8824 struct file *file = prsrc->file;
05f3fb3c
JA
8825#if defined(CONFIG_UNIX)
8826 struct sock *sock = ctx->ring_sock->sk;
8827 struct sk_buff_head list, *head = &sock->sk_receive_queue;
8828 struct sk_buff *skb;
8829 int i;
8830
8831 __skb_queue_head_init(&list);
8832
8833 /*
8834 * Find the skb that holds this file in its SCM_RIGHTS. When found,
8835 * remove this entry and rearrange the file array.
8836 */
8837 skb = skb_dequeue(head);
8838 while (skb) {
8839 struct scm_fp_list *fp;
8840
8841 fp = UNIXCB(skb).fp;
8842 for (i = 0; i < fp->count; i++) {
8843 int left;
8844
8845 if (fp->fp[i] != file)
8846 continue;
8847
8848 unix_notinflight(fp->user, fp->fp[i]);
8849 left = fp->count - 1 - i;
8850 if (left) {
8851 memmove(&fp->fp[i], &fp->fp[i + 1],
8852 left * sizeof(struct file *));
8853 }
8854 fp->count--;
8855 if (!fp->count) {
8856 kfree_skb(skb);
8857 skb = NULL;
8858 } else {
8859 __skb_queue_tail(&list, skb);
8860 }
8861 fput(file);
8862 file = NULL;
8863 break;
8864 }
8865
8866 if (!file)
8867 break;
8868
8869 __skb_queue_tail(&list, skb);
8870
8871 skb = skb_dequeue(head);
8872 }
8873
8874 if (skb_peek(&list)) {
8875 spin_lock_irq(&head->lock);
8876 while ((skb = __skb_dequeue(&list)) != NULL)
8877 __skb_queue_tail(head, skb);
8878 spin_unlock_irq(&head->lock);
8879 }
8880#else
8881 fput(file);
8882#endif
8883}
8884
b895c9a6 8885static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
65e19f54 8886{
b895c9a6 8887 struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
269bbe5f
BM
8888 struct io_ring_ctx *ctx = rsrc_data->ctx;
8889 struct io_rsrc_put *prsrc, *tmp;
05589553 8890
269bbe5f
BM
8891 list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
8892 list_del(&prsrc->list);
b60c8dce
PB
8893
8894 if (prsrc->tag) {
8895 bool lock_ring = ctx->flags & IORING_SETUP_IOPOLL;
b60c8dce
PB
8896
8897 io_ring_submit_lock(ctx, lock_ring);
79ebeaee 8898 spin_lock(&ctx->completion_lock);
913a571a 8899 io_fill_cqe_aux(ctx, prsrc->tag, 0, 0);
b60c8dce 8900 io_commit_cqring(ctx);
79ebeaee 8901 spin_unlock(&ctx->completion_lock);
b60c8dce
PB
8902 io_cqring_ev_posted(ctx);
8903 io_ring_submit_unlock(ctx, lock_ring);
8904 }
8905
40ae0ff7 8906 rsrc_data->do_put(ctx, prsrc);
269bbe5f 8907 kfree(prsrc);
65e19f54 8908 }
05589553 8909
28a9fe25 8910 io_rsrc_node_destroy(ref_node);
3e942498
PB
8911 if (atomic_dec_and_test(&rsrc_data->refs))
8912 complete(&rsrc_data->done);
2faf852d 8913}
65e19f54 8914
269bbe5f 8915static void io_rsrc_put_work(struct work_struct *work)
4a38aed2
JA
8916{
8917 struct io_ring_ctx *ctx;
8918 struct llist_node *node;
8919
269bbe5f
BM
8920 ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
8921 node = llist_del_all(&ctx->rsrc_put_llist);
4a38aed2
JA
8922
8923 while (node) {
b895c9a6 8924 struct io_rsrc_node *ref_node;
4a38aed2
JA
8925 struct llist_node *next = node->next;
8926
b895c9a6 8927 ref_node = llist_entry(node, struct io_rsrc_node, llist);
269bbe5f 8928 __io_rsrc_put_work(ref_node);
4a38aed2
JA
8929 node = next;
8930 }
8931}
8932
6b06314c 8933static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
792e3582 8934 unsigned nr_args, u64 __user *tags)
6b06314c
JA
8935{
8936 __s32 __user *fds = (__s32 __user *) arg;
05f3fb3c 8937 struct file *file;
f3baed39 8938 int fd, ret;
846a4ef2 8939 unsigned i;
6b06314c 8940
05f3fb3c 8941 if (ctx->file_data)
6b06314c
JA
8942 return -EBUSY;
8943 if (!nr_args)
8944 return -EINVAL;
8945 if (nr_args > IORING_MAX_FIXED_FILES)
8946 return -EMFILE;
3a1b8a4e
PB
8947 if (nr_args > rlimit(RLIMIT_NOFILE))
8948 return -EMFILE;
a7f0ed5a 8949 ret = io_rsrc_node_switch_start(ctx);
f3baed39
PB
8950 if (ret)
8951 return ret;
d878c816
PB
8952 ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
8953 &ctx->file_data);
8954 if (ret)
8955 return ret;
6b06314c 8956
f3baed39 8957 ret = -ENOMEM;
aeca241b 8958 if (!io_alloc_file_tables(&ctx->file_table, nr_args))
1ad555c6 8959 goto out_free;
65e19f54 8960
08a45173 8961 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
d878c816 8962 if (copy_from_user(&fd, &fds[i], sizeof(fd))) {
600cf3f8
PB
8963 ret = -EFAULT;
8964 goto out_fput;
8965 }
08a45173 8966 /* allow sparse sets */
792e3582
PB
8967 if (fd == -1) {
8968 ret = -EINVAL;
2d091d62 8969 if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
792e3582 8970 goto out_fput;
08a45173 8971 continue;
792e3582 8972 }
6b06314c 8973
05f3fb3c 8974 file = fget(fd);
6b06314c 8975 ret = -EBADF;
792e3582 8976 if (unlikely(!file))
600cf3f8 8977 goto out_fput;
05f3fb3c 8978
6b06314c
JA
8979 /*
8980 * Don't allow io_uring instances to be registered. If UNIX
8981 * isn't enabled, then this causes a reference cycle and this
8982 * instance can never get freed. If UNIX is enabled we'll
8983 * handle it just fine, but there's still no point in allowing
8984 * a ring fd as it doesn't support regular read/write anyway.
8985 */
05f3fb3c
JA
8986 if (file->f_op == &io_uring_fops) {
8987 fput(file);
600cf3f8 8988 goto out_fput;
6b06314c 8989 }
aeca241b 8990 io_fixed_file_set(io_fixed_file_slot(&ctx->file_table, i), file);
6b06314c
JA
8991 }
8992
6b06314c 8993 ret = io_sqe_files_scm(ctx);
05589553 8994 if (ret) {
08480400 8995 __io_sqe_files_unregister(ctx);
05589553
XW
8996 return ret;
8997 }
6b06314c 8998
a7f0ed5a 8999 io_rsrc_node_switch(ctx, NULL);
6b06314c 9000 return ret;
600cf3f8
PB
9001out_fput:
9002 for (i = 0; i < ctx->nr_user_files; i++) {
9003 file = io_file_from_index(ctx, i);
9004 if (file)
9005 fput(file);
9006 }
042b0d85 9007 io_free_file_tables(&ctx->file_table);
600cf3f8 9008 ctx->nr_user_files = 0;
600cf3f8 9009out_free:
44b31f2f 9010 io_rsrc_data_free(ctx->file_data);
55cbc256 9011 ctx->file_data = NULL;
6b06314c
JA
9012 return ret;
9013}
9014
c3a31e60
JA
9015static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
9016 int index)
9017{
9018#if defined(CONFIG_UNIX)
9019 struct sock *sock = ctx->ring_sock->sk;
9020 struct sk_buff_head *head = &sock->sk_receive_queue;
9021 struct sk_buff *skb;
9022
9023 /*
9024 * See if we can merge this file into an existing skb SCM_RIGHTS
9025 * file set. If there's no room, fall back to allocating a new skb
9026 * and filling it in.
9027 */
9028 spin_lock_irq(&head->lock);
9029 skb = skb_peek(head);
9030 if (skb) {
9031 struct scm_fp_list *fpl = UNIXCB(skb).fp;
9032
9033 if (fpl->count < SCM_MAX_FD) {
9034 __skb_unlink(skb, head);
9035 spin_unlock_irq(&head->lock);
9036 fpl->fp[fpl->count] = get_file(file);
9037 unix_inflight(fpl->user, fpl->fp[fpl->count]);
9038 fpl->count++;
9039 spin_lock_irq(&head->lock);
9040 __skb_queue_head(head, skb);
9041 } else {
9042 skb = NULL;
9043 }
9044 }
9045 spin_unlock_irq(&head->lock);
9046
9047 if (skb) {
9048 fput(file);
9049 return 0;
9050 }
9051
9052 return __io_sqe_files_scm(ctx, 1, index);
9053#else
9054 return 0;
9055#endif
9056}
9057
9c7b0ba8
PB
9058static int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
9059 struct io_rsrc_node *node, void *rsrc)
9060{
9061 struct io_rsrc_put *prsrc;
9062
9063 prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
9064 if (!prsrc)
9065 return -ENOMEM;
9066
9067 prsrc->tag = *io_get_tag_slot(data, idx);
9068 prsrc->rsrc = rsrc;
9069 list_add(&prsrc->list, &node->rsrc_list);
9070 return 0;
9071}
9072
b9445598
PB
9073static int io_install_fixed_file(struct io_kiocb *req, struct file *file,
9074 unsigned int issue_flags, u32 slot_index)
9075{
9076 struct io_ring_ctx *ctx = req->ctx;
3b44b371 9077 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
9c7b0ba8 9078 bool needs_switch = false;
b9445598
PB
9079 struct io_fixed_file *file_slot;
9080 int ret = -EBADF;
9081
3b44b371 9082 io_ring_submit_lock(ctx, needs_lock);
b9445598
PB
9083 if (file->f_op == &io_uring_fops)
9084 goto err;
9085 ret = -ENXIO;
9086 if (!ctx->file_data)
9087 goto err;
9088 ret = -EINVAL;
9089 if (slot_index >= ctx->nr_user_files)
9090 goto err;
9091
9092 slot_index = array_index_nospec(slot_index, ctx->nr_user_files);
9093 file_slot = io_fixed_file_slot(&ctx->file_table, slot_index);
9c7b0ba8
PB
9094
9095 if (file_slot->file_ptr) {
9096 struct file *old_file;
9097
9098 ret = io_rsrc_node_switch_start(ctx);
9099 if (ret)
9100 goto err;
9101
9102 old_file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9103 ret = io_queue_rsrc_removal(ctx->file_data, slot_index,
9104 ctx->rsrc_node, old_file);
9105 if (ret)
9106 goto err;
9107 file_slot->file_ptr = 0;
9108 needs_switch = true;
9109 }
b9445598
PB
9110
9111 *io_get_tag_slot(ctx->file_data, slot_index) = 0;
9112 io_fixed_file_set(file_slot, file);
9113 ret = io_sqe_file_register(ctx, file, slot_index);
9114 if (ret) {
9115 file_slot->file_ptr = 0;
9116 goto err;
9117 }
9118
9119 ret = 0;
9120err:
9c7b0ba8
PB
9121 if (needs_switch)
9122 io_rsrc_node_switch(ctx, ctx->file_data);
3b44b371 9123 io_ring_submit_unlock(ctx, needs_lock);
b9445598
PB
9124 if (ret)
9125 fput(file);
9126 return ret;
9127}
9128
7df778be
PB
9129static int io_close_fixed(struct io_kiocb *req, unsigned int issue_flags)
9130{
9131 unsigned int offset = req->close.file_slot - 1;
9132 struct io_ring_ctx *ctx = req->ctx;
3b44b371 9133 bool needs_lock = issue_flags & IO_URING_F_UNLOCKED;
7df778be
PB
9134 struct io_fixed_file *file_slot;
9135 struct file *file;
9136 int ret, i;
9137
3b44b371 9138 io_ring_submit_lock(ctx, needs_lock);
7df778be
PB
9139 ret = -ENXIO;
9140 if (unlikely(!ctx->file_data))
9141 goto out;
9142 ret = -EINVAL;
9143 if (offset >= ctx->nr_user_files)
9144 goto out;
9145 ret = io_rsrc_node_switch_start(ctx);
9146 if (ret)
9147 goto out;
9148
9149 i = array_index_nospec(offset, ctx->nr_user_files);
9150 file_slot = io_fixed_file_slot(&ctx->file_table, i);
9151 ret = -EBADF;
9152 if (!file_slot->file_ptr)
9153 goto out;
9154
9155 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
9156 ret = io_queue_rsrc_removal(ctx->file_data, offset, ctx->rsrc_node, file);
9157 if (ret)
9158 goto out;
9159
9160 file_slot->file_ptr = 0;
9161 io_rsrc_node_switch(ctx, ctx->file_data);
9162 ret = 0;
9163out:
3b44b371 9164 io_ring_submit_unlock(ctx, needs_lock);
7df778be
PB
9165 return ret;
9166}
9167
05f3fb3c 9168static int __io_sqe_files_update(struct io_ring_ctx *ctx,
c3bdad02 9169 struct io_uring_rsrc_update2 *up,
05f3fb3c
JA
9170 unsigned nr_args)
9171{
c3bdad02 9172 u64 __user *tags = u64_to_user_ptr(up->tags);
98f0b3b4 9173 __s32 __user *fds = u64_to_user_ptr(up->data);
b895c9a6 9174 struct io_rsrc_data *data = ctx->file_data;
a04b0ac0
PB
9175 struct io_fixed_file *file_slot;
9176 struct file *file;
98f0b3b4
PB
9177 int fd, i, err = 0;
9178 unsigned int done;
05589553 9179 bool needs_switch = false;
c3a31e60 9180
98f0b3b4
PB
9181 if (!ctx->file_data)
9182 return -ENXIO;
9183 if (up->offset + nr_args > ctx->nr_user_files)
c3a31e60
JA
9184 return -EINVAL;
9185
67973b93 9186 for (done = 0; done < nr_args; done++) {
c3bdad02
PB
9187 u64 tag = 0;
9188
9189 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
9190 copy_from_user(&fd, &fds[done], sizeof(fd))) {
c3a31e60
JA
9191 err = -EFAULT;
9192 break;
9193 }
c3bdad02
PB
9194 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
9195 err = -EINVAL;
9196 break;
9197 }
4e0377a1 9198 if (fd == IORING_REGISTER_FILES_SKIP)
9199 continue;
9200
67973b93 9201 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
aeca241b 9202 file_slot = io_fixed_file_slot(&ctx->file_table, i);
ea64ec02 9203
a04b0ac0
PB
9204 if (file_slot->file_ptr) {
9205 file = (struct file *)(file_slot->file_ptr & FFS_MASK);
b60c8dce
PB
9206 err = io_queue_rsrc_removal(data, up->offset + done,
9207 ctx->rsrc_node, file);
a5318d3c
HD
9208 if (err)
9209 break;
a04b0ac0 9210 file_slot->file_ptr = 0;
05589553 9211 needs_switch = true;
c3a31e60
JA
9212 }
9213 if (fd != -1) {
c3a31e60
JA
9214 file = fget(fd);
9215 if (!file) {
9216 err = -EBADF;
9217 break;
9218 }
9219 /*
9220 * Don't allow io_uring instances to be registered. If
9221 * UNIX isn't enabled, then this causes a reference
9222 * cycle and this instance can never get freed. If UNIX
9223 * is enabled we'll handle it just fine, but there's
9224 * still no point in allowing a ring fd as it doesn't
9225 * support regular read/write anyway.
9226 */
9227 if (file->f_op == &io_uring_fops) {
9228 fput(file);
9229 err = -EBADF;
9230 break;
9231 }
2d091d62 9232 *io_get_tag_slot(data, up->offset + done) = tag;
9a321c98 9233 io_fixed_file_set(file_slot, file);
c3a31e60 9234 err = io_sqe_file_register(ctx, file, i);
f3bd9dae 9235 if (err) {
a04b0ac0 9236 file_slot->file_ptr = 0;
f3bd9dae 9237 fput(file);
c3a31e60 9238 break;
f3bd9dae 9239 }
c3a31e60 9240 }
05f3fb3c
JA
9241 }
9242
a7f0ed5a
PB
9243 if (needs_switch)
9244 io_rsrc_node_switch(ctx, data);
c3a31e60
JA
9245 return done ? done : err;
9246}
05589553 9247
685fe7fe
JA
9248static struct io_wq *io_init_wq_offload(struct io_ring_ctx *ctx,
9249 struct task_struct *task)
24369c2e 9250{
e941894e 9251 struct io_wq_hash *hash;
24369c2e 9252 struct io_wq_data data;
24369c2e 9253 unsigned int concurrency;
24369c2e 9254
362a9e65 9255 mutex_lock(&ctx->uring_lock);
e941894e
JA
9256 hash = ctx->hash_map;
9257 if (!hash) {
9258 hash = kzalloc(sizeof(*hash), GFP_KERNEL);
362a9e65
YY
9259 if (!hash) {
9260 mutex_unlock(&ctx->uring_lock);
e941894e 9261 return ERR_PTR(-ENOMEM);
362a9e65 9262 }
e941894e
JA
9263 refcount_set(&hash->refs, 1);
9264 init_waitqueue_head(&hash->wait);
9265 ctx->hash_map = hash;
24369c2e 9266 }
362a9e65 9267 mutex_unlock(&ctx->uring_lock);
24369c2e 9268
e941894e 9269 data.hash = hash;
685fe7fe 9270 data.task = task;
ebc11b6c 9271 data.free_work = io_wq_free_work;
f5fa38c5 9272 data.do_work = io_wq_submit_work;
24369c2e 9273
d25e3a3d
JA
9274 /* Do QD, or 4 * CPUS, whatever is smallest */
9275 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
24369c2e 9276
5aa75ed5 9277 return io_wq_create(concurrency, &data);
24369c2e
PB
9278}
9279
c072481d
PB
9280static __cold int io_uring_alloc_task_context(struct task_struct *task,
9281 struct io_ring_ctx *ctx)
0f212204
JA
9282{
9283 struct io_uring_task *tctx;
d8a6df10 9284 int ret;
0f212204 9285
09899b19 9286 tctx = kzalloc(sizeof(*tctx), GFP_KERNEL);
0f212204
JA
9287 if (unlikely(!tctx))
9288 return -ENOMEM;
9289
e7a6c00d
JA
9290 tctx->registered_rings = kcalloc(IO_RINGFD_REG_MAX,
9291 sizeof(struct file *), GFP_KERNEL);
9292 if (unlikely(!tctx->registered_rings)) {
9293 kfree(tctx);
9294 return -ENOMEM;
9295 }
9296
d8a6df10
JA
9297 ret = percpu_counter_init(&tctx->inflight, 0, GFP_KERNEL);
9298 if (unlikely(ret)) {
e7a6c00d 9299 kfree(tctx->registered_rings);
d8a6df10
JA
9300 kfree(tctx);
9301 return ret;
9302 }
9303
685fe7fe 9304 tctx->io_wq = io_init_wq_offload(ctx, task);
5aa75ed5
JA
9305 if (IS_ERR(tctx->io_wq)) {
9306 ret = PTR_ERR(tctx->io_wq);
9307 percpu_counter_destroy(&tctx->inflight);
e7a6c00d 9308 kfree(tctx->registered_rings);
5aa75ed5
JA
9309 kfree(tctx);
9310 return ret;
9311 }
9312
0f212204
JA
9313 xa_init(&tctx->xa);
9314 init_waitqueue_head(&tctx->wait);
fdaf083c 9315 atomic_set(&tctx->in_idle, 0);
b303fe2e 9316 atomic_set(&tctx->inflight_tracked, 0);
0f212204 9317 task->io_uring = tctx;
7cbf1722
JA
9318 spin_lock_init(&tctx->task_lock);
9319 INIT_WQ_LIST(&tctx->task_list);
4813c377 9320 INIT_WQ_LIST(&tctx->prior_task_list);
7cbf1722 9321 init_task_work(&tctx->task_work, tctx_task_work);
0f212204
JA
9322 return 0;
9323}
9324
9325void __io_uring_free(struct task_struct *tsk)
9326{
9327 struct io_uring_task *tctx = tsk->io_uring;
9328
9329 WARN_ON_ONCE(!xa_empty(&tctx->xa));
ef8eaa4e 9330 WARN_ON_ONCE(tctx->io_wq);
09899b19 9331 WARN_ON_ONCE(tctx->cached_refs);
ef8eaa4e 9332
e7a6c00d 9333 kfree(tctx->registered_rings);
d8a6df10 9334 percpu_counter_destroy(&tctx->inflight);
0f212204
JA
9335 kfree(tctx);
9336 tsk->io_uring = NULL;
9337}
9338
c072481d
PB
9339static __cold int io_sq_offload_create(struct io_ring_ctx *ctx,
9340 struct io_uring_params *p)
2b188cc1
JA
9341{
9342 int ret;
9343
d25e3a3d
JA
9344 /* Retain compatibility with failing for an invalid attach attempt */
9345 if ((ctx->flags & (IORING_SETUP_ATTACH_WQ | IORING_SETUP_SQPOLL)) ==
9346 IORING_SETUP_ATTACH_WQ) {
9347 struct fd f;
9348
9349 f = fdget(p->wq_fd);
9350 if (!f.file)
9351 return -ENXIO;
0cc936f7
JA
9352 if (f.file->f_op != &io_uring_fops) {
9353 fdput(f);
f2a48dd0 9354 return -EINVAL;
0cc936f7
JA
9355 }
9356 fdput(f);
d25e3a3d 9357 }
6c271ce2 9358 if (ctx->flags & IORING_SETUP_SQPOLL) {
46fe18b1 9359 struct task_struct *tsk;
534ca6d6 9360 struct io_sq_data *sqd;
26984fbf 9361 bool attached;
534ca6d6 9362
cdc1404a
PM
9363 ret = security_uring_sqpoll();
9364 if (ret)
9365 return ret;
9366
26984fbf 9367 sqd = io_get_sq_data(p, &attached);
534ca6d6
JA
9368 if (IS_ERR(sqd)) {
9369 ret = PTR_ERR(sqd);
9370 goto err;
9371 }
69fb2131 9372
7c30f36a 9373 ctx->sq_creds = get_current_cred();
534ca6d6 9374 ctx->sq_data = sqd;
917257da
JA
9375 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
9376 if (!ctx->sq_thread_idle)
9377 ctx->sq_thread_idle = HZ;
9378
78d7f6ba 9379 io_sq_thread_park(sqd);
de75a3d3
PB
9380 list_add(&ctx->sqd_list, &sqd->ctx_list);
9381 io_sqd_update_thread_idle(sqd);
26984fbf 9382 /* don't attach to a dying SQPOLL thread, would be racy */
f2a48dd0 9383 ret = (attached && !sqd->thread) ? -ENXIO : 0;
78d7f6ba
PB
9384 io_sq_thread_unpark(sqd);
9385
de75a3d3
PB
9386 if (ret < 0)
9387 goto err;
9388 if (attached)
5aa75ed5 9389 return 0;
aa06165d 9390
6c271ce2 9391 if (p->flags & IORING_SETUP_SQ_AFF) {
44a9bd18 9392 int cpu = p->sq_thread_cpu;
6c271ce2 9393
917257da 9394 ret = -EINVAL;
f2a48dd0 9395 if (cpu >= nr_cpu_ids || !cpu_online(cpu))
e8f98f24 9396 goto err_sqpoll;
37d1e2e3 9397 sqd->sq_cpu = cpu;
6c271ce2 9398 } else {
37d1e2e3 9399 sqd->sq_cpu = -1;
6c271ce2 9400 }
37d1e2e3
JA
9401
9402 sqd->task_pid = current->pid;
5c2469e0 9403 sqd->task_tgid = current->tgid;
46fe18b1
JA
9404 tsk = create_io_thread(io_sq_thread, sqd, NUMA_NO_NODE);
9405 if (IS_ERR(tsk)) {
9406 ret = PTR_ERR(tsk);
e8f98f24 9407 goto err_sqpoll;
6c271ce2 9408 }
97a73a0f 9409
46fe18b1 9410 sqd->thread = tsk;
97a73a0f 9411 ret = io_uring_alloc_task_context(tsk, ctx);
46fe18b1 9412 wake_up_new_task(tsk);
0f212204
JA
9413 if (ret)
9414 goto err;
6c271ce2
JA
9415 } else if (p->flags & IORING_SETUP_SQ_AFF) {
9416 /* Can't have SQ_AFF without SQPOLL */
9417 ret = -EINVAL;
9418 goto err;
9419 }
9420
2b188cc1 9421 return 0;
f2a48dd0
PB
9422err_sqpoll:
9423 complete(&ctx->sq_data->exited);
2b188cc1 9424err:
37d1e2e3 9425 io_sq_thread_finish(ctx);
2b188cc1
JA
9426 return ret;
9427}
9428
a087e2b5
BM
9429static inline void __io_unaccount_mem(struct user_struct *user,
9430 unsigned long nr_pages)
2b188cc1
JA
9431{
9432 atomic_long_sub(nr_pages, &user->locked_vm);
9433}
9434
a087e2b5
BM
9435static inline int __io_account_mem(struct user_struct *user,
9436 unsigned long nr_pages)
2b188cc1
JA
9437{
9438 unsigned long page_limit, cur_pages, new_pages;
9439
9440 /* Don't allow more pages than we can safely lock */
9441 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
9442
9443 do {
9444 cur_pages = atomic_long_read(&user->locked_vm);
9445 new_pages = cur_pages + nr_pages;
9446 if (new_pages > page_limit)
9447 return -ENOMEM;
9448 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
9449 new_pages) != cur_pages);
9450
9451 return 0;
9452}
9453
26bfa89e 9454static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
a087e2b5 9455{
62e398be 9456 if (ctx->user)
a087e2b5 9457 __io_unaccount_mem(ctx->user, nr_pages);
30975825 9458
26bfa89e
JA
9459 if (ctx->mm_account)
9460 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
a087e2b5
BM
9461}
9462
26bfa89e 9463static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
a087e2b5 9464{
30975825
BM
9465 int ret;
9466
62e398be 9467 if (ctx->user) {
30975825
BM
9468 ret = __io_account_mem(ctx->user, nr_pages);
9469 if (ret)
9470 return ret;
9471 }
9472
26bfa89e
JA
9473 if (ctx->mm_account)
9474 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
a087e2b5
BM
9475
9476 return 0;
9477}
9478
2b188cc1
JA
9479static void io_mem_free(void *ptr)
9480{
52e04ef4
MR
9481 struct page *page;
9482
9483 if (!ptr)
9484 return;
2b188cc1 9485
52e04ef4 9486 page = virt_to_head_page(ptr);
2b188cc1
JA
9487 if (put_page_testzero(page))
9488 free_compound_page(page);
9489}
9490
9491static void *io_mem_alloc(size_t size)
9492{
0a3f1e0b 9493 gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP;
2b188cc1 9494
0a3f1e0b 9495 return (void *) __get_free_pages(gfp, get_order(size));
2b188cc1
JA
9496}
9497
75b28aff
HV
9498static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
9499 size_t *sq_offset)
9500{
9501 struct io_rings *rings;
9502 size_t off, sq_array_size;
9503
9504 off = struct_size(rings, cqes, cq_entries);
9505 if (off == SIZE_MAX)
9506 return SIZE_MAX;
9507
9508#ifdef CONFIG_SMP
9509 off = ALIGN(off, SMP_CACHE_BYTES);
9510 if (off == 0)
9511 return SIZE_MAX;
9512#endif
9513
b36200f5
DV
9514 if (sq_offset)
9515 *sq_offset = off;
9516
75b28aff
HV
9517 sq_array_size = array_size(sizeof(u32), sq_entries);
9518 if (sq_array_size == SIZE_MAX)
9519 return SIZE_MAX;
9520
9521 if (check_add_overflow(off, sq_array_size, &off))
9522 return SIZE_MAX;
9523
75b28aff
HV
9524 return off;
9525}
9526
41edf1a5 9527static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
7f61a1e9 9528{
41edf1a5 9529 struct io_mapped_ubuf *imu = *slot;
7f61a1e9
PB
9530 unsigned int i;
9531
6224843d
PB
9532 if (imu != ctx->dummy_ubuf) {
9533 for (i = 0; i < imu->nr_bvecs; i++)
9534 unpin_user_page(imu->bvec[i].bv_page);
9535 if (imu->acct_pages)
9536 io_unaccount_mem(ctx, imu->acct_pages);
9537 kvfree(imu);
9538 }
41edf1a5 9539 *slot = NULL;
7f61a1e9
PB
9540}
9541
bd54b6fe 9542static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
edafccee 9543{
634d00df
PB
9544 io_buffer_unmap(ctx, &prsrc->buf);
9545 prsrc->buf = NULL;
bd54b6fe 9546}
edafccee 9547
bd54b6fe
BM
9548static void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
9549{
9550 unsigned int i;
edafccee 9551
7f61a1e9
PB
9552 for (i = 0; i < ctx->nr_user_bufs; i++)
9553 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
edafccee 9554 kfree(ctx->user_bufs);
bb6659cc 9555 io_rsrc_data_free(ctx->buf_data);
edafccee 9556 ctx->user_bufs = NULL;
bd54b6fe 9557 ctx->buf_data = NULL;
edafccee 9558 ctx->nr_user_bufs = 0;
bd54b6fe
BM
9559}
9560
0a96bbe4 9561static int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
edafccee 9562{
bd54b6fe 9563 int ret;
edafccee 9564
bd54b6fe 9565 if (!ctx->buf_data)
edafccee
JA
9566 return -ENXIO;
9567
bd54b6fe
BM
9568 ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
9569 if (!ret)
9570 __io_sqe_buffers_unregister(ctx);
9571 return ret;
edafccee
JA
9572}
9573
9574static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
9575 void __user *arg, unsigned index)
9576{
9577 struct iovec __user *src;
9578
9579#ifdef CONFIG_COMPAT
9580 if (ctx->compat) {
9581 struct compat_iovec __user *ciovs;
9582 struct compat_iovec ciov;
9583
9584 ciovs = (struct compat_iovec __user *) arg;
9585 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
9586 return -EFAULT;
9587
d55e5f5b 9588 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
edafccee
JA
9589 dst->iov_len = ciov.iov_len;
9590 return 0;
9591 }
9592#endif
9593 src = (struct iovec __user *) arg;
9594 if (copy_from_user(dst, &src[index], sizeof(*dst)))
9595 return -EFAULT;
9596 return 0;
9597}
9598
de293938
JA
9599/*
9600 * Not super efficient, but this is just a registration time. And we do cache
9601 * the last compound head, so generally we'll only do a full search if we don't
9602 * match that one.
9603 *
9604 * We check if the given compound head page has already been accounted, to
9605 * avoid double accounting it. This allows us to account the full size of the
9606 * page, not just the constituent pages of a huge page.
9607 */
9608static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
9609 int nr_pages, struct page *hpage)
9610{
9611 int i, j;
9612
9613 /* check current page array */
9614 for (i = 0; i < nr_pages; i++) {
9615 if (!PageCompound(pages[i]))
9616 continue;
9617 if (compound_head(pages[i]) == hpage)
9618 return true;
9619 }
9620
9621 /* check previously registered pages */
9622 for (i = 0; i < ctx->nr_user_bufs; i++) {
41edf1a5 9623 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
de293938
JA
9624
9625 for (j = 0; j < imu->nr_bvecs; j++) {
9626 if (!PageCompound(imu->bvec[j].bv_page))
9627 continue;
9628 if (compound_head(imu->bvec[j].bv_page) == hpage)
9629 return true;
9630 }
9631 }
9632
9633 return false;
9634}
9635
9636static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
9637 int nr_pages, struct io_mapped_ubuf *imu,
9638 struct page **last_hpage)
9639{
9640 int i, ret;
9641
216e5835 9642 imu->acct_pages = 0;
de293938
JA
9643 for (i = 0; i < nr_pages; i++) {
9644 if (!PageCompound(pages[i])) {
9645 imu->acct_pages++;
9646 } else {
9647 struct page *hpage;
9648
9649 hpage = compound_head(pages[i]);
9650 if (hpage == *last_hpage)
9651 continue;
9652 *last_hpage = hpage;
9653 if (headpage_already_acct(ctx, pages, i, hpage))
9654 continue;
9655 imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
9656 }
9657 }
9658
9659 if (!imu->acct_pages)
9660 return 0;
9661
26bfa89e 9662 ret = io_account_mem(ctx, imu->acct_pages);
de293938
JA
9663 if (ret)
9664 imu->acct_pages = 0;
9665 return ret;
9666}
9667
0a96bbe4 9668static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
41edf1a5 9669 struct io_mapped_ubuf **pimu,
0a96bbe4 9670 struct page **last_hpage)
edafccee 9671{
41edf1a5 9672 struct io_mapped_ubuf *imu = NULL;
edafccee
JA
9673 struct vm_area_struct **vmas = NULL;
9674 struct page **pages = NULL;
0a96bbe4
BM
9675 unsigned long off, start, end, ubuf;
9676 size_t size;
9677 int ret, pret, nr_pages, i;
9678
6224843d
PB
9679 if (!iov->iov_base) {
9680 *pimu = ctx->dummy_ubuf;
9681 return 0;
9682 }
9683
0a96bbe4
BM
9684 ubuf = (unsigned long) iov->iov_base;
9685 end = (ubuf + iov->iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
9686 start = ubuf >> PAGE_SHIFT;
9687 nr_pages = end - start;
9688
41edf1a5 9689 *pimu = NULL;
0a96bbe4
BM
9690 ret = -ENOMEM;
9691
9692 pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
9693 if (!pages)
9694 goto done;
9695
9696 vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
9697 GFP_KERNEL);
9698 if (!vmas)
9699 goto done;
edafccee 9700
41edf1a5 9701 imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
a2b4198c 9702 if (!imu)
0a96bbe4
BM
9703 goto done;
9704
9705 ret = 0;
9706 mmap_read_lock(current->mm);
9707 pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
9708 pages, vmas);
9709 if (pret == nr_pages) {
9710 /* don't support file backed memory */
9711 for (i = 0; i < nr_pages; i++) {
9712 struct vm_area_struct *vma = vmas[i];
9713
40dad765
PB
9714 if (vma_is_shmem(vma))
9715 continue;
0a96bbe4
BM
9716 if (vma->vm_file &&
9717 !is_file_hugepages(vma->vm_file)) {
9718 ret = -EOPNOTSUPP;
9719 break;
9720 }
9721 }
9722 } else {
9723 ret = pret < 0 ? pret : -EFAULT;
9724 }
9725 mmap_read_unlock(current->mm);
9726 if (ret) {
9727 /*
9728 * if we did partial map, or found file backed vmas,
9729 * release any pages we did get
9730 */
9731 if (pret > 0)
9732 unpin_user_pages(pages, pret);
0a96bbe4
BM
9733 goto done;
9734 }
9735
9736 ret = io_buffer_account_pin(ctx, pages, pret, imu, last_hpage);
9737 if (ret) {
9738 unpin_user_pages(pages, pret);
0a96bbe4
BM
9739 goto done;
9740 }
9741
9742 off = ubuf & ~PAGE_MASK;
9743 size = iov->iov_len;
9744 for (i = 0; i < nr_pages; i++) {
9745 size_t vec_len;
9746
9747 vec_len = min_t(size_t, size, PAGE_SIZE - off);
9748 imu->bvec[i].bv_page = pages[i];
9749 imu->bvec[i].bv_len = vec_len;
9750 imu->bvec[i].bv_offset = off;
9751 off = 0;
9752 size -= vec_len;
9753 }
9754 /* store original address for later verification */
9755 imu->ubuf = ubuf;
4751f53d 9756 imu->ubuf_end = ubuf + iov->iov_len;
0a96bbe4 9757 imu->nr_bvecs = nr_pages;
41edf1a5 9758 *pimu = imu;
0a96bbe4
BM
9759 ret = 0;
9760done:
41edf1a5
PB
9761 if (ret)
9762 kvfree(imu);
0a96bbe4
BM
9763 kvfree(pages);
9764 kvfree(vmas);
9765 return ret;
9766}
9767
2b358604 9768static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
0a96bbe4 9769{
87094465
PB
9770 ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
9771 return ctx->user_bufs ? 0 : -ENOMEM;
2b358604 9772}
edafccee 9773
2b358604
BM
9774static int io_buffer_validate(struct iovec *iov)
9775{
50e96989
PB
9776 unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
9777
2b358604
BM
9778 /*
9779 * Don't impose further limits on the size and buffer
9780 * constraints here, we'll -EINVAL later when IO is
9781 * submitted if they are wrong.
9782 */
6224843d
PB
9783 if (!iov->iov_base)
9784 return iov->iov_len ? -EFAULT : 0;
9785 if (!iov->iov_len)
2b358604 9786 return -EFAULT;
edafccee 9787
2b358604
BM
9788 /* arbitrary limit, but we need something */
9789 if (iov->iov_len > SZ_1G)
9790 return -EFAULT;
edafccee 9791
50e96989
PB
9792 if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
9793 return -EOVERFLOW;
9794
2b358604
BM
9795 return 0;
9796}
edafccee 9797
2b358604 9798static int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
634d00df 9799 unsigned int nr_args, u64 __user *tags)
2b358604 9800{
bd54b6fe
BM
9801 struct page *last_hpage = NULL;
9802 struct io_rsrc_data *data;
2b358604
BM
9803 int i, ret;
9804 struct iovec iov;
edafccee 9805
87094465
PB
9806 if (ctx->user_bufs)
9807 return -EBUSY;
489809e2 9808 if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
87094465 9809 return -EINVAL;
bd54b6fe 9810 ret = io_rsrc_node_switch_start(ctx);
2b358604
BM
9811 if (ret)
9812 return ret;
d878c816
PB
9813 ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
9814 if (ret)
9815 return ret;
bd54b6fe
BM
9816 ret = io_buffers_map_alloc(ctx, nr_args);
9817 if (ret) {
bb6659cc 9818 io_rsrc_data_free(data);
bd54b6fe
BM
9819 return ret;
9820 }
edafccee 9821
87094465 9822 for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
edafccee
JA
9823 ret = io_copy_iov(ctx, &iov, arg, i);
9824 if (ret)
0a96bbe4 9825 break;
2b358604
BM
9826 ret = io_buffer_validate(&iov);
9827 if (ret)
0a96bbe4 9828 break;
2d091d62 9829 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
cf3770e7
CIK
9830 ret = -EINVAL;
9831 break;
9832 }
edafccee 9833
41edf1a5
PB
9834 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
9835 &last_hpage);
0a96bbe4
BM
9836 if (ret)
9837 break;
edafccee 9838 }
0a96bbe4 9839
bd54b6fe 9840 WARN_ON_ONCE(ctx->buf_data);
0a96bbe4 9841
bd54b6fe
BM
9842 ctx->buf_data = data;
9843 if (ret)
9844 __io_sqe_buffers_unregister(ctx);
9845 else
9846 io_rsrc_node_switch(ctx, NULL);
edafccee
JA
9847 return ret;
9848}
9849
634d00df
PB
9850static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
9851 struct io_uring_rsrc_update2 *up,
9852 unsigned int nr_args)
9853{
9854 u64 __user *tags = u64_to_user_ptr(up->tags);
9855 struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
634d00df
PB
9856 struct page *last_hpage = NULL;
9857 bool needs_switch = false;
9858 __u32 done;
9859 int i, err;
9860
9861 if (!ctx->buf_data)
9862 return -ENXIO;
9863 if (up->offset + nr_args > ctx->nr_user_bufs)
9864 return -EINVAL;
9865
9866 for (done = 0; done < nr_args; done++) {
0b8c0e7c
PB
9867 struct io_mapped_ubuf *imu;
9868 int offset = up->offset + done;
634d00df
PB
9869 u64 tag = 0;
9870
9871 err = io_copy_iov(ctx, &iov, iovs, done);
9872 if (err)
9873 break;
9874 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
9875 err = -EFAULT;
9876 break;
9877 }
0b8c0e7c
PB
9878 err = io_buffer_validate(&iov);
9879 if (err)
9880 break;
cf3770e7
CIK
9881 if (!iov.iov_base && tag) {
9882 err = -EINVAL;
9883 break;
9884 }
0b8c0e7c
PB
9885 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
9886 if (err)
9887 break;
634d00df 9888
0b8c0e7c 9889 i = array_index_nospec(offset, ctx->nr_user_bufs);
6224843d 9890 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
0b8c0e7c
PB
9891 err = io_queue_rsrc_removal(ctx->buf_data, offset,
9892 ctx->rsrc_node, ctx->user_bufs[i]);
9893 if (unlikely(err)) {
9894 io_buffer_unmap(ctx, &imu);
634d00df 9895 break;
0b8c0e7c 9896 }
634d00df
PB
9897 ctx->user_bufs[i] = NULL;
9898 needs_switch = true;
9899 }
9900
0b8c0e7c 9901 ctx->user_bufs[i] = imu;
2d091d62 9902 *io_get_tag_slot(ctx->buf_data, offset) = tag;
634d00df
PB
9903 }
9904
9905 if (needs_switch)
9906 io_rsrc_node_switch(ctx, ctx->buf_data);
9907 return done ? done : err;
9908}
9909
c75312dd
UA
9910static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg,
9911 unsigned int eventfd_async)
9b402849 9912{
77bc59b4 9913 struct io_ev_fd *ev_fd;
9b402849 9914 __s32 __user *fds = arg;
f0a4e62b 9915 int fd;
9b402849 9916
77bc59b4
UA
9917 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9918 lockdep_is_held(&ctx->uring_lock));
9919 if (ev_fd)
9b402849
JA
9920 return -EBUSY;
9921
9922 if (copy_from_user(&fd, fds, sizeof(*fds)))
9923 return -EFAULT;
9924
77bc59b4
UA
9925 ev_fd = kmalloc(sizeof(*ev_fd), GFP_KERNEL);
9926 if (!ev_fd)
9927 return -ENOMEM;
fe7e3257 9928
77bc59b4
UA
9929 ev_fd->cq_ev_fd = eventfd_ctx_fdget(fd);
9930 if (IS_ERR(ev_fd->cq_ev_fd)) {
f0a4e62b 9931 int ret = PTR_ERR(ev_fd->cq_ev_fd);
77bc59b4 9932 kfree(ev_fd);
9b402849
JA
9933 return ret;
9934 }
c75312dd 9935 ev_fd->eventfd_async = eventfd_async;
9aa8dfde 9936 ctx->has_evfd = true;
77bc59b4 9937 rcu_assign_pointer(ctx->io_ev_fd, ev_fd);
f0a4e62b 9938 return 0;
77bc59b4
UA
9939}
9940
9941static void io_eventfd_put(struct rcu_head *rcu)
9942{
9943 struct io_ev_fd *ev_fd = container_of(rcu, struct io_ev_fd, rcu);
9944
9945 eventfd_ctx_put(ev_fd->cq_ev_fd);
9946 kfree(ev_fd);
9b402849
JA
9947}
9948
9949static int io_eventfd_unregister(struct io_ring_ctx *ctx)
9950{
77bc59b4
UA
9951 struct io_ev_fd *ev_fd;
9952
9953 ev_fd = rcu_dereference_protected(ctx->io_ev_fd,
9954 lockdep_is_held(&ctx->uring_lock));
9955 if (ev_fd) {
9aa8dfde 9956 ctx->has_evfd = false;
77bc59b4
UA
9957 rcu_assign_pointer(ctx->io_ev_fd, NULL);
9958 call_rcu(&ev_fd->rcu, io_eventfd_put);
9b402849
JA
9959 return 0;
9960 }
9961
9962 return -ENXIO;
9963}
9964
5a2e745d
JA
9965static void io_destroy_buffers(struct io_ring_ctx *ctx)
9966{
dbc7d452
JA
9967 int i;
9968
9969 for (i = 0; i < (1U << IO_BUFFERS_HASH_BITS); i++) {
9970 struct list_head *list = &ctx->io_buffers[i];
9e15c3a0 9971
dbc7d452
JA
9972 while (!list_empty(list)) {
9973 struct io_buffer_list *bl;
9974
9975 bl = list_first_entry(list, struct io_buffer_list, list);
9976 __io_remove_buffers(ctx, bl, -1U);
9977 list_del(&bl->list);
9978 kfree(bl);
9979 }
9980 }
cc3cec83
JA
9981
9982 while (!list_empty(&ctx->io_buffers_pages)) {
9983 struct page *page;
9984
9985 page = list_first_entry(&ctx->io_buffers_pages, struct page, lru);
9986 list_del_init(&page->lru);
9987 __free_page(page);
9988 }
5a2e745d
JA
9989}
9990
4010fec4 9991static void io_req_caches_free(struct io_ring_ctx *ctx)
2b188cc1 9992{
cd0ca2e0 9993 struct io_submit_state *state = &ctx->submit_state;
37f0e767 9994 int nr = 0;
bf019da7 9995
9a4fdbd8 9996 mutex_lock(&ctx->uring_lock);
cd0ca2e0 9997 io_flush_cached_locked_reqs(ctx, state);
9a4fdbd8 9998
c2b6c6bc
PB
9999 while (state->free_list.next) {
10000 struct io_wq_work_node *node;
10001 struct io_kiocb *req;
9a4fdbd8 10002
c2b6c6bc
PB
10003 node = wq_stack_extract(&state->free_list);
10004 req = container_of(node, struct io_kiocb, comp_list);
10005 kmem_cache_free(req_cachep, req);
37f0e767 10006 nr++;
c2b6c6bc 10007 }
37f0e767
PB
10008 if (nr)
10009 percpu_ref_put_many(&ctx->refs, nr);
9a4fdbd8
JA
10010 mutex_unlock(&ctx->uring_lock);
10011}
10012
43597aac 10013static void io_wait_rsrc_data(struct io_rsrc_data *data)
2b188cc1 10014{
43597aac 10015 if (data && !atomic_dec_and_test(&data->refs))
bd54b6fe 10016 wait_for_completion(&data->done);
bd54b6fe 10017}
04fc6c80 10018
4d9237e3
JA
10019static void io_flush_apoll_cache(struct io_ring_ctx *ctx)
10020{
10021 struct async_poll *apoll;
10022
10023 while (!list_empty(&ctx->apoll_cache)) {
10024 apoll = list_first_entry(&ctx->apoll_cache, struct async_poll,
10025 poll.wait.entry);
10026 list_del(&apoll->poll.wait.entry);
10027 kfree(apoll);
10028 }
10029}
10030
c072481d 10031static __cold void io_ring_ctx_free(struct io_ring_ctx *ctx)
2b188cc1 10032{
37d1e2e3 10033 io_sq_thread_finish(ctx);
2aede0e4 10034
37d1e2e3 10035 if (ctx->mm_account) {
2aede0e4
JA
10036 mmdrop(ctx->mm_account);
10037 ctx->mm_account = NULL;
30975825 10038 }
def596e9 10039
ab409402 10040 io_rsrc_refs_drop(ctx);
43597aac
PB
10041 /* __io_rsrc_put_work() may need uring_lock to progress, wait w/o it */
10042 io_wait_rsrc_data(ctx->buf_data);
10043 io_wait_rsrc_data(ctx->file_data);
10044
8bad28d8 10045 mutex_lock(&ctx->uring_lock);
43597aac 10046 if (ctx->buf_data)
bd54b6fe 10047 __io_sqe_buffers_unregister(ctx);
43597aac 10048 if (ctx->file_data)
08480400 10049 __io_sqe_files_unregister(ctx);
c4ea060e
PB
10050 if (ctx->rings)
10051 __io_cqring_overflow_flush(ctx, true);
9b402849 10052 io_eventfd_unregister(ctx);
4d9237e3 10053 io_flush_apoll_cache(ctx);
77bc59b4 10054 mutex_unlock(&ctx->uring_lock);
5a2e745d 10055 io_destroy_buffers(ctx);
07db298a
PB
10056 if (ctx->sq_creds)
10057 put_cred(ctx->sq_creds);
def596e9 10058
a7f0ed5a
PB
10059 /* there are no registered resources left, nobody uses it */
10060 if (ctx->rsrc_node)
10061 io_rsrc_node_destroy(ctx->rsrc_node);
8dd03afe 10062 if (ctx->rsrc_backup_node)
b895c9a6 10063 io_rsrc_node_destroy(ctx->rsrc_backup_node);
a7f0ed5a 10064 flush_delayed_work(&ctx->rsrc_put_work);
756ab7c0 10065 flush_delayed_work(&ctx->fallback_work);
a7f0ed5a
PB
10066
10067 WARN_ON_ONCE(!list_empty(&ctx->rsrc_ref_list));
10068 WARN_ON_ONCE(!llist_empty(&ctx->rsrc_put_llist));
def596e9 10069
2b188cc1 10070#if defined(CONFIG_UNIX)
355e8d26
EB
10071 if (ctx->ring_sock) {
10072 ctx->ring_sock->file = NULL; /* so that iput() is called */
2b188cc1 10073 sock_release(ctx->ring_sock);
355e8d26 10074 }
2b188cc1 10075#endif
ef9dd637 10076 WARN_ON_ONCE(!list_empty(&ctx->ltimeout_list));
2b188cc1 10077
75b28aff 10078 io_mem_free(ctx->rings);
2b188cc1 10079 io_mem_free(ctx->sq_sqes);
2b188cc1
JA
10080
10081 percpu_ref_exit(&ctx->refs);
2b188cc1 10082 free_uid(ctx->user);
4010fec4 10083 io_req_caches_free(ctx);
e941894e
JA
10084 if (ctx->hash_map)
10085 io_wq_put_hash(ctx->hash_map);
adc8682e 10086 io_free_napi_list(ctx);
78076bb6 10087 kfree(ctx->cancel_hash);
6224843d 10088 kfree(ctx->dummy_ubuf);
dbc7d452 10089 kfree(ctx->io_buffers);
2b188cc1
JA
10090 kfree(ctx);
10091}
10092
10093static __poll_t io_uring_poll(struct file *file, poll_table *wait)
10094{
10095 struct io_ring_ctx *ctx = file->private_data;
10096 __poll_t mask = 0;
10097
d60aa65b 10098 poll_wait(file, &ctx->cq_wait, wait);
4f7067c3
SB
10099 /*
10100 * synchronizes with barrier from wq_has_sleeper call in
10101 * io_commit_cqring
10102 */
2b188cc1 10103 smp_rmb();
90554200 10104 if (!io_sqring_full(ctx))
2b188cc1 10105 mask |= EPOLLOUT | EPOLLWRNORM;
ed670c3f
HX
10106
10107 /*
10108 * Don't flush cqring overflow list here, just do a simple check.
10109 * Otherwise there could possible be ABBA deadlock:
10110 * CPU0 CPU1
10111 * ---- ----
10112 * lock(&ctx->uring_lock);
10113 * lock(&ep->mtx);
10114 * lock(&ctx->uring_lock);
10115 * lock(&ep->mtx);
10116 *
10117 * Users may get EPOLLIN meanwhile seeing nothing in cqring, this
10118 * pushs them to do the flush.
10119 */
5ed7a37d 10120 if (io_cqring_events(ctx) || test_bit(0, &ctx->check_cq_overflow))
2b188cc1
JA
10121 mask |= EPOLLIN | EPOLLRDNORM;
10122
10123 return mask;
10124}
10125
0bead8cd 10126static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
071698e1 10127{
4379bf8b 10128 const struct cred *creds;
071698e1 10129
61cf9370 10130 creds = xa_erase(&ctx->personalities, id);
4379bf8b
JA
10131 if (creds) {
10132 put_cred(creds);
0bead8cd 10133 return 0;
1e6fa521 10134 }
0bead8cd
YD
10135
10136 return -EINVAL;
10137}
10138
d56d938b
PB
10139struct io_tctx_exit {
10140 struct callback_head task_work;
10141 struct completion completion;
baf186c4 10142 struct io_ring_ctx *ctx;
d56d938b
PB
10143};
10144
c072481d 10145static __cold void io_tctx_exit_cb(struct callback_head *cb)
d56d938b
PB
10146{
10147 struct io_uring_task *tctx = current->io_uring;
10148 struct io_tctx_exit *work;
10149
10150 work = container_of(cb, struct io_tctx_exit, task_work);
10151 /*
10152 * When @in_idle, we're in cancellation and it's racy to remove the
10153 * node. It'll be removed by the end of cancellation, just ignore it.
10154 */
10155 if (!atomic_read(&tctx->in_idle))
eef51daa 10156 io_uring_del_tctx_node((unsigned long)work->ctx);
d56d938b
PB
10157 complete(&work->completion);
10158}
10159
c072481d 10160static __cold bool io_cancel_ctx_cb(struct io_wq_work *work, void *data)
28090c13
PB
10161{
10162 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
10163
10164 return req->ctx == data;
10165}
10166
c072481d 10167static __cold void io_ring_exit_work(struct work_struct *work)
85faa7b8 10168{
d56d938b 10169 struct io_ring_ctx *ctx = container_of(work, struct io_ring_ctx, exit_work);
b5bb3a24 10170 unsigned long timeout = jiffies + HZ * 60 * 5;
58d3be2c 10171 unsigned long interval = HZ / 20;
d56d938b
PB
10172 struct io_tctx_exit exit;
10173 struct io_tctx_node *node;
10174 int ret;
85faa7b8 10175
56952e91
JA
10176 /*
10177 * If we're doing polled IO and end up having requests being
10178 * submitted async (out-of-line), then completions can come in while
10179 * we're waiting for refs to drop. We need to reap these manually,
10180 * as nobody else will be looking for them.
10181 */
b2edc0a7 10182 do {
3dd0c97a 10183 io_uring_try_cancel_requests(ctx, NULL, true);
28090c13
PB
10184 if (ctx->sq_data) {
10185 struct io_sq_data *sqd = ctx->sq_data;
10186 struct task_struct *tsk;
10187
10188 io_sq_thread_park(sqd);
10189 tsk = sqd->thread;
10190 if (tsk && tsk->io_uring && tsk->io_uring->io_wq)
10191 io_wq_cancel_cb(tsk->io_uring->io_wq,
10192 io_cancel_ctx_cb, ctx, true);
10193 io_sq_thread_unpark(sqd);
10194 }
b5bb3a24 10195
37f0e767
PB
10196 io_req_caches_free(ctx);
10197
58d3be2c
PB
10198 if (WARN_ON_ONCE(time_after(jiffies, timeout))) {
10199 /* there is little hope left, don't run it too often */
10200 interval = HZ * 60;
10201 }
10202 } while (!wait_for_completion_timeout(&ctx->ref_comp, interval));
d56d938b 10203
7f00651a
PB
10204 init_completion(&exit.completion);
10205 init_task_work(&exit.task_work, io_tctx_exit_cb);
10206 exit.ctx = ctx;
89b5066e
PB
10207 /*
10208 * Some may use context even when all refs and requests have been put,
10209 * and they are free to do so while still holding uring_lock or
5b0a6acc 10210 * completion_lock, see io_req_task_submit(). Apart from other work,
89b5066e
PB
10211 * this lock/unlock section also waits them to finish.
10212 */
d56d938b
PB
10213 mutex_lock(&ctx->uring_lock);
10214 while (!list_empty(&ctx->tctx_list)) {
b5bb3a24
PB
10215 WARN_ON_ONCE(time_after(jiffies, timeout));
10216
d56d938b
PB
10217 node = list_first_entry(&ctx->tctx_list, struct io_tctx_node,
10218 ctx_node);
7f00651a
PB
10219 /* don't spin on a single task if cancellation failed */
10220 list_rotate_left(&ctx->tctx_list);
d56d938b
PB
10221 ret = task_work_add(node->task, &exit.task_work, TWA_SIGNAL);
10222 if (WARN_ON_ONCE(ret))
10223 continue;
d56d938b
PB
10224
10225 mutex_unlock(&ctx->uring_lock);
10226 wait_for_completion(&exit.completion);
d56d938b
PB
10227 mutex_lock(&ctx->uring_lock);
10228 }
10229 mutex_unlock(&ctx->uring_lock);
79ebeaee
JA
10230 spin_lock(&ctx->completion_lock);
10231 spin_unlock(&ctx->completion_lock);
d56d938b 10232
85faa7b8
JA
10233 io_ring_ctx_free(ctx);
10234}
10235
80c4cbdb 10236/* Returns true if we found and killed one or more timeouts */
c072481d
PB
10237static __cold bool io_kill_timeouts(struct io_ring_ctx *ctx,
10238 struct task_struct *tsk, bool cancel_all)
80c4cbdb
PB
10239{
10240 struct io_kiocb *req, *tmp;
10241 int canceled = 0;
10242
79ebeaee
JA
10243 spin_lock(&ctx->completion_lock);
10244 spin_lock_irq(&ctx->timeout_lock);
80c4cbdb 10245 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, timeout.list) {
3dd0c97a 10246 if (io_match_task(req, tsk, cancel_all)) {
80c4cbdb
PB
10247 io_kill_timeout(req, -ECANCELED);
10248 canceled++;
10249 }
10250 }
79ebeaee 10251 spin_unlock_irq(&ctx->timeout_lock);
51520426
PB
10252 if (canceled != 0)
10253 io_commit_cqring(ctx);
79ebeaee 10254 spin_unlock(&ctx->completion_lock);
80c4cbdb
PB
10255 if (canceled != 0)
10256 io_cqring_ev_posted(ctx);
10257 return canceled != 0;
10258}
10259
c072481d 10260static __cold void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
2b188cc1 10261{
61cf9370
MWO
10262 unsigned long index;
10263 struct creds *creds;
10264
2b188cc1
JA
10265 mutex_lock(&ctx->uring_lock);
10266 percpu_ref_kill(&ctx->refs);
634578f8 10267 if (ctx->rings)
6c2450ae 10268 __io_cqring_overflow_flush(ctx, true);
61cf9370
MWO
10269 xa_for_each(&ctx->personalities, index, creds)
10270 io_unregister_personality(ctx, index);
2b188cc1
JA
10271 mutex_unlock(&ctx->uring_lock);
10272
3dd0c97a
PB
10273 io_kill_timeouts(ctx, NULL, true);
10274 io_poll_remove_all(ctx, NULL, true);
561fb04a 10275
15dff286 10276 /* if we failed setting up the ctx, we might not have any rings */
b2edc0a7 10277 io_iopoll_try_reap_events(ctx);
309fc03a 10278
85faa7b8 10279 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
fc666777
JA
10280 /*
10281 * Use system_unbound_wq to avoid spawning tons of event kworkers
10282 * if we're exiting a ton of rings at the same time. It just adds
10283 * noise and overhead, there's no discernable change in runtime
10284 * over using system_wq.
10285 */
10286 queue_work(system_unbound_wq, &ctx->exit_work);
2b188cc1
JA
10287}
10288
10289static int io_uring_release(struct inode *inode, struct file *file)
10290{
10291 struct io_ring_ctx *ctx = file->private_data;
10292
10293 file->private_data = NULL;
10294 io_ring_ctx_wait_and_kill(ctx);
10295 return 0;
10296}
10297
f6edbabb
PB
10298struct io_task_cancel {
10299 struct task_struct *task;
3dd0c97a 10300 bool all;
f6edbabb 10301};
f254ac04 10302
f6edbabb 10303static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
b711d4ea 10304{
9a472ef7 10305 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
f6edbabb 10306 struct io_task_cancel *cancel = data;
9a472ef7 10307
6af3f48b 10308 return io_match_task_safe(req, cancel->task, cancel->all);
b711d4ea
JA
10309}
10310
c072481d
PB
10311static __cold bool io_cancel_defer_files(struct io_ring_ctx *ctx,
10312 struct task_struct *task,
10313 bool cancel_all)
b7ddce3c 10314{
e1915f76 10315 struct io_defer_entry *de;
b7ddce3c
PB
10316 LIST_HEAD(list);
10317
79ebeaee 10318 spin_lock(&ctx->completion_lock);
b7ddce3c 10319 list_for_each_entry_reverse(de, &ctx->defer_list, list) {
6af3f48b 10320 if (io_match_task_safe(de->req, task, cancel_all)) {
b7ddce3c
PB
10321 list_cut_position(&list, &ctx->defer_list, &de->list);
10322 break;
10323 }
10324 }
79ebeaee 10325 spin_unlock(&ctx->completion_lock);
e1915f76
PB
10326 if (list_empty(&list))
10327 return false;
b7ddce3c
PB
10328
10329 while (!list_empty(&list)) {
10330 de = list_first_entry(&list, struct io_defer_entry, list);
10331 list_del_init(&de->list);
f41db273 10332 io_req_complete_failed(de->req, -ECANCELED);
b7ddce3c
PB
10333 kfree(de);
10334 }
e1915f76 10335 return true;
b7ddce3c
PB
10336}
10337
c072481d 10338static __cold bool io_uring_try_cancel_iowq(struct io_ring_ctx *ctx)
1b00764f
PB
10339{
10340 struct io_tctx_node *node;
10341 enum io_wq_cancel cret;
10342 bool ret = false;
10343
10344 mutex_lock(&ctx->uring_lock);
10345 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
10346 struct io_uring_task *tctx = node->task->io_uring;
10347
10348 /*
10349 * io_wq will stay alive while we hold uring_lock, because it's
10350 * killed after ctx nodes, which requires to take the lock.
10351 */
10352 if (!tctx || !tctx->io_wq)
10353 continue;
10354 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_ctx_cb, ctx, true);
10355 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10356 }
10357 mutex_unlock(&ctx->uring_lock);
10358
10359 return ret;
10360}
10361
c072481d
PB
10362static __cold void io_uring_try_cancel_requests(struct io_ring_ctx *ctx,
10363 struct task_struct *task,
10364 bool cancel_all)
9936c7c2 10365{
3dd0c97a 10366 struct io_task_cancel cancel = { .task = task, .all = cancel_all, };
1b00764f 10367 struct io_uring_task *tctx = task ? task->io_uring : NULL;
9936c7c2
PB
10368
10369 while (1) {
10370 enum io_wq_cancel cret;
10371 bool ret = false;
10372
1b00764f
PB
10373 if (!task) {
10374 ret |= io_uring_try_cancel_iowq(ctx);
10375 } else if (tctx && tctx->io_wq) {
10376 /*
10377 * Cancels requests of all rings, not only @ctx, but
10378 * it's fine as the task is in exit/exec.
10379 */
5aa75ed5 10380 cret = io_wq_cancel_cb(tctx->io_wq, io_cancel_task_cb,
9936c7c2
PB
10381 &cancel, true);
10382 ret |= (cret != IO_WQ_CANCEL_NOTFOUND);
10383 }
10384
10385 /* SQPOLL thread does its own polling */
3dd0c97a 10386 if ((!(ctx->flags & IORING_SETUP_SQPOLL) && cancel_all) ||
d052d1d6 10387 (ctx->sq_data && ctx->sq_data->thread == current)) {
5eef4e87 10388 while (!wq_list_empty(&ctx->iopoll_list)) {
9936c7c2
PB
10389 io_iopoll_try_reap_events(ctx);
10390 ret = true;
10391 }
10392 }
10393
3dd0c97a
PB
10394 ret |= io_cancel_defer_files(ctx, task, cancel_all);
10395 ret |= io_poll_remove_all(ctx, task, cancel_all);
10396 ret |= io_kill_timeouts(ctx, task, cancel_all);
e5dc480d
PB
10397 if (task)
10398 ret |= io_run_task_work();
9936c7c2
PB
10399 if (!ret)
10400 break;
10401 cond_resched();
10402 }
10403}
10404
eef51daa 10405static int __io_uring_add_tctx_node(struct io_ring_ctx *ctx)
0f212204 10406{
236434c3 10407 struct io_uring_task *tctx = current->io_uring;
13bf43f5 10408 struct io_tctx_node *node;
a528b04e 10409 int ret;
236434c3
MWO
10410
10411 if (unlikely(!tctx)) {
5aa75ed5 10412 ret = io_uring_alloc_task_context(current, ctx);
0f212204
JA
10413 if (unlikely(ret))
10414 return ret;
e139a1ec 10415
236434c3 10416 tctx = current->io_uring;
e139a1ec
PB
10417 if (ctx->iowq_limits_set) {
10418 unsigned int limits[2] = { ctx->iowq_limits[0],
10419 ctx->iowq_limits[1], };
10420
10421 ret = io_wq_max_workers(tctx->io_wq, limits);
10422 if (ret)
10423 return ret;
10424 }
0f212204 10425 }
cf27f3b1
PB
10426 if (!xa_load(&tctx->xa, (unsigned long)ctx)) {
10427 node = kmalloc(sizeof(*node), GFP_KERNEL);
10428 if (!node)
10429 return -ENOMEM;
10430 node->ctx = ctx;
10431 node->task = current;
13bf43f5 10432
cf27f3b1
PB
10433 ret = xa_err(xa_store(&tctx->xa, (unsigned long)ctx,
10434 node, GFP_KERNEL));
10435 if (ret) {
10436 kfree(node);
10437 return ret;
0f212204 10438 }
cf27f3b1
PB
10439
10440 mutex_lock(&ctx->uring_lock);
10441 list_add(&node->ctx_node, &ctx->tctx_list);
10442 mutex_unlock(&ctx->uring_lock);
0f212204 10443 }
cf27f3b1 10444 tctx->last = ctx;
0f212204
JA
10445 return 0;
10446}
10447
cf27f3b1
PB
10448/*
10449 * Note that this task has used io_uring. We use it for cancelation purposes.
10450 */
eef51daa 10451static inline int io_uring_add_tctx_node(struct io_ring_ctx *ctx)
cf27f3b1
PB
10452{
10453 struct io_uring_task *tctx = current->io_uring;
10454
10455 if (likely(tctx && tctx->last == ctx))
10456 return 0;
eef51daa 10457 return __io_uring_add_tctx_node(ctx);
cf27f3b1
PB
10458}
10459
0f212204
JA
10460/*
10461 * Remove this io_uring_file -> task mapping.
10462 */
c072481d 10463static __cold void io_uring_del_tctx_node(unsigned long index)
0f212204
JA
10464{
10465 struct io_uring_task *tctx = current->io_uring;
13bf43f5 10466 struct io_tctx_node *node;
2941267b 10467
eebd2e37
PB
10468 if (!tctx)
10469 return;
13bf43f5
PB
10470 node = xa_erase(&tctx->xa, index);
10471 if (!node)
2941267b 10472 return;
0f212204 10473
13bf43f5
PB
10474 WARN_ON_ONCE(current != node->task);
10475 WARN_ON_ONCE(list_empty(&node->ctx_node));
10476
10477 mutex_lock(&node->ctx->uring_lock);
10478 list_del(&node->ctx_node);
10479 mutex_unlock(&node->ctx->uring_lock);
10480
baf186c4 10481 if (tctx->last == node->ctx)
0f212204 10482 tctx->last = NULL;
13bf43f5 10483 kfree(node);
0f212204
JA
10484}
10485
c072481d 10486static __cold void io_uring_clean_tctx(struct io_uring_task *tctx)
de7f1d9e 10487{
ba5ef6dc 10488 struct io_wq *wq = tctx->io_wq;
13bf43f5 10489 struct io_tctx_node *node;
de7f1d9e
PB
10490 unsigned long index;
10491
8bab4c09 10492 xa_for_each(&tctx->xa, index, node) {
eef51daa 10493 io_uring_del_tctx_node(index);
8bab4c09
JA
10494 cond_resched();
10495 }
b16ef427
ME
10496 if (wq) {
10497 /*
f6f9b278 10498 * Must be after io_uring_del_tctx_node() (removes nodes under
b16ef427
ME
10499 * uring_lock) to avoid race with io_uring_try_cancel_iowq().
10500 */
ba5ef6dc 10501 io_wq_put_and_exit(wq);
dadebc35 10502 tctx->io_wq = NULL;
b16ef427 10503 }
de7f1d9e
PB
10504}
10505
3f48cf18 10506static s64 tctx_inflight(struct io_uring_task *tctx, bool tracked)
521d6a73 10507{
3f48cf18
PB
10508 if (tracked)
10509 return atomic_read(&tctx->inflight_tracked);
521d6a73
PB
10510 return percpu_counter_sum(&tctx->inflight);
10511}
10512
78cc687b
PB
10513/*
10514 * Find any io_uring ctx that this task has registered or done IO on, and cancel
78a78060 10515 * requests. @sqd should be not-null IFF it's an SQPOLL thread cancellation.
78cc687b 10516 */
c072481d
PB
10517static __cold void io_uring_cancel_generic(bool cancel_all,
10518 struct io_sq_data *sqd)
0e9ddb39 10519{
521d6a73 10520 struct io_uring_task *tctx = current->io_uring;
734551df 10521 struct io_ring_ctx *ctx;
0e9ddb39
PB
10522 s64 inflight;
10523 DEFINE_WAIT(wait);
fdaf083c 10524
78cc687b
PB
10525 WARN_ON_ONCE(sqd && sqd->thread != current);
10526
6d042ffb
PO
10527 if (!current->io_uring)
10528 return;
17a91051
PB
10529 if (tctx->io_wq)
10530 io_wq_exit_start(tctx->io_wq);
10531
0e9ddb39
PB
10532 atomic_inc(&tctx->in_idle);
10533 do {
e9dbe221 10534 io_uring_drop_tctx_refs(current);
0e9ddb39 10535 /* read completions before cancelations */
78cc687b 10536 inflight = tctx_inflight(tctx, !cancel_all);
0e9ddb39
PB
10537 if (!inflight)
10538 break;
fdaf083c 10539
78cc687b
PB
10540 if (!sqd) {
10541 struct io_tctx_node *node;
10542 unsigned long index;
0f212204 10543
78cc687b
PB
10544 xa_for_each(&tctx->xa, index, node) {
10545 /* sqpoll task will cancel all its requests */
10546 if (node->ctx->sq_data)
10547 continue;
10548 io_uring_try_cancel_requests(node->ctx, current,
10549 cancel_all);
10550 }
10551 } else {
10552 list_for_each_entry(ctx, &sqd->ctx_list, sqd_list)
10553 io_uring_try_cancel_requests(ctx, current,
10554 cancel_all);
10555 }
17a91051 10556
78a78060
JA
10557 prepare_to_wait(&tctx->wait, &wait, TASK_INTERRUPTIBLE);
10558 io_run_task_work();
e9dbe221 10559 io_uring_drop_tctx_refs(current);
78a78060 10560
0f212204 10561 /*
a1bb3cd5
PB
10562 * If we've seen completions, retry without waiting. This
10563 * avoids a race where a completion comes in before we did
10564 * prepare_to_wait().
0f212204 10565 */
3dd0c97a 10566 if (inflight == tctx_inflight(tctx, !cancel_all))
a1bb3cd5 10567 schedule();
f57555ed 10568 finish_wait(&tctx->wait, &wait);
d8a6df10 10569 } while (1);
de7f1d9e 10570
8452d4a6 10571 io_uring_clean_tctx(tctx);
3dd0c97a 10572 if (cancel_all) {
3cc7fdb9
PB
10573 /*
10574 * We shouldn't run task_works after cancel, so just leave
10575 * ->in_idle set for normal exit.
10576 */
10577 atomic_dec(&tctx->in_idle);
3f48cf18
PB
10578 /* for exec all current's requests should be gone, kill tctx */
10579 __io_uring_free(current);
10580 }
44e728b8
PB
10581}
10582
f552a27a 10583void __io_uring_cancel(bool cancel_all)
78cc687b 10584{
f552a27a 10585 io_uring_cancel_generic(cancel_all, NULL);
78cc687b
PB
10586}
10587
e7a6c00d
JA
10588void io_uring_unreg_ringfd(void)
10589{
10590 struct io_uring_task *tctx = current->io_uring;
10591 int i;
10592
10593 for (i = 0; i < IO_RINGFD_REG_MAX; i++) {
10594 if (tctx->registered_rings[i]) {
10595 fput(tctx->registered_rings[i]);
10596 tctx->registered_rings[i] = NULL;
10597 }
10598 }
10599}
10600
10601static int io_ring_add_registered_fd(struct io_uring_task *tctx, int fd,
10602 int start, int end)
10603{
10604 struct file *file;
10605 int offset;
10606
10607 for (offset = start; offset < end; offset++) {
10608 offset = array_index_nospec(offset, IO_RINGFD_REG_MAX);
10609 if (tctx->registered_rings[offset])
10610 continue;
10611
10612 file = fget(fd);
10613 if (!file) {
10614 return -EBADF;
10615 } else if (file->f_op != &io_uring_fops) {
10616 fput(file);
10617 return -EOPNOTSUPP;
10618 }
10619 tctx->registered_rings[offset] = file;
10620 return offset;
10621 }
10622
10623 return -EBUSY;
10624}
10625
10626/*
10627 * Register a ring fd to avoid fdget/fdput for each io_uring_enter()
10628 * invocation. User passes in an array of struct io_uring_rsrc_update
10629 * with ->data set to the ring_fd, and ->offset given for the desired
10630 * index. If no index is desired, application may set ->offset == -1U
10631 * and we'll find an available index. Returns number of entries
10632 * successfully processed, or < 0 on error if none were processed.
10633 */
10634static int io_ringfd_register(struct io_ring_ctx *ctx, void __user *__arg,
10635 unsigned nr_args)
10636{
10637 struct io_uring_rsrc_update __user *arg = __arg;
10638 struct io_uring_rsrc_update reg;
10639 struct io_uring_task *tctx;
10640 int ret, i;
10641
10642 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10643 return -EINVAL;
10644
10645 mutex_unlock(&ctx->uring_lock);
10646 ret = io_uring_add_tctx_node(ctx);
10647 mutex_lock(&ctx->uring_lock);
10648 if (ret)
10649 return ret;
10650
10651 tctx = current->io_uring;
10652 for (i = 0; i < nr_args; i++) {
10653 int start, end;
10654
10655 if (copy_from_user(&reg, &arg[i], sizeof(reg))) {
10656 ret = -EFAULT;
10657 break;
10658 }
10659
10660 if (reg.offset == -1U) {
10661 start = 0;
10662 end = IO_RINGFD_REG_MAX;
10663 } else {
10664 if (reg.offset >= IO_RINGFD_REG_MAX) {
10665 ret = -EINVAL;
10666 break;
10667 }
10668 start = reg.offset;
10669 end = start + 1;
10670 }
10671
10672 ret = io_ring_add_registered_fd(tctx, reg.data, start, end);
10673 if (ret < 0)
10674 break;
10675
10676 reg.offset = ret;
10677 if (copy_to_user(&arg[i], &reg, sizeof(reg))) {
10678 fput(tctx->registered_rings[reg.offset]);
10679 tctx->registered_rings[reg.offset] = NULL;
10680 ret = -EFAULT;
10681 break;
10682 }
10683 }
10684
10685 return i ? i : ret;
10686}
10687
10688static int io_ringfd_unregister(struct io_ring_ctx *ctx, void __user *__arg,
10689 unsigned nr_args)
10690{
10691 struct io_uring_rsrc_update __user *arg = __arg;
10692 struct io_uring_task *tctx = current->io_uring;
10693 struct io_uring_rsrc_update reg;
10694 int ret = 0, i;
10695
10696 if (!nr_args || nr_args > IO_RINGFD_REG_MAX)
10697 return -EINVAL;
10698 if (!tctx)
10699 return 0;
10700
10701 for (i = 0; i < nr_args; i++) {
10702 if (copy_from_user(&reg, &arg[i], sizeof(reg))) {
10703 ret = -EFAULT;
10704 break;
10705 }
10706 if (reg.offset >= IO_RINGFD_REG_MAX) {
10707 ret = -EINVAL;
10708 break;
10709 }
10710
10711 reg.offset = array_index_nospec(reg.offset, IO_RINGFD_REG_MAX);
10712 if (tctx->registered_rings[reg.offset]) {
10713 fput(tctx->registered_rings[reg.offset]);
10714 tctx->registered_rings[reg.offset] = NULL;
10715 }
10716 }
10717
10718 return i ? i : ret;
10719}
10720
6c5c240e
RP
10721static void *io_uring_validate_mmap_request(struct file *file,
10722 loff_t pgoff, size_t sz)
2b188cc1 10723{
2b188cc1 10724 struct io_ring_ctx *ctx = file->private_data;
6c5c240e 10725 loff_t offset = pgoff << PAGE_SHIFT;
2b188cc1
JA
10726 struct page *page;
10727 void *ptr;
10728
10729 switch (offset) {
10730 case IORING_OFF_SQ_RING:
75b28aff
HV
10731 case IORING_OFF_CQ_RING:
10732 ptr = ctx->rings;
2b188cc1
JA
10733 break;
10734 case IORING_OFF_SQES:
10735 ptr = ctx->sq_sqes;
10736 break;
2b188cc1 10737 default:
6c5c240e 10738 return ERR_PTR(-EINVAL);
2b188cc1
JA
10739 }
10740
10741 page = virt_to_head_page(ptr);
a50b854e 10742 if (sz > page_size(page))
6c5c240e
RP
10743 return ERR_PTR(-EINVAL);
10744
10745 return ptr;
10746}
10747
10748#ifdef CONFIG_MMU
10749
c072481d 10750static __cold int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
6c5c240e
RP
10751{
10752 size_t sz = vma->vm_end - vma->vm_start;
10753 unsigned long pfn;
10754 void *ptr;
10755
10756 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
10757 if (IS_ERR(ptr))
10758 return PTR_ERR(ptr);
2b188cc1
JA
10759
10760 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
10761 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
10762}
10763
6c5c240e
RP
10764#else /* !CONFIG_MMU */
10765
10766static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
10767{
10768 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
10769}
10770
10771static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
10772{
10773 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
10774}
10775
10776static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
10777 unsigned long addr, unsigned long len,
10778 unsigned long pgoff, unsigned long flags)
10779{
10780 void *ptr;
10781
10782 ptr = io_uring_validate_mmap_request(file, pgoff, len);
10783 if (IS_ERR(ptr))
10784 return PTR_ERR(ptr);
10785
10786 return (unsigned long) ptr;
10787}
10788
10789#endif /* !CONFIG_MMU */
10790
d9d05217 10791static int io_sqpoll_wait_sq(struct io_ring_ctx *ctx)
90554200
JA
10792{
10793 DEFINE_WAIT(wait);
10794
10795 do {
10796 if (!io_sqring_full(ctx))
10797 break;
90554200
JA
10798 prepare_to_wait(&ctx->sqo_sq_wait, &wait, TASK_INTERRUPTIBLE);
10799
10800 if (!io_sqring_full(ctx))
10801 break;
90554200
JA
10802 schedule();
10803 } while (!signal_pending(current));
10804
10805 finish_wait(&ctx->sqo_sq_wait, &wait);
5199328a 10806 return 0;
90554200
JA
10807}
10808
c73ebb68
HX
10809static int io_get_ext_arg(unsigned flags, const void __user *argp, size_t *argsz,
10810 struct __kernel_timespec __user **ts,
10811 const sigset_t __user **sig)
10812{
10813 struct io_uring_getevents_arg arg;
10814
10815 /*
10816 * If EXT_ARG isn't set, then we have no timespec and the argp pointer
10817 * is just a pointer to the sigset_t.
10818 */
10819 if (!(flags & IORING_ENTER_EXT_ARG)) {
10820 *sig = (const sigset_t __user *) argp;
10821 *ts = NULL;
10822 return 0;
10823 }
10824
10825 /*
10826 * EXT_ARG is set - ensure we agree on the size of it and copy in our
10827 * timespec and sigset_t pointers if good.
10828 */
10829 if (*argsz != sizeof(arg))
10830 return -EINVAL;
10831 if (copy_from_user(&arg, argp, sizeof(arg)))
10832 return -EFAULT;
10833 *sig = u64_to_user_ptr(arg.sigmask);
10834 *argsz = arg.sigmask_sz;
10835 *ts = u64_to_user_ptr(arg.ts);
10836 return 0;
10837}
10838
2b188cc1 10839SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
c73ebb68
HX
10840 u32, min_complete, u32, flags, const void __user *, argp,
10841 size_t, argsz)
2b188cc1
JA
10842{
10843 struct io_ring_ctx *ctx;
2b188cc1
JA
10844 int submitted = 0;
10845 struct fd f;
33f993da 10846 long ret;
2b188cc1 10847
4c6e277c 10848 io_run_task_work();
b41e9852 10849
33f993da 10850 if (unlikely(flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP |
e7a6c00d
JA
10851 IORING_ENTER_SQ_WAIT | IORING_ENTER_EXT_ARG |
10852 IORING_ENTER_REGISTERED_RING)))
2b188cc1
JA
10853 return -EINVAL;
10854
e7a6c00d
JA
10855 /*
10856 * Ring fd has been registered via IORING_REGISTER_RING_FDS, we
10857 * need only dereference our task private array to find it.
10858 */
10859 if (flags & IORING_ENTER_REGISTERED_RING) {
10860 struct io_uring_task *tctx = current->io_uring;
10861
10862 if (!tctx || fd >= IO_RINGFD_REG_MAX)
10863 return -EINVAL;
10864 fd = array_index_nospec(fd, IO_RINGFD_REG_MAX);
10865 f.file = tctx->registered_rings[fd];
10866 if (unlikely(!f.file))
10867 return -EBADF;
10868 } else {
10869 f = fdget(fd);
10870 if (unlikely(!f.file))
10871 return -EBADF;
10872 }
2b188cc1
JA
10873
10874 ret = -EOPNOTSUPP;
33f993da 10875 if (unlikely(f.file->f_op != &io_uring_fops))
2b188cc1
JA
10876 goto out_fput;
10877
10878 ret = -ENXIO;
10879 ctx = f.file->private_data;
33f993da 10880 if (unlikely(!percpu_ref_tryget(&ctx->refs)))
2b188cc1
JA
10881 goto out_fput;
10882
7e84e1c7 10883 ret = -EBADFD;
33f993da 10884 if (unlikely(ctx->flags & IORING_SETUP_R_DISABLED))
7e84e1c7
SG
10885 goto out;
10886
6c271ce2
JA
10887 /*
10888 * For SQ polling, the thread will do all submissions and completions.
10889 * Just return the requested submit count, and wake the thread if
10890 * we were asked to.
10891 */
b2a9eada 10892 ret = 0;
6c271ce2 10893 if (ctx->flags & IORING_SETUP_SQPOLL) {
90f67366 10894 io_cqring_overflow_flush(ctx);
89448c47 10895
21f96522
JA
10896 if (unlikely(ctx->sq_data->thread == NULL)) {
10897 ret = -EOWNERDEAD;
04147488 10898 goto out;
21f96522 10899 }
6c271ce2 10900 if (flags & IORING_ENTER_SQ_WAKEUP)
534ca6d6 10901 wake_up(&ctx->sq_data->wait);
d9d05217
PB
10902 if (flags & IORING_ENTER_SQ_WAIT) {
10903 ret = io_sqpoll_wait_sq(ctx);
10904 if (ret)
10905 goto out;
10906 }
6c271ce2 10907 submitted = to_submit;
b2a9eada 10908 } else if (to_submit) {
eef51daa 10909 ret = io_uring_add_tctx_node(ctx);
0f212204
JA
10910 if (unlikely(ret))
10911 goto out;
2b188cc1 10912 mutex_lock(&ctx->uring_lock);
0f212204 10913 submitted = io_submit_sqes(ctx, to_submit);
2b188cc1 10914 mutex_unlock(&ctx->uring_lock);
7c504e65
PB
10915
10916 if (submitted != to_submit)
10917 goto out;
2b188cc1
JA
10918 }
10919 if (flags & IORING_ENTER_GETEVENTS) {
c73ebb68
HX
10920 const sigset_t __user *sig;
10921 struct __kernel_timespec __user *ts;
10922
10923 ret = io_get_ext_arg(flags, argp, &argsz, &ts, &sig);
10924 if (unlikely(ret))
10925 goto out;
10926
2b188cc1
JA
10927 min_complete = min(min_complete, ctx->cq_entries);
10928
32b2244a
XW
10929 /*
10930 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
10931 * space applications don't need to do io completion events
10932 * polling again, they can rely on io_sq_thread to do polling
10933 * work, which can reduce cpu usage and uring_lock contention.
10934 */
10935 if (ctx->flags & IORING_SETUP_IOPOLL &&
10936 !(ctx->flags & IORING_SETUP_SQPOLL)) {
7668b92a 10937 ret = io_iopoll_check(ctx, min_complete);
def596e9 10938 } else {
c73ebb68 10939 ret = io_cqring_wait(ctx, min_complete, sig, argsz, ts);
def596e9 10940 }
2b188cc1
JA
10941 }
10942
7c504e65 10943out:
6805b32e 10944 percpu_ref_put(&ctx->refs);
2b188cc1 10945out_fput:
e7a6c00d
JA
10946 if (!(flags & IORING_ENTER_REGISTERED_RING))
10947 fdput(f);
2b188cc1
JA
10948 return submitted ? submitted : ret;
10949}
10950
bebdb65e 10951#ifdef CONFIG_PROC_FS
c072481d 10952static __cold int io_uring_show_cred(struct seq_file *m, unsigned int id,
61cf9370 10953 const struct cred *cred)
87ce955b 10954{
87ce955b
JA
10955 struct user_namespace *uns = seq_user_ns(m);
10956 struct group_info *gi;
10957 kernel_cap_t cap;
10958 unsigned __capi;
10959 int g;
10960
10961 seq_printf(m, "%5d\n", id);
10962 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
10963 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
10964 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
10965 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
10966 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
10967 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
10968 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
10969 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
10970 seq_puts(m, "\n\tGroups:\t");
10971 gi = cred->group_info;
10972 for (g = 0; g < gi->ngroups; g++) {
10973 seq_put_decimal_ull(m, g ? " " : "",
10974 from_kgid_munged(uns, gi->gid[g]));
10975 }
10976 seq_puts(m, "\n\tCapEff:\t");
10977 cap = cred->cap_effective;
10978 CAP_FOR_EACH_U32(__capi)
10979 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
10980 seq_putc(m, '\n');
10981 return 0;
10982}
10983
c072481d
PB
10984static __cold void __io_uring_show_fdinfo(struct io_ring_ctx *ctx,
10985 struct seq_file *m)
87ce955b 10986{
dbbe9c64 10987 struct io_sq_data *sq = NULL;
83f84356
HX
10988 struct io_overflow_cqe *ocqe;
10989 struct io_rings *r = ctx->rings;
10990 unsigned int sq_mask = ctx->sq_entries - 1, cq_mask = ctx->cq_entries - 1;
83f84356
HX
10991 unsigned int sq_head = READ_ONCE(r->sq.head);
10992 unsigned int sq_tail = READ_ONCE(r->sq.tail);
10993 unsigned int cq_head = READ_ONCE(r->cq.head);
10994 unsigned int cq_tail = READ_ONCE(r->cq.tail);
f75d1183 10995 unsigned int sq_entries, cq_entries;
fad8e0de 10996 bool has_lock;
83f84356
HX
10997 unsigned int i;
10998
10999 /*
11000 * we may get imprecise sqe and cqe info if uring is actively running
11001 * since we get cached_sq_head and cached_cq_tail without uring_lock
11002 * and sq_tail and cq_head are changed by userspace. But it's ok since
11003 * we usually use these info when it is stuck.
11004 */
c0235652 11005 seq_printf(m, "SqMask:\t0x%x\n", sq_mask);
f75d1183
JA
11006 seq_printf(m, "SqHead:\t%u\n", sq_head);
11007 seq_printf(m, "SqTail:\t%u\n", sq_tail);
11008 seq_printf(m, "CachedSqHead:\t%u\n", ctx->cached_sq_head);
11009 seq_printf(m, "CqMask:\t0x%x\n", cq_mask);
11010 seq_printf(m, "CqHead:\t%u\n", cq_head);
11011 seq_printf(m, "CqTail:\t%u\n", cq_tail);
11012 seq_printf(m, "CachedCqTail:\t%u\n", ctx->cached_cq_tail);
11013 seq_printf(m, "SQEs:\t%u\n", sq_tail - ctx->cached_sq_head);
11014 sq_entries = min(sq_tail - sq_head, ctx->sq_entries);
11015 for (i = 0; i < sq_entries; i++) {
11016 unsigned int entry = i + sq_head;
11017 unsigned int sq_idx = READ_ONCE(ctx->sq_array[entry & sq_mask]);
a1957780 11018 struct io_uring_sqe *sqe;
f75d1183
JA
11019
11020 if (sq_idx > sq_mask)
11021 continue;
11022 sqe = &ctx->sq_sqes[sq_idx];
11023 seq_printf(m, "%5u: opcode:%d, fd:%d, flags:%x, user_data:%llu\n",
11024 sq_idx, sqe->opcode, sqe->fd, sqe->flags,
11025 sqe->user_data);
83f84356 11026 }
f75d1183
JA
11027 seq_printf(m, "CQEs:\t%u\n", cq_tail - cq_head);
11028 cq_entries = min(cq_tail - cq_head, ctx->cq_entries);
11029 for (i = 0; i < cq_entries; i++) {
11030 unsigned int entry = i + cq_head;
11031 struct io_uring_cqe *cqe = &r->cqes[entry & cq_mask];
83f84356
HX
11032
11033 seq_printf(m, "%5u: user_data:%llu, res:%d, flag:%x\n",
f75d1183
JA
11034 entry & cq_mask, cqe->user_data, cqe->res,
11035 cqe->flags);
83f84356 11036 }
87ce955b 11037
fad8e0de
JA
11038 /*
11039 * Avoid ABBA deadlock between the seq lock and the io_uring mutex,
11040 * since fdinfo case grabs it in the opposite direction of normal use
11041 * cases. If we fail to get the lock, we just don't iterate any
11042 * structures that could be going away outside the io_uring mutex.
11043 */
11044 has_lock = mutex_trylock(&ctx->uring_lock);
11045
5f3f26f9 11046 if (has_lock && (ctx->flags & IORING_SETUP_SQPOLL)) {
dbbe9c64 11047 sq = ctx->sq_data;
5f3f26f9
JA
11048 if (!sq->thread)
11049 sq = NULL;
11050 }
dbbe9c64
JQ
11051
11052 seq_printf(m, "SqThread:\t%d\n", sq ? task_pid_nr(sq->thread) : -1);
11053 seq_printf(m, "SqThreadCpu:\t%d\n", sq ? task_cpu(sq->thread) : -1);
87ce955b 11054 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
fad8e0de 11055 for (i = 0; has_lock && i < ctx->nr_user_files; i++) {
7b29f92d 11056 struct file *f = io_file_from_index(ctx, i);
87ce955b 11057
87ce955b
JA
11058 if (f)
11059 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
11060 else
11061 seq_printf(m, "%5u: <none>\n", i);
11062 }
11063 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
fad8e0de 11064 for (i = 0; has_lock && i < ctx->nr_user_bufs; i++) {
41edf1a5 11065 struct io_mapped_ubuf *buf = ctx->user_bufs[i];
4751f53d 11066 unsigned int len = buf->ubuf_end - buf->ubuf;
87ce955b 11067
4751f53d 11068 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf, len);
87ce955b 11069 }
61cf9370
MWO
11070 if (has_lock && !xa_empty(&ctx->personalities)) {
11071 unsigned long index;
11072 const struct cred *cred;
11073
87ce955b 11074 seq_printf(m, "Personalities:\n");
61cf9370
MWO
11075 xa_for_each(&ctx->personalities, index, cred)
11076 io_uring_show_cred(m, index, cred);
87ce955b 11077 }
83f84356
HX
11078 if (has_lock)
11079 mutex_unlock(&ctx->uring_lock);
11080
11081 seq_puts(m, "PollList:\n");
79ebeaee 11082 spin_lock(&ctx->completion_lock);
d7718a9d
JA
11083 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
11084 struct hlist_head *list = &ctx->cancel_hash[i];
11085 struct io_kiocb *req;
11086
11087 hlist_for_each_entry(req, list, hash_node)
11088 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
11089 req->task->task_works != NULL);
11090 }
83f84356
HX
11091
11092 seq_puts(m, "CqOverflowList:\n");
11093 list_for_each_entry(ocqe, &ctx->cq_overflow_list, list) {
11094 struct io_uring_cqe *cqe = &ocqe->cqe;
11095
11096 seq_printf(m, " user_data=%llu, res=%d, flags=%x\n",
11097 cqe->user_data, cqe->res, cqe->flags);
11098
11099 }
11100
79ebeaee 11101 spin_unlock(&ctx->completion_lock);
87ce955b
JA
11102}
11103
c072481d 11104static __cold void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
87ce955b
JA
11105{
11106 struct io_ring_ctx *ctx = f->private_data;
11107
11108 if (percpu_ref_tryget(&ctx->refs)) {
11109 __io_uring_show_fdinfo(ctx, m);
11110 percpu_ref_put(&ctx->refs);
11111 }
11112}
bebdb65e 11113#endif
87ce955b 11114
2b188cc1
JA
11115static const struct file_operations io_uring_fops = {
11116 .release = io_uring_release,
11117 .mmap = io_uring_mmap,
6c5c240e
RP
11118#ifndef CONFIG_MMU
11119 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
11120 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
11121#endif
2b188cc1 11122 .poll = io_uring_poll,
bebdb65e 11123#ifdef CONFIG_PROC_FS
87ce955b 11124 .show_fdinfo = io_uring_show_fdinfo,
bebdb65e 11125#endif
2b188cc1
JA
11126};
11127
c072481d
PB
11128static __cold int io_allocate_scq_urings(struct io_ring_ctx *ctx,
11129 struct io_uring_params *p)
2b188cc1 11130{
75b28aff
HV
11131 struct io_rings *rings;
11132 size_t size, sq_array_offset;
2b188cc1 11133
bd740481
JA
11134 /* make sure these are sane, as we already accounted them */
11135 ctx->sq_entries = p->sq_entries;
11136 ctx->cq_entries = p->cq_entries;
11137
75b28aff
HV
11138 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
11139 if (size == SIZE_MAX)
11140 return -EOVERFLOW;
11141
11142 rings = io_mem_alloc(size);
11143 if (!rings)
2b188cc1
JA
11144 return -ENOMEM;
11145
75b28aff
HV
11146 ctx->rings = rings;
11147 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
11148 rings->sq_ring_mask = p->sq_entries - 1;
11149 rings->cq_ring_mask = p->cq_entries - 1;
11150 rings->sq_ring_entries = p->sq_entries;
11151 rings->cq_ring_entries = p->cq_entries;
2b188cc1
JA
11152
11153 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
eb065d30
JA
11154 if (size == SIZE_MAX) {
11155 io_mem_free(ctx->rings);
11156 ctx->rings = NULL;
2b188cc1 11157 return -EOVERFLOW;
eb065d30 11158 }
2b188cc1
JA
11159
11160 ctx->sq_sqes = io_mem_alloc(size);
eb065d30
JA
11161 if (!ctx->sq_sqes) {
11162 io_mem_free(ctx->rings);
11163 ctx->rings = NULL;
2b188cc1 11164 return -ENOMEM;
eb065d30 11165 }
2b188cc1 11166
2b188cc1
JA
11167 return 0;
11168}
11169
9faadcc8
PB
11170static int io_uring_install_fd(struct io_ring_ctx *ctx, struct file *file)
11171{
11172 int ret, fd;
11173
11174 fd = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
11175 if (fd < 0)
11176 return fd;
11177
eef51daa 11178 ret = io_uring_add_tctx_node(ctx);
9faadcc8
PB
11179 if (ret) {
11180 put_unused_fd(fd);
11181 return ret;
11182 }
11183 fd_install(fd, file);
11184 return fd;
11185}
11186
2b188cc1
JA
11187/*
11188 * Allocate an anonymous fd, this is what constitutes the application
11189 * visible backing of an io_uring instance. The application mmaps this
11190 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
11191 * we have to tie this fd to a socket for file garbage collection purposes.
11192 */
9faadcc8 11193static struct file *io_uring_get_file(struct io_ring_ctx *ctx)
2b188cc1
JA
11194{
11195 struct file *file;
9faadcc8 11196#if defined(CONFIG_UNIX)
2b188cc1
JA
11197 int ret;
11198
2b188cc1
JA
11199 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
11200 &ctx->ring_sock);
11201 if (ret)
9faadcc8 11202 return ERR_PTR(ret);
2b188cc1
JA
11203#endif
11204
91a9ab7c
PM
11205 file = anon_inode_getfile_secure("[io_uring]", &io_uring_fops, ctx,
11206 O_RDWR | O_CLOEXEC, NULL);
2b188cc1 11207#if defined(CONFIG_UNIX)
9faadcc8
PB
11208 if (IS_ERR(file)) {
11209 sock_release(ctx->ring_sock);
11210 ctx->ring_sock = NULL;
11211 } else {
11212 ctx->ring_sock->file = file;
0f212204 11213 }
2b188cc1 11214#endif
9faadcc8 11215 return file;
2b188cc1
JA
11216}
11217
c072481d
PB
11218static __cold int io_uring_create(unsigned entries, struct io_uring_params *p,
11219 struct io_uring_params __user *params)
2b188cc1 11220{
2b188cc1 11221 struct io_ring_ctx *ctx;
9faadcc8 11222 struct file *file;
2b188cc1
JA
11223 int ret;
11224
8110c1a6 11225 if (!entries)
2b188cc1 11226 return -EINVAL;
8110c1a6
JA
11227 if (entries > IORING_MAX_ENTRIES) {
11228 if (!(p->flags & IORING_SETUP_CLAMP))
11229 return -EINVAL;
11230 entries = IORING_MAX_ENTRIES;
11231 }
2b188cc1
JA
11232
11233 /*
11234 * Use twice as many entries for the CQ ring. It's possible for the
11235 * application to drive a higher depth than the size of the SQ ring,
11236 * since the sqes are only used at submission time. This allows for
33a107f0
JA
11237 * some flexibility in overcommitting a bit. If the application has
11238 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
11239 * of CQ ring entries manually.
2b188cc1
JA
11240 */
11241 p->sq_entries = roundup_pow_of_two(entries);
33a107f0
JA
11242 if (p->flags & IORING_SETUP_CQSIZE) {
11243 /*
11244 * If IORING_SETUP_CQSIZE is set, we do the same roundup
11245 * to a power-of-two, if it isn't already. We do NOT impose
11246 * any cq vs sq ring sizing.
11247 */
eb2667b3 11248 if (!p->cq_entries)
33a107f0 11249 return -EINVAL;
8110c1a6
JA
11250 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
11251 if (!(p->flags & IORING_SETUP_CLAMP))
11252 return -EINVAL;
11253 p->cq_entries = IORING_MAX_CQ_ENTRIES;
11254 }
eb2667b3
JQ
11255 p->cq_entries = roundup_pow_of_two(p->cq_entries);
11256 if (p->cq_entries < p->sq_entries)
11257 return -EINVAL;
33a107f0
JA
11258 } else {
11259 p->cq_entries = 2 * p->sq_entries;
11260 }
2b188cc1 11261
2b188cc1 11262 ctx = io_ring_ctx_alloc(p);
62e398be 11263 if (!ctx)
2b188cc1 11264 return -ENOMEM;
2b188cc1 11265 ctx->compat = in_compat_syscall();
62e398be
JA
11266 if (!capable(CAP_IPC_LOCK))
11267 ctx->user = get_uid(current_user());
2aede0e4
JA
11268
11269 /*
11270 * This is just grabbed for accounting purposes. When a process exits,
11271 * the mm is exited and dropped before the files, hence we need to hang
11272 * on to this mm purely for the purposes of being able to unaccount
11273 * memory (locked/pinned vm). It's not used for anything else.
11274 */
6b7898eb 11275 mmgrab(current->mm);
2aede0e4 11276 ctx->mm_account = current->mm;
6b7898eb 11277
2b188cc1
JA
11278 ret = io_allocate_scq_urings(ctx, p);
11279 if (ret)
11280 goto err;
11281
7e84e1c7 11282 ret = io_sq_offload_create(ctx, p);
2b188cc1
JA
11283 if (ret)
11284 goto err;
eae071c9 11285 /* always set a rsrc node */
47b228ce
PB
11286 ret = io_rsrc_node_switch_start(ctx);
11287 if (ret)
11288 goto err;
eae071c9 11289 io_rsrc_node_switch(ctx, NULL);
2b188cc1 11290
2b188cc1 11291 memset(&p->sq_off, 0, sizeof(p->sq_off));
75b28aff
HV
11292 p->sq_off.head = offsetof(struct io_rings, sq.head);
11293 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
11294 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
11295 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
11296 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
11297 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
11298 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
2b188cc1
JA
11299
11300 memset(&p->cq_off, 0, sizeof(p->cq_off));
75b28aff
HV
11301 p->cq_off.head = offsetof(struct io_rings, cq.head);
11302 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
11303 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
11304 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
11305 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
11306 p->cq_off.cqes = offsetof(struct io_rings, cqes);
0d9b5b3a 11307 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
ac90f249 11308
7f13657d
XW
11309 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
11310 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
5769a351 11311 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
c73ebb68 11312 IORING_FEAT_POLL_32BITS | IORING_FEAT_SQPOLL_NONFIXED |
9690557e 11313 IORING_FEAT_EXT_ARG | IORING_FEAT_NATIVE_WORKERS |
04c76b41 11314 IORING_FEAT_RSRC_TAGS | IORING_FEAT_CQE_SKIP;
7f13657d
XW
11315
11316 if (copy_to_user(params, p, sizeof(*p))) {
11317 ret = -EFAULT;
11318 goto err;
11319 }
d1719f70 11320
9faadcc8
PB
11321 file = io_uring_get_file(ctx);
11322 if (IS_ERR(file)) {
11323 ret = PTR_ERR(file);
11324 goto err;
11325 }
11326
044c1ab3
JA
11327 /*
11328 * Install ring fd as the very last thing, so we don't risk someone
11329 * having closed it before we finish setup
11330 */
9faadcc8
PB
11331 ret = io_uring_install_fd(ctx, file);
11332 if (ret < 0) {
11333 /* fput will clean it up */
11334 fput(file);
11335 return ret;
11336 }
044c1ab3 11337
c826bd7a 11338 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
2b188cc1
JA
11339 return ret;
11340err:
11341 io_ring_ctx_wait_and_kill(ctx);
11342 return ret;
11343}
11344
11345/*
11346 * Sets up an aio uring context, and returns the fd. Applications asks for a
11347 * ring size, we return the actual sq/cq ring sizes (among other things) in the
11348 * params structure passed in.
11349 */
11350static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
11351{
11352 struct io_uring_params p;
2b188cc1
JA
11353 int i;
11354
11355 if (copy_from_user(&p, params, sizeof(p)))
11356 return -EFAULT;
11357 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
11358 if (p.resv[i])
11359 return -EINVAL;
11360 }
11361
6c271ce2 11362 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
8110c1a6 11363 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
7e84e1c7 11364 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ |
bcbb7bf6 11365 IORING_SETUP_R_DISABLED | IORING_SETUP_SUBMIT_ALL))
2b188cc1
JA
11366 return -EINVAL;
11367
7f13657d 11368 return io_uring_create(entries, &p, params);
2b188cc1
JA
11369}
11370
11371SYSCALL_DEFINE2(io_uring_setup, u32, entries,
11372 struct io_uring_params __user *, params)
11373{
11374 return io_uring_setup(entries, params);
11375}
11376
c072481d
PB
11377static __cold int io_probe(struct io_ring_ctx *ctx, void __user *arg,
11378 unsigned nr_args)
66f4af93
JA
11379{
11380 struct io_uring_probe *p;
11381 size_t size;
11382 int i, ret;
11383
11384 size = struct_size(p, ops, nr_args);
11385 if (size == SIZE_MAX)
11386 return -EOVERFLOW;
11387 p = kzalloc(size, GFP_KERNEL);
11388 if (!p)
11389 return -ENOMEM;
11390
11391 ret = -EFAULT;
11392 if (copy_from_user(p, arg, size))
11393 goto out;
11394 ret = -EINVAL;
11395 if (memchr_inv(p, 0, size))
11396 goto out;
11397
11398 p->last_op = IORING_OP_LAST - 1;
11399 if (nr_args > IORING_OP_LAST)
11400 nr_args = IORING_OP_LAST;
11401
11402 for (i = 0; i < nr_args; i++) {
11403 p->ops[i].op = i;
11404 if (!io_op_defs[i].not_supported)
11405 p->ops[i].flags = IO_URING_OP_SUPPORTED;
11406 }
11407 p->ops_len = i;
11408
11409 ret = 0;
11410 if (copy_to_user(arg, p, size))
11411 ret = -EFAULT;
11412out:
11413 kfree(p);
11414 return ret;
11415}
11416
071698e1
JA
11417static int io_register_personality(struct io_ring_ctx *ctx)
11418{
4379bf8b 11419 const struct cred *creds;
61cf9370 11420 u32 id;
1e6fa521 11421 int ret;
071698e1 11422
4379bf8b 11423 creds = get_current_cred();
1e6fa521 11424
61cf9370
MWO
11425 ret = xa_alloc_cyclic(&ctx->personalities, &id, (void *)creds,
11426 XA_LIMIT(0, USHRT_MAX), &ctx->pers_next, GFP_KERNEL);
a30f895a
JA
11427 if (ret < 0) {
11428 put_cred(creds);
11429 return ret;
11430 }
11431 return id;
071698e1
JA
11432}
11433
c072481d
PB
11434static __cold int io_register_restrictions(struct io_ring_ctx *ctx,
11435 void __user *arg, unsigned int nr_args)
21b55dbc
SG
11436{
11437 struct io_uring_restriction *res;
11438 size_t size;
11439 int i, ret;
11440
7e84e1c7
SG
11441 /* Restrictions allowed only if rings started disabled */
11442 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11443 return -EBADFD;
11444
21b55dbc 11445 /* We allow only a single restrictions registration */
7e84e1c7 11446 if (ctx->restrictions.registered)
21b55dbc
SG
11447 return -EBUSY;
11448
11449 if (!arg || nr_args > IORING_MAX_RESTRICTIONS)
11450 return -EINVAL;
11451
11452 size = array_size(nr_args, sizeof(*res));
11453 if (size == SIZE_MAX)
11454 return -EOVERFLOW;
11455
11456 res = memdup_user(arg, size);
11457 if (IS_ERR(res))
11458 return PTR_ERR(res);
11459
11460 ret = 0;
11461
11462 for (i = 0; i < nr_args; i++) {
11463 switch (res[i].opcode) {
11464 case IORING_RESTRICTION_REGISTER_OP:
11465 if (res[i].register_op >= IORING_REGISTER_LAST) {
11466 ret = -EINVAL;
11467 goto out;
11468 }
11469
11470 __set_bit(res[i].register_op,
11471 ctx->restrictions.register_op);
11472 break;
11473 case IORING_RESTRICTION_SQE_OP:
11474 if (res[i].sqe_op >= IORING_OP_LAST) {
11475 ret = -EINVAL;
11476 goto out;
11477 }
11478
11479 __set_bit(res[i].sqe_op, ctx->restrictions.sqe_op);
11480 break;
11481 case IORING_RESTRICTION_SQE_FLAGS_ALLOWED:
11482 ctx->restrictions.sqe_flags_allowed = res[i].sqe_flags;
11483 break;
11484 case IORING_RESTRICTION_SQE_FLAGS_REQUIRED:
11485 ctx->restrictions.sqe_flags_required = res[i].sqe_flags;
11486 break;
11487 default:
11488 ret = -EINVAL;
11489 goto out;
11490 }
11491 }
11492
11493out:
11494 /* Reset all restrictions if an error happened */
11495 if (ret != 0)
11496 memset(&ctx->restrictions, 0, sizeof(ctx->restrictions));
11497 else
7e84e1c7 11498 ctx->restrictions.registered = true;
21b55dbc
SG
11499
11500 kfree(res);
11501 return ret;
11502}
11503
7e84e1c7
SG
11504static int io_register_enable_rings(struct io_ring_ctx *ctx)
11505{
11506 if (!(ctx->flags & IORING_SETUP_R_DISABLED))
11507 return -EBADFD;
11508
11509 if (ctx->restrictions.registered)
11510 ctx->restricted = 1;
11511
0298ef96
PB
11512 ctx->flags &= ~IORING_SETUP_R_DISABLED;
11513 if (ctx->sq_data && wq_has_sleeper(&ctx->sq_data->wait))
11514 wake_up(&ctx->sq_data->wait);
7e84e1c7
SG
11515 return 0;
11516}
11517
fdecb662 11518static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
c3bdad02 11519 struct io_uring_rsrc_update2 *up,
98f0b3b4
PB
11520 unsigned nr_args)
11521{
11522 __u32 tmp;
11523 int err;
11524
c3bdad02
PB
11525 if (up->resv)
11526 return -EINVAL;
98f0b3b4
PB
11527 if (check_add_overflow(up->offset, nr_args, &tmp))
11528 return -EOVERFLOW;
11529 err = io_rsrc_node_switch_start(ctx);
11530 if (err)
11531 return err;
11532
fdecb662
PB
11533 switch (type) {
11534 case IORING_RSRC_FILE:
98f0b3b4 11535 return __io_sqe_files_update(ctx, up, nr_args);
634d00df
PB
11536 case IORING_RSRC_BUFFER:
11537 return __io_sqe_buffers_update(ctx, up, nr_args);
98f0b3b4
PB
11538 }
11539 return -EINVAL;
11540}
11541
c3bdad02
PB
11542static int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
11543 unsigned nr_args)
98f0b3b4 11544{
c3bdad02 11545 struct io_uring_rsrc_update2 up;
98f0b3b4
PB
11546
11547 if (!nr_args)
11548 return -EINVAL;
c3bdad02
PB
11549 memset(&up, 0, sizeof(up));
11550 if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
11551 return -EFAULT;
11552 return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
11553}
11554
11555static int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
992da01a 11556 unsigned size, unsigned type)
c3bdad02
PB
11557{
11558 struct io_uring_rsrc_update2 up;
11559
11560 if (size != sizeof(up))
11561 return -EINVAL;
98f0b3b4
PB
11562 if (copy_from_user(&up, arg, sizeof(up)))
11563 return -EFAULT;
992da01a 11564 if (!up.nr || up.resv)
98f0b3b4 11565 return -EINVAL;
992da01a 11566 return __io_register_rsrc_update(ctx, type, &up, up.nr);
98f0b3b4
PB
11567}
11568
c072481d 11569static __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
992da01a 11570 unsigned int size, unsigned int type)
792e3582
PB
11571{
11572 struct io_uring_rsrc_register rr;
11573
11574 /* keep it extendible */
11575 if (size != sizeof(rr))
11576 return -EINVAL;
11577
11578 memset(&rr, 0, sizeof(rr));
11579 if (copy_from_user(&rr, arg, size))
11580 return -EFAULT;
992da01a 11581 if (!rr.nr || rr.resv || rr.resv2)
792e3582
PB
11582 return -EINVAL;
11583
992da01a 11584 switch (type) {
792e3582
PB
11585 case IORING_RSRC_FILE:
11586 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
11587 rr.nr, u64_to_user_ptr(rr.tags));
634d00df
PB
11588 case IORING_RSRC_BUFFER:
11589 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
11590 rr.nr, u64_to_user_ptr(rr.tags));
792e3582
PB
11591 }
11592 return -EINVAL;
11593}
11594
c072481d
PB
11595static __cold int io_register_iowq_aff(struct io_ring_ctx *ctx,
11596 void __user *arg, unsigned len)
fe76421d
JA
11597{
11598 struct io_uring_task *tctx = current->io_uring;
11599 cpumask_var_t new_mask;
11600 int ret;
11601
11602 if (!tctx || !tctx->io_wq)
11603 return -EINVAL;
11604
11605 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
11606 return -ENOMEM;
11607
11608 cpumask_clear(new_mask);
11609 if (len > cpumask_size())
11610 len = cpumask_size();
11611
11612 if (copy_from_user(new_mask, arg, len)) {
11613 free_cpumask_var(new_mask);
11614 return -EFAULT;
11615 }
11616
11617 ret = io_wq_cpu_affinity(tctx->io_wq, new_mask);
11618 free_cpumask_var(new_mask);
11619 return ret;
11620}
11621
c072481d 11622static __cold int io_unregister_iowq_aff(struct io_ring_ctx *ctx)
fe76421d
JA
11623{
11624 struct io_uring_task *tctx = current->io_uring;
11625
11626 if (!tctx || !tctx->io_wq)
11627 return -EINVAL;
11628
11629 return io_wq_cpu_affinity(tctx->io_wq, NULL);
11630}
11631
c072481d
PB
11632static __cold int io_register_iowq_max_workers(struct io_ring_ctx *ctx,
11633 void __user *arg)
b22fa62a 11634 __must_hold(&ctx->uring_lock)
2e480058 11635{
b22fa62a 11636 struct io_tctx_node *node;
fa84693b
JA
11637 struct io_uring_task *tctx = NULL;
11638 struct io_sq_data *sqd = NULL;
2e480058
JA
11639 __u32 new_count[2];
11640 int i, ret;
11641
2e480058
JA
11642 if (copy_from_user(new_count, arg, sizeof(new_count)))
11643 return -EFAULT;
11644 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11645 if (new_count[i] > INT_MAX)
11646 return -EINVAL;
11647
fa84693b
JA
11648 if (ctx->flags & IORING_SETUP_SQPOLL) {
11649 sqd = ctx->sq_data;
11650 if (sqd) {
009ad9f0
JA
11651 /*
11652 * Observe the correct sqd->lock -> ctx->uring_lock
11653 * ordering. Fine to drop uring_lock here, we hold
11654 * a ref to the ctx.
11655 */
41d3a6bd 11656 refcount_inc(&sqd->refs);
009ad9f0 11657 mutex_unlock(&ctx->uring_lock);
fa84693b 11658 mutex_lock(&sqd->lock);
009ad9f0 11659 mutex_lock(&ctx->uring_lock);
41d3a6bd
JA
11660 if (sqd->thread)
11661 tctx = sqd->thread->io_uring;
fa84693b
JA
11662 }
11663 } else {
11664 tctx = current->io_uring;
11665 }
11666
e139a1ec 11667 BUILD_BUG_ON(sizeof(new_count) != sizeof(ctx->iowq_limits));
fa84693b 11668
bad119b9
PB
11669 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11670 if (new_count[i])
11671 ctx->iowq_limits[i] = new_count[i];
e139a1ec
PB
11672 ctx->iowq_limits_set = true;
11673
e139a1ec
PB
11674 if (tctx && tctx->io_wq) {
11675 ret = io_wq_max_workers(tctx->io_wq, new_count);
11676 if (ret)
11677 goto err;
11678 } else {
11679 memset(new_count, 0, sizeof(new_count));
11680 }
fa84693b 11681
41d3a6bd 11682 if (sqd) {
fa84693b 11683 mutex_unlock(&sqd->lock);
41d3a6bd
JA
11684 io_put_sq_data(sqd);
11685 }
2e480058
JA
11686
11687 if (copy_to_user(arg, new_count, sizeof(new_count)))
11688 return -EFAULT;
11689
b22fa62a
PB
11690 /* that's it for SQPOLL, only the SQPOLL task creates requests */
11691 if (sqd)
11692 return 0;
11693
11694 /* now propagate the restriction to all registered users */
11695 list_for_each_entry(node, &ctx->tctx_list, ctx_node) {
11696 struct io_uring_task *tctx = node->task->io_uring;
11697
11698 if (WARN_ON_ONCE(!tctx->io_wq))
11699 continue;
11700
11701 for (i = 0; i < ARRAY_SIZE(new_count); i++)
11702 new_count[i] = ctx->iowq_limits[i];
11703 /* ignore errors, it always returns zero anyway */
11704 (void)io_wq_max_workers(tctx->io_wq, new_count);
11705 }
2e480058 11706 return 0;
fa84693b 11707err:
41d3a6bd 11708 if (sqd) {
fa84693b 11709 mutex_unlock(&sqd->lock);
41d3a6bd
JA
11710 io_put_sq_data(sqd);
11711 }
fa84693b 11712 return ret;
2e480058
JA
11713}
11714
edafccee
JA
11715static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
11716 void __user *arg, unsigned nr_args)
b19062a5
JA
11717 __releases(ctx->uring_lock)
11718 __acquires(ctx->uring_lock)
edafccee
JA
11719{
11720 int ret;
11721
35fa71a0
JA
11722 /*
11723 * We're inside the ring mutex, if the ref is already dying, then
11724 * someone else killed the ctx or is already going through
11725 * io_uring_register().
11726 */
11727 if (percpu_ref_is_dying(&ctx->refs))
11728 return -ENXIO;
11729
75c4021a
PB
11730 if (ctx->restricted) {
11731 if (opcode >= IORING_REGISTER_LAST)
11732 return -EINVAL;
11733 opcode = array_index_nospec(opcode, IORING_REGISTER_LAST);
11734 if (!test_bit(opcode, ctx->restrictions.register_op))
11735 return -EACCES;
11736 }
11737
edafccee
JA
11738 switch (opcode) {
11739 case IORING_REGISTER_BUFFERS:
634d00df 11740 ret = io_sqe_buffers_register(ctx, arg, nr_args, NULL);
edafccee
JA
11741 break;
11742 case IORING_UNREGISTER_BUFFERS:
11743 ret = -EINVAL;
11744 if (arg || nr_args)
11745 break;
0a96bbe4 11746 ret = io_sqe_buffers_unregister(ctx);
edafccee 11747 break;
6b06314c 11748 case IORING_REGISTER_FILES:
792e3582 11749 ret = io_sqe_files_register(ctx, arg, nr_args, NULL);
6b06314c
JA
11750 break;
11751 case IORING_UNREGISTER_FILES:
11752 ret = -EINVAL;
11753 if (arg || nr_args)
11754 break;
11755 ret = io_sqe_files_unregister(ctx);
11756 break;
c3a31e60 11757 case IORING_REGISTER_FILES_UPDATE:
c3bdad02 11758 ret = io_register_files_update(ctx, arg, nr_args);
c3a31e60 11759 break;
9b402849
JA
11760 case IORING_REGISTER_EVENTFD:
11761 ret = -EINVAL;
11762 if (nr_args != 1)
11763 break;
c75312dd
UA
11764 ret = io_eventfd_register(ctx, arg, 0);
11765 break;
11766 case IORING_REGISTER_EVENTFD_ASYNC:
11767 ret = -EINVAL;
11768 if (nr_args != 1)
f2842ab5 11769 break;
c75312dd 11770 ret = io_eventfd_register(ctx, arg, 1);
9b402849
JA
11771 break;
11772 case IORING_UNREGISTER_EVENTFD:
11773 ret = -EINVAL;
11774 if (arg || nr_args)
11775 break;
11776 ret = io_eventfd_unregister(ctx);
11777 break;
66f4af93
JA
11778 case IORING_REGISTER_PROBE:
11779 ret = -EINVAL;
11780 if (!arg || nr_args > 256)
11781 break;
11782 ret = io_probe(ctx, arg, nr_args);
11783 break;
071698e1
JA
11784 case IORING_REGISTER_PERSONALITY:
11785 ret = -EINVAL;
11786 if (arg || nr_args)
11787 break;
11788 ret = io_register_personality(ctx);
11789 break;
11790 case IORING_UNREGISTER_PERSONALITY:
11791 ret = -EINVAL;
11792 if (arg)
11793 break;
11794 ret = io_unregister_personality(ctx, nr_args);
11795 break;
7e84e1c7
SG
11796 case IORING_REGISTER_ENABLE_RINGS:
11797 ret = -EINVAL;
11798 if (arg || nr_args)
11799 break;
11800 ret = io_register_enable_rings(ctx);
11801 break;
21b55dbc
SG
11802 case IORING_REGISTER_RESTRICTIONS:
11803 ret = io_register_restrictions(ctx, arg, nr_args);
11804 break;
992da01a
PB
11805 case IORING_REGISTER_FILES2:
11806 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_FILE);
11807 break;
11808 case IORING_REGISTER_FILES_UPDATE2:
11809 ret = io_register_rsrc_update(ctx, arg, nr_args,
11810 IORING_RSRC_FILE);
11811 break;
11812 case IORING_REGISTER_BUFFERS2:
11813 ret = io_register_rsrc(ctx, arg, nr_args, IORING_RSRC_BUFFER);
792e3582 11814 break;
992da01a
PB
11815 case IORING_REGISTER_BUFFERS_UPDATE:
11816 ret = io_register_rsrc_update(ctx, arg, nr_args,
11817 IORING_RSRC_BUFFER);
c3bdad02 11818 break;
fe76421d
JA
11819 case IORING_REGISTER_IOWQ_AFF:
11820 ret = -EINVAL;
11821 if (!arg || !nr_args)
11822 break;
11823 ret = io_register_iowq_aff(ctx, arg, nr_args);
11824 break;
11825 case IORING_UNREGISTER_IOWQ_AFF:
11826 ret = -EINVAL;
11827 if (arg || nr_args)
11828 break;
11829 ret = io_unregister_iowq_aff(ctx);
11830 break;
2e480058
JA
11831 case IORING_REGISTER_IOWQ_MAX_WORKERS:
11832 ret = -EINVAL;
11833 if (!arg || nr_args != 2)
11834 break;
11835 ret = io_register_iowq_max_workers(ctx, arg);
11836 break;
e7a6c00d
JA
11837 case IORING_REGISTER_RING_FDS:
11838 ret = io_ringfd_register(ctx, arg, nr_args);
11839 break;
11840 case IORING_UNREGISTER_RING_FDS:
11841 ret = io_ringfd_unregister(ctx, arg, nr_args);
11842 break;
edafccee
JA
11843 default:
11844 ret = -EINVAL;
11845 break;
11846 }
11847
edafccee
JA
11848 return ret;
11849}
11850
11851SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
11852 void __user *, arg, unsigned int, nr_args)
11853{
11854 struct io_ring_ctx *ctx;
11855 long ret = -EBADF;
11856 struct fd f;
11857
11858 f = fdget(fd);
11859 if (!f.file)
11860 return -EBADF;
11861
11862 ret = -EOPNOTSUPP;
11863 if (f.file->f_op != &io_uring_fops)
11864 goto out_fput;
11865
11866 ctx = f.file->private_data;
11867
b6c23dd5
PB
11868 io_run_task_work();
11869
edafccee
JA
11870 mutex_lock(&ctx->uring_lock);
11871 ret = __io_uring_register(ctx, opcode, arg, nr_args);
11872 mutex_unlock(&ctx->uring_lock);
2757be22 11873 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs, ret);
edafccee
JA
11874out_fput:
11875 fdput(f);
11876 return ret;
11877}
11878
2b188cc1
JA
11879static int __init io_uring_init(void)
11880{
d7f62e82
SM
11881#define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
11882 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
11883 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
11884} while (0)
11885
11886#define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
11887 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
11888 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
11889 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
11890 BUILD_BUG_SQE_ELEM(1, __u8, flags);
11891 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
11892 BUILD_BUG_SQE_ELEM(4, __s32, fd);
11893 BUILD_BUG_SQE_ELEM(8, __u64, off);
11894 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
11895 BUILD_BUG_SQE_ELEM(16, __u64, addr);
7d67af2c 11896 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
d7f62e82
SM
11897 BUILD_BUG_SQE_ELEM(24, __u32, len);
11898 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
11899 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
11900 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
11901 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
5769a351
JX
11902 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
11903 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
d7f62e82
SM
11904 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
11905 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
11906 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
11907 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
11908 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
11909 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
11910 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
11911 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
7d67af2c 11912 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
d7f62e82
SM
11913 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
11914 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
16340eab 11915 BUILD_BUG_SQE_ELEM(40, __u16, buf_group);
d7f62e82 11916 BUILD_BUG_SQE_ELEM(42, __u16, personality);
7d67af2c 11917 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
b9445598 11918 BUILD_BUG_SQE_ELEM(44, __u32, file_index);
d7f62e82 11919
b0d658ec
PB
11920 BUILD_BUG_ON(sizeof(struct io_uring_files_update) !=
11921 sizeof(struct io_uring_rsrc_update));
11922 BUILD_BUG_ON(sizeof(struct io_uring_rsrc_update) >
11923 sizeof(struct io_uring_rsrc_update2));
90499ad0
PB
11924
11925 /* ->buf_index is u16 */
11926 BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
11927
b0d658ec
PB
11928 /* should fit into one byte */
11929 BUILD_BUG_ON(SQE_VALID_FLAGS >= (1 << 8));
68fe256a
PB
11930 BUILD_BUG_ON(SQE_COMMON_FLAGS >= (1 << 8));
11931 BUILD_BUG_ON((SQE_VALID_FLAGS | SQE_COMMON_FLAGS) != SQE_VALID_FLAGS);
b0d658ec 11932
d3656344 11933 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
32c2d33e 11934 BUILD_BUG_ON(__REQ_F_LAST_BIT > 8 * sizeof(int));
16340eab 11935
91f245d5
JA
11936 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC |
11937 SLAB_ACCOUNT);
2b188cc1
JA
11938 return 0;
11939};
11940__initcall(io_uring_init);