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