xref: /linux/drivers/infiniband/hw/mlx5/mr.c (revision 576d7fed09c7edbae7600f29a8a3ed6c1ead904f)
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 		if (attr->access_flags & ~MLX5_IB_DM_SW_ICM_ALLOWED_ACCESS)
1351 			return ERR_PTR(-EINVAL);
1352 
1353 		mode = MLX5_MKC_ACCESS_MODE_SW_ICM;
1354 		break;
1355 	default:
1356 		return ERR_PTR(-EINVAL);
1357 	}
1358 
1359 	return mlx5_ib_get_dm_mr(pd, start_addr, attr->length,
1360 				 attr->access_flags, mode);
1361 }
1362 
1363 static struct ib_mr *create_real_mr(struct ib_pd *pd, struct ib_umem *umem,
1364 				    u64 iova, int access_flags)
1365 {
1366 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1367 	struct mlx5_ib_mr *mr = NULL;
1368 	bool xlt_with_umr;
1369 	int err;
1370 
1371 	xlt_with_umr = mlx5r_umr_can_load_pas(dev, umem->length);
1372 	if (xlt_with_umr) {
1373 		mr = alloc_cacheable_mr(pd, umem, iova, access_flags);
1374 	} else {
1375 		unsigned int page_size = mlx5_umem_find_best_pgsz(
1376 			umem, mkc, log_page_size, 0, iova);
1377 
1378 		mutex_lock(&dev->slow_path_mutex);
1379 		mr = reg_create(pd, umem, iova, access_flags, page_size, true);
1380 		mutex_unlock(&dev->slow_path_mutex);
1381 	}
1382 	if (IS_ERR(mr)) {
1383 		ib_umem_release(umem);
1384 		return ERR_CAST(mr);
1385 	}
1386 
1387 	mlx5_ib_dbg(dev, "mkey 0x%x\n", mr->mmkey.key);
1388 
1389 	atomic_add(ib_umem_num_pages(umem), &dev->mdev->priv.reg_pages);
1390 
1391 	if (xlt_with_umr) {
1392 		/*
1393 		 * If the MR was created with reg_create then it will be
1394 		 * configured properly but left disabled. It is safe to go ahead
1395 		 * and configure it again via UMR while enabling it.
1396 		 */
1397 		err = mlx5r_umr_update_mr_pas(mr, MLX5_IB_UPD_XLT_ENABLE);
1398 		if (err) {
1399 			mlx5_ib_dereg_mr(&mr->ibmr, NULL);
1400 			return ERR_PTR(err);
1401 		}
1402 	}
1403 	return &mr->ibmr;
1404 }
1405 
1406 static struct ib_mr *create_user_odp_mr(struct ib_pd *pd, u64 start, u64 length,
1407 					u64 iova, int access_flags,
1408 					struct ib_udata *udata)
1409 {
1410 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1411 	struct ib_umem_odp *odp;
1412 	struct mlx5_ib_mr *mr;
1413 	int err;
1414 
1415 	if (!IS_ENABLED(CONFIG_INFINIBAND_ON_DEMAND_PAGING))
1416 		return ERR_PTR(-EOPNOTSUPP);
1417 
1418 	err = mlx5r_odp_create_eq(dev, &dev->odp_pf_eq);
1419 	if (err)
1420 		return ERR_PTR(err);
1421 	if (!start && length == U64_MAX) {
1422 		if (iova != 0)
1423 			return ERR_PTR(-EINVAL);
1424 		if (!(dev->odp_caps.general_caps & IB_ODP_SUPPORT_IMPLICIT))
1425 			return ERR_PTR(-EINVAL);
1426 
1427 		mr = mlx5_ib_alloc_implicit_mr(to_mpd(pd), access_flags);
1428 		if (IS_ERR(mr))
1429 			return ERR_CAST(mr);
1430 		return &mr->ibmr;
1431 	}
1432 
1433 	/* ODP requires xlt update via umr to work. */
1434 	if (!mlx5r_umr_can_load_pas(dev, length))
1435 		return ERR_PTR(-EINVAL);
1436 
1437 	odp = ib_umem_odp_get(&dev->ib_dev, start, length, access_flags,
1438 			      &mlx5_mn_ops);
1439 	if (IS_ERR(odp))
1440 		return ERR_CAST(odp);
1441 
1442 	mr = alloc_cacheable_mr(pd, &odp->umem, iova, access_flags);
1443 	if (IS_ERR(mr)) {
1444 		ib_umem_release(&odp->umem);
1445 		return ERR_CAST(mr);
1446 	}
1447 	xa_init(&mr->implicit_children);
1448 
1449 	odp->private = mr;
1450 	err = mlx5r_store_odp_mkey(dev, &mr->mmkey);
1451 	if (err)
1452 		goto err_dereg_mr;
1453 
1454 	err = mlx5_ib_init_odp_mr(mr);
1455 	if (err)
1456 		goto err_dereg_mr;
1457 	return &mr->ibmr;
1458 
1459 err_dereg_mr:
1460 	mlx5_ib_dereg_mr(&mr->ibmr, NULL);
1461 	return ERR_PTR(err);
1462 }
1463 
1464 struct ib_mr *mlx5_ib_reg_user_mr(struct ib_pd *pd, u64 start, u64 length,
1465 				  u64 iova, int access_flags,
1466 				  struct ib_udata *udata)
1467 {
1468 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1469 	struct ib_umem *umem;
1470 
1471 	if (!IS_ENABLED(CONFIG_INFINIBAND_USER_MEM))
1472 		return ERR_PTR(-EOPNOTSUPP);
1473 
1474 	mlx5_ib_dbg(dev, "start 0x%llx, iova 0x%llx, length 0x%llx, access_flags 0x%x\n",
1475 		    start, iova, length, access_flags);
1476 
1477 	if (access_flags & IB_ACCESS_ON_DEMAND)
1478 		return create_user_odp_mr(pd, start, length, iova, access_flags,
1479 					  udata);
1480 	umem = ib_umem_get(&dev->ib_dev, start, length, access_flags);
1481 	if (IS_ERR(umem))
1482 		return ERR_CAST(umem);
1483 	return create_real_mr(pd, umem, iova, access_flags);
1484 }
1485 
1486 static void mlx5_ib_dmabuf_invalidate_cb(struct dma_buf_attachment *attach)
1487 {
1488 	struct ib_umem_dmabuf *umem_dmabuf = attach->importer_priv;
1489 	struct mlx5_ib_mr *mr = umem_dmabuf->private;
1490 
1491 	dma_resv_assert_held(umem_dmabuf->attach->dmabuf->resv);
1492 
1493 	if (!umem_dmabuf->sgt)
1494 		return;
1495 
1496 	mlx5r_umr_update_mr_pas(mr, MLX5_IB_UPD_XLT_ZAP);
1497 	ib_umem_dmabuf_unmap_pages(umem_dmabuf);
1498 }
1499 
1500 static struct dma_buf_attach_ops mlx5_ib_dmabuf_attach_ops = {
1501 	.allow_peer2peer = 1,
1502 	.move_notify = mlx5_ib_dmabuf_invalidate_cb,
1503 };
1504 
1505 struct ib_mr *mlx5_ib_reg_user_mr_dmabuf(struct ib_pd *pd, u64 offset,
1506 					 u64 length, u64 virt_addr,
1507 					 int fd, int access_flags,
1508 					 struct ib_udata *udata)
1509 {
1510 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1511 	struct mlx5_ib_mr *mr = NULL;
1512 	struct ib_umem_dmabuf *umem_dmabuf;
1513 	int err;
1514 
1515 	if (!IS_ENABLED(CONFIG_INFINIBAND_USER_MEM) ||
1516 	    !IS_ENABLED(CONFIG_INFINIBAND_ON_DEMAND_PAGING))
1517 		return ERR_PTR(-EOPNOTSUPP);
1518 
1519 	mlx5_ib_dbg(dev,
1520 		    "offset 0x%llx, virt_addr 0x%llx, length 0x%llx, fd %d, access_flags 0x%x\n",
1521 		    offset, virt_addr, length, fd, access_flags);
1522 
1523 	/* dmabuf requires xlt update via umr to work. */
1524 	if (!mlx5r_umr_can_load_pas(dev, length))
1525 		return ERR_PTR(-EINVAL);
1526 
1527 	umem_dmabuf = ib_umem_dmabuf_get(&dev->ib_dev, offset, length, fd,
1528 					 access_flags,
1529 					 &mlx5_ib_dmabuf_attach_ops);
1530 	if (IS_ERR(umem_dmabuf)) {
1531 		mlx5_ib_dbg(dev, "umem_dmabuf get failed (%ld)\n",
1532 			    PTR_ERR(umem_dmabuf));
1533 		return ERR_CAST(umem_dmabuf);
1534 	}
1535 
1536 	mr = alloc_cacheable_mr(pd, &umem_dmabuf->umem, virt_addr,
1537 				access_flags);
1538 	if (IS_ERR(mr)) {
1539 		ib_umem_release(&umem_dmabuf->umem);
1540 		return ERR_CAST(mr);
1541 	}
1542 
1543 	mlx5_ib_dbg(dev, "mkey 0x%x\n", mr->mmkey.key);
1544 
1545 	atomic_add(ib_umem_num_pages(mr->umem), &dev->mdev->priv.reg_pages);
1546 	umem_dmabuf->private = mr;
1547 	err = mlx5r_store_odp_mkey(dev, &mr->mmkey);
1548 	if (err)
1549 		goto err_dereg_mr;
1550 
1551 	err = mlx5_ib_init_dmabuf_mr(mr);
1552 	if (err)
1553 		goto err_dereg_mr;
1554 	return &mr->ibmr;
1555 
1556 err_dereg_mr:
1557 	mlx5_ib_dereg_mr(&mr->ibmr, NULL);
1558 	return ERR_PTR(err);
1559 }
1560 
1561 /*
1562  * True if the change in access flags can be done via UMR, only some access
1563  * flags can be updated.
1564  */
1565 static bool can_use_umr_rereg_access(struct mlx5_ib_dev *dev,
1566 				     unsigned int current_access_flags,
1567 				     unsigned int target_access_flags)
1568 {
1569 	unsigned int diffs = current_access_flags ^ target_access_flags;
1570 
1571 	if (diffs & ~(IB_ACCESS_LOCAL_WRITE | IB_ACCESS_REMOTE_WRITE |
1572 		      IB_ACCESS_REMOTE_READ | IB_ACCESS_RELAXED_ORDERING))
1573 		return false;
1574 	return mlx5r_umr_can_reconfig(dev, current_access_flags,
1575 				      target_access_flags);
1576 }
1577 
1578 static bool can_use_umr_rereg_pas(struct mlx5_ib_mr *mr,
1579 				  struct ib_umem *new_umem,
1580 				  int new_access_flags, u64 iova,
1581 				  unsigned long *page_size)
1582 {
1583 	struct mlx5_ib_dev *dev = to_mdev(mr->ibmr.device);
1584 
1585 	/* We only track the allocated sizes of MRs from the cache */
1586 	if (!mr->mmkey.cache_ent)
1587 		return false;
1588 	if (!mlx5r_umr_can_load_pas(dev, new_umem->length))
1589 		return false;
1590 
1591 	*page_size =
1592 		mlx5_umem_find_best_pgsz(new_umem, mkc, log_page_size, 0, iova);
1593 	if (WARN_ON(!*page_size))
1594 		return false;
1595 	return (mr->mmkey.cache_ent->rb_key.ndescs) >=
1596 	       ib_umem_num_dma_blocks(new_umem, *page_size);
1597 }
1598 
1599 static int umr_rereg_pas(struct mlx5_ib_mr *mr, struct ib_pd *pd,
1600 			 int access_flags, int flags, struct ib_umem *new_umem,
1601 			 u64 iova, unsigned long page_size)
1602 {
1603 	struct mlx5_ib_dev *dev = to_mdev(mr->ibmr.device);
1604 	int upd_flags = MLX5_IB_UPD_XLT_ADDR | MLX5_IB_UPD_XLT_ENABLE;
1605 	struct ib_umem *old_umem = mr->umem;
1606 	int err;
1607 
1608 	/*
1609 	 * To keep everything simple the MR is revoked before we start to mess
1610 	 * with it. This ensure the change is atomic relative to any use of the
1611 	 * MR.
1612 	 */
1613 	err = mlx5r_umr_revoke_mr(mr);
1614 	if (err)
1615 		return err;
1616 
1617 	if (flags & IB_MR_REREG_PD) {
1618 		mr->ibmr.pd = pd;
1619 		upd_flags |= MLX5_IB_UPD_XLT_PD;
1620 	}
1621 	if (flags & IB_MR_REREG_ACCESS) {
1622 		mr->access_flags = access_flags;
1623 		upd_flags |= MLX5_IB_UPD_XLT_ACCESS;
1624 	}
1625 
1626 	mr->ibmr.iova = iova;
1627 	mr->ibmr.length = new_umem->length;
1628 	mr->page_shift = order_base_2(page_size);
1629 	mr->umem = new_umem;
1630 	err = mlx5r_umr_update_mr_pas(mr, upd_flags);
1631 	if (err) {
1632 		/*
1633 		 * The MR is revoked at this point so there is no issue to free
1634 		 * new_umem.
1635 		 */
1636 		mr->umem = old_umem;
1637 		return err;
1638 	}
1639 
1640 	atomic_sub(ib_umem_num_pages(old_umem), &dev->mdev->priv.reg_pages);
1641 	ib_umem_release(old_umem);
1642 	atomic_add(ib_umem_num_pages(new_umem), &dev->mdev->priv.reg_pages);
1643 	return 0;
1644 }
1645 
1646 struct ib_mr *mlx5_ib_rereg_user_mr(struct ib_mr *ib_mr, int flags, u64 start,
1647 				    u64 length, u64 iova, int new_access_flags,
1648 				    struct ib_pd *new_pd,
1649 				    struct ib_udata *udata)
1650 {
1651 	struct mlx5_ib_dev *dev = to_mdev(ib_mr->device);
1652 	struct mlx5_ib_mr *mr = to_mmr(ib_mr);
1653 	int err;
1654 
1655 	if (!IS_ENABLED(CONFIG_INFINIBAND_USER_MEM))
1656 		return ERR_PTR(-EOPNOTSUPP);
1657 
1658 	mlx5_ib_dbg(
1659 		dev,
1660 		"start 0x%llx, iova 0x%llx, length 0x%llx, access_flags 0x%x\n",
1661 		start, iova, length, new_access_flags);
1662 
1663 	if (flags & ~(IB_MR_REREG_TRANS | IB_MR_REREG_PD | IB_MR_REREG_ACCESS))
1664 		return ERR_PTR(-EOPNOTSUPP);
1665 
1666 	if (!(flags & IB_MR_REREG_ACCESS))
1667 		new_access_flags = mr->access_flags;
1668 	if (!(flags & IB_MR_REREG_PD))
1669 		new_pd = ib_mr->pd;
1670 
1671 	if (!(flags & IB_MR_REREG_TRANS)) {
1672 		struct ib_umem *umem;
1673 
1674 		/* Fast path for PD/access change */
1675 		if (can_use_umr_rereg_access(dev, mr->access_flags,
1676 					     new_access_flags)) {
1677 			err = mlx5r_umr_rereg_pd_access(mr, new_pd,
1678 							new_access_flags);
1679 			if (err)
1680 				return ERR_PTR(err);
1681 			return NULL;
1682 		}
1683 		/* DM or ODP MR's don't have a normal umem so we can't re-use it */
1684 		if (!mr->umem || is_odp_mr(mr) || is_dmabuf_mr(mr))
1685 			goto recreate;
1686 
1687 		/*
1688 		 * Only one active MR can refer to a umem at one time, revoke
1689 		 * the old MR before assigning the umem to the new one.
1690 		 */
1691 		err = mlx5r_umr_revoke_mr(mr);
1692 		if (err)
1693 			return ERR_PTR(err);
1694 		umem = mr->umem;
1695 		mr->umem = NULL;
1696 		atomic_sub(ib_umem_num_pages(umem), &dev->mdev->priv.reg_pages);
1697 
1698 		return create_real_mr(new_pd, umem, mr->ibmr.iova,
1699 				      new_access_flags);
1700 	}
1701 
1702 	/*
1703 	 * DM doesn't have a PAS list so we can't re-use it, odp/dmabuf does
1704 	 * but the logic around releasing the umem is different
1705 	 */
1706 	if (!mr->umem || is_odp_mr(mr) || is_dmabuf_mr(mr))
1707 		goto recreate;
1708 
1709 	if (!(new_access_flags & IB_ACCESS_ON_DEMAND) &&
1710 	    can_use_umr_rereg_access(dev, mr->access_flags, new_access_flags)) {
1711 		struct ib_umem *new_umem;
1712 		unsigned long page_size;
1713 
1714 		new_umem = ib_umem_get(&dev->ib_dev, start, length,
1715 				       new_access_flags);
1716 		if (IS_ERR(new_umem))
1717 			return ERR_CAST(new_umem);
1718 
1719 		/* Fast path for PAS change */
1720 		if (can_use_umr_rereg_pas(mr, new_umem, new_access_flags, iova,
1721 					  &page_size)) {
1722 			err = umr_rereg_pas(mr, new_pd, new_access_flags, flags,
1723 					    new_umem, iova, page_size);
1724 			if (err) {
1725 				ib_umem_release(new_umem);
1726 				return ERR_PTR(err);
1727 			}
1728 			return NULL;
1729 		}
1730 		return create_real_mr(new_pd, new_umem, iova, new_access_flags);
1731 	}
1732 
1733 	/*
1734 	 * Everything else has no state we can preserve, just create a new MR
1735 	 * from scratch
1736 	 */
1737 recreate:
1738 	return mlx5_ib_reg_user_mr(new_pd, start, length, iova,
1739 				   new_access_flags, udata);
1740 }
1741 
1742 static int
1743 mlx5_alloc_priv_descs(struct ib_device *device,
1744 		      struct mlx5_ib_mr *mr,
1745 		      int ndescs,
1746 		      int desc_size)
1747 {
1748 	struct mlx5_ib_dev *dev = to_mdev(device);
1749 	struct device *ddev = &dev->mdev->pdev->dev;
1750 	int size = ndescs * desc_size;
1751 	int add_size;
1752 	int ret;
1753 
1754 	add_size = max_t(int, MLX5_UMR_ALIGN - ARCH_KMALLOC_MINALIGN, 0);
1755 	if (is_power_of_2(MLX5_UMR_ALIGN) && add_size) {
1756 		int end = max_t(int, MLX5_UMR_ALIGN, roundup_pow_of_two(size));
1757 
1758 		add_size = min_t(int, end - size, add_size);
1759 	}
1760 
1761 	mr->descs_alloc = kzalloc(size + add_size, GFP_KERNEL);
1762 	if (!mr->descs_alloc)
1763 		return -ENOMEM;
1764 
1765 	mr->descs = PTR_ALIGN(mr->descs_alloc, MLX5_UMR_ALIGN);
1766 
1767 	mr->desc_map = dma_map_single(ddev, mr->descs, size, DMA_TO_DEVICE);
1768 	if (dma_mapping_error(ddev, mr->desc_map)) {
1769 		ret = -ENOMEM;
1770 		goto err;
1771 	}
1772 
1773 	return 0;
1774 err:
1775 	kfree(mr->descs_alloc);
1776 
1777 	return ret;
1778 }
1779 
1780 static void
1781 mlx5_free_priv_descs(struct mlx5_ib_mr *mr)
1782 {
1783 	if (!mr->umem && mr->descs) {
1784 		struct ib_device *device = mr->ibmr.device;
1785 		int size = mr->max_descs * mr->desc_size;
1786 		struct mlx5_ib_dev *dev = to_mdev(device);
1787 
1788 		dma_unmap_single(&dev->mdev->pdev->dev, mr->desc_map, size,
1789 				 DMA_TO_DEVICE);
1790 		kfree(mr->descs_alloc);
1791 		mr->descs = NULL;
1792 	}
1793 }
1794 
1795 static int cache_ent_find_and_store(struct mlx5_ib_dev *dev,
1796 				    struct mlx5_ib_mr *mr)
1797 {
1798 	struct mlx5_mkey_cache *cache = &dev->cache;
1799 	struct mlx5_cache_ent *ent;
1800 	int ret;
1801 
1802 	if (mr->mmkey.cache_ent) {
1803 		spin_lock_irq(&mr->mmkey.cache_ent->mkeys_queue.lock);
1804 		mr->mmkey.cache_ent->in_use--;
1805 		goto end;
1806 	}
1807 
1808 	mutex_lock(&cache->rb_lock);
1809 	ent = mkey_cache_ent_from_rb_key(dev, mr->mmkey.rb_key);
1810 	if (ent) {
1811 		if (ent->rb_key.ndescs == mr->mmkey.rb_key.ndescs) {
1812 			if (ent->disabled) {
1813 				mutex_unlock(&cache->rb_lock);
1814 				return -EOPNOTSUPP;
1815 			}
1816 			mr->mmkey.cache_ent = ent;
1817 			spin_lock_irq(&mr->mmkey.cache_ent->mkeys_queue.lock);
1818 			mutex_unlock(&cache->rb_lock);
1819 			goto end;
1820 		}
1821 	}
1822 
1823 	ent = mlx5r_cache_create_ent_locked(dev, mr->mmkey.rb_key, false);
1824 	mutex_unlock(&cache->rb_lock);
1825 	if (IS_ERR(ent))
1826 		return PTR_ERR(ent);
1827 
1828 	mr->mmkey.cache_ent = ent;
1829 	spin_lock_irq(&mr->mmkey.cache_ent->mkeys_queue.lock);
1830 
1831 end:
1832 	ret = push_mkey_locked(mr->mmkey.cache_ent, mr->mmkey.key);
1833 	spin_unlock_irq(&mr->mmkey.cache_ent->mkeys_queue.lock);
1834 	return ret;
1835 }
1836 
1837 int mlx5_ib_dereg_mr(struct ib_mr *ibmr, struct ib_udata *udata)
1838 {
1839 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
1840 	struct mlx5_ib_dev *dev = to_mdev(ibmr->device);
1841 	int rc;
1842 
1843 	/*
1844 	 * Any async use of the mr must hold the refcount, once the refcount
1845 	 * goes to zero no other thread, such as ODP page faults, prefetch, any
1846 	 * UMR activity, etc can touch the mkey. Thus it is safe to destroy it.
1847 	 */
1848 	if (IS_ENABLED(CONFIG_INFINIBAND_ON_DEMAND_PAGING) &&
1849 	    refcount_read(&mr->mmkey.usecount) != 0 &&
1850 	    xa_erase(&mr_to_mdev(mr)->odp_mkeys, mlx5_base_mkey(mr->mmkey.key)))
1851 		mlx5r_deref_wait_odp_mkey(&mr->mmkey);
1852 
1853 	if (ibmr->type == IB_MR_TYPE_INTEGRITY) {
1854 		xa_cmpxchg(&dev->sig_mrs, mlx5_base_mkey(mr->mmkey.key),
1855 			   mr->sig, NULL, GFP_KERNEL);
1856 
1857 		if (mr->mtt_mr) {
1858 			rc = mlx5_ib_dereg_mr(&mr->mtt_mr->ibmr, NULL);
1859 			if (rc)
1860 				return rc;
1861 			mr->mtt_mr = NULL;
1862 		}
1863 		if (mr->klm_mr) {
1864 			rc = mlx5_ib_dereg_mr(&mr->klm_mr->ibmr, NULL);
1865 			if (rc)
1866 				return rc;
1867 			mr->klm_mr = NULL;
1868 		}
1869 
1870 		if (mlx5_core_destroy_psv(dev->mdev,
1871 					  mr->sig->psv_memory.psv_idx))
1872 			mlx5_ib_warn(dev, "failed to destroy mem psv %d\n",
1873 				     mr->sig->psv_memory.psv_idx);
1874 		if (mlx5_core_destroy_psv(dev->mdev, mr->sig->psv_wire.psv_idx))
1875 			mlx5_ib_warn(dev, "failed to destroy wire psv %d\n",
1876 				     mr->sig->psv_wire.psv_idx);
1877 		kfree(mr->sig);
1878 		mr->sig = NULL;
1879 	}
1880 
1881 	/* Stop DMA */
1882 	if (mr->umem && mlx5r_umr_can_load_pas(dev, mr->umem->length))
1883 		if (mlx5r_umr_revoke_mr(mr) ||
1884 		    cache_ent_find_and_store(dev, mr))
1885 			mr->mmkey.cache_ent = NULL;
1886 
1887 	if (!mr->mmkey.cache_ent) {
1888 		rc = destroy_mkey(to_mdev(mr->ibmr.device), mr);
1889 		if (rc)
1890 			return rc;
1891 	}
1892 
1893 	if (mr->umem) {
1894 		bool is_odp = is_odp_mr(mr);
1895 
1896 		if (!is_odp)
1897 			atomic_sub(ib_umem_num_pages(mr->umem),
1898 				   &dev->mdev->priv.reg_pages);
1899 		ib_umem_release(mr->umem);
1900 		if (is_odp)
1901 			mlx5_ib_free_odp_mr(mr);
1902 	}
1903 
1904 	if (!mr->mmkey.cache_ent)
1905 		mlx5_free_priv_descs(mr);
1906 
1907 	kfree(mr);
1908 	return 0;
1909 }
1910 
1911 static void mlx5_set_umr_free_mkey(struct ib_pd *pd, u32 *in, int ndescs,
1912 				   int access_mode, int page_shift)
1913 {
1914 	void *mkc;
1915 
1916 	mkc = MLX5_ADDR_OF(create_mkey_in, in, memory_key_mkey_entry);
1917 
1918 	/* This is only used from the kernel, so setting the PD is OK. */
1919 	set_mkc_access_pd_addr_fields(mkc, IB_ACCESS_RELAXED_ORDERING, 0, pd);
1920 	MLX5_SET(mkc, mkc, free, 1);
1921 	MLX5_SET(mkc, mkc, translations_octword_size, ndescs);
1922 	MLX5_SET(mkc, mkc, access_mode_1_0, access_mode & 0x3);
1923 	MLX5_SET(mkc, mkc, access_mode_4_2, (access_mode >> 2) & 0x7);
1924 	MLX5_SET(mkc, mkc, umr_en, 1);
1925 	MLX5_SET(mkc, mkc, log_page_size, page_shift);
1926 }
1927 
1928 static int _mlx5_alloc_mkey_descs(struct ib_pd *pd, struct mlx5_ib_mr *mr,
1929 				  int ndescs, int desc_size, int page_shift,
1930 				  int access_mode, u32 *in, int inlen)
1931 {
1932 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1933 	int err;
1934 
1935 	mr->access_mode = access_mode;
1936 	mr->desc_size = desc_size;
1937 	mr->max_descs = ndescs;
1938 
1939 	err = mlx5_alloc_priv_descs(pd->device, mr, ndescs, desc_size);
1940 	if (err)
1941 		return err;
1942 
1943 	mlx5_set_umr_free_mkey(pd, in, ndescs, access_mode, page_shift);
1944 
1945 	err = mlx5_ib_create_mkey(dev, &mr->mmkey, in, inlen);
1946 	if (err)
1947 		goto err_free_descs;
1948 
1949 	mr->mmkey.type = MLX5_MKEY_MR;
1950 	mr->ibmr.lkey = mr->mmkey.key;
1951 	mr->ibmr.rkey = mr->mmkey.key;
1952 
1953 	return 0;
1954 
1955 err_free_descs:
1956 	mlx5_free_priv_descs(mr);
1957 	return err;
1958 }
1959 
1960 static struct mlx5_ib_mr *mlx5_ib_alloc_pi_mr(struct ib_pd *pd,
1961 				u32 max_num_sg, u32 max_num_meta_sg,
1962 				int desc_size, int access_mode)
1963 {
1964 	int inlen = MLX5_ST_SZ_BYTES(create_mkey_in);
1965 	int ndescs = ALIGN(max_num_sg + max_num_meta_sg, 4);
1966 	int page_shift = 0;
1967 	struct mlx5_ib_mr *mr;
1968 	u32 *in;
1969 	int err;
1970 
1971 	mr = kzalloc(sizeof(*mr), GFP_KERNEL);
1972 	if (!mr)
1973 		return ERR_PTR(-ENOMEM);
1974 
1975 	mr->ibmr.pd = pd;
1976 	mr->ibmr.device = pd->device;
1977 
1978 	in = kzalloc(inlen, GFP_KERNEL);
1979 	if (!in) {
1980 		err = -ENOMEM;
1981 		goto err_free;
1982 	}
1983 
1984 	if (access_mode == MLX5_MKC_ACCESS_MODE_MTT)
1985 		page_shift = PAGE_SHIFT;
1986 
1987 	err = _mlx5_alloc_mkey_descs(pd, mr, ndescs, desc_size, page_shift,
1988 				     access_mode, in, inlen);
1989 	if (err)
1990 		goto err_free_in;
1991 
1992 	mr->umem = NULL;
1993 	kfree(in);
1994 
1995 	return mr;
1996 
1997 err_free_in:
1998 	kfree(in);
1999 err_free:
2000 	kfree(mr);
2001 	return ERR_PTR(err);
2002 }
2003 
2004 static int mlx5_alloc_mem_reg_descs(struct ib_pd *pd, struct mlx5_ib_mr *mr,
2005 				    int ndescs, u32 *in, int inlen)
2006 {
2007 	return _mlx5_alloc_mkey_descs(pd, mr, ndescs, sizeof(struct mlx5_mtt),
2008 				      PAGE_SHIFT, MLX5_MKC_ACCESS_MODE_MTT, in,
2009 				      inlen);
2010 }
2011 
2012 static int mlx5_alloc_sg_gaps_descs(struct ib_pd *pd, struct mlx5_ib_mr *mr,
2013 				    int ndescs, u32 *in, int inlen)
2014 {
2015 	return _mlx5_alloc_mkey_descs(pd, mr, ndescs, sizeof(struct mlx5_klm),
2016 				      0, MLX5_MKC_ACCESS_MODE_KLMS, in, inlen);
2017 }
2018 
2019 static int mlx5_alloc_integrity_descs(struct ib_pd *pd, struct mlx5_ib_mr *mr,
2020 				      int max_num_sg, int max_num_meta_sg,
2021 				      u32 *in, int inlen)
2022 {
2023 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
2024 	u32 psv_index[2];
2025 	void *mkc;
2026 	int err;
2027 
2028 	mr->sig = kzalloc(sizeof(*mr->sig), GFP_KERNEL);
2029 	if (!mr->sig)
2030 		return -ENOMEM;
2031 
2032 	/* create mem & wire PSVs */
2033 	err = mlx5_core_create_psv(dev->mdev, to_mpd(pd)->pdn, 2, psv_index);
2034 	if (err)
2035 		goto err_free_sig;
2036 
2037 	mr->sig->psv_memory.psv_idx = psv_index[0];
2038 	mr->sig->psv_wire.psv_idx = psv_index[1];
2039 
2040 	mr->sig->sig_status_checked = true;
2041 	mr->sig->sig_err_exists = false;
2042 	/* Next UMR, Arm SIGERR */
2043 	++mr->sig->sigerr_count;
2044 	mr->klm_mr = mlx5_ib_alloc_pi_mr(pd, max_num_sg, max_num_meta_sg,
2045 					 sizeof(struct mlx5_klm),
2046 					 MLX5_MKC_ACCESS_MODE_KLMS);
2047 	if (IS_ERR(mr->klm_mr)) {
2048 		err = PTR_ERR(mr->klm_mr);
2049 		goto err_destroy_psv;
2050 	}
2051 	mr->mtt_mr = mlx5_ib_alloc_pi_mr(pd, max_num_sg, max_num_meta_sg,
2052 					 sizeof(struct mlx5_mtt),
2053 					 MLX5_MKC_ACCESS_MODE_MTT);
2054 	if (IS_ERR(mr->mtt_mr)) {
2055 		err = PTR_ERR(mr->mtt_mr);
2056 		goto err_free_klm_mr;
2057 	}
2058 
2059 	/* Set bsf descriptors for mkey */
2060 	mkc = MLX5_ADDR_OF(create_mkey_in, in, memory_key_mkey_entry);
2061 	MLX5_SET(mkc, mkc, bsf_en, 1);
2062 	MLX5_SET(mkc, mkc, bsf_octword_size, MLX5_MKEY_BSF_OCTO_SIZE);
2063 
2064 	err = _mlx5_alloc_mkey_descs(pd, mr, 4, sizeof(struct mlx5_klm), 0,
2065 				     MLX5_MKC_ACCESS_MODE_KLMS, in, inlen);
2066 	if (err)
2067 		goto err_free_mtt_mr;
2068 
2069 	err = xa_err(xa_store(&dev->sig_mrs, mlx5_base_mkey(mr->mmkey.key),
2070 			      mr->sig, GFP_KERNEL));
2071 	if (err)
2072 		goto err_free_descs;
2073 	return 0;
2074 
2075 err_free_descs:
2076 	destroy_mkey(dev, mr);
2077 	mlx5_free_priv_descs(mr);
2078 err_free_mtt_mr:
2079 	mlx5_ib_dereg_mr(&mr->mtt_mr->ibmr, NULL);
2080 	mr->mtt_mr = NULL;
2081 err_free_klm_mr:
2082 	mlx5_ib_dereg_mr(&mr->klm_mr->ibmr, NULL);
2083 	mr->klm_mr = NULL;
2084 err_destroy_psv:
2085 	if (mlx5_core_destroy_psv(dev->mdev, mr->sig->psv_memory.psv_idx))
2086 		mlx5_ib_warn(dev, "failed to destroy mem psv %d\n",
2087 			     mr->sig->psv_memory.psv_idx);
2088 	if (mlx5_core_destroy_psv(dev->mdev, mr->sig->psv_wire.psv_idx))
2089 		mlx5_ib_warn(dev, "failed to destroy wire psv %d\n",
2090 			     mr->sig->psv_wire.psv_idx);
2091 err_free_sig:
2092 	kfree(mr->sig);
2093 
2094 	return err;
2095 }
2096 
2097 static struct ib_mr *__mlx5_ib_alloc_mr(struct ib_pd *pd,
2098 					enum ib_mr_type mr_type, u32 max_num_sg,
2099 					u32 max_num_meta_sg)
2100 {
2101 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
2102 	int inlen = MLX5_ST_SZ_BYTES(create_mkey_in);
2103 	int ndescs = ALIGN(max_num_sg, 4);
2104 	struct mlx5_ib_mr *mr;
2105 	u32 *in;
2106 	int err;
2107 
2108 	mr = kzalloc(sizeof(*mr), GFP_KERNEL);
2109 	if (!mr)
2110 		return ERR_PTR(-ENOMEM);
2111 
2112 	in = kzalloc(inlen, GFP_KERNEL);
2113 	if (!in) {
2114 		err = -ENOMEM;
2115 		goto err_free;
2116 	}
2117 
2118 	mr->ibmr.device = pd->device;
2119 	mr->umem = NULL;
2120 
2121 	switch (mr_type) {
2122 	case IB_MR_TYPE_MEM_REG:
2123 		err = mlx5_alloc_mem_reg_descs(pd, mr, ndescs, in, inlen);
2124 		break;
2125 	case IB_MR_TYPE_SG_GAPS:
2126 		err = mlx5_alloc_sg_gaps_descs(pd, mr, ndescs, in, inlen);
2127 		break;
2128 	case IB_MR_TYPE_INTEGRITY:
2129 		err = mlx5_alloc_integrity_descs(pd, mr, max_num_sg,
2130 						 max_num_meta_sg, in, inlen);
2131 		break;
2132 	default:
2133 		mlx5_ib_warn(dev, "Invalid mr type %d\n", mr_type);
2134 		err = -EINVAL;
2135 	}
2136 
2137 	if (err)
2138 		goto err_free_in;
2139 
2140 	kfree(in);
2141 
2142 	return &mr->ibmr;
2143 
2144 err_free_in:
2145 	kfree(in);
2146 err_free:
2147 	kfree(mr);
2148 	return ERR_PTR(err);
2149 }
2150 
2151 struct ib_mr *mlx5_ib_alloc_mr(struct ib_pd *pd, enum ib_mr_type mr_type,
2152 			       u32 max_num_sg)
2153 {
2154 	return __mlx5_ib_alloc_mr(pd, mr_type, max_num_sg, 0);
2155 }
2156 
2157 struct ib_mr *mlx5_ib_alloc_mr_integrity(struct ib_pd *pd,
2158 					 u32 max_num_sg, u32 max_num_meta_sg)
2159 {
2160 	return __mlx5_ib_alloc_mr(pd, IB_MR_TYPE_INTEGRITY, max_num_sg,
2161 				  max_num_meta_sg);
2162 }
2163 
2164 int mlx5_ib_alloc_mw(struct ib_mw *ibmw, struct ib_udata *udata)
2165 {
2166 	struct mlx5_ib_dev *dev = to_mdev(ibmw->device);
2167 	int inlen = MLX5_ST_SZ_BYTES(create_mkey_in);
2168 	struct mlx5_ib_mw *mw = to_mmw(ibmw);
2169 	unsigned int ndescs;
2170 	u32 *in = NULL;
2171 	void *mkc;
2172 	int err;
2173 	struct mlx5_ib_alloc_mw req = {};
2174 	struct {
2175 		__u32	comp_mask;
2176 		__u32	response_length;
2177 	} resp = {};
2178 
2179 	err = ib_copy_from_udata(&req, udata, min(udata->inlen, sizeof(req)));
2180 	if (err)
2181 		return err;
2182 
2183 	if (req.comp_mask || req.reserved1 || req.reserved2)
2184 		return -EOPNOTSUPP;
2185 
2186 	if (udata->inlen > sizeof(req) &&
2187 	    !ib_is_udata_cleared(udata, sizeof(req),
2188 				 udata->inlen - sizeof(req)))
2189 		return -EOPNOTSUPP;
2190 
2191 	ndescs = req.num_klms ? roundup(req.num_klms, 4) : roundup(1, 4);
2192 
2193 	in = kzalloc(inlen, GFP_KERNEL);
2194 	if (!in)
2195 		return -ENOMEM;
2196 
2197 	mkc = MLX5_ADDR_OF(create_mkey_in, in, memory_key_mkey_entry);
2198 
2199 	MLX5_SET(mkc, mkc, free, 1);
2200 	MLX5_SET(mkc, mkc, translations_octword_size, ndescs);
2201 	MLX5_SET(mkc, mkc, pd, to_mpd(ibmw->pd)->pdn);
2202 	MLX5_SET(mkc, mkc, umr_en, 1);
2203 	MLX5_SET(mkc, mkc, lr, 1);
2204 	MLX5_SET(mkc, mkc, access_mode_1_0, MLX5_MKC_ACCESS_MODE_KLMS);
2205 	MLX5_SET(mkc, mkc, en_rinval, !!((ibmw->type == IB_MW_TYPE_2)));
2206 	MLX5_SET(mkc, mkc, qpn, 0xffffff);
2207 
2208 	err = mlx5_ib_create_mkey(dev, &mw->mmkey, in, inlen);
2209 	if (err)
2210 		goto free;
2211 
2212 	mw->mmkey.type = MLX5_MKEY_MW;
2213 	ibmw->rkey = mw->mmkey.key;
2214 	mw->mmkey.ndescs = ndescs;
2215 
2216 	resp.response_length =
2217 		min(offsetofend(typeof(resp), response_length), udata->outlen);
2218 	if (resp.response_length) {
2219 		err = ib_copy_to_udata(udata, &resp, resp.response_length);
2220 		if (err)
2221 			goto free_mkey;
2222 	}
2223 
2224 	if (IS_ENABLED(CONFIG_INFINIBAND_ON_DEMAND_PAGING)) {
2225 		err = mlx5r_store_odp_mkey(dev, &mw->mmkey);
2226 		if (err)
2227 			goto free_mkey;
2228 	}
2229 
2230 	kfree(in);
2231 	return 0;
2232 
2233 free_mkey:
2234 	mlx5_core_destroy_mkey(dev->mdev, mw->mmkey.key);
2235 free:
2236 	kfree(in);
2237 	return err;
2238 }
2239 
2240 int mlx5_ib_dealloc_mw(struct ib_mw *mw)
2241 {
2242 	struct mlx5_ib_dev *dev = to_mdev(mw->device);
2243 	struct mlx5_ib_mw *mmw = to_mmw(mw);
2244 
2245 	if (IS_ENABLED(CONFIG_INFINIBAND_ON_DEMAND_PAGING) &&
2246 	    xa_erase(&dev->odp_mkeys, mlx5_base_mkey(mmw->mmkey.key)))
2247 		/*
2248 		 * pagefault_single_data_segment() may be accessing mmw
2249 		 * if the user bound an ODP MR to this MW.
2250 		 */
2251 		mlx5r_deref_wait_odp_mkey(&mmw->mmkey);
2252 
2253 	return mlx5_core_destroy_mkey(dev->mdev, mmw->mmkey.key);
2254 }
2255 
2256 int mlx5_ib_check_mr_status(struct ib_mr *ibmr, u32 check_mask,
2257 			    struct ib_mr_status *mr_status)
2258 {
2259 	struct mlx5_ib_mr *mmr = to_mmr(ibmr);
2260 	int ret = 0;
2261 
2262 	if (check_mask & ~IB_MR_CHECK_SIG_STATUS) {
2263 		pr_err("Invalid status check mask\n");
2264 		ret = -EINVAL;
2265 		goto done;
2266 	}
2267 
2268 	mr_status->fail_status = 0;
2269 	if (check_mask & IB_MR_CHECK_SIG_STATUS) {
2270 		if (!mmr->sig) {
2271 			ret = -EINVAL;
2272 			pr_err("signature status check requested on a non-signature enabled MR\n");
2273 			goto done;
2274 		}
2275 
2276 		mmr->sig->sig_status_checked = true;
2277 		if (!mmr->sig->sig_err_exists)
2278 			goto done;
2279 
2280 		if (ibmr->lkey == mmr->sig->err_item.key)
2281 			memcpy(&mr_status->sig_err, &mmr->sig->err_item,
2282 			       sizeof(mr_status->sig_err));
2283 		else {
2284 			mr_status->sig_err.err_type = IB_SIG_BAD_GUARD;
2285 			mr_status->sig_err.sig_err_offset = 0;
2286 			mr_status->sig_err.key = mmr->sig->err_item.key;
2287 		}
2288 
2289 		mmr->sig->sig_err_exists = false;
2290 		mr_status->fail_status |= IB_MR_CHECK_SIG_STATUS;
2291 	}
2292 
2293 done:
2294 	return ret;
2295 }
2296 
2297 static int
2298 mlx5_ib_map_pa_mr_sg_pi(struct ib_mr *ibmr, struct scatterlist *data_sg,
2299 			int data_sg_nents, unsigned int *data_sg_offset,
2300 			struct scatterlist *meta_sg, int meta_sg_nents,
2301 			unsigned int *meta_sg_offset)
2302 {
2303 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
2304 	unsigned int sg_offset = 0;
2305 	int n = 0;
2306 
2307 	mr->meta_length = 0;
2308 	if (data_sg_nents == 1) {
2309 		n++;
2310 		mr->mmkey.ndescs = 1;
2311 		if (data_sg_offset)
2312 			sg_offset = *data_sg_offset;
2313 		mr->data_length = sg_dma_len(data_sg) - sg_offset;
2314 		mr->data_iova = sg_dma_address(data_sg) + sg_offset;
2315 		if (meta_sg_nents == 1) {
2316 			n++;
2317 			mr->meta_ndescs = 1;
2318 			if (meta_sg_offset)
2319 				sg_offset = *meta_sg_offset;
2320 			else
2321 				sg_offset = 0;
2322 			mr->meta_length = sg_dma_len(meta_sg) - sg_offset;
2323 			mr->pi_iova = sg_dma_address(meta_sg) + sg_offset;
2324 		}
2325 		ibmr->length = mr->data_length + mr->meta_length;
2326 	}
2327 
2328 	return n;
2329 }
2330 
2331 static int
2332 mlx5_ib_sg_to_klms(struct mlx5_ib_mr *mr,
2333 		   struct scatterlist *sgl,
2334 		   unsigned short sg_nents,
2335 		   unsigned int *sg_offset_p,
2336 		   struct scatterlist *meta_sgl,
2337 		   unsigned short meta_sg_nents,
2338 		   unsigned int *meta_sg_offset_p)
2339 {
2340 	struct scatterlist *sg = sgl;
2341 	struct mlx5_klm *klms = mr->descs;
2342 	unsigned int sg_offset = sg_offset_p ? *sg_offset_p : 0;
2343 	u32 lkey = mr->ibmr.pd->local_dma_lkey;
2344 	int i, j = 0;
2345 
2346 	mr->ibmr.iova = sg_dma_address(sg) + sg_offset;
2347 	mr->ibmr.length = 0;
2348 
2349 	for_each_sg(sgl, sg, sg_nents, i) {
2350 		if (unlikely(i >= mr->max_descs))
2351 			break;
2352 		klms[i].va = cpu_to_be64(sg_dma_address(sg) + sg_offset);
2353 		klms[i].bcount = cpu_to_be32(sg_dma_len(sg) - sg_offset);
2354 		klms[i].key = cpu_to_be32(lkey);
2355 		mr->ibmr.length += sg_dma_len(sg) - sg_offset;
2356 
2357 		sg_offset = 0;
2358 	}
2359 
2360 	if (sg_offset_p)
2361 		*sg_offset_p = sg_offset;
2362 
2363 	mr->mmkey.ndescs = i;
2364 	mr->data_length = mr->ibmr.length;
2365 
2366 	if (meta_sg_nents) {
2367 		sg = meta_sgl;
2368 		sg_offset = meta_sg_offset_p ? *meta_sg_offset_p : 0;
2369 		for_each_sg(meta_sgl, sg, meta_sg_nents, j) {
2370 			if (unlikely(i + j >= mr->max_descs))
2371 				break;
2372 			klms[i + j].va = cpu_to_be64(sg_dma_address(sg) +
2373 						     sg_offset);
2374 			klms[i + j].bcount = cpu_to_be32(sg_dma_len(sg) -
2375 							 sg_offset);
2376 			klms[i + j].key = cpu_to_be32(lkey);
2377 			mr->ibmr.length += sg_dma_len(sg) - sg_offset;
2378 
2379 			sg_offset = 0;
2380 		}
2381 		if (meta_sg_offset_p)
2382 			*meta_sg_offset_p = sg_offset;
2383 
2384 		mr->meta_ndescs = j;
2385 		mr->meta_length = mr->ibmr.length - mr->data_length;
2386 	}
2387 
2388 	return i + j;
2389 }
2390 
2391 static int mlx5_set_page(struct ib_mr *ibmr, u64 addr)
2392 {
2393 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
2394 	__be64 *descs;
2395 
2396 	if (unlikely(mr->mmkey.ndescs == mr->max_descs))
2397 		return -ENOMEM;
2398 
2399 	descs = mr->descs;
2400 	descs[mr->mmkey.ndescs++] = cpu_to_be64(addr | MLX5_EN_RD | MLX5_EN_WR);
2401 
2402 	return 0;
2403 }
2404 
2405 static int mlx5_set_page_pi(struct ib_mr *ibmr, u64 addr)
2406 {
2407 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
2408 	__be64 *descs;
2409 
2410 	if (unlikely(mr->mmkey.ndescs + mr->meta_ndescs == mr->max_descs))
2411 		return -ENOMEM;
2412 
2413 	descs = mr->descs;
2414 	descs[mr->mmkey.ndescs + mr->meta_ndescs++] =
2415 		cpu_to_be64(addr | MLX5_EN_RD | MLX5_EN_WR);
2416 
2417 	return 0;
2418 }
2419 
2420 static int
2421 mlx5_ib_map_mtt_mr_sg_pi(struct ib_mr *ibmr, struct scatterlist *data_sg,
2422 			 int data_sg_nents, unsigned int *data_sg_offset,
2423 			 struct scatterlist *meta_sg, int meta_sg_nents,
2424 			 unsigned int *meta_sg_offset)
2425 {
2426 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
2427 	struct mlx5_ib_mr *pi_mr = mr->mtt_mr;
2428 	int n;
2429 
2430 	pi_mr->mmkey.ndescs = 0;
2431 	pi_mr->meta_ndescs = 0;
2432 	pi_mr->meta_length = 0;
2433 
2434 	ib_dma_sync_single_for_cpu(ibmr->device, pi_mr->desc_map,
2435 				   pi_mr->desc_size * pi_mr->max_descs,
2436 				   DMA_TO_DEVICE);
2437 
2438 	pi_mr->ibmr.page_size = ibmr->page_size;
2439 	n = ib_sg_to_pages(&pi_mr->ibmr, data_sg, data_sg_nents, data_sg_offset,
2440 			   mlx5_set_page);
2441 	if (n != data_sg_nents)
2442 		return n;
2443 
2444 	pi_mr->data_iova = pi_mr->ibmr.iova;
2445 	pi_mr->data_length = pi_mr->ibmr.length;
2446 	pi_mr->ibmr.length = pi_mr->data_length;
2447 	ibmr->length = pi_mr->data_length;
2448 
2449 	if (meta_sg_nents) {
2450 		u64 page_mask = ~((u64)ibmr->page_size - 1);
2451 		u64 iova = pi_mr->data_iova;
2452 
2453 		n += ib_sg_to_pages(&pi_mr->ibmr, meta_sg, meta_sg_nents,
2454 				    meta_sg_offset, mlx5_set_page_pi);
2455 
2456 		pi_mr->meta_length = pi_mr->ibmr.length;
2457 		/*
2458 		 * PI address for the HW is the offset of the metadata address
2459 		 * relative to the first data page address.
2460 		 * It equals to first data page address + size of data pages +
2461 		 * metadata offset at the first metadata page
2462 		 */
2463 		pi_mr->pi_iova = (iova & page_mask) +
2464 				 pi_mr->mmkey.ndescs * ibmr->page_size +
2465 				 (pi_mr->ibmr.iova & ~page_mask);
2466 		/*
2467 		 * In order to use one MTT MR for data and metadata, we register
2468 		 * also the gaps between the end of the data and the start of
2469 		 * the metadata (the sig MR will verify that the HW will access
2470 		 * to right addresses). This mapping is safe because we use
2471 		 * internal mkey for the registration.
2472 		 */
2473 		pi_mr->ibmr.length = pi_mr->pi_iova + pi_mr->meta_length - iova;
2474 		pi_mr->ibmr.iova = iova;
2475 		ibmr->length += pi_mr->meta_length;
2476 	}
2477 
2478 	ib_dma_sync_single_for_device(ibmr->device, pi_mr->desc_map,
2479 				      pi_mr->desc_size * pi_mr->max_descs,
2480 				      DMA_TO_DEVICE);
2481 
2482 	return n;
2483 }
2484 
2485 static int
2486 mlx5_ib_map_klm_mr_sg_pi(struct ib_mr *ibmr, struct scatterlist *data_sg,
2487 			 int data_sg_nents, unsigned int *data_sg_offset,
2488 			 struct scatterlist *meta_sg, int meta_sg_nents,
2489 			 unsigned int *meta_sg_offset)
2490 {
2491 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
2492 	struct mlx5_ib_mr *pi_mr = mr->klm_mr;
2493 	int n;
2494 
2495 	pi_mr->mmkey.ndescs = 0;
2496 	pi_mr->meta_ndescs = 0;
2497 	pi_mr->meta_length = 0;
2498 
2499 	ib_dma_sync_single_for_cpu(ibmr->device, pi_mr->desc_map,
2500 				   pi_mr->desc_size * pi_mr->max_descs,
2501 				   DMA_TO_DEVICE);
2502 
2503 	n = mlx5_ib_sg_to_klms(pi_mr, data_sg, data_sg_nents, data_sg_offset,
2504 			       meta_sg, meta_sg_nents, meta_sg_offset);
2505 
2506 	ib_dma_sync_single_for_device(ibmr->device, pi_mr->desc_map,
2507 				      pi_mr->desc_size * pi_mr->max_descs,
2508 				      DMA_TO_DEVICE);
2509 
2510 	/* This is zero-based memory region */
2511 	pi_mr->data_iova = 0;
2512 	pi_mr->ibmr.iova = 0;
2513 	pi_mr->pi_iova = pi_mr->data_length;
2514 	ibmr->length = pi_mr->ibmr.length;
2515 
2516 	return n;
2517 }
2518 
2519 int mlx5_ib_map_mr_sg_pi(struct ib_mr *ibmr, struct scatterlist *data_sg,
2520 			 int data_sg_nents, unsigned int *data_sg_offset,
2521 			 struct scatterlist *meta_sg, int meta_sg_nents,
2522 			 unsigned int *meta_sg_offset)
2523 {
2524 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
2525 	struct mlx5_ib_mr *pi_mr = NULL;
2526 	int n;
2527 
2528 	WARN_ON(ibmr->type != IB_MR_TYPE_INTEGRITY);
2529 
2530 	mr->mmkey.ndescs = 0;
2531 	mr->data_length = 0;
2532 	mr->data_iova = 0;
2533 	mr->meta_ndescs = 0;
2534 	mr->pi_iova = 0;
2535 	/*
2536 	 * As a performance optimization, if possible, there is no need to
2537 	 * perform UMR operation to register the data/metadata buffers.
2538 	 * First try to map the sg lists to PA descriptors with local_dma_lkey.
2539 	 * Fallback to UMR only in case of a failure.
2540 	 */
2541 	n = mlx5_ib_map_pa_mr_sg_pi(ibmr, data_sg, data_sg_nents,
2542 				    data_sg_offset, meta_sg, meta_sg_nents,
2543 				    meta_sg_offset);
2544 	if (n == data_sg_nents + meta_sg_nents)
2545 		goto out;
2546 	/*
2547 	 * As a performance optimization, if possible, there is no need to map
2548 	 * the sg lists to KLM descriptors. First try to map the sg lists to MTT
2549 	 * descriptors and fallback to KLM only in case of a failure.
2550 	 * It's more efficient for the HW to work with MTT descriptors
2551 	 * (especially in high load).
2552 	 * Use KLM (indirect access) only if it's mandatory.
2553 	 */
2554 	pi_mr = mr->mtt_mr;
2555 	n = mlx5_ib_map_mtt_mr_sg_pi(ibmr, data_sg, data_sg_nents,
2556 				     data_sg_offset, meta_sg, meta_sg_nents,
2557 				     meta_sg_offset);
2558 	if (n == data_sg_nents + meta_sg_nents)
2559 		goto out;
2560 
2561 	pi_mr = mr->klm_mr;
2562 	n = mlx5_ib_map_klm_mr_sg_pi(ibmr, data_sg, data_sg_nents,
2563 				     data_sg_offset, meta_sg, meta_sg_nents,
2564 				     meta_sg_offset);
2565 	if (unlikely(n != data_sg_nents + meta_sg_nents))
2566 		return -ENOMEM;
2567 
2568 out:
2569 	/* This is zero-based memory region */
2570 	ibmr->iova = 0;
2571 	mr->pi_mr = pi_mr;
2572 	if (pi_mr)
2573 		ibmr->sig_attrs->meta_length = pi_mr->meta_length;
2574 	else
2575 		ibmr->sig_attrs->meta_length = mr->meta_length;
2576 
2577 	return 0;
2578 }
2579 
2580 int mlx5_ib_map_mr_sg(struct ib_mr *ibmr, struct scatterlist *sg, int sg_nents,
2581 		      unsigned int *sg_offset)
2582 {
2583 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
2584 	int n;
2585 
2586 	mr->mmkey.ndescs = 0;
2587 
2588 	ib_dma_sync_single_for_cpu(ibmr->device, mr->desc_map,
2589 				   mr->desc_size * mr->max_descs,
2590 				   DMA_TO_DEVICE);
2591 
2592 	if (mr->access_mode == MLX5_MKC_ACCESS_MODE_KLMS)
2593 		n = mlx5_ib_sg_to_klms(mr, sg, sg_nents, sg_offset, NULL, 0,
2594 				       NULL);
2595 	else
2596 		n = ib_sg_to_pages(ibmr, sg, sg_nents, sg_offset,
2597 				mlx5_set_page);
2598 
2599 	ib_dma_sync_single_for_device(ibmr->device, mr->desc_map,
2600 				      mr->desc_size * mr->max_descs,
2601 				      DMA_TO_DEVICE);
2602 
2603 	return n;
2604 }
2605