1/*-
2 * SPDX-License-Identifier: BSD-2-Clause OR GPL-2.0
3 *
4 * Copyright (c) 2005 Topspin Communications.  All rights reserved.
5 * Copyright (c) 2005 Cisco Systems.  All rights reserved.
6 * Copyright (c) 2005 Mellanox Technologies. All rights reserved.
7 *
8 * This software is available to you under a choice of one of two
9 * licenses.  You may choose to be licensed under the terms of the GNU
10 * General Public License (GPL) Version 2, available from the file
11 * COPYING in the main directory of this source tree, or the
12 * OpenIB.org BSD license below:
13 *
14 *     Redistribution and use in source and binary forms, with or
15 *     without modification, are permitted provided that the following
16 *     conditions are met:
17 *
18 *      - Redistributions of source code must retain the above
19 *        copyright notice, this list of conditions and the following
20 *        disclaimer.
21 *
22 *      - Redistributions in binary form must reproduce the above
23 *        copyright notice, this list of conditions and the following
24 *        disclaimer in the documentation and/or other materials
25 *        provided with the distribution.
26 *
27 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
31 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
32 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
33 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
34 * SOFTWARE.
35 */
36
37#include <sys/cdefs.h>
38#define	LINUXKPI_PARAM_PREFIX ibcore_
39
40#include <linux/mm.h>
41#include <linux/dma-mapping.h>
42#include <linux/sched.h>
43#include <linux/slab.h>
44#include <linux/wait.h>
45#include <rdma/ib_umem_odp.h>
46
47#include "uverbs.h"
48
49#include <sys/priv.h>
50
51static void __ib_umem_release(struct ib_device *dev, struct ib_umem *umem, int dirty)
52{
53	struct scatterlist *sg;
54	struct page *page;
55	int i;
56
57	if (umem->nmap > 0)
58		ib_dma_unmap_sg(dev, umem->sg_head.sgl,
59				umem->nmap,
60				DMA_BIDIRECTIONAL);
61
62	for_each_sg(umem->sg_head.sgl, sg, umem->npages, i) {
63
64		page = sg_page(sg);
65		put_page(page);
66	}
67
68	sg_free_table(&umem->sg_head);
69	return;
70
71}
72
73/**
74 * ib_umem_get - Pin and DMA map userspace memory.
75 *
76 * If access flags indicate ODP memory, avoid pinning. Instead, stores
77 * the mm for future page fault handling in conjunction with MMU notifiers.
78 *
79 * @context: userspace context to pin memory for
80 * @addr: userspace virtual address to start at
81 * @size: length of region to pin
82 * @access: IB_ACCESS_xxx flags for memory being pinned
83 * @dmasync: flush in-flight DMA when the memory region is written
84 */
85struct ib_umem *ib_umem_get(struct ib_ucontext *context, unsigned long addr,
86			    size_t size, int access, int dmasync)
87{
88	struct ib_umem *umem;
89	struct page **page_list;
90	struct vm_area_struct **vma_list;
91	unsigned long locked;
92	unsigned long cur_base;
93	unsigned long npages;
94	int ret;
95	int i;
96	struct dma_attrs dma_attrs = { 0 };
97	struct scatterlist *sg, *sg_list_start;
98	int need_release = 0;
99	unsigned int gup_flags = FOLL_WRITE;
100
101	if (dmasync)
102		dma_attrs.flags |= DMA_ATTR_WRITE_BARRIER;
103
104	if (!size)
105		return ERR_PTR(-EINVAL);
106
107	/*
108	 * If the combination of the addr and size requested for this memory
109	 * region causes an integer overflow, return error.
110	 */
111	if (((addr + size) < addr) ||
112	    PAGE_ALIGN(addr + size) < (addr + size))
113		return ERR_PTR(-EINVAL);
114
115	if (priv_check(curthread, PRIV_VM_MLOCK) != 0)
116		return ERR_PTR(-EPERM);
117
118	umem = kzalloc(sizeof *umem, GFP_KERNEL);
119	if (!umem)
120		return ERR_PTR(-ENOMEM);
121
122	umem->context   = context;
123	umem->length    = size;
124	umem->address   = addr;
125	umem->page_size = PAGE_SIZE;
126	umem->pid       = get_pid(task_pid(current));
127	/*
128	 * We ask for writable memory if any of the following
129	 * access flags are set.  "Local write" and "remote write"
130	 * obviously require write access.  "Remote atomic" can do
131	 * things like fetch and add, which will modify memory, and
132	 * "MW bind" can change permissions by binding a window.
133	 */
134	umem->writable  = !!(access &
135		(IB_ACCESS_LOCAL_WRITE   | IB_ACCESS_REMOTE_WRITE |
136		 IB_ACCESS_REMOTE_ATOMIC | IB_ACCESS_MW_BIND));
137
138	if (access & IB_ACCESS_ON_DEMAND) {
139		ret = ib_umem_odp_get(context, umem);
140		if (ret) {
141			kfree(umem);
142			return ERR_PTR(ret);
143		}
144		return umem;
145	}
146
147	umem->odp_data = NULL;
148
149	page_list = (struct page **) __get_free_page(GFP_KERNEL);
150	if (!page_list) {
151		kfree(umem);
152		return ERR_PTR(-ENOMEM);
153	}
154
155	vma_list = (struct vm_area_struct **) __get_free_page(GFP_KERNEL);
156
157	npages = ib_umem_num_pages(umem);
158
159	down_write(&current->mm->mmap_sem);
160
161	locked     = npages + current->mm->pinned_vm;
162
163	cur_base = addr & PAGE_MASK;
164
165	if (npages == 0 || npages > UINT_MAX) {
166		ret = -EINVAL;
167		goto out;
168	}
169
170	ret = sg_alloc_table(&umem->sg_head, npages, GFP_KERNEL);
171	if (ret)
172		goto out;
173
174	if (!umem->writable)
175		gup_flags |= FOLL_FORCE;
176
177	need_release = 1;
178	sg_list_start = umem->sg_head.sgl;
179
180	while (npages) {
181		ret = get_user_pages(cur_base,
182				     min_t(unsigned long, npages,
183					   PAGE_SIZE / sizeof (struct page *)),
184				     gup_flags, page_list, vma_list);
185
186		if (ret < 0)
187			goto out;
188
189		umem->npages += ret;
190		cur_base += ret * PAGE_SIZE;
191		npages   -= ret;
192
193		for_each_sg(sg_list_start, sg, ret, i) {
194			sg_set_page(sg, page_list[i], PAGE_SIZE, 0);
195		}
196
197		/* preparing for next loop */
198		sg_list_start = sg;
199	}
200
201	umem->nmap = ib_dma_map_sg_attrs(context->device,
202				  umem->sg_head.sgl,
203				  umem->npages,
204				  DMA_BIDIRECTIONAL,
205				  &dma_attrs);
206
207	if (umem->nmap <= 0) {
208		ret = -ENOMEM;
209		goto out;
210	}
211
212	ret = 0;
213
214out:
215	if (ret < 0) {
216		if (need_release)
217			__ib_umem_release(context->device, umem, 0);
218		put_pid(umem->pid);
219		kfree(umem);
220	} else
221		current->mm->pinned_vm = locked;
222
223	up_write(&current->mm->mmap_sem);
224	if (vma_list)
225		free_page((unsigned long) vma_list);
226	free_page((unsigned long) page_list);
227
228	return ret < 0 ? ERR_PTR(ret) : umem;
229}
230EXPORT_SYMBOL(ib_umem_get);
231
232static void ib_umem_account(struct work_struct *work)
233{
234	struct ib_umem *umem = container_of(work, struct ib_umem, work);
235
236	down_write(&umem->mm->mmap_sem);
237	umem->mm->pinned_vm -= umem->diff;
238	up_write(&umem->mm->mmap_sem);
239	mmput(umem->mm);
240	kfree(umem);
241}
242
243/**
244 * ib_umem_release - release memory pinned with ib_umem_get
245 * @umem: umem struct to release
246 */
247void ib_umem_release(struct ib_umem *umem)
248{
249	struct mm_struct *mm;
250	struct task_struct *task;
251	unsigned long diff;
252
253	if (!umem)
254		return;
255
256	if (umem->odp_data) {
257		ib_umem_odp_release(umem);
258		return;
259	}
260
261	__ib_umem_release(umem->context->device, umem, 1);
262
263	task = get_pid_task(umem->pid, PIDTYPE_PID);
264	put_pid(umem->pid);
265	if (!task)
266		goto out;
267	mm = get_task_mm(task);
268	put_task_struct(task);
269	if (!mm)
270		goto out;
271
272	diff = ib_umem_num_pages(umem);
273
274	/*
275	 * We may be called with the mm's mmap_sem already held.  This
276	 * can happen when a userspace munmap() is the call that drops
277	 * the last reference to our file and calls our release
278	 * method.  If there are memory regions to destroy, we'll end
279	 * up here and not be able to take the mmap_sem.  In that case
280	 * we defer the vm_locked accounting to the system workqueue.
281	 */
282	if (umem->context->closing) {
283		if (!down_write_trylock(&mm->mmap_sem)) {
284			INIT_WORK(&umem->work, ib_umem_account);
285			umem->mm   = mm;
286			umem->diff = diff;
287
288			queue_work(ib_wq, &umem->work);
289			return;
290		}
291	} else
292		down_write(&mm->mmap_sem);
293
294	mm->pinned_vm -= diff;
295	up_write(&mm->mmap_sem);
296	mmput(mm);
297out:
298	kfree(umem);
299}
300EXPORT_SYMBOL(ib_umem_release);
301
302int ib_umem_page_count(struct ib_umem *umem)
303{
304	int shift;
305	int i;
306	int n;
307	struct scatterlist *sg;
308
309	if (umem->odp_data)
310		return ib_umem_num_pages(umem);
311
312	shift = ilog2(umem->page_size);
313
314	n = 0;
315	for_each_sg(umem->sg_head.sgl, sg, umem->nmap, i)
316		n += sg_dma_len(sg) >> shift;
317
318	return n;
319}
320EXPORT_SYMBOL(ib_umem_page_count);
321
322/*
323 * Copy from the given ib_umem's pages to the given buffer.
324 *
325 * umem - the umem to copy from
326 * offset - offset to start copying from
327 * dst - destination buffer
328 * length - buffer length
329 *
330 * Returns 0 on success, or an error code.
331 */
332int ib_umem_copy_from(void *dst, struct ib_umem *umem, size_t offset,
333		      size_t length)
334{
335	size_t end = offset + length;
336	int ret;
337
338	if (offset > umem->length || length > umem->length - offset) {
339		pr_err("ib_umem_copy_from not in range. offset: %zd umem length: %zd end: %zd\n",
340		       offset, umem->length, end);
341		return -EINVAL;
342	}
343
344#ifdef __linux__
345	ret = sg_pcopy_to_buffer(umem->sg_head.sgl, umem->nmap, dst, length,
346				 offset + ib_umem_offset(umem));
347#else
348	ret = 0;
349#endif
350	if (ret < 0)
351		return ret;
352	else if (ret != length)
353		return -EINVAL;
354	else
355		return 0;
356}
357EXPORT_SYMBOL(ib_umem_copy_from);
358