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