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