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