xref: /linux/io_uring/rsrc.c (revision 889dd44491b37c890b1b4ef40876cf19032ca897)
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 #include <linux/io_uring/cmd.h>
13 #include <linux/dma-buf-io.h>
14 
15 #include <uapi/linux/io_uring.h>
16 
17 #include "filetable.h"
18 #include "io_uring.h"
19 #include "openclose.h"
20 #include "rsrc.h"
21 #include "memmap.h"
22 #include "register.h"
23 #include "dma-buf.h"
24 
25 struct io_rsrc_update {
26 	struct file			*file;
27 	u64				arg;
28 	u32				nr_args;
29 	u32				offset;
30 };
31 
32 static struct io_rsrc_node *io_sqe_buffer_register(struct io_ring_ctx *ctx,
33 						   struct io_uring_regbuf_desc *desc);
34 
35 static int hpage_acct_ref(struct io_ring_ctx *ctx, struct page *hpage,
36 			  bool *acct_new)
37 {
38 	unsigned long key = (unsigned long) hpage;
39 	unsigned long count;
40 	void *entry;
41 	int ret;
42 
43 	lockdep_assert_held(&ctx->uring_lock);
44 
45 	entry = xa_load(&ctx->hpage_acct, key);
46 	if (entry) {
47 		*acct_new = false;
48 		count = xa_to_value(entry) + 1;
49 	} else {
50 		ret = xa_reserve(&ctx->hpage_acct, key, GFP_KERNEL_ACCOUNT);
51 		if (ret)
52 			return ret;
53 		*acct_new = true;
54 		count = 1;
55 	}
56 	xa_store(&ctx->hpage_acct, key, xa_mk_value(count), GFP_KERNEL_ACCOUNT);
57 	return 0;
58 }
59 
60 static bool hpage_acct_unref(struct io_ring_ctx *ctx, struct page *hpage)
61 {
62 	unsigned long key = (unsigned long) hpage;
63 	unsigned long count;
64 	void *entry;
65 
66 	lockdep_assert_held(&ctx->uring_lock);
67 
68 	entry = xa_load(&ctx->hpage_acct, key);
69 	if (WARN_ON_ONCE(!entry))
70 		return false;
71 	count = xa_to_value(entry);
72 	if (count == 1) {
73 		xa_erase(&ctx->hpage_acct, key);
74 		return true;
75 	}
76 	xa_store(&ctx->hpage_acct, key, xa_mk_value(count - 1), GFP_KERNEL_ACCOUNT);
77 	return false;
78 }
79 
80 /* only define max */
81 #define IORING_MAX_FIXED_FILES	(1U << 20)
82 #define IORING_MAX_REG_BUFFERS	(1U << 14)
83 
84 #define IO_CACHED_BVECS_SEGS	32
85 
86 static void io_iov_to_regbuf_desc(const struct iovec *iov,
87 				  struct io_uring_regbuf_desc *desc)
88 {
89 	*desc = (struct io_uring_regbuf_desc) {
90 		.type = IO_REGBUF_TYPE_UADDR,
91 		.uaddr = (u64)(uintptr_t)iov->iov_base,
92 		.size = iov->iov_len,
93 	};
94 	if (!desc->uaddr)
95 		desc->type = IO_REGBUF_TYPE_EMPTY;
96 }
97 
98 int __io_account_mem(struct user_struct *user, unsigned long nr_pages)
99 {
100 	unsigned long page_limit, cur_pages, new_pages;
101 
102 	if (!nr_pages)
103 		return 0;
104 
105 	/* Don't allow more pages than we can safely lock */
106 	page_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
107 
108 	cur_pages = atomic_long_read(&user->locked_vm);
109 	do {
110 		new_pages = cur_pages + nr_pages;
111 		if (new_pages > page_limit)
112 			return -ENOMEM;
113 	} while (!atomic_long_try_cmpxchg(&user->locked_vm,
114 					  &cur_pages, new_pages));
115 	return 0;
116 }
117 
118 void io_unaccount_mem(struct user_struct *user, struct mm_struct *mm_account,
119 		      unsigned long nr_pages)
120 {
121 	if (user)
122 		__io_unaccount_mem(user, nr_pages);
123 
124 	if (mm_account)
125 		atomic64_sub(nr_pages, &mm_account->pinned_vm);
126 }
127 
128 int io_account_mem(struct user_struct *user, struct mm_struct *mm_account,
129 		   unsigned long nr_pages)
130 {
131 	int ret;
132 
133 	if (user) {
134 		ret = __io_account_mem(user, nr_pages);
135 		if (ret)
136 			return ret;
137 	}
138 
139 	if (mm_account)
140 		atomic64_add(nr_pages, &mm_account->pinned_vm);
141 
142 	return 0;
143 }
144 
145 int io_validate_user_buf_range(u64 uaddr, u64 ulen)
146 {
147 	unsigned long tmp, base = (unsigned long)uaddr;
148 	unsigned long acct_len = (unsigned long)PAGE_ALIGN(ulen);
149 
150 	if (!ulen)
151 		return -EFAULT;
152 	/* 32-bit sanity checking */
153 	if (ulen > ULONG_MAX || uaddr > ULONG_MAX)
154 		return -EFAULT;
155 	/* cap to 1TB for 64-bit */
156 	if (ulen > SZ_1T)
157 		return -EINVAL;
158 	if (check_add_overflow(base, acct_len, &tmp))
159 		return -EOVERFLOW;
160 	return 0;
161 }
162 
163 static void io_release_ubuf(void *priv)
164 {
165 	struct io_mapped_ubuf *imu = priv;
166 	unsigned int i;
167 
168 	for (i = 0; i < imu->nr_bvecs; i++) {
169 		struct folio *folio = bvec_folio(&imu->bvec[i]);
170 
171 		unpin_user_folio(folio, 1);
172 	}
173 }
174 
175 static struct io_mapped_ubuf *io_alloc_imu(struct io_ring_ctx *ctx,
176 					   int nr_bvecs)
177 {
178 	if (nr_bvecs <= IO_CACHED_BVECS_SEGS)
179 		return io_cache_alloc(&ctx->imu_cache, GFP_KERNEL_ACCOUNT);
180 	return kvmalloc_flex(struct io_mapped_ubuf, bvec, nr_bvecs,
181 			     GFP_KERNEL_ACCOUNT);
182 }
183 
184 static void io_free_imu(struct io_ring_ctx *ctx, struct io_mapped_ubuf *imu)
185 {
186 	if (imu->nr_bvecs <= IO_CACHED_BVECS_SEGS)
187 		io_cache_free(&ctx->imu_cache, imu);
188 	else
189 		kvfree(imu);
190 }
191 
192 static unsigned long io_imu_unaccount_hpages(struct io_ring_ctx *ctx,
193 					     struct io_mapped_ubuf *imu)
194 {
195 	struct page *seen = NULL;
196 	unsigned long acct = 0;
197 	int i;
198 
199 	if (imu->flags & IO_REGBUF_F_KBUF || !ctx->user)
200 		return 0;
201 
202 	for (i = 0; i < imu->nr_bvecs; i++) {
203 		struct page *page = imu->bvec[i].bv_page;
204 		struct page *hpage;
205 
206 		if (!PageCompound(page))
207 			continue;
208 
209 		hpage = compound_head(page);
210 		if (hpage == seen)
211 			continue;
212 		seen = hpage;
213 
214 		if (hpage_acct_unref(ctx, hpage))
215 			acct += page_size(hpage) >> PAGE_SHIFT;
216 		cond_resched();
217 	}
218 
219 	return acct;
220 }
221 
222 static unsigned long io_imu_unaccount_reg_pages(struct io_ring_ctx *ctx,
223 						struct io_mapped_ubuf *imu)
224 {
225 	unsigned long acct = 0;
226 	int i;
227 
228 	if (imu->flags & IO_REGBUF_F_KBUF || !ctx->user)
229 		return 0;
230 
231 	for (i = 0; i < imu->nr_bvecs; i++) {
232 		if (!PageCompound(imu->bvec[i].bv_page))
233 			acct++;
234 	}
235 	return acct;
236 }
237 
238 static void io_buffer_unmap(struct io_ring_ctx *ctx, struct io_mapped_ubuf *imu)
239 {
240 	unsigned long acct_pages;
241 
242 	/* Compound hpages are accounted per-ring in ctx->hpage_acct */
243 	acct_pages = io_imu_unaccount_hpages(ctx, imu);
244 
245 	if (unlikely(refcount_read(&imu->refs) > 1)) {
246 		if (!refcount_dec_and_test(&imu->refs)) {
247 			if (acct_pages)
248 				io_unaccount_mem(ctx->user, ctx->mm_account, acct_pages);
249 			return;
250 		}
251 	}
252 
253 	acct_pages += io_imu_unaccount_reg_pages(ctx, imu);
254 	if (acct_pages)
255 		io_unaccount_mem(ctx->user, ctx->mm_account, acct_pages);
256 	imu->release(imu->priv);
257 	io_free_imu(ctx, imu);
258 }
259 
260 struct io_rsrc_node *io_rsrc_node_alloc(struct io_ring_ctx *ctx, int type)
261 {
262 	struct io_rsrc_node *node;
263 
264 	node = io_cache_alloc(&ctx->node_cache, GFP_KERNEL_ACCOUNT);
265 	if (node) {
266 		node->type = type;
267 		node->refs = 1;
268 		node->tag = 0;
269 		node->file_ptr = 0;
270 	}
271 	return node;
272 }
273 
274 bool io_rsrc_cache_init(struct io_ring_ctx *ctx)
275 {
276 	const int imu_cache_size = struct_size_t(struct io_mapped_ubuf, bvec,
277 						 IO_CACHED_BVECS_SEGS);
278 	const int node_size = sizeof(struct io_rsrc_node);
279 	bool ret;
280 
281 	ret = io_alloc_cache_init(&ctx->node_cache, IO_ALLOC_CACHE_MAX,
282 				  node_size, 0);
283 	ret |= io_alloc_cache_init(&ctx->imu_cache, IO_ALLOC_CACHE_MAX,
284 				   imu_cache_size, 0);
285 	return ret;
286 }
287 
288 void io_rsrc_cache_free(struct io_ring_ctx *ctx)
289 {
290 	io_alloc_cache_free(&ctx->node_cache, kfree);
291 	io_alloc_cache_free(&ctx->imu_cache, kvfree);
292 }
293 
294 static void io_clear_table_tags(struct io_rsrc_data *data)
295 {
296 	int i;
297 
298 	for (i = 0; i < data->nr; i++) {
299 		struct io_rsrc_node *node = data->nodes[i];
300 
301 		if (node)
302 			node->tag = 0;
303 	}
304 }
305 
306 __cold void io_rsrc_data_free(struct io_ring_ctx *ctx,
307 			      struct io_rsrc_data *data)
308 {
309 	if (!data->nr)
310 		return;
311 	while (data->nr--) {
312 		if (data->nodes[data->nr])
313 			io_put_rsrc_node(ctx, data->nodes[data->nr]);
314 	}
315 	kvfree(data->nodes);
316 	data->nodes = NULL;
317 	data->nr = 0;
318 }
319 
320 __cold int io_rsrc_data_alloc(struct io_rsrc_data *data, unsigned nr)
321 {
322 	data->nodes = kvmalloc_objs(struct io_rsrc_node *, nr,
323 				    GFP_KERNEL_ACCOUNT | __GFP_ZERO);
324 	if (data->nodes) {
325 		data->nr = nr;
326 		return 0;
327 	}
328 	return -ENOMEM;
329 }
330 
331 static int __io_sqe_files_update(struct io_ring_ctx *ctx,
332 				 struct io_uring_rsrc_update2 *up,
333 				 unsigned nr_args)
334 {
335 	u64 __user *tags = u64_to_user_ptr(up->tags);
336 	__s32 __user *fds = u64_to_user_ptr(up->data);
337 	int fd, i, err = 0;
338 	unsigned int done;
339 
340 	if (!ctx->file_table.data.nr)
341 		return -ENXIO;
342 	if (up->offset + nr_args > ctx->file_table.data.nr)
343 		return -EINVAL;
344 	if (up->flags)
345 		return -EINVAL;
346 
347 	for (done = 0; done < nr_args; done++) {
348 		u64 tag = 0;
349 
350 		if ((tags && copy_from_user(&tag, &tags[done], sizeof(tag))) ||
351 		    copy_from_user(&fd, &fds[done], sizeof(fd))) {
352 			err = -EFAULT;
353 			break;
354 		}
355 		if ((fd == IORING_REGISTER_FILES_SKIP || fd == -1) && tag) {
356 			err = -EINVAL;
357 			break;
358 		}
359 		if (fd == IORING_REGISTER_FILES_SKIP)
360 			continue;
361 
362 		i = up->offset + done;
363 		if (i >= ctx->file_table.data.nr)
364 			break;
365 		i = array_index_nospec(i, ctx->file_table.data.nr);
366 		if (io_reset_rsrc_node(ctx, &ctx->file_table.data, i))
367 			io_file_bitmap_clear(&ctx->file_table, i);
368 
369 		if (fd != -1) {
370 			struct file *file = fget(fd);
371 			struct io_rsrc_node *node;
372 
373 			if (!file) {
374 				err = -EBADF;
375 				break;
376 			}
377 			/*
378 			 * Don't allow io_uring instances to be registered.
379 			 */
380 			if (io_is_uring_fops(file)) {
381 				fput(file);
382 				err = -EBADF;
383 				break;
384 			}
385 			node = io_rsrc_node_alloc(ctx, IORING_RSRC_FILE);
386 			if (!node) {
387 				err = -ENOMEM;
388 				fput(file);
389 				break;
390 			}
391 			ctx->file_table.data.nodes[i] = node;
392 			if (tag)
393 				node->tag = tag;
394 			io_fixed_file_set(node, file);
395 			io_file_bitmap_set(&ctx->file_table, i);
396 		}
397 	}
398 	return done ? done : err;
399 }
400 
401 static int __io_sqe_buffers_update(struct io_ring_ctx *ctx,
402 				   struct io_uring_rsrc_update2 *up,
403 				   unsigned int nr_args)
404 {
405 	bool extended = up->flags & IORING_RSRC_UPDATE_EXTENDED;
406 	u64 __user *tags = u64_to_user_ptr(up->tags);
407 	u64 user_data = up->data;
408 	__u32 done;
409 	int i, err;
410 
411 	if (!ctx->buf_table.nr)
412 		return -ENXIO;
413 	if (up->offset + nr_args > ctx->buf_table.nr)
414 		return -EINVAL;
415 	if (up->flags & ~IORING_RSRC_UPDATE_EXTENDED)
416 		return -EINVAL;
417 
418 	for (done = 0; done < nr_args; done++) {
419 		struct io_uring_regbuf_desc desc;
420 		struct io_rsrc_node *node;
421 		u64 tag = 0;
422 
423 		if (tags && copy_from_user(&tag, &tags[done], sizeof(tag))) {
424 			err = -EFAULT;
425 			break;
426 		}
427 
428 		if (extended) {
429 			if (copy_from_user(&desc, u64_to_user_ptr(user_data),
430 					   sizeof(desc))) {
431 				err = -EFAULT;
432 				break;
433 			}
434 			user_data += sizeof(desc);
435 		} else {
436 			struct iovec __user *uvec = u64_to_user_ptr(user_data);
437 			struct iovec fast_iov, *iov;
438 
439 			if (io_is_compat(ctx))
440 				user_data += sizeof(struct compat_iovec);
441 			else
442 				user_data += sizeof(struct iovec);
443 
444 			iov = iovec_from_user(uvec, 1, 1, &fast_iov, io_is_compat(ctx));
445 			if (IS_ERR(iov)) {
446 				err = PTR_ERR(iov);
447 				break;
448 			}
449 			io_iov_to_regbuf_desc(iov, &desc);
450 		}
451 
452 		node = io_sqe_buffer_register(ctx, &desc);
453 		if (IS_ERR(node)) {
454 			err = PTR_ERR(node);
455 			break;
456 		}
457 
458 		if (tag) {
459 			if (!node) {
460 				err = -EINVAL;
461 				break;
462 			}
463 			node->tag = tag;
464 		}
465 		i = array_index_nospec(up->offset + done, ctx->buf_table.nr);
466 		io_reset_rsrc_node(ctx, &ctx->buf_table, i);
467 		ctx->buf_table.nodes[i] = node;
468 	}
469 	return done ? done : err;
470 }
471 
472 static int __io_register_rsrc_update(struct io_ring_ctx *ctx, unsigned type,
473 				     struct io_uring_rsrc_update2 *up,
474 				     unsigned nr_args)
475 {
476 	__u32 tmp;
477 
478 	lockdep_assert_held(&ctx->uring_lock);
479 
480 	if (check_add_overflow(up->offset, nr_args, &tmp))
481 		return -EOVERFLOW;
482 
483 	switch (type) {
484 	case IORING_RSRC_FILE:
485 		return __io_sqe_files_update(ctx, up, nr_args);
486 	case IORING_RSRC_BUFFER:
487 		return __io_sqe_buffers_update(ctx, up, nr_args);
488 	}
489 	return -EINVAL;
490 }
491 
492 int io_register_files_update(struct io_ring_ctx *ctx, void __user *arg,
493 			     unsigned nr_args)
494 {
495 	struct io_uring_rsrc_update2 up;
496 
497 	if (!nr_args)
498 		return -EINVAL;
499 	memset(&up, 0, sizeof(up));
500 	if (copy_from_user(&up, arg, sizeof(struct io_uring_rsrc_update)))
501 		return -EFAULT;
502 	if (up.resv2)
503 		return -EINVAL;
504 	return __io_register_rsrc_update(ctx, IORING_RSRC_FILE, &up, nr_args);
505 }
506 
507 int io_register_rsrc_update(struct io_ring_ctx *ctx, void __user *arg,
508 			    unsigned size, unsigned type)
509 {
510 	struct io_uring_rsrc_update2 up;
511 
512 	if (size != sizeof(up))
513 		return -EINVAL;
514 	if (copy_from_user(&up, arg, sizeof(up)))
515 		return -EFAULT;
516 	if (!up.nr || up.resv2)
517 		return -EINVAL;
518 	return __io_register_rsrc_update(ctx, type, &up, up.nr);
519 }
520 
521 __cold int io_register_rsrc(struct io_ring_ctx *ctx, void __user *arg,
522 			    unsigned int size, unsigned int type)
523 {
524 	struct io_uring_rsrc_register rr;
525 
526 	/* keep it extendible */
527 	if (size != sizeof(rr))
528 		return -EINVAL;
529 
530 	memset(&rr, 0, sizeof(rr));
531 	if (copy_from_user(&rr, arg, size))
532 		return -EFAULT;
533 	if (!rr.nr || rr.resv2)
534 		return -EINVAL;
535 	if (rr.flags & ~IORING_RSRC_REGISTER_SPARSE)
536 		return -EINVAL;
537 
538 	switch (type) {
539 	case IORING_RSRC_FILE:
540 		if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
541 			break;
542 		return io_sqe_files_register(ctx, u64_to_user_ptr(rr.data),
543 					     rr.nr, u64_to_user_ptr(rr.tags));
544 	case IORING_RSRC_BUFFER:
545 		if (rr.flags & IORING_RSRC_REGISTER_SPARSE && rr.data)
546 			break;
547 		return io_sqe_buffers_register(ctx, u64_to_user_ptr(rr.data),
548 					       rr.nr, u64_to_user_ptr(rr.tags));
549 	}
550 	return -EINVAL;
551 }
552 
553 int io_files_update_prep(struct io_kiocb *req, const struct io_uring_sqe *sqe)
554 {
555 	struct io_rsrc_update *up = io_kiocb_to_cmd(req, struct io_rsrc_update);
556 
557 	if (unlikely(req->flags & (REQ_F_FIXED_FILE | REQ_F_BUFFER_SELECT)))
558 		return -EINVAL;
559 	if (sqe->rw_flags || sqe->splice_fd_in)
560 		return -EINVAL;
561 
562 	up->offset = READ_ONCE(sqe->off);
563 	up->nr_args = READ_ONCE(sqe->len);
564 	if (!up->nr_args)
565 		return -EINVAL;
566 	up->arg = READ_ONCE(sqe->addr);
567 	return 0;
568 }
569 
570 static int io_files_update_with_index_alloc(struct io_kiocb *req,
571 					    unsigned int issue_flags)
572 {
573 	struct io_rsrc_update *up = io_kiocb_to_cmd(req, struct io_rsrc_update);
574 	__s32 __user *fds = u64_to_user_ptr(up->arg);
575 	struct io_ring_ctx *ctx = req->ctx;
576 	unsigned int done;
577 	struct file *file;
578 	int ret, fd;
579 
580 	if (!ctx->file_table.data.nr)
581 		return -ENXIO;
582 
583 	for (done = 0; done < up->nr_args; done++) {
584 		if (get_user(fd, &fds[done])) {
585 			ret = -EFAULT;
586 			break;
587 		}
588 
589 		file = fget(fd);
590 		if (!file) {
591 			ret = -EBADF;
592 			break;
593 		}
594 		/*
595 		 * Hold the lock across the put_user(), if it's dropped the
596 		 * slot can be closed and reused before the error path runs.
597 		 */
598 		io_ring_submit_lock(ctx, issue_flags);
599 		ret = __io_fixed_fd_install(ctx, file,
600 					    IORING_FILE_INDEX_ALLOC);
601 		if (ret < 0) {
602 			io_ring_submit_unlock(ctx, issue_flags);
603 			fput(file);
604 			break;
605 		}
606 		if (put_user(ret, &fds[done])) {
607 			io_fixed_fd_remove(ctx, ret);
608 			io_ring_submit_unlock(ctx, issue_flags);
609 			ret = -EFAULT;
610 			break;
611 		}
612 		io_ring_submit_unlock(ctx, issue_flags);
613 	}
614 
615 	if (done)
616 		return done;
617 	return ret;
618 }
619 
620 int io_files_update(struct io_kiocb *req, unsigned int issue_flags)
621 {
622 	struct io_rsrc_update *up = io_kiocb_to_cmd(req, struct io_rsrc_update);
623 	struct io_ring_ctx *ctx = req->ctx;
624 	struct io_uring_rsrc_update2 up2;
625 	int ret;
626 
627 	memset(&up2, 0, sizeof(up2));
628 	up2.offset = up->offset;
629 	up2.data = up->arg;
630 
631 	if (up->offset == IORING_FILE_INDEX_ALLOC) {
632 		ret = io_files_update_with_index_alloc(req, issue_flags);
633 	} else {
634 		io_ring_submit_lock(ctx, issue_flags);
635 		ret = __io_register_rsrc_update(ctx, IORING_RSRC_FILE,
636 						&up2, up->nr_args);
637 		io_ring_submit_unlock(ctx, issue_flags);
638 	}
639 
640 	if (ret < 0)
641 		req_set_fail(req);
642 	io_req_set_res(req, ret, 0);
643 	return IOU_COMPLETE;
644 }
645 
646 void io_free_rsrc_node(struct io_ring_ctx *ctx, struct io_rsrc_node *node)
647 {
648 	if (node->tag)
649 		io_post_aux_cqe(ctx, node->tag, 0, 0);
650 
651 	switch (node->type) {
652 	case IORING_RSRC_FILE:
653 		fput(io_slot_file(node));
654 		break;
655 	case IORING_RSRC_BUFFER:
656 		io_buffer_unmap(ctx, node->buf);
657 		break;
658 	default:
659 		WARN_ON_ONCE(1);
660 		break;
661 	}
662 
663 	io_cache_free(&ctx->node_cache, node);
664 }
665 
666 int io_sqe_files_unregister(struct io_ring_ctx *ctx)
667 {
668 	if (!ctx->file_table.data.nr)
669 		return -ENXIO;
670 
671 	io_free_file_tables(ctx, &ctx->file_table);
672 	io_file_table_set_alloc_range(ctx, 0, 0);
673 	return 0;
674 }
675 
676 int io_sqe_files_register(struct io_ring_ctx *ctx, void __user *arg,
677 			  unsigned nr_args, u64 __user *tags)
678 {
679 	__s32 __user *fds = (__s32 __user *) arg;
680 	struct file *file;
681 	int fd, ret;
682 	unsigned i;
683 
684 	if (ctx->file_table.data.nr)
685 		return -EBUSY;
686 	if (!nr_args)
687 		return -EINVAL;
688 	if (nr_args > IORING_MAX_FIXED_FILES)
689 		return -EMFILE;
690 	if (nr_args > rlimit(RLIMIT_NOFILE))
691 		return -EMFILE;
692 	if (!io_alloc_file_tables(ctx, &ctx->file_table, nr_args))
693 		return -ENOMEM;
694 
695 	for (i = 0; i < nr_args; i++) {
696 		struct io_rsrc_node *node;
697 		u64 tag = 0;
698 
699 		ret = -EFAULT;
700 		if (tags && copy_from_user(&tag, &tags[i], sizeof(tag)))
701 			goto fail;
702 		if (fds && copy_from_user(&fd, &fds[i], sizeof(fd)))
703 			goto fail;
704 		/* allow sparse sets */
705 		if (!fds || fd == -1) {
706 			ret = -EINVAL;
707 			if (tag)
708 				goto fail;
709 			continue;
710 		}
711 
712 		file = fget(fd);
713 		ret = -EBADF;
714 		if (unlikely(!file))
715 			goto fail;
716 
717 		/*
718 		 * Don't allow io_uring instances to be registered.
719 		 */
720 		if (io_is_uring_fops(file)) {
721 			fput(file);
722 			goto fail;
723 		}
724 		ret = -ENOMEM;
725 		node = io_rsrc_node_alloc(ctx, IORING_RSRC_FILE);
726 		if (!node) {
727 			fput(file);
728 			goto fail;
729 		}
730 		if (tag)
731 			node->tag = tag;
732 		ctx->file_table.data.nodes[i] = node;
733 		io_fixed_file_set(node, file);
734 		io_file_bitmap_set(&ctx->file_table, i);
735 	}
736 
737 	/* default it to the whole table */
738 	io_file_table_set_alloc_range(ctx, 0, ctx->file_table.data.nr);
739 	return 0;
740 fail:
741 	io_clear_table_tags(&ctx->file_table.data);
742 	io_sqe_files_unregister(ctx);
743 	return ret;
744 }
745 
746 int io_sqe_buffers_unregister(struct io_ring_ctx *ctx)
747 {
748 	if (!ctx->buf_table.nr)
749 		return -ENXIO;
750 	io_rsrc_data_free(ctx, &ctx->buf_table);
751 	return 0;
752 }
753 
754 /*
755  * Undo hpage_acct_ref() calls made during io_buffer_account_pin() on failure.
756  * This operates on the pages array since imu->bvec isn't populated yet.
757  */
758 static void io_buffer_unaccount_hpages(struct io_ring_ctx *ctx,
759 				       struct page **pages, int nr_pages)
760 {
761 	struct page *seen = NULL;
762 	int i;
763 
764 	if (!ctx->user)
765 		return;
766 
767 	for (i = 0; i < nr_pages; i++) {
768 		struct page *hpage;
769 
770 		if (!PageCompound(pages[i]))
771 			continue;
772 
773 		hpage = compound_head(pages[i]);
774 		if (hpage == seen)
775 			continue;
776 		seen = hpage;
777 
778 		hpage_acct_unref(ctx, hpage);
779 		cond_resched();
780 	}
781 }
782 
783 static int io_buffer_account_pin(struct io_ring_ctx *ctx, struct page **pages,
784 				 int nr_pages)
785 {
786 	unsigned long acct_pages = 0;
787 	struct page *seen = NULL;
788 	int i, ret;
789 
790 	if (!ctx->user)
791 		return 0;
792 
793 	for (i = 0; i < nr_pages; i++) {
794 		struct page *hpage;
795 		bool acct_new;
796 
797 		if (!PageCompound(pages[i])) {
798 			acct_pages++;
799 			continue;
800 		}
801 
802 		hpage = compound_head(pages[i]);
803 		if (hpage == seen)
804 			continue;
805 		seen = hpage;
806 
807 		ret = hpage_acct_ref(ctx, hpage, &acct_new);
808 		if (ret) {
809 			io_buffer_unaccount_hpages(ctx, pages, i);
810 			return ret;
811 		}
812 		if (acct_new)
813 			acct_pages += page_size(hpage) >> PAGE_SHIFT;
814 		cond_resched();
815 	}
816 
817 	/* Try to account the memory */
818 	if (acct_pages) {
819 		ret = io_account_mem(ctx->user, ctx->mm_account, acct_pages);
820 		if (ret) {
821 			/* Undo the refs we just added */
822 			io_buffer_unaccount_hpages(ctx, pages, nr_pages);
823 			return ret;
824 		}
825 	}
826 
827 	return 0;
828 }
829 
830 static bool io_coalesce_buffer(struct page ***pages, int *nr_pages,
831 				struct io_imu_folio_data *data)
832 {
833 	struct page **page_array = *pages, **new_array = NULL;
834 	unsigned nr_pages_left = *nr_pages;
835 	unsigned nr_folios = data->nr_folios;
836 	unsigned i, j;
837 
838 	/* Store head pages only*/
839 	new_array = kvmalloc_objs(struct page *, nr_folios);
840 	if (!new_array)
841 		return false;
842 
843 	for (i = 0, j = 0; i < nr_folios; i++) {
844 		struct page *p = compound_head(page_array[j]);
845 		struct folio *folio = page_folio(p);
846 		unsigned int nr;
847 
848 		WARN_ON_ONCE(i > 0 && p != page_array[j]);
849 
850 		nr = i ? data->nr_pages_mid : data->nr_pages_head;
851 		nr = min(nr, nr_pages_left);
852 		/* Drop all but one ref, the entire folio will remain pinned. */
853 		if (nr > 1)
854 			unpin_user_folio(folio, nr - 1);
855 		j += nr;
856 		nr_pages_left -= nr;
857 		new_array[i] = p;
858 	}
859 
860 	WARN_ON_ONCE(j != *nr_pages);
861 
862 	kvfree(page_array);
863 	*pages = new_array;
864 	*nr_pages = nr_folios;
865 	return true;
866 }
867 
868 bool io_check_coalesce_buffer(struct page **page_array, int nr_pages,
869 			      struct io_imu_folio_data *data)
870 {
871 	struct folio *folio = page_folio(page_array[0]);
872 	unsigned int count = 1, nr_folios = 1;
873 	int i;
874 
875 	data->nr_pages_mid = folio_nr_pages(folio);
876 	data->folio_shift = folio_shift(folio);
877 	data->first_folio_page_idx = folio_page_idx(folio, page_array[0]);
878 
879 	/*
880 	 * Check if pages are contiguous inside a folio, and all folios have
881 	 * the same page count except for the head and tail.
882 	 */
883 	for (i = 1; i < nr_pages; i++) {
884 		if (page_folio(page_array[i]) == folio &&
885 			page_array[i] == page_array[i-1] + 1) {
886 			count++;
887 			continue;
888 		}
889 
890 		if (nr_folios == 1) {
891 			if (folio_page_idx(folio, page_array[i-1]) !=
892 				data->nr_pages_mid - 1)
893 				return false;
894 
895 			data->nr_pages_head = count;
896 		} else if (count != data->nr_pages_mid) {
897 			return false;
898 		}
899 
900 		folio = page_folio(page_array[i]);
901 		if (folio_size(folio) != (1UL << data->folio_shift) ||
902 			folio_page_idx(folio, page_array[i]) != 0)
903 			return false;
904 
905 		count = 1;
906 		nr_folios++;
907 	}
908 	if (nr_folios == 1)
909 		data->nr_pages_head = count;
910 
911 	data->nr_folios = nr_folios;
912 	return true;
913 }
914 
915 static struct io_rsrc_node *io_register_dmabuf_desc(struct io_ring_ctx *ctx,
916 						    struct io_uring_regbuf_desc *desc)
917 {
918 	struct io_rsrc_node *node = NULL;
919 	struct io_mapped_ubuf *imu = NULL;
920 	int ret;
921 
922 	node = io_rsrc_node_alloc(ctx, IORING_RSRC_BUFFER);
923 	if (!node)
924 		return ERR_PTR(-ENOMEM);
925 
926 	imu = io_alloc_imu(ctx, 0);
927 	if (!imu) {
928 		ret = -ENOMEM;
929 		goto err;
930 	}
931 	memset(imu, 0, sizeof(*imu));
932 	refcount_set(&imu->refs, 1);
933 
934 	ret = io_register_dmabuf(ctx, desc, imu);
935 	if (ret)
936 		goto err;
937 	node->buf = imu;
938 	return node;
939 err:
940 	if (imu)
941 		io_free_imu(ctx, imu);
942 	if (node)
943 		io_cache_free(&ctx->node_cache, node);
944 	return ERR_PTR(ret);
945 }
946 
947 static struct io_rsrc_node *io_sqe_buffer_register(struct io_ring_ctx *ctx,
948 						   struct io_uring_regbuf_desc *desc)
949 {
950 	unsigned long uaddr = (unsigned long)desc->uaddr;
951 	size_t size = desc->size;
952 	struct io_mapped_ubuf *imu = NULL;
953 	struct page **pages = NULL;
954 	struct io_rsrc_node *node;
955 	unsigned long off;
956 	int ret, nr_pages, i;
957 	struct io_imu_folio_data data;
958 	bool coalesced = false;
959 
960 	if (uaddr != desc->uaddr || size != desc->size)
961 		return ERR_PTR(-EOVERFLOW);
962 	if (desc->type >= __IO_REGBUF_TYPE_MAX)
963 		return ERR_PTR(-EINVAL);
964 	if (!mem_is_zero(&desc->__resv, sizeof(desc->__resv)) || desc->flags)
965 		return ERR_PTR(-EINVAL);
966 
967 	if (desc->type == IO_REGBUF_TYPE_DMABUF)
968 		return io_register_dmabuf_desc(ctx, desc);
969 
970 	if (desc->dmabuf_fd || desc->target_fd)
971 		return ERR_PTR(-EINVAL);
972 
973 	if (desc->type == IO_REGBUF_TYPE_EMPTY) {
974 		if (uaddr || size)
975 			return ERR_PTR(-EFAULT);
976 		/* remove the buffer without installing a new one */
977 		return NULL;
978 	}
979 
980 	ret = io_validate_user_buf_range(uaddr, size);
981 	if (ret)
982 		return ERR_PTR(ret);
983 
984 	node = io_rsrc_node_alloc(ctx, IORING_RSRC_BUFFER);
985 	if (!node)
986 		return ERR_PTR(-ENOMEM);
987 
988 	ret = -ENOMEM;
989 	pages = io_pin_pages(uaddr, size, &nr_pages);
990 	if (IS_ERR(pages)) {
991 		ret = PTR_ERR(pages);
992 		pages = NULL;
993 		goto done;
994 	}
995 
996 	/* If it's huge page(s), try to coalesce them into fewer bvec entries */
997 	if (nr_pages > 1 && io_check_coalesce_buffer(pages, nr_pages, &data)) {
998 		if (data.nr_pages_mid != 1)
999 			coalesced = io_coalesce_buffer(&pages, &nr_pages, &data);
1000 	}
1001 
1002 	imu = io_alloc_imu(ctx, nr_pages);
1003 	if (!imu)
1004 		goto done;
1005 
1006 	imu->nr_bvecs = nr_pages;
1007 	ret = io_buffer_account_pin(ctx, pages, nr_pages);
1008 	if (ret)
1009 		goto done;
1010 
1011 	/* store original address for later verification */
1012 	imu->ubuf = uaddr;
1013 	imu->len = size;
1014 	imu->folio_shift = PAGE_SHIFT;
1015 	imu->release = io_release_ubuf;
1016 	imu->priv = imu;
1017 	imu->flags = 0;
1018 	imu->dir = IO_BUF_DEST | IO_BUF_SOURCE;
1019 	if (coalesced)
1020 		imu->folio_shift = data.folio_shift;
1021 	refcount_set(&imu->refs, 1);
1022 
1023 	off = uaddr & ~PAGE_MASK;
1024 	if (coalesced)
1025 		off += data.first_folio_page_idx << PAGE_SHIFT;
1026 
1027 	node->buf = imu;
1028 	ret = 0;
1029 
1030 	for (i = 0; i < nr_pages; i++) {
1031 		size_t vec_len;
1032 
1033 		vec_len = min_t(size_t, size, (1UL << imu->folio_shift) - off);
1034 		bvec_set_page(&imu->bvec[i], pages[i], vec_len, off);
1035 		off = 0;
1036 		size -= vec_len;
1037 	}
1038 done:
1039 	if (ret) {
1040 		if (imu)
1041 			io_free_imu(ctx, imu);
1042 		if (pages) {
1043 			for (i = 0; i < nr_pages; i++)
1044 				unpin_user_folio(page_folio(pages[i]), 1);
1045 		}
1046 		io_cache_free(&ctx->node_cache, node);
1047 		node = ERR_PTR(ret);
1048 	}
1049 	kvfree(pages);
1050 	return node;
1051 }
1052 
1053 int io_sqe_buffers_register(struct io_ring_ctx *ctx, void __user *arg,
1054 			    unsigned int nr_args, u64 __user *tags)
1055 {
1056 	struct io_rsrc_data data;
1057 	struct iovec fast_iov, *iov = &fast_iov;
1058 	const struct iovec __user *uvec;
1059 	int i, ret;
1060 
1061 	BUILD_BUG_ON(IORING_MAX_REG_BUFFERS >= (1u << 16));
1062 
1063 	if (ctx->buf_table.nr)
1064 		return -EBUSY;
1065 	if (!nr_args || nr_args > IORING_MAX_REG_BUFFERS)
1066 		return -EINVAL;
1067 	ret = io_rsrc_data_alloc(&data, nr_args);
1068 	if (ret)
1069 		return ret;
1070 
1071 	if (!arg)
1072 		memset(iov, 0, sizeof(*iov));
1073 
1074 	for (i = 0; i < nr_args; i++) {
1075 		struct io_uring_regbuf_desc desc;
1076 		struct io_rsrc_node *node;
1077 		u64 tag = 0;
1078 
1079 		if (arg) {
1080 			uvec = (struct iovec __user *) arg;
1081 			iov = iovec_from_user(uvec, 1, 1, &fast_iov, io_is_compat(ctx));
1082 			if (IS_ERR(iov)) {
1083 				ret = PTR_ERR(iov);
1084 				break;
1085 			}
1086 			if (io_is_compat(ctx))
1087 				arg += sizeof(struct compat_iovec);
1088 			else
1089 				arg += sizeof(struct iovec);
1090 		}
1091 
1092 		if (tags) {
1093 			if (copy_from_user(&tag, &tags[i], sizeof(tag))) {
1094 				ret = -EFAULT;
1095 				break;
1096 			}
1097 		}
1098 
1099 		io_iov_to_regbuf_desc(iov, &desc);
1100 		node = io_sqe_buffer_register(ctx, &desc);
1101 		if (IS_ERR(node)) {
1102 			ret = PTR_ERR(node);
1103 			break;
1104 		}
1105 		if (tag) {
1106 			if (!node) {
1107 				ret = -EINVAL;
1108 				break;
1109 			}
1110 			node->tag = tag;
1111 		}
1112 		data.nodes[i] = node;
1113 	}
1114 
1115 	ctx->buf_table = data;
1116 	if (ret) {
1117 		io_clear_table_tags(&ctx->buf_table);
1118 		io_sqe_buffers_unregister(ctx);
1119 	}
1120 	return ret;
1121 }
1122 
1123 static struct io_mapped_ubuf *io_kernel_buffer_init(struct io_ring_ctx *ctx,
1124 						    unsigned int nr_bvecs,
1125 						    unsigned int total_bytes,
1126 						    u8 dir,
1127 						    void (*release)(void *),
1128 						    void *priv,
1129 						    unsigned int index)
1130 {
1131 	struct io_rsrc_data *data = &ctx->buf_table;
1132 	struct io_mapped_ubuf *imu;
1133 	struct io_rsrc_node *node;
1134 
1135 	if (index >= data->nr)
1136 		return ERR_PTR(-EINVAL);
1137 	index = array_index_nospec(index, data->nr);
1138 
1139 	if (data->nodes[index])
1140 		return ERR_PTR(-EBUSY);
1141 
1142 	node = io_rsrc_node_alloc(ctx, IORING_RSRC_BUFFER);
1143 	if (!node)
1144 		return ERR_PTR(-ENOMEM);
1145 
1146 	imu = io_alloc_imu(ctx, nr_bvecs);
1147 	if (!imu) {
1148 		io_cache_free(&ctx->node_cache, node);
1149 		return ERR_PTR(-ENOMEM);
1150 	}
1151 
1152 	imu->ubuf = 0;
1153 	imu->len = total_bytes;
1154 	imu->folio_shift = PAGE_SHIFT;
1155 	imu->nr_bvecs = nr_bvecs;
1156 	refcount_set(&imu->refs, 1);
1157 	imu->release = release;
1158 	imu->priv = priv;
1159 	imu->dir = dir;
1160 	imu->flags = IO_REGBUF_F_KBUF;
1161 
1162 	node->buf = imu;
1163 	data->nodes[index] = node;
1164 
1165 	return imu;
1166 }
1167 
1168 int io_buffer_register_request(struct io_uring_cmd *cmd, struct request *rq,
1169 			       void (*release)(void *), unsigned int index,
1170 			       unsigned int issue_flags)
1171 {
1172 	struct io_ring_ctx *ctx = cmd_to_io_kiocb(cmd)->ctx;
1173 	struct req_iterator rq_iter;
1174 	struct io_mapped_ubuf *imu;
1175 	struct bio_vec bv;
1176 	/*
1177 	 * blk_rq_nr_phys_segments() may overestimate the number of bvecs
1178 	 * but avoids needing to iterate over the bvecs
1179 	 */
1180 	unsigned int nr_bvecs = blk_rq_nr_phys_segments(rq);
1181 	unsigned int total_bytes = blk_rq_bytes(rq);
1182 	int ret = 0;
1183 
1184 	io_ring_submit_lock(ctx, issue_flags);
1185 
1186 	imu = io_kernel_buffer_init(ctx, nr_bvecs, total_bytes,
1187 				    1 << rq_data_dir(rq), release, rq, index);
1188 	if (IS_ERR(imu)) {
1189 		ret = PTR_ERR(imu);
1190 		goto unlock;
1191 	}
1192 
1193 	nr_bvecs = 0;
1194 	rq_for_each_bvec(bv, rq, rq_iter)
1195 		imu->bvec[nr_bvecs++] = bv;
1196 	imu->nr_bvecs = nr_bvecs;
1197 
1198 unlock:
1199 	io_ring_submit_unlock(ctx, issue_flags);
1200 	return ret;
1201 }
1202 EXPORT_SYMBOL_GPL(io_buffer_register_request);
1203 
1204 /*
1205  * bvs is copied internally. caller may free it on return.
1206  */
1207 int io_buffer_register_bvec(struct io_uring_cmd *cmd, const struct bio_vec *bvs,
1208 			    unsigned int nr_bvecs, void (*release)(void *),
1209 			    void *priv, u8 dir, unsigned int index,
1210 			    unsigned int issue_flags)
1211 {
1212 	struct io_ring_ctx *ctx = cmd_to_io_kiocb(cmd)->ctx;
1213 	struct io_mapped_ubuf *imu;
1214 	struct bio_vec *bvec;
1215 	unsigned int i, total_bytes = 0;
1216 	int ret = 0;
1217 
1218 	for (i = 0; i < nr_bvecs; i++)
1219 		total_bytes += bvs[i].bv_len;
1220 
1221 	io_ring_submit_lock(ctx, issue_flags);
1222 	imu = io_kernel_buffer_init(ctx, nr_bvecs, total_bytes, dir, release,
1223 				    priv, index);
1224 	if (IS_ERR(imu)) {
1225 		ret = PTR_ERR(imu);
1226 		goto unlock;
1227 	}
1228 
1229 	bvec = imu->bvec;
1230 	for (i = 0; i < nr_bvecs; i++)
1231 		bvec[i] = bvs[i];
1232 
1233 unlock:
1234 	io_ring_submit_unlock(ctx, issue_flags);
1235 	return ret;
1236 }
1237 EXPORT_SYMBOL_GPL(io_buffer_register_bvec);
1238 
1239 int io_buffer_unregister(struct io_uring_cmd *cmd, unsigned int index,
1240 			 unsigned int issue_flags)
1241 {
1242 	struct io_ring_ctx *ctx = cmd_to_io_kiocb(cmd)->ctx;
1243 	struct io_rsrc_data *data = &ctx->buf_table;
1244 	struct io_rsrc_node *node;
1245 	int ret = 0;
1246 
1247 	io_ring_submit_lock(ctx, issue_flags);
1248 	if (index >= data->nr) {
1249 		ret = -EINVAL;
1250 		goto unlock;
1251 	}
1252 	index = array_index_nospec(index, data->nr);
1253 
1254 	node = data->nodes[index];
1255 	if (!node) {
1256 		ret = -EINVAL;
1257 		goto unlock;
1258 	}
1259 	if (!(node->buf->flags & IO_REGBUF_F_KBUF)) {
1260 		ret = -EBUSY;
1261 		goto unlock;
1262 	}
1263 
1264 	io_put_rsrc_node(ctx, node);
1265 	data->nodes[index] = NULL;
1266 unlock:
1267 	io_ring_submit_unlock(ctx, issue_flags);
1268 	return ret;
1269 }
1270 EXPORT_SYMBOL_GPL(io_buffer_unregister);
1271 
1272 static int validate_fixed_range(u64 buf_addr, size_t len,
1273 				const struct io_mapped_ubuf *imu)
1274 {
1275 	u64 buf_end;
1276 
1277 	if (unlikely(check_add_overflow(buf_addr, (u64)len, &buf_end)))
1278 		return -EFAULT;
1279 	/* not inside the mapped region */
1280 	if (unlikely(buf_addr < imu->ubuf || buf_end > (imu->ubuf + imu->len)))
1281 		return -EFAULT;
1282 	if (unlikely(len > MAX_RW_COUNT))
1283 		return -EFAULT;
1284 	return 0;
1285 }
1286 
1287 static int io_import_kbuf(int ddir, struct iov_iter *iter,
1288 			  struct io_mapped_ubuf *imu, size_t len, size_t offset)
1289 {
1290 	size_t count = len + offset;
1291 
1292 	iov_iter_bvec(iter, ddir, imu->bvec, imu->nr_bvecs, count);
1293 	iov_iter_advance(iter, offset);
1294 	return 0;
1295 }
1296 
1297 static int io_import_fixed(struct io_kiocb *req,
1298 			   int ddir, struct iov_iter *iter,
1299 			   struct io_mapped_ubuf *imu,
1300 			   u64 buf_addr, size_t len,
1301 			   unsigned issue_flags,
1302 			   unsigned import_flags)
1303 {
1304 	const struct bio_vec *bvec;
1305 	size_t folio_mask;
1306 	unsigned nr_segs;
1307 	size_t offset;
1308 	int ret;
1309 
1310 	ret = validate_fixed_range(buf_addr, len, imu);
1311 	if (unlikely(ret))
1312 		return ret;
1313 	if (!(imu->dir & (1 << ddir)))
1314 		return -EFAULT;
1315 	if (unlikely(!len)) {
1316 		iov_iter_bvec(iter, ddir, NULL, 0, 0);
1317 		return 0;
1318 	}
1319 
1320 	offset = buf_addr - imu->ubuf;
1321 
1322 	if (imu->flags & IO_REGBUF_F_DMABUF) {
1323 		if (!(import_flags & IO_REGBUF_IMPORT_ALLOW_DMABUF))
1324 			return -EFAULT;
1325 		return io_import_dmabuf_map(req, ddir, iter, imu, len, offset);
1326 	}
1327 	if (imu->flags & IO_REGBUF_F_KBUF)
1328 		return io_import_kbuf(ddir, iter, imu, len, offset);
1329 
1330 	/*
1331 	 * Don't use iov_iter_advance() here, as it's really slow for
1332 	 * using the latter parts of a big fixed buffer - it iterates
1333 	 * over each segment manually. We can cheat a bit here for user
1334 	 * registered nodes, because we know that:
1335 	 *
1336 	 * 1) it's a BVEC iter, we set it up
1337 	 * 2) all bvecs are the same in size, except potentially the
1338 	 *    first and last bvec
1339 	 */
1340 	folio_mask = (1UL << imu->folio_shift) - 1;
1341 	bvec = imu->bvec;
1342 	if (offset >= bvec->bv_len) {
1343 		unsigned long seg_skip;
1344 
1345 		/* skip first vec */
1346 		offset -= bvec->bv_len;
1347 		seg_skip = 1 + (offset >> imu->folio_shift);
1348 		bvec += seg_skip;
1349 		offset &= folio_mask;
1350 	}
1351 	nr_segs = (offset + len + bvec->bv_offset + folio_mask) >> imu->folio_shift;
1352 	iov_iter_bvec(iter, ddir, bvec, nr_segs, len);
1353 	iter->iov_offset = offset;
1354 	return 0;
1355 }
1356 
1357 inline struct io_rsrc_node *io_find_buf_node(struct io_kiocb *req,
1358 					     unsigned issue_flags)
1359 {
1360 	struct io_ring_ctx *ctx = req->ctx;
1361 	struct io_rsrc_node *node;
1362 
1363 	if (req->flags & REQ_F_BUF_NODE)
1364 		return req->buf_node;
1365 	req->flags |= REQ_F_BUF_NODE;
1366 
1367 	io_ring_submit_lock(ctx, issue_flags);
1368 	node = io_rsrc_node_lookup(&ctx->buf_table, req->buf_index);
1369 	if (node) {
1370 		node->refs++;
1371 		req->buf_node = node;
1372 		io_ring_submit_unlock(ctx, issue_flags);
1373 		return node;
1374 	}
1375 	req->flags &= ~REQ_F_BUF_NODE;
1376 	io_ring_submit_unlock(ctx, issue_flags);
1377 	return NULL;
1378 }
1379 
1380 int __io_import_reg_buf(struct io_kiocb *req, struct iov_iter *iter,
1381 			u64 buf_addr, size_t len, int ddir,
1382 			unsigned issue_flags, unsigned import_flags)
1383 {
1384 	struct io_rsrc_node *node;
1385 
1386 	node = io_find_buf_node(req, issue_flags);
1387 	if (!node)
1388 		return -EFAULT;
1389 	return io_import_fixed(req, ddir, iter, node->buf, buf_addr, len,
1390 				issue_flags, import_flags);
1391 }
1392 
1393 static int io_buffer_acct_cloned_hpages(struct io_ring_ctx *ctx,
1394 					struct io_mapped_ubuf *imu)
1395 {
1396 	struct page *seen = NULL;
1397 	unsigned long acct = 0;
1398 	int i, ret = 0;
1399 
1400 	if (imu->flags & IO_REGBUF_F_KBUF || !ctx->user)
1401 		return 0;
1402 
1403 	for (i = 0; i < imu->nr_bvecs; i++) {
1404 		struct page *page = imu->bvec[i].bv_page;
1405 		struct page *hpage;
1406 		bool acct_new;
1407 
1408 		if (!PageCompound(page))
1409 			continue;
1410 
1411 		hpage = compound_head(page);
1412 		if (hpage == seen)
1413 			continue;
1414 		seen = hpage;
1415 
1416 		/* Atomically add reference for cloned buffer */
1417 		ret = hpage_acct_ref(ctx, hpage, &acct_new);
1418 		if (ret)
1419 			break;
1420 		if (acct_new)
1421 			acct += page_size(hpage) >> PAGE_SHIFT;
1422 
1423 		cond_resched();
1424 	}
1425 
1426 	if (!ret && acct)
1427 		ret = io_account_mem(ctx->user, ctx->mm_account, acct);
1428 	if (!ret)
1429 		return 0;
1430 
1431 	/* Undo refs we added for bvecs [0..i) */
1432 	seen = NULL;
1433 	for (int j = 0; j < i; j++) {
1434 		struct page *p = imu->bvec[j].bv_page;
1435 		struct page *hp;
1436 
1437 		if (!PageCompound(p))
1438 			continue;
1439 		hp = compound_head(p);
1440 		if (hp == seen)
1441 			continue;
1442 		seen = hp;
1443 		hpage_acct_unref(ctx, hp);
1444 	}
1445 	return ret;
1446 }
1447 
1448 /* Lock two rings at once. The rings must be different! */
1449 static void lock_two_rings(struct io_ring_ctx *ctx1, struct io_ring_ctx *ctx2)
1450 {
1451 	if (ctx1 > ctx2)
1452 		swap(ctx1, ctx2);
1453 	mutex_lock(&ctx1->uring_lock);
1454 	mutex_lock_nested(&ctx2->uring_lock, SINGLE_DEPTH_NESTING);
1455 }
1456 
1457 /* Both rings are locked by the caller. */
1458 static int io_clone_buffers(struct io_ring_ctx *ctx, struct io_ring_ctx *src_ctx,
1459 			    struct io_uring_clone_buffers *arg)
1460 {
1461 	struct io_rsrc_data data;
1462 	int i, ret, off, nr;
1463 	unsigned int nbufs;
1464 
1465 	lockdep_assert_held(&ctx->uring_lock);
1466 	lockdep_assert_held(&src_ctx->uring_lock);
1467 
1468 	/*
1469 	 * Accounting state is shared between the two rings; that only works if
1470 	 * both rings are accounted towards the same counters.
1471 	 */
1472 	if (ctx->user != src_ctx->user || ctx->mm_account != src_ctx->mm_account)
1473 		return -EINVAL;
1474 
1475 	/* if offsets are given, must have nr specified too */
1476 	if (!arg->nr && (arg->dst_off || arg->src_off))
1477 		return -EINVAL;
1478 	/* not allowed unless REPLACE is set */
1479 	if (ctx->buf_table.nr && !(arg->flags & IORING_REGISTER_DST_REPLACE))
1480 		return -EBUSY;
1481 
1482 	nbufs = src_ctx->buf_table.nr;
1483 	if (!nbufs)
1484 		return -ENXIO;
1485 	if (!arg->nr)
1486 		arg->nr = nbufs;
1487 	else if (arg->nr > nbufs)
1488 		return -EINVAL;
1489 	else if (arg->nr > IORING_MAX_REG_BUFFERS)
1490 		return -EINVAL;
1491 	if (check_add_overflow(arg->nr, arg->src_off, &off) || off > nbufs)
1492 		return -EOVERFLOW;
1493 	if (check_add_overflow(arg->nr, arg->dst_off, &nbufs))
1494 		return -EOVERFLOW;
1495 	if (nbufs > IORING_MAX_REG_BUFFERS)
1496 		return -EINVAL;
1497 
1498 	ret = io_rsrc_data_alloc(&data, max(nbufs, ctx->buf_table.nr));
1499 	if (ret)
1500 		return ret;
1501 
1502 	/* Copy original dst nodes from before the cloned range */
1503 	for (i = 0; i < min(arg->dst_off, ctx->buf_table.nr); i++) {
1504 		struct io_rsrc_node *node = ctx->buf_table.nodes[i];
1505 
1506 		if (node) {
1507 			data.nodes[i] = node;
1508 			node->refs++;
1509 		}
1510 	}
1511 
1512 	off = arg->dst_off;
1513 	i = arg->src_off;
1514 	nr = arg->nr;
1515 	while (nr--) {
1516 		struct io_rsrc_node *dst_node, *src_node;
1517 
1518 		src_node = io_rsrc_node_lookup(&src_ctx->buf_table, i);
1519 		if (!src_node) {
1520 			dst_node = NULL;
1521 		} else {
1522 			/* we don't allow IOPOLL rw with dma-buf for now */
1523 			if ((src_node->buf->flags & IO_REGBUF_F_DMABUF) &&
1524 			    (ctx->flags & IORING_SETUP_IOPOLL)) {
1525 				io_rsrc_data_free(ctx, &data);
1526 				return -EOPNOTSUPP;
1527 			}
1528 
1529 			dst_node = io_rsrc_node_alloc(ctx, IORING_RSRC_BUFFER);
1530 			if (!dst_node) {
1531 				io_rsrc_data_free(ctx, &data);
1532 				return -ENOMEM;
1533 			}
1534 
1535 			refcount_inc(&src_node->buf->refs);
1536 			dst_node->buf = src_node->buf;
1537 			/* track compound references to clones */
1538 			ret = io_buffer_acct_cloned_hpages(ctx, src_node->buf);
1539 			if (ret) {
1540 				refcount_dec(&src_node->buf->refs);
1541 				io_cache_free(&ctx->node_cache, dst_node);
1542 				io_rsrc_data_free(ctx, &data);
1543 				return ret;
1544 			}
1545 		}
1546 		data.nodes[off++] = dst_node;
1547 		i++;
1548 	}
1549 
1550 	/* Copy original dst nodes from after the cloned range */
1551 	for (i = nbufs; i < ctx->buf_table.nr; i++) {
1552 		struct io_rsrc_node *node = ctx->buf_table.nodes[i];
1553 
1554 		if (node) {
1555 			data.nodes[i] = node;
1556 			node->refs++;
1557 		}
1558 	}
1559 
1560 	/*
1561 	 * If asked for replace, put the old table. data->nodes[] holds both
1562 	 * old and new nodes at this point.
1563 	 */
1564 	if (arg->flags & IORING_REGISTER_DST_REPLACE)
1565 		io_rsrc_data_free(ctx, &ctx->buf_table);
1566 
1567 	/*
1568 	 * ctx->buf_table must be empty now - either the contents are being
1569 	 * replaced and we just freed the table, or the contents are being
1570 	 * copied to a ring that does not have buffers yet (checked at function
1571 	 * entry).
1572 	 */
1573 	WARN_ON_ONCE(ctx->buf_table.nr);
1574 	ctx->buf_table = data;
1575 	return 0;
1576 }
1577 
1578 /*
1579  * Copy the registered buffers from the source ring whose file descriptor
1580  * is given in the src_fd to the current ring. This is identical to registering
1581  * the buffers with ctx, except faster as mappings already exist.
1582  *
1583  * Since the memory is already accounted once, don't account it again.
1584  */
1585 int io_register_clone_buffers(struct io_ring_ctx *ctx, void __user *arg)
1586 {
1587 	struct io_uring_clone_buffers buf;
1588 	struct io_ring_ctx *src_ctx;
1589 	bool registered_src;
1590 	struct file *file;
1591 	int ret;
1592 
1593 	if (copy_from_user(&buf, arg, sizeof(buf)))
1594 		return -EFAULT;
1595 	if (buf.flags & ~(IORING_REGISTER_SRC_REGISTERED|IORING_REGISTER_DST_REPLACE))
1596 		return -EINVAL;
1597 	if (!(buf.flags & IORING_REGISTER_DST_REPLACE) && ctx->buf_table.nr)
1598 		return -EBUSY;
1599 	if (memchr_inv(buf.pad, 0, sizeof(buf.pad)))
1600 		return -EINVAL;
1601 
1602 	registered_src = (buf.flags & IORING_REGISTER_SRC_REGISTERED) != 0;
1603 	file = io_uring_ctx_get_file(buf.src_fd, registered_src);
1604 	if (IS_ERR(file))
1605 		return PTR_ERR(file);
1606 
1607 	src_ctx = file->private_data;
1608 	if (src_ctx != ctx) {
1609 		mutex_unlock(&ctx->uring_lock);
1610 		lock_two_rings(ctx, src_ctx);
1611 
1612 		if (src_ctx->submitter_task &&
1613 		    src_ctx->submitter_task != current) {
1614 			ret = -EEXIST;
1615 			goto out;
1616 		}
1617 	}
1618 
1619 	ret = io_clone_buffers(ctx, src_ctx, &buf);
1620 
1621 out:
1622 	if (src_ctx != ctx)
1623 		mutex_unlock(&src_ctx->uring_lock);
1624 
1625 	if (!registered_src)
1626 		fput(file);
1627 	return ret;
1628 }
1629 
1630 void io_vec_free(struct iou_vec *iv)
1631 {
1632 	if (!iv->iovec)
1633 		return;
1634 	kfree(iv->iovec);
1635 	iv->iovec = NULL;
1636 	iv->nr = 0;
1637 }
1638 
1639 int io_vec_realloc(struct iou_vec *iv, unsigned nr_entries)
1640 {
1641 	gfp_t gfp = GFP_KERNEL_ACCOUNT | __GFP_NOWARN;
1642 	struct iovec *iov;
1643 
1644 	iov = kmalloc_objs(iov[0], nr_entries, gfp);
1645 	if (!iov)
1646 		return -ENOMEM;
1647 
1648 	io_vec_free(iv);
1649 	iv->iovec = iov;
1650 	iv->nr = nr_entries;
1651 	return 0;
1652 }
1653 
1654 static int io_vec_fill_bvec(int ddir, struct iov_iter *iter,
1655 				struct io_mapped_ubuf *imu,
1656 				struct iovec *iovec, unsigned nr_iovs,
1657 				struct iou_vec *vec)
1658 {
1659 	unsigned long folio_size = 1UL << imu->folio_shift;
1660 	unsigned long folio_mask = folio_size - 1;
1661 	struct bio_vec *res_bvec = vec->bvec;
1662 	size_t total_len = 0;
1663 	unsigned bvec_idx = 0;
1664 	unsigned iov_idx;
1665 
1666 	for (iov_idx = 0; iov_idx < nr_iovs; iov_idx++) {
1667 		size_t iov_len = iovec[iov_idx].iov_len;
1668 		u64 buf_addr = (u64)(uintptr_t)iovec[iov_idx].iov_base;
1669 		struct bio_vec *src_bvec;
1670 		size_t offset;
1671 		int ret;
1672 
1673 		ret = validate_fixed_range(buf_addr, iov_len, imu);
1674 		if (unlikely(ret))
1675 			return ret;
1676 
1677 		if (unlikely(!iov_len))
1678 			return -EFAULT;
1679 		if (unlikely(check_add_overflow(total_len, iov_len, &total_len)))
1680 			return -EOVERFLOW;
1681 
1682 		offset = buf_addr - imu->ubuf;
1683 		/*
1684 		 * Only the first bvec can have non zero bv_offset, account it
1685 		 * here and work with full folios below.
1686 		 */
1687 		offset += imu->bvec[0].bv_offset;
1688 
1689 		src_bvec = imu->bvec + (offset >> imu->folio_shift);
1690 		offset &= folio_mask;
1691 
1692 		for (; iov_len; offset = 0, bvec_idx++, src_bvec++) {
1693 			size_t seg_size = min_t(size_t, iov_len,
1694 						folio_size - offset);
1695 
1696 			bvec_set_page(&res_bvec[bvec_idx],
1697 				      src_bvec->bv_page, seg_size, offset);
1698 			iov_len -= seg_size;
1699 		}
1700 	}
1701 	if (total_len > MAX_RW_COUNT)
1702 		return -EINVAL;
1703 
1704 	iov_iter_bvec(iter, ddir, res_bvec, bvec_idx, total_len);
1705 	return 0;
1706 }
1707 
1708 static int io_estimate_bvec_size(struct iovec *iov, unsigned nr_iovs,
1709 				 struct io_mapped_ubuf *imu)
1710 {
1711 	unsigned shift = imu->folio_shift;
1712 	size_t max_segs = 0;
1713 	unsigned i;
1714 
1715 	for (i = 0; i < nr_iovs; i++) {
1716 		max_segs += (iov[i].iov_len >> shift) + 2;
1717 		if (max_segs > INT_MAX)
1718 			return -EOVERFLOW;
1719 	}
1720 	return max_segs;
1721 }
1722 
1723 static int io_vec_fill_kern_bvec(int ddir, struct iov_iter *iter,
1724 				 struct io_mapped_ubuf *imu,
1725 				 struct iovec *iovec, unsigned nr_iovs,
1726 				 struct iou_vec *vec)
1727 {
1728 	const struct bio_vec *src_bvec = imu->bvec;
1729 	struct bio_vec *res_bvec = vec->bvec;
1730 	unsigned res_idx = 0;
1731 	size_t total_len = 0;
1732 	unsigned iov_idx;
1733 
1734 	for (iov_idx = 0; iov_idx < nr_iovs; iov_idx++) {
1735 		size_t offset = (size_t)(uintptr_t)iovec[iov_idx].iov_base;
1736 		size_t iov_len = iovec[iov_idx].iov_len;
1737 		struct bvec_iter bi = {
1738 			.bi_size        = offset + iov_len,
1739 		};
1740 		struct bio_vec bv;
1741 
1742 		bvec_iter_advance(src_bvec, &bi, offset);
1743 		for_each_mp_bvec(bv, src_bvec, bi, bi)
1744 			res_bvec[res_idx++] = bv;
1745 		total_len += iov_len;
1746 	}
1747 	iov_iter_bvec(iter, ddir, res_bvec, res_idx, total_len);
1748 	return 0;
1749 }
1750 
1751 static int iov_kern_bvec_size(const struct iovec *iov,
1752 			      const struct io_mapped_ubuf *imu,
1753 			      unsigned int *nr_seg)
1754 {
1755 	size_t offset = (size_t)(uintptr_t)iov->iov_base;
1756 	const struct bio_vec *bvec = imu->bvec;
1757 	int start = 0, i = 0;
1758 	size_t off = 0;
1759 	int ret;
1760 
1761 	ret = validate_fixed_range(offset, iov->iov_len, imu);
1762 	if (unlikely(ret))
1763 		return ret;
1764 
1765 	for (i = 0; off < offset + iov->iov_len && i < imu->nr_bvecs;
1766 			off += bvec[i].bv_len, i++) {
1767 		if (offset >= off && offset < off + bvec[i].bv_len)
1768 			start = i;
1769 	}
1770 	*nr_seg = i - start;
1771 	return 0;
1772 }
1773 
1774 static int io_kern_bvec_size(struct iovec *iov, unsigned nr_iovs,
1775 			     struct io_mapped_ubuf *imu, unsigned *nr_segs)
1776 {
1777 	unsigned max_segs = 0;
1778 	size_t total_len = 0;
1779 	unsigned i;
1780 	int ret;
1781 
1782 	*nr_segs = 0;
1783 	for (i = 0; i < nr_iovs; i++) {
1784 		if (unlikely(!iov[i].iov_len))
1785 			return -EFAULT;
1786 		if (unlikely(check_add_overflow(total_len, iov[i].iov_len,
1787 						&total_len)))
1788 			return -EOVERFLOW;
1789 		ret = iov_kern_bvec_size(&iov[i], imu, &max_segs);
1790 		if (unlikely(ret))
1791 			return ret;
1792 		*nr_segs += max_segs;
1793 	}
1794 	if (total_len > MAX_RW_COUNT)
1795 		return -EINVAL;
1796 	return 0;
1797 }
1798 
1799 int __io_import_reg_vec(int ddir, struct iov_iter *iter,
1800 			struct io_kiocb *req, struct iou_vec *vec,
1801 			unsigned nr_iovs, unsigned issue_flags, unsigned import_flags)
1802 {
1803 	struct io_rsrc_node *node;
1804 	struct io_mapped_ubuf *imu;
1805 	unsigned iovec_off;
1806 	struct iovec *iov;
1807 	unsigned nr_segs;
1808 
1809 	node = io_find_buf_node(req, issue_flags);
1810 	if (!node)
1811 		return -EFAULT;
1812 	imu = node->buf;
1813 	if (!(imu->dir & (1 << ddir)))
1814 		return -EFAULT;
1815 
1816 	iovec_off = vec->nr - nr_iovs;
1817 	iov = vec->iovec + iovec_off;
1818 
1819 	if (imu->flags & IO_REGBUF_F_DMABUF) {
1820 		return -EOPNOTSUPP;
1821 	} else if (imu->flags & IO_REGBUF_F_KBUF) {
1822 		int ret = io_kern_bvec_size(iov, nr_iovs, imu, &nr_segs);
1823 
1824 		if (unlikely(ret))
1825 			return ret;
1826 	} else {
1827 		int ret = io_estimate_bvec_size(iov, nr_iovs, imu);
1828 
1829 		if (ret < 0)
1830 			return ret;
1831 		nr_segs = ret;
1832 	}
1833 
1834 	if (sizeof(struct bio_vec) > sizeof(struct iovec)) {
1835 		size_t bvec_bytes;
1836 
1837 		if (check_mul_overflow((size_t)nr_segs, sizeof(struct bio_vec),
1838 				       &bvec_bytes) ||
1839 		    check_add_overflow(bvec_bytes, sizeof(*iov) - 1,
1840 				       &bvec_bytes))
1841 			return -EOVERFLOW;
1842 		nr_segs = bvec_bytes / sizeof(*iov);
1843 		nr_segs += nr_iovs;
1844 	}
1845 
1846 	if (nr_segs > vec->nr) {
1847 		struct iou_vec tmp_vec = {};
1848 		int ret;
1849 
1850 		ret = io_vec_realloc(&tmp_vec, nr_segs);
1851 		if (ret)
1852 			return ret;
1853 
1854 		iovec_off = tmp_vec.nr - nr_iovs;
1855 		memcpy(tmp_vec.iovec + iovec_off, iov, sizeof(*iov) * nr_iovs);
1856 		io_vec_free(vec);
1857 
1858 		*vec = tmp_vec;
1859 		iov = vec->iovec + iovec_off;
1860 		req->flags |= REQ_F_NEED_CLEANUP;
1861 	}
1862 
1863 	if (imu->flags & IO_REGBUF_F_KBUF)
1864 		return io_vec_fill_kern_bvec(ddir, iter, imu, iov, nr_iovs, vec);
1865 
1866 	return io_vec_fill_bvec(ddir, iter, imu, iov, nr_iovs, vec);
1867 }
1868 
1869 int io_prep_reg_iovec(struct io_kiocb *req, struct iou_vec *iv,
1870 		      const struct iovec __user *uvec, size_t uvec_segs)
1871 {
1872 	struct iovec *iov;
1873 	int iovec_off, ret;
1874 	void *res;
1875 
1876 	if (uvec_segs > iv->nr) {
1877 		ret = io_vec_realloc(iv, uvec_segs);
1878 		if (ret)
1879 			return ret;
1880 		req->flags |= REQ_F_NEED_CLEANUP;
1881 	}
1882 
1883 	/* pad iovec to the right */
1884 	iovec_off = iv->nr - uvec_segs;
1885 	iov = iv->iovec + iovec_off;
1886 	res = iovec_from_user(uvec, uvec_segs, uvec_segs, iov,
1887 			      io_is_compat(req->ctx));
1888 	if (IS_ERR(res))
1889 		return PTR_ERR(res);
1890 
1891 	req->flags |= REQ_F_IMPORT_BUFFER;
1892 	return 0;
1893 }
1894