1 /*
2  * Copyright (c) 2014 Mellanox Technologies. All rights reserved.
3  *
4  * This software is available to you under a choice of one of two
5  * licenses.  You may choose to be licensed under the terms of the GNU
6  * General Public License (GPL) Version 2, available from the file
7  * COPYING in the main directory of this source tree, or the
8  * OpenIB.org BSD license below:
9  *
10  *     Redistribution and use in source and binary forms, with or
11  *     without modification, are permitted provided that the following
12  *     conditions are met:
13  *
14  *      - Redistributions of source code must retain the above
15  *        copyright notice, this list of conditions and the following
16  *        disclaimer.
17  *
18  *      - Redistributions in binary form must reproduce the above
19  *        copyright notice, this list of conditions and the following
20  *        disclaimer in the documentation and/or other materials
21  *        provided with the distribution.
22  *
23  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
27  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
28  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
29  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30  * SOFTWARE.
31  */
32 
33 #include <linux/types.h>
34 #include <linux/sched.h>
35 #include <linux/sched/mm.h>
36 #include <linux/sched/task.h>
37 #include <linux/pid.h>
38 #include <linux/slab.h>
39 #include <linux/export.h>
40 #include <linux/vmalloc.h>
41 #include <linux/hugetlb.h>
42 #include <linux/interval_tree.h>
43 #include <linux/pagemap.h>
44 
45 #include <rdma/ib_verbs.h>
46 #include <rdma/ib_umem.h>
47 #include <rdma/ib_umem_odp.h>
48 
49 #include "uverbs.h"
50 
51 static inline int ib_init_umem_odp(struct ib_umem_odp *umem_odp,
52 				   const struct mmu_interval_notifier_ops *ops)
53 {
54 	int ret;
55 
56 	umem_odp->umem.is_odp = 1;
57 	mutex_init(&umem_odp->umem_mutex);
58 
59 	if (!umem_odp->is_implicit_odp) {
60 		size_t page_size = 1UL << umem_odp->page_shift;
61 		unsigned long start;
62 		unsigned long end;
63 		size_t pages;
64 
65 		start = ALIGN_DOWN(umem_odp->umem.address, page_size);
66 		if (check_add_overflow(umem_odp->umem.address,
67 				       (unsigned long)umem_odp->umem.length,
68 				       &end))
69 			return -EOVERFLOW;
70 		end = ALIGN(end, page_size);
71 		if (unlikely(end < page_size))
72 			return -EOVERFLOW;
73 
74 		pages = (end - start) >> umem_odp->page_shift;
75 		if (!pages)
76 			return -EINVAL;
77 
78 		umem_odp->page_list = kvcalloc(
79 			pages, sizeof(*umem_odp->page_list), GFP_KERNEL);
80 		if (!umem_odp->page_list)
81 			return -ENOMEM;
82 
83 		umem_odp->dma_list = kvcalloc(
84 			pages, sizeof(*umem_odp->dma_list), GFP_KERNEL);
85 		if (!umem_odp->dma_list) {
86 			ret = -ENOMEM;
87 			goto out_page_list;
88 		}
89 
90 		ret = mmu_interval_notifier_insert(&umem_odp->notifier,
91 						   umem_odp->umem.owning_mm,
92 						   start, end - start, ops);
93 		if (ret)
94 			goto out_dma_list;
95 	}
96 
97 	return 0;
98 
99 out_dma_list:
100 	kvfree(umem_odp->dma_list);
101 out_page_list:
102 	kvfree(umem_odp->page_list);
103 	return ret;
104 }
105 
106 /**
107  * ib_umem_odp_alloc_implicit - Allocate a parent implicit ODP umem
108  *
109  * Implicit ODP umems do not have a VA range and do not have any page lists.
110  * They exist only to hold the per_mm reference to help the driver create
111  * children umems.
112  *
113  * @device: IB device to create UMEM
114  * @access: ib_reg_mr access flags
115  */
116 struct ib_umem_odp *ib_umem_odp_alloc_implicit(struct ib_device *device,
117 					       int access)
118 {
119 	struct ib_umem *umem;
120 	struct ib_umem_odp *umem_odp;
121 	int ret;
122 
123 	if (access & IB_ACCESS_HUGETLB)
124 		return ERR_PTR(-EINVAL);
125 
126 	umem_odp = kzalloc(sizeof(*umem_odp), GFP_KERNEL);
127 	if (!umem_odp)
128 		return ERR_PTR(-ENOMEM);
129 	umem = &umem_odp->umem;
130 	umem->ibdev = device;
131 	umem->writable = ib_access_writable(access);
132 	umem->owning_mm = current->mm;
133 	umem_odp->is_implicit_odp = 1;
134 	umem_odp->page_shift = PAGE_SHIFT;
135 
136 	umem_odp->tgid = get_task_pid(current->group_leader, PIDTYPE_PID);
137 	ret = ib_init_umem_odp(umem_odp, NULL);
138 	if (ret) {
139 		put_pid(umem_odp->tgid);
140 		kfree(umem_odp);
141 		return ERR_PTR(ret);
142 	}
143 	return umem_odp;
144 }
145 EXPORT_SYMBOL(ib_umem_odp_alloc_implicit);
146 
147 /**
148  * ib_umem_odp_alloc_child - Allocate a child ODP umem under an implicit
149  *                           parent ODP umem
150  *
151  * @root: The parent umem enclosing the child. This must be allocated using
152  *        ib_alloc_implicit_odp_umem()
153  * @addr: The starting userspace VA
154  * @size: The length of the userspace VA
155  * @ops: MMU interval ops, currently only @invalidate
156  */
157 struct ib_umem_odp *
158 ib_umem_odp_alloc_child(struct ib_umem_odp *root, unsigned long addr,
159 			size_t size,
160 			const struct mmu_interval_notifier_ops *ops)
161 {
162 	/*
163 	 * Caller must ensure that root cannot be freed during the call to
164 	 * ib_alloc_odp_umem.
165 	 */
166 	struct ib_umem_odp *odp_data;
167 	struct ib_umem *umem;
168 	int ret;
169 
170 	if (WARN_ON(!root->is_implicit_odp))
171 		return ERR_PTR(-EINVAL);
172 
173 	odp_data = kzalloc(sizeof(*odp_data), GFP_KERNEL);
174 	if (!odp_data)
175 		return ERR_PTR(-ENOMEM);
176 	umem = &odp_data->umem;
177 	umem->ibdev = root->umem.ibdev;
178 	umem->length     = size;
179 	umem->address    = addr;
180 	umem->writable   = root->umem.writable;
181 	umem->owning_mm  = root->umem.owning_mm;
182 	odp_data->page_shift = PAGE_SHIFT;
183 	odp_data->notifier.ops = ops;
184 
185 	/*
186 	 * A mmget must be held when registering a notifier, the owming_mm only
187 	 * has a mm_grab at this point.
188 	 */
189 	if (!mmget_not_zero(umem->owning_mm)) {
190 		ret = -EFAULT;
191 		goto out_free;
192 	}
193 
194 	odp_data->tgid = get_pid(root->tgid);
195 	ret = ib_init_umem_odp(odp_data, ops);
196 	if (ret)
197 		goto out_tgid;
198 	mmput(umem->owning_mm);
199 	return odp_data;
200 
201 out_tgid:
202 	put_pid(odp_data->tgid);
203 	mmput(umem->owning_mm);
204 out_free:
205 	kfree(odp_data);
206 	return ERR_PTR(ret);
207 }
208 EXPORT_SYMBOL(ib_umem_odp_alloc_child);
209 
210 /**
211  * ib_umem_odp_get - Create a umem_odp for a userspace va
212  *
213  * @device: IB device struct to get UMEM
214  * @addr: userspace virtual address to start at
215  * @size: length of region to pin
216  * @access: IB_ACCESS_xxx flags for memory being pinned
217  * @ops: MMU interval ops, currently only @invalidate
218  *
219  * The driver should use when the access flags indicate ODP memory. It avoids
220  * pinning, instead, stores the mm for future page fault handling in
221  * conjunction with MMU notifiers.
222  */
223 struct ib_umem_odp *ib_umem_odp_get(struct ib_device *device,
224 				    unsigned long addr, size_t size, int access,
225 				    const struct mmu_interval_notifier_ops *ops)
226 {
227 	struct ib_umem_odp *umem_odp;
228 	struct mm_struct *mm;
229 	int ret;
230 
231 	if (WARN_ON_ONCE(!(access & IB_ACCESS_ON_DEMAND)))
232 		return ERR_PTR(-EINVAL);
233 
234 	umem_odp = kzalloc(sizeof(struct ib_umem_odp), GFP_KERNEL);
235 	if (!umem_odp)
236 		return ERR_PTR(-ENOMEM);
237 
238 	umem_odp->umem.ibdev = device;
239 	umem_odp->umem.length = size;
240 	umem_odp->umem.address = addr;
241 	umem_odp->umem.writable = ib_access_writable(access);
242 	umem_odp->umem.owning_mm = mm = current->mm;
243 	umem_odp->notifier.ops = ops;
244 
245 	umem_odp->page_shift = PAGE_SHIFT;
246 #ifdef CONFIG_HUGETLB_PAGE
247 	if (access & IB_ACCESS_HUGETLB)
248 		umem_odp->page_shift = HPAGE_SHIFT;
249 #endif
250 
251 	umem_odp->tgid = get_task_pid(current->group_leader, PIDTYPE_PID);
252 	ret = ib_init_umem_odp(umem_odp, ops);
253 	if (ret)
254 		goto err_put_pid;
255 	return umem_odp;
256 
257 err_put_pid:
258 	put_pid(umem_odp->tgid);
259 	kfree(umem_odp);
260 	return ERR_PTR(ret);
261 }
262 EXPORT_SYMBOL(ib_umem_odp_get);
263 
264 void ib_umem_odp_release(struct ib_umem_odp *umem_odp)
265 {
266 	/*
267 	 * Ensure that no more pages are mapped in the umem.
268 	 *
269 	 * It is the driver's responsibility to ensure, before calling us,
270 	 * that the hardware will not attempt to access the MR any more.
271 	 */
272 	if (!umem_odp->is_implicit_odp) {
273 		mutex_lock(&umem_odp->umem_mutex);
274 		ib_umem_odp_unmap_dma_pages(umem_odp, ib_umem_start(umem_odp),
275 					    ib_umem_end(umem_odp));
276 		mutex_unlock(&umem_odp->umem_mutex);
277 		mmu_interval_notifier_remove(&umem_odp->notifier);
278 		kvfree(umem_odp->dma_list);
279 		kvfree(umem_odp->page_list);
280 	}
281 	put_pid(umem_odp->tgid);
282 	kfree(umem_odp);
283 }
284 EXPORT_SYMBOL(ib_umem_odp_release);
285 
286 /*
287  * Map for DMA and insert a single page into the on-demand paging page tables.
288  *
289  * @umem: the umem to insert the page to.
290  * @page_index: index in the umem to add the page to.
291  * @page: the page struct to map and add.
292  * @access_mask: access permissions needed for this page.
293  * @current_seq: sequence number for synchronization with invalidations.
294  *               the sequence number is taken from
295  *               umem_odp->notifiers_seq.
296  *
297  * The function returns -EFAULT if the DMA mapping operation fails. It returns
298  * -EAGAIN if a concurrent invalidation prevents us from updating the page.
299  *
300  * The page is released via put_page even if the operation failed. For on-demand
301  * pinning, the page is released whenever it isn't stored in the umem.
302  */
303 static int ib_umem_odp_map_dma_single_page(
304 		struct ib_umem_odp *umem_odp,
305 		unsigned int page_index,
306 		struct page *page,
307 		u64 access_mask,
308 		unsigned long current_seq)
309 {
310 	struct ib_device *dev = umem_odp->umem.ibdev;
311 	dma_addr_t dma_addr;
312 	int ret = 0;
313 
314 	if (mmu_interval_check_retry(&umem_odp->notifier, current_seq)) {
315 		ret = -EAGAIN;
316 		goto out;
317 	}
318 	if (!(umem_odp->dma_list[page_index])) {
319 		dma_addr =
320 			ib_dma_map_page(dev, page, 0, BIT(umem_odp->page_shift),
321 					DMA_BIDIRECTIONAL);
322 		if (ib_dma_mapping_error(dev, dma_addr)) {
323 			ret = -EFAULT;
324 			goto out;
325 		}
326 		umem_odp->dma_list[page_index] = dma_addr | access_mask;
327 		umem_odp->page_list[page_index] = page;
328 		umem_odp->npages++;
329 	} else if (umem_odp->page_list[page_index] == page) {
330 		umem_odp->dma_list[page_index] |= access_mask;
331 	} else {
332 		/*
333 		 * This is a race here where we could have done:
334 		 *
335 		 *         CPU0                             CPU1
336 		 *   get_user_pages()
337 		 *                                       invalidate()
338 		 *                                       page_fault()
339 		 *   mutex_lock(umem_mutex)
340 		 *    page from GUP != page in ODP
341 		 *
342 		 * It should be prevented by the retry test above as reading
343 		 * the seq number should be reliable under the
344 		 * umem_mutex. Thus something is really not working right if
345 		 * things get here.
346 		 */
347 		WARN(true,
348 		     "Got different pages in IB device and from get_user_pages. IB device page: %p, gup page: %p\n",
349 		     umem_odp->page_list[page_index], page);
350 		ret = -EAGAIN;
351 	}
352 
353 out:
354 	put_page(page);
355 	return ret;
356 }
357 
358 /**
359  * ib_umem_odp_map_dma_pages - Pin and DMA map userspace memory in an ODP MR.
360  *
361  * Pins the range of pages passed in the argument, and maps them to
362  * DMA addresses. The DMA addresses of the mapped pages is updated in
363  * umem_odp->dma_list.
364  *
365  * Returns the number of pages mapped in success, negative error code
366  * for failure.
367  * An -EAGAIN error code is returned when a concurrent mmu notifier prevents
368  * the function from completing its task.
369  * An -ENOENT error code indicates that userspace process is being terminated
370  * and mm was already destroyed.
371  * @umem_odp: the umem to map and pin
372  * @user_virt: the address from which we need to map.
373  * @bcnt: the minimal number of bytes to pin and map. The mapping might be
374  *        bigger due to alignment, and may also be smaller in case of an error
375  *        pinning or mapping a page. The actual pages mapped is returned in
376  *        the return value.
377  * @access_mask: bit mask of the requested access permissions for the given
378  *               range.
379  * @current_seq: the MMU notifiers sequance value for synchronization with
380  *               invalidations. the sequance number is read from
381  *               umem_odp->notifiers_seq before calling this function
382  */
383 int ib_umem_odp_map_dma_pages(struct ib_umem_odp *umem_odp, u64 user_virt,
384 			      u64 bcnt, u64 access_mask,
385 			      unsigned long current_seq)
386 {
387 	struct task_struct *owning_process  = NULL;
388 	struct mm_struct *owning_mm = umem_odp->umem.owning_mm;
389 	struct page       **local_page_list = NULL;
390 	u64 page_mask, off;
391 	int j, k, ret = 0, start_idx, npages = 0;
392 	unsigned int flags = 0, page_shift;
393 	phys_addr_t p = 0;
394 
395 	if (access_mask == 0)
396 		return -EINVAL;
397 
398 	if (user_virt < ib_umem_start(umem_odp) ||
399 	    user_virt + bcnt > ib_umem_end(umem_odp))
400 		return -EFAULT;
401 
402 	local_page_list = (struct page **)__get_free_page(GFP_KERNEL);
403 	if (!local_page_list)
404 		return -ENOMEM;
405 
406 	page_shift = umem_odp->page_shift;
407 	page_mask = ~(BIT(page_shift) - 1);
408 	off = user_virt & (~page_mask);
409 	user_virt = user_virt & page_mask;
410 	bcnt += off; /* Charge for the first page offset as well. */
411 
412 	/*
413 	 * owning_process is allowed to be NULL, this means somehow the mm is
414 	 * existing beyond the lifetime of the originating process.. Presumably
415 	 * mmget_not_zero will fail in this case.
416 	 */
417 	owning_process = get_pid_task(umem_odp->tgid, PIDTYPE_PID);
418 	if (!owning_process || !mmget_not_zero(owning_mm)) {
419 		ret = -EINVAL;
420 		goto out_put_task;
421 	}
422 
423 	if (access_mask & ODP_WRITE_ALLOWED_BIT)
424 		flags |= FOLL_WRITE;
425 
426 	start_idx = (user_virt - ib_umem_start(umem_odp)) >> page_shift;
427 	k = start_idx;
428 
429 	while (bcnt > 0) {
430 		const size_t gup_num_pages = min_t(size_t,
431 				ALIGN(bcnt, PAGE_SIZE) / PAGE_SIZE,
432 				PAGE_SIZE / sizeof(struct page *));
433 
434 		mmap_read_lock(owning_mm);
435 		/*
436 		 * Note: this might result in redundent page getting. We can
437 		 * avoid this by checking dma_list to be 0 before calling
438 		 * get_user_pages. However, this make the code much more
439 		 * complex (and doesn't gain us much performance in most use
440 		 * cases).
441 		 */
442 		npages = get_user_pages_remote(owning_mm,
443 				user_virt, gup_num_pages,
444 				flags, local_page_list, NULL, NULL);
445 		mmap_read_unlock(owning_mm);
446 
447 		if (npages < 0) {
448 			if (npages != -EAGAIN)
449 				pr_warn("fail to get %zu user pages with error %d\n", gup_num_pages, npages);
450 			else
451 				pr_debug("fail to get %zu user pages with error %d\n", gup_num_pages, npages);
452 			break;
453 		}
454 
455 		bcnt -= min_t(size_t, npages << PAGE_SHIFT, bcnt);
456 		mutex_lock(&umem_odp->umem_mutex);
457 		for (j = 0; j < npages; j++, user_virt += PAGE_SIZE) {
458 			if (user_virt & ~page_mask) {
459 				p += PAGE_SIZE;
460 				if (page_to_phys(local_page_list[j]) != p) {
461 					ret = -EFAULT;
462 					break;
463 				}
464 				put_page(local_page_list[j]);
465 				continue;
466 			}
467 
468 			ret = ib_umem_odp_map_dma_single_page(
469 					umem_odp, k, local_page_list[j],
470 					access_mask, current_seq);
471 			if (ret < 0) {
472 				if (ret != -EAGAIN)
473 					pr_warn("ib_umem_odp_map_dma_single_page failed with error %d\n", ret);
474 				else
475 					pr_debug("ib_umem_odp_map_dma_single_page failed with error %d\n", ret);
476 				break;
477 			}
478 
479 			p = page_to_phys(local_page_list[j]);
480 			k++;
481 		}
482 		mutex_unlock(&umem_odp->umem_mutex);
483 
484 		if (ret < 0) {
485 			/*
486 			 * Release pages, remembering that the first page
487 			 * to hit an error was already released by
488 			 * ib_umem_odp_map_dma_single_page().
489 			 */
490 			if (npages - (j + 1) > 0)
491 				release_pages(&local_page_list[j+1],
492 					      npages - (j + 1));
493 			break;
494 		}
495 	}
496 
497 	if (ret >= 0) {
498 		if (npages < 0 && k == start_idx)
499 			ret = npages;
500 		else
501 			ret = k - start_idx;
502 	}
503 
504 	mmput(owning_mm);
505 out_put_task:
506 	if (owning_process)
507 		put_task_struct(owning_process);
508 	free_page((unsigned long)local_page_list);
509 	return ret;
510 }
511 EXPORT_SYMBOL(ib_umem_odp_map_dma_pages);
512 
513 void ib_umem_odp_unmap_dma_pages(struct ib_umem_odp *umem_odp, u64 virt,
514 				 u64 bound)
515 {
516 	int idx;
517 	u64 addr;
518 	struct ib_device *dev = umem_odp->umem.ibdev;
519 
520 	lockdep_assert_held(&umem_odp->umem_mutex);
521 
522 	virt = max_t(u64, virt, ib_umem_start(umem_odp));
523 	bound = min_t(u64, bound, ib_umem_end(umem_odp));
524 	/* Note that during the run of this function, the
525 	 * notifiers_count of the MR is > 0, preventing any racing
526 	 * faults from completion. We might be racing with other
527 	 * invalidations, so we must make sure we free each page only
528 	 * once. */
529 	for (addr = virt; addr < bound; addr += BIT(umem_odp->page_shift)) {
530 		idx = (addr - ib_umem_start(umem_odp)) >> umem_odp->page_shift;
531 		if (umem_odp->page_list[idx]) {
532 			struct page *page = umem_odp->page_list[idx];
533 			dma_addr_t dma = umem_odp->dma_list[idx];
534 			dma_addr_t dma_addr = dma & ODP_DMA_ADDR_MASK;
535 
536 			WARN_ON(!dma_addr);
537 
538 			ib_dma_unmap_page(dev, dma_addr,
539 					  BIT(umem_odp->page_shift),
540 					  DMA_BIDIRECTIONAL);
541 			if (dma & ODP_WRITE_ALLOWED_BIT) {
542 				struct page *head_page = compound_head(page);
543 				/*
544 				 * set_page_dirty prefers being called with
545 				 * the page lock. However, MMU notifiers are
546 				 * called sometimes with and sometimes without
547 				 * the lock. We rely on the umem_mutex instead
548 				 * to prevent other mmu notifiers from
549 				 * continuing and allowing the page mapping to
550 				 * be removed.
551 				 */
552 				set_page_dirty(head_page);
553 			}
554 			umem_odp->page_list[idx] = NULL;
555 			umem_odp->dma_list[idx] = 0;
556 			umem_odp->npages--;
557 		}
558 	}
559 }
560 EXPORT_SYMBOL(ib_umem_odp_unmap_dma_pages);
561