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