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