]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blob - fs/io_uring.c
io_uring: pass in completion state to appropriate issue side handlers
[mirror_ubuntu-jammy-kernel.git] / fs / io_uring.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Shared application/kernel submission and completion ring pairs, for
4 * supporting fast/efficient IO.
5 *
6 * A note on the read/write ordering memory barriers that are matched between
7 * the application and kernel side.
8 *
9 * After the application reads the CQ ring tail, it must use an
10 * appropriate smp_rmb() to pair with the smp_wmb() the kernel uses
11 * before writing the tail (using smp_load_acquire to read the tail will
12 * do). It also needs a smp_mb() before updating CQ head (ordering the
13 * entry load(s) with the head store), pairing with an implicit barrier
14 * through a control-dependency in io_get_cqring (smp_store_release to
15 * store head will do). Failure to do so could lead to reading invalid
16 * CQ entries.
17 *
18 * Likewise, the application must use an appropriate smp_wmb() before
19 * writing the SQ tail (ordering SQ entry stores with the tail store),
20 * which pairs with smp_load_acquire in io_get_sqring (smp_store_release
21 * to store the tail will do). And it needs a barrier ordering the SQ
22 * head load before writing new SQ entries (smp_load_acquire to read
23 * head will do).
24 *
25 * When using the SQ poll thread (IORING_SETUP_SQPOLL), the application
26 * needs to check the SQ flags for IORING_SQ_NEED_WAKEUP *after*
27 * updating the SQ tail; a full memory barrier smp_mb() is needed
28 * between.
29 *
30 * Also see the examples in the liburing library:
31 *
32 * git://git.kernel.dk/liburing
33 *
34 * io_uring also uses READ/WRITE_ONCE() for _any_ store or load that happens
35 * from data shared between the kernel and application. This is done both
36 * for ordering purposes, but also to ensure that once a value is loaded from
37 * data that the application could potentially modify, it remains stable.
38 *
39 * Copyright (C) 2018-2019 Jens Axboe
40 * Copyright (c) 2018-2019 Christoph Hellwig
41 */
42 #include <linux/kernel.h>
43 #include <linux/init.h>
44 #include <linux/errno.h>
45 #include <linux/syscalls.h>
46 #include <linux/compat.h>
47 #include <net/compat.h>
48 #include <linux/refcount.h>
49 #include <linux/uio.h>
50 #include <linux/bits.h>
51
52 #include <linux/sched/signal.h>
53 #include <linux/fs.h>
54 #include <linux/file.h>
55 #include <linux/fdtable.h>
56 #include <linux/mm.h>
57 #include <linux/mman.h>
58 #include <linux/percpu.h>
59 #include <linux/slab.h>
60 #include <linux/kthread.h>
61 #include <linux/blkdev.h>
62 #include <linux/bvec.h>
63 #include <linux/net.h>
64 #include <net/sock.h>
65 #include <net/af_unix.h>
66 #include <net/scm.h>
67 #include <linux/anon_inodes.h>
68 #include <linux/sched/mm.h>
69 #include <linux/uaccess.h>
70 #include <linux/nospec.h>
71 #include <linux/sizes.h>
72 #include <linux/hugetlb.h>
73 #include <linux/highmem.h>
74 #include <linux/namei.h>
75 #include <linux/fsnotify.h>
76 #include <linux/fadvise.h>
77 #include <linux/eventpoll.h>
78 #include <linux/fs_struct.h>
79 #include <linux/splice.h>
80 #include <linux/task_work.h>
81 #include <linux/pagemap.h>
82
83 #define CREATE_TRACE_POINTS
84 #include <trace/events/io_uring.h>
85
86 #include <uapi/linux/io_uring.h>
87
88 #include "internal.h"
89 #include "io-wq.h"
90
91 #define IORING_MAX_ENTRIES 32768
92 #define IORING_MAX_CQ_ENTRIES (2 * IORING_MAX_ENTRIES)
93
94 /*
95 * Shift of 9 is 512 entries, or exactly one page on 64-bit archs
96 */
97 #define IORING_FILE_TABLE_SHIFT 9
98 #define IORING_MAX_FILES_TABLE (1U << IORING_FILE_TABLE_SHIFT)
99 #define IORING_FILE_TABLE_MASK (IORING_MAX_FILES_TABLE - 1)
100 #define IORING_MAX_FIXED_FILES (64 * IORING_MAX_FILES_TABLE)
101
102 struct io_uring {
103 u32 head ____cacheline_aligned_in_smp;
104 u32 tail ____cacheline_aligned_in_smp;
105 };
106
107 /*
108 * This data is shared with the application through the mmap at offsets
109 * IORING_OFF_SQ_RING and IORING_OFF_CQ_RING.
110 *
111 * The offsets to the member fields are published through struct
112 * io_sqring_offsets when calling io_uring_setup.
113 */
114 struct io_rings {
115 /*
116 * Head and tail offsets into the ring; the offsets need to be
117 * masked to get valid indices.
118 *
119 * The kernel controls head of the sq ring and the tail of the cq ring,
120 * and the application controls tail of the sq ring and the head of the
121 * cq ring.
122 */
123 struct io_uring sq, cq;
124 /*
125 * Bitmasks to apply to head and tail offsets (constant, equals
126 * ring_entries - 1)
127 */
128 u32 sq_ring_mask, cq_ring_mask;
129 /* Ring sizes (constant, power of 2) */
130 u32 sq_ring_entries, cq_ring_entries;
131 /*
132 * Number of invalid entries dropped by the kernel due to
133 * invalid index stored in array
134 *
135 * Written by the kernel, shouldn't be modified by the
136 * application (i.e. get number of "new events" by comparing to
137 * cached value).
138 *
139 * After a new SQ head value was read by the application this
140 * counter includes all submissions that were dropped reaching
141 * the new SQ head (and possibly more).
142 */
143 u32 sq_dropped;
144 /*
145 * Runtime SQ flags
146 *
147 * Written by the kernel, shouldn't be modified by the
148 * application.
149 *
150 * The application needs a full memory barrier before checking
151 * for IORING_SQ_NEED_WAKEUP after updating the sq tail.
152 */
153 u32 sq_flags;
154 /*
155 * Runtime CQ flags
156 *
157 * Written by the application, shouldn't be modified by the
158 * kernel.
159 */
160 u32 cq_flags;
161 /*
162 * Number of completion events lost because the queue was full;
163 * this should be avoided by the application by making sure
164 * there are not more requests pending than there is space in
165 * the completion queue.
166 *
167 * Written by the kernel, shouldn't be modified by the
168 * application (i.e. get number of "new events" by comparing to
169 * cached value).
170 *
171 * As completion events come in out of order this counter is not
172 * ordered with any other data.
173 */
174 u32 cq_overflow;
175 /*
176 * Ring buffer of completion events.
177 *
178 * The kernel writes completion events fresh every time they are
179 * produced, so the application is allowed to modify pending
180 * entries.
181 */
182 struct io_uring_cqe cqes[] ____cacheline_aligned_in_smp;
183 };
184
185 struct io_mapped_ubuf {
186 u64 ubuf;
187 size_t len;
188 struct bio_vec *bvec;
189 unsigned int nr_bvecs;
190 };
191
192 struct fixed_file_table {
193 struct file **files;
194 };
195
196 struct fixed_file_ref_node {
197 struct percpu_ref refs;
198 struct list_head node;
199 struct list_head file_list;
200 struct fixed_file_data *file_data;
201 struct llist_node llist;
202 };
203
204 struct fixed_file_data {
205 struct fixed_file_table *table;
206 struct io_ring_ctx *ctx;
207
208 struct percpu_ref *cur_refs;
209 struct percpu_ref refs;
210 struct completion done;
211 struct list_head ref_list;
212 spinlock_t lock;
213 };
214
215 struct io_buffer {
216 struct list_head list;
217 __u64 addr;
218 __s32 len;
219 __u16 bid;
220 };
221
222 struct io_ring_ctx {
223 struct {
224 struct percpu_ref refs;
225 } ____cacheline_aligned_in_smp;
226
227 struct {
228 unsigned int flags;
229 unsigned int compat: 1;
230 unsigned int limit_mem: 1;
231 unsigned int cq_overflow_flushed: 1;
232 unsigned int drain_next: 1;
233 unsigned int eventfd_async: 1;
234
235 /*
236 * Ring buffer of indices into array of io_uring_sqe, which is
237 * mmapped by the application using the IORING_OFF_SQES offset.
238 *
239 * This indirection could e.g. be used to assign fixed
240 * io_uring_sqe entries to operations and only submit them to
241 * the queue when needed.
242 *
243 * The kernel modifies neither the indices array nor the entries
244 * array.
245 */
246 u32 *sq_array;
247 unsigned cached_sq_head;
248 unsigned sq_entries;
249 unsigned sq_mask;
250 unsigned sq_thread_idle;
251 unsigned cached_sq_dropped;
252 atomic_t cached_cq_overflow;
253 unsigned long sq_check_overflow;
254
255 struct list_head defer_list;
256 struct list_head timeout_list;
257 struct list_head cq_overflow_list;
258
259 wait_queue_head_t inflight_wait;
260 struct io_uring_sqe *sq_sqes;
261 } ____cacheline_aligned_in_smp;
262
263 struct io_rings *rings;
264
265 /* IO offload */
266 struct io_wq *io_wq;
267 struct task_struct *sqo_thread; /* if using sq thread polling */
268 struct mm_struct *sqo_mm;
269 wait_queue_head_t sqo_wait;
270
271 /*
272 * If used, fixed file set. Writers must ensure that ->refs is dead,
273 * readers must ensure that ->refs is alive as long as the file* is
274 * used. Only updated through io_uring_register(2).
275 */
276 struct fixed_file_data *file_data;
277 unsigned nr_user_files;
278 int ring_fd;
279 struct file *ring_file;
280
281 /* if used, fixed mapped user buffers */
282 unsigned nr_user_bufs;
283 struct io_mapped_ubuf *user_bufs;
284
285 struct user_struct *user;
286
287 const struct cred *creds;
288
289 struct completion ref_comp;
290 struct completion sq_thread_comp;
291
292 /* if all else fails... */
293 struct io_kiocb *fallback_req;
294
295 #if defined(CONFIG_UNIX)
296 struct socket *ring_sock;
297 #endif
298
299 struct idr io_buffer_idr;
300
301 struct idr personality_idr;
302
303 struct {
304 unsigned cached_cq_tail;
305 unsigned cq_entries;
306 unsigned cq_mask;
307 atomic_t cq_timeouts;
308 unsigned long cq_check_overflow;
309 struct wait_queue_head cq_wait;
310 struct fasync_struct *cq_fasync;
311 struct eventfd_ctx *cq_ev_fd;
312 } ____cacheline_aligned_in_smp;
313
314 struct {
315 struct mutex uring_lock;
316 wait_queue_head_t wait;
317 } ____cacheline_aligned_in_smp;
318
319 struct {
320 spinlock_t completion_lock;
321
322 /*
323 * ->poll_list is protected by the ctx->uring_lock for
324 * io_uring instances that don't use IORING_SETUP_SQPOLL.
325 * For SQPOLL, only the single threaded io_sq_thread() will
326 * manipulate the list, hence no extra locking is needed there.
327 */
328 struct list_head poll_list;
329 struct hlist_head *cancel_hash;
330 unsigned cancel_hash_bits;
331 bool poll_multi_file;
332
333 spinlock_t inflight_lock;
334 struct list_head inflight_list;
335 } ____cacheline_aligned_in_smp;
336
337 struct delayed_work file_put_work;
338 struct llist_head file_put_llist;
339
340 struct work_struct exit_work;
341 };
342
343 /*
344 * First field must be the file pointer in all the
345 * iocb unions! See also 'struct kiocb' in <linux/fs.h>
346 */
347 struct io_poll_iocb {
348 struct file *file;
349 union {
350 struct wait_queue_head *head;
351 u64 addr;
352 };
353 __poll_t events;
354 bool done;
355 bool canceled;
356 struct wait_queue_entry wait;
357 };
358
359 struct io_close {
360 struct file *file;
361 struct file *put_file;
362 int fd;
363 };
364
365 struct io_timeout_data {
366 struct io_kiocb *req;
367 struct hrtimer timer;
368 struct timespec64 ts;
369 enum hrtimer_mode mode;
370 };
371
372 struct io_accept {
373 struct file *file;
374 struct sockaddr __user *addr;
375 int __user *addr_len;
376 int flags;
377 unsigned long nofile;
378 };
379
380 struct io_sync {
381 struct file *file;
382 loff_t len;
383 loff_t off;
384 int flags;
385 int mode;
386 };
387
388 struct io_cancel {
389 struct file *file;
390 u64 addr;
391 };
392
393 struct io_timeout {
394 struct file *file;
395 u64 addr;
396 int flags;
397 u32 off;
398 u32 target_seq;
399 };
400
401 struct io_rw {
402 /* NOTE: kiocb has the file as the first member, so don't do it here */
403 struct kiocb kiocb;
404 u64 addr;
405 u64 len;
406 };
407
408 struct io_connect {
409 struct file *file;
410 struct sockaddr __user *addr;
411 int addr_len;
412 };
413
414 struct io_sr_msg {
415 struct file *file;
416 union {
417 struct user_msghdr __user *msg;
418 void __user *buf;
419 };
420 int msg_flags;
421 int bgid;
422 size_t len;
423 struct io_buffer *kbuf;
424 };
425
426 struct io_open {
427 struct file *file;
428 int dfd;
429 struct filename *filename;
430 struct open_how how;
431 unsigned long nofile;
432 };
433
434 struct io_files_update {
435 struct file *file;
436 u64 arg;
437 u32 nr_args;
438 u32 offset;
439 };
440
441 struct io_fadvise {
442 struct file *file;
443 u64 offset;
444 u32 len;
445 u32 advice;
446 };
447
448 struct io_madvise {
449 struct file *file;
450 u64 addr;
451 u32 len;
452 u32 advice;
453 };
454
455 struct io_epoll {
456 struct file *file;
457 int epfd;
458 int op;
459 int fd;
460 struct epoll_event event;
461 };
462
463 struct io_splice {
464 struct file *file_out;
465 struct file *file_in;
466 loff_t off_out;
467 loff_t off_in;
468 u64 len;
469 unsigned int flags;
470 };
471
472 struct io_provide_buf {
473 struct file *file;
474 __u64 addr;
475 __s32 len;
476 __u32 bgid;
477 __u16 nbufs;
478 __u16 bid;
479 };
480
481 struct io_statx {
482 struct file *file;
483 int dfd;
484 unsigned int mask;
485 unsigned int flags;
486 const char __user *filename;
487 struct statx __user *buffer;
488 };
489
490 struct io_async_connect {
491 struct sockaddr_storage address;
492 };
493
494 struct io_async_msghdr {
495 struct iovec fast_iov[UIO_FASTIOV];
496 struct iovec *iov;
497 struct sockaddr __user *uaddr;
498 struct msghdr msg;
499 struct sockaddr_storage addr;
500 };
501
502 struct io_async_rw {
503 struct iovec fast_iov[UIO_FASTIOV];
504 struct iovec *iov;
505 ssize_t nr_segs;
506 ssize_t size;
507 struct wait_page_queue wpq;
508 struct callback_head task_work;
509 };
510
511 struct io_async_ctx {
512 union {
513 struct io_async_rw rw;
514 struct io_async_msghdr msg;
515 struct io_async_connect connect;
516 struct io_timeout_data timeout;
517 };
518 };
519
520 enum {
521 REQ_F_FIXED_FILE_BIT = IOSQE_FIXED_FILE_BIT,
522 REQ_F_IO_DRAIN_BIT = IOSQE_IO_DRAIN_BIT,
523 REQ_F_LINK_BIT = IOSQE_IO_LINK_BIT,
524 REQ_F_HARDLINK_BIT = IOSQE_IO_HARDLINK_BIT,
525 REQ_F_FORCE_ASYNC_BIT = IOSQE_ASYNC_BIT,
526 REQ_F_BUFFER_SELECT_BIT = IOSQE_BUFFER_SELECT_BIT,
527
528 REQ_F_LINK_HEAD_BIT,
529 REQ_F_LINK_NEXT_BIT,
530 REQ_F_FAIL_LINK_BIT,
531 REQ_F_INFLIGHT_BIT,
532 REQ_F_CUR_POS_BIT,
533 REQ_F_NOWAIT_BIT,
534 REQ_F_LINK_TIMEOUT_BIT,
535 REQ_F_TIMEOUT_BIT,
536 REQ_F_ISREG_BIT,
537 REQ_F_TIMEOUT_NOSEQ_BIT,
538 REQ_F_COMP_LOCKED_BIT,
539 REQ_F_NEED_CLEANUP_BIT,
540 REQ_F_OVERFLOW_BIT,
541 REQ_F_POLLED_BIT,
542 REQ_F_BUFFER_SELECTED_BIT,
543 REQ_F_NO_FILE_TABLE_BIT,
544 REQ_F_QUEUE_TIMEOUT_BIT,
545 REQ_F_WORK_INITIALIZED_BIT,
546 REQ_F_TASK_PINNED_BIT,
547
548 /* not a real bit, just to check we're not overflowing the space */
549 __REQ_F_LAST_BIT,
550 };
551
552 enum {
553 /* ctx owns file */
554 REQ_F_FIXED_FILE = BIT(REQ_F_FIXED_FILE_BIT),
555 /* drain existing IO first */
556 REQ_F_IO_DRAIN = BIT(REQ_F_IO_DRAIN_BIT),
557 /* linked sqes */
558 REQ_F_LINK = BIT(REQ_F_LINK_BIT),
559 /* doesn't sever on completion < 0 */
560 REQ_F_HARDLINK = BIT(REQ_F_HARDLINK_BIT),
561 /* IOSQE_ASYNC */
562 REQ_F_FORCE_ASYNC = BIT(REQ_F_FORCE_ASYNC_BIT),
563 /* IOSQE_BUFFER_SELECT */
564 REQ_F_BUFFER_SELECT = BIT(REQ_F_BUFFER_SELECT_BIT),
565
566 /* head of a link */
567 REQ_F_LINK_HEAD = BIT(REQ_F_LINK_HEAD_BIT),
568 /* already grabbed next link */
569 REQ_F_LINK_NEXT = BIT(REQ_F_LINK_NEXT_BIT),
570 /* fail rest of links */
571 REQ_F_FAIL_LINK = BIT(REQ_F_FAIL_LINK_BIT),
572 /* on inflight list */
573 REQ_F_INFLIGHT = BIT(REQ_F_INFLIGHT_BIT),
574 /* read/write uses file position */
575 REQ_F_CUR_POS = BIT(REQ_F_CUR_POS_BIT),
576 /* must not punt to workers */
577 REQ_F_NOWAIT = BIT(REQ_F_NOWAIT_BIT),
578 /* has linked timeout */
579 REQ_F_LINK_TIMEOUT = BIT(REQ_F_LINK_TIMEOUT_BIT),
580 /* timeout request */
581 REQ_F_TIMEOUT = BIT(REQ_F_TIMEOUT_BIT),
582 /* regular file */
583 REQ_F_ISREG = BIT(REQ_F_ISREG_BIT),
584 /* no timeout sequence */
585 REQ_F_TIMEOUT_NOSEQ = BIT(REQ_F_TIMEOUT_NOSEQ_BIT),
586 /* completion under lock */
587 REQ_F_COMP_LOCKED = BIT(REQ_F_COMP_LOCKED_BIT),
588 /* needs cleanup */
589 REQ_F_NEED_CLEANUP = BIT(REQ_F_NEED_CLEANUP_BIT),
590 /* in overflow list */
591 REQ_F_OVERFLOW = BIT(REQ_F_OVERFLOW_BIT),
592 /* already went through poll handler */
593 REQ_F_POLLED = BIT(REQ_F_POLLED_BIT),
594 /* buffer already selected */
595 REQ_F_BUFFER_SELECTED = BIT(REQ_F_BUFFER_SELECTED_BIT),
596 /* doesn't need file table for this request */
597 REQ_F_NO_FILE_TABLE = BIT(REQ_F_NO_FILE_TABLE_BIT),
598 /* needs to queue linked timeout */
599 REQ_F_QUEUE_TIMEOUT = BIT(REQ_F_QUEUE_TIMEOUT_BIT),
600 /* io_wq_work is initialized */
601 REQ_F_WORK_INITIALIZED = BIT(REQ_F_WORK_INITIALIZED_BIT),
602 /* req->task is refcounted */
603 REQ_F_TASK_PINNED = BIT(REQ_F_TASK_PINNED_BIT),
604 };
605
606 struct async_poll {
607 struct io_poll_iocb poll;
608 struct io_wq_work work;
609 };
610
611 /*
612 * NOTE! Each of the iocb union members has the file pointer
613 * as the first entry in their struct definition. So you can
614 * access the file pointer through any of the sub-structs,
615 * or directly as just 'ki_filp' in this struct.
616 */
617 struct io_kiocb {
618 union {
619 struct file *file;
620 struct io_rw rw;
621 struct io_poll_iocb poll;
622 struct io_accept accept;
623 struct io_sync sync;
624 struct io_cancel cancel;
625 struct io_timeout timeout;
626 struct io_connect connect;
627 struct io_sr_msg sr_msg;
628 struct io_open open;
629 struct io_close close;
630 struct io_files_update files_update;
631 struct io_fadvise fadvise;
632 struct io_madvise madvise;
633 struct io_epoll epoll;
634 struct io_splice splice;
635 struct io_provide_buf pbuf;
636 struct io_statx statx;
637 };
638
639 struct io_async_ctx *io;
640 int cflags;
641 u8 opcode;
642 /* polled IO has completed */
643 u8 iopoll_completed;
644
645 u16 buf_index;
646
647 struct io_ring_ctx *ctx;
648 struct list_head list;
649 unsigned int flags;
650 refcount_t refs;
651 struct task_struct *task;
652 unsigned long fsize;
653 u64 user_data;
654 u32 result;
655 u32 sequence;
656
657 struct list_head link_list;
658
659 struct list_head inflight_entry;
660
661 struct percpu_ref *fixed_file_refs;
662
663 union {
664 /*
665 * Only commands that never go async can use the below fields,
666 * obviously. Right now only IORING_OP_POLL_ADD uses them, and
667 * async armed poll handlers for regular commands. The latter
668 * restore the work, if needed.
669 */
670 struct {
671 struct callback_head task_work;
672 struct hlist_node hash_node;
673 struct async_poll *apoll;
674 };
675 struct io_wq_work work;
676 };
677 };
678
679 #define IO_IOPOLL_BATCH 8
680
681 struct io_comp_state {
682 unsigned int nr;
683 struct list_head list;
684 struct io_ring_ctx *ctx;
685 };
686
687 struct io_submit_state {
688 struct blk_plug plug;
689
690 /*
691 * io_kiocb alloc cache
692 */
693 void *reqs[IO_IOPOLL_BATCH];
694 unsigned int free_reqs;
695
696 /*
697 * Batch completion logic
698 */
699 struct io_comp_state comp;
700
701 /*
702 * File reference cache
703 */
704 struct file *file;
705 unsigned int fd;
706 unsigned int has_refs;
707 unsigned int used_refs;
708 unsigned int ios_left;
709 };
710
711 struct io_op_def {
712 /* needs req->io allocated for deferral/async */
713 unsigned async_ctx : 1;
714 /* needs current->mm setup, does mm access */
715 unsigned needs_mm : 1;
716 /* needs req->file assigned */
717 unsigned needs_file : 1;
718 /* don't fail if file grab fails */
719 unsigned needs_file_no_error : 1;
720 /* hash wq insertion if file is a regular file */
721 unsigned hash_reg_file : 1;
722 /* unbound wq insertion if file is a non-regular file */
723 unsigned unbound_nonreg_file : 1;
724 /* opcode is not supported by this kernel */
725 unsigned not_supported : 1;
726 /* needs file table */
727 unsigned file_table : 1;
728 /* needs ->fs */
729 unsigned needs_fs : 1;
730 /* set if opcode supports polled "wait" */
731 unsigned pollin : 1;
732 unsigned pollout : 1;
733 /* op supports buffer selection */
734 unsigned buffer_select : 1;
735 };
736
737 static const struct io_op_def io_op_defs[] = {
738 [IORING_OP_NOP] = {},
739 [IORING_OP_READV] = {
740 .async_ctx = 1,
741 .needs_mm = 1,
742 .needs_file = 1,
743 .unbound_nonreg_file = 1,
744 .pollin = 1,
745 .buffer_select = 1,
746 },
747 [IORING_OP_WRITEV] = {
748 .async_ctx = 1,
749 .needs_mm = 1,
750 .needs_file = 1,
751 .hash_reg_file = 1,
752 .unbound_nonreg_file = 1,
753 .pollout = 1,
754 },
755 [IORING_OP_FSYNC] = {
756 .needs_file = 1,
757 },
758 [IORING_OP_READ_FIXED] = {
759 .needs_file = 1,
760 .unbound_nonreg_file = 1,
761 .pollin = 1,
762 },
763 [IORING_OP_WRITE_FIXED] = {
764 .needs_file = 1,
765 .hash_reg_file = 1,
766 .unbound_nonreg_file = 1,
767 .pollout = 1,
768 },
769 [IORING_OP_POLL_ADD] = {
770 .needs_file = 1,
771 .unbound_nonreg_file = 1,
772 },
773 [IORING_OP_POLL_REMOVE] = {},
774 [IORING_OP_SYNC_FILE_RANGE] = {
775 .needs_file = 1,
776 },
777 [IORING_OP_SENDMSG] = {
778 .async_ctx = 1,
779 .needs_mm = 1,
780 .needs_file = 1,
781 .unbound_nonreg_file = 1,
782 .needs_fs = 1,
783 .pollout = 1,
784 },
785 [IORING_OP_RECVMSG] = {
786 .async_ctx = 1,
787 .needs_mm = 1,
788 .needs_file = 1,
789 .unbound_nonreg_file = 1,
790 .needs_fs = 1,
791 .pollin = 1,
792 .buffer_select = 1,
793 },
794 [IORING_OP_TIMEOUT] = {
795 .async_ctx = 1,
796 .needs_mm = 1,
797 },
798 [IORING_OP_TIMEOUT_REMOVE] = {},
799 [IORING_OP_ACCEPT] = {
800 .needs_mm = 1,
801 .needs_file = 1,
802 .unbound_nonreg_file = 1,
803 .file_table = 1,
804 .pollin = 1,
805 },
806 [IORING_OP_ASYNC_CANCEL] = {},
807 [IORING_OP_LINK_TIMEOUT] = {
808 .async_ctx = 1,
809 .needs_mm = 1,
810 },
811 [IORING_OP_CONNECT] = {
812 .async_ctx = 1,
813 .needs_mm = 1,
814 .needs_file = 1,
815 .unbound_nonreg_file = 1,
816 .pollout = 1,
817 },
818 [IORING_OP_FALLOCATE] = {
819 .needs_file = 1,
820 },
821 [IORING_OP_OPENAT] = {
822 .file_table = 1,
823 .needs_fs = 1,
824 },
825 [IORING_OP_CLOSE] = {
826 .needs_file = 1,
827 .needs_file_no_error = 1,
828 .file_table = 1,
829 },
830 [IORING_OP_FILES_UPDATE] = {
831 .needs_mm = 1,
832 .file_table = 1,
833 },
834 [IORING_OP_STATX] = {
835 .needs_mm = 1,
836 .needs_fs = 1,
837 .file_table = 1,
838 },
839 [IORING_OP_READ] = {
840 .needs_mm = 1,
841 .needs_file = 1,
842 .unbound_nonreg_file = 1,
843 .pollin = 1,
844 .buffer_select = 1,
845 },
846 [IORING_OP_WRITE] = {
847 .needs_mm = 1,
848 .needs_file = 1,
849 .unbound_nonreg_file = 1,
850 .pollout = 1,
851 },
852 [IORING_OP_FADVISE] = {
853 .needs_file = 1,
854 },
855 [IORING_OP_MADVISE] = {
856 .needs_mm = 1,
857 },
858 [IORING_OP_SEND] = {
859 .needs_mm = 1,
860 .needs_file = 1,
861 .unbound_nonreg_file = 1,
862 .pollout = 1,
863 },
864 [IORING_OP_RECV] = {
865 .needs_mm = 1,
866 .needs_file = 1,
867 .unbound_nonreg_file = 1,
868 .pollin = 1,
869 .buffer_select = 1,
870 },
871 [IORING_OP_OPENAT2] = {
872 .file_table = 1,
873 .needs_fs = 1,
874 },
875 [IORING_OP_EPOLL_CTL] = {
876 .unbound_nonreg_file = 1,
877 .file_table = 1,
878 },
879 [IORING_OP_SPLICE] = {
880 .needs_file = 1,
881 .hash_reg_file = 1,
882 .unbound_nonreg_file = 1,
883 },
884 [IORING_OP_PROVIDE_BUFFERS] = {},
885 [IORING_OP_REMOVE_BUFFERS] = {},
886 [IORING_OP_TEE] = {
887 .needs_file = 1,
888 .hash_reg_file = 1,
889 .unbound_nonreg_file = 1,
890 },
891 };
892
893 enum io_mem_account {
894 ACCT_LOCKED,
895 ACCT_PINNED,
896 };
897
898 static void io_wq_submit_work(struct io_wq_work **workptr);
899 static void io_cqring_fill_event(struct io_kiocb *req, long res);
900 static void io_put_req(struct io_kiocb *req);
901 static void __io_double_put_req(struct io_kiocb *req);
902 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req);
903 static void io_queue_linked_timeout(struct io_kiocb *req);
904 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
905 struct io_uring_files_update *ip,
906 unsigned nr_args);
907 static int io_grab_files(struct io_kiocb *req);
908 static void io_cleanup_req(struct io_kiocb *req);
909 static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
910 int fd, struct file **out_file, bool fixed);
911 static void __io_queue_sqe(struct io_kiocb *req,
912 const struct io_uring_sqe *sqe,
913 struct io_comp_state *cs);
914
915 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
916 struct iovec **iovec, struct iov_iter *iter,
917 bool needs_lock);
918 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
919 struct iovec *iovec, struct iovec *fast_iov,
920 struct iov_iter *iter);
921
922 static struct kmem_cache *req_cachep;
923
924 static const struct file_operations io_uring_fops;
925
926 struct sock *io_uring_get_socket(struct file *file)
927 {
928 #if defined(CONFIG_UNIX)
929 if (file->f_op == &io_uring_fops) {
930 struct io_ring_ctx *ctx = file->private_data;
931
932 return ctx->ring_sock->sk;
933 }
934 #endif
935 return NULL;
936 }
937 EXPORT_SYMBOL(io_uring_get_socket);
938
939 static void io_get_req_task(struct io_kiocb *req)
940 {
941 if (req->flags & REQ_F_TASK_PINNED)
942 return;
943 get_task_struct(req->task);
944 req->flags |= REQ_F_TASK_PINNED;
945 }
946
947 /* not idempotent -- it doesn't clear REQ_F_TASK_PINNED */
948 static void __io_put_req_task(struct io_kiocb *req)
949 {
950 if (req->flags & REQ_F_TASK_PINNED)
951 put_task_struct(req->task);
952 }
953
954 static void io_file_put_work(struct work_struct *work);
955
956 /*
957 * Note: must call io_req_init_async() for the first time you
958 * touch any members of io_wq_work.
959 */
960 static inline void io_req_init_async(struct io_kiocb *req)
961 {
962 if (req->flags & REQ_F_WORK_INITIALIZED)
963 return;
964
965 memset(&req->work, 0, sizeof(req->work));
966 req->flags |= REQ_F_WORK_INITIALIZED;
967 }
968
969 static inline bool io_async_submit(struct io_ring_ctx *ctx)
970 {
971 return ctx->flags & IORING_SETUP_SQPOLL;
972 }
973
974 static void io_ring_ctx_ref_free(struct percpu_ref *ref)
975 {
976 struct io_ring_ctx *ctx = container_of(ref, struct io_ring_ctx, refs);
977
978 complete(&ctx->ref_comp);
979 }
980
981 static struct io_ring_ctx *io_ring_ctx_alloc(struct io_uring_params *p)
982 {
983 struct io_ring_ctx *ctx;
984 int hash_bits;
985
986 ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
987 if (!ctx)
988 return NULL;
989
990 ctx->fallback_req = kmem_cache_alloc(req_cachep, GFP_KERNEL);
991 if (!ctx->fallback_req)
992 goto err;
993
994 /*
995 * Use 5 bits less than the max cq entries, that should give us around
996 * 32 entries per hash list if totally full and uniformly spread.
997 */
998 hash_bits = ilog2(p->cq_entries);
999 hash_bits -= 5;
1000 if (hash_bits <= 0)
1001 hash_bits = 1;
1002 ctx->cancel_hash_bits = hash_bits;
1003 ctx->cancel_hash = kmalloc((1U << hash_bits) * sizeof(struct hlist_head),
1004 GFP_KERNEL);
1005 if (!ctx->cancel_hash)
1006 goto err;
1007 __hash_init(ctx->cancel_hash, 1U << hash_bits);
1008
1009 if (percpu_ref_init(&ctx->refs, io_ring_ctx_ref_free,
1010 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL))
1011 goto err;
1012
1013 ctx->flags = p->flags;
1014 init_waitqueue_head(&ctx->sqo_wait);
1015 init_waitqueue_head(&ctx->cq_wait);
1016 INIT_LIST_HEAD(&ctx->cq_overflow_list);
1017 init_completion(&ctx->ref_comp);
1018 init_completion(&ctx->sq_thread_comp);
1019 idr_init(&ctx->io_buffer_idr);
1020 idr_init(&ctx->personality_idr);
1021 mutex_init(&ctx->uring_lock);
1022 init_waitqueue_head(&ctx->wait);
1023 spin_lock_init(&ctx->completion_lock);
1024 INIT_LIST_HEAD(&ctx->poll_list);
1025 INIT_LIST_HEAD(&ctx->defer_list);
1026 INIT_LIST_HEAD(&ctx->timeout_list);
1027 init_waitqueue_head(&ctx->inflight_wait);
1028 spin_lock_init(&ctx->inflight_lock);
1029 INIT_LIST_HEAD(&ctx->inflight_list);
1030 INIT_DELAYED_WORK(&ctx->file_put_work, io_file_put_work);
1031 init_llist_head(&ctx->file_put_llist);
1032 return ctx;
1033 err:
1034 if (ctx->fallback_req)
1035 kmem_cache_free(req_cachep, ctx->fallback_req);
1036 kfree(ctx->cancel_hash);
1037 kfree(ctx);
1038 return NULL;
1039 }
1040
1041 static inline bool __req_need_defer(struct io_kiocb *req)
1042 {
1043 struct io_ring_ctx *ctx = req->ctx;
1044
1045 return req->sequence != ctx->cached_cq_tail
1046 + atomic_read(&ctx->cached_cq_overflow);
1047 }
1048
1049 static inline bool req_need_defer(struct io_kiocb *req)
1050 {
1051 if (unlikely(req->flags & REQ_F_IO_DRAIN))
1052 return __req_need_defer(req);
1053
1054 return false;
1055 }
1056
1057 static void __io_commit_cqring(struct io_ring_ctx *ctx)
1058 {
1059 struct io_rings *rings = ctx->rings;
1060
1061 /* order cqe stores with ring update */
1062 smp_store_release(&rings->cq.tail, ctx->cached_cq_tail);
1063
1064 if (wq_has_sleeper(&ctx->cq_wait)) {
1065 wake_up_interruptible(&ctx->cq_wait);
1066 kill_fasync(&ctx->cq_fasync, SIGIO, POLL_IN);
1067 }
1068 }
1069
1070 static inline void io_req_work_grab_env(struct io_kiocb *req,
1071 const struct io_op_def *def)
1072 {
1073 if (!req->work.mm && def->needs_mm) {
1074 mmgrab(current->mm);
1075 req->work.mm = current->mm;
1076 }
1077 if (!req->work.creds)
1078 req->work.creds = get_current_cred();
1079 if (!req->work.fs && def->needs_fs) {
1080 spin_lock(&current->fs->lock);
1081 if (!current->fs->in_exec) {
1082 req->work.fs = current->fs;
1083 req->work.fs->users++;
1084 } else {
1085 req->work.flags |= IO_WQ_WORK_CANCEL;
1086 }
1087 spin_unlock(&current->fs->lock);
1088 }
1089 }
1090
1091 static inline void io_req_work_drop_env(struct io_kiocb *req)
1092 {
1093 if (!(req->flags & REQ_F_WORK_INITIALIZED))
1094 return;
1095
1096 if (req->work.mm) {
1097 mmdrop(req->work.mm);
1098 req->work.mm = NULL;
1099 }
1100 if (req->work.creds) {
1101 put_cred(req->work.creds);
1102 req->work.creds = NULL;
1103 }
1104 if (req->work.fs) {
1105 struct fs_struct *fs = req->work.fs;
1106
1107 spin_lock(&req->work.fs->lock);
1108 if (--fs->users)
1109 fs = NULL;
1110 spin_unlock(&req->work.fs->lock);
1111 if (fs)
1112 free_fs_struct(fs);
1113 }
1114 }
1115
1116 static inline void io_prep_async_work(struct io_kiocb *req,
1117 struct io_kiocb **link)
1118 {
1119 const struct io_op_def *def = &io_op_defs[req->opcode];
1120
1121 if (req->flags & REQ_F_ISREG) {
1122 if (def->hash_reg_file)
1123 io_wq_hash_work(&req->work, file_inode(req->file));
1124 } else {
1125 if (def->unbound_nonreg_file)
1126 req->work.flags |= IO_WQ_WORK_UNBOUND;
1127 }
1128
1129 io_req_init_async(req);
1130 io_req_work_grab_env(req, def);
1131
1132 *link = io_prep_linked_timeout(req);
1133 }
1134
1135 static inline void io_queue_async_work(struct io_kiocb *req)
1136 {
1137 struct io_ring_ctx *ctx = req->ctx;
1138 struct io_kiocb *link;
1139
1140 io_prep_async_work(req, &link);
1141
1142 trace_io_uring_queue_async_work(ctx, io_wq_is_hashed(&req->work), req,
1143 &req->work, req->flags);
1144 io_wq_enqueue(ctx->io_wq, &req->work);
1145
1146 if (link)
1147 io_queue_linked_timeout(link);
1148 }
1149
1150 static void io_kill_timeout(struct io_kiocb *req)
1151 {
1152 int ret;
1153
1154 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1155 if (ret != -1) {
1156 atomic_inc(&req->ctx->cq_timeouts);
1157 list_del_init(&req->list);
1158 req->flags |= REQ_F_COMP_LOCKED;
1159 io_cqring_fill_event(req, 0);
1160 io_put_req(req);
1161 }
1162 }
1163
1164 static void io_kill_timeouts(struct io_ring_ctx *ctx)
1165 {
1166 struct io_kiocb *req, *tmp;
1167
1168 spin_lock_irq(&ctx->completion_lock);
1169 list_for_each_entry_safe(req, tmp, &ctx->timeout_list, list)
1170 io_kill_timeout(req);
1171 spin_unlock_irq(&ctx->completion_lock);
1172 }
1173
1174 static void __io_queue_deferred(struct io_ring_ctx *ctx)
1175 {
1176 do {
1177 struct io_kiocb *req = list_first_entry(&ctx->defer_list,
1178 struct io_kiocb, list);
1179
1180 if (req_need_defer(req))
1181 break;
1182 list_del_init(&req->list);
1183 io_queue_async_work(req);
1184 } while (!list_empty(&ctx->defer_list));
1185 }
1186
1187 static void io_flush_timeouts(struct io_ring_ctx *ctx)
1188 {
1189 while (!list_empty(&ctx->timeout_list)) {
1190 struct io_kiocb *req = list_first_entry(&ctx->timeout_list,
1191 struct io_kiocb, list);
1192
1193 if (req->flags & REQ_F_TIMEOUT_NOSEQ)
1194 break;
1195 if (req->timeout.target_seq != ctx->cached_cq_tail
1196 - atomic_read(&ctx->cq_timeouts))
1197 break;
1198
1199 list_del_init(&req->list);
1200 io_kill_timeout(req);
1201 }
1202 }
1203
1204 static void io_commit_cqring(struct io_ring_ctx *ctx)
1205 {
1206 io_flush_timeouts(ctx);
1207 __io_commit_cqring(ctx);
1208
1209 if (unlikely(!list_empty(&ctx->defer_list)))
1210 __io_queue_deferred(ctx);
1211 }
1212
1213 static struct io_uring_cqe *io_get_cqring(struct io_ring_ctx *ctx)
1214 {
1215 struct io_rings *rings = ctx->rings;
1216 unsigned tail;
1217
1218 tail = ctx->cached_cq_tail;
1219 /*
1220 * writes to the cq entry need to come after reading head; the
1221 * control dependency is enough as we're using WRITE_ONCE to
1222 * fill the cq entry
1223 */
1224 if (tail - READ_ONCE(rings->cq.head) == rings->cq_ring_entries)
1225 return NULL;
1226
1227 ctx->cached_cq_tail++;
1228 return &rings->cqes[tail & ctx->cq_mask];
1229 }
1230
1231 static inline bool io_should_trigger_evfd(struct io_ring_ctx *ctx)
1232 {
1233 if (!ctx->cq_ev_fd)
1234 return false;
1235 if (READ_ONCE(ctx->rings->cq_flags) & IORING_CQ_EVENTFD_DISABLED)
1236 return false;
1237 if (!ctx->eventfd_async)
1238 return true;
1239 return io_wq_current_is_worker();
1240 }
1241
1242 static void io_cqring_ev_posted(struct io_ring_ctx *ctx)
1243 {
1244 if (waitqueue_active(&ctx->wait))
1245 wake_up(&ctx->wait);
1246 if (waitqueue_active(&ctx->sqo_wait))
1247 wake_up(&ctx->sqo_wait);
1248 if (io_should_trigger_evfd(ctx))
1249 eventfd_signal(ctx->cq_ev_fd, 1);
1250 }
1251
1252 /* Returns true if there are no backlogged entries after the flush */
1253 static bool io_cqring_overflow_flush(struct io_ring_ctx *ctx, bool force)
1254 {
1255 struct io_rings *rings = ctx->rings;
1256 struct io_uring_cqe *cqe;
1257 struct io_kiocb *req;
1258 unsigned long flags;
1259 LIST_HEAD(list);
1260
1261 if (!force) {
1262 if (list_empty_careful(&ctx->cq_overflow_list))
1263 return true;
1264 if ((ctx->cached_cq_tail - READ_ONCE(rings->cq.head) ==
1265 rings->cq_ring_entries))
1266 return false;
1267 }
1268
1269 spin_lock_irqsave(&ctx->completion_lock, flags);
1270
1271 /* if force is set, the ring is going away. always drop after that */
1272 if (force)
1273 ctx->cq_overflow_flushed = 1;
1274
1275 cqe = NULL;
1276 while (!list_empty(&ctx->cq_overflow_list)) {
1277 cqe = io_get_cqring(ctx);
1278 if (!cqe && !force)
1279 break;
1280
1281 req = list_first_entry(&ctx->cq_overflow_list, struct io_kiocb,
1282 list);
1283 list_move(&req->list, &list);
1284 req->flags &= ~REQ_F_OVERFLOW;
1285 if (cqe) {
1286 WRITE_ONCE(cqe->user_data, req->user_data);
1287 WRITE_ONCE(cqe->res, req->result);
1288 WRITE_ONCE(cqe->flags, req->cflags);
1289 } else {
1290 WRITE_ONCE(ctx->rings->cq_overflow,
1291 atomic_inc_return(&ctx->cached_cq_overflow));
1292 }
1293 }
1294
1295 io_commit_cqring(ctx);
1296 if (cqe) {
1297 clear_bit(0, &ctx->sq_check_overflow);
1298 clear_bit(0, &ctx->cq_check_overflow);
1299 }
1300 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1301 io_cqring_ev_posted(ctx);
1302
1303 while (!list_empty(&list)) {
1304 req = list_first_entry(&list, struct io_kiocb, list);
1305 list_del(&req->list);
1306 io_put_req(req);
1307 }
1308
1309 return cqe != NULL;
1310 }
1311
1312 static void __io_cqring_fill_event(struct io_kiocb *req, long res, long cflags)
1313 {
1314 struct io_ring_ctx *ctx = req->ctx;
1315 struct io_uring_cqe *cqe;
1316
1317 trace_io_uring_complete(ctx, req->user_data, res);
1318
1319 /*
1320 * If we can't get a cq entry, userspace overflowed the
1321 * submission (by quite a lot). Increment the overflow count in
1322 * the ring.
1323 */
1324 cqe = io_get_cqring(ctx);
1325 if (likely(cqe)) {
1326 WRITE_ONCE(cqe->user_data, req->user_data);
1327 WRITE_ONCE(cqe->res, res);
1328 WRITE_ONCE(cqe->flags, cflags);
1329 } else if (ctx->cq_overflow_flushed) {
1330 WRITE_ONCE(ctx->rings->cq_overflow,
1331 atomic_inc_return(&ctx->cached_cq_overflow));
1332 } else {
1333 if (list_empty(&ctx->cq_overflow_list)) {
1334 set_bit(0, &ctx->sq_check_overflow);
1335 set_bit(0, &ctx->cq_check_overflow);
1336 }
1337 req->flags |= REQ_F_OVERFLOW;
1338 refcount_inc(&req->refs);
1339 req->result = res;
1340 req->cflags = cflags;
1341 list_add_tail(&req->list, &ctx->cq_overflow_list);
1342 }
1343 }
1344
1345 static void io_cqring_fill_event(struct io_kiocb *req, long res)
1346 {
1347 __io_cqring_fill_event(req, res, 0);
1348 }
1349
1350 static void io_cqring_add_event(struct io_kiocb *req, long res, long cflags)
1351 {
1352 struct io_ring_ctx *ctx = req->ctx;
1353 unsigned long flags;
1354
1355 spin_lock_irqsave(&ctx->completion_lock, flags);
1356 __io_cqring_fill_event(req, res, cflags);
1357 io_commit_cqring(ctx);
1358 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1359
1360 io_cqring_ev_posted(ctx);
1361 }
1362
1363 static void io_submit_flush_completions(struct io_comp_state *cs)
1364 {
1365 struct io_ring_ctx *ctx = cs->ctx;
1366
1367 spin_lock_irq(&ctx->completion_lock);
1368 while (!list_empty(&cs->list)) {
1369 struct io_kiocb *req;
1370
1371 req = list_first_entry(&cs->list, struct io_kiocb, list);
1372 list_del(&req->list);
1373 io_cqring_fill_event(req, req->result);
1374 if (!(req->flags & REQ_F_LINK_HEAD)) {
1375 req->flags |= REQ_F_COMP_LOCKED;
1376 io_put_req(req);
1377 } else {
1378 spin_unlock_irq(&ctx->completion_lock);
1379 io_put_req(req);
1380 spin_lock_irq(&ctx->completion_lock);
1381 }
1382 }
1383 io_commit_cqring(ctx);
1384 spin_unlock_irq(&ctx->completion_lock);
1385
1386 io_cqring_ev_posted(ctx);
1387 cs->nr = 0;
1388 }
1389
1390 static void __io_req_complete(struct io_kiocb *req, long res, unsigned cflags,
1391 struct io_comp_state *cs)
1392 {
1393 if (!cs) {
1394 io_cqring_add_event(req, res, cflags);
1395 io_put_req(req);
1396 } else {
1397 req->result = res;
1398 list_add_tail(&req->list, &cs->list);
1399 if (++cs->nr >= 32)
1400 io_submit_flush_completions(cs);
1401 }
1402 }
1403
1404 static void io_req_complete(struct io_kiocb *req, long res)
1405 {
1406 __io_req_complete(req, res, 0, NULL);
1407 }
1408
1409 static inline bool io_is_fallback_req(struct io_kiocb *req)
1410 {
1411 return req == (struct io_kiocb *)
1412 ((unsigned long) req->ctx->fallback_req & ~1UL);
1413 }
1414
1415 static struct io_kiocb *io_get_fallback_req(struct io_ring_ctx *ctx)
1416 {
1417 struct io_kiocb *req;
1418
1419 req = ctx->fallback_req;
1420 if (!test_and_set_bit_lock(0, (unsigned long *) &ctx->fallback_req))
1421 return req;
1422
1423 return NULL;
1424 }
1425
1426 static struct io_kiocb *io_alloc_req(struct io_ring_ctx *ctx,
1427 struct io_submit_state *state)
1428 {
1429 gfp_t gfp = GFP_KERNEL | __GFP_NOWARN;
1430 struct io_kiocb *req;
1431
1432 if (!state->free_reqs) {
1433 size_t sz;
1434 int ret;
1435
1436 sz = min_t(size_t, state->ios_left, ARRAY_SIZE(state->reqs));
1437 ret = kmem_cache_alloc_bulk(req_cachep, gfp, sz, state->reqs);
1438
1439 /*
1440 * Bulk alloc is all-or-nothing. If we fail to get a batch,
1441 * retry single alloc to be on the safe side.
1442 */
1443 if (unlikely(ret <= 0)) {
1444 state->reqs[0] = kmem_cache_alloc(req_cachep, gfp);
1445 if (!state->reqs[0])
1446 goto fallback;
1447 ret = 1;
1448 }
1449 state->free_reqs = ret - 1;
1450 req = state->reqs[ret - 1];
1451 } else {
1452 state->free_reqs--;
1453 req = state->reqs[state->free_reqs];
1454 }
1455
1456 return req;
1457 fallback:
1458 return io_get_fallback_req(ctx);
1459 }
1460
1461 static inline void io_put_file(struct io_kiocb *req, struct file *file,
1462 bool fixed)
1463 {
1464 if (fixed)
1465 percpu_ref_put(req->fixed_file_refs);
1466 else
1467 fput(file);
1468 }
1469
1470 static void __io_req_aux_free(struct io_kiocb *req)
1471 {
1472 if (req->flags & REQ_F_NEED_CLEANUP)
1473 io_cleanup_req(req);
1474
1475 kfree(req->io);
1476 if (req->file)
1477 io_put_file(req, req->file, (req->flags & REQ_F_FIXED_FILE));
1478 __io_put_req_task(req);
1479 io_req_work_drop_env(req);
1480 }
1481
1482 static void __io_free_req(struct io_kiocb *req)
1483 {
1484 __io_req_aux_free(req);
1485
1486 if (req->flags & REQ_F_INFLIGHT) {
1487 struct io_ring_ctx *ctx = req->ctx;
1488 unsigned long flags;
1489
1490 spin_lock_irqsave(&ctx->inflight_lock, flags);
1491 list_del(&req->inflight_entry);
1492 if (waitqueue_active(&ctx->inflight_wait))
1493 wake_up(&ctx->inflight_wait);
1494 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1495 }
1496
1497 percpu_ref_put(&req->ctx->refs);
1498 if (likely(!io_is_fallback_req(req)))
1499 kmem_cache_free(req_cachep, req);
1500 else
1501 clear_bit_unlock(0, (unsigned long *) &req->ctx->fallback_req);
1502 }
1503
1504 struct req_batch {
1505 void *reqs[IO_IOPOLL_BATCH];
1506 int to_free;
1507 int need_iter;
1508 };
1509
1510 static void io_free_req_many(struct io_ring_ctx *ctx, struct req_batch *rb)
1511 {
1512 if (!rb->to_free)
1513 return;
1514 if (rb->need_iter) {
1515 int i, inflight = 0;
1516 unsigned long flags;
1517
1518 for (i = 0; i < rb->to_free; i++) {
1519 struct io_kiocb *req = rb->reqs[i];
1520
1521 if (req->flags & REQ_F_INFLIGHT)
1522 inflight++;
1523 __io_req_aux_free(req);
1524 }
1525 if (!inflight)
1526 goto do_free;
1527
1528 spin_lock_irqsave(&ctx->inflight_lock, flags);
1529 for (i = 0; i < rb->to_free; i++) {
1530 struct io_kiocb *req = rb->reqs[i];
1531
1532 if (req->flags & REQ_F_INFLIGHT) {
1533 list_del(&req->inflight_entry);
1534 if (!--inflight)
1535 break;
1536 }
1537 }
1538 spin_unlock_irqrestore(&ctx->inflight_lock, flags);
1539
1540 if (waitqueue_active(&ctx->inflight_wait))
1541 wake_up(&ctx->inflight_wait);
1542 }
1543 do_free:
1544 kmem_cache_free_bulk(req_cachep, rb->to_free, rb->reqs);
1545 percpu_ref_put_many(&ctx->refs, rb->to_free);
1546 rb->to_free = rb->need_iter = 0;
1547 }
1548
1549 static bool io_link_cancel_timeout(struct io_kiocb *req)
1550 {
1551 struct io_ring_ctx *ctx = req->ctx;
1552 int ret;
1553
1554 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
1555 if (ret != -1) {
1556 io_cqring_fill_event(req, -ECANCELED);
1557 io_commit_cqring(ctx);
1558 req->flags &= ~REQ_F_LINK_HEAD;
1559 io_put_req(req);
1560 return true;
1561 }
1562
1563 return false;
1564 }
1565
1566 static void io_req_link_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1567 {
1568 struct io_ring_ctx *ctx = req->ctx;
1569 bool wake_ev = false;
1570
1571 /* Already got next link */
1572 if (req->flags & REQ_F_LINK_NEXT)
1573 return;
1574
1575 /*
1576 * The list should never be empty when we are called here. But could
1577 * potentially happen if the chain is messed up, check to be on the
1578 * safe side.
1579 */
1580 while (!list_empty(&req->link_list)) {
1581 struct io_kiocb *nxt = list_first_entry(&req->link_list,
1582 struct io_kiocb, link_list);
1583
1584 if (unlikely((req->flags & REQ_F_LINK_TIMEOUT) &&
1585 (nxt->flags & REQ_F_TIMEOUT))) {
1586 list_del_init(&nxt->link_list);
1587 wake_ev |= io_link_cancel_timeout(nxt);
1588 req->flags &= ~REQ_F_LINK_TIMEOUT;
1589 continue;
1590 }
1591
1592 list_del_init(&req->link_list);
1593 if (!list_empty(&nxt->link_list))
1594 nxt->flags |= REQ_F_LINK_HEAD;
1595 *nxtptr = nxt;
1596 break;
1597 }
1598
1599 req->flags |= REQ_F_LINK_NEXT;
1600 if (wake_ev)
1601 io_cqring_ev_posted(ctx);
1602 }
1603
1604 /*
1605 * Called if REQ_F_LINK_HEAD is set, and we fail the head request
1606 */
1607 static void io_fail_links(struct io_kiocb *req)
1608 {
1609 struct io_ring_ctx *ctx = req->ctx;
1610 unsigned long flags;
1611
1612 spin_lock_irqsave(&ctx->completion_lock, flags);
1613
1614 while (!list_empty(&req->link_list)) {
1615 struct io_kiocb *link = list_first_entry(&req->link_list,
1616 struct io_kiocb, link_list);
1617
1618 list_del_init(&link->link_list);
1619 trace_io_uring_fail_link(req, link);
1620
1621 if ((req->flags & REQ_F_LINK_TIMEOUT) &&
1622 link->opcode == IORING_OP_LINK_TIMEOUT) {
1623 io_link_cancel_timeout(link);
1624 } else {
1625 io_cqring_fill_event(link, -ECANCELED);
1626 __io_double_put_req(link);
1627 }
1628 req->flags &= ~REQ_F_LINK_TIMEOUT;
1629 }
1630
1631 io_commit_cqring(ctx);
1632 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1633 io_cqring_ev_posted(ctx);
1634 }
1635
1636 static void io_req_find_next(struct io_kiocb *req, struct io_kiocb **nxt)
1637 {
1638 if (likely(!(req->flags & REQ_F_LINK_HEAD)))
1639 return;
1640
1641 /*
1642 * If LINK is set, we have dependent requests in this chain. If we
1643 * didn't fail this request, queue the first one up, moving any other
1644 * dependencies to the next request. In case of failure, fail the rest
1645 * of the chain.
1646 */
1647 if (req->flags & REQ_F_FAIL_LINK) {
1648 io_fail_links(req);
1649 } else if ((req->flags & (REQ_F_LINK_TIMEOUT | REQ_F_COMP_LOCKED)) ==
1650 REQ_F_LINK_TIMEOUT) {
1651 struct io_ring_ctx *ctx = req->ctx;
1652 unsigned long flags;
1653
1654 /*
1655 * If this is a timeout link, we could be racing with the
1656 * timeout timer. Grab the completion lock for this case to
1657 * protect against that.
1658 */
1659 spin_lock_irqsave(&ctx->completion_lock, flags);
1660 io_req_link_next(req, nxt);
1661 spin_unlock_irqrestore(&ctx->completion_lock, flags);
1662 } else {
1663 io_req_link_next(req, nxt);
1664 }
1665 }
1666
1667 static void io_free_req(struct io_kiocb *req)
1668 {
1669 struct io_kiocb *nxt = NULL;
1670
1671 io_req_find_next(req, &nxt);
1672 __io_free_req(req);
1673
1674 if (nxt)
1675 io_queue_async_work(nxt);
1676 }
1677
1678 static void io_wq_assign_next(struct io_wq_work **workptr, struct io_kiocb *nxt)
1679 {
1680 struct io_kiocb *link;
1681 const struct io_op_def *def = &io_op_defs[nxt->opcode];
1682
1683 if ((nxt->flags & REQ_F_ISREG) && def->hash_reg_file)
1684 io_wq_hash_work(&nxt->work, file_inode(nxt->file));
1685
1686 *workptr = &nxt->work;
1687 link = io_prep_linked_timeout(nxt);
1688 if (link)
1689 nxt->flags |= REQ_F_QUEUE_TIMEOUT;
1690 }
1691
1692 /*
1693 * Drop reference to request, return next in chain (if there is one) if this
1694 * was the last reference to this request.
1695 */
1696 __attribute__((nonnull))
1697 static void io_put_req_find_next(struct io_kiocb *req, struct io_kiocb **nxtptr)
1698 {
1699 if (refcount_dec_and_test(&req->refs)) {
1700 io_req_find_next(req, nxtptr);
1701 __io_free_req(req);
1702 }
1703 }
1704
1705 static void io_put_req(struct io_kiocb *req)
1706 {
1707 if (refcount_dec_and_test(&req->refs))
1708 io_free_req(req);
1709 }
1710
1711 static void io_steal_work(struct io_kiocb *req,
1712 struct io_wq_work **workptr)
1713 {
1714 /*
1715 * It's in an io-wq worker, so there always should be at least
1716 * one reference, which will be dropped in io_put_work() just
1717 * after the current handler returns.
1718 *
1719 * It also means, that if the counter dropped to 1, then there is
1720 * no asynchronous users left, so it's safe to steal the next work.
1721 */
1722 if (refcount_read(&req->refs) == 1) {
1723 struct io_kiocb *nxt = NULL;
1724
1725 io_req_find_next(req, &nxt);
1726 if (nxt)
1727 io_wq_assign_next(workptr, nxt);
1728 }
1729 }
1730
1731 /*
1732 * Must only be used if we don't need to care about links, usually from
1733 * within the completion handling itself.
1734 */
1735 static void __io_double_put_req(struct io_kiocb *req)
1736 {
1737 /* drop both submit and complete references */
1738 if (refcount_sub_and_test(2, &req->refs))
1739 __io_free_req(req);
1740 }
1741
1742 static void io_double_put_req(struct io_kiocb *req)
1743 {
1744 /* drop both submit and complete references */
1745 if (refcount_sub_and_test(2, &req->refs))
1746 io_free_req(req);
1747 }
1748
1749 static unsigned io_cqring_events(struct io_ring_ctx *ctx, bool noflush)
1750 {
1751 struct io_rings *rings = ctx->rings;
1752
1753 if (test_bit(0, &ctx->cq_check_overflow)) {
1754 /*
1755 * noflush == true is from the waitqueue handler, just ensure
1756 * we wake up the task, and the next invocation will flush the
1757 * entries. We cannot safely to it from here.
1758 */
1759 if (noflush && !list_empty(&ctx->cq_overflow_list))
1760 return -1U;
1761
1762 io_cqring_overflow_flush(ctx, false);
1763 }
1764
1765 /* See comment at the top of this file */
1766 smp_rmb();
1767 return ctx->cached_cq_tail - READ_ONCE(rings->cq.head);
1768 }
1769
1770 static inline unsigned int io_sqring_entries(struct io_ring_ctx *ctx)
1771 {
1772 struct io_rings *rings = ctx->rings;
1773
1774 /* make sure SQ entry isn't read before tail */
1775 return smp_load_acquire(&rings->sq.tail) - ctx->cached_sq_head;
1776 }
1777
1778 static inline bool io_req_multi_free(struct req_batch *rb, struct io_kiocb *req)
1779 {
1780 if ((req->flags & REQ_F_LINK_HEAD) || io_is_fallback_req(req))
1781 return false;
1782
1783 if (req->file || req->io)
1784 rb->need_iter++;
1785
1786 rb->reqs[rb->to_free++] = req;
1787 if (unlikely(rb->to_free == ARRAY_SIZE(rb->reqs)))
1788 io_free_req_many(req->ctx, rb);
1789 return true;
1790 }
1791
1792 static int io_put_kbuf(struct io_kiocb *req)
1793 {
1794 struct io_buffer *kbuf;
1795 int cflags;
1796
1797 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
1798 cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
1799 cflags |= IORING_CQE_F_BUFFER;
1800 req->rw.addr = 0;
1801 kfree(kbuf);
1802 return cflags;
1803 }
1804
1805 static void io_iopoll_queue(struct list_head *again)
1806 {
1807 struct io_kiocb *req;
1808
1809 do {
1810 req = list_first_entry(again, struct io_kiocb, list);
1811 list_del(&req->list);
1812 refcount_inc(&req->refs);
1813 io_queue_async_work(req);
1814 } while (!list_empty(again));
1815 }
1816
1817 /*
1818 * Find and free completed poll iocbs
1819 */
1820 static void io_iopoll_complete(struct io_ring_ctx *ctx, unsigned int *nr_events,
1821 struct list_head *done)
1822 {
1823 struct req_batch rb;
1824 struct io_kiocb *req;
1825 LIST_HEAD(again);
1826
1827 /* order with ->result store in io_complete_rw_iopoll() */
1828 smp_rmb();
1829
1830 rb.to_free = rb.need_iter = 0;
1831 while (!list_empty(done)) {
1832 int cflags = 0;
1833
1834 req = list_first_entry(done, struct io_kiocb, list);
1835 if (READ_ONCE(req->result) == -EAGAIN) {
1836 req->iopoll_completed = 0;
1837 list_move_tail(&req->list, &again);
1838 continue;
1839 }
1840 list_del(&req->list);
1841
1842 if (req->flags & REQ_F_BUFFER_SELECTED)
1843 cflags = io_put_kbuf(req);
1844
1845 __io_cqring_fill_event(req, req->result, cflags);
1846 (*nr_events)++;
1847
1848 if (refcount_dec_and_test(&req->refs) &&
1849 !io_req_multi_free(&rb, req))
1850 io_free_req(req);
1851 }
1852
1853 io_commit_cqring(ctx);
1854 if (ctx->flags & IORING_SETUP_SQPOLL)
1855 io_cqring_ev_posted(ctx);
1856 io_free_req_many(ctx, &rb);
1857
1858 if (!list_empty(&again))
1859 io_iopoll_queue(&again);
1860 }
1861
1862 static int io_do_iopoll(struct io_ring_ctx *ctx, unsigned int *nr_events,
1863 long min)
1864 {
1865 struct io_kiocb *req, *tmp;
1866 LIST_HEAD(done);
1867 bool spin;
1868 int ret;
1869
1870 /*
1871 * Only spin for completions if we don't have multiple devices hanging
1872 * off our complete list, and we're under the requested amount.
1873 */
1874 spin = !ctx->poll_multi_file && *nr_events < min;
1875
1876 ret = 0;
1877 list_for_each_entry_safe(req, tmp, &ctx->poll_list, list) {
1878 struct kiocb *kiocb = &req->rw.kiocb;
1879
1880 /*
1881 * Move completed and retryable entries to our local lists.
1882 * If we find a request that requires polling, break out
1883 * and complete those lists first, if we have entries there.
1884 */
1885 if (READ_ONCE(req->iopoll_completed)) {
1886 list_move_tail(&req->list, &done);
1887 continue;
1888 }
1889 if (!list_empty(&done))
1890 break;
1891
1892 ret = kiocb->ki_filp->f_op->iopoll(kiocb, spin);
1893 if (ret < 0)
1894 break;
1895
1896 if (ret && spin)
1897 spin = false;
1898 ret = 0;
1899 }
1900
1901 if (!list_empty(&done))
1902 io_iopoll_complete(ctx, nr_events, &done);
1903
1904 return ret;
1905 }
1906
1907 /*
1908 * Poll for a minimum of 'min' events. Note that if min == 0 we consider that a
1909 * non-spinning poll check - we'll still enter the driver poll loop, but only
1910 * as a non-spinning completion check.
1911 */
1912 static int io_iopoll_getevents(struct io_ring_ctx *ctx, unsigned int *nr_events,
1913 long min)
1914 {
1915 while (!list_empty(&ctx->poll_list) && !need_resched()) {
1916 int ret;
1917
1918 ret = io_do_iopoll(ctx, nr_events, min);
1919 if (ret < 0)
1920 return ret;
1921 if (!min || *nr_events >= min)
1922 return 0;
1923 }
1924
1925 return 1;
1926 }
1927
1928 /*
1929 * We can't just wait for polled events to come to us, we have to actively
1930 * find and complete them.
1931 */
1932 static void io_iopoll_reap_events(struct io_ring_ctx *ctx)
1933 {
1934 if (!(ctx->flags & IORING_SETUP_IOPOLL))
1935 return;
1936
1937 mutex_lock(&ctx->uring_lock);
1938 while (!list_empty(&ctx->poll_list)) {
1939 unsigned int nr_events = 0;
1940
1941 io_iopoll_getevents(ctx, &nr_events, 1);
1942
1943 /*
1944 * Ensure we allow local-to-the-cpu processing to take place,
1945 * in this case we need to ensure that we reap all events.
1946 */
1947 cond_resched();
1948 }
1949 mutex_unlock(&ctx->uring_lock);
1950 }
1951
1952 static int io_iopoll_check(struct io_ring_ctx *ctx, unsigned *nr_events,
1953 long min)
1954 {
1955 int iters = 0, ret = 0;
1956
1957 /*
1958 * We disallow the app entering submit/complete with polling, but we
1959 * still need to lock the ring to prevent racing with polled issue
1960 * that got punted to a workqueue.
1961 */
1962 mutex_lock(&ctx->uring_lock);
1963 do {
1964 int tmin = 0;
1965
1966 /*
1967 * Don't enter poll loop if we already have events pending.
1968 * If we do, we can potentially be spinning for commands that
1969 * already triggered a CQE (eg in error).
1970 */
1971 if (io_cqring_events(ctx, false))
1972 break;
1973
1974 /*
1975 * If a submit got punted to a workqueue, we can have the
1976 * application entering polling for a command before it gets
1977 * issued. That app will hold the uring_lock for the duration
1978 * of the poll right here, so we need to take a breather every
1979 * now and then to ensure that the issue has a chance to add
1980 * the poll to the issued list. Otherwise we can spin here
1981 * forever, while the workqueue is stuck trying to acquire the
1982 * very same mutex.
1983 */
1984 if (!(++iters & 7)) {
1985 mutex_unlock(&ctx->uring_lock);
1986 mutex_lock(&ctx->uring_lock);
1987 }
1988
1989 if (*nr_events < min)
1990 tmin = min - *nr_events;
1991
1992 ret = io_iopoll_getevents(ctx, nr_events, tmin);
1993 if (ret <= 0)
1994 break;
1995 ret = 0;
1996 } while (min && !*nr_events && !need_resched());
1997
1998 mutex_unlock(&ctx->uring_lock);
1999 return ret;
2000 }
2001
2002 static void kiocb_end_write(struct io_kiocb *req)
2003 {
2004 /*
2005 * Tell lockdep we inherited freeze protection from submission
2006 * thread.
2007 */
2008 if (req->flags & REQ_F_ISREG) {
2009 struct inode *inode = file_inode(req->file);
2010
2011 __sb_writers_acquired(inode->i_sb, SB_FREEZE_WRITE);
2012 }
2013 file_end_write(req->file);
2014 }
2015
2016 static inline void req_set_fail_links(struct io_kiocb *req)
2017 {
2018 if ((req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) == REQ_F_LINK)
2019 req->flags |= REQ_F_FAIL_LINK;
2020 }
2021
2022 static void io_complete_rw_common(struct kiocb *kiocb, long res)
2023 {
2024 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2025 int cflags = 0;
2026
2027 if (kiocb->ki_flags & IOCB_WRITE)
2028 kiocb_end_write(req);
2029
2030 if (res != req->result)
2031 req_set_fail_links(req);
2032 if (req->flags & REQ_F_BUFFER_SELECTED)
2033 cflags = io_put_kbuf(req);
2034 io_cqring_add_event(req, res, cflags);
2035 }
2036
2037 static void io_sq_thread_drop_mm(struct io_ring_ctx *ctx)
2038 {
2039 struct mm_struct *mm = current->mm;
2040
2041 if (mm) {
2042 kthread_unuse_mm(mm);
2043 mmput(mm);
2044 }
2045 }
2046
2047 static int __io_sq_thread_acquire_mm(struct io_ring_ctx *ctx)
2048 {
2049 if (!current->mm) {
2050 if (unlikely(!mmget_not_zero(ctx->sqo_mm)))
2051 return -EFAULT;
2052 kthread_use_mm(ctx->sqo_mm);
2053 }
2054
2055 return 0;
2056 }
2057
2058 static int io_sq_thread_acquire_mm(struct io_ring_ctx *ctx,
2059 struct io_kiocb *req)
2060 {
2061 if (!io_op_defs[req->opcode].needs_mm)
2062 return 0;
2063 return __io_sq_thread_acquire_mm(ctx);
2064 }
2065
2066 #ifdef CONFIG_BLOCK
2067 static bool io_resubmit_prep(struct io_kiocb *req, int error)
2068 {
2069 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2070 ssize_t ret = -ECANCELED;
2071 struct iov_iter iter;
2072 int rw;
2073
2074 if (error) {
2075 ret = error;
2076 goto end_req;
2077 }
2078
2079 switch (req->opcode) {
2080 case IORING_OP_READV:
2081 case IORING_OP_READ_FIXED:
2082 case IORING_OP_READ:
2083 rw = READ;
2084 break;
2085 case IORING_OP_WRITEV:
2086 case IORING_OP_WRITE_FIXED:
2087 case IORING_OP_WRITE:
2088 rw = WRITE;
2089 break;
2090 default:
2091 printk_once(KERN_WARNING "io_uring: bad opcode in resubmit %d\n",
2092 req->opcode);
2093 goto end_req;
2094 }
2095
2096 ret = io_import_iovec(rw, req, &iovec, &iter, false);
2097 if (ret < 0)
2098 goto end_req;
2099 ret = io_setup_async_rw(req, ret, iovec, inline_vecs, &iter);
2100 if (!ret)
2101 return true;
2102 kfree(iovec);
2103 end_req:
2104 req_set_fail_links(req);
2105 io_req_complete(req, ret);
2106 return false;
2107 }
2108
2109 static void io_rw_resubmit(struct callback_head *cb)
2110 {
2111 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
2112 struct io_ring_ctx *ctx = req->ctx;
2113 int err;
2114
2115 __set_current_state(TASK_RUNNING);
2116
2117 err = io_sq_thread_acquire_mm(ctx, req);
2118
2119 if (io_resubmit_prep(req, err)) {
2120 refcount_inc(&req->refs);
2121 io_queue_async_work(req);
2122 }
2123 }
2124 #endif
2125
2126 static bool io_rw_reissue(struct io_kiocb *req, long res)
2127 {
2128 #ifdef CONFIG_BLOCK
2129 struct task_struct *tsk;
2130 int ret;
2131
2132 if ((res != -EAGAIN && res != -EOPNOTSUPP) || io_wq_current_is_worker())
2133 return false;
2134
2135 tsk = req->task;
2136 init_task_work(&req->task_work, io_rw_resubmit);
2137 ret = task_work_add(tsk, &req->task_work, true);
2138 if (!ret)
2139 return true;
2140 #endif
2141 return false;
2142 }
2143
2144 static void io_complete_rw(struct kiocb *kiocb, long res, long res2)
2145 {
2146 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2147
2148 if (!io_rw_reissue(req, res)) {
2149 io_complete_rw_common(kiocb, res);
2150 io_put_req(req);
2151 }
2152 }
2153
2154 static void io_complete_rw_iopoll(struct kiocb *kiocb, long res, long res2)
2155 {
2156 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2157
2158 if (kiocb->ki_flags & IOCB_WRITE)
2159 kiocb_end_write(req);
2160
2161 if (res != -EAGAIN && res != req->result)
2162 req_set_fail_links(req);
2163
2164 WRITE_ONCE(req->result, res);
2165 /* order with io_poll_complete() checking ->result */
2166 if (res != -EAGAIN) {
2167 smp_wmb();
2168 WRITE_ONCE(req->iopoll_completed, 1);
2169 }
2170 }
2171
2172 /*
2173 * After the iocb has been issued, it's safe to be found on the poll list.
2174 * Adding the kiocb to the list AFTER submission ensures that we don't
2175 * find it from a io_iopoll_getevents() thread before the issuer is done
2176 * accessing the kiocb cookie.
2177 */
2178 static void io_iopoll_req_issued(struct io_kiocb *req)
2179 {
2180 struct io_ring_ctx *ctx = req->ctx;
2181
2182 /*
2183 * Track whether we have multiple files in our lists. This will impact
2184 * how we do polling eventually, not spinning if we're on potentially
2185 * different devices.
2186 */
2187 if (list_empty(&ctx->poll_list)) {
2188 ctx->poll_multi_file = false;
2189 } else if (!ctx->poll_multi_file) {
2190 struct io_kiocb *list_req;
2191
2192 list_req = list_first_entry(&ctx->poll_list, struct io_kiocb,
2193 list);
2194 if (list_req->file != req->file)
2195 ctx->poll_multi_file = true;
2196 }
2197
2198 /*
2199 * For fast devices, IO may have already completed. If it has, add
2200 * it to the front so we find it first.
2201 */
2202 if (READ_ONCE(req->iopoll_completed))
2203 list_add(&req->list, &ctx->poll_list);
2204 else
2205 list_add_tail(&req->list, &ctx->poll_list);
2206
2207 if ((ctx->flags & IORING_SETUP_SQPOLL) &&
2208 wq_has_sleeper(&ctx->sqo_wait))
2209 wake_up(&ctx->sqo_wait);
2210 }
2211
2212 static void __io_state_file_put(struct io_submit_state *state)
2213 {
2214 int diff = state->has_refs - state->used_refs;
2215
2216 if (diff)
2217 fput_many(state->file, diff);
2218 state->file = NULL;
2219 }
2220
2221 static inline void io_state_file_put(struct io_submit_state *state)
2222 {
2223 if (state->file)
2224 __io_state_file_put(state);
2225 }
2226
2227 /*
2228 * Get as many references to a file as we have IOs left in this submission,
2229 * assuming most submissions are for one file, or at least that each file
2230 * has more than one submission.
2231 */
2232 static struct file *__io_file_get(struct io_submit_state *state, int fd)
2233 {
2234 if (!state)
2235 return fget(fd);
2236
2237 if (state->file) {
2238 if (state->fd == fd) {
2239 state->used_refs++;
2240 state->ios_left--;
2241 return state->file;
2242 }
2243 __io_state_file_put(state);
2244 }
2245 state->file = fget_many(fd, state->ios_left);
2246 if (!state->file)
2247 return NULL;
2248
2249 state->fd = fd;
2250 state->has_refs = state->ios_left;
2251 state->used_refs = 1;
2252 state->ios_left--;
2253 return state->file;
2254 }
2255
2256 static bool io_bdev_nowait(struct block_device *bdev)
2257 {
2258 #ifdef CONFIG_BLOCK
2259 return !bdev || queue_is_mq(bdev_get_queue(bdev));
2260 #else
2261 return true;
2262 #endif
2263 }
2264
2265 /*
2266 * If we tracked the file through the SCM inflight mechanism, we could support
2267 * any file. For now, just ensure that anything potentially problematic is done
2268 * inline.
2269 */
2270 static bool io_file_supports_async(struct file *file, int rw)
2271 {
2272 umode_t mode = file_inode(file)->i_mode;
2273
2274 if (S_ISBLK(mode)) {
2275 if (io_bdev_nowait(file->f_inode->i_bdev))
2276 return true;
2277 return false;
2278 }
2279 if (S_ISCHR(mode) || S_ISSOCK(mode))
2280 return true;
2281 if (S_ISREG(mode)) {
2282 if (io_bdev_nowait(file->f_inode->i_sb->s_bdev) &&
2283 file->f_op != &io_uring_fops)
2284 return true;
2285 return false;
2286 }
2287
2288 /* any ->read/write should understand O_NONBLOCK */
2289 if (file->f_flags & O_NONBLOCK)
2290 return true;
2291
2292 if (!(file->f_mode & FMODE_NOWAIT))
2293 return false;
2294
2295 if (rw == READ)
2296 return file->f_op->read_iter != NULL;
2297
2298 return file->f_op->write_iter != NULL;
2299 }
2300
2301 static int io_prep_rw(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2302 bool force_nonblock)
2303 {
2304 struct io_ring_ctx *ctx = req->ctx;
2305 struct kiocb *kiocb = &req->rw.kiocb;
2306 unsigned ioprio;
2307 int ret;
2308
2309 if (S_ISREG(file_inode(req->file)->i_mode))
2310 req->flags |= REQ_F_ISREG;
2311
2312 kiocb->ki_pos = READ_ONCE(sqe->off);
2313 if (kiocb->ki_pos == -1 && !(req->file->f_mode & FMODE_STREAM)) {
2314 req->flags |= REQ_F_CUR_POS;
2315 kiocb->ki_pos = req->file->f_pos;
2316 }
2317 kiocb->ki_hint = ki_hint_validate(file_write_hint(kiocb->ki_filp));
2318 kiocb->ki_flags = iocb_flags(kiocb->ki_filp);
2319 ret = kiocb_set_rw_flags(kiocb, READ_ONCE(sqe->rw_flags));
2320 if (unlikely(ret))
2321 return ret;
2322
2323 ioprio = READ_ONCE(sqe->ioprio);
2324 if (ioprio) {
2325 ret = ioprio_check_cap(ioprio);
2326 if (ret)
2327 return ret;
2328
2329 kiocb->ki_ioprio = ioprio;
2330 } else
2331 kiocb->ki_ioprio = get_current_ioprio();
2332
2333 /* don't allow async punt if RWF_NOWAIT was requested */
2334 if (kiocb->ki_flags & IOCB_NOWAIT)
2335 req->flags |= REQ_F_NOWAIT;
2336
2337 if (kiocb->ki_flags & IOCB_DIRECT)
2338 io_get_req_task(req);
2339
2340 if (force_nonblock)
2341 kiocb->ki_flags |= IOCB_NOWAIT;
2342
2343 if (ctx->flags & IORING_SETUP_IOPOLL) {
2344 if (!(kiocb->ki_flags & IOCB_DIRECT) ||
2345 !kiocb->ki_filp->f_op->iopoll)
2346 return -EOPNOTSUPP;
2347
2348 kiocb->ki_flags |= IOCB_HIPRI;
2349 kiocb->ki_complete = io_complete_rw_iopoll;
2350 req->result = 0;
2351 req->iopoll_completed = 0;
2352 } else {
2353 if (kiocb->ki_flags & IOCB_HIPRI)
2354 return -EINVAL;
2355 kiocb->ki_complete = io_complete_rw;
2356 }
2357
2358 req->rw.addr = READ_ONCE(sqe->addr);
2359 req->rw.len = READ_ONCE(sqe->len);
2360 req->buf_index = READ_ONCE(sqe->buf_index);
2361 return 0;
2362 }
2363
2364 static inline void io_rw_done(struct kiocb *kiocb, ssize_t ret)
2365 {
2366 switch (ret) {
2367 case -EIOCBQUEUED:
2368 break;
2369 case -ERESTARTSYS:
2370 case -ERESTARTNOINTR:
2371 case -ERESTARTNOHAND:
2372 case -ERESTART_RESTARTBLOCK:
2373 /*
2374 * We can't just restart the syscall, since previously
2375 * submitted sqes may already be in progress. Just fail this
2376 * IO with EINTR.
2377 */
2378 ret = -EINTR;
2379 /* fall through */
2380 default:
2381 kiocb->ki_complete(kiocb, ret, 0);
2382 }
2383 }
2384
2385 static void kiocb_done(struct kiocb *kiocb, ssize_t ret)
2386 {
2387 struct io_kiocb *req = container_of(kiocb, struct io_kiocb, rw.kiocb);
2388
2389 if (req->flags & REQ_F_CUR_POS)
2390 req->file->f_pos = kiocb->ki_pos;
2391 if (ret >= 0 && kiocb->ki_complete == io_complete_rw)
2392 io_complete_rw(kiocb, ret, 0);
2393 else
2394 io_rw_done(kiocb, ret);
2395 }
2396
2397 static ssize_t io_import_fixed(struct io_kiocb *req, int rw,
2398 struct iov_iter *iter)
2399 {
2400 struct io_ring_ctx *ctx = req->ctx;
2401 size_t len = req->rw.len;
2402 struct io_mapped_ubuf *imu;
2403 u16 index, buf_index;
2404 size_t offset;
2405 u64 buf_addr;
2406
2407 /* attempt to use fixed buffers without having provided iovecs */
2408 if (unlikely(!ctx->user_bufs))
2409 return -EFAULT;
2410
2411 buf_index = req->buf_index;
2412 if (unlikely(buf_index >= ctx->nr_user_bufs))
2413 return -EFAULT;
2414
2415 index = array_index_nospec(buf_index, ctx->nr_user_bufs);
2416 imu = &ctx->user_bufs[index];
2417 buf_addr = req->rw.addr;
2418
2419 /* overflow */
2420 if (buf_addr + len < buf_addr)
2421 return -EFAULT;
2422 /* not inside the mapped region */
2423 if (buf_addr < imu->ubuf || buf_addr + len > imu->ubuf + imu->len)
2424 return -EFAULT;
2425
2426 /*
2427 * May not be a start of buffer, set size appropriately
2428 * and advance us to the beginning.
2429 */
2430 offset = buf_addr - imu->ubuf;
2431 iov_iter_bvec(iter, rw, imu->bvec, imu->nr_bvecs, offset + len);
2432
2433 if (offset) {
2434 /*
2435 * Don't use iov_iter_advance() here, as it's really slow for
2436 * using the latter parts of a big fixed buffer - it iterates
2437 * over each segment manually. We can cheat a bit here, because
2438 * we know that:
2439 *
2440 * 1) it's a BVEC iter, we set it up
2441 * 2) all bvecs are PAGE_SIZE in size, except potentially the
2442 * first and last bvec
2443 *
2444 * So just find our index, and adjust the iterator afterwards.
2445 * If the offset is within the first bvec (or the whole first
2446 * bvec, just use iov_iter_advance(). This makes it easier
2447 * since we can just skip the first segment, which may not
2448 * be PAGE_SIZE aligned.
2449 */
2450 const struct bio_vec *bvec = imu->bvec;
2451
2452 if (offset <= bvec->bv_len) {
2453 iov_iter_advance(iter, offset);
2454 } else {
2455 unsigned long seg_skip;
2456
2457 /* skip first vec */
2458 offset -= bvec->bv_len;
2459 seg_skip = 1 + (offset >> PAGE_SHIFT);
2460
2461 iter->bvec = bvec + seg_skip;
2462 iter->nr_segs -= seg_skip;
2463 iter->count -= bvec->bv_len + offset;
2464 iter->iov_offset = offset & ~PAGE_MASK;
2465 }
2466 }
2467
2468 return len;
2469 }
2470
2471 static void io_ring_submit_unlock(struct io_ring_ctx *ctx, bool needs_lock)
2472 {
2473 if (needs_lock)
2474 mutex_unlock(&ctx->uring_lock);
2475 }
2476
2477 static void io_ring_submit_lock(struct io_ring_ctx *ctx, bool needs_lock)
2478 {
2479 /*
2480 * "Normal" inline submissions always hold the uring_lock, since we
2481 * grab it from the system call. Same is true for the SQPOLL offload.
2482 * The only exception is when we've detached the request and issue it
2483 * from an async worker thread, grab the lock for that case.
2484 */
2485 if (needs_lock)
2486 mutex_lock(&ctx->uring_lock);
2487 }
2488
2489 static struct io_buffer *io_buffer_select(struct io_kiocb *req, size_t *len,
2490 int bgid, struct io_buffer *kbuf,
2491 bool needs_lock)
2492 {
2493 struct io_buffer *head;
2494
2495 if (req->flags & REQ_F_BUFFER_SELECTED)
2496 return kbuf;
2497
2498 io_ring_submit_lock(req->ctx, needs_lock);
2499
2500 lockdep_assert_held(&req->ctx->uring_lock);
2501
2502 head = idr_find(&req->ctx->io_buffer_idr, bgid);
2503 if (head) {
2504 if (!list_empty(&head->list)) {
2505 kbuf = list_last_entry(&head->list, struct io_buffer,
2506 list);
2507 list_del(&kbuf->list);
2508 } else {
2509 kbuf = head;
2510 idr_remove(&req->ctx->io_buffer_idr, bgid);
2511 }
2512 if (*len > kbuf->len)
2513 *len = kbuf->len;
2514 } else {
2515 kbuf = ERR_PTR(-ENOBUFS);
2516 }
2517
2518 io_ring_submit_unlock(req->ctx, needs_lock);
2519
2520 return kbuf;
2521 }
2522
2523 static void __user *io_rw_buffer_select(struct io_kiocb *req, size_t *len,
2524 bool needs_lock)
2525 {
2526 struct io_buffer *kbuf;
2527 u16 bgid;
2528
2529 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2530 bgid = req->buf_index;
2531 kbuf = io_buffer_select(req, len, bgid, kbuf, needs_lock);
2532 if (IS_ERR(kbuf))
2533 return kbuf;
2534 req->rw.addr = (u64) (unsigned long) kbuf;
2535 req->flags |= REQ_F_BUFFER_SELECTED;
2536 return u64_to_user_ptr(kbuf->addr);
2537 }
2538
2539 #ifdef CONFIG_COMPAT
2540 static ssize_t io_compat_import(struct io_kiocb *req, struct iovec *iov,
2541 bool needs_lock)
2542 {
2543 struct compat_iovec __user *uiov;
2544 compat_ssize_t clen;
2545 void __user *buf;
2546 ssize_t len;
2547
2548 uiov = u64_to_user_ptr(req->rw.addr);
2549 if (!access_ok(uiov, sizeof(*uiov)))
2550 return -EFAULT;
2551 if (__get_user(clen, &uiov->iov_len))
2552 return -EFAULT;
2553 if (clen < 0)
2554 return -EINVAL;
2555
2556 len = clen;
2557 buf = io_rw_buffer_select(req, &len, needs_lock);
2558 if (IS_ERR(buf))
2559 return PTR_ERR(buf);
2560 iov[0].iov_base = buf;
2561 iov[0].iov_len = (compat_size_t) len;
2562 return 0;
2563 }
2564 #endif
2565
2566 static ssize_t __io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2567 bool needs_lock)
2568 {
2569 struct iovec __user *uiov = u64_to_user_ptr(req->rw.addr);
2570 void __user *buf;
2571 ssize_t len;
2572
2573 if (copy_from_user(iov, uiov, sizeof(*uiov)))
2574 return -EFAULT;
2575
2576 len = iov[0].iov_len;
2577 if (len < 0)
2578 return -EINVAL;
2579 buf = io_rw_buffer_select(req, &len, needs_lock);
2580 if (IS_ERR(buf))
2581 return PTR_ERR(buf);
2582 iov[0].iov_base = buf;
2583 iov[0].iov_len = len;
2584 return 0;
2585 }
2586
2587 static ssize_t io_iov_buffer_select(struct io_kiocb *req, struct iovec *iov,
2588 bool needs_lock)
2589 {
2590 if (req->flags & REQ_F_BUFFER_SELECTED) {
2591 struct io_buffer *kbuf;
2592
2593 kbuf = (struct io_buffer *) (unsigned long) req->rw.addr;
2594 iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
2595 iov[0].iov_len = kbuf->len;
2596 return 0;
2597 }
2598 if (!req->rw.len)
2599 return 0;
2600 else if (req->rw.len > 1)
2601 return -EINVAL;
2602
2603 #ifdef CONFIG_COMPAT
2604 if (req->ctx->compat)
2605 return io_compat_import(req, iov, needs_lock);
2606 #endif
2607
2608 return __io_iov_buffer_select(req, iov, needs_lock);
2609 }
2610
2611 static ssize_t io_import_iovec(int rw, struct io_kiocb *req,
2612 struct iovec **iovec, struct iov_iter *iter,
2613 bool needs_lock)
2614 {
2615 void __user *buf = u64_to_user_ptr(req->rw.addr);
2616 size_t sqe_len = req->rw.len;
2617 ssize_t ret;
2618 u8 opcode;
2619
2620 opcode = req->opcode;
2621 if (opcode == IORING_OP_READ_FIXED || opcode == IORING_OP_WRITE_FIXED) {
2622 *iovec = NULL;
2623 return io_import_fixed(req, rw, iter);
2624 }
2625
2626 /* buffer index only valid with fixed read/write, or buffer select */
2627 if (req->buf_index && !(req->flags & REQ_F_BUFFER_SELECT))
2628 return -EINVAL;
2629
2630 if (opcode == IORING_OP_READ || opcode == IORING_OP_WRITE) {
2631 if (req->flags & REQ_F_BUFFER_SELECT) {
2632 buf = io_rw_buffer_select(req, &sqe_len, needs_lock);
2633 if (IS_ERR(buf)) {
2634 *iovec = NULL;
2635 return PTR_ERR(buf);
2636 }
2637 req->rw.len = sqe_len;
2638 }
2639
2640 ret = import_single_range(rw, buf, sqe_len, *iovec, iter);
2641 *iovec = NULL;
2642 return ret < 0 ? ret : sqe_len;
2643 }
2644
2645 if (req->io) {
2646 struct io_async_rw *iorw = &req->io->rw;
2647
2648 *iovec = iorw->iov;
2649 iov_iter_init(iter, rw, *iovec, iorw->nr_segs, iorw->size);
2650 if (iorw->iov == iorw->fast_iov)
2651 *iovec = NULL;
2652 return iorw->size;
2653 }
2654
2655 if (req->flags & REQ_F_BUFFER_SELECT) {
2656 ret = io_iov_buffer_select(req, *iovec, needs_lock);
2657 if (!ret) {
2658 ret = (*iovec)->iov_len;
2659 iov_iter_init(iter, rw, *iovec, 1, ret);
2660 }
2661 *iovec = NULL;
2662 return ret;
2663 }
2664
2665 #ifdef CONFIG_COMPAT
2666 if (req->ctx->compat)
2667 return compat_import_iovec(rw, buf, sqe_len, UIO_FASTIOV,
2668 iovec, iter);
2669 #endif
2670
2671 return import_iovec(rw, buf, sqe_len, UIO_FASTIOV, iovec, iter);
2672 }
2673
2674 /*
2675 * For files that don't have ->read_iter() and ->write_iter(), handle them
2676 * by looping over ->read() or ->write() manually.
2677 */
2678 static ssize_t loop_rw_iter(int rw, struct file *file, struct kiocb *kiocb,
2679 struct iov_iter *iter)
2680 {
2681 ssize_t ret = 0;
2682
2683 /*
2684 * Don't support polled IO through this interface, and we can't
2685 * support non-blocking either. For the latter, this just causes
2686 * the kiocb to be handled from an async context.
2687 */
2688 if (kiocb->ki_flags & IOCB_HIPRI)
2689 return -EOPNOTSUPP;
2690 if (kiocb->ki_flags & IOCB_NOWAIT)
2691 return -EAGAIN;
2692
2693 while (iov_iter_count(iter)) {
2694 struct iovec iovec;
2695 ssize_t nr;
2696
2697 if (!iov_iter_is_bvec(iter)) {
2698 iovec = iov_iter_iovec(iter);
2699 } else {
2700 /* fixed buffers import bvec */
2701 iovec.iov_base = kmap(iter->bvec->bv_page)
2702 + iter->iov_offset;
2703 iovec.iov_len = min(iter->count,
2704 iter->bvec->bv_len - iter->iov_offset);
2705 }
2706
2707 if (rw == READ) {
2708 nr = file->f_op->read(file, iovec.iov_base,
2709 iovec.iov_len, &kiocb->ki_pos);
2710 } else {
2711 nr = file->f_op->write(file, iovec.iov_base,
2712 iovec.iov_len, &kiocb->ki_pos);
2713 }
2714
2715 if (iov_iter_is_bvec(iter))
2716 kunmap(iter->bvec->bv_page);
2717
2718 if (nr < 0) {
2719 if (!ret)
2720 ret = nr;
2721 break;
2722 }
2723 ret += nr;
2724 if (nr != iovec.iov_len)
2725 break;
2726 iov_iter_advance(iter, nr);
2727 }
2728
2729 return ret;
2730 }
2731
2732 static void io_req_map_rw(struct io_kiocb *req, ssize_t io_size,
2733 struct iovec *iovec, struct iovec *fast_iov,
2734 struct iov_iter *iter)
2735 {
2736 req->io->rw.nr_segs = iter->nr_segs;
2737 req->io->rw.size = io_size;
2738 req->io->rw.iov = iovec;
2739 if (!req->io->rw.iov) {
2740 req->io->rw.iov = req->io->rw.fast_iov;
2741 if (req->io->rw.iov != fast_iov)
2742 memcpy(req->io->rw.iov, fast_iov,
2743 sizeof(struct iovec) * iter->nr_segs);
2744 } else {
2745 req->flags |= REQ_F_NEED_CLEANUP;
2746 }
2747 }
2748
2749 static inline int __io_alloc_async_ctx(struct io_kiocb *req)
2750 {
2751 req->io = kmalloc(sizeof(*req->io), GFP_KERNEL);
2752 return req->io == NULL;
2753 }
2754
2755 static int io_alloc_async_ctx(struct io_kiocb *req)
2756 {
2757 if (!io_op_defs[req->opcode].async_ctx)
2758 return 0;
2759
2760 return __io_alloc_async_ctx(req);
2761 }
2762
2763 static int io_setup_async_rw(struct io_kiocb *req, ssize_t io_size,
2764 struct iovec *iovec, struct iovec *fast_iov,
2765 struct iov_iter *iter)
2766 {
2767 if (!io_op_defs[req->opcode].async_ctx)
2768 return 0;
2769 if (!req->io) {
2770 if (__io_alloc_async_ctx(req))
2771 return -ENOMEM;
2772
2773 io_req_map_rw(req, io_size, iovec, fast_iov, iter);
2774 }
2775 return 0;
2776 }
2777
2778 static int io_read_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2779 bool force_nonblock)
2780 {
2781 struct io_async_ctx *io;
2782 struct iov_iter iter;
2783 ssize_t ret;
2784
2785 ret = io_prep_rw(req, sqe, force_nonblock);
2786 if (ret)
2787 return ret;
2788
2789 if (unlikely(!(req->file->f_mode & FMODE_READ)))
2790 return -EBADF;
2791
2792 /* either don't need iovec imported or already have it */
2793 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
2794 return 0;
2795
2796 io = req->io;
2797 io->rw.iov = io->rw.fast_iov;
2798 req->io = NULL;
2799 ret = io_import_iovec(READ, req, &io->rw.iov, &iter, !force_nonblock);
2800 req->io = io;
2801 if (ret < 0)
2802 return ret;
2803
2804 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
2805 return 0;
2806 }
2807
2808 static void __io_async_buf_error(struct io_kiocb *req, int error)
2809 {
2810 struct io_ring_ctx *ctx = req->ctx;
2811
2812 spin_lock_irq(&ctx->completion_lock);
2813 io_cqring_fill_event(req, error);
2814 io_commit_cqring(ctx);
2815 spin_unlock_irq(&ctx->completion_lock);
2816
2817 io_cqring_ev_posted(ctx);
2818 req_set_fail_links(req);
2819 io_double_put_req(req);
2820 }
2821
2822 static void io_async_buf_cancel(struct callback_head *cb)
2823 {
2824 struct io_async_rw *rw;
2825 struct io_kiocb *req;
2826
2827 rw = container_of(cb, struct io_async_rw, task_work);
2828 req = rw->wpq.wait.private;
2829 __io_async_buf_error(req, -ECANCELED);
2830 }
2831
2832 static void io_async_buf_retry(struct callback_head *cb)
2833 {
2834 struct io_async_rw *rw;
2835 struct io_ring_ctx *ctx;
2836 struct io_kiocb *req;
2837
2838 rw = container_of(cb, struct io_async_rw, task_work);
2839 req = rw->wpq.wait.private;
2840 ctx = req->ctx;
2841
2842 __set_current_state(TASK_RUNNING);
2843 if (!__io_sq_thread_acquire_mm(ctx)) {
2844 mutex_lock(&ctx->uring_lock);
2845 __io_queue_sqe(req, NULL, NULL);
2846 mutex_unlock(&ctx->uring_lock);
2847 } else {
2848 __io_async_buf_error(req, -EFAULT);
2849 }
2850 }
2851
2852 static int io_async_buf_func(struct wait_queue_entry *wait, unsigned mode,
2853 int sync, void *arg)
2854 {
2855 struct wait_page_queue *wpq;
2856 struct io_kiocb *req = wait->private;
2857 struct io_async_rw *rw = &req->io->rw;
2858 struct wait_page_key *key = arg;
2859 struct task_struct *tsk;
2860 int ret;
2861
2862 wpq = container_of(wait, struct wait_page_queue, wait);
2863
2864 ret = wake_page_match(wpq, key);
2865 if (ret != 1)
2866 return ret;
2867
2868 list_del_init(&wait->entry);
2869
2870 init_task_work(&rw->task_work, io_async_buf_retry);
2871 /* submit ref gets dropped, acquire a new one */
2872 refcount_inc(&req->refs);
2873 tsk = req->task;
2874 ret = task_work_add(tsk, &rw->task_work, true);
2875 if (unlikely(ret)) {
2876 /* queue just for cancelation */
2877 init_task_work(&rw->task_work, io_async_buf_cancel);
2878 tsk = io_wq_get_task(req->ctx->io_wq);
2879 task_work_add(tsk, &rw->task_work, true);
2880 }
2881 wake_up_process(tsk);
2882 return 1;
2883 }
2884
2885 static bool io_rw_should_retry(struct io_kiocb *req)
2886 {
2887 struct kiocb *kiocb = &req->rw.kiocb;
2888 int ret;
2889
2890 /* never retry for NOWAIT, we just complete with -EAGAIN */
2891 if (req->flags & REQ_F_NOWAIT)
2892 return false;
2893
2894 /* already tried, or we're doing O_DIRECT */
2895 if (kiocb->ki_flags & (IOCB_DIRECT | IOCB_WAITQ))
2896 return false;
2897 /*
2898 * just use poll if we can, and don't attempt if the fs doesn't
2899 * support callback based unlocks
2900 */
2901 if (file_can_poll(req->file) || !(req->file->f_mode & FMODE_BUF_RASYNC))
2902 return false;
2903
2904 /*
2905 * If request type doesn't require req->io to defer in general,
2906 * we need to allocate it here
2907 */
2908 if (!req->io && __io_alloc_async_ctx(req))
2909 return false;
2910
2911 ret = kiocb_wait_page_queue_init(kiocb, &req->io->rw.wpq,
2912 io_async_buf_func, req);
2913 if (!ret) {
2914 io_get_req_task(req);
2915 return true;
2916 }
2917
2918 return false;
2919 }
2920
2921 static int io_iter_do_read(struct io_kiocb *req, struct iov_iter *iter)
2922 {
2923 if (req->file->f_op->read_iter)
2924 return call_read_iter(req->file, &req->rw.kiocb, iter);
2925 return loop_rw_iter(READ, req->file, &req->rw.kiocb, iter);
2926 }
2927
2928 static int io_read(struct io_kiocb *req, bool force_nonblock)
2929 {
2930 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
2931 struct kiocb *kiocb = &req->rw.kiocb;
2932 struct iov_iter iter;
2933 size_t iov_count;
2934 ssize_t io_size, ret;
2935
2936 ret = io_import_iovec(READ, req, &iovec, &iter, !force_nonblock);
2937 if (ret < 0)
2938 return ret;
2939
2940 /* Ensure we clear previously set non-block flag */
2941 if (!force_nonblock)
2942 kiocb->ki_flags &= ~IOCB_NOWAIT;
2943
2944 req->result = 0;
2945 io_size = ret;
2946 if (req->flags & REQ_F_LINK_HEAD)
2947 req->result = io_size;
2948
2949 /* If the file doesn't support async, just async punt */
2950 if (force_nonblock && !io_file_supports_async(req->file, READ))
2951 goto copy_iov;
2952
2953 iov_count = iov_iter_count(&iter);
2954 ret = rw_verify_area(READ, req->file, &kiocb->ki_pos, iov_count);
2955 if (!ret) {
2956 unsigned long nr_segs = iter.nr_segs;
2957 ssize_t ret2 = 0;
2958
2959 ret2 = io_iter_do_read(req, &iter);
2960
2961 /* Catch -EAGAIN return for forced non-blocking submission */
2962 if (!force_nonblock || (ret2 != -EAGAIN && ret2 != -EIO)) {
2963 kiocb_done(kiocb, ret2);
2964 } else {
2965 iter.count = iov_count;
2966 iter.nr_segs = nr_segs;
2967 copy_iov:
2968 ret = io_setup_async_rw(req, io_size, iovec,
2969 inline_vecs, &iter);
2970 if (ret)
2971 goto out_free;
2972 /* if we can retry, do so with the callbacks armed */
2973 if (io_rw_should_retry(req)) {
2974 ret2 = io_iter_do_read(req, &iter);
2975 if (ret2 == -EIOCBQUEUED) {
2976 goto out_free;
2977 } else if (ret2 != -EAGAIN) {
2978 kiocb_done(kiocb, ret2);
2979 goto out_free;
2980 }
2981 }
2982 kiocb->ki_flags &= ~IOCB_WAITQ;
2983 return -EAGAIN;
2984 }
2985 }
2986 out_free:
2987 if (!(req->flags & REQ_F_NEED_CLEANUP))
2988 kfree(iovec);
2989 return ret;
2990 }
2991
2992 static int io_write_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
2993 bool force_nonblock)
2994 {
2995 struct io_async_ctx *io;
2996 struct iov_iter iter;
2997 ssize_t ret;
2998
2999 ret = io_prep_rw(req, sqe, force_nonblock);
3000 if (ret)
3001 return ret;
3002
3003 if (unlikely(!(req->file->f_mode & FMODE_WRITE)))
3004 return -EBADF;
3005
3006 req->fsize = rlimit(RLIMIT_FSIZE);
3007
3008 /* either don't need iovec imported or already have it */
3009 if (!req->io || req->flags & REQ_F_NEED_CLEANUP)
3010 return 0;
3011
3012 io = req->io;
3013 io->rw.iov = io->rw.fast_iov;
3014 req->io = NULL;
3015 ret = io_import_iovec(WRITE, req, &io->rw.iov, &iter, !force_nonblock);
3016 req->io = io;
3017 if (ret < 0)
3018 return ret;
3019
3020 io_req_map_rw(req, ret, io->rw.iov, io->rw.fast_iov, &iter);
3021 return 0;
3022 }
3023
3024 static int io_write(struct io_kiocb *req, bool force_nonblock)
3025 {
3026 struct iovec inline_vecs[UIO_FASTIOV], *iovec = inline_vecs;
3027 struct kiocb *kiocb = &req->rw.kiocb;
3028 struct iov_iter iter;
3029 size_t iov_count;
3030 ssize_t ret, io_size;
3031
3032 ret = io_import_iovec(WRITE, req, &iovec, &iter, !force_nonblock);
3033 if (ret < 0)
3034 return ret;
3035
3036 /* Ensure we clear previously set non-block flag */
3037 if (!force_nonblock)
3038 req->rw.kiocb.ki_flags &= ~IOCB_NOWAIT;
3039
3040 req->result = 0;
3041 io_size = ret;
3042 if (req->flags & REQ_F_LINK_HEAD)
3043 req->result = io_size;
3044
3045 /* If the file doesn't support async, just async punt */
3046 if (force_nonblock && !io_file_supports_async(req->file, WRITE))
3047 goto copy_iov;
3048
3049 /* file path doesn't support NOWAIT for non-direct_IO */
3050 if (force_nonblock && !(kiocb->ki_flags & IOCB_DIRECT) &&
3051 (req->flags & REQ_F_ISREG))
3052 goto copy_iov;
3053
3054 iov_count = iov_iter_count(&iter);
3055 ret = rw_verify_area(WRITE, req->file, &kiocb->ki_pos, iov_count);
3056 if (!ret) {
3057 unsigned long nr_segs = iter.nr_segs;
3058 ssize_t ret2;
3059
3060 /*
3061 * Open-code file_start_write here to grab freeze protection,
3062 * which will be released by another thread in
3063 * io_complete_rw(). Fool lockdep by telling it the lock got
3064 * released so that it doesn't complain about the held lock when
3065 * we return to userspace.
3066 */
3067 if (req->flags & REQ_F_ISREG) {
3068 __sb_start_write(file_inode(req->file)->i_sb,
3069 SB_FREEZE_WRITE, true);
3070 __sb_writers_release(file_inode(req->file)->i_sb,
3071 SB_FREEZE_WRITE);
3072 }
3073 kiocb->ki_flags |= IOCB_WRITE;
3074
3075 if (!force_nonblock)
3076 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
3077
3078 if (req->file->f_op->write_iter)
3079 ret2 = call_write_iter(req->file, kiocb, &iter);
3080 else
3081 ret2 = loop_rw_iter(WRITE, req->file, kiocb, &iter);
3082
3083 if (!force_nonblock)
3084 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
3085
3086 /*
3087 * Raw bdev writes will return -EOPNOTSUPP for IOCB_NOWAIT. Just
3088 * retry them without IOCB_NOWAIT.
3089 */
3090 if (ret2 == -EOPNOTSUPP && (kiocb->ki_flags & IOCB_NOWAIT))
3091 ret2 = -EAGAIN;
3092 if (!force_nonblock || ret2 != -EAGAIN) {
3093 kiocb_done(kiocb, ret2);
3094 } else {
3095 iter.count = iov_count;
3096 iter.nr_segs = nr_segs;
3097 copy_iov:
3098 ret = io_setup_async_rw(req, io_size, iovec,
3099 inline_vecs, &iter);
3100 if (ret)
3101 goto out_free;
3102 return -EAGAIN;
3103 }
3104 }
3105 out_free:
3106 if (!(req->flags & REQ_F_NEED_CLEANUP))
3107 kfree(iovec);
3108 return ret;
3109 }
3110
3111 static int __io_splice_prep(struct io_kiocb *req,
3112 const struct io_uring_sqe *sqe)
3113 {
3114 struct io_splice* sp = &req->splice;
3115 unsigned int valid_flags = SPLICE_F_FD_IN_FIXED | SPLICE_F_ALL;
3116 int ret;
3117
3118 if (req->flags & REQ_F_NEED_CLEANUP)
3119 return 0;
3120 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3121 return -EINVAL;
3122
3123 sp->file_in = NULL;
3124 sp->len = READ_ONCE(sqe->len);
3125 sp->flags = READ_ONCE(sqe->splice_flags);
3126
3127 if (unlikely(sp->flags & ~valid_flags))
3128 return -EINVAL;
3129
3130 ret = io_file_get(NULL, req, READ_ONCE(sqe->splice_fd_in), &sp->file_in,
3131 (sp->flags & SPLICE_F_FD_IN_FIXED));
3132 if (ret)
3133 return ret;
3134 req->flags |= REQ_F_NEED_CLEANUP;
3135
3136 if (!S_ISREG(file_inode(sp->file_in)->i_mode)) {
3137 /*
3138 * Splice operation will be punted aync, and here need to
3139 * modify io_wq_work.flags, so initialize io_wq_work firstly.
3140 */
3141 io_req_init_async(req);
3142 req->work.flags |= IO_WQ_WORK_UNBOUND;
3143 }
3144
3145 return 0;
3146 }
3147
3148 static int io_tee_prep(struct io_kiocb *req,
3149 const struct io_uring_sqe *sqe)
3150 {
3151 if (READ_ONCE(sqe->splice_off_in) || READ_ONCE(sqe->off))
3152 return -EINVAL;
3153 return __io_splice_prep(req, sqe);
3154 }
3155
3156 static int io_tee(struct io_kiocb *req, bool force_nonblock)
3157 {
3158 struct io_splice *sp = &req->splice;
3159 struct file *in = sp->file_in;
3160 struct file *out = sp->file_out;
3161 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3162 long ret = 0;
3163
3164 if (force_nonblock)
3165 return -EAGAIN;
3166 if (sp->len)
3167 ret = do_tee(in, out, sp->len, flags);
3168
3169 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3170 req->flags &= ~REQ_F_NEED_CLEANUP;
3171
3172 if (ret != sp->len)
3173 req_set_fail_links(req);
3174 io_req_complete(req, ret);
3175 return 0;
3176 }
3177
3178 static int io_splice_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3179 {
3180 struct io_splice* sp = &req->splice;
3181
3182 sp->off_in = READ_ONCE(sqe->splice_off_in);
3183 sp->off_out = READ_ONCE(sqe->off);
3184 return __io_splice_prep(req, sqe);
3185 }
3186
3187 static int io_splice(struct io_kiocb *req, bool force_nonblock)
3188 {
3189 struct io_splice *sp = &req->splice;
3190 struct file *in = sp->file_in;
3191 struct file *out = sp->file_out;
3192 unsigned int flags = sp->flags & ~SPLICE_F_FD_IN_FIXED;
3193 loff_t *poff_in, *poff_out;
3194 long ret = 0;
3195
3196 if (force_nonblock)
3197 return -EAGAIN;
3198
3199 poff_in = (sp->off_in == -1) ? NULL : &sp->off_in;
3200 poff_out = (sp->off_out == -1) ? NULL : &sp->off_out;
3201
3202 if (sp->len)
3203 ret = do_splice(in, poff_in, out, poff_out, sp->len, flags);
3204
3205 io_put_file(req, in, (sp->flags & SPLICE_F_FD_IN_FIXED));
3206 req->flags &= ~REQ_F_NEED_CLEANUP;
3207
3208 if (ret != sp->len)
3209 req_set_fail_links(req);
3210 io_req_complete(req, ret);
3211 return 0;
3212 }
3213
3214 /*
3215 * IORING_OP_NOP just posts a completion event, nothing else.
3216 */
3217 static int io_nop(struct io_kiocb *req, struct io_comp_state *cs)
3218 {
3219 struct io_ring_ctx *ctx = req->ctx;
3220
3221 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3222 return -EINVAL;
3223
3224 __io_req_complete(req, 0, 0, cs);
3225 return 0;
3226 }
3227
3228 static int io_prep_fsync(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3229 {
3230 struct io_ring_ctx *ctx = req->ctx;
3231
3232 if (!req->file)
3233 return -EBADF;
3234
3235 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3236 return -EINVAL;
3237 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3238 return -EINVAL;
3239
3240 req->sync.flags = READ_ONCE(sqe->fsync_flags);
3241 if (unlikely(req->sync.flags & ~IORING_FSYNC_DATASYNC))
3242 return -EINVAL;
3243
3244 req->sync.off = READ_ONCE(sqe->off);
3245 req->sync.len = READ_ONCE(sqe->len);
3246 return 0;
3247 }
3248
3249 static int io_fsync(struct io_kiocb *req, bool force_nonblock)
3250 {
3251 loff_t end = req->sync.off + req->sync.len;
3252 int ret;
3253
3254 /* fsync always requires a blocking context */
3255 if (force_nonblock)
3256 return -EAGAIN;
3257
3258 ret = vfs_fsync_range(req->file, req->sync.off,
3259 end > 0 ? end : LLONG_MAX,
3260 req->sync.flags & IORING_FSYNC_DATASYNC);
3261 if (ret < 0)
3262 req_set_fail_links(req);
3263 io_req_complete(req, ret);
3264 return 0;
3265 }
3266
3267 static int io_fallocate_prep(struct io_kiocb *req,
3268 const struct io_uring_sqe *sqe)
3269 {
3270 if (sqe->ioprio || sqe->buf_index || sqe->rw_flags)
3271 return -EINVAL;
3272 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3273 return -EINVAL;
3274
3275 req->sync.off = READ_ONCE(sqe->off);
3276 req->sync.len = READ_ONCE(sqe->addr);
3277 req->sync.mode = READ_ONCE(sqe->len);
3278 req->fsize = rlimit(RLIMIT_FSIZE);
3279 return 0;
3280 }
3281
3282 static int io_fallocate(struct io_kiocb *req, bool force_nonblock)
3283 {
3284 int ret;
3285
3286 /* fallocate always requiring blocking context */
3287 if (force_nonblock)
3288 return -EAGAIN;
3289
3290 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = req->fsize;
3291 ret = vfs_fallocate(req->file, req->sync.mode, req->sync.off,
3292 req->sync.len);
3293 current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
3294 if (ret < 0)
3295 req_set_fail_links(req);
3296 io_req_complete(req, ret);
3297 return 0;
3298 }
3299
3300 static int __io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3301 {
3302 const char __user *fname;
3303 int ret;
3304
3305 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3306 return -EINVAL;
3307 if (unlikely(sqe->ioprio || sqe->buf_index))
3308 return -EINVAL;
3309 if (unlikely(req->flags & REQ_F_FIXED_FILE))
3310 return -EBADF;
3311
3312 /* open.how should be already initialised */
3313 if (!(req->open.how.flags & O_PATH) && force_o_largefile())
3314 req->open.how.flags |= O_LARGEFILE;
3315
3316 req->open.dfd = READ_ONCE(sqe->fd);
3317 fname = u64_to_user_ptr(READ_ONCE(sqe->addr));
3318 req->open.filename = getname(fname);
3319 if (IS_ERR(req->open.filename)) {
3320 ret = PTR_ERR(req->open.filename);
3321 req->open.filename = NULL;
3322 return ret;
3323 }
3324 req->open.nofile = rlimit(RLIMIT_NOFILE);
3325 req->flags |= REQ_F_NEED_CLEANUP;
3326 return 0;
3327 }
3328
3329 static int io_openat_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3330 {
3331 u64 flags, mode;
3332
3333 if (req->flags & REQ_F_NEED_CLEANUP)
3334 return 0;
3335 mode = READ_ONCE(sqe->len);
3336 flags = READ_ONCE(sqe->open_flags);
3337 req->open.how = build_open_how(flags, mode);
3338 return __io_openat_prep(req, sqe);
3339 }
3340
3341 static int io_openat2_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3342 {
3343 struct open_how __user *how;
3344 size_t len;
3345 int ret;
3346
3347 if (req->flags & REQ_F_NEED_CLEANUP)
3348 return 0;
3349 how = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3350 len = READ_ONCE(sqe->len);
3351 if (len < OPEN_HOW_SIZE_VER0)
3352 return -EINVAL;
3353
3354 ret = copy_struct_from_user(&req->open.how, sizeof(req->open.how), how,
3355 len);
3356 if (ret)
3357 return ret;
3358
3359 return __io_openat_prep(req, sqe);
3360 }
3361
3362 static int io_openat2(struct io_kiocb *req, bool force_nonblock)
3363 {
3364 struct open_flags op;
3365 struct file *file;
3366 int ret;
3367
3368 if (force_nonblock)
3369 return -EAGAIN;
3370
3371 ret = build_open_flags(&req->open.how, &op);
3372 if (ret)
3373 goto err;
3374
3375 ret = __get_unused_fd_flags(req->open.how.flags, req->open.nofile);
3376 if (ret < 0)
3377 goto err;
3378
3379 file = do_filp_open(req->open.dfd, req->open.filename, &op);
3380 if (IS_ERR(file)) {
3381 put_unused_fd(ret);
3382 ret = PTR_ERR(file);
3383 } else {
3384 fsnotify_open(file);
3385 fd_install(ret, file);
3386 }
3387 err:
3388 putname(req->open.filename);
3389 req->flags &= ~REQ_F_NEED_CLEANUP;
3390 if (ret < 0)
3391 req_set_fail_links(req);
3392 io_req_complete(req, ret);
3393 return 0;
3394 }
3395
3396 static int io_openat(struct io_kiocb *req, bool force_nonblock)
3397 {
3398 return io_openat2(req, force_nonblock);
3399 }
3400
3401 static int io_remove_buffers_prep(struct io_kiocb *req,
3402 const struct io_uring_sqe *sqe)
3403 {
3404 struct io_provide_buf *p = &req->pbuf;
3405 u64 tmp;
3406
3407 if (sqe->ioprio || sqe->rw_flags || sqe->addr || sqe->len || sqe->off)
3408 return -EINVAL;
3409
3410 tmp = READ_ONCE(sqe->fd);
3411 if (!tmp || tmp > USHRT_MAX)
3412 return -EINVAL;
3413
3414 memset(p, 0, sizeof(*p));
3415 p->nbufs = tmp;
3416 p->bgid = READ_ONCE(sqe->buf_group);
3417 return 0;
3418 }
3419
3420 static int __io_remove_buffers(struct io_ring_ctx *ctx, struct io_buffer *buf,
3421 int bgid, unsigned nbufs)
3422 {
3423 unsigned i = 0;
3424
3425 /* shouldn't happen */
3426 if (!nbufs)
3427 return 0;
3428
3429 /* the head kbuf is the list itself */
3430 while (!list_empty(&buf->list)) {
3431 struct io_buffer *nxt;
3432
3433 nxt = list_first_entry(&buf->list, struct io_buffer, list);
3434 list_del(&nxt->list);
3435 kfree(nxt);
3436 if (++i == nbufs)
3437 return i;
3438 }
3439 i++;
3440 kfree(buf);
3441 idr_remove(&ctx->io_buffer_idr, bgid);
3442
3443 return i;
3444 }
3445
3446 static int io_remove_buffers(struct io_kiocb *req, bool force_nonblock,
3447 struct io_comp_state *cs)
3448 {
3449 struct io_provide_buf *p = &req->pbuf;
3450 struct io_ring_ctx *ctx = req->ctx;
3451 struct io_buffer *head;
3452 int ret = 0;
3453
3454 io_ring_submit_lock(ctx, !force_nonblock);
3455
3456 lockdep_assert_held(&ctx->uring_lock);
3457
3458 ret = -ENOENT;
3459 head = idr_find(&ctx->io_buffer_idr, p->bgid);
3460 if (head)
3461 ret = __io_remove_buffers(ctx, head, p->bgid, p->nbufs);
3462
3463 io_ring_submit_lock(ctx, !force_nonblock);
3464 if (ret < 0)
3465 req_set_fail_links(req);
3466 __io_req_complete(req, ret, 0, cs);
3467 return 0;
3468 }
3469
3470 static int io_provide_buffers_prep(struct io_kiocb *req,
3471 const struct io_uring_sqe *sqe)
3472 {
3473 struct io_provide_buf *p = &req->pbuf;
3474 u64 tmp;
3475
3476 if (sqe->ioprio || sqe->rw_flags)
3477 return -EINVAL;
3478
3479 tmp = READ_ONCE(sqe->fd);
3480 if (!tmp || tmp > USHRT_MAX)
3481 return -E2BIG;
3482 p->nbufs = tmp;
3483 p->addr = READ_ONCE(sqe->addr);
3484 p->len = READ_ONCE(sqe->len);
3485
3486 if (!access_ok(u64_to_user_ptr(p->addr), (p->len * p->nbufs)))
3487 return -EFAULT;
3488
3489 p->bgid = READ_ONCE(sqe->buf_group);
3490 tmp = READ_ONCE(sqe->off);
3491 if (tmp > USHRT_MAX)
3492 return -E2BIG;
3493 p->bid = tmp;
3494 return 0;
3495 }
3496
3497 static int io_add_buffers(struct io_provide_buf *pbuf, struct io_buffer **head)
3498 {
3499 struct io_buffer *buf;
3500 u64 addr = pbuf->addr;
3501 int i, bid = pbuf->bid;
3502
3503 for (i = 0; i < pbuf->nbufs; i++) {
3504 buf = kmalloc(sizeof(*buf), GFP_KERNEL);
3505 if (!buf)
3506 break;
3507
3508 buf->addr = addr;
3509 buf->len = pbuf->len;
3510 buf->bid = bid;
3511 addr += pbuf->len;
3512 bid++;
3513 if (!*head) {
3514 INIT_LIST_HEAD(&buf->list);
3515 *head = buf;
3516 } else {
3517 list_add_tail(&buf->list, &(*head)->list);
3518 }
3519 }
3520
3521 return i ? i : -ENOMEM;
3522 }
3523
3524 static int io_provide_buffers(struct io_kiocb *req, bool force_nonblock,
3525 struct io_comp_state *cs)
3526 {
3527 struct io_provide_buf *p = &req->pbuf;
3528 struct io_ring_ctx *ctx = req->ctx;
3529 struct io_buffer *head, *list;
3530 int ret = 0;
3531
3532 io_ring_submit_lock(ctx, !force_nonblock);
3533
3534 lockdep_assert_held(&ctx->uring_lock);
3535
3536 list = head = idr_find(&ctx->io_buffer_idr, p->bgid);
3537
3538 ret = io_add_buffers(p, &head);
3539 if (ret < 0)
3540 goto out;
3541
3542 if (!list) {
3543 ret = idr_alloc(&ctx->io_buffer_idr, head, p->bgid, p->bgid + 1,
3544 GFP_KERNEL);
3545 if (ret < 0) {
3546 __io_remove_buffers(ctx, head, p->bgid, -1U);
3547 goto out;
3548 }
3549 }
3550 out:
3551 io_ring_submit_unlock(ctx, !force_nonblock);
3552 if (ret < 0)
3553 req_set_fail_links(req);
3554 __io_req_complete(req, ret, 0, cs);
3555 return 0;
3556 }
3557
3558 static int io_epoll_ctl_prep(struct io_kiocb *req,
3559 const struct io_uring_sqe *sqe)
3560 {
3561 #if defined(CONFIG_EPOLL)
3562 if (sqe->ioprio || sqe->buf_index)
3563 return -EINVAL;
3564 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3565 return -EINVAL;
3566
3567 req->epoll.epfd = READ_ONCE(sqe->fd);
3568 req->epoll.op = READ_ONCE(sqe->len);
3569 req->epoll.fd = READ_ONCE(sqe->off);
3570
3571 if (ep_op_has_event(req->epoll.op)) {
3572 struct epoll_event __user *ev;
3573
3574 ev = u64_to_user_ptr(READ_ONCE(sqe->addr));
3575 if (copy_from_user(&req->epoll.event, ev, sizeof(*ev)))
3576 return -EFAULT;
3577 }
3578
3579 return 0;
3580 #else
3581 return -EOPNOTSUPP;
3582 #endif
3583 }
3584
3585 static int io_epoll_ctl(struct io_kiocb *req, bool force_nonblock,
3586 struct io_comp_state *cs)
3587 {
3588 #if defined(CONFIG_EPOLL)
3589 struct io_epoll *ie = &req->epoll;
3590 int ret;
3591
3592 ret = do_epoll_ctl(ie->epfd, ie->op, ie->fd, &ie->event, force_nonblock);
3593 if (force_nonblock && ret == -EAGAIN)
3594 return -EAGAIN;
3595
3596 if (ret < 0)
3597 req_set_fail_links(req);
3598 __io_req_complete(req, ret, 0, cs);
3599 return 0;
3600 #else
3601 return -EOPNOTSUPP;
3602 #endif
3603 }
3604
3605 static int io_madvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3606 {
3607 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3608 if (sqe->ioprio || sqe->buf_index || sqe->off)
3609 return -EINVAL;
3610 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3611 return -EINVAL;
3612
3613 req->madvise.addr = READ_ONCE(sqe->addr);
3614 req->madvise.len = READ_ONCE(sqe->len);
3615 req->madvise.advice = READ_ONCE(sqe->fadvise_advice);
3616 return 0;
3617 #else
3618 return -EOPNOTSUPP;
3619 #endif
3620 }
3621
3622 static int io_madvise(struct io_kiocb *req, bool force_nonblock)
3623 {
3624 #if defined(CONFIG_ADVISE_SYSCALLS) && defined(CONFIG_MMU)
3625 struct io_madvise *ma = &req->madvise;
3626 int ret;
3627
3628 if (force_nonblock)
3629 return -EAGAIN;
3630
3631 ret = do_madvise(ma->addr, ma->len, ma->advice);
3632 if (ret < 0)
3633 req_set_fail_links(req);
3634 io_req_complete(req, ret);
3635 return 0;
3636 #else
3637 return -EOPNOTSUPP;
3638 #endif
3639 }
3640
3641 static int io_fadvise_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3642 {
3643 if (sqe->ioprio || sqe->buf_index || sqe->addr)
3644 return -EINVAL;
3645 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3646 return -EINVAL;
3647
3648 req->fadvise.offset = READ_ONCE(sqe->off);
3649 req->fadvise.len = READ_ONCE(sqe->len);
3650 req->fadvise.advice = READ_ONCE(sqe->fadvise_advice);
3651 return 0;
3652 }
3653
3654 static int io_fadvise(struct io_kiocb *req, bool force_nonblock)
3655 {
3656 struct io_fadvise *fa = &req->fadvise;
3657 int ret;
3658
3659 if (force_nonblock) {
3660 switch (fa->advice) {
3661 case POSIX_FADV_NORMAL:
3662 case POSIX_FADV_RANDOM:
3663 case POSIX_FADV_SEQUENTIAL:
3664 break;
3665 default:
3666 return -EAGAIN;
3667 }
3668 }
3669
3670 ret = vfs_fadvise(req->file, fa->offset, fa->len, fa->advice);
3671 if (ret < 0)
3672 req_set_fail_links(req);
3673 io_req_complete(req, ret);
3674 return 0;
3675 }
3676
3677 static int io_statx_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3678 {
3679 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3680 return -EINVAL;
3681 if (sqe->ioprio || sqe->buf_index)
3682 return -EINVAL;
3683 if (req->flags & REQ_F_FIXED_FILE)
3684 return -EBADF;
3685
3686 req->statx.dfd = READ_ONCE(sqe->fd);
3687 req->statx.mask = READ_ONCE(sqe->len);
3688 req->statx.filename = u64_to_user_ptr(READ_ONCE(sqe->addr));
3689 req->statx.buffer = u64_to_user_ptr(READ_ONCE(sqe->addr2));
3690 req->statx.flags = READ_ONCE(sqe->statx_flags);
3691
3692 return 0;
3693 }
3694
3695 static int io_statx(struct io_kiocb *req, bool force_nonblock)
3696 {
3697 struct io_statx *ctx = &req->statx;
3698 int ret;
3699
3700 if (force_nonblock) {
3701 /* only need file table for an actual valid fd */
3702 if (ctx->dfd == -1 || ctx->dfd == AT_FDCWD)
3703 req->flags |= REQ_F_NO_FILE_TABLE;
3704 return -EAGAIN;
3705 }
3706
3707 ret = do_statx(ctx->dfd, ctx->filename, ctx->flags, ctx->mask,
3708 ctx->buffer);
3709
3710 if (ret < 0)
3711 req_set_fail_links(req);
3712 io_req_complete(req, ret);
3713 return 0;
3714 }
3715
3716 static int io_close_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3717 {
3718 /*
3719 * If we queue this for async, it must not be cancellable. That would
3720 * leave the 'file' in an undeterminate state, and here need to modify
3721 * io_wq_work.flags, so initialize io_wq_work firstly.
3722 */
3723 io_req_init_async(req);
3724 req->work.flags |= IO_WQ_WORK_NO_CANCEL;
3725
3726 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
3727 return -EINVAL;
3728 if (sqe->ioprio || sqe->off || sqe->addr || sqe->len ||
3729 sqe->rw_flags || sqe->buf_index)
3730 return -EINVAL;
3731 if (req->flags & REQ_F_FIXED_FILE)
3732 return -EBADF;
3733
3734 req->close.fd = READ_ONCE(sqe->fd);
3735 if ((req->file && req->file->f_op == &io_uring_fops) ||
3736 req->close.fd == req->ctx->ring_fd)
3737 return -EBADF;
3738
3739 req->close.put_file = NULL;
3740 return 0;
3741 }
3742
3743 static int io_close(struct io_kiocb *req, bool force_nonblock,
3744 struct io_comp_state *cs)
3745 {
3746 struct io_close *close = &req->close;
3747 int ret;
3748
3749 /* might be already done during nonblock submission */
3750 if (!close->put_file) {
3751 ret = __close_fd_get_file(close->fd, &close->put_file);
3752 if (ret < 0)
3753 return (ret == -ENOENT) ? -EBADF : ret;
3754 }
3755
3756 /* if the file has a flush method, be safe and punt to async */
3757 if (close->put_file->f_op->flush && force_nonblock) {
3758 /* was never set, but play safe */
3759 req->flags &= ~REQ_F_NOWAIT;
3760 /* avoid grabbing files - we don't need the files */
3761 req->flags |= REQ_F_NO_FILE_TABLE;
3762 return -EAGAIN;
3763 }
3764
3765 /* No ->flush() or already async, safely close from here */
3766 ret = filp_close(close->put_file, req->work.files);
3767 if (ret < 0)
3768 req_set_fail_links(req);
3769 fput(close->put_file);
3770 close->put_file = NULL;
3771 __io_req_complete(req, ret, 0, cs);
3772 return 0;
3773 }
3774
3775 static int io_prep_sfr(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3776 {
3777 struct io_ring_ctx *ctx = req->ctx;
3778
3779 if (!req->file)
3780 return -EBADF;
3781
3782 if (unlikely(ctx->flags & IORING_SETUP_IOPOLL))
3783 return -EINVAL;
3784 if (unlikely(sqe->addr || sqe->ioprio || sqe->buf_index))
3785 return -EINVAL;
3786
3787 req->sync.off = READ_ONCE(sqe->off);
3788 req->sync.len = READ_ONCE(sqe->len);
3789 req->sync.flags = READ_ONCE(sqe->sync_range_flags);
3790 return 0;
3791 }
3792
3793 static int io_sync_file_range(struct io_kiocb *req, bool force_nonblock)
3794 {
3795 int ret;
3796
3797 /* sync_file_range always requires a blocking context */
3798 if (force_nonblock)
3799 return -EAGAIN;
3800
3801 ret = sync_file_range(req->file, req->sync.off, req->sync.len,
3802 req->sync.flags);
3803 if (ret < 0)
3804 req_set_fail_links(req);
3805 io_req_complete(req, ret);
3806 return 0;
3807 }
3808
3809 #if defined(CONFIG_NET)
3810 static int io_setup_async_msg(struct io_kiocb *req,
3811 struct io_async_msghdr *kmsg)
3812 {
3813 if (req->io)
3814 return -EAGAIN;
3815 if (io_alloc_async_ctx(req)) {
3816 if (kmsg->iov != kmsg->fast_iov)
3817 kfree(kmsg->iov);
3818 return -ENOMEM;
3819 }
3820 req->flags |= REQ_F_NEED_CLEANUP;
3821 memcpy(&req->io->msg, kmsg, sizeof(*kmsg));
3822 return -EAGAIN;
3823 }
3824
3825 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
3826 {
3827 struct io_sr_msg *sr = &req->sr_msg;
3828 struct io_async_ctx *io = req->io;
3829 int ret;
3830
3831 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
3832 return -EINVAL;
3833
3834 sr->msg_flags = READ_ONCE(sqe->msg_flags);
3835 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
3836 sr->len = READ_ONCE(sqe->len);
3837
3838 #ifdef CONFIG_COMPAT
3839 if (req->ctx->compat)
3840 sr->msg_flags |= MSG_CMSG_COMPAT;
3841 #endif
3842
3843 if (!io || req->opcode == IORING_OP_SEND)
3844 return 0;
3845 /* iovec is already imported */
3846 if (req->flags & REQ_F_NEED_CLEANUP)
3847 return 0;
3848
3849 io->msg.iov = io->msg.fast_iov;
3850 ret = sendmsg_copy_msghdr(&io->msg.msg, sr->msg, sr->msg_flags,
3851 &io->msg.iov);
3852 if (!ret)
3853 req->flags |= REQ_F_NEED_CLEANUP;
3854 return ret;
3855 }
3856
3857 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock,
3858 struct io_comp_state *cs)
3859 {
3860 struct io_async_msghdr *kmsg = NULL;
3861 struct socket *sock;
3862 int ret;
3863
3864 sock = sock_from_file(req->file, &ret);
3865 if (sock) {
3866 struct io_async_ctx io;
3867 unsigned flags;
3868
3869 if (req->io) {
3870 kmsg = &req->io->msg;
3871 kmsg->msg.msg_name = &req->io->msg.addr;
3872 /* if iov is set, it's allocated already */
3873 if (!kmsg->iov)
3874 kmsg->iov = kmsg->fast_iov;
3875 kmsg->msg.msg_iter.iov = kmsg->iov;
3876 } else {
3877 struct io_sr_msg *sr = &req->sr_msg;
3878
3879 kmsg = &io.msg;
3880 kmsg->msg.msg_name = &io.msg.addr;
3881
3882 io.msg.iov = io.msg.fast_iov;
3883 ret = sendmsg_copy_msghdr(&io.msg.msg, sr->msg,
3884 sr->msg_flags, &io.msg.iov);
3885 if (ret)
3886 return ret;
3887 }
3888
3889 flags = req->sr_msg.msg_flags;
3890 if (flags & MSG_DONTWAIT)
3891 req->flags |= REQ_F_NOWAIT;
3892 else if (force_nonblock)
3893 flags |= MSG_DONTWAIT;
3894
3895 ret = __sys_sendmsg_sock(sock, &kmsg->msg, flags);
3896 if (force_nonblock && ret == -EAGAIN)
3897 return io_setup_async_msg(req, kmsg);
3898 if (ret == -ERESTARTSYS)
3899 ret = -EINTR;
3900 }
3901
3902 if (kmsg && kmsg->iov != kmsg->fast_iov)
3903 kfree(kmsg->iov);
3904 req->flags &= ~REQ_F_NEED_CLEANUP;
3905 if (ret < 0)
3906 req_set_fail_links(req);
3907 __io_req_complete(req, ret, 0, cs);
3908 return 0;
3909 }
3910
3911 static int io_send(struct io_kiocb *req, bool force_nonblock,
3912 struct io_comp_state *cs)
3913 {
3914 struct socket *sock;
3915 int ret;
3916
3917 sock = sock_from_file(req->file, &ret);
3918 if (sock) {
3919 struct io_sr_msg *sr = &req->sr_msg;
3920 struct msghdr msg;
3921 struct iovec iov;
3922 unsigned flags;
3923
3924 ret = import_single_range(WRITE, sr->buf, sr->len, &iov,
3925 &msg.msg_iter);
3926 if (ret)
3927 return ret;
3928
3929 msg.msg_name = NULL;
3930 msg.msg_control = NULL;
3931 msg.msg_controllen = 0;
3932 msg.msg_namelen = 0;
3933
3934 flags = req->sr_msg.msg_flags;
3935 if (flags & MSG_DONTWAIT)
3936 req->flags |= REQ_F_NOWAIT;
3937 else if (force_nonblock)
3938 flags |= MSG_DONTWAIT;
3939
3940 msg.msg_flags = flags;
3941 ret = sock_sendmsg(sock, &msg);
3942 if (force_nonblock && ret == -EAGAIN)
3943 return -EAGAIN;
3944 if (ret == -ERESTARTSYS)
3945 ret = -EINTR;
3946 }
3947
3948 if (ret < 0)
3949 req_set_fail_links(req);
3950 __io_req_complete(req, ret, 0, cs);
3951 return 0;
3952 }
3953
3954 static int __io_recvmsg_copy_hdr(struct io_kiocb *req, struct io_async_ctx *io)
3955 {
3956 struct io_sr_msg *sr = &req->sr_msg;
3957 struct iovec __user *uiov;
3958 size_t iov_len;
3959 int ret;
3960
3961 ret = __copy_msghdr_from_user(&io->msg.msg, sr->msg, &io->msg.uaddr,
3962 &uiov, &iov_len);
3963 if (ret)
3964 return ret;
3965
3966 if (req->flags & REQ_F_BUFFER_SELECT) {
3967 if (iov_len > 1)
3968 return -EINVAL;
3969 if (copy_from_user(io->msg.iov, uiov, sizeof(*uiov)))
3970 return -EFAULT;
3971 sr->len = io->msg.iov[0].iov_len;
3972 iov_iter_init(&io->msg.msg.msg_iter, READ, io->msg.iov, 1,
3973 sr->len);
3974 io->msg.iov = NULL;
3975 } else {
3976 ret = import_iovec(READ, uiov, iov_len, UIO_FASTIOV,
3977 &io->msg.iov, &io->msg.msg.msg_iter);
3978 if (ret > 0)
3979 ret = 0;
3980 }
3981
3982 return ret;
3983 }
3984
3985 #ifdef CONFIG_COMPAT
3986 static int __io_compat_recvmsg_copy_hdr(struct io_kiocb *req,
3987 struct io_async_ctx *io)
3988 {
3989 struct compat_msghdr __user *msg_compat;
3990 struct io_sr_msg *sr = &req->sr_msg;
3991 struct compat_iovec __user *uiov;
3992 compat_uptr_t ptr;
3993 compat_size_t len;
3994 int ret;
3995
3996 msg_compat = (struct compat_msghdr __user *) sr->msg;
3997 ret = __get_compat_msghdr(&io->msg.msg, msg_compat, &io->msg.uaddr,
3998 &ptr, &len);
3999 if (ret)
4000 return ret;
4001
4002 uiov = compat_ptr(ptr);
4003 if (req->flags & REQ_F_BUFFER_SELECT) {
4004 compat_ssize_t clen;
4005
4006 if (len > 1)
4007 return -EINVAL;
4008 if (!access_ok(uiov, sizeof(*uiov)))
4009 return -EFAULT;
4010 if (__get_user(clen, &uiov->iov_len))
4011 return -EFAULT;
4012 if (clen < 0)
4013 return -EINVAL;
4014 sr->len = io->msg.iov[0].iov_len;
4015 io->msg.iov = NULL;
4016 } else {
4017 ret = compat_import_iovec(READ, uiov, len, UIO_FASTIOV,
4018 &io->msg.iov,
4019 &io->msg.msg.msg_iter);
4020 if (ret < 0)
4021 return ret;
4022 }
4023
4024 return 0;
4025 }
4026 #endif
4027
4028 static int io_recvmsg_copy_hdr(struct io_kiocb *req, struct io_async_ctx *io)
4029 {
4030 io->msg.iov = io->msg.fast_iov;
4031
4032 #ifdef CONFIG_COMPAT
4033 if (req->ctx->compat)
4034 return __io_compat_recvmsg_copy_hdr(req, io);
4035 #endif
4036
4037 return __io_recvmsg_copy_hdr(req, io);
4038 }
4039
4040 static struct io_buffer *io_recv_buffer_select(struct io_kiocb *req,
4041 int *cflags, bool needs_lock)
4042 {
4043 struct io_sr_msg *sr = &req->sr_msg;
4044 struct io_buffer *kbuf;
4045
4046 if (!(req->flags & REQ_F_BUFFER_SELECT))
4047 return NULL;
4048
4049 kbuf = io_buffer_select(req, &sr->len, sr->bgid, sr->kbuf, needs_lock);
4050 if (IS_ERR(kbuf))
4051 return kbuf;
4052
4053 sr->kbuf = kbuf;
4054 req->flags |= REQ_F_BUFFER_SELECTED;
4055
4056 *cflags = kbuf->bid << IORING_CQE_BUFFER_SHIFT;
4057 *cflags |= IORING_CQE_F_BUFFER;
4058 return kbuf;
4059 }
4060
4061 static int io_recvmsg_prep(struct io_kiocb *req,
4062 const struct io_uring_sqe *sqe)
4063 {
4064 struct io_sr_msg *sr = &req->sr_msg;
4065 struct io_async_ctx *io = req->io;
4066 int ret;
4067
4068 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4069 return -EINVAL;
4070
4071 sr->msg_flags = READ_ONCE(sqe->msg_flags);
4072 sr->msg = u64_to_user_ptr(READ_ONCE(sqe->addr));
4073 sr->len = READ_ONCE(sqe->len);
4074 sr->bgid = READ_ONCE(sqe->buf_group);
4075
4076 #ifdef CONFIG_COMPAT
4077 if (req->ctx->compat)
4078 sr->msg_flags |= MSG_CMSG_COMPAT;
4079 #endif
4080
4081 if (!io || req->opcode == IORING_OP_RECV)
4082 return 0;
4083 /* iovec is already imported */
4084 if (req->flags & REQ_F_NEED_CLEANUP)
4085 return 0;
4086
4087 ret = io_recvmsg_copy_hdr(req, io);
4088 if (!ret)
4089 req->flags |= REQ_F_NEED_CLEANUP;
4090 return ret;
4091 }
4092
4093 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock,
4094 struct io_comp_state *cs)
4095 {
4096 struct io_async_msghdr *kmsg = NULL;
4097 struct socket *sock;
4098 int ret, cflags = 0;
4099
4100 sock = sock_from_file(req->file, &ret);
4101 if (sock) {
4102 struct io_buffer *kbuf;
4103 struct io_async_ctx io;
4104 unsigned flags;
4105
4106 if (req->io) {
4107 kmsg = &req->io->msg;
4108 kmsg->msg.msg_name = &req->io->msg.addr;
4109 /* if iov is set, it's allocated already */
4110 if (!kmsg->iov)
4111 kmsg->iov = kmsg->fast_iov;
4112 kmsg->msg.msg_iter.iov = kmsg->iov;
4113 } else {
4114 kmsg = &io.msg;
4115 kmsg->msg.msg_name = &io.msg.addr;
4116
4117 ret = io_recvmsg_copy_hdr(req, &io);
4118 if (ret)
4119 return ret;
4120 }
4121
4122 kbuf = io_recv_buffer_select(req, &cflags, !force_nonblock);
4123 if (IS_ERR(kbuf)) {
4124 return PTR_ERR(kbuf);
4125 } else if (kbuf) {
4126 kmsg->fast_iov[0].iov_base = u64_to_user_ptr(kbuf->addr);
4127 iov_iter_init(&kmsg->msg.msg_iter, READ, kmsg->iov,
4128 1, req->sr_msg.len);
4129 }
4130
4131 flags = req->sr_msg.msg_flags;
4132 if (flags & MSG_DONTWAIT)
4133 req->flags |= REQ_F_NOWAIT;
4134 else if (force_nonblock)
4135 flags |= MSG_DONTWAIT;
4136
4137 ret = __sys_recvmsg_sock(sock, &kmsg->msg, req->sr_msg.msg,
4138 kmsg->uaddr, flags);
4139 if (force_nonblock && ret == -EAGAIN)
4140 return io_setup_async_msg(req, kmsg);
4141 if (ret == -ERESTARTSYS)
4142 ret = -EINTR;
4143 }
4144
4145 if (kmsg && kmsg->iov != kmsg->fast_iov)
4146 kfree(kmsg->iov);
4147 req->flags &= ~REQ_F_NEED_CLEANUP;
4148 if (ret < 0)
4149 req_set_fail_links(req);
4150 __io_req_complete(req, ret, cflags, cs);
4151 return 0;
4152 }
4153
4154 static int io_recv(struct io_kiocb *req, bool force_nonblock,
4155 struct io_comp_state *cs)
4156 {
4157 struct io_buffer *kbuf = NULL;
4158 struct socket *sock;
4159 int ret, cflags = 0;
4160
4161 sock = sock_from_file(req->file, &ret);
4162 if (sock) {
4163 struct io_sr_msg *sr = &req->sr_msg;
4164 void __user *buf = sr->buf;
4165 struct msghdr msg;
4166 struct iovec iov;
4167 unsigned flags;
4168
4169 kbuf = io_recv_buffer_select(req, &cflags, !force_nonblock);
4170 if (IS_ERR(kbuf))
4171 return PTR_ERR(kbuf);
4172 else if (kbuf)
4173 buf = u64_to_user_ptr(kbuf->addr);
4174
4175 ret = import_single_range(READ, buf, sr->len, &iov,
4176 &msg.msg_iter);
4177 if (ret) {
4178 kfree(kbuf);
4179 return ret;
4180 }
4181
4182 req->flags |= REQ_F_NEED_CLEANUP;
4183 msg.msg_name = NULL;
4184 msg.msg_control = NULL;
4185 msg.msg_controllen = 0;
4186 msg.msg_namelen = 0;
4187 msg.msg_iocb = NULL;
4188 msg.msg_flags = 0;
4189
4190 flags = req->sr_msg.msg_flags;
4191 if (flags & MSG_DONTWAIT)
4192 req->flags |= REQ_F_NOWAIT;
4193 else if (force_nonblock)
4194 flags |= MSG_DONTWAIT;
4195
4196 ret = sock_recvmsg(sock, &msg, flags);
4197 if (force_nonblock && ret == -EAGAIN)
4198 return -EAGAIN;
4199 if (ret == -ERESTARTSYS)
4200 ret = -EINTR;
4201 }
4202
4203 kfree(kbuf);
4204 req->flags &= ~REQ_F_NEED_CLEANUP;
4205 if (ret < 0)
4206 req_set_fail_links(req);
4207 __io_req_complete(req, ret, cflags, cs);
4208 return 0;
4209 }
4210
4211 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4212 {
4213 struct io_accept *accept = &req->accept;
4214
4215 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4216 return -EINVAL;
4217 if (sqe->ioprio || sqe->len || sqe->buf_index)
4218 return -EINVAL;
4219
4220 accept->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4221 accept->addr_len = u64_to_user_ptr(READ_ONCE(sqe->addr2));
4222 accept->flags = READ_ONCE(sqe->accept_flags);
4223 accept->nofile = rlimit(RLIMIT_NOFILE);
4224 return 0;
4225 }
4226
4227 static int io_accept(struct io_kiocb *req, bool force_nonblock,
4228 struct io_comp_state *cs)
4229 {
4230 struct io_accept *accept = &req->accept;
4231 unsigned int file_flags = force_nonblock ? O_NONBLOCK : 0;
4232 int ret;
4233
4234 if (req->file->f_flags & O_NONBLOCK)
4235 req->flags |= REQ_F_NOWAIT;
4236
4237 ret = __sys_accept4_file(req->file, file_flags, accept->addr,
4238 accept->addr_len, accept->flags,
4239 accept->nofile);
4240 if (ret == -EAGAIN && force_nonblock)
4241 return -EAGAIN;
4242 if (ret < 0) {
4243 if (ret == -ERESTARTSYS)
4244 ret = -EINTR;
4245 req_set_fail_links(req);
4246 }
4247 __io_req_complete(req, ret, 0, cs);
4248 return 0;
4249 }
4250
4251 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4252 {
4253 struct io_connect *conn = &req->connect;
4254 struct io_async_ctx *io = req->io;
4255
4256 if (unlikely(req->ctx->flags & (IORING_SETUP_IOPOLL|IORING_SETUP_SQPOLL)))
4257 return -EINVAL;
4258 if (sqe->ioprio || sqe->len || sqe->buf_index || sqe->rw_flags)
4259 return -EINVAL;
4260
4261 conn->addr = u64_to_user_ptr(READ_ONCE(sqe->addr));
4262 conn->addr_len = READ_ONCE(sqe->addr2);
4263
4264 if (!io)
4265 return 0;
4266
4267 return move_addr_to_kernel(conn->addr, conn->addr_len,
4268 &io->connect.address);
4269 }
4270
4271 static int io_connect(struct io_kiocb *req, bool force_nonblock,
4272 struct io_comp_state *cs)
4273 {
4274 struct io_async_ctx __io, *io;
4275 unsigned file_flags;
4276 int ret;
4277
4278 if (req->io) {
4279 io = req->io;
4280 } else {
4281 ret = move_addr_to_kernel(req->connect.addr,
4282 req->connect.addr_len,
4283 &__io.connect.address);
4284 if (ret)
4285 goto out;
4286 io = &__io;
4287 }
4288
4289 file_flags = force_nonblock ? O_NONBLOCK : 0;
4290
4291 ret = __sys_connect_file(req->file, &io->connect.address,
4292 req->connect.addr_len, file_flags);
4293 if ((ret == -EAGAIN || ret == -EINPROGRESS) && force_nonblock) {
4294 if (req->io)
4295 return -EAGAIN;
4296 if (io_alloc_async_ctx(req)) {
4297 ret = -ENOMEM;
4298 goto out;
4299 }
4300 memcpy(&req->io->connect, &__io.connect, sizeof(__io.connect));
4301 return -EAGAIN;
4302 }
4303 if (ret == -ERESTARTSYS)
4304 ret = -EINTR;
4305 out:
4306 if (ret < 0)
4307 req_set_fail_links(req);
4308 __io_req_complete(req, ret, 0, cs);
4309 return 0;
4310 }
4311 #else /* !CONFIG_NET */
4312 static int io_sendmsg_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4313 {
4314 return -EOPNOTSUPP;
4315 }
4316
4317 static int io_sendmsg(struct io_kiocb *req, bool force_nonblock)
4318 {
4319 return -EOPNOTSUPP;
4320 }
4321
4322 static int io_send(struct io_kiocb *req, bool force_nonblock)
4323 {
4324 return -EOPNOTSUPP;
4325 }
4326
4327 static int io_recvmsg_prep(struct io_kiocb *req,
4328 const struct io_uring_sqe *sqe)
4329 {
4330 return -EOPNOTSUPP;
4331 }
4332
4333 static int io_recvmsg(struct io_kiocb *req, bool force_nonblock)
4334 {
4335 return -EOPNOTSUPP;
4336 }
4337
4338 static int io_recv(struct io_kiocb *req, bool force_nonblock)
4339 {
4340 return -EOPNOTSUPP;
4341 }
4342
4343 static int io_accept_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4344 {
4345 return -EOPNOTSUPP;
4346 }
4347
4348 static int io_accept(struct io_kiocb *req, bool force_nonblock)
4349 {
4350 return -EOPNOTSUPP;
4351 }
4352
4353 static int io_connect_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4354 {
4355 return -EOPNOTSUPP;
4356 }
4357
4358 static int io_connect(struct io_kiocb *req, bool force_nonblock)
4359 {
4360 return -EOPNOTSUPP;
4361 }
4362 #endif /* CONFIG_NET */
4363
4364 struct io_poll_table {
4365 struct poll_table_struct pt;
4366 struct io_kiocb *req;
4367 int error;
4368 };
4369
4370 static int __io_async_wake(struct io_kiocb *req, struct io_poll_iocb *poll,
4371 __poll_t mask, task_work_func_t func)
4372 {
4373 struct task_struct *tsk;
4374 int ret;
4375
4376 /* for instances that support it check for an event match first: */
4377 if (mask && !(mask & poll->events))
4378 return 0;
4379
4380 trace_io_uring_task_add(req->ctx, req->opcode, req->user_data, mask);
4381
4382 list_del_init(&poll->wait.entry);
4383
4384 tsk = req->task;
4385 req->result = mask;
4386 init_task_work(&req->task_work, func);
4387 /*
4388 * If this fails, then the task is exiting. When a task exits, the
4389 * work gets canceled, so just cancel this request as well instead
4390 * of executing it. We can't safely execute it anyway, as we may not
4391 * have the needed state needed for it anyway.
4392 */
4393 ret = task_work_add(tsk, &req->task_work, true);
4394 if (unlikely(ret)) {
4395 WRITE_ONCE(poll->canceled, true);
4396 tsk = io_wq_get_task(req->ctx->io_wq);
4397 task_work_add(tsk, &req->task_work, true);
4398 }
4399 wake_up_process(tsk);
4400 return 1;
4401 }
4402
4403 static bool io_poll_rewait(struct io_kiocb *req, struct io_poll_iocb *poll)
4404 __acquires(&req->ctx->completion_lock)
4405 {
4406 struct io_ring_ctx *ctx = req->ctx;
4407
4408 if (!req->result && !READ_ONCE(poll->canceled)) {
4409 struct poll_table_struct pt = { ._key = poll->events };
4410
4411 req->result = vfs_poll(req->file, &pt) & poll->events;
4412 }
4413
4414 spin_lock_irq(&ctx->completion_lock);
4415 if (!req->result && !READ_ONCE(poll->canceled)) {
4416 add_wait_queue(poll->head, &poll->wait);
4417 return true;
4418 }
4419
4420 return false;
4421 }
4422
4423 static void io_poll_remove_double(struct io_kiocb *req)
4424 {
4425 struct io_poll_iocb *poll = (struct io_poll_iocb *) req->io;
4426
4427 lockdep_assert_held(&req->ctx->completion_lock);
4428
4429 if (poll && poll->head) {
4430 struct wait_queue_head *head = poll->head;
4431
4432 spin_lock(&head->lock);
4433 list_del_init(&poll->wait.entry);
4434 if (poll->wait.private)
4435 refcount_dec(&req->refs);
4436 poll->head = NULL;
4437 spin_unlock(&head->lock);
4438 }
4439 }
4440
4441 static void io_poll_complete(struct io_kiocb *req, __poll_t mask, int error)
4442 {
4443 struct io_ring_ctx *ctx = req->ctx;
4444
4445 io_poll_remove_double(req);
4446 req->poll.done = true;
4447 io_cqring_fill_event(req, error ? error : mangle_poll(mask));
4448 io_commit_cqring(ctx);
4449 }
4450
4451 static void io_poll_task_handler(struct io_kiocb *req, struct io_kiocb **nxt)
4452 {
4453 struct io_ring_ctx *ctx = req->ctx;
4454
4455 if (io_poll_rewait(req, &req->poll)) {
4456 spin_unlock_irq(&ctx->completion_lock);
4457 return;
4458 }
4459
4460 hash_del(&req->hash_node);
4461 io_poll_complete(req, req->result, 0);
4462 req->flags |= REQ_F_COMP_LOCKED;
4463 io_put_req_find_next(req, nxt);
4464 spin_unlock_irq(&ctx->completion_lock);
4465
4466 io_cqring_ev_posted(ctx);
4467 }
4468
4469 static void io_poll_task_func(struct callback_head *cb)
4470 {
4471 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4472 struct io_kiocb *nxt = NULL;
4473
4474 io_poll_task_handler(req, &nxt);
4475 if (nxt) {
4476 struct io_ring_ctx *ctx = nxt->ctx;
4477
4478 mutex_lock(&ctx->uring_lock);
4479 __io_queue_sqe(nxt, NULL, NULL);
4480 mutex_unlock(&ctx->uring_lock);
4481 }
4482 }
4483
4484 static int io_poll_double_wake(struct wait_queue_entry *wait, unsigned mode,
4485 int sync, void *key)
4486 {
4487 struct io_kiocb *req = wait->private;
4488 struct io_poll_iocb *poll = (struct io_poll_iocb *) req->io;
4489 __poll_t mask = key_to_poll(key);
4490
4491 /* for instances that support it check for an event match first: */
4492 if (mask && !(mask & poll->events))
4493 return 0;
4494
4495 if (req->poll.head) {
4496 bool done;
4497
4498 spin_lock(&req->poll.head->lock);
4499 done = list_empty(&req->poll.wait.entry);
4500 if (!done)
4501 list_del_init(&req->poll.wait.entry);
4502 spin_unlock(&req->poll.head->lock);
4503 if (!done)
4504 __io_async_wake(req, poll, mask, io_poll_task_func);
4505 }
4506 refcount_dec(&req->refs);
4507 return 1;
4508 }
4509
4510 static void io_init_poll_iocb(struct io_poll_iocb *poll, __poll_t events,
4511 wait_queue_func_t wake_func)
4512 {
4513 poll->head = NULL;
4514 poll->done = false;
4515 poll->canceled = false;
4516 poll->events = events;
4517 INIT_LIST_HEAD(&poll->wait.entry);
4518 init_waitqueue_func_entry(&poll->wait, wake_func);
4519 }
4520
4521 static void __io_queue_proc(struct io_poll_iocb *poll, struct io_poll_table *pt,
4522 struct wait_queue_head *head)
4523 {
4524 struct io_kiocb *req = pt->req;
4525
4526 /*
4527 * If poll->head is already set, it's because the file being polled
4528 * uses multiple waitqueues for poll handling (eg one for read, one
4529 * for write). Setup a separate io_poll_iocb if this happens.
4530 */
4531 if (unlikely(poll->head)) {
4532 /* already have a 2nd entry, fail a third attempt */
4533 if (req->io) {
4534 pt->error = -EINVAL;
4535 return;
4536 }
4537 poll = kmalloc(sizeof(*poll), GFP_ATOMIC);
4538 if (!poll) {
4539 pt->error = -ENOMEM;
4540 return;
4541 }
4542 io_init_poll_iocb(poll, req->poll.events, io_poll_double_wake);
4543 refcount_inc(&req->refs);
4544 poll->wait.private = req;
4545 req->io = (void *) poll;
4546 }
4547
4548 pt->error = 0;
4549 poll->head = head;
4550
4551 if (poll->events & EPOLLEXCLUSIVE)
4552 add_wait_queue_exclusive(head, &poll->wait);
4553 else
4554 add_wait_queue(head, &poll->wait);
4555 }
4556
4557 static void io_async_queue_proc(struct file *file, struct wait_queue_head *head,
4558 struct poll_table_struct *p)
4559 {
4560 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4561
4562 __io_queue_proc(&pt->req->apoll->poll, pt, head);
4563 }
4564
4565 static void io_async_task_func(struct callback_head *cb)
4566 {
4567 struct io_kiocb *req = container_of(cb, struct io_kiocb, task_work);
4568 struct async_poll *apoll = req->apoll;
4569 struct io_ring_ctx *ctx = req->ctx;
4570 bool canceled = false;
4571
4572 trace_io_uring_task_run(req->ctx, req->opcode, req->user_data);
4573
4574 if (io_poll_rewait(req, &apoll->poll)) {
4575 spin_unlock_irq(&ctx->completion_lock);
4576 return;
4577 }
4578
4579 /* If req is still hashed, it cannot have been canceled. Don't check. */
4580 if (hash_hashed(&req->hash_node)) {
4581 hash_del(&req->hash_node);
4582 } else {
4583 canceled = READ_ONCE(apoll->poll.canceled);
4584 if (canceled) {
4585 io_cqring_fill_event(req, -ECANCELED);
4586 io_commit_cqring(ctx);
4587 }
4588 }
4589
4590 spin_unlock_irq(&ctx->completion_lock);
4591
4592 /* restore ->work in case we need to retry again */
4593 if (req->flags & REQ_F_WORK_INITIALIZED)
4594 memcpy(&req->work, &apoll->work, sizeof(req->work));
4595 kfree(apoll);
4596
4597 if (!canceled) {
4598 __set_current_state(TASK_RUNNING);
4599 if (io_sq_thread_acquire_mm(ctx, req)) {
4600 io_cqring_add_event(req, -EFAULT, 0);
4601 goto end_req;
4602 }
4603 mutex_lock(&ctx->uring_lock);
4604 __io_queue_sqe(req, NULL, NULL);
4605 mutex_unlock(&ctx->uring_lock);
4606 } else {
4607 io_cqring_ev_posted(ctx);
4608 end_req:
4609 req_set_fail_links(req);
4610 io_double_put_req(req);
4611 }
4612 }
4613
4614 static int io_async_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4615 void *key)
4616 {
4617 struct io_kiocb *req = wait->private;
4618 struct io_poll_iocb *poll = &req->apoll->poll;
4619
4620 trace_io_uring_poll_wake(req->ctx, req->opcode, req->user_data,
4621 key_to_poll(key));
4622
4623 return __io_async_wake(req, poll, key_to_poll(key), io_async_task_func);
4624 }
4625
4626 static void io_poll_req_insert(struct io_kiocb *req)
4627 {
4628 struct io_ring_ctx *ctx = req->ctx;
4629 struct hlist_head *list;
4630
4631 list = &ctx->cancel_hash[hash_long(req->user_data, ctx->cancel_hash_bits)];
4632 hlist_add_head(&req->hash_node, list);
4633 }
4634
4635 static __poll_t __io_arm_poll_handler(struct io_kiocb *req,
4636 struct io_poll_iocb *poll,
4637 struct io_poll_table *ipt, __poll_t mask,
4638 wait_queue_func_t wake_func)
4639 __acquires(&ctx->completion_lock)
4640 {
4641 struct io_ring_ctx *ctx = req->ctx;
4642 bool cancel = false;
4643
4644 io_init_poll_iocb(poll, mask, wake_func);
4645 poll->file = req->file;
4646 poll->wait.private = req;
4647
4648 ipt->pt._key = mask;
4649 ipt->req = req;
4650 ipt->error = -EINVAL;
4651
4652 mask = vfs_poll(req->file, &ipt->pt) & poll->events;
4653
4654 spin_lock_irq(&ctx->completion_lock);
4655 if (likely(poll->head)) {
4656 spin_lock(&poll->head->lock);
4657 if (unlikely(list_empty(&poll->wait.entry))) {
4658 if (ipt->error)
4659 cancel = true;
4660 ipt->error = 0;
4661 mask = 0;
4662 }
4663 if (mask || ipt->error)
4664 list_del_init(&poll->wait.entry);
4665 else if (cancel)
4666 WRITE_ONCE(poll->canceled, true);
4667 else if (!poll->done) /* actually waiting for an event */
4668 io_poll_req_insert(req);
4669 spin_unlock(&poll->head->lock);
4670 }
4671
4672 return mask;
4673 }
4674
4675 static bool io_arm_poll_handler(struct io_kiocb *req)
4676 {
4677 const struct io_op_def *def = &io_op_defs[req->opcode];
4678 struct io_ring_ctx *ctx = req->ctx;
4679 struct async_poll *apoll;
4680 struct io_poll_table ipt;
4681 __poll_t mask, ret;
4682 bool had_io;
4683
4684 if (!req->file || !file_can_poll(req->file))
4685 return false;
4686 if (req->flags & REQ_F_POLLED)
4687 return false;
4688 if (!def->pollin && !def->pollout)
4689 return false;
4690
4691 apoll = kmalloc(sizeof(*apoll), GFP_ATOMIC);
4692 if (unlikely(!apoll))
4693 return false;
4694
4695 req->flags |= REQ_F_POLLED;
4696 if (req->flags & REQ_F_WORK_INITIALIZED)
4697 memcpy(&apoll->work, &req->work, sizeof(req->work));
4698 had_io = req->io != NULL;
4699
4700 io_get_req_task(req);
4701 req->apoll = apoll;
4702 INIT_HLIST_NODE(&req->hash_node);
4703
4704 mask = 0;
4705 if (def->pollin)
4706 mask |= POLLIN | POLLRDNORM;
4707 if (def->pollout)
4708 mask |= POLLOUT | POLLWRNORM;
4709 mask |= POLLERR | POLLPRI;
4710
4711 ipt.pt._qproc = io_async_queue_proc;
4712
4713 ret = __io_arm_poll_handler(req, &apoll->poll, &ipt, mask,
4714 io_async_wake);
4715 if (ret) {
4716 ipt.error = 0;
4717 /* only remove double add if we did it here */
4718 if (!had_io)
4719 io_poll_remove_double(req);
4720 spin_unlock_irq(&ctx->completion_lock);
4721 if (req->flags & REQ_F_WORK_INITIALIZED)
4722 memcpy(&req->work, &apoll->work, sizeof(req->work));
4723 kfree(apoll);
4724 return false;
4725 }
4726 spin_unlock_irq(&ctx->completion_lock);
4727 trace_io_uring_poll_arm(ctx, req->opcode, req->user_data, mask,
4728 apoll->poll.events);
4729 return true;
4730 }
4731
4732 static bool __io_poll_remove_one(struct io_kiocb *req,
4733 struct io_poll_iocb *poll)
4734 {
4735 bool do_complete = false;
4736
4737 spin_lock(&poll->head->lock);
4738 WRITE_ONCE(poll->canceled, true);
4739 if (!list_empty(&poll->wait.entry)) {
4740 list_del_init(&poll->wait.entry);
4741 do_complete = true;
4742 }
4743 spin_unlock(&poll->head->lock);
4744 hash_del(&req->hash_node);
4745 return do_complete;
4746 }
4747
4748 static bool io_poll_remove_one(struct io_kiocb *req)
4749 {
4750 bool do_complete;
4751
4752 if (req->opcode == IORING_OP_POLL_ADD) {
4753 io_poll_remove_double(req);
4754 do_complete = __io_poll_remove_one(req, &req->poll);
4755 } else {
4756 struct async_poll *apoll = req->apoll;
4757
4758 /* non-poll requests have submit ref still */
4759 do_complete = __io_poll_remove_one(req, &apoll->poll);
4760 if (do_complete) {
4761 io_put_req(req);
4762 /*
4763 * restore ->work because we will call
4764 * io_req_work_drop_env below when dropping the
4765 * final reference.
4766 */
4767 if (req->flags & REQ_F_WORK_INITIALIZED)
4768 memcpy(&req->work, &apoll->work,
4769 sizeof(req->work));
4770 kfree(apoll);
4771 }
4772 }
4773
4774 if (do_complete) {
4775 io_cqring_fill_event(req, -ECANCELED);
4776 io_commit_cqring(req->ctx);
4777 req->flags |= REQ_F_COMP_LOCKED;
4778 io_put_req(req);
4779 }
4780
4781 return do_complete;
4782 }
4783
4784 static void io_poll_remove_all(struct io_ring_ctx *ctx)
4785 {
4786 struct hlist_node *tmp;
4787 struct io_kiocb *req;
4788 int posted = 0, i;
4789
4790 spin_lock_irq(&ctx->completion_lock);
4791 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
4792 struct hlist_head *list;
4793
4794 list = &ctx->cancel_hash[i];
4795 hlist_for_each_entry_safe(req, tmp, list, hash_node)
4796 posted += io_poll_remove_one(req);
4797 }
4798 spin_unlock_irq(&ctx->completion_lock);
4799
4800 if (posted)
4801 io_cqring_ev_posted(ctx);
4802 }
4803
4804 static int io_poll_cancel(struct io_ring_ctx *ctx, __u64 sqe_addr)
4805 {
4806 struct hlist_head *list;
4807 struct io_kiocb *req;
4808
4809 list = &ctx->cancel_hash[hash_long(sqe_addr, ctx->cancel_hash_bits)];
4810 hlist_for_each_entry(req, list, hash_node) {
4811 if (sqe_addr != req->user_data)
4812 continue;
4813 if (io_poll_remove_one(req))
4814 return 0;
4815 return -EALREADY;
4816 }
4817
4818 return -ENOENT;
4819 }
4820
4821 static int io_poll_remove_prep(struct io_kiocb *req,
4822 const struct io_uring_sqe *sqe)
4823 {
4824 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4825 return -EINVAL;
4826 if (sqe->ioprio || sqe->off || sqe->len || sqe->buf_index ||
4827 sqe->poll_events)
4828 return -EINVAL;
4829
4830 req->poll.addr = READ_ONCE(sqe->addr);
4831 return 0;
4832 }
4833
4834 /*
4835 * Find a running poll command that matches one specified in sqe->addr,
4836 * and remove it if found.
4837 */
4838 static int io_poll_remove(struct io_kiocb *req)
4839 {
4840 struct io_ring_ctx *ctx = req->ctx;
4841 u64 addr;
4842 int ret;
4843
4844 addr = req->poll.addr;
4845 spin_lock_irq(&ctx->completion_lock);
4846 ret = io_poll_cancel(ctx, addr);
4847 spin_unlock_irq(&ctx->completion_lock);
4848
4849 if (ret < 0)
4850 req_set_fail_links(req);
4851 io_req_complete(req, ret);
4852 return 0;
4853 }
4854
4855 static int io_poll_wake(struct wait_queue_entry *wait, unsigned mode, int sync,
4856 void *key)
4857 {
4858 struct io_kiocb *req = wait->private;
4859 struct io_poll_iocb *poll = &req->poll;
4860
4861 return __io_async_wake(req, poll, key_to_poll(key), io_poll_task_func);
4862 }
4863
4864 static void io_poll_queue_proc(struct file *file, struct wait_queue_head *head,
4865 struct poll_table_struct *p)
4866 {
4867 struct io_poll_table *pt = container_of(p, struct io_poll_table, pt);
4868
4869 __io_queue_proc(&pt->req->poll, pt, head);
4870 }
4871
4872 static int io_poll_add_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
4873 {
4874 struct io_poll_iocb *poll = &req->poll;
4875 u32 events;
4876
4877 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4878 return -EINVAL;
4879 if (sqe->addr || sqe->ioprio || sqe->off || sqe->len || sqe->buf_index)
4880 return -EINVAL;
4881 if (!poll->file)
4882 return -EBADF;
4883
4884 events = READ_ONCE(sqe->poll32_events);
4885 #ifdef __BIG_ENDIAN
4886 events = swahw32(events);
4887 #endif
4888 poll->events = demangle_poll(events) | EPOLLERR | EPOLLHUP |
4889 (events & EPOLLEXCLUSIVE);
4890
4891 io_get_req_task(req);
4892 return 0;
4893 }
4894
4895 static int io_poll_add(struct io_kiocb *req)
4896 {
4897 struct io_poll_iocb *poll = &req->poll;
4898 struct io_ring_ctx *ctx = req->ctx;
4899 struct io_poll_table ipt;
4900 __poll_t mask;
4901
4902 INIT_HLIST_NODE(&req->hash_node);
4903 INIT_LIST_HEAD(&req->list);
4904 ipt.pt._qproc = io_poll_queue_proc;
4905
4906 mask = __io_arm_poll_handler(req, &req->poll, &ipt, poll->events,
4907 io_poll_wake);
4908
4909 if (mask) { /* no async, we'd stolen it */
4910 ipt.error = 0;
4911 io_poll_complete(req, mask, 0);
4912 }
4913 spin_unlock_irq(&ctx->completion_lock);
4914
4915 if (mask) {
4916 io_cqring_ev_posted(ctx);
4917 io_put_req(req);
4918 }
4919 return ipt.error;
4920 }
4921
4922 static enum hrtimer_restart io_timeout_fn(struct hrtimer *timer)
4923 {
4924 struct io_timeout_data *data = container_of(timer,
4925 struct io_timeout_data, timer);
4926 struct io_kiocb *req = data->req;
4927 struct io_ring_ctx *ctx = req->ctx;
4928 unsigned long flags;
4929
4930 atomic_inc(&ctx->cq_timeouts);
4931
4932 spin_lock_irqsave(&ctx->completion_lock, flags);
4933 /*
4934 * We could be racing with timeout deletion. If the list is empty,
4935 * then timeout lookup already found it and will be handling it.
4936 */
4937 if (!list_empty(&req->list))
4938 list_del_init(&req->list);
4939
4940 io_cqring_fill_event(req, -ETIME);
4941 io_commit_cqring(ctx);
4942 spin_unlock_irqrestore(&ctx->completion_lock, flags);
4943
4944 io_cqring_ev_posted(ctx);
4945 req_set_fail_links(req);
4946 io_put_req(req);
4947 return HRTIMER_NORESTART;
4948 }
4949
4950 static int io_timeout_cancel(struct io_ring_ctx *ctx, __u64 user_data)
4951 {
4952 struct io_kiocb *req;
4953 int ret = -ENOENT;
4954
4955 list_for_each_entry(req, &ctx->timeout_list, list) {
4956 if (user_data == req->user_data) {
4957 list_del_init(&req->list);
4958 ret = 0;
4959 break;
4960 }
4961 }
4962
4963 if (ret == -ENOENT)
4964 return ret;
4965
4966 ret = hrtimer_try_to_cancel(&req->io->timeout.timer);
4967 if (ret == -1)
4968 return -EALREADY;
4969
4970 req_set_fail_links(req);
4971 io_cqring_fill_event(req, -ECANCELED);
4972 io_put_req(req);
4973 return 0;
4974 }
4975
4976 static int io_timeout_remove_prep(struct io_kiocb *req,
4977 const struct io_uring_sqe *sqe)
4978 {
4979 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
4980 return -EINVAL;
4981 if (sqe->flags || sqe->ioprio || sqe->buf_index || sqe->len)
4982 return -EINVAL;
4983
4984 req->timeout.addr = READ_ONCE(sqe->addr);
4985 req->timeout.flags = READ_ONCE(sqe->timeout_flags);
4986 if (req->timeout.flags)
4987 return -EINVAL;
4988
4989 return 0;
4990 }
4991
4992 /*
4993 * Remove or update an existing timeout command
4994 */
4995 static int io_timeout_remove(struct io_kiocb *req)
4996 {
4997 struct io_ring_ctx *ctx = req->ctx;
4998 int ret;
4999
5000 spin_lock_irq(&ctx->completion_lock);
5001 ret = io_timeout_cancel(ctx, req->timeout.addr);
5002
5003 io_cqring_fill_event(req, ret);
5004 io_commit_cqring(ctx);
5005 spin_unlock_irq(&ctx->completion_lock);
5006 io_cqring_ev_posted(ctx);
5007 if (ret < 0)
5008 req_set_fail_links(req);
5009 io_put_req(req);
5010 return 0;
5011 }
5012
5013 static int io_timeout_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5014 bool is_timeout_link)
5015 {
5016 struct io_timeout_data *data;
5017 unsigned flags;
5018 u32 off = READ_ONCE(sqe->off);
5019
5020 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5021 return -EINVAL;
5022 if (sqe->ioprio || sqe->buf_index || sqe->len != 1)
5023 return -EINVAL;
5024 if (off && is_timeout_link)
5025 return -EINVAL;
5026 flags = READ_ONCE(sqe->timeout_flags);
5027 if (flags & ~IORING_TIMEOUT_ABS)
5028 return -EINVAL;
5029
5030 req->timeout.off = off;
5031
5032 if (!req->io && io_alloc_async_ctx(req))
5033 return -ENOMEM;
5034
5035 data = &req->io->timeout;
5036 data->req = req;
5037 req->flags |= REQ_F_TIMEOUT;
5038
5039 if (get_timespec64(&data->ts, u64_to_user_ptr(sqe->addr)))
5040 return -EFAULT;
5041
5042 if (flags & IORING_TIMEOUT_ABS)
5043 data->mode = HRTIMER_MODE_ABS;
5044 else
5045 data->mode = HRTIMER_MODE_REL;
5046
5047 hrtimer_init(&data->timer, CLOCK_MONOTONIC, data->mode);
5048 return 0;
5049 }
5050
5051 static int io_timeout(struct io_kiocb *req)
5052 {
5053 struct io_ring_ctx *ctx = req->ctx;
5054 struct io_timeout_data *data = &req->io->timeout;
5055 struct list_head *entry;
5056 u32 tail, off = req->timeout.off;
5057
5058 spin_lock_irq(&ctx->completion_lock);
5059
5060 /*
5061 * sqe->off holds how many events that need to occur for this
5062 * timeout event to be satisfied. If it isn't set, then this is
5063 * a pure timeout request, sequence isn't used.
5064 */
5065 if (!off) {
5066 req->flags |= REQ_F_TIMEOUT_NOSEQ;
5067 entry = ctx->timeout_list.prev;
5068 goto add;
5069 }
5070
5071 tail = ctx->cached_cq_tail - atomic_read(&ctx->cq_timeouts);
5072 req->timeout.target_seq = tail + off;
5073
5074 /*
5075 * Insertion sort, ensuring the first entry in the list is always
5076 * the one we need first.
5077 */
5078 list_for_each_prev(entry, &ctx->timeout_list) {
5079 struct io_kiocb *nxt = list_entry(entry, struct io_kiocb, list);
5080
5081 if (nxt->flags & REQ_F_TIMEOUT_NOSEQ)
5082 continue;
5083 /* nxt.seq is behind @tail, otherwise would've been completed */
5084 if (off >= nxt->timeout.target_seq - tail)
5085 break;
5086 }
5087 add:
5088 list_add(&req->list, entry);
5089 data->timer.function = io_timeout_fn;
5090 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts), data->mode);
5091 spin_unlock_irq(&ctx->completion_lock);
5092 return 0;
5093 }
5094
5095 static bool io_cancel_cb(struct io_wq_work *work, void *data)
5096 {
5097 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5098
5099 return req->user_data == (unsigned long) data;
5100 }
5101
5102 static int io_async_cancel_one(struct io_ring_ctx *ctx, void *sqe_addr)
5103 {
5104 enum io_wq_cancel cancel_ret;
5105 int ret = 0;
5106
5107 cancel_ret = io_wq_cancel_cb(ctx->io_wq, io_cancel_cb, sqe_addr, false);
5108 switch (cancel_ret) {
5109 case IO_WQ_CANCEL_OK:
5110 ret = 0;
5111 break;
5112 case IO_WQ_CANCEL_RUNNING:
5113 ret = -EALREADY;
5114 break;
5115 case IO_WQ_CANCEL_NOTFOUND:
5116 ret = -ENOENT;
5117 break;
5118 }
5119
5120 return ret;
5121 }
5122
5123 static void io_async_find_and_cancel(struct io_ring_ctx *ctx,
5124 struct io_kiocb *req, __u64 sqe_addr,
5125 int success_ret)
5126 {
5127 unsigned long flags;
5128 int ret;
5129
5130 ret = io_async_cancel_one(ctx, (void *) (unsigned long) sqe_addr);
5131 if (ret != -ENOENT) {
5132 spin_lock_irqsave(&ctx->completion_lock, flags);
5133 goto done;
5134 }
5135
5136 spin_lock_irqsave(&ctx->completion_lock, flags);
5137 ret = io_timeout_cancel(ctx, sqe_addr);
5138 if (ret != -ENOENT)
5139 goto done;
5140 ret = io_poll_cancel(ctx, sqe_addr);
5141 done:
5142 if (!ret)
5143 ret = success_ret;
5144 io_cqring_fill_event(req, ret);
5145 io_commit_cqring(ctx);
5146 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5147 io_cqring_ev_posted(ctx);
5148
5149 if (ret < 0)
5150 req_set_fail_links(req);
5151 io_put_req(req);
5152 }
5153
5154 static int io_async_cancel_prep(struct io_kiocb *req,
5155 const struct io_uring_sqe *sqe)
5156 {
5157 if (unlikely(req->ctx->flags & IORING_SETUP_IOPOLL))
5158 return -EINVAL;
5159 if (sqe->flags || sqe->ioprio || sqe->off || sqe->len ||
5160 sqe->cancel_flags)
5161 return -EINVAL;
5162
5163 req->cancel.addr = READ_ONCE(sqe->addr);
5164 return 0;
5165 }
5166
5167 static int io_async_cancel(struct io_kiocb *req)
5168 {
5169 struct io_ring_ctx *ctx = req->ctx;
5170
5171 io_async_find_and_cancel(ctx, req, req->cancel.addr, 0);
5172 return 0;
5173 }
5174
5175 static int io_files_update_prep(struct io_kiocb *req,
5176 const struct io_uring_sqe *sqe)
5177 {
5178 if (sqe->flags || sqe->ioprio || sqe->rw_flags)
5179 return -EINVAL;
5180
5181 req->files_update.offset = READ_ONCE(sqe->off);
5182 req->files_update.nr_args = READ_ONCE(sqe->len);
5183 if (!req->files_update.nr_args)
5184 return -EINVAL;
5185 req->files_update.arg = READ_ONCE(sqe->addr);
5186 return 0;
5187 }
5188
5189 static int io_files_update(struct io_kiocb *req, bool force_nonblock,
5190 struct io_comp_state *cs)
5191 {
5192 struct io_ring_ctx *ctx = req->ctx;
5193 struct io_uring_files_update up;
5194 int ret;
5195
5196 if (force_nonblock)
5197 return -EAGAIN;
5198
5199 up.offset = req->files_update.offset;
5200 up.fds = req->files_update.arg;
5201
5202 mutex_lock(&ctx->uring_lock);
5203 ret = __io_sqe_files_update(ctx, &up, req->files_update.nr_args);
5204 mutex_unlock(&ctx->uring_lock);
5205
5206 if (ret < 0)
5207 req_set_fail_links(req);
5208 __io_req_complete(req, ret, 0, cs);
5209 return 0;
5210 }
5211
5212 static int io_req_defer_prep(struct io_kiocb *req,
5213 const struct io_uring_sqe *sqe)
5214 {
5215 ssize_t ret = 0;
5216
5217 if (!sqe)
5218 return 0;
5219
5220 io_req_init_async(req);
5221
5222 if (io_op_defs[req->opcode].file_table) {
5223 ret = io_grab_files(req);
5224 if (unlikely(ret))
5225 return ret;
5226 }
5227
5228 io_req_work_grab_env(req, &io_op_defs[req->opcode]);
5229
5230 switch (req->opcode) {
5231 case IORING_OP_NOP:
5232 break;
5233 case IORING_OP_READV:
5234 case IORING_OP_READ_FIXED:
5235 case IORING_OP_READ:
5236 ret = io_read_prep(req, sqe, true);
5237 break;
5238 case IORING_OP_WRITEV:
5239 case IORING_OP_WRITE_FIXED:
5240 case IORING_OP_WRITE:
5241 ret = io_write_prep(req, sqe, true);
5242 break;
5243 case IORING_OP_POLL_ADD:
5244 ret = io_poll_add_prep(req, sqe);
5245 break;
5246 case IORING_OP_POLL_REMOVE:
5247 ret = io_poll_remove_prep(req, sqe);
5248 break;
5249 case IORING_OP_FSYNC:
5250 ret = io_prep_fsync(req, sqe);
5251 break;
5252 case IORING_OP_SYNC_FILE_RANGE:
5253 ret = io_prep_sfr(req, sqe);
5254 break;
5255 case IORING_OP_SENDMSG:
5256 case IORING_OP_SEND:
5257 ret = io_sendmsg_prep(req, sqe);
5258 break;
5259 case IORING_OP_RECVMSG:
5260 case IORING_OP_RECV:
5261 ret = io_recvmsg_prep(req, sqe);
5262 break;
5263 case IORING_OP_CONNECT:
5264 ret = io_connect_prep(req, sqe);
5265 break;
5266 case IORING_OP_TIMEOUT:
5267 ret = io_timeout_prep(req, sqe, false);
5268 break;
5269 case IORING_OP_TIMEOUT_REMOVE:
5270 ret = io_timeout_remove_prep(req, sqe);
5271 break;
5272 case IORING_OP_ASYNC_CANCEL:
5273 ret = io_async_cancel_prep(req, sqe);
5274 break;
5275 case IORING_OP_LINK_TIMEOUT:
5276 ret = io_timeout_prep(req, sqe, true);
5277 break;
5278 case IORING_OP_ACCEPT:
5279 ret = io_accept_prep(req, sqe);
5280 break;
5281 case IORING_OP_FALLOCATE:
5282 ret = io_fallocate_prep(req, sqe);
5283 break;
5284 case IORING_OP_OPENAT:
5285 ret = io_openat_prep(req, sqe);
5286 break;
5287 case IORING_OP_CLOSE:
5288 ret = io_close_prep(req, sqe);
5289 break;
5290 case IORING_OP_FILES_UPDATE:
5291 ret = io_files_update_prep(req, sqe);
5292 break;
5293 case IORING_OP_STATX:
5294 ret = io_statx_prep(req, sqe);
5295 break;
5296 case IORING_OP_FADVISE:
5297 ret = io_fadvise_prep(req, sqe);
5298 break;
5299 case IORING_OP_MADVISE:
5300 ret = io_madvise_prep(req, sqe);
5301 break;
5302 case IORING_OP_OPENAT2:
5303 ret = io_openat2_prep(req, sqe);
5304 break;
5305 case IORING_OP_EPOLL_CTL:
5306 ret = io_epoll_ctl_prep(req, sqe);
5307 break;
5308 case IORING_OP_SPLICE:
5309 ret = io_splice_prep(req, sqe);
5310 break;
5311 case IORING_OP_PROVIDE_BUFFERS:
5312 ret = io_provide_buffers_prep(req, sqe);
5313 break;
5314 case IORING_OP_REMOVE_BUFFERS:
5315 ret = io_remove_buffers_prep(req, sqe);
5316 break;
5317 case IORING_OP_TEE:
5318 ret = io_tee_prep(req, sqe);
5319 break;
5320 default:
5321 printk_once(KERN_WARNING "io_uring: unhandled opcode %d\n",
5322 req->opcode);
5323 ret = -EINVAL;
5324 break;
5325 }
5326
5327 return ret;
5328 }
5329
5330 static int io_req_defer(struct io_kiocb *req, const struct io_uring_sqe *sqe)
5331 {
5332 struct io_ring_ctx *ctx = req->ctx;
5333 int ret;
5334
5335 /* Still need defer if there is pending req in defer list. */
5336 if (!req_need_defer(req) && list_empty_careful(&ctx->defer_list))
5337 return 0;
5338
5339 if (!req->io) {
5340 if (io_alloc_async_ctx(req))
5341 return -EAGAIN;
5342 ret = io_req_defer_prep(req, sqe);
5343 if (ret < 0)
5344 return ret;
5345 }
5346
5347 spin_lock_irq(&ctx->completion_lock);
5348 if (!req_need_defer(req) && list_empty(&ctx->defer_list)) {
5349 spin_unlock_irq(&ctx->completion_lock);
5350 return 0;
5351 }
5352
5353 trace_io_uring_defer(ctx, req, req->user_data);
5354 list_add_tail(&req->list, &ctx->defer_list);
5355 spin_unlock_irq(&ctx->completion_lock);
5356 return -EIOCBQUEUED;
5357 }
5358
5359 static void io_cleanup_req(struct io_kiocb *req)
5360 {
5361 struct io_async_ctx *io = req->io;
5362
5363 switch (req->opcode) {
5364 case IORING_OP_READV:
5365 case IORING_OP_READ_FIXED:
5366 case IORING_OP_READ:
5367 if (req->flags & REQ_F_BUFFER_SELECTED)
5368 kfree((void *)(unsigned long)req->rw.addr);
5369 /* fallthrough */
5370 case IORING_OP_WRITEV:
5371 case IORING_OP_WRITE_FIXED:
5372 case IORING_OP_WRITE:
5373 if (io->rw.iov != io->rw.fast_iov)
5374 kfree(io->rw.iov);
5375 break;
5376 case IORING_OP_RECVMSG:
5377 if (req->flags & REQ_F_BUFFER_SELECTED)
5378 kfree(req->sr_msg.kbuf);
5379 /* fallthrough */
5380 case IORING_OP_SENDMSG:
5381 if (io->msg.iov != io->msg.fast_iov)
5382 kfree(io->msg.iov);
5383 break;
5384 case IORING_OP_RECV:
5385 if (req->flags & REQ_F_BUFFER_SELECTED)
5386 kfree(req->sr_msg.kbuf);
5387 break;
5388 case IORING_OP_OPENAT:
5389 case IORING_OP_OPENAT2:
5390 break;
5391 case IORING_OP_SPLICE:
5392 case IORING_OP_TEE:
5393 io_put_file(req, req->splice.file_in,
5394 (req->splice.flags & SPLICE_F_FD_IN_FIXED));
5395 break;
5396 }
5397
5398 req->flags &= ~REQ_F_NEED_CLEANUP;
5399 }
5400
5401 static int io_issue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5402 bool force_nonblock, struct io_comp_state *cs)
5403 {
5404 struct io_ring_ctx *ctx = req->ctx;
5405 int ret;
5406
5407 switch (req->opcode) {
5408 case IORING_OP_NOP:
5409 ret = io_nop(req, cs);
5410 break;
5411 case IORING_OP_READV:
5412 case IORING_OP_READ_FIXED:
5413 case IORING_OP_READ:
5414 if (sqe) {
5415 ret = io_read_prep(req, sqe, force_nonblock);
5416 if (ret < 0)
5417 break;
5418 }
5419 ret = io_read(req, force_nonblock);
5420 break;
5421 case IORING_OP_WRITEV:
5422 case IORING_OP_WRITE_FIXED:
5423 case IORING_OP_WRITE:
5424 if (sqe) {
5425 ret = io_write_prep(req, sqe, force_nonblock);
5426 if (ret < 0)
5427 break;
5428 }
5429 ret = io_write(req, force_nonblock);
5430 break;
5431 case IORING_OP_FSYNC:
5432 if (sqe) {
5433 ret = io_prep_fsync(req, sqe);
5434 if (ret < 0)
5435 break;
5436 }
5437 ret = io_fsync(req, force_nonblock);
5438 break;
5439 case IORING_OP_POLL_ADD:
5440 if (sqe) {
5441 ret = io_poll_add_prep(req, sqe);
5442 if (ret)
5443 break;
5444 }
5445 ret = io_poll_add(req);
5446 break;
5447 case IORING_OP_POLL_REMOVE:
5448 if (sqe) {
5449 ret = io_poll_remove_prep(req, sqe);
5450 if (ret < 0)
5451 break;
5452 }
5453 ret = io_poll_remove(req);
5454 break;
5455 case IORING_OP_SYNC_FILE_RANGE:
5456 if (sqe) {
5457 ret = io_prep_sfr(req, sqe);
5458 if (ret < 0)
5459 break;
5460 }
5461 ret = io_sync_file_range(req, force_nonblock);
5462 break;
5463 case IORING_OP_SENDMSG:
5464 case IORING_OP_SEND:
5465 if (sqe) {
5466 ret = io_sendmsg_prep(req, sqe);
5467 if (ret < 0)
5468 break;
5469 }
5470 if (req->opcode == IORING_OP_SENDMSG)
5471 ret = io_sendmsg(req, force_nonblock, cs);
5472 else
5473 ret = io_send(req, force_nonblock, cs);
5474 break;
5475 case IORING_OP_RECVMSG:
5476 case IORING_OP_RECV:
5477 if (sqe) {
5478 ret = io_recvmsg_prep(req, sqe);
5479 if (ret)
5480 break;
5481 }
5482 if (req->opcode == IORING_OP_RECVMSG)
5483 ret = io_recvmsg(req, force_nonblock, cs);
5484 else
5485 ret = io_recv(req, force_nonblock, cs);
5486 break;
5487 case IORING_OP_TIMEOUT:
5488 if (sqe) {
5489 ret = io_timeout_prep(req, sqe, false);
5490 if (ret)
5491 break;
5492 }
5493 ret = io_timeout(req);
5494 break;
5495 case IORING_OP_TIMEOUT_REMOVE:
5496 if (sqe) {
5497 ret = io_timeout_remove_prep(req, sqe);
5498 if (ret)
5499 break;
5500 }
5501 ret = io_timeout_remove(req);
5502 break;
5503 case IORING_OP_ACCEPT:
5504 if (sqe) {
5505 ret = io_accept_prep(req, sqe);
5506 if (ret)
5507 break;
5508 }
5509 ret = io_accept(req, force_nonblock, cs);
5510 break;
5511 case IORING_OP_CONNECT:
5512 if (sqe) {
5513 ret = io_connect_prep(req, sqe);
5514 if (ret)
5515 break;
5516 }
5517 ret = io_connect(req, force_nonblock, cs);
5518 break;
5519 case IORING_OP_ASYNC_CANCEL:
5520 if (sqe) {
5521 ret = io_async_cancel_prep(req, sqe);
5522 if (ret)
5523 break;
5524 }
5525 ret = io_async_cancel(req);
5526 break;
5527 case IORING_OP_FALLOCATE:
5528 if (sqe) {
5529 ret = io_fallocate_prep(req, sqe);
5530 if (ret)
5531 break;
5532 }
5533 ret = io_fallocate(req, force_nonblock);
5534 break;
5535 case IORING_OP_OPENAT:
5536 if (sqe) {
5537 ret = io_openat_prep(req, sqe);
5538 if (ret)
5539 break;
5540 }
5541 ret = io_openat(req, force_nonblock);
5542 break;
5543 case IORING_OP_CLOSE:
5544 if (sqe) {
5545 ret = io_close_prep(req, sqe);
5546 if (ret)
5547 break;
5548 }
5549 ret = io_close(req, force_nonblock, cs);
5550 break;
5551 case IORING_OP_FILES_UPDATE:
5552 if (sqe) {
5553 ret = io_files_update_prep(req, sqe);
5554 if (ret)
5555 break;
5556 }
5557 ret = io_files_update(req, force_nonblock, cs);
5558 break;
5559 case IORING_OP_STATX:
5560 if (sqe) {
5561 ret = io_statx_prep(req, sqe);
5562 if (ret)
5563 break;
5564 }
5565 ret = io_statx(req, force_nonblock);
5566 break;
5567 case IORING_OP_FADVISE:
5568 if (sqe) {
5569 ret = io_fadvise_prep(req, sqe);
5570 if (ret)
5571 break;
5572 }
5573 ret = io_fadvise(req, force_nonblock);
5574 break;
5575 case IORING_OP_MADVISE:
5576 if (sqe) {
5577 ret = io_madvise_prep(req, sqe);
5578 if (ret)
5579 break;
5580 }
5581 ret = io_madvise(req, force_nonblock);
5582 break;
5583 case IORING_OP_OPENAT2:
5584 if (sqe) {
5585 ret = io_openat2_prep(req, sqe);
5586 if (ret)
5587 break;
5588 }
5589 ret = io_openat2(req, force_nonblock);
5590 break;
5591 case IORING_OP_EPOLL_CTL:
5592 if (sqe) {
5593 ret = io_epoll_ctl_prep(req, sqe);
5594 if (ret)
5595 break;
5596 }
5597 ret = io_epoll_ctl(req, force_nonblock, cs);
5598 break;
5599 case IORING_OP_SPLICE:
5600 if (sqe) {
5601 ret = io_splice_prep(req, sqe);
5602 if (ret < 0)
5603 break;
5604 }
5605 ret = io_splice(req, force_nonblock);
5606 break;
5607 case IORING_OP_PROVIDE_BUFFERS:
5608 if (sqe) {
5609 ret = io_provide_buffers_prep(req, sqe);
5610 if (ret)
5611 break;
5612 }
5613 ret = io_provide_buffers(req, force_nonblock, cs);
5614 break;
5615 case IORING_OP_REMOVE_BUFFERS:
5616 if (sqe) {
5617 ret = io_remove_buffers_prep(req, sqe);
5618 if (ret)
5619 break;
5620 }
5621 ret = io_remove_buffers(req, force_nonblock, cs);
5622 break;
5623 case IORING_OP_TEE:
5624 if (sqe) {
5625 ret = io_tee_prep(req, sqe);
5626 if (ret < 0)
5627 break;
5628 }
5629 ret = io_tee(req, force_nonblock);
5630 break;
5631 default:
5632 ret = -EINVAL;
5633 break;
5634 }
5635
5636 if (ret)
5637 return ret;
5638
5639 /* If the op doesn't have a file, we're not polling for it */
5640 if ((ctx->flags & IORING_SETUP_IOPOLL) && req->file) {
5641 const bool in_async = io_wq_current_is_worker();
5642
5643 if (req->result == -EAGAIN)
5644 return -EAGAIN;
5645
5646 /* workqueue context doesn't hold uring_lock, grab it now */
5647 if (in_async)
5648 mutex_lock(&ctx->uring_lock);
5649
5650 io_iopoll_req_issued(req);
5651
5652 if (in_async)
5653 mutex_unlock(&ctx->uring_lock);
5654 }
5655
5656 return 0;
5657 }
5658
5659 static void io_arm_async_linked_timeout(struct io_kiocb *req)
5660 {
5661 struct io_kiocb *link;
5662
5663 /* link head's timeout is queued in io_queue_async_work() */
5664 if (!(req->flags & REQ_F_QUEUE_TIMEOUT))
5665 return;
5666
5667 link = list_first_entry(&req->link_list, struct io_kiocb, link_list);
5668 io_queue_linked_timeout(link);
5669 }
5670
5671 static void io_wq_submit_work(struct io_wq_work **workptr)
5672 {
5673 struct io_wq_work *work = *workptr;
5674 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
5675 int ret = 0;
5676
5677 io_arm_async_linked_timeout(req);
5678
5679 /* if NO_CANCEL is set, we must still run the work */
5680 if ((work->flags & (IO_WQ_WORK_CANCEL|IO_WQ_WORK_NO_CANCEL)) ==
5681 IO_WQ_WORK_CANCEL) {
5682 ret = -ECANCELED;
5683 }
5684
5685 if (!ret) {
5686 do {
5687 ret = io_issue_sqe(req, NULL, false, NULL);
5688 /*
5689 * We can get EAGAIN for polled IO even though we're
5690 * forcing a sync submission from here, since we can't
5691 * wait for request slots on the block side.
5692 */
5693 if (ret != -EAGAIN)
5694 break;
5695 cond_resched();
5696 } while (1);
5697 }
5698
5699 if (ret) {
5700 req_set_fail_links(req);
5701 io_req_complete(req, ret);
5702 }
5703
5704 io_steal_work(req, workptr);
5705 }
5706
5707 static inline struct file *io_file_from_index(struct io_ring_ctx *ctx,
5708 int index)
5709 {
5710 struct fixed_file_table *table;
5711
5712 table = &ctx->file_data->table[index >> IORING_FILE_TABLE_SHIFT];
5713 return table->files[index & IORING_FILE_TABLE_MASK];
5714 }
5715
5716 static int io_file_get(struct io_submit_state *state, struct io_kiocb *req,
5717 int fd, struct file **out_file, bool fixed)
5718 {
5719 struct io_ring_ctx *ctx = req->ctx;
5720 struct file *file;
5721
5722 if (fixed) {
5723 if (unlikely(!ctx->file_data ||
5724 (unsigned) fd >= ctx->nr_user_files))
5725 return -EBADF;
5726 fd = array_index_nospec(fd, ctx->nr_user_files);
5727 file = io_file_from_index(ctx, fd);
5728 if (file) {
5729 req->fixed_file_refs = ctx->file_data->cur_refs;
5730 percpu_ref_get(req->fixed_file_refs);
5731 }
5732 } else {
5733 trace_io_uring_file_get(ctx, fd);
5734 file = __io_file_get(state, fd);
5735 }
5736
5737 if (file || io_op_defs[req->opcode].needs_file_no_error) {
5738 *out_file = file;
5739 return 0;
5740 }
5741 return -EBADF;
5742 }
5743
5744 static int io_req_set_file(struct io_submit_state *state, struct io_kiocb *req,
5745 int fd)
5746 {
5747 bool fixed;
5748
5749 fixed = (req->flags & REQ_F_FIXED_FILE) != 0;
5750 if (unlikely(!fixed && io_async_submit(req->ctx)))
5751 return -EBADF;
5752
5753 return io_file_get(state, req, fd, &req->file, fixed);
5754 }
5755
5756 static int io_grab_files(struct io_kiocb *req)
5757 {
5758 int ret = -EBADF;
5759 struct io_ring_ctx *ctx = req->ctx;
5760
5761 if (req->work.files || (req->flags & REQ_F_NO_FILE_TABLE))
5762 return 0;
5763 if (!ctx->ring_file)
5764 return -EBADF;
5765
5766 rcu_read_lock();
5767 spin_lock_irq(&ctx->inflight_lock);
5768 /*
5769 * We use the f_ops->flush() handler to ensure that we can flush
5770 * out work accessing these files if the fd is closed. Check if
5771 * the fd has changed since we started down this path, and disallow
5772 * this operation if it has.
5773 */
5774 if (fcheck(ctx->ring_fd) == ctx->ring_file) {
5775 list_add(&req->inflight_entry, &ctx->inflight_list);
5776 req->flags |= REQ_F_INFLIGHT;
5777 req->work.files = current->files;
5778 ret = 0;
5779 }
5780 spin_unlock_irq(&ctx->inflight_lock);
5781 rcu_read_unlock();
5782
5783 return ret;
5784 }
5785
5786 static enum hrtimer_restart io_link_timeout_fn(struct hrtimer *timer)
5787 {
5788 struct io_timeout_data *data = container_of(timer,
5789 struct io_timeout_data, timer);
5790 struct io_kiocb *req = data->req;
5791 struct io_ring_ctx *ctx = req->ctx;
5792 struct io_kiocb *prev = NULL;
5793 unsigned long flags;
5794
5795 spin_lock_irqsave(&ctx->completion_lock, flags);
5796
5797 /*
5798 * We don't expect the list to be empty, that will only happen if we
5799 * race with the completion of the linked work.
5800 */
5801 if (!list_empty(&req->link_list)) {
5802 prev = list_entry(req->link_list.prev, struct io_kiocb,
5803 link_list);
5804 if (refcount_inc_not_zero(&prev->refs)) {
5805 list_del_init(&req->link_list);
5806 prev->flags &= ~REQ_F_LINK_TIMEOUT;
5807 } else
5808 prev = NULL;
5809 }
5810
5811 spin_unlock_irqrestore(&ctx->completion_lock, flags);
5812
5813 if (prev) {
5814 req_set_fail_links(prev);
5815 io_async_find_and_cancel(ctx, req, prev->user_data, -ETIME);
5816 io_put_req(prev);
5817 } else {
5818 io_req_complete(req, -ETIME);
5819 }
5820 return HRTIMER_NORESTART;
5821 }
5822
5823 static void io_queue_linked_timeout(struct io_kiocb *req)
5824 {
5825 struct io_ring_ctx *ctx = req->ctx;
5826
5827 /*
5828 * If the list is now empty, then our linked request finished before
5829 * we got a chance to setup the timer
5830 */
5831 spin_lock_irq(&ctx->completion_lock);
5832 if (!list_empty(&req->link_list)) {
5833 struct io_timeout_data *data = &req->io->timeout;
5834
5835 data->timer.function = io_link_timeout_fn;
5836 hrtimer_start(&data->timer, timespec64_to_ktime(data->ts),
5837 data->mode);
5838 }
5839 spin_unlock_irq(&ctx->completion_lock);
5840
5841 /* drop submission reference */
5842 io_put_req(req);
5843 }
5844
5845 static struct io_kiocb *io_prep_linked_timeout(struct io_kiocb *req)
5846 {
5847 struct io_kiocb *nxt;
5848
5849 if (!(req->flags & REQ_F_LINK_HEAD))
5850 return NULL;
5851 /* for polled retry, if flag is set, we already went through here */
5852 if (req->flags & REQ_F_POLLED)
5853 return NULL;
5854
5855 nxt = list_first_entry_or_null(&req->link_list, struct io_kiocb,
5856 link_list);
5857 if (!nxt || nxt->opcode != IORING_OP_LINK_TIMEOUT)
5858 return NULL;
5859
5860 req->flags |= REQ_F_LINK_TIMEOUT;
5861 return nxt;
5862 }
5863
5864 static void __io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5865 struct io_comp_state *cs)
5866 {
5867 struct io_kiocb *linked_timeout;
5868 struct io_kiocb *nxt;
5869 const struct cred *old_creds = NULL;
5870 int ret;
5871
5872 again:
5873 linked_timeout = io_prep_linked_timeout(req);
5874
5875 if ((req->flags & REQ_F_WORK_INITIALIZED) && req->work.creds &&
5876 req->work.creds != current_cred()) {
5877 if (old_creds)
5878 revert_creds(old_creds);
5879 if (old_creds == req->work.creds)
5880 old_creds = NULL; /* restored original creds */
5881 else
5882 old_creds = override_creds(req->work.creds);
5883 }
5884
5885 ret = io_issue_sqe(req, sqe, true, cs);
5886
5887 /*
5888 * We async punt it if the file wasn't marked NOWAIT, or if the file
5889 * doesn't support non-blocking read/write attempts
5890 */
5891 if (ret == -EAGAIN && !(req->flags & REQ_F_NOWAIT)) {
5892 if (io_arm_poll_handler(req)) {
5893 if (linked_timeout)
5894 io_queue_linked_timeout(linked_timeout);
5895 goto exit;
5896 }
5897 punt:
5898 io_req_init_async(req);
5899
5900 if (io_op_defs[req->opcode].file_table) {
5901 ret = io_grab_files(req);
5902 if (ret)
5903 goto err;
5904 }
5905
5906 /*
5907 * Queued up for async execution, worker will release
5908 * submit reference when the iocb is actually submitted.
5909 */
5910 io_queue_async_work(req);
5911 goto exit;
5912 }
5913
5914 err:
5915 nxt = NULL;
5916 /* drop submission reference */
5917 io_put_req_find_next(req, &nxt);
5918
5919 if (linked_timeout) {
5920 if (!ret)
5921 io_queue_linked_timeout(linked_timeout);
5922 else
5923 io_put_req(linked_timeout);
5924 }
5925
5926 /* and drop final reference, if we failed */
5927 if (ret) {
5928 req_set_fail_links(req);
5929 io_req_complete(req, ret);
5930 }
5931 if (nxt) {
5932 req = nxt;
5933
5934 if (req->flags & REQ_F_FORCE_ASYNC)
5935 goto punt;
5936 goto again;
5937 }
5938 exit:
5939 if (old_creds)
5940 revert_creds(old_creds);
5941 }
5942
5943 static void io_queue_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5944 struct io_comp_state *cs)
5945 {
5946 int ret;
5947
5948 ret = io_req_defer(req, sqe);
5949 if (ret) {
5950 if (ret != -EIOCBQUEUED) {
5951 fail_req:
5952 req_set_fail_links(req);
5953 io_put_req(req);
5954 io_req_complete(req, ret);
5955 }
5956 } else if (req->flags & REQ_F_FORCE_ASYNC) {
5957 if (!req->io) {
5958 ret = -EAGAIN;
5959 if (io_alloc_async_ctx(req))
5960 goto fail_req;
5961 ret = io_req_defer_prep(req, sqe);
5962 if (unlikely(ret < 0))
5963 goto fail_req;
5964 }
5965
5966 /*
5967 * Never try inline submit of IOSQE_ASYNC is set, go straight
5968 * to async execution.
5969 */
5970 req->work.flags |= IO_WQ_WORK_CONCURRENT;
5971 io_queue_async_work(req);
5972 } else {
5973 __io_queue_sqe(req, sqe, cs);
5974 }
5975 }
5976
5977 static inline void io_queue_link_head(struct io_kiocb *req,
5978 struct io_comp_state *cs)
5979 {
5980 if (unlikely(req->flags & REQ_F_FAIL_LINK)) {
5981 io_put_req(req);
5982 io_req_complete(req, -ECANCELED);
5983 } else
5984 io_queue_sqe(req, NULL, cs);
5985 }
5986
5987 static int io_submit_sqe(struct io_kiocb *req, const struct io_uring_sqe *sqe,
5988 struct io_kiocb **link, struct io_comp_state *cs)
5989 {
5990 struct io_ring_ctx *ctx = req->ctx;
5991 int ret;
5992
5993 /*
5994 * If we already have a head request, queue this one for async
5995 * submittal once the head completes. If we don't have a head but
5996 * IOSQE_IO_LINK is set in the sqe, start a new head. This one will be
5997 * submitted sync once the chain is complete. If none of those
5998 * conditions are true (normal request), then just queue it.
5999 */
6000 if (*link) {
6001 struct io_kiocb *head = *link;
6002
6003 /*
6004 * Taking sequential execution of a link, draining both sides
6005 * of the link also fullfils IOSQE_IO_DRAIN semantics for all
6006 * requests in the link. So, it drains the head and the
6007 * next after the link request. The last one is done via
6008 * drain_next flag to persist the effect across calls.
6009 */
6010 if (req->flags & REQ_F_IO_DRAIN) {
6011 head->flags |= REQ_F_IO_DRAIN;
6012 ctx->drain_next = 1;
6013 }
6014 if (io_alloc_async_ctx(req))
6015 return -EAGAIN;
6016
6017 ret = io_req_defer_prep(req, sqe);
6018 if (ret) {
6019 /* fail even hard links since we don't submit */
6020 head->flags |= REQ_F_FAIL_LINK;
6021 return ret;
6022 }
6023 trace_io_uring_link(ctx, req, head);
6024 list_add_tail(&req->link_list, &head->link_list);
6025
6026 /* last request of a link, enqueue the link */
6027 if (!(req->flags & (REQ_F_LINK | REQ_F_HARDLINK))) {
6028 io_queue_link_head(head, cs);
6029 *link = NULL;
6030 }
6031 } else {
6032 if (unlikely(ctx->drain_next)) {
6033 req->flags |= REQ_F_IO_DRAIN;
6034 ctx->drain_next = 0;
6035 }
6036 if (req->flags & (REQ_F_LINK | REQ_F_HARDLINK)) {
6037 req->flags |= REQ_F_LINK_HEAD;
6038 INIT_LIST_HEAD(&req->link_list);
6039
6040 if (io_alloc_async_ctx(req))
6041 return -EAGAIN;
6042
6043 ret = io_req_defer_prep(req, sqe);
6044 if (ret)
6045 req->flags |= REQ_F_FAIL_LINK;
6046 *link = req;
6047 } else {
6048 io_queue_sqe(req, sqe, cs);
6049 }
6050 }
6051
6052 return 0;
6053 }
6054
6055 /*
6056 * Batched submission is done, ensure local IO is flushed out.
6057 */
6058 static void io_submit_state_end(struct io_submit_state *state)
6059 {
6060 if (!list_empty(&state->comp.list))
6061 io_submit_flush_completions(&state->comp);
6062 blk_finish_plug(&state->plug);
6063 io_state_file_put(state);
6064 if (state->free_reqs)
6065 kmem_cache_free_bulk(req_cachep, state->free_reqs, state->reqs);
6066 }
6067
6068 /*
6069 * Start submission side cache.
6070 */
6071 static void io_submit_state_start(struct io_submit_state *state,
6072 struct io_ring_ctx *ctx, unsigned int max_ios)
6073 {
6074 blk_start_plug(&state->plug);
6075 #ifdef CONFIG_BLOCK
6076 state->plug.nowait = true;
6077 #endif
6078 state->comp.nr = 0;
6079 INIT_LIST_HEAD(&state->comp.list);
6080 state->comp.ctx = ctx;
6081 state->free_reqs = 0;
6082 state->file = NULL;
6083 state->ios_left = max_ios;
6084 }
6085
6086 static void io_commit_sqring(struct io_ring_ctx *ctx)
6087 {
6088 struct io_rings *rings = ctx->rings;
6089
6090 /*
6091 * Ensure any loads from the SQEs are done at this point,
6092 * since once we write the new head, the application could
6093 * write new data to them.
6094 */
6095 smp_store_release(&rings->sq.head, ctx->cached_sq_head);
6096 }
6097
6098 /*
6099 * Fetch an sqe, if one is available. Note that sqe_ptr will point to memory
6100 * that is mapped by userspace. This means that care needs to be taken to
6101 * ensure that reads are stable, as we cannot rely on userspace always
6102 * being a good citizen. If members of the sqe are validated and then later
6103 * used, it's important that those reads are done through READ_ONCE() to
6104 * prevent a re-load down the line.
6105 */
6106 static const struct io_uring_sqe *io_get_sqe(struct io_ring_ctx *ctx)
6107 {
6108 u32 *sq_array = ctx->sq_array;
6109 unsigned head;
6110
6111 /*
6112 * The cached sq head (or cq tail) serves two purposes:
6113 *
6114 * 1) allows us to batch the cost of updating the user visible
6115 * head updates.
6116 * 2) allows the kernel side to track the head on its own, even
6117 * though the application is the one updating it.
6118 */
6119 head = READ_ONCE(sq_array[ctx->cached_sq_head & ctx->sq_mask]);
6120 if (likely(head < ctx->sq_entries))
6121 return &ctx->sq_sqes[head];
6122
6123 /* drop invalid entries */
6124 ctx->cached_sq_dropped++;
6125 WRITE_ONCE(ctx->rings->sq_dropped, ctx->cached_sq_dropped);
6126 return NULL;
6127 }
6128
6129 static inline void io_consume_sqe(struct io_ring_ctx *ctx)
6130 {
6131 ctx->cached_sq_head++;
6132 }
6133
6134 #define SQE_VALID_FLAGS (IOSQE_FIXED_FILE|IOSQE_IO_DRAIN|IOSQE_IO_LINK| \
6135 IOSQE_IO_HARDLINK | IOSQE_ASYNC | \
6136 IOSQE_BUFFER_SELECT)
6137
6138 static int io_init_req(struct io_ring_ctx *ctx, struct io_kiocb *req,
6139 const struct io_uring_sqe *sqe,
6140 struct io_submit_state *state)
6141 {
6142 unsigned int sqe_flags;
6143 int id;
6144
6145 /*
6146 * All io need record the previous position, if LINK vs DARIN,
6147 * it can be used to mark the position of the first IO in the
6148 * link list.
6149 */
6150 req->sequence = ctx->cached_sq_head - ctx->cached_sq_dropped;
6151 req->opcode = READ_ONCE(sqe->opcode);
6152 req->user_data = READ_ONCE(sqe->user_data);
6153 req->io = NULL;
6154 req->file = NULL;
6155 req->ctx = ctx;
6156 req->flags = 0;
6157 /* one is dropped after submission, the other at completion */
6158 refcount_set(&req->refs, 2);
6159 req->task = current;
6160 req->result = 0;
6161
6162 if (unlikely(req->opcode >= IORING_OP_LAST))
6163 return -EINVAL;
6164
6165 if (unlikely(io_sq_thread_acquire_mm(ctx, req)))
6166 return -EFAULT;
6167
6168 sqe_flags = READ_ONCE(sqe->flags);
6169 /* enforce forwards compatibility on users */
6170 if (unlikely(sqe_flags & ~SQE_VALID_FLAGS))
6171 return -EINVAL;
6172
6173 if ((sqe_flags & IOSQE_BUFFER_SELECT) &&
6174 !io_op_defs[req->opcode].buffer_select)
6175 return -EOPNOTSUPP;
6176
6177 id = READ_ONCE(sqe->personality);
6178 if (id) {
6179 io_req_init_async(req);
6180 req->work.creds = idr_find(&ctx->personality_idr, id);
6181 if (unlikely(!req->work.creds))
6182 return -EINVAL;
6183 get_cred(req->work.creds);
6184 }
6185
6186 /* same numerical values with corresponding REQ_F_*, safe to copy */
6187 req->flags |= sqe_flags;
6188
6189 if (!io_op_defs[req->opcode].needs_file)
6190 return 0;
6191
6192 return io_req_set_file(state, req, READ_ONCE(sqe->fd));
6193 }
6194
6195 static int io_submit_sqes(struct io_ring_ctx *ctx, unsigned int nr,
6196 struct file *ring_file, int ring_fd)
6197 {
6198 struct io_submit_state state;
6199 struct io_kiocb *link = NULL;
6200 int i, submitted = 0;
6201
6202 /* if we have a backlog and couldn't flush it all, return BUSY */
6203 if (test_bit(0, &ctx->sq_check_overflow)) {
6204 if (!list_empty(&ctx->cq_overflow_list) &&
6205 !io_cqring_overflow_flush(ctx, false))
6206 return -EBUSY;
6207 }
6208
6209 /* make sure SQ entry isn't read before tail */
6210 nr = min3(nr, ctx->sq_entries, io_sqring_entries(ctx));
6211
6212 if (!percpu_ref_tryget_many(&ctx->refs, nr))
6213 return -EAGAIN;
6214
6215 io_submit_state_start(&state, ctx, nr);
6216
6217 ctx->ring_fd = ring_fd;
6218 ctx->ring_file = ring_file;
6219
6220 for (i = 0; i < nr; i++) {
6221 const struct io_uring_sqe *sqe;
6222 struct io_kiocb *req;
6223 int err;
6224
6225 sqe = io_get_sqe(ctx);
6226 if (unlikely(!sqe)) {
6227 io_consume_sqe(ctx);
6228 break;
6229 }
6230 req = io_alloc_req(ctx, &state);
6231 if (unlikely(!req)) {
6232 if (!submitted)
6233 submitted = -EAGAIN;
6234 break;
6235 }
6236
6237 err = io_init_req(ctx, req, sqe, &state);
6238 io_consume_sqe(ctx);
6239 /* will complete beyond this point, count as submitted */
6240 submitted++;
6241
6242 if (unlikely(err)) {
6243 fail_req:
6244 io_put_req(req);
6245 io_req_complete(req, err);
6246 break;
6247 }
6248
6249 trace_io_uring_submit_sqe(ctx, req->opcode, req->user_data,
6250 true, io_async_submit(ctx));
6251 err = io_submit_sqe(req, sqe, &link, &state.comp);
6252 if (err)
6253 goto fail_req;
6254 }
6255
6256 if (unlikely(submitted != nr)) {
6257 int ref_used = (submitted == -EAGAIN) ? 0 : submitted;
6258
6259 percpu_ref_put_many(&ctx->refs, nr - ref_used);
6260 }
6261 if (link)
6262 io_queue_link_head(link, &state.comp);
6263 io_submit_state_end(&state);
6264
6265 /* Commit SQ ring head once we've consumed and submitted all SQEs */
6266 io_commit_sqring(ctx);
6267
6268 return submitted;
6269 }
6270
6271 static int io_sq_thread(void *data)
6272 {
6273 struct io_ring_ctx *ctx = data;
6274 const struct cred *old_cred;
6275 DEFINE_WAIT(wait);
6276 unsigned long timeout;
6277 int ret = 0;
6278
6279 complete(&ctx->sq_thread_comp);
6280
6281 old_cred = override_creds(ctx->creds);
6282
6283 timeout = jiffies + ctx->sq_thread_idle;
6284 while (!kthread_should_park()) {
6285 unsigned int to_submit;
6286
6287 if (!list_empty(&ctx->poll_list)) {
6288 unsigned nr_events = 0;
6289
6290 mutex_lock(&ctx->uring_lock);
6291 if (!list_empty(&ctx->poll_list))
6292 io_iopoll_getevents(ctx, &nr_events, 0);
6293 else
6294 timeout = jiffies + ctx->sq_thread_idle;
6295 mutex_unlock(&ctx->uring_lock);
6296 }
6297
6298 to_submit = io_sqring_entries(ctx);
6299
6300 /*
6301 * If submit got -EBUSY, flag us as needing the application
6302 * to enter the kernel to reap and flush events.
6303 */
6304 if (!to_submit || ret == -EBUSY) {
6305 /*
6306 * Drop cur_mm before scheduling, we can't hold it for
6307 * long periods (or over schedule()). Do this before
6308 * adding ourselves to the waitqueue, as the unuse/drop
6309 * may sleep.
6310 */
6311 io_sq_thread_drop_mm(ctx);
6312
6313 /*
6314 * We're polling. If we're within the defined idle
6315 * period, then let us spin without work before going
6316 * to sleep. The exception is if we got EBUSY doing
6317 * more IO, we should wait for the application to
6318 * reap events and wake us up.
6319 */
6320 if (!list_empty(&ctx->poll_list) ||
6321 (!time_after(jiffies, timeout) && ret != -EBUSY &&
6322 !percpu_ref_is_dying(&ctx->refs))) {
6323 if (current->task_works)
6324 task_work_run();
6325 cond_resched();
6326 continue;
6327 }
6328
6329 prepare_to_wait(&ctx->sqo_wait, &wait,
6330 TASK_INTERRUPTIBLE);
6331
6332 /*
6333 * While doing polled IO, before going to sleep, we need
6334 * to check if there are new reqs added to poll_list, it
6335 * is because reqs may have been punted to io worker and
6336 * will be added to poll_list later, hence check the
6337 * poll_list again.
6338 */
6339 if ((ctx->flags & IORING_SETUP_IOPOLL) &&
6340 !list_empty_careful(&ctx->poll_list)) {
6341 finish_wait(&ctx->sqo_wait, &wait);
6342 continue;
6343 }
6344
6345 /* Tell userspace we may need a wakeup call */
6346 ctx->rings->sq_flags |= IORING_SQ_NEED_WAKEUP;
6347 /* make sure to read SQ tail after writing flags */
6348 smp_mb();
6349
6350 to_submit = io_sqring_entries(ctx);
6351 if (!to_submit || ret == -EBUSY) {
6352 if (kthread_should_park()) {
6353 finish_wait(&ctx->sqo_wait, &wait);
6354 break;
6355 }
6356 if (current->task_works) {
6357 task_work_run();
6358 finish_wait(&ctx->sqo_wait, &wait);
6359 continue;
6360 }
6361 if (signal_pending(current))
6362 flush_signals(current);
6363 schedule();
6364 finish_wait(&ctx->sqo_wait, &wait);
6365
6366 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6367 ret = 0;
6368 continue;
6369 }
6370 finish_wait(&ctx->sqo_wait, &wait);
6371
6372 ctx->rings->sq_flags &= ~IORING_SQ_NEED_WAKEUP;
6373 }
6374
6375 mutex_lock(&ctx->uring_lock);
6376 if (likely(!percpu_ref_is_dying(&ctx->refs)))
6377 ret = io_submit_sqes(ctx, to_submit, NULL, -1);
6378 mutex_unlock(&ctx->uring_lock);
6379 timeout = jiffies + ctx->sq_thread_idle;
6380 }
6381
6382 if (current->task_works)
6383 task_work_run();
6384
6385 io_sq_thread_drop_mm(ctx);
6386 revert_creds(old_cred);
6387
6388 kthread_parkme();
6389
6390 return 0;
6391 }
6392
6393 struct io_wait_queue {
6394 struct wait_queue_entry wq;
6395 struct io_ring_ctx *ctx;
6396 unsigned to_wait;
6397 unsigned nr_timeouts;
6398 };
6399
6400 static inline bool io_should_wake(struct io_wait_queue *iowq, bool noflush)
6401 {
6402 struct io_ring_ctx *ctx = iowq->ctx;
6403
6404 /*
6405 * Wake up if we have enough events, or if a timeout occurred since we
6406 * started waiting. For timeouts, we always want to return to userspace,
6407 * regardless of event count.
6408 */
6409 return io_cqring_events(ctx, noflush) >= iowq->to_wait ||
6410 atomic_read(&ctx->cq_timeouts) != iowq->nr_timeouts;
6411 }
6412
6413 static int io_wake_function(struct wait_queue_entry *curr, unsigned int mode,
6414 int wake_flags, void *key)
6415 {
6416 struct io_wait_queue *iowq = container_of(curr, struct io_wait_queue,
6417 wq);
6418
6419 /* use noflush == true, as we can't safely rely on locking context */
6420 if (!io_should_wake(iowq, true))
6421 return -1;
6422
6423 return autoremove_wake_function(curr, mode, wake_flags, key);
6424 }
6425
6426 /*
6427 * Wait until events become available, if we don't already have some. The
6428 * application must reap them itself, as they reside on the shared cq ring.
6429 */
6430 static int io_cqring_wait(struct io_ring_ctx *ctx, int min_events,
6431 const sigset_t __user *sig, size_t sigsz)
6432 {
6433 struct io_wait_queue iowq = {
6434 .wq = {
6435 .private = current,
6436 .func = io_wake_function,
6437 .entry = LIST_HEAD_INIT(iowq.wq.entry),
6438 },
6439 .ctx = ctx,
6440 .to_wait = min_events,
6441 };
6442 struct io_rings *rings = ctx->rings;
6443 int ret = 0;
6444
6445 do {
6446 if (io_cqring_events(ctx, false) >= min_events)
6447 return 0;
6448 if (!current->task_works)
6449 break;
6450 task_work_run();
6451 } while (1);
6452
6453 if (sig) {
6454 #ifdef CONFIG_COMPAT
6455 if (in_compat_syscall())
6456 ret = set_compat_user_sigmask((const compat_sigset_t __user *)sig,
6457 sigsz);
6458 else
6459 #endif
6460 ret = set_user_sigmask(sig, sigsz);
6461
6462 if (ret)
6463 return ret;
6464 }
6465
6466 iowq.nr_timeouts = atomic_read(&ctx->cq_timeouts);
6467 trace_io_uring_cqring_wait(ctx, min_events);
6468 do {
6469 prepare_to_wait_exclusive(&ctx->wait, &iowq.wq,
6470 TASK_INTERRUPTIBLE);
6471 if (current->task_works)
6472 task_work_run();
6473 if (io_should_wake(&iowq, false))
6474 break;
6475 schedule();
6476 if (signal_pending(current)) {
6477 ret = -EINTR;
6478 break;
6479 }
6480 } while (1);
6481 finish_wait(&ctx->wait, &iowq.wq);
6482
6483 restore_saved_sigmask_unless(ret == -EINTR);
6484
6485 return READ_ONCE(rings->cq.head) == READ_ONCE(rings->cq.tail) ? ret : 0;
6486 }
6487
6488 static void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
6489 {
6490 #if defined(CONFIG_UNIX)
6491 if (ctx->ring_sock) {
6492 struct sock *sock = ctx->ring_sock->sk;
6493 struct sk_buff *skb;
6494
6495 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
6496 kfree_skb(skb);
6497 }
6498 #else
6499 int i;
6500
6501 for (i = 0; i < ctx->nr_user_files; i++) {
6502 struct file *file;
6503
6504 file = io_file_from_index(ctx, i);
6505 if (file)
6506 fput(file);
6507 }
6508 #endif
6509 }
6510
6511 static void io_file_ref_kill(struct percpu_ref *ref)
6512 {
6513 struct fixed_file_data *data;
6514
6515 data = container_of(ref, struct fixed_file_data, refs);
6516 complete(&data->done);
6517 }
6518
6519 static int io_sqe_files_unregister(struct io_ring_ctx *ctx)
6520 {
6521 struct fixed_file_data *data = ctx->file_data;
6522 struct fixed_file_ref_node *ref_node = NULL;
6523 unsigned nr_tables, i;
6524
6525 if (!data)
6526 return -ENXIO;
6527
6528 spin_lock(&data->lock);
6529 if (!list_empty(&data->ref_list))
6530 ref_node = list_first_entry(&data->ref_list,
6531 struct fixed_file_ref_node, node);
6532 spin_unlock(&data->lock);
6533 if (ref_node)
6534 percpu_ref_kill(&ref_node->refs);
6535
6536 percpu_ref_kill(&data->refs);
6537
6538 /* wait for all refs nodes to complete */
6539 flush_delayed_work(&ctx->file_put_work);
6540 wait_for_completion(&data->done);
6541
6542 __io_sqe_files_unregister(ctx);
6543 nr_tables = DIV_ROUND_UP(ctx->nr_user_files, IORING_MAX_FILES_TABLE);
6544 for (i = 0; i < nr_tables; i++)
6545 kfree(data->table[i].files);
6546 kfree(data->table);
6547 percpu_ref_exit(&data->refs);
6548 kfree(data);
6549 ctx->file_data = NULL;
6550 ctx->nr_user_files = 0;
6551 return 0;
6552 }
6553
6554 static void io_sq_thread_stop(struct io_ring_ctx *ctx)
6555 {
6556 if (ctx->sqo_thread) {
6557 wait_for_completion(&ctx->sq_thread_comp);
6558 /*
6559 * The park is a bit of a work-around, without it we get
6560 * warning spews on shutdown with SQPOLL set and affinity
6561 * set to a single CPU.
6562 */
6563 kthread_park(ctx->sqo_thread);
6564 kthread_stop(ctx->sqo_thread);
6565 ctx->sqo_thread = NULL;
6566 }
6567 }
6568
6569 static void io_finish_async(struct io_ring_ctx *ctx)
6570 {
6571 io_sq_thread_stop(ctx);
6572
6573 if (ctx->io_wq) {
6574 io_wq_destroy(ctx->io_wq);
6575 ctx->io_wq = NULL;
6576 }
6577 }
6578
6579 #if defined(CONFIG_UNIX)
6580 /*
6581 * Ensure the UNIX gc is aware of our file set, so we are certain that
6582 * the io_uring can be safely unregistered on process exit, even if we have
6583 * loops in the file referencing.
6584 */
6585 static int __io_sqe_files_scm(struct io_ring_ctx *ctx, int nr, int offset)
6586 {
6587 struct sock *sk = ctx->ring_sock->sk;
6588 struct scm_fp_list *fpl;
6589 struct sk_buff *skb;
6590 int i, nr_files;
6591
6592 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
6593 if (!fpl)
6594 return -ENOMEM;
6595
6596 skb = alloc_skb(0, GFP_KERNEL);
6597 if (!skb) {
6598 kfree(fpl);
6599 return -ENOMEM;
6600 }
6601
6602 skb->sk = sk;
6603
6604 nr_files = 0;
6605 fpl->user = get_uid(ctx->user);
6606 for (i = 0; i < nr; i++) {
6607 struct file *file = io_file_from_index(ctx, i + offset);
6608
6609 if (!file)
6610 continue;
6611 fpl->fp[nr_files] = get_file(file);
6612 unix_inflight(fpl->user, fpl->fp[nr_files]);
6613 nr_files++;
6614 }
6615
6616 if (nr_files) {
6617 fpl->max = SCM_MAX_FD;
6618 fpl->count = nr_files;
6619 UNIXCB(skb).fp = fpl;
6620 skb->destructor = unix_destruct_scm;
6621 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
6622 skb_queue_head(&sk->sk_receive_queue, skb);
6623
6624 for (i = 0; i < nr_files; i++)
6625 fput(fpl->fp[i]);
6626 } else {
6627 kfree_skb(skb);
6628 kfree(fpl);
6629 }
6630
6631 return 0;
6632 }
6633
6634 /*
6635 * If UNIX sockets are enabled, fd passing can cause a reference cycle which
6636 * causes regular reference counting to break down. We rely on the UNIX
6637 * garbage collection to take care of this problem for us.
6638 */
6639 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
6640 {
6641 unsigned left, total;
6642 int ret = 0;
6643
6644 total = 0;
6645 left = ctx->nr_user_files;
6646 while (left) {
6647 unsigned this_files = min_t(unsigned, left, SCM_MAX_FD);
6648
6649 ret = __io_sqe_files_scm(ctx, this_files, total);
6650 if (ret)
6651 break;
6652 left -= this_files;
6653 total += this_files;
6654 }
6655
6656 if (!ret)
6657 return 0;
6658
6659 while (total < ctx->nr_user_files) {
6660 struct file *file = io_file_from_index(ctx, total);
6661
6662 if (file)
6663 fput(file);
6664 total++;
6665 }
6666
6667 return ret;
6668 }
6669 #else
6670 static int io_sqe_files_scm(struct io_ring_ctx *ctx)
6671 {
6672 return 0;
6673 }
6674 #endif
6675
6676 static int io_sqe_alloc_file_tables(struct io_ring_ctx *ctx, unsigned nr_tables,
6677 unsigned nr_files)
6678 {
6679 int i;
6680
6681 for (i = 0; i < nr_tables; i++) {
6682 struct fixed_file_table *table = &ctx->file_data->table[i];
6683 unsigned this_files;
6684
6685 this_files = min(nr_files, IORING_MAX_FILES_TABLE);
6686 table->files = kcalloc(this_files, sizeof(struct file *),
6687 GFP_KERNEL);
6688 if (!table->files)
6689 break;
6690 nr_files -= this_files;
6691 }
6692
6693 if (i == nr_tables)
6694 return 0;
6695
6696 for (i = 0; i < nr_tables; i++) {
6697 struct fixed_file_table *table = &ctx->file_data->table[i];
6698 kfree(table->files);
6699 }
6700 return 1;
6701 }
6702
6703 static void io_ring_file_put(struct io_ring_ctx *ctx, struct file *file)
6704 {
6705 #if defined(CONFIG_UNIX)
6706 struct sock *sock = ctx->ring_sock->sk;
6707 struct sk_buff_head list, *head = &sock->sk_receive_queue;
6708 struct sk_buff *skb;
6709 int i;
6710
6711 __skb_queue_head_init(&list);
6712
6713 /*
6714 * Find the skb that holds this file in its SCM_RIGHTS. When found,
6715 * remove this entry and rearrange the file array.
6716 */
6717 skb = skb_dequeue(head);
6718 while (skb) {
6719 struct scm_fp_list *fp;
6720
6721 fp = UNIXCB(skb).fp;
6722 for (i = 0; i < fp->count; i++) {
6723 int left;
6724
6725 if (fp->fp[i] != file)
6726 continue;
6727
6728 unix_notinflight(fp->user, fp->fp[i]);
6729 left = fp->count - 1 - i;
6730 if (left) {
6731 memmove(&fp->fp[i], &fp->fp[i + 1],
6732 left * sizeof(struct file *));
6733 }
6734 fp->count--;
6735 if (!fp->count) {
6736 kfree_skb(skb);
6737 skb = NULL;
6738 } else {
6739 __skb_queue_tail(&list, skb);
6740 }
6741 fput(file);
6742 file = NULL;
6743 break;
6744 }
6745
6746 if (!file)
6747 break;
6748
6749 __skb_queue_tail(&list, skb);
6750
6751 skb = skb_dequeue(head);
6752 }
6753
6754 if (skb_peek(&list)) {
6755 spin_lock_irq(&head->lock);
6756 while ((skb = __skb_dequeue(&list)) != NULL)
6757 __skb_queue_tail(head, skb);
6758 spin_unlock_irq(&head->lock);
6759 }
6760 #else
6761 fput(file);
6762 #endif
6763 }
6764
6765 struct io_file_put {
6766 struct list_head list;
6767 struct file *file;
6768 };
6769
6770 static void __io_file_put_work(struct fixed_file_ref_node *ref_node)
6771 {
6772 struct fixed_file_data *file_data = ref_node->file_data;
6773 struct io_ring_ctx *ctx = file_data->ctx;
6774 struct io_file_put *pfile, *tmp;
6775
6776 list_for_each_entry_safe(pfile, tmp, &ref_node->file_list, list) {
6777 list_del(&pfile->list);
6778 io_ring_file_put(ctx, pfile->file);
6779 kfree(pfile);
6780 }
6781
6782 spin_lock(&file_data->lock);
6783 list_del(&ref_node->node);
6784 spin_unlock(&file_data->lock);
6785
6786 percpu_ref_exit(&ref_node->refs);
6787 kfree(ref_node);
6788 percpu_ref_put(&file_data->refs);
6789 }
6790
6791 static void io_file_put_work(struct work_struct *work)
6792 {
6793 struct io_ring_ctx *ctx;
6794 struct llist_node *node;
6795
6796 ctx = container_of(work, struct io_ring_ctx, file_put_work.work);
6797 node = llist_del_all(&ctx->file_put_llist);
6798
6799 while (node) {
6800 struct fixed_file_ref_node *ref_node;
6801 struct llist_node *next = node->next;
6802
6803 ref_node = llist_entry(node, struct fixed_file_ref_node, llist);
6804 __io_file_put_work(ref_node);
6805 node = next;
6806 }
6807 }
6808
6809 static void io_file_data_ref_zero(struct percpu_ref *ref)
6810 {
6811 struct fixed_file_ref_node *ref_node;
6812 struct io_ring_ctx *ctx;
6813 bool first_add;
6814 int delay = HZ;
6815
6816 ref_node = container_of(ref, struct fixed_file_ref_node, refs);
6817 ctx = ref_node->file_data->ctx;
6818
6819 if (percpu_ref_is_dying(&ctx->file_data->refs))
6820 delay = 0;
6821
6822 first_add = llist_add(&ref_node->llist, &ctx->file_put_llist);
6823 if (!delay)
6824 mod_delayed_work(system_wq, &ctx->file_put_work, 0);
6825 else if (first_add)
6826 queue_delayed_work(system_wq, &ctx->file_put_work, delay);
6827 }
6828
6829 static struct fixed_file_ref_node *alloc_fixed_file_ref_node(
6830 struct io_ring_ctx *ctx)
6831 {
6832 struct fixed_file_ref_node *ref_node;
6833
6834 ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
6835 if (!ref_node)
6836 return ERR_PTR(-ENOMEM);
6837
6838 if (percpu_ref_init(&ref_node->refs, io_file_data_ref_zero,
6839 0, GFP_KERNEL)) {
6840 kfree(ref_node);
6841 return ERR_PTR(-ENOMEM);
6842 }
6843 INIT_LIST_HEAD(&ref_node->node);
6844 INIT_LIST_HEAD(&ref_node->file_list);
6845 ref_node->file_data = ctx->file_data;
6846 return ref_node;
6847 }
6848
6849 static void destroy_fixed_file_ref_node(struct fixed_file_ref_node *ref_node)
6850 {
6851 percpu_ref_exit(&ref_node->refs);
6852 kfree(ref_node);
6853 }
6854
6855 static int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
6856 unsigned nr_args)
6857 {
6858 __s32 __user *fds = (__s32 __user *) arg;
6859 unsigned nr_tables;
6860 struct file *file;
6861 int fd, ret = 0;
6862 unsigned i;
6863 struct fixed_file_ref_node *ref_node;
6864
6865 if (ctx->file_data)
6866 return -EBUSY;
6867 if (!nr_args)
6868 return -EINVAL;
6869 if (nr_args > IORING_MAX_FIXED_FILES)
6870 return -EMFILE;
6871
6872 ctx->file_data = kzalloc(sizeof(*ctx->file_data), GFP_KERNEL);
6873 if (!ctx->file_data)
6874 return -ENOMEM;
6875 ctx->file_data->ctx = ctx;
6876 init_completion(&ctx->file_data->done);
6877 INIT_LIST_HEAD(&ctx->file_data->ref_list);
6878 spin_lock_init(&ctx->file_data->lock);
6879
6880 nr_tables = DIV_ROUND_UP(nr_args, IORING_MAX_FILES_TABLE);
6881 ctx->file_data->table = kcalloc(nr_tables,
6882 sizeof(struct fixed_file_table),
6883 GFP_KERNEL);
6884 if (!ctx->file_data->table) {
6885 kfree(ctx->file_data);
6886 ctx->file_data = NULL;
6887 return -ENOMEM;
6888 }
6889
6890 if (percpu_ref_init(&ctx->file_data->refs, io_file_ref_kill,
6891 PERCPU_REF_ALLOW_REINIT, GFP_KERNEL)) {
6892 kfree(ctx->file_data->table);
6893 kfree(ctx->file_data);
6894 ctx->file_data = NULL;
6895 return -ENOMEM;
6896 }
6897
6898 if (io_sqe_alloc_file_tables(ctx, nr_tables, nr_args)) {
6899 percpu_ref_exit(&ctx->file_data->refs);
6900 kfree(ctx->file_data->table);
6901 kfree(ctx->file_data);
6902 ctx->file_data = NULL;
6903 return -ENOMEM;
6904 }
6905
6906 for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
6907 struct fixed_file_table *table;
6908 unsigned index;
6909
6910 ret = -EFAULT;
6911 if (copy_from_user(&fd, &fds[i], sizeof(fd)))
6912 break;
6913 /* allow sparse sets */
6914 if (fd == -1) {
6915 ret = 0;
6916 continue;
6917 }
6918
6919 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
6920 index = i & IORING_FILE_TABLE_MASK;
6921 file = fget(fd);
6922
6923 ret = -EBADF;
6924 if (!file)
6925 break;
6926
6927 /*
6928 * Don't allow io_uring instances to be registered. If UNIX
6929 * isn't enabled, then this causes a reference cycle and this
6930 * instance can never get freed. If UNIX is enabled we'll
6931 * handle it just fine, but there's still no point in allowing
6932 * a ring fd as it doesn't support regular read/write anyway.
6933 */
6934 if (file->f_op == &io_uring_fops) {
6935 fput(file);
6936 break;
6937 }
6938 ret = 0;
6939 table->files[index] = file;
6940 }
6941
6942 if (ret) {
6943 for (i = 0; i < ctx->nr_user_files; i++) {
6944 file = io_file_from_index(ctx, i);
6945 if (file)
6946 fput(file);
6947 }
6948 for (i = 0; i < nr_tables; i++)
6949 kfree(ctx->file_data->table[i].files);
6950
6951 kfree(ctx->file_data->table);
6952 kfree(ctx->file_data);
6953 ctx->file_data = NULL;
6954 ctx->nr_user_files = 0;
6955 return ret;
6956 }
6957
6958 ret = io_sqe_files_scm(ctx);
6959 if (ret) {
6960 io_sqe_files_unregister(ctx);
6961 return ret;
6962 }
6963
6964 ref_node = alloc_fixed_file_ref_node(ctx);
6965 if (IS_ERR(ref_node)) {
6966 io_sqe_files_unregister(ctx);
6967 return PTR_ERR(ref_node);
6968 }
6969
6970 ctx->file_data->cur_refs = &ref_node->refs;
6971 spin_lock(&ctx->file_data->lock);
6972 list_add(&ref_node->node, &ctx->file_data->ref_list);
6973 spin_unlock(&ctx->file_data->lock);
6974 percpu_ref_get(&ctx->file_data->refs);
6975 return ret;
6976 }
6977
6978 static int io_sqe_file_register(struct io_ring_ctx *ctx, struct file *file,
6979 int index)
6980 {
6981 #if defined(CONFIG_UNIX)
6982 struct sock *sock = ctx->ring_sock->sk;
6983 struct sk_buff_head *head = &sock->sk_receive_queue;
6984 struct sk_buff *skb;
6985
6986 /*
6987 * See if we can merge this file into an existing skb SCM_RIGHTS
6988 * file set. If there's no room, fall back to allocating a new skb
6989 * and filling it in.
6990 */
6991 spin_lock_irq(&head->lock);
6992 skb = skb_peek(head);
6993 if (skb) {
6994 struct scm_fp_list *fpl = UNIXCB(skb).fp;
6995
6996 if (fpl->count < SCM_MAX_FD) {
6997 __skb_unlink(skb, head);
6998 spin_unlock_irq(&head->lock);
6999 fpl->fp[fpl->count] = get_file(file);
7000 unix_inflight(fpl->user, fpl->fp[fpl->count]);
7001 fpl->count++;
7002 spin_lock_irq(&head->lock);
7003 __skb_queue_head(head, skb);
7004 } else {
7005 skb = NULL;
7006 }
7007 }
7008 spin_unlock_irq(&head->lock);
7009
7010 if (skb) {
7011 fput(file);
7012 return 0;
7013 }
7014
7015 return __io_sqe_files_scm(ctx, 1, index);
7016 #else
7017 return 0;
7018 #endif
7019 }
7020
7021 static int io_queue_file_removal(struct fixed_file_data *data,
7022 struct file *file)
7023 {
7024 struct io_file_put *pfile;
7025 struct percpu_ref *refs = data->cur_refs;
7026 struct fixed_file_ref_node *ref_node;
7027
7028 pfile = kzalloc(sizeof(*pfile), GFP_KERNEL);
7029 if (!pfile)
7030 return -ENOMEM;
7031
7032 ref_node = container_of(refs, struct fixed_file_ref_node, refs);
7033 pfile->file = file;
7034 list_add(&pfile->list, &ref_node->file_list);
7035
7036 return 0;
7037 }
7038
7039 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
7040 struct io_uring_files_update *up,
7041 unsigned nr_args)
7042 {
7043 struct fixed_file_data *data = ctx->file_data;
7044 struct fixed_file_ref_node *ref_node;
7045 struct file *file;
7046 __s32 __user *fds;
7047 int fd, i, err;
7048 __u32 done;
7049 bool needs_switch = false;
7050
7051 if (check_add_overflow(up->offset, nr_args, &done))
7052 return -EOVERFLOW;
7053 if (done > ctx->nr_user_files)
7054 return -EINVAL;
7055
7056 ref_node = alloc_fixed_file_ref_node(ctx);
7057 if (IS_ERR(ref_node))
7058 return PTR_ERR(ref_node);
7059
7060 done = 0;
7061 fds = u64_to_user_ptr(up->fds);
7062 while (nr_args) {
7063 struct fixed_file_table *table;
7064 unsigned index;
7065
7066 err = 0;
7067 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
7068 err = -EFAULT;
7069 break;
7070 }
7071 i = array_index_nospec(up->offset, ctx->nr_user_files);
7072 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
7073 index = i & IORING_FILE_TABLE_MASK;
7074 if (table->files[index]) {
7075 file = io_file_from_index(ctx, index);
7076 err = io_queue_file_removal(data, file);
7077 if (err)
7078 break;
7079 table->files[index] = NULL;
7080 needs_switch = true;
7081 }
7082 if (fd != -1) {
7083 file = fget(fd);
7084 if (!file) {
7085 err = -EBADF;
7086 break;
7087 }
7088 /*
7089 * Don't allow io_uring instances to be registered. If
7090 * UNIX isn't enabled, then this causes a reference
7091 * cycle and this instance can never get freed. If UNIX
7092 * is enabled we'll handle it just fine, but there's
7093 * still no point in allowing a ring fd as it doesn't
7094 * support regular read/write anyway.
7095 */
7096 if (file->f_op == &io_uring_fops) {
7097 fput(file);
7098 err = -EBADF;
7099 break;
7100 }
7101 table->files[index] = file;
7102 err = io_sqe_file_register(ctx, file, i);
7103 if (err)
7104 break;
7105 }
7106 nr_args--;
7107 done++;
7108 up->offset++;
7109 }
7110
7111 if (needs_switch) {
7112 percpu_ref_kill(data->cur_refs);
7113 spin_lock(&data->lock);
7114 list_add(&ref_node->node, &data->ref_list);
7115 data->cur_refs = &ref_node->refs;
7116 spin_unlock(&data->lock);
7117 percpu_ref_get(&ctx->file_data->refs);
7118 } else
7119 destroy_fixed_file_ref_node(ref_node);
7120
7121 return done ? done : err;
7122 }
7123
7124 static int io_sqe_files_update(struct io_ring_ctx *ctx, void __user *arg,
7125 unsigned nr_args)
7126 {
7127 struct io_uring_files_update up;
7128
7129 if (!ctx->file_data)
7130 return -ENXIO;
7131 if (!nr_args)
7132 return -EINVAL;
7133 if (copy_from_user(&up, arg, sizeof(up)))
7134 return -EFAULT;
7135 if (up.resv)
7136 return -EINVAL;
7137
7138 return __io_sqe_files_update(ctx, &up, nr_args);
7139 }
7140
7141 static void io_free_work(struct io_wq_work *work)
7142 {
7143 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7144
7145 /* Consider that io_steal_work() relies on this ref */
7146 io_put_req(req);
7147 }
7148
7149 static int io_init_wq_offload(struct io_ring_ctx *ctx,
7150 struct io_uring_params *p)
7151 {
7152 struct io_wq_data data;
7153 struct fd f;
7154 struct io_ring_ctx *ctx_attach;
7155 unsigned int concurrency;
7156 int ret = 0;
7157
7158 data.user = ctx->user;
7159 data.free_work = io_free_work;
7160 data.do_work = io_wq_submit_work;
7161
7162 if (!(p->flags & IORING_SETUP_ATTACH_WQ)) {
7163 /* Do QD, or 4 * CPUS, whatever is smallest */
7164 concurrency = min(ctx->sq_entries, 4 * num_online_cpus());
7165
7166 ctx->io_wq = io_wq_create(concurrency, &data);
7167 if (IS_ERR(ctx->io_wq)) {
7168 ret = PTR_ERR(ctx->io_wq);
7169 ctx->io_wq = NULL;
7170 }
7171 return ret;
7172 }
7173
7174 f = fdget(p->wq_fd);
7175 if (!f.file)
7176 return -EBADF;
7177
7178 if (f.file->f_op != &io_uring_fops) {
7179 ret = -EINVAL;
7180 goto out_fput;
7181 }
7182
7183 ctx_attach = f.file->private_data;
7184 /* @io_wq is protected by holding the fd */
7185 if (!io_wq_get(ctx_attach->io_wq, &data)) {
7186 ret = -EINVAL;
7187 goto out_fput;
7188 }
7189
7190 ctx->io_wq = ctx_attach->io_wq;
7191 out_fput:
7192 fdput(f);
7193 return ret;
7194 }
7195
7196 static int io_sq_offload_start(struct io_ring_ctx *ctx,
7197 struct io_uring_params *p)
7198 {
7199 int ret;
7200
7201 mmgrab(current->mm);
7202 ctx->sqo_mm = current->mm;
7203
7204 if (ctx->flags & IORING_SETUP_SQPOLL) {
7205 ret = -EPERM;
7206 if (!capable(CAP_SYS_ADMIN))
7207 goto err;
7208
7209 ctx->sq_thread_idle = msecs_to_jiffies(p->sq_thread_idle);
7210 if (!ctx->sq_thread_idle)
7211 ctx->sq_thread_idle = HZ;
7212
7213 if (p->flags & IORING_SETUP_SQ_AFF) {
7214 int cpu = p->sq_thread_cpu;
7215
7216 ret = -EINVAL;
7217 if (cpu >= nr_cpu_ids)
7218 goto err;
7219 if (!cpu_online(cpu))
7220 goto err;
7221
7222 ctx->sqo_thread = kthread_create_on_cpu(io_sq_thread,
7223 ctx, cpu,
7224 "io_uring-sq");
7225 } else {
7226 ctx->sqo_thread = kthread_create(io_sq_thread, ctx,
7227 "io_uring-sq");
7228 }
7229 if (IS_ERR(ctx->sqo_thread)) {
7230 ret = PTR_ERR(ctx->sqo_thread);
7231 ctx->sqo_thread = NULL;
7232 goto err;
7233 }
7234 wake_up_process(ctx->sqo_thread);
7235 } else if (p->flags & IORING_SETUP_SQ_AFF) {
7236 /* Can't have SQ_AFF without SQPOLL */
7237 ret = -EINVAL;
7238 goto err;
7239 }
7240
7241 ret = io_init_wq_offload(ctx, p);
7242 if (ret)
7243 goto err;
7244
7245 return 0;
7246 err:
7247 io_finish_async(ctx);
7248 mmdrop(ctx->sqo_mm);
7249 ctx->sqo_mm = NULL;
7250 return ret;
7251 }
7252
7253 static inline void __io_unaccount_mem(struct user_struct *user,
7254 unsigned long nr_pages)
7255 {
7256 atomic_long_sub(nr_pages, &user->locked_vm);
7257 }
7258
7259 static inline int __io_account_mem(struct user_struct *user,
7260 unsigned long nr_pages)
7261 {
7262 unsigned long page_limit, cur_pages, new_pages;
7263
7264 /* Don't allow more pages than we can safely lock */
7265 page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
7266
7267 do {
7268 cur_pages = atomic_long_read(&user->locked_vm);
7269 new_pages = cur_pages + nr_pages;
7270 if (new_pages > page_limit)
7271 return -ENOMEM;
7272 } while (atomic_long_cmpxchg(&user->locked_vm, cur_pages,
7273 new_pages) != cur_pages);
7274
7275 return 0;
7276 }
7277
7278 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7279 enum io_mem_account acct)
7280 {
7281 if (ctx->limit_mem)
7282 __io_unaccount_mem(ctx->user, nr_pages);
7283
7284 if (ctx->sqo_mm) {
7285 if (acct == ACCT_LOCKED)
7286 ctx->sqo_mm->locked_vm -= nr_pages;
7287 else if (acct == ACCT_PINNED)
7288 atomic64_sub(nr_pages, &ctx->sqo_mm->pinned_vm);
7289 }
7290 }
7291
7292 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages,
7293 enum io_mem_account acct)
7294 {
7295 int ret;
7296
7297 if (ctx->limit_mem) {
7298 ret = __io_account_mem(ctx->user, nr_pages);
7299 if (ret)
7300 return ret;
7301 }
7302
7303 if (ctx->sqo_mm) {
7304 if (acct == ACCT_LOCKED)
7305 ctx->sqo_mm->locked_vm += nr_pages;
7306 else if (acct == ACCT_PINNED)
7307 atomic64_add(nr_pages, &ctx->sqo_mm->pinned_vm);
7308 }
7309
7310 return 0;
7311 }
7312
7313 static void io_mem_free(void *ptr)
7314 {
7315 struct page *page;
7316
7317 if (!ptr)
7318 return;
7319
7320 page = virt_to_head_page(ptr);
7321 if (put_page_testzero(page))
7322 free_compound_page(page);
7323 }
7324
7325 static void *io_mem_alloc(size_t size)
7326 {
7327 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | __GFP_NOWARN | __GFP_COMP |
7328 __GFP_NORETRY;
7329
7330 return (void *) __get_free_pages(gfp_flags, get_order(size));
7331 }
7332
7333 static unsigned long rings_size(unsigned sq_entries, unsigned cq_entries,
7334 size_t *sq_offset)
7335 {
7336 struct io_rings *rings;
7337 size_t off, sq_array_size;
7338
7339 off = struct_size(rings, cqes, cq_entries);
7340 if (off == SIZE_MAX)
7341 return SIZE_MAX;
7342
7343 #ifdef CONFIG_SMP
7344 off = ALIGN(off, SMP_CACHE_BYTES);
7345 if (off == 0)
7346 return SIZE_MAX;
7347 #endif
7348
7349 sq_array_size = array_size(sizeof(u32), sq_entries);
7350 if (sq_array_size == SIZE_MAX)
7351 return SIZE_MAX;
7352
7353 if (check_add_overflow(off, sq_array_size, &off))
7354 return SIZE_MAX;
7355
7356 if (sq_offset)
7357 *sq_offset = off;
7358
7359 return off;
7360 }
7361
7362 static unsigned long ring_pages(unsigned sq_entries, unsigned cq_entries)
7363 {
7364 size_t pages;
7365
7366 pages = (size_t)1 << get_order(
7367 rings_size(sq_entries, cq_entries, NULL));
7368 pages += (size_t)1 << get_order(
7369 array_size(sizeof(struct io_uring_sqe), sq_entries));
7370
7371 return pages;
7372 }
7373
7374 static int io_sqe_buffer_unregister(struct io_ring_ctx *ctx)
7375 {
7376 int i, j;
7377
7378 if (!ctx->user_bufs)
7379 return -ENXIO;
7380
7381 for (i = 0; i < ctx->nr_user_bufs; i++) {
7382 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7383
7384 for (j = 0; j < imu->nr_bvecs; j++)
7385 unpin_user_page(imu->bvec[j].bv_page);
7386
7387 io_unaccount_mem(ctx, imu->nr_bvecs, ACCT_PINNED);
7388 kvfree(imu->bvec);
7389 imu->nr_bvecs = 0;
7390 }
7391
7392 kfree(ctx->user_bufs);
7393 ctx->user_bufs = NULL;
7394 ctx->nr_user_bufs = 0;
7395 return 0;
7396 }
7397
7398 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
7399 void __user *arg, unsigned index)
7400 {
7401 struct iovec __user *src;
7402
7403 #ifdef CONFIG_COMPAT
7404 if (ctx->compat) {
7405 struct compat_iovec __user *ciovs;
7406 struct compat_iovec ciov;
7407
7408 ciovs = (struct compat_iovec __user *) arg;
7409 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
7410 return -EFAULT;
7411
7412 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
7413 dst->iov_len = ciov.iov_len;
7414 return 0;
7415 }
7416 #endif
7417 src = (struct iovec __user *) arg;
7418 if (copy_from_user(dst, &src[index], sizeof(*dst)))
7419 return -EFAULT;
7420 return 0;
7421 }
7422
7423 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, void __user *arg,
7424 unsigned nr_args)
7425 {
7426 struct vm_area_struct **vmas = NULL;
7427 struct page **pages = NULL;
7428 int i, j, got_pages = 0;
7429 int ret = -EINVAL;
7430
7431 if (ctx->user_bufs)
7432 return -EBUSY;
7433 if (!nr_args || nr_args > UIO_MAXIOV)
7434 return -EINVAL;
7435
7436 ctx->user_bufs = kcalloc(nr_args, sizeof(struct io_mapped_ubuf),
7437 GFP_KERNEL);
7438 if (!ctx->user_bufs)
7439 return -ENOMEM;
7440
7441 for (i = 0; i < nr_args; i++) {
7442 struct io_mapped_ubuf *imu = &ctx->user_bufs[i];
7443 unsigned long off, start, end, ubuf;
7444 int pret, nr_pages;
7445 struct iovec iov;
7446 size_t size;
7447
7448 ret = io_copy_iov(ctx, &iov, arg, i);
7449 if (ret)
7450 goto err;
7451
7452 /*
7453 * Don't impose further limits on the size and buffer
7454 * constraints here, we'll -EINVAL later when IO is
7455 * submitted if they are wrong.
7456 */
7457 ret = -EFAULT;
7458 if (!iov.iov_base || !iov.iov_len)
7459 goto err;
7460
7461 /* arbitrary limit, but we need something */
7462 if (iov.iov_len > SZ_1G)
7463 goto err;
7464
7465 ubuf = (unsigned long) iov.iov_base;
7466 end = (ubuf + iov.iov_len + PAGE_SIZE - 1) >> PAGE_SHIFT;
7467 start = ubuf >> PAGE_SHIFT;
7468 nr_pages = end - start;
7469
7470 ret = io_account_mem(ctx, nr_pages, ACCT_PINNED);
7471 if (ret)
7472 goto err;
7473
7474 ret = 0;
7475 if (!pages || nr_pages > got_pages) {
7476 kvfree(vmas);
7477 kvfree(pages);
7478 pages = kvmalloc_array(nr_pages, sizeof(struct page *),
7479 GFP_KERNEL);
7480 vmas = kvmalloc_array(nr_pages,
7481 sizeof(struct vm_area_struct *),
7482 GFP_KERNEL);
7483 if (!pages || !vmas) {
7484 ret = -ENOMEM;
7485 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
7486 goto err;
7487 }
7488 got_pages = nr_pages;
7489 }
7490
7491 imu->bvec = kvmalloc_array(nr_pages, sizeof(struct bio_vec),
7492 GFP_KERNEL);
7493 ret = -ENOMEM;
7494 if (!imu->bvec) {
7495 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
7496 goto err;
7497 }
7498
7499 ret = 0;
7500 mmap_read_lock(current->mm);
7501 pret = pin_user_pages(ubuf, nr_pages,
7502 FOLL_WRITE | FOLL_LONGTERM,
7503 pages, vmas);
7504 if (pret == nr_pages) {
7505 /* don't support file backed memory */
7506 for (j = 0; j < nr_pages; j++) {
7507 struct vm_area_struct *vma = vmas[j];
7508
7509 if (vma->vm_file &&
7510 !is_file_hugepages(vma->vm_file)) {
7511 ret = -EOPNOTSUPP;
7512 break;
7513 }
7514 }
7515 } else {
7516 ret = pret < 0 ? pret : -EFAULT;
7517 }
7518 mmap_read_unlock(current->mm);
7519 if (ret) {
7520 /*
7521 * if we did partial map, or found file backed vmas,
7522 * release any pages we did get
7523 */
7524 if (pret > 0)
7525 unpin_user_pages(pages, pret);
7526 io_unaccount_mem(ctx, nr_pages, ACCT_PINNED);
7527 kvfree(imu->bvec);
7528 goto err;
7529 }
7530
7531 off = ubuf & ~PAGE_MASK;
7532 size = iov.iov_len;
7533 for (j = 0; j < nr_pages; j++) {
7534 size_t vec_len;
7535
7536 vec_len = min_t(size_t, size, PAGE_SIZE - off);
7537 imu->bvec[j].bv_page = pages[j];
7538 imu->bvec[j].bv_len = vec_len;
7539 imu->bvec[j].bv_offset = off;
7540 off = 0;
7541 size -= vec_len;
7542 }
7543 /* store original address for later verification */
7544 imu->ubuf = ubuf;
7545 imu->len = iov.iov_len;
7546 imu->nr_bvecs = nr_pages;
7547
7548 ctx->nr_user_bufs++;
7549 }
7550 kvfree(pages);
7551 kvfree(vmas);
7552 return 0;
7553 err:
7554 kvfree(pages);
7555 kvfree(vmas);
7556 io_sqe_buffer_unregister(ctx);
7557 return ret;
7558 }
7559
7560 static int io_eventfd_register(struct io_ring_ctx *ctx, void __user *arg)
7561 {
7562 __s32 __user *fds = arg;
7563 int fd;
7564
7565 if (ctx->cq_ev_fd)
7566 return -EBUSY;
7567
7568 if (copy_from_user(&fd, fds, sizeof(*fds)))
7569 return -EFAULT;
7570
7571 ctx->cq_ev_fd = eventfd_ctx_fdget(fd);
7572 if (IS_ERR(ctx->cq_ev_fd)) {
7573 int ret = PTR_ERR(ctx->cq_ev_fd);
7574 ctx->cq_ev_fd = NULL;
7575 return ret;
7576 }
7577
7578 return 0;
7579 }
7580
7581 static int io_eventfd_unregister(struct io_ring_ctx *ctx)
7582 {
7583 if (ctx->cq_ev_fd) {
7584 eventfd_ctx_put(ctx->cq_ev_fd);
7585 ctx->cq_ev_fd = NULL;
7586 return 0;
7587 }
7588
7589 return -ENXIO;
7590 }
7591
7592 static int __io_destroy_buffers(int id, void *p, void *data)
7593 {
7594 struct io_ring_ctx *ctx = data;
7595 struct io_buffer *buf = p;
7596
7597 __io_remove_buffers(ctx, buf, id, -1U);
7598 return 0;
7599 }
7600
7601 static void io_destroy_buffers(struct io_ring_ctx *ctx)
7602 {
7603 idr_for_each(&ctx->io_buffer_idr, __io_destroy_buffers, ctx);
7604 idr_destroy(&ctx->io_buffer_idr);
7605 }
7606
7607 static void io_ring_ctx_free(struct io_ring_ctx *ctx)
7608 {
7609 io_finish_async(ctx);
7610 if (ctx->sqo_mm) {
7611 mmdrop(ctx->sqo_mm);
7612 ctx->sqo_mm = NULL;
7613 }
7614
7615 io_iopoll_reap_events(ctx);
7616 io_sqe_buffer_unregister(ctx);
7617 io_sqe_files_unregister(ctx);
7618 io_eventfd_unregister(ctx);
7619 io_destroy_buffers(ctx);
7620 idr_destroy(&ctx->personality_idr);
7621
7622 #if defined(CONFIG_UNIX)
7623 if (ctx->ring_sock) {
7624 ctx->ring_sock->file = NULL; /* so that iput() is called */
7625 sock_release(ctx->ring_sock);
7626 }
7627 #endif
7628
7629 io_mem_free(ctx->rings);
7630 io_mem_free(ctx->sq_sqes);
7631
7632 percpu_ref_exit(&ctx->refs);
7633 io_unaccount_mem(ctx, ring_pages(ctx->sq_entries, ctx->cq_entries),
7634 ACCT_LOCKED);
7635 free_uid(ctx->user);
7636 put_cred(ctx->creds);
7637 kfree(ctx->cancel_hash);
7638 kmem_cache_free(req_cachep, ctx->fallback_req);
7639 kfree(ctx);
7640 }
7641
7642 static __poll_t io_uring_poll(struct file *file, poll_table *wait)
7643 {
7644 struct io_ring_ctx *ctx = file->private_data;
7645 __poll_t mask = 0;
7646
7647 poll_wait(file, &ctx->cq_wait, wait);
7648 /*
7649 * synchronizes with barrier from wq_has_sleeper call in
7650 * io_commit_cqring
7651 */
7652 smp_rmb();
7653 if (READ_ONCE(ctx->rings->sq.tail) - ctx->cached_sq_head !=
7654 ctx->rings->sq_ring_entries)
7655 mask |= EPOLLOUT | EPOLLWRNORM;
7656 if (io_cqring_events(ctx, false))
7657 mask |= EPOLLIN | EPOLLRDNORM;
7658
7659 return mask;
7660 }
7661
7662 static int io_uring_fasync(int fd, struct file *file, int on)
7663 {
7664 struct io_ring_ctx *ctx = file->private_data;
7665
7666 return fasync_helper(fd, file, on, &ctx->cq_fasync);
7667 }
7668
7669 static int io_remove_personalities(int id, void *p, void *data)
7670 {
7671 struct io_ring_ctx *ctx = data;
7672 const struct cred *cred;
7673
7674 cred = idr_remove(&ctx->personality_idr, id);
7675 if (cred)
7676 put_cred(cred);
7677 return 0;
7678 }
7679
7680 static void io_ring_exit_work(struct work_struct *work)
7681 {
7682 struct io_ring_ctx *ctx;
7683
7684 ctx = container_of(work, struct io_ring_ctx, exit_work);
7685 if (ctx->rings)
7686 io_cqring_overflow_flush(ctx, true);
7687
7688 /*
7689 * If we're doing polled IO and end up having requests being
7690 * submitted async (out-of-line), then completions can come in while
7691 * we're waiting for refs to drop. We need to reap these manually,
7692 * as nobody else will be looking for them.
7693 */
7694 while (!wait_for_completion_timeout(&ctx->ref_comp, HZ/20)) {
7695 io_iopoll_reap_events(ctx);
7696 if (ctx->rings)
7697 io_cqring_overflow_flush(ctx, true);
7698 }
7699 io_ring_ctx_free(ctx);
7700 }
7701
7702 static void io_ring_ctx_wait_and_kill(struct io_ring_ctx *ctx)
7703 {
7704 mutex_lock(&ctx->uring_lock);
7705 percpu_ref_kill(&ctx->refs);
7706 mutex_unlock(&ctx->uring_lock);
7707
7708 io_kill_timeouts(ctx);
7709 io_poll_remove_all(ctx);
7710
7711 if (ctx->io_wq)
7712 io_wq_cancel_all(ctx->io_wq);
7713
7714 io_iopoll_reap_events(ctx);
7715 /* if we failed setting up the ctx, we might not have any rings */
7716 if (ctx->rings)
7717 io_cqring_overflow_flush(ctx, true);
7718 idr_for_each(&ctx->personality_idr, io_remove_personalities, ctx);
7719 INIT_WORK(&ctx->exit_work, io_ring_exit_work);
7720 queue_work(system_wq, &ctx->exit_work);
7721 }
7722
7723 static int io_uring_release(struct inode *inode, struct file *file)
7724 {
7725 struct io_ring_ctx *ctx = file->private_data;
7726
7727 file->private_data = NULL;
7728 io_ring_ctx_wait_and_kill(ctx);
7729 return 0;
7730 }
7731
7732 static bool io_wq_files_match(struct io_wq_work *work, void *data)
7733 {
7734 struct files_struct *files = data;
7735
7736 return work->files == files;
7737 }
7738
7739 static void io_uring_cancel_files(struct io_ring_ctx *ctx,
7740 struct files_struct *files)
7741 {
7742 if (list_empty_careful(&ctx->inflight_list))
7743 return;
7744
7745 /* cancel all at once, should be faster than doing it one by one*/
7746 io_wq_cancel_cb(ctx->io_wq, io_wq_files_match, files, true);
7747
7748 while (!list_empty_careful(&ctx->inflight_list)) {
7749 struct io_kiocb *cancel_req = NULL, *req;
7750 DEFINE_WAIT(wait);
7751
7752 spin_lock_irq(&ctx->inflight_lock);
7753 list_for_each_entry(req, &ctx->inflight_list, inflight_entry) {
7754 if (req->work.files != files)
7755 continue;
7756 /* req is being completed, ignore */
7757 if (!refcount_inc_not_zero(&req->refs))
7758 continue;
7759 cancel_req = req;
7760 break;
7761 }
7762 if (cancel_req)
7763 prepare_to_wait(&ctx->inflight_wait, &wait,
7764 TASK_UNINTERRUPTIBLE);
7765 spin_unlock_irq(&ctx->inflight_lock);
7766
7767 /* We need to keep going until we don't find a matching req */
7768 if (!cancel_req)
7769 break;
7770
7771 if (cancel_req->flags & REQ_F_OVERFLOW) {
7772 spin_lock_irq(&ctx->completion_lock);
7773 list_del(&cancel_req->list);
7774 cancel_req->flags &= ~REQ_F_OVERFLOW;
7775 if (list_empty(&ctx->cq_overflow_list)) {
7776 clear_bit(0, &ctx->sq_check_overflow);
7777 clear_bit(0, &ctx->cq_check_overflow);
7778 }
7779 spin_unlock_irq(&ctx->completion_lock);
7780
7781 WRITE_ONCE(ctx->rings->cq_overflow,
7782 atomic_inc_return(&ctx->cached_cq_overflow));
7783
7784 /*
7785 * Put inflight ref and overflow ref. If that's
7786 * all we had, then we're done with this request.
7787 */
7788 if (refcount_sub_and_test(2, &cancel_req->refs)) {
7789 io_free_req(cancel_req);
7790 finish_wait(&ctx->inflight_wait, &wait);
7791 continue;
7792 }
7793 } else {
7794 io_wq_cancel_work(ctx->io_wq, &cancel_req->work);
7795 io_put_req(cancel_req);
7796 }
7797
7798 schedule();
7799 finish_wait(&ctx->inflight_wait, &wait);
7800 }
7801 }
7802
7803 static bool io_cancel_task_cb(struct io_wq_work *work, void *data)
7804 {
7805 struct io_kiocb *req = container_of(work, struct io_kiocb, work);
7806 struct task_struct *task = data;
7807
7808 return req->task == task;
7809 }
7810
7811 static int io_uring_flush(struct file *file, void *data)
7812 {
7813 struct io_ring_ctx *ctx = file->private_data;
7814
7815 io_uring_cancel_files(ctx, data);
7816
7817 /*
7818 * If the task is going away, cancel work it may have pending
7819 */
7820 if (fatal_signal_pending(current) || (current->flags & PF_EXITING))
7821 io_wq_cancel_cb(ctx->io_wq, io_cancel_task_cb, current, true);
7822
7823 return 0;
7824 }
7825
7826 static void *io_uring_validate_mmap_request(struct file *file,
7827 loff_t pgoff, size_t sz)
7828 {
7829 struct io_ring_ctx *ctx = file->private_data;
7830 loff_t offset = pgoff << PAGE_SHIFT;
7831 struct page *page;
7832 void *ptr;
7833
7834 switch (offset) {
7835 case IORING_OFF_SQ_RING:
7836 case IORING_OFF_CQ_RING:
7837 ptr = ctx->rings;
7838 break;
7839 case IORING_OFF_SQES:
7840 ptr = ctx->sq_sqes;
7841 break;
7842 default:
7843 return ERR_PTR(-EINVAL);
7844 }
7845
7846 page = virt_to_head_page(ptr);
7847 if (sz > page_size(page))
7848 return ERR_PTR(-EINVAL);
7849
7850 return ptr;
7851 }
7852
7853 #ifdef CONFIG_MMU
7854
7855 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
7856 {
7857 size_t sz = vma->vm_end - vma->vm_start;
7858 unsigned long pfn;
7859 void *ptr;
7860
7861 ptr = io_uring_validate_mmap_request(file, vma->vm_pgoff, sz);
7862 if (IS_ERR(ptr))
7863 return PTR_ERR(ptr);
7864
7865 pfn = virt_to_phys(ptr) >> PAGE_SHIFT;
7866 return remap_pfn_range(vma, vma->vm_start, pfn, sz, vma->vm_page_prot);
7867 }
7868
7869 #else /* !CONFIG_MMU */
7870
7871 static int io_uring_mmap(struct file *file, struct vm_area_struct *vma)
7872 {
7873 return vma->vm_flags & (VM_SHARED | VM_MAYSHARE) ? 0 : -EINVAL;
7874 }
7875
7876 static unsigned int io_uring_nommu_mmap_capabilities(struct file *file)
7877 {
7878 return NOMMU_MAP_DIRECT | NOMMU_MAP_READ | NOMMU_MAP_WRITE;
7879 }
7880
7881 static unsigned long io_uring_nommu_get_unmapped_area(struct file *file,
7882 unsigned long addr, unsigned long len,
7883 unsigned long pgoff, unsigned long flags)
7884 {
7885 void *ptr;
7886
7887 ptr = io_uring_validate_mmap_request(file, pgoff, len);
7888 if (IS_ERR(ptr))
7889 return PTR_ERR(ptr);
7890
7891 return (unsigned long) ptr;
7892 }
7893
7894 #endif /* !CONFIG_MMU */
7895
7896 SYSCALL_DEFINE6(io_uring_enter, unsigned int, fd, u32, to_submit,
7897 u32, min_complete, u32, flags, const sigset_t __user *, sig,
7898 size_t, sigsz)
7899 {
7900 struct io_ring_ctx *ctx;
7901 long ret = -EBADF;
7902 int submitted = 0;
7903 struct fd f;
7904
7905 if (current->task_works)
7906 task_work_run();
7907
7908 if (flags & ~(IORING_ENTER_GETEVENTS | IORING_ENTER_SQ_WAKEUP))
7909 return -EINVAL;
7910
7911 f = fdget(fd);
7912 if (!f.file)
7913 return -EBADF;
7914
7915 ret = -EOPNOTSUPP;
7916 if (f.file->f_op != &io_uring_fops)
7917 goto out_fput;
7918
7919 ret = -ENXIO;
7920 ctx = f.file->private_data;
7921 if (!percpu_ref_tryget(&ctx->refs))
7922 goto out_fput;
7923
7924 /*
7925 * For SQ polling, the thread will do all submissions and completions.
7926 * Just return the requested submit count, and wake the thread if
7927 * we were asked to.
7928 */
7929 ret = 0;
7930 if (ctx->flags & IORING_SETUP_SQPOLL) {
7931 if (!list_empty_careful(&ctx->cq_overflow_list))
7932 io_cqring_overflow_flush(ctx, false);
7933 if (flags & IORING_ENTER_SQ_WAKEUP)
7934 wake_up(&ctx->sqo_wait);
7935 submitted = to_submit;
7936 } else if (to_submit) {
7937 mutex_lock(&ctx->uring_lock);
7938 submitted = io_submit_sqes(ctx, to_submit, f.file, fd);
7939 mutex_unlock(&ctx->uring_lock);
7940
7941 if (submitted != to_submit)
7942 goto out;
7943 }
7944 if (flags & IORING_ENTER_GETEVENTS) {
7945 unsigned nr_events = 0;
7946
7947 min_complete = min(min_complete, ctx->cq_entries);
7948
7949 /*
7950 * When SETUP_IOPOLL and SETUP_SQPOLL are both enabled, user
7951 * space applications don't need to do io completion events
7952 * polling again, they can rely on io_sq_thread to do polling
7953 * work, which can reduce cpu usage and uring_lock contention.
7954 */
7955 if (ctx->flags & IORING_SETUP_IOPOLL &&
7956 !(ctx->flags & IORING_SETUP_SQPOLL)) {
7957 ret = io_iopoll_check(ctx, &nr_events, min_complete);
7958 } else {
7959 ret = io_cqring_wait(ctx, min_complete, sig, sigsz);
7960 }
7961 }
7962
7963 out:
7964 percpu_ref_put(&ctx->refs);
7965 out_fput:
7966 fdput(f);
7967 return submitted ? submitted : ret;
7968 }
7969
7970 #ifdef CONFIG_PROC_FS
7971 static int io_uring_show_cred(int id, void *p, void *data)
7972 {
7973 const struct cred *cred = p;
7974 struct seq_file *m = data;
7975 struct user_namespace *uns = seq_user_ns(m);
7976 struct group_info *gi;
7977 kernel_cap_t cap;
7978 unsigned __capi;
7979 int g;
7980
7981 seq_printf(m, "%5d\n", id);
7982 seq_put_decimal_ull(m, "\tUid:\t", from_kuid_munged(uns, cred->uid));
7983 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->euid));
7984 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->suid));
7985 seq_put_decimal_ull(m, "\t\t", from_kuid_munged(uns, cred->fsuid));
7986 seq_put_decimal_ull(m, "\n\tGid:\t", from_kgid_munged(uns, cred->gid));
7987 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->egid));
7988 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->sgid));
7989 seq_put_decimal_ull(m, "\t\t", from_kgid_munged(uns, cred->fsgid));
7990 seq_puts(m, "\n\tGroups:\t");
7991 gi = cred->group_info;
7992 for (g = 0; g < gi->ngroups; g++) {
7993 seq_put_decimal_ull(m, g ? " " : "",
7994 from_kgid_munged(uns, gi->gid[g]));
7995 }
7996 seq_puts(m, "\n\tCapEff:\t");
7997 cap = cred->cap_effective;
7998 CAP_FOR_EACH_U32(__capi)
7999 seq_put_hex_ll(m, NULL, cap.cap[CAP_LAST_U32 - __capi], 8);
8000 seq_putc(m, '\n');
8001 return 0;
8002 }
8003
8004 static void __io_uring_show_fdinfo(struct io_ring_ctx *ctx, struct seq_file *m)
8005 {
8006 int i;
8007
8008 mutex_lock(&ctx->uring_lock);
8009 seq_printf(m, "UserFiles:\t%u\n", ctx->nr_user_files);
8010 for (i = 0; i < ctx->nr_user_files; i++) {
8011 struct fixed_file_table *table;
8012 struct file *f;
8013
8014 table = &ctx->file_data->table[i >> IORING_FILE_TABLE_SHIFT];
8015 f = table->files[i & IORING_FILE_TABLE_MASK];
8016 if (f)
8017 seq_printf(m, "%5u: %s\n", i, file_dentry(f)->d_iname);
8018 else
8019 seq_printf(m, "%5u: <none>\n", i);
8020 }
8021 seq_printf(m, "UserBufs:\t%u\n", ctx->nr_user_bufs);
8022 for (i = 0; i < ctx->nr_user_bufs; i++) {
8023 struct io_mapped_ubuf *buf = &ctx->user_bufs[i];
8024
8025 seq_printf(m, "%5u: 0x%llx/%u\n", i, buf->ubuf,
8026 (unsigned int) buf->len);
8027 }
8028 if (!idr_is_empty(&ctx->personality_idr)) {
8029 seq_printf(m, "Personalities:\n");
8030 idr_for_each(&ctx->personality_idr, io_uring_show_cred, m);
8031 }
8032 seq_printf(m, "PollList:\n");
8033 spin_lock_irq(&ctx->completion_lock);
8034 for (i = 0; i < (1U << ctx->cancel_hash_bits); i++) {
8035 struct hlist_head *list = &ctx->cancel_hash[i];
8036 struct io_kiocb *req;
8037
8038 hlist_for_each_entry(req, list, hash_node)
8039 seq_printf(m, " op=%d, task_works=%d\n", req->opcode,
8040 req->task->task_works != NULL);
8041 }
8042 spin_unlock_irq(&ctx->completion_lock);
8043 mutex_unlock(&ctx->uring_lock);
8044 }
8045
8046 static void io_uring_show_fdinfo(struct seq_file *m, struct file *f)
8047 {
8048 struct io_ring_ctx *ctx = f->private_data;
8049
8050 if (percpu_ref_tryget(&ctx->refs)) {
8051 __io_uring_show_fdinfo(ctx, m);
8052 percpu_ref_put(&ctx->refs);
8053 }
8054 }
8055 #endif
8056
8057 static const struct file_operations io_uring_fops = {
8058 .release = io_uring_release,
8059 .flush = io_uring_flush,
8060 .mmap = io_uring_mmap,
8061 #ifndef CONFIG_MMU
8062 .get_unmapped_area = io_uring_nommu_get_unmapped_area,
8063 .mmap_capabilities = io_uring_nommu_mmap_capabilities,
8064 #endif
8065 .poll = io_uring_poll,
8066 .fasync = io_uring_fasync,
8067 #ifdef CONFIG_PROC_FS
8068 .show_fdinfo = io_uring_show_fdinfo,
8069 #endif
8070 };
8071
8072 static int io_allocate_scq_urings(struct io_ring_ctx *ctx,
8073 struct io_uring_params *p)
8074 {
8075 struct io_rings *rings;
8076 size_t size, sq_array_offset;
8077
8078 size = rings_size(p->sq_entries, p->cq_entries, &sq_array_offset);
8079 if (size == SIZE_MAX)
8080 return -EOVERFLOW;
8081
8082 rings = io_mem_alloc(size);
8083 if (!rings)
8084 return -ENOMEM;
8085
8086 ctx->rings = rings;
8087 ctx->sq_array = (u32 *)((char *)rings + sq_array_offset);
8088 rings->sq_ring_mask = p->sq_entries - 1;
8089 rings->cq_ring_mask = p->cq_entries - 1;
8090 rings->sq_ring_entries = p->sq_entries;
8091 rings->cq_ring_entries = p->cq_entries;
8092 ctx->sq_mask = rings->sq_ring_mask;
8093 ctx->cq_mask = rings->cq_ring_mask;
8094 ctx->sq_entries = rings->sq_ring_entries;
8095 ctx->cq_entries = rings->cq_ring_entries;
8096
8097 size = array_size(sizeof(struct io_uring_sqe), p->sq_entries);
8098 if (size == SIZE_MAX) {
8099 io_mem_free(ctx->rings);
8100 ctx->rings = NULL;
8101 return -EOVERFLOW;
8102 }
8103
8104 ctx->sq_sqes = io_mem_alloc(size);
8105 if (!ctx->sq_sqes) {
8106 io_mem_free(ctx->rings);
8107 ctx->rings = NULL;
8108 return -ENOMEM;
8109 }
8110
8111 return 0;
8112 }
8113
8114 /*
8115 * Allocate an anonymous fd, this is what constitutes the application
8116 * visible backing of an io_uring instance. The application mmaps this
8117 * fd to gain access to the SQ/CQ ring details. If UNIX sockets are enabled,
8118 * we have to tie this fd to a socket for file garbage collection purposes.
8119 */
8120 static int io_uring_get_fd(struct io_ring_ctx *ctx)
8121 {
8122 struct file *file;
8123 int ret;
8124
8125 #if defined(CONFIG_UNIX)
8126 ret = sock_create_kern(&init_net, PF_UNIX, SOCK_RAW, IPPROTO_IP,
8127 &ctx->ring_sock);
8128 if (ret)
8129 return ret;
8130 #endif
8131
8132 ret = get_unused_fd_flags(O_RDWR | O_CLOEXEC);
8133 if (ret < 0)
8134 goto err;
8135
8136 file = anon_inode_getfile("[io_uring]", &io_uring_fops, ctx,
8137 O_RDWR | O_CLOEXEC);
8138 if (IS_ERR(file)) {
8139 put_unused_fd(ret);
8140 ret = PTR_ERR(file);
8141 goto err;
8142 }
8143
8144 #if defined(CONFIG_UNIX)
8145 ctx->ring_sock->file = file;
8146 #endif
8147 fd_install(ret, file);
8148 return ret;
8149 err:
8150 #if defined(CONFIG_UNIX)
8151 sock_release(ctx->ring_sock);
8152 ctx->ring_sock = NULL;
8153 #endif
8154 return ret;
8155 }
8156
8157 static int io_uring_create(unsigned entries, struct io_uring_params *p,
8158 struct io_uring_params __user *params)
8159 {
8160 struct user_struct *user = NULL;
8161 struct io_ring_ctx *ctx;
8162 bool limit_mem;
8163 int ret;
8164
8165 if (!entries)
8166 return -EINVAL;
8167 if (entries > IORING_MAX_ENTRIES) {
8168 if (!(p->flags & IORING_SETUP_CLAMP))
8169 return -EINVAL;
8170 entries = IORING_MAX_ENTRIES;
8171 }
8172
8173 /*
8174 * Use twice as many entries for the CQ ring. It's possible for the
8175 * application to drive a higher depth than the size of the SQ ring,
8176 * since the sqes are only used at submission time. This allows for
8177 * some flexibility in overcommitting a bit. If the application has
8178 * set IORING_SETUP_CQSIZE, it will have passed in the desired number
8179 * of CQ ring entries manually.
8180 */
8181 p->sq_entries = roundup_pow_of_two(entries);
8182 if (p->flags & IORING_SETUP_CQSIZE) {
8183 /*
8184 * If IORING_SETUP_CQSIZE is set, we do the same roundup
8185 * to a power-of-two, if it isn't already. We do NOT impose
8186 * any cq vs sq ring sizing.
8187 */
8188 if (p->cq_entries < p->sq_entries)
8189 return -EINVAL;
8190 if (p->cq_entries > IORING_MAX_CQ_ENTRIES) {
8191 if (!(p->flags & IORING_SETUP_CLAMP))
8192 return -EINVAL;
8193 p->cq_entries = IORING_MAX_CQ_ENTRIES;
8194 }
8195 p->cq_entries = roundup_pow_of_two(p->cq_entries);
8196 } else {
8197 p->cq_entries = 2 * p->sq_entries;
8198 }
8199
8200 user = get_uid(current_user());
8201 limit_mem = !capable(CAP_IPC_LOCK);
8202
8203 if (limit_mem) {
8204 ret = __io_account_mem(user,
8205 ring_pages(p->sq_entries, p->cq_entries));
8206 if (ret) {
8207 free_uid(user);
8208 return ret;
8209 }
8210 }
8211
8212 ctx = io_ring_ctx_alloc(p);
8213 if (!ctx) {
8214 if (limit_mem)
8215 __io_unaccount_mem(user, ring_pages(p->sq_entries,
8216 p->cq_entries));
8217 free_uid(user);
8218 return -ENOMEM;
8219 }
8220 ctx->compat = in_compat_syscall();
8221 ctx->user = user;
8222 ctx->creds = get_current_cred();
8223
8224 ret = io_allocate_scq_urings(ctx, p);
8225 if (ret)
8226 goto err;
8227
8228 ret = io_sq_offload_start(ctx, p);
8229 if (ret)
8230 goto err;
8231
8232 memset(&p->sq_off, 0, sizeof(p->sq_off));
8233 p->sq_off.head = offsetof(struct io_rings, sq.head);
8234 p->sq_off.tail = offsetof(struct io_rings, sq.tail);
8235 p->sq_off.ring_mask = offsetof(struct io_rings, sq_ring_mask);
8236 p->sq_off.ring_entries = offsetof(struct io_rings, sq_ring_entries);
8237 p->sq_off.flags = offsetof(struct io_rings, sq_flags);
8238 p->sq_off.dropped = offsetof(struct io_rings, sq_dropped);
8239 p->sq_off.array = (char *)ctx->sq_array - (char *)ctx->rings;
8240
8241 memset(&p->cq_off, 0, sizeof(p->cq_off));
8242 p->cq_off.head = offsetof(struct io_rings, cq.head);
8243 p->cq_off.tail = offsetof(struct io_rings, cq.tail);
8244 p->cq_off.ring_mask = offsetof(struct io_rings, cq_ring_mask);
8245 p->cq_off.ring_entries = offsetof(struct io_rings, cq_ring_entries);
8246 p->cq_off.overflow = offsetof(struct io_rings, cq_overflow);
8247 p->cq_off.cqes = offsetof(struct io_rings, cqes);
8248 p->cq_off.flags = offsetof(struct io_rings, cq_flags);
8249
8250 p->features = IORING_FEAT_SINGLE_MMAP | IORING_FEAT_NODROP |
8251 IORING_FEAT_SUBMIT_STABLE | IORING_FEAT_RW_CUR_POS |
8252 IORING_FEAT_CUR_PERSONALITY | IORING_FEAT_FAST_POLL |
8253 IORING_FEAT_POLL_32BITS;
8254
8255 if (copy_to_user(params, p, sizeof(*p))) {
8256 ret = -EFAULT;
8257 goto err;
8258 }
8259 /*
8260 * Install ring fd as the very last thing, so we don't risk someone
8261 * having closed it before we finish setup
8262 */
8263 ret = io_uring_get_fd(ctx);
8264 if (ret < 0)
8265 goto err;
8266
8267 trace_io_uring_create(ret, ctx, p->sq_entries, p->cq_entries, p->flags);
8268 io_account_mem(ctx, ring_pages(p->sq_entries, p->cq_entries),
8269 ACCT_LOCKED);
8270 ctx->limit_mem = limit_mem;
8271 return ret;
8272 err:
8273 io_ring_ctx_wait_and_kill(ctx);
8274 return ret;
8275 }
8276
8277 /*
8278 * Sets up an aio uring context, and returns the fd. Applications asks for a
8279 * ring size, we return the actual sq/cq ring sizes (among other things) in the
8280 * params structure passed in.
8281 */
8282 static long io_uring_setup(u32 entries, struct io_uring_params __user *params)
8283 {
8284 struct io_uring_params p;
8285 int i;
8286
8287 if (copy_from_user(&p, params, sizeof(p)))
8288 return -EFAULT;
8289 for (i = 0; i < ARRAY_SIZE(p.resv); i++) {
8290 if (p.resv[i])
8291 return -EINVAL;
8292 }
8293
8294 if (p.flags & ~(IORING_SETUP_IOPOLL | IORING_SETUP_SQPOLL |
8295 IORING_SETUP_SQ_AFF | IORING_SETUP_CQSIZE |
8296 IORING_SETUP_CLAMP | IORING_SETUP_ATTACH_WQ))
8297 return -EINVAL;
8298
8299 return io_uring_create(entries, &p, params);
8300 }
8301
8302 SYSCALL_DEFINE2(io_uring_setup, u32, entries,
8303 struct io_uring_params __user *, params)
8304 {
8305 return io_uring_setup(entries, params);
8306 }
8307
8308 static int io_probe(struct io_ring_ctx *ctx, void __user *arg, unsigned nr_args)
8309 {
8310 struct io_uring_probe *p;
8311 size_t size;
8312 int i, ret;
8313
8314 size = struct_size(p, ops, nr_args);
8315 if (size == SIZE_MAX)
8316 return -EOVERFLOW;
8317 p = kzalloc(size, GFP_KERNEL);
8318 if (!p)
8319 return -ENOMEM;
8320
8321 ret = -EFAULT;
8322 if (copy_from_user(p, arg, size))
8323 goto out;
8324 ret = -EINVAL;
8325 if (memchr_inv(p, 0, size))
8326 goto out;
8327
8328 p->last_op = IORING_OP_LAST - 1;
8329 if (nr_args > IORING_OP_LAST)
8330 nr_args = IORING_OP_LAST;
8331
8332 for (i = 0; i < nr_args; i++) {
8333 p->ops[i].op = i;
8334 if (!io_op_defs[i].not_supported)
8335 p->ops[i].flags = IO_URING_OP_SUPPORTED;
8336 }
8337 p->ops_len = i;
8338
8339 ret = 0;
8340 if (copy_to_user(arg, p, size))
8341 ret = -EFAULT;
8342 out:
8343 kfree(p);
8344 return ret;
8345 }
8346
8347 static int io_register_personality(struct io_ring_ctx *ctx)
8348 {
8349 const struct cred *creds = get_current_cred();
8350 int id;
8351
8352 id = idr_alloc_cyclic(&ctx->personality_idr, (void *) creds, 1,
8353 USHRT_MAX, GFP_KERNEL);
8354 if (id < 0)
8355 put_cred(creds);
8356 return id;
8357 }
8358
8359 static int io_unregister_personality(struct io_ring_ctx *ctx, unsigned id)
8360 {
8361 const struct cred *old_creds;
8362
8363 old_creds = idr_remove(&ctx->personality_idr, id);
8364 if (old_creds) {
8365 put_cred(old_creds);
8366 return 0;
8367 }
8368
8369 return -EINVAL;
8370 }
8371
8372 static bool io_register_op_must_quiesce(int op)
8373 {
8374 switch (op) {
8375 case IORING_UNREGISTER_FILES:
8376 case IORING_REGISTER_FILES_UPDATE:
8377 case IORING_REGISTER_PROBE:
8378 case IORING_REGISTER_PERSONALITY:
8379 case IORING_UNREGISTER_PERSONALITY:
8380 return false;
8381 default:
8382 return true;
8383 }
8384 }
8385
8386 static int __io_uring_register(struct io_ring_ctx *ctx, unsigned opcode,
8387 void __user *arg, unsigned nr_args)
8388 __releases(ctx->uring_lock)
8389 __acquires(ctx->uring_lock)
8390 {
8391 int ret;
8392
8393 /*
8394 * We're inside the ring mutex, if the ref is already dying, then
8395 * someone else killed the ctx or is already going through
8396 * io_uring_register().
8397 */
8398 if (percpu_ref_is_dying(&ctx->refs))
8399 return -ENXIO;
8400
8401 if (io_register_op_must_quiesce(opcode)) {
8402 percpu_ref_kill(&ctx->refs);
8403
8404 /*
8405 * Drop uring mutex before waiting for references to exit. If
8406 * another thread is currently inside io_uring_enter() it might
8407 * need to grab the uring_lock to make progress. If we hold it
8408 * here across the drain wait, then we can deadlock. It's safe
8409 * to drop the mutex here, since no new references will come in
8410 * after we've killed the percpu ref.
8411 */
8412 mutex_unlock(&ctx->uring_lock);
8413 ret = wait_for_completion_interruptible(&ctx->ref_comp);
8414 mutex_lock(&ctx->uring_lock);
8415 if (ret) {
8416 percpu_ref_resurrect(&ctx->refs);
8417 ret = -EINTR;
8418 goto out;
8419 }
8420 }
8421
8422 switch (opcode) {
8423 case IORING_REGISTER_BUFFERS:
8424 ret = io_sqe_buffer_register(ctx, arg, nr_args);
8425 break;
8426 case IORING_UNREGISTER_BUFFERS:
8427 ret = -EINVAL;
8428 if (arg || nr_args)
8429 break;
8430 ret = io_sqe_buffer_unregister(ctx);
8431 break;
8432 case IORING_REGISTER_FILES:
8433 ret = io_sqe_files_register(ctx, arg, nr_args);
8434 break;
8435 case IORING_UNREGISTER_FILES:
8436 ret = -EINVAL;
8437 if (arg || nr_args)
8438 break;
8439 ret = io_sqe_files_unregister(ctx);
8440 break;
8441 case IORING_REGISTER_FILES_UPDATE:
8442 ret = io_sqe_files_update(ctx, arg, nr_args);
8443 break;
8444 case IORING_REGISTER_EVENTFD:
8445 case IORING_REGISTER_EVENTFD_ASYNC:
8446 ret = -EINVAL;
8447 if (nr_args != 1)
8448 break;
8449 ret = io_eventfd_register(ctx, arg);
8450 if (ret)
8451 break;
8452 if (opcode == IORING_REGISTER_EVENTFD_ASYNC)
8453 ctx->eventfd_async = 1;
8454 else
8455 ctx->eventfd_async = 0;
8456 break;
8457 case IORING_UNREGISTER_EVENTFD:
8458 ret = -EINVAL;
8459 if (arg || nr_args)
8460 break;
8461 ret = io_eventfd_unregister(ctx);
8462 break;
8463 case IORING_REGISTER_PROBE:
8464 ret = -EINVAL;
8465 if (!arg || nr_args > 256)
8466 break;
8467 ret = io_probe(ctx, arg, nr_args);
8468 break;
8469 case IORING_REGISTER_PERSONALITY:
8470 ret = -EINVAL;
8471 if (arg || nr_args)
8472 break;
8473 ret = io_register_personality(ctx);
8474 break;
8475 case IORING_UNREGISTER_PERSONALITY:
8476 ret = -EINVAL;
8477 if (arg)
8478 break;
8479 ret = io_unregister_personality(ctx, nr_args);
8480 break;
8481 default:
8482 ret = -EINVAL;
8483 break;
8484 }
8485
8486 if (io_register_op_must_quiesce(opcode)) {
8487 /* bring the ctx back to life */
8488 percpu_ref_reinit(&ctx->refs);
8489 out:
8490 reinit_completion(&ctx->ref_comp);
8491 }
8492 return ret;
8493 }
8494
8495 SYSCALL_DEFINE4(io_uring_register, unsigned int, fd, unsigned int, opcode,
8496 void __user *, arg, unsigned int, nr_args)
8497 {
8498 struct io_ring_ctx *ctx;
8499 long ret = -EBADF;
8500 struct fd f;
8501
8502 f = fdget(fd);
8503 if (!f.file)
8504 return -EBADF;
8505
8506 ret = -EOPNOTSUPP;
8507 if (f.file->f_op != &io_uring_fops)
8508 goto out_fput;
8509
8510 ctx = f.file->private_data;
8511
8512 mutex_lock(&ctx->uring_lock);
8513 ret = __io_uring_register(ctx, opcode, arg, nr_args);
8514 mutex_unlock(&ctx->uring_lock);
8515 trace_io_uring_register(ctx, opcode, ctx->nr_user_files, ctx->nr_user_bufs,
8516 ctx->cq_ev_fd != NULL, ret);
8517 out_fput:
8518 fdput(f);
8519 return ret;
8520 }
8521
8522 static int __init io_uring_init(void)
8523 {
8524 #define __BUILD_BUG_VERIFY_ELEMENT(stype, eoffset, etype, ename) do { \
8525 BUILD_BUG_ON(offsetof(stype, ename) != eoffset); \
8526 BUILD_BUG_ON(sizeof(etype) != sizeof_field(stype, ename)); \
8527 } while (0)
8528
8529 #define BUILD_BUG_SQE_ELEM(eoffset, etype, ename) \
8530 __BUILD_BUG_VERIFY_ELEMENT(struct io_uring_sqe, eoffset, etype, ename)
8531 BUILD_BUG_ON(sizeof(struct io_uring_sqe) != 64);
8532 BUILD_BUG_SQE_ELEM(0, __u8, opcode);
8533 BUILD_BUG_SQE_ELEM(1, __u8, flags);
8534 BUILD_BUG_SQE_ELEM(2, __u16, ioprio);
8535 BUILD_BUG_SQE_ELEM(4, __s32, fd);
8536 BUILD_BUG_SQE_ELEM(8, __u64, off);
8537 BUILD_BUG_SQE_ELEM(8, __u64, addr2);
8538 BUILD_BUG_SQE_ELEM(16, __u64, addr);
8539 BUILD_BUG_SQE_ELEM(16, __u64, splice_off_in);
8540 BUILD_BUG_SQE_ELEM(24, __u32, len);
8541 BUILD_BUG_SQE_ELEM(28, __kernel_rwf_t, rw_flags);
8542 BUILD_BUG_SQE_ELEM(28, /* compat */ int, rw_flags);
8543 BUILD_BUG_SQE_ELEM(28, /* compat */ __u32, rw_flags);
8544 BUILD_BUG_SQE_ELEM(28, __u32, fsync_flags);
8545 BUILD_BUG_SQE_ELEM(28, /* compat */ __u16, poll_events);
8546 BUILD_BUG_SQE_ELEM(28, __u32, poll32_events);
8547 BUILD_BUG_SQE_ELEM(28, __u32, sync_range_flags);
8548 BUILD_BUG_SQE_ELEM(28, __u32, msg_flags);
8549 BUILD_BUG_SQE_ELEM(28, __u32, timeout_flags);
8550 BUILD_BUG_SQE_ELEM(28, __u32, accept_flags);
8551 BUILD_BUG_SQE_ELEM(28, __u32, cancel_flags);
8552 BUILD_BUG_SQE_ELEM(28, __u32, open_flags);
8553 BUILD_BUG_SQE_ELEM(28, __u32, statx_flags);
8554 BUILD_BUG_SQE_ELEM(28, __u32, fadvise_advice);
8555 BUILD_BUG_SQE_ELEM(28, __u32, splice_flags);
8556 BUILD_BUG_SQE_ELEM(32, __u64, user_data);
8557 BUILD_BUG_SQE_ELEM(40, __u16, buf_index);
8558 BUILD_BUG_SQE_ELEM(42, __u16, personality);
8559 BUILD_BUG_SQE_ELEM(44, __s32, splice_fd_in);
8560
8561 BUILD_BUG_ON(ARRAY_SIZE(io_op_defs) != IORING_OP_LAST);
8562 BUILD_BUG_ON(__REQ_F_LAST_BIT >= 8 * sizeof(int));
8563 req_cachep = KMEM_CACHE(io_kiocb, SLAB_HWCACHE_ALIGN | SLAB_PANIC);
8564 return 0;
8565 };
8566 __initcall(io_uring_init);