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