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