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