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