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