xref: /openbmc/linux/drivers/infiniband/hw/mlx5/mr.c (revision b240b419db5d624ce7a5a397d6f62a1a686009ec)
1 /*
2  * Copyright (c) 2013-2015, Mellanox Technologies. All rights reserved.
3  *
4  * This software is available to you under a choice of one of two
5  * licenses.  You may choose to be licensed under the terms of the GNU
6  * General Public License (GPL) Version 2, available from the file
7  * COPYING in the main directory of this source tree, or the
8  * OpenIB.org BSD license below:
9  *
10  *     Redistribution and use in source and binary forms, with or
11  *     without modification, are permitted provided that the following
12  *     conditions are met:
13  *
14  *      - Redistributions of source code must retain the above
15  *        copyright notice, this list of conditions and the following
16  *        disclaimer.
17  *
18  *      - Redistributions in binary form must reproduce the above
19  *        copyright notice, this list of conditions and the following
20  *        disclaimer in the documentation and/or other materials
21  *        provided with the distribution.
22  *
23  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
27  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
28  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
29  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30  * SOFTWARE.
31  */
32 
33 
34 #include <linux/kref.h>
35 #include <linux/random.h>
36 #include <linux/debugfs.h>
37 #include <linux/export.h>
38 #include <linux/delay.h>
39 #include <rdma/ib_umem.h>
40 #include <rdma/ib_umem_odp.h>
41 #include <rdma/ib_verbs.h>
42 #include "mlx5_ib.h"
43 
44 enum {
45 	MAX_PENDING_REG_MR = 8,
46 };
47 
48 #define MLX5_UMR_ALIGN 2048
49 
50 static int clean_mr(struct mlx5_ib_dev *dev, struct mlx5_ib_mr *mr);
51 static int dereg_mr(struct mlx5_ib_dev *dev, struct mlx5_ib_mr *mr);
52 static int mr_cache_max_order(struct mlx5_ib_dev *dev);
53 static int unreg_umr(struct mlx5_ib_dev *dev, struct mlx5_ib_mr *mr);
54 
55 static int destroy_mkey(struct mlx5_ib_dev *dev, struct mlx5_ib_mr *mr)
56 {
57 	int err = mlx5_core_destroy_mkey(dev->mdev, &mr->mmkey);
58 
59 #ifdef CONFIG_INFINIBAND_ON_DEMAND_PAGING
60 	/* Wait until all page fault handlers using the mr complete. */
61 	synchronize_srcu(&dev->mr_srcu);
62 #endif
63 
64 	return err;
65 }
66 
67 static int order2idx(struct mlx5_ib_dev *dev, int order)
68 {
69 	struct mlx5_mr_cache *cache = &dev->cache;
70 
71 	if (order < cache->ent[0].order)
72 		return 0;
73 	else
74 		return order - cache->ent[0].order;
75 }
76 
77 static bool use_umr_mtt_update(struct mlx5_ib_mr *mr, u64 start, u64 length)
78 {
79 	return ((u64)1 << mr->order) * MLX5_ADAPTER_PAGE_SIZE >=
80 		length + (start & (MLX5_ADAPTER_PAGE_SIZE - 1));
81 }
82 
83 #ifdef CONFIG_INFINIBAND_ON_DEMAND_PAGING
84 static void update_odp_mr(struct mlx5_ib_mr *mr)
85 {
86 	if (mr->umem->odp_data) {
87 		/*
88 		 * This barrier prevents the compiler from moving the
89 		 * setting of umem->odp_data->private to point to our
90 		 * MR, before reg_umr finished, to ensure that the MR
91 		 * initialization have finished before starting to
92 		 * handle invalidations.
93 		 */
94 		smp_wmb();
95 		mr->umem->odp_data->private = mr;
96 		/*
97 		 * Make sure we will see the new
98 		 * umem->odp_data->private value in the invalidation
99 		 * routines, before we can get page faults on the
100 		 * MR. Page faults can happen once we put the MR in
101 		 * the tree, below this line. Without the barrier,
102 		 * there can be a fault handling and an invalidation
103 		 * before umem->odp_data->private == mr is visible to
104 		 * the invalidation handler.
105 		 */
106 		smp_wmb();
107 	}
108 }
109 #endif
110 
111 static void reg_mr_callback(int status, void *context)
112 {
113 	struct mlx5_ib_mr *mr = context;
114 	struct mlx5_ib_dev *dev = mr->dev;
115 	struct mlx5_mr_cache *cache = &dev->cache;
116 	int c = order2idx(dev, mr->order);
117 	struct mlx5_cache_ent *ent = &cache->ent[c];
118 	u8 key;
119 	unsigned long flags;
120 	struct mlx5_mkey_table *table = &dev->mdev->priv.mkey_table;
121 	int err;
122 
123 	spin_lock_irqsave(&ent->lock, flags);
124 	ent->pending--;
125 	spin_unlock_irqrestore(&ent->lock, flags);
126 	if (status) {
127 		mlx5_ib_warn(dev, "async reg mr failed. status %d\n", status);
128 		kfree(mr);
129 		dev->fill_delay = 1;
130 		mod_timer(&dev->delay_timer, jiffies + HZ);
131 		return;
132 	}
133 
134 	mr->mmkey.type = MLX5_MKEY_MR;
135 	spin_lock_irqsave(&dev->mdev->priv.mkey_lock, flags);
136 	key = dev->mdev->priv.mkey_key++;
137 	spin_unlock_irqrestore(&dev->mdev->priv.mkey_lock, flags);
138 	mr->mmkey.key = mlx5_idx_to_mkey(MLX5_GET(create_mkey_out, mr->out, mkey_index)) | key;
139 
140 	cache->last_add = jiffies;
141 
142 	spin_lock_irqsave(&ent->lock, flags);
143 	list_add_tail(&mr->list, &ent->head);
144 	ent->cur++;
145 	ent->size++;
146 	spin_unlock_irqrestore(&ent->lock, flags);
147 
148 	write_lock_irqsave(&table->lock, flags);
149 	err = radix_tree_insert(&table->tree, mlx5_base_mkey(mr->mmkey.key),
150 				&mr->mmkey);
151 	if (err)
152 		pr_err("Error inserting to mkey tree. 0x%x\n", -err);
153 	write_unlock_irqrestore(&table->lock, flags);
154 
155 	if (!completion_done(&ent->compl))
156 		complete(&ent->compl);
157 }
158 
159 static int add_keys(struct mlx5_ib_dev *dev, int c, int num)
160 {
161 	struct mlx5_mr_cache *cache = &dev->cache;
162 	struct mlx5_cache_ent *ent = &cache->ent[c];
163 	int inlen = MLX5_ST_SZ_BYTES(create_mkey_in);
164 	struct mlx5_ib_mr *mr;
165 	void *mkc;
166 	u32 *in;
167 	int err = 0;
168 	int i;
169 
170 	in = kzalloc(inlen, GFP_KERNEL);
171 	if (!in)
172 		return -ENOMEM;
173 
174 	mkc = MLX5_ADDR_OF(create_mkey_in, in, memory_key_mkey_entry);
175 	for (i = 0; i < num; i++) {
176 		if (ent->pending >= MAX_PENDING_REG_MR) {
177 			err = -EAGAIN;
178 			break;
179 		}
180 
181 		mr = kzalloc(sizeof(*mr), GFP_KERNEL);
182 		if (!mr) {
183 			err = -ENOMEM;
184 			break;
185 		}
186 		mr->order = ent->order;
187 		mr->allocated_from_cache = 1;
188 		mr->dev = dev;
189 
190 		MLX5_SET(mkc, mkc, free, 1);
191 		MLX5_SET(mkc, mkc, umr_en, 1);
192 		MLX5_SET(mkc, mkc, access_mode, ent->access_mode);
193 
194 		MLX5_SET(mkc, mkc, qpn, 0xffffff);
195 		MLX5_SET(mkc, mkc, translations_octword_size, ent->xlt);
196 		MLX5_SET(mkc, mkc, log_page_size, ent->page);
197 
198 		spin_lock_irq(&ent->lock);
199 		ent->pending++;
200 		spin_unlock_irq(&ent->lock);
201 		err = mlx5_core_create_mkey_cb(dev->mdev, &mr->mmkey,
202 					       in, inlen,
203 					       mr->out, sizeof(mr->out),
204 					       reg_mr_callback, mr);
205 		if (err) {
206 			spin_lock_irq(&ent->lock);
207 			ent->pending--;
208 			spin_unlock_irq(&ent->lock);
209 			mlx5_ib_warn(dev, "create mkey failed %d\n", err);
210 			kfree(mr);
211 			break;
212 		}
213 	}
214 
215 	kfree(in);
216 	return err;
217 }
218 
219 static void remove_keys(struct mlx5_ib_dev *dev, int c, int num)
220 {
221 	struct mlx5_mr_cache *cache = &dev->cache;
222 	struct mlx5_cache_ent *ent = &cache->ent[c];
223 	struct mlx5_ib_mr *mr;
224 	int err;
225 	int i;
226 
227 	for (i = 0; i < num; i++) {
228 		spin_lock_irq(&ent->lock);
229 		if (list_empty(&ent->head)) {
230 			spin_unlock_irq(&ent->lock);
231 			return;
232 		}
233 		mr = list_first_entry(&ent->head, struct mlx5_ib_mr, list);
234 		list_del(&mr->list);
235 		ent->cur--;
236 		ent->size--;
237 		spin_unlock_irq(&ent->lock);
238 		err = destroy_mkey(dev, mr);
239 		if (err)
240 			mlx5_ib_warn(dev, "failed destroy mkey\n");
241 		else
242 			kfree(mr);
243 	}
244 }
245 
246 static ssize_t size_write(struct file *filp, const char __user *buf,
247 			  size_t count, loff_t *pos)
248 {
249 	struct mlx5_cache_ent *ent = filp->private_data;
250 	struct mlx5_ib_dev *dev = ent->dev;
251 	char lbuf[20];
252 	u32 var;
253 	int err;
254 	int c;
255 
256 	if (copy_from_user(lbuf, buf, sizeof(lbuf)))
257 		return -EFAULT;
258 
259 	c = order2idx(dev, ent->order);
260 	lbuf[sizeof(lbuf) - 1] = 0;
261 
262 	if (sscanf(lbuf, "%u", &var) != 1)
263 		return -EINVAL;
264 
265 	if (var < ent->limit)
266 		return -EINVAL;
267 
268 	if (var > ent->size) {
269 		do {
270 			err = add_keys(dev, c, var - ent->size);
271 			if (err && err != -EAGAIN)
272 				return err;
273 
274 			usleep_range(3000, 5000);
275 		} while (err);
276 	} else if (var < ent->size) {
277 		remove_keys(dev, c, ent->size - var);
278 	}
279 
280 	return count;
281 }
282 
283 static ssize_t size_read(struct file *filp, char __user *buf, size_t count,
284 			 loff_t *pos)
285 {
286 	struct mlx5_cache_ent *ent = filp->private_data;
287 	char lbuf[20];
288 	int err;
289 
290 	if (*pos)
291 		return 0;
292 
293 	err = snprintf(lbuf, sizeof(lbuf), "%d\n", ent->size);
294 	if (err < 0)
295 		return err;
296 
297 	if (copy_to_user(buf, lbuf, err))
298 		return -EFAULT;
299 
300 	*pos += err;
301 
302 	return err;
303 }
304 
305 static const struct file_operations size_fops = {
306 	.owner	= THIS_MODULE,
307 	.open	= simple_open,
308 	.write	= size_write,
309 	.read	= size_read,
310 };
311 
312 static ssize_t limit_write(struct file *filp, const char __user *buf,
313 			   size_t count, loff_t *pos)
314 {
315 	struct mlx5_cache_ent *ent = filp->private_data;
316 	struct mlx5_ib_dev *dev = ent->dev;
317 	char lbuf[20];
318 	u32 var;
319 	int err;
320 	int c;
321 
322 	if (copy_from_user(lbuf, buf, sizeof(lbuf)))
323 		return -EFAULT;
324 
325 	c = order2idx(dev, ent->order);
326 	lbuf[sizeof(lbuf) - 1] = 0;
327 
328 	if (sscanf(lbuf, "%u", &var) != 1)
329 		return -EINVAL;
330 
331 	if (var > ent->size)
332 		return -EINVAL;
333 
334 	ent->limit = var;
335 
336 	if (ent->cur < ent->limit) {
337 		err = add_keys(dev, c, 2 * ent->limit - ent->cur);
338 		if (err)
339 			return err;
340 	}
341 
342 	return count;
343 }
344 
345 static ssize_t limit_read(struct file *filp, char __user *buf, size_t count,
346 			  loff_t *pos)
347 {
348 	struct mlx5_cache_ent *ent = filp->private_data;
349 	char lbuf[20];
350 	int err;
351 
352 	if (*pos)
353 		return 0;
354 
355 	err = snprintf(lbuf, sizeof(lbuf), "%d\n", ent->limit);
356 	if (err < 0)
357 		return err;
358 
359 	if (copy_to_user(buf, lbuf, err))
360 		return -EFAULT;
361 
362 	*pos += err;
363 
364 	return err;
365 }
366 
367 static const struct file_operations limit_fops = {
368 	.owner	= THIS_MODULE,
369 	.open	= simple_open,
370 	.write	= limit_write,
371 	.read	= limit_read,
372 };
373 
374 static int someone_adding(struct mlx5_mr_cache *cache)
375 {
376 	int i;
377 
378 	for (i = 0; i < MAX_MR_CACHE_ENTRIES; i++) {
379 		if (cache->ent[i].cur < cache->ent[i].limit)
380 			return 1;
381 	}
382 
383 	return 0;
384 }
385 
386 static void __cache_work_func(struct mlx5_cache_ent *ent)
387 {
388 	struct mlx5_ib_dev *dev = ent->dev;
389 	struct mlx5_mr_cache *cache = &dev->cache;
390 	int i = order2idx(dev, ent->order);
391 	int err;
392 
393 	if (cache->stopped)
394 		return;
395 
396 	ent = &dev->cache.ent[i];
397 	if (ent->cur < 2 * ent->limit && !dev->fill_delay) {
398 		err = add_keys(dev, i, 1);
399 		if (ent->cur < 2 * ent->limit) {
400 			if (err == -EAGAIN) {
401 				mlx5_ib_dbg(dev, "returned eagain, order %d\n",
402 					    i + 2);
403 				queue_delayed_work(cache->wq, &ent->dwork,
404 						   msecs_to_jiffies(3));
405 			} else if (err) {
406 				mlx5_ib_warn(dev, "command failed order %d, err %d\n",
407 					     i + 2, err);
408 				queue_delayed_work(cache->wq, &ent->dwork,
409 						   msecs_to_jiffies(1000));
410 			} else {
411 				queue_work(cache->wq, &ent->work);
412 			}
413 		}
414 	} else if (ent->cur > 2 * ent->limit) {
415 		/*
416 		 * The remove_keys() logic is performed as garbage collection
417 		 * task. Such task is intended to be run when no other active
418 		 * processes are running.
419 		 *
420 		 * The need_resched() will return TRUE if there are user tasks
421 		 * to be activated in near future.
422 		 *
423 		 * In such case, we don't execute remove_keys() and postpone
424 		 * the garbage collection work to try to run in next cycle,
425 		 * in order to free CPU resources to other tasks.
426 		 */
427 		if (!need_resched() && !someone_adding(cache) &&
428 		    time_after(jiffies, cache->last_add + 300 * HZ)) {
429 			remove_keys(dev, i, 1);
430 			if (ent->cur > ent->limit)
431 				queue_work(cache->wq, &ent->work);
432 		} else {
433 			queue_delayed_work(cache->wq, &ent->dwork, 300 * HZ);
434 		}
435 	}
436 }
437 
438 static void delayed_cache_work_func(struct work_struct *work)
439 {
440 	struct mlx5_cache_ent *ent;
441 
442 	ent = container_of(work, struct mlx5_cache_ent, dwork.work);
443 	__cache_work_func(ent);
444 }
445 
446 static void cache_work_func(struct work_struct *work)
447 {
448 	struct mlx5_cache_ent *ent;
449 
450 	ent = container_of(work, struct mlx5_cache_ent, work);
451 	__cache_work_func(ent);
452 }
453 
454 struct mlx5_ib_mr *mlx5_mr_cache_alloc(struct mlx5_ib_dev *dev, int entry)
455 {
456 	struct mlx5_mr_cache *cache = &dev->cache;
457 	struct mlx5_cache_ent *ent;
458 	struct mlx5_ib_mr *mr;
459 	int err;
460 
461 	if (entry < 0 || entry >= MAX_MR_CACHE_ENTRIES) {
462 		mlx5_ib_err(dev, "cache entry %d is out of range\n", entry);
463 		return NULL;
464 	}
465 
466 	ent = &cache->ent[entry];
467 	while (1) {
468 		spin_lock_irq(&ent->lock);
469 		if (list_empty(&ent->head)) {
470 			spin_unlock_irq(&ent->lock);
471 
472 			err = add_keys(dev, entry, 1);
473 			if (err && err != -EAGAIN)
474 				return ERR_PTR(err);
475 
476 			wait_for_completion(&ent->compl);
477 		} else {
478 			mr = list_first_entry(&ent->head, struct mlx5_ib_mr,
479 					      list);
480 			list_del(&mr->list);
481 			ent->cur--;
482 			spin_unlock_irq(&ent->lock);
483 			if (ent->cur < ent->limit)
484 				queue_work(cache->wq, &ent->work);
485 			return mr;
486 		}
487 	}
488 }
489 
490 static struct mlx5_ib_mr *alloc_cached_mr(struct mlx5_ib_dev *dev, int order)
491 {
492 	struct mlx5_mr_cache *cache = &dev->cache;
493 	struct mlx5_ib_mr *mr = NULL;
494 	struct mlx5_cache_ent *ent;
495 	int last_umr_cache_entry;
496 	int c;
497 	int i;
498 
499 	c = order2idx(dev, order);
500 	last_umr_cache_entry = order2idx(dev, mr_cache_max_order(dev));
501 	if (c < 0 || c > last_umr_cache_entry) {
502 		mlx5_ib_warn(dev, "order %d, cache index %d\n", order, c);
503 		return NULL;
504 	}
505 
506 	for (i = c; i <= last_umr_cache_entry; i++) {
507 		ent = &cache->ent[i];
508 
509 		mlx5_ib_dbg(dev, "order %d, cache index %d\n", ent->order, i);
510 
511 		spin_lock_irq(&ent->lock);
512 		if (!list_empty(&ent->head)) {
513 			mr = list_first_entry(&ent->head, struct mlx5_ib_mr,
514 					      list);
515 			list_del(&mr->list);
516 			ent->cur--;
517 			spin_unlock_irq(&ent->lock);
518 			if (ent->cur < ent->limit)
519 				queue_work(cache->wq, &ent->work);
520 			break;
521 		}
522 		spin_unlock_irq(&ent->lock);
523 
524 		queue_work(cache->wq, &ent->work);
525 	}
526 
527 	if (!mr)
528 		cache->ent[c].miss++;
529 
530 	return mr;
531 }
532 
533 void mlx5_mr_cache_free(struct mlx5_ib_dev *dev, struct mlx5_ib_mr *mr)
534 {
535 	struct mlx5_mr_cache *cache = &dev->cache;
536 	struct mlx5_cache_ent *ent;
537 	int shrink = 0;
538 	int c;
539 
540 	c = order2idx(dev, mr->order);
541 	if (c < 0 || c >= MAX_MR_CACHE_ENTRIES) {
542 		mlx5_ib_warn(dev, "order %d, cache index %d\n", mr->order, c);
543 		return;
544 	}
545 
546 	if (unreg_umr(dev, mr))
547 		return;
548 
549 	ent = &cache->ent[c];
550 	spin_lock_irq(&ent->lock);
551 	list_add_tail(&mr->list, &ent->head);
552 	ent->cur++;
553 	if (ent->cur > 2 * ent->limit)
554 		shrink = 1;
555 	spin_unlock_irq(&ent->lock);
556 
557 	if (shrink)
558 		queue_work(cache->wq, &ent->work);
559 }
560 
561 static void clean_keys(struct mlx5_ib_dev *dev, int c)
562 {
563 	struct mlx5_mr_cache *cache = &dev->cache;
564 	struct mlx5_cache_ent *ent = &cache->ent[c];
565 	struct mlx5_ib_mr *mr;
566 	int err;
567 
568 	cancel_delayed_work(&ent->dwork);
569 	while (1) {
570 		spin_lock_irq(&ent->lock);
571 		if (list_empty(&ent->head)) {
572 			spin_unlock_irq(&ent->lock);
573 			return;
574 		}
575 		mr = list_first_entry(&ent->head, struct mlx5_ib_mr, list);
576 		list_del(&mr->list);
577 		ent->cur--;
578 		ent->size--;
579 		spin_unlock_irq(&ent->lock);
580 		err = destroy_mkey(dev, mr);
581 		if (err)
582 			mlx5_ib_warn(dev, "failed destroy mkey\n");
583 		else
584 			kfree(mr);
585 	}
586 }
587 
588 static void mlx5_mr_cache_debugfs_cleanup(struct mlx5_ib_dev *dev)
589 {
590 	if (!mlx5_debugfs_root || dev->rep)
591 		return;
592 
593 	debugfs_remove_recursive(dev->cache.root);
594 	dev->cache.root = NULL;
595 }
596 
597 static int mlx5_mr_cache_debugfs_init(struct mlx5_ib_dev *dev)
598 {
599 	struct mlx5_mr_cache *cache = &dev->cache;
600 	struct mlx5_cache_ent *ent;
601 	int i;
602 
603 	if (!mlx5_debugfs_root || dev->rep)
604 		return 0;
605 
606 	cache->root = debugfs_create_dir("mr_cache", dev->mdev->priv.dbg_root);
607 	if (!cache->root)
608 		return -ENOMEM;
609 
610 	for (i = 0; i < MAX_MR_CACHE_ENTRIES; i++) {
611 		ent = &cache->ent[i];
612 		sprintf(ent->name, "%d", ent->order);
613 		ent->dir = debugfs_create_dir(ent->name,  cache->root);
614 		if (!ent->dir)
615 			goto err;
616 
617 		ent->fsize = debugfs_create_file("size", 0600, ent->dir, ent,
618 						 &size_fops);
619 		if (!ent->fsize)
620 			goto err;
621 
622 		ent->flimit = debugfs_create_file("limit", 0600, ent->dir, ent,
623 						  &limit_fops);
624 		if (!ent->flimit)
625 			goto err;
626 
627 		ent->fcur = debugfs_create_u32("cur", 0400, ent->dir,
628 					       &ent->cur);
629 		if (!ent->fcur)
630 			goto err;
631 
632 		ent->fmiss = debugfs_create_u32("miss", 0600, ent->dir,
633 						&ent->miss);
634 		if (!ent->fmiss)
635 			goto err;
636 	}
637 
638 	return 0;
639 err:
640 	mlx5_mr_cache_debugfs_cleanup(dev);
641 
642 	return -ENOMEM;
643 }
644 
645 static void delay_time_func(struct timer_list *t)
646 {
647 	struct mlx5_ib_dev *dev = from_timer(dev, t, delay_timer);
648 
649 	dev->fill_delay = 0;
650 }
651 
652 int mlx5_mr_cache_init(struct mlx5_ib_dev *dev)
653 {
654 	struct mlx5_mr_cache *cache = &dev->cache;
655 	struct mlx5_cache_ent *ent;
656 	int err;
657 	int i;
658 
659 	mutex_init(&dev->slow_path_mutex);
660 	cache->wq = alloc_ordered_workqueue("mkey_cache", WQ_MEM_RECLAIM);
661 	if (!cache->wq) {
662 		mlx5_ib_warn(dev, "failed to create work queue\n");
663 		return -ENOMEM;
664 	}
665 
666 	timer_setup(&dev->delay_timer, delay_time_func, 0);
667 	for (i = 0; i < MAX_MR_CACHE_ENTRIES; i++) {
668 		ent = &cache->ent[i];
669 		INIT_LIST_HEAD(&ent->head);
670 		spin_lock_init(&ent->lock);
671 		ent->order = i + 2;
672 		ent->dev = dev;
673 		ent->limit = 0;
674 
675 		init_completion(&ent->compl);
676 		INIT_WORK(&ent->work, cache_work_func);
677 		INIT_DELAYED_WORK(&ent->dwork, delayed_cache_work_func);
678 		queue_work(cache->wq, &ent->work);
679 
680 		if (i > MR_CACHE_LAST_STD_ENTRY) {
681 			mlx5_odp_init_mr_cache_entry(ent);
682 			continue;
683 		}
684 
685 		if (ent->order > mr_cache_max_order(dev))
686 			continue;
687 
688 		ent->page = PAGE_SHIFT;
689 		ent->xlt = (1 << ent->order) * sizeof(struct mlx5_mtt) /
690 			   MLX5_IB_UMR_OCTOWORD;
691 		ent->access_mode = MLX5_MKC_ACCESS_MODE_MTT;
692 		if ((dev->mdev->profile->mask & MLX5_PROF_MASK_MR_CACHE) &&
693 		    !dev->rep &&
694 		    mlx5_core_is_pf(dev->mdev))
695 			ent->limit = dev->mdev->profile->mr_cache[i].limit;
696 		else
697 			ent->limit = 0;
698 	}
699 
700 	err = mlx5_mr_cache_debugfs_init(dev);
701 	if (err)
702 		mlx5_ib_warn(dev, "cache debugfs failure\n");
703 
704 	/*
705 	 * We don't want to fail driver if debugfs failed to initialize,
706 	 * so we are not forwarding error to the user.
707 	 */
708 
709 	return 0;
710 }
711 
712 static void wait_for_async_commands(struct mlx5_ib_dev *dev)
713 {
714 	struct mlx5_mr_cache *cache = &dev->cache;
715 	struct mlx5_cache_ent *ent;
716 	int total = 0;
717 	int i;
718 	int j;
719 
720 	for (i = 0; i < MAX_MR_CACHE_ENTRIES; i++) {
721 		ent = &cache->ent[i];
722 		for (j = 0 ; j < 1000; j++) {
723 			if (!ent->pending)
724 				break;
725 			msleep(50);
726 		}
727 	}
728 	for (i = 0; i < MAX_MR_CACHE_ENTRIES; i++) {
729 		ent = &cache->ent[i];
730 		total += ent->pending;
731 	}
732 
733 	if (total)
734 		mlx5_ib_warn(dev, "aborted while there are %d pending mr requests\n", total);
735 	else
736 		mlx5_ib_warn(dev, "done with all pending requests\n");
737 }
738 
739 int mlx5_mr_cache_cleanup(struct mlx5_ib_dev *dev)
740 {
741 	int i;
742 
743 	if (!dev->cache.wq)
744 		return 0;
745 
746 	dev->cache.stopped = 1;
747 	flush_workqueue(dev->cache.wq);
748 
749 	mlx5_mr_cache_debugfs_cleanup(dev);
750 
751 	for (i = 0; i < MAX_MR_CACHE_ENTRIES; i++)
752 		clean_keys(dev, i);
753 
754 	destroy_workqueue(dev->cache.wq);
755 	wait_for_async_commands(dev);
756 	del_timer_sync(&dev->delay_timer);
757 
758 	return 0;
759 }
760 
761 struct ib_mr *mlx5_ib_get_dma_mr(struct ib_pd *pd, int acc)
762 {
763 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
764 	int inlen = MLX5_ST_SZ_BYTES(create_mkey_in);
765 	struct mlx5_core_dev *mdev = dev->mdev;
766 	struct mlx5_ib_mr *mr;
767 	void *mkc;
768 	u32 *in;
769 	int err;
770 
771 	mr = kzalloc(sizeof(*mr), GFP_KERNEL);
772 	if (!mr)
773 		return ERR_PTR(-ENOMEM);
774 
775 	in = kzalloc(inlen, GFP_KERNEL);
776 	if (!in) {
777 		err = -ENOMEM;
778 		goto err_free;
779 	}
780 
781 	mkc = MLX5_ADDR_OF(create_mkey_in, in, memory_key_mkey_entry);
782 
783 	MLX5_SET(mkc, mkc, access_mode, MLX5_MKC_ACCESS_MODE_PA);
784 	MLX5_SET(mkc, mkc, a, !!(acc & IB_ACCESS_REMOTE_ATOMIC));
785 	MLX5_SET(mkc, mkc, rw, !!(acc & IB_ACCESS_REMOTE_WRITE));
786 	MLX5_SET(mkc, mkc, rr, !!(acc & IB_ACCESS_REMOTE_READ));
787 	MLX5_SET(mkc, mkc, lw, !!(acc & IB_ACCESS_LOCAL_WRITE));
788 	MLX5_SET(mkc, mkc, lr, 1);
789 
790 	MLX5_SET(mkc, mkc, length64, 1);
791 	MLX5_SET(mkc, mkc, pd, to_mpd(pd)->pdn);
792 	MLX5_SET(mkc, mkc, qpn, 0xffffff);
793 	MLX5_SET64(mkc, mkc, start_addr, 0);
794 
795 	err = mlx5_core_create_mkey(mdev, &mr->mmkey, in, inlen);
796 	if (err)
797 		goto err_in;
798 
799 	kfree(in);
800 	mr->mmkey.type = MLX5_MKEY_MR;
801 	mr->ibmr.lkey = mr->mmkey.key;
802 	mr->ibmr.rkey = mr->mmkey.key;
803 	mr->umem = NULL;
804 
805 	return &mr->ibmr;
806 
807 err_in:
808 	kfree(in);
809 
810 err_free:
811 	kfree(mr);
812 
813 	return ERR_PTR(err);
814 }
815 
816 static int get_octo_len(u64 addr, u64 len, int page_shift)
817 {
818 	u64 page_size = 1ULL << page_shift;
819 	u64 offset;
820 	int npages;
821 
822 	offset = addr & (page_size - 1);
823 	npages = ALIGN(len + offset, page_size) >> page_shift;
824 	return (npages + 1) / 2;
825 }
826 
827 static int mr_cache_max_order(struct mlx5_ib_dev *dev)
828 {
829 	if (MLX5_CAP_GEN(dev->mdev, umr_extended_translation_offset))
830 		return MR_CACHE_LAST_STD_ENTRY + 2;
831 	return MLX5_MAX_UMR_SHIFT;
832 }
833 
834 static int mr_umem_get(struct ib_pd *pd, u64 start, u64 length,
835 		       int access_flags, struct ib_umem **umem,
836 		       int *npages, int *page_shift, int *ncont,
837 		       int *order)
838 {
839 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
840 	int err;
841 
842 	*umem = ib_umem_get(pd->uobject->context, start, length,
843 			    access_flags, 0);
844 	err = PTR_ERR_OR_ZERO(*umem);
845 	if (err) {
846 		*umem = NULL;
847 		mlx5_ib_err(dev, "umem get failed (%d)\n", err);
848 		return err;
849 	}
850 
851 	mlx5_ib_cont_pages(*umem, start, MLX5_MKEY_PAGE_SHIFT_MASK, npages,
852 			   page_shift, ncont, order);
853 	if (!*npages) {
854 		mlx5_ib_warn(dev, "avoid zero region\n");
855 		ib_umem_release(*umem);
856 		return -EINVAL;
857 	}
858 
859 	mlx5_ib_dbg(dev, "npages %d, ncont %d, order %d, page_shift %d\n",
860 		    *npages, *ncont, *order, *page_shift);
861 
862 	return 0;
863 }
864 
865 static void mlx5_ib_umr_done(struct ib_cq *cq, struct ib_wc *wc)
866 {
867 	struct mlx5_ib_umr_context *context =
868 		container_of(wc->wr_cqe, struct mlx5_ib_umr_context, cqe);
869 
870 	context->status = wc->status;
871 	complete(&context->done);
872 }
873 
874 static inline void mlx5_ib_init_umr_context(struct mlx5_ib_umr_context *context)
875 {
876 	context->cqe.done = mlx5_ib_umr_done;
877 	context->status = -1;
878 	init_completion(&context->done);
879 }
880 
881 static int mlx5_ib_post_send_wait(struct mlx5_ib_dev *dev,
882 				  struct mlx5_umr_wr *umrwr)
883 {
884 	struct umr_common *umrc = &dev->umrc;
885 	struct ib_send_wr *bad;
886 	int err;
887 	struct mlx5_ib_umr_context umr_context;
888 
889 	mlx5_ib_init_umr_context(&umr_context);
890 	umrwr->wr.wr_cqe = &umr_context.cqe;
891 
892 	down(&umrc->sem);
893 	err = ib_post_send(umrc->qp, &umrwr->wr, &bad);
894 	if (err) {
895 		mlx5_ib_warn(dev, "UMR post send failed, err %d\n", err);
896 	} else {
897 		wait_for_completion(&umr_context.done);
898 		if (umr_context.status != IB_WC_SUCCESS) {
899 			mlx5_ib_warn(dev, "reg umr failed (%u)\n",
900 				     umr_context.status);
901 			err = -EFAULT;
902 		}
903 	}
904 	up(&umrc->sem);
905 	return err;
906 }
907 
908 static struct mlx5_ib_mr *alloc_mr_from_cache(
909 				  struct ib_pd *pd, struct ib_umem *umem,
910 				  u64 virt_addr, u64 len, int npages,
911 				  int page_shift, int order, int access_flags)
912 {
913 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
914 	struct mlx5_ib_mr *mr;
915 	int err = 0;
916 	int i;
917 
918 	for (i = 0; i < 1; i++) {
919 		mr = alloc_cached_mr(dev, order);
920 		if (mr)
921 			break;
922 
923 		err = add_keys(dev, order2idx(dev, order), 1);
924 		if (err && err != -EAGAIN) {
925 			mlx5_ib_warn(dev, "add_keys failed, err %d\n", err);
926 			break;
927 		}
928 	}
929 
930 	if (!mr)
931 		return ERR_PTR(-EAGAIN);
932 
933 	mr->ibmr.pd = pd;
934 	mr->umem = umem;
935 	mr->access_flags = access_flags;
936 	mr->desc_size = sizeof(struct mlx5_mtt);
937 	mr->mmkey.iova = virt_addr;
938 	mr->mmkey.size = len;
939 	mr->mmkey.pd = to_mpd(pd)->pdn;
940 
941 	return mr;
942 }
943 
944 static inline int populate_xlt(struct mlx5_ib_mr *mr, int idx, int npages,
945 			       void *xlt, int page_shift, size_t size,
946 			       int flags)
947 {
948 	struct mlx5_ib_dev *dev = mr->dev;
949 	struct ib_umem *umem = mr->umem;
950 	if (flags & MLX5_IB_UPD_XLT_INDIRECT) {
951 		mlx5_odp_populate_klm(xlt, idx, npages, mr, flags);
952 		return npages;
953 	}
954 
955 	npages = min_t(size_t, npages, ib_umem_num_pages(umem) - idx);
956 
957 	if (!(flags & MLX5_IB_UPD_XLT_ZAP)) {
958 		__mlx5_ib_populate_pas(dev, umem, page_shift,
959 				       idx, npages, xlt,
960 				       MLX5_IB_MTT_PRESENT);
961 		/* Clear padding after the pages
962 		 * brought from the umem.
963 		 */
964 		memset(xlt + (npages * sizeof(struct mlx5_mtt)), 0,
965 		       size - npages * sizeof(struct mlx5_mtt));
966 	}
967 
968 	return npages;
969 }
970 
971 #define MLX5_MAX_UMR_CHUNK ((1 << (MLX5_MAX_UMR_SHIFT + 4)) - \
972 			    MLX5_UMR_MTT_ALIGNMENT)
973 #define MLX5_SPARE_UMR_CHUNK 0x10000
974 
975 int mlx5_ib_update_xlt(struct mlx5_ib_mr *mr, u64 idx, int npages,
976 		       int page_shift, int flags)
977 {
978 	struct mlx5_ib_dev *dev = mr->dev;
979 	struct device *ddev = dev->ib_dev.dev.parent;
980 	struct mlx5_ib_ucontext *uctx = NULL;
981 	int size;
982 	void *xlt;
983 	dma_addr_t dma;
984 	struct mlx5_umr_wr wr;
985 	struct ib_sge sg;
986 	int err = 0;
987 	int desc_size = (flags & MLX5_IB_UPD_XLT_INDIRECT)
988 			       ? sizeof(struct mlx5_klm)
989 			       : sizeof(struct mlx5_mtt);
990 	const int page_align = MLX5_UMR_MTT_ALIGNMENT / desc_size;
991 	const int page_mask = page_align - 1;
992 	size_t pages_mapped = 0;
993 	size_t pages_to_map = 0;
994 	size_t pages_iter = 0;
995 	gfp_t gfp;
996 
997 	/* UMR copies MTTs in units of MLX5_UMR_MTT_ALIGNMENT bytes,
998 	 * so we need to align the offset and length accordingly
999 	 */
1000 	if (idx & page_mask) {
1001 		npages += idx & page_mask;
1002 		idx &= ~page_mask;
1003 	}
1004 
1005 	gfp = flags & MLX5_IB_UPD_XLT_ATOMIC ? GFP_ATOMIC : GFP_KERNEL;
1006 	gfp |= __GFP_ZERO | __GFP_NOWARN;
1007 
1008 	pages_to_map = ALIGN(npages, page_align);
1009 	size = desc_size * pages_to_map;
1010 	size = min_t(int, size, MLX5_MAX_UMR_CHUNK);
1011 
1012 	xlt = (void *)__get_free_pages(gfp, get_order(size));
1013 	if (!xlt && size > MLX5_SPARE_UMR_CHUNK) {
1014 		mlx5_ib_dbg(dev, "Failed to allocate %d bytes of order %d. fallback to spare UMR allocation od %d bytes\n",
1015 			    size, get_order(size), MLX5_SPARE_UMR_CHUNK);
1016 
1017 		size = MLX5_SPARE_UMR_CHUNK;
1018 		xlt = (void *)__get_free_pages(gfp, get_order(size));
1019 	}
1020 
1021 	if (!xlt) {
1022 		uctx = to_mucontext(mr->ibmr.pd->uobject->context);
1023 		mlx5_ib_warn(dev, "Using XLT emergency buffer\n");
1024 		size = PAGE_SIZE;
1025 		xlt = (void *)uctx->upd_xlt_page;
1026 		mutex_lock(&uctx->upd_xlt_page_mutex);
1027 		memset(xlt, 0, size);
1028 	}
1029 	pages_iter = size / desc_size;
1030 	dma = dma_map_single(ddev, xlt, size, DMA_TO_DEVICE);
1031 	if (dma_mapping_error(ddev, dma)) {
1032 		mlx5_ib_err(dev, "unable to map DMA during XLT update.\n");
1033 		err = -ENOMEM;
1034 		goto free_xlt;
1035 	}
1036 
1037 	sg.addr = dma;
1038 	sg.lkey = dev->umrc.pd->local_dma_lkey;
1039 
1040 	memset(&wr, 0, sizeof(wr));
1041 	wr.wr.send_flags = MLX5_IB_SEND_UMR_UPDATE_XLT;
1042 	if (!(flags & MLX5_IB_UPD_XLT_ENABLE))
1043 		wr.wr.send_flags |= MLX5_IB_SEND_UMR_FAIL_IF_FREE;
1044 	wr.wr.sg_list = &sg;
1045 	wr.wr.num_sge = 1;
1046 	wr.wr.opcode = MLX5_IB_WR_UMR;
1047 
1048 	wr.pd = mr->ibmr.pd;
1049 	wr.mkey = mr->mmkey.key;
1050 	wr.length = mr->mmkey.size;
1051 	wr.virt_addr = mr->mmkey.iova;
1052 	wr.access_flags = mr->access_flags;
1053 	wr.page_shift = page_shift;
1054 
1055 	for (pages_mapped = 0;
1056 	     pages_mapped < pages_to_map && !err;
1057 	     pages_mapped += pages_iter, idx += pages_iter) {
1058 		npages = min_t(int, pages_iter, pages_to_map - pages_mapped);
1059 		dma_sync_single_for_cpu(ddev, dma, size, DMA_TO_DEVICE);
1060 		npages = populate_xlt(mr, idx, npages, xlt,
1061 				      page_shift, size, flags);
1062 
1063 		dma_sync_single_for_device(ddev, dma, size, DMA_TO_DEVICE);
1064 
1065 		sg.length = ALIGN(npages * desc_size,
1066 				  MLX5_UMR_MTT_ALIGNMENT);
1067 
1068 		if (pages_mapped + pages_iter >= pages_to_map) {
1069 			if (flags & MLX5_IB_UPD_XLT_ENABLE)
1070 				wr.wr.send_flags |=
1071 					MLX5_IB_SEND_UMR_ENABLE_MR |
1072 					MLX5_IB_SEND_UMR_UPDATE_PD_ACCESS |
1073 					MLX5_IB_SEND_UMR_UPDATE_TRANSLATION;
1074 			if (flags & MLX5_IB_UPD_XLT_PD ||
1075 			    flags & MLX5_IB_UPD_XLT_ACCESS)
1076 				wr.wr.send_flags |=
1077 					MLX5_IB_SEND_UMR_UPDATE_PD_ACCESS;
1078 			if (flags & MLX5_IB_UPD_XLT_ADDR)
1079 				wr.wr.send_flags |=
1080 					MLX5_IB_SEND_UMR_UPDATE_TRANSLATION;
1081 		}
1082 
1083 		wr.offset = idx * desc_size;
1084 		wr.xlt_size = sg.length;
1085 
1086 		err = mlx5_ib_post_send_wait(dev, &wr);
1087 	}
1088 	dma_unmap_single(ddev, dma, size, DMA_TO_DEVICE);
1089 
1090 free_xlt:
1091 	if (uctx)
1092 		mutex_unlock(&uctx->upd_xlt_page_mutex);
1093 	else
1094 		free_pages((unsigned long)xlt, get_order(size));
1095 
1096 	return err;
1097 }
1098 
1099 /*
1100  * If ibmr is NULL it will be allocated by reg_create.
1101  * Else, the given ibmr will be used.
1102  */
1103 static struct mlx5_ib_mr *reg_create(struct ib_mr *ibmr, struct ib_pd *pd,
1104 				     u64 virt_addr, u64 length,
1105 				     struct ib_umem *umem, int npages,
1106 				     int page_shift, int access_flags,
1107 				     bool populate)
1108 {
1109 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1110 	struct mlx5_ib_mr *mr;
1111 	__be64 *pas;
1112 	void *mkc;
1113 	int inlen;
1114 	u32 *in;
1115 	int err;
1116 	bool pg_cap = !!(MLX5_CAP_GEN(dev->mdev, pg));
1117 
1118 	mr = ibmr ? to_mmr(ibmr) : kzalloc(sizeof(*mr), GFP_KERNEL);
1119 	if (!mr)
1120 		return ERR_PTR(-ENOMEM);
1121 
1122 	mr->ibmr.pd = pd;
1123 	mr->access_flags = access_flags;
1124 
1125 	inlen = MLX5_ST_SZ_BYTES(create_mkey_in);
1126 	if (populate)
1127 		inlen += sizeof(*pas) * roundup(npages, 2);
1128 	in = kvzalloc(inlen, GFP_KERNEL);
1129 	if (!in) {
1130 		err = -ENOMEM;
1131 		goto err_1;
1132 	}
1133 	pas = (__be64 *)MLX5_ADDR_OF(create_mkey_in, in, klm_pas_mtt);
1134 	if (populate && !(access_flags & IB_ACCESS_ON_DEMAND))
1135 		mlx5_ib_populate_pas(dev, umem, page_shift, pas,
1136 				     pg_cap ? MLX5_IB_MTT_PRESENT : 0);
1137 
1138 	/* The pg_access bit allows setting the access flags
1139 	 * in the page list submitted with the command. */
1140 	MLX5_SET(create_mkey_in, in, pg_access, !!(pg_cap));
1141 
1142 	mkc = MLX5_ADDR_OF(create_mkey_in, in, memory_key_mkey_entry);
1143 	MLX5_SET(mkc, mkc, free, !populate);
1144 	MLX5_SET(mkc, mkc, access_mode, MLX5_MKC_ACCESS_MODE_MTT);
1145 	MLX5_SET(mkc, mkc, a, !!(access_flags & IB_ACCESS_REMOTE_ATOMIC));
1146 	MLX5_SET(mkc, mkc, rw, !!(access_flags & IB_ACCESS_REMOTE_WRITE));
1147 	MLX5_SET(mkc, mkc, rr, !!(access_flags & IB_ACCESS_REMOTE_READ));
1148 	MLX5_SET(mkc, mkc, lw, !!(access_flags & IB_ACCESS_LOCAL_WRITE));
1149 	MLX5_SET(mkc, mkc, lr, 1);
1150 	MLX5_SET(mkc, mkc, umr_en, 1);
1151 
1152 	MLX5_SET64(mkc, mkc, start_addr, virt_addr);
1153 	MLX5_SET64(mkc, mkc, len, length);
1154 	MLX5_SET(mkc, mkc, pd, to_mpd(pd)->pdn);
1155 	MLX5_SET(mkc, mkc, bsf_octword_size, 0);
1156 	MLX5_SET(mkc, mkc, translations_octword_size,
1157 		 get_octo_len(virt_addr, length, page_shift));
1158 	MLX5_SET(mkc, mkc, log_page_size, page_shift);
1159 	MLX5_SET(mkc, mkc, qpn, 0xffffff);
1160 	if (populate) {
1161 		MLX5_SET(create_mkey_in, in, translations_octword_actual_size,
1162 			 get_octo_len(virt_addr, length, page_shift));
1163 	}
1164 
1165 	err = mlx5_core_create_mkey(dev->mdev, &mr->mmkey, in, inlen);
1166 	if (err) {
1167 		mlx5_ib_warn(dev, "create mkey failed\n");
1168 		goto err_2;
1169 	}
1170 	mr->mmkey.type = MLX5_MKEY_MR;
1171 	mr->desc_size = sizeof(struct mlx5_mtt);
1172 	mr->dev = dev;
1173 	kvfree(in);
1174 
1175 	mlx5_ib_dbg(dev, "mkey = 0x%x\n", mr->mmkey.key);
1176 
1177 	return mr;
1178 
1179 err_2:
1180 	kvfree(in);
1181 
1182 err_1:
1183 	if (!ibmr)
1184 		kfree(mr);
1185 
1186 	return ERR_PTR(err);
1187 }
1188 
1189 static void set_mr_fileds(struct mlx5_ib_dev *dev, struct mlx5_ib_mr *mr,
1190 			  int npages, u64 length, int access_flags)
1191 {
1192 	mr->npages = npages;
1193 	atomic_add(npages, &dev->mdev->priv.reg_pages);
1194 	mr->ibmr.lkey = mr->mmkey.key;
1195 	mr->ibmr.rkey = mr->mmkey.key;
1196 	mr->ibmr.length = length;
1197 	mr->access_flags = access_flags;
1198 }
1199 
1200 struct ib_mr *mlx5_ib_reg_user_mr(struct ib_pd *pd, u64 start, u64 length,
1201 				  u64 virt_addr, int access_flags,
1202 				  struct ib_udata *udata)
1203 {
1204 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1205 	struct mlx5_ib_mr *mr = NULL;
1206 	struct ib_umem *umem;
1207 	int page_shift;
1208 	int npages;
1209 	int ncont;
1210 	int order;
1211 	int err;
1212 	bool use_umr = true;
1213 
1214 	if (!IS_ENABLED(CONFIG_INFINIBAND_USER_MEM))
1215 		return ERR_PTR(-EINVAL);
1216 
1217 	mlx5_ib_dbg(dev, "start 0x%llx, virt_addr 0x%llx, length 0x%llx, access_flags 0x%x\n",
1218 		    start, virt_addr, length, access_flags);
1219 
1220 #ifdef CONFIG_INFINIBAND_ON_DEMAND_PAGING
1221 	if (!start && length == U64_MAX) {
1222 		if (!(access_flags & IB_ACCESS_ON_DEMAND) ||
1223 		    !(dev->odp_caps.general_caps & IB_ODP_SUPPORT_IMPLICIT))
1224 			return ERR_PTR(-EINVAL);
1225 
1226 		mr = mlx5_ib_alloc_implicit_mr(to_mpd(pd), access_flags);
1227 		return &mr->ibmr;
1228 	}
1229 #endif
1230 
1231 	err = mr_umem_get(pd, start, length, access_flags, &umem, &npages,
1232 			   &page_shift, &ncont, &order);
1233 
1234 	if (err < 0)
1235 		return ERR_PTR(err);
1236 
1237 	if (order <= mr_cache_max_order(dev)) {
1238 		mr = alloc_mr_from_cache(pd, umem, virt_addr, length, ncont,
1239 					 page_shift, order, access_flags);
1240 		if (PTR_ERR(mr) == -EAGAIN) {
1241 			mlx5_ib_dbg(dev, "cache empty for order %d\n", order);
1242 			mr = NULL;
1243 		}
1244 	} else if (!MLX5_CAP_GEN(dev->mdev, umr_extended_translation_offset)) {
1245 		if (access_flags & IB_ACCESS_ON_DEMAND) {
1246 			err = -EINVAL;
1247 			pr_err("Got MR registration for ODP MR > 512MB, not supported for Connect-IB\n");
1248 			goto error;
1249 		}
1250 		use_umr = false;
1251 	}
1252 
1253 	if (!mr) {
1254 		mutex_lock(&dev->slow_path_mutex);
1255 		mr = reg_create(NULL, pd, virt_addr, length, umem, ncont,
1256 				page_shift, access_flags, !use_umr);
1257 		mutex_unlock(&dev->slow_path_mutex);
1258 	}
1259 
1260 	if (IS_ERR(mr)) {
1261 		err = PTR_ERR(mr);
1262 		goto error;
1263 	}
1264 
1265 	mlx5_ib_dbg(dev, "mkey 0x%x\n", mr->mmkey.key);
1266 
1267 	mr->umem = umem;
1268 	set_mr_fileds(dev, mr, npages, length, access_flags);
1269 
1270 #ifdef CONFIG_INFINIBAND_ON_DEMAND_PAGING
1271 	update_odp_mr(mr);
1272 #endif
1273 
1274 	if (use_umr) {
1275 		int update_xlt_flags = MLX5_IB_UPD_XLT_ENABLE;
1276 
1277 		if (access_flags & IB_ACCESS_ON_DEMAND)
1278 			update_xlt_flags |= MLX5_IB_UPD_XLT_ZAP;
1279 
1280 		err = mlx5_ib_update_xlt(mr, 0, ncont, page_shift,
1281 					 update_xlt_flags);
1282 
1283 		if (err) {
1284 			dereg_mr(dev, mr);
1285 			return ERR_PTR(err);
1286 		}
1287 	}
1288 
1289 	mr->live = 1;
1290 	return &mr->ibmr;
1291 error:
1292 	ib_umem_release(umem);
1293 	return ERR_PTR(err);
1294 }
1295 
1296 static int unreg_umr(struct mlx5_ib_dev *dev, struct mlx5_ib_mr *mr)
1297 {
1298 	struct mlx5_core_dev *mdev = dev->mdev;
1299 	struct mlx5_umr_wr umrwr = {};
1300 
1301 	if (mdev->state == MLX5_DEVICE_STATE_INTERNAL_ERROR)
1302 		return 0;
1303 
1304 	umrwr.wr.send_flags = MLX5_IB_SEND_UMR_DISABLE_MR |
1305 			      MLX5_IB_SEND_UMR_FAIL_IF_FREE;
1306 	umrwr.wr.opcode = MLX5_IB_WR_UMR;
1307 	umrwr.mkey = mr->mmkey.key;
1308 
1309 	return mlx5_ib_post_send_wait(dev, &umrwr);
1310 }
1311 
1312 static int rereg_umr(struct ib_pd *pd, struct mlx5_ib_mr *mr,
1313 		     int access_flags, int flags)
1314 {
1315 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1316 	struct mlx5_umr_wr umrwr = {};
1317 	int err;
1318 
1319 	umrwr.wr.send_flags = MLX5_IB_SEND_UMR_FAIL_IF_FREE;
1320 
1321 	umrwr.wr.opcode = MLX5_IB_WR_UMR;
1322 	umrwr.mkey = mr->mmkey.key;
1323 
1324 	if (flags & IB_MR_REREG_PD || flags & IB_MR_REREG_ACCESS) {
1325 		umrwr.pd = pd;
1326 		umrwr.access_flags = access_flags;
1327 		umrwr.wr.send_flags |= MLX5_IB_SEND_UMR_UPDATE_PD_ACCESS;
1328 	}
1329 
1330 	err = mlx5_ib_post_send_wait(dev, &umrwr);
1331 
1332 	return err;
1333 }
1334 
1335 int mlx5_ib_rereg_user_mr(struct ib_mr *ib_mr, int flags, u64 start,
1336 			  u64 length, u64 virt_addr, int new_access_flags,
1337 			  struct ib_pd *new_pd, struct ib_udata *udata)
1338 {
1339 	struct mlx5_ib_dev *dev = to_mdev(ib_mr->device);
1340 	struct mlx5_ib_mr *mr = to_mmr(ib_mr);
1341 	struct ib_pd *pd = (flags & IB_MR_REREG_PD) ? new_pd : ib_mr->pd;
1342 	int access_flags = flags & IB_MR_REREG_ACCESS ?
1343 			    new_access_flags :
1344 			    mr->access_flags;
1345 	u64 addr = (flags & IB_MR_REREG_TRANS) ? virt_addr : mr->umem->address;
1346 	u64 len = (flags & IB_MR_REREG_TRANS) ? length : mr->umem->length;
1347 	int page_shift = 0;
1348 	int upd_flags = 0;
1349 	int npages = 0;
1350 	int ncont = 0;
1351 	int order = 0;
1352 	int err;
1353 
1354 	mlx5_ib_dbg(dev, "start 0x%llx, virt_addr 0x%llx, length 0x%llx, access_flags 0x%x\n",
1355 		    start, virt_addr, length, access_flags);
1356 
1357 	atomic_sub(mr->npages, &dev->mdev->priv.reg_pages);
1358 
1359 	if (flags != IB_MR_REREG_PD) {
1360 		/*
1361 		 * Replace umem. This needs to be done whether or not UMR is
1362 		 * used.
1363 		 */
1364 		flags |= IB_MR_REREG_TRANS;
1365 		ib_umem_release(mr->umem);
1366 		err = mr_umem_get(pd, addr, len, access_flags, &mr->umem,
1367 				  &npages, &page_shift, &ncont, &order);
1368 		if (err < 0) {
1369 			clean_mr(dev, mr);
1370 			return err;
1371 		}
1372 	}
1373 
1374 	if (flags & IB_MR_REREG_TRANS && !use_umr_mtt_update(mr, addr, len)) {
1375 		/*
1376 		 * UMR can't be used - MKey needs to be replaced.
1377 		 */
1378 		if (mr->allocated_from_cache) {
1379 			err = unreg_umr(dev, mr);
1380 			if (err)
1381 				mlx5_ib_warn(dev, "Failed to unregister MR\n");
1382 		} else {
1383 			err = destroy_mkey(dev, mr);
1384 			if (err)
1385 				mlx5_ib_warn(dev, "Failed to destroy MKey\n");
1386 		}
1387 		if (err)
1388 			return err;
1389 
1390 		mr = reg_create(ib_mr, pd, addr, len, mr->umem, ncont,
1391 				page_shift, access_flags, true);
1392 
1393 		if (IS_ERR(mr))
1394 			return PTR_ERR(mr);
1395 
1396 		mr->allocated_from_cache = 0;
1397 		mr->live = 1;
1398 	} else {
1399 		/*
1400 		 * Send a UMR WQE
1401 		 */
1402 		mr->ibmr.pd = pd;
1403 		mr->access_flags = access_flags;
1404 		mr->mmkey.iova = addr;
1405 		mr->mmkey.size = len;
1406 		mr->mmkey.pd = to_mpd(pd)->pdn;
1407 
1408 		if (flags & IB_MR_REREG_TRANS) {
1409 			upd_flags = MLX5_IB_UPD_XLT_ADDR;
1410 			if (flags & IB_MR_REREG_PD)
1411 				upd_flags |= MLX5_IB_UPD_XLT_PD;
1412 			if (flags & IB_MR_REREG_ACCESS)
1413 				upd_flags |= MLX5_IB_UPD_XLT_ACCESS;
1414 			err = mlx5_ib_update_xlt(mr, 0, npages, page_shift,
1415 						 upd_flags);
1416 		} else {
1417 			err = rereg_umr(pd, mr, access_flags, flags);
1418 		}
1419 
1420 		if (err) {
1421 			mlx5_ib_warn(dev, "Failed to rereg UMR\n");
1422 			ib_umem_release(mr->umem);
1423 			mr->umem = NULL;
1424 			clean_mr(dev, mr);
1425 			return err;
1426 		}
1427 	}
1428 
1429 	set_mr_fileds(dev, mr, npages, len, access_flags);
1430 
1431 #ifdef CONFIG_INFINIBAND_ON_DEMAND_PAGING
1432 	update_odp_mr(mr);
1433 #endif
1434 	return 0;
1435 }
1436 
1437 static int
1438 mlx5_alloc_priv_descs(struct ib_device *device,
1439 		      struct mlx5_ib_mr *mr,
1440 		      int ndescs,
1441 		      int desc_size)
1442 {
1443 	int size = ndescs * desc_size;
1444 	int add_size;
1445 	int ret;
1446 
1447 	add_size = max_t(int, MLX5_UMR_ALIGN - ARCH_KMALLOC_MINALIGN, 0);
1448 
1449 	mr->descs_alloc = kzalloc(size + add_size, GFP_KERNEL);
1450 	if (!mr->descs_alloc)
1451 		return -ENOMEM;
1452 
1453 	mr->descs = PTR_ALIGN(mr->descs_alloc, MLX5_UMR_ALIGN);
1454 
1455 	mr->desc_map = dma_map_single(device->dev.parent, mr->descs,
1456 				      size, DMA_TO_DEVICE);
1457 	if (dma_mapping_error(device->dev.parent, mr->desc_map)) {
1458 		ret = -ENOMEM;
1459 		goto err;
1460 	}
1461 
1462 	return 0;
1463 err:
1464 	kfree(mr->descs_alloc);
1465 
1466 	return ret;
1467 }
1468 
1469 static void
1470 mlx5_free_priv_descs(struct mlx5_ib_mr *mr)
1471 {
1472 	if (mr->descs) {
1473 		struct ib_device *device = mr->ibmr.device;
1474 		int size = mr->max_descs * mr->desc_size;
1475 
1476 		dma_unmap_single(device->dev.parent, mr->desc_map,
1477 				 size, DMA_TO_DEVICE);
1478 		kfree(mr->descs_alloc);
1479 		mr->descs = NULL;
1480 	}
1481 }
1482 
1483 static int clean_mr(struct mlx5_ib_dev *dev, struct mlx5_ib_mr *mr)
1484 {
1485 	int allocated_from_cache = mr->allocated_from_cache;
1486 	int err;
1487 
1488 	if (mr->sig) {
1489 		if (mlx5_core_destroy_psv(dev->mdev,
1490 					  mr->sig->psv_memory.psv_idx))
1491 			mlx5_ib_warn(dev, "failed to destroy mem psv %d\n",
1492 				     mr->sig->psv_memory.psv_idx);
1493 		if (mlx5_core_destroy_psv(dev->mdev,
1494 					  mr->sig->psv_wire.psv_idx))
1495 			mlx5_ib_warn(dev, "failed to destroy wire psv %d\n",
1496 				     mr->sig->psv_wire.psv_idx);
1497 		kfree(mr->sig);
1498 		mr->sig = NULL;
1499 	}
1500 
1501 	mlx5_free_priv_descs(mr);
1502 
1503 	if (!allocated_from_cache) {
1504 		u32 key = mr->mmkey.key;
1505 
1506 		err = destroy_mkey(dev, mr);
1507 		if (err) {
1508 			mlx5_ib_warn(dev, "failed to destroy mkey 0x%x (%d)\n",
1509 				     key, err);
1510 			return err;
1511 		}
1512 	}
1513 
1514 	return 0;
1515 }
1516 
1517 static int dereg_mr(struct mlx5_ib_dev *dev, struct mlx5_ib_mr *mr)
1518 {
1519 	int npages = mr->npages;
1520 	struct ib_umem *umem = mr->umem;
1521 
1522 #ifdef CONFIG_INFINIBAND_ON_DEMAND_PAGING
1523 	if (umem && umem->odp_data) {
1524 		/* Prevent new page faults from succeeding */
1525 		mr->live = 0;
1526 		/* Wait for all running page-fault handlers to finish. */
1527 		synchronize_srcu(&dev->mr_srcu);
1528 		/* Destroy all page mappings */
1529 		if (umem->odp_data->page_list)
1530 			mlx5_ib_invalidate_range(umem, ib_umem_start(umem),
1531 						 ib_umem_end(umem));
1532 		else
1533 			mlx5_ib_free_implicit_mr(mr);
1534 		/*
1535 		 * We kill the umem before the MR for ODP,
1536 		 * so that there will not be any invalidations in
1537 		 * flight, looking at the *mr struct.
1538 		 */
1539 		ib_umem_release(umem);
1540 		atomic_sub(npages, &dev->mdev->priv.reg_pages);
1541 
1542 		/* Avoid double-freeing the umem. */
1543 		umem = NULL;
1544 	}
1545 #endif
1546 
1547 	clean_mr(dev, mr);
1548 
1549 	if (umem) {
1550 		ib_umem_release(umem);
1551 		atomic_sub(npages, &dev->mdev->priv.reg_pages);
1552 	}
1553 
1554 	if (!mr->allocated_from_cache)
1555 		kfree(mr);
1556 	else
1557 		mlx5_mr_cache_free(dev, mr);
1558 
1559 	return 0;
1560 }
1561 
1562 int mlx5_ib_dereg_mr(struct ib_mr *ibmr)
1563 {
1564 	struct mlx5_ib_dev *dev = to_mdev(ibmr->device);
1565 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
1566 
1567 	return dereg_mr(dev, mr);
1568 }
1569 
1570 struct ib_mr *mlx5_ib_alloc_mr(struct ib_pd *pd,
1571 			       enum ib_mr_type mr_type,
1572 			       u32 max_num_sg)
1573 {
1574 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1575 	int inlen = MLX5_ST_SZ_BYTES(create_mkey_in);
1576 	int ndescs = ALIGN(max_num_sg, 4);
1577 	struct mlx5_ib_mr *mr;
1578 	void *mkc;
1579 	u32 *in;
1580 	int err;
1581 
1582 	mr = kzalloc(sizeof(*mr), GFP_KERNEL);
1583 	if (!mr)
1584 		return ERR_PTR(-ENOMEM);
1585 
1586 	in = kzalloc(inlen, GFP_KERNEL);
1587 	if (!in) {
1588 		err = -ENOMEM;
1589 		goto err_free;
1590 	}
1591 
1592 	mkc = MLX5_ADDR_OF(create_mkey_in, in, memory_key_mkey_entry);
1593 	MLX5_SET(mkc, mkc, free, 1);
1594 	MLX5_SET(mkc, mkc, translations_octword_size, ndescs);
1595 	MLX5_SET(mkc, mkc, qpn, 0xffffff);
1596 	MLX5_SET(mkc, mkc, pd, to_mpd(pd)->pdn);
1597 
1598 	if (mr_type == IB_MR_TYPE_MEM_REG) {
1599 		mr->access_mode = MLX5_MKC_ACCESS_MODE_MTT;
1600 		MLX5_SET(mkc, mkc, log_page_size, PAGE_SHIFT);
1601 		err = mlx5_alloc_priv_descs(pd->device, mr,
1602 					    ndescs, sizeof(struct mlx5_mtt));
1603 		if (err)
1604 			goto err_free_in;
1605 
1606 		mr->desc_size = sizeof(struct mlx5_mtt);
1607 		mr->max_descs = ndescs;
1608 	} else if (mr_type == IB_MR_TYPE_SG_GAPS) {
1609 		mr->access_mode = MLX5_MKC_ACCESS_MODE_KLMS;
1610 
1611 		err = mlx5_alloc_priv_descs(pd->device, mr,
1612 					    ndescs, sizeof(struct mlx5_klm));
1613 		if (err)
1614 			goto err_free_in;
1615 		mr->desc_size = sizeof(struct mlx5_klm);
1616 		mr->max_descs = ndescs;
1617 	} else if (mr_type == IB_MR_TYPE_SIGNATURE) {
1618 		u32 psv_index[2];
1619 
1620 		MLX5_SET(mkc, mkc, bsf_en, 1);
1621 		MLX5_SET(mkc, mkc, bsf_octword_size, MLX5_MKEY_BSF_OCTO_SIZE);
1622 		mr->sig = kzalloc(sizeof(*mr->sig), GFP_KERNEL);
1623 		if (!mr->sig) {
1624 			err = -ENOMEM;
1625 			goto err_free_in;
1626 		}
1627 
1628 		/* create mem & wire PSVs */
1629 		err = mlx5_core_create_psv(dev->mdev, to_mpd(pd)->pdn,
1630 					   2, psv_index);
1631 		if (err)
1632 			goto err_free_sig;
1633 
1634 		mr->access_mode = MLX5_MKC_ACCESS_MODE_KLMS;
1635 		mr->sig->psv_memory.psv_idx = psv_index[0];
1636 		mr->sig->psv_wire.psv_idx = psv_index[1];
1637 
1638 		mr->sig->sig_status_checked = true;
1639 		mr->sig->sig_err_exists = false;
1640 		/* Next UMR, Arm SIGERR */
1641 		++mr->sig->sigerr_count;
1642 	} else {
1643 		mlx5_ib_warn(dev, "Invalid mr type %d\n", mr_type);
1644 		err = -EINVAL;
1645 		goto err_free_in;
1646 	}
1647 
1648 	MLX5_SET(mkc, mkc, access_mode, mr->access_mode);
1649 	MLX5_SET(mkc, mkc, umr_en, 1);
1650 
1651 	mr->ibmr.device = pd->device;
1652 	err = mlx5_core_create_mkey(dev->mdev, &mr->mmkey, in, inlen);
1653 	if (err)
1654 		goto err_destroy_psv;
1655 
1656 	mr->mmkey.type = MLX5_MKEY_MR;
1657 	mr->ibmr.lkey = mr->mmkey.key;
1658 	mr->ibmr.rkey = mr->mmkey.key;
1659 	mr->umem = NULL;
1660 	kfree(in);
1661 
1662 	return &mr->ibmr;
1663 
1664 err_destroy_psv:
1665 	if (mr->sig) {
1666 		if (mlx5_core_destroy_psv(dev->mdev,
1667 					  mr->sig->psv_memory.psv_idx))
1668 			mlx5_ib_warn(dev, "failed to destroy mem psv %d\n",
1669 				     mr->sig->psv_memory.psv_idx);
1670 		if (mlx5_core_destroy_psv(dev->mdev,
1671 					  mr->sig->psv_wire.psv_idx))
1672 			mlx5_ib_warn(dev, "failed to destroy wire psv %d\n",
1673 				     mr->sig->psv_wire.psv_idx);
1674 	}
1675 	mlx5_free_priv_descs(mr);
1676 err_free_sig:
1677 	kfree(mr->sig);
1678 err_free_in:
1679 	kfree(in);
1680 err_free:
1681 	kfree(mr);
1682 	return ERR_PTR(err);
1683 }
1684 
1685 struct ib_mw *mlx5_ib_alloc_mw(struct ib_pd *pd, enum ib_mw_type type,
1686 			       struct ib_udata *udata)
1687 {
1688 	struct mlx5_ib_dev *dev = to_mdev(pd->device);
1689 	int inlen = MLX5_ST_SZ_BYTES(create_mkey_in);
1690 	struct mlx5_ib_mw *mw = NULL;
1691 	u32 *in = NULL;
1692 	void *mkc;
1693 	int ndescs;
1694 	int err;
1695 	struct mlx5_ib_alloc_mw req = {};
1696 	struct {
1697 		__u32	comp_mask;
1698 		__u32	response_length;
1699 	} resp = {};
1700 
1701 	err = ib_copy_from_udata(&req, udata, min(udata->inlen, sizeof(req)));
1702 	if (err)
1703 		return ERR_PTR(err);
1704 
1705 	if (req.comp_mask || req.reserved1 || req.reserved2)
1706 		return ERR_PTR(-EOPNOTSUPP);
1707 
1708 	if (udata->inlen > sizeof(req) &&
1709 	    !ib_is_udata_cleared(udata, sizeof(req),
1710 				 udata->inlen - sizeof(req)))
1711 		return ERR_PTR(-EOPNOTSUPP);
1712 
1713 	ndescs = req.num_klms ? roundup(req.num_klms, 4) : roundup(1, 4);
1714 
1715 	mw = kzalloc(sizeof(*mw), GFP_KERNEL);
1716 	in = kzalloc(inlen, GFP_KERNEL);
1717 	if (!mw || !in) {
1718 		err = -ENOMEM;
1719 		goto free;
1720 	}
1721 
1722 	mkc = MLX5_ADDR_OF(create_mkey_in, in, memory_key_mkey_entry);
1723 
1724 	MLX5_SET(mkc, mkc, free, 1);
1725 	MLX5_SET(mkc, mkc, translations_octword_size, ndescs);
1726 	MLX5_SET(mkc, mkc, pd, to_mpd(pd)->pdn);
1727 	MLX5_SET(mkc, mkc, umr_en, 1);
1728 	MLX5_SET(mkc, mkc, lr, 1);
1729 	MLX5_SET(mkc, mkc, access_mode, MLX5_MKC_ACCESS_MODE_KLMS);
1730 	MLX5_SET(mkc, mkc, en_rinval, !!((type == IB_MW_TYPE_2)));
1731 	MLX5_SET(mkc, mkc, qpn, 0xffffff);
1732 
1733 	err = mlx5_core_create_mkey(dev->mdev, &mw->mmkey, in, inlen);
1734 	if (err)
1735 		goto free;
1736 
1737 	mw->mmkey.type = MLX5_MKEY_MW;
1738 	mw->ibmw.rkey = mw->mmkey.key;
1739 	mw->ndescs = ndescs;
1740 
1741 	resp.response_length = min(offsetof(typeof(resp), response_length) +
1742 				   sizeof(resp.response_length), udata->outlen);
1743 	if (resp.response_length) {
1744 		err = ib_copy_to_udata(udata, &resp, resp.response_length);
1745 		if (err) {
1746 			mlx5_core_destroy_mkey(dev->mdev, &mw->mmkey);
1747 			goto free;
1748 		}
1749 	}
1750 
1751 	kfree(in);
1752 	return &mw->ibmw;
1753 
1754 free:
1755 	kfree(mw);
1756 	kfree(in);
1757 	return ERR_PTR(err);
1758 }
1759 
1760 int mlx5_ib_dealloc_mw(struct ib_mw *mw)
1761 {
1762 	struct mlx5_ib_mw *mmw = to_mmw(mw);
1763 	int err;
1764 
1765 	err =  mlx5_core_destroy_mkey((to_mdev(mw->device))->mdev,
1766 				      &mmw->mmkey);
1767 	if (!err)
1768 		kfree(mmw);
1769 	return err;
1770 }
1771 
1772 int mlx5_ib_check_mr_status(struct ib_mr *ibmr, u32 check_mask,
1773 			    struct ib_mr_status *mr_status)
1774 {
1775 	struct mlx5_ib_mr *mmr = to_mmr(ibmr);
1776 	int ret = 0;
1777 
1778 	if (check_mask & ~IB_MR_CHECK_SIG_STATUS) {
1779 		pr_err("Invalid status check mask\n");
1780 		ret = -EINVAL;
1781 		goto done;
1782 	}
1783 
1784 	mr_status->fail_status = 0;
1785 	if (check_mask & IB_MR_CHECK_SIG_STATUS) {
1786 		if (!mmr->sig) {
1787 			ret = -EINVAL;
1788 			pr_err("signature status check requested on a non-signature enabled MR\n");
1789 			goto done;
1790 		}
1791 
1792 		mmr->sig->sig_status_checked = true;
1793 		if (!mmr->sig->sig_err_exists)
1794 			goto done;
1795 
1796 		if (ibmr->lkey == mmr->sig->err_item.key)
1797 			memcpy(&mr_status->sig_err, &mmr->sig->err_item,
1798 			       sizeof(mr_status->sig_err));
1799 		else {
1800 			mr_status->sig_err.err_type = IB_SIG_BAD_GUARD;
1801 			mr_status->sig_err.sig_err_offset = 0;
1802 			mr_status->sig_err.key = mmr->sig->err_item.key;
1803 		}
1804 
1805 		mmr->sig->sig_err_exists = false;
1806 		mr_status->fail_status |= IB_MR_CHECK_SIG_STATUS;
1807 	}
1808 
1809 done:
1810 	return ret;
1811 }
1812 
1813 static int
1814 mlx5_ib_sg_to_klms(struct mlx5_ib_mr *mr,
1815 		   struct scatterlist *sgl,
1816 		   unsigned short sg_nents,
1817 		   unsigned int *sg_offset_p)
1818 {
1819 	struct scatterlist *sg = sgl;
1820 	struct mlx5_klm *klms = mr->descs;
1821 	unsigned int sg_offset = sg_offset_p ? *sg_offset_p : 0;
1822 	u32 lkey = mr->ibmr.pd->local_dma_lkey;
1823 	int i;
1824 
1825 	mr->ibmr.iova = sg_dma_address(sg) + sg_offset;
1826 	mr->ibmr.length = 0;
1827 
1828 	for_each_sg(sgl, sg, sg_nents, i) {
1829 		if (unlikely(i >= mr->max_descs))
1830 			break;
1831 		klms[i].va = cpu_to_be64(sg_dma_address(sg) + sg_offset);
1832 		klms[i].bcount = cpu_to_be32(sg_dma_len(sg) - sg_offset);
1833 		klms[i].key = cpu_to_be32(lkey);
1834 		mr->ibmr.length += sg_dma_len(sg) - sg_offset;
1835 
1836 		sg_offset = 0;
1837 	}
1838 	mr->ndescs = i;
1839 
1840 	if (sg_offset_p)
1841 		*sg_offset_p = sg_offset;
1842 
1843 	return i;
1844 }
1845 
1846 static int mlx5_set_page(struct ib_mr *ibmr, u64 addr)
1847 {
1848 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
1849 	__be64 *descs;
1850 
1851 	if (unlikely(mr->ndescs == mr->max_descs))
1852 		return -ENOMEM;
1853 
1854 	descs = mr->descs;
1855 	descs[mr->ndescs++] = cpu_to_be64(addr | MLX5_EN_RD | MLX5_EN_WR);
1856 
1857 	return 0;
1858 }
1859 
1860 int mlx5_ib_map_mr_sg(struct ib_mr *ibmr, struct scatterlist *sg, int sg_nents,
1861 		      unsigned int *sg_offset)
1862 {
1863 	struct mlx5_ib_mr *mr = to_mmr(ibmr);
1864 	int n;
1865 
1866 	mr->ndescs = 0;
1867 
1868 	ib_dma_sync_single_for_cpu(ibmr->device, mr->desc_map,
1869 				   mr->desc_size * mr->max_descs,
1870 				   DMA_TO_DEVICE);
1871 
1872 	if (mr->access_mode == MLX5_MKC_ACCESS_MODE_KLMS)
1873 		n = mlx5_ib_sg_to_klms(mr, sg, sg_nents, sg_offset);
1874 	else
1875 		n = ib_sg_to_pages(ibmr, sg, sg_nents, sg_offset,
1876 				mlx5_set_page);
1877 
1878 	ib_dma_sync_single_for_device(ibmr->device, mr->desc_map,
1879 				      mr->desc_size * mr->max_descs,
1880 				      DMA_TO_DEVICE);
1881 
1882 	return n;
1883 }
1884