xref: /linux/drivers/infiniband/hw/mlx5/mr.c (revision be239684b18e1cdcafcf8c7face4a2f562c745ad)
1 /*
2  * Copyright (c) 2013-2015, Mellanox Technologies. All rights reserved.
3  * Copyright (c) 2020, Intel Corporation. All rights reserved.
4  *
5  * This software is available to you under a choice of one of two
6  * licenses.  You may choose to be licensed under the terms of the GNU
7  * General Public License (GPL) Version 2, available from the file
8  * COPYING in the main directory of this source tree, or the
9  * OpenIB.org BSD license below:
10  *
11  *     Redistribution and use in source and binary forms, with or
12  *     without modification, are permitted provided that the following
13  *     conditions are met:
14  *
15  *      - Redistributions of source code must retain the above
16  *        copyright notice, this list of conditions and the following
17  *        disclaimer.
18  *
19  *      - Redistributions in binary form must reproduce the above
20  *        copyright notice, this list of conditions and the following
21  *        disclaimer in the documentation and/or other materials
22  *        provided with the distribution.
23  *
24  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
28  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
29  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
30  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31  * SOFTWARE.
32  */
33 
34 
35 #include <linux/kref.h>
36 #include <linux/random.h>
37 #include <linux/debugfs.h>
38 #include <linux/export.h>
39 #include <linux/delay.h>
40 #include <linux/dma-buf.h>
41 #include <linux/dma-resv.h>
42 #include <rdma/ib_umem_odp.h>
43 #include "dm.h"
44 #include "mlx5_ib.h"
45 #include "umr.h"
46 
47 enum {
48 	MAX_PENDING_REG_MR = 8,
49 };
50 
51 #define MLX5_UMR_ALIGN 2048
52 
53 static void
54 create_mkey_callback(int status, struct mlx5_async_work *context);
55 static struct mlx5_ib_mr *reg_create(struct ib_pd *pd, struct ib_umem *umem,
56 				     u64 iova, int access_flags,
57 				     unsigned int page_size, bool populate);
58 
59 static void set_mkc_access_pd_addr_fields(void *mkc, int acc, u64 start_addr,
60 					  struct ib_pd *pd)
61 {
62 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
63 
64 	MLX5_SET(mkc, mkc, a, !!(acc & IB_ACCESS_REMOTE_ATOMIC));
65 	MLX5_SET(mkc, mkc, rw, !!(acc & IB_ACCESS_REMOTE_WRITE));
66 	MLX5_SET(mkc, mkc, rr, !!(acc & IB_ACCESS_REMOTE_READ));
67 	MLX5_SET(mkc, mkc, lw, !!(acc & IB_ACCESS_LOCAL_WRITE));
68 	MLX5_SET(mkc, mkc, lr, 1);
69 
70 	if (acc & IB_ACCESS_RELAXED_ORDERING) {
71 		if (MLX5_CAP_GEN(dev->mdev, relaxed_ordering_write))
72 			MLX5_SET(mkc, mkc, relaxed_ordering_write, 1);
73 
74 		if (MLX5_CAP_GEN(dev->mdev, relaxed_ordering_read) ||
75 		    (MLX5_CAP_GEN(dev->mdev,
76 				  relaxed_ordering_read_pci_enabled) &&
77 		     pcie_relaxed_ordering_enabled(dev->mdev->pdev)))
78 			MLX5_SET(mkc, mkc, relaxed_ordering_read, 1);
79 	}
80 
81 	MLX5_SET(mkc, mkc, pd, to_mpd(pd)->pdn);
82 	MLX5_SET(mkc, mkc, qpn, 0xffffff);
83 	MLX5_SET64(mkc, mkc, start_addr, start_addr);
84 }
85 
86 static void assign_mkey_variant(struct mlx5_ib_dev *dev, u32 *mkey, u32 *in)
87 {
88 	u8 key = atomic_inc_return(&dev->mkey_var);
89 	void *mkc;
90 
91 	mkc = MLX5_ADDR_OF(create_mkey_in, in, memory_key_mkey_entry);
92 	MLX5_SET(mkc, mkc, mkey_7_0, key);
93 	*mkey = key;
94 }
95 
96 static int mlx5_ib_create_mkey(struct mlx5_ib_dev *dev,
97 			       struct mlx5_ib_mkey *mkey, u32 *in, int inlen)
98 {
99 	int ret;
100 
101 	assign_mkey_variant(dev, &mkey->key, in);
102 	ret = mlx5_core_create_mkey(dev->mdev, &mkey->key, in, inlen);
103 	if (!ret)
104 		init_waitqueue_head(&mkey->wait);
105 
106 	return ret;
107 }
108 
109 static int mlx5_ib_create_mkey_cb(struct mlx5r_async_create_mkey *async_create)
110 {
111 	struct mlx5_ib_dev *dev = async_create->ent->dev;
112 	size_t inlen = MLX5_ST_SZ_BYTES(create_mkey_in);
113 	size_t outlen = MLX5_ST_SZ_BYTES(create_mkey_out);
114 
115 	MLX5_SET(create_mkey_in, async_create->in, opcode,
116 		 MLX5_CMD_OP_CREATE_MKEY);
117 	assign_mkey_variant(dev, &async_create->mkey, async_create->in);
118 	return mlx5_cmd_exec_cb(&dev->async_ctx, async_create->in, inlen,
119 				async_create->out, outlen, create_mkey_callback,
120 				&async_create->cb_work);
121 }
122 
123 static int mkey_cache_max_order(struct mlx5_ib_dev *dev);
124 static void queue_adjust_cache_locked(struct mlx5_cache_ent *ent);
125 
126 static int destroy_mkey(struct mlx5_ib_dev *dev, struct mlx5_ib_mr *mr)
127 {
128 	WARN_ON(xa_load(&dev->odp_mkeys, mlx5_base_mkey(mr->mmkey.key)));
129 
130 	return mlx5_core_destroy_mkey(dev->mdev, mr->mmkey.key);
131 }
132 
133 static void create_mkey_warn(struct mlx5_ib_dev *dev, int status, void *out)
134 {
135 	if (status == -ENXIO) /* core driver is not available */
136 		return;
137 
138 	mlx5_ib_warn(dev, "async reg mr failed. status %d\n", status);
139 	if (status != -EREMOTEIO) /* driver specific failure */
140 		return;
141 
142 	/* Failed in FW, print cmd out failure details */
143 	mlx5_cmd_out_err(dev->mdev, MLX5_CMD_OP_CREATE_MKEY, 0, out);
144 }
145 
146 static int push_mkey_locked(struct mlx5_cache_ent *ent, u32 mkey)
147 {
148 	unsigned long tmp = ent->mkeys_queue.ci % NUM_MKEYS_PER_PAGE;
149 	struct mlx5_mkeys_page *page;
150 
151 	lockdep_assert_held(&ent->mkeys_queue.lock);
152 	if (ent->mkeys_queue.ci >=
153 	    ent->mkeys_queue.num_pages * NUM_MKEYS_PER_PAGE) {
154 		page = kzalloc(sizeof(*page), GFP_ATOMIC);
155 		if (!page)
156 			return -ENOMEM;
157 		ent->mkeys_queue.num_pages++;
158 		list_add_tail(&page->list, &ent->mkeys_queue.pages_list);
159 	} else {
160 		page = list_last_entry(&ent->mkeys_queue.pages_list,
161 				       struct mlx5_mkeys_page, list);
162 	}
163 
164 	page->mkeys[tmp] = mkey;
165 	ent->mkeys_queue.ci++;
166 	return 0;
167 }
168 
169 static int pop_mkey_locked(struct mlx5_cache_ent *ent)
170 {
171 	unsigned long tmp = (ent->mkeys_queue.ci - 1) % NUM_MKEYS_PER_PAGE;
172 	struct mlx5_mkeys_page *last_page;
173 	u32 mkey;
174 
175 	lockdep_assert_held(&ent->mkeys_queue.lock);
176 	last_page = list_last_entry(&ent->mkeys_queue.pages_list,
177 				    struct mlx5_mkeys_page, list);
178 	mkey = last_page->mkeys[tmp];
179 	last_page->mkeys[tmp] = 0;
180 	ent->mkeys_queue.ci--;
181 	if (ent->mkeys_queue.num_pages > 1 && !tmp) {
182 		list_del(&last_page->list);
183 		ent->mkeys_queue.num_pages--;
184 		kfree(last_page);
185 	}
186 	return mkey;
187 }
188 
189 static void create_mkey_callback(int status, struct mlx5_async_work *context)
190 {
191 	struct mlx5r_async_create_mkey *mkey_out =
192 		container_of(context, struct mlx5r_async_create_mkey, cb_work);
193 	struct mlx5_cache_ent *ent = mkey_out->ent;
194 	struct mlx5_ib_dev *dev = ent->dev;
195 	unsigned long flags;
196 
197 	if (status) {
198 		create_mkey_warn(dev, status, mkey_out->out);
199 		kfree(mkey_out);
200 		spin_lock_irqsave(&ent->mkeys_queue.lock, flags);
201 		ent->pending--;
202 		WRITE_ONCE(dev->fill_delay, 1);
203 		spin_unlock_irqrestore(&ent->mkeys_queue.lock, flags);
204 		mod_timer(&dev->delay_timer, jiffies + HZ);
205 		return;
206 	}
207 
208 	mkey_out->mkey |= mlx5_idx_to_mkey(
209 		MLX5_GET(create_mkey_out, mkey_out->out, mkey_index));
210 	WRITE_ONCE(dev->cache.last_add, jiffies);
211 
212 	spin_lock_irqsave(&ent->mkeys_queue.lock, flags);
213 	push_mkey_locked(ent, mkey_out->mkey);
214 	/* If we are doing fill_to_high_water then keep going. */
215 	queue_adjust_cache_locked(ent);
216 	ent->pending--;
217 	spin_unlock_irqrestore(&ent->mkeys_queue.lock, flags);
218 	kfree(mkey_out);
219 }
220 
221 static int get_mkc_octo_size(unsigned int access_mode, unsigned int ndescs)
222 {
223 	int ret = 0;
224 
225 	switch (access_mode) {
226 	case MLX5_MKC_ACCESS_MODE_MTT:
227 		ret = DIV_ROUND_UP(ndescs, MLX5_IB_UMR_OCTOWORD /
228 						   sizeof(struct mlx5_mtt));
229 		break;
230 	case MLX5_MKC_ACCESS_MODE_KSM:
231 		ret = DIV_ROUND_UP(ndescs, MLX5_IB_UMR_OCTOWORD /
232 						   sizeof(struct mlx5_klm));
233 		break;
234 	default:
235 		WARN_ON(1);
236 	}
237 	return ret;
238 }
239 
240 static void set_cache_mkc(struct mlx5_cache_ent *ent, void *mkc)
241 {
242 	set_mkc_access_pd_addr_fields(mkc, ent->rb_key.access_flags, 0,
243 				      ent->dev->umrc.pd);
244 	MLX5_SET(mkc, mkc, free, 1);
245 	MLX5_SET(mkc, mkc, umr_en, 1);
246 	MLX5_SET(mkc, mkc, access_mode_1_0, ent->rb_key.access_mode & 0x3);
247 	MLX5_SET(mkc, mkc, access_mode_4_2,
248 		(ent->rb_key.access_mode >> 2) & 0x7);
249 
250 	MLX5_SET(mkc, mkc, translations_octword_size,
251 		 get_mkc_octo_size(ent->rb_key.access_mode,
252 				   ent->rb_key.ndescs));
253 	MLX5_SET(mkc, mkc, log_page_size, PAGE_SHIFT);
254 }
255 
256 /* Asynchronously schedule new MRs to be populated in the cache. */
257 static int add_keys(struct mlx5_cache_ent *ent, unsigned int num)
258 {
259 	struct mlx5r_async_create_mkey *async_create;
260 	void *mkc;
261 	int err = 0;
262 	int i;
263 
264 	for (i = 0; i < num; i++) {
265 		async_create = kzalloc(sizeof(struct mlx5r_async_create_mkey),
266 				       GFP_KERNEL);
267 		if (!async_create)
268 			return -ENOMEM;
269 		mkc = MLX5_ADDR_OF(create_mkey_in, async_create->in,
270 				   memory_key_mkey_entry);
271 		set_cache_mkc(ent, mkc);
272 		async_create->ent = ent;
273 
274 		spin_lock_irq(&ent->mkeys_queue.lock);
275 		if (ent->pending >= MAX_PENDING_REG_MR) {
276 			err = -EAGAIN;
277 			goto free_async_create;
278 		}
279 		ent->pending++;
280 		spin_unlock_irq(&ent->mkeys_queue.lock);
281 
282 		err = mlx5_ib_create_mkey_cb(async_create);
283 		if (err) {
284 			mlx5_ib_warn(ent->dev, "create mkey failed %d\n", err);
285 			goto err_create_mkey;
286 		}
287 	}
288 
289 	return 0;
290 
291 err_create_mkey:
292 	spin_lock_irq(&ent->mkeys_queue.lock);
293 	ent->pending--;
294 free_async_create:
295 	spin_unlock_irq(&ent->mkeys_queue.lock);
296 	kfree(async_create);
297 	return err;
298 }
299 
300 /* Synchronously create a MR in the cache */
301 static int create_cache_mkey(struct mlx5_cache_ent *ent, u32 *mkey)
302 {
303 	size_t inlen = MLX5_ST_SZ_BYTES(create_mkey_in);
304 	void *mkc;
305 	u32 *in;
306 	int err;
307 
308 	in = kzalloc(inlen, GFP_KERNEL);
309 	if (!in)
310 		return -ENOMEM;
311 	mkc = MLX5_ADDR_OF(create_mkey_in, in, memory_key_mkey_entry);
312 	set_cache_mkc(ent, mkc);
313 
314 	err = mlx5_core_create_mkey(ent->dev->mdev, mkey, in, inlen);
315 	if (err)
316 		goto free_in;
317 
318 	WRITE_ONCE(ent->dev->cache.last_add, jiffies);
319 free_in:
320 	kfree(in);
321 	return err;
322 }
323 
324 static void remove_cache_mr_locked(struct mlx5_cache_ent *ent)
325 {
326 	u32 mkey;
327 
328 	lockdep_assert_held(&ent->mkeys_queue.lock);
329 	if (!ent->mkeys_queue.ci)
330 		return;
331 	mkey = pop_mkey_locked(ent);
332 	spin_unlock_irq(&ent->mkeys_queue.lock);
333 	mlx5_core_destroy_mkey(ent->dev->mdev, mkey);
334 	spin_lock_irq(&ent->mkeys_queue.lock);
335 }
336 
337 static int resize_available_mrs(struct mlx5_cache_ent *ent, unsigned int target,
338 				bool limit_fill)
339 	__acquires(&ent->mkeys_queue.lock) __releases(&ent->mkeys_queue.lock)
340 {
341 	int err;
342 
343 	lockdep_assert_held(&ent->mkeys_queue.lock);
344 
345 	while (true) {
346 		if (limit_fill)
347 			target = ent->limit * 2;
348 		if (target == ent->pending + ent->mkeys_queue.ci)
349 			return 0;
350 		if (target > ent->pending + ent->mkeys_queue.ci) {
351 			u32 todo = target - (ent->pending + ent->mkeys_queue.ci);
352 
353 			spin_unlock_irq(&ent->mkeys_queue.lock);
354 			err = add_keys(ent, todo);
355 			if (err == -EAGAIN)
356 				usleep_range(3000, 5000);
357 			spin_lock_irq(&ent->mkeys_queue.lock);
358 			if (err) {
359 				if (err != -EAGAIN)
360 					return err;
361 			} else
362 				return 0;
363 		} else {
364 			remove_cache_mr_locked(ent);
365 		}
366 	}
367 }
368 
369 static ssize_t size_write(struct file *filp, const char __user *buf,
370 			  size_t count, loff_t *pos)
371 {
372 	struct mlx5_cache_ent *ent = filp->private_data;
373 	u32 target;
374 	int err;
375 
376 	err = kstrtou32_from_user(buf, count, 0, &target);
377 	if (err)
378 		return err;
379 
380 	/*
381 	 * Target is the new value of total_mrs the user requests, however we
382 	 * cannot free MRs that are in use. Compute the target value for stored
383 	 * mkeys.
384 	 */
385 	spin_lock_irq(&ent->mkeys_queue.lock);
386 	if (target < ent->in_use) {
387 		err = -EINVAL;
388 		goto err_unlock;
389 	}
390 	target = target - ent->in_use;
391 	if (target < ent->limit || target > ent->limit*2) {
392 		err = -EINVAL;
393 		goto err_unlock;
394 	}
395 	err = resize_available_mrs(ent, target, false);
396 	if (err)
397 		goto err_unlock;
398 	spin_unlock_irq(&ent->mkeys_queue.lock);
399 
400 	return count;
401 
402 err_unlock:
403 	spin_unlock_irq(&ent->mkeys_queue.lock);
404 	return err;
405 }
406 
407 static ssize_t size_read(struct file *filp, char __user *buf, size_t count,
408 			 loff_t *pos)
409 {
410 	struct mlx5_cache_ent *ent = filp->private_data;
411 	char lbuf[20];
412 	int err;
413 
414 	err = snprintf(lbuf, sizeof(lbuf), "%ld\n",
415 		       ent->mkeys_queue.ci + ent->in_use);
416 	if (err < 0)
417 		return err;
418 
419 	return simple_read_from_buffer(buf, count, pos, lbuf, err);
420 }
421 
422 static const struct file_operations size_fops = {
423 	.owner	= THIS_MODULE,
424 	.open	= simple_open,
425 	.write	= size_write,
426 	.read	= size_read,
427 };
428 
429 static ssize_t limit_write(struct file *filp, const char __user *buf,
430 			   size_t count, loff_t *pos)
431 {
432 	struct mlx5_cache_ent *ent = filp->private_data;
433 	u32 var;
434 	int err;
435 
436 	err = kstrtou32_from_user(buf, count, 0, &var);
437 	if (err)
438 		return err;
439 
440 	/*
441 	 * Upon set we immediately fill the cache to high water mark implied by
442 	 * the limit.
443 	 */
444 	spin_lock_irq(&ent->mkeys_queue.lock);
445 	ent->limit = var;
446 	err = resize_available_mrs(ent, 0, true);
447 	spin_unlock_irq(&ent->mkeys_queue.lock);
448 	if (err)
449 		return err;
450 	return count;
451 }
452 
453 static ssize_t limit_read(struct file *filp, char __user *buf, size_t count,
454 			  loff_t *pos)
455 {
456 	struct mlx5_cache_ent *ent = filp->private_data;
457 	char lbuf[20];
458 	int err;
459 
460 	err = snprintf(lbuf, sizeof(lbuf), "%d\n", ent->limit);
461 	if (err < 0)
462 		return err;
463 
464 	return simple_read_from_buffer(buf, count, pos, lbuf, err);
465 }
466 
467 static const struct file_operations limit_fops = {
468 	.owner	= THIS_MODULE,
469 	.open	= simple_open,
470 	.write	= limit_write,
471 	.read	= limit_read,
472 };
473 
474 static bool someone_adding(struct mlx5_mkey_cache *cache)
475 {
476 	struct mlx5_cache_ent *ent;
477 	struct rb_node *node;
478 	bool ret;
479 
480 	mutex_lock(&cache->rb_lock);
481 	for (node = rb_first(&cache->rb_root); node; node = rb_next(node)) {
482 		ent = rb_entry(node, struct mlx5_cache_ent, node);
483 		spin_lock_irq(&ent->mkeys_queue.lock);
484 		ret = ent->mkeys_queue.ci < ent->limit;
485 		spin_unlock_irq(&ent->mkeys_queue.lock);
486 		if (ret) {
487 			mutex_unlock(&cache->rb_lock);
488 			return true;
489 		}
490 	}
491 	mutex_unlock(&cache->rb_lock);
492 	return false;
493 }
494 
495 /*
496  * Check if the bucket is outside the high/low water mark and schedule an async
497  * update. The cache refill has hysteresis, once the low water mark is hit it is
498  * refilled up to the high mark.
499  */
500 static void queue_adjust_cache_locked(struct mlx5_cache_ent *ent)
501 {
502 	lockdep_assert_held(&ent->mkeys_queue.lock);
503 
504 	if (ent->disabled || READ_ONCE(ent->dev->fill_delay) || ent->is_tmp)
505 		return;
506 	if (ent->mkeys_queue.ci < ent->limit) {
507 		ent->fill_to_high_water = true;
508 		mod_delayed_work(ent->dev->cache.wq, &ent->dwork, 0);
509 	} else if (ent->fill_to_high_water &&
510 		   ent->mkeys_queue.ci + ent->pending < 2 * ent->limit) {
511 		/*
512 		 * Once we start populating due to hitting a low water mark
513 		 * continue until we pass the high water mark.
514 		 */
515 		mod_delayed_work(ent->dev->cache.wq, &ent->dwork, 0);
516 	} else if (ent->mkeys_queue.ci == 2 * ent->limit) {
517 		ent->fill_to_high_water = false;
518 	} else if (ent->mkeys_queue.ci > 2 * ent->limit) {
519 		/* Queue deletion of excess entries */
520 		ent->fill_to_high_water = false;
521 		if (ent->pending)
522 			queue_delayed_work(ent->dev->cache.wq, &ent->dwork,
523 					   msecs_to_jiffies(1000));
524 		else
525 			mod_delayed_work(ent->dev->cache.wq, &ent->dwork, 0);
526 	}
527 }
528 
529 static void __cache_work_func(struct mlx5_cache_ent *ent)
530 {
531 	struct mlx5_ib_dev *dev = ent->dev;
532 	struct mlx5_mkey_cache *cache = &dev->cache;
533 	int err;
534 
535 	spin_lock_irq(&ent->mkeys_queue.lock);
536 	if (ent->disabled)
537 		goto out;
538 
539 	if (ent->fill_to_high_water &&
540 	    ent->mkeys_queue.ci + ent->pending < 2 * ent->limit &&
541 	    !READ_ONCE(dev->fill_delay)) {
542 		spin_unlock_irq(&ent->mkeys_queue.lock);
543 		err = add_keys(ent, 1);
544 		spin_lock_irq(&ent->mkeys_queue.lock);
545 		if (ent->disabled)
546 			goto out;
547 		if (err) {
548 			/*
549 			 * EAGAIN only happens if there are pending MRs, so we
550 			 * will be rescheduled when storing them. The only
551 			 * failure path here is ENOMEM.
552 			 */
553 			if (err != -EAGAIN) {
554 				mlx5_ib_warn(
555 					dev,
556 					"add keys command failed, err %d\n",
557 					err);
558 				queue_delayed_work(cache->wq, &ent->dwork,
559 						   msecs_to_jiffies(1000));
560 			}
561 		}
562 	} else if (ent->mkeys_queue.ci > 2 * ent->limit) {
563 		bool need_delay;
564 
565 		/*
566 		 * The remove_cache_mr() logic is performed as garbage
567 		 * collection task. Such task is intended to be run when no
568 		 * other active processes are running.
569 		 *
570 		 * The need_resched() will return TRUE if there are user tasks
571 		 * to be activated in near future.
572 		 *
573 		 * In such case, we don't execute remove_cache_mr() and postpone
574 		 * the garbage collection work to try to run in next cycle, in
575 		 * order to free CPU resources to other tasks.
576 		 */
577 		spin_unlock_irq(&ent->mkeys_queue.lock);
578 		need_delay = need_resched() || someone_adding(cache) ||
579 			     !time_after(jiffies,
580 					 READ_ONCE(cache->last_add) + 300 * HZ);
581 		spin_lock_irq(&ent->mkeys_queue.lock);
582 		if (ent->disabled)
583 			goto out;
584 		if (need_delay) {
585 			queue_delayed_work(cache->wq, &ent->dwork, 300 * HZ);
586 			goto out;
587 		}
588 		remove_cache_mr_locked(ent);
589 		queue_adjust_cache_locked(ent);
590 	}
591 out:
592 	spin_unlock_irq(&ent->mkeys_queue.lock);
593 }
594 
595 static void delayed_cache_work_func(struct work_struct *work)
596 {
597 	struct mlx5_cache_ent *ent;
598 
599 	ent = container_of(work, struct mlx5_cache_ent, dwork.work);
600 	__cache_work_func(ent);
601 }
602 
603 static int cache_ent_key_cmp(struct mlx5r_cache_rb_key key1,
604 			     struct mlx5r_cache_rb_key key2)
605 {
606 	int res;
607 
608 	res = key1.ats - key2.ats;
609 	if (res)
610 		return res;
611 
612 	res = key1.access_mode - key2.access_mode;
613 	if (res)
614 		return res;
615 
616 	res = key1.access_flags - key2.access_flags;
617 	if (res)
618 		return res;
619 
620 	/*
621 	 * keep ndescs the last in the compare table since the find function
622 	 * searches for an exact match on all properties and only closest
623 	 * match in size.
624 	 */
625 	return key1.ndescs - key2.ndescs;
626 }
627 
628 static int mlx5_cache_ent_insert(struct mlx5_mkey_cache *cache,
629 				 struct mlx5_cache_ent *ent)
630 {
631 	struct rb_node **new = &cache->rb_root.rb_node, *parent = NULL;
632 	struct mlx5_cache_ent *cur;
633 	int cmp;
634 
635 	/* Figure out where to put new node */
636 	while (*new) {
637 		cur = rb_entry(*new, struct mlx5_cache_ent, node);
638 		parent = *new;
639 		cmp = cache_ent_key_cmp(cur->rb_key, ent->rb_key);
640 		if (cmp > 0)
641 			new = &((*new)->rb_left);
642 		if (cmp < 0)
643 			new = &((*new)->rb_right);
644 		if (cmp == 0) {
645 			mutex_unlock(&cache->rb_lock);
646 			return -EEXIST;
647 		}
648 	}
649 
650 	/* Add new node and rebalance tree. */
651 	rb_link_node(&ent->node, parent, new);
652 	rb_insert_color(&ent->node, &cache->rb_root);
653 
654 	return 0;
655 }
656 
657 static struct mlx5_cache_ent *
658 mkey_cache_ent_from_rb_key(struct mlx5_ib_dev *dev,
659 			   struct mlx5r_cache_rb_key rb_key)
660 {
661 	struct rb_node *node = dev->cache.rb_root.rb_node;
662 	struct mlx5_cache_ent *cur, *smallest = NULL;
663 	int cmp;
664 
665 	/*
666 	 * Find the smallest ent with order >= requested_order.
667 	 */
668 	while (node) {
669 		cur = rb_entry(node, struct mlx5_cache_ent, node);
670 		cmp = cache_ent_key_cmp(cur->rb_key, rb_key);
671 		if (cmp > 0) {
672 			smallest = cur;
673 			node = node->rb_left;
674 		}
675 		if (cmp < 0)
676 			node = node->rb_right;
677 		if (cmp == 0)
678 			return cur;
679 	}
680 
681 	return (smallest &&
682 		smallest->rb_key.access_mode == rb_key.access_mode &&
683 		smallest->rb_key.access_flags == rb_key.access_flags &&
684 		smallest->rb_key.ats == rb_key.ats) ?
685 		       smallest :
686 		       NULL;
687 }
688 
689 static struct mlx5_ib_mr *_mlx5_mr_cache_alloc(struct mlx5_ib_dev *dev,
690 					struct mlx5_cache_ent *ent,
691 					int access_flags)
692 {
693 	struct mlx5_ib_mr *mr;
694 	int err;
695 
696 	mr = kzalloc(sizeof(*mr), GFP_KERNEL);
697 	if (!mr)
698 		return ERR_PTR(-ENOMEM);
699 
700 	spin_lock_irq(&ent->mkeys_queue.lock);
701 	ent->in_use++;
702 
703 	if (!ent->mkeys_queue.ci) {
704 		queue_adjust_cache_locked(ent);
705 		ent->miss++;
706 		spin_unlock_irq(&ent->mkeys_queue.lock);
707 		err = create_cache_mkey(ent, &mr->mmkey.key);
708 		if (err) {
709 			spin_lock_irq(&ent->mkeys_queue.lock);
710 			ent->in_use--;
711 			spin_unlock_irq(&ent->mkeys_queue.lock);
712 			kfree(mr);
713 			return ERR_PTR(err);
714 		}
715 	} else {
716 		mr->mmkey.key = pop_mkey_locked(ent);
717 		queue_adjust_cache_locked(ent);
718 		spin_unlock_irq(&ent->mkeys_queue.lock);
719 	}
720 	mr->mmkey.cache_ent = ent;
721 	mr->mmkey.type = MLX5_MKEY_MR;
722 	init_waitqueue_head(&mr->mmkey.wait);
723 	return mr;
724 }
725 
726 static int get_unchangeable_access_flags(struct mlx5_ib_dev *dev,
727 					 int access_flags)
728 {
729 	int ret = 0;
730 
731 	if ((access_flags & IB_ACCESS_REMOTE_ATOMIC) &&
732 	    MLX5_CAP_GEN(dev->mdev, atomic) &&
733 	    MLX5_CAP_GEN(dev->mdev, umr_modify_atomic_disabled))
734 		ret |= IB_ACCESS_REMOTE_ATOMIC;
735 
736 	if ((access_flags & IB_ACCESS_RELAXED_ORDERING) &&
737 	    MLX5_CAP_GEN(dev->mdev, relaxed_ordering_write) &&
738 	    !MLX5_CAP_GEN(dev->mdev, relaxed_ordering_write_umr))
739 		ret |= IB_ACCESS_RELAXED_ORDERING;
740 
741 	if ((access_flags & IB_ACCESS_RELAXED_ORDERING) &&
742 	    (MLX5_CAP_GEN(dev->mdev, relaxed_ordering_read) ||
743 	     MLX5_CAP_GEN(dev->mdev, relaxed_ordering_read_pci_enabled)) &&
744 	    !MLX5_CAP_GEN(dev->mdev, relaxed_ordering_read_umr))
745 		ret |= IB_ACCESS_RELAXED_ORDERING;
746 
747 	return ret;
748 }
749 
750 struct mlx5_ib_mr *mlx5_mr_cache_alloc(struct mlx5_ib_dev *dev,
751 				       int access_flags, int access_mode,
752 				       int ndescs)
753 {
754 	struct mlx5r_cache_rb_key rb_key = {
755 		.ndescs = ndescs,
756 		.access_mode = access_mode,
757 		.access_flags = get_unchangeable_access_flags(dev, access_flags)
758 	};
759 	struct mlx5_cache_ent *ent = mkey_cache_ent_from_rb_key(dev, rb_key);
760 
761 	if (!ent)
762 		return ERR_PTR(-EOPNOTSUPP);
763 
764 	return _mlx5_mr_cache_alloc(dev, ent, access_flags);
765 }
766 
767 static void clean_keys(struct mlx5_ib_dev *dev, struct mlx5_cache_ent *ent)
768 {
769 	u32 mkey;
770 
771 	cancel_delayed_work(&ent->dwork);
772 	spin_lock_irq(&ent->mkeys_queue.lock);
773 	while (ent->mkeys_queue.ci) {
774 		mkey = pop_mkey_locked(ent);
775 		spin_unlock_irq(&ent->mkeys_queue.lock);
776 		mlx5_core_destroy_mkey(dev->mdev, mkey);
777 		spin_lock_irq(&ent->mkeys_queue.lock);
778 	}
779 	spin_unlock_irq(&ent->mkeys_queue.lock);
780 }
781 
782 static void mlx5_mkey_cache_debugfs_cleanup(struct mlx5_ib_dev *dev)
783 {
784 	if (!mlx5_debugfs_root || dev->is_rep)
785 		return;
786 
787 	debugfs_remove_recursive(dev->cache.fs_root);
788 	dev->cache.fs_root = NULL;
789 }
790 
791 static void mlx5_mkey_cache_debugfs_add_ent(struct mlx5_ib_dev *dev,
792 					    struct mlx5_cache_ent *ent)
793 {
794 	int order = order_base_2(ent->rb_key.ndescs);
795 	struct dentry *dir;
796 
797 	if (!mlx5_debugfs_root || dev->is_rep)
798 		return;
799 
800 	if (ent->rb_key.access_mode == MLX5_MKC_ACCESS_MODE_KSM)
801 		order = MLX5_IMR_KSM_CACHE_ENTRY + 2;
802 
803 	sprintf(ent->name, "%d", order);
804 	dir = debugfs_create_dir(ent->name, dev->cache.fs_root);
805 	debugfs_create_file("size", 0600, dir, ent, &size_fops);
806 	debugfs_create_file("limit", 0600, dir, ent, &limit_fops);
807 	debugfs_create_ulong("cur", 0400, dir, &ent->mkeys_queue.ci);
808 	debugfs_create_u32("miss", 0600, dir, &ent->miss);
809 }
810 
811 static void mlx5_mkey_cache_debugfs_init(struct mlx5_ib_dev *dev)
812 {
813 	struct dentry *dbg_root = mlx5_debugfs_get_dev_root(dev->mdev);
814 	struct mlx5_mkey_cache *cache = &dev->cache;
815 
816 	if (!mlx5_debugfs_root || dev->is_rep)
817 		return;
818 
819 	cache->fs_root = debugfs_create_dir("mr_cache", dbg_root);
820 }
821 
822 static void delay_time_func(struct timer_list *t)
823 {
824 	struct mlx5_ib_dev *dev = from_timer(dev, t, delay_timer);
825 
826 	WRITE_ONCE(dev->fill_delay, 0);
827 }
828 
829 static int mlx5r_mkeys_init(struct mlx5_cache_ent *ent)
830 {
831 	struct mlx5_mkeys_page *page;
832 
833 	page = kzalloc(sizeof(*page), GFP_KERNEL);
834 	if (!page)
835 		return -ENOMEM;
836 	INIT_LIST_HEAD(&ent->mkeys_queue.pages_list);
837 	spin_lock_init(&ent->mkeys_queue.lock);
838 	list_add_tail(&page->list, &ent->mkeys_queue.pages_list);
839 	ent->mkeys_queue.num_pages++;
840 	return 0;
841 }
842 
843 static void mlx5r_mkeys_uninit(struct mlx5_cache_ent *ent)
844 {
845 	struct mlx5_mkeys_page *page;
846 
847 	WARN_ON(ent->mkeys_queue.ci || ent->mkeys_queue.num_pages > 1);
848 	page = list_last_entry(&ent->mkeys_queue.pages_list,
849 			       struct mlx5_mkeys_page, list);
850 	list_del(&page->list);
851 	kfree(page);
852 }
853 
854 struct mlx5_cache_ent *
855 mlx5r_cache_create_ent_locked(struct mlx5_ib_dev *dev,
856 			      struct mlx5r_cache_rb_key rb_key,
857 			      bool persistent_entry)
858 {
859 	struct mlx5_cache_ent *ent;
860 	int order;
861 	int ret;
862 
863 	ent = kzalloc(sizeof(*ent), GFP_KERNEL);
864 	if (!ent)
865 		return ERR_PTR(-ENOMEM);
866 
867 	ret = mlx5r_mkeys_init(ent);
868 	if (ret)
869 		goto mkeys_err;
870 	ent->rb_key = rb_key;
871 	ent->dev = dev;
872 	ent->is_tmp = !persistent_entry;
873 
874 	INIT_DELAYED_WORK(&ent->dwork, delayed_cache_work_func);
875 
876 	ret = mlx5_cache_ent_insert(&dev->cache, ent);
877 	if (ret)
878 		goto ent_insert_err;
879 
880 	if (persistent_entry) {
881 		if (rb_key.access_mode == MLX5_MKC_ACCESS_MODE_KSM)
882 			order = MLX5_IMR_KSM_CACHE_ENTRY;
883 		else
884 			order = order_base_2(rb_key.ndescs) - 2;
885 
886 		if ((dev->mdev->profile.mask & MLX5_PROF_MASK_MR_CACHE) &&
887 		    !dev->is_rep && mlx5_core_is_pf(dev->mdev) &&
888 		    mlx5r_umr_can_load_pas(dev, 0))
889 			ent->limit = dev->mdev->profile.mr_cache[order].limit;
890 		else
891 			ent->limit = 0;
892 
893 		mlx5_mkey_cache_debugfs_add_ent(dev, ent);
894 	} else {
895 		mod_delayed_work(ent->dev->cache.wq,
896 				 &ent->dev->cache.remove_ent_dwork,
897 				 msecs_to_jiffies(30 * 1000));
898 	}
899 
900 	return ent;
901 ent_insert_err:
902 	mlx5r_mkeys_uninit(ent);
903 mkeys_err:
904 	kfree(ent);
905 	return ERR_PTR(ret);
906 }
907 
908 static void remove_ent_work_func(struct work_struct *work)
909 {
910 	struct mlx5_mkey_cache *cache;
911 	struct mlx5_cache_ent *ent;
912 	struct rb_node *cur;
913 
914 	cache = container_of(work, struct mlx5_mkey_cache,
915 			     remove_ent_dwork.work);
916 	mutex_lock(&cache->rb_lock);
917 	cur = rb_last(&cache->rb_root);
918 	while (cur) {
919 		ent = rb_entry(cur, struct mlx5_cache_ent, node);
920 		cur = rb_prev(cur);
921 		mutex_unlock(&cache->rb_lock);
922 
923 		spin_lock_irq(&ent->mkeys_queue.lock);
924 		if (!ent->is_tmp) {
925 			spin_unlock_irq(&ent->mkeys_queue.lock);
926 			mutex_lock(&cache->rb_lock);
927 			continue;
928 		}
929 		spin_unlock_irq(&ent->mkeys_queue.lock);
930 
931 		clean_keys(ent->dev, ent);
932 		mutex_lock(&cache->rb_lock);
933 	}
934 	mutex_unlock(&cache->rb_lock);
935 }
936 
937 int mlx5_mkey_cache_init(struct mlx5_ib_dev *dev)
938 {
939 	struct mlx5_mkey_cache *cache = &dev->cache;
940 	struct rb_root *root = &dev->cache.rb_root;
941 	struct mlx5r_cache_rb_key rb_key = {
942 		.access_mode = MLX5_MKC_ACCESS_MODE_MTT,
943 	};
944 	struct mlx5_cache_ent *ent;
945 	struct rb_node *node;
946 	int ret;
947 	int i;
948 
949 	mutex_init(&dev->slow_path_mutex);
950 	mutex_init(&dev->cache.rb_lock);
951 	dev->cache.rb_root = RB_ROOT;
952 	INIT_DELAYED_WORK(&dev->cache.remove_ent_dwork, remove_ent_work_func);
953 	cache->wq = alloc_ordered_workqueue("mkey_cache", WQ_MEM_RECLAIM);
954 	if (!cache->wq) {
955 		mlx5_ib_warn(dev, "failed to create work queue\n");
956 		return -ENOMEM;
957 	}
958 
959 	mlx5_cmd_init_async_ctx(dev->mdev, &dev->async_ctx);
960 	timer_setup(&dev->delay_timer, delay_time_func, 0);
961 	mlx5_mkey_cache_debugfs_init(dev);
962 	mutex_lock(&cache->rb_lock);
963 	for (i = 0; i <= mkey_cache_max_order(dev); i++) {
964 		rb_key.ndescs = 1 << (i + 2);
965 		ent = mlx5r_cache_create_ent_locked(dev, rb_key, true);
966 		if (IS_ERR(ent)) {
967 			ret = PTR_ERR(ent);
968 			goto err;
969 		}
970 	}
971 
972 	ret = mlx5_odp_init_mkey_cache(dev);
973 	if (ret)
974 		goto err;
975 
976 	mutex_unlock(&cache->rb_lock);
977 	for (node = rb_first(root); node; node = rb_next(node)) {
978 		ent = rb_entry(node, struct mlx5_cache_ent, node);
979 		spin_lock_irq(&ent->mkeys_queue.lock);
980 		queue_adjust_cache_locked(ent);
981 		spin_unlock_irq(&ent->mkeys_queue.lock);
982 	}
983 
984 	return 0;
985 
986 err:
987 	mutex_unlock(&cache->rb_lock);
988 	mlx5_mkey_cache_debugfs_cleanup(dev);
989 	mlx5_ib_warn(dev, "failed to create mkey cache entry\n");
990 	return ret;
991 }
992 
993 void mlx5_mkey_cache_cleanup(struct mlx5_ib_dev *dev)
994 {
995 	struct rb_root *root = &dev->cache.rb_root;
996 	struct mlx5_cache_ent *ent;
997 	struct rb_node *node;
998 
999 	if (!dev->cache.wq)
1000 		return;
1001 
1002 	mutex_lock(&dev->cache.rb_lock);
1003 	cancel_delayed_work(&dev->cache.remove_ent_dwork);
1004 	for (node = rb_first(root); node; node = rb_next(node)) {
1005 		ent = rb_entry(node, struct mlx5_cache_ent, node);
1006 		spin_lock_irq(&ent->mkeys_queue.lock);
1007 		ent->disabled = true;
1008 		spin_unlock_irq(&ent->mkeys_queue.lock);
1009 		cancel_delayed_work(&ent->dwork);
1010 	}
1011 	mutex_unlock(&dev->cache.rb_lock);
1012 
1013 	/*
1014 	 * After all entries are disabled and will not reschedule on WQ,
1015 	 * flush it and all async commands.
1016 	 */
1017 	flush_workqueue(dev->cache.wq);
1018 
1019 	mlx5_mkey_cache_debugfs_cleanup(dev);
1020 	mlx5_cmd_cleanup_async_ctx(&dev->async_ctx);
1021 
1022 	/* At this point all entries are disabled and have no concurrent work. */
1023 	mutex_lock(&dev->cache.rb_lock);
1024 	node = rb_first(root);
1025 	while (node) {
1026 		ent = rb_entry(node, struct mlx5_cache_ent, node);
1027 		node = rb_next(node);
1028 		clean_keys(dev, ent);
1029 		rb_erase(&ent->node, root);
1030 		mlx5r_mkeys_uninit(ent);
1031 		kfree(ent);
1032 	}
1033 	mutex_unlock(&dev->cache.rb_lock);
1034 
1035 	destroy_workqueue(dev->cache.wq);
1036 	del_timer_sync(&dev->delay_timer);
1037 }
1038 
1039 struct ib_mr *mlx5_ib_get_dma_mr(struct ib_pd *pd, int acc)
1040 {
1041 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1042 	int inlen = MLX5_ST_SZ_BYTES(create_mkey_in);
1043 	struct mlx5_ib_mr *mr;
1044 	void *mkc;
1045 	u32 *in;
1046 	int err;
1047 
1048 	mr = kzalloc(sizeof(*mr), GFP_KERNEL);
1049 	if (!mr)
1050 		return ERR_PTR(-ENOMEM);
1051 
1052 	in = kzalloc(inlen, GFP_KERNEL);
1053 	if (!in) {
1054 		err = -ENOMEM;
1055 		goto err_free;
1056 	}
1057 
1058 	mkc = MLX5_ADDR_OF(create_mkey_in, in, memory_key_mkey_entry);
1059 
1060 	MLX5_SET(mkc, mkc, access_mode_1_0, MLX5_MKC_ACCESS_MODE_PA);
1061 	MLX5_SET(mkc, mkc, length64, 1);
1062 	set_mkc_access_pd_addr_fields(mkc, acc | IB_ACCESS_RELAXED_ORDERING, 0,
1063 				      pd);
1064 
1065 	err = mlx5_ib_create_mkey(dev, &mr->mmkey, in, inlen);
1066 	if (err)
1067 		goto err_in;
1068 
1069 	kfree(in);
1070 	mr->mmkey.type = MLX5_MKEY_MR;
1071 	mr->ibmr.lkey = mr->mmkey.key;
1072 	mr->ibmr.rkey = mr->mmkey.key;
1073 	mr->umem = NULL;
1074 
1075 	return &mr->ibmr;
1076 
1077 err_in:
1078 	kfree(in);
1079 
1080 err_free:
1081 	kfree(mr);
1082 
1083 	return ERR_PTR(err);
1084 }
1085 
1086 static int get_octo_len(u64 addr, u64 len, int page_shift)
1087 {
1088 	u64 page_size = 1ULL << page_shift;
1089 	u64 offset;
1090 	int npages;
1091 
1092 	offset = addr & (page_size - 1);
1093 	npages = ALIGN(len + offset, page_size) >> page_shift;
1094 	return (npages + 1) / 2;
1095 }
1096 
1097 static int mkey_cache_max_order(struct mlx5_ib_dev *dev)
1098 {
1099 	if (MLX5_CAP_GEN(dev->mdev, umr_extended_translation_offset))
1100 		return MKEY_CACHE_LAST_STD_ENTRY;
1101 	return MLX5_MAX_UMR_SHIFT;
1102 }
1103 
1104 static void set_mr_fields(struct mlx5_ib_dev *dev, struct mlx5_ib_mr *mr,
1105 			  u64 length, int access_flags, u64 iova)
1106 {
1107 	mr->ibmr.lkey = mr->mmkey.key;
1108 	mr->ibmr.rkey = mr->mmkey.key;
1109 	mr->ibmr.length = length;
1110 	mr->ibmr.device = &dev->ib_dev;
1111 	mr->ibmr.iova = iova;
1112 	mr->access_flags = access_flags;
1113 }
1114 
1115 static unsigned int mlx5_umem_dmabuf_default_pgsz(struct ib_umem *umem,
1116 						  u64 iova)
1117 {
1118 	/*
1119 	 * The alignment of iova has already been checked upon entering
1120 	 * UVERBS_METHOD_REG_DMABUF_MR
1121 	 */
1122 	umem->iova = iova;
1123 	return PAGE_SIZE;
1124 }
1125 
1126 static struct mlx5_ib_mr *alloc_cacheable_mr(struct ib_pd *pd,
1127 					     struct ib_umem *umem, u64 iova,
1128 					     int access_flags)
1129 {
1130 	struct mlx5r_cache_rb_key rb_key = {
1131 		.access_mode = MLX5_MKC_ACCESS_MODE_MTT,
1132 	};
1133 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1134 	struct mlx5_cache_ent *ent;
1135 	struct mlx5_ib_mr *mr;
1136 	unsigned int page_size;
1137 
1138 	if (umem->is_dmabuf)
1139 		page_size = mlx5_umem_dmabuf_default_pgsz(umem, iova);
1140 	else
1141 		page_size = mlx5_umem_find_best_pgsz(umem, mkc, log_page_size,
1142 						     0, iova);
1143 	if (WARN_ON(!page_size))
1144 		return ERR_PTR(-EINVAL);
1145 
1146 	rb_key.ndescs = ib_umem_num_dma_blocks(umem, page_size);
1147 	rb_key.ats = mlx5_umem_needs_ats(dev, umem, access_flags);
1148 	rb_key.access_flags = get_unchangeable_access_flags(dev, access_flags);
1149 	ent = mkey_cache_ent_from_rb_key(dev, rb_key);
1150 	/*
1151 	 * If the MR can't come from the cache then synchronously create an uncached
1152 	 * one.
1153 	 */
1154 	if (!ent) {
1155 		mutex_lock(&dev->slow_path_mutex);
1156 		mr = reg_create(pd, umem, iova, access_flags, page_size, false);
1157 		mutex_unlock(&dev->slow_path_mutex);
1158 		if (IS_ERR(mr))
1159 			return mr;
1160 		mr->mmkey.rb_key = rb_key;
1161 		return mr;
1162 	}
1163 
1164 	mr = _mlx5_mr_cache_alloc(dev, ent, access_flags);
1165 	if (IS_ERR(mr))
1166 		return mr;
1167 
1168 	mr->ibmr.pd = pd;
1169 	mr->umem = umem;
1170 	mr->page_shift = order_base_2(page_size);
1171 	set_mr_fields(dev, mr, umem->length, access_flags, iova);
1172 
1173 	return mr;
1174 }
1175 
1176 /*
1177  * If ibmr is NULL it will be allocated by reg_create.
1178  * Else, the given ibmr will be used.
1179  */
1180 static struct mlx5_ib_mr *reg_create(struct ib_pd *pd, struct ib_umem *umem,
1181 				     u64 iova, int access_flags,
1182 				     unsigned int page_size, bool populate)
1183 {
1184 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1185 	struct mlx5_ib_mr *mr;
1186 	__be64 *pas;
1187 	void *mkc;
1188 	int inlen;
1189 	u32 *in;
1190 	int err;
1191 	bool pg_cap = !!(MLX5_CAP_GEN(dev->mdev, pg));
1192 
1193 	if (!page_size)
1194 		return ERR_PTR(-EINVAL);
1195 	mr = kzalloc(sizeof(*mr), GFP_KERNEL);
1196 	if (!mr)
1197 		return ERR_PTR(-ENOMEM);
1198 
1199 	mr->ibmr.pd = pd;
1200 	mr->access_flags = access_flags;
1201 	mr->page_shift = order_base_2(page_size);
1202 
1203 	inlen = MLX5_ST_SZ_BYTES(create_mkey_in);
1204 	if (populate)
1205 		inlen += sizeof(*pas) *
1206 			 roundup(ib_umem_num_dma_blocks(umem, page_size), 2);
1207 	in = kvzalloc(inlen, GFP_KERNEL);
1208 	if (!in) {
1209 		err = -ENOMEM;
1210 		goto err_1;
1211 	}
1212 	pas = (__be64 *)MLX5_ADDR_OF(create_mkey_in, in, klm_pas_mtt);
1213 	if (populate) {
1214 		if (WARN_ON(access_flags & IB_ACCESS_ON_DEMAND)) {
1215 			err = -EINVAL;
1216 			goto err_2;
1217 		}
1218 		mlx5_ib_populate_pas(umem, 1UL << mr->page_shift, pas,
1219 				     pg_cap ? MLX5_IB_MTT_PRESENT : 0);
1220 	}
1221 
1222 	/* The pg_access bit allows setting the access flags
1223 	 * in the page list submitted with the command.
1224 	 */
1225 	MLX5_SET(create_mkey_in, in, pg_access, !!(pg_cap));
1226 
1227 	mkc = MLX5_ADDR_OF(create_mkey_in, in, memory_key_mkey_entry);
1228 	set_mkc_access_pd_addr_fields(mkc, access_flags, iova,
1229 				      populate ? pd : dev->umrc.pd);
1230 	MLX5_SET(mkc, mkc, free, !populate);
1231 	MLX5_SET(mkc, mkc, access_mode_1_0, MLX5_MKC_ACCESS_MODE_MTT);
1232 	MLX5_SET(mkc, mkc, umr_en, 1);
1233 
1234 	MLX5_SET64(mkc, mkc, len, umem->length);
1235 	MLX5_SET(mkc, mkc, bsf_octword_size, 0);
1236 	MLX5_SET(mkc, mkc, translations_octword_size,
1237 		 get_octo_len(iova, umem->length, mr->page_shift));
1238 	MLX5_SET(mkc, mkc, log_page_size, mr->page_shift);
1239 	if (mlx5_umem_needs_ats(dev, umem, access_flags))
1240 		MLX5_SET(mkc, mkc, ma_translation_mode, 1);
1241 	if (populate) {
1242 		MLX5_SET(create_mkey_in, in, translations_octword_actual_size,
1243 			 get_octo_len(iova, umem->length, mr->page_shift));
1244 	}
1245 
1246 	err = mlx5_ib_create_mkey(dev, &mr->mmkey, in, inlen);
1247 	if (err) {
1248 		mlx5_ib_warn(dev, "create mkey failed\n");
1249 		goto err_2;
1250 	}
1251 	mr->mmkey.type = MLX5_MKEY_MR;
1252 	mr->mmkey.ndescs = get_octo_len(iova, umem->length, mr->page_shift);
1253 	mr->umem = umem;
1254 	set_mr_fields(dev, mr, umem->length, access_flags, iova);
1255 	kvfree(in);
1256 
1257 	mlx5_ib_dbg(dev, "mkey = 0x%x\n", mr->mmkey.key);
1258 
1259 	return mr;
1260 
1261 err_2:
1262 	kvfree(in);
1263 err_1:
1264 	kfree(mr);
1265 	return ERR_PTR(err);
1266 }
1267 
1268 static struct ib_mr *mlx5_ib_get_dm_mr(struct ib_pd *pd, u64 start_addr,
1269 				       u64 length, int acc, int mode)
1270 {
1271 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1272 	int inlen = MLX5_ST_SZ_BYTES(create_mkey_in);
1273 	struct mlx5_ib_mr *mr;
1274 	void *mkc;
1275 	u32 *in;
1276 	int err;
1277 
1278 	mr = kzalloc(sizeof(*mr), GFP_KERNEL);
1279 	if (!mr)
1280 		return ERR_PTR(-ENOMEM);
1281 
1282 	in = kzalloc(inlen, GFP_KERNEL);
1283 	if (!in) {
1284 		err = -ENOMEM;
1285 		goto err_free;
1286 	}
1287 
1288 	mkc = MLX5_ADDR_OF(create_mkey_in, in, memory_key_mkey_entry);
1289 
1290 	MLX5_SET(mkc, mkc, access_mode_1_0, mode & 0x3);
1291 	MLX5_SET(mkc, mkc, access_mode_4_2, (mode >> 2) & 0x7);
1292 	MLX5_SET64(mkc, mkc, len, length);
1293 	set_mkc_access_pd_addr_fields(mkc, acc, start_addr, pd);
1294 
1295 	err = mlx5_ib_create_mkey(dev, &mr->mmkey, in, inlen);
1296 	if (err)
1297 		goto err_in;
1298 
1299 	kfree(in);
1300 
1301 	set_mr_fields(dev, mr, length, acc, start_addr);
1302 
1303 	return &mr->ibmr;
1304 
1305 err_in:
1306 	kfree(in);
1307 
1308 err_free:
1309 	kfree(mr);
1310 
1311 	return ERR_PTR(err);
1312 }
1313 
1314 int mlx5_ib_advise_mr(struct ib_pd *pd,
1315 		      enum ib_uverbs_advise_mr_advice advice,
1316 		      u32 flags,
1317 		      struct ib_sge *sg_list,
1318 		      u32 num_sge,
1319 		      struct uverbs_attr_bundle *attrs)
1320 {
1321 	if (advice != IB_UVERBS_ADVISE_MR_ADVICE_PREFETCH &&
1322 	    advice != IB_UVERBS_ADVISE_MR_ADVICE_PREFETCH_WRITE &&
1323 	    advice != IB_UVERBS_ADVISE_MR_ADVICE_PREFETCH_NO_FAULT)
1324 		return -EOPNOTSUPP;
1325 
1326 	return mlx5_ib_advise_mr_prefetch(pd, advice, flags,
1327 					 sg_list, num_sge);
1328 }
1329 
1330 struct ib_mr *mlx5_ib_reg_dm_mr(struct ib_pd *pd, struct ib_dm *dm,
1331 				struct ib_dm_mr_attr *attr,
1332 				struct uverbs_attr_bundle *attrs)
1333 {
1334 	struct mlx5_ib_dm *mdm = to_mdm(dm);
1335 	struct mlx5_core_dev *dev = to_mdev(dm->device)->mdev;
1336 	u64 start_addr = mdm->dev_addr + attr->offset;
1337 	int mode;
1338 
1339 	switch (mdm->type) {
1340 	case MLX5_IB_UAPI_DM_TYPE_MEMIC:
1341 		if (attr->access_flags & ~MLX5_IB_DM_MEMIC_ALLOWED_ACCESS)
1342 			return ERR_PTR(-EINVAL);
1343 
1344 		mode = MLX5_MKC_ACCESS_MODE_MEMIC;
1345 		start_addr -= pci_resource_start(dev->pdev, 0);
1346 		break;
1347 	case MLX5_IB_UAPI_DM_TYPE_STEERING_SW_ICM:
1348 	case MLX5_IB_UAPI_DM_TYPE_HEADER_MODIFY_SW_ICM:
1349 	case MLX5_IB_UAPI_DM_TYPE_HEADER_MODIFY_PATTERN_SW_ICM:
1350 	case MLX5_IB_UAPI_DM_TYPE_ENCAP_SW_ICM:
1351 		if (attr->access_flags & ~MLX5_IB_DM_SW_ICM_ALLOWED_ACCESS)
1352 			return ERR_PTR(-EINVAL);
1353 
1354 		mode = MLX5_MKC_ACCESS_MODE_SW_ICM;
1355 		break;
1356 	default:
1357 		return ERR_PTR(-EINVAL);
1358 	}
1359 
1360 	return mlx5_ib_get_dm_mr(pd, start_addr, attr->length,
1361 				 attr->access_flags, mode);
1362 }
1363 
1364 static struct ib_mr *create_real_mr(struct ib_pd *pd, struct ib_umem *umem,
1365 				    u64 iova, int access_flags)
1366 {
1367 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1368 	struct mlx5_ib_mr *mr = NULL;
1369 	bool xlt_with_umr;
1370 	int err;
1371 
1372 	xlt_with_umr = mlx5r_umr_can_load_pas(dev, umem->length);
1373 	if (xlt_with_umr) {
1374 		mr = alloc_cacheable_mr(pd, umem, iova, access_flags);
1375 	} else {
1376 		unsigned int page_size = mlx5_umem_find_best_pgsz(
1377 			umem, mkc, log_page_size, 0, iova);
1378 
1379 		mutex_lock(&dev->slow_path_mutex);
1380 		mr = reg_create(pd, umem, iova, access_flags, page_size, true);
1381 		mutex_unlock(&dev->slow_path_mutex);
1382 	}
1383 	if (IS_ERR(mr)) {
1384 		ib_umem_release(umem);
1385 		return ERR_CAST(mr);
1386 	}
1387 
1388 	mlx5_ib_dbg(dev, "mkey 0x%x\n", mr->mmkey.key);
1389 
1390 	atomic_add(ib_umem_num_pages(umem), &dev->mdev->priv.reg_pages);
1391 
1392 	if (xlt_with_umr) {
1393 		/*
1394 		 * If the MR was created with reg_create then it will be
1395 		 * configured properly but left disabled. It is safe to go ahead
1396 		 * and configure it again via UMR while enabling it.
1397 		 */
1398 		err = mlx5r_umr_update_mr_pas(mr, MLX5_IB_UPD_XLT_ENABLE);
1399 		if (err) {
1400 			mlx5_ib_dereg_mr(&mr->ibmr, NULL);
1401 			return ERR_PTR(err);
1402 		}
1403 	}
1404 	return &mr->ibmr;
1405 }
1406 
1407 static struct ib_mr *create_user_odp_mr(struct ib_pd *pd, u64 start, u64 length,
1408 					u64 iova, int access_flags,
1409 					struct ib_udata *udata)
1410 {
1411 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1412 	struct ib_umem_odp *odp;
1413 	struct mlx5_ib_mr *mr;
1414 	int err;
1415 
1416 	if (!IS_ENABLED(CONFIG_INFINIBAND_ON_DEMAND_PAGING))
1417 		return ERR_PTR(-EOPNOTSUPP);
1418 
1419 	err = mlx5r_odp_create_eq(dev, &dev->odp_pf_eq);
1420 	if (err)
1421 		return ERR_PTR(err);
1422 	if (!start && length == U64_MAX) {
1423 		if (iova != 0)
1424 			return ERR_PTR(-EINVAL);
1425 		if (!(dev->odp_caps.general_caps & IB_ODP_SUPPORT_IMPLICIT))
1426 			return ERR_PTR(-EINVAL);
1427 
1428 		mr = mlx5_ib_alloc_implicit_mr(to_mpd(pd), access_flags);
1429 		if (IS_ERR(mr))
1430 			return ERR_CAST(mr);
1431 		return &mr->ibmr;
1432 	}
1433 
1434 	/* ODP requires xlt update via umr to work. */
1435 	if (!mlx5r_umr_can_load_pas(dev, length))
1436 		return ERR_PTR(-EINVAL);
1437 
1438 	odp = ib_umem_odp_get(&dev->ib_dev, start, length, access_flags,
1439 			      &mlx5_mn_ops);
1440 	if (IS_ERR(odp))
1441 		return ERR_CAST(odp);
1442 
1443 	mr = alloc_cacheable_mr(pd, &odp->umem, iova, access_flags);
1444 	if (IS_ERR(mr)) {
1445 		ib_umem_release(&odp->umem);
1446 		return ERR_CAST(mr);
1447 	}
1448 	xa_init(&mr->implicit_children);
1449 
1450 	odp->private = mr;
1451 	err = mlx5r_store_odp_mkey(dev, &mr->mmkey);
1452 	if (err)
1453 		goto err_dereg_mr;
1454 
1455 	err = mlx5_ib_init_odp_mr(mr);
1456 	if (err)
1457 		goto err_dereg_mr;
1458 	return &mr->ibmr;
1459 
1460 err_dereg_mr:
1461 	mlx5_ib_dereg_mr(&mr->ibmr, NULL);
1462 	return ERR_PTR(err);
1463 }
1464 
1465 struct ib_mr *mlx5_ib_reg_user_mr(struct ib_pd *pd, u64 start, u64 length,
1466 				  u64 iova, int access_flags,
1467 				  struct ib_udata *udata)
1468 {
1469 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1470 	struct ib_umem *umem;
1471 
1472 	if (!IS_ENABLED(CONFIG_INFINIBAND_USER_MEM))
1473 		return ERR_PTR(-EOPNOTSUPP);
1474 
1475 	mlx5_ib_dbg(dev, "start 0x%llx, iova 0x%llx, length 0x%llx, access_flags 0x%x\n",
1476 		    start, iova, length, access_flags);
1477 
1478 	if (access_flags & IB_ACCESS_ON_DEMAND)
1479 		return create_user_odp_mr(pd, start, length, iova, access_flags,
1480 					  udata);
1481 	umem = ib_umem_get(&dev->ib_dev, start, length, access_flags);
1482 	if (IS_ERR(umem))
1483 		return ERR_CAST(umem);
1484 	return create_real_mr(pd, umem, iova, access_flags);
1485 }
1486 
1487 static void mlx5_ib_dmabuf_invalidate_cb(struct dma_buf_attachment *attach)
1488 {
1489 	struct ib_umem_dmabuf *umem_dmabuf = attach->importer_priv;
1490 	struct mlx5_ib_mr *mr = umem_dmabuf->private;
1491 
1492 	dma_resv_assert_held(umem_dmabuf->attach->dmabuf->resv);
1493 
1494 	if (!umem_dmabuf->sgt)
1495 		return;
1496 
1497 	mlx5r_umr_update_mr_pas(mr, MLX5_IB_UPD_XLT_ZAP);
1498 	ib_umem_dmabuf_unmap_pages(umem_dmabuf);
1499 }
1500 
1501 static struct dma_buf_attach_ops mlx5_ib_dmabuf_attach_ops = {
1502 	.allow_peer2peer = 1,
1503 	.move_notify = mlx5_ib_dmabuf_invalidate_cb,
1504 };
1505 
1506 struct ib_mr *mlx5_ib_reg_user_mr_dmabuf(struct ib_pd *pd, u64 offset,
1507 					 u64 length, u64 virt_addr,
1508 					 int fd, int access_flags,
1509 					 struct ib_udata *udata)
1510 {
1511 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1512 	struct mlx5_ib_mr *mr = NULL;
1513 	struct ib_umem_dmabuf *umem_dmabuf;
1514 	int err;
1515 
1516 	if (!IS_ENABLED(CONFIG_INFINIBAND_USER_MEM) ||
1517 	    !IS_ENABLED(CONFIG_INFINIBAND_ON_DEMAND_PAGING))
1518 		return ERR_PTR(-EOPNOTSUPP);
1519 
1520 	mlx5_ib_dbg(dev,
1521 		    "offset 0x%llx, virt_addr 0x%llx, length 0x%llx, fd %d, access_flags 0x%x\n",
1522 		    offset, virt_addr, length, fd, access_flags);
1523 
1524 	/* dmabuf requires xlt update via umr to work. */
1525 	if (!mlx5r_umr_can_load_pas(dev, length))
1526 		return ERR_PTR(-EINVAL);
1527 
1528 	umem_dmabuf = ib_umem_dmabuf_get(&dev->ib_dev, offset, length, fd,
1529 					 access_flags,
1530 					 &mlx5_ib_dmabuf_attach_ops);
1531 	if (IS_ERR(umem_dmabuf)) {
1532 		mlx5_ib_dbg(dev, "umem_dmabuf get failed (%ld)\n",
1533 			    PTR_ERR(umem_dmabuf));
1534 		return ERR_CAST(umem_dmabuf);
1535 	}
1536 
1537 	mr = alloc_cacheable_mr(pd, &umem_dmabuf->umem, virt_addr,
1538 				access_flags);
1539 	if (IS_ERR(mr)) {
1540 		ib_umem_release(&umem_dmabuf->umem);
1541 		return ERR_CAST(mr);
1542 	}
1543 
1544 	mlx5_ib_dbg(dev, "mkey 0x%x\n", mr->mmkey.key);
1545 
1546 	atomic_add(ib_umem_num_pages(mr->umem), &dev->mdev->priv.reg_pages);
1547 	umem_dmabuf->private = mr;
1548 	err = mlx5r_store_odp_mkey(dev, &mr->mmkey);
1549 	if (err)
1550 		goto err_dereg_mr;
1551 
1552 	err = mlx5_ib_init_dmabuf_mr(mr);
1553 	if (err)
1554 		goto err_dereg_mr;
1555 	return &mr->ibmr;
1556 
1557 err_dereg_mr:
1558 	mlx5_ib_dereg_mr(&mr->ibmr, NULL);
1559 	return ERR_PTR(err);
1560 }
1561 
1562 /*
1563  * True if the change in access flags can be done via UMR, only some access
1564  * flags can be updated.
1565  */
1566 static bool can_use_umr_rereg_access(struct mlx5_ib_dev *dev,
1567 				     unsigned int current_access_flags,
1568 				     unsigned int target_access_flags)
1569 {
1570 	unsigned int diffs = current_access_flags ^ target_access_flags;
1571 
1572 	if (diffs & ~(IB_ACCESS_LOCAL_WRITE | IB_ACCESS_REMOTE_WRITE |
1573 		      IB_ACCESS_REMOTE_READ | IB_ACCESS_RELAXED_ORDERING))
1574 		return false;
1575 	return mlx5r_umr_can_reconfig(dev, current_access_flags,
1576 				      target_access_flags);
1577 }
1578 
1579 static bool can_use_umr_rereg_pas(struct mlx5_ib_mr *mr,
1580 				  struct ib_umem *new_umem,
1581 				  int new_access_flags, u64 iova,
1582 				  unsigned long *page_size)
1583 {
1584 	struct mlx5_ib_dev *dev = to_mdev(mr->ibmr.device);
1585 
1586 	/* We only track the allocated sizes of MRs from the cache */
1587 	if (!mr->mmkey.cache_ent)
1588 		return false;
1589 	if (!mlx5r_umr_can_load_pas(dev, new_umem->length))
1590 		return false;
1591 
1592 	*page_size =
1593 		mlx5_umem_find_best_pgsz(new_umem, mkc, log_page_size, 0, iova);
1594 	if (WARN_ON(!*page_size))
1595 		return false;
1596 	return (mr->mmkey.cache_ent->rb_key.ndescs) >=
1597 	       ib_umem_num_dma_blocks(new_umem, *page_size);
1598 }
1599 
1600 static int umr_rereg_pas(struct mlx5_ib_mr *mr, struct ib_pd *pd,
1601 			 int access_flags, int flags, struct ib_umem *new_umem,
1602 			 u64 iova, unsigned long page_size)
1603 {
1604 	struct mlx5_ib_dev *dev = to_mdev(mr->ibmr.device);
1605 	int upd_flags = MLX5_IB_UPD_XLT_ADDR | MLX5_IB_UPD_XLT_ENABLE;
1606 	struct ib_umem *old_umem = mr->umem;
1607 	int err;
1608 
1609 	/*
1610 	 * To keep everything simple the MR is revoked before we start to mess
1611 	 * with it. This ensure the change is atomic relative to any use of the
1612 	 * MR.
1613 	 */
1614 	err = mlx5r_umr_revoke_mr(mr);
1615 	if (err)
1616 		return err;
1617 
1618 	if (flags & IB_MR_REREG_PD) {
1619 		mr->ibmr.pd = pd;
1620 		upd_flags |= MLX5_IB_UPD_XLT_PD;
1621 	}
1622 	if (flags & IB_MR_REREG_ACCESS) {
1623 		mr->access_flags = access_flags;
1624 		upd_flags |= MLX5_IB_UPD_XLT_ACCESS;
1625 	}
1626 
1627 	mr->ibmr.iova = iova;
1628 	mr->ibmr.length = new_umem->length;
1629 	mr->page_shift = order_base_2(page_size);
1630 	mr->umem = new_umem;
1631 	err = mlx5r_umr_update_mr_pas(mr, upd_flags);
1632 	if (err) {
1633 		/*
1634 		 * The MR is revoked at this point so there is no issue to free
1635 		 * new_umem.
1636 		 */
1637 		mr->umem = old_umem;
1638 		return err;
1639 	}
1640 
1641 	atomic_sub(ib_umem_num_pages(old_umem), &dev->mdev->priv.reg_pages);
1642 	ib_umem_release(old_umem);
1643 	atomic_add(ib_umem_num_pages(new_umem), &dev->mdev->priv.reg_pages);
1644 	return 0;
1645 }
1646 
1647 struct ib_mr *mlx5_ib_rereg_user_mr(struct ib_mr *ib_mr, int flags, u64 start,
1648 				    u64 length, u64 iova, int new_access_flags,
1649 				    struct ib_pd *new_pd,
1650 				    struct ib_udata *udata)
1651 {
1652 	struct mlx5_ib_dev *dev = to_mdev(ib_mr->device);
1653 	struct mlx5_ib_mr *mr = to_mmr(ib_mr);
1654 	int err;
1655 
1656 	if (!IS_ENABLED(CONFIG_INFINIBAND_USER_MEM))
1657 		return ERR_PTR(-EOPNOTSUPP);
1658 
1659 	mlx5_ib_dbg(
1660 		dev,
1661 		"start 0x%llx, iova 0x%llx, length 0x%llx, access_flags 0x%x\n",
1662 		start, iova, length, new_access_flags);
1663 
1664 	if (flags & ~(IB_MR_REREG_TRANS | IB_MR_REREG_PD | IB_MR_REREG_ACCESS))
1665 		return ERR_PTR(-EOPNOTSUPP);
1666 
1667 	if (!(flags & IB_MR_REREG_ACCESS))
1668 		new_access_flags = mr->access_flags;
1669 	if (!(flags & IB_MR_REREG_PD))
1670 		new_pd = ib_mr->pd;
1671 
1672 	if (!(flags & IB_MR_REREG_TRANS)) {
1673 		struct ib_umem *umem;
1674 
1675 		/* Fast path for PD/access change */
1676 		if (can_use_umr_rereg_access(dev, mr->access_flags,
1677 					     new_access_flags)) {
1678 			err = mlx5r_umr_rereg_pd_access(mr, new_pd,
1679 							new_access_flags);
1680 			if (err)
1681 				return ERR_PTR(err);
1682 			return NULL;
1683 		}
1684 		/* DM or ODP MR's don't have a normal umem so we can't re-use it */
1685 		if (!mr->umem || is_odp_mr(mr) || is_dmabuf_mr(mr))
1686 			goto recreate;
1687 
1688 		/*
1689 		 * Only one active MR can refer to a umem at one time, revoke
1690 		 * the old MR before assigning the umem to the new one.
1691 		 */
1692 		err = mlx5r_umr_revoke_mr(mr);
1693 		if (err)
1694 			return ERR_PTR(err);
1695 		umem = mr->umem;
1696 		mr->umem = NULL;
1697 		atomic_sub(ib_umem_num_pages(umem), &dev->mdev->priv.reg_pages);
1698 
1699 		return create_real_mr(new_pd, umem, mr->ibmr.iova,
1700 				      new_access_flags);
1701 	}
1702 
1703 	/*
1704 	 * DM doesn't have a PAS list so we can't re-use it, odp/dmabuf does
1705 	 * but the logic around releasing the umem is different
1706 	 */
1707 	if (!mr->umem || is_odp_mr(mr) || is_dmabuf_mr(mr))
1708 		goto recreate;
1709 
1710 	if (!(new_access_flags & IB_ACCESS_ON_DEMAND) &&
1711 	    can_use_umr_rereg_access(dev, mr->access_flags, new_access_flags)) {
1712 		struct ib_umem *new_umem;
1713 		unsigned long page_size;
1714 
1715 		new_umem = ib_umem_get(&dev->ib_dev, start, length,
1716 				       new_access_flags);
1717 		if (IS_ERR(new_umem))
1718 			return ERR_CAST(new_umem);
1719 
1720 		/* Fast path for PAS change */
1721 		if (can_use_umr_rereg_pas(mr, new_umem, new_access_flags, iova,
1722 					  &page_size)) {
1723 			err = umr_rereg_pas(mr, new_pd, new_access_flags, flags,
1724 					    new_umem, iova, page_size);
1725 			if (err) {
1726 				ib_umem_release(new_umem);
1727 				return ERR_PTR(err);
1728 			}
1729 			return NULL;
1730 		}
1731 		return create_real_mr(new_pd, new_umem, iova, new_access_flags);
1732 	}
1733 
1734 	/*
1735 	 * Everything else has no state we can preserve, just create a new MR
1736 	 * from scratch
1737 	 */
1738 recreate:
1739 	return mlx5_ib_reg_user_mr(new_pd, start, length, iova,
1740 				   new_access_flags, udata);
1741 }
1742 
1743 static int
1744 mlx5_alloc_priv_descs(struct ib_device *device,
1745 		      struct mlx5_ib_mr *mr,
1746 		      int ndescs,
1747 		      int desc_size)
1748 {
1749 	struct mlx5_ib_dev *dev = to_mdev(device);
1750 	struct device *ddev = &dev->mdev->pdev->dev;
1751 	int size = ndescs * desc_size;
1752 	int add_size;
1753 	int ret;
1754 
1755 	add_size = max_t(int, MLX5_UMR_ALIGN - ARCH_KMALLOC_MINALIGN, 0);
1756 	if (is_power_of_2(MLX5_UMR_ALIGN) && add_size) {
1757 		int end = max_t(int, MLX5_UMR_ALIGN, roundup_pow_of_two(size));
1758 
1759 		add_size = min_t(int, end - size, add_size);
1760 	}
1761 
1762 	mr->descs_alloc = kzalloc(size + add_size, GFP_KERNEL);
1763 	if (!mr->descs_alloc)
1764 		return -ENOMEM;
1765 
1766 	mr->descs = PTR_ALIGN(mr->descs_alloc, MLX5_UMR_ALIGN);
1767 
1768 	mr->desc_map = dma_map_single(ddev, mr->descs, size, DMA_TO_DEVICE);
1769 	if (dma_mapping_error(ddev, mr->desc_map)) {
1770 		ret = -ENOMEM;
1771 		goto err;
1772 	}
1773 
1774 	return 0;
1775 err:
1776 	kfree(mr->descs_alloc);
1777 
1778 	return ret;
1779 }
1780 
1781 static void
1782 mlx5_free_priv_descs(struct mlx5_ib_mr *mr)
1783 {
1784 	if (!mr->umem && mr->descs) {
1785 		struct ib_device *device = mr->ibmr.device;
1786 		int size = mr->max_descs * mr->desc_size;
1787 		struct mlx5_ib_dev *dev = to_mdev(device);
1788 
1789 		dma_unmap_single(&dev->mdev->pdev->dev, mr->desc_map, size,
1790 				 DMA_TO_DEVICE);
1791 		kfree(mr->descs_alloc);
1792 		mr->descs = NULL;
1793 	}
1794 }
1795 
1796 static int cache_ent_find_and_store(struct mlx5_ib_dev *dev,
1797 				    struct mlx5_ib_mr *mr)
1798 {
1799 	struct mlx5_mkey_cache *cache = &dev->cache;
1800 	struct mlx5_cache_ent *ent;
1801 	int ret;
1802 
1803 	if (mr->mmkey.cache_ent) {
1804 		spin_lock_irq(&mr->mmkey.cache_ent->mkeys_queue.lock);
1805 		mr->mmkey.cache_ent->in_use--;
1806 		goto end;
1807 	}
1808 
1809 	mutex_lock(&cache->rb_lock);
1810 	ent = mkey_cache_ent_from_rb_key(dev, mr->mmkey.rb_key);
1811 	if (ent) {
1812 		if (ent->rb_key.ndescs == mr->mmkey.rb_key.ndescs) {
1813 			if (ent->disabled) {
1814 				mutex_unlock(&cache->rb_lock);
1815 				return -EOPNOTSUPP;
1816 			}
1817 			mr->mmkey.cache_ent = ent;
1818 			spin_lock_irq(&mr->mmkey.cache_ent->mkeys_queue.lock);
1819 			mutex_unlock(&cache->rb_lock);
1820 			goto end;
1821 		}
1822 	}
1823 
1824 	ent = mlx5r_cache_create_ent_locked(dev, mr->mmkey.rb_key, false);
1825 	mutex_unlock(&cache->rb_lock);
1826 	if (IS_ERR(ent))
1827 		return PTR_ERR(ent);
1828 
1829 	mr->mmkey.cache_ent = ent;
1830 	spin_lock_irq(&mr->mmkey.cache_ent->mkeys_queue.lock);
1831 
1832 end:
1833 	ret = push_mkey_locked(mr->mmkey.cache_ent, mr->mmkey.key);
1834 	spin_unlock_irq(&mr->mmkey.cache_ent->mkeys_queue.lock);
1835 	return ret;
1836 }
1837 
1838 int mlx5_ib_dereg_mr(struct ib_mr *ibmr, struct ib_udata *udata)
1839 {
1840 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
1841 	struct mlx5_ib_dev *dev = to_mdev(ibmr->device);
1842 	int rc;
1843 
1844 	/*
1845 	 * Any async use of the mr must hold the refcount, once the refcount
1846 	 * goes to zero no other thread, such as ODP page faults, prefetch, any
1847 	 * UMR activity, etc can touch the mkey. Thus it is safe to destroy it.
1848 	 */
1849 	if (IS_ENABLED(CONFIG_INFINIBAND_ON_DEMAND_PAGING) &&
1850 	    refcount_read(&mr->mmkey.usecount) != 0 &&
1851 	    xa_erase(&mr_to_mdev(mr)->odp_mkeys, mlx5_base_mkey(mr->mmkey.key)))
1852 		mlx5r_deref_wait_odp_mkey(&mr->mmkey);
1853 
1854 	if (ibmr->type == IB_MR_TYPE_INTEGRITY) {
1855 		xa_cmpxchg(&dev->sig_mrs, mlx5_base_mkey(mr->mmkey.key),
1856 			   mr->sig, NULL, GFP_KERNEL);
1857 
1858 		if (mr->mtt_mr) {
1859 			rc = mlx5_ib_dereg_mr(&mr->mtt_mr->ibmr, NULL);
1860 			if (rc)
1861 				return rc;
1862 			mr->mtt_mr = NULL;
1863 		}
1864 		if (mr->klm_mr) {
1865 			rc = mlx5_ib_dereg_mr(&mr->klm_mr->ibmr, NULL);
1866 			if (rc)
1867 				return rc;
1868 			mr->klm_mr = NULL;
1869 		}
1870 
1871 		if (mlx5_core_destroy_psv(dev->mdev,
1872 					  mr->sig->psv_memory.psv_idx))
1873 			mlx5_ib_warn(dev, "failed to destroy mem psv %d\n",
1874 				     mr->sig->psv_memory.psv_idx);
1875 		if (mlx5_core_destroy_psv(dev->mdev, mr->sig->psv_wire.psv_idx))
1876 			mlx5_ib_warn(dev, "failed to destroy wire psv %d\n",
1877 				     mr->sig->psv_wire.psv_idx);
1878 		kfree(mr->sig);
1879 		mr->sig = NULL;
1880 	}
1881 
1882 	/* Stop DMA */
1883 	if (mr->umem && mlx5r_umr_can_load_pas(dev, mr->umem->length))
1884 		if (mlx5r_umr_revoke_mr(mr) ||
1885 		    cache_ent_find_and_store(dev, mr))
1886 			mr->mmkey.cache_ent = NULL;
1887 
1888 	if (!mr->mmkey.cache_ent) {
1889 		rc = destroy_mkey(to_mdev(mr->ibmr.device), mr);
1890 		if (rc)
1891 			return rc;
1892 	}
1893 
1894 	if (mr->umem) {
1895 		bool is_odp = is_odp_mr(mr);
1896 
1897 		if (!is_odp)
1898 			atomic_sub(ib_umem_num_pages(mr->umem),
1899 				   &dev->mdev->priv.reg_pages);
1900 		ib_umem_release(mr->umem);
1901 		if (is_odp)
1902 			mlx5_ib_free_odp_mr(mr);
1903 	}
1904 
1905 	if (!mr->mmkey.cache_ent)
1906 		mlx5_free_priv_descs(mr);
1907 
1908 	kfree(mr);
1909 	return 0;
1910 }
1911 
1912 static void mlx5_set_umr_free_mkey(struct ib_pd *pd, u32 *in, int ndescs,
1913 				   int access_mode, int page_shift)
1914 {
1915 	void *mkc;
1916 
1917 	mkc = MLX5_ADDR_OF(create_mkey_in, in, memory_key_mkey_entry);
1918 
1919 	/* This is only used from the kernel, so setting the PD is OK. */
1920 	set_mkc_access_pd_addr_fields(mkc, IB_ACCESS_RELAXED_ORDERING, 0, pd);
1921 	MLX5_SET(mkc, mkc, free, 1);
1922 	MLX5_SET(mkc, mkc, translations_octword_size, ndescs);
1923 	MLX5_SET(mkc, mkc, access_mode_1_0, access_mode & 0x3);
1924 	MLX5_SET(mkc, mkc, access_mode_4_2, (access_mode >> 2) & 0x7);
1925 	MLX5_SET(mkc, mkc, umr_en, 1);
1926 	MLX5_SET(mkc, mkc, log_page_size, page_shift);
1927 }
1928 
1929 static int _mlx5_alloc_mkey_descs(struct ib_pd *pd, struct mlx5_ib_mr *mr,
1930 				  int ndescs, int desc_size, int page_shift,
1931 				  int access_mode, u32 *in, int inlen)
1932 {
1933 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1934 	int err;
1935 
1936 	mr->access_mode = access_mode;
1937 	mr->desc_size = desc_size;
1938 	mr->max_descs = ndescs;
1939 
1940 	err = mlx5_alloc_priv_descs(pd->device, mr, ndescs, desc_size);
1941 	if (err)
1942 		return err;
1943 
1944 	mlx5_set_umr_free_mkey(pd, in, ndescs, access_mode, page_shift);
1945 
1946 	err = mlx5_ib_create_mkey(dev, &mr->mmkey, in, inlen);
1947 	if (err)
1948 		goto err_free_descs;
1949 
1950 	mr->mmkey.type = MLX5_MKEY_MR;
1951 	mr->ibmr.lkey = mr->mmkey.key;
1952 	mr->ibmr.rkey = mr->mmkey.key;
1953 
1954 	return 0;
1955 
1956 err_free_descs:
1957 	mlx5_free_priv_descs(mr);
1958 	return err;
1959 }
1960 
1961 static struct mlx5_ib_mr *mlx5_ib_alloc_pi_mr(struct ib_pd *pd,
1962 				u32 max_num_sg, u32 max_num_meta_sg,
1963 				int desc_size, int access_mode)
1964 {
1965 	int inlen = MLX5_ST_SZ_BYTES(create_mkey_in);
1966 	int ndescs = ALIGN(max_num_sg + max_num_meta_sg, 4);
1967 	int page_shift = 0;
1968 	struct mlx5_ib_mr *mr;
1969 	u32 *in;
1970 	int err;
1971 
1972 	mr = kzalloc(sizeof(*mr), GFP_KERNEL);
1973 	if (!mr)
1974 		return ERR_PTR(-ENOMEM);
1975 
1976 	mr->ibmr.pd = pd;
1977 	mr->ibmr.device = pd->device;
1978 
1979 	in = kzalloc(inlen, GFP_KERNEL);
1980 	if (!in) {
1981 		err = -ENOMEM;
1982 		goto err_free;
1983 	}
1984 
1985 	if (access_mode == MLX5_MKC_ACCESS_MODE_MTT)
1986 		page_shift = PAGE_SHIFT;
1987 
1988 	err = _mlx5_alloc_mkey_descs(pd, mr, ndescs, desc_size, page_shift,
1989 				     access_mode, in, inlen);
1990 	if (err)
1991 		goto err_free_in;
1992 
1993 	mr->umem = NULL;
1994 	kfree(in);
1995 
1996 	return mr;
1997 
1998 err_free_in:
1999 	kfree(in);
2000 err_free:
2001 	kfree(mr);
2002 	return ERR_PTR(err);
2003 }
2004 
2005 static int mlx5_alloc_mem_reg_descs(struct ib_pd *pd, struct mlx5_ib_mr *mr,
2006 				    int ndescs, u32 *in, int inlen)
2007 {
2008 	return _mlx5_alloc_mkey_descs(pd, mr, ndescs, sizeof(struct mlx5_mtt),
2009 				      PAGE_SHIFT, MLX5_MKC_ACCESS_MODE_MTT, in,
2010 				      inlen);
2011 }
2012 
2013 static int mlx5_alloc_sg_gaps_descs(struct ib_pd *pd, struct mlx5_ib_mr *mr,
2014 				    int ndescs, u32 *in, int inlen)
2015 {
2016 	return _mlx5_alloc_mkey_descs(pd, mr, ndescs, sizeof(struct mlx5_klm),
2017 				      0, MLX5_MKC_ACCESS_MODE_KLMS, in, inlen);
2018 }
2019 
2020 static int mlx5_alloc_integrity_descs(struct ib_pd *pd, struct mlx5_ib_mr *mr,
2021 				      int max_num_sg, int max_num_meta_sg,
2022 				      u32 *in, int inlen)
2023 {
2024 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
2025 	u32 psv_index[2];
2026 	void *mkc;
2027 	int err;
2028 
2029 	mr->sig = kzalloc(sizeof(*mr->sig), GFP_KERNEL);
2030 	if (!mr->sig)
2031 		return -ENOMEM;
2032 
2033 	/* create mem & wire PSVs */
2034 	err = mlx5_core_create_psv(dev->mdev, to_mpd(pd)->pdn, 2, psv_index);
2035 	if (err)
2036 		goto err_free_sig;
2037 
2038 	mr->sig->psv_memory.psv_idx = psv_index[0];
2039 	mr->sig->psv_wire.psv_idx = psv_index[1];
2040 
2041 	mr->sig->sig_status_checked = true;
2042 	mr->sig->sig_err_exists = false;
2043 	/* Next UMR, Arm SIGERR */
2044 	++mr->sig->sigerr_count;
2045 	mr->klm_mr = mlx5_ib_alloc_pi_mr(pd, max_num_sg, max_num_meta_sg,
2046 					 sizeof(struct mlx5_klm),
2047 					 MLX5_MKC_ACCESS_MODE_KLMS);
2048 	if (IS_ERR(mr->klm_mr)) {
2049 		err = PTR_ERR(mr->klm_mr);
2050 		goto err_destroy_psv;
2051 	}
2052 	mr->mtt_mr = mlx5_ib_alloc_pi_mr(pd, max_num_sg, max_num_meta_sg,
2053 					 sizeof(struct mlx5_mtt),
2054 					 MLX5_MKC_ACCESS_MODE_MTT);
2055 	if (IS_ERR(mr->mtt_mr)) {
2056 		err = PTR_ERR(mr->mtt_mr);
2057 		goto err_free_klm_mr;
2058 	}
2059 
2060 	/* Set bsf descriptors for mkey */
2061 	mkc = MLX5_ADDR_OF(create_mkey_in, in, memory_key_mkey_entry);
2062 	MLX5_SET(mkc, mkc, bsf_en, 1);
2063 	MLX5_SET(mkc, mkc, bsf_octword_size, MLX5_MKEY_BSF_OCTO_SIZE);
2064 
2065 	err = _mlx5_alloc_mkey_descs(pd, mr, 4, sizeof(struct mlx5_klm), 0,
2066 				     MLX5_MKC_ACCESS_MODE_KLMS, in, inlen);
2067 	if (err)
2068 		goto err_free_mtt_mr;
2069 
2070 	err = xa_err(xa_store(&dev->sig_mrs, mlx5_base_mkey(mr->mmkey.key),
2071 			      mr->sig, GFP_KERNEL));
2072 	if (err)
2073 		goto err_free_descs;
2074 	return 0;
2075 
2076 err_free_descs:
2077 	destroy_mkey(dev, mr);
2078 	mlx5_free_priv_descs(mr);
2079 err_free_mtt_mr:
2080 	mlx5_ib_dereg_mr(&mr->mtt_mr->ibmr, NULL);
2081 	mr->mtt_mr = NULL;
2082 err_free_klm_mr:
2083 	mlx5_ib_dereg_mr(&mr->klm_mr->ibmr, NULL);
2084 	mr->klm_mr = NULL;
2085 err_destroy_psv:
2086 	if (mlx5_core_destroy_psv(dev->mdev, mr->sig->psv_memory.psv_idx))
2087 		mlx5_ib_warn(dev, "failed to destroy mem psv %d\n",
2088 			     mr->sig->psv_memory.psv_idx);
2089 	if (mlx5_core_destroy_psv(dev->mdev, mr->sig->psv_wire.psv_idx))
2090 		mlx5_ib_warn(dev, "failed to destroy wire psv %d\n",
2091 			     mr->sig->psv_wire.psv_idx);
2092 err_free_sig:
2093 	kfree(mr->sig);
2094 
2095 	return err;
2096 }
2097 
2098 static struct ib_mr *__mlx5_ib_alloc_mr(struct ib_pd *pd,
2099 					enum ib_mr_type mr_type, u32 max_num_sg,
2100 					u32 max_num_meta_sg)
2101 {
2102 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
2103 	int inlen = MLX5_ST_SZ_BYTES(create_mkey_in);
2104 	int ndescs = ALIGN(max_num_sg, 4);
2105 	struct mlx5_ib_mr *mr;
2106 	u32 *in;
2107 	int err;
2108 
2109 	mr = kzalloc(sizeof(*mr), GFP_KERNEL);
2110 	if (!mr)
2111 		return ERR_PTR(-ENOMEM);
2112 
2113 	in = kzalloc(inlen, GFP_KERNEL);
2114 	if (!in) {
2115 		err = -ENOMEM;
2116 		goto err_free;
2117 	}
2118 
2119 	mr->ibmr.device = pd->device;
2120 	mr->umem = NULL;
2121 
2122 	switch (mr_type) {
2123 	case IB_MR_TYPE_MEM_REG:
2124 		err = mlx5_alloc_mem_reg_descs(pd, mr, ndescs, in, inlen);
2125 		break;
2126 	case IB_MR_TYPE_SG_GAPS:
2127 		err = mlx5_alloc_sg_gaps_descs(pd, mr, ndescs, in, inlen);
2128 		break;
2129 	case IB_MR_TYPE_INTEGRITY:
2130 		err = mlx5_alloc_integrity_descs(pd, mr, max_num_sg,
2131 						 max_num_meta_sg, in, inlen);
2132 		break;
2133 	default:
2134 		mlx5_ib_warn(dev, "Invalid mr type %d\n", mr_type);
2135 		err = -EINVAL;
2136 	}
2137 
2138 	if (err)
2139 		goto err_free_in;
2140 
2141 	kfree(in);
2142 
2143 	return &mr->ibmr;
2144 
2145 err_free_in:
2146 	kfree(in);
2147 err_free:
2148 	kfree(mr);
2149 	return ERR_PTR(err);
2150 }
2151 
2152 struct ib_mr *mlx5_ib_alloc_mr(struct ib_pd *pd, enum ib_mr_type mr_type,
2153 			       u32 max_num_sg)
2154 {
2155 	return __mlx5_ib_alloc_mr(pd, mr_type, max_num_sg, 0);
2156 }
2157 
2158 struct ib_mr *mlx5_ib_alloc_mr_integrity(struct ib_pd *pd,
2159 					 u32 max_num_sg, u32 max_num_meta_sg)
2160 {
2161 	return __mlx5_ib_alloc_mr(pd, IB_MR_TYPE_INTEGRITY, max_num_sg,
2162 				  max_num_meta_sg);
2163 }
2164 
2165 int mlx5_ib_alloc_mw(struct ib_mw *ibmw, struct ib_udata *udata)
2166 {
2167 	struct mlx5_ib_dev *dev = to_mdev(ibmw->device);
2168 	int inlen = MLX5_ST_SZ_BYTES(create_mkey_in);
2169 	struct mlx5_ib_mw *mw = to_mmw(ibmw);
2170 	unsigned int ndescs;
2171 	u32 *in = NULL;
2172 	void *mkc;
2173 	int err;
2174 	struct mlx5_ib_alloc_mw req = {};
2175 	struct {
2176 		__u32	comp_mask;
2177 		__u32	response_length;
2178 	} resp = {};
2179 
2180 	err = ib_copy_from_udata(&req, udata, min(udata->inlen, sizeof(req)));
2181 	if (err)
2182 		return err;
2183 
2184 	if (req.comp_mask || req.reserved1 || req.reserved2)
2185 		return -EOPNOTSUPP;
2186 
2187 	if (udata->inlen > sizeof(req) &&
2188 	    !ib_is_udata_cleared(udata, sizeof(req),
2189 				 udata->inlen - sizeof(req)))
2190 		return -EOPNOTSUPP;
2191 
2192 	ndescs = req.num_klms ? roundup(req.num_klms, 4) : roundup(1, 4);
2193 
2194 	in = kzalloc(inlen, GFP_KERNEL);
2195 	if (!in)
2196 		return -ENOMEM;
2197 
2198 	mkc = MLX5_ADDR_OF(create_mkey_in, in, memory_key_mkey_entry);
2199 
2200 	MLX5_SET(mkc, mkc, free, 1);
2201 	MLX5_SET(mkc, mkc, translations_octword_size, ndescs);
2202 	MLX5_SET(mkc, mkc, pd, to_mpd(ibmw->pd)->pdn);
2203 	MLX5_SET(mkc, mkc, umr_en, 1);
2204 	MLX5_SET(mkc, mkc, lr, 1);
2205 	MLX5_SET(mkc, mkc, access_mode_1_0, MLX5_MKC_ACCESS_MODE_KLMS);
2206 	MLX5_SET(mkc, mkc, en_rinval, !!((ibmw->type == IB_MW_TYPE_2)));
2207 	MLX5_SET(mkc, mkc, qpn, 0xffffff);
2208 
2209 	err = mlx5_ib_create_mkey(dev, &mw->mmkey, in, inlen);
2210 	if (err)
2211 		goto free;
2212 
2213 	mw->mmkey.type = MLX5_MKEY_MW;
2214 	ibmw->rkey = mw->mmkey.key;
2215 	mw->mmkey.ndescs = ndescs;
2216 
2217 	resp.response_length =
2218 		min(offsetofend(typeof(resp), response_length), udata->outlen);
2219 	if (resp.response_length) {
2220 		err = ib_copy_to_udata(udata, &resp, resp.response_length);
2221 		if (err)
2222 			goto free_mkey;
2223 	}
2224 
2225 	if (IS_ENABLED(CONFIG_INFINIBAND_ON_DEMAND_PAGING)) {
2226 		err = mlx5r_store_odp_mkey(dev, &mw->mmkey);
2227 		if (err)
2228 			goto free_mkey;
2229 	}
2230 
2231 	kfree(in);
2232 	return 0;
2233 
2234 free_mkey:
2235 	mlx5_core_destroy_mkey(dev->mdev, mw->mmkey.key);
2236 free:
2237 	kfree(in);
2238 	return err;
2239 }
2240 
2241 int mlx5_ib_dealloc_mw(struct ib_mw *mw)
2242 {
2243 	struct mlx5_ib_dev *dev = to_mdev(mw->device);
2244 	struct mlx5_ib_mw *mmw = to_mmw(mw);
2245 
2246 	if (IS_ENABLED(CONFIG_INFINIBAND_ON_DEMAND_PAGING) &&
2247 	    xa_erase(&dev->odp_mkeys, mlx5_base_mkey(mmw->mmkey.key)))
2248 		/*
2249 		 * pagefault_single_data_segment() may be accessing mmw
2250 		 * if the user bound an ODP MR to this MW.
2251 		 */
2252 		mlx5r_deref_wait_odp_mkey(&mmw->mmkey);
2253 
2254 	return mlx5_core_destroy_mkey(dev->mdev, mmw->mmkey.key);
2255 }
2256 
2257 int mlx5_ib_check_mr_status(struct ib_mr *ibmr, u32 check_mask,
2258 			    struct ib_mr_status *mr_status)
2259 {
2260 	struct mlx5_ib_mr *mmr = to_mmr(ibmr);
2261 	int ret = 0;
2262 
2263 	if (check_mask & ~IB_MR_CHECK_SIG_STATUS) {
2264 		pr_err("Invalid status check mask\n");
2265 		ret = -EINVAL;
2266 		goto done;
2267 	}
2268 
2269 	mr_status->fail_status = 0;
2270 	if (check_mask & IB_MR_CHECK_SIG_STATUS) {
2271 		if (!mmr->sig) {
2272 			ret = -EINVAL;
2273 			pr_err("signature status check requested on a non-signature enabled MR\n");
2274 			goto done;
2275 		}
2276 
2277 		mmr->sig->sig_status_checked = true;
2278 		if (!mmr->sig->sig_err_exists)
2279 			goto done;
2280 
2281 		if (ibmr->lkey == mmr->sig->err_item.key)
2282 			memcpy(&mr_status->sig_err, &mmr->sig->err_item,
2283 			       sizeof(mr_status->sig_err));
2284 		else {
2285 			mr_status->sig_err.err_type = IB_SIG_BAD_GUARD;
2286 			mr_status->sig_err.sig_err_offset = 0;
2287 			mr_status->sig_err.key = mmr->sig->err_item.key;
2288 		}
2289 
2290 		mmr->sig->sig_err_exists = false;
2291 		mr_status->fail_status |= IB_MR_CHECK_SIG_STATUS;
2292 	}
2293 
2294 done:
2295 	return ret;
2296 }
2297 
2298 static int
2299 mlx5_ib_map_pa_mr_sg_pi(struct ib_mr *ibmr, struct scatterlist *data_sg,
2300 			int data_sg_nents, unsigned int *data_sg_offset,
2301 			struct scatterlist *meta_sg, int meta_sg_nents,
2302 			unsigned int *meta_sg_offset)
2303 {
2304 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
2305 	unsigned int sg_offset = 0;
2306 	int n = 0;
2307 
2308 	mr->meta_length = 0;
2309 	if (data_sg_nents == 1) {
2310 		n++;
2311 		mr->mmkey.ndescs = 1;
2312 		if (data_sg_offset)
2313 			sg_offset = *data_sg_offset;
2314 		mr->data_length = sg_dma_len(data_sg) - sg_offset;
2315 		mr->data_iova = sg_dma_address(data_sg) + sg_offset;
2316 		if (meta_sg_nents == 1) {
2317 			n++;
2318 			mr->meta_ndescs = 1;
2319 			if (meta_sg_offset)
2320 				sg_offset = *meta_sg_offset;
2321 			else
2322 				sg_offset = 0;
2323 			mr->meta_length = sg_dma_len(meta_sg) - sg_offset;
2324 			mr->pi_iova = sg_dma_address(meta_sg) + sg_offset;
2325 		}
2326 		ibmr->length = mr->data_length + mr->meta_length;
2327 	}
2328 
2329 	return n;
2330 }
2331 
2332 static int
2333 mlx5_ib_sg_to_klms(struct mlx5_ib_mr *mr,
2334 		   struct scatterlist *sgl,
2335 		   unsigned short sg_nents,
2336 		   unsigned int *sg_offset_p,
2337 		   struct scatterlist *meta_sgl,
2338 		   unsigned short meta_sg_nents,
2339 		   unsigned int *meta_sg_offset_p)
2340 {
2341 	struct scatterlist *sg = sgl;
2342 	struct mlx5_klm *klms = mr->descs;
2343 	unsigned int sg_offset = sg_offset_p ? *sg_offset_p : 0;
2344 	u32 lkey = mr->ibmr.pd->local_dma_lkey;
2345 	int i, j = 0;
2346 
2347 	mr->ibmr.iova = sg_dma_address(sg) + sg_offset;
2348 	mr->ibmr.length = 0;
2349 
2350 	for_each_sg(sgl, sg, sg_nents, i) {
2351 		if (unlikely(i >= mr->max_descs))
2352 			break;
2353 		klms[i].va = cpu_to_be64(sg_dma_address(sg) + sg_offset);
2354 		klms[i].bcount = cpu_to_be32(sg_dma_len(sg) - sg_offset);
2355 		klms[i].key = cpu_to_be32(lkey);
2356 		mr->ibmr.length += sg_dma_len(sg) - sg_offset;
2357 
2358 		sg_offset = 0;
2359 	}
2360 
2361 	if (sg_offset_p)
2362 		*sg_offset_p = sg_offset;
2363 
2364 	mr->mmkey.ndescs = i;
2365 	mr->data_length = mr->ibmr.length;
2366 
2367 	if (meta_sg_nents) {
2368 		sg = meta_sgl;
2369 		sg_offset = meta_sg_offset_p ? *meta_sg_offset_p : 0;
2370 		for_each_sg(meta_sgl, sg, meta_sg_nents, j) {
2371 			if (unlikely(i + j >= mr->max_descs))
2372 				break;
2373 			klms[i + j].va = cpu_to_be64(sg_dma_address(sg) +
2374 						     sg_offset);
2375 			klms[i + j].bcount = cpu_to_be32(sg_dma_len(sg) -
2376 							 sg_offset);
2377 			klms[i + j].key = cpu_to_be32(lkey);
2378 			mr->ibmr.length += sg_dma_len(sg) - sg_offset;
2379 
2380 			sg_offset = 0;
2381 		}
2382 		if (meta_sg_offset_p)
2383 			*meta_sg_offset_p = sg_offset;
2384 
2385 		mr->meta_ndescs = j;
2386 		mr->meta_length = mr->ibmr.length - mr->data_length;
2387 	}
2388 
2389 	return i + j;
2390 }
2391 
2392 static int mlx5_set_page(struct ib_mr *ibmr, u64 addr)
2393 {
2394 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
2395 	__be64 *descs;
2396 
2397 	if (unlikely(mr->mmkey.ndescs == mr->max_descs))
2398 		return -ENOMEM;
2399 
2400 	descs = mr->descs;
2401 	descs[mr->mmkey.ndescs++] = cpu_to_be64(addr | MLX5_EN_RD | MLX5_EN_WR);
2402 
2403 	return 0;
2404 }
2405 
2406 static int mlx5_set_page_pi(struct ib_mr *ibmr, u64 addr)
2407 {
2408 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
2409 	__be64 *descs;
2410 
2411 	if (unlikely(mr->mmkey.ndescs + mr->meta_ndescs == mr->max_descs))
2412 		return -ENOMEM;
2413 
2414 	descs = mr->descs;
2415 	descs[mr->mmkey.ndescs + mr->meta_ndescs++] =
2416 		cpu_to_be64(addr | MLX5_EN_RD | MLX5_EN_WR);
2417 
2418 	return 0;
2419 }
2420 
2421 static int
2422 mlx5_ib_map_mtt_mr_sg_pi(struct ib_mr *ibmr, struct scatterlist *data_sg,
2423 			 int data_sg_nents, unsigned int *data_sg_offset,
2424 			 struct scatterlist *meta_sg, int meta_sg_nents,
2425 			 unsigned int *meta_sg_offset)
2426 {
2427 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
2428 	struct mlx5_ib_mr *pi_mr = mr->mtt_mr;
2429 	int n;
2430 
2431 	pi_mr->mmkey.ndescs = 0;
2432 	pi_mr->meta_ndescs = 0;
2433 	pi_mr->meta_length = 0;
2434 
2435 	ib_dma_sync_single_for_cpu(ibmr->device, pi_mr->desc_map,
2436 				   pi_mr->desc_size * pi_mr->max_descs,
2437 				   DMA_TO_DEVICE);
2438 
2439 	pi_mr->ibmr.page_size = ibmr->page_size;
2440 	n = ib_sg_to_pages(&pi_mr->ibmr, data_sg, data_sg_nents, data_sg_offset,
2441 			   mlx5_set_page);
2442 	if (n != data_sg_nents)
2443 		return n;
2444 
2445 	pi_mr->data_iova = pi_mr->ibmr.iova;
2446 	pi_mr->data_length = pi_mr->ibmr.length;
2447 	pi_mr->ibmr.length = pi_mr->data_length;
2448 	ibmr->length = pi_mr->data_length;
2449 
2450 	if (meta_sg_nents) {
2451 		u64 page_mask = ~((u64)ibmr->page_size - 1);
2452 		u64 iova = pi_mr->data_iova;
2453 
2454 		n += ib_sg_to_pages(&pi_mr->ibmr, meta_sg, meta_sg_nents,
2455 				    meta_sg_offset, mlx5_set_page_pi);
2456 
2457 		pi_mr->meta_length = pi_mr->ibmr.length;
2458 		/*
2459 		 * PI address for the HW is the offset of the metadata address
2460 		 * relative to the first data page address.
2461 		 * It equals to first data page address + size of data pages +
2462 		 * metadata offset at the first metadata page
2463 		 */
2464 		pi_mr->pi_iova = (iova & page_mask) +
2465 				 pi_mr->mmkey.ndescs * ibmr->page_size +
2466 				 (pi_mr->ibmr.iova & ~page_mask);
2467 		/*
2468 		 * In order to use one MTT MR for data and metadata, we register
2469 		 * also the gaps between the end of the data and the start of
2470 		 * the metadata (the sig MR will verify that the HW will access
2471 		 * to right addresses). This mapping is safe because we use
2472 		 * internal mkey for the registration.
2473 		 */
2474 		pi_mr->ibmr.length = pi_mr->pi_iova + pi_mr->meta_length - iova;
2475 		pi_mr->ibmr.iova = iova;
2476 		ibmr->length += pi_mr->meta_length;
2477 	}
2478 
2479 	ib_dma_sync_single_for_device(ibmr->device, pi_mr->desc_map,
2480 				      pi_mr->desc_size * pi_mr->max_descs,
2481 				      DMA_TO_DEVICE);
2482 
2483 	return n;
2484 }
2485 
2486 static int
2487 mlx5_ib_map_klm_mr_sg_pi(struct ib_mr *ibmr, struct scatterlist *data_sg,
2488 			 int data_sg_nents, unsigned int *data_sg_offset,
2489 			 struct scatterlist *meta_sg, int meta_sg_nents,
2490 			 unsigned int *meta_sg_offset)
2491 {
2492 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
2493 	struct mlx5_ib_mr *pi_mr = mr->klm_mr;
2494 	int n;
2495 
2496 	pi_mr->mmkey.ndescs = 0;
2497 	pi_mr->meta_ndescs = 0;
2498 	pi_mr->meta_length = 0;
2499 
2500 	ib_dma_sync_single_for_cpu(ibmr->device, pi_mr->desc_map,
2501 				   pi_mr->desc_size * pi_mr->max_descs,
2502 				   DMA_TO_DEVICE);
2503 
2504 	n = mlx5_ib_sg_to_klms(pi_mr, data_sg, data_sg_nents, data_sg_offset,
2505 			       meta_sg, meta_sg_nents, meta_sg_offset);
2506 
2507 	ib_dma_sync_single_for_device(ibmr->device, pi_mr->desc_map,
2508 				      pi_mr->desc_size * pi_mr->max_descs,
2509 				      DMA_TO_DEVICE);
2510 
2511 	/* This is zero-based memory region */
2512 	pi_mr->data_iova = 0;
2513 	pi_mr->ibmr.iova = 0;
2514 	pi_mr->pi_iova = pi_mr->data_length;
2515 	ibmr->length = pi_mr->ibmr.length;
2516 
2517 	return n;
2518 }
2519 
2520 int mlx5_ib_map_mr_sg_pi(struct ib_mr *ibmr, struct scatterlist *data_sg,
2521 			 int data_sg_nents, unsigned int *data_sg_offset,
2522 			 struct scatterlist *meta_sg, int meta_sg_nents,
2523 			 unsigned int *meta_sg_offset)
2524 {
2525 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
2526 	struct mlx5_ib_mr *pi_mr = NULL;
2527 	int n;
2528 
2529 	WARN_ON(ibmr->type != IB_MR_TYPE_INTEGRITY);
2530 
2531 	mr->mmkey.ndescs = 0;
2532 	mr->data_length = 0;
2533 	mr->data_iova = 0;
2534 	mr->meta_ndescs = 0;
2535 	mr->pi_iova = 0;
2536 	/*
2537 	 * As a performance optimization, if possible, there is no need to
2538 	 * perform UMR operation to register the data/metadata buffers.
2539 	 * First try to map the sg lists to PA descriptors with local_dma_lkey.
2540 	 * Fallback to UMR only in case of a failure.
2541 	 */
2542 	n = mlx5_ib_map_pa_mr_sg_pi(ibmr, data_sg, data_sg_nents,
2543 				    data_sg_offset, meta_sg, meta_sg_nents,
2544 				    meta_sg_offset);
2545 	if (n == data_sg_nents + meta_sg_nents)
2546 		goto out;
2547 	/*
2548 	 * As a performance optimization, if possible, there is no need to map
2549 	 * the sg lists to KLM descriptors. First try to map the sg lists to MTT
2550 	 * descriptors and fallback to KLM only in case of a failure.
2551 	 * It's more efficient for the HW to work with MTT descriptors
2552 	 * (especially in high load).
2553 	 * Use KLM (indirect access) only if it's mandatory.
2554 	 */
2555 	pi_mr = mr->mtt_mr;
2556 	n = mlx5_ib_map_mtt_mr_sg_pi(ibmr, data_sg, data_sg_nents,
2557 				     data_sg_offset, meta_sg, meta_sg_nents,
2558 				     meta_sg_offset);
2559 	if (n == data_sg_nents + meta_sg_nents)
2560 		goto out;
2561 
2562 	pi_mr = mr->klm_mr;
2563 	n = mlx5_ib_map_klm_mr_sg_pi(ibmr, data_sg, data_sg_nents,
2564 				     data_sg_offset, meta_sg, meta_sg_nents,
2565 				     meta_sg_offset);
2566 	if (unlikely(n != data_sg_nents + meta_sg_nents))
2567 		return -ENOMEM;
2568 
2569 out:
2570 	/* This is zero-based memory region */
2571 	ibmr->iova = 0;
2572 	mr->pi_mr = pi_mr;
2573 	if (pi_mr)
2574 		ibmr->sig_attrs->meta_length = pi_mr->meta_length;
2575 	else
2576 		ibmr->sig_attrs->meta_length = mr->meta_length;
2577 
2578 	return 0;
2579 }
2580 
2581 int mlx5_ib_map_mr_sg(struct ib_mr *ibmr, struct scatterlist *sg, int sg_nents,
2582 		      unsigned int *sg_offset)
2583 {
2584 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
2585 	int n;
2586 
2587 	mr->mmkey.ndescs = 0;
2588 
2589 	ib_dma_sync_single_for_cpu(ibmr->device, mr->desc_map,
2590 				   mr->desc_size * mr->max_descs,
2591 				   DMA_TO_DEVICE);
2592 
2593 	if (mr->access_mode == MLX5_MKC_ACCESS_MODE_KLMS)
2594 		n = mlx5_ib_sg_to_klms(mr, sg, sg_nents, sg_offset, NULL, 0,
2595 				       NULL);
2596 	else
2597 		n = ib_sg_to_pages(ibmr, sg, sg_nents, sg_offset,
2598 				mlx5_set_page);
2599 
2600 	ib_dma_sync_single_for_device(ibmr->device, mr->desc_map,
2601 				      mr->desc_size * mr->max_descs,
2602 				      DMA_TO_DEVICE);
2603 
2604 	return n;
2605 }
2606