xref: /linux/drivers/infiniband/core/ib_core_uverbs.c (revision 43b57d73ebbe5e7964a8b3ee3ffde0948fae6e2e)
1 // SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB
2 /*
3  * Copyright (c) 2005 Mellanox Technologies. All rights reserved.
4  * Copyright 2018-2019 Amazon.com, Inc. or its affiliates. All rights reserved.
5  * Copyright 2019 Marvell. All rights reserved.
6  */
7 #include <linux/xarray.h>
8 #include <linux/dma-buf.h>
9 #include <linux/dma-resv.h>
10 #include "uverbs.h"
11 #include "core_priv.h"
12 #include "rdma_core.h"
13 
14 MODULE_IMPORT_NS("DMA_BUF");
15 
16 /**
17  * rdma_umap_priv_init() - Initialize the private data of a vma
18  *
19  * @priv: The already allocated private data
20  * @vma: The vm area struct that needs private data
21  * @entry: entry into the mmap_xa that needs to be linked with
22  *       this vma
23  *
24  * Each time we map IO memory into user space this keeps track of the
25  * mapping. When the device is hot-unplugged we 'zap' the mmaps in user space
26  * to point to the zero page and allow the hot unplug to proceed.
27  *
28  * This is necessary for cases like PCI physical hot unplug as the actual BAR
29  * memory may vanish after this and access to it from userspace could MCE.
30  *
31  * RDMA drivers supporting disassociation must have their user space designed
32  * to cope in some way with their IO pages going to the zero page.
33  *
34  */
35 void rdma_umap_priv_init(struct rdma_umap_priv *priv,
36 			 struct vm_area_struct *vma,
37 			 struct rdma_user_mmap_entry *entry)
38 {
39 	struct ib_uverbs_file *ufile = vma->vm_file->private_data;
40 
41 	priv->vma = vma;
42 	if (entry) {
43 		kref_get(&entry->ref);
44 		priv->entry = entry;
45 	}
46 	vma->vm_private_data = priv;
47 	/* vm_ops is setup in ib_uverbs_mmap() to avoid module dependencies */
48 
49 	mutex_lock(&ufile->umap_lock);
50 	list_add(&priv->list, &ufile->umaps);
51 	mutex_unlock(&ufile->umap_lock);
52 }
53 EXPORT_SYMBOL(rdma_umap_priv_init);
54 
55 /**
56  * rdma_user_mmap_io() - Map IO memory into a process
57  *
58  * @ucontext: associated user context
59  * @vma: the vma related to the current mmap call
60  * @pfn: pfn to map
61  * @size: size to map
62  * @prot: pgprot to use in remap call
63  * @entry: mmap_entry retrieved from rdma_user_mmap_entry_get(), or NULL
64  *         if mmap_entry is not used by the driver
65  *
66  * This is to be called by drivers as part of their mmap() functions if they
67  * wish to send something like PCI-E BAR memory to userspace.
68  *
69  * Return -EINVAL on wrong flags or size, -EAGAIN on failure to map. 0 on
70  * success.
71  */
72 int rdma_user_mmap_io(struct ib_ucontext *ucontext, struct vm_area_struct *vma,
73 		      unsigned long pfn, unsigned long size, pgprot_t prot,
74 		      struct rdma_user_mmap_entry *entry)
75 {
76 	struct ib_uverbs_file *ufile = ucontext->ufile;
77 	struct rdma_umap_priv *priv;
78 
79 	if (!(vma->vm_flags & VM_SHARED))
80 		return -EINVAL;
81 
82 	if (vma->vm_end - vma->vm_start != size)
83 		return -EINVAL;
84 
85 	/* Driver is using this wrong, must be called by ib_uverbs_mmap */
86 	if (WARN_ON(!vma->vm_file ||
87 		    vma->vm_file->private_data != ufile))
88 		return -EINVAL;
89 	lockdep_assert_held(&ufile->device->disassociate_srcu);
90 
91 	priv = kzalloc_obj(*priv);
92 	if (!priv)
93 		return -ENOMEM;
94 
95 	vma->vm_page_prot = prot;
96 	if (io_remap_pfn_range(vma, vma->vm_start, pfn, size, prot)) {
97 		kfree(priv);
98 		return -EAGAIN;
99 	}
100 
101 	rdma_umap_priv_init(priv, vma, entry);
102 	return 0;
103 }
104 EXPORT_SYMBOL(rdma_user_mmap_io);
105 
106 /**
107  * rdma_user_mmap_entry_get_pgoff() - Get an entry from the mmap_xa
108  *
109  * @ucontext: associated user context
110  * @pgoff: The mmap offset >> PAGE_SHIFT
111  *
112  * This function is called when a user tries to mmap with an offset (returned
113  * by rdma_user_mmap_get_offset()) it initially received from the driver. The
114  * rdma_user_mmap_entry was created by the function
115  * rdma_user_mmap_entry_insert().  This function increases the refcnt of the
116  * entry so that it won't be deleted from the xarray in the meantime.
117  *
118  * Return an reference to an entry if exists or NULL if there is no
119  * match. rdma_user_mmap_entry_put() must be called to put the reference.
120  */
121 struct rdma_user_mmap_entry *
122 rdma_user_mmap_entry_get_pgoff(struct ib_ucontext *ucontext,
123 			       unsigned long pgoff)
124 {
125 	struct rdma_user_mmap_entry *entry;
126 
127 	if (pgoff > U32_MAX)
128 		return NULL;
129 
130 	xa_lock(&ucontext->mmap_xa);
131 
132 	entry = xa_load(&ucontext->mmap_xa, pgoff);
133 
134 	/*
135 	 * If refcount is zero, entry is already being deleted, driver_removed
136 	 * indicates that the no further mmaps are possible and we waiting for
137 	 * the active VMAs to be closed.
138 	 */
139 	if (!entry || entry->start_pgoff != pgoff || entry->driver_removed ||
140 	    !kref_get_unless_zero(&entry->ref))
141 		goto err;
142 
143 	xa_unlock(&ucontext->mmap_xa);
144 
145 	ibdev_dbg(ucontext->device, "mmap: pgoff[%#lx] npages[%#zx] returned\n",
146 		  pgoff, entry->npages);
147 
148 	return entry;
149 
150 err:
151 	xa_unlock(&ucontext->mmap_xa);
152 	return NULL;
153 }
154 EXPORT_SYMBOL(rdma_user_mmap_entry_get_pgoff);
155 
156 /**
157  * rdma_user_mmap_entry_get() - Get an entry from the mmap_xa
158  *
159  * @ucontext: associated user context
160  * @vma: the vma being mmap'd into
161  *
162  * This function is like rdma_user_mmap_entry_get_pgoff() except that it also
163  * checks that the VMA is correct.
164  */
165 struct rdma_user_mmap_entry *
166 rdma_user_mmap_entry_get(struct ib_ucontext *ucontext,
167 			 struct vm_area_struct *vma)
168 {
169 	struct rdma_user_mmap_entry *entry;
170 
171 	if (!(vma->vm_flags & VM_SHARED))
172 		return NULL;
173 	entry = rdma_user_mmap_entry_get_pgoff(ucontext, vma->vm_pgoff);
174 	if (!entry)
175 		return NULL;
176 	if (entry->npages * PAGE_SIZE != vma->vm_end - vma->vm_start) {
177 		rdma_user_mmap_entry_put(entry);
178 		return NULL;
179 	}
180 	return entry;
181 }
182 EXPORT_SYMBOL(rdma_user_mmap_entry_get);
183 
184 static void rdma_user_mmap_entry_free(struct kref *kref)
185 {
186 	struct rdma_user_mmap_entry *entry =
187 		container_of(kref, struct rdma_user_mmap_entry, ref);
188 	struct ib_ucontext *ucontext = entry->ucontext;
189 	unsigned long i;
190 
191 	/*
192 	 * Erase all entries occupied by this single entry, this is deferred
193 	 * until all VMA are closed so that the mmap offsets remain unique.
194 	 */
195 	xa_lock(&ucontext->mmap_xa);
196 	for (i = 0; i < entry->npages; i++)
197 		__xa_erase(&ucontext->mmap_xa, entry->start_pgoff + i);
198 	xa_unlock(&ucontext->mmap_xa);
199 
200 	ibdev_dbg(ucontext->device, "mmap: pgoff[%#lx] npages[%#zx] removed\n",
201 		  entry->start_pgoff, entry->npages);
202 
203 	if (ucontext->device->ops.mmap_free)
204 		ucontext->device->ops.mmap_free(entry);
205 }
206 
207 /**
208  * rdma_user_mmap_entry_put() - Drop reference to the mmap entry
209  *
210  * @entry: an entry in the mmap_xa
211  *
212  * This function is called when the mapping is closed if it was
213  * an io mapping or when the driver is done with the entry for
214  * some other reason.
215  * Should be called after rdma_user_mmap_entry_get was called
216  * and entry is no longer needed. This function will erase the
217  * entry and free it if its refcnt reaches zero.
218  */
219 void rdma_user_mmap_entry_put(struct rdma_user_mmap_entry *entry)
220 {
221 	kref_put(&entry->ref, rdma_user_mmap_entry_free);
222 }
223 EXPORT_SYMBOL(rdma_user_mmap_entry_put);
224 
225 /**
226  * rdma_user_mmap_entry_remove() - Drop reference to entry and
227  *				   mark it as unmmapable
228  *
229  * @entry: the entry to insert into the mmap_xa
230  *
231  * Drivers can call this to prevent userspace from creating more mappings for
232  * entry, however existing mmaps continue to exist and ops->mmap_free() will
233  * not be called until all user mmaps are destroyed.
234  */
235 void rdma_user_mmap_entry_remove(struct rdma_user_mmap_entry *entry)
236 {
237 	struct ib_uverbs_dmabuf_file *uverbs_dmabuf, *tmp;
238 
239 	if (!entry)
240 		return;
241 
242 	mutex_lock(&entry->dmabufs_lock);
243 	xa_lock(&entry->ucontext->mmap_xa);
244 	entry->driver_removed = true;
245 	xa_unlock(&entry->ucontext->mmap_xa);
246 	list_for_each_entry_safe(uverbs_dmabuf, tmp, &entry->dmabufs, dmabufs_elm) {
247 		dma_resv_lock(uverbs_dmabuf->dmabuf->resv, NULL);
248 		list_del(&uverbs_dmabuf->dmabufs_elm);
249 		uverbs_dmabuf->revoked = true;
250 		dma_buf_invalidate_mappings(uverbs_dmabuf->dmabuf);
251 		dma_resv_wait_timeout(uverbs_dmabuf->dmabuf->resv,
252 				      DMA_RESV_USAGE_BOOKKEEP, false,
253 				      MAX_SCHEDULE_TIMEOUT);
254 		dma_resv_unlock(uverbs_dmabuf->dmabuf->resv);
255 		kref_put(&uverbs_dmabuf->kref, ib_uverbs_dmabuf_done);
256 		wait_for_completion(&uverbs_dmabuf->comp);
257 	}
258 	mutex_unlock(&entry->dmabufs_lock);
259 
260 	kref_put(&entry->ref, rdma_user_mmap_entry_free);
261 }
262 EXPORT_SYMBOL(rdma_user_mmap_entry_remove);
263 
264 /**
265  * rdma_user_mmap_entry_insert_range() - Insert an entry to the mmap_xa
266  *					 in a given range.
267  *
268  * @ucontext: associated user context.
269  * @entry: the entry to insert into the mmap_xa
270  * @length: length of the address that will be mmapped
271  * @min_pgoff: minimum pgoff to be returned
272  * @max_pgoff: maximum pgoff to be returned
273  *
274  * This function should be called by drivers that use the rdma_user_mmap
275  * interface for implementing their mmap syscall A database of mmap offsets is
276  * handled in the core and helper functions are provided to insert entries
277  * into the database and extract entries when the user calls mmap with the
278  * given offset. The function allocates a unique page offset in a given range
279  * that should be provided to user, the user will use the offset to retrieve
280  * information such as address to be mapped and how.
281  *
282  * Return: 0 on success and -ENOMEM on failure
283  */
284 int rdma_user_mmap_entry_insert_range(struct ib_ucontext *ucontext,
285 				      struct rdma_user_mmap_entry *entry,
286 				      size_t length, u32 min_pgoff,
287 				      u32 max_pgoff)
288 {
289 	struct ib_uverbs_file *ufile = ucontext->ufile;
290 	XA_STATE(xas, &ucontext->mmap_xa, min_pgoff);
291 	u32 xa_first, xa_last, npages;
292 	int err;
293 	u32 i;
294 
295 	if (!entry)
296 		return -EINVAL;
297 
298 	kref_init(&entry->ref);
299 	INIT_LIST_HEAD(&entry->dmabufs);
300 	mutex_init(&entry->dmabufs_lock);
301 
302 	entry->ucontext = ucontext;
303 
304 	/*
305 	 * We want the whole allocation to be done without interruption from a
306 	 * different thread. The allocation requires finding a free range and
307 	 * storing. During the xa_insert the lock could be released, possibly
308 	 * allowing another thread to choose the same range.
309 	 */
310 	mutex_lock(&ufile->umap_lock);
311 
312 	xa_lock(&ucontext->mmap_xa);
313 
314 	/* We want to find an empty range */
315 	npages = (u32)DIV_ROUND_UP(length, PAGE_SIZE);
316 	entry->npages = npages;
317 	while (true) {
318 		/* First find an empty index */
319 		xas_find_marked(&xas, max_pgoff, XA_FREE_MARK);
320 		if (xas.xa_node == XAS_RESTART)
321 			goto err_unlock;
322 
323 		xa_first = xas.xa_index;
324 
325 		/* Is there enough room to have the range? */
326 		if (check_add_overflow(xa_first, npages, &xa_last))
327 			goto err_unlock;
328 
329 		/*
330 		 * Now look for the next present entry. If an entry doesn't
331 		 * exist, we found an empty range and can proceed.
332 		 */
333 		xas_next_entry(&xas, xa_last - 1);
334 		if (xas.xa_node == XAS_BOUNDS || xas.xa_index >= xa_last)
335 			break;
336 	}
337 
338 	for (i = xa_first; i < xa_last; i++) {
339 		err = __xa_insert(&ucontext->mmap_xa, i, entry, GFP_KERNEL);
340 		if (err)
341 			goto err_undo;
342 	}
343 
344 	/*
345 	 * Internally the kernel uses a page offset, in libc this is a byte
346 	 * offset. Drivers should not return pgoff to userspace.
347 	 */
348 	entry->start_pgoff = xa_first;
349 	xa_unlock(&ucontext->mmap_xa);
350 	mutex_unlock(&ufile->umap_lock);
351 
352 	ibdev_dbg(ucontext->device, "mmap: pgoff[%#lx] npages[%#x] inserted\n",
353 		  entry->start_pgoff, npages);
354 
355 	return 0;
356 
357 err_undo:
358 	for (; i > xa_first; i--)
359 		__xa_erase(&ucontext->mmap_xa, i - 1);
360 
361 err_unlock:
362 	xa_unlock(&ucontext->mmap_xa);
363 	mutex_unlock(&ufile->umap_lock);
364 	return -ENOMEM;
365 }
366 EXPORT_SYMBOL(rdma_user_mmap_entry_insert_range);
367 
368 /**
369  * rdma_user_mmap_entry_insert() - Insert an entry to the mmap_xa.
370  *
371  * @ucontext: associated user context.
372  * @entry: the entry to insert into the mmap_xa
373  * @length: length of the address that will be mmapped
374  *
375  * This function should be called by drivers that use the rdma_user_mmap
376  * interface for handling user mmapped addresses. The database is handled in
377  * the core and helper functions are provided to insert entries into the
378  * database and extract entries when the user calls mmap with the given offset.
379  * The function allocates a unique page offset that should be provided to user,
380  * the user will use the offset to retrieve information such as address to
381  * be mapped and how.
382  *
383  * Return: 0 on success and -ENOMEM on failure
384  */
385 int rdma_user_mmap_entry_insert(struct ib_ucontext *ucontext,
386 				struct rdma_user_mmap_entry *entry,
387 				size_t length)
388 {
389 	return rdma_user_mmap_entry_insert_range(ucontext, entry, length, 0,
390 						 U32_MAX);
391 }
392 EXPORT_SYMBOL(rdma_user_mmap_entry_insert);
393 
394 /**
395  * rdma_udata_to_dev - Get a ib_device from a udata
396  * @udata: The system calls ib_udata struct
397  *
398  * The struct ib_device that is handling the uverbs call. Must not be called if
399  * udata is NULL. The result can be NULL.
400  */
401 static struct ib_device *rdma_udata_to_dev(struct ib_udata *udata)
402 {
403 	struct uverbs_attr_bundle *bundle =
404 		rdma_udata_to_uverbs_attr_bundle(udata);
405 
406 	lockdep_assert_held(&bundle->ufile->device->disassociate_srcu);
407 
408 	if (bundle->context)
409 		return bundle->context->device;
410 
411 	/*
412 	 * If the context hasn't been created yet use the ufile's dev, but it
413 	 * might be NULL if we are racing with disassociate.
414 	 */
415 	return srcu_dereference(bundle->ufile->device->ib_dev,
416 				&bundle->ufile->device->disassociate_srcu);
417 }
418 
419 typedef int (*uverbs_api_ioctl_handler_fn)(struct uverbs_attr_bundle *attrs);
420 static uverbs_api_ioctl_handler_fn uverbs_get_handler_fn(struct ib_udata *udata)
421 {
422 	struct uverbs_attr_bundle *bundle =
423 		rdma_udata_to_uverbs_attr_bundle(udata);
424 
425 	lockdep_assert_held(&bundle->ufile->device->disassociate_srcu);
426 
427 	return srcu_dereference(bundle->method_elm->handler,
428 				&bundle->ufile->device->disassociate_srcu);
429 }
430 
431 int _ib_copy_validate_udata_in(struct ib_udata *udata, void *req,
432 			       size_t kernel_size, size_t minimum_size)
433 {
434 	int err;
435 
436 	if (udata->inlen < minimum_size) {
437 		ibdev_dbg(
438 			rdma_udata_to_dev(udata),
439 			"System call driver input udata too small (%zu < %zu) for ioctl %ps called by %pSR\n",
440 			udata->inlen, minimum_size,
441 			uverbs_get_handler_fn(udata),
442 			__builtin_return_address(0));
443 		return -EINVAL;
444 	}
445 
446 	err = copy_struct_from_user(req, kernel_size, udata->inbuf,
447 				    udata->inlen);
448 	if (err) {
449 		if (err == -E2BIG) {
450 			ibdev_dbg(
451 				rdma_udata_to_dev(udata),
452 				"System call driver input udata not zero from %zu -> %zu for ioctl %ps called by %pSR\n",
453 				minimum_size, udata->inlen,
454 				uverbs_get_handler_fn(udata),
455 				__builtin_return_address(0));
456 			return -EOPNOTSUPP;
457 		}
458 		ibdev_dbg(
459 			rdma_udata_to_dev(udata),
460 			"System call driver input udata EFAULT for ioctl %ps called by %pSR\n",
461 			uverbs_get_handler_fn(udata),
462 			__builtin_return_address(0));
463 		return err;
464 	}
465 	return 0;
466 }
467 EXPORT_SYMBOL(_ib_copy_validate_udata_in);
468 
469 int _ib_copy_validate_udata_cm_fail(struct ib_udata *udata, u64 req_cm,
470 				    u64 valid_cm)
471 {
472 	ibdev_dbg(
473 		rdma_udata_to_dev(udata),
474 		"System call driver input udata has unsupported comp_mask %llx & ~%llx = %llx for ioctl %ps called by %pSR\n",
475 		req_cm, valid_cm, req_cm & ~valid_cm,
476 		uverbs_get_handler_fn(udata), __builtin_return_address(0));
477 	return -EOPNOTSUPP;
478 }
479 EXPORT_SYMBOL(_ib_copy_validate_udata_cm_fail);
480 
481 int _ib_respond_udata(struct ib_udata *udata, const void *src, size_t len)
482 {
483 	size_t copy_len;
484 
485 	/* 0 length copy_len is a NOP for copy_to_user() and doesn't fail. */
486 	copy_len = min(len, udata->outlen);
487 	if (copy_to_user(udata->outbuf, src, copy_len))
488 		goto err_fault;
489 	if (copy_len < udata->outlen) {
490 		if (clear_user(udata->outbuf + copy_len,
491 			       udata->outlen - copy_len))
492 			goto err_fault;
493 	}
494 	return 0;
495 err_fault:
496 	ibdev_dbg(
497 		rdma_udata_to_dev(udata),
498 		"System call driver out udata has EFAULT (%zu into %zu) for ioctl %ps called by %pSR\n",
499 		len, udata->outlen, uverbs_get_handler_fn(udata),
500 		__builtin_return_address(0));
501 	return -EFAULT;
502 }
503 EXPORT_SYMBOL(_ib_respond_udata);
504 
505 /*
506  * Must be called with the ufile->device->disassociate_srcu held, and the lock
507  * must be held until use of the ucontext is finished.
508  */
509 struct ib_ucontext *ib_uverbs_get_ucontext_file(struct ib_uverbs_file *ufile)
510 {
511 	/*
512 	 * We do not hold the hw_destroy_rwsem lock for this flow, instead
513 	 * srcu is used. It does not matter if someone races this with
514 	 * get_context, we get NULL or valid ucontext.
515 	 */
516 	struct ib_ucontext *ucontext = smp_load_acquire(&ufile->ucontext);
517 
518 	if (!srcu_dereference(ufile->device->ib_dev,
519 			      &ufile->device->disassociate_srcu))
520 		return ERR_PTR(-EIO);
521 
522 	if (!ucontext)
523 		return ERR_PTR(-EINVAL);
524 
525 	return ucontext;
526 }
527 EXPORT_SYMBOL(ib_uverbs_get_ucontext_file);
528 
529 int uverbs_destroy_def_handler(struct uverbs_attr_bundle *attrs)
530 {
531 	return 0;
532 }
533 EXPORT_SYMBOL(uverbs_destroy_def_handler);
534 
535 /*
536  * When calling a destroy function during an error unwind we need to pass in
537  * the udata that is sanitized of all user arguments. Ie from the driver
538  * perspective it looks like no udata was passed.
539  */
540 struct ib_udata *uverbs_get_cleared_udata(struct uverbs_attr_bundle *attrs)
541 {
542 	attrs->driver_udata = (struct ib_udata){};
543 	return &attrs->driver_udata;
544 }
545 EXPORT_SYMBOL_NS_GPL(uverbs_get_cleared_udata, "rdma_core");
546 
547 /**
548  * _uverbs_alloc() - Quickly allocate memory for use with a bundle
549  * @bundle: The bundle
550  * @size: Number of bytes to allocate
551  * @flags: Allocator flags
552  *
553  * The bundle allocator is intended for allocations that are connected with
554  * processing the system call related to the bundle. The allocated memory is
555  * always freed once the system call completes, and cannot be freed any other
556  * way.
557  *
558  * This tries to use a small pool of pre-allocated memory for performance.
559  */
560 __malloc void *_uverbs_alloc(struct uverbs_attr_bundle *bundle, size_t size,
561 			     gfp_t flags)
562 {
563 	struct bundle_priv *pbundle =
564 		container_of(&bundle->hdr, struct bundle_priv, bundle);
565 	size_t new_used;
566 	void *res;
567 
568 	if (check_add_overflow(size, pbundle->internal_used, &new_used))
569 		return ERR_PTR(-EOVERFLOW);
570 
571 	if (new_used > pbundle->internal_avail) {
572 		struct bundle_alloc_head *buf;
573 
574 		buf = kvmalloc_flex(*buf, data, size, flags);
575 		if (!buf)
576 			return ERR_PTR(-ENOMEM);
577 		buf->next = pbundle->allocated_mem;
578 		pbundle->allocated_mem = buf;
579 		return buf->data;
580 	}
581 
582 	res = (void *)pbundle->internal_buffer + pbundle->internal_used;
583 	pbundle->internal_used =
584 		ALIGN(new_used, sizeof(*pbundle->internal_buffer));
585 	if (want_init_on_alloc(flags))
586 		memset(res, 0, size);
587 	return res;
588 }
589 EXPORT_SYMBOL(_uverbs_alloc);
590 
591 int uverbs_copy_to(const struct uverbs_attr_bundle *bundle, size_t idx,
592 		   const void *from, size_t size)
593 {
594 	const struct uverbs_attr *attr = uverbs_attr_get(bundle, idx);
595 	size_t min_size;
596 
597 	if (IS_ERR(attr))
598 		return PTR_ERR(attr);
599 
600 	min_size = min_t(size_t, attr->ptr_attr.len, size);
601 	if (copy_to_user(u64_to_user_ptr(attr->ptr_attr.data), from, min_size))
602 		return -EFAULT;
603 
604 	return uverbs_set_output(bundle, attr);
605 }
606 EXPORT_SYMBOL(uverbs_copy_to);
607 
608 int uverbs_copy_to_struct_or_zero(const struct uverbs_attr_bundle *bundle,
609 				  size_t idx, const void *from, size_t size)
610 {
611 	const struct uverbs_attr *attr = uverbs_attr_get(bundle, idx);
612 
613 	if (IS_ERR(attr))
614 		return PTR_ERR(attr);
615 
616 	if (size < attr->ptr_attr.len) {
617 		if (clear_user(u64_to_user_ptr(attr->ptr_attr.data) + size,
618 			       attr->ptr_attr.len - size))
619 			return -EFAULT;
620 	}
621 	return uverbs_copy_to(bundle, idx, from, size);
622 }
623 EXPORT_SYMBOL(uverbs_copy_to_struct_or_zero);
624 
625 int _uverbs_get_const_unsigned(u64 *to,
626 			       const struct uverbs_attr_bundle *attrs_bundle,
627 			       size_t idx, u64 upper_bound, u64 *def_val)
628 {
629 	const struct uverbs_attr *attr;
630 
631 	attr = uverbs_attr_get(attrs_bundle, idx);
632 	if (IS_ERR(attr)) {
633 		if ((PTR_ERR(attr) != -ENOENT) || !def_val)
634 			return PTR_ERR(attr);
635 
636 		*to = *def_val;
637 	} else {
638 		*to = attr->ptr_attr.data;
639 	}
640 
641 	if (*to > upper_bound)
642 		return -EINVAL;
643 
644 	return 0;
645 }
646 EXPORT_SYMBOL(_uverbs_get_const_unsigned);
647 
648 int _uverbs_get_const_signed(s64 *to,
649 			     const struct uverbs_attr_bundle *attrs_bundle,
650 			     size_t idx, s64 lower_bound, u64 upper_bound,
651 			     s64  *def_val)
652 {
653 	const struct uverbs_attr *attr;
654 
655 	attr = uverbs_attr_get(attrs_bundle, idx);
656 	if (IS_ERR(attr)) {
657 		if ((PTR_ERR(attr) != -ENOENT) || !def_val)
658 			return PTR_ERR(attr);
659 
660 		*to = *def_val;
661 	} else {
662 		*to = attr->ptr_attr.data;
663 	}
664 
665 	if (*to < lower_bound || (*to > 0 && (u64)*to > upper_bound))
666 		return -EINVAL;
667 
668 	return 0;
669 }
670 EXPORT_SYMBOL(_uverbs_get_const_signed);
671 
672 int uverbs_get_flags64(u64 *to, const struct uverbs_attr_bundle *attrs_bundle,
673 		       size_t idx, u64 allowed_bits)
674 {
675 	const struct uverbs_attr *attr;
676 	u64 flags;
677 
678 	attr = uverbs_attr_get(attrs_bundle, idx);
679 	/* Missing attribute means 0 flags */
680 	if (IS_ERR(attr)) {
681 		*to = 0;
682 		return 0;
683 	}
684 
685 	/*
686 	 * New userspace code should use 8 bytes to pass flags, but we
687 	 * transparently support old userspaces that were using 4 bytes as
688 	 * well.
689 	 */
690 	if (attr->ptr_attr.len == 8)
691 		flags = attr->ptr_attr.data;
692 	else if (attr->ptr_attr.len == 4)
693 		flags = *(u32 *)&attr->ptr_attr.data;
694 	else
695 		return -EINVAL;
696 
697 	if (flags & ~allowed_bits)
698 		return -EINVAL;
699 
700 	*to = flags;
701 	return 0;
702 }
703 EXPORT_SYMBOL(uverbs_get_flags64);
704 
705 int uverbs_get_flags32(u32 *to, const struct uverbs_attr_bundle *attrs_bundle,
706 		       size_t idx, u64 allowed_bits)
707 {
708 	u64 flags;
709 	int ret;
710 
711 	ret = uverbs_get_flags64(&flags, attrs_bundle, idx, allowed_bits);
712 	if (ret)
713 		return ret;
714 
715 	if (flags > U32_MAX)
716 		return -EINVAL;
717 	*to = flags;
718 
719 	return 0;
720 }
721 EXPORT_SYMBOL(uverbs_get_flags32);
722 
723 /**
724  * uverbs_get_buffer_desc - Read a buffer descriptor from a uverbs attr.
725  * @attrs_bundle: uverbs attribute bundle.
726  * @attr_id:      id of an UVERBS_ATTR_UMEM-typed attribute.
727  * @desc:         descriptor to fill.
728  *
729  * Return: 0 on success, -ENOENT if @attr_id is not set, -EINVAL on a
730  * malformed descriptor, or any other negative errno propagated from
731  * uverbs_copy_from() (notably -EFAULT on copy_from_user() failure).
732  */
733 int uverbs_get_buffer_desc(const struct uverbs_attr_bundle *attrs_bundle,
734 			   u16 attr_id, struct ib_uverbs_buffer_desc *desc)
735 {
736 	int ret;
737 
738 	ret = uverbs_copy_from(desc, attrs_bundle, attr_id);
739 	if (ret)
740 		return ret;
741 	if (desc->flags & ~IB_UVERBS_BUFFER_DESC_FLAGS_KNOWN_MASK)
742 		return -EINVAL;
743 	desc->optional_flags &= IB_UVERBS_BUFFER_DESC_OPTIONAL_FLAGS_KNOWN_MASK;
744 	return 0;
745 }
746 EXPORT_SYMBOL(uverbs_get_buffer_desc);
747 
748 /* Once called an abort will call through to the type's destroy_hw() */
749 void uverbs_finalize_uobj_create(const struct uverbs_attr_bundle *bundle,
750 				 u16 idx)
751 {
752 	struct bundle_priv *pbundle =
753 		container_of(&bundle->hdr, struct bundle_priv, bundle);
754 
755 	__set_bit(uapi_bkey_attr(uapi_key_attr(idx)),
756 		  pbundle->uobj_hw_obj_valid);
757 }
758 EXPORT_SYMBOL(uverbs_finalize_uobj_create);
759