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