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