fc2b337e6c25a90fa6e69bbe05c4353914bcff15
[linux-2.6-microblaze.git] / io_uring / rsrc.c
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/kernel.h>
3 #include <linux/errno.h>
4 #include <linux/fs.h>
5 #include <linux/file.h>
6 #include <linux/mm.h>
7 #include <linux/slab.h>
8 #include <linux/nospec.h>
9 #include <linux/hugetlb.h>
10 #include <linux/compat.h>
11 #include <linux/io_uring.h>
12
13 #include <uapi/linux/io_uring.h>
14
15 #include "io_uring.h"
16 #include "openclose.h"
17 #include "rsrc.h"
18
19 struct io_rsrc_update {
20         struct file                     *file;
21         u64                             arg;
22         u32                             nr_args;
23         u32                             offset;
24         int                             type;
25 };
26
27 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
28                                   struct io_mapped_ubuf **pimu,
29                                   struct page **last_hpage);
30
31 #define IO_RSRC_REF_BATCH       100
32
33 /* only define max */
34 #define IORING_MAX_FIXED_FILES  (1U << 20)
35 #define IORING_MAX_REG_BUFFERS  (1U << 14)
36
37 void io_rsrc_refs_drop(struct io_ring_ctx *ctx)
38         __must_hold(&ctx->uring_lock)
39 {
40         if (ctx->rsrc_cached_refs) {
41                 io_rsrc_put_node(ctx->rsrc_node, ctx->rsrc_cached_refs);
42                 ctx->rsrc_cached_refs = 0;
43         }
44 }
45
46 static inline void __io_unaccount_mem(struct user_struct *user,
47                                       unsigned long nr_pages)
48 {
49         atomic_long_sub(nr_pages, &user->locked_vm);
50 }
51
52 static inline int __io_account_mem(struct user_struct *user,
53                                    unsigned long nr_pages)
54 {
55         unsigned long page_limit, cur_pages, new_pages;
56
57         /* Don't allow more pages than we can safely lock */
58         page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
59
60         cur_pages = atomic_long_read(&user->locked_vm);
61         do {
62                 new_pages = cur_pages + nr_pages;
63                 if (new_pages > page_limit)
64                         return -ENOMEM;
65         } while (!atomic_long_try_cmpxchg(&user->locked_vm,
66                                           &cur_pages, new_pages));
67         return 0;
68 }
69
70 static void io_unaccount_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
71 {
72         if (ctx->user)
73                 __io_unaccount_mem(ctx->user, nr_pages);
74
75         if (ctx->mm_account)
76                 atomic64_sub(nr_pages, &ctx->mm_account->pinned_vm);
77 }
78
79 static int io_account_mem(struct io_ring_ctx *ctx, unsigned long nr_pages)
80 {
81         int ret;
82
83         if (ctx->user) {
84                 ret = __io_account_mem(ctx->user, nr_pages);
85                 if (ret)
86                         return ret;
87         }
88
89         if (ctx->mm_account)
90                 atomic64_add(nr_pages, &ctx->mm_account->pinned_vm);
91
92         return 0;
93 }
94
95 static int io_copy_iov(struct io_ring_ctx *ctx, struct iovec *dst,
96                        void __user *arg, unsigned index)
97 {
98         struct iovec __user *src;
99
100 #ifdef CONFIG_COMPAT
101         if (ctx->compat) {
102                 struct compat_iovec __user *ciovs;
103                 struct compat_iovec ciov;
104
105                 ciovs = (struct compat_iovec __user *) arg;
106                 if (copy_from_user(&ciov, &ciovs[index], sizeof(ciov)))
107                         return -EFAULT;
108
109                 dst->iov_base = u64_to_user_ptr((u64)ciov.iov_base);
110                 dst->iov_len = ciov.iov_len;
111                 return 0;
112         }
113 #endif
114         src = (struct iovec __user *) arg;
115         if (copy_from_user(dst, &src[index], sizeof(*dst)))
116                 return -EFAULT;
117         return 0;
118 }
119
120 static int io_buffer_validate(struct iovec *iov)
121 {
122         unsigned long tmp, acct_len = iov->iov_len + (PAGE_SIZE - 1);
123
124         /*
125          * Don't impose further limits on the size and buffer
126          * constraints here, we'll -EINVAL later when IO is
127          * submitted if they are wrong.
128          */
129         if (!iov->iov_base)
130                 return iov->iov_len ? -EFAULT : 0;
131         if (!iov->iov_len)
132                 return -EFAULT;
133
134         /* arbitrary limit, but we need something */
135         if (iov->iov_len > SZ_1G)
136                 return -EFAULT;
137
138         if (check_add_overflow((unsigned long)iov->iov_base, acct_len, &tmp))
139                 return -EOVERFLOW;
140
141         return 0;
142 }
143
144 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf **slot)
145 {
146         struct io_mapped_ubuf *imu = *slot;
147         unsigned int i;
148
149         if (imu != ctx->dummy_ubuf) {
150                 for (i = 0; i < imu->nr_bvecs; i++)
151                         unpin_user_page(imu->bvec[i].bv_page);
152                 if (imu->acct_pages)
153                         io_unaccount_mem(ctx, imu->acct_pages);
154                 kvfree(imu);
155         }
156         *slot = NULL;
157 }
158
159 void io_rsrc_refs_refill(struct io_ring_ctx *ctx)
160         __must_hold(&ctx->uring_lock)
161 {
162         ctx->rsrc_cached_refs += IO_RSRC_REF_BATCH;
163         percpu_ref_get_many(&ctx->rsrc_node->refs, IO_RSRC_REF_BATCH);
164 }
165
166 static void __io_rsrc_put_work(struct io_rsrc_node *ref_node)
167 {
168         struct io_rsrc_data *rsrc_data = ref_node->rsrc_data;
169         struct io_ring_ctx *ctx = rsrc_data->ctx;
170         struct io_rsrc_put *prsrc, *tmp;
171
172         list_for_each_entry_safe(prsrc, tmp, &ref_node->rsrc_list, list) {
173                 list_del(&prsrc->list);
174
175                 if (prsrc->tag) {
176                         if (ctx->flags & IORING_SETUP_IOPOLL) {
177                                 mutex_lock(&ctx->uring_lock);
178                                 io_post_aux_cqe(ctx, prsrc->tag, 0, 0, true);
179                                 mutex_unlock(&ctx->uring_lock);
180                         } else {
181                                 io_post_aux_cqe(ctx, prsrc->tag, 0, 0, true);
182                         }
183                 }
184
185                 rsrc_data->do_put(ctx, prsrc);
186                 kfree(prsrc);
187         }
188
189         io_rsrc_node_destroy(ref_node);
190         if (atomic_dec_and_test(&rsrc_data->refs))
191                 complete(&rsrc_data->done);
192 }
193
194 void io_rsrc_put_work(struct work_struct *work)
195 {
196         struct io_ring_ctx *ctx;
197         struct llist_node *node;
198
199         ctx = container_of(work, struct io_ring_ctx, rsrc_put_work.work);
200         node = llist_del_all(&ctx->rsrc_put_llist);
201
202         while (node) {
203                 struct io_rsrc_node *ref_node;
204                 struct llist_node *next = node->next;
205
206                 ref_node = llist_entry(node, struct io_rsrc_node, llist);
207                 __io_rsrc_put_work(ref_node);
208                 node = next;
209         }
210 }
211
212 void io_wait_rsrc_data(struct io_rsrc_data *data)
213 {
214         if (data && !atomic_dec_and_test(&data->refs))
215                 wait_for_completion(&data->done);
216 }
217
218 void io_rsrc_node_destroy(struct io_rsrc_node *ref_node)
219 {
220         percpu_ref_exit(&ref_node->refs);
221         kfree(ref_node);
222 }
223
224 static __cold void io_rsrc_node_ref_zero(struct percpu_ref *ref)
225 {
226         struct io_rsrc_node *node = container_of(ref, struct io_rsrc_node, refs);
227         struct io_ring_ctx *ctx = node->rsrc_data->ctx;
228         unsigned long flags;
229         bool first_add = false;
230         unsigned long delay = HZ;
231
232         spin_lock_irqsave(&ctx->rsrc_ref_lock, flags);
233         node->done = true;
234
235         /* if we are mid-quiesce then do not delay */
236         if (node->rsrc_data->quiesce)
237                 delay = 0;
238
239         while (!list_empty(&ctx->rsrc_ref_list)) {
240                 node = list_first_entry(&ctx->rsrc_ref_list,
241                                             struct io_rsrc_node, node);
242                 /* recycle ref nodes in order */
243                 if (!node->done)
244                         break;
245                 list_del(&node->node);
246                 first_add |= llist_add(&node->llist, &ctx->rsrc_put_llist);
247         }
248         spin_unlock_irqrestore(&ctx->rsrc_ref_lock, flags);
249
250         if (first_add)
251                 mod_delayed_work(system_wq, &ctx->rsrc_put_work, delay);
252 }
253
254 static struct io_rsrc_node *io_rsrc_node_alloc(void)
255 {
256         struct io_rsrc_node *ref_node;
257
258         ref_node = kzalloc(sizeof(*ref_node), GFP_KERNEL);
259         if (!ref_node)
260                 return NULL;
261
262         if (percpu_ref_init(&ref_node->refs, io_rsrc_node_ref_zero,
263                             0, GFP_KERNEL)) {
264                 kfree(ref_node);
265                 return NULL;
266         }
267         INIT_LIST_HEAD(&ref_node->node);
268         INIT_LIST_HEAD(&ref_node->rsrc_list);
269         ref_node->done = false;
270         return ref_node;
271 }
272
273 void io_rsrc_node_switch(struct io_ring_ctx *ctx,
274                          struct io_rsrc_data *data_to_kill)
275         __must_hold(&ctx->uring_lock)
276 {
277         WARN_ON_ONCE(!ctx->rsrc_backup_node);
278         WARN_ON_ONCE(data_to_kill && !ctx->rsrc_node);
279
280         io_rsrc_refs_drop(ctx);
281
282         if (data_to_kill) {
283                 struct io_rsrc_node *rsrc_node = ctx->rsrc_node;
284
285                 rsrc_node->rsrc_data = data_to_kill;
286                 spin_lock_irq(&ctx->rsrc_ref_lock);
287                 list_add_tail(&rsrc_node->node, &ctx->rsrc_ref_list);
288                 spin_unlock_irq(&ctx->rsrc_ref_lock);
289
290                 atomic_inc(&data_to_kill->refs);
291                 percpu_ref_kill(&rsrc_node->refs);
292                 ctx->rsrc_node = NULL;
293         }
294
295         if (!ctx->rsrc_node) {
296                 ctx->rsrc_node = ctx->rsrc_backup_node;
297                 ctx->rsrc_backup_node = NULL;
298         }
299 }
300
301 int io_rsrc_node_switch_start(struct io_ring_ctx *ctx)
302 {
303         if (ctx->rsrc_backup_node)
304                 return 0;
305         ctx->rsrc_backup_node = io_rsrc_node_alloc();
306         return ctx->rsrc_backup_node ? 0 : -ENOMEM;
307 }
308
309 __cold static int io_rsrc_ref_quiesce(struct io_rsrc_data *data,
310                                       struct io_ring_ctx *ctx)
311 {
312         int ret;
313
314         /* As we may drop ->uring_lock, other task may have started quiesce */
315         if (data->quiesce)
316                 return -ENXIO;
317
318         data->quiesce = true;
319         do {
320                 ret = io_rsrc_node_switch_start(ctx);
321                 if (ret)
322                         break;
323                 io_rsrc_node_switch(ctx, data);
324
325                 /* kill initial ref, already quiesced if zero */
326                 if (atomic_dec_and_test(&data->refs))
327                         break;
328                 mutex_unlock(&ctx->uring_lock);
329                 flush_delayed_work(&ctx->rsrc_put_work);
330                 ret = wait_for_completion_interruptible(&data->done);
331                 if (!ret) {
332                         mutex_lock(&ctx->uring_lock);
333                         if (atomic_read(&data->refs) > 0) {
334                                 /*
335                                  * it has been revived by another thread while
336                                  * we were unlocked
337                                  */
338                                 mutex_unlock(&ctx->uring_lock);
339                         } else {
340                                 break;
341                         }
342                 }
343
344                 atomic_inc(&data->refs);
345                 /* wait for all works potentially completing data->done */
346                 flush_delayed_work(&ctx->rsrc_put_work);
347                 reinit_completion(&data->done);
348
349                 ret = io_run_task_work_sig();
350                 mutex_lock(&ctx->uring_lock);
351         } while (ret >= 0);
352         data->quiesce = false;
353
354         return ret;
355 }
356
357 static void io_free_page_table(void **table, size_t size)
358 {
359         unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
360
361         for (i = 0; i < nr_tables; i++)
362                 kfree(table[i]);
363         kfree(table);
364 }
365
366 static void io_rsrc_data_free(struct io_rsrc_data *data)
367 {
368         size_t size = data->nr * sizeof(data->tags[0][0]);
369
370         if (data->tags)
371                 io_free_page_table((void **)data->tags, size);
372         kfree(data);
373 }
374
375 static __cold void **io_alloc_page_table(size_t size)
376 {
377         unsigned i, nr_tables = DIV_ROUND_UP(size, PAGE_SIZE);
378         size_t init_size = size;
379         void **table;
380
381         table = kcalloc(nr_tables, sizeof(*table), GFP_KERNEL_ACCOUNT);
382         if (!table)
383                 return NULL;
384
385         for (i = 0; i < nr_tables; i++) {
386                 unsigned int this_size = min_t(size_t, size, PAGE_SIZE);
387
388                 table[i] = kzalloc(this_size, GFP_KERNEL_ACCOUNT);
389                 if (!table[i]) {
390                         io_free_page_table(table, init_size);
391                         return NULL;
392                 }
393                 size -= this_size;
394         }
395         return table;
396 }
397
398 __cold static int io_rsrc_data_alloc(struct io_ring_ctx *ctx,
399                                      rsrc_put_fn *do_put, u64 __user *utags,
400                                      unsigned nr, struct io_rsrc_data **pdata)
401 {
402         struct io_rsrc_data *data;
403         int ret = -ENOMEM;
404         unsigned i;
405
406         data = kzalloc(sizeof(*data), GFP_KERNEL);
407         if (!data)
408                 return -ENOMEM;
409         data->tags = (u64 **)io_alloc_page_table(nr * sizeof(data->tags[0][0]));
410         if (!data->tags) {
411                 kfree(data);
412                 return -ENOMEM;
413         }
414
415         data->nr = nr;
416         data->ctx = ctx;
417         data->do_put = do_put;
418         if (utags) {
419                 ret = -EFAULT;
420                 for (i = 0; i < nr; i++) {
421                         u64 *tag_slot = io_get_tag_slot(data, i);
422
423                         if (copy_from_user(tag_slot, &utags[i],
424                                            sizeof(*tag_slot)))
425                                 goto fail;
426                 }
427         }
428
429         atomic_set(&data->refs, 1);
430         init_completion(&data->done);
431         *pdata = data;
432         return 0;
433 fail:
434         io_rsrc_data_free(data);
435         return ret;
436 }
437
438 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
439                                  struct io_uring_rsrc_update2 *up,
440                                  unsigned nr_args)
441 {
442         u64 __user *tags = u64_to_user_ptr(up->tags);
443         __s32 __user *fds = u64_to_user_ptr(up->data);
444         struct io_rsrc_data *data = ctx->file_data;
445         struct io_fixed_file *file_slot;
446         struct file *file;
447         int fd, i, err = 0;
448         unsigned int done;
449         bool needs_switch = false;
450
451         if (!ctx->file_data)
452                 return -ENXIO;
453         if (up->offset + nr_args > ctx->nr_user_files)
454                 return -EINVAL;
455
456         for (done = 0; done < nr_args; done++) {
457                 u64 tag = 0;
458
459                 if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
460                     copy_from_user(&fd, &fds[done], sizeof(fd))) {
461                         err = -EFAULT;
462                         break;
463                 }
464                 if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
465                         err = -EINVAL;
466                         break;
467                 }
468                 if (fd == IORING_REGISTER_FILES_SKIP)
469                         continue;
470
471                 i = array_index_nospec(up->offset + done, ctx->nr_user_files);
472                 file_slot = io_fixed_file_slot(&ctx->file_table, i);
473
474                 if (file_slot->file_ptr) {
475                         file = (struct file *)(file_slot->file_ptr & FFS_MASK);
476                         err = io_queue_rsrc_removal(data, i, ctx->rsrc_node, file);
477                         if (err)
478                                 break;
479                         file_slot->file_ptr = 0;
480                         io_file_bitmap_clear(&ctx->file_table, i);
481                         needs_switch = true;
482                 }
483                 if (fd != -1) {
484                         file = fget(fd);
485                         if (!file) {
486                                 err = -EBADF;
487                                 break;
488                         }
489                         /*
490                          * Don't allow io_uring instances to be registered. If
491                          * UNIX isn't enabled, then this causes a reference
492                          * cycle and this instance can never get freed. If UNIX
493                          * is enabled we'll handle it just fine, but there's
494                          * still no point in allowing a ring fd as it doesn't
495                          * support regular read/write anyway.
496                          */
497                         if (io_is_uring_fops(file)) {
498                                 fput(file);
499                                 err = -EBADF;
500                                 break;
501                         }
502                         err = io_scm_file_account(ctx, file);
503                         if (err) {
504                                 fput(file);
505                                 break;
506                         }
507                         *io_get_tag_slot(data, i) = tag;
508                         io_fixed_file_set(file_slot, file);
509                         io_file_bitmap_set(&ctx->file_table, i);
510                 }
511         }
512
513         if (needs_switch)
514                 io_rsrc_node_switch(ctx, data);
515         return done ? done : err;
516 }
517
518 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
519                                    struct io_uring_rsrc_update2 *up,
520                                    unsigned int nr_args)
521 {
522         u64 __user *tags = u64_to_user_ptr(up->tags);
523         struct iovec iov, __user *iovs = u64_to_user_ptr(up->data);
524         struct page *last_hpage = NULL;
525         bool needs_switch = false;
526         __u32 done;
527         int i, err;
528
529         if (!ctx->buf_data)
530                 return -ENXIO;
531         if (up->offset + nr_args > ctx->nr_user_bufs)
532                 return -EINVAL;
533
534         for (done = 0; done < nr_args; done++) {
535                 struct io_mapped_ubuf *imu;
536                 int offset = up->offset + done;
537                 u64 tag = 0;
538
539                 err = io_copy_iov(ctx, &iov, iovs, done);
540                 if (err)
541                         break;
542                 if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
543                         err = -EFAULT;
544                         break;
545                 }
546                 err = io_buffer_validate(&iov);
547                 if (err)
548                         break;
549                 if (!iov.iov_base && tag) {
550                         err = -EINVAL;
551                         break;
552                 }
553                 err = io_sqe_buffer_register(ctx, &iov, &imu, &last_hpage);
554                 if (err)
555                         break;
556
557                 i = array_index_nospec(offset, ctx->nr_user_bufs);
558                 if (ctx->user_bufs[i] != ctx->dummy_ubuf) {
559                         err = io_queue_rsrc_removal(ctx->buf_data, i,
560                                                     ctx->rsrc_node, ctx->user_bufs[i]);
561                         if (unlikely(err)) {
562                                 io_buffer_unmap(ctx, &imu);
563                                 break;
564                         }
565                         ctx->user_bufs[i] = ctx->dummy_ubuf;
566                         needs_switch = true;
567                 }
568
569                 ctx->user_bufs[i] = imu;
570                 *io_get_tag_slot(ctx->buf_data, offset) = tag;
571         }
572
573         if (needs_switch)
574                 io_rsrc_node_switch(ctx, ctx->buf_data);
575         return done ? done : err;
576 }
577
578 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
579                                      struct io_uring_rsrc_update2 *up,
580                                      unsigned nr_args)
581 {
582         __u32 tmp;
583         int err;
584
585         if (check_add_overflow(up->offset, nr_args, &tmp))
586                 return -EOVERFLOW;
587         err = io_rsrc_node_switch_start(ctx);
588         if (err)
589                 return err;
590
591         switch (type) {
592         case IORING_RSRC_FILE:
593                 return __io_sqe_files_update(ctx, up, nr_args);
594         case IORING_RSRC_BUFFER:
595                 return __io_sqe_buffers_update(ctx, up, nr_args);
596         }
597         return -EINVAL;
598 }
599
600 int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
601                              unsigned nr_args)
602 {
603         struct io_uring_rsrc_update2 up;
604
605         if (!nr_args)
606                 return -EINVAL;
607         memset(&up, 0, sizeof(up));
608         if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
609                 return -EFAULT;
610         if (up.resv || up.resv2)
611                 return -EINVAL;
612         return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
613 }
614
615 int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
616                             unsigned size, unsigned type)
617 {
618         struct io_uring_rsrc_update2 up;
619
620         if (size != sizeof(up))
621                 return -EINVAL;
622         if (copy_from_user(&up, arg, sizeof(up)))
623                 return -EFAULT;
624         if (!up.nr || up.resv || up.resv2)
625                 return -EINVAL;
626         return __io_register_rsrc_update(ctx, type, &up, up.nr);
627 }
628
629 __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
630                             unsigned int size, unsigned int type)
631 {
632         struct io_uring_rsrc_register rr;
633
634         /* keep it extendible */
635         if (size != sizeof(rr))
636                 return -EINVAL;
637
638         memset(&rr, 0, sizeof(rr));
639         if (copy_from_user(&rr, arg, size))
640                 return -EFAULT;
641         if (!rr.nr || rr.resv2)
642                 return -EINVAL;
643         if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
644                 return -EINVAL;
645
646         switch (type) {
647         case IORING_RSRC_FILE:
648                 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
649                         break;
650                 return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
651                                              rr.nr, u64_to_user_ptr(rr.tags));
652         case IORING_RSRC_BUFFER:
653                 if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
654                         break;
655                 return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
656                                                rr.nr, u64_to_user_ptr(rr.tags));
657         }
658         return -EINVAL;
659 }
660
661 int io_rsrc_update_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
662 {
663         struct io_rsrc_update *up = io_kiocb_to_cmd(req);
664
665         if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
666                 return -EINVAL;
667         if (sqe->rw_flags || sqe->splice_fd_in)
668                 return -EINVAL;
669
670         up->offset = READ_ONCE(sqe->off);
671         up->nr_args = READ_ONCE(sqe->len);
672         if (!up->nr_args)
673                 return -EINVAL;
674         up->arg = READ_ONCE(sqe->addr);
675         up->type = READ_ONCE(sqe->ioprio);
676         return 0;
677 }
678
679 static int io_files_update_with_index_alloc(struct io_kiocb *req,
680                                             unsigned int issue_flags)
681 {
682         struct io_rsrc_update *up = io_kiocb_to_cmd(req);
683         __s32 __user *fds = u64_to_user_ptr(up->arg);
684         unsigned int done;
685         struct file *file;
686         int ret, fd;
687
688         if (!req->ctx->file_data)
689                 return -ENXIO;
690
691         for (done = 0; done < up->nr_args; done++) {
692                 if (copy_from_user(&fd, &fds[done], sizeof(fd))) {
693                         ret = -EFAULT;
694                         break;
695                 }
696
697                 file = fget(fd);
698                 if (!file) {
699                         ret = -EBADF;
700                         break;
701                 }
702                 ret = io_fixed_fd_install(req, issue_flags, file,
703                                           IORING_FILE_INDEX_ALLOC);
704                 if (ret < 0)
705                         break;
706                 if (copy_to_user(&fds[done], &ret, sizeof(ret))) {
707                         __io_close_fixed(req->ctx, issue_flags, ret);
708                         ret = -EFAULT;
709                         break;
710                 }
711         }
712
713         if (done)
714                 return done;
715         return ret;
716 }
717
718 static int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
719 {
720         struct io_rsrc_update *up = io_kiocb_to_cmd(req);
721         struct io_ring_ctx *ctx = req->ctx;
722         struct io_uring_rsrc_update2 up2;
723         int ret;
724
725         up2.offset = up->offset;
726         up2.data = up->arg;
727         up2.nr = 0;
728         up2.tags = 0;
729         up2.resv = 0;
730         up2.resv2 = 0;
731
732         if (up->offset == IORING_FILE_INDEX_ALLOC) {
733                 ret = io_files_update_with_index_alloc(req, issue_flags);
734         } else {
735                 io_ring_submit_lock(ctx, issue_flags);
736                 ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
737                                                 &up2, up->nr_args);
738                 io_ring_submit_unlock(ctx, issue_flags);
739         }
740
741         if (ret < 0)
742                 req_set_fail(req);
743         io_req_set_res(req, ret, 0);
744         return IOU_OK;
745 }
746
747 int io_rsrc_update(struct io_kiocb *req, unsigned int issue_flags)
748 {
749         struct io_rsrc_update *up = io_kiocb_to_cmd(req);
750
751         switch (up->type) {
752         case IORING_RSRC_UPDATE_FILES:
753                 return io_files_update(req, issue_flags);
754         }
755         return -EINVAL;
756 }
757
758 int io_queue_rsrc_removal(struct io_rsrc_data *data, unsigned idx,
759                           struct io_rsrc_node *node, void *rsrc)
760 {
761         u64 *tag_slot = io_get_tag_slot(data, idx);
762         struct io_rsrc_put *prsrc;
763
764         prsrc = kzalloc(sizeof(*prsrc), GFP_KERNEL);
765         if (!prsrc)
766                 return -ENOMEM;
767
768         prsrc->tag = *tag_slot;
769         *tag_slot = 0;
770         prsrc->rsrc = rsrc;
771         list_add(&prsrc->list, &node->rsrc_list);
772         return 0;
773 }
774
775 void __io_sqe_files_unregister(struct io_ring_ctx *ctx)
776 {
777 #if !defined(IO_URING_SCM_ALL)
778         int i;
779
780         for (i = 0; i < ctx->nr_user_files; i++) {
781                 struct file *file = io_file_from_index(&ctx->file_table, i);
782
783                 if (!file)
784                         continue;
785                 if (io_fixed_file_slot(&ctx->file_table, i)->file_ptr & FFS_SCM)
786                         continue;
787                 io_file_bitmap_clear(&ctx->file_table, i);
788                 fput(file);
789         }
790 #endif
791
792 #if defined(CONFIG_UNIX)
793         if (ctx->ring_sock) {
794                 struct sock *sock = ctx->ring_sock->sk;
795                 struct sk_buff *skb;
796
797                 while ((skb = skb_dequeue(&sock->sk_receive_queue)) != NULL)
798                         kfree_skb(skb);
799         }
800 #endif
801         io_free_file_tables(&ctx->file_table);
802         io_rsrc_data_free(ctx->file_data);
803         ctx->file_data = NULL;
804         ctx->nr_user_files = 0;
805 }
806
807 int io_sqe_files_unregister(struct io_ring_ctx *ctx)
808 {
809         unsigned nr = ctx->nr_user_files;
810         int ret;
811
812         if (!ctx->file_data)
813                 return -ENXIO;
814
815         /*
816          * Quiesce may unlock ->uring_lock, and while it's not held
817          * prevent new requests using the table.
818          */
819         ctx->nr_user_files = 0;
820         ret = io_rsrc_ref_quiesce(ctx->file_data, ctx);
821         ctx->nr_user_files = nr;
822         if (!ret)
823                 __io_sqe_files_unregister(ctx);
824         return ret;
825 }
826
827 /*
828  * Ensure the UNIX gc is aware of our file set, so we are certain that
829  * the io_uring can be safely unregistered on process exit, even if we have
830  * loops in the file referencing. We account only files that can hold other
831  * files because otherwise they can't form a loop and so are not interesting
832  * for GC.
833  */
834 int __io_scm_file_account(struct io_ring_ctx *ctx, struct file *file)
835 {
836 #if defined(CONFIG_UNIX)
837         struct sock *sk = ctx->ring_sock->sk;
838         struct sk_buff_head *head = &sk->sk_receive_queue;
839         struct scm_fp_list *fpl;
840         struct sk_buff *skb;
841
842         if (likely(!io_file_need_scm(file)))
843                 return 0;
844
845         /*
846          * See if we can merge this file into an existing skb SCM_RIGHTS
847          * file set. If there's no room, fall back to allocating a new skb
848          * and filling it in.
849          */
850         spin_lock_irq(&head->lock);
851         skb = skb_peek(head);
852         if (skb && UNIXCB(skb).fp->count < SCM_MAX_FD)
853                 __skb_unlink(skb, head);
854         else
855                 skb = NULL;
856         spin_unlock_irq(&head->lock);
857
858         if (!skb) {
859                 fpl = kzalloc(sizeof(*fpl), GFP_KERNEL);
860                 if (!fpl)
861                         return -ENOMEM;
862
863                 skb = alloc_skb(0, GFP_KERNEL);
864                 if (!skb) {
865                         kfree(fpl);
866                         return -ENOMEM;
867                 }
868
869                 fpl->user = get_uid(current_user());
870                 fpl->max = SCM_MAX_FD;
871                 fpl->count = 0;
872
873                 UNIXCB(skb).fp = fpl;
874                 skb->sk = sk;
875                 skb->destructor = unix_destruct_scm;
876                 refcount_add(skb->truesize, &sk->sk_wmem_alloc);
877         }
878
879         fpl = UNIXCB(skb).fp;
880         fpl->fp[fpl->count++] = get_file(file);
881         unix_inflight(fpl->user, file);
882         skb_queue_head(head, skb);
883         fput(file);
884 #endif
885         return 0;
886 }
887
888 static void io_rsrc_file_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
889 {
890         struct file *file = prsrc->file;
891 #if defined(CONFIG_UNIX)
892         struct sock *sock = ctx->ring_sock->sk;
893         struct sk_buff_head list, *head = &sock->sk_receive_queue;
894         struct sk_buff *skb;
895         int i;
896
897         if (!io_file_need_scm(file)) {
898                 fput(file);
899                 return;
900         }
901
902         __skb_queue_head_init(&list);
903
904         /*
905          * Find the skb that holds this file in its SCM_RIGHTS. When found,
906          * remove this entry and rearrange the file array.
907          */
908         skb = skb_dequeue(head);
909         while (skb) {
910                 struct scm_fp_list *fp;
911
912                 fp = UNIXCB(skb).fp;
913                 for (i = 0; i < fp->count; i++) {
914                         int left;
915
916                         if (fp->fp[i] != file)
917                                 continue;
918
919                         unix_notinflight(fp->user, fp->fp[i]);
920                         left = fp->count - 1 - i;
921                         if (left) {
922                                 memmove(&fp->fp[i], &fp->fp[i + 1],
923                                                 left * sizeof(struct file *));
924                         }
925                         fp->count--;
926                         if (!fp->count) {
927                                 kfree_skb(skb);
928                                 skb = NULL;
929                         } else {
930                                 __skb_queue_tail(&list, skb);
931                         }
932                         fput(file);
933                         file = NULL;
934                         break;
935                 }
936
937                 if (!file)
938                         break;
939
940                 __skb_queue_tail(&list, skb);
941
942                 skb = skb_dequeue(head);
943         }
944
945         if (skb_peek(&list)) {
946                 spin_lock_irq(&head->lock);
947                 while ((skb = __skb_dequeue(&list)) != NULL)
948                         __skb_queue_tail(head, skb);
949                 spin_unlock_irq(&head->lock);
950         }
951 #else
952         fput(file);
953 #endif
954 }
955
956 int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
957                           unsigned nr_args, u64 __user *tags)
958 {
959         __s32 __user *fds = (__s32 __user *) arg;
960         struct file *file;
961         int fd, ret;
962         unsigned i;
963
964         if (ctx->file_data)
965                 return -EBUSY;
966         if (!nr_args)
967                 return -EINVAL;
968         if (nr_args > IORING_MAX_FIXED_FILES)
969                 return -EMFILE;
970         if (nr_args > rlimit(RLIMIT_NOFILE))
971                 return -EMFILE;
972         ret = io_rsrc_node_switch_start(ctx);
973         if (ret)
974                 return ret;
975         ret = io_rsrc_data_alloc(ctx, io_rsrc_file_put, tags, nr_args,
976                                  &ctx->file_data);
977         if (ret)
978                 return ret;
979
980         if (!io_alloc_file_tables(&ctx->file_table, nr_args)) {
981                 io_rsrc_data_free(ctx->file_data);
982                 ctx->file_data = NULL;
983                 return -ENOMEM;
984         }
985
986         for (i = 0; i < nr_args; i++, ctx->nr_user_files++) {
987                 struct io_fixed_file *file_slot;
988
989                 if (fds && copy_from_user(&fd, &fds[i], sizeof(fd))) {
990                         ret = -EFAULT;
991                         goto fail;
992                 }
993                 /* allow sparse sets */
994                 if (!fds || fd == -1) {
995                         ret = -EINVAL;
996                         if (unlikely(*io_get_tag_slot(ctx->file_data, i)))
997                                 goto fail;
998                         continue;
999                 }
1000
1001                 file = fget(fd);
1002                 ret = -EBADF;
1003                 if (unlikely(!file))
1004                         goto fail;
1005
1006                 /*
1007                  * Don't allow io_uring instances to be registered. If UNIX
1008                  * isn't enabled, then this causes a reference cycle and this
1009                  * instance can never get freed. If UNIX is enabled we'll
1010                  * handle it just fine, but there's still no point in allowing
1011                  * a ring fd as it doesn't support regular read/write anyway.
1012                  */
1013                 if (io_is_uring_fops(file)) {
1014                         fput(file);
1015                         goto fail;
1016                 }
1017                 ret = io_scm_file_account(ctx, file);
1018                 if (ret) {
1019                         fput(file);
1020                         goto fail;
1021                 }
1022                 file_slot = io_fixed_file_slot(&ctx->file_table, i);
1023                 io_fixed_file_set(file_slot, file);
1024                 io_file_bitmap_set(&ctx->file_table, i);
1025         }
1026
1027         /* default it to the whole table */
1028         io_file_table_set_alloc_range(ctx, 0, ctx->nr_user_files);
1029         io_rsrc_node_switch(ctx, NULL);
1030         return 0;
1031 fail:
1032         __io_sqe_files_unregister(ctx);
1033         return ret;
1034 }
1035
1036 static void io_rsrc_buf_put(struct io_ring_ctx *ctx, struct io_rsrc_put *prsrc)
1037 {
1038         io_buffer_unmap(ctx, &prsrc->buf);
1039         prsrc->buf = NULL;
1040 }
1041
1042 void __io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
1043 {
1044         unsigned int i;
1045
1046         for (i = 0; i < ctx->nr_user_bufs; i++)
1047                 io_buffer_unmap(ctx, &ctx->user_bufs[i]);
1048         kfree(ctx->user_bufs);
1049         io_rsrc_data_free(ctx->buf_data);
1050         ctx->user_bufs = NULL;
1051         ctx->buf_data = NULL;
1052         ctx->nr_user_bufs = 0;
1053 }
1054
1055 int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
1056 {
1057         unsigned nr = ctx->nr_user_bufs;
1058         int ret;
1059
1060         if (!ctx->buf_data)
1061                 return -ENXIO;
1062
1063         /*
1064          * Quiesce may unlock ->uring_lock, and while it's not held
1065          * prevent new requests using the table.
1066          */
1067         ctx->nr_user_bufs = 0;
1068         ret = io_rsrc_ref_quiesce(ctx->buf_data, ctx);
1069         ctx->nr_user_bufs = nr;
1070         if (!ret)
1071                 __io_sqe_buffers_unregister(ctx);
1072         return ret;
1073 }
1074
1075 /*
1076  * Not super efficient, but this is just a registration time. And we do cache
1077  * the last compound head, so generally we'll only do a full search if we don't
1078  * match that one.
1079  *
1080  * We check if the given compound head page has already been accounted, to
1081  * avoid double accounting it. This allows us to account the full size of the
1082  * page, not just the constituent pages of a huge page.
1083  */
1084 static bool headpage_already_acct(struct io_ring_ctx *ctx, struct page **pages,
1085                                   int nr_pages, struct page *hpage)
1086 {
1087         int i, j;
1088
1089         /* check current page array */
1090         for (i = 0; i < nr_pages; i++) {
1091                 if (!PageCompound(pages[i]))
1092                         continue;
1093                 if (compound_head(pages[i]) == hpage)
1094                         return true;
1095         }
1096
1097         /* check previously registered pages */
1098         for (i = 0; i < ctx->nr_user_bufs; i++) {
1099                 struct io_mapped_ubuf *imu = ctx->user_bufs[i];
1100
1101                 for (j = 0; j < imu->nr_bvecs; j++) {
1102                         if (!PageCompound(imu->bvec[j].bv_page))
1103                                 continue;
1104                         if (compound_head(imu->bvec[j].bv_page) == hpage)
1105                                 return true;
1106                 }
1107         }
1108
1109         return false;
1110 }
1111
1112 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
1113                                  int nr_pages, struct io_mapped_ubuf *imu,
1114                                  struct page **last_hpage)
1115 {
1116         int i, ret;
1117
1118         imu->acct_pages = 0;
1119         for (i = 0; i < nr_pages; i++) {
1120                 if (!PageCompound(pages[i])) {
1121                         imu->acct_pages++;
1122                 } else {
1123                         struct page *hpage;
1124
1125                         hpage = compound_head(pages[i]);
1126                         if (hpage == *last_hpage)
1127                                 continue;
1128                         *last_hpage = hpage;
1129                         if (headpage_already_acct(ctx, pages, i, hpage))
1130                                 continue;
1131                         imu->acct_pages += page_size(hpage) >> PAGE_SHIFT;
1132                 }
1133         }
1134
1135         if (!imu->acct_pages)
1136                 return 0;
1137
1138         ret = io_account_mem(ctx, imu->acct_pages);
1139         if (ret)
1140                 imu->acct_pages = 0;
1141         return ret;
1142 }
1143
1144 struct page **io_pin_pages(unsigned long ubuf, unsigned long len, int *npages)
1145 {
1146         unsigned long start, end, nr_pages;
1147         struct vm_area_struct **vmas = NULL;
1148         struct page **pages = NULL;
1149         int i, pret, ret = -ENOMEM;
1150
1151         end = (ubuf + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
1152         start = ubuf >> PAGE_SHIFT;
1153         nr_pages = end - start;
1154
1155         pages = kvmalloc_array(nr_pages, sizeof(struct page *), GFP_KERNEL);
1156         if (!pages)
1157                 goto done;
1158
1159         vmas = kvmalloc_array(nr_pages, sizeof(struct vm_area_struct *),
1160                               GFP_KERNEL);
1161         if (!vmas)
1162                 goto done;
1163
1164         ret = 0;
1165         mmap_read_lock(current->mm);
1166         pret = pin_user_pages(ubuf, nr_pages, FOLL_WRITE | FOLL_LONGTERM,
1167                               pages, vmas);
1168         if (pret == nr_pages) {
1169                 /* don't support file backed memory */
1170                 for (i = 0; i < nr_pages; i++) {
1171                         struct vm_area_struct *vma = vmas[i];
1172
1173                         if (vma_is_shmem(vma))
1174                                 continue;
1175                         if (vma->vm_file &&
1176                             !is_file_hugepages(vma->vm_file)) {
1177                                 ret = -EOPNOTSUPP;
1178                                 break;
1179                         }
1180                 }
1181                 *npages = nr_pages;
1182         } else {
1183                 ret = pret < 0 ? pret : -EFAULT;
1184         }
1185         mmap_read_unlock(current->mm);
1186         if (ret) {
1187                 /*
1188                  * if we did partial map, or found file backed vmas,
1189                  * release any pages we did get
1190                  */
1191                 if (pret > 0)
1192                         unpin_user_pages(pages, pret);
1193                 goto done;
1194         }
1195         ret = 0;
1196 done:
1197         kvfree(vmas);
1198         if (ret < 0) {
1199                 kvfree(pages);
1200                 pages = ERR_PTR(ret);
1201         }
1202         return pages;
1203 }
1204
1205 static int io_sqe_buffer_register(struct io_ring_ctx *ctx, struct iovec *iov,
1206                                   struct io_mapped_ubuf **pimu,
1207                                   struct page **last_hpage)
1208 {
1209         struct io_mapped_ubuf *imu = NULL;
1210         struct page **pages = NULL;
1211         unsigned long off;
1212         size_t size;
1213         int ret, nr_pages, i;
1214
1215         *pimu = ctx->dummy_ubuf;
1216         if (!iov->iov_base)
1217                 return 0;
1218
1219         ret = -ENOMEM;
1220         pages = io_pin_pages((unsigned long) iov->iov_base, iov->iov_len,
1221                                 &nr_pages);
1222         if (IS_ERR(pages)) {
1223                 ret = PTR_ERR(pages);
1224                 pages = NULL;
1225                 goto done;
1226         }
1227
1228         imu = kvmalloc(struct_size(imu, bvec, nr_pages), GFP_KERNEL);
1229         if (!imu)
1230                 goto done;
1231
1232         ret = io_buffer_account_pin(ctx, pages, nr_pages, imu, last_hpage);
1233         if (ret) {
1234                 unpin_user_pages(pages, nr_pages);
1235                 goto done;
1236         }
1237
1238         off = (unsigned long) iov->iov_base & ~PAGE_MASK;
1239         size = iov->iov_len;
1240         for (i = 0; i < nr_pages; i++) {
1241                 size_t vec_len;
1242
1243                 vec_len = min_t(size_t, size, PAGE_SIZE - off);
1244                 imu->bvec[i].bv_page = pages[i];
1245                 imu->bvec[i].bv_len = vec_len;
1246                 imu->bvec[i].bv_offset = off;
1247                 off = 0;
1248                 size -= vec_len;
1249         }
1250         /* store original address for later verification */
1251         imu->ubuf = (unsigned long) iov->iov_base;
1252         imu->ubuf_end = imu->ubuf + iov->iov_len;
1253         imu->nr_bvecs = nr_pages;
1254         *pimu = imu;
1255         ret = 0;
1256 done:
1257         if (ret)
1258                 kvfree(imu);
1259         kvfree(pages);
1260         return ret;
1261 }
1262
1263 static int io_buffers_map_alloc(struct io_ring_ctx *ctx, unsigned int nr_args)
1264 {
1265         ctx->user_bufs = kcalloc(nr_args, sizeof(*ctx->user_bufs), GFP_KERNEL);
1266         return ctx->user_bufs ? 0 : -ENOMEM;
1267 }
1268
1269 int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
1270                             unsigned int nr_args, u64 __user *tags)
1271 {
1272         struct page *last_hpage = NULL;
1273         struct io_rsrc_data *data;
1274         int i, ret;
1275         struct iovec iov;
1276
1277         BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
1278
1279         if (ctx->user_bufs)
1280                 return -EBUSY;
1281         if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
1282                 return -EINVAL;
1283         ret = io_rsrc_node_switch_start(ctx);
1284         if (ret)
1285                 return ret;
1286         ret = io_rsrc_data_alloc(ctx, io_rsrc_buf_put, tags, nr_args, &data);
1287         if (ret)
1288                 return ret;
1289         ret = io_buffers_map_alloc(ctx, nr_args);
1290         if (ret) {
1291                 io_rsrc_data_free(data);
1292                 return ret;
1293         }
1294
1295         for (i = 0; i < nr_args; i++, ctx->nr_user_bufs++) {
1296                 if (arg) {
1297                         ret = io_copy_iov(ctx, &iov, arg, i);
1298                         if (ret)
1299                                 break;
1300                         ret = io_buffer_validate(&iov);
1301                         if (ret)
1302                                 break;
1303                 } else {
1304                         memset(&iov, 0, sizeof(iov));
1305                 }
1306
1307                 if (!iov.iov_base && *io_get_tag_slot(data, i)) {
1308                         ret = -EINVAL;
1309                         break;
1310                 }
1311
1312                 ret = io_sqe_buffer_register(ctx, &iov, &ctx->user_bufs[i],
1313                                              &last_hpage);
1314                 if (ret)
1315                         break;
1316         }
1317
1318         WARN_ON_ONCE(ctx->buf_data);
1319
1320         ctx->buf_data = data;
1321         if (ret)
1322                 __io_sqe_buffers_unregister(ctx);
1323         else
1324                 io_rsrc_node_switch(ctx, NULL);
1325         return ret;
1326 }
1327
1328 int io_import_fixed(int ddir, struct iov_iter *iter,
1329                            struct io_mapped_ubuf *imu,
1330                            u64 buf_addr, size_t len)
1331 {
1332         u64 buf_end;
1333         size_t offset;
1334
1335         if (WARN_ON_ONCE(!imu))
1336                 return -EFAULT;
1337         if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
1338                 return -EFAULT;
1339         /* not inside the mapped region */
1340         if (unlikely(buf_addr < imu->ubuf || buf_end > imu->ubuf_end))
1341                 return -EFAULT;
1342
1343         /*
1344          * May not be a start of buffer, set size appropriately
1345          * and advance us to the beginning.
1346          */
1347         offset = buf_addr - imu->ubuf;
1348         iov_iter_bvec(iter, ddir, imu->bvec, imu->nr_bvecs, offset + len);
1349
1350         if (offset) {
1351                 /*
1352                  * Don't use iov_iter_advance() here, as it's really slow for
1353                  * using the latter parts of a big fixed buffer - it iterates
1354                  * over each segment manually. We can cheat a bit here, because
1355                  * we know that:
1356                  *
1357                  * 1) it's a BVEC iter, we set it up
1358                  * 2) all bvecs are PAGE_SIZE in size, except potentially the
1359                  *    first and last bvec
1360                  *
1361                  * So just find our index, and adjust the iterator afterwards.
1362                  * If the offset is within the first bvec (or the whole first
1363                  * bvec, just use iov_iter_advance(). This makes it easier
1364                  * since we can just skip the first segment, which may not
1365                  * be PAGE_SIZE aligned.
1366                  */
1367                 const struct bio_vec *bvec = imu->bvec;
1368
1369                 if (offset <= bvec->bv_len) {
1370                         iov_iter_advance(iter, offset);
1371                 } else {
1372                         unsigned long seg_skip;
1373
1374                         /* skip first vec */
1375                         offset -= bvec->bv_len;
1376                         seg_skip = 1 + (offset >> PAGE_SHIFT);
1377
1378                         iter->bvec = bvec + seg_skip;
1379                         iter->nr_segs -= seg_skip;
1380                         iter->count -= bvec->bv_len + offset;
1381                         iter->iov_offset = offset & ~PAGE_MASK;
1382                 }
1383         }
1384
1385         return 0;
1386 }