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