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