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