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_generic.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 /*
50  * The ib_umem list keeps track of memory regions for which the HW
51  * device request to receive notification when the related memory
52  * mapping is changed.
53  *
54  * ib_umem_lock protects the list.
55  */
56 
57 static u64 node_start(struct umem_odp_node *n)
58 {
59 	struct ib_umem_odp *umem_odp =
60 			container_of(n, struct ib_umem_odp, interval_tree);
61 
62 	return ib_umem_start(&umem_odp->umem);
63 }
64 
65 /* Note that the representation of the intervals in the interval tree
66  * considers the ending point as contained in the interval, while the
67  * function ib_umem_end returns the first address which is not contained
68  * in the umem.
69  */
70 static u64 node_last(struct umem_odp_node *n)
71 {
72 	struct ib_umem_odp *umem_odp =
73 			container_of(n, struct ib_umem_odp, interval_tree);
74 
75 	return ib_umem_end(&umem_odp->umem) - 1;
76 }
77 
78 INTERVAL_TREE_DEFINE(struct umem_odp_node, rb, u64, __subtree_last,
79 		     node_start, node_last, static, rbt_ib_umem)
80 
81 static void ib_umem_notifier_start_account(struct ib_umem_odp *umem_odp)
82 {
83 	mutex_lock(&umem_odp->umem_mutex);
84 	if (umem_odp->notifiers_count++ == 0)
85 		/*
86 		 * Initialize the completion object for waiting on
87 		 * notifiers. Since notifier_count is zero, no one should be
88 		 * waiting right now.
89 		 */
90 		reinit_completion(&umem_odp->notifier_completion);
91 	mutex_unlock(&umem_odp->umem_mutex);
92 }
93 
94 static void ib_umem_notifier_end_account(struct ib_umem_odp *umem_odp)
95 {
96 	mutex_lock(&umem_odp->umem_mutex);
97 	/*
98 	 * This sequence increase will notify the QP page fault that the page
99 	 * that is going to be mapped in the spte could have been freed.
100 	 */
101 	++umem_odp->notifiers_seq;
102 	if (--umem_odp->notifiers_count == 0)
103 		complete_all(&umem_odp->notifier_completion);
104 	mutex_unlock(&umem_odp->umem_mutex);
105 }
106 
107 static int ib_umem_notifier_release_trampoline(struct ib_umem_odp *umem_odp,
108 					       u64 start, u64 end, void *cookie)
109 {
110 	struct ib_umem *umem = &umem_odp->umem;
111 
112 	/*
113 	 * Increase the number of notifiers running, to
114 	 * prevent any further fault handling on this MR.
115 	 */
116 	ib_umem_notifier_start_account(umem_odp);
117 	umem_odp->dying = 1;
118 	/* Make sure that the fact the umem is dying is out before we release
119 	 * all pending page faults. */
120 	smp_wmb();
121 	complete_all(&umem_odp->notifier_completion);
122 	umem->context->invalidate_range(umem_odp, ib_umem_start(umem),
123 					ib_umem_end(umem));
124 	return 0;
125 }
126 
127 static void ib_umem_notifier_release(struct mmu_notifier *mn,
128 				     struct mm_struct *mm)
129 {
130 	struct ib_ucontext_per_mm *per_mm =
131 		container_of(mn, struct ib_ucontext_per_mm, mn);
132 
133 	down_read(&per_mm->umem_rwsem);
134 	if (per_mm->active)
135 		rbt_ib_umem_for_each_in_range(
136 			&per_mm->umem_tree, 0, ULLONG_MAX,
137 			ib_umem_notifier_release_trampoline, true, NULL);
138 	up_read(&per_mm->umem_rwsem);
139 }
140 
141 static int invalidate_range_start_trampoline(struct ib_umem_odp *item,
142 					     u64 start, u64 end, void *cookie)
143 {
144 	ib_umem_notifier_start_account(item);
145 	item->umem.context->invalidate_range(item, start, end);
146 	return 0;
147 }
148 
149 static int ib_umem_notifier_invalidate_range_start(struct mmu_notifier *mn,
150 				const struct mmu_notifier_range *range)
151 {
152 	struct ib_ucontext_per_mm *per_mm =
153 		container_of(mn, struct ib_ucontext_per_mm, mn);
154 
155 	if (range->blockable)
156 		down_read(&per_mm->umem_rwsem);
157 	else if (!down_read_trylock(&per_mm->umem_rwsem))
158 		return -EAGAIN;
159 
160 	if (!per_mm->active) {
161 		up_read(&per_mm->umem_rwsem);
162 		/*
163 		 * At this point active is permanently set and visible to this
164 		 * CPU without a lock, that fact is relied on to skip the unlock
165 		 * in range_end.
166 		 */
167 		return 0;
168 	}
169 
170 	return rbt_ib_umem_for_each_in_range(&per_mm->umem_tree, range->start,
171 					     range->end,
172 					     invalidate_range_start_trampoline,
173 					     range->blockable, NULL);
174 }
175 
176 static int invalidate_range_end_trampoline(struct ib_umem_odp *item, u64 start,
177 					   u64 end, void *cookie)
178 {
179 	ib_umem_notifier_end_account(item);
180 	return 0;
181 }
182 
183 static void ib_umem_notifier_invalidate_range_end(struct mmu_notifier *mn,
184 				const struct mmu_notifier_range *range)
185 {
186 	struct ib_ucontext_per_mm *per_mm =
187 		container_of(mn, struct ib_ucontext_per_mm, mn);
188 
189 	if (unlikely(!per_mm->active))
190 		return;
191 
192 	rbt_ib_umem_for_each_in_range(&per_mm->umem_tree, range->start,
193 				      range->end,
194 				      invalidate_range_end_trampoline, true, NULL);
195 	up_read(&per_mm->umem_rwsem);
196 }
197 
198 static const struct mmu_notifier_ops ib_umem_notifiers = {
199 	.release                    = ib_umem_notifier_release,
200 	.invalidate_range_start     = ib_umem_notifier_invalidate_range_start,
201 	.invalidate_range_end       = ib_umem_notifier_invalidate_range_end,
202 };
203 
204 static void add_umem_to_per_mm(struct ib_umem_odp *umem_odp)
205 {
206 	struct ib_ucontext_per_mm *per_mm = umem_odp->per_mm;
207 	struct ib_umem *umem = &umem_odp->umem;
208 
209 	down_write(&per_mm->umem_rwsem);
210 	if (likely(ib_umem_start(umem) != ib_umem_end(umem)))
211 		rbt_ib_umem_insert(&umem_odp->interval_tree,
212 				   &per_mm->umem_tree);
213 	up_write(&per_mm->umem_rwsem);
214 }
215 
216 static void remove_umem_from_per_mm(struct ib_umem_odp *umem_odp)
217 {
218 	struct ib_ucontext_per_mm *per_mm = umem_odp->per_mm;
219 	struct ib_umem *umem = &umem_odp->umem;
220 
221 	down_write(&per_mm->umem_rwsem);
222 	if (likely(ib_umem_start(umem) != ib_umem_end(umem)))
223 		rbt_ib_umem_remove(&umem_odp->interval_tree,
224 				   &per_mm->umem_tree);
225 	complete_all(&umem_odp->notifier_completion);
226 
227 	up_write(&per_mm->umem_rwsem);
228 }
229 
230 static struct ib_ucontext_per_mm *alloc_per_mm(struct ib_ucontext *ctx,
231 					       struct mm_struct *mm)
232 {
233 	struct ib_ucontext_per_mm *per_mm;
234 	int ret;
235 
236 	per_mm = kzalloc(sizeof(*per_mm), GFP_KERNEL);
237 	if (!per_mm)
238 		return ERR_PTR(-ENOMEM);
239 
240 	per_mm->context = ctx;
241 	per_mm->mm = mm;
242 	per_mm->umem_tree = RB_ROOT_CACHED;
243 	init_rwsem(&per_mm->umem_rwsem);
244 	per_mm->active = true;
245 
246 	rcu_read_lock();
247 	per_mm->tgid = get_task_pid(current->group_leader, PIDTYPE_PID);
248 	rcu_read_unlock();
249 
250 	WARN_ON(mm != current->mm);
251 
252 	per_mm->mn.ops = &ib_umem_notifiers;
253 	ret = mmu_notifier_register(&per_mm->mn, per_mm->mm);
254 	if (ret) {
255 		dev_err(&ctx->device->dev,
256 			"Failed to register mmu_notifier %d\n", ret);
257 		goto out_pid;
258 	}
259 
260 	list_add(&per_mm->ucontext_list, &ctx->per_mm_list);
261 	return per_mm;
262 
263 out_pid:
264 	put_pid(per_mm->tgid);
265 	kfree(per_mm);
266 	return ERR_PTR(ret);
267 }
268 
269 static int get_per_mm(struct ib_umem_odp *umem_odp)
270 {
271 	struct ib_ucontext *ctx = umem_odp->umem.context;
272 	struct ib_ucontext_per_mm *per_mm;
273 
274 	/*
275 	 * Generally speaking we expect only one or two per_mm in this list,
276 	 * so no reason to optimize this search today.
277 	 */
278 	mutex_lock(&ctx->per_mm_list_lock);
279 	list_for_each_entry(per_mm, &ctx->per_mm_list, ucontext_list) {
280 		if (per_mm->mm == umem_odp->umem.owning_mm)
281 			goto found;
282 	}
283 
284 	per_mm = alloc_per_mm(ctx, umem_odp->umem.owning_mm);
285 	if (IS_ERR(per_mm)) {
286 		mutex_unlock(&ctx->per_mm_list_lock);
287 		return PTR_ERR(per_mm);
288 	}
289 
290 found:
291 	umem_odp->per_mm = per_mm;
292 	per_mm->odp_mrs_count++;
293 	mutex_unlock(&ctx->per_mm_list_lock);
294 
295 	return 0;
296 }
297 
298 static void free_per_mm(struct rcu_head *rcu)
299 {
300 	kfree(container_of(rcu, struct ib_ucontext_per_mm, rcu));
301 }
302 
303 static void put_per_mm(struct ib_umem_odp *umem_odp)
304 {
305 	struct ib_ucontext_per_mm *per_mm = umem_odp->per_mm;
306 	struct ib_ucontext *ctx = umem_odp->umem.context;
307 	bool need_free;
308 
309 	mutex_lock(&ctx->per_mm_list_lock);
310 	umem_odp->per_mm = NULL;
311 	per_mm->odp_mrs_count--;
312 	need_free = per_mm->odp_mrs_count == 0;
313 	if (need_free)
314 		list_del(&per_mm->ucontext_list);
315 	mutex_unlock(&ctx->per_mm_list_lock);
316 
317 	if (!need_free)
318 		return;
319 
320 	/*
321 	 * NOTE! mmu_notifier_unregister() can happen between a start/end
322 	 * callback, resulting in an start/end, and thus an unbalanced
323 	 * lock. This doesn't really matter to us since we are about to kfree
324 	 * the memory that holds the lock, however LOCKDEP doesn't like this.
325 	 */
326 	down_write(&per_mm->umem_rwsem);
327 	per_mm->active = false;
328 	up_write(&per_mm->umem_rwsem);
329 
330 	WARN_ON(!RB_EMPTY_ROOT(&per_mm->umem_tree.rb_root));
331 	mmu_notifier_unregister_no_release(&per_mm->mn, per_mm->mm);
332 	put_pid(per_mm->tgid);
333 	mmu_notifier_call_srcu(&per_mm->rcu, free_per_mm);
334 }
335 
336 struct ib_umem_odp *ib_alloc_odp_umem(struct ib_umem_odp *root,
337 				      unsigned long addr, size_t size)
338 {
339 	struct ib_ucontext_per_mm *per_mm = root->per_mm;
340 	struct ib_ucontext *ctx = per_mm->context;
341 	struct ib_umem_odp *odp_data;
342 	struct ib_umem *umem;
343 	int pages = size >> PAGE_SHIFT;
344 	int ret;
345 
346 	odp_data = kzalloc(sizeof(*odp_data), GFP_KERNEL);
347 	if (!odp_data)
348 		return ERR_PTR(-ENOMEM);
349 	umem = &odp_data->umem;
350 	umem->context    = ctx;
351 	umem->length     = size;
352 	umem->address    = addr;
353 	umem->page_shift = PAGE_SHIFT;
354 	umem->writable   = root->umem.writable;
355 	umem->is_odp = 1;
356 	odp_data->per_mm = per_mm;
357 	umem->owning_mm  = per_mm->mm;
358 	mmgrab(umem->owning_mm);
359 
360 	mutex_init(&odp_data->umem_mutex);
361 	init_completion(&odp_data->notifier_completion);
362 
363 	odp_data->page_list =
364 		vzalloc(array_size(pages, sizeof(*odp_data->page_list)));
365 	if (!odp_data->page_list) {
366 		ret = -ENOMEM;
367 		goto out_odp_data;
368 	}
369 
370 	odp_data->dma_list =
371 		vzalloc(array_size(pages, sizeof(*odp_data->dma_list)));
372 	if (!odp_data->dma_list) {
373 		ret = -ENOMEM;
374 		goto out_page_list;
375 	}
376 
377 	/*
378 	 * Caller must ensure that the umem_odp that the per_mm came from
379 	 * cannot be freed during the call to ib_alloc_odp_umem.
380 	 */
381 	mutex_lock(&ctx->per_mm_list_lock);
382 	per_mm->odp_mrs_count++;
383 	mutex_unlock(&ctx->per_mm_list_lock);
384 	add_umem_to_per_mm(odp_data);
385 
386 	return odp_data;
387 
388 out_page_list:
389 	vfree(odp_data->page_list);
390 out_odp_data:
391 	mmdrop(umem->owning_mm);
392 	kfree(odp_data);
393 	return ERR_PTR(ret);
394 }
395 EXPORT_SYMBOL(ib_alloc_odp_umem);
396 
397 int ib_umem_odp_get(struct ib_umem_odp *umem_odp, int access)
398 {
399 	struct ib_umem *umem = &umem_odp->umem;
400 	/*
401 	 * NOTE: This must called in a process context where umem->owning_mm
402 	 * == current->mm
403 	 */
404 	struct mm_struct *mm = umem->owning_mm;
405 	int ret_val;
406 
407 	if (access & IB_ACCESS_HUGETLB) {
408 		struct vm_area_struct *vma;
409 		struct hstate *h;
410 
411 		down_read(&mm->mmap_sem);
412 		vma = find_vma(mm, ib_umem_start(umem));
413 		if (!vma || !is_vm_hugetlb_page(vma)) {
414 			up_read(&mm->mmap_sem);
415 			return -EINVAL;
416 		}
417 		h = hstate_vma(vma);
418 		umem->page_shift = huge_page_shift(h);
419 		up_read(&mm->mmap_sem);
420 		umem->hugetlb = 1;
421 	} else {
422 		umem->hugetlb = 0;
423 	}
424 
425 	mutex_init(&umem_odp->umem_mutex);
426 
427 	init_completion(&umem_odp->notifier_completion);
428 
429 	if (ib_umem_num_pages(umem)) {
430 		umem_odp->page_list =
431 			vzalloc(array_size(sizeof(*umem_odp->page_list),
432 					   ib_umem_num_pages(umem)));
433 		if (!umem_odp->page_list)
434 			return -ENOMEM;
435 
436 		umem_odp->dma_list =
437 			vzalloc(array_size(sizeof(*umem_odp->dma_list),
438 					   ib_umem_num_pages(umem)));
439 		if (!umem_odp->dma_list) {
440 			ret_val = -ENOMEM;
441 			goto out_page_list;
442 		}
443 	}
444 
445 	ret_val = get_per_mm(umem_odp);
446 	if (ret_val)
447 		goto out_dma_list;
448 	add_umem_to_per_mm(umem_odp);
449 
450 	return 0;
451 
452 out_dma_list:
453 	vfree(umem_odp->dma_list);
454 out_page_list:
455 	vfree(umem_odp->page_list);
456 	return ret_val;
457 }
458 
459 void ib_umem_odp_release(struct ib_umem_odp *umem_odp)
460 {
461 	struct ib_umem *umem = &umem_odp->umem;
462 
463 	/*
464 	 * Ensure that no more pages are mapped in the umem.
465 	 *
466 	 * It is the driver's responsibility to ensure, before calling us,
467 	 * that the hardware will not attempt to access the MR any more.
468 	 */
469 	ib_umem_odp_unmap_dma_pages(umem_odp, ib_umem_start(umem),
470 				    ib_umem_end(umem));
471 
472 	remove_umem_from_per_mm(umem_odp);
473 	put_per_mm(umem_odp);
474 	vfree(umem_odp->dma_list);
475 	vfree(umem_odp->page_list);
476 }
477 
478 /*
479  * Map for DMA and insert a single page into the on-demand paging page tables.
480  *
481  * @umem: the umem to insert the page to.
482  * @page_index: index in the umem to add the page to.
483  * @page: the page struct to map and add.
484  * @access_mask: access permissions needed for this page.
485  * @current_seq: sequence number for synchronization with invalidations.
486  *               the sequence number is taken from
487  *               umem_odp->notifiers_seq.
488  *
489  * The function returns -EFAULT if the DMA mapping operation fails. It returns
490  * -EAGAIN if a concurrent invalidation prevents us from updating the page.
491  *
492  * The page is released via put_page even if the operation failed. For
493  * on-demand pinning, the page is released whenever it isn't stored in the
494  * umem.
495  */
496 static int ib_umem_odp_map_dma_single_page(
497 		struct ib_umem_odp *umem_odp,
498 		int page_index,
499 		struct page *page,
500 		u64 access_mask,
501 		unsigned long current_seq)
502 {
503 	struct ib_umem *umem = &umem_odp->umem;
504 	struct ib_device *dev = umem->context->device;
505 	dma_addr_t dma_addr;
506 	int remove_existing_mapping = 0;
507 	int ret = 0;
508 
509 	/*
510 	 * Note: we avoid writing if seq is different from the initial seq, to
511 	 * handle case of a racing notifier. This check also allows us to bail
512 	 * early if we have a notifier running in parallel with us.
513 	 */
514 	if (ib_umem_mmu_notifier_retry(umem_odp, current_seq)) {
515 		ret = -EAGAIN;
516 		goto out;
517 	}
518 	if (!(umem_odp->dma_list[page_index])) {
519 		dma_addr = ib_dma_map_page(dev,
520 					   page,
521 					   0, BIT(umem->page_shift),
522 					   DMA_BIDIRECTIONAL);
523 		if (ib_dma_mapping_error(dev, dma_addr)) {
524 			ret = -EFAULT;
525 			goto out;
526 		}
527 		umem_odp->dma_list[page_index] = dma_addr | access_mask;
528 		umem_odp->page_list[page_index] = page;
529 		umem_odp->npages++;
530 	} else if (umem_odp->page_list[page_index] == page) {
531 		umem_odp->dma_list[page_index] |= access_mask;
532 	} else {
533 		pr_err("error: got different pages in IB device and from get_user_pages. IB device page: %p, gup page: %p\n",
534 		       umem_odp->page_list[page_index], page);
535 		/* Better remove the mapping now, to prevent any further
536 		 * damage. */
537 		remove_existing_mapping = 1;
538 	}
539 
540 out:
541 	put_page(page);
542 
543 	if (remove_existing_mapping) {
544 		ib_umem_notifier_start_account(umem_odp);
545 		umem->context->invalidate_range(
546 			umem_odp,
547 			ib_umem_start(umem) + (page_index << umem->page_shift),
548 			ib_umem_start(umem) +
549 				((page_index + 1) << umem->page_shift));
550 		ib_umem_notifier_end_account(umem_odp);
551 		ret = -EAGAIN;
552 	}
553 
554 	return ret;
555 }
556 
557 /**
558  * ib_umem_odp_map_dma_pages - Pin and DMA map userspace memory in an ODP MR.
559  *
560  * Pins the range of pages passed in the argument, and maps them to
561  * DMA addresses. The DMA addresses of the mapped pages is updated in
562  * umem_odp->dma_list.
563  *
564  * Returns the number of pages mapped in success, negative error code
565  * for failure.
566  * An -EAGAIN error code is returned when a concurrent mmu notifier prevents
567  * the function from completing its task.
568  * An -ENOENT error code indicates that userspace process is being terminated
569  * and mm was already destroyed.
570  * @umem_odp: the umem to map and pin
571  * @user_virt: the address from which we need to map.
572  * @bcnt: the minimal number of bytes to pin and map. The mapping might be
573  *        bigger due to alignment, and may also be smaller in case of an error
574  *        pinning or mapping a page. The actual pages mapped is returned in
575  *        the return value.
576  * @access_mask: bit mask of the requested access permissions for the given
577  *               range.
578  * @current_seq: the MMU notifiers sequance value for synchronization with
579  *               invalidations. the sequance number is read from
580  *               umem_odp->notifiers_seq before calling this function
581  */
582 int ib_umem_odp_map_dma_pages(struct ib_umem_odp *umem_odp, u64 user_virt,
583 			      u64 bcnt, u64 access_mask,
584 			      unsigned long current_seq)
585 {
586 	struct ib_umem *umem = &umem_odp->umem;
587 	struct task_struct *owning_process  = NULL;
588 	struct mm_struct *owning_mm = umem_odp->umem.owning_mm;
589 	struct page       **local_page_list = NULL;
590 	u64 page_mask, off;
591 	int j, k, ret = 0, start_idx, npages = 0, page_shift;
592 	unsigned int flags = 0;
593 	phys_addr_t p = 0;
594 
595 	if (access_mask == 0)
596 		return -EINVAL;
597 
598 	if (user_virt < ib_umem_start(umem) ||
599 	    user_virt + bcnt > ib_umem_end(umem))
600 		return -EFAULT;
601 
602 	local_page_list = (struct page **)__get_free_page(GFP_KERNEL);
603 	if (!local_page_list)
604 		return -ENOMEM;
605 
606 	page_shift = umem->page_shift;
607 	page_mask = ~(BIT(page_shift) - 1);
608 	off = user_virt & (~page_mask);
609 	user_virt = user_virt & page_mask;
610 	bcnt += off; /* Charge for the first page offset as well. */
611 
612 	/*
613 	 * owning_process is allowed to be NULL, this means somehow the mm is
614 	 * existing beyond the lifetime of the originating process.. Presumably
615 	 * mmget_not_zero will fail in this case.
616 	 */
617 	owning_process = get_pid_task(umem_odp->per_mm->tgid, PIDTYPE_PID);
618 	if (!owning_process || !mmget_not_zero(owning_mm)) {
619 		ret = -EINVAL;
620 		goto out_put_task;
621 	}
622 
623 	if (access_mask & ODP_WRITE_ALLOWED_BIT)
624 		flags |= FOLL_WRITE;
625 
626 	start_idx = (user_virt - ib_umem_start(umem)) >> page_shift;
627 	k = start_idx;
628 
629 	while (bcnt > 0) {
630 		const size_t gup_num_pages = min_t(size_t,
631 				(bcnt + BIT(page_shift) - 1) >> page_shift,
632 				PAGE_SIZE / sizeof(struct page *));
633 
634 		down_read(&owning_mm->mmap_sem);
635 		/*
636 		 * Note: this might result in redundent page getting. We can
637 		 * avoid this by checking dma_list to be 0 before calling
638 		 * get_user_pages. However, this make the code much more
639 		 * complex (and doesn't gain us much performance in most use
640 		 * cases).
641 		 */
642 		npages = get_user_pages_remote(owning_process, owning_mm,
643 				user_virt, gup_num_pages,
644 				flags, local_page_list, NULL, NULL);
645 		up_read(&owning_mm->mmap_sem);
646 
647 		if (npages < 0) {
648 			if (npages != -EAGAIN)
649 				pr_warn("fail to get %zu user pages with error %d\n", gup_num_pages, npages);
650 			else
651 				pr_debug("fail to get %zu user pages with error %d\n", gup_num_pages, npages);
652 			break;
653 		}
654 
655 		bcnt -= min_t(size_t, npages << PAGE_SHIFT, bcnt);
656 		mutex_lock(&umem_odp->umem_mutex);
657 		for (j = 0; j < npages; j++, user_virt += PAGE_SIZE) {
658 			if (user_virt & ~page_mask) {
659 				p += PAGE_SIZE;
660 				if (page_to_phys(local_page_list[j]) != p) {
661 					ret = -EFAULT;
662 					break;
663 				}
664 				put_page(local_page_list[j]);
665 				continue;
666 			}
667 
668 			ret = ib_umem_odp_map_dma_single_page(
669 					umem_odp, k, local_page_list[j],
670 					access_mask, current_seq);
671 			if (ret < 0) {
672 				if (ret != -EAGAIN)
673 					pr_warn("ib_umem_odp_map_dma_single_page failed with error %d\n", ret);
674 				else
675 					pr_debug("ib_umem_odp_map_dma_single_page failed with error %d\n", ret);
676 				break;
677 			}
678 
679 			p = page_to_phys(local_page_list[j]);
680 			k++;
681 		}
682 		mutex_unlock(&umem_odp->umem_mutex);
683 
684 		if (ret < 0) {
685 			/*
686 			 * Release pages, remembering that the first page
687 			 * to hit an error was already released by
688 			 * ib_umem_odp_map_dma_single_page().
689 			 */
690 			if (npages - (j + 1) > 0)
691 				release_pages(&local_page_list[j+1],
692 					      npages - (j + 1));
693 			break;
694 		}
695 	}
696 
697 	if (ret >= 0) {
698 		if (npages < 0 && k == start_idx)
699 			ret = npages;
700 		else
701 			ret = k - start_idx;
702 	}
703 
704 	mmput(owning_mm);
705 out_put_task:
706 	if (owning_process)
707 		put_task_struct(owning_process);
708 	free_page((unsigned long)local_page_list);
709 	return ret;
710 }
711 EXPORT_SYMBOL(ib_umem_odp_map_dma_pages);
712 
713 void ib_umem_odp_unmap_dma_pages(struct ib_umem_odp *umem_odp, u64 virt,
714 				 u64 bound)
715 {
716 	struct ib_umem *umem = &umem_odp->umem;
717 	int idx;
718 	u64 addr;
719 	struct ib_device *dev = umem->context->device;
720 
721 	virt  = max_t(u64, virt,  ib_umem_start(umem));
722 	bound = min_t(u64, bound, ib_umem_end(umem));
723 	/* Note that during the run of this function, the
724 	 * notifiers_count of the MR is > 0, preventing any racing
725 	 * faults from completion. We might be racing with other
726 	 * invalidations, so we must make sure we free each page only
727 	 * once. */
728 	mutex_lock(&umem_odp->umem_mutex);
729 	for (addr = virt; addr < bound; addr += BIT(umem->page_shift)) {
730 		idx = (addr - ib_umem_start(umem)) >> umem->page_shift;
731 		if (umem_odp->page_list[idx]) {
732 			struct page *page = umem_odp->page_list[idx];
733 			dma_addr_t dma = umem_odp->dma_list[idx];
734 			dma_addr_t dma_addr = dma & ODP_DMA_ADDR_MASK;
735 
736 			WARN_ON(!dma_addr);
737 
738 			ib_dma_unmap_page(dev, dma_addr, PAGE_SIZE,
739 					  DMA_BIDIRECTIONAL);
740 			if (dma & ODP_WRITE_ALLOWED_BIT) {
741 				struct page *head_page = compound_head(page);
742 				/*
743 				 * set_page_dirty prefers being called with
744 				 * the page lock. However, MMU notifiers are
745 				 * called sometimes with and sometimes without
746 				 * the lock. We rely on the umem_mutex instead
747 				 * to prevent other mmu notifiers from
748 				 * continuing and allowing the page mapping to
749 				 * be removed.
750 				 */
751 				set_page_dirty(head_page);
752 			}
753 			umem_odp->page_list[idx] = NULL;
754 			umem_odp->dma_list[idx] = 0;
755 			umem_odp->npages--;
756 		}
757 	}
758 	mutex_unlock(&umem_odp->umem_mutex);
759 }
760 EXPORT_SYMBOL(ib_umem_odp_unmap_dma_pages);
761 
762 /* @last is not a part of the interval. See comment for function
763  * node_last.
764  */
765 int rbt_ib_umem_for_each_in_range(struct rb_root_cached *root,
766 				  u64 start, u64 last,
767 				  umem_call_back cb,
768 				  bool blockable,
769 				  void *cookie)
770 {
771 	int ret_val = 0;
772 	struct umem_odp_node *node, *next;
773 	struct ib_umem_odp *umem;
774 
775 	if (unlikely(start == last))
776 		return ret_val;
777 
778 	for (node = rbt_ib_umem_iter_first(root, start, last - 1);
779 			node; node = next) {
780 		/* TODO move the blockable decision up to the callback */
781 		if (!blockable)
782 			return -EAGAIN;
783 		next = rbt_ib_umem_iter_next(node, start, last - 1);
784 		umem = container_of(node, struct ib_umem_odp, interval_tree);
785 		ret_val = cb(umem, start, last, cookie) || ret_val;
786 	}
787 
788 	return ret_val;
789 }
790 EXPORT_SYMBOL(rbt_ib_umem_for_each_in_range);
791 
792 struct ib_umem_odp *rbt_ib_umem_lookup(struct rb_root_cached *root,
793 				       u64 addr, u64 length)
794 {
795 	struct umem_odp_node *node;
796 
797 	node = rbt_ib_umem_iter_first(root, addr, addr + length - 1);
798 	if (node)
799 		return container_of(node, struct ib_umem_odp, interval_tree);
800 	return NULL;
801 
802 }
803 EXPORT_SYMBOL(rbt_ib_umem_lookup);
804