xref: /openbmc/linux/drivers/infiniband/hw/mlx5/odp.c (revision 6f4eaea2)
1 /*
2  * Copyright (c) 2013-2015, 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 <rdma/ib_umem.h>
34 #include <rdma/ib_umem_odp.h>
35 #include <linux/kernel.h>
36 #include <linux/dma-buf.h>
37 #include <linux/dma-resv.h>
38 
39 #include "mlx5_ib.h"
40 #include "cmd.h"
41 #include "qp.h"
42 
43 #include <linux/mlx5/eq.h>
44 
45 /* Contains the details of a pagefault. */
46 struct mlx5_pagefault {
47 	u32			bytes_committed;
48 	u32			token;
49 	u8			event_subtype;
50 	u8			type;
51 	union {
52 		/* Initiator or send message responder pagefault details. */
53 		struct {
54 			/* Received packet size, only valid for responders. */
55 			u32	packet_size;
56 			/*
57 			 * Number of resource holding WQE, depends on type.
58 			 */
59 			u32	wq_num;
60 			/*
61 			 * WQE index. Refers to either the send queue or
62 			 * receive queue, according to event_subtype.
63 			 */
64 			u16	wqe_index;
65 		} wqe;
66 		/* RDMA responder pagefault details */
67 		struct {
68 			u32	r_key;
69 			/*
70 			 * Received packet size, minimal size page fault
71 			 * resolution required for forward progress.
72 			 */
73 			u32	packet_size;
74 			u32	rdma_op_len;
75 			u64	rdma_va;
76 		} rdma;
77 	};
78 
79 	struct mlx5_ib_pf_eq	*eq;
80 	struct work_struct	work;
81 };
82 
83 #define MAX_PREFETCH_LEN (4*1024*1024U)
84 
85 /* Timeout in ms to wait for an active mmu notifier to complete when handling
86  * a pagefault. */
87 #define MMU_NOTIFIER_TIMEOUT 1000
88 
89 #define MLX5_IMR_MTT_BITS (30 - PAGE_SHIFT)
90 #define MLX5_IMR_MTT_SHIFT (MLX5_IMR_MTT_BITS + PAGE_SHIFT)
91 #define MLX5_IMR_MTT_ENTRIES BIT_ULL(MLX5_IMR_MTT_BITS)
92 #define MLX5_IMR_MTT_SIZE BIT_ULL(MLX5_IMR_MTT_SHIFT)
93 #define MLX5_IMR_MTT_MASK (~(MLX5_IMR_MTT_SIZE - 1))
94 
95 #define MLX5_KSM_PAGE_SHIFT MLX5_IMR_MTT_SHIFT
96 
97 static u64 mlx5_imr_ksm_entries;
98 
99 static void populate_klm(struct mlx5_klm *pklm, size_t idx, size_t nentries,
100 			struct mlx5_ib_mr *imr, int flags)
101 {
102 	struct mlx5_klm *end = pklm + nentries;
103 
104 	if (flags & MLX5_IB_UPD_XLT_ZAP) {
105 		for (; pklm != end; pklm++, idx++) {
106 			pklm->bcount = cpu_to_be32(MLX5_IMR_MTT_SIZE);
107 			pklm->key = cpu_to_be32(mr_to_mdev(imr)->null_mkey);
108 			pklm->va = 0;
109 		}
110 		return;
111 	}
112 
113 	/*
114 	 * The locking here is pretty subtle. Ideally the implicit_children
115 	 * xarray would be protected by the umem_mutex, however that is not
116 	 * possible. Instead this uses a weaker update-then-lock pattern:
117 	 *
118 	 *    xa_store()
119 	 *    mutex_lock(umem_mutex)
120 	 *     mlx5_ib_update_xlt()
121 	 *    mutex_unlock(umem_mutex)
122 	 *    destroy lkey
123 	 *
124 	 * ie any change the xarray must be followed by the locked update_xlt
125 	 * before destroying.
126 	 *
127 	 * The umem_mutex provides the acquire/release semantic needed to make
128 	 * the xa_store() visible to a racing thread.
129 	 */
130 	lockdep_assert_held(&to_ib_umem_odp(imr->umem)->umem_mutex);
131 
132 	for (; pklm != end; pklm++, idx++) {
133 		struct mlx5_ib_mr *mtt = xa_load(&imr->implicit_children, idx);
134 
135 		pklm->bcount = cpu_to_be32(MLX5_IMR_MTT_SIZE);
136 		if (mtt) {
137 			pklm->key = cpu_to_be32(mtt->ibmr.lkey);
138 			pklm->va = cpu_to_be64(idx * MLX5_IMR_MTT_SIZE);
139 		} else {
140 			pklm->key = cpu_to_be32(mr_to_mdev(imr)->null_mkey);
141 			pklm->va = 0;
142 		}
143 	}
144 }
145 
146 static u64 umem_dma_to_mtt(dma_addr_t umem_dma)
147 {
148 	u64 mtt_entry = umem_dma & ODP_DMA_ADDR_MASK;
149 
150 	if (umem_dma & ODP_READ_ALLOWED_BIT)
151 		mtt_entry |= MLX5_IB_MTT_READ;
152 	if (umem_dma & ODP_WRITE_ALLOWED_BIT)
153 		mtt_entry |= MLX5_IB_MTT_WRITE;
154 
155 	return mtt_entry;
156 }
157 
158 static void populate_mtt(__be64 *pas, size_t idx, size_t nentries,
159 			 struct mlx5_ib_mr *mr, int flags)
160 {
161 	struct ib_umem_odp *odp = to_ib_umem_odp(mr->umem);
162 	dma_addr_t pa;
163 	size_t i;
164 
165 	if (flags & MLX5_IB_UPD_XLT_ZAP)
166 		return;
167 
168 	for (i = 0; i < nentries; i++) {
169 		pa = odp->dma_list[idx + i];
170 		pas[i] = cpu_to_be64(umem_dma_to_mtt(pa));
171 	}
172 }
173 
174 void mlx5_odp_populate_xlt(void *xlt, size_t idx, size_t nentries,
175 			   struct mlx5_ib_mr *mr, int flags)
176 {
177 	if (flags & MLX5_IB_UPD_XLT_INDIRECT) {
178 		populate_klm(xlt, idx, nentries, mr, flags);
179 	} else {
180 		populate_mtt(xlt, idx, nentries, mr, flags);
181 	}
182 }
183 
184 static void dma_fence_odp_mr(struct mlx5_ib_mr *mr)
185 {
186 	struct ib_umem_odp *odp = to_ib_umem_odp(mr->umem);
187 
188 	/* Ensure mlx5_ib_invalidate_range() will not touch the MR any more */
189 	mutex_lock(&odp->umem_mutex);
190 	if (odp->npages) {
191 		mlx5_mr_cache_invalidate(mr);
192 		ib_umem_odp_unmap_dma_pages(odp, ib_umem_start(odp),
193 					    ib_umem_end(odp));
194 		WARN_ON(odp->npages);
195 	}
196 	odp->private = NULL;
197 	mutex_unlock(&odp->umem_mutex);
198 
199 	if (!mr->cache_ent) {
200 		mlx5_core_destroy_mkey(mr_to_mdev(mr)->mdev, &mr->mmkey);
201 		WARN_ON(mr->descs);
202 	}
203 }
204 
205 /*
206  * This must be called after the mr has been removed from implicit_children.
207  * NOTE: The MR does not necessarily have to be
208  * empty here, parallel page faults could have raced with the free process and
209  * added pages to it.
210  */
211 static void free_implicit_child_mr(struct mlx5_ib_mr *mr, bool need_imr_xlt)
212 {
213 	struct mlx5_ib_mr *imr = mr->parent;
214 	struct ib_umem_odp *odp_imr = to_ib_umem_odp(imr->umem);
215 	struct ib_umem_odp *odp = to_ib_umem_odp(mr->umem);
216 	unsigned long idx = ib_umem_start(odp) >> MLX5_IMR_MTT_SHIFT;
217 
218 	mlx5r_deref_wait_odp_mkey(&mr->mmkey);
219 
220 	if (need_imr_xlt) {
221 		mutex_lock(&odp_imr->umem_mutex);
222 		mlx5_ib_update_xlt(mr->parent, idx, 1, 0,
223 				   MLX5_IB_UPD_XLT_INDIRECT |
224 				   MLX5_IB_UPD_XLT_ATOMIC);
225 		mutex_unlock(&odp_imr->umem_mutex);
226 	}
227 
228 	dma_fence_odp_mr(mr);
229 
230 	mr->parent = NULL;
231 	mlx5_mr_cache_free(mr_to_mdev(mr), mr);
232 	ib_umem_odp_release(odp);
233 }
234 
235 static void free_implicit_child_mr_work(struct work_struct *work)
236 {
237 	struct mlx5_ib_mr *mr =
238 		container_of(work, struct mlx5_ib_mr, odp_destroy.work);
239 	struct mlx5_ib_mr *imr = mr->parent;
240 
241 	free_implicit_child_mr(mr, true);
242 	mlx5r_deref_odp_mkey(&imr->mmkey);
243 }
244 
245 static void destroy_unused_implicit_child_mr(struct mlx5_ib_mr *mr)
246 {
247 	struct ib_umem_odp *odp = to_ib_umem_odp(mr->umem);
248 	unsigned long idx = ib_umem_start(odp) >> MLX5_IMR_MTT_SHIFT;
249 	struct mlx5_ib_mr *imr = mr->parent;
250 
251 	if (!refcount_inc_not_zero(&imr->mmkey.usecount))
252 		return;
253 
254 	xa_erase(&imr->implicit_children, idx);
255 
256 	/* Freeing a MR is a sleeping operation, so bounce to a work queue */
257 	INIT_WORK(&mr->odp_destroy.work, free_implicit_child_mr_work);
258 	queue_work(system_unbound_wq, &mr->odp_destroy.work);
259 }
260 
261 static bool mlx5_ib_invalidate_range(struct mmu_interval_notifier *mni,
262 				     const struct mmu_notifier_range *range,
263 				     unsigned long cur_seq)
264 {
265 	struct ib_umem_odp *umem_odp =
266 		container_of(mni, struct ib_umem_odp, notifier);
267 	struct mlx5_ib_mr *mr;
268 	const u64 umr_block_mask = (MLX5_UMR_MTT_ALIGNMENT /
269 				    sizeof(struct mlx5_mtt)) - 1;
270 	u64 idx = 0, blk_start_idx = 0;
271 	u64 invalidations = 0;
272 	unsigned long start;
273 	unsigned long end;
274 	int in_block = 0;
275 	u64 addr;
276 
277 	if (!mmu_notifier_range_blockable(range))
278 		return false;
279 
280 	mutex_lock(&umem_odp->umem_mutex);
281 	mmu_interval_set_seq(mni, cur_seq);
282 	/*
283 	 * If npages is zero then umem_odp->private may not be setup yet. This
284 	 * does not complete until after the first page is mapped for DMA.
285 	 */
286 	if (!umem_odp->npages)
287 		goto out;
288 	mr = umem_odp->private;
289 
290 	start = max_t(u64, ib_umem_start(umem_odp), range->start);
291 	end = min_t(u64, ib_umem_end(umem_odp), range->end);
292 
293 	/*
294 	 * Iteration one - zap the HW's MTTs. The notifiers_count ensures that
295 	 * while we are doing the invalidation, no page fault will attempt to
296 	 * overwrite the same MTTs.  Concurent invalidations might race us,
297 	 * but they will write 0s as well, so no difference in the end result.
298 	 */
299 	for (addr = start; addr < end; addr += BIT(umem_odp->page_shift)) {
300 		idx = (addr - ib_umem_start(umem_odp)) >> umem_odp->page_shift;
301 		/*
302 		 * Strive to write the MTTs in chunks, but avoid overwriting
303 		 * non-existing MTTs. The huristic here can be improved to
304 		 * estimate the cost of another UMR vs. the cost of bigger
305 		 * UMR.
306 		 */
307 		if (umem_odp->dma_list[idx] &
308 		    (ODP_READ_ALLOWED_BIT | ODP_WRITE_ALLOWED_BIT)) {
309 			if (!in_block) {
310 				blk_start_idx = idx;
311 				in_block = 1;
312 			}
313 
314 			/* Count page invalidations */
315 			invalidations += idx - blk_start_idx + 1;
316 		} else {
317 			u64 umr_offset = idx & umr_block_mask;
318 
319 			if (in_block && umr_offset == 0) {
320 				mlx5_ib_update_xlt(mr, blk_start_idx,
321 						   idx - blk_start_idx, 0,
322 						   MLX5_IB_UPD_XLT_ZAP |
323 						   MLX5_IB_UPD_XLT_ATOMIC);
324 				in_block = 0;
325 			}
326 		}
327 	}
328 	if (in_block)
329 		mlx5_ib_update_xlt(mr, blk_start_idx,
330 				   idx - blk_start_idx + 1, 0,
331 				   MLX5_IB_UPD_XLT_ZAP |
332 				   MLX5_IB_UPD_XLT_ATOMIC);
333 
334 	mlx5_update_odp_stats(mr, invalidations, invalidations);
335 
336 	/*
337 	 * We are now sure that the device will not access the
338 	 * memory. We can safely unmap it, and mark it as dirty if
339 	 * needed.
340 	 */
341 
342 	ib_umem_odp_unmap_dma_pages(umem_odp, start, end);
343 
344 	if (unlikely(!umem_odp->npages && mr->parent))
345 		destroy_unused_implicit_child_mr(mr);
346 out:
347 	mutex_unlock(&umem_odp->umem_mutex);
348 	return true;
349 }
350 
351 const struct mmu_interval_notifier_ops mlx5_mn_ops = {
352 	.invalidate = mlx5_ib_invalidate_range,
353 };
354 
355 void mlx5_ib_internal_fill_odp_caps(struct mlx5_ib_dev *dev)
356 {
357 	struct ib_odp_caps *caps = &dev->odp_caps;
358 
359 	memset(caps, 0, sizeof(*caps));
360 
361 	if (!MLX5_CAP_GEN(dev->mdev, pg) ||
362 	    !mlx5_ib_can_load_pas_with_umr(dev, 0))
363 		return;
364 
365 	caps->general_caps = IB_ODP_SUPPORT;
366 
367 	if (MLX5_CAP_GEN(dev->mdev, umr_extended_translation_offset))
368 		dev->odp_max_size = U64_MAX;
369 	else
370 		dev->odp_max_size = BIT_ULL(MLX5_MAX_UMR_SHIFT + PAGE_SHIFT);
371 
372 	if (MLX5_CAP_ODP(dev->mdev, ud_odp_caps.send))
373 		caps->per_transport_caps.ud_odp_caps |= IB_ODP_SUPPORT_SEND;
374 
375 	if (MLX5_CAP_ODP(dev->mdev, ud_odp_caps.srq_receive))
376 		caps->per_transport_caps.ud_odp_caps |= IB_ODP_SUPPORT_SRQ_RECV;
377 
378 	if (MLX5_CAP_ODP(dev->mdev, rc_odp_caps.send))
379 		caps->per_transport_caps.rc_odp_caps |= IB_ODP_SUPPORT_SEND;
380 
381 	if (MLX5_CAP_ODP(dev->mdev, rc_odp_caps.receive))
382 		caps->per_transport_caps.rc_odp_caps |= IB_ODP_SUPPORT_RECV;
383 
384 	if (MLX5_CAP_ODP(dev->mdev, rc_odp_caps.write))
385 		caps->per_transport_caps.rc_odp_caps |= IB_ODP_SUPPORT_WRITE;
386 
387 	if (MLX5_CAP_ODP(dev->mdev, rc_odp_caps.read))
388 		caps->per_transport_caps.rc_odp_caps |= IB_ODP_SUPPORT_READ;
389 
390 	if (MLX5_CAP_ODP(dev->mdev, rc_odp_caps.atomic))
391 		caps->per_transport_caps.rc_odp_caps |= IB_ODP_SUPPORT_ATOMIC;
392 
393 	if (MLX5_CAP_ODP(dev->mdev, rc_odp_caps.srq_receive))
394 		caps->per_transport_caps.rc_odp_caps |= IB_ODP_SUPPORT_SRQ_RECV;
395 
396 	if (MLX5_CAP_ODP(dev->mdev, xrc_odp_caps.send))
397 		caps->per_transport_caps.xrc_odp_caps |= IB_ODP_SUPPORT_SEND;
398 
399 	if (MLX5_CAP_ODP(dev->mdev, xrc_odp_caps.receive))
400 		caps->per_transport_caps.xrc_odp_caps |= IB_ODP_SUPPORT_RECV;
401 
402 	if (MLX5_CAP_ODP(dev->mdev, xrc_odp_caps.write))
403 		caps->per_transport_caps.xrc_odp_caps |= IB_ODP_SUPPORT_WRITE;
404 
405 	if (MLX5_CAP_ODP(dev->mdev, xrc_odp_caps.read))
406 		caps->per_transport_caps.xrc_odp_caps |= IB_ODP_SUPPORT_READ;
407 
408 	if (MLX5_CAP_ODP(dev->mdev, xrc_odp_caps.atomic))
409 		caps->per_transport_caps.xrc_odp_caps |= IB_ODP_SUPPORT_ATOMIC;
410 
411 	if (MLX5_CAP_ODP(dev->mdev, xrc_odp_caps.srq_receive))
412 		caps->per_transport_caps.xrc_odp_caps |= IB_ODP_SUPPORT_SRQ_RECV;
413 
414 	if (MLX5_CAP_GEN(dev->mdev, fixed_buffer_size) &&
415 	    MLX5_CAP_GEN(dev->mdev, null_mkey) &&
416 	    MLX5_CAP_GEN(dev->mdev, umr_extended_translation_offset) &&
417 	    !MLX5_CAP_GEN(dev->mdev, umr_indirect_mkey_disabled))
418 		caps->general_caps |= IB_ODP_SUPPORT_IMPLICIT;
419 }
420 
421 static void mlx5_ib_page_fault_resume(struct mlx5_ib_dev *dev,
422 				      struct mlx5_pagefault *pfault,
423 				      int error)
424 {
425 	int wq_num = pfault->event_subtype == MLX5_PFAULT_SUBTYPE_WQE ?
426 		     pfault->wqe.wq_num : pfault->token;
427 	u32 in[MLX5_ST_SZ_DW(page_fault_resume_in)] = {};
428 	int err;
429 
430 	MLX5_SET(page_fault_resume_in, in, opcode, MLX5_CMD_OP_PAGE_FAULT_RESUME);
431 	MLX5_SET(page_fault_resume_in, in, page_fault_type, pfault->type);
432 	MLX5_SET(page_fault_resume_in, in, token, pfault->token);
433 	MLX5_SET(page_fault_resume_in, in, wq_number, wq_num);
434 	MLX5_SET(page_fault_resume_in, in, error, !!error);
435 
436 	err = mlx5_cmd_exec_in(dev->mdev, page_fault_resume, in);
437 	if (err)
438 		mlx5_ib_err(dev, "Failed to resolve the page fault on WQ 0x%x err %d\n",
439 			    wq_num, err);
440 }
441 
442 static struct mlx5_ib_mr *implicit_get_child_mr(struct mlx5_ib_mr *imr,
443 						unsigned long idx)
444 {
445 	struct ib_umem_odp *odp;
446 	struct mlx5_ib_mr *mr;
447 	struct mlx5_ib_mr *ret;
448 	int err;
449 
450 	odp = ib_umem_odp_alloc_child(to_ib_umem_odp(imr->umem),
451 				      idx * MLX5_IMR_MTT_SIZE,
452 				      MLX5_IMR_MTT_SIZE, &mlx5_mn_ops);
453 	if (IS_ERR(odp))
454 		return ERR_CAST(odp);
455 
456 	ret = mr = mlx5_mr_cache_alloc(
457 		mr_to_mdev(imr), MLX5_IMR_MTT_CACHE_ENTRY, imr->access_flags);
458 	if (IS_ERR(mr))
459 		goto out_umem;
460 
461 	mr->ibmr.pd = imr->ibmr.pd;
462 	mr->ibmr.device = &mr_to_mdev(imr)->ib_dev;
463 	mr->umem = &odp->umem;
464 	mr->ibmr.lkey = mr->mmkey.key;
465 	mr->ibmr.rkey = mr->mmkey.key;
466 	mr->mmkey.iova = idx * MLX5_IMR_MTT_SIZE;
467 	mr->parent = imr;
468 	odp->private = mr;
469 
470 	/*
471 	 * First refcount is owned by the xarray and second refconut
472 	 * is returned to the caller.
473 	 */
474 	refcount_set(&mr->mmkey.usecount, 2);
475 
476 	err = mlx5_ib_update_xlt(mr, 0,
477 				 MLX5_IMR_MTT_ENTRIES,
478 				 PAGE_SHIFT,
479 				 MLX5_IB_UPD_XLT_ZAP |
480 				 MLX5_IB_UPD_XLT_ENABLE);
481 	if (err) {
482 		ret = ERR_PTR(err);
483 		goto out_mr;
484 	}
485 
486 	xa_lock(&imr->implicit_children);
487 	ret = __xa_cmpxchg(&imr->implicit_children, idx, NULL, mr,
488 			   GFP_KERNEL);
489 	if (unlikely(ret)) {
490 		if (xa_is_err(ret)) {
491 			ret = ERR_PTR(xa_err(ret));
492 			goto out_lock;
493 		}
494 		/*
495 		 * Another thread beat us to creating the child mr, use
496 		 * theirs.
497 		 */
498 		refcount_inc(&ret->mmkey.usecount);
499 		goto out_lock;
500 	}
501 	xa_unlock(&imr->implicit_children);
502 
503 	mlx5_ib_dbg(mr_to_mdev(imr), "key %x mr %p\n", mr->mmkey.key, mr);
504 	return mr;
505 
506 out_lock:
507 	xa_unlock(&imr->implicit_children);
508 out_mr:
509 	mlx5_mr_cache_free(mr_to_mdev(imr), mr);
510 out_umem:
511 	ib_umem_odp_release(odp);
512 	return ret;
513 }
514 
515 struct mlx5_ib_mr *mlx5_ib_alloc_implicit_mr(struct mlx5_ib_pd *pd,
516 					     struct ib_udata *udata,
517 					     int access_flags)
518 {
519 	struct mlx5_ib_dev *dev = to_mdev(pd->ibpd.device);
520 	struct ib_umem_odp *umem_odp;
521 	struct mlx5_ib_mr *imr;
522 	int err;
523 
524 	if (!mlx5_ib_can_load_pas_with_umr(dev,
525 					   MLX5_IMR_MTT_ENTRIES * PAGE_SIZE))
526 		return ERR_PTR(-EOPNOTSUPP);
527 
528 	umem_odp = ib_umem_odp_alloc_implicit(&dev->ib_dev, access_flags);
529 	if (IS_ERR(umem_odp))
530 		return ERR_CAST(umem_odp);
531 
532 	imr = mlx5_mr_cache_alloc(dev, MLX5_IMR_KSM_CACHE_ENTRY, access_flags);
533 	if (IS_ERR(imr)) {
534 		err = PTR_ERR(imr);
535 		goto out_umem;
536 	}
537 
538 	imr->ibmr.pd = &pd->ibpd;
539 	imr->mmkey.iova = 0;
540 	imr->umem = &umem_odp->umem;
541 	imr->ibmr.lkey = imr->mmkey.key;
542 	imr->ibmr.rkey = imr->mmkey.key;
543 	imr->ibmr.device = &dev->ib_dev;
544 	imr->umem = &umem_odp->umem;
545 	imr->is_odp_implicit = true;
546 	xa_init(&imr->implicit_children);
547 
548 	err = mlx5_ib_update_xlt(imr, 0,
549 				 mlx5_imr_ksm_entries,
550 				 MLX5_KSM_PAGE_SHIFT,
551 				 MLX5_IB_UPD_XLT_INDIRECT |
552 				 MLX5_IB_UPD_XLT_ZAP |
553 				 MLX5_IB_UPD_XLT_ENABLE);
554 	if (err)
555 		goto out_mr;
556 
557 	err = mlx5r_store_odp_mkey(dev, &imr->mmkey);
558 	if (err)
559 		goto out_mr;
560 
561 	mlx5_ib_dbg(dev, "key %x mr %p\n", imr->mmkey.key, imr);
562 	return imr;
563 out_mr:
564 	mlx5_ib_err(dev, "Failed to register MKEY %d\n", err);
565 	mlx5_mr_cache_free(dev, imr);
566 out_umem:
567 	ib_umem_odp_release(umem_odp);
568 	return ERR_PTR(err);
569 }
570 
571 void mlx5_ib_free_implicit_mr(struct mlx5_ib_mr *imr)
572 {
573 	struct ib_umem_odp *odp_imr = to_ib_umem_odp(imr->umem);
574 	struct mlx5_ib_dev *dev = mr_to_mdev(imr);
575 	struct mlx5_ib_mr *mtt;
576 	unsigned long idx;
577 
578 	xa_erase(&dev->odp_mkeys, mlx5_base_mkey(imr->mmkey.key));
579 	/*
580 	 * All work on the prefetch list must be completed, xa_erase() prevented
581 	 * new work from being created.
582 	 */
583 	mlx5r_deref_wait_odp_mkey(&imr->mmkey);
584 	/*
585 	 * At this point it is forbidden for any other thread to enter
586 	 * pagefault_mr() on this imr. It is already forbidden to call
587 	 * pagefault_mr() on an implicit child. Due to this additions to
588 	 * implicit_children are prevented.
589 	 * In addition, any new call to destroy_unused_implicit_child_mr()
590 	 * may return immediately.
591 	 */
592 
593 	/*
594 	 * Fence the imr before we destroy the children. This allows us to
595 	 * skip updating the XLT of the imr during destroy of the child mkey
596 	 * the imr points to.
597 	 */
598 	mlx5_mr_cache_invalidate(imr);
599 
600 	xa_for_each(&imr->implicit_children, idx, mtt) {
601 		xa_erase(&imr->implicit_children, idx);
602 		free_implicit_child_mr(mtt, false);
603 	}
604 
605 	mlx5_mr_cache_free(dev, imr);
606 	ib_umem_odp_release(odp_imr);
607 }
608 
609 /**
610  * mlx5_ib_fence_odp_mr - Stop all access to the ODP MR
611  * @mr: to fence
612  *
613  * On return no parallel threads will be touching this MR and no DMA will be
614  * active.
615  */
616 void mlx5_ib_fence_odp_mr(struct mlx5_ib_mr *mr)
617 {
618 	/* Prevent new page faults and prefetch requests from succeeding */
619 	xa_erase(&mr_to_mdev(mr)->odp_mkeys, mlx5_base_mkey(mr->mmkey.key));
620 
621 	/* Wait for all running page-fault handlers to finish. */
622 	mlx5r_deref_wait_odp_mkey(&mr->mmkey);
623 
624 	dma_fence_odp_mr(mr);
625 }
626 
627 /**
628  * mlx5_ib_fence_dmabuf_mr - Stop all access to the dmabuf MR
629  * @mr: to fence
630  *
631  * On return no parallel threads will be touching this MR and no DMA will be
632  * active.
633  */
634 void mlx5_ib_fence_dmabuf_mr(struct mlx5_ib_mr *mr)
635 {
636 	struct ib_umem_dmabuf *umem_dmabuf = to_ib_umem_dmabuf(mr->umem);
637 
638 	/* Prevent new page faults and prefetch requests from succeeding */
639 	xa_erase(&mr_to_mdev(mr)->odp_mkeys, mlx5_base_mkey(mr->mmkey.key));
640 
641 	mlx5r_deref_wait_odp_mkey(&mr->mmkey);
642 
643 	dma_resv_lock(umem_dmabuf->attach->dmabuf->resv, NULL);
644 	mlx5_mr_cache_invalidate(mr);
645 	umem_dmabuf->private = NULL;
646 	ib_umem_dmabuf_unmap_pages(umem_dmabuf);
647 	dma_resv_unlock(umem_dmabuf->attach->dmabuf->resv);
648 
649 	if (!mr->cache_ent) {
650 		mlx5_core_destroy_mkey(mr_to_mdev(mr)->mdev, &mr->mmkey);
651 		WARN_ON(mr->descs);
652 	}
653 }
654 
655 #define MLX5_PF_FLAGS_DOWNGRADE BIT(1)
656 #define MLX5_PF_FLAGS_SNAPSHOT BIT(2)
657 #define MLX5_PF_FLAGS_ENABLE BIT(3)
658 static int pagefault_real_mr(struct mlx5_ib_mr *mr, struct ib_umem_odp *odp,
659 			     u64 user_va, size_t bcnt, u32 *bytes_mapped,
660 			     u32 flags)
661 {
662 	int page_shift, ret, np;
663 	bool downgrade = flags & MLX5_PF_FLAGS_DOWNGRADE;
664 	u64 access_mask;
665 	u64 start_idx;
666 	bool fault = !(flags & MLX5_PF_FLAGS_SNAPSHOT);
667 	u32 xlt_flags = MLX5_IB_UPD_XLT_ATOMIC;
668 
669 	if (flags & MLX5_PF_FLAGS_ENABLE)
670 		xlt_flags |= MLX5_IB_UPD_XLT_ENABLE;
671 
672 	page_shift = odp->page_shift;
673 	start_idx = (user_va - ib_umem_start(odp)) >> page_shift;
674 	access_mask = ODP_READ_ALLOWED_BIT;
675 
676 	if (odp->umem.writable && !downgrade)
677 		access_mask |= ODP_WRITE_ALLOWED_BIT;
678 
679 	np = ib_umem_odp_map_dma_and_lock(odp, user_va, bcnt, access_mask, fault);
680 	if (np < 0)
681 		return np;
682 
683 	/*
684 	 * No need to check whether the MTTs really belong to this MR, since
685 	 * ib_umem_odp_map_dma_and_lock already checks this.
686 	 */
687 	ret = mlx5_ib_update_xlt(mr, start_idx, np, page_shift, xlt_flags);
688 	mutex_unlock(&odp->umem_mutex);
689 
690 	if (ret < 0) {
691 		if (ret != -EAGAIN)
692 			mlx5_ib_err(mr_to_mdev(mr),
693 				    "Failed to update mkey page tables\n");
694 		goto out;
695 	}
696 
697 	if (bytes_mapped) {
698 		u32 new_mappings = (np << page_shift) -
699 			(user_va - round_down(user_va, 1 << page_shift));
700 
701 		*bytes_mapped += min_t(u32, new_mappings, bcnt);
702 	}
703 
704 	return np << (page_shift - PAGE_SHIFT);
705 
706 out:
707 	return ret;
708 }
709 
710 static int pagefault_implicit_mr(struct mlx5_ib_mr *imr,
711 				 struct ib_umem_odp *odp_imr, u64 user_va,
712 				 size_t bcnt, u32 *bytes_mapped, u32 flags)
713 {
714 	unsigned long end_idx = (user_va + bcnt - 1) >> MLX5_IMR_MTT_SHIFT;
715 	unsigned long upd_start_idx = end_idx + 1;
716 	unsigned long upd_len = 0;
717 	unsigned long npages = 0;
718 	int err;
719 	int ret;
720 
721 	if (unlikely(user_va >= mlx5_imr_ksm_entries * MLX5_IMR_MTT_SIZE ||
722 		     mlx5_imr_ksm_entries * MLX5_IMR_MTT_SIZE - user_va < bcnt))
723 		return -EFAULT;
724 
725 	/* Fault each child mr that intersects with our interval. */
726 	while (bcnt) {
727 		unsigned long idx = user_va >> MLX5_IMR_MTT_SHIFT;
728 		struct ib_umem_odp *umem_odp;
729 		struct mlx5_ib_mr *mtt;
730 		u64 len;
731 
732 		xa_lock(&imr->implicit_children);
733 		mtt = xa_load(&imr->implicit_children, idx);
734 		if (unlikely(!mtt)) {
735 			xa_unlock(&imr->implicit_children);
736 			mtt = implicit_get_child_mr(imr, idx);
737 			if (IS_ERR(mtt)) {
738 				ret = PTR_ERR(mtt);
739 				goto out;
740 			}
741 			upd_start_idx = min(upd_start_idx, idx);
742 			upd_len = idx - upd_start_idx + 1;
743 		} else {
744 			refcount_inc(&mtt->mmkey.usecount);
745 			xa_unlock(&imr->implicit_children);
746 		}
747 
748 		umem_odp = to_ib_umem_odp(mtt->umem);
749 		len = min_t(u64, user_va + bcnt, ib_umem_end(umem_odp)) -
750 		      user_va;
751 
752 		ret = pagefault_real_mr(mtt, umem_odp, user_va, len,
753 					bytes_mapped, flags);
754 
755 		mlx5r_deref_odp_mkey(&mtt->mmkey);
756 
757 		if (ret < 0)
758 			goto out;
759 		user_va += len;
760 		bcnt -= len;
761 		npages += ret;
762 	}
763 
764 	ret = npages;
765 
766 	/*
767 	 * Any time the implicit_children are changed we must perform an
768 	 * update of the xlt before exiting to ensure the HW and the
769 	 * implicit_children remains synchronized.
770 	 */
771 out:
772 	if (likely(!upd_len))
773 		return ret;
774 
775 	/*
776 	 * Notice this is not strictly ordered right, the KSM is updated after
777 	 * the implicit_children is updated, so a parallel page fault could
778 	 * see a MR that is not yet visible in the KSM.  This is similar to a
779 	 * parallel page fault seeing a MR that is being concurrently removed
780 	 * from the KSM. Both of these improbable situations are resolved
781 	 * safely by resuming the HW and then taking another page fault. The
782 	 * next pagefault handler will see the new information.
783 	 */
784 	mutex_lock(&odp_imr->umem_mutex);
785 	err = mlx5_ib_update_xlt(imr, upd_start_idx, upd_len, 0,
786 				 MLX5_IB_UPD_XLT_INDIRECT |
787 					 MLX5_IB_UPD_XLT_ATOMIC);
788 	mutex_unlock(&odp_imr->umem_mutex);
789 	if (err) {
790 		mlx5_ib_err(mr_to_mdev(imr), "Failed to update PAS\n");
791 		return err;
792 	}
793 	return ret;
794 }
795 
796 static int pagefault_dmabuf_mr(struct mlx5_ib_mr *mr, size_t bcnt,
797 			       u32 *bytes_mapped, u32 flags)
798 {
799 	struct ib_umem_dmabuf *umem_dmabuf = to_ib_umem_dmabuf(mr->umem);
800 	u32 xlt_flags = 0;
801 	int err;
802 	unsigned int page_size;
803 
804 	if (flags & MLX5_PF_FLAGS_ENABLE)
805 		xlt_flags |= MLX5_IB_UPD_XLT_ENABLE;
806 
807 	dma_resv_lock(umem_dmabuf->attach->dmabuf->resv, NULL);
808 	err = ib_umem_dmabuf_map_pages(umem_dmabuf);
809 	if (err) {
810 		dma_resv_unlock(umem_dmabuf->attach->dmabuf->resv);
811 		return err;
812 	}
813 
814 	page_size = mlx5_umem_find_best_pgsz(&umem_dmabuf->umem, mkc,
815 					     log_page_size, 0,
816 					     umem_dmabuf->umem.iova);
817 	if (unlikely(page_size < PAGE_SIZE)) {
818 		ib_umem_dmabuf_unmap_pages(umem_dmabuf);
819 		err = -EINVAL;
820 	} else {
821 		err = mlx5_ib_update_mr_pas(mr, xlt_flags);
822 	}
823 	dma_resv_unlock(umem_dmabuf->attach->dmabuf->resv);
824 
825 	if (err)
826 		return err;
827 
828 	if (bytes_mapped)
829 		*bytes_mapped += bcnt;
830 
831 	return ib_umem_num_pages(mr->umem);
832 }
833 
834 /*
835  * Returns:
836  *  -EFAULT: The io_virt->bcnt is not within the MR, it covers pages that are
837  *           not accessible, or the MR is no longer valid.
838  *  -EAGAIN/-ENOMEM: The operation should be retried
839  *
840  *  -EINVAL/others: General internal malfunction
841  *  >0: Number of pages mapped
842  */
843 static int pagefault_mr(struct mlx5_ib_mr *mr, u64 io_virt, size_t bcnt,
844 			u32 *bytes_mapped, u32 flags)
845 {
846 	struct ib_umem_odp *odp = to_ib_umem_odp(mr->umem);
847 
848 	if (unlikely(io_virt < mr->mmkey.iova))
849 		return -EFAULT;
850 
851 	if (mr->umem->is_dmabuf)
852 		return pagefault_dmabuf_mr(mr, bcnt, bytes_mapped, flags);
853 
854 	if (!odp->is_implicit_odp) {
855 		u64 user_va;
856 
857 		if (check_add_overflow(io_virt - mr->mmkey.iova,
858 				       (u64)odp->umem.address, &user_va))
859 			return -EFAULT;
860 		if (unlikely(user_va >= ib_umem_end(odp) ||
861 			     ib_umem_end(odp) - user_va < bcnt))
862 			return -EFAULT;
863 		return pagefault_real_mr(mr, odp, user_va, bcnt, bytes_mapped,
864 					 flags);
865 	}
866 	return pagefault_implicit_mr(mr, odp, io_virt, bcnt, bytes_mapped,
867 				     flags);
868 }
869 
870 int mlx5_ib_init_odp_mr(struct mlx5_ib_mr *mr)
871 {
872 	int ret;
873 
874 	ret = pagefault_real_mr(mr, to_ib_umem_odp(mr->umem), mr->umem->address,
875 				mr->umem->length, NULL,
876 				MLX5_PF_FLAGS_SNAPSHOT | MLX5_PF_FLAGS_ENABLE);
877 	return ret >= 0 ? 0 : ret;
878 }
879 
880 int mlx5_ib_init_dmabuf_mr(struct mlx5_ib_mr *mr)
881 {
882 	int ret;
883 
884 	ret = pagefault_dmabuf_mr(mr, mr->umem->length, NULL,
885 				  MLX5_PF_FLAGS_ENABLE);
886 
887 	return ret >= 0 ? 0 : ret;
888 }
889 
890 struct pf_frame {
891 	struct pf_frame *next;
892 	u32 key;
893 	u64 io_virt;
894 	size_t bcnt;
895 	int depth;
896 };
897 
898 static bool mkey_is_eq(struct mlx5_core_mkey *mmkey, u32 key)
899 {
900 	if (!mmkey)
901 		return false;
902 	if (mmkey->type == MLX5_MKEY_MW)
903 		return mlx5_base_mkey(mmkey->key) == mlx5_base_mkey(key);
904 	return mmkey->key == key;
905 }
906 
907 static int get_indirect_num_descs(struct mlx5_core_mkey *mmkey)
908 {
909 	struct mlx5_ib_mw *mw;
910 	struct mlx5_ib_devx_mr *devx_mr;
911 
912 	if (mmkey->type == MLX5_MKEY_MW) {
913 		mw = container_of(mmkey, struct mlx5_ib_mw, mmkey);
914 		return mw->ndescs;
915 	}
916 
917 	devx_mr = container_of(mmkey, struct mlx5_ib_devx_mr,
918 			       mmkey);
919 	return devx_mr->ndescs;
920 }
921 
922 /*
923  * Handle a single data segment in a page-fault WQE or RDMA region.
924  *
925  * Returns number of OS pages retrieved on success. The caller may continue to
926  * the next data segment.
927  * Can return the following error codes:
928  * -EAGAIN to designate a temporary error. The caller will abort handling the
929  *  page fault and resolve it.
930  * -EFAULT when there's an error mapping the requested pages. The caller will
931  *  abort the page fault handling.
932  */
933 static int pagefault_single_data_segment(struct mlx5_ib_dev *dev,
934 					 struct ib_pd *pd, u32 key,
935 					 u64 io_virt, size_t bcnt,
936 					 u32 *bytes_committed,
937 					 u32 *bytes_mapped)
938 {
939 	int npages = 0, ret, i, outlen, cur_outlen = 0, depth = 0;
940 	struct pf_frame *head = NULL, *frame;
941 	struct mlx5_core_mkey *mmkey;
942 	struct mlx5_ib_mr *mr;
943 	struct mlx5_klm *pklm;
944 	u32 *out = NULL;
945 	size_t offset;
946 	int ndescs;
947 
948 	io_virt += *bytes_committed;
949 	bcnt -= *bytes_committed;
950 
951 next_mr:
952 	xa_lock(&dev->odp_mkeys);
953 	mmkey = xa_load(&dev->odp_mkeys, mlx5_base_mkey(key));
954 	if (!mmkey) {
955 		xa_unlock(&dev->odp_mkeys);
956 		mlx5_ib_dbg(
957 			dev,
958 			"skipping non ODP MR (lkey=0x%06x) in page fault handler.\n",
959 			key);
960 		if (bytes_mapped)
961 			*bytes_mapped += bcnt;
962 		/*
963 		 * The user could specify a SGL with multiple lkeys and only
964 		 * some of them are ODP. Treat the non-ODP ones as fully
965 		 * faulted.
966 		 */
967 		ret = 0;
968 		goto end;
969 	}
970 	refcount_inc(&mmkey->usecount);
971 	xa_unlock(&dev->odp_mkeys);
972 
973 	if (!mkey_is_eq(mmkey, key)) {
974 		mlx5_ib_dbg(dev, "failed to find mkey %x\n", key);
975 		ret = -EFAULT;
976 		goto end;
977 	}
978 
979 	switch (mmkey->type) {
980 	case MLX5_MKEY_MR:
981 		mr = container_of(mmkey, struct mlx5_ib_mr, mmkey);
982 
983 		ret = pagefault_mr(mr, io_virt, bcnt, bytes_mapped, 0);
984 		if (ret < 0)
985 			goto end;
986 
987 		mlx5_update_odp_stats(mr, faults, ret);
988 
989 		npages += ret;
990 		ret = 0;
991 		break;
992 
993 	case MLX5_MKEY_MW:
994 	case MLX5_MKEY_INDIRECT_DEVX:
995 		ndescs = get_indirect_num_descs(mmkey);
996 
997 		if (depth >= MLX5_CAP_GEN(dev->mdev, max_indirection)) {
998 			mlx5_ib_dbg(dev, "indirection level exceeded\n");
999 			ret = -EFAULT;
1000 			goto end;
1001 		}
1002 
1003 		outlen = MLX5_ST_SZ_BYTES(query_mkey_out) +
1004 			sizeof(*pklm) * (ndescs - 2);
1005 
1006 		if (outlen > cur_outlen) {
1007 			kfree(out);
1008 			out = kzalloc(outlen, GFP_KERNEL);
1009 			if (!out) {
1010 				ret = -ENOMEM;
1011 				goto end;
1012 			}
1013 			cur_outlen = outlen;
1014 		}
1015 
1016 		pklm = (struct mlx5_klm *)MLX5_ADDR_OF(query_mkey_out, out,
1017 						       bsf0_klm0_pas_mtt0_1);
1018 
1019 		ret = mlx5_core_query_mkey(dev->mdev, mmkey, out, outlen);
1020 		if (ret)
1021 			goto end;
1022 
1023 		offset = io_virt - MLX5_GET64(query_mkey_out, out,
1024 					      memory_key_mkey_entry.start_addr);
1025 
1026 		for (i = 0; bcnt && i < ndescs; i++, pklm++) {
1027 			if (offset >= be32_to_cpu(pklm->bcount)) {
1028 				offset -= be32_to_cpu(pklm->bcount);
1029 				continue;
1030 			}
1031 
1032 			frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1033 			if (!frame) {
1034 				ret = -ENOMEM;
1035 				goto end;
1036 			}
1037 
1038 			frame->key = be32_to_cpu(pklm->key);
1039 			frame->io_virt = be64_to_cpu(pklm->va) + offset;
1040 			frame->bcnt = min_t(size_t, bcnt,
1041 					    be32_to_cpu(pklm->bcount) - offset);
1042 			frame->depth = depth + 1;
1043 			frame->next = head;
1044 			head = frame;
1045 
1046 			bcnt -= frame->bcnt;
1047 			offset = 0;
1048 		}
1049 		break;
1050 
1051 	default:
1052 		mlx5_ib_dbg(dev, "wrong mkey type %d\n", mmkey->type);
1053 		ret = -EFAULT;
1054 		goto end;
1055 	}
1056 
1057 	if (head) {
1058 		frame = head;
1059 		head = frame->next;
1060 
1061 		key = frame->key;
1062 		io_virt = frame->io_virt;
1063 		bcnt = frame->bcnt;
1064 		depth = frame->depth;
1065 		kfree(frame);
1066 
1067 		mlx5r_deref_odp_mkey(mmkey);
1068 		goto next_mr;
1069 	}
1070 
1071 end:
1072 	if (mmkey)
1073 		mlx5r_deref_odp_mkey(mmkey);
1074 	while (head) {
1075 		frame = head;
1076 		head = frame->next;
1077 		kfree(frame);
1078 	}
1079 	kfree(out);
1080 
1081 	*bytes_committed = 0;
1082 	return ret ? ret : npages;
1083 }
1084 
1085 /*
1086  * Parse a series of data segments for page fault handling.
1087  *
1088  * @dev:  Pointer to mlx5 IB device
1089  * @pfault: contains page fault information.
1090  * @wqe: points at the first data segment in the WQE.
1091  * @wqe_end: points after the end of the WQE.
1092  * @bytes_mapped: receives the number of bytes that the function was able to
1093  *                map. This allows the caller to decide intelligently whether
1094  *                enough memory was mapped to resolve the page fault
1095  *                successfully (e.g. enough for the next MTU, or the entire
1096  *                WQE).
1097  * @total_wqe_bytes: receives the total data size of this WQE in bytes (minus
1098  *                   the committed bytes).
1099  * @receive_queue: receive WQE end of sg list
1100  *
1101  * Returns the number of pages loaded if positive, zero for an empty WQE, or a
1102  * negative error code.
1103  */
1104 static int pagefault_data_segments(struct mlx5_ib_dev *dev,
1105 				   struct mlx5_pagefault *pfault,
1106 				   void *wqe,
1107 				   void *wqe_end, u32 *bytes_mapped,
1108 				   u32 *total_wqe_bytes, bool receive_queue)
1109 {
1110 	int ret = 0, npages = 0;
1111 	u64 io_virt;
1112 	u32 key;
1113 	u32 byte_count;
1114 	size_t bcnt;
1115 	int inline_segment;
1116 
1117 	if (bytes_mapped)
1118 		*bytes_mapped = 0;
1119 	if (total_wqe_bytes)
1120 		*total_wqe_bytes = 0;
1121 
1122 	while (wqe < wqe_end) {
1123 		struct mlx5_wqe_data_seg *dseg = wqe;
1124 
1125 		io_virt = be64_to_cpu(dseg->addr);
1126 		key = be32_to_cpu(dseg->lkey);
1127 		byte_count = be32_to_cpu(dseg->byte_count);
1128 		inline_segment = !!(byte_count &  MLX5_INLINE_SEG);
1129 		bcnt	       = byte_count & ~MLX5_INLINE_SEG;
1130 
1131 		if (inline_segment) {
1132 			bcnt = bcnt & MLX5_WQE_INLINE_SEG_BYTE_COUNT_MASK;
1133 			wqe += ALIGN(sizeof(struct mlx5_wqe_inline_seg) + bcnt,
1134 				     16);
1135 		} else {
1136 			wqe += sizeof(*dseg);
1137 		}
1138 
1139 		/* receive WQE end of sg list. */
1140 		if (receive_queue && bcnt == 0 && key == MLX5_INVALID_LKEY &&
1141 		    io_virt == 0)
1142 			break;
1143 
1144 		if (!inline_segment && total_wqe_bytes) {
1145 			*total_wqe_bytes += bcnt - min_t(size_t, bcnt,
1146 					pfault->bytes_committed);
1147 		}
1148 
1149 		/* A zero length data segment designates a length of 2GB. */
1150 		if (bcnt == 0)
1151 			bcnt = 1U << 31;
1152 
1153 		if (inline_segment || bcnt <= pfault->bytes_committed) {
1154 			pfault->bytes_committed -=
1155 				min_t(size_t, bcnt,
1156 				      pfault->bytes_committed);
1157 			continue;
1158 		}
1159 
1160 		ret = pagefault_single_data_segment(dev, NULL, key,
1161 						    io_virt, bcnt,
1162 						    &pfault->bytes_committed,
1163 						    bytes_mapped);
1164 		if (ret < 0)
1165 			break;
1166 		npages += ret;
1167 	}
1168 
1169 	return ret < 0 ? ret : npages;
1170 }
1171 
1172 /*
1173  * Parse initiator WQE. Advances the wqe pointer to point at the
1174  * scatter-gather list, and set wqe_end to the end of the WQE.
1175  */
1176 static int mlx5_ib_mr_initiator_pfault_handler(
1177 	struct mlx5_ib_dev *dev, struct mlx5_pagefault *pfault,
1178 	struct mlx5_ib_qp *qp, void **wqe, void **wqe_end, int wqe_length)
1179 {
1180 	struct mlx5_wqe_ctrl_seg *ctrl = *wqe;
1181 	u16 wqe_index = pfault->wqe.wqe_index;
1182 	struct mlx5_base_av *av;
1183 	unsigned ds, opcode;
1184 	u32 qpn = qp->trans_qp.base.mqp.qpn;
1185 
1186 	ds = be32_to_cpu(ctrl->qpn_ds) & MLX5_WQE_CTRL_DS_MASK;
1187 	if (ds * MLX5_WQE_DS_UNITS > wqe_length) {
1188 		mlx5_ib_err(dev, "Unable to read the complete WQE. ds = 0x%x, ret = 0x%x\n",
1189 			    ds, wqe_length);
1190 		return -EFAULT;
1191 	}
1192 
1193 	if (ds == 0) {
1194 		mlx5_ib_err(dev, "Got WQE with zero DS. wqe_index=%x, qpn=%x\n",
1195 			    wqe_index, qpn);
1196 		return -EFAULT;
1197 	}
1198 
1199 	*wqe_end = *wqe + ds * MLX5_WQE_DS_UNITS;
1200 	*wqe += sizeof(*ctrl);
1201 
1202 	opcode = be32_to_cpu(ctrl->opmod_idx_opcode) &
1203 		 MLX5_WQE_CTRL_OPCODE_MASK;
1204 
1205 	if (qp->ibqp.qp_type == IB_QPT_XRC_INI)
1206 		*wqe += sizeof(struct mlx5_wqe_xrc_seg);
1207 
1208 	if (qp->type == IB_QPT_UD || qp->type == MLX5_IB_QPT_DCI) {
1209 		av = *wqe;
1210 		if (av->dqp_dct & cpu_to_be32(MLX5_EXTENDED_UD_AV))
1211 			*wqe += sizeof(struct mlx5_av);
1212 		else
1213 			*wqe += sizeof(struct mlx5_base_av);
1214 	}
1215 
1216 	switch (opcode) {
1217 	case MLX5_OPCODE_RDMA_WRITE:
1218 	case MLX5_OPCODE_RDMA_WRITE_IMM:
1219 	case MLX5_OPCODE_RDMA_READ:
1220 		*wqe += sizeof(struct mlx5_wqe_raddr_seg);
1221 		break;
1222 	case MLX5_OPCODE_ATOMIC_CS:
1223 	case MLX5_OPCODE_ATOMIC_FA:
1224 		*wqe += sizeof(struct mlx5_wqe_raddr_seg);
1225 		*wqe += sizeof(struct mlx5_wqe_atomic_seg);
1226 		break;
1227 	}
1228 
1229 	return 0;
1230 }
1231 
1232 /*
1233  * Parse responder WQE and set wqe_end to the end of the WQE.
1234  */
1235 static int mlx5_ib_mr_responder_pfault_handler_srq(struct mlx5_ib_dev *dev,
1236 						   struct mlx5_ib_srq *srq,
1237 						   void **wqe, void **wqe_end,
1238 						   int wqe_length)
1239 {
1240 	int wqe_size = 1 << srq->msrq.wqe_shift;
1241 
1242 	if (wqe_size > wqe_length) {
1243 		mlx5_ib_err(dev, "Couldn't read all of the receive WQE's content\n");
1244 		return -EFAULT;
1245 	}
1246 
1247 	*wqe_end = *wqe + wqe_size;
1248 	*wqe += sizeof(struct mlx5_wqe_srq_next_seg);
1249 
1250 	return 0;
1251 }
1252 
1253 static int mlx5_ib_mr_responder_pfault_handler_rq(struct mlx5_ib_dev *dev,
1254 						  struct mlx5_ib_qp *qp,
1255 						  void *wqe, void **wqe_end,
1256 						  int wqe_length)
1257 {
1258 	struct mlx5_ib_wq *wq = &qp->rq;
1259 	int wqe_size = 1 << wq->wqe_shift;
1260 
1261 	if (qp->flags_en & MLX5_QP_FLAG_SIGNATURE) {
1262 		mlx5_ib_err(dev, "ODP fault with WQE signatures is not supported\n");
1263 		return -EFAULT;
1264 	}
1265 
1266 	if (wqe_size > wqe_length) {
1267 		mlx5_ib_err(dev, "Couldn't read all of the receive WQE's content\n");
1268 		return -EFAULT;
1269 	}
1270 
1271 	*wqe_end = wqe + wqe_size;
1272 
1273 	return 0;
1274 }
1275 
1276 static inline struct mlx5_core_rsc_common *odp_get_rsc(struct mlx5_ib_dev *dev,
1277 						       u32 wq_num, int pf_type)
1278 {
1279 	struct mlx5_core_rsc_common *common = NULL;
1280 	struct mlx5_core_srq *srq;
1281 
1282 	switch (pf_type) {
1283 	case MLX5_WQE_PF_TYPE_RMP:
1284 		srq = mlx5_cmd_get_srq(dev, wq_num);
1285 		if (srq)
1286 			common = &srq->common;
1287 		break;
1288 	case MLX5_WQE_PF_TYPE_REQ_SEND_OR_WRITE:
1289 	case MLX5_WQE_PF_TYPE_RESP:
1290 	case MLX5_WQE_PF_TYPE_REQ_READ_OR_ATOMIC:
1291 		common = mlx5_core_res_hold(dev, wq_num, MLX5_RES_QP);
1292 		break;
1293 	default:
1294 		break;
1295 	}
1296 
1297 	return common;
1298 }
1299 
1300 static inline struct mlx5_ib_qp *res_to_qp(struct mlx5_core_rsc_common *res)
1301 {
1302 	struct mlx5_core_qp *mqp = (struct mlx5_core_qp *)res;
1303 
1304 	return to_mibqp(mqp);
1305 }
1306 
1307 static inline struct mlx5_ib_srq *res_to_srq(struct mlx5_core_rsc_common *res)
1308 {
1309 	struct mlx5_core_srq *msrq =
1310 		container_of(res, struct mlx5_core_srq, common);
1311 
1312 	return to_mibsrq(msrq);
1313 }
1314 
1315 static void mlx5_ib_mr_wqe_pfault_handler(struct mlx5_ib_dev *dev,
1316 					  struct mlx5_pagefault *pfault)
1317 {
1318 	bool sq = pfault->type & MLX5_PFAULT_REQUESTOR;
1319 	u16 wqe_index = pfault->wqe.wqe_index;
1320 	void *wqe, *wqe_start = NULL, *wqe_end = NULL;
1321 	u32 bytes_mapped, total_wqe_bytes;
1322 	struct mlx5_core_rsc_common *res;
1323 	int resume_with_error = 1;
1324 	struct mlx5_ib_qp *qp;
1325 	size_t bytes_copied;
1326 	int ret = 0;
1327 
1328 	res = odp_get_rsc(dev, pfault->wqe.wq_num, pfault->type);
1329 	if (!res) {
1330 		mlx5_ib_dbg(dev, "wqe page fault for missing resource %d\n", pfault->wqe.wq_num);
1331 		return;
1332 	}
1333 
1334 	if (res->res != MLX5_RES_QP && res->res != MLX5_RES_SRQ &&
1335 	    res->res != MLX5_RES_XSRQ) {
1336 		mlx5_ib_err(dev, "wqe page fault for unsupported type %d\n",
1337 			    pfault->type);
1338 		goto resolve_page_fault;
1339 	}
1340 
1341 	wqe_start = (void *)__get_free_page(GFP_KERNEL);
1342 	if (!wqe_start) {
1343 		mlx5_ib_err(dev, "Error allocating memory for IO page fault handling.\n");
1344 		goto resolve_page_fault;
1345 	}
1346 
1347 	wqe = wqe_start;
1348 	qp = (res->res == MLX5_RES_QP) ? res_to_qp(res) : NULL;
1349 	if (qp && sq) {
1350 		ret = mlx5_ib_read_wqe_sq(qp, wqe_index, wqe, PAGE_SIZE,
1351 					  &bytes_copied);
1352 		if (ret)
1353 			goto read_user;
1354 		ret = mlx5_ib_mr_initiator_pfault_handler(
1355 			dev, pfault, qp, &wqe, &wqe_end, bytes_copied);
1356 	} else if (qp && !sq) {
1357 		ret = mlx5_ib_read_wqe_rq(qp, wqe_index, wqe, PAGE_SIZE,
1358 					  &bytes_copied);
1359 		if (ret)
1360 			goto read_user;
1361 		ret = mlx5_ib_mr_responder_pfault_handler_rq(
1362 			dev, qp, wqe, &wqe_end, bytes_copied);
1363 	} else if (!qp) {
1364 		struct mlx5_ib_srq *srq = res_to_srq(res);
1365 
1366 		ret = mlx5_ib_read_wqe_srq(srq, wqe_index, wqe, PAGE_SIZE,
1367 					   &bytes_copied);
1368 		if (ret)
1369 			goto read_user;
1370 		ret = mlx5_ib_mr_responder_pfault_handler_srq(
1371 			dev, srq, &wqe, &wqe_end, bytes_copied);
1372 	}
1373 
1374 	if (ret < 0 || wqe >= wqe_end)
1375 		goto resolve_page_fault;
1376 
1377 	ret = pagefault_data_segments(dev, pfault, wqe, wqe_end, &bytes_mapped,
1378 				      &total_wqe_bytes, !sq);
1379 	if (ret == -EAGAIN)
1380 		goto out;
1381 
1382 	if (ret < 0 || total_wqe_bytes > bytes_mapped)
1383 		goto resolve_page_fault;
1384 
1385 out:
1386 	ret = 0;
1387 	resume_with_error = 0;
1388 
1389 read_user:
1390 	if (ret)
1391 		mlx5_ib_err(
1392 			dev,
1393 			"Failed reading a WQE following page fault, error %d, wqe_index %x, qpn %x\n",
1394 			ret, wqe_index, pfault->token);
1395 
1396 resolve_page_fault:
1397 	mlx5_ib_page_fault_resume(dev, pfault, resume_with_error);
1398 	mlx5_ib_dbg(dev, "PAGE FAULT completed. QP 0x%x resume_with_error=%d, type: 0x%x\n",
1399 		    pfault->wqe.wq_num, resume_with_error,
1400 		    pfault->type);
1401 	mlx5_core_res_put(res);
1402 	free_page((unsigned long)wqe_start);
1403 }
1404 
1405 static int pages_in_range(u64 address, u32 length)
1406 {
1407 	return (ALIGN(address + length, PAGE_SIZE) -
1408 		(address & PAGE_MASK)) >> PAGE_SHIFT;
1409 }
1410 
1411 static void mlx5_ib_mr_rdma_pfault_handler(struct mlx5_ib_dev *dev,
1412 					   struct mlx5_pagefault *pfault)
1413 {
1414 	u64 address;
1415 	u32 length;
1416 	u32 prefetch_len = pfault->bytes_committed;
1417 	int prefetch_activated = 0;
1418 	u32 rkey = pfault->rdma.r_key;
1419 	int ret;
1420 
1421 	/* The RDMA responder handler handles the page fault in two parts.
1422 	 * First it brings the necessary pages for the current packet
1423 	 * (and uses the pfault context), and then (after resuming the QP)
1424 	 * prefetches more pages. The second operation cannot use the pfault
1425 	 * context and therefore uses the dummy_pfault context allocated on
1426 	 * the stack */
1427 	pfault->rdma.rdma_va += pfault->bytes_committed;
1428 	pfault->rdma.rdma_op_len -= min(pfault->bytes_committed,
1429 					 pfault->rdma.rdma_op_len);
1430 	pfault->bytes_committed = 0;
1431 
1432 	address = pfault->rdma.rdma_va;
1433 	length  = pfault->rdma.rdma_op_len;
1434 
1435 	/* For some operations, the hardware cannot tell the exact message
1436 	 * length, and in those cases it reports zero. Use prefetch
1437 	 * logic. */
1438 	if (length == 0) {
1439 		prefetch_activated = 1;
1440 		length = pfault->rdma.packet_size;
1441 		prefetch_len = min(MAX_PREFETCH_LEN, prefetch_len);
1442 	}
1443 
1444 	ret = pagefault_single_data_segment(dev, NULL, rkey, address, length,
1445 					    &pfault->bytes_committed, NULL);
1446 	if (ret == -EAGAIN) {
1447 		/* We're racing with an invalidation, don't prefetch */
1448 		prefetch_activated = 0;
1449 	} else if (ret < 0 || pages_in_range(address, length) > ret) {
1450 		mlx5_ib_page_fault_resume(dev, pfault, 1);
1451 		if (ret != -ENOENT)
1452 			mlx5_ib_dbg(dev, "PAGE FAULT error %d. QP 0x%x, type: 0x%x\n",
1453 				    ret, pfault->token, pfault->type);
1454 		return;
1455 	}
1456 
1457 	mlx5_ib_page_fault_resume(dev, pfault, 0);
1458 	mlx5_ib_dbg(dev, "PAGE FAULT completed. QP 0x%x, type: 0x%x, prefetch_activated: %d\n",
1459 		    pfault->token, pfault->type,
1460 		    prefetch_activated);
1461 
1462 	/* At this point, there might be a new pagefault already arriving in
1463 	 * the eq, switch to the dummy pagefault for the rest of the
1464 	 * processing. We're still OK with the objects being alive as the
1465 	 * work-queue is being fenced. */
1466 
1467 	if (prefetch_activated) {
1468 		u32 bytes_committed = 0;
1469 
1470 		ret = pagefault_single_data_segment(dev, NULL, rkey, address,
1471 						    prefetch_len,
1472 						    &bytes_committed, NULL);
1473 		if (ret < 0 && ret != -EAGAIN) {
1474 			mlx5_ib_dbg(dev, "Prefetch failed. ret: %d, QP 0x%x, address: 0x%.16llx, length = 0x%.16x\n",
1475 				    ret, pfault->token, address, prefetch_len);
1476 		}
1477 	}
1478 }
1479 
1480 static void mlx5_ib_pfault(struct mlx5_ib_dev *dev, struct mlx5_pagefault *pfault)
1481 {
1482 	u8 event_subtype = pfault->event_subtype;
1483 
1484 	switch (event_subtype) {
1485 	case MLX5_PFAULT_SUBTYPE_WQE:
1486 		mlx5_ib_mr_wqe_pfault_handler(dev, pfault);
1487 		break;
1488 	case MLX5_PFAULT_SUBTYPE_RDMA:
1489 		mlx5_ib_mr_rdma_pfault_handler(dev, pfault);
1490 		break;
1491 	default:
1492 		mlx5_ib_err(dev, "Invalid page fault event subtype: 0x%x\n",
1493 			    event_subtype);
1494 		mlx5_ib_page_fault_resume(dev, pfault, 1);
1495 	}
1496 }
1497 
1498 static void mlx5_ib_eqe_pf_action(struct work_struct *work)
1499 {
1500 	struct mlx5_pagefault *pfault = container_of(work,
1501 						     struct mlx5_pagefault,
1502 						     work);
1503 	struct mlx5_ib_pf_eq *eq = pfault->eq;
1504 
1505 	mlx5_ib_pfault(eq->dev, pfault);
1506 	mempool_free(pfault, eq->pool);
1507 }
1508 
1509 static void mlx5_ib_eq_pf_process(struct mlx5_ib_pf_eq *eq)
1510 {
1511 	struct mlx5_eqe_page_fault *pf_eqe;
1512 	struct mlx5_pagefault *pfault;
1513 	struct mlx5_eqe *eqe;
1514 	int cc = 0;
1515 
1516 	while ((eqe = mlx5_eq_get_eqe(eq->core, cc))) {
1517 		pfault = mempool_alloc(eq->pool, GFP_ATOMIC);
1518 		if (!pfault) {
1519 			schedule_work(&eq->work);
1520 			break;
1521 		}
1522 
1523 		pf_eqe = &eqe->data.page_fault;
1524 		pfault->event_subtype = eqe->sub_type;
1525 		pfault->bytes_committed = be32_to_cpu(pf_eqe->bytes_committed);
1526 
1527 		mlx5_ib_dbg(eq->dev,
1528 			    "PAGE_FAULT: subtype: 0x%02x, bytes_committed: 0x%06x\n",
1529 			    eqe->sub_type, pfault->bytes_committed);
1530 
1531 		switch (eqe->sub_type) {
1532 		case MLX5_PFAULT_SUBTYPE_RDMA:
1533 			/* RDMA based event */
1534 			pfault->type =
1535 				be32_to_cpu(pf_eqe->rdma.pftype_token) >> 24;
1536 			pfault->token =
1537 				be32_to_cpu(pf_eqe->rdma.pftype_token) &
1538 				MLX5_24BIT_MASK;
1539 			pfault->rdma.r_key =
1540 				be32_to_cpu(pf_eqe->rdma.r_key);
1541 			pfault->rdma.packet_size =
1542 				be16_to_cpu(pf_eqe->rdma.packet_length);
1543 			pfault->rdma.rdma_op_len =
1544 				be32_to_cpu(pf_eqe->rdma.rdma_op_len);
1545 			pfault->rdma.rdma_va =
1546 				be64_to_cpu(pf_eqe->rdma.rdma_va);
1547 			mlx5_ib_dbg(eq->dev,
1548 				    "PAGE_FAULT: type:0x%x, token: 0x%06x, r_key: 0x%08x\n",
1549 				    pfault->type, pfault->token,
1550 				    pfault->rdma.r_key);
1551 			mlx5_ib_dbg(eq->dev,
1552 				    "PAGE_FAULT: rdma_op_len: 0x%08x, rdma_va: 0x%016llx\n",
1553 				    pfault->rdma.rdma_op_len,
1554 				    pfault->rdma.rdma_va);
1555 			break;
1556 
1557 		case MLX5_PFAULT_SUBTYPE_WQE:
1558 			/* WQE based event */
1559 			pfault->type =
1560 				(be32_to_cpu(pf_eqe->wqe.pftype_wq) >> 24) & 0x7;
1561 			pfault->token =
1562 				be32_to_cpu(pf_eqe->wqe.token);
1563 			pfault->wqe.wq_num =
1564 				be32_to_cpu(pf_eqe->wqe.pftype_wq) &
1565 				MLX5_24BIT_MASK;
1566 			pfault->wqe.wqe_index =
1567 				be16_to_cpu(pf_eqe->wqe.wqe_index);
1568 			pfault->wqe.packet_size =
1569 				be16_to_cpu(pf_eqe->wqe.packet_length);
1570 			mlx5_ib_dbg(eq->dev,
1571 				    "PAGE_FAULT: type:0x%x, token: 0x%06x, wq_num: 0x%06x, wqe_index: 0x%04x\n",
1572 				    pfault->type, pfault->token,
1573 				    pfault->wqe.wq_num,
1574 				    pfault->wqe.wqe_index);
1575 			break;
1576 
1577 		default:
1578 			mlx5_ib_warn(eq->dev,
1579 				     "Unsupported page fault event sub-type: 0x%02hhx\n",
1580 				     eqe->sub_type);
1581 			/* Unsupported page faults should still be
1582 			 * resolved by the page fault handler
1583 			 */
1584 		}
1585 
1586 		pfault->eq = eq;
1587 		INIT_WORK(&pfault->work, mlx5_ib_eqe_pf_action);
1588 		queue_work(eq->wq, &pfault->work);
1589 
1590 		cc = mlx5_eq_update_cc(eq->core, ++cc);
1591 	}
1592 
1593 	mlx5_eq_update_ci(eq->core, cc, 1);
1594 }
1595 
1596 static int mlx5_ib_eq_pf_int(struct notifier_block *nb, unsigned long type,
1597 			     void *data)
1598 {
1599 	struct mlx5_ib_pf_eq *eq =
1600 		container_of(nb, struct mlx5_ib_pf_eq, irq_nb);
1601 	unsigned long flags;
1602 
1603 	if (spin_trylock_irqsave(&eq->lock, flags)) {
1604 		mlx5_ib_eq_pf_process(eq);
1605 		spin_unlock_irqrestore(&eq->lock, flags);
1606 	} else {
1607 		schedule_work(&eq->work);
1608 	}
1609 
1610 	return IRQ_HANDLED;
1611 }
1612 
1613 /* mempool_refill() was proposed but unfortunately wasn't accepted
1614  * http://lkml.iu.edu/hypermail/linux/kernel/1512.1/05073.html
1615  * Cheap workaround.
1616  */
1617 static void mempool_refill(mempool_t *pool)
1618 {
1619 	while (pool->curr_nr < pool->min_nr)
1620 		mempool_free(mempool_alloc(pool, GFP_KERNEL), pool);
1621 }
1622 
1623 static void mlx5_ib_eq_pf_action(struct work_struct *work)
1624 {
1625 	struct mlx5_ib_pf_eq *eq =
1626 		container_of(work, struct mlx5_ib_pf_eq, work);
1627 
1628 	mempool_refill(eq->pool);
1629 
1630 	spin_lock_irq(&eq->lock);
1631 	mlx5_ib_eq_pf_process(eq);
1632 	spin_unlock_irq(&eq->lock);
1633 }
1634 
1635 enum {
1636 	MLX5_IB_NUM_PF_EQE	= 0x1000,
1637 	MLX5_IB_NUM_PF_DRAIN	= 64,
1638 };
1639 
1640 static int
1641 mlx5_ib_create_pf_eq(struct mlx5_ib_dev *dev, struct mlx5_ib_pf_eq *eq)
1642 {
1643 	struct mlx5_eq_param param = {};
1644 	int err;
1645 
1646 	INIT_WORK(&eq->work, mlx5_ib_eq_pf_action);
1647 	spin_lock_init(&eq->lock);
1648 	eq->dev = dev;
1649 
1650 	eq->pool = mempool_create_kmalloc_pool(MLX5_IB_NUM_PF_DRAIN,
1651 					       sizeof(struct mlx5_pagefault));
1652 	if (!eq->pool)
1653 		return -ENOMEM;
1654 
1655 	eq->wq = alloc_workqueue("mlx5_ib_page_fault",
1656 				 WQ_HIGHPRI | WQ_UNBOUND | WQ_MEM_RECLAIM,
1657 				 MLX5_NUM_CMD_EQE);
1658 	if (!eq->wq) {
1659 		err = -ENOMEM;
1660 		goto err_mempool;
1661 	}
1662 
1663 	eq->irq_nb.notifier_call = mlx5_ib_eq_pf_int;
1664 	param = (struct mlx5_eq_param) {
1665 		.irq_index = 0,
1666 		.nent = MLX5_IB_NUM_PF_EQE,
1667 	};
1668 	param.mask[0] = 1ull << MLX5_EVENT_TYPE_PAGE_FAULT;
1669 	eq->core = mlx5_eq_create_generic(dev->mdev, &param);
1670 	if (IS_ERR(eq->core)) {
1671 		err = PTR_ERR(eq->core);
1672 		goto err_wq;
1673 	}
1674 	err = mlx5_eq_enable(dev->mdev, eq->core, &eq->irq_nb);
1675 	if (err) {
1676 		mlx5_ib_err(dev, "failed to enable odp EQ %d\n", err);
1677 		goto err_eq;
1678 	}
1679 
1680 	return 0;
1681 err_eq:
1682 	mlx5_eq_destroy_generic(dev->mdev, eq->core);
1683 err_wq:
1684 	destroy_workqueue(eq->wq);
1685 err_mempool:
1686 	mempool_destroy(eq->pool);
1687 	return err;
1688 }
1689 
1690 static int
1691 mlx5_ib_destroy_pf_eq(struct mlx5_ib_dev *dev, struct mlx5_ib_pf_eq *eq)
1692 {
1693 	int err;
1694 
1695 	mlx5_eq_disable(dev->mdev, eq->core, &eq->irq_nb);
1696 	err = mlx5_eq_destroy_generic(dev->mdev, eq->core);
1697 	cancel_work_sync(&eq->work);
1698 	destroy_workqueue(eq->wq);
1699 	mempool_destroy(eq->pool);
1700 
1701 	return err;
1702 }
1703 
1704 void mlx5_odp_init_mr_cache_entry(struct mlx5_cache_ent *ent)
1705 {
1706 	if (!(ent->dev->odp_caps.general_caps & IB_ODP_SUPPORT_IMPLICIT))
1707 		return;
1708 
1709 	switch (ent->order - 2) {
1710 	case MLX5_IMR_MTT_CACHE_ENTRY:
1711 		ent->page = PAGE_SHIFT;
1712 		ent->xlt = MLX5_IMR_MTT_ENTRIES *
1713 			   sizeof(struct mlx5_mtt) /
1714 			   MLX5_IB_UMR_OCTOWORD;
1715 		ent->access_mode = MLX5_MKC_ACCESS_MODE_MTT;
1716 		ent->limit = 0;
1717 		break;
1718 
1719 	case MLX5_IMR_KSM_CACHE_ENTRY:
1720 		ent->page = MLX5_KSM_PAGE_SHIFT;
1721 		ent->xlt = mlx5_imr_ksm_entries *
1722 			   sizeof(struct mlx5_klm) /
1723 			   MLX5_IB_UMR_OCTOWORD;
1724 		ent->access_mode = MLX5_MKC_ACCESS_MODE_KSM;
1725 		ent->limit = 0;
1726 		break;
1727 	}
1728 }
1729 
1730 static const struct ib_device_ops mlx5_ib_dev_odp_ops = {
1731 	.advise_mr = mlx5_ib_advise_mr,
1732 };
1733 
1734 int mlx5_ib_odp_init_one(struct mlx5_ib_dev *dev)
1735 {
1736 	int ret = 0;
1737 
1738 	if (!(dev->odp_caps.general_caps & IB_ODP_SUPPORT))
1739 		return ret;
1740 
1741 	ib_set_device_ops(&dev->ib_dev, &mlx5_ib_dev_odp_ops);
1742 
1743 	if (dev->odp_caps.general_caps & IB_ODP_SUPPORT_IMPLICIT) {
1744 		ret = mlx5_cmd_null_mkey(dev->mdev, &dev->null_mkey);
1745 		if (ret) {
1746 			mlx5_ib_err(dev, "Error getting null_mkey %d\n", ret);
1747 			return ret;
1748 		}
1749 	}
1750 
1751 	ret = mlx5_ib_create_pf_eq(dev, &dev->odp_pf_eq);
1752 
1753 	return ret;
1754 }
1755 
1756 void mlx5_ib_odp_cleanup_one(struct mlx5_ib_dev *dev)
1757 {
1758 	if (!(dev->odp_caps.general_caps & IB_ODP_SUPPORT))
1759 		return;
1760 
1761 	mlx5_ib_destroy_pf_eq(dev, &dev->odp_pf_eq);
1762 }
1763 
1764 int mlx5_ib_odp_init(void)
1765 {
1766 	mlx5_imr_ksm_entries = BIT_ULL(get_order(TASK_SIZE) -
1767 				       MLX5_IMR_MTT_BITS);
1768 
1769 	return 0;
1770 }
1771 
1772 struct prefetch_mr_work {
1773 	struct work_struct work;
1774 	u32 pf_flags;
1775 	u32 num_sge;
1776 	struct {
1777 		u64 io_virt;
1778 		struct mlx5_ib_mr *mr;
1779 		size_t length;
1780 	} frags[];
1781 };
1782 
1783 static void destroy_prefetch_work(struct prefetch_mr_work *work)
1784 {
1785 	u32 i;
1786 
1787 	for (i = 0; i < work->num_sge; ++i)
1788 		mlx5r_deref_odp_mkey(&work->frags[i].mr->mmkey);
1789 
1790 	kvfree(work);
1791 }
1792 
1793 static struct mlx5_ib_mr *
1794 get_prefetchable_mr(struct ib_pd *pd, enum ib_uverbs_advise_mr_advice advice,
1795 		    u32 lkey)
1796 {
1797 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1798 	struct mlx5_core_mkey *mmkey;
1799 	struct mlx5_ib_mr *mr = NULL;
1800 
1801 	xa_lock(&dev->odp_mkeys);
1802 	mmkey = xa_load(&dev->odp_mkeys, mlx5_base_mkey(lkey));
1803 	if (!mmkey || mmkey->key != lkey || mmkey->type != MLX5_MKEY_MR)
1804 		goto end;
1805 
1806 	mr = container_of(mmkey, struct mlx5_ib_mr, mmkey);
1807 
1808 	if (mr->ibmr.pd != pd) {
1809 		mr = NULL;
1810 		goto end;
1811 	}
1812 
1813 	/* prefetch with write-access must be supported by the MR */
1814 	if (advice == IB_UVERBS_ADVISE_MR_ADVICE_PREFETCH_WRITE &&
1815 	    !mr->umem->writable) {
1816 		mr = NULL;
1817 		goto end;
1818 	}
1819 
1820 	refcount_inc(&mmkey->usecount);
1821 end:
1822 	xa_unlock(&dev->odp_mkeys);
1823 	return mr;
1824 }
1825 
1826 static void mlx5_ib_prefetch_mr_work(struct work_struct *w)
1827 {
1828 	struct prefetch_mr_work *work =
1829 		container_of(w, struct prefetch_mr_work, work);
1830 	u32 bytes_mapped = 0;
1831 	int ret;
1832 	u32 i;
1833 
1834 	/* We rely on IB/core that work is executed if we have num_sge != 0 only. */
1835 	WARN_ON(!work->num_sge);
1836 	for (i = 0; i < work->num_sge; ++i) {
1837 		ret = pagefault_mr(work->frags[i].mr, work->frags[i].io_virt,
1838 				   work->frags[i].length, &bytes_mapped,
1839 				   work->pf_flags);
1840 		if (ret <= 0)
1841 			continue;
1842 		mlx5_update_odp_stats(work->frags[i].mr, prefetch, ret);
1843 	}
1844 
1845 	destroy_prefetch_work(work);
1846 }
1847 
1848 static bool init_prefetch_work(struct ib_pd *pd,
1849 			       enum ib_uverbs_advise_mr_advice advice,
1850 			       u32 pf_flags, struct prefetch_mr_work *work,
1851 			       struct ib_sge *sg_list, u32 num_sge)
1852 {
1853 	u32 i;
1854 
1855 	INIT_WORK(&work->work, mlx5_ib_prefetch_mr_work);
1856 	work->pf_flags = pf_flags;
1857 
1858 	for (i = 0; i < num_sge; ++i) {
1859 		work->frags[i].io_virt = sg_list[i].addr;
1860 		work->frags[i].length = sg_list[i].length;
1861 		work->frags[i].mr =
1862 			get_prefetchable_mr(pd, advice, sg_list[i].lkey);
1863 		if (!work->frags[i].mr) {
1864 			work->num_sge = i;
1865 			return false;
1866 		}
1867 	}
1868 	work->num_sge = num_sge;
1869 	return true;
1870 }
1871 
1872 static int mlx5_ib_prefetch_sg_list(struct ib_pd *pd,
1873 				    enum ib_uverbs_advise_mr_advice advice,
1874 				    u32 pf_flags, struct ib_sge *sg_list,
1875 				    u32 num_sge)
1876 {
1877 	u32 bytes_mapped = 0;
1878 	int ret = 0;
1879 	u32 i;
1880 
1881 	for (i = 0; i < num_sge; ++i) {
1882 		struct mlx5_ib_mr *mr;
1883 
1884 		mr = get_prefetchable_mr(pd, advice, sg_list[i].lkey);
1885 		if (!mr)
1886 			return -ENOENT;
1887 		ret = pagefault_mr(mr, sg_list[i].addr, sg_list[i].length,
1888 				   &bytes_mapped, pf_flags);
1889 		if (ret < 0) {
1890 			mlx5r_deref_odp_mkey(&mr->mmkey);
1891 			return ret;
1892 		}
1893 		mlx5_update_odp_stats(mr, prefetch, ret);
1894 		mlx5r_deref_odp_mkey(&mr->mmkey);
1895 	}
1896 
1897 	return 0;
1898 }
1899 
1900 int mlx5_ib_advise_mr_prefetch(struct ib_pd *pd,
1901 			       enum ib_uverbs_advise_mr_advice advice,
1902 			       u32 flags, struct ib_sge *sg_list, u32 num_sge)
1903 {
1904 	u32 pf_flags = 0;
1905 	struct prefetch_mr_work *work;
1906 
1907 	if (advice == IB_UVERBS_ADVISE_MR_ADVICE_PREFETCH)
1908 		pf_flags |= MLX5_PF_FLAGS_DOWNGRADE;
1909 
1910 	if (advice == IB_UVERBS_ADVISE_MR_ADVICE_PREFETCH_NO_FAULT)
1911 		pf_flags |= MLX5_PF_FLAGS_SNAPSHOT;
1912 
1913 	if (flags & IB_UVERBS_ADVISE_MR_FLAG_FLUSH)
1914 		return mlx5_ib_prefetch_sg_list(pd, advice, pf_flags, sg_list,
1915 						num_sge);
1916 
1917 	work = kvzalloc(struct_size(work, frags, num_sge), GFP_KERNEL);
1918 	if (!work)
1919 		return -ENOMEM;
1920 
1921 	if (!init_prefetch_work(pd, advice, pf_flags, work, sg_list, num_sge)) {
1922 		destroy_prefetch_work(work);
1923 		return -EINVAL;
1924 	}
1925 	queue_work(system_unbound_wq, &work->work);
1926 	return 0;
1927 }
1928