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