xref: /openbmc/linux/drivers/infiniband/hw/mlx5/main.c (revision 547840bd)
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 #include <linux/debugfs.h>
34 #include <linux/highmem.h>
35 #include <linux/module.h>
36 #include <linux/init.h>
37 #include <linux/errno.h>
38 #include <linux/pci.h>
39 #include <linux/dma-mapping.h>
40 #include <linux/slab.h>
41 #include <linux/bitmap.h>
42 #include <linux/sched.h>
43 #include <linux/sched/mm.h>
44 #include <linux/sched/task.h>
45 #include <linux/delay.h>
46 #include <rdma/ib_user_verbs.h>
47 #include <rdma/ib_addr.h>
48 #include <rdma/ib_cache.h>
49 #include <linux/mlx5/port.h>
50 #include <linux/mlx5/vport.h>
51 #include <linux/mlx5/fs.h>
52 #include <linux/mlx5/eswitch.h>
53 #include <linux/list.h>
54 #include <rdma/ib_smi.h>
55 #include <rdma/ib_umem.h>
56 #include <linux/in.h>
57 #include <linux/etherdevice.h>
58 #include "mlx5_ib.h"
59 #include "ib_rep.h"
60 #include "cmd.h"
61 #include "srq.h"
62 #include "qp.h"
63 #include <linux/mlx5/fs_helpers.h>
64 #include <linux/mlx5/accel.h>
65 #include <rdma/uverbs_std_types.h>
66 #include <rdma/mlx5_user_ioctl_verbs.h>
67 #include <rdma/mlx5_user_ioctl_cmds.h>
68 #include <rdma/ib_umem_odp.h>
69 
70 #define UVERBS_MODULE_NAME mlx5_ib
71 #include <rdma/uverbs_named_ioctl.h>
72 
73 #define DRIVER_NAME "mlx5_ib"
74 #define DRIVER_VERSION "5.0-0"
75 
76 MODULE_AUTHOR("Eli Cohen <eli@mellanox.com>");
77 MODULE_DESCRIPTION("Mellanox Connect-IB HCA IB driver");
78 MODULE_LICENSE("Dual BSD/GPL");
79 
80 static char mlx5_version[] =
81 	DRIVER_NAME ": Mellanox Connect-IB Infiniband driver v"
82 	DRIVER_VERSION "\n";
83 
84 struct mlx5_ib_event_work {
85 	struct work_struct	work;
86 	union {
87 		struct mlx5_ib_dev	      *dev;
88 		struct mlx5_ib_multiport_info *mpi;
89 	};
90 	bool			is_slave;
91 	unsigned int		event;
92 	void			*param;
93 };
94 
95 enum {
96 	MLX5_ATOMIC_SIZE_QP_8BYTES = 1 << 3,
97 };
98 
99 static struct workqueue_struct *mlx5_ib_event_wq;
100 static LIST_HEAD(mlx5_ib_unaffiliated_port_list);
101 static LIST_HEAD(mlx5_ib_dev_list);
102 /*
103  * This mutex should be held when accessing either of the above lists
104  */
105 static DEFINE_MUTEX(mlx5_ib_multiport_mutex);
106 
107 /* We can't use an array for xlt_emergency_page because dma_map_single
108  * doesn't work on kernel modules memory
109  */
110 static unsigned long xlt_emergency_page;
111 static struct mutex xlt_emergency_page_mutex;
112 
113 struct mlx5_ib_dev *mlx5_ib_get_ibdev_from_mpi(struct mlx5_ib_multiport_info *mpi)
114 {
115 	struct mlx5_ib_dev *dev;
116 
117 	mutex_lock(&mlx5_ib_multiport_mutex);
118 	dev = mpi->ibdev;
119 	mutex_unlock(&mlx5_ib_multiport_mutex);
120 	return dev;
121 }
122 
123 static enum rdma_link_layer
124 mlx5_port_type_cap_to_rdma_ll(int port_type_cap)
125 {
126 	switch (port_type_cap) {
127 	case MLX5_CAP_PORT_TYPE_IB:
128 		return IB_LINK_LAYER_INFINIBAND;
129 	case MLX5_CAP_PORT_TYPE_ETH:
130 		return IB_LINK_LAYER_ETHERNET;
131 	default:
132 		return IB_LINK_LAYER_UNSPECIFIED;
133 	}
134 }
135 
136 static enum rdma_link_layer
137 mlx5_ib_port_link_layer(struct ib_device *device, u8 port_num)
138 {
139 	struct mlx5_ib_dev *dev = to_mdev(device);
140 	int port_type_cap = MLX5_CAP_GEN(dev->mdev, port_type);
141 
142 	return mlx5_port_type_cap_to_rdma_ll(port_type_cap);
143 }
144 
145 static int get_port_state(struct ib_device *ibdev,
146 			  u8 port_num,
147 			  enum ib_port_state *state)
148 {
149 	struct ib_port_attr attr;
150 	int ret;
151 
152 	memset(&attr, 0, sizeof(attr));
153 	ret = ibdev->ops.query_port(ibdev, port_num, &attr);
154 	if (!ret)
155 		*state = attr.state;
156 	return ret;
157 }
158 
159 static struct mlx5_roce *mlx5_get_rep_roce(struct mlx5_ib_dev *dev,
160 					   struct net_device *ndev,
161 					   u8 *port_num)
162 {
163 	struct mlx5_eswitch *esw = dev->mdev->priv.eswitch;
164 	struct net_device *rep_ndev;
165 	struct mlx5_ib_port *port;
166 	int i;
167 
168 	for (i = 0; i < dev->num_ports; i++) {
169 		port  = &dev->port[i];
170 		if (!port->rep)
171 			continue;
172 
173 		read_lock(&port->roce.netdev_lock);
174 		rep_ndev = mlx5_ib_get_rep_netdev(esw,
175 						  port->rep->vport);
176 		if (rep_ndev == ndev) {
177 			read_unlock(&port->roce.netdev_lock);
178 			*port_num = i + 1;
179 			return &port->roce;
180 		}
181 		read_unlock(&port->roce.netdev_lock);
182 	}
183 
184 	return NULL;
185 }
186 
187 static int mlx5_netdev_event(struct notifier_block *this,
188 			     unsigned long event, void *ptr)
189 {
190 	struct mlx5_roce *roce = container_of(this, struct mlx5_roce, nb);
191 	struct net_device *ndev = netdev_notifier_info_to_dev(ptr);
192 	u8 port_num = roce->native_port_num;
193 	struct mlx5_core_dev *mdev;
194 	struct mlx5_ib_dev *ibdev;
195 
196 	ibdev = roce->dev;
197 	mdev = mlx5_ib_get_native_port_mdev(ibdev, port_num, NULL);
198 	if (!mdev)
199 		return NOTIFY_DONE;
200 
201 	switch (event) {
202 	case NETDEV_REGISTER:
203 		/* Should already be registered during the load */
204 		if (ibdev->is_rep)
205 			break;
206 		write_lock(&roce->netdev_lock);
207 		if (ndev->dev.parent == mdev->device)
208 			roce->netdev = ndev;
209 		write_unlock(&roce->netdev_lock);
210 		break;
211 
212 	case NETDEV_UNREGISTER:
213 		/* In case of reps, ib device goes away before the netdevs */
214 		write_lock(&roce->netdev_lock);
215 		if (roce->netdev == ndev)
216 			roce->netdev = NULL;
217 		write_unlock(&roce->netdev_lock);
218 		break;
219 
220 	case NETDEV_CHANGE:
221 	case NETDEV_UP:
222 	case NETDEV_DOWN: {
223 		struct net_device *lag_ndev = mlx5_lag_get_roce_netdev(mdev);
224 		struct net_device *upper = NULL;
225 
226 		if (lag_ndev) {
227 			upper = netdev_master_upper_dev_get(lag_ndev);
228 			dev_put(lag_ndev);
229 		}
230 
231 		if (ibdev->is_rep)
232 			roce = mlx5_get_rep_roce(ibdev, ndev, &port_num);
233 		if (!roce)
234 			return NOTIFY_DONE;
235 		if ((upper == ndev || (!upper && ndev == roce->netdev))
236 		    && ibdev->ib_active) {
237 			struct ib_event ibev = { };
238 			enum ib_port_state port_state;
239 
240 			if (get_port_state(&ibdev->ib_dev, port_num,
241 					   &port_state))
242 				goto done;
243 
244 			if (roce->last_port_state == port_state)
245 				goto done;
246 
247 			roce->last_port_state = port_state;
248 			ibev.device = &ibdev->ib_dev;
249 			if (port_state == IB_PORT_DOWN)
250 				ibev.event = IB_EVENT_PORT_ERR;
251 			else if (port_state == IB_PORT_ACTIVE)
252 				ibev.event = IB_EVENT_PORT_ACTIVE;
253 			else
254 				goto done;
255 
256 			ibev.element.port_num = port_num;
257 			ib_dispatch_event(&ibev);
258 		}
259 		break;
260 	}
261 
262 	default:
263 		break;
264 	}
265 done:
266 	mlx5_ib_put_native_port_mdev(ibdev, port_num);
267 	return NOTIFY_DONE;
268 }
269 
270 static struct net_device *mlx5_ib_get_netdev(struct ib_device *device,
271 					     u8 port_num)
272 {
273 	struct mlx5_ib_dev *ibdev = to_mdev(device);
274 	struct net_device *ndev;
275 	struct mlx5_core_dev *mdev;
276 
277 	mdev = mlx5_ib_get_native_port_mdev(ibdev, port_num, NULL);
278 	if (!mdev)
279 		return NULL;
280 
281 	ndev = mlx5_lag_get_roce_netdev(mdev);
282 	if (ndev)
283 		goto out;
284 
285 	/* Ensure ndev does not disappear before we invoke dev_hold()
286 	 */
287 	read_lock(&ibdev->port[port_num - 1].roce.netdev_lock);
288 	ndev = ibdev->port[port_num - 1].roce.netdev;
289 	if (ndev)
290 		dev_hold(ndev);
291 	read_unlock(&ibdev->port[port_num - 1].roce.netdev_lock);
292 
293 out:
294 	mlx5_ib_put_native_port_mdev(ibdev, port_num);
295 	return ndev;
296 }
297 
298 struct mlx5_core_dev *mlx5_ib_get_native_port_mdev(struct mlx5_ib_dev *ibdev,
299 						   u8 ib_port_num,
300 						   u8 *native_port_num)
301 {
302 	enum rdma_link_layer ll = mlx5_ib_port_link_layer(&ibdev->ib_dev,
303 							  ib_port_num);
304 	struct mlx5_core_dev *mdev = NULL;
305 	struct mlx5_ib_multiport_info *mpi;
306 	struct mlx5_ib_port *port;
307 
308 	if (!mlx5_core_mp_enabled(ibdev->mdev) ||
309 	    ll != IB_LINK_LAYER_ETHERNET) {
310 		if (native_port_num)
311 			*native_port_num = ib_port_num;
312 		return ibdev->mdev;
313 	}
314 
315 	if (native_port_num)
316 		*native_port_num = 1;
317 
318 	port = &ibdev->port[ib_port_num - 1];
319 	if (!port)
320 		return NULL;
321 
322 	spin_lock(&port->mp.mpi_lock);
323 	mpi = ibdev->port[ib_port_num - 1].mp.mpi;
324 	if (mpi && !mpi->unaffiliate) {
325 		mdev = mpi->mdev;
326 		/* If it's the master no need to refcount, it'll exist
327 		 * as long as the ib_dev exists.
328 		 */
329 		if (!mpi->is_master)
330 			mpi->mdev_refcnt++;
331 	}
332 	spin_unlock(&port->mp.mpi_lock);
333 
334 	return mdev;
335 }
336 
337 void mlx5_ib_put_native_port_mdev(struct mlx5_ib_dev *ibdev, u8 port_num)
338 {
339 	enum rdma_link_layer ll = mlx5_ib_port_link_layer(&ibdev->ib_dev,
340 							  port_num);
341 	struct mlx5_ib_multiport_info *mpi;
342 	struct mlx5_ib_port *port;
343 
344 	if (!mlx5_core_mp_enabled(ibdev->mdev) || ll != IB_LINK_LAYER_ETHERNET)
345 		return;
346 
347 	port = &ibdev->port[port_num - 1];
348 
349 	spin_lock(&port->mp.mpi_lock);
350 	mpi = ibdev->port[port_num - 1].mp.mpi;
351 	if (mpi->is_master)
352 		goto out;
353 
354 	mpi->mdev_refcnt--;
355 	if (mpi->unaffiliate)
356 		complete(&mpi->unref_comp);
357 out:
358 	spin_unlock(&port->mp.mpi_lock);
359 }
360 
361 static int translate_eth_legacy_proto_oper(u32 eth_proto_oper, u8 *active_speed,
362 					   u8 *active_width)
363 {
364 	switch (eth_proto_oper) {
365 	case MLX5E_PROT_MASK(MLX5E_1000BASE_CX_SGMII):
366 	case MLX5E_PROT_MASK(MLX5E_1000BASE_KX):
367 	case MLX5E_PROT_MASK(MLX5E_100BASE_TX):
368 	case MLX5E_PROT_MASK(MLX5E_1000BASE_T):
369 		*active_width = IB_WIDTH_1X;
370 		*active_speed = IB_SPEED_SDR;
371 		break;
372 	case MLX5E_PROT_MASK(MLX5E_10GBASE_T):
373 	case MLX5E_PROT_MASK(MLX5E_10GBASE_CX4):
374 	case MLX5E_PROT_MASK(MLX5E_10GBASE_KX4):
375 	case MLX5E_PROT_MASK(MLX5E_10GBASE_KR):
376 	case MLX5E_PROT_MASK(MLX5E_10GBASE_CR):
377 	case MLX5E_PROT_MASK(MLX5E_10GBASE_SR):
378 	case MLX5E_PROT_MASK(MLX5E_10GBASE_ER):
379 		*active_width = IB_WIDTH_1X;
380 		*active_speed = IB_SPEED_QDR;
381 		break;
382 	case MLX5E_PROT_MASK(MLX5E_25GBASE_CR):
383 	case MLX5E_PROT_MASK(MLX5E_25GBASE_KR):
384 	case MLX5E_PROT_MASK(MLX5E_25GBASE_SR):
385 		*active_width = IB_WIDTH_1X;
386 		*active_speed = IB_SPEED_EDR;
387 		break;
388 	case MLX5E_PROT_MASK(MLX5E_40GBASE_CR4):
389 	case MLX5E_PROT_MASK(MLX5E_40GBASE_KR4):
390 	case MLX5E_PROT_MASK(MLX5E_40GBASE_SR4):
391 	case MLX5E_PROT_MASK(MLX5E_40GBASE_LR4):
392 		*active_width = IB_WIDTH_4X;
393 		*active_speed = IB_SPEED_QDR;
394 		break;
395 	case MLX5E_PROT_MASK(MLX5E_50GBASE_CR2):
396 	case MLX5E_PROT_MASK(MLX5E_50GBASE_KR2):
397 	case MLX5E_PROT_MASK(MLX5E_50GBASE_SR2):
398 		*active_width = IB_WIDTH_1X;
399 		*active_speed = IB_SPEED_HDR;
400 		break;
401 	case MLX5E_PROT_MASK(MLX5E_56GBASE_R4):
402 		*active_width = IB_WIDTH_4X;
403 		*active_speed = IB_SPEED_FDR;
404 		break;
405 	case MLX5E_PROT_MASK(MLX5E_100GBASE_CR4):
406 	case MLX5E_PROT_MASK(MLX5E_100GBASE_SR4):
407 	case MLX5E_PROT_MASK(MLX5E_100GBASE_KR4):
408 	case MLX5E_PROT_MASK(MLX5E_100GBASE_LR4):
409 		*active_width = IB_WIDTH_4X;
410 		*active_speed = IB_SPEED_EDR;
411 		break;
412 	default:
413 		return -EINVAL;
414 	}
415 
416 	return 0;
417 }
418 
419 static int translate_eth_ext_proto_oper(u32 eth_proto_oper, u8 *active_speed,
420 					u8 *active_width)
421 {
422 	switch (eth_proto_oper) {
423 	case MLX5E_PROT_MASK(MLX5E_SGMII_100M):
424 	case MLX5E_PROT_MASK(MLX5E_1000BASE_X_SGMII):
425 		*active_width = IB_WIDTH_1X;
426 		*active_speed = IB_SPEED_SDR;
427 		break;
428 	case MLX5E_PROT_MASK(MLX5E_5GBASE_R):
429 		*active_width = IB_WIDTH_1X;
430 		*active_speed = IB_SPEED_DDR;
431 		break;
432 	case MLX5E_PROT_MASK(MLX5E_10GBASE_XFI_XAUI_1):
433 		*active_width = IB_WIDTH_1X;
434 		*active_speed = IB_SPEED_QDR;
435 		break;
436 	case MLX5E_PROT_MASK(MLX5E_40GBASE_XLAUI_4_XLPPI_4):
437 		*active_width = IB_WIDTH_4X;
438 		*active_speed = IB_SPEED_QDR;
439 		break;
440 	case MLX5E_PROT_MASK(MLX5E_25GAUI_1_25GBASE_CR_KR):
441 		*active_width = IB_WIDTH_1X;
442 		*active_speed = IB_SPEED_EDR;
443 		break;
444 	case MLX5E_PROT_MASK(MLX5E_50GAUI_2_LAUI_2_50GBASE_CR2_KR2):
445 		*active_width = IB_WIDTH_2X;
446 		*active_speed = IB_SPEED_EDR;
447 		break;
448 	case MLX5E_PROT_MASK(MLX5E_50GAUI_1_LAUI_1_50GBASE_CR_KR):
449 		*active_width = IB_WIDTH_1X;
450 		*active_speed = IB_SPEED_HDR;
451 		break;
452 	case MLX5E_PROT_MASK(MLX5E_CAUI_4_100GBASE_CR4_KR4):
453 		*active_width = IB_WIDTH_4X;
454 		*active_speed = IB_SPEED_EDR;
455 		break;
456 	case MLX5E_PROT_MASK(MLX5E_100GAUI_2_100GBASE_CR2_KR2):
457 		*active_width = IB_WIDTH_2X;
458 		*active_speed = IB_SPEED_HDR;
459 		break;
460 	case MLX5E_PROT_MASK(MLX5E_200GAUI_4_200GBASE_CR4_KR4):
461 		*active_width = IB_WIDTH_4X;
462 		*active_speed = IB_SPEED_HDR;
463 		break;
464 	default:
465 		return -EINVAL;
466 	}
467 
468 	return 0;
469 }
470 
471 static int translate_eth_proto_oper(u32 eth_proto_oper, u8 *active_speed,
472 				    u8 *active_width, bool ext)
473 {
474 	return ext ?
475 		translate_eth_ext_proto_oper(eth_proto_oper, active_speed,
476 					     active_width) :
477 		translate_eth_legacy_proto_oper(eth_proto_oper, active_speed,
478 						active_width);
479 }
480 
481 static int mlx5_query_port_roce(struct ib_device *device, u8 port_num,
482 				struct ib_port_attr *props)
483 {
484 	struct mlx5_ib_dev *dev = to_mdev(device);
485 	u32 out[MLX5_ST_SZ_DW(ptys_reg)] = {0};
486 	struct mlx5_core_dev *mdev;
487 	struct net_device *ndev, *upper;
488 	enum ib_mtu ndev_ib_mtu;
489 	bool put_mdev = true;
490 	u16 qkey_viol_cntr;
491 	u32 eth_prot_oper;
492 	u8 mdev_port_num;
493 	bool ext;
494 	int err;
495 
496 	mdev = mlx5_ib_get_native_port_mdev(dev, port_num, &mdev_port_num);
497 	if (!mdev) {
498 		/* This means the port isn't affiliated yet. Get the
499 		 * info for the master port instead.
500 		 */
501 		put_mdev = false;
502 		mdev = dev->mdev;
503 		mdev_port_num = 1;
504 		port_num = 1;
505 	}
506 
507 	/* Possible bad flows are checked before filling out props so in case
508 	 * of an error it will still be zeroed out.
509 	 * Use native port in case of reps
510 	 */
511 	if (dev->is_rep)
512 		err = mlx5_query_port_ptys(mdev, out, sizeof(out), MLX5_PTYS_EN,
513 					   1);
514 	else
515 		err = mlx5_query_port_ptys(mdev, out, sizeof(out), MLX5_PTYS_EN,
516 					   mdev_port_num);
517 	if (err)
518 		goto out;
519 	ext = MLX5_CAP_PCAM_FEATURE(dev->mdev, ptys_extended_ethernet);
520 	eth_prot_oper = MLX5_GET_ETH_PROTO(ptys_reg, out, ext, eth_proto_oper);
521 
522 	props->active_width     = IB_WIDTH_4X;
523 	props->active_speed     = IB_SPEED_QDR;
524 
525 	translate_eth_proto_oper(eth_prot_oper, &props->active_speed,
526 				 &props->active_width, ext);
527 
528 	props->port_cap_flags |= IB_PORT_CM_SUP;
529 	props->ip_gids = true;
530 
531 	props->gid_tbl_len      = MLX5_CAP_ROCE(dev->mdev,
532 						roce_address_table_size);
533 	props->max_mtu          = IB_MTU_4096;
534 	props->max_msg_sz       = 1 << MLX5_CAP_GEN(dev->mdev, log_max_msg);
535 	props->pkey_tbl_len     = 1;
536 	props->state            = IB_PORT_DOWN;
537 	props->phys_state       = IB_PORT_PHYS_STATE_DISABLED;
538 
539 	mlx5_query_nic_vport_qkey_viol_cntr(mdev, &qkey_viol_cntr);
540 	props->qkey_viol_cntr = qkey_viol_cntr;
541 
542 	/* If this is a stub query for an unaffiliated port stop here */
543 	if (!put_mdev)
544 		goto out;
545 
546 	ndev = mlx5_ib_get_netdev(device, port_num);
547 	if (!ndev)
548 		goto out;
549 
550 	if (dev->lag_active) {
551 		rcu_read_lock();
552 		upper = netdev_master_upper_dev_get_rcu(ndev);
553 		if (upper) {
554 			dev_put(ndev);
555 			ndev = upper;
556 			dev_hold(ndev);
557 		}
558 		rcu_read_unlock();
559 	}
560 
561 	if (netif_running(ndev) && netif_carrier_ok(ndev)) {
562 		props->state      = IB_PORT_ACTIVE;
563 		props->phys_state = IB_PORT_PHYS_STATE_LINK_UP;
564 	}
565 
566 	ndev_ib_mtu = iboe_get_mtu(ndev->mtu);
567 
568 	dev_put(ndev);
569 
570 	props->active_mtu	= min(props->max_mtu, ndev_ib_mtu);
571 out:
572 	if (put_mdev)
573 		mlx5_ib_put_native_port_mdev(dev, port_num);
574 	return err;
575 }
576 
577 static int set_roce_addr(struct mlx5_ib_dev *dev, u8 port_num,
578 			 unsigned int index, const union ib_gid *gid,
579 			 const struct ib_gid_attr *attr)
580 {
581 	enum ib_gid_type gid_type = IB_GID_TYPE_IB;
582 	u16 vlan_id = 0xffff;
583 	u8 roce_version = 0;
584 	u8 roce_l3_type = 0;
585 	u8 mac[ETH_ALEN];
586 	int ret;
587 
588 	if (gid) {
589 		gid_type = attr->gid_type;
590 		ret = rdma_read_gid_l2_fields(attr, &vlan_id, &mac[0]);
591 		if (ret)
592 			return ret;
593 	}
594 
595 	switch (gid_type) {
596 	case IB_GID_TYPE_IB:
597 		roce_version = MLX5_ROCE_VERSION_1;
598 		break;
599 	case IB_GID_TYPE_ROCE_UDP_ENCAP:
600 		roce_version = MLX5_ROCE_VERSION_2;
601 		if (ipv6_addr_v4mapped((void *)gid))
602 			roce_l3_type = MLX5_ROCE_L3_TYPE_IPV4;
603 		else
604 			roce_l3_type = MLX5_ROCE_L3_TYPE_IPV6;
605 		break;
606 
607 	default:
608 		mlx5_ib_warn(dev, "Unexpected GID type %u\n", gid_type);
609 	}
610 
611 	return mlx5_core_roce_gid_set(dev->mdev, index, roce_version,
612 				      roce_l3_type, gid->raw, mac,
613 				      vlan_id < VLAN_CFI_MASK, vlan_id,
614 				      port_num);
615 }
616 
617 static int mlx5_ib_add_gid(const struct ib_gid_attr *attr,
618 			   __always_unused void **context)
619 {
620 	return set_roce_addr(to_mdev(attr->device), attr->port_num,
621 			     attr->index, &attr->gid, attr);
622 }
623 
624 static int mlx5_ib_del_gid(const struct ib_gid_attr *attr,
625 			   __always_unused void **context)
626 {
627 	return set_roce_addr(to_mdev(attr->device), attr->port_num,
628 			     attr->index, NULL, NULL);
629 }
630 
631 __be16 mlx5_get_roce_udp_sport(struct mlx5_ib_dev *dev,
632 			       const struct ib_gid_attr *attr)
633 {
634 	if (attr->gid_type != IB_GID_TYPE_ROCE_UDP_ENCAP)
635 		return 0;
636 
637 	return cpu_to_be16(MLX5_CAP_ROCE(dev->mdev, r_roce_min_src_udp_port));
638 }
639 
640 static int mlx5_use_mad_ifc(struct mlx5_ib_dev *dev)
641 {
642 	if (MLX5_CAP_GEN(dev->mdev, port_type) == MLX5_CAP_PORT_TYPE_IB)
643 		return !MLX5_CAP_GEN(dev->mdev, ib_virt);
644 	return 0;
645 }
646 
647 enum {
648 	MLX5_VPORT_ACCESS_METHOD_MAD,
649 	MLX5_VPORT_ACCESS_METHOD_HCA,
650 	MLX5_VPORT_ACCESS_METHOD_NIC,
651 };
652 
653 static int mlx5_get_vport_access_method(struct ib_device *ibdev)
654 {
655 	if (mlx5_use_mad_ifc(to_mdev(ibdev)))
656 		return MLX5_VPORT_ACCESS_METHOD_MAD;
657 
658 	if (mlx5_ib_port_link_layer(ibdev, 1) ==
659 	    IB_LINK_LAYER_ETHERNET)
660 		return MLX5_VPORT_ACCESS_METHOD_NIC;
661 
662 	return MLX5_VPORT_ACCESS_METHOD_HCA;
663 }
664 
665 static void get_atomic_caps(struct mlx5_ib_dev *dev,
666 			    u8 atomic_size_qp,
667 			    struct ib_device_attr *props)
668 {
669 	u8 tmp;
670 	u8 atomic_operations = MLX5_CAP_ATOMIC(dev->mdev, atomic_operations);
671 	u8 atomic_req_8B_endianness_mode =
672 		MLX5_CAP_ATOMIC(dev->mdev, atomic_req_8B_endianness_mode);
673 
674 	/* Check if HW supports 8 bytes standard atomic operations and capable
675 	 * of host endianness respond
676 	 */
677 	tmp = MLX5_ATOMIC_OPS_CMP_SWAP | MLX5_ATOMIC_OPS_FETCH_ADD;
678 	if (((atomic_operations & tmp) == tmp) &&
679 	    (atomic_size_qp & MLX5_ATOMIC_SIZE_QP_8BYTES) &&
680 	    (atomic_req_8B_endianness_mode)) {
681 		props->atomic_cap = IB_ATOMIC_HCA;
682 	} else {
683 		props->atomic_cap = IB_ATOMIC_NONE;
684 	}
685 }
686 
687 static void get_atomic_caps_qp(struct mlx5_ib_dev *dev,
688 			       struct ib_device_attr *props)
689 {
690 	u8 atomic_size_qp = MLX5_CAP_ATOMIC(dev->mdev, atomic_size_qp);
691 
692 	get_atomic_caps(dev, atomic_size_qp, props);
693 }
694 
695 static int mlx5_query_system_image_guid(struct ib_device *ibdev,
696 					__be64 *sys_image_guid)
697 {
698 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
699 	struct mlx5_core_dev *mdev = dev->mdev;
700 	u64 tmp;
701 	int err;
702 
703 	switch (mlx5_get_vport_access_method(ibdev)) {
704 	case MLX5_VPORT_ACCESS_METHOD_MAD:
705 		return mlx5_query_mad_ifc_system_image_guid(ibdev,
706 							    sys_image_guid);
707 
708 	case MLX5_VPORT_ACCESS_METHOD_HCA:
709 		err = mlx5_query_hca_vport_system_image_guid(mdev, &tmp);
710 		break;
711 
712 	case MLX5_VPORT_ACCESS_METHOD_NIC:
713 		err = mlx5_query_nic_vport_system_image_guid(mdev, &tmp);
714 		break;
715 
716 	default:
717 		return -EINVAL;
718 	}
719 
720 	if (!err)
721 		*sys_image_guid = cpu_to_be64(tmp);
722 
723 	return err;
724 
725 }
726 
727 static int mlx5_query_max_pkeys(struct ib_device *ibdev,
728 				u16 *max_pkeys)
729 {
730 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
731 	struct mlx5_core_dev *mdev = dev->mdev;
732 
733 	switch (mlx5_get_vport_access_method(ibdev)) {
734 	case MLX5_VPORT_ACCESS_METHOD_MAD:
735 		return mlx5_query_mad_ifc_max_pkeys(ibdev, max_pkeys);
736 
737 	case MLX5_VPORT_ACCESS_METHOD_HCA:
738 	case MLX5_VPORT_ACCESS_METHOD_NIC:
739 		*max_pkeys = mlx5_to_sw_pkey_sz(MLX5_CAP_GEN(mdev,
740 						pkey_table_size));
741 		return 0;
742 
743 	default:
744 		return -EINVAL;
745 	}
746 }
747 
748 static int mlx5_query_vendor_id(struct ib_device *ibdev,
749 				u32 *vendor_id)
750 {
751 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
752 
753 	switch (mlx5_get_vport_access_method(ibdev)) {
754 	case MLX5_VPORT_ACCESS_METHOD_MAD:
755 		return mlx5_query_mad_ifc_vendor_id(ibdev, vendor_id);
756 
757 	case MLX5_VPORT_ACCESS_METHOD_HCA:
758 	case MLX5_VPORT_ACCESS_METHOD_NIC:
759 		return mlx5_core_query_vendor_id(dev->mdev, vendor_id);
760 
761 	default:
762 		return -EINVAL;
763 	}
764 }
765 
766 static int mlx5_query_node_guid(struct mlx5_ib_dev *dev,
767 				__be64 *node_guid)
768 {
769 	u64 tmp;
770 	int err;
771 
772 	switch (mlx5_get_vport_access_method(&dev->ib_dev)) {
773 	case MLX5_VPORT_ACCESS_METHOD_MAD:
774 		return mlx5_query_mad_ifc_node_guid(dev, node_guid);
775 
776 	case MLX5_VPORT_ACCESS_METHOD_HCA:
777 		err = mlx5_query_hca_vport_node_guid(dev->mdev, &tmp);
778 		break;
779 
780 	case MLX5_VPORT_ACCESS_METHOD_NIC:
781 		err = mlx5_query_nic_vport_node_guid(dev->mdev, &tmp);
782 		break;
783 
784 	default:
785 		return -EINVAL;
786 	}
787 
788 	if (!err)
789 		*node_guid = cpu_to_be64(tmp);
790 
791 	return err;
792 }
793 
794 struct mlx5_reg_node_desc {
795 	u8	desc[IB_DEVICE_NODE_DESC_MAX];
796 };
797 
798 static int mlx5_query_node_desc(struct mlx5_ib_dev *dev, char *node_desc)
799 {
800 	struct mlx5_reg_node_desc in;
801 
802 	if (mlx5_use_mad_ifc(dev))
803 		return mlx5_query_mad_ifc_node_desc(dev, node_desc);
804 
805 	memset(&in, 0, sizeof(in));
806 
807 	return mlx5_core_access_reg(dev->mdev, &in, sizeof(in), node_desc,
808 				    sizeof(struct mlx5_reg_node_desc),
809 				    MLX5_REG_NODE_DESC, 0, 0);
810 }
811 
812 static int mlx5_ib_query_device(struct ib_device *ibdev,
813 				struct ib_device_attr *props,
814 				struct ib_udata *uhw)
815 {
816 	size_t uhw_outlen = (uhw) ? uhw->outlen : 0;
817 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
818 	struct mlx5_core_dev *mdev = dev->mdev;
819 	int err = -ENOMEM;
820 	int max_sq_desc;
821 	int max_rq_sg;
822 	int max_sq_sg;
823 	u64 min_page_size = 1ull << MLX5_CAP_GEN(mdev, log_pg_sz);
824 	bool raw_support = !mlx5_core_mp_enabled(mdev);
825 	struct mlx5_ib_query_device_resp resp = {};
826 	size_t resp_len;
827 	u64 max_tso;
828 
829 	resp_len = sizeof(resp.comp_mask) + sizeof(resp.response_length);
830 	if (uhw_outlen && uhw_outlen < resp_len)
831 		return -EINVAL;
832 
833 	resp.response_length = resp_len;
834 
835 	if (uhw && uhw->inlen && !ib_is_udata_cleared(uhw, 0, uhw->inlen))
836 		return -EINVAL;
837 
838 	memset(props, 0, sizeof(*props));
839 	err = mlx5_query_system_image_guid(ibdev,
840 					   &props->sys_image_guid);
841 	if (err)
842 		return err;
843 
844 	err = mlx5_query_max_pkeys(ibdev, &props->max_pkeys);
845 	if (err)
846 		return err;
847 
848 	err = mlx5_query_vendor_id(ibdev, &props->vendor_id);
849 	if (err)
850 		return err;
851 
852 	props->fw_ver = ((u64)fw_rev_maj(dev->mdev) << 32) |
853 		(fw_rev_min(dev->mdev) << 16) |
854 		fw_rev_sub(dev->mdev);
855 	props->device_cap_flags    = IB_DEVICE_CHANGE_PHY_PORT |
856 		IB_DEVICE_PORT_ACTIVE_EVENT		|
857 		IB_DEVICE_SYS_IMAGE_GUID		|
858 		IB_DEVICE_RC_RNR_NAK_GEN;
859 
860 	if (MLX5_CAP_GEN(mdev, pkv))
861 		props->device_cap_flags |= IB_DEVICE_BAD_PKEY_CNTR;
862 	if (MLX5_CAP_GEN(mdev, qkv))
863 		props->device_cap_flags |= IB_DEVICE_BAD_QKEY_CNTR;
864 	if (MLX5_CAP_GEN(mdev, apm))
865 		props->device_cap_flags |= IB_DEVICE_AUTO_PATH_MIG;
866 	if (MLX5_CAP_GEN(mdev, xrc))
867 		props->device_cap_flags |= IB_DEVICE_XRC;
868 	if (MLX5_CAP_GEN(mdev, imaicl)) {
869 		props->device_cap_flags |= IB_DEVICE_MEM_WINDOW |
870 					   IB_DEVICE_MEM_WINDOW_TYPE_2B;
871 		props->max_mw = 1 << MLX5_CAP_GEN(mdev, log_max_mkey);
872 		/* We support 'Gappy' memory registration too */
873 		props->device_cap_flags |= IB_DEVICE_SG_GAPS_REG;
874 	}
875 	props->device_cap_flags |= IB_DEVICE_MEM_MGT_EXTENSIONS;
876 	if (MLX5_CAP_GEN(mdev, sho)) {
877 		props->device_cap_flags |= IB_DEVICE_INTEGRITY_HANDOVER;
878 		/* At this stage no support for signature handover */
879 		props->sig_prot_cap = IB_PROT_T10DIF_TYPE_1 |
880 				      IB_PROT_T10DIF_TYPE_2 |
881 				      IB_PROT_T10DIF_TYPE_3;
882 		props->sig_guard_cap = IB_GUARD_T10DIF_CRC |
883 				       IB_GUARD_T10DIF_CSUM;
884 	}
885 	if (MLX5_CAP_GEN(mdev, block_lb_mc))
886 		props->device_cap_flags |= IB_DEVICE_BLOCK_MULTICAST_LOOPBACK;
887 
888 	if (MLX5_CAP_GEN(dev->mdev, eth_net_offloads) && raw_support) {
889 		if (MLX5_CAP_ETH(mdev, csum_cap)) {
890 			/* Legacy bit to support old userspace libraries */
891 			props->device_cap_flags |= IB_DEVICE_RAW_IP_CSUM;
892 			props->raw_packet_caps |= IB_RAW_PACKET_CAP_IP_CSUM;
893 		}
894 
895 		if (MLX5_CAP_ETH(dev->mdev, vlan_cap))
896 			props->raw_packet_caps |=
897 				IB_RAW_PACKET_CAP_CVLAN_STRIPPING;
898 
899 		if (offsetofend(typeof(resp), tso_caps) <= uhw_outlen) {
900 			max_tso = MLX5_CAP_ETH(mdev, max_lso_cap);
901 			if (max_tso) {
902 				resp.tso_caps.max_tso = 1 << max_tso;
903 				resp.tso_caps.supported_qpts |=
904 					1 << IB_QPT_RAW_PACKET;
905 				resp.response_length += sizeof(resp.tso_caps);
906 			}
907 		}
908 
909 		if (offsetofend(typeof(resp), rss_caps) <= uhw_outlen) {
910 			resp.rss_caps.rx_hash_function =
911 						MLX5_RX_HASH_FUNC_TOEPLITZ;
912 			resp.rss_caps.rx_hash_fields_mask =
913 						MLX5_RX_HASH_SRC_IPV4 |
914 						MLX5_RX_HASH_DST_IPV4 |
915 						MLX5_RX_HASH_SRC_IPV6 |
916 						MLX5_RX_HASH_DST_IPV6 |
917 						MLX5_RX_HASH_SRC_PORT_TCP |
918 						MLX5_RX_HASH_DST_PORT_TCP |
919 						MLX5_RX_HASH_SRC_PORT_UDP |
920 						MLX5_RX_HASH_DST_PORT_UDP |
921 						MLX5_RX_HASH_INNER;
922 			if (mlx5_accel_ipsec_device_caps(dev->mdev) &
923 			    MLX5_ACCEL_IPSEC_CAP_DEVICE)
924 				resp.rss_caps.rx_hash_fields_mask |=
925 					MLX5_RX_HASH_IPSEC_SPI;
926 			resp.response_length += sizeof(resp.rss_caps);
927 		}
928 	} else {
929 		if (offsetofend(typeof(resp), tso_caps) <= uhw_outlen)
930 			resp.response_length += sizeof(resp.tso_caps);
931 		if (offsetofend(typeof(resp), rss_caps) <= uhw_outlen)
932 			resp.response_length += sizeof(resp.rss_caps);
933 	}
934 
935 	if (MLX5_CAP_GEN(mdev, ipoib_basic_offloads)) {
936 		props->device_cap_flags |= IB_DEVICE_UD_IP_CSUM;
937 		props->device_cap_flags |= IB_DEVICE_UD_TSO;
938 	}
939 
940 	if (MLX5_CAP_GEN(dev->mdev, rq_delay_drop) &&
941 	    MLX5_CAP_GEN(dev->mdev, general_notification_event) &&
942 	    raw_support)
943 		props->raw_packet_caps |= IB_RAW_PACKET_CAP_DELAY_DROP;
944 
945 	if (MLX5_CAP_GEN(mdev, ipoib_enhanced_offloads) &&
946 	    MLX5_CAP_IPOIB_ENHANCED(mdev, csum_cap))
947 		props->device_cap_flags |= IB_DEVICE_UD_IP_CSUM;
948 
949 	if (MLX5_CAP_GEN(dev->mdev, eth_net_offloads) &&
950 	    MLX5_CAP_ETH(dev->mdev, scatter_fcs) &&
951 	    raw_support) {
952 		/* Legacy bit to support old userspace libraries */
953 		props->device_cap_flags |= IB_DEVICE_RAW_SCATTER_FCS;
954 		props->raw_packet_caps |= IB_RAW_PACKET_CAP_SCATTER_FCS;
955 	}
956 
957 	if (MLX5_CAP_DEV_MEM(mdev, memic)) {
958 		props->max_dm_size =
959 			MLX5_CAP_DEV_MEM(mdev, max_memic_size);
960 	}
961 
962 	if (mlx5_get_flow_namespace(dev->mdev, MLX5_FLOW_NAMESPACE_BYPASS))
963 		props->device_cap_flags |= IB_DEVICE_MANAGED_FLOW_STEERING;
964 
965 	if (MLX5_CAP_GEN(mdev, end_pad))
966 		props->device_cap_flags |= IB_DEVICE_PCI_WRITE_END_PADDING;
967 
968 	props->vendor_part_id	   = mdev->pdev->device;
969 	props->hw_ver		   = mdev->pdev->revision;
970 
971 	props->max_mr_size	   = ~0ull;
972 	props->page_size_cap	   = ~(min_page_size - 1);
973 	props->max_qp		   = 1 << MLX5_CAP_GEN(mdev, log_max_qp);
974 	props->max_qp_wr	   = 1 << MLX5_CAP_GEN(mdev, log_max_qp_sz);
975 	max_rq_sg =  MLX5_CAP_GEN(mdev, max_wqe_sz_rq) /
976 		     sizeof(struct mlx5_wqe_data_seg);
977 	max_sq_desc = min_t(int, MLX5_CAP_GEN(mdev, max_wqe_sz_sq), 512);
978 	max_sq_sg = (max_sq_desc - sizeof(struct mlx5_wqe_ctrl_seg) -
979 		     sizeof(struct mlx5_wqe_raddr_seg)) /
980 		sizeof(struct mlx5_wqe_data_seg);
981 	props->max_send_sge = max_sq_sg;
982 	props->max_recv_sge = max_rq_sg;
983 	props->max_sge_rd	   = MLX5_MAX_SGE_RD;
984 	props->max_cq		   = 1 << MLX5_CAP_GEN(mdev, log_max_cq);
985 	props->max_cqe = (1 << MLX5_CAP_GEN(mdev, log_max_cq_sz)) - 1;
986 	props->max_mr		   = 1 << MLX5_CAP_GEN(mdev, log_max_mkey);
987 	props->max_pd		   = 1 << MLX5_CAP_GEN(mdev, log_max_pd);
988 	props->max_qp_rd_atom	   = 1 << MLX5_CAP_GEN(mdev, log_max_ra_req_qp);
989 	props->max_qp_init_rd_atom = 1 << MLX5_CAP_GEN(mdev, log_max_ra_res_qp);
990 	props->max_srq		   = 1 << MLX5_CAP_GEN(mdev, log_max_srq);
991 	props->max_srq_wr = (1 << MLX5_CAP_GEN(mdev, log_max_srq_sz)) - 1;
992 	props->local_ca_ack_delay  = MLX5_CAP_GEN(mdev, local_ca_ack_delay);
993 	props->max_res_rd_atom	   = props->max_qp_rd_atom * props->max_qp;
994 	props->max_srq_sge	   = max_rq_sg - 1;
995 	props->max_fast_reg_page_list_len =
996 		1 << MLX5_CAP_GEN(mdev, log_max_klm_list_size);
997 	props->max_pi_fast_reg_page_list_len =
998 		props->max_fast_reg_page_list_len / 2;
999 	props->max_sgl_rd =
1000 		MLX5_CAP_GEN(mdev, max_sgl_for_optimized_performance);
1001 	get_atomic_caps_qp(dev, props);
1002 	props->masked_atomic_cap   = IB_ATOMIC_NONE;
1003 	props->max_mcast_grp	   = 1 << MLX5_CAP_GEN(mdev, log_max_mcg);
1004 	props->max_mcast_qp_attach = MLX5_CAP_GEN(mdev, max_qp_mcg);
1005 	props->max_total_mcast_qp_attach = props->max_mcast_qp_attach *
1006 					   props->max_mcast_grp;
1007 	props->max_map_per_fmr = INT_MAX; /* no limit in ConnectIB */
1008 	props->max_ah = INT_MAX;
1009 	props->hca_core_clock = MLX5_CAP_GEN(mdev, device_frequency_khz);
1010 	props->timestamp_mask = 0x7FFFFFFFFFFFFFFFULL;
1011 
1012 	if (IS_ENABLED(CONFIG_INFINIBAND_ON_DEMAND_PAGING)) {
1013 		if (dev->odp_caps.general_caps & IB_ODP_SUPPORT)
1014 			props->device_cap_flags |= IB_DEVICE_ON_DEMAND_PAGING;
1015 		props->odp_caps = dev->odp_caps;
1016 		if (!uhw) {
1017 			/* ODP for kernel QPs is not implemented for receive
1018 			 * WQEs and SRQ WQEs
1019 			 */
1020 			props->odp_caps.per_transport_caps.rc_odp_caps &=
1021 				~(IB_ODP_SUPPORT_READ |
1022 				  IB_ODP_SUPPORT_SRQ_RECV);
1023 			props->odp_caps.per_transport_caps.uc_odp_caps &=
1024 				~(IB_ODP_SUPPORT_READ |
1025 				  IB_ODP_SUPPORT_SRQ_RECV);
1026 			props->odp_caps.per_transport_caps.ud_odp_caps &=
1027 				~(IB_ODP_SUPPORT_READ |
1028 				  IB_ODP_SUPPORT_SRQ_RECV);
1029 			props->odp_caps.per_transport_caps.xrc_odp_caps &=
1030 				~(IB_ODP_SUPPORT_READ |
1031 				  IB_ODP_SUPPORT_SRQ_RECV);
1032 		}
1033 	}
1034 
1035 	if (MLX5_CAP_GEN(mdev, cd))
1036 		props->device_cap_flags |= IB_DEVICE_CROSS_CHANNEL;
1037 
1038 	if (mlx5_core_is_vf(mdev))
1039 		props->device_cap_flags |= IB_DEVICE_VIRTUAL_FUNCTION;
1040 
1041 	if (mlx5_ib_port_link_layer(ibdev, 1) ==
1042 	    IB_LINK_LAYER_ETHERNET && raw_support) {
1043 		props->rss_caps.max_rwq_indirection_tables =
1044 			1 << MLX5_CAP_GEN(dev->mdev, log_max_rqt);
1045 		props->rss_caps.max_rwq_indirection_table_size =
1046 			1 << MLX5_CAP_GEN(dev->mdev, log_max_rqt_size);
1047 		props->rss_caps.supported_qpts = 1 << IB_QPT_RAW_PACKET;
1048 		props->max_wq_type_rq =
1049 			1 << MLX5_CAP_GEN(dev->mdev, log_max_rq);
1050 	}
1051 
1052 	if (MLX5_CAP_GEN(mdev, tag_matching)) {
1053 		props->tm_caps.max_num_tags =
1054 			(1 << MLX5_CAP_GEN(mdev, log_tag_matching_list_sz)) - 1;
1055 		props->tm_caps.max_ops =
1056 			1 << MLX5_CAP_GEN(mdev, log_max_qp_sz);
1057 		props->tm_caps.max_sge = MLX5_TM_MAX_SGE;
1058 	}
1059 
1060 	if (MLX5_CAP_GEN(mdev, tag_matching) &&
1061 	    MLX5_CAP_GEN(mdev, rndv_offload_rc)) {
1062 		props->tm_caps.flags = IB_TM_CAP_RNDV_RC;
1063 		props->tm_caps.max_rndv_hdr_size = MLX5_TM_MAX_RNDV_MSG_SIZE;
1064 	}
1065 
1066 	if (MLX5_CAP_GEN(dev->mdev, cq_moderation)) {
1067 		props->cq_caps.max_cq_moderation_count =
1068 						MLX5_MAX_CQ_COUNT;
1069 		props->cq_caps.max_cq_moderation_period =
1070 						MLX5_MAX_CQ_PERIOD;
1071 	}
1072 
1073 	if (offsetofend(typeof(resp), cqe_comp_caps) <= uhw_outlen) {
1074 		resp.response_length += sizeof(resp.cqe_comp_caps);
1075 
1076 		if (MLX5_CAP_GEN(dev->mdev, cqe_compression)) {
1077 			resp.cqe_comp_caps.max_num =
1078 				MLX5_CAP_GEN(dev->mdev,
1079 					     cqe_compression_max_num);
1080 
1081 			resp.cqe_comp_caps.supported_format =
1082 				MLX5_IB_CQE_RES_FORMAT_HASH |
1083 				MLX5_IB_CQE_RES_FORMAT_CSUM;
1084 
1085 			if (MLX5_CAP_GEN(dev->mdev, mini_cqe_resp_stride_index))
1086 				resp.cqe_comp_caps.supported_format |=
1087 					MLX5_IB_CQE_RES_FORMAT_CSUM_STRIDX;
1088 		}
1089 	}
1090 
1091 	if (offsetofend(typeof(resp), packet_pacing_caps) <= uhw_outlen &&
1092 	    raw_support) {
1093 		if (MLX5_CAP_QOS(mdev, packet_pacing) &&
1094 		    MLX5_CAP_GEN(mdev, qos)) {
1095 			resp.packet_pacing_caps.qp_rate_limit_max =
1096 				MLX5_CAP_QOS(mdev, packet_pacing_max_rate);
1097 			resp.packet_pacing_caps.qp_rate_limit_min =
1098 				MLX5_CAP_QOS(mdev, packet_pacing_min_rate);
1099 			resp.packet_pacing_caps.supported_qpts |=
1100 				1 << IB_QPT_RAW_PACKET;
1101 			if (MLX5_CAP_QOS(mdev, packet_pacing_burst_bound) &&
1102 			    MLX5_CAP_QOS(mdev, packet_pacing_typical_size))
1103 				resp.packet_pacing_caps.cap_flags |=
1104 					MLX5_IB_PP_SUPPORT_BURST;
1105 		}
1106 		resp.response_length += sizeof(resp.packet_pacing_caps);
1107 	}
1108 
1109 	if (offsetofend(typeof(resp), mlx5_ib_support_multi_pkt_send_wqes) <=
1110 	    uhw_outlen) {
1111 		if (MLX5_CAP_ETH(mdev, multi_pkt_send_wqe))
1112 			resp.mlx5_ib_support_multi_pkt_send_wqes =
1113 				MLX5_IB_ALLOW_MPW;
1114 
1115 		if (MLX5_CAP_ETH(mdev, enhanced_multi_pkt_send_wqe))
1116 			resp.mlx5_ib_support_multi_pkt_send_wqes |=
1117 				MLX5_IB_SUPPORT_EMPW;
1118 
1119 		resp.response_length +=
1120 			sizeof(resp.mlx5_ib_support_multi_pkt_send_wqes);
1121 	}
1122 
1123 	if (offsetofend(typeof(resp), flags) <= uhw_outlen) {
1124 		resp.response_length += sizeof(resp.flags);
1125 
1126 		if (MLX5_CAP_GEN(mdev, cqe_compression_128))
1127 			resp.flags |=
1128 				MLX5_IB_QUERY_DEV_RESP_FLAGS_CQE_128B_COMP;
1129 
1130 		if (MLX5_CAP_GEN(mdev, cqe_128_always))
1131 			resp.flags |= MLX5_IB_QUERY_DEV_RESP_FLAGS_CQE_128B_PAD;
1132 		if (MLX5_CAP_GEN(mdev, qp_packet_based))
1133 			resp.flags |=
1134 				MLX5_IB_QUERY_DEV_RESP_PACKET_BASED_CREDIT_MODE;
1135 
1136 		resp.flags |= MLX5_IB_QUERY_DEV_RESP_FLAGS_SCAT2CQE_DCT;
1137 	}
1138 
1139 	if (offsetofend(typeof(resp), sw_parsing_caps) <= uhw_outlen) {
1140 		resp.response_length += sizeof(resp.sw_parsing_caps);
1141 		if (MLX5_CAP_ETH(mdev, swp)) {
1142 			resp.sw_parsing_caps.sw_parsing_offloads |=
1143 				MLX5_IB_SW_PARSING;
1144 
1145 			if (MLX5_CAP_ETH(mdev, swp_csum))
1146 				resp.sw_parsing_caps.sw_parsing_offloads |=
1147 					MLX5_IB_SW_PARSING_CSUM;
1148 
1149 			if (MLX5_CAP_ETH(mdev, swp_lso))
1150 				resp.sw_parsing_caps.sw_parsing_offloads |=
1151 					MLX5_IB_SW_PARSING_LSO;
1152 
1153 			if (resp.sw_parsing_caps.sw_parsing_offloads)
1154 				resp.sw_parsing_caps.supported_qpts =
1155 					BIT(IB_QPT_RAW_PACKET);
1156 		}
1157 	}
1158 
1159 	if (offsetofend(typeof(resp), striding_rq_caps) <= uhw_outlen &&
1160 	    raw_support) {
1161 		resp.response_length += sizeof(resp.striding_rq_caps);
1162 		if (MLX5_CAP_GEN(mdev, striding_rq)) {
1163 			resp.striding_rq_caps.min_single_stride_log_num_of_bytes =
1164 				MLX5_MIN_SINGLE_STRIDE_LOG_NUM_BYTES;
1165 			resp.striding_rq_caps.max_single_stride_log_num_of_bytes =
1166 				MLX5_MAX_SINGLE_STRIDE_LOG_NUM_BYTES;
1167 			if (MLX5_CAP_GEN(dev->mdev, ext_stride_num_range))
1168 				resp.striding_rq_caps
1169 					.min_single_wqe_log_num_of_strides =
1170 					MLX5_EXT_MIN_SINGLE_WQE_LOG_NUM_STRIDES;
1171 			else
1172 				resp.striding_rq_caps
1173 					.min_single_wqe_log_num_of_strides =
1174 					MLX5_MIN_SINGLE_WQE_LOG_NUM_STRIDES;
1175 			resp.striding_rq_caps.max_single_wqe_log_num_of_strides =
1176 				MLX5_MAX_SINGLE_WQE_LOG_NUM_STRIDES;
1177 			resp.striding_rq_caps.supported_qpts =
1178 				BIT(IB_QPT_RAW_PACKET);
1179 		}
1180 	}
1181 
1182 	if (offsetofend(typeof(resp), tunnel_offloads_caps) <= uhw_outlen) {
1183 		resp.response_length += sizeof(resp.tunnel_offloads_caps);
1184 		if (MLX5_CAP_ETH(mdev, tunnel_stateless_vxlan))
1185 			resp.tunnel_offloads_caps |=
1186 				MLX5_IB_TUNNELED_OFFLOADS_VXLAN;
1187 		if (MLX5_CAP_ETH(mdev, tunnel_stateless_geneve_rx))
1188 			resp.tunnel_offloads_caps |=
1189 				MLX5_IB_TUNNELED_OFFLOADS_GENEVE;
1190 		if (MLX5_CAP_ETH(mdev, tunnel_stateless_gre))
1191 			resp.tunnel_offloads_caps |=
1192 				MLX5_IB_TUNNELED_OFFLOADS_GRE;
1193 		if (MLX5_CAP_ETH(mdev, tunnel_stateless_mpls_over_gre))
1194 			resp.tunnel_offloads_caps |=
1195 				MLX5_IB_TUNNELED_OFFLOADS_MPLS_GRE;
1196 		if (MLX5_CAP_ETH(mdev, tunnel_stateless_mpls_over_udp))
1197 			resp.tunnel_offloads_caps |=
1198 				MLX5_IB_TUNNELED_OFFLOADS_MPLS_UDP;
1199 	}
1200 
1201 	if (uhw_outlen) {
1202 		err = ib_copy_to_udata(uhw, &resp, resp.response_length);
1203 
1204 		if (err)
1205 			return err;
1206 	}
1207 
1208 	return 0;
1209 }
1210 
1211 enum mlx5_ib_width {
1212 	MLX5_IB_WIDTH_1X	= 1 << 0,
1213 	MLX5_IB_WIDTH_2X	= 1 << 1,
1214 	MLX5_IB_WIDTH_4X	= 1 << 2,
1215 	MLX5_IB_WIDTH_8X	= 1 << 3,
1216 	MLX5_IB_WIDTH_12X	= 1 << 4
1217 };
1218 
1219 static void translate_active_width(struct ib_device *ibdev, u8 active_width,
1220 				  u8 *ib_width)
1221 {
1222 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
1223 
1224 	if (active_width & MLX5_IB_WIDTH_1X)
1225 		*ib_width = IB_WIDTH_1X;
1226 	else if (active_width & MLX5_IB_WIDTH_2X)
1227 		*ib_width = IB_WIDTH_2X;
1228 	else if (active_width & MLX5_IB_WIDTH_4X)
1229 		*ib_width = IB_WIDTH_4X;
1230 	else if (active_width & MLX5_IB_WIDTH_8X)
1231 		*ib_width = IB_WIDTH_8X;
1232 	else if (active_width & MLX5_IB_WIDTH_12X)
1233 		*ib_width = IB_WIDTH_12X;
1234 	else {
1235 		mlx5_ib_dbg(dev, "Invalid active_width %d, setting width to default value: 4x\n",
1236 			    (int)active_width);
1237 		*ib_width = IB_WIDTH_4X;
1238 	}
1239 
1240 	return;
1241 }
1242 
1243 static int mlx5_mtu_to_ib_mtu(int mtu)
1244 {
1245 	switch (mtu) {
1246 	case 256: return 1;
1247 	case 512: return 2;
1248 	case 1024: return 3;
1249 	case 2048: return 4;
1250 	case 4096: return 5;
1251 	default:
1252 		pr_warn("invalid mtu\n");
1253 		return -1;
1254 	}
1255 }
1256 
1257 enum ib_max_vl_num {
1258 	__IB_MAX_VL_0		= 1,
1259 	__IB_MAX_VL_0_1		= 2,
1260 	__IB_MAX_VL_0_3		= 3,
1261 	__IB_MAX_VL_0_7		= 4,
1262 	__IB_MAX_VL_0_14	= 5,
1263 };
1264 
1265 enum mlx5_vl_hw_cap {
1266 	MLX5_VL_HW_0	= 1,
1267 	MLX5_VL_HW_0_1	= 2,
1268 	MLX5_VL_HW_0_2	= 3,
1269 	MLX5_VL_HW_0_3	= 4,
1270 	MLX5_VL_HW_0_4	= 5,
1271 	MLX5_VL_HW_0_5	= 6,
1272 	MLX5_VL_HW_0_6	= 7,
1273 	MLX5_VL_HW_0_7	= 8,
1274 	MLX5_VL_HW_0_14	= 15
1275 };
1276 
1277 static int translate_max_vl_num(struct ib_device *ibdev, u8 vl_hw_cap,
1278 				u8 *max_vl_num)
1279 {
1280 	switch (vl_hw_cap) {
1281 	case MLX5_VL_HW_0:
1282 		*max_vl_num = __IB_MAX_VL_0;
1283 		break;
1284 	case MLX5_VL_HW_0_1:
1285 		*max_vl_num = __IB_MAX_VL_0_1;
1286 		break;
1287 	case MLX5_VL_HW_0_3:
1288 		*max_vl_num = __IB_MAX_VL_0_3;
1289 		break;
1290 	case MLX5_VL_HW_0_7:
1291 		*max_vl_num = __IB_MAX_VL_0_7;
1292 		break;
1293 	case MLX5_VL_HW_0_14:
1294 		*max_vl_num = __IB_MAX_VL_0_14;
1295 		break;
1296 
1297 	default:
1298 		return -EINVAL;
1299 	}
1300 
1301 	return 0;
1302 }
1303 
1304 static int mlx5_query_hca_port(struct ib_device *ibdev, u8 port,
1305 			       struct ib_port_attr *props)
1306 {
1307 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
1308 	struct mlx5_core_dev *mdev = dev->mdev;
1309 	struct mlx5_hca_vport_context *rep;
1310 	u16 max_mtu;
1311 	u16 oper_mtu;
1312 	int err;
1313 	u8 ib_link_width_oper;
1314 	u8 vl_hw_cap;
1315 
1316 	rep = kzalloc(sizeof(*rep), GFP_KERNEL);
1317 	if (!rep) {
1318 		err = -ENOMEM;
1319 		goto out;
1320 	}
1321 
1322 	/* props being zeroed by the caller, avoid zeroing it here */
1323 
1324 	err = mlx5_query_hca_vport_context(mdev, 0, port, 0, rep);
1325 	if (err)
1326 		goto out;
1327 
1328 	props->lid		= rep->lid;
1329 	props->lmc		= rep->lmc;
1330 	props->sm_lid		= rep->sm_lid;
1331 	props->sm_sl		= rep->sm_sl;
1332 	props->state		= rep->vport_state;
1333 	props->phys_state	= rep->port_physical_state;
1334 	props->port_cap_flags	= rep->cap_mask1;
1335 	props->gid_tbl_len	= mlx5_get_gid_table_len(MLX5_CAP_GEN(mdev, gid_table_size));
1336 	props->max_msg_sz	= 1 << MLX5_CAP_GEN(mdev, log_max_msg);
1337 	props->pkey_tbl_len	= mlx5_to_sw_pkey_sz(MLX5_CAP_GEN(mdev, pkey_table_size));
1338 	props->bad_pkey_cntr	= rep->pkey_violation_counter;
1339 	props->qkey_viol_cntr	= rep->qkey_violation_counter;
1340 	props->subnet_timeout	= rep->subnet_timeout;
1341 	props->init_type_reply	= rep->init_type_reply;
1342 
1343 	if (props->port_cap_flags & IB_PORT_CAP_MASK2_SUP)
1344 		props->port_cap_flags2 = rep->cap_mask2;
1345 
1346 	err = mlx5_query_port_link_width_oper(mdev, &ib_link_width_oper, port);
1347 	if (err)
1348 		goto out;
1349 
1350 	translate_active_width(ibdev, ib_link_width_oper, &props->active_width);
1351 
1352 	err = mlx5_query_port_ib_proto_oper(mdev, &props->active_speed, port);
1353 	if (err)
1354 		goto out;
1355 
1356 	mlx5_query_port_max_mtu(mdev, &max_mtu, port);
1357 
1358 	props->max_mtu = mlx5_mtu_to_ib_mtu(max_mtu);
1359 
1360 	mlx5_query_port_oper_mtu(mdev, &oper_mtu, port);
1361 
1362 	props->active_mtu = mlx5_mtu_to_ib_mtu(oper_mtu);
1363 
1364 	err = mlx5_query_port_vl_hw_cap(mdev, &vl_hw_cap, port);
1365 	if (err)
1366 		goto out;
1367 
1368 	err = translate_max_vl_num(ibdev, vl_hw_cap,
1369 				   &props->max_vl_num);
1370 out:
1371 	kfree(rep);
1372 	return err;
1373 }
1374 
1375 int mlx5_ib_query_port(struct ib_device *ibdev, u8 port,
1376 		       struct ib_port_attr *props)
1377 {
1378 	unsigned int count;
1379 	int ret;
1380 
1381 	switch (mlx5_get_vport_access_method(ibdev)) {
1382 	case MLX5_VPORT_ACCESS_METHOD_MAD:
1383 		ret = mlx5_query_mad_ifc_port(ibdev, port, props);
1384 		break;
1385 
1386 	case MLX5_VPORT_ACCESS_METHOD_HCA:
1387 		ret = mlx5_query_hca_port(ibdev, port, props);
1388 		break;
1389 
1390 	case MLX5_VPORT_ACCESS_METHOD_NIC:
1391 		ret = mlx5_query_port_roce(ibdev, port, props);
1392 		break;
1393 
1394 	default:
1395 		ret = -EINVAL;
1396 	}
1397 
1398 	if (!ret && props) {
1399 		struct mlx5_ib_dev *dev = to_mdev(ibdev);
1400 		struct mlx5_core_dev *mdev;
1401 		bool put_mdev = true;
1402 
1403 		mdev = mlx5_ib_get_native_port_mdev(dev, port, NULL);
1404 		if (!mdev) {
1405 			/* If the port isn't affiliated yet query the master.
1406 			 * The master and slave will have the same values.
1407 			 */
1408 			mdev = dev->mdev;
1409 			port = 1;
1410 			put_mdev = false;
1411 		}
1412 		count = mlx5_core_reserved_gids_count(mdev);
1413 		if (put_mdev)
1414 			mlx5_ib_put_native_port_mdev(dev, port);
1415 		props->gid_tbl_len -= count;
1416 	}
1417 	return ret;
1418 }
1419 
1420 static int mlx5_ib_rep_query_port(struct ib_device *ibdev, u8 port,
1421 				  struct ib_port_attr *props)
1422 {
1423 	int ret;
1424 
1425 	/* Only link layer == ethernet is valid for representors
1426 	 * and we always use port 1
1427 	 */
1428 	ret = mlx5_query_port_roce(ibdev, port, props);
1429 	if (ret || !props)
1430 		return ret;
1431 
1432 	/* We don't support GIDS */
1433 	props->gid_tbl_len = 0;
1434 
1435 	return ret;
1436 }
1437 
1438 static int mlx5_ib_query_gid(struct ib_device *ibdev, u8 port, int index,
1439 			     union ib_gid *gid)
1440 {
1441 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
1442 	struct mlx5_core_dev *mdev = dev->mdev;
1443 
1444 	switch (mlx5_get_vport_access_method(ibdev)) {
1445 	case MLX5_VPORT_ACCESS_METHOD_MAD:
1446 		return mlx5_query_mad_ifc_gids(ibdev, port, index, gid);
1447 
1448 	case MLX5_VPORT_ACCESS_METHOD_HCA:
1449 		return mlx5_query_hca_vport_gid(mdev, 0, port, 0, index, gid);
1450 
1451 	default:
1452 		return -EINVAL;
1453 	}
1454 
1455 }
1456 
1457 static int mlx5_query_hca_nic_pkey(struct ib_device *ibdev, u8 port,
1458 				   u16 index, u16 *pkey)
1459 {
1460 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
1461 	struct mlx5_core_dev *mdev;
1462 	bool put_mdev = true;
1463 	u8 mdev_port_num;
1464 	int err;
1465 
1466 	mdev = mlx5_ib_get_native_port_mdev(dev, port, &mdev_port_num);
1467 	if (!mdev) {
1468 		/* The port isn't affiliated yet, get the PKey from the master
1469 		 * port. For RoCE the PKey tables will be the same.
1470 		 */
1471 		put_mdev = false;
1472 		mdev = dev->mdev;
1473 		mdev_port_num = 1;
1474 	}
1475 
1476 	err = mlx5_query_hca_vport_pkey(mdev, 0, mdev_port_num, 0,
1477 					index, pkey);
1478 	if (put_mdev)
1479 		mlx5_ib_put_native_port_mdev(dev, port);
1480 
1481 	return err;
1482 }
1483 
1484 static int mlx5_ib_query_pkey(struct ib_device *ibdev, u8 port, u16 index,
1485 			      u16 *pkey)
1486 {
1487 	switch (mlx5_get_vport_access_method(ibdev)) {
1488 	case MLX5_VPORT_ACCESS_METHOD_MAD:
1489 		return mlx5_query_mad_ifc_pkey(ibdev, port, index, pkey);
1490 
1491 	case MLX5_VPORT_ACCESS_METHOD_HCA:
1492 	case MLX5_VPORT_ACCESS_METHOD_NIC:
1493 		return mlx5_query_hca_nic_pkey(ibdev, port, index, pkey);
1494 	default:
1495 		return -EINVAL;
1496 	}
1497 }
1498 
1499 static int mlx5_ib_modify_device(struct ib_device *ibdev, int mask,
1500 				 struct ib_device_modify *props)
1501 {
1502 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
1503 	struct mlx5_reg_node_desc in;
1504 	struct mlx5_reg_node_desc out;
1505 	int err;
1506 
1507 	if (mask & ~IB_DEVICE_MODIFY_NODE_DESC)
1508 		return -EOPNOTSUPP;
1509 
1510 	if (!(mask & IB_DEVICE_MODIFY_NODE_DESC))
1511 		return 0;
1512 
1513 	/*
1514 	 * If possible, pass node desc to FW, so it can generate
1515 	 * a 144 trap.  If cmd fails, just ignore.
1516 	 */
1517 	memcpy(&in, props->node_desc, IB_DEVICE_NODE_DESC_MAX);
1518 	err = mlx5_core_access_reg(dev->mdev, &in, sizeof(in), &out,
1519 				   sizeof(out), MLX5_REG_NODE_DESC, 0, 1);
1520 	if (err)
1521 		return err;
1522 
1523 	memcpy(ibdev->node_desc, props->node_desc, IB_DEVICE_NODE_DESC_MAX);
1524 
1525 	return err;
1526 }
1527 
1528 static int set_port_caps_atomic(struct mlx5_ib_dev *dev, u8 port_num, u32 mask,
1529 				u32 value)
1530 {
1531 	struct mlx5_hca_vport_context ctx = {};
1532 	struct mlx5_core_dev *mdev;
1533 	u8 mdev_port_num;
1534 	int err;
1535 
1536 	mdev = mlx5_ib_get_native_port_mdev(dev, port_num, &mdev_port_num);
1537 	if (!mdev)
1538 		return -ENODEV;
1539 
1540 	err = mlx5_query_hca_vport_context(mdev, 0, mdev_port_num, 0, &ctx);
1541 	if (err)
1542 		goto out;
1543 
1544 	if (~ctx.cap_mask1_perm & mask) {
1545 		mlx5_ib_warn(dev, "trying to change bitmask 0x%X but change supported 0x%X\n",
1546 			     mask, ctx.cap_mask1_perm);
1547 		err = -EINVAL;
1548 		goto out;
1549 	}
1550 
1551 	ctx.cap_mask1 = value;
1552 	ctx.cap_mask1_perm = mask;
1553 	err = mlx5_core_modify_hca_vport_context(mdev, 0, mdev_port_num,
1554 						 0, &ctx);
1555 
1556 out:
1557 	mlx5_ib_put_native_port_mdev(dev, port_num);
1558 
1559 	return err;
1560 }
1561 
1562 static int mlx5_ib_modify_port(struct ib_device *ibdev, u8 port, int mask,
1563 			       struct ib_port_modify *props)
1564 {
1565 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
1566 	struct ib_port_attr attr;
1567 	u32 tmp;
1568 	int err;
1569 	u32 change_mask;
1570 	u32 value;
1571 	bool is_ib = (mlx5_ib_port_link_layer(ibdev, port) ==
1572 		      IB_LINK_LAYER_INFINIBAND);
1573 
1574 	/* CM layer calls ib_modify_port() regardless of the link layer. For
1575 	 * Ethernet ports, qkey violation and Port capabilities are meaningless.
1576 	 */
1577 	if (!is_ib)
1578 		return 0;
1579 
1580 	if (MLX5_CAP_GEN(dev->mdev, ib_virt) && is_ib) {
1581 		change_mask = props->clr_port_cap_mask | props->set_port_cap_mask;
1582 		value = ~props->clr_port_cap_mask | props->set_port_cap_mask;
1583 		return set_port_caps_atomic(dev, port, change_mask, value);
1584 	}
1585 
1586 	mutex_lock(&dev->cap_mask_mutex);
1587 
1588 	err = ib_query_port(ibdev, port, &attr);
1589 	if (err)
1590 		goto out;
1591 
1592 	tmp = (attr.port_cap_flags | props->set_port_cap_mask) &
1593 		~props->clr_port_cap_mask;
1594 
1595 	err = mlx5_set_port_caps(dev->mdev, port, tmp);
1596 
1597 out:
1598 	mutex_unlock(&dev->cap_mask_mutex);
1599 	return err;
1600 }
1601 
1602 static void print_lib_caps(struct mlx5_ib_dev *dev, u64 caps)
1603 {
1604 	mlx5_ib_dbg(dev, "MLX5_LIB_CAP_4K_UAR = %s\n",
1605 		    caps & MLX5_LIB_CAP_4K_UAR ? "y" : "n");
1606 }
1607 
1608 static u16 calc_dynamic_bfregs(int uars_per_sys_page)
1609 {
1610 	/* Large page with non 4k uar support might limit the dynamic size */
1611 	if (uars_per_sys_page == 1  && PAGE_SIZE > 4096)
1612 		return MLX5_MIN_DYN_BFREGS;
1613 
1614 	return MLX5_MAX_DYN_BFREGS;
1615 }
1616 
1617 static int calc_total_bfregs(struct mlx5_ib_dev *dev, bool lib_uar_4k,
1618 			     struct mlx5_ib_alloc_ucontext_req_v2 *req,
1619 			     struct mlx5_bfreg_info *bfregi)
1620 {
1621 	int uars_per_sys_page;
1622 	int bfregs_per_sys_page;
1623 	int ref_bfregs = req->total_num_bfregs;
1624 
1625 	if (req->total_num_bfregs == 0)
1626 		return -EINVAL;
1627 
1628 	BUILD_BUG_ON(MLX5_MAX_BFREGS % MLX5_NON_FP_BFREGS_IN_PAGE);
1629 	BUILD_BUG_ON(MLX5_MAX_BFREGS < MLX5_NON_FP_BFREGS_IN_PAGE);
1630 
1631 	if (req->total_num_bfregs > MLX5_MAX_BFREGS)
1632 		return -ENOMEM;
1633 
1634 	uars_per_sys_page = get_uars_per_sys_page(dev, lib_uar_4k);
1635 	bfregs_per_sys_page = uars_per_sys_page * MLX5_NON_FP_BFREGS_PER_UAR;
1636 	/* This holds the required static allocation asked by the user */
1637 	req->total_num_bfregs = ALIGN(req->total_num_bfregs, bfregs_per_sys_page);
1638 	if (req->num_low_latency_bfregs > req->total_num_bfregs - 1)
1639 		return -EINVAL;
1640 
1641 	bfregi->num_static_sys_pages = req->total_num_bfregs / bfregs_per_sys_page;
1642 	bfregi->num_dyn_bfregs = ALIGN(calc_dynamic_bfregs(uars_per_sys_page), bfregs_per_sys_page);
1643 	bfregi->total_num_bfregs = req->total_num_bfregs + bfregi->num_dyn_bfregs;
1644 	bfregi->num_sys_pages = bfregi->total_num_bfregs / bfregs_per_sys_page;
1645 
1646 	mlx5_ib_dbg(dev, "uar_4k: fw support %s, lib support %s, user requested %d bfregs, allocated %d, total bfregs %d, using %d sys pages\n",
1647 		    MLX5_CAP_GEN(dev->mdev, uar_4k) ? "yes" : "no",
1648 		    lib_uar_4k ? "yes" : "no", ref_bfregs,
1649 		    req->total_num_bfregs, bfregi->total_num_bfregs,
1650 		    bfregi->num_sys_pages);
1651 
1652 	return 0;
1653 }
1654 
1655 static int allocate_uars(struct mlx5_ib_dev *dev, struct mlx5_ib_ucontext *context)
1656 {
1657 	struct mlx5_bfreg_info *bfregi;
1658 	int err;
1659 	int i;
1660 
1661 	bfregi = &context->bfregi;
1662 	for (i = 0; i < bfregi->num_static_sys_pages; i++) {
1663 		err = mlx5_cmd_alloc_uar(dev->mdev, &bfregi->sys_pages[i]);
1664 		if (err)
1665 			goto error;
1666 
1667 		mlx5_ib_dbg(dev, "allocated uar %d\n", bfregi->sys_pages[i]);
1668 	}
1669 
1670 	for (i = bfregi->num_static_sys_pages; i < bfregi->num_sys_pages; i++)
1671 		bfregi->sys_pages[i] = MLX5_IB_INVALID_UAR_INDEX;
1672 
1673 	return 0;
1674 
1675 error:
1676 	for (--i; i >= 0; i--)
1677 		if (mlx5_cmd_free_uar(dev->mdev, bfregi->sys_pages[i]))
1678 			mlx5_ib_warn(dev, "failed to free uar %d\n", i);
1679 
1680 	return err;
1681 }
1682 
1683 static void deallocate_uars(struct mlx5_ib_dev *dev,
1684 			    struct mlx5_ib_ucontext *context)
1685 {
1686 	struct mlx5_bfreg_info *bfregi;
1687 	int i;
1688 
1689 	bfregi = &context->bfregi;
1690 	for (i = 0; i < bfregi->num_sys_pages; i++)
1691 		if (i < bfregi->num_static_sys_pages ||
1692 		    bfregi->sys_pages[i] != MLX5_IB_INVALID_UAR_INDEX)
1693 			mlx5_cmd_free_uar(dev->mdev, bfregi->sys_pages[i]);
1694 }
1695 
1696 int mlx5_ib_enable_lb(struct mlx5_ib_dev *dev, bool td, bool qp)
1697 {
1698 	int err = 0;
1699 
1700 	mutex_lock(&dev->lb.mutex);
1701 	if (td)
1702 		dev->lb.user_td++;
1703 	if (qp)
1704 		dev->lb.qps++;
1705 
1706 	if (dev->lb.user_td == 2 ||
1707 	    dev->lb.qps == 1) {
1708 		if (!dev->lb.enabled) {
1709 			err = mlx5_nic_vport_update_local_lb(dev->mdev, true);
1710 			dev->lb.enabled = true;
1711 		}
1712 	}
1713 
1714 	mutex_unlock(&dev->lb.mutex);
1715 
1716 	return err;
1717 }
1718 
1719 void mlx5_ib_disable_lb(struct mlx5_ib_dev *dev, bool td, bool qp)
1720 {
1721 	mutex_lock(&dev->lb.mutex);
1722 	if (td)
1723 		dev->lb.user_td--;
1724 	if (qp)
1725 		dev->lb.qps--;
1726 
1727 	if (dev->lb.user_td == 1 &&
1728 	    dev->lb.qps == 0) {
1729 		if (dev->lb.enabled) {
1730 			mlx5_nic_vport_update_local_lb(dev->mdev, false);
1731 			dev->lb.enabled = false;
1732 		}
1733 	}
1734 
1735 	mutex_unlock(&dev->lb.mutex);
1736 }
1737 
1738 static int mlx5_ib_alloc_transport_domain(struct mlx5_ib_dev *dev, u32 *tdn,
1739 					  u16 uid)
1740 {
1741 	int err;
1742 
1743 	if (!MLX5_CAP_GEN(dev->mdev, log_max_transport_domain))
1744 		return 0;
1745 
1746 	err = mlx5_cmd_alloc_transport_domain(dev->mdev, tdn, uid);
1747 	if (err)
1748 		return err;
1749 
1750 	if ((MLX5_CAP_GEN(dev->mdev, port_type) != MLX5_CAP_PORT_TYPE_ETH) ||
1751 	    (!MLX5_CAP_GEN(dev->mdev, disable_local_lb_uc) &&
1752 	     !MLX5_CAP_GEN(dev->mdev, disable_local_lb_mc)))
1753 		return err;
1754 
1755 	return mlx5_ib_enable_lb(dev, true, false);
1756 }
1757 
1758 static void mlx5_ib_dealloc_transport_domain(struct mlx5_ib_dev *dev, u32 tdn,
1759 					     u16 uid)
1760 {
1761 	if (!MLX5_CAP_GEN(dev->mdev, log_max_transport_domain))
1762 		return;
1763 
1764 	mlx5_cmd_dealloc_transport_domain(dev->mdev, tdn, uid);
1765 
1766 	if ((MLX5_CAP_GEN(dev->mdev, port_type) != MLX5_CAP_PORT_TYPE_ETH) ||
1767 	    (!MLX5_CAP_GEN(dev->mdev, disable_local_lb_uc) &&
1768 	     !MLX5_CAP_GEN(dev->mdev, disable_local_lb_mc)))
1769 		return;
1770 
1771 	mlx5_ib_disable_lb(dev, true, false);
1772 }
1773 
1774 static int mlx5_ib_alloc_ucontext(struct ib_ucontext *uctx,
1775 				  struct ib_udata *udata)
1776 {
1777 	struct ib_device *ibdev = uctx->device;
1778 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
1779 	struct mlx5_ib_alloc_ucontext_req_v2 req = {};
1780 	struct mlx5_ib_alloc_ucontext_resp resp = {};
1781 	struct mlx5_core_dev *mdev = dev->mdev;
1782 	struct mlx5_ib_ucontext *context = to_mucontext(uctx);
1783 	struct mlx5_bfreg_info *bfregi;
1784 	int ver;
1785 	int err;
1786 	size_t min_req_v2 = offsetof(struct mlx5_ib_alloc_ucontext_req_v2,
1787 				     max_cqe_version);
1788 	u32 dump_fill_mkey;
1789 	bool lib_uar_4k;
1790 	bool lib_uar_dyn;
1791 
1792 	if (!dev->ib_active)
1793 		return -EAGAIN;
1794 
1795 	if (udata->inlen == sizeof(struct mlx5_ib_alloc_ucontext_req))
1796 		ver = 0;
1797 	else if (udata->inlen >= min_req_v2)
1798 		ver = 2;
1799 	else
1800 		return -EINVAL;
1801 
1802 	err = ib_copy_from_udata(&req, udata, min(udata->inlen, sizeof(req)));
1803 	if (err)
1804 		return err;
1805 
1806 	if (req.flags & ~MLX5_IB_ALLOC_UCTX_DEVX)
1807 		return -EOPNOTSUPP;
1808 
1809 	if (req.comp_mask || req.reserved0 || req.reserved1 || req.reserved2)
1810 		return -EOPNOTSUPP;
1811 
1812 	req.total_num_bfregs = ALIGN(req.total_num_bfregs,
1813 				    MLX5_NON_FP_BFREGS_PER_UAR);
1814 	if (req.num_low_latency_bfregs > req.total_num_bfregs - 1)
1815 		return -EINVAL;
1816 
1817 	resp.qp_tab_size = 1 << MLX5_CAP_GEN(dev->mdev, log_max_qp);
1818 	if (dev->wc_support)
1819 		resp.bf_reg_size = 1 << MLX5_CAP_GEN(dev->mdev, log_bf_reg_size);
1820 	resp.cache_line_size = cache_line_size();
1821 	resp.max_sq_desc_sz = MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq);
1822 	resp.max_rq_desc_sz = MLX5_CAP_GEN(dev->mdev, max_wqe_sz_rq);
1823 	resp.max_send_wqebb = 1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz);
1824 	resp.max_recv_wr = 1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz);
1825 	resp.max_srq_recv_wr = 1 << MLX5_CAP_GEN(dev->mdev, log_max_srq_sz);
1826 	resp.cqe_version = min_t(__u8,
1827 				 (__u8)MLX5_CAP_GEN(dev->mdev, cqe_version),
1828 				 req.max_cqe_version);
1829 	resp.log_uar_size = MLX5_CAP_GEN(dev->mdev, uar_4k) ?
1830 				MLX5_ADAPTER_PAGE_SHIFT : PAGE_SHIFT;
1831 	resp.num_uars_per_page = MLX5_CAP_GEN(dev->mdev, uar_4k) ?
1832 					MLX5_CAP_GEN(dev->mdev, num_of_uars_per_page) : 1;
1833 	resp.response_length = min(offsetof(typeof(resp), response_length) +
1834 				   sizeof(resp.response_length), udata->outlen);
1835 
1836 	if (mlx5_accel_ipsec_device_caps(dev->mdev) & MLX5_ACCEL_IPSEC_CAP_DEVICE) {
1837 		if (mlx5_get_flow_namespace(dev->mdev, MLX5_FLOW_NAMESPACE_EGRESS))
1838 			resp.flow_action_flags |= MLX5_USER_ALLOC_UCONTEXT_FLOW_ACTION_FLAGS_ESP_AES_GCM;
1839 		if (mlx5_accel_ipsec_device_caps(dev->mdev) & MLX5_ACCEL_IPSEC_CAP_REQUIRED_METADATA)
1840 			resp.flow_action_flags |= MLX5_USER_ALLOC_UCONTEXT_FLOW_ACTION_FLAGS_ESP_AES_GCM_REQ_METADATA;
1841 		if (MLX5_CAP_FLOWTABLE(dev->mdev, flow_table_properties_nic_receive.ft_field_support.outer_esp_spi))
1842 			resp.flow_action_flags |= MLX5_USER_ALLOC_UCONTEXT_FLOW_ACTION_FLAGS_ESP_AES_GCM_SPI_STEERING;
1843 		if (mlx5_accel_ipsec_device_caps(dev->mdev) & MLX5_ACCEL_IPSEC_CAP_TX_IV_IS_ESN)
1844 			resp.flow_action_flags |= MLX5_USER_ALLOC_UCONTEXT_FLOW_ACTION_FLAGS_ESP_AES_GCM_TX_IV_IS_ESN;
1845 		/* MLX5_USER_ALLOC_UCONTEXT_FLOW_ACTION_FLAGS_ESP_AES_GCM_FULL_OFFLOAD is currently always 0 */
1846 	}
1847 
1848 	lib_uar_4k = req.lib_caps & MLX5_LIB_CAP_4K_UAR;
1849 	lib_uar_dyn = req.lib_caps & MLX5_LIB_CAP_DYN_UAR;
1850 	bfregi = &context->bfregi;
1851 
1852 	if (lib_uar_dyn) {
1853 		bfregi->lib_uar_dyn = lib_uar_dyn;
1854 		goto uar_done;
1855 	}
1856 
1857 	/* updates req->total_num_bfregs */
1858 	err = calc_total_bfregs(dev, lib_uar_4k, &req, bfregi);
1859 	if (err)
1860 		goto out_ctx;
1861 
1862 	mutex_init(&bfregi->lock);
1863 	bfregi->lib_uar_4k = lib_uar_4k;
1864 	bfregi->count = kcalloc(bfregi->total_num_bfregs, sizeof(*bfregi->count),
1865 				GFP_KERNEL);
1866 	if (!bfregi->count) {
1867 		err = -ENOMEM;
1868 		goto out_ctx;
1869 	}
1870 
1871 	bfregi->sys_pages = kcalloc(bfregi->num_sys_pages,
1872 				    sizeof(*bfregi->sys_pages),
1873 				    GFP_KERNEL);
1874 	if (!bfregi->sys_pages) {
1875 		err = -ENOMEM;
1876 		goto out_count;
1877 	}
1878 
1879 	err = allocate_uars(dev, context);
1880 	if (err)
1881 		goto out_sys_pages;
1882 
1883 uar_done:
1884 	if (req.flags & MLX5_IB_ALLOC_UCTX_DEVX) {
1885 		err = mlx5_ib_devx_create(dev, true);
1886 		if (err < 0)
1887 			goto out_uars;
1888 		context->devx_uid = err;
1889 	}
1890 
1891 	err = mlx5_ib_alloc_transport_domain(dev, &context->tdn,
1892 					     context->devx_uid);
1893 	if (err)
1894 		goto out_devx;
1895 
1896 	if (MLX5_CAP_GEN(dev->mdev, dump_fill_mkey)) {
1897 		err = mlx5_cmd_dump_fill_mkey(dev->mdev, &dump_fill_mkey);
1898 		if (err)
1899 			goto out_mdev;
1900 	}
1901 
1902 	INIT_LIST_HEAD(&context->db_page_list);
1903 	mutex_init(&context->db_page_mutex);
1904 
1905 	resp.tot_bfregs = lib_uar_dyn ? 0 : req.total_num_bfregs;
1906 	resp.num_ports = dev->num_ports;
1907 
1908 	if (offsetofend(typeof(resp), cqe_version) <= udata->outlen)
1909 		resp.response_length += sizeof(resp.cqe_version);
1910 
1911 	if (offsetofend(typeof(resp), cmds_supp_uhw) <= udata->outlen) {
1912 		resp.cmds_supp_uhw |= MLX5_USER_CMDS_SUPP_UHW_QUERY_DEVICE |
1913 				      MLX5_USER_CMDS_SUPP_UHW_CREATE_AH;
1914 		resp.response_length += sizeof(resp.cmds_supp_uhw);
1915 	}
1916 
1917 	if (offsetofend(typeof(resp), eth_min_inline) <= udata->outlen) {
1918 		if (mlx5_ib_port_link_layer(ibdev, 1) == IB_LINK_LAYER_ETHERNET) {
1919 			mlx5_query_min_inline(dev->mdev, &resp.eth_min_inline);
1920 			resp.eth_min_inline++;
1921 		}
1922 		resp.response_length += sizeof(resp.eth_min_inline);
1923 	}
1924 
1925 	if (offsetofend(typeof(resp), clock_info_versions) <= udata->outlen) {
1926 		if (mdev->clock_info)
1927 			resp.clock_info_versions = BIT(MLX5_IB_CLOCK_INFO_V1);
1928 		resp.response_length += sizeof(resp.clock_info_versions);
1929 	}
1930 
1931 	/*
1932 	 * We don't want to expose information from the PCI bar that is located
1933 	 * after 4096 bytes, so if the arch only supports larger pages, let's
1934 	 * pretend we don't support reading the HCA's core clock. This is also
1935 	 * forced by mmap function.
1936 	 */
1937 	if (offsetofend(typeof(resp), hca_core_clock_offset) <= udata->outlen) {
1938 		if (PAGE_SIZE <= 4096) {
1939 			resp.comp_mask |=
1940 				MLX5_IB_ALLOC_UCONTEXT_RESP_MASK_CORE_CLOCK_OFFSET;
1941 			resp.hca_core_clock_offset =
1942 				offsetof(struct mlx5_init_seg, internal_timer_h) % PAGE_SIZE;
1943 		}
1944 		resp.response_length += sizeof(resp.hca_core_clock_offset);
1945 	}
1946 
1947 	if (offsetofend(typeof(resp), log_uar_size) <= udata->outlen)
1948 		resp.response_length += sizeof(resp.log_uar_size);
1949 
1950 	if (offsetofend(typeof(resp), num_uars_per_page) <= udata->outlen)
1951 		resp.response_length += sizeof(resp.num_uars_per_page);
1952 
1953 	if (offsetofend(typeof(resp), num_dyn_bfregs) <= udata->outlen) {
1954 		resp.num_dyn_bfregs = bfregi->num_dyn_bfregs;
1955 		resp.response_length += sizeof(resp.num_dyn_bfregs);
1956 	}
1957 
1958 	if (offsetofend(typeof(resp), dump_fill_mkey) <= udata->outlen) {
1959 		if (MLX5_CAP_GEN(dev->mdev, dump_fill_mkey)) {
1960 			resp.dump_fill_mkey = dump_fill_mkey;
1961 			resp.comp_mask |=
1962 				MLX5_IB_ALLOC_UCONTEXT_RESP_MASK_DUMP_FILL_MKEY;
1963 		}
1964 		resp.response_length += sizeof(resp.dump_fill_mkey);
1965 	}
1966 
1967 	err = ib_copy_to_udata(udata, &resp, resp.response_length);
1968 	if (err)
1969 		goto out_mdev;
1970 
1971 	bfregi->ver = ver;
1972 	bfregi->num_low_latency_bfregs = req.num_low_latency_bfregs;
1973 	context->cqe_version = resp.cqe_version;
1974 	context->lib_caps = req.lib_caps;
1975 	print_lib_caps(dev, context->lib_caps);
1976 
1977 	if (dev->lag_active) {
1978 		u8 port = mlx5_core_native_port_num(dev->mdev) - 1;
1979 
1980 		atomic_set(&context->tx_port_affinity,
1981 			   atomic_add_return(
1982 				   1, &dev->port[port].roce.tx_port_affinity));
1983 	}
1984 
1985 	return 0;
1986 
1987 out_mdev:
1988 	mlx5_ib_dealloc_transport_domain(dev, context->tdn, context->devx_uid);
1989 out_devx:
1990 	if (req.flags & MLX5_IB_ALLOC_UCTX_DEVX)
1991 		mlx5_ib_devx_destroy(dev, context->devx_uid);
1992 
1993 out_uars:
1994 	deallocate_uars(dev, context);
1995 
1996 out_sys_pages:
1997 	kfree(bfregi->sys_pages);
1998 
1999 out_count:
2000 	kfree(bfregi->count);
2001 
2002 out_ctx:
2003 	return err;
2004 }
2005 
2006 static void mlx5_ib_dealloc_ucontext(struct ib_ucontext *ibcontext)
2007 {
2008 	struct mlx5_ib_ucontext *context = to_mucontext(ibcontext);
2009 	struct mlx5_ib_dev *dev = to_mdev(ibcontext->device);
2010 	struct mlx5_bfreg_info *bfregi;
2011 
2012 	bfregi = &context->bfregi;
2013 	mlx5_ib_dealloc_transport_domain(dev, context->tdn, context->devx_uid);
2014 
2015 	if (context->devx_uid)
2016 		mlx5_ib_devx_destroy(dev, context->devx_uid);
2017 
2018 	deallocate_uars(dev, context);
2019 	kfree(bfregi->sys_pages);
2020 	kfree(bfregi->count);
2021 }
2022 
2023 static phys_addr_t uar_index2pfn(struct mlx5_ib_dev *dev,
2024 				 int uar_idx)
2025 {
2026 	int fw_uars_per_page;
2027 
2028 	fw_uars_per_page = MLX5_CAP_GEN(dev->mdev, uar_4k) ? MLX5_UARS_IN_PAGE : 1;
2029 
2030 	return (dev->mdev->bar_addr >> PAGE_SHIFT) + uar_idx / fw_uars_per_page;
2031 }
2032 
2033 static u64 uar_index2paddress(struct mlx5_ib_dev *dev,
2034 				 int uar_idx)
2035 {
2036 	unsigned int fw_uars_per_page;
2037 
2038 	fw_uars_per_page = MLX5_CAP_GEN(dev->mdev, uar_4k) ?
2039 				MLX5_UARS_IN_PAGE : 1;
2040 
2041 	return (dev->mdev->bar_addr + (uar_idx / fw_uars_per_page) * PAGE_SIZE);
2042 }
2043 
2044 static int get_command(unsigned long offset)
2045 {
2046 	return (offset >> MLX5_IB_MMAP_CMD_SHIFT) & MLX5_IB_MMAP_CMD_MASK;
2047 }
2048 
2049 static int get_arg(unsigned long offset)
2050 {
2051 	return offset & ((1 << MLX5_IB_MMAP_CMD_SHIFT) - 1);
2052 }
2053 
2054 static int get_index(unsigned long offset)
2055 {
2056 	return get_arg(offset);
2057 }
2058 
2059 /* Index resides in an extra byte to enable larger values than 255 */
2060 static int get_extended_index(unsigned long offset)
2061 {
2062 	return get_arg(offset) | ((offset >> 16) & 0xff) << 8;
2063 }
2064 
2065 
2066 static void mlx5_ib_disassociate_ucontext(struct ib_ucontext *ibcontext)
2067 {
2068 }
2069 
2070 static inline char *mmap_cmd2str(enum mlx5_ib_mmap_cmd cmd)
2071 {
2072 	switch (cmd) {
2073 	case MLX5_IB_MMAP_WC_PAGE:
2074 		return "WC";
2075 	case MLX5_IB_MMAP_REGULAR_PAGE:
2076 		return "best effort WC";
2077 	case MLX5_IB_MMAP_NC_PAGE:
2078 		return "NC";
2079 	case MLX5_IB_MMAP_DEVICE_MEM:
2080 		return "Device Memory";
2081 	default:
2082 		return NULL;
2083 	}
2084 }
2085 
2086 static int mlx5_ib_mmap_clock_info_page(struct mlx5_ib_dev *dev,
2087 					struct vm_area_struct *vma,
2088 					struct mlx5_ib_ucontext *context)
2089 {
2090 	if ((vma->vm_end - vma->vm_start != PAGE_SIZE) ||
2091 	    !(vma->vm_flags & VM_SHARED))
2092 		return -EINVAL;
2093 
2094 	if (get_index(vma->vm_pgoff) != MLX5_IB_CLOCK_INFO_V1)
2095 		return -EOPNOTSUPP;
2096 
2097 	if (vma->vm_flags & (VM_WRITE | VM_EXEC))
2098 		return -EPERM;
2099 	vma->vm_flags &= ~VM_MAYWRITE;
2100 
2101 	if (!dev->mdev->clock_info)
2102 		return -EOPNOTSUPP;
2103 
2104 	return vm_insert_page(vma, vma->vm_start,
2105 			      virt_to_page(dev->mdev->clock_info));
2106 }
2107 
2108 static void mlx5_ib_mmap_free(struct rdma_user_mmap_entry *entry)
2109 {
2110 	struct mlx5_user_mmap_entry *mentry = to_mmmap(entry);
2111 	struct mlx5_ib_dev *dev = to_mdev(entry->ucontext->device);
2112 	struct mlx5_var_table *var_table = &dev->var_table;
2113 	struct mlx5_ib_dm *mdm;
2114 
2115 	switch (mentry->mmap_flag) {
2116 	case MLX5_IB_MMAP_TYPE_MEMIC:
2117 		mdm = container_of(mentry, struct mlx5_ib_dm, mentry);
2118 		mlx5_cmd_dealloc_memic(&dev->dm, mdm->dev_addr,
2119 				       mdm->size);
2120 		kfree(mdm);
2121 		break;
2122 	case MLX5_IB_MMAP_TYPE_VAR:
2123 		mutex_lock(&var_table->bitmap_lock);
2124 		clear_bit(mentry->page_idx, var_table->bitmap);
2125 		mutex_unlock(&var_table->bitmap_lock);
2126 		kfree(mentry);
2127 		break;
2128 	case MLX5_IB_MMAP_TYPE_UAR_WC:
2129 	case MLX5_IB_MMAP_TYPE_UAR_NC:
2130 		mlx5_cmd_free_uar(dev->mdev, mentry->page_idx);
2131 		kfree(mentry);
2132 		break;
2133 	default:
2134 		WARN_ON(true);
2135 	}
2136 }
2137 
2138 static int uar_mmap(struct mlx5_ib_dev *dev, enum mlx5_ib_mmap_cmd cmd,
2139 		    struct vm_area_struct *vma,
2140 		    struct mlx5_ib_ucontext *context)
2141 {
2142 	struct mlx5_bfreg_info *bfregi = &context->bfregi;
2143 	int err;
2144 	unsigned long idx;
2145 	phys_addr_t pfn;
2146 	pgprot_t prot;
2147 	u32 bfreg_dyn_idx = 0;
2148 	u32 uar_index;
2149 	int dyn_uar = (cmd == MLX5_IB_MMAP_ALLOC_WC);
2150 	int max_valid_idx = dyn_uar ? bfregi->num_sys_pages :
2151 				bfregi->num_static_sys_pages;
2152 
2153 	if (bfregi->lib_uar_dyn)
2154 		return -EINVAL;
2155 
2156 	if (vma->vm_end - vma->vm_start != PAGE_SIZE)
2157 		return -EINVAL;
2158 
2159 	if (dyn_uar)
2160 		idx = get_extended_index(vma->vm_pgoff) + bfregi->num_static_sys_pages;
2161 	else
2162 		idx = get_index(vma->vm_pgoff);
2163 
2164 	if (idx >= max_valid_idx) {
2165 		mlx5_ib_warn(dev, "invalid uar index %lu, max=%d\n",
2166 			     idx, max_valid_idx);
2167 		return -EINVAL;
2168 	}
2169 
2170 	switch (cmd) {
2171 	case MLX5_IB_MMAP_WC_PAGE:
2172 	case MLX5_IB_MMAP_ALLOC_WC:
2173 	case MLX5_IB_MMAP_REGULAR_PAGE:
2174 		/* For MLX5_IB_MMAP_REGULAR_PAGE do the best effort to get WC */
2175 		prot = pgprot_writecombine(vma->vm_page_prot);
2176 		break;
2177 	case MLX5_IB_MMAP_NC_PAGE:
2178 		prot = pgprot_noncached(vma->vm_page_prot);
2179 		break;
2180 	default:
2181 		return -EINVAL;
2182 	}
2183 
2184 	if (dyn_uar) {
2185 		int uars_per_page;
2186 
2187 		uars_per_page = get_uars_per_sys_page(dev, bfregi->lib_uar_4k);
2188 		bfreg_dyn_idx = idx * (uars_per_page * MLX5_NON_FP_BFREGS_PER_UAR);
2189 		if (bfreg_dyn_idx >= bfregi->total_num_bfregs) {
2190 			mlx5_ib_warn(dev, "invalid bfreg_dyn_idx %u, max=%u\n",
2191 				     bfreg_dyn_idx, bfregi->total_num_bfregs);
2192 			return -EINVAL;
2193 		}
2194 
2195 		mutex_lock(&bfregi->lock);
2196 		/* Fail if uar already allocated, first bfreg index of each
2197 		 * page holds its count.
2198 		 */
2199 		if (bfregi->count[bfreg_dyn_idx]) {
2200 			mlx5_ib_warn(dev, "wrong offset, idx %lu is busy, bfregn=%u\n", idx, bfreg_dyn_idx);
2201 			mutex_unlock(&bfregi->lock);
2202 			return -EINVAL;
2203 		}
2204 
2205 		bfregi->count[bfreg_dyn_idx]++;
2206 		mutex_unlock(&bfregi->lock);
2207 
2208 		err = mlx5_cmd_alloc_uar(dev->mdev, &uar_index);
2209 		if (err) {
2210 			mlx5_ib_warn(dev, "UAR alloc failed\n");
2211 			goto free_bfreg;
2212 		}
2213 	} else {
2214 		uar_index = bfregi->sys_pages[idx];
2215 	}
2216 
2217 	pfn = uar_index2pfn(dev, uar_index);
2218 	mlx5_ib_dbg(dev, "uar idx 0x%lx, pfn %pa\n", idx, &pfn);
2219 
2220 	err = rdma_user_mmap_io(&context->ibucontext, vma, pfn, PAGE_SIZE,
2221 				prot, NULL);
2222 	if (err) {
2223 		mlx5_ib_err(dev,
2224 			    "rdma_user_mmap_io failed with error=%d, mmap_cmd=%s\n",
2225 			    err, mmap_cmd2str(cmd));
2226 		goto err;
2227 	}
2228 
2229 	if (dyn_uar)
2230 		bfregi->sys_pages[idx] = uar_index;
2231 	return 0;
2232 
2233 err:
2234 	if (!dyn_uar)
2235 		return err;
2236 
2237 	mlx5_cmd_free_uar(dev->mdev, idx);
2238 
2239 free_bfreg:
2240 	mlx5_ib_free_bfreg(dev, bfregi, bfreg_dyn_idx);
2241 
2242 	return err;
2243 }
2244 
2245 static int add_dm_mmap_entry(struct ib_ucontext *context,
2246 			     struct mlx5_ib_dm *mdm,
2247 			     u64 address)
2248 {
2249 	mdm->mentry.mmap_flag = MLX5_IB_MMAP_TYPE_MEMIC;
2250 	mdm->mentry.address = address;
2251 	return rdma_user_mmap_entry_insert_range(
2252 			context, &mdm->mentry.rdma_entry,
2253 			mdm->size,
2254 			MLX5_IB_MMAP_DEVICE_MEM << 16,
2255 			(MLX5_IB_MMAP_DEVICE_MEM << 16) + (1UL << 16) - 1);
2256 }
2257 
2258 static unsigned long mlx5_vma_to_pgoff(struct vm_area_struct *vma)
2259 {
2260 	unsigned long idx;
2261 	u8 command;
2262 
2263 	command = get_command(vma->vm_pgoff);
2264 	idx = get_extended_index(vma->vm_pgoff);
2265 
2266 	return (command << 16 | idx);
2267 }
2268 
2269 static int mlx5_ib_mmap_offset(struct mlx5_ib_dev *dev,
2270 			       struct vm_area_struct *vma,
2271 			       struct ib_ucontext *ucontext)
2272 {
2273 	struct mlx5_user_mmap_entry *mentry;
2274 	struct rdma_user_mmap_entry *entry;
2275 	unsigned long pgoff;
2276 	pgprot_t prot;
2277 	phys_addr_t pfn;
2278 	int ret;
2279 
2280 	pgoff = mlx5_vma_to_pgoff(vma);
2281 	entry = rdma_user_mmap_entry_get_pgoff(ucontext, pgoff);
2282 	if (!entry)
2283 		return -EINVAL;
2284 
2285 	mentry = to_mmmap(entry);
2286 	pfn = (mentry->address >> PAGE_SHIFT);
2287 	if (mentry->mmap_flag == MLX5_IB_MMAP_TYPE_VAR ||
2288 	    mentry->mmap_flag == MLX5_IB_MMAP_TYPE_UAR_NC)
2289 		prot = pgprot_noncached(vma->vm_page_prot);
2290 	else
2291 		prot = pgprot_writecombine(vma->vm_page_prot);
2292 	ret = rdma_user_mmap_io(ucontext, vma, pfn,
2293 				entry->npages * PAGE_SIZE,
2294 				prot,
2295 				entry);
2296 	rdma_user_mmap_entry_put(&mentry->rdma_entry);
2297 	return ret;
2298 }
2299 
2300 static u64 mlx5_entry_to_mmap_offset(struct mlx5_user_mmap_entry *entry)
2301 {
2302 	u64 cmd = (entry->rdma_entry.start_pgoff >> 16) & 0xFFFF;
2303 	u64 index = entry->rdma_entry.start_pgoff & 0xFFFF;
2304 
2305 	return (((index >> 8) << 16) | (cmd << MLX5_IB_MMAP_CMD_SHIFT) |
2306 		(index & 0xFF)) << PAGE_SHIFT;
2307 }
2308 
2309 static int mlx5_ib_mmap(struct ib_ucontext *ibcontext, struct vm_area_struct *vma)
2310 {
2311 	struct mlx5_ib_ucontext *context = to_mucontext(ibcontext);
2312 	struct mlx5_ib_dev *dev = to_mdev(ibcontext->device);
2313 	unsigned long command;
2314 	phys_addr_t pfn;
2315 
2316 	command = get_command(vma->vm_pgoff);
2317 	switch (command) {
2318 	case MLX5_IB_MMAP_WC_PAGE:
2319 	case MLX5_IB_MMAP_ALLOC_WC:
2320 		if (!dev->wc_support)
2321 			return -EPERM;
2322 		fallthrough;
2323 	case MLX5_IB_MMAP_NC_PAGE:
2324 	case MLX5_IB_MMAP_REGULAR_PAGE:
2325 		return uar_mmap(dev, command, vma, context);
2326 
2327 	case MLX5_IB_MMAP_GET_CONTIGUOUS_PAGES:
2328 		return -ENOSYS;
2329 
2330 	case MLX5_IB_MMAP_CORE_CLOCK:
2331 		if (vma->vm_end - vma->vm_start != PAGE_SIZE)
2332 			return -EINVAL;
2333 
2334 		if (vma->vm_flags & VM_WRITE)
2335 			return -EPERM;
2336 		vma->vm_flags &= ~VM_MAYWRITE;
2337 
2338 		/* Don't expose to user-space information it shouldn't have */
2339 		if (PAGE_SIZE > 4096)
2340 			return -EOPNOTSUPP;
2341 
2342 		pfn = (dev->mdev->iseg_base +
2343 		       offsetof(struct mlx5_init_seg, internal_timer_h)) >>
2344 			PAGE_SHIFT;
2345 		return rdma_user_mmap_io(&context->ibucontext, vma, pfn,
2346 					 PAGE_SIZE,
2347 					 pgprot_noncached(vma->vm_page_prot),
2348 					 NULL);
2349 	case MLX5_IB_MMAP_CLOCK_INFO:
2350 		return mlx5_ib_mmap_clock_info_page(dev, vma, context);
2351 
2352 	default:
2353 		return mlx5_ib_mmap_offset(dev, vma, ibcontext);
2354 	}
2355 
2356 	return 0;
2357 }
2358 
2359 static inline int check_dm_type_support(struct mlx5_ib_dev *dev,
2360 					u32 type)
2361 {
2362 	switch (type) {
2363 	case MLX5_IB_UAPI_DM_TYPE_MEMIC:
2364 		if (!MLX5_CAP_DEV_MEM(dev->mdev, memic))
2365 			return -EOPNOTSUPP;
2366 		break;
2367 	case MLX5_IB_UAPI_DM_TYPE_STEERING_SW_ICM:
2368 	case MLX5_IB_UAPI_DM_TYPE_HEADER_MODIFY_SW_ICM:
2369 		if (!capable(CAP_SYS_RAWIO) ||
2370 		    !capable(CAP_NET_RAW))
2371 			return -EPERM;
2372 
2373 		if (!(MLX5_CAP_FLOWTABLE_NIC_RX(dev->mdev, sw_owner) ||
2374 		      MLX5_CAP_FLOWTABLE_NIC_TX(dev->mdev, sw_owner)))
2375 			return -EOPNOTSUPP;
2376 		break;
2377 	}
2378 
2379 	return 0;
2380 }
2381 
2382 static int handle_alloc_dm_memic(struct ib_ucontext *ctx,
2383 				 struct mlx5_ib_dm *dm,
2384 				 struct ib_dm_alloc_attr *attr,
2385 				 struct uverbs_attr_bundle *attrs)
2386 {
2387 	struct mlx5_dm *dm_db = &to_mdev(ctx->device)->dm;
2388 	u64 start_offset;
2389 	u16 page_idx;
2390 	int err;
2391 	u64 address;
2392 
2393 	dm->size = roundup(attr->length, MLX5_MEMIC_BASE_SIZE);
2394 
2395 	err = mlx5_cmd_alloc_memic(dm_db, &dm->dev_addr,
2396 				   dm->size, attr->alignment);
2397 	if (err)
2398 		return err;
2399 
2400 	address = dm->dev_addr & PAGE_MASK;
2401 	err = add_dm_mmap_entry(ctx, dm, address);
2402 	if (err)
2403 		goto err_dealloc;
2404 
2405 	page_idx = dm->mentry.rdma_entry.start_pgoff & 0xFFFF;
2406 	err = uverbs_copy_to(attrs,
2407 			     MLX5_IB_ATTR_ALLOC_DM_RESP_PAGE_INDEX,
2408 			     &page_idx,
2409 			     sizeof(page_idx));
2410 	if (err)
2411 		goto err_copy;
2412 
2413 	start_offset = dm->dev_addr & ~PAGE_MASK;
2414 	err = uverbs_copy_to(attrs,
2415 			     MLX5_IB_ATTR_ALLOC_DM_RESP_START_OFFSET,
2416 			     &start_offset, sizeof(start_offset));
2417 	if (err)
2418 		goto err_copy;
2419 
2420 	return 0;
2421 
2422 err_copy:
2423 	rdma_user_mmap_entry_remove(&dm->mentry.rdma_entry);
2424 err_dealloc:
2425 	mlx5_cmd_dealloc_memic(dm_db, dm->dev_addr, dm->size);
2426 
2427 	return err;
2428 }
2429 
2430 static int handle_alloc_dm_sw_icm(struct ib_ucontext *ctx,
2431 				  struct mlx5_ib_dm *dm,
2432 				  struct ib_dm_alloc_attr *attr,
2433 				  struct uverbs_attr_bundle *attrs,
2434 				  int type)
2435 {
2436 	struct mlx5_core_dev *dev = to_mdev(ctx->device)->mdev;
2437 	u64 act_size;
2438 	int err;
2439 
2440 	/* Allocation size must a multiple of the basic block size
2441 	 * and a power of 2.
2442 	 */
2443 	act_size = round_up(attr->length, MLX5_SW_ICM_BLOCK_SIZE(dev));
2444 	act_size = roundup_pow_of_two(act_size);
2445 
2446 	dm->size = act_size;
2447 	err = mlx5_dm_sw_icm_alloc(dev, type, act_size, attr->alignment,
2448 				   to_mucontext(ctx)->devx_uid, &dm->dev_addr,
2449 				   &dm->icm_dm.obj_id);
2450 	if (err)
2451 		return err;
2452 
2453 	err = uverbs_copy_to(attrs,
2454 			     MLX5_IB_ATTR_ALLOC_DM_RESP_START_OFFSET,
2455 			     &dm->dev_addr, sizeof(dm->dev_addr));
2456 	if (err)
2457 		mlx5_dm_sw_icm_dealloc(dev, type, dm->size,
2458 				       to_mucontext(ctx)->devx_uid, dm->dev_addr,
2459 				       dm->icm_dm.obj_id);
2460 
2461 	return err;
2462 }
2463 
2464 struct ib_dm *mlx5_ib_alloc_dm(struct ib_device *ibdev,
2465 			       struct ib_ucontext *context,
2466 			       struct ib_dm_alloc_attr *attr,
2467 			       struct uverbs_attr_bundle *attrs)
2468 {
2469 	struct mlx5_ib_dm *dm;
2470 	enum mlx5_ib_uapi_dm_type type;
2471 	int err;
2472 
2473 	err = uverbs_get_const_default(&type, attrs,
2474 				       MLX5_IB_ATTR_ALLOC_DM_REQ_TYPE,
2475 				       MLX5_IB_UAPI_DM_TYPE_MEMIC);
2476 	if (err)
2477 		return ERR_PTR(err);
2478 
2479 	mlx5_ib_dbg(to_mdev(ibdev), "alloc_dm req: dm_type=%d user_length=0x%llx log_alignment=%d\n",
2480 		    type, attr->length, attr->alignment);
2481 
2482 	err = check_dm_type_support(to_mdev(ibdev), type);
2483 	if (err)
2484 		return ERR_PTR(err);
2485 
2486 	dm = kzalloc(sizeof(*dm), GFP_KERNEL);
2487 	if (!dm)
2488 		return ERR_PTR(-ENOMEM);
2489 
2490 	dm->type = type;
2491 
2492 	switch (type) {
2493 	case MLX5_IB_UAPI_DM_TYPE_MEMIC:
2494 		err = handle_alloc_dm_memic(context, dm,
2495 					    attr,
2496 					    attrs);
2497 		break;
2498 	case MLX5_IB_UAPI_DM_TYPE_STEERING_SW_ICM:
2499 		err = handle_alloc_dm_sw_icm(context, dm,
2500 					     attr, attrs,
2501 					     MLX5_SW_ICM_TYPE_STEERING);
2502 		break;
2503 	case MLX5_IB_UAPI_DM_TYPE_HEADER_MODIFY_SW_ICM:
2504 		err = handle_alloc_dm_sw_icm(context, dm,
2505 					     attr, attrs,
2506 					     MLX5_SW_ICM_TYPE_HEADER_MODIFY);
2507 		break;
2508 	default:
2509 		err = -EOPNOTSUPP;
2510 	}
2511 
2512 	if (err)
2513 		goto err_free;
2514 
2515 	return &dm->ibdm;
2516 
2517 err_free:
2518 	kfree(dm);
2519 	return ERR_PTR(err);
2520 }
2521 
2522 int mlx5_ib_dealloc_dm(struct ib_dm *ibdm, struct uverbs_attr_bundle *attrs)
2523 {
2524 	struct mlx5_ib_ucontext *ctx = rdma_udata_to_drv_context(
2525 		&attrs->driver_udata, struct mlx5_ib_ucontext, ibucontext);
2526 	struct mlx5_core_dev *dev = to_mdev(ibdm->device)->mdev;
2527 	struct mlx5_ib_dm *dm = to_mdm(ibdm);
2528 	int ret;
2529 
2530 	switch (dm->type) {
2531 	case MLX5_IB_UAPI_DM_TYPE_MEMIC:
2532 		rdma_user_mmap_entry_remove(&dm->mentry.rdma_entry);
2533 		return 0;
2534 	case MLX5_IB_UAPI_DM_TYPE_STEERING_SW_ICM:
2535 		ret = mlx5_dm_sw_icm_dealloc(dev, MLX5_SW_ICM_TYPE_STEERING,
2536 					     dm->size, ctx->devx_uid, dm->dev_addr,
2537 					     dm->icm_dm.obj_id);
2538 		if (ret)
2539 			return ret;
2540 		break;
2541 	case MLX5_IB_UAPI_DM_TYPE_HEADER_MODIFY_SW_ICM:
2542 		ret = mlx5_dm_sw_icm_dealloc(dev, MLX5_SW_ICM_TYPE_HEADER_MODIFY,
2543 					     dm->size, ctx->devx_uid, dm->dev_addr,
2544 					     dm->icm_dm.obj_id);
2545 		if (ret)
2546 			return ret;
2547 		break;
2548 	default:
2549 		return -EOPNOTSUPP;
2550 	}
2551 
2552 	kfree(dm);
2553 
2554 	return 0;
2555 }
2556 
2557 static int mlx5_ib_alloc_pd(struct ib_pd *ibpd, struct ib_udata *udata)
2558 {
2559 	struct mlx5_ib_pd *pd = to_mpd(ibpd);
2560 	struct ib_device *ibdev = ibpd->device;
2561 	struct mlx5_ib_alloc_pd_resp resp;
2562 	int err;
2563 	u32 out[MLX5_ST_SZ_DW(alloc_pd_out)] = {};
2564 	u32 in[MLX5_ST_SZ_DW(alloc_pd_in)]   = {};
2565 	u16 uid = 0;
2566 	struct mlx5_ib_ucontext *context = rdma_udata_to_drv_context(
2567 		udata, struct mlx5_ib_ucontext, ibucontext);
2568 
2569 	uid = context ? context->devx_uid : 0;
2570 	MLX5_SET(alloc_pd_in, in, opcode, MLX5_CMD_OP_ALLOC_PD);
2571 	MLX5_SET(alloc_pd_in, in, uid, uid);
2572 	err = mlx5_cmd_exec(to_mdev(ibdev)->mdev, in, sizeof(in),
2573 			    out, sizeof(out));
2574 	if (err)
2575 		return err;
2576 
2577 	pd->pdn = MLX5_GET(alloc_pd_out, out, pd);
2578 	pd->uid = uid;
2579 	if (udata) {
2580 		resp.pdn = pd->pdn;
2581 		if (ib_copy_to_udata(udata, &resp, sizeof(resp))) {
2582 			mlx5_cmd_dealloc_pd(to_mdev(ibdev)->mdev, pd->pdn, uid);
2583 			return -EFAULT;
2584 		}
2585 	}
2586 
2587 	return 0;
2588 }
2589 
2590 static void mlx5_ib_dealloc_pd(struct ib_pd *pd, struct ib_udata *udata)
2591 {
2592 	struct mlx5_ib_dev *mdev = to_mdev(pd->device);
2593 	struct mlx5_ib_pd *mpd = to_mpd(pd);
2594 
2595 	mlx5_cmd_dealloc_pd(mdev->mdev, mpd->pdn, mpd->uid);
2596 }
2597 
2598 enum {
2599 	MATCH_CRITERIA_ENABLE_OUTER_BIT,
2600 	MATCH_CRITERIA_ENABLE_MISC_BIT,
2601 	MATCH_CRITERIA_ENABLE_INNER_BIT,
2602 	MATCH_CRITERIA_ENABLE_MISC2_BIT
2603 };
2604 
2605 #define HEADER_IS_ZERO(match_criteria, headers)			           \
2606 	!(memchr_inv(MLX5_ADDR_OF(fte_match_param, match_criteria, headers), \
2607 		    0, MLX5_FLD_SZ_BYTES(fte_match_param, headers)))       \
2608 
2609 static u8 get_match_criteria_enable(u32 *match_criteria)
2610 {
2611 	u8 match_criteria_enable;
2612 
2613 	match_criteria_enable =
2614 		(!HEADER_IS_ZERO(match_criteria, outer_headers)) <<
2615 		MATCH_CRITERIA_ENABLE_OUTER_BIT;
2616 	match_criteria_enable |=
2617 		(!HEADER_IS_ZERO(match_criteria, misc_parameters)) <<
2618 		MATCH_CRITERIA_ENABLE_MISC_BIT;
2619 	match_criteria_enable |=
2620 		(!HEADER_IS_ZERO(match_criteria, inner_headers)) <<
2621 		MATCH_CRITERIA_ENABLE_INNER_BIT;
2622 	match_criteria_enable |=
2623 		(!HEADER_IS_ZERO(match_criteria, misc_parameters_2)) <<
2624 		MATCH_CRITERIA_ENABLE_MISC2_BIT;
2625 
2626 	return match_criteria_enable;
2627 }
2628 
2629 static int set_proto(void *outer_c, void *outer_v, u8 mask, u8 val)
2630 {
2631 	u8 entry_mask;
2632 	u8 entry_val;
2633 	int err = 0;
2634 
2635 	if (!mask)
2636 		goto out;
2637 
2638 	entry_mask = MLX5_GET(fte_match_set_lyr_2_4, outer_c,
2639 			      ip_protocol);
2640 	entry_val = MLX5_GET(fte_match_set_lyr_2_4, outer_v,
2641 			     ip_protocol);
2642 	if (!entry_mask) {
2643 		MLX5_SET(fte_match_set_lyr_2_4, outer_c, ip_protocol, mask);
2644 		MLX5_SET(fte_match_set_lyr_2_4, outer_v, ip_protocol, val);
2645 		goto out;
2646 	}
2647 	/* Don't override existing ip protocol */
2648 	if (mask != entry_mask || val != entry_val)
2649 		err = -EINVAL;
2650 out:
2651 	return err;
2652 }
2653 
2654 static void set_flow_label(void *misc_c, void *misc_v, u32 mask, u32 val,
2655 			   bool inner)
2656 {
2657 	if (inner) {
2658 		MLX5_SET(fte_match_set_misc,
2659 			 misc_c, inner_ipv6_flow_label, mask);
2660 		MLX5_SET(fte_match_set_misc,
2661 			 misc_v, inner_ipv6_flow_label, val);
2662 	} else {
2663 		MLX5_SET(fte_match_set_misc,
2664 			 misc_c, outer_ipv6_flow_label, mask);
2665 		MLX5_SET(fte_match_set_misc,
2666 			 misc_v, outer_ipv6_flow_label, val);
2667 	}
2668 }
2669 
2670 static void set_tos(void *outer_c, void *outer_v, u8 mask, u8 val)
2671 {
2672 	MLX5_SET(fte_match_set_lyr_2_4, outer_c, ip_ecn, mask);
2673 	MLX5_SET(fte_match_set_lyr_2_4, outer_v, ip_ecn, val);
2674 	MLX5_SET(fte_match_set_lyr_2_4, outer_c, ip_dscp, mask >> 2);
2675 	MLX5_SET(fte_match_set_lyr_2_4, outer_v, ip_dscp, val >> 2);
2676 }
2677 
2678 static int check_mpls_supp_fields(u32 field_support, const __be32 *set_mask)
2679 {
2680 	if (MLX5_GET(fte_match_mpls, set_mask, mpls_label) &&
2681 	    !(field_support & MLX5_FIELD_SUPPORT_MPLS_LABEL))
2682 		return -EOPNOTSUPP;
2683 
2684 	if (MLX5_GET(fte_match_mpls, set_mask, mpls_exp) &&
2685 	    !(field_support & MLX5_FIELD_SUPPORT_MPLS_EXP))
2686 		return -EOPNOTSUPP;
2687 
2688 	if (MLX5_GET(fte_match_mpls, set_mask, mpls_s_bos) &&
2689 	    !(field_support & MLX5_FIELD_SUPPORT_MPLS_S_BOS))
2690 		return -EOPNOTSUPP;
2691 
2692 	if (MLX5_GET(fte_match_mpls, set_mask, mpls_ttl) &&
2693 	    !(field_support & MLX5_FIELD_SUPPORT_MPLS_TTL))
2694 		return -EOPNOTSUPP;
2695 
2696 	return 0;
2697 }
2698 
2699 #define LAST_ETH_FIELD vlan_tag
2700 #define LAST_IB_FIELD sl
2701 #define LAST_IPV4_FIELD tos
2702 #define LAST_IPV6_FIELD traffic_class
2703 #define LAST_TCP_UDP_FIELD src_port
2704 #define LAST_TUNNEL_FIELD tunnel_id
2705 #define LAST_FLOW_TAG_FIELD tag_id
2706 #define LAST_DROP_FIELD size
2707 #define LAST_COUNTERS_FIELD counters
2708 
2709 /* Field is the last supported field */
2710 #define FIELDS_NOT_SUPPORTED(filter, field)\
2711 	memchr_inv((void *)&filter.field  +\
2712 		   sizeof(filter.field), 0,\
2713 		   sizeof(filter) -\
2714 		   offsetof(typeof(filter), field) -\
2715 		   sizeof(filter.field))
2716 
2717 int parse_flow_flow_action(struct mlx5_ib_flow_action *maction,
2718 			   bool is_egress,
2719 			   struct mlx5_flow_act *action)
2720 {
2721 
2722 	switch (maction->ib_action.type) {
2723 	case IB_FLOW_ACTION_ESP:
2724 		if (action->action & (MLX5_FLOW_CONTEXT_ACTION_ENCRYPT |
2725 				      MLX5_FLOW_CONTEXT_ACTION_DECRYPT))
2726 			return -EINVAL;
2727 		/* Currently only AES_GCM keymat is supported by the driver */
2728 		action->esp_id = (uintptr_t)maction->esp_aes_gcm.ctx;
2729 		action->action |= is_egress ?
2730 			MLX5_FLOW_CONTEXT_ACTION_ENCRYPT :
2731 			MLX5_FLOW_CONTEXT_ACTION_DECRYPT;
2732 		return 0;
2733 	case IB_FLOW_ACTION_UNSPECIFIED:
2734 		if (maction->flow_action_raw.sub_type ==
2735 		    MLX5_IB_FLOW_ACTION_MODIFY_HEADER) {
2736 			if (action->action & MLX5_FLOW_CONTEXT_ACTION_MOD_HDR)
2737 				return -EINVAL;
2738 			action->action |= MLX5_FLOW_CONTEXT_ACTION_MOD_HDR;
2739 			action->modify_hdr =
2740 				maction->flow_action_raw.modify_hdr;
2741 			return 0;
2742 		}
2743 		if (maction->flow_action_raw.sub_type ==
2744 		    MLX5_IB_FLOW_ACTION_DECAP) {
2745 			if (action->action & MLX5_FLOW_CONTEXT_ACTION_DECAP)
2746 				return -EINVAL;
2747 			action->action |= MLX5_FLOW_CONTEXT_ACTION_DECAP;
2748 			return 0;
2749 		}
2750 		if (maction->flow_action_raw.sub_type ==
2751 		    MLX5_IB_FLOW_ACTION_PACKET_REFORMAT) {
2752 			if (action->action &
2753 			    MLX5_FLOW_CONTEXT_ACTION_PACKET_REFORMAT)
2754 				return -EINVAL;
2755 			action->action |=
2756 				MLX5_FLOW_CONTEXT_ACTION_PACKET_REFORMAT;
2757 			action->pkt_reformat =
2758 				maction->flow_action_raw.pkt_reformat;
2759 			return 0;
2760 		}
2761 		/* fall through */
2762 	default:
2763 		return -EOPNOTSUPP;
2764 	}
2765 }
2766 
2767 static int parse_flow_attr(struct mlx5_core_dev *mdev,
2768 			   struct mlx5_flow_spec *spec,
2769 			   const union ib_flow_spec *ib_spec,
2770 			   const struct ib_flow_attr *flow_attr,
2771 			   struct mlx5_flow_act *action, u32 prev_type)
2772 {
2773 	struct mlx5_flow_context *flow_context = &spec->flow_context;
2774 	u32 *match_c = spec->match_criteria;
2775 	u32 *match_v = spec->match_value;
2776 	void *misc_params_c = MLX5_ADDR_OF(fte_match_param, match_c,
2777 					   misc_parameters);
2778 	void *misc_params_v = MLX5_ADDR_OF(fte_match_param, match_v,
2779 					   misc_parameters);
2780 	void *misc_params2_c = MLX5_ADDR_OF(fte_match_param, match_c,
2781 					    misc_parameters_2);
2782 	void *misc_params2_v = MLX5_ADDR_OF(fte_match_param, match_v,
2783 					    misc_parameters_2);
2784 	void *headers_c;
2785 	void *headers_v;
2786 	int match_ipv;
2787 	int ret;
2788 
2789 	if (ib_spec->type & IB_FLOW_SPEC_INNER) {
2790 		headers_c = MLX5_ADDR_OF(fte_match_param, match_c,
2791 					 inner_headers);
2792 		headers_v = MLX5_ADDR_OF(fte_match_param, match_v,
2793 					 inner_headers);
2794 		match_ipv = MLX5_CAP_FLOWTABLE_NIC_RX(mdev,
2795 					ft_field_support.inner_ip_version);
2796 	} else {
2797 		headers_c = MLX5_ADDR_OF(fte_match_param, match_c,
2798 					 outer_headers);
2799 		headers_v = MLX5_ADDR_OF(fte_match_param, match_v,
2800 					 outer_headers);
2801 		match_ipv = MLX5_CAP_FLOWTABLE_NIC_RX(mdev,
2802 					ft_field_support.outer_ip_version);
2803 	}
2804 
2805 	switch (ib_spec->type & ~IB_FLOW_SPEC_INNER) {
2806 	case IB_FLOW_SPEC_ETH:
2807 		if (FIELDS_NOT_SUPPORTED(ib_spec->eth.mask, LAST_ETH_FIELD))
2808 			return -EOPNOTSUPP;
2809 
2810 		ether_addr_copy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, headers_c,
2811 					     dmac_47_16),
2812 				ib_spec->eth.mask.dst_mac);
2813 		ether_addr_copy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, headers_v,
2814 					     dmac_47_16),
2815 				ib_spec->eth.val.dst_mac);
2816 
2817 		ether_addr_copy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, headers_c,
2818 					     smac_47_16),
2819 				ib_spec->eth.mask.src_mac);
2820 		ether_addr_copy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, headers_v,
2821 					     smac_47_16),
2822 				ib_spec->eth.val.src_mac);
2823 
2824 		if (ib_spec->eth.mask.vlan_tag) {
2825 			MLX5_SET(fte_match_set_lyr_2_4, headers_c,
2826 				 cvlan_tag, 1);
2827 			MLX5_SET(fte_match_set_lyr_2_4, headers_v,
2828 				 cvlan_tag, 1);
2829 
2830 			MLX5_SET(fte_match_set_lyr_2_4, headers_c,
2831 				 first_vid, ntohs(ib_spec->eth.mask.vlan_tag));
2832 			MLX5_SET(fte_match_set_lyr_2_4, headers_v,
2833 				 first_vid, ntohs(ib_spec->eth.val.vlan_tag));
2834 
2835 			MLX5_SET(fte_match_set_lyr_2_4, headers_c,
2836 				 first_cfi,
2837 				 ntohs(ib_spec->eth.mask.vlan_tag) >> 12);
2838 			MLX5_SET(fte_match_set_lyr_2_4, headers_v,
2839 				 first_cfi,
2840 				 ntohs(ib_spec->eth.val.vlan_tag) >> 12);
2841 
2842 			MLX5_SET(fte_match_set_lyr_2_4, headers_c,
2843 				 first_prio,
2844 				 ntohs(ib_spec->eth.mask.vlan_tag) >> 13);
2845 			MLX5_SET(fte_match_set_lyr_2_4, headers_v,
2846 				 first_prio,
2847 				 ntohs(ib_spec->eth.val.vlan_tag) >> 13);
2848 		}
2849 		MLX5_SET(fte_match_set_lyr_2_4, headers_c,
2850 			 ethertype, ntohs(ib_spec->eth.mask.ether_type));
2851 		MLX5_SET(fte_match_set_lyr_2_4, headers_v,
2852 			 ethertype, ntohs(ib_spec->eth.val.ether_type));
2853 		break;
2854 	case IB_FLOW_SPEC_IPV4:
2855 		if (FIELDS_NOT_SUPPORTED(ib_spec->ipv4.mask, LAST_IPV4_FIELD))
2856 			return -EOPNOTSUPP;
2857 
2858 		if (match_ipv) {
2859 			MLX5_SET(fte_match_set_lyr_2_4, headers_c,
2860 				 ip_version, 0xf);
2861 			MLX5_SET(fte_match_set_lyr_2_4, headers_v,
2862 				 ip_version, MLX5_FS_IPV4_VERSION);
2863 		} else {
2864 			MLX5_SET(fte_match_set_lyr_2_4, headers_c,
2865 				 ethertype, 0xffff);
2866 			MLX5_SET(fte_match_set_lyr_2_4, headers_v,
2867 				 ethertype, ETH_P_IP);
2868 		}
2869 
2870 		memcpy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, headers_c,
2871 				    src_ipv4_src_ipv6.ipv4_layout.ipv4),
2872 		       &ib_spec->ipv4.mask.src_ip,
2873 		       sizeof(ib_spec->ipv4.mask.src_ip));
2874 		memcpy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, headers_v,
2875 				    src_ipv4_src_ipv6.ipv4_layout.ipv4),
2876 		       &ib_spec->ipv4.val.src_ip,
2877 		       sizeof(ib_spec->ipv4.val.src_ip));
2878 		memcpy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, headers_c,
2879 				    dst_ipv4_dst_ipv6.ipv4_layout.ipv4),
2880 		       &ib_spec->ipv4.mask.dst_ip,
2881 		       sizeof(ib_spec->ipv4.mask.dst_ip));
2882 		memcpy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, headers_v,
2883 				    dst_ipv4_dst_ipv6.ipv4_layout.ipv4),
2884 		       &ib_spec->ipv4.val.dst_ip,
2885 		       sizeof(ib_spec->ipv4.val.dst_ip));
2886 
2887 		set_tos(headers_c, headers_v,
2888 			ib_spec->ipv4.mask.tos, ib_spec->ipv4.val.tos);
2889 
2890 		if (set_proto(headers_c, headers_v,
2891 			      ib_spec->ipv4.mask.proto,
2892 			      ib_spec->ipv4.val.proto))
2893 			return -EINVAL;
2894 		break;
2895 	case IB_FLOW_SPEC_IPV6:
2896 		if (FIELDS_NOT_SUPPORTED(ib_spec->ipv6.mask, LAST_IPV6_FIELD))
2897 			return -EOPNOTSUPP;
2898 
2899 		if (match_ipv) {
2900 			MLX5_SET(fte_match_set_lyr_2_4, headers_c,
2901 				 ip_version, 0xf);
2902 			MLX5_SET(fte_match_set_lyr_2_4, headers_v,
2903 				 ip_version, MLX5_FS_IPV6_VERSION);
2904 		} else {
2905 			MLX5_SET(fte_match_set_lyr_2_4, headers_c,
2906 				 ethertype, 0xffff);
2907 			MLX5_SET(fte_match_set_lyr_2_4, headers_v,
2908 				 ethertype, ETH_P_IPV6);
2909 		}
2910 
2911 		memcpy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, headers_c,
2912 				    src_ipv4_src_ipv6.ipv6_layout.ipv6),
2913 		       &ib_spec->ipv6.mask.src_ip,
2914 		       sizeof(ib_spec->ipv6.mask.src_ip));
2915 		memcpy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, headers_v,
2916 				    src_ipv4_src_ipv6.ipv6_layout.ipv6),
2917 		       &ib_spec->ipv6.val.src_ip,
2918 		       sizeof(ib_spec->ipv6.val.src_ip));
2919 		memcpy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, headers_c,
2920 				    dst_ipv4_dst_ipv6.ipv6_layout.ipv6),
2921 		       &ib_spec->ipv6.mask.dst_ip,
2922 		       sizeof(ib_spec->ipv6.mask.dst_ip));
2923 		memcpy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, headers_v,
2924 				    dst_ipv4_dst_ipv6.ipv6_layout.ipv6),
2925 		       &ib_spec->ipv6.val.dst_ip,
2926 		       sizeof(ib_spec->ipv6.val.dst_ip));
2927 
2928 		set_tos(headers_c, headers_v,
2929 			ib_spec->ipv6.mask.traffic_class,
2930 			ib_spec->ipv6.val.traffic_class);
2931 
2932 		if (set_proto(headers_c, headers_v,
2933 			      ib_spec->ipv6.mask.next_hdr,
2934 			      ib_spec->ipv6.val.next_hdr))
2935 			return -EINVAL;
2936 
2937 		set_flow_label(misc_params_c, misc_params_v,
2938 			       ntohl(ib_spec->ipv6.mask.flow_label),
2939 			       ntohl(ib_spec->ipv6.val.flow_label),
2940 			       ib_spec->type & IB_FLOW_SPEC_INNER);
2941 		break;
2942 	case IB_FLOW_SPEC_ESP:
2943 		if (ib_spec->esp.mask.seq)
2944 			return -EOPNOTSUPP;
2945 
2946 		MLX5_SET(fte_match_set_misc, misc_params_c, outer_esp_spi,
2947 			 ntohl(ib_spec->esp.mask.spi));
2948 		MLX5_SET(fte_match_set_misc, misc_params_v, outer_esp_spi,
2949 			 ntohl(ib_spec->esp.val.spi));
2950 		break;
2951 	case IB_FLOW_SPEC_TCP:
2952 		if (FIELDS_NOT_SUPPORTED(ib_spec->tcp_udp.mask,
2953 					 LAST_TCP_UDP_FIELD))
2954 			return -EOPNOTSUPP;
2955 
2956 		if (set_proto(headers_c, headers_v, 0xff, IPPROTO_TCP))
2957 			return -EINVAL;
2958 
2959 		MLX5_SET(fte_match_set_lyr_2_4, headers_c, tcp_sport,
2960 			 ntohs(ib_spec->tcp_udp.mask.src_port));
2961 		MLX5_SET(fte_match_set_lyr_2_4, headers_v, tcp_sport,
2962 			 ntohs(ib_spec->tcp_udp.val.src_port));
2963 
2964 		MLX5_SET(fte_match_set_lyr_2_4, headers_c, tcp_dport,
2965 			 ntohs(ib_spec->tcp_udp.mask.dst_port));
2966 		MLX5_SET(fte_match_set_lyr_2_4, headers_v, tcp_dport,
2967 			 ntohs(ib_spec->tcp_udp.val.dst_port));
2968 		break;
2969 	case IB_FLOW_SPEC_UDP:
2970 		if (FIELDS_NOT_SUPPORTED(ib_spec->tcp_udp.mask,
2971 					 LAST_TCP_UDP_FIELD))
2972 			return -EOPNOTSUPP;
2973 
2974 		if (set_proto(headers_c, headers_v, 0xff, IPPROTO_UDP))
2975 			return -EINVAL;
2976 
2977 		MLX5_SET(fte_match_set_lyr_2_4, headers_c, udp_sport,
2978 			 ntohs(ib_spec->tcp_udp.mask.src_port));
2979 		MLX5_SET(fte_match_set_lyr_2_4, headers_v, udp_sport,
2980 			 ntohs(ib_spec->tcp_udp.val.src_port));
2981 
2982 		MLX5_SET(fte_match_set_lyr_2_4, headers_c, udp_dport,
2983 			 ntohs(ib_spec->tcp_udp.mask.dst_port));
2984 		MLX5_SET(fte_match_set_lyr_2_4, headers_v, udp_dport,
2985 			 ntohs(ib_spec->tcp_udp.val.dst_port));
2986 		break;
2987 	case IB_FLOW_SPEC_GRE:
2988 		if (ib_spec->gre.mask.c_ks_res0_ver)
2989 			return -EOPNOTSUPP;
2990 
2991 		if (set_proto(headers_c, headers_v, 0xff, IPPROTO_GRE))
2992 			return -EINVAL;
2993 
2994 		MLX5_SET(fte_match_set_lyr_2_4, headers_c, ip_protocol,
2995 			 0xff);
2996 		MLX5_SET(fte_match_set_lyr_2_4, headers_v, ip_protocol,
2997 			 IPPROTO_GRE);
2998 
2999 		MLX5_SET(fte_match_set_misc, misc_params_c, gre_protocol,
3000 			 ntohs(ib_spec->gre.mask.protocol));
3001 		MLX5_SET(fte_match_set_misc, misc_params_v, gre_protocol,
3002 			 ntohs(ib_spec->gre.val.protocol));
3003 
3004 		memcpy(MLX5_ADDR_OF(fte_match_set_misc, misc_params_c,
3005 				    gre_key.nvgre.hi),
3006 		       &ib_spec->gre.mask.key,
3007 		       sizeof(ib_spec->gre.mask.key));
3008 		memcpy(MLX5_ADDR_OF(fte_match_set_misc, misc_params_v,
3009 				    gre_key.nvgre.hi),
3010 		       &ib_spec->gre.val.key,
3011 		       sizeof(ib_spec->gre.val.key));
3012 		break;
3013 	case IB_FLOW_SPEC_MPLS:
3014 		switch (prev_type) {
3015 		case IB_FLOW_SPEC_UDP:
3016 			if (check_mpls_supp_fields(MLX5_CAP_FLOWTABLE_NIC_RX(mdev,
3017 						   ft_field_support.outer_first_mpls_over_udp),
3018 						   &ib_spec->mpls.mask.tag))
3019 				return -EOPNOTSUPP;
3020 
3021 			memcpy(MLX5_ADDR_OF(fte_match_set_misc2, misc_params2_v,
3022 					    outer_first_mpls_over_udp),
3023 			       &ib_spec->mpls.val.tag,
3024 			       sizeof(ib_spec->mpls.val.tag));
3025 			memcpy(MLX5_ADDR_OF(fte_match_set_misc2, misc_params2_c,
3026 					    outer_first_mpls_over_udp),
3027 			       &ib_spec->mpls.mask.tag,
3028 			       sizeof(ib_spec->mpls.mask.tag));
3029 			break;
3030 		case IB_FLOW_SPEC_GRE:
3031 			if (check_mpls_supp_fields(MLX5_CAP_FLOWTABLE_NIC_RX(mdev,
3032 						   ft_field_support.outer_first_mpls_over_gre),
3033 						   &ib_spec->mpls.mask.tag))
3034 				return -EOPNOTSUPP;
3035 
3036 			memcpy(MLX5_ADDR_OF(fte_match_set_misc2, misc_params2_v,
3037 					    outer_first_mpls_over_gre),
3038 			       &ib_spec->mpls.val.tag,
3039 			       sizeof(ib_spec->mpls.val.tag));
3040 			memcpy(MLX5_ADDR_OF(fte_match_set_misc2, misc_params2_c,
3041 					    outer_first_mpls_over_gre),
3042 			       &ib_spec->mpls.mask.tag,
3043 			       sizeof(ib_spec->mpls.mask.tag));
3044 			break;
3045 		default:
3046 			if (ib_spec->type & IB_FLOW_SPEC_INNER) {
3047 				if (check_mpls_supp_fields(MLX5_CAP_FLOWTABLE_NIC_RX(mdev,
3048 							   ft_field_support.inner_first_mpls),
3049 							   &ib_spec->mpls.mask.tag))
3050 					return -EOPNOTSUPP;
3051 
3052 				memcpy(MLX5_ADDR_OF(fte_match_set_misc2, misc_params2_v,
3053 						    inner_first_mpls),
3054 				       &ib_spec->mpls.val.tag,
3055 				       sizeof(ib_spec->mpls.val.tag));
3056 				memcpy(MLX5_ADDR_OF(fte_match_set_misc2, misc_params2_c,
3057 						    inner_first_mpls),
3058 				       &ib_spec->mpls.mask.tag,
3059 				       sizeof(ib_spec->mpls.mask.tag));
3060 			} else {
3061 				if (check_mpls_supp_fields(MLX5_CAP_FLOWTABLE_NIC_RX(mdev,
3062 							   ft_field_support.outer_first_mpls),
3063 							   &ib_spec->mpls.mask.tag))
3064 					return -EOPNOTSUPP;
3065 
3066 				memcpy(MLX5_ADDR_OF(fte_match_set_misc2, misc_params2_v,
3067 						    outer_first_mpls),
3068 				       &ib_spec->mpls.val.tag,
3069 				       sizeof(ib_spec->mpls.val.tag));
3070 				memcpy(MLX5_ADDR_OF(fte_match_set_misc2, misc_params2_c,
3071 						    outer_first_mpls),
3072 				       &ib_spec->mpls.mask.tag,
3073 				       sizeof(ib_spec->mpls.mask.tag));
3074 			}
3075 		}
3076 		break;
3077 	case IB_FLOW_SPEC_VXLAN_TUNNEL:
3078 		if (FIELDS_NOT_SUPPORTED(ib_spec->tunnel.mask,
3079 					 LAST_TUNNEL_FIELD))
3080 			return -EOPNOTSUPP;
3081 
3082 		MLX5_SET(fte_match_set_misc, misc_params_c, vxlan_vni,
3083 			 ntohl(ib_spec->tunnel.mask.tunnel_id));
3084 		MLX5_SET(fte_match_set_misc, misc_params_v, vxlan_vni,
3085 			 ntohl(ib_spec->tunnel.val.tunnel_id));
3086 		break;
3087 	case IB_FLOW_SPEC_ACTION_TAG:
3088 		if (FIELDS_NOT_SUPPORTED(ib_spec->flow_tag,
3089 					 LAST_FLOW_TAG_FIELD))
3090 			return -EOPNOTSUPP;
3091 		if (ib_spec->flow_tag.tag_id >= BIT(24))
3092 			return -EINVAL;
3093 
3094 		flow_context->flow_tag = ib_spec->flow_tag.tag_id;
3095 		flow_context->flags |= FLOW_CONTEXT_HAS_TAG;
3096 		break;
3097 	case IB_FLOW_SPEC_ACTION_DROP:
3098 		if (FIELDS_NOT_SUPPORTED(ib_spec->drop,
3099 					 LAST_DROP_FIELD))
3100 			return -EOPNOTSUPP;
3101 		action->action |= MLX5_FLOW_CONTEXT_ACTION_DROP;
3102 		break;
3103 	case IB_FLOW_SPEC_ACTION_HANDLE:
3104 		ret = parse_flow_flow_action(to_mflow_act(ib_spec->action.act),
3105 			flow_attr->flags & IB_FLOW_ATTR_FLAGS_EGRESS, action);
3106 		if (ret)
3107 			return ret;
3108 		break;
3109 	case IB_FLOW_SPEC_ACTION_COUNT:
3110 		if (FIELDS_NOT_SUPPORTED(ib_spec->flow_count,
3111 					 LAST_COUNTERS_FIELD))
3112 			return -EOPNOTSUPP;
3113 
3114 		/* for now support only one counters spec per flow */
3115 		if (action->action & MLX5_FLOW_CONTEXT_ACTION_COUNT)
3116 			return -EINVAL;
3117 
3118 		action->counters = ib_spec->flow_count.counters;
3119 		action->action |= MLX5_FLOW_CONTEXT_ACTION_COUNT;
3120 		break;
3121 	default:
3122 		return -EINVAL;
3123 	}
3124 
3125 	return 0;
3126 }
3127 
3128 /* If a flow could catch both multicast and unicast packets,
3129  * it won't fall into the multicast flow steering table and this rule
3130  * could steal other multicast packets.
3131  */
3132 static bool flow_is_multicast_only(const struct ib_flow_attr *ib_attr)
3133 {
3134 	union ib_flow_spec *flow_spec;
3135 
3136 	if (ib_attr->type != IB_FLOW_ATTR_NORMAL ||
3137 	    ib_attr->num_of_specs < 1)
3138 		return false;
3139 
3140 	flow_spec = (union ib_flow_spec *)(ib_attr + 1);
3141 	if (flow_spec->type == IB_FLOW_SPEC_IPV4) {
3142 		struct ib_flow_spec_ipv4 *ipv4_spec;
3143 
3144 		ipv4_spec = (struct ib_flow_spec_ipv4 *)flow_spec;
3145 		if (ipv4_is_multicast(ipv4_spec->val.dst_ip))
3146 			return true;
3147 
3148 		return false;
3149 	}
3150 
3151 	if (flow_spec->type == IB_FLOW_SPEC_ETH) {
3152 		struct ib_flow_spec_eth *eth_spec;
3153 
3154 		eth_spec = (struct ib_flow_spec_eth *)flow_spec;
3155 		return is_multicast_ether_addr(eth_spec->mask.dst_mac) &&
3156 		       is_multicast_ether_addr(eth_spec->val.dst_mac);
3157 	}
3158 
3159 	return false;
3160 }
3161 
3162 enum valid_spec {
3163 	VALID_SPEC_INVALID,
3164 	VALID_SPEC_VALID,
3165 	VALID_SPEC_NA,
3166 };
3167 
3168 static enum valid_spec
3169 is_valid_esp_aes_gcm(struct mlx5_core_dev *mdev,
3170 		     const struct mlx5_flow_spec *spec,
3171 		     const struct mlx5_flow_act *flow_act,
3172 		     bool egress)
3173 {
3174 	const u32 *match_c = spec->match_criteria;
3175 	bool is_crypto =
3176 		(flow_act->action & (MLX5_FLOW_CONTEXT_ACTION_ENCRYPT |
3177 				     MLX5_FLOW_CONTEXT_ACTION_DECRYPT));
3178 	bool is_ipsec = mlx5_fs_is_ipsec_flow(match_c);
3179 	bool is_drop = flow_act->action & MLX5_FLOW_CONTEXT_ACTION_DROP;
3180 
3181 	/*
3182 	 * Currently only crypto is supported in egress, when regular egress
3183 	 * rules would be supported, always return VALID_SPEC_NA.
3184 	 */
3185 	if (!is_crypto)
3186 		return VALID_SPEC_NA;
3187 
3188 	return is_crypto && is_ipsec &&
3189 		(!egress || (!is_drop &&
3190 			     !(spec->flow_context.flags & FLOW_CONTEXT_HAS_TAG))) ?
3191 		VALID_SPEC_VALID : VALID_SPEC_INVALID;
3192 }
3193 
3194 static bool is_valid_spec(struct mlx5_core_dev *mdev,
3195 			  const struct mlx5_flow_spec *spec,
3196 			  const struct mlx5_flow_act *flow_act,
3197 			  bool egress)
3198 {
3199 	/* We curretly only support ipsec egress flow */
3200 	return is_valid_esp_aes_gcm(mdev, spec, flow_act, egress) != VALID_SPEC_INVALID;
3201 }
3202 
3203 static bool is_valid_ethertype(struct mlx5_core_dev *mdev,
3204 			       const struct ib_flow_attr *flow_attr,
3205 			       bool check_inner)
3206 {
3207 	union ib_flow_spec *ib_spec = (union ib_flow_spec *)(flow_attr + 1);
3208 	int match_ipv = check_inner ?
3209 			MLX5_CAP_FLOWTABLE_NIC_RX(mdev,
3210 					ft_field_support.inner_ip_version) :
3211 			MLX5_CAP_FLOWTABLE_NIC_RX(mdev,
3212 					ft_field_support.outer_ip_version);
3213 	int inner_bit = check_inner ? IB_FLOW_SPEC_INNER : 0;
3214 	bool ipv4_spec_valid, ipv6_spec_valid;
3215 	unsigned int ip_spec_type = 0;
3216 	bool has_ethertype = false;
3217 	unsigned int spec_index;
3218 	bool mask_valid = true;
3219 	u16 eth_type = 0;
3220 	bool type_valid;
3221 
3222 	/* Validate that ethertype is correct */
3223 	for (spec_index = 0; spec_index < flow_attr->num_of_specs; spec_index++) {
3224 		if ((ib_spec->type == (IB_FLOW_SPEC_ETH | inner_bit)) &&
3225 		    ib_spec->eth.mask.ether_type) {
3226 			mask_valid = (ib_spec->eth.mask.ether_type ==
3227 				      htons(0xffff));
3228 			has_ethertype = true;
3229 			eth_type = ntohs(ib_spec->eth.val.ether_type);
3230 		} else if ((ib_spec->type == (IB_FLOW_SPEC_IPV4 | inner_bit)) ||
3231 			   (ib_spec->type == (IB_FLOW_SPEC_IPV6 | inner_bit))) {
3232 			ip_spec_type = ib_spec->type;
3233 		}
3234 		ib_spec = (void *)ib_spec + ib_spec->size;
3235 	}
3236 
3237 	type_valid = (!has_ethertype) || (!ip_spec_type);
3238 	if (!type_valid && mask_valid) {
3239 		ipv4_spec_valid = (eth_type == ETH_P_IP) &&
3240 			(ip_spec_type == (IB_FLOW_SPEC_IPV4 | inner_bit));
3241 		ipv6_spec_valid = (eth_type == ETH_P_IPV6) &&
3242 			(ip_spec_type == (IB_FLOW_SPEC_IPV6 | inner_bit));
3243 
3244 		type_valid = (ipv4_spec_valid) || (ipv6_spec_valid) ||
3245 			     (((eth_type == ETH_P_MPLS_UC) ||
3246 			       (eth_type == ETH_P_MPLS_MC)) && match_ipv);
3247 	}
3248 
3249 	return type_valid;
3250 }
3251 
3252 static bool is_valid_attr(struct mlx5_core_dev *mdev,
3253 			  const struct ib_flow_attr *flow_attr)
3254 {
3255 	return is_valid_ethertype(mdev, flow_attr, false) &&
3256 	       is_valid_ethertype(mdev, flow_attr, true);
3257 }
3258 
3259 static void put_flow_table(struct mlx5_ib_dev *dev,
3260 			   struct mlx5_ib_flow_prio *prio, bool ft_added)
3261 {
3262 	prio->refcount -= !!ft_added;
3263 	if (!prio->refcount) {
3264 		mlx5_destroy_flow_table(prio->flow_table);
3265 		prio->flow_table = NULL;
3266 	}
3267 }
3268 
3269 static void counters_clear_description(struct ib_counters *counters)
3270 {
3271 	struct mlx5_ib_mcounters *mcounters = to_mcounters(counters);
3272 
3273 	mutex_lock(&mcounters->mcntrs_mutex);
3274 	kfree(mcounters->counters_data);
3275 	mcounters->counters_data = NULL;
3276 	mcounters->cntrs_max_index = 0;
3277 	mutex_unlock(&mcounters->mcntrs_mutex);
3278 }
3279 
3280 static int mlx5_ib_destroy_flow(struct ib_flow *flow_id)
3281 {
3282 	struct mlx5_ib_flow_handler *handler = container_of(flow_id,
3283 							  struct mlx5_ib_flow_handler,
3284 							  ibflow);
3285 	struct mlx5_ib_flow_handler *iter, *tmp;
3286 	struct mlx5_ib_dev *dev = handler->dev;
3287 
3288 	mutex_lock(&dev->flow_db->lock);
3289 
3290 	list_for_each_entry_safe(iter, tmp, &handler->list, list) {
3291 		mlx5_del_flow_rules(iter->rule);
3292 		put_flow_table(dev, iter->prio, true);
3293 		list_del(&iter->list);
3294 		kfree(iter);
3295 	}
3296 
3297 	mlx5_del_flow_rules(handler->rule);
3298 	put_flow_table(dev, handler->prio, true);
3299 	if (handler->ibcounters &&
3300 	    atomic_read(&handler->ibcounters->usecnt) == 1)
3301 		counters_clear_description(handler->ibcounters);
3302 
3303 	mutex_unlock(&dev->flow_db->lock);
3304 	if (handler->flow_matcher)
3305 		atomic_dec(&handler->flow_matcher->usecnt);
3306 	kfree(handler);
3307 
3308 	return 0;
3309 }
3310 
3311 static int ib_prio_to_core_prio(unsigned int priority, bool dont_trap)
3312 {
3313 	priority *= 2;
3314 	if (!dont_trap)
3315 		priority++;
3316 	return priority;
3317 }
3318 
3319 enum flow_table_type {
3320 	MLX5_IB_FT_RX,
3321 	MLX5_IB_FT_TX
3322 };
3323 
3324 #define MLX5_FS_MAX_TYPES	 6
3325 #define MLX5_FS_MAX_ENTRIES	 BIT(16)
3326 
3327 static struct mlx5_ib_flow_prio *_get_prio(struct mlx5_flow_namespace *ns,
3328 					   struct mlx5_ib_flow_prio *prio,
3329 					   int priority,
3330 					   int num_entries, int num_groups,
3331 					   u32 flags)
3332 {
3333 	struct mlx5_flow_table_attr ft_attr = {};
3334 	struct mlx5_flow_table *ft;
3335 
3336 	ft_attr.prio = priority;
3337 	ft_attr.max_fte = num_entries;
3338 	ft_attr.flags = flags;
3339 	ft_attr.autogroup.max_num_groups = num_groups;
3340 	ft = mlx5_create_auto_grouped_flow_table(ns, &ft_attr);
3341 	if (IS_ERR(ft))
3342 		return ERR_CAST(ft);
3343 
3344 	prio->flow_table = ft;
3345 	prio->refcount = 0;
3346 	return prio;
3347 }
3348 
3349 static struct mlx5_ib_flow_prio *get_flow_table(struct mlx5_ib_dev *dev,
3350 						struct ib_flow_attr *flow_attr,
3351 						enum flow_table_type ft_type)
3352 {
3353 	bool dont_trap = flow_attr->flags & IB_FLOW_ATTR_FLAGS_DONT_TRAP;
3354 	struct mlx5_flow_namespace *ns = NULL;
3355 	struct mlx5_ib_flow_prio *prio;
3356 	struct mlx5_flow_table *ft;
3357 	int max_table_size;
3358 	int num_entries;
3359 	int num_groups;
3360 	bool esw_encap;
3361 	u32 flags = 0;
3362 	int priority;
3363 
3364 	max_table_size = BIT(MLX5_CAP_FLOWTABLE_NIC_RX(dev->mdev,
3365 						       log_max_ft_size));
3366 	esw_encap = mlx5_eswitch_get_encap_mode(dev->mdev) !=
3367 		DEVLINK_ESWITCH_ENCAP_MODE_NONE;
3368 	if (flow_attr->type == IB_FLOW_ATTR_NORMAL) {
3369 		enum mlx5_flow_namespace_type fn_type;
3370 
3371 		if (flow_is_multicast_only(flow_attr) &&
3372 		    !dont_trap)
3373 			priority = MLX5_IB_FLOW_MCAST_PRIO;
3374 		else
3375 			priority = ib_prio_to_core_prio(flow_attr->priority,
3376 							dont_trap);
3377 		if (ft_type == MLX5_IB_FT_RX) {
3378 			fn_type = MLX5_FLOW_NAMESPACE_BYPASS;
3379 			prio = &dev->flow_db->prios[priority];
3380 			if (!dev->is_rep && !esw_encap &&
3381 			    MLX5_CAP_FLOWTABLE_NIC_RX(dev->mdev, decap))
3382 				flags |= MLX5_FLOW_TABLE_TUNNEL_EN_DECAP;
3383 			if (!dev->is_rep && !esw_encap &&
3384 			    MLX5_CAP_FLOWTABLE_NIC_RX(dev->mdev,
3385 					reformat_l3_tunnel_to_l2))
3386 				flags |= MLX5_FLOW_TABLE_TUNNEL_EN_REFORMAT;
3387 		} else {
3388 			max_table_size =
3389 				BIT(MLX5_CAP_FLOWTABLE_NIC_TX(dev->mdev,
3390 							      log_max_ft_size));
3391 			fn_type = MLX5_FLOW_NAMESPACE_EGRESS;
3392 			prio = &dev->flow_db->egress_prios[priority];
3393 			if (!dev->is_rep && !esw_encap &&
3394 			    MLX5_CAP_FLOWTABLE_NIC_TX(dev->mdev, reformat))
3395 				flags |= MLX5_FLOW_TABLE_TUNNEL_EN_REFORMAT;
3396 		}
3397 		ns = mlx5_get_flow_namespace(dev->mdev, fn_type);
3398 		num_entries = MLX5_FS_MAX_ENTRIES;
3399 		num_groups = MLX5_FS_MAX_TYPES;
3400 	} else if (flow_attr->type == IB_FLOW_ATTR_ALL_DEFAULT ||
3401 		   flow_attr->type == IB_FLOW_ATTR_MC_DEFAULT) {
3402 		ns = mlx5_get_flow_namespace(dev->mdev,
3403 					     MLX5_FLOW_NAMESPACE_LEFTOVERS);
3404 		build_leftovers_ft_param(&priority,
3405 					 &num_entries,
3406 					 &num_groups);
3407 		prio = &dev->flow_db->prios[MLX5_IB_FLOW_LEFTOVERS_PRIO];
3408 	} else if (flow_attr->type == IB_FLOW_ATTR_SNIFFER) {
3409 		if (!MLX5_CAP_FLOWTABLE(dev->mdev,
3410 					allow_sniffer_and_nic_rx_shared_tir))
3411 			return ERR_PTR(-ENOTSUPP);
3412 
3413 		ns = mlx5_get_flow_namespace(dev->mdev, ft_type == MLX5_IB_FT_RX ?
3414 					     MLX5_FLOW_NAMESPACE_SNIFFER_RX :
3415 					     MLX5_FLOW_NAMESPACE_SNIFFER_TX);
3416 
3417 		prio = &dev->flow_db->sniffer[ft_type];
3418 		priority = 0;
3419 		num_entries = 1;
3420 		num_groups = 1;
3421 	}
3422 
3423 	if (!ns)
3424 		return ERR_PTR(-ENOTSUPP);
3425 
3426 	max_table_size = min_t(int, num_entries, max_table_size);
3427 
3428 	ft = prio->flow_table;
3429 	if (!ft)
3430 		return _get_prio(ns, prio, priority, max_table_size, num_groups,
3431 				 flags);
3432 
3433 	return prio;
3434 }
3435 
3436 static void set_underlay_qp(struct mlx5_ib_dev *dev,
3437 			    struct mlx5_flow_spec *spec,
3438 			    u32 underlay_qpn)
3439 {
3440 	void *misc_params_c = MLX5_ADDR_OF(fte_match_param,
3441 					   spec->match_criteria,
3442 					   misc_parameters);
3443 	void *misc_params_v = MLX5_ADDR_OF(fte_match_param, spec->match_value,
3444 					   misc_parameters);
3445 
3446 	if (underlay_qpn &&
3447 	    MLX5_CAP_FLOWTABLE_NIC_RX(dev->mdev,
3448 				      ft_field_support.bth_dst_qp)) {
3449 		MLX5_SET(fte_match_set_misc,
3450 			 misc_params_v, bth_dst_qp, underlay_qpn);
3451 		MLX5_SET(fte_match_set_misc,
3452 			 misc_params_c, bth_dst_qp, 0xffffff);
3453 	}
3454 }
3455 
3456 static int read_flow_counters(struct ib_device *ibdev,
3457 			      struct mlx5_read_counters_attr *read_attr)
3458 {
3459 	struct mlx5_fc *fc = read_attr->hw_cntrs_hndl;
3460 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
3461 
3462 	return mlx5_fc_query(dev->mdev, fc,
3463 			     &read_attr->out[IB_COUNTER_PACKETS],
3464 			     &read_attr->out[IB_COUNTER_BYTES]);
3465 }
3466 
3467 /* flow counters currently expose two counters packets and bytes */
3468 #define FLOW_COUNTERS_NUM 2
3469 static int counters_set_description(struct ib_counters *counters,
3470 				    enum mlx5_ib_counters_type counters_type,
3471 				    struct mlx5_ib_flow_counters_desc *desc_data,
3472 				    u32 ncounters)
3473 {
3474 	struct mlx5_ib_mcounters *mcounters = to_mcounters(counters);
3475 	u32 cntrs_max_index = 0;
3476 	int i;
3477 
3478 	if (counters_type != MLX5_IB_COUNTERS_FLOW)
3479 		return -EINVAL;
3480 
3481 	/* init the fields for the object */
3482 	mcounters->type = counters_type;
3483 	mcounters->read_counters = read_flow_counters;
3484 	mcounters->counters_num = FLOW_COUNTERS_NUM;
3485 	mcounters->ncounters = ncounters;
3486 	/* each counter entry have both description and index pair */
3487 	for (i = 0; i < ncounters; i++) {
3488 		if (desc_data[i].description > IB_COUNTER_BYTES)
3489 			return -EINVAL;
3490 
3491 		if (cntrs_max_index <= desc_data[i].index)
3492 			cntrs_max_index = desc_data[i].index + 1;
3493 	}
3494 
3495 	mutex_lock(&mcounters->mcntrs_mutex);
3496 	mcounters->counters_data = desc_data;
3497 	mcounters->cntrs_max_index = cntrs_max_index;
3498 	mutex_unlock(&mcounters->mcntrs_mutex);
3499 
3500 	return 0;
3501 }
3502 
3503 #define MAX_COUNTERS_NUM (USHRT_MAX / (sizeof(u32) * 2))
3504 static int flow_counters_set_data(struct ib_counters *ibcounters,
3505 				  struct mlx5_ib_create_flow *ucmd)
3506 {
3507 	struct mlx5_ib_mcounters *mcounters = to_mcounters(ibcounters);
3508 	struct mlx5_ib_flow_counters_data *cntrs_data = NULL;
3509 	struct mlx5_ib_flow_counters_desc *desc_data = NULL;
3510 	bool hw_hndl = false;
3511 	int ret = 0;
3512 
3513 	if (ucmd && ucmd->ncounters_data != 0) {
3514 		cntrs_data = ucmd->data;
3515 		if (cntrs_data->ncounters > MAX_COUNTERS_NUM)
3516 			return -EINVAL;
3517 
3518 		desc_data = kcalloc(cntrs_data->ncounters,
3519 				    sizeof(*desc_data),
3520 				    GFP_KERNEL);
3521 		if (!desc_data)
3522 			return  -ENOMEM;
3523 
3524 		if (copy_from_user(desc_data,
3525 				   u64_to_user_ptr(cntrs_data->counters_data),
3526 				   sizeof(*desc_data) * cntrs_data->ncounters)) {
3527 			ret = -EFAULT;
3528 			goto free;
3529 		}
3530 	}
3531 
3532 	if (!mcounters->hw_cntrs_hndl) {
3533 		mcounters->hw_cntrs_hndl = mlx5_fc_create(
3534 			to_mdev(ibcounters->device)->mdev, false);
3535 		if (IS_ERR(mcounters->hw_cntrs_hndl)) {
3536 			ret = PTR_ERR(mcounters->hw_cntrs_hndl);
3537 			goto free;
3538 		}
3539 		hw_hndl = true;
3540 	}
3541 
3542 	if (desc_data) {
3543 		/* counters already bound to at least one flow */
3544 		if (mcounters->cntrs_max_index) {
3545 			ret = -EINVAL;
3546 			goto free_hndl;
3547 		}
3548 
3549 		ret = counters_set_description(ibcounters,
3550 					       MLX5_IB_COUNTERS_FLOW,
3551 					       desc_data,
3552 					       cntrs_data->ncounters);
3553 		if (ret)
3554 			goto free_hndl;
3555 
3556 	} else if (!mcounters->cntrs_max_index) {
3557 		/* counters not bound yet, must have udata passed */
3558 		ret = -EINVAL;
3559 		goto free_hndl;
3560 	}
3561 
3562 	return 0;
3563 
3564 free_hndl:
3565 	if (hw_hndl) {
3566 		mlx5_fc_destroy(to_mdev(ibcounters->device)->mdev,
3567 				mcounters->hw_cntrs_hndl);
3568 		mcounters->hw_cntrs_hndl = NULL;
3569 	}
3570 free:
3571 	kfree(desc_data);
3572 	return ret;
3573 }
3574 
3575 static void mlx5_ib_set_rule_source_port(struct mlx5_ib_dev *dev,
3576 					 struct mlx5_flow_spec *spec,
3577 					 struct mlx5_eswitch_rep *rep)
3578 {
3579 	struct mlx5_eswitch *esw = dev->mdev->priv.eswitch;
3580 	void *misc;
3581 
3582 	if (mlx5_eswitch_vport_match_metadata_enabled(esw)) {
3583 		misc = MLX5_ADDR_OF(fte_match_param, spec->match_value,
3584 				    misc_parameters_2);
3585 
3586 		MLX5_SET(fte_match_set_misc2, misc, metadata_reg_c_0,
3587 			 mlx5_eswitch_get_vport_metadata_for_match(esw,
3588 								   rep->vport));
3589 		misc = MLX5_ADDR_OF(fte_match_param, spec->match_criteria,
3590 				    misc_parameters_2);
3591 
3592 		MLX5_SET(fte_match_set_misc2, misc, metadata_reg_c_0,
3593 			 mlx5_eswitch_get_vport_metadata_mask());
3594 	} else {
3595 		misc = MLX5_ADDR_OF(fte_match_param, spec->match_value,
3596 				    misc_parameters);
3597 
3598 		MLX5_SET(fte_match_set_misc, misc, source_port, rep->vport);
3599 
3600 		misc = MLX5_ADDR_OF(fte_match_param, spec->match_criteria,
3601 				    misc_parameters);
3602 
3603 		MLX5_SET_TO_ONES(fte_match_set_misc, misc, source_port);
3604 	}
3605 }
3606 
3607 static struct mlx5_ib_flow_handler *_create_flow_rule(struct mlx5_ib_dev *dev,
3608 						      struct mlx5_ib_flow_prio *ft_prio,
3609 						      const struct ib_flow_attr *flow_attr,
3610 						      struct mlx5_flow_destination *dst,
3611 						      u32 underlay_qpn,
3612 						      struct mlx5_ib_create_flow *ucmd)
3613 {
3614 	struct mlx5_flow_table	*ft = ft_prio->flow_table;
3615 	struct mlx5_ib_flow_handler *handler;
3616 	struct mlx5_flow_act flow_act = {};
3617 	struct mlx5_flow_spec *spec;
3618 	struct mlx5_flow_destination dest_arr[2] = {};
3619 	struct mlx5_flow_destination *rule_dst = dest_arr;
3620 	const void *ib_flow = (const void *)flow_attr + sizeof(*flow_attr);
3621 	unsigned int spec_index;
3622 	u32 prev_type = 0;
3623 	int err = 0;
3624 	int dest_num = 0;
3625 	bool is_egress = flow_attr->flags & IB_FLOW_ATTR_FLAGS_EGRESS;
3626 
3627 	if (!is_valid_attr(dev->mdev, flow_attr))
3628 		return ERR_PTR(-EINVAL);
3629 
3630 	if (dev->is_rep && is_egress)
3631 		return ERR_PTR(-EINVAL);
3632 
3633 	spec = kvzalloc(sizeof(*spec), GFP_KERNEL);
3634 	handler = kzalloc(sizeof(*handler), GFP_KERNEL);
3635 	if (!handler || !spec) {
3636 		err = -ENOMEM;
3637 		goto free;
3638 	}
3639 
3640 	INIT_LIST_HEAD(&handler->list);
3641 
3642 	for (spec_index = 0; spec_index < flow_attr->num_of_specs; spec_index++) {
3643 		err = parse_flow_attr(dev->mdev, spec,
3644 				      ib_flow, flow_attr, &flow_act,
3645 				      prev_type);
3646 		if (err < 0)
3647 			goto free;
3648 
3649 		prev_type = ((union ib_flow_spec *)ib_flow)->type;
3650 		ib_flow += ((union ib_flow_spec *)ib_flow)->size;
3651 	}
3652 
3653 	if (dst && !(flow_act.action & MLX5_FLOW_CONTEXT_ACTION_DROP)) {
3654 		memcpy(&dest_arr[0], dst, sizeof(*dst));
3655 		dest_num++;
3656 	}
3657 
3658 	if (!flow_is_multicast_only(flow_attr))
3659 		set_underlay_qp(dev, spec, underlay_qpn);
3660 
3661 	if (dev->is_rep) {
3662 		struct mlx5_eswitch_rep *rep;
3663 
3664 		rep = dev->port[flow_attr->port - 1].rep;
3665 		if (!rep) {
3666 			err = -EINVAL;
3667 			goto free;
3668 		}
3669 
3670 		mlx5_ib_set_rule_source_port(dev, spec, rep);
3671 	}
3672 
3673 	spec->match_criteria_enable = get_match_criteria_enable(spec->match_criteria);
3674 
3675 	if (is_egress &&
3676 	    !is_valid_spec(dev->mdev, spec, &flow_act, is_egress)) {
3677 		err = -EINVAL;
3678 		goto free;
3679 	}
3680 
3681 	if (flow_act.action & MLX5_FLOW_CONTEXT_ACTION_COUNT) {
3682 		struct mlx5_ib_mcounters *mcounters;
3683 
3684 		err = flow_counters_set_data(flow_act.counters, ucmd);
3685 		if (err)
3686 			goto free;
3687 
3688 		mcounters = to_mcounters(flow_act.counters);
3689 		handler->ibcounters = flow_act.counters;
3690 		dest_arr[dest_num].type =
3691 			MLX5_FLOW_DESTINATION_TYPE_COUNTER;
3692 		dest_arr[dest_num].counter_id =
3693 			mlx5_fc_id(mcounters->hw_cntrs_hndl);
3694 		dest_num++;
3695 	}
3696 
3697 	if (flow_act.action & MLX5_FLOW_CONTEXT_ACTION_DROP) {
3698 		if (!dest_num)
3699 			rule_dst = NULL;
3700 	} else {
3701 		if (flow_attr->flags & IB_FLOW_ATTR_FLAGS_DONT_TRAP)
3702 			flow_act.action |=
3703 				MLX5_FLOW_CONTEXT_ACTION_FWD_NEXT_PRIO;
3704 		if (is_egress)
3705 			flow_act.action |= MLX5_FLOW_CONTEXT_ACTION_ALLOW;
3706 		else if (dest_num)
3707 			flow_act.action |= MLX5_FLOW_CONTEXT_ACTION_FWD_DEST;
3708 	}
3709 
3710 	if ((spec->flow_context.flags & FLOW_CONTEXT_HAS_TAG)  &&
3711 	    (flow_attr->type == IB_FLOW_ATTR_ALL_DEFAULT ||
3712 	     flow_attr->type == IB_FLOW_ATTR_MC_DEFAULT)) {
3713 		mlx5_ib_warn(dev, "Flow tag %u and attribute type %x isn't allowed in leftovers\n",
3714 			     spec->flow_context.flow_tag, flow_attr->type);
3715 		err = -EINVAL;
3716 		goto free;
3717 	}
3718 	handler->rule = mlx5_add_flow_rules(ft, spec,
3719 					    &flow_act,
3720 					    rule_dst, dest_num);
3721 
3722 	if (IS_ERR(handler->rule)) {
3723 		err = PTR_ERR(handler->rule);
3724 		goto free;
3725 	}
3726 
3727 	ft_prio->refcount++;
3728 	handler->prio = ft_prio;
3729 	handler->dev = dev;
3730 
3731 	ft_prio->flow_table = ft;
3732 free:
3733 	if (err && handler) {
3734 		if (handler->ibcounters &&
3735 		    atomic_read(&handler->ibcounters->usecnt) == 1)
3736 			counters_clear_description(handler->ibcounters);
3737 		kfree(handler);
3738 	}
3739 	kvfree(spec);
3740 	return err ? ERR_PTR(err) : handler;
3741 }
3742 
3743 static struct mlx5_ib_flow_handler *create_flow_rule(struct mlx5_ib_dev *dev,
3744 						     struct mlx5_ib_flow_prio *ft_prio,
3745 						     const struct ib_flow_attr *flow_attr,
3746 						     struct mlx5_flow_destination *dst)
3747 {
3748 	return _create_flow_rule(dev, ft_prio, flow_attr, dst, 0, NULL);
3749 }
3750 
3751 enum {
3752 	LEFTOVERS_MC,
3753 	LEFTOVERS_UC,
3754 };
3755 
3756 static struct mlx5_ib_flow_handler *create_leftovers_rule(struct mlx5_ib_dev *dev,
3757 							  struct mlx5_ib_flow_prio *ft_prio,
3758 							  struct ib_flow_attr *flow_attr,
3759 							  struct mlx5_flow_destination *dst)
3760 {
3761 	struct mlx5_ib_flow_handler *handler_ucast = NULL;
3762 	struct mlx5_ib_flow_handler *handler = NULL;
3763 
3764 	static struct {
3765 		struct ib_flow_attr	flow_attr;
3766 		struct ib_flow_spec_eth eth_flow;
3767 	} leftovers_specs[] = {
3768 		[LEFTOVERS_MC] = {
3769 			.flow_attr = {
3770 				.num_of_specs = 1,
3771 				.size = sizeof(leftovers_specs[0])
3772 			},
3773 			.eth_flow = {
3774 				.type = IB_FLOW_SPEC_ETH,
3775 				.size = sizeof(struct ib_flow_spec_eth),
3776 				.mask = {.dst_mac = {0x1} },
3777 				.val =  {.dst_mac = {0x1} }
3778 			}
3779 		},
3780 		[LEFTOVERS_UC] = {
3781 			.flow_attr = {
3782 				.num_of_specs = 1,
3783 				.size = sizeof(leftovers_specs[0])
3784 			},
3785 			.eth_flow = {
3786 				.type = IB_FLOW_SPEC_ETH,
3787 				.size = sizeof(struct ib_flow_spec_eth),
3788 				.mask = {.dst_mac = {0x1} },
3789 				.val = {.dst_mac = {} }
3790 			}
3791 		}
3792 	};
3793 
3794 	handler = create_flow_rule(dev, ft_prio,
3795 				   &leftovers_specs[LEFTOVERS_MC].flow_attr,
3796 				   dst);
3797 	if (!IS_ERR(handler) &&
3798 	    flow_attr->type == IB_FLOW_ATTR_ALL_DEFAULT) {
3799 		handler_ucast = create_flow_rule(dev, ft_prio,
3800 						 &leftovers_specs[LEFTOVERS_UC].flow_attr,
3801 						 dst);
3802 		if (IS_ERR(handler_ucast)) {
3803 			mlx5_del_flow_rules(handler->rule);
3804 			ft_prio->refcount--;
3805 			kfree(handler);
3806 			handler = handler_ucast;
3807 		} else {
3808 			list_add(&handler_ucast->list, &handler->list);
3809 		}
3810 	}
3811 
3812 	return handler;
3813 }
3814 
3815 static struct mlx5_ib_flow_handler *create_sniffer_rule(struct mlx5_ib_dev *dev,
3816 							struct mlx5_ib_flow_prio *ft_rx,
3817 							struct mlx5_ib_flow_prio *ft_tx,
3818 							struct mlx5_flow_destination *dst)
3819 {
3820 	struct mlx5_ib_flow_handler *handler_rx;
3821 	struct mlx5_ib_flow_handler *handler_tx;
3822 	int err;
3823 	static const struct ib_flow_attr flow_attr  = {
3824 		.num_of_specs = 0,
3825 		.size = sizeof(flow_attr)
3826 	};
3827 
3828 	handler_rx = create_flow_rule(dev, ft_rx, &flow_attr, dst);
3829 	if (IS_ERR(handler_rx)) {
3830 		err = PTR_ERR(handler_rx);
3831 		goto err;
3832 	}
3833 
3834 	handler_tx = create_flow_rule(dev, ft_tx, &flow_attr, dst);
3835 	if (IS_ERR(handler_tx)) {
3836 		err = PTR_ERR(handler_tx);
3837 		goto err_tx;
3838 	}
3839 
3840 	list_add(&handler_tx->list, &handler_rx->list);
3841 
3842 	return handler_rx;
3843 
3844 err_tx:
3845 	mlx5_del_flow_rules(handler_rx->rule);
3846 	ft_rx->refcount--;
3847 	kfree(handler_rx);
3848 err:
3849 	return ERR_PTR(err);
3850 }
3851 
3852 static struct ib_flow *mlx5_ib_create_flow(struct ib_qp *qp,
3853 					   struct ib_flow_attr *flow_attr,
3854 					   int domain,
3855 					   struct ib_udata *udata)
3856 {
3857 	struct mlx5_ib_dev *dev = to_mdev(qp->device);
3858 	struct mlx5_ib_qp *mqp = to_mqp(qp);
3859 	struct mlx5_ib_flow_handler *handler = NULL;
3860 	struct mlx5_flow_destination *dst = NULL;
3861 	struct mlx5_ib_flow_prio *ft_prio_tx = NULL;
3862 	struct mlx5_ib_flow_prio *ft_prio;
3863 	bool is_egress = flow_attr->flags & IB_FLOW_ATTR_FLAGS_EGRESS;
3864 	struct mlx5_ib_create_flow *ucmd = NULL, ucmd_hdr;
3865 	size_t min_ucmd_sz, required_ucmd_sz;
3866 	int err;
3867 	int underlay_qpn;
3868 
3869 	if (udata && udata->inlen) {
3870 		min_ucmd_sz = offsetof(typeof(ucmd_hdr), reserved) +
3871 				sizeof(ucmd_hdr.reserved);
3872 		if (udata->inlen < min_ucmd_sz)
3873 			return ERR_PTR(-EOPNOTSUPP);
3874 
3875 		err = ib_copy_from_udata(&ucmd_hdr, udata, min_ucmd_sz);
3876 		if (err)
3877 			return ERR_PTR(err);
3878 
3879 		/* currently supports only one counters data */
3880 		if (ucmd_hdr.ncounters_data > 1)
3881 			return ERR_PTR(-EINVAL);
3882 
3883 		required_ucmd_sz = min_ucmd_sz +
3884 			sizeof(struct mlx5_ib_flow_counters_data) *
3885 			ucmd_hdr.ncounters_data;
3886 		if (udata->inlen > required_ucmd_sz &&
3887 		    !ib_is_udata_cleared(udata, required_ucmd_sz,
3888 					 udata->inlen - required_ucmd_sz))
3889 			return ERR_PTR(-EOPNOTSUPP);
3890 
3891 		ucmd = kzalloc(required_ucmd_sz, GFP_KERNEL);
3892 		if (!ucmd)
3893 			return ERR_PTR(-ENOMEM);
3894 
3895 		err = ib_copy_from_udata(ucmd, udata, required_ucmd_sz);
3896 		if (err)
3897 			goto free_ucmd;
3898 	}
3899 
3900 	if (flow_attr->priority > MLX5_IB_FLOW_LAST_PRIO) {
3901 		err = -ENOMEM;
3902 		goto free_ucmd;
3903 	}
3904 
3905 	if (domain != IB_FLOW_DOMAIN_USER ||
3906 	    flow_attr->port > dev->num_ports ||
3907 	    (flow_attr->flags & ~(IB_FLOW_ATTR_FLAGS_DONT_TRAP |
3908 				  IB_FLOW_ATTR_FLAGS_EGRESS))) {
3909 		err = -EINVAL;
3910 		goto free_ucmd;
3911 	}
3912 
3913 	if (is_egress &&
3914 	    (flow_attr->type == IB_FLOW_ATTR_ALL_DEFAULT ||
3915 	     flow_attr->type == IB_FLOW_ATTR_MC_DEFAULT)) {
3916 		err = -EINVAL;
3917 		goto free_ucmd;
3918 	}
3919 
3920 	dst = kzalloc(sizeof(*dst), GFP_KERNEL);
3921 	if (!dst) {
3922 		err = -ENOMEM;
3923 		goto free_ucmd;
3924 	}
3925 
3926 	mutex_lock(&dev->flow_db->lock);
3927 
3928 	ft_prio = get_flow_table(dev, flow_attr,
3929 				 is_egress ? MLX5_IB_FT_TX : MLX5_IB_FT_RX);
3930 	if (IS_ERR(ft_prio)) {
3931 		err = PTR_ERR(ft_prio);
3932 		goto unlock;
3933 	}
3934 	if (flow_attr->type == IB_FLOW_ATTR_SNIFFER) {
3935 		ft_prio_tx = get_flow_table(dev, flow_attr, MLX5_IB_FT_TX);
3936 		if (IS_ERR(ft_prio_tx)) {
3937 			err = PTR_ERR(ft_prio_tx);
3938 			ft_prio_tx = NULL;
3939 			goto destroy_ft;
3940 		}
3941 	}
3942 
3943 	if (is_egress) {
3944 		dst->type = MLX5_FLOW_DESTINATION_TYPE_PORT;
3945 	} else {
3946 		dst->type = MLX5_FLOW_DESTINATION_TYPE_TIR;
3947 		if (mqp->flags & MLX5_IB_QP_RSS)
3948 			dst->tir_num = mqp->rss_qp.tirn;
3949 		else
3950 			dst->tir_num = mqp->raw_packet_qp.rq.tirn;
3951 	}
3952 
3953 	if (flow_attr->type == IB_FLOW_ATTR_NORMAL) {
3954 		underlay_qpn = (mqp->flags & IB_QP_CREATE_SOURCE_QPN) ?
3955 				       mqp->underlay_qpn :
3956 				       0;
3957 		handler = _create_flow_rule(dev, ft_prio, flow_attr, dst,
3958 					    underlay_qpn, ucmd);
3959 	} else if (flow_attr->type == IB_FLOW_ATTR_ALL_DEFAULT ||
3960 		   flow_attr->type == IB_FLOW_ATTR_MC_DEFAULT) {
3961 		handler = create_leftovers_rule(dev, ft_prio, flow_attr,
3962 						dst);
3963 	} else if (flow_attr->type == IB_FLOW_ATTR_SNIFFER) {
3964 		handler = create_sniffer_rule(dev, ft_prio, ft_prio_tx, dst);
3965 	} else {
3966 		err = -EINVAL;
3967 		goto destroy_ft;
3968 	}
3969 
3970 	if (IS_ERR(handler)) {
3971 		err = PTR_ERR(handler);
3972 		handler = NULL;
3973 		goto destroy_ft;
3974 	}
3975 
3976 	mutex_unlock(&dev->flow_db->lock);
3977 	kfree(dst);
3978 	kfree(ucmd);
3979 
3980 	return &handler->ibflow;
3981 
3982 destroy_ft:
3983 	put_flow_table(dev, ft_prio, false);
3984 	if (ft_prio_tx)
3985 		put_flow_table(dev, ft_prio_tx, false);
3986 unlock:
3987 	mutex_unlock(&dev->flow_db->lock);
3988 	kfree(dst);
3989 free_ucmd:
3990 	kfree(ucmd);
3991 	return ERR_PTR(err);
3992 }
3993 
3994 static struct mlx5_ib_flow_prio *
3995 _get_flow_table(struct mlx5_ib_dev *dev,
3996 		struct mlx5_ib_flow_matcher *fs_matcher,
3997 		bool mcast)
3998 {
3999 	struct mlx5_flow_namespace *ns = NULL;
4000 	struct mlx5_ib_flow_prio *prio = NULL;
4001 	int max_table_size = 0;
4002 	bool esw_encap;
4003 	u32 flags = 0;
4004 	int priority;
4005 
4006 	if (mcast)
4007 		priority = MLX5_IB_FLOW_MCAST_PRIO;
4008 	else
4009 		priority = ib_prio_to_core_prio(fs_matcher->priority, false);
4010 
4011 	esw_encap = mlx5_eswitch_get_encap_mode(dev->mdev) !=
4012 		DEVLINK_ESWITCH_ENCAP_MODE_NONE;
4013 	if (fs_matcher->ns_type == MLX5_FLOW_NAMESPACE_BYPASS) {
4014 		max_table_size = BIT(MLX5_CAP_FLOWTABLE_NIC_RX(dev->mdev,
4015 					log_max_ft_size));
4016 		if (MLX5_CAP_FLOWTABLE_NIC_RX(dev->mdev, decap) && !esw_encap)
4017 			flags |= MLX5_FLOW_TABLE_TUNNEL_EN_DECAP;
4018 		if (MLX5_CAP_FLOWTABLE_NIC_RX(dev->mdev,
4019 					      reformat_l3_tunnel_to_l2) &&
4020 		    !esw_encap)
4021 			flags |= MLX5_FLOW_TABLE_TUNNEL_EN_REFORMAT;
4022 	} else if (fs_matcher->ns_type == MLX5_FLOW_NAMESPACE_EGRESS) {
4023 		max_table_size = BIT(
4024 			MLX5_CAP_FLOWTABLE_NIC_TX(dev->mdev, log_max_ft_size));
4025 		if (MLX5_CAP_FLOWTABLE_NIC_TX(dev->mdev, reformat) && !esw_encap)
4026 			flags |= MLX5_FLOW_TABLE_TUNNEL_EN_REFORMAT;
4027 	} else if (fs_matcher->ns_type == MLX5_FLOW_NAMESPACE_FDB) {
4028 		max_table_size = BIT(
4029 			MLX5_CAP_ESW_FLOWTABLE_FDB(dev->mdev, log_max_ft_size));
4030 		if (MLX5_CAP_ESW_FLOWTABLE_FDB(dev->mdev, decap) && esw_encap)
4031 			flags |= MLX5_FLOW_TABLE_TUNNEL_EN_DECAP;
4032 		if (MLX5_CAP_ESW_FLOWTABLE_FDB(dev->mdev, reformat_l3_tunnel_to_l2) &&
4033 		    esw_encap)
4034 			flags |= MLX5_FLOW_TABLE_TUNNEL_EN_REFORMAT;
4035 		priority = FDB_BYPASS_PATH;
4036 	} else if (fs_matcher->ns_type == MLX5_FLOW_NAMESPACE_RDMA_RX) {
4037 		max_table_size =
4038 			BIT(MLX5_CAP_FLOWTABLE_RDMA_RX(dev->mdev,
4039 						       log_max_ft_size));
4040 		priority = fs_matcher->priority;
4041 	} else if (fs_matcher->ns_type == MLX5_FLOW_NAMESPACE_RDMA_TX) {
4042 		max_table_size =
4043 			BIT(MLX5_CAP_FLOWTABLE_RDMA_TX(dev->mdev,
4044 						       log_max_ft_size));
4045 		priority = fs_matcher->priority;
4046 	}
4047 
4048 	max_table_size = min_t(int, max_table_size, MLX5_FS_MAX_ENTRIES);
4049 
4050 	ns = mlx5_get_flow_namespace(dev->mdev, fs_matcher->ns_type);
4051 	if (!ns)
4052 		return ERR_PTR(-ENOTSUPP);
4053 
4054 	if (fs_matcher->ns_type == MLX5_FLOW_NAMESPACE_BYPASS)
4055 		prio = &dev->flow_db->prios[priority];
4056 	else if (fs_matcher->ns_type == MLX5_FLOW_NAMESPACE_EGRESS)
4057 		prio = &dev->flow_db->egress_prios[priority];
4058 	else if (fs_matcher->ns_type == MLX5_FLOW_NAMESPACE_FDB)
4059 		prio = &dev->flow_db->fdb;
4060 	else if (fs_matcher->ns_type == MLX5_FLOW_NAMESPACE_RDMA_RX)
4061 		prio = &dev->flow_db->rdma_rx[priority];
4062 	else if (fs_matcher->ns_type == MLX5_FLOW_NAMESPACE_RDMA_TX)
4063 		prio = &dev->flow_db->rdma_tx[priority];
4064 
4065 	if (!prio)
4066 		return ERR_PTR(-EINVAL);
4067 
4068 	if (prio->flow_table)
4069 		return prio;
4070 
4071 	return _get_prio(ns, prio, priority, max_table_size,
4072 			 MLX5_FS_MAX_TYPES, flags);
4073 }
4074 
4075 static struct mlx5_ib_flow_handler *
4076 _create_raw_flow_rule(struct mlx5_ib_dev *dev,
4077 		      struct mlx5_ib_flow_prio *ft_prio,
4078 		      struct mlx5_flow_destination *dst,
4079 		      struct mlx5_ib_flow_matcher  *fs_matcher,
4080 		      struct mlx5_flow_context *flow_context,
4081 		      struct mlx5_flow_act *flow_act,
4082 		      void *cmd_in, int inlen,
4083 		      int dst_num)
4084 {
4085 	struct mlx5_ib_flow_handler *handler;
4086 	struct mlx5_flow_spec *spec;
4087 	struct mlx5_flow_table *ft = ft_prio->flow_table;
4088 	int err = 0;
4089 
4090 	spec = kvzalloc(sizeof(*spec), GFP_KERNEL);
4091 	handler = kzalloc(sizeof(*handler), GFP_KERNEL);
4092 	if (!handler || !spec) {
4093 		err = -ENOMEM;
4094 		goto free;
4095 	}
4096 
4097 	INIT_LIST_HEAD(&handler->list);
4098 
4099 	memcpy(spec->match_value, cmd_in, inlen);
4100 	memcpy(spec->match_criteria, fs_matcher->matcher_mask.match_params,
4101 	       fs_matcher->mask_len);
4102 	spec->match_criteria_enable = fs_matcher->match_criteria_enable;
4103 	spec->flow_context = *flow_context;
4104 
4105 	handler->rule = mlx5_add_flow_rules(ft, spec,
4106 					    flow_act, dst, dst_num);
4107 
4108 	if (IS_ERR(handler->rule)) {
4109 		err = PTR_ERR(handler->rule);
4110 		goto free;
4111 	}
4112 
4113 	ft_prio->refcount++;
4114 	handler->prio = ft_prio;
4115 	handler->dev = dev;
4116 	ft_prio->flow_table = ft;
4117 
4118 free:
4119 	if (err)
4120 		kfree(handler);
4121 	kvfree(spec);
4122 	return err ? ERR_PTR(err) : handler;
4123 }
4124 
4125 static bool raw_fs_is_multicast(struct mlx5_ib_flow_matcher *fs_matcher,
4126 				void *match_v)
4127 {
4128 	void *match_c;
4129 	void *match_v_set_lyr_2_4, *match_c_set_lyr_2_4;
4130 	void *dmac, *dmac_mask;
4131 	void *ipv4, *ipv4_mask;
4132 
4133 	if (!(fs_matcher->match_criteria_enable &
4134 	      (1 << MATCH_CRITERIA_ENABLE_OUTER_BIT)))
4135 		return false;
4136 
4137 	match_c = fs_matcher->matcher_mask.match_params;
4138 	match_v_set_lyr_2_4 = MLX5_ADDR_OF(fte_match_param, match_v,
4139 					   outer_headers);
4140 	match_c_set_lyr_2_4 = MLX5_ADDR_OF(fte_match_param, match_c,
4141 					   outer_headers);
4142 
4143 	dmac = MLX5_ADDR_OF(fte_match_set_lyr_2_4, match_v_set_lyr_2_4,
4144 			    dmac_47_16);
4145 	dmac_mask = MLX5_ADDR_OF(fte_match_set_lyr_2_4, match_c_set_lyr_2_4,
4146 				 dmac_47_16);
4147 
4148 	if (is_multicast_ether_addr(dmac) &&
4149 	    is_multicast_ether_addr(dmac_mask))
4150 		return true;
4151 
4152 	ipv4 = MLX5_ADDR_OF(fte_match_set_lyr_2_4, match_v_set_lyr_2_4,
4153 			    dst_ipv4_dst_ipv6.ipv4_layout.ipv4);
4154 
4155 	ipv4_mask = MLX5_ADDR_OF(fte_match_set_lyr_2_4, match_c_set_lyr_2_4,
4156 				 dst_ipv4_dst_ipv6.ipv4_layout.ipv4);
4157 
4158 	if (ipv4_is_multicast(*(__be32 *)(ipv4)) &&
4159 	    ipv4_is_multicast(*(__be32 *)(ipv4_mask)))
4160 		return true;
4161 
4162 	return false;
4163 }
4164 
4165 struct mlx5_ib_flow_handler *
4166 mlx5_ib_raw_fs_rule_add(struct mlx5_ib_dev *dev,
4167 			struct mlx5_ib_flow_matcher *fs_matcher,
4168 			struct mlx5_flow_context *flow_context,
4169 			struct mlx5_flow_act *flow_act,
4170 			u32 counter_id,
4171 			void *cmd_in, int inlen, int dest_id,
4172 			int dest_type)
4173 {
4174 	struct mlx5_flow_destination *dst;
4175 	struct mlx5_ib_flow_prio *ft_prio;
4176 	struct mlx5_ib_flow_handler *handler;
4177 	int dst_num = 0;
4178 	bool mcast;
4179 	int err;
4180 
4181 	if (fs_matcher->flow_type != MLX5_IB_FLOW_TYPE_NORMAL)
4182 		return ERR_PTR(-EOPNOTSUPP);
4183 
4184 	if (fs_matcher->priority > MLX5_IB_FLOW_LAST_PRIO)
4185 		return ERR_PTR(-ENOMEM);
4186 
4187 	dst = kcalloc(2, sizeof(*dst), GFP_KERNEL);
4188 	if (!dst)
4189 		return ERR_PTR(-ENOMEM);
4190 
4191 	mcast = raw_fs_is_multicast(fs_matcher, cmd_in);
4192 	mutex_lock(&dev->flow_db->lock);
4193 
4194 	ft_prio = _get_flow_table(dev, fs_matcher, mcast);
4195 	if (IS_ERR(ft_prio)) {
4196 		err = PTR_ERR(ft_prio);
4197 		goto unlock;
4198 	}
4199 
4200 	if (dest_type == MLX5_FLOW_DESTINATION_TYPE_TIR) {
4201 		dst[dst_num].type = dest_type;
4202 		dst[dst_num].tir_num = dest_id;
4203 		flow_act->action |= MLX5_FLOW_CONTEXT_ACTION_FWD_DEST;
4204 	} else if (dest_type == MLX5_FLOW_DESTINATION_TYPE_FLOW_TABLE) {
4205 		dst[dst_num].type = MLX5_FLOW_DESTINATION_TYPE_FLOW_TABLE_NUM;
4206 		dst[dst_num].ft_num = dest_id;
4207 		flow_act->action |= MLX5_FLOW_CONTEXT_ACTION_FWD_DEST;
4208 	} else {
4209 		dst[dst_num].type = MLX5_FLOW_DESTINATION_TYPE_PORT;
4210 		flow_act->action |= MLX5_FLOW_CONTEXT_ACTION_ALLOW;
4211 	}
4212 
4213 	dst_num++;
4214 
4215 	if (flow_act->action & MLX5_FLOW_CONTEXT_ACTION_COUNT) {
4216 		dst[dst_num].type = MLX5_FLOW_DESTINATION_TYPE_COUNTER;
4217 		dst[dst_num].counter_id = counter_id;
4218 		dst_num++;
4219 	}
4220 
4221 	handler = _create_raw_flow_rule(dev, ft_prio, dst, fs_matcher,
4222 					flow_context, flow_act,
4223 					cmd_in, inlen, dst_num);
4224 
4225 	if (IS_ERR(handler)) {
4226 		err = PTR_ERR(handler);
4227 		goto destroy_ft;
4228 	}
4229 
4230 	mutex_unlock(&dev->flow_db->lock);
4231 	atomic_inc(&fs_matcher->usecnt);
4232 	handler->flow_matcher = fs_matcher;
4233 
4234 	kfree(dst);
4235 
4236 	return handler;
4237 
4238 destroy_ft:
4239 	put_flow_table(dev, ft_prio, false);
4240 unlock:
4241 	mutex_unlock(&dev->flow_db->lock);
4242 	kfree(dst);
4243 
4244 	return ERR_PTR(err);
4245 }
4246 
4247 static u32 mlx5_ib_flow_action_flags_to_accel_xfrm_flags(u32 mlx5_flags)
4248 {
4249 	u32 flags = 0;
4250 
4251 	if (mlx5_flags & MLX5_IB_UAPI_FLOW_ACTION_FLAGS_REQUIRE_METADATA)
4252 		flags |= MLX5_ACCEL_XFRM_FLAG_REQUIRE_METADATA;
4253 
4254 	return flags;
4255 }
4256 
4257 #define MLX5_FLOW_ACTION_ESP_CREATE_LAST_SUPPORTED	MLX5_IB_UAPI_FLOW_ACTION_FLAGS_REQUIRE_METADATA
4258 static struct ib_flow_action *
4259 mlx5_ib_create_flow_action_esp(struct ib_device *device,
4260 			       const struct ib_flow_action_attrs_esp *attr,
4261 			       struct uverbs_attr_bundle *attrs)
4262 {
4263 	struct mlx5_ib_dev *mdev = to_mdev(device);
4264 	struct ib_uverbs_flow_action_esp_keymat_aes_gcm *aes_gcm;
4265 	struct mlx5_accel_esp_xfrm_attrs accel_attrs = {};
4266 	struct mlx5_ib_flow_action *action;
4267 	u64 action_flags;
4268 	u64 flags;
4269 	int err = 0;
4270 
4271 	err = uverbs_get_flags64(
4272 		&action_flags, attrs, MLX5_IB_ATTR_CREATE_FLOW_ACTION_FLAGS,
4273 		((MLX5_FLOW_ACTION_ESP_CREATE_LAST_SUPPORTED << 1) - 1));
4274 	if (err)
4275 		return ERR_PTR(err);
4276 
4277 	flags = mlx5_ib_flow_action_flags_to_accel_xfrm_flags(action_flags);
4278 
4279 	/* We current only support a subset of the standard features. Only a
4280 	 * keymat of type AES_GCM, with icv_len == 16, iv_algo == SEQ and esn
4281 	 * (with overlap). Full offload mode isn't supported.
4282 	 */
4283 	if (!attr->keymat || attr->replay || attr->encap ||
4284 	    attr->spi || attr->seq || attr->tfc_pad ||
4285 	    attr->hard_limit_pkts ||
4286 	    (attr->flags & ~(IB_FLOW_ACTION_ESP_FLAGS_ESN_TRIGGERED |
4287 			     IB_UVERBS_FLOW_ACTION_ESP_FLAGS_ENCRYPT)))
4288 		return ERR_PTR(-EOPNOTSUPP);
4289 
4290 	if (attr->keymat->protocol !=
4291 	    IB_UVERBS_FLOW_ACTION_ESP_KEYMAT_AES_GCM)
4292 		return ERR_PTR(-EOPNOTSUPP);
4293 
4294 	aes_gcm = &attr->keymat->keymat.aes_gcm;
4295 
4296 	if (aes_gcm->icv_len != 16 ||
4297 	    aes_gcm->iv_algo != IB_UVERBS_FLOW_ACTION_IV_ALGO_SEQ)
4298 		return ERR_PTR(-EOPNOTSUPP);
4299 
4300 	action = kmalloc(sizeof(*action), GFP_KERNEL);
4301 	if (!action)
4302 		return ERR_PTR(-ENOMEM);
4303 
4304 	action->esp_aes_gcm.ib_flags = attr->flags;
4305 	memcpy(&accel_attrs.keymat.aes_gcm.aes_key, &aes_gcm->aes_key,
4306 	       sizeof(accel_attrs.keymat.aes_gcm.aes_key));
4307 	accel_attrs.keymat.aes_gcm.key_len = aes_gcm->key_len * 8;
4308 	memcpy(&accel_attrs.keymat.aes_gcm.salt, &aes_gcm->salt,
4309 	       sizeof(accel_attrs.keymat.aes_gcm.salt));
4310 	memcpy(&accel_attrs.keymat.aes_gcm.seq_iv, &aes_gcm->iv,
4311 	       sizeof(accel_attrs.keymat.aes_gcm.seq_iv));
4312 	accel_attrs.keymat.aes_gcm.icv_len = aes_gcm->icv_len * 8;
4313 	accel_attrs.keymat.aes_gcm.iv_algo = MLX5_ACCEL_ESP_AES_GCM_IV_ALGO_SEQ;
4314 	accel_attrs.keymat_type = MLX5_ACCEL_ESP_KEYMAT_AES_GCM;
4315 
4316 	accel_attrs.esn = attr->esn;
4317 	if (attr->flags & IB_FLOW_ACTION_ESP_FLAGS_ESN_TRIGGERED)
4318 		accel_attrs.flags |= MLX5_ACCEL_ESP_FLAGS_ESN_TRIGGERED;
4319 	if (attr->flags & IB_UVERBS_FLOW_ACTION_ESP_FLAGS_ESN_NEW_WINDOW)
4320 		accel_attrs.flags |= MLX5_ACCEL_ESP_FLAGS_ESN_STATE_OVERLAP;
4321 
4322 	if (attr->flags & IB_UVERBS_FLOW_ACTION_ESP_FLAGS_ENCRYPT)
4323 		accel_attrs.action |= MLX5_ACCEL_ESP_ACTION_ENCRYPT;
4324 
4325 	action->esp_aes_gcm.ctx =
4326 		mlx5_accel_esp_create_xfrm(mdev->mdev, &accel_attrs, flags);
4327 	if (IS_ERR(action->esp_aes_gcm.ctx)) {
4328 		err = PTR_ERR(action->esp_aes_gcm.ctx);
4329 		goto err_parse;
4330 	}
4331 
4332 	action->esp_aes_gcm.ib_flags = attr->flags;
4333 
4334 	return &action->ib_action;
4335 
4336 err_parse:
4337 	kfree(action);
4338 	return ERR_PTR(err);
4339 }
4340 
4341 static int
4342 mlx5_ib_modify_flow_action_esp(struct ib_flow_action *action,
4343 			       const struct ib_flow_action_attrs_esp *attr,
4344 			       struct uverbs_attr_bundle *attrs)
4345 {
4346 	struct mlx5_ib_flow_action *maction = to_mflow_act(action);
4347 	struct mlx5_accel_esp_xfrm_attrs accel_attrs;
4348 	int err = 0;
4349 
4350 	if (attr->keymat || attr->replay || attr->encap ||
4351 	    attr->spi || attr->seq || attr->tfc_pad ||
4352 	    attr->hard_limit_pkts ||
4353 	    (attr->flags & ~(IB_FLOW_ACTION_ESP_FLAGS_ESN_TRIGGERED |
4354 			     IB_FLOW_ACTION_ESP_FLAGS_MOD_ESP_ATTRS |
4355 			     IB_UVERBS_FLOW_ACTION_ESP_FLAGS_ESN_NEW_WINDOW)))
4356 		return -EOPNOTSUPP;
4357 
4358 	/* Only the ESN value or the MLX5_ACCEL_ESP_FLAGS_ESN_STATE_OVERLAP can
4359 	 * be modified.
4360 	 */
4361 	if (!(maction->esp_aes_gcm.ib_flags &
4362 	      IB_FLOW_ACTION_ESP_FLAGS_ESN_TRIGGERED) &&
4363 	    attr->flags & (IB_FLOW_ACTION_ESP_FLAGS_ESN_TRIGGERED |
4364 			   IB_UVERBS_FLOW_ACTION_ESP_FLAGS_ESN_NEW_WINDOW))
4365 		return -EINVAL;
4366 
4367 	memcpy(&accel_attrs, &maction->esp_aes_gcm.ctx->attrs,
4368 	       sizeof(accel_attrs));
4369 
4370 	accel_attrs.esn = attr->esn;
4371 	if (attr->flags & IB_UVERBS_FLOW_ACTION_ESP_FLAGS_ESN_NEW_WINDOW)
4372 		accel_attrs.flags |= MLX5_ACCEL_ESP_FLAGS_ESN_STATE_OVERLAP;
4373 	else
4374 		accel_attrs.flags &= ~MLX5_ACCEL_ESP_FLAGS_ESN_STATE_OVERLAP;
4375 
4376 	err = mlx5_accel_esp_modify_xfrm(maction->esp_aes_gcm.ctx,
4377 					 &accel_attrs);
4378 	if (err)
4379 		return err;
4380 
4381 	maction->esp_aes_gcm.ib_flags &=
4382 		~IB_UVERBS_FLOW_ACTION_ESP_FLAGS_ESN_NEW_WINDOW;
4383 	maction->esp_aes_gcm.ib_flags |=
4384 		attr->flags & IB_UVERBS_FLOW_ACTION_ESP_FLAGS_ESN_NEW_WINDOW;
4385 
4386 	return 0;
4387 }
4388 
4389 static int mlx5_ib_destroy_flow_action(struct ib_flow_action *action)
4390 {
4391 	struct mlx5_ib_flow_action *maction = to_mflow_act(action);
4392 
4393 	switch (action->type) {
4394 	case IB_FLOW_ACTION_ESP:
4395 		/*
4396 		 * We only support aes_gcm by now, so we implicitly know this is
4397 		 * the underline crypto.
4398 		 */
4399 		mlx5_accel_esp_destroy_xfrm(maction->esp_aes_gcm.ctx);
4400 		break;
4401 	case IB_FLOW_ACTION_UNSPECIFIED:
4402 		mlx5_ib_destroy_flow_action_raw(maction);
4403 		break;
4404 	default:
4405 		WARN_ON(true);
4406 		break;
4407 	}
4408 
4409 	kfree(maction);
4410 	return 0;
4411 }
4412 
4413 static int mlx5_ib_mcg_attach(struct ib_qp *ibqp, union ib_gid *gid, u16 lid)
4414 {
4415 	struct mlx5_ib_dev *dev = to_mdev(ibqp->device);
4416 	struct mlx5_ib_qp *mqp = to_mqp(ibqp);
4417 	int err;
4418 	u16 uid;
4419 
4420 	uid = ibqp->pd ?
4421 		to_mpd(ibqp->pd)->uid : 0;
4422 
4423 	if (mqp->flags & MLX5_IB_QP_UNDERLAY) {
4424 		mlx5_ib_dbg(dev, "Attaching a multi cast group to underlay QP is not supported\n");
4425 		return -EOPNOTSUPP;
4426 	}
4427 
4428 	err = mlx5_cmd_attach_mcg(dev->mdev, gid, ibqp->qp_num, uid);
4429 	if (err)
4430 		mlx5_ib_warn(dev, "failed attaching QPN 0x%x, MGID %pI6\n",
4431 			     ibqp->qp_num, gid->raw);
4432 
4433 	return err;
4434 }
4435 
4436 static int mlx5_ib_mcg_detach(struct ib_qp *ibqp, union ib_gid *gid, u16 lid)
4437 {
4438 	struct mlx5_ib_dev *dev = to_mdev(ibqp->device);
4439 	int err;
4440 	u16 uid;
4441 
4442 	uid = ibqp->pd ?
4443 		to_mpd(ibqp->pd)->uid : 0;
4444 	err = mlx5_cmd_detach_mcg(dev->mdev, gid, ibqp->qp_num, uid);
4445 	if (err)
4446 		mlx5_ib_warn(dev, "failed detaching QPN 0x%x, MGID %pI6\n",
4447 			     ibqp->qp_num, gid->raw);
4448 
4449 	return err;
4450 }
4451 
4452 static int init_node_data(struct mlx5_ib_dev *dev)
4453 {
4454 	int err;
4455 
4456 	err = mlx5_query_node_desc(dev, dev->ib_dev.node_desc);
4457 	if (err)
4458 		return err;
4459 
4460 	dev->mdev->rev_id = dev->mdev->pdev->revision;
4461 
4462 	return mlx5_query_node_guid(dev, &dev->ib_dev.node_guid);
4463 }
4464 
4465 static ssize_t fw_pages_show(struct device *device,
4466 			     struct device_attribute *attr, char *buf)
4467 {
4468 	struct mlx5_ib_dev *dev =
4469 		rdma_device_to_drv_device(device, struct mlx5_ib_dev, ib_dev);
4470 
4471 	return sprintf(buf, "%d\n", dev->mdev->priv.fw_pages);
4472 }
4473 static DEVICE_ATTR_RO(fw_pages);
4474 
4475 static ssize_t reg_pages_show(struct device *device,
4476 			      struct device_attribute *attr, char *buf)
4477 {
4478 	struct mlx5_ib_dev *dev =
4479 		rdma_device_to_drv_device(device, struct mlx5_ib_dev, ib_dev);
4480 
4481 	return sprintf(buf, "%d\n", atomic_read(&dev->mdev->priv.reg_pages));
4482 }
4483 static DEVICE_ATTR_RO(reg_pages);
4484 
4485 static ssize_t hca_type_show(struct device *device,
4486 			     struct device_attribute *attr, char *buf)
4487 {
4488 	struct mlx5_ib_dev *dev =
4489 		rdma_device_to_drv_device(device, struct mlx5_ib_dev, ib_dev);
4490 
4491 	return sprintf(buf, "MT%d\n", dev->mdev->pdev->device);
4492 }
4493 static DEVICE_ATTR_RO(hca_type);
4494 
4495 static ssize_t hw_rev_show(struct device *device,
4496 			   struct device_attribute *attr, char *buf)
4497 {
4498 	struct mlx5_ib_dev *dev =
4499 		rdma_device_to_drv_device(device, struct mlx5_ib_dev, ib_dev);
4500 
4501 	return sprintf(buf, "%x\n", dev->mdev->rev_id);
4502 }
4503 static DEVICE_ATTR_RO(hw_rev);
4504 
4505 static ssize_t board_id_show(struct device *device,
4506 			     struct device_attribute *attr, char *buf)
4507 {
4508 	struct mlx5_ib_dev *dev =
4509 		rdma_device_to_drv_device(device, struct mlx5_ib_dev, ib_dev);
4510 
4511 	return sprintf(buf, "%.*s\n", MLX5_BOARD_ID_LEN,
4512 		       dev->mdev->board_id);
4513 }
4514 static DEVICE_ATTR_RO(board_id);
4515 
4516 static struct attribute *mlx5_class_attributes[] = {
4517 	&dev_attr_hw_rev.attr,
4518 	&dev_attr_hca_type.attr,
4519 	&dev_attr_board_id.attr,
4520 	&dev_attr_fw_pages.attr,
4521 	&dev_attr_reg_pages.attr,
4522 	NULL,
4523 };
4524 
4525 static const struct attribute_group mlx5_attr_group = {
4526 	.attrs = mlx5_class_attributes,
4527 };
4528 
4529 static void pkey_change_handler(struct work_struct *work)
4530 {
4531 	struct mlx5_ib_port_resources *ports =
4532 		container_of(work, struct mlx5_ib_port_resources,
4533 			     pkey_change_work);
4534 
4535 	mutex_lock(&ports->devr->mutex);
4536 	mlx5_ib_gsi_pkey_change(ports->gsi);
4537 	mutex_unlock(&ports->devr->mutex);
4538 }
4539 
4540 static void mlx5_ib_handle_internal_error(struct mlx5_ib_dev *ibdev)
4541 {
4542 	struct mlx5_ib_qp *mqp;
4543 	struct mlx5_ib_cq *send_mcq, *recv_mcq;
4544 	struct mlx5_core_cq *mcq;
4545 	struct list_head cq_armed_list;
4546 	unsigned long flags_qp;
4547 	unsigned long flags_cq;
4548 	unsigned long flags;
4549 
4550 	INIT_LIST_HEAD(&cq_armed_list);
4551 
4552 	/* Go over qp list reside on that ibdev, sync with create/destroy qp.*/
4553 	spin_lock_irqsave(&ibdev->reset_flow_resource_lock, flags);
4554 	list_for_each_entry(mqp, &ibdev->qp_list, qps_list) {
4555 		spin_lock_irqsave(&mqp->sq.lock, flags_qp);
4556 		if (mqp->sq.tail != mqp->sq.head) {
4557 			send_mcq = to_mcq(mqp->ibqp.send_cq);
4558 			spin_lock_irqsave(&send_mcq->lock, flags_cq);
4559 			if (send_mcq->mcq.comp &&
4560 			    mqp->ibqp.send_cq->comp_handler) {
4561 				if (!send_mcq->mcq.reset_notify_added) {
4562 					send_mcq->mcq.reset_notify_added = 1;
4563 					list_add_tail(&send_mcq->mcq.reset_notify,
4564 						      &cq_armed_list);
4565 				}
4566 			}
4567 			spin_unlock_irqrestore(&send_mcq->lock, flags_cq);
4568 		}
4569 		spin_unlock_irqrestore(&mqp->sq.lock, flags_qp);
4570 		spin_lock_irqsave(&mqp->rq.lock, flags_qp);
4571 		/* no handling is needed for SRQ */
4572 		if (!mqp->ibqp.srq) {
4573 			if (mqp->rq.tail != mqp->rq.head) {
4574 				recv_mcq = to_mcq(mqp->ibqp.recv_cq);
4575 				spin_lock_irqsave(&recv_mcq->lock, flags_cq);
4576 				if (recv_mcq->mcq.comp &&
4577 				    mqp->ibqp.recv_cq->comp_handler) {
4578 					if (!recv_mcq->mcq.reset_notify_added) {
4579 						recv_mcq->mcq.reset_notify_added = 1;
4580 						list_add_tail(&recv_mcq->mcq.reset_notify,
4581 							      &cq_armed_list);
4582 					}
4583 				}
4584 				spin_unlock_irqrestore(&recv_mcq->lock,
4585 						       flags_cq);
4586 			}
4587 		}
4588 		spin_unlock_irqrestore(&mqp->rq.lock, flags_qp);
4589 	}
4590 	/*At that point all inflight post send were put to be executed as of we
4591 	 * lock/unlock above locks Now need to arm all involved CQs.
4592 	 */
4593 	list_for_each_entry(mcq, &cq_armed_list, reset_notify) {
4594 		mcq->comp(mcq, NULL);
4595 	}
4596 	spin_unlock_irqrestore(&ibdev->reset_flow_resource_lock, flags);
4597 }
4598 
4599 static void delay_drop_handler(struct work_struct *work)
4600 {
4601 	int err;
4602 	struct mlx5_ib_delay_drop *delay_drop =
4603 		container_of(work, struct mlx5_ib_delay_drop,
4604 			     delay_drop_work);
4605 
4606 	atomic_inc(&delay_drop->events_cnt);
4607 
4608 	mutex_lock(&delay_drop->lock);
4609 	err = mlx5_core_set_delay_drop(delay_drop->dev, delay_drop->timeout);
4610 	if (err) {
4611 		mlx5_ib_warn(delay_drop->dev, "Failed to set delay drop, timeout=%u\n",
4612 			     delay_drop->timeout);
4613 		delay_drop->activate = false;
4614 	}
4615 	mutex_unlock(&delay_drop->lock);
4616 }
4617 
4618 static void handle_general_event(struct mlx5_ib_dev *ibdev, struct mlx5_eqe *eqe,
4619 				 struct ib_event *ibev)
4620 {
4621 	u8 port = (eqe->data.port.port >> 4) & 0xf;
4622 
4623 	switch (eqe->sub_type) {
4624 	case MLX5_GENERAL_SUBTYPE_DELAY_DROP_TIMEOUT:
4625 		if (mlx5_ib_port_link_layer(&ibdev->ib_dev, port) ==
4626 					    IB_LINK_LAYER_ETHERNET)
4627 			schedule_work(&ibdev->delay_drop.delay_drop_work);
4628 		break;
4629 	default: /* do nothing */
4630 		return;
4631 	}
4632 }
4633 
4634 static int handle_port_change(struct mlx5_ib_dev *ibdev, struct mlx5_eqe *eqe,
4635 			      struct ib_event *ibev)
4636 {
4637 	u8 port = (eqe->data.port.port >> 4) & 0xf;
4638 
4639 	ibev->element.port_num = port;
4640 
4641 	switch (eqe->sub_type) {
4642 	case MLX5_PORT_CHANGE_SUBTYPE_ACTIVE:
4643 	case MLX5_PORT_CHANGE_SUBTYPE_DOWN:
4644 	case MLX5_PORT_CHANGE_SUBTYPE_INITIALIZED:
4645 		/* In RoCE, port up/down events are handled in
4646 		 * mlx5_netdev_event().
4647 		 */
4648 		if (mlx5_ib_port_link_layer(&ibdev->ib_dev, port) ==
4649 					    IB_LINK_LAYER_ETHERNET)
4650 			return -EINVAL;
4651 
4652 		ibev->event = (eqe->sub_type == MLX5_PORT_CHANGE_SUBTYPE_ACTIVE) ?
4653 				IB_EVENT_PORT_ACTIVE : IB_EVENT_PORT_ERR;
4654 		break;
4655 
4656 	case MLX5_PORT_CHANGE_SUBTYPE_LID:
4657 		ibev->event = IB_EVENT_LID_CHANGE;
4658 		break;
4659 
4660 	case MLX5_PORT_CHANGE_SUBTYPE_PKEY:
4661 		ibev->event = IB_EVENT_PKEY_CHANGE;
4662 		schedule_work(&ibdev->devr.ports[port - 1].pkey_change_work);
4663 		break;
4664 
4665 	case MLX5_PORT_CHANGE_SUBTYPE_GUID:
4666 		ibev->event = IB_EVENT_GID_CHANGE;
4667 		break;
4668 
4669 	case MLX5_PORT_CHANGE_SUBTYPE_CLIENT_REREG:
4670 		ibev->event = IB_EVENT_CLIENT_REREGISTER;
4671 		break;
4672 	default:
4673 		return -EINVAL;
4674 	}
4675 
4676 	return 0;
4677 }
4678 
4679 static void mlx5_ib_handle_event(struct work_struct *_work)
4680 {
4681 	struct mlx5_ib_event_work *work =
4682 		container_of(_work, struct mlx5_ib_event_work, work);
4683 	struct mlx5_ib_dev *ibdev;
4684 	struct ib_event ibev;
4685 	bool fatal = false;
4686 
4687 	if (work->is_slave) {
4688 		ibdev = mlx5_ib_get_ibdev_from_mpi(work->mpi);
4689 		if (!ibdev)
4690 			goto out;
4691 	} else {
4692 		ibdev = work->dev;
4693 	}
4694 
4695 	switch (work->event) {
4696 	case MLX5_DEV_EVENT_SYS_ERROR:
4697 		ibev.event = IB_EVENT_DEVICE_FATAL;
4698 		mlx5_ib_handle_internal_error(ibdev);
4699 		ibev.element.port_num  = (u8)(unsigned long)work->param;
4700 		fatal = true;
4701 		break;
4702 	case MLX5_EVENT_TYPE_PORT_CHANGE:
4703 		if (handle_port_change(ibdev, work->param, &ibev))
4704 			goto out;
4705 		break;
4706 	case MLX5_EVENT_TYPE_GENERAL_EVENT:
4707 		handle_general_event(ibdev, work->param, &ibev);
4708 		/* fall through */
4709 	default:
4710 		goto out;
4711 	}
4712 
4713 	ibev.device = &ibdev->ib_dev;
4714 
4715 	if (!rdma_is_port_valid(&ibdev->ib_dev, ibev.element.port_num)) {
4716 		mlx5_ib_warn(ibdev, "warning: event on port %d\n",  ibev.element.port_num);
4717 		goto out;
4718 	}
4719 
4720 	if (ibdev->ib_active)
4721 		ib_dispatch_event(&ibev);
4722 
4723 	if (fatal)
4724 		ibdev->ib_active = false;
4725 out:
4726 	kfree(work);
4727 }
4728 
4729 static int mlx5_ib_event(struct notifier_block *nb,
4730 			 unsigned long event, void *param)
4731 {
4732 	struct mlx5_ib_event_work *work;
4733 
4734 	work = kmalloc(sizeof(*work), GFP_ATOMIC);
4735 	if (!work)
4736 		return NOTIFY_DONE;
4737 
4738 	INIT_WORK(&work->work, mlx5_ib_handle_event);
4739 	work->dev = container_of(nb, struct mlx5_ib_dev, mdev_events);
4740 	work->is_slave = false;
4741 	work->param = param;
4742 	work->event = event;
4743 
4744 	queue_work(mlx5_ib_event_wq, &work->work);
4745 
4746 	return NOTIFY_OK;
4747 }
4748 
4749 static int mlx5_ib_event_slave_port(struct notifier_block *nb,
4750 				    unsigned long event, void *param)
4751 {
4752 	struct mlx5_ib_event_work *work;
4753 
4754 	work = kmalloc(sizeof(*work), GFP_ATOMIC);
4755 	if (!work)
4756 		return NOTIFY_DONE;
4757 
4758 	INIT_WORK(&work->work, mlx5_ib_handle_event);
4759 	work->mpi = container_of(nb, struct mlx5_ib_multiport_info, mdev_events);
4760 	work->is_slave = true;
4761 	work->param = param;
4762 	work->event = event;
4763 	queue_work(mlx5_ib_event_wq, &work->work);
4764 
4765 	return NOTIFY_OK;
4766 }
4767 
4768 static int set_has_smi_cap(struct mlx5_ib_dev *dev)
4769 {
4770 	struct mlx5_hca_vport_context vport_ctx;
4771 	int err;
4772 	int port;
4773 
4774 	for (port = 1; port <= ARRAY_SIZE(dev->mdev->port_caps); port++) {
4775 		dev->mdev->port_caps[port - 1].has_smi = false;
4776 		if (MLX5_CAP_GEN(dev->mdev, port_type) ==
4777 		    MLX5_CAP_PORT_TYPE_IB) {
4778 			if (MLX5_CAP_GEN(dev->mdev, ib_virt)) {
4779 				err = mlx5_query_hca_vport_context(dev->mdev, 0,
4780 								   port, 0,
4781 								   &vport_ctx);
4782 				if (err) {
4783 					mlx5_ib_err(dev, "query_hca_vport_context for port=%d failed %d\n",
4784 						    port, err);
4785 					return err;
4786 				}
4787 				dev->mdev->port_caps[port - 1].has_smi =
4788 					vport_ctx.has_smi;
4789 			} else {
4790 				dev->mdev->port_caps[port - 1].has_smi = true;
4791 			}
4792 		}
4793 	}
4794 	return 0;
4795 }
4796 
4797 static void get_ext_port_caps(struct mlx5_ib_dev *dev)
4798 {
4799 	int port;
4800 
4801 	for (port = 1; port <= dev->num_ports; port++)
4802 		mlx5_query_ext_port_caps(dev, port);
4803 }
4804 
4805 static int __get_port_caps(struct mlx5_ib_dev *dev, u8 port)
4806 {
4807 	struct ib_device_attr *dprops = NULL;
4808 	struct ib_port_attr *pprops = NULL;
4809 	int err = -ENOMEM;
4810 
4811 	pprops = kzalloc(sizeof(*pprops), GFP_KERNEL);
4812 	if (!pprops)
4813 		goto out;
4814 
4815 	dprops = kmalloc(sizeof(*dprops), GFP_KERNEL);
4816 	if (!dprops)
4817 		goto out;
4818 
4819 	err = mlx5_ib_query_device(&dev->ib_dev, dprops, NULL);
4820 	if (err) {
4821 		mlx5_ib_warn(dev, "query_device failed %d\n", err);
4822 		goto out;
4823 	}
4824 
4825 	err = mlx5_ib_query_port(&dev->ib_dev, port, pprops);
4826 	if (err) {
4827 		mlx5_ib_warn(dev, "query_port %d failed %d\n",
4828 			     port, err);
4829 		goto out;
4830 	}
4831 
4832 	dev->mdev->port_caps[port - 1].pkey_table_len =
4833 					dprops->max_pkeys;
4834 	dev->mdev->port_caps[port - 1].gid_table_len =
4835 					pprops->gid_tbl_len;
4836 	mlx5_ib_dbg(dev, "port %d: pkey_table_len %d, gid_table_len %d\n",
4837 		    port, dprops->max_pkeys, pprops->gid_tbl_len);
4838 
4839 out:
4840 	kfree(pprops);
4841 	kfree(dprops);
4842 
4843 	return err;
4844 }
4845 
4846 static int get_port_caps(struct mlx5_ib_dev *dev, u8 port)
4847 {
4848 	/* For representors use port 1, is this is the only native
4849 	 * port
4850 	 */
4851 	if (dev->is_rep)
4852 		return __get_port_caps(dev, 1);
4853 	return __get_port_caps(dev, port);
4854 }
4855 
4856 static void destroy_umrc_res(struct mlx5_ib_dev *dev)
4857 {
4858 	int err;
4859 
4860 	err = mlx5_mr_cache_cleanup(dev);
4861 	if (err)
4862 		mlx5_ib_warn(dev, "mr cache cleanup failed\n");
4863 
4864 	if (dev->umrc.qp)
4865 		mlx5_ib_destroy_qp(dev->umrc.qp, NULL);
4866 	if (dev->umrc.cq)
4867 		ib_free_cq(dev->umrc.cq);
4868 	if (dev->umrc.pd)
4869 		ib_dealloc_pd(dev->umrc.pd);
4870 }
4871 
4872 enum {
4873 	MAX_UMR_WR = 128,
4874 };
4875 
4876 static int create_umr_res(struct mlx5_ib_dev *dev)
4877 {
4878 	struct ib_qp_init_attr *init_attr = NULL;
4879 	struct ib_qp_attr *attr = NULL;
4880 	struct ib_pd *pd;
4881 	struct ib_cq *cq;
4882 	struct ib_qp *qp;
4883 	int ret;
4884 
4885 	attr = kzalloc(sizeof(*attr), GFP_KERNEL);
4886 	init_attr = kzalloc(sizeof(*init_attr), GFP_KERNEL);
4887 	if (!attr || !init_attr) {
4888 		ret = -ENOMEM;
4889 		goto error_0;
4890 	}
4891 
4892 	pd = ib_alloc_pd(&dev->ib_dev, 0);
4893 	if (IS_ERR(pd)) {
4894 		mlx5_ib_dbg(dev, "Couldn't create PD for sync UMR QP\n");
4895 		ret = PTR_ERR(pd);
4896 		goto error_0;
4897 	}
4898 
4899 	cq = ib_alloc_cq(&dev->ib_dev, NULL, 128, 0, IB_POLL_SOFTIRQ);
4900 	if (IS_ERR(cq)) {
4901 		mlx5_ib_dbg(dev, "Couldn't create CQ for sync UMR QP\n");
4902 		ret = PTR_ERR(cq);
4903 		goto error_2;
4904 	}
4905 
4906 	init_attr->send_cq = cq;
4907 	init_attr->recv_cq = cq;
4908 	init_attr->sq_sig_type = IB_SIGNAL_ALL_WR;
4909 	init_attr->cap.max_send_wr = MAX_UMR_WR;
4910 	init_attr->cap.max_send_sge = 1;
4911 	init_attr->qp_type = MLX5_IB_QPT_REG_UMR;
4912 	init_attr->port_num = 1;
4913 	qp = mlx5_ib_create_qp(pd, init_attr, NULL);
4914 	if (IS_ERR(qp)) {
4915 		mlx5_ib_dbg(dev, "Couldn't create sync UMR QP\n");
4916 		ret = PTR_ERR(qp);
4917 		goto error_3;
4918 	}
4919 	qp->device     = &dev->ib_dev;
4920 	qp->real_qp    = qp;
4921 	qp->uobject    = NULL;
4922 	qp->qp_type    = MLX5_IB_QPT_REG_UMR;
4923 	qp->send_cq    = init_attr->send_cq;
4924 	qp->recv_cq    = init_attr->recv_cq;
4925 
4926 	attr->qp_state = IB_QPS_INIT;
4927 	attr->port_num = 1;
4928 	ret = mlx5_ib_modify_qp(qp, attr, IB_QP_STATE | IB_QP_PKEY_INDEX |
4929 				IB_QP_PORT, NULL);
4930 	if (ret) {
4931 		mlx5_ib_dbg(dev, "Couldn't modify UMR QP\n");
4932 		goto error_4;
4933 	}
4934 
4935 	memset(attr, 0, sizeof(*attr));
4936 	attr->qp_state = IB_QPS_RTR;
4937 	attr->path_mtu = IB_MTU_256;
4938 
4939 	ret = mlx5_ib_modify_qp(qp, attr, IB_QP_STATE, NULL);
4940 	if (ret) {
4941 		mlx5_ib_dbg(dev, "Couldn't modify umr QP to rtr\n");
4942 		goto error_4;
4943 	}
4944 
4945 	memset(attr, 0, sizeof(*attr));
4946 	attr->qp_state = IB_QPS_RTS;
4947 	ret = mlx5_ib_modify_qp(qp, attr, IB_QP_STATE, NULL);
4948 	if (ret) {
4949 		mlx5_ib_dbg(dev, "Couldn't modify umr QP to rts\n");
4950 		goto error_4;
4951 	}
4952 
4953 	dev->umrc.qp = qp;
4954 	dev->umrc.cq = cq;
4955 	dev->umrc.pd = pd;
4956 
4957 	sema_init(&dev->umrc.sem, MAX_UMR_WR);
4958 	ret = mlx5_mr_cache_init(dev);
4959 	if (ret) {
4960 		mlx5_ib_warn(dev, "mr cache init failed %d\n", ret);
4961 		goto error_4;
4962 	}
4963 
4964 	kfree(attr);
4965 	kfree(init_attr);
4966 
4967 	return 0;
4968 
4969 error_4:
4970 	mlx5_ib_destroy_qp(qp, NULL);
4971 	dev->umrc.qp = NULL;
4972 
4973 error_3:
4974 	ib_free_cq(cq);
4975 	dev->umrc.cq = NULL;
4976 
4977 error_2:
4978 	ib_dealloc_pd(pd);
4979 	dev->umrc.pd = NULL;
4980 
4981 error_0:
4982 	kfree(attr);
4983 	kfree(init_attr);
4984 	return ret;
4985 }
4986 
4987 static u8 mlx5_get_umr_fence(u8 umr_fence_cap)
4988 {
4989 	switch (umr_fence_cap) {
4990 	case MLX5_CAP_UMR_FENCE_NONE:
4991 		return MLX5_FENCE_MODE_NONE;
4992 	case MLX5_CAP_UMR_FENCE_SMALL:
4993 		return MLX5_FENCE_MODE_INITIATOR_SMALL;
4994 	default:
4995 		return MLX5_FENCE_MODE_STRONG_ORDERING;
4996 	}
4997 }
4998 
4999 static int create_dev_resources(struct mlx5_ib_resources *devr)
5000 {
5001 	struct ib_srq_init_attr attr;
5002 	struct mlx5_ib_dev *dev;
5003 	struct ib_device *ibdev;
5004 	struct ib_cq_init_attr cq_attr = {.cqe = 1};
5005 	int port;
5006 	int ret = 0;
5007 
5008 	dev = container_of(devr, struct mlx5_ib_dev, devr);
5009 	ibdev = &dev->ib_dev;
5010 
5011 	mutex_init(&devr->mutex);
5012 
5013 	devr->p0 = rdma_zalloc_drv_obj(ibdev, ib_pd);
5014 	if (!devr->p0)
5015 		return -ENOMEM;
5016 
5017 	devr->p0->device  = ibdev;
5018 	devr->p0->uobject = NULL;
5019 	atomic_set(&devr->p0->usecnt, 0);
5020 
5021 	ret = mlx5_ib_alloc_pd(devr->p0, NULL);
5022 	if (ret)
5023 		goto error0;
5024 
5025 	devr->c0 = rdma_zalloc_drv_obj(ibdev, ib_cq);
5026 	if (!devr->c0) {
5027 		ret = -ENOMEM;
5028 		goto error1;
5029 	}
5030 
5031 	devr->c0->device = &dev->ib_dev;
5032 	atomic_set(&devr->c0->usecnt, 0);
5033 
5034 	ret = mlx5_ib_create_cq(devr->c0, &cq_attr, NULL);
5035 	if (ret)
5036 		goto err_create_cq;
5037 
5038 	devr->x0 = mlx5_ib_alloc_xrcd(&dev->ib_dev, NULL);
5039 	if (IS_ERR(devr->x0)) {
5040 		ret = PTR_ERR(devr->x0);
5041 		goto error2;
5042 	}
5043 	devr->x0->device = &dev->ib_dev;
5044 	devr->x0->inode = NULL;
5045 	atomic_set(&devr->x0->usecnt, 0);
5046 	mutex_init(&devr->x0->tgt_qp_mutex);
5047 	INIT_LIST_HEAD(&devr->x0->tgt_qp_list);
5048 
5049 	devr->x1 = mlx5_ib_alloc_xrcd(&dev->ib_dev, NULL);
5050 	if (IS_ERR(devr->x1)) {
5051 		ret = PTR_ERR(devr->x1);
5052 		goto error3;
5053 	}
5054 	devr->x1->device = &dev->ib_dev;
5055 	devr->x1->inode = NULL;
5056 	atomic_set(&devr->x1->usecnt, 0);
5057 	mutex_init(&devr->x1->tgt_qp_mutex);
5058 	INIT_LIST_HEAD(&devr->x1->tgt_qp_list);
5059 
5060 	memset(&attr, 0, sizeof(attr));
5061 	attr.attr.max_sge = 1;
5062 	attr.attr.max_wr = 1;
5063 	attr.srq_type = IB_SRQT_XRC;
5064 	attr.ext.cq = devr->c0;
5065 	attr.ext.xrc.xrcd = devr->x0;
5066 
5067 	devr->s0 = rdma_zalloc_drv_obj(ibdev, ib_srq);
5068 	if (!devr->s0) {
5069 		ret = -ENOMEM;
5070 		goto error4;
5071 	}
5072 
5073 	devr->s0->device	= &dev->ib_dev;
5074 	devr->s0->pd		= devr->p0;
5075 	devr->s0->srq_type      = IB_SRQT_XRC;
5076 	devr->s0->ext.xrc.xrcd	= devr->x0;
5077 	devr->s0->ext.cq	= devr->c0;
5078 	ret = mlx5_ib_create_srq(devr->s0, &attr, NULL);
5079 	if (ret)
5080 		goto err_create;
5081 
5082 	atomic_inc(&devr->s0->ext.xrc.xrcd->usecnt);
5083 	atomic_inc(&devr->s0->ext.cq->usecnt);
5084 	atomic_inc(&devr->p0->usecnt);
5085 	atomic_set(&devr->s0->usecnt, 0);
5086 
5087 	memset(&attr, 0, sizeof(attr));
5088 	attr.attr.max_sge = 1;
5089 	attr.attr.max_wr = 1;
5090 	attr.srq_type = IB_SRQT_BASIC;
5091 	devr->s1 = rdma_zalloc_drv_obj(ibdev, ib_srq);
5092 	if (!devr->s1) {
5093 		ret = -ENOMEM;
5094 		goto error5;
5095 	}
5096 
5097 	devr->s1->device	= &dev->ib_dev;
5098 	devr->s1->pd		= devr->p0;
5099 	devr->s1->srq_type      = IB_SRQT_BASIC;
5100 	devr->s1->ext.cq	= devr->c0;
5101 
5102 	ret = mlx5_ib_create_srq(devr->s1, &attr, NULL);
5103 	if (ret)
5104 		goto error6;
5105 
5106 	atomic_inc(&devr->p0->usecnt);
5107 	atomic_set(&devr->s1->usecnt, 0);
5108 
5109 	for (port = 0; port < ARRAY_SIZE(devr->ports); ++port) {
5110 		INIT_WORK(&devr->ports[port].pkey_change_work,
5111 			  pkey_change_handler);
5112 		devr->ports[port].devr = devr;
5113 	}
5114 
5115 	return 0;
5116 
5117 error6:
5118 	kfree(devr->s1);
5119 error5:
5120 	mlx5_ib_destroy_srq(devr->s0, NULL);
5121 err_create:
5122 	kfree(devr->s0);
5123 error4:
5124 	mlx5_ib_dealloc_xrcd(devr->x1, NULL);
5125 error3:
5126 	mlx5_ib_dealloc_xrcd(devr->x0, NULL);
5127 error2:
5128 	mlx5_ib_destroy_cq(devr->c0, NULL);
5129 err_create_cq:
5130 	kfree(devr->c0);
5131 error1:
5132 	mlx5_ib_dealloc_pd(devr->p0, NULL);
5133 error0:
5134 	kfree(devr->p0);
5135 	return ret;
5136 }
5137 
5138 static void destroy_dev_resources(struct mlx5_ib_resources *devr)
5139 {
5140 	int port;
5141 
5142 	mlx5_ib_destroy_srq(devr->s1, NULL);
5143 	kfree(devr->s1);
5144 	mlx5_ib_destroy_srq(devr->s0, NULL);
5145 	kfree(devr->s0);
5146 	mlx5_ib_dealloc_xrcd(devr->x0, NULL);
5147 	mlx5_ib_dealloc_xrcd(devr->x1, NULL);
5148 	mlx5_ib_destroy_cq(devr->c0, NULL);
5149 	kfree(devr->c0);
5150 	mlx5_ib_dealloc_pd(devr->p0, NULL);
5151 	kfree(devr->p0);
5152 
5153 	/* Make sure no change P_Key work items are still executing */
5154 	for (port = 0; port < ARRAY_SIZE(devr->ports); ++port)
5155 		cancel_work_sync(&devr->ports[port].pkey_change_work);
5156 }
5157 
5158 static u32 get_core_cap_flags(struct ib_device *ibdev,
5159 			      struct mlx5_hca_vport_context *rep)
5160 {
5161 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
5162 	enum rdma_link_layer ll = mlx5_ib_port_link_layer(ibdev, 1);
5163 	u8 l3_type_cap = MLX5_CAP_ROCE(dev->mdev, l3_type);
5164 	u8 roce_version_cap = MLX5_CAP_ROCE(dev->mdev, roce_version);
5165 	bool raw_support = !mlx5_core_mp_enabled(dev->mdev);
5166 	u32 ret = 0;
5167 
5168 	if (rep->grh_required)
5169 		ret |= RDMA_CORE_CAP_IB_GRH_REQUIRED;
5170 
5171 	if (ll == IB_LINK_LAYER_INFINIBAND)
5172 		return ret | RDMA_CORE_PORT_IBA_IB;
5173 
5174 	if (raw_support)
5175 		ret |= RDMA_CORE_PORT_RAW_PACKET;
5176 
5177 	if (!(l3_type_cap & MLX5_ROCE_L3_TYPE_IPV4_CAP))
5178 		return ret;
5179 
5180 	if (!(l3_type_cap & MLX5_ROCE_L3_TYPE_IPV6_CAP))
5181 		return ret;
5182 
5183 	if (roce_version_cap & MLX5_ROCE_VERSION_1_CAP)
5184 		ret |= RDMA_CORE_PORT_IBA_ROCE;
5185 
5186 	if (roce_version_cap & MLX5_ROCE_VERSION_2_CAP)
5187 		ret |= RDMA_CORE_PORT_IBA_ROCE_UDP_ENCAP;
5188 
5189 	return ret;
5190 }
5191 
5192 static int mlx5_port_immutable(struct ib_device *ibdev, u8 port_num,
5193 			       struct ib_port_immutable *immutable)
5194 {
5195 	struct ib_port_attr attr;
5196 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
5197 	enum rdma_link_layer ll = mlx5_ib_port_link_layer(ibdev, port_num);
5198 	struct mlx5_hca_vport_context rep = {0};
5199 	int err;
5200 
5201 	err = ib_query_port(ibdev, port_num, &attr);
5202 	if (err)
5203 		return err;
5204 
5205 	if (ll == IB_LINK_LAYER_INFINIBAND) {
5206 		err = mlx5_query_hca_vport_context(dev->mdev, 0, port_num, 0,
5207 						   &rep);
5208 		if (err)
5209 			return err;
5210 	}
5211 
5212 	immutable->pkey_tbl_len = attr.pkey_tbl_len;
5213 	immutable->gid_tbl_len = attr.gid_tbl_len;
5214 	immutable->core_cap_flags = get_core_cap_flags(ibdev, &rep);
5215 	immutable->max_mad_size = IB_MGMT_MAD_SIZE;
5216 
5217 	return 0;
5218 }
5219 
5220 static int mlx5_port_rep_immutable(struct ib_device *ibdev, u8 port_num,
5221 				   struct ib_port_immutable *immutable)
5222 {
5223 	struct ib_port_attr attr;
5224 	int err;
5225 
5226 	immutable->core_cap_flags = RDMA_CORE_PORT_RAW_PACKET;
5227 
5228 	err = ib_query_port(ibdev, port_num, &attr);
5229 	if (err)
5230 		return err;
5231 
5232 	immutable->pkey_tbl_len = attr.pkey_tbl_len;
5233 	immutable->gid_tbl_len = attr.gid_tbl_len;
5234 	immutable->core_cap_flags = RDMA_CORE_PORT_RAW_PACKET;
5235 
5236 	return 0;
5237 }
5238 
5239 static void get_dev_fw_str(struct ib_device *ibdev, char *str)
5240 {
5241 	struct mlx5_ib_dev *dev =
5242 		container_of(ibdev, struct mlx5_ib_dev, ib_dev);
5243 	snprintf(str, IB_FW_VERSION_NAME_MAX, "%d.%d.%04d",
5244 		 fw_rev_maj(dev->mdev), fw_rev_min(dev->mdev),
5245 		 fw_rev_sub(dev->mdev));
5246 }
5247 
5248 static int mlx5_eth_lag_init(struct mlx5_ib_dev *dev)
5249 {
5250 	struct mlx5_core_dev *mdev = dev->mdev;
5251 	struct mlx5_flow_namespace *ns = mlx5_get_flow_namespace(mdev,
5252 								 MLX5_FLOW_NAMESPACE_LAG);
5253 	struct mlx5_flow_table *ft;
5254 	int err;
5255 
5256 	if (!ns || !mlx5_lag_is_roce(mdev))
5257 		return 0;
5258 
5259 	err = mlx5_cmd_create_vport_lag(mdev);
5260 	if (err)
5261 		return err;
5262 
5263 	ft = mlx5_create_lag_demux_flow_table(ns, 0, 0);
5264 	if (IS_ERR(ft)) {
5265 		err = PTR_ERR(ft);
5266 		goto err_destroy_vport_lag;
5267 	}
5268 
5269 	dev->flow_db->lag_demux_ft = ft;
5270 	dev->lag_active = true;
5271 	return 0;
5272 
5273 err_destroy_vport_lag:
5274 	mlx5_cmd_destroy_vport_lag(mdev);
5275 	return err;
5276 }
5277 
5278 static void mlx5_eth_lag_cleanup(struct mlx5_ib_dev *dev)
5279 {
5280 	struct mlx5_core_dev *mdev = dev->mdev;
5281 
5282 	if (dev->lag_active) {
5283 		dev->lag_active = false;
5284 
5285 		mlx5_destroy_flow_table(dev->flow_db->lag_demux_ft);
5286 		dev->flow_db->lag_demux_ft = NULL;
5287 
5288 		mlx5_cmd_destroy_vport_lag(mdev);
5289 	}
5290 }
5291 
5292 static int mlx5_add_netdev_notifier(struct mlx5_ib_dev *dev, u8 port_num)
5293 {
5294 	int err;
5295 
5296 	dev->port[port_num].roce.nb.notifier_call = mlx5_netdev_event;
5297 	err = register_netdevice_notifier(&dev->port[port_num].roce.nb);
5298 	if (err) {
5299 		dev->port[port_num].roce.nb.notifier_call = NULL;
5300 		return err;
5301 	}
5302 
5303 	return 0;
5304 }
5305 
5306 static void mlx5_remove_netdev_notifier(struct mlx5_ib_dev *dev, u8 port_num)
5307 {
5308 	if (dev->port[port_num].roce.nb.notifier_call) {
5309 		unregister_netdevice_notifier(&dev->port[port_num].roce.nb);
5310 		dev->port[port_num].roce.nb.notifier_call = NULL;
5311 	}
5312 }
5313 
5314 static int mlx5_enable_eth(struct mlx5_ib_dev *dev)
5315 {
5316 	int err;
5317 
5318 	err = mlx5_nic_vport_enable_roce(dev->mdev);
5319 	if (err)
5320 		return err;
5321 
5322 	err = mlx5_eth_lag_init(dev);
5323 	if (err)
5324 		goto err_disable_roce;
5325 
5326 	return 0;
5327 
5328 err_disable_roce:
5329 	mlx5_nic_vport_disable_roce(dev->mdev);
5330 
5331 	return err;
5332 }
5333 
5334 static void mlx5_disable_eth(struct mlx5_ib_dev *dev)
5335 {
5336 	mlx5_eth_lag_cleanup(dev);
5337 	mlx5_nic_vport_disable_roce(dev->mdev);
5338 }
5339 
5340 struct mlx5_ib_counter {
5341 	const char *name;
5342 	size_t offset;
5343 };
5344 
5345 #define INIT_Q_COUNTER(_name)		\
5346 	{ .name = #_name, .offset = MLX5_BYTE_OFF(query_q_counter_out, _name)}
5347 
5348 static const struct mlx5_ib_counter basic_q_cnts[] = {
5349 	INIT_Q_COUNTER(rx_write_requests),
5350 	INIT_Q_COUNTER(rx_read_requests),
5351 	INIT_Q_COUNTER(rx_atomic_requests),
5352 	INIT_Q_COUNTER(out_of_buffer),
5353 };
5354 
5355 static const struct mlx5_ib_counter out_of_seq_q_cnts[] = {
5356 	INIT_Q_COUNTER(out_of_sequence),
5357 };
5358 
5359 static const struct mlx5_ib_counter retrans_q_cnts[] = {
5360 	INIT_Q_COUNTER(duplicate_request),
5361 	INIT_Q_COUNTER(rnr_nak_retry_err),
5362 	INIT_Q_COUNTER(packet_seq_err),
5363 	INIT_Q_COUNTER(implied_nak_seq_err),
5364 	INIT_Q_COUNTER(local_ack_timeout_err),
5365 };
5366 
5367 #define INIT_CONG_COUNTER(_name)		\
5368 	{ .name = #_name, .offset =	\
5369 		MLX5_BYTE_OFF(query_cong_statistics_out, _name ## _high)}
5370 
5371 static const struct mlx5_ib_counter cong_cnts[] = {
5372 	INIT_CONG_COUNTER(rp_cnp_ignored),
5373 	INIT_CONG_COUNTER(rp_cnp_handled),
5374 	INIT_CONG_COUNTER(np_ecn_marked_roce_packets),
5375 	INIT_CONG_COUNTER(np_cnp_sent),
5376 };
5377 
5378 static const struct mlx5_ib_counter extended_err_cnts[] = {
5379 	INIT_Q_COUNTER(resp_local_length_error),
5380 	INIT_Q_COUNTER(resp_cqe_error),
5381 	INIT_Q_COUNTER(req_cqe_error),
5382 	INIT_Q_COUNTER(req_remote_invalid_request),
5383 	INIT_Q_COUNTER(req_remote_access_errors),
5384 	INIT_Q_COUNTER(resp_remote_access_errors),
5385 	INIT_Q_COUNTER(resp_cqe_flush_error),
5386 	INIT_Q_COUNTER(req_cqe_flush_error),
5387 };
5388 
5389 static const struct mlx5_ib_counter roce_accl_cnts[] = {
5390 	INIT_Q_COUNTER(roce_adp_retrans),
5391 	INIT_Q_COUNTER(roce_adp_retrans_to),
5392 	INIT_Q_COUNTER(roce_slow_restart),
5393 	INIT_Q_COUNTER(roce_slow_restart_cnps),
5394 	INIT_Q_COUNTER(roce_slow_restart_trans),
5395 };
5396 
5397 #define INIT_EXT_PPCNT_COUNTER(_name)		\
5398 	{ .name = #_name, .offset =	\
5399 	MLX5_BYTE_OFF(ppcnt_reg, \
5400 		      counter_set.eth_extended_cntrs_grp_data_layout._name##_high)}
5401 
5402 static const struct mlx5_ib_counter ext_ppcnt_cnts[] = {
5403 	INIT_EXT_PPCNT_COUNTER(rx_icrc_encapsulated),
5404 };
5405 
5406 static bool is_mdev_switchdev_mode(const struct mlx5_core_dev *mdev)
5407 {
5408 	return MLX5_ESWITCH_MANAGER(mdev) &&
5409 	       mlx5_ib_eswitch_mode(mdev->priv.eswitch) ==
5410 		       MLX5_ESWITCH_OFFLOADS;
5411 }
5412 
5413 static void mlx5_ib_dealloc_counters(struct mlx5_ib_dev *dev)
5414 {
5415 	u32 in[MLX5_ST_SZ_DW(dealloc_q_counter_in)] = {};
5416 	int num_cnt_ports;
5417 	int i;
5418 
5419 	num_cnt_ports = is_mdev_switchdev_mode(dev->mdev) ? 1 : dev->num_ports;
5420 
5421 	MLX5_SET(dealloc_q_counter_in, in, opcode,
5422 		 MLX5_CMD_OP_DEALLOC_Q_COUNTER);
5423 
5424 	for (i = 0; i < num_cnt_ports; i++) {
5425 		if (dev->port[i].cnts.set_id) {
5426 			MLX5_SET(dealloc_q_counter_in, in, counter_set_id,
5427 				 dev->port[i].cnts.set_id);
5428 			mlx5_cmd_exec_in(dev->mdev, dealloc_q_counter, in);
5429 		}
5430 		kfree(dev->port[i].cnts.names);
5431 		kfree(dev->port[i].cnts.offsets);
5432 	}
5433 }
5434 
5435 static int __mlx5_ib_alloc_counters(struct mlx5_ib_dev *dev,
5436 				    struct mlx5_ib_counters *cnts)
5437 {
5438 	u32 num_counters;
5439 
5440 	num_counters = ARRAY_SIZE(basic_q_cnts);
5441 
5442 	if (MLX5_CAP_GEN(dev->mdev, out_of_seq_cnt))
5443 		num_counters += ARRAY_SIZE(out_of_seq_q_cnts);
5444 
5445 	if (MLX5_CAP_GEN(dev->mdev, retransmission_q_counters))
5446 		num_counters += ARRAY_SIZE(retrans_q_cnts);
5447 
5448 	if (MLX5_CAP_GEN(dev->mdev, enhanced_error_q_counters))
5449 		num_counters += ARRAY_SIZE(extended_err_cnts);
5450 
5451 	if (MLX5_CAP_GEN(dev->mdev, roce_accl))
5452 		num_counters += ARRAY_SIZE(roce_accl_cnts);
5453 
5454 	cnts->num_q_counters = num_counters;
5455 
5456 	if (MLX5_CAP_GEN(dev->mdev, cc_query_allowed)) {
5457 		cnts->num_cong_counters = ARRAY_SIZE(cong_cnts);
5458 		num_counters += ARRAY_SIZE(cong_cnts);
5459 	}
5460 	if (MLX5_CAP_PCAM_FEATURE(dev->mdev, rx_icrc_encapsulated_counter)) {
5461 		cnts->num_ext_ppcnt_counters = ARRAY_SIZE(ext_ppcnt_cnts);
5462 		num_counters += ARRAY_SIZE(ext_ppcnt_cnts);
5463 	}
5464 	cnts->names = kcalloc(num_counters, sizeof(cnts->names), GFP_KERNEL);
5465 	if (!cnts->names)
5466 		return -ENOMEM;
5467 
5468 	cnts->offsets = kcalloc(num_counters,
5469 				sizeof(cnts->offsets), GFP_KERNEL);
5470 	if (!cnts->offsets)
5471 		goto err_names;
5472 
5473 	return 0;
5474 
5475 err_names:
5476 	kfree(cnts->names);
5477 	cnts->names = NULL;
5478 	return -ENOMEM;
5479 }
5480 
5481 static void mlx5_ib_fill_counters(struct mlx5_ib_dev *dev,
5482 				  const char **names,
5483 				  size_t *offsets)
5484 {
5485 	int i;
5486 	int j = 0;
5487 
5488 	for (i = 0; i < ARRAY_SIZE(basic_q_cnts); i++, j++) {
5489 		names[j] = basic_q_cnts[i].name;
5490 		offsets[j] = basic_q_cnts[i].offset;
5491 	}
5492 
5493 	if (MLX5_CAP_GEN(dev->mdev, out_of_seq_cnt)) {
5494 		for (i = 0; i < ARRAY_SIZE(out_of_seq_q_cnts); i++, j++) {
5495 			names[j] = out_of_seq_q_cnts[i].name;
5496 			offsets[j] = out_of_seq_q_cnts[i].offset;
5497 		}
5498 	}
5499 
5500 	if (MLX5_CAP_GEN(dev->mdev, retransmission_q_counters)) {
5501 		for (i = 0; i < ARRAY_SIZE(retrans_q_cnts); i++, j++) {
5502 			names[j] = retrans_q_cnts[i].name;
5503 			offsets[j] = retrans_q_cnts[i].offset;
5504 		}
5505 	}
5506 
5507 	if (MLX5_CAP_GEN(dev->mdev, enhanced_error_q_counters)) {
5508 		for (i = 0; i < ARRAY_SIZE(extended_err_cnts); i++, j++) {
5509 			names[j] = extended_err_cnts[i].name;
5510 			offsets[j] = extended_err_cnts[i].offset;
5511 		}
5512 	}
5513 
5514 	if (MLX5_CAP_GEN(dev->mdev, roce_accl)) {
5515 		for (i = 0; i < ARRAY_SIZE(roce_accl_cnts); i++, j++) {
5516 			names[j] = roce_accl_cnts[i].name;
5517 			offsets[j] = roce_accl_cnts[i].offset;
5518 		}
5519 	}
5520 
5521 	if (MLX5_CAP_GEN(dev->mdev, cc_query_allowed)) {
5522 		for (i = 0; i < ARRAY_SIZE(cong_cnts); i++, j++) {
5523 			names[j] = cong_cnts[i].name;
5524 			offsets[j] = cong_cnts[i].offset;
5525 		}
5526 	}
5527 
5528 	if (MLX5_CAP_PCAM_FEATURE(dev->mdev, rx_icrc_encapsulated_counter)) {
5529 		for (i = 0; i < ARRAY_SIZE(ext_ppcnt_cnts); i++, j++) {
5530 			names[j] = ext_ppcnt_cnts[i].name;
5531 			offsets[j] = ext_ppcnt_cnts[i].offset;
5532 		}
5533 	}
5534 }
5535 
5536 static int mlx5_ib_alloc_counters(struct mlx5_ib_dev *dev)
5537 {
5538 	u32 out[MLX5_ST_SZ_DW(alloc_q_counter_out)] = {};
5539 	u32 in[MLX5_ST_SZ_DW(alloc_q_counter_in)] = {};
5540 	int num_cnt_ports;
5541 	int err = 0;
5542 	int i;
5543 	bool is_shared;
5544 
5545 	MLX5_SET(alloc_q_counter_in, in, opcode, MLX5_CMD_OP_ALLOC_Q_COUNTER);
5546 	is_shared = MLX5_CAP_GEN(dev->mdev, log_max_uctx) != 0;
5547 	num_cnt_ports = is_mdev_switchdev_mode(dev->mdev) ? 1 : dev->num_ports;
5548 
5549 	for (i = 0; i < num_cnt_ports; i++) {
5550 		err = __mlx5_ib_alloc_counters(dev, &dev->port[i].cnts);
5551 		if (err)
5552 			goto err_alloc;
5553 
5554 		mlx5_ib_fill_counters(dev, dev->port[i].cnts.names,
5555 				      dev->port[i].cnts.offsets);
5556 
5557 		MLX5_SET(alloc_q_counter_in, in, uid,
5558 			 is_shared ? MLX5_SHARED_RESOURCE_UID : 0);
5559 
5560 		err = mlx5_cmd_exec_inout(dev->mdev, alloc_q_counter, in, out);
5561 		if (err) {
5562 			mlx5_ib_warn(dev,
5563 				     "couldn't allocate queue counter for port %d, err %d\n",
5564 				     i + 1, err);
5565 			goto err_alloc;
5566 		}
5567 
5568 		dev->port[i].cnts.set_id =
5569 			MLX5_GET(alloc_q_counter_out, out, counter_set_id);
5570 	}
5571 	return 0;
5572 
5573 err_alloc:
5574 	mlx5_ib_dealloc_counters(dev);
5575 	return err;
5576 }
5577 
5578 static const struct mlx5_ib_counters *get_counters(struct mlx5_ib_dev *dev,
5579 						   u8 port_num)
5580 {
5581 	return is_mdev_switchdev_mode(dev->mdev) ? &dev->port[0].cnts :
5582 						   &dev->port[port_num].cnts;
5583 }
5584 
5585 /**
5586  * mlx5_ib_get_counters_id - Returns counters id to use for device+port
5587  * @dev:	Pointer to mlx5 IB device
5588  * @port_num:	Zero based port number
5589  *
5590  * mlx5_ib_get_counters_id() Returns counters set id to use for given
5591  * device port combination in switchdev and non switchdev mode of the
5592  * parent device.
5593  */
5594 u16 mlx5_ib_get_counters_id(struct mlx5_ib_dev *dev, u8 port_num)
5595 {
5596 	const struct mlx5_ib_counters *cnts = get_counters(dev, port_num);
5597 
5598 	return cnts->set_id;
5599 }
5600 
5601 static struct rdma_hw_stats *mlx5_ib_alloc_hw_stats(struct ib_device *ibdev,
5602 						    u8 port_num)
5603 {
5604 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
5605 	const struct mlx5_ib_counters *cnts;
5606 	bool is_switchdev = is_mdev_switchdev_mode(dev->mdev);
5607 
5608 	if ((is_switchdev && port_num) || (!is_switchdev && !port_num))
5609 		return NULL;
5610 
5611 	cnts = get_counters(dev, port_num - 1);
5612 
5613 	return rdma_alloc_hw_stats_struct(cnts->names,
5614 					  cnts->num_q_counters +
5615 					  cnts->num_cong_counters +
5616 					  cnts->num_ext_ppcnt_counters,
5617 					  RDMA_HW_STATS_DEFAULT_LIFESPAN);
5618 }
5619 
5620 static int mlx5_ib_query_q_counters(struct mlx5_core_dev *mdev,
5621 				    const struct mlx5_ib_counters *cnts,
5622 				    struct rdma_hw_stats *stats,
5623 				    u16 set_id)
5624 {
5625 	u32 out[MLX5_ST_SZ_DW(query_q_counter_out)] = {};
5626 	u32 in[MLX5_ST_SZ_DW(query_q_counter_in)] = {};
5627 	__be32 val;
5628 	int ret, i;
5629 
5630 	MLX5_SET(query_q_counter_in, in, opcode, MLX5_CMD_OP_QUERY_Q_COUNTER);
5631 	MLX5_SET(query_q_counter_in, in, counter_set_id, set_id);
5632 	ret = mlx5_cmd_exec_inout(mdev, query_q_counter, in, out);
5633 	if (ret)
5634 		return ret;
5635 
5636 	for (i = 0; i < cnts->num_q_counters; i++) {
5637 		val = *(__be32 *)((void *)out + cnts->offsets[i]);
5638 		stats->value[i] = (u64)be32_to_cpu(val);
5639 	}
5640 
5641 	return 0;
5642 }
5643 
5644 static int mlx5_ib_query_ext_ppcnt_counters(struct mlx5_ib_dev *dev,
5645 					    const struct mlx5_ib_counters *cnts,
5646 					    struct rdma_hw_stats *stats)
5647 {
5648 	int offset = cnts->num_q_counters + cnts->num_cong_counters;
5649 	int sz = MLX5_ST_SZ_BYTES(ppcnt_reg);
5650 	int ret, i;
5651 	void *out;
5652 
5653 	out = kvzalloc(sz, GFP_KERNEL);
5654 	if (!out)
5655 		return -ENOMEM;
5656 
5657 	ret = mlx5_cmd_query_ext_ppcnt_counters(dev->mdev, out);
5658 	if (ret)
5659 		goto free;
5660 
5661 	for (i = 0; i < cnts->num_ext_ppcnt_counters; i++)
5662 		stats->value[i + offset] =
5663 			be64_to_cpup((__be64 *)(out +
5664 				    cnts->offsets[i + offset]));
5665 free:
5666 	kvfree(out);
5667 	return ret;
5668 }
5669 
5670 static int mlx5_ib_get_hw_stats(struct ib_device *ibdev,
5671 				struct rdma_hw_stats *stats,
5672 				u8 port_num, int index)
5673 {
5674 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
5675 	const struct mlx5_ib_counters *cnts = get_counters(dev, port_num - 1);
5676 	struct mlx5_core_dev *mdev;
5677 	int ret, num_counters;
5678 	u8 mdev_port_num;
5679 
5680 	if (!stats)
5681 		return -EINVAL;
5682 
5683 	num_counters = cnts->num_q_counters +
5684 		       cnts->num_cong_counters +
5685 		       cnts->num_ext_ppcnt_counters;
5686 
5687 	/* q_counters are per IB device, query the master mdev */
5688 	ret = mlx5_ib_query_q_counters(dev->mdev, cnts, stats, cnts->set_id);
5689 	if (ret)
5690 		return ret;
5691 
5692 	if (MLX5_CAP_PCAM_FEATURE(dev->mdev, rx_icrc_encapsulated_counter)) {
5693 		ret =  mlx5_ib_query_ext_ppcnt_counters(dev, cnts, stats);
5694 		if (ret)
5695 			return ret;
5696 	}
5697 
5698 	if (MLX5_CAP_GEN(dev->mdev, cc_query_allowed)) {
5699 		mdev = mlx5_ib_get_native_port_mdev(dev, port_num,
5700 						    &mdev_port_num);
5701 		if (!mdev) {
5702 			/* If port is not affiliated yet, its in down state
5703 			 * which doesn't have any counters yet, so it would be
5704 			 * zero. So no need to read from the HCA.
5705 			 */
5706 			goto done;
5707 		}
5708 		ret = mlx5_lag_query_cong_counters(dev->mdev,
5709 						   stats->value +
5710 						   cnts->num_q_counters,
5711 						   cnts->num_cong_counters,
5712 						   cnts->offsets +
5713 						   cnts->num_q_counters);
5714 
5715 		mlx5_ib_put_native_port_mdev(dev, port_num);
5716 		if (ret)
5717 			return ret;
5718 	}
5719 
5720 done:
5721 	return num_counters;
5722 }
5723 
5724 static struct rdma_hw_stats *
5725 mlx5_ib_counter_alloc_stats(struct rdma_counter *counter)
5726 {
5727 	struct mlx5_ib_dev *dev = to_mdev(counter->device);
5728 	const struct mlx5_ib_counters *cnts =
5729 		get_counters(dev, counter->port - 1);
5730 
5731 	return rdma_alloc_hw_stats_struct(cnts->names,
5732 					  cnts->num_q_counters +
5733 					  cnts->num_cong_counters +
5734 					  cnts->num_ext_ppcnt_counters,
5735 					  RDMA_HW_STATS_DEFAULT_LIFESPAN);
5736 }
5737 
5738 static int mlx5_ib_counter_update_stats(struct rdma_counter *counter)
5739 {
5740 	struct mlx5_ib_dev *dev = to_mdev(counter->device);
5741 	const struct mlx5_ib_counters *cnts =
5742 		get_counters(dev, counter->port - 1);
5743 
5744 	return mlx5_ib_query_q_counters(dev->mdev, cnts,
5745 					counter->stats, counter->id);
5746 }
5747 
5748 static int mlx5_ib_counter_dealloc(struct rdma_counter *counter)
5749 {
5750 	struct mlx5_ib_dev *dev = to_mdev(counter->device);
5751 	u32 in[MLX5_ST_SZ_DW(dealloc_q_counter_in)] = {};
5752 
5753 	if (!counter->id)
5754 		return 0;
5755 
5756 	MLX5_SET(dealloc_q_counter_in, in, opcode,
5757 		 MLX5_CMD_OP_DEALLOC_Q_COUNTER);
5758 	MLX5_SET(dealloc_q_counter_in, in, counter_set_id, counter->id);
5759 	return mlx5_cmd_exec_in(dev->mdev, dealloc_q_counter, in);
5760 }
5761 
5762 static int mlx5_ib_counter_bind_qp(struct rdma_counter *counter,
5763 				   struct ib_qp *qp)
5764 {
5765 	struct mlx5_ib_dev *dev = to_mdev(qp->device);
5766 	int err;
5767 
5768 	if (!counter->id) {
5769 		u32 out[MLX5_ST_SZ_DW(alloc_q_counter_out)] = {};
5770 		u32 in[MLX5_ST_SZ_DW(alloc_q_counter_in)] = {};
5771 
5772 		MLX5_SET(alloc_q_counter_in, in, opcode,
5773 			 MLX5_CMD_OP_ALLOC_Q_COUNTER);
5774 		MLX5_SET(alloc_q_counter_in, in, uid, MLX5_SHARED_RESOURCE_UID);
5775 		err = mlx5_cmd_exec_inout(dev->mdev, alloc_q_counter, in, out);
5776 		if (err)
5777 			return err;
5778 		counter->id =
5779 			MLX5_GET(alloc_q_counter_out, out, counter_set_id);
5780 	}
5781 
5782 	err = mlx5_ib_qp_set_counter(qp, counter);
5783 	if (err)
5784 		goto fail_set_counter;
5785 
5786 	return 0;
5787 
5788 fail_set_counter:
5789 	mlx5_ib_counter_dealloc(counter);
5790 	counter->id = 0;
5791 
5792 	return err;
5793 }
5794 
5795 static int mlx5_ib_counter_unbind_qp(struct ib_qp *qp)
5796 {
5797 	return mlx5_ib_qp_set_counter(qp, NULL);
5798 }
5799 
5800 static int mlx5_ib_rn_get_params(struct ib_device *device, u8 port_num,
5801 				 enum rdma_netdev_t type,
5802 				 struct rdma_netdev_alloc_params *params)
5803 {
5804 	if (type != RDMA_NETDEV_IPOIB)
5805 		return -EOPNOTSUPP;
5806 
5807 	return mlx5_rdma_rn_get_params(to_mdev(device)->mdev, device, params);
5808 }
5809 
5810 static void delay_drop_debugfs_cleanup(struct mlx5_ib_dev *dev)
5811 {
5812 	if (!dev->delay_drop.dir_debugfs)
5813 		return;
5814 	debugfs_remove_recursive(dev->delay_drop.dir_debugfs);
5815 	dev->delay_drop.dir_debugfs = NULL;
5816 }
5817 
5818 static void cancel_delay_drop(struct mlx5_ib_dev *dev)
5819 {
5820 	if (!(dev->ib_dev.attrs.raw_packet_caps & IB_RAW_PACKET_CAP_DELAY_DROP))
5821 		return;
5822 
5823 	cancel_work_sync(&dev->delay_drop.delay_drop_work);
5824 	delay_drop_debugfs_cleanup(dev);
5825 }
5826 
5827 static ssize_t delay_drop_timeout_read(struct file *filp, char __user *buf,
5828 				       size_t count, loff_t *pos)
5829 {
5830 	struct mlx5_ib_delay_drop *delay_drop = filp->private_data;
5831 	char lbuf[20];
5832 	int len;
5833 
5834 	len = snprintf(lbuf, sizeof(lbuf), "%u\n", delay_drop->timeout);
5835 	return simple_read_from_buffer(buf, count, pos, lbuf, len);
5836 }
5837 
5838 static ssize_t delay_drop_timeout_write(struct file *filp, const char __user *buf,
5839 					size_t count, loff_t *pos)
5840 {
5841 	struct mlx5_ib_delay_drop *delay_drop = filp->private_data;
5842 	u32 timeout;
5843 	u32 var;
5844 
5845 	if (kstrtouint_from_user(buf, count, 0, &var))
5846 		return -EFAULT;
5847 
5848 	timeout = min_t(u32, roundup(var, 100), MLX5_MAX_DELAY_DROP_TIMEOUT_MS *
5849 			1000);
5850 	if (timeout != var)
5851 		mlx5_ib_dbg(delay_drop->dev, "Round delay drop timeout to %u usec\n",
5852 			    timeout);
5853 
5854 	delay_drop->timeout = timeout;
5855 
5856 	return count;
5857 }
5858 
5859 static const struct file_operations fops_delay_drop_timeout = {
5860 	.owner	= THIS_MODULE,
5861 	.open	= simple_open,
5862 	.write	= delay_drop_timeout_write,
5863 	.read	= delay_drop_timeout_read,
5864 };
5865 
5866 static void delay_drop_debugfs_init(struct mlx5_ib_dev *dev)
5867 {
5868 	struct dentry *root;
5869 
5870 	if (!mlx5_debugfs_root)
5871 		return;
5872 
5873 	root = debugfs_create_dir("delay_drop", dev->mdev->priv.dbg_root);
5874 	dev->delay_drop.dir_debugfs = root;
5875 
5876 	debugfs_create_atomic_t("num_timeout_events", 0400, root,
5877 				&dev->delay_drop.events_cnt);
5878 	debugfs_create_atomic_t("num_rqs", 0400, root,
5879 				&dev->delay_drop.rqs_cnt);
5880 	debugfs_create_file("timeout", 0600, root, &dev->delay_drop,
5881 			    &fops_delay_drop_timeout);
5882 }
5883 
5884 static void init_delay_drop(struct mlx5_ib_dev *dev)
5885 {
5886 	if (!(dev->ib_dev.attrs.raw_packet_caps & IB_RAW_PACKET_CAP_DELAY_DROP))
5887 		return;
5888 
5889 	mutex_init(&dev->delay_drop.lock);
5890 	dev->delay_drop.dev = dev;
5891 	dev->delay_drop.activate = false;
5892 	dev->delay_drop.timeout = MLX5_MAX_DELAY_DROP_TIMEOUT_MS * 1000;
5893 	INIT_WORK(&dev->delay_drop.delay_drop_work, delay_drop_handler);
5894 	atomic_set(&dev->delay_drop.rqs_cnt, 0);
5895 	atomic_set(&dev->delay_drop.events_cnt, 0);
5896 
5897 	delay_drop_debugfs_init(dev);
5898 }
5899 
5900 static void mlx5_ib_unbind_slave_port(struct mlx5_ib_dev *ibdev,
5901 				      struct mlx5_ib_multiport_info *mpi)
5902 {
5903 	u8 port_num = mlx5_core_native_port_num(mpi->mdev) - 1;
5904 	struct mlx5_ib_port *port = &ibdev->port[port_num];
5905 	int comps;
5906 	int err;
5907 	int i;
5908 
5909 	lockdep_assert_held(&mlx5_ib_multiport_mutex);
5910 
5911 	mlx5_ib_cleanup_cong_debugfs(ibdev, port_num);
5912 
5913 	spin_lock(&port->mp.mpi_lock);
5914 	if (!mpi->ibdev) {
5915 		spin_unlock(&port->mp.mpi_lock);
5916 		return;
5917 	}
5918 
5919 	mpi->ibdev = NULL;
5920 
5921 	spin_unlock(&port->mp.mpi_lock);
5922 	if (mpi->mdev_events.notifier_call)
5923 		mlx5_notifier_unregister(mpi->mdev, &mpi->mdev_events);
5924 	mpi->mdev_events.notifier_call = NULL;
5925 	mlx5_remove_netdev_notifier(ibdev, port_num);
5926 	spin_lock(&port->mp.mpi_lock);
5927 
5928 	comps = mpi->mdev_refcnt;
5929 	if (comps) {
5930 		mpi->unaffiliate = true;
5931 		init_completion(&mpi->unref_comp);
5932 		spin_unlock(&port->mp.mpi_lock);
5933 
5934 		for (i = 0; i < comps; i++)
5935 			wait_for_completion(&mpi->unref_comp);
5936 
5937 		spin_lock(&port->mp.mpi_lock);
5938 		mpi->unaffiliate = false;
5939 	}
5940 
5941 	port->mp.mpi = NULL;
5942 
5943 	list_add_tail(&mpi->list, &mlx5_ib_unaffiliated_port_list);
5944 
5945 	spin_unlock(&port->mp.mpi_lock);
5946 
5947 	err = mlx5_nic_vport_unaffiliate_multiport(mpi->mdev);
5948 
5949 	mlx5_ib_dbg(ibdev, "unaffiliated port %d\n", port_num + 1);
5950 	/* Log an error, still needed to cleanup the pointers and add
5951 	 * it back to the list.
5952 	 */
5953 	if (err)
5954 		mlx5_ib_err(ibdev, "Failed to unaffiliate port %u\n",
5955 			    port_num + 1);
5956 
5957 	ibdev->port[port_num].roce.last_port_state = IB_PORT_DOWN;
5958 }
5959 
5960 static bool mlx5_ib_bind_slave_port(struct mlx5_ib_dev *ibdev,
5961 				    struct mlx5_ib_multiport_info *mpi)
5962 {
5963 	u8 port_num = mlx5_core_native_port_num(mpi->mdev) - 1;
5964 	int err;
5965 
5966 	lockdep_assert_held(&mlx5_ib_multiport_mutex);
5967 
5968 	spin_lock(&ibdev->port[port_num].mp.mpi_lock);
5969 	if (ibdev->port[port_num].mp.mpi) {
5970 		mlx5_ib_dbg(ibdev, "port %d already affiliated.\n",
5971 			    port_num + 1);
5972 		spin_unlock(&ibdev->port[port_num].mp.mpi_lock);
5973 		return false;
5974 	}
5975 
5976 	ibdev->port[port_num].mp.mpi = mpi;
5977 	mpi->ibdev = ibdev;
5978 	mpi->mdev_events.notifier_call = NULL;
5979 	spin_unlock(&ibdev->port[port_num].mp.mpi_lock);
5980 
5981 	err = mlx5_nic_vport_affiliate_multiport(ibdev->mdev, mpi->mdev);
5982 	if (err)
5983 		goto unbind;
5984 
5985 	err = get_port_caps(ibdev, mlx5_core_native_port_num(mpi->mdev));
5986 	if (err)
5987 		goto unbind;
5988 
5989 	err = mlx5_add_netdev_notifier(ibdev, port_num);
5990 	if (err) {
5991 		mlx5_ib_err(ibdev, "failed adding netdev notifier for port %u\n",
5992 			    port_num + 1);
5993 		goto unbind;
5994 	}
5995 
5996 	mpi->mdev_events.notifier_call = mlx5_ib_event_slave_port;
5997 	mlx5_notifier_register(mpi->mdev, &mpi->mdev_events);
5998 
5999 	mlx5_ib_init_cong_debugfs(ibdev, port_num);
6000 
6001 	return true;
6002 
6003 unbind:
6004 	mlx5_ib_unbind_slave_port(ibdev, mpi);
6005 	return false;
6006 }
6007 
6008 static int mlx5_ib_init_multiport_master(struct mlx5_ib_dev *dev)
6009 {
6010 	int port_num = mlx5_core_native_port_num(dev->mdev) - 1;
6011 	enum rdma_link_layer ll = mlx5_ib_port_link_layer(&dev->ib_dev,
6012 							  port_num + 1);
6013 	struct mlx5_ib_multiport_info *mpi;
6014 	int err;
6015 	int i;
6016 
6017 	if (!mlx5_core_is_mp_master(dev->mdev) || ll != IB_LINK_LAYER_ETHERNET)
6018 		return 0;
6019 
6020 	err = mlx5_query_nic_vport_system_image_guid(dev->mdev,
6021 						     &dev->sys_image_guid);
6022 	if (err)
6023 		return err;
6024 
6025 	err = mlx5_nic_vport_enable_roce(dev->mdev);
6026 	if (err)
6027 		return err;
6028 
6029 	mutex_lock(&mlx5_ib_multiport_mutex);
6030 	for (i = 0; i < dev->num_ports; i++) {
6031 		bool bound = false;
6032 
6033 		/* build a stub multiport info struct for the native port. */
6034 		if (i == port_num) {
6035 			mpi = kzalloc(sizeof(*mpi), GFP_KERNEL);
6036 			if (!mpi) {
6037 				mutex_unlock(&mlx5_ib_multiport_mutex);
6038 				mlx5_nic_vport_disable_roce(dev->mdev);
6039 				return -ENOMEM;
6040 			}
6041 
6042 			mpi->is_master = true;
6043 			mpi->mdev = dev->mdev;
6044 			mpi->sys_image_guid = dev->sys_image_guid;
6045 			dev->port[i].mp.mpi = mpi;
6046 			mpi->ibdev = dev;
6047 			mpi = NULL;
6048 			continue;
6049 		}
6050 
6051 		list_for_each_entry(mpi, &mlx5_ib_unaffiliated_port_list,
6052 				    list) {
6053 			if (dev->sys_image_guid == mpi->sys_image_guid &&
6054 			    (mlx5_core_native_port_num(mpi->mdev) - 1) == i) {
6055 				bound = mlx5_ib_bind_slave_port(dev, mpi);
6056 			}
6057 
6058 			if (bound) {
6059 				dev_dbg(mpi->mdev->device,
6060 					"removing port from unaffiliated list.\n");
6061 				mlx5_ib_dbg(dev, "port %d bound\n", i + 1);
6062 				list_del(&mpi->list);
6063 				break;
6064 			}
6065 		}
6066 		if (!bound) {
6067 			get_port_caps(dev, i + 1);
6068 			mlx5_ib_dbg(dev, "no free port found for port %d\n",
6069 				    i + 1);
6070 		}
6071 	}
6072 
6073 	list_add_tail(&dev->ib_dev_list, &mlx5_ib_dev_list);
6074 	mutex_unlock(&mlx5_ib_multiport_mutex);
6075 	return err;
6076 }
6077 
6078 static void mlx5_ib_cleanup_multiport_master(struct mlx5_ib_dev *dev)
6079 {
6080 	int port_num = mlx5_core_native_port_num(dev->mdev) - 1;
6081 	enum rdma_link_layer ll = mlx5_ib_port_link_layer(&dev->ib_dev,
6082 							  port_num + 1);
6083 	int i;
6084 
6085 	if (!mlx5_core_is_mp_master(dev->mdev) || ll != IB_LINK_LAYER_ETHERNET)
6086 		return;
6087 
6088 	mutex_lock(&mlx5_ib_multiport_mutex);
6089 	for (i = 0; i < dev->num_ports; i++) {
6090 		if (dev->port[i].mp.mpi) {
6091 			/* Destroy the native port stub */
6092 			if (i == port_num) {
6093 				kfree(dev->port[i].mp.mpi);
6094 				dev->port[i].mp.mpi = NULL;
6095 			} else {
6096 				mlx5_ib_dbg(dev, "unbinding port_num: %d\n", i + 1);
6097 				mlx5_ib_unbind_slave_port(dev, dev->port[i].mp.mpi);
6098 			}
6099 		}
6100 	}
6101 
6102 	mlx5_ib_dbg(dev, "removing from devlist\n");
6103 	list_del(&dev->ib_dev_list);
6104 	mutex_unlock(&mlx5_ib_multiport_mutex);
6105 
6106 	mlx5_nic_vport_disable_roce(dev->mdev);
6107 }
6108 
6109 static int mmap_obj_cleanup(struct ib_uobject *uobject,
6110 			    enum rdma_remove_reason why,
6111 			    struct uverbs_attr_bundle *attrs)
6112 {
6113 	struct mlx5_user_mmap_entry *obj = uobject->object;
6114 
6115 	rdma_user_mmap_entry_remove(&obj->rdma_entry);
6116 	return 0;
6117 }
6118 
6119 static int mlx5_rdma_user_mmap_entry_insert(struct mlx5_ib_ucontext *c,
6120 					    struct mlx5_user_mmap_entry *entry,
6121 					    size_t length)
6122 {
6123 	return rdma_user_mmap_entry_insert_range(
6124 		&c->ibucontext, &entry->rdma_entry, length,
6125 		(MLX5_IB_MMAP_OFFSET_START << 16),
6126 		((MLX5_IB_MMAP_OFFSET_END << 16) + (1UL << 16) - 1));
6127 }
6128 
6129 static struct mlx5_user_mmap_entry *
6130 alloc_var_entry(struct mlx5_ib_ucontext *c)
6131 {
6132 	struct mlx5_user_mmap_entry *entry;
6133 	struct mlx5_var_table *var_table;
6134 	u32 page_idx;
6135 	int err;
6136 
6137 	var_table = &to_mdev(c->ibucontext.device)->var_table;
6138 	entry = kzalloc(sizeof(*entry), GFP_KERNEL);
6139 	if (!entry)
6140 		return ERR_PTR(-ENOMEM);
6141 
6142 	mutex_lock(&var_table->bitmap_lock);
6143 	page_idx = find_first_zero_bit(var_table->bitmap,
6144 				       var_table->num_var_hw_entries);
6145 	if (page_idx >= var_table->num_var_hw_entries) {
6146 		err = -ENOSPC;
6147 		mutex_unlock(&var_table->bitmap_lock);
6148 		goto end;
6149 	}
6150 
6151 	set_bit(page_idx, var_table->bitmap);
6152 	mutex_unlock(&var_table->bitmap_lock);
6153 
6154 	entry->address = var_table->hw_start_addr +
6155 				(page_idx * var_table->stride_size);
6156 	entry->page_idx = page_idx;
6157 	entry->mmap_flag = MLX5_IB_MMAP_TYPE_VAR;
6158 
6159 	err = mlx5_rdma_user_mmap_entry_insert(c, entry,
6160 					       var_table->stride_size);
6161 	if (err)
6162 		goto err_insert;
6163 
6164 	return entry;
6165 
6166 err_insert:
6167 	mutex_lock(&var_table->bitmap_lock);
6168 	clear_bit(page_idx, var_table->bitmap);
6169 	mutex_unlock(&var_table->bitmap_lock);
6170 end:
6171 	kfree(entry);
6172 	return ERR_PTR(err);
6173 }
6174 
6175 static int UVERBS_HANDLER(MLX5_IB_METHOD_VAR_OBJ_ALLOC)(
6176 	struct uverbs_attr_bundle *attrs)
6177 {
6178 	struct ib_uobject *uobj = uverbs_attr_get_uobject(
6179 		attrs, MLX5_IB_ATTR_VAR_OBJ_ALLOC_HANDLE);
6180 	struct mlx5_ib_ucontext *c;
6181 	struct mlx5_user_mmap_entry *entry;
6182 	u64 mmap_offset;
6183 	u32 length;
6184 	int err;
6185 
6186 	c = to_mucontext(ib_uverbs_get_ucontext(attrs));
6187 	if (IS_ERR(c))
6188 		return PTR_ERR(c);
6189 
6190 	entry = alloc_var_entry(c);
6191 	if (IS_ERR(entry))
6192 		return PTR_ERR(entry);
6193 
6194 	mmap_offset = mlx5_entry_to_mmap_offset(entry);
6195 	length = entry->rdma_entry.npages * PAGE_SIZE;
6196 	uobj->object = entry;
6197 
6198 	err = uverbs_copy_to(attrs, MLX5_IB_ATTR_VAR_OBJ_ALLOC_MMAP_OFFSET,
6199 			     &mmap_offset, sizeof(mmap_offset));
6200 	if (err)
6201 		goto err;
6202 
6203 	err = uverbs_copy_to(attrs, MLX5_IB_ATTR_VAR_OBJ_ALLOC_PAGE_ID,
6204 			     &entry->page_idx, sizeof(entry->page_idx));
6205 	if (err)
6206 		goto err;
6207 
6208 	err = uverbs_copy_to(attrs, MLX5_IB_ATTR_VAR_OBJ_ALLOC_MMAP_LENGTH,
6209 			     &length, sizeof(length));
6210 	if (err)
6211 		goto err;
6212 
6213 	return 0;
6214 
6215 err:
6216 	rdma_user_mmap_entry_remove(&entry->rdma_entry);
6217 	return err;
6218 }
6219 
6220 DECLARE_UVERBS_NAMED_METHOD(
6221 	MLX5_IB_METHOD_VAR_OBJ_ALLOC,
6222 	UVERBS_ATTR_IDR(MLX5_IB_ATTR_VAR_OBJ_ALLOC_HANDLE,
6223 			MLX5_IB_OBJECT_VAR,
6224 			UVERBS_ACCESS_NEW,
6225 			UA_MANDATORY),
6226 	UVERBS_ATTR_PTR_OUT(MLX5_IB_ATTR_VAR_OBJ_ALLOC_PAGE_ID,
6227 			   UVERBS_ATTR_TYPE(u32),
6228 			   UA_MANDATORY),
6229 	UVERBS_ATTR_PTR_OUT(MLX5_IB_ATTR_VAR_OBJ_ALLOC_MMAP_LENGTH,
6230 			   UVERBS_ATTR_TYPE(u32),
6231 			   UA_MANDATORY),
6232 	UVERBS_ATTR_PTR_OUT(MLX5_IB_ATTR_VAR_OBJ_ALLOC_MMAP_OFFSET,
6233 			    UVERBS_ATTR_TYPE(u64),
6234 			    UA_MANDATORY));
6235 
6236 DECLARE_UVERBS_NAMED_METHOD_DESTROY(
6237 	MLX5_IB_METHOD_VAR_OBJ_DESTROY,
6238 	UVERBS_ATTR_IDR(MLX5_IB_ATTR_VAR_OBJ_DESTROY_HANDLE,
6239 			MLX5_IB_OBJECT_VAR,
6240 			UVERBS_ACCESS_DESTROY,
6241 			UA_MANDATORY));
6242 
6243 DECLARE_UVERBS_NAMED_OBJECT(MLX5_IB_OBJECT_VAR,
6244 			    UVERBS_TYPE_ALLOC_IDR(mmap_obj_cleanup),
6245 			    &UVERBS_METHOD(MLX5_IB_METHOD_VAR_OBJ_ALLOC),
6246 			    &UVERBS_METHOD(MLX5_IB_METHOD_VAR_OBJ_DESTROY));
6247 
6248 static bool var_is_supported(struct ib_device *device)
6249 {
6250 	struct mlx5_ib_dev *dev = to_mdev(device);
6251 
6252 	return (MLX5_CAP_GEN_64(dev->mdev, general_obj_types) &
6253 			MLX5_GENERAL_OBJ_TYPES_CAP_VIRTIO_NET_Q);
6254 }
6255 
6256 static struct mlx5_user_mmap_entry *
6257 alloc_uar_entry(struct mlx5_ib_ucontext *c,
6258 		enum mlx5_ib_uapi_uar_alloc_type alloc_type)
6259 {
6260 	struct mlx5_user_mmap_entry *entry;
6261 	struct mlx5_ib_dev *dev;
6262 	u32 uar_index;
6263 	int err;
6264 
6265 	entry = kzalloc(sizeof(*entry), GFP_KERNEL);
6266 	if (!entry)
6267 		return ERR_PTR(-ENOMEM);
6268 
6269 	dev = to_mdev(c->ibucontext.device);
6270 	err = mlx5_cmd_alloc_uar(dev->mdev, &uar_index);
6271 	if (err)
6272 		goto end;
6273 
6274 	entry->page_idx = uar_index;
6275 	entry->address = uar_index2paddress(dev, uar_index);
6276 	if (alloc_type == MLX5_IB_UAPI_UAR_ALLOC_TYPE_BF)
6277 		entry->mmap_flag = MLX5_IB_MMAP_TYPE_UAR_WC;
6278 	else
6279 		entry->mmap_flag = MLX5_IB_MMAP_TYPE_UAR_NC;
6280 
6281 	err = mlx5_rdma_user_mmap_entry_insert(c, entry, PAGE_SIZE);
6282 	if (err)
6283 		goto err_insert;
6284 
6285 	return entry;
6286 
6287 err_insert:
6288 	mlx5_cmd_free_uar(dev->mdev, uar_index);
6289 end:
6290 	kfree(entry);
6291 	return ERR_PTR(err);
6292 }
6293 
6294 static int UVERBS_HANDLER(MLX5_IB_METHOD_UAR_OBJ_ALLOC)(
6295 	struct uverbs_attr_bundle *attrs)
6296 {
6297 	struct ib_uobject *uobj = uverbs_attr_get_uobject(
6298 		attrs, MLX5_IB_ATTR_UAR_OBJ_ALLOC_HANDLE);
6299 	enum mlx5_ib_uapi_uar_alloc_type alloc_type;
6300 	struct mlx5_ib_ucontext *c;
6301 	struct mlx5_user_mmap_entry *entry;
6302 	u64 mmap_offset;
6303 	u32 length;
6304 	int err;
6305 
6306 	c = to_mucontext(ib_uverbs_get_ucontext(attrs));
6307 	if (IS_ERR(c))
6308 		return PTR_ERR(c);
6309 
6310 	err = uverbs_get_const(&alloc_type, attrs,
6311 			       MLX5_IB_ATTR_UAR_OBJ_ALLOC_TYPE);
6312 	if (err)
6313 		return err;
6314 
6315 	if (alloc_type != MLX5_IB_UAPI_UAR_ALLOC_TYPE_BF &&
6316 	    alloc_type != MLX5_IB_UAPI_UAR_ALLOC_TYPE_NC)
6317 		return -EOPNOTSUPP;
6318 
6319 	if (!to_mdev(c->ibucontext.device)->wc_support &&
6320 	    alloc_type == MLX5_IB_UAPI_UAR_ALLOC_TYPE_BF)
6321 		return -EOPNOTSUPP;
6322 
6323 	entry = alloc_uar_entry(c, alloc_type);
6324 	if (IS_ERR(entry))
6325 		return PTR_ERR(entry);
6326 
6327 	mmap_offset = mlx5_entry_to_mmap_offset(entry);
6328 	length = entry->rdma_entry.npages * PAGE_SIZE;
6329 	uobj->object = entry;
6330 
6331 	err = uverbs_copy_to(attrs, MLX5_IB_ATTR_UAR_OBJ_ALLOC_MMAP_OFFSET,
6332 			     &mmap_offset, sizeof(mmap_offset));
6333 	if (err)
6334 		goto err;
6335 
6336 	err = uverbs_copy_to(attrs, MLX5_IB_ATTR_UAR_OBJ_ALLOC_PAGE_ID,
6337 			     &entry->page_idx, sizeof(entry->page_idx));
6338 	if (err)
6339 		goto err;
6340 
6341 	err = uverbs_copy_to(attrs, MLX5_IB_ATTR_UAR_OBJ_ALLOC_MMAP_LENGTH,
6342 			     &length, sizeof(length));
6343 	if (err)
6344 		goto err;
6345 
6346 	return 0;
6347 
6348 err:
6349 	rdma_user_mmap_entry_remove(&entry->rdma_entry);
6350 	return err;
6351 }
6352 
6353 DECLARE_UVERBS_NAMED_METHOD(
6354 	MLX5_IB_METHOD_UAR_OBJ_ALLOC,
6355 	UVERBS_ATTR_IDR(MLX5_IB_ATTR_UAR_OBJ_ALLOC_HANDLE,
6356 			MLX5_IB_OBJECT_UAR,
6357 			UVERBS_ACCESS_NEW,
6358 			UA_MANDATORY),
6359 	UVERBS_ATTR_CONST_IN(MLX5_IB_ATTR_UAR_OBJ_ALLOC_TYPE,
6360 			     enum mlx5_ib_uapi_uar_alloc_type,
6361 			     UA_MANDATORY),
6362 	UVERBS_ATTR_PTR_OUT(MLX5_IB_ATTR_UAR_OBJ_ALLOC_PAGE_ID,
6363 			   UVERBS_ATTR_TYPE(u32),
6364 			   UA_MANDATORY),
6365 	UVERBS_ATTR_PTR_OUT(MLX5_IB_ATTR_UAR_OBJ_ALLOC_MMAP_LENGTH,
6366 			   UVERBS_ATTR_TYPE(u32),
6367 			   UA_MANDATORY),
6368 	UVERBS_ATTR_PTR_OUT(MLX5_IB_ATTR_UAR_OBJ_ALLOC_MMAP_OFFSET,
6369 			    UVERBS_ATTR_TYPE(u64),
6370 			    UA_MANDATORY));
6371 
6372 DECLARE_UVERBS_NAMED_METHOD_DESTROY(
6373 	MLX5_IB_METHOD_UAR_OBJ_DESTROY,
6374 	UVERBS_ATTR_IDR(MLX5_IB_ATTR_UAR_OBJ_DESTROY_HANDLE,
6375 			MLX5_IB_OBJECT_UAR,
6376 			UVERBS_ACCESS_DESTROY,
6377 			UA_MANDATORY));
6378 
6379 DECLARE_UVERBS_NAMED_OBJECT(MLX5_IB_OBJECT_UAR,
6380 			    UVERBS_TYPE_ALLOC_IDR(mmap_obj_cleanup),
6381 			    &UVERBS_METHOD(MLX5_IB_METHOD_UAR_OBJ_ALLOC),
6382 			    &UVERBS_METHOD(MLX5_IB_METHOD_UAR_OBJ_DESTROY));
6383 
6384 ADD_UVERBS_ATTRIBUTES_SIMPLE(
6385 	mlx5_ib_dm,
6386 	UVERBS_OBJECT_DM,
6387 	UVERBS_METHOD_DM_ALLOC,
6388 	UVERBS_ATTR_PTR_OUT(MLX5_IB_ATTR_ALLOC_DM_RESP_START_OFFSET,
6389 			    UVERBS_ATTR_TYPE(u64),
6390 			    UA_MANDATORY),
6391 	UVERBS_ATTR_PTR_OUT(MLX5_IB_ATTR_ALLOC_DM_RESP_PAGE_INDEX,
6392 			    UVERBS_ATTR_TYPE(u16),
6393 			    UA_OPTIONAL),
6394 	UVERBS_ATTR_CONST_IN(MLX5_IB_ATTR_ALLOC_DM_REQ_TYPE,
6395 			     enum mlx5_ib_uapi_dm_type,
6396 			     UA_OPTIONAL));
6397 
6398 ADD_UVERBS_ATTRIBUTES_SIMPLE(
6399 	mlx5_ib_flow_action,
6400 	UVERBS_OBJECT_FLOW_ACTION,
6401 	UVERBS_METHOD_FLOW_ACTION_ESP_CREATE,
6402 	UVERBS_ATTR_FLAGS_IN(MLX5_IB_ATTR_CREATE_FLOW_ACTION_FLAGS,
6403 			     enum mlx5_ib_uapi_flow_action_flags));
6404 
6405 static const struct uapi_definition mlx5_ib_defs[] = {
6406 	UAPI_DEF_CHAIN(mlx5_ib_devx_defs),
6407 	UAPI_DEF_CHAIN(mlx5_ib_flow_defs),
6408 	UAPI_DEF_CHAIN(mlx5_ib_qos_defs),
6409 
6410 	UAPI_DEF_CHAIN_OBJ_TREE(UVERBS_OBJECT_FLOW_ACTION,
6411 				&mlx5_ib_flow_action),
6412 	UAPI_DEF_CHAIN_OBJ_TREE(UVERBS_OBJECT_DM, &mlx5_ib_dm),
6413 	UAPI_DEF_CHAIN_OBJ_TREE_NAMED(MLX5_IB_OBJECT_VAR,
6414 				UAPI_DEF_IS_OBJ_SUPPORTED(var_is_supported)),
6415 	UAPI_DEF_CHAIN_OBJ_TREE_NAMED(MLX5_IB_OBJECT_UAR),
6416 	{}
6417 };
6418 
6419 static int mlx5_ib_read_counters(struct ib_counters *counters,
6420 				 struct ib_counters_read_attr *read_attr,
6421 				 struct uverbs_attr_bundle *attrs)
6422 {
6423 	struct mlx5_ib_mcounters *mcounters = to_mcounters(counters);
6424 	struct mlx5_read_counters_attr mread_attr = {};
6425 	struct mlx5_ib_flow_counters_desc *desc;
6426 	int ret, i;
6427 
6428 	mutex_lock(&mcounters->mcntrs_mutex);
6429 	if (mcounters->cntrs_max_index > read_attr->ncounters) {
6430 		ret = -EINVAL;
6431 		goto err_bound;
6432 	}
6433 
6434 	mread_attr.out = kcalloc(mcounters->counters_num, sizeof(u64),
6435 				 GFP_KERNEL);
6436 	if (!mread_attr.out) {
6437 		ret = -ENOMEM;
6438 		goto err_bound;
6439 	}
6440 
6441 	mread_attr.hw_cntrs_hndl = mcounters->hw_cntrs_hndl;
6442 	mread_attr.flags = read_attr->flags;
6443 	ret = mcounters->read_counters(counters->device, &mread_attr);
6444 	if (ret)
6445 		goto err_read;
6446 
6447 	/* do the pass over the counters data array to assign according to the
6448 	 * descriptions and indexing pairs
6449 	 */
6450 	desc = mcounters->counters_data;
6451 	for (i = 0; i < mcounters->ncounters; i++)
6452 		read_attr->counters_buff[desc[i].index] += mread_attr.out[desc[i].description];
6453 
6454 err_read:
6455 	kfree(mread_attr.out);
6456 err_bound:
6457 	mutex_unlock(&mcounters->mcntrs_mutex);
6458 	return ret;
6459 }
6460 
6461 static int mlx5_ib_destroy_counters(struct ib_counters *counters)
6462 {
6463 	struct mlx5_ib_mcounters *mcounters = to_mcounters(counters);
6464 
6465 	counters_clear_description(counters);
6466 	if (mcounters->hw_cntrs_hndl)
6467 		mlx5_fc_destroy(to_mdev(counters->device)->mdev,
6468 				mcounters->hw_cntrs_hndl);
6469 
6470 	kfree(mcounters);
6471 
6472 	return 0;
6473 }
6474 
6475 static struct ib_counters *mlx5_ib_create_counters(struct ib_device *device,
6476 						   struct uverbs_attr_bundle *attrs)
6477 {
6478 	struct mlx5_ib_mcounters *mcounters;
6479 
6480 	mcounters = kzalloc(sizeof(*mcounters), GFP_KERNEL);
6481 	if (!mcounters)
6482 		return ERR_PTR(-ENOMEM);
6483 
6484 	mutex_init(&mcounters->mcntrs_mutex);
6485 
6486 	return &mcounters->ibcntrs;
6487 }
6488 
6489 static void mlx5_ib_stage_init_cleanup(struct mlx5_ib_dev *dev)
6490 {
6491 	mlx5_ib_cleanup_multiport_master(dev);
6492 	WARN_ON(!xa_empty(&dev->odp_mkeys));
6493 	cleanup_srcu_struct(&dev->odp_srcu);
6494 
6495 	WARN_ON(!xa_empty(&dev->sig_mrs));
6496 	WARN_ON(!bitmap_empty(dev->dm.memic_alloc_pages, MLX5_MAX_MEMIC_PAGES));
6497 }
6498 
6499 static int mlx5_ib_stage_init_init(struct mlx5_ib_dev *dev)
6500 {
6501 	struct mlx5_core_dev *mdev = dev->mdev;
6502 	int err;
6503 	int i;
6504 
6505 	for (i = 0; i < dev->num_ports; i++) {
6506 		spin_lock_init(&dev->port[i].mp.mpi_lock);
6507 		rwlock_init(&dev->port[i].roce.netdev_lock);
6508 		dev->port[i].roce.dev = dev;
6509 		dev->port[i].roce.native_port_num = i + 1;
6510 		dev->port[i].roce.last_port_state = IB_PORT_DOWN;
6511 	}
6512 
6513 	mlx5_ib_internal_fill_odp_caps(dev);
6514 
6515 	err = mlx5_ib_init_multiport_master(dev);
6516 	if (err)
6517 		return err;
6518 
6519 	err = set_has_smi_cap(dev);
6520 	if (err)
6521 		return err;
6522 
6523 	if (!mlx5_core_mp_enabled(mdev)) {
6524 		for (i = 1; i <= dev->num_ports; i++) {
6525 			err = get_port_caps(dev, i);
6526 			if (err)
6527 				break;
6528 		}
6529 	} else {
6530 		err = get_port_caps(dev, mlx5_core_native_port_num(mdev));
6531 	}
6532 	if (err)
6533 		goto err_mp;
6534 
6535 	if (mlx5_use_mad_ifc(dev))
6536 		get_ext_port_caps(dev);
6537 
6538 	dev->ib_dev.node_type		= RDMA_NODE_IB_CA;
6539 	dev->ib_dev.local_dma_lkey	= 0 /* not supported for now */;
6540 	dev->ib_dev.phys_port_cnt	= dev->num_ports;
6541 	dev->ib_dev.num_comp_vectors    = mlx5_comp_vectors_count(mdev);
6542 	dev->ib_dev.dev.parent		= mdev->device;
6543 
6544 	mutex_init(&dev->cap_mask_mutex);
6545 	INIT_LIST_HEAD(&dev->qp_list);
6546 	spin_lock_init(&dev->reset_flow_resource_lock);
6547 	xa_init(&dev->odp_mkeys);
6548 	xa_init(&dev->sig_mrs);
6549 	atomic_set(&dev->mkey_var, 0);
6550 
6551 	spin_lock_init(&dev->dm.lock);
6552 	dev->dm.dev = mdev;
6553 
6554 	err = init_srcu_struct(&dev->odp_srcu);
6555 	if (err)
6556 		goto err_mp;
6557 
6558 	return 0;
6559 
6560 err_mp:
6561 	mlx5_ib_cleanup_multiport_master(dev);
6562 
6563 	return -ENOMEM;
6564 }
6565 
6566 static int mlx5_ib_stage_flow_db_init(struct mlx5_ib_dev *dev)
6567 {
6568 	dev->flow_db = kzalloc(sizeof(*dev->flow_db), GFP_KERNEL);
6569 
6570 	if (!dev->flow_db)
6571 		return -ENOMEM;
6572 
6573 	mutex_init(&dev->flow_db->lock);
6574 
6575 	return 0;
6576 }
6577 
6578 static void mlx5_ib_stage_flow_db_cleanup(struct mlx5_ib_dev *dev)
6579 {
6580 	kfree(dev->flow_db);
6581 }
6582 
6583 static const struct ib_device_ops mlx5_ib_dev_ops = {
6584 	.owner = THIS_MODULE,
6585 	.driver_id = RDMA_DRIVER_MLX5,
6586 	.uverbs_abi_ver	= MLX5_IB_UVERBS_ABI_VERSION,
6587 
6588 	.add_gid = mlx5_ib_add_gid,
6589 	.alloc_mr = mlx5_ib_alloc_mr,
6590 	.alloc_mr_integrity = mlx5_ib_alloc_mr_integrity,
6591 	.alloc_pd = mlx5_ib_alloc_pd,
6592 	.alloc_ucontext = mlx5_ib_alloc_ucontext,
6593 	.attach_mcast = mlx5_ib_mcg_attach,
6594 	.check_mr_status = mlx5_ib_check_mr_status,
6595 	.create_ah = mlx5_ib_create_ah,
6596 	.create_counters = mlx5_ib_create_counters,
6597 	.create_cq = mlx5_ib_create_cq,
6598 	.create_flow = mlx5_ib_create_flow,
6599 	.create_qp = mlx5_ib_create_qp,
6600 	.create_srq = mlx5_ib_create_srq,
6601 	.dealloc_pd = mlx5_ib_dealloc_pd,
6602 	.dealloc_ucontext = mlx5_ib_dealloc_ucontext,
6603 	.del_gid = mlx5_ib_del_gid,
6604 	.dereg_mr = mlx5_ib_dereg_mr,
6605 	.destroy_ah = mlx5_ib_destroy_ah,
6606 	.destroy_counters = mlx5_ib_destroy_counters,
6607 	.destroy_cq = mlx5_ib_destroy_cq,
6608 	.destroy_flow = mlx5_ib_destroy_flow,
6609 	.destroy_flow_action = mlx5_ib_destroy_flow_action,
6610 	.destroy_qp = mlx5_ib_destroy_qp,
6611 	.destroy_srq = mlx5_ib_destroy_srq,
6612 	.detach_mcast = mlx5_ib_mcg_detach,
6613 	.disassociate_ucontext = mlx5_ib_disassociate_ucontext,
6614 	.drain_rq = mlx5_ib_drain_rq,
6615 	.drain_sq = mlx5_ib_drain_sq,
6616 	.enable_driver = mlx5_ib_enable_driver,
6617 	.fill_res_entry = mlx5_ib_fill_res_entry,
6618 	.fill_stat_entry = mlx5_ib_fill_stat_entry,
6619 	.get_dev_fw_str = get_dev_fw_str,
6620 	.get_dma_mr = mlx5_ib_get_dma_mr,
6621 	.get_link_layer = mlx5_ib_port_link_layer,
6622 	.map_mr_sg = mlx5_ib_map_mr_sg,
6623 	.map_mr_sg_pi = mlx5_ib_map_mr_sg_pi,
6624 	.mmap = mlx5_ib_mmap,
6625 	.mmap_free = mlx5_ib_mmap_free,
6626 	.modify_cq = mlx5_ib_modify_cq,
6627 	.modify_device = mlx5_ib_modify_device,
6628 	.modify_port = mlx5_ib_modify_port,
6629 	.modify_qp = mlx5_ib_modify_qp,
6630 	.modify_srq = mlx5_ib_modify_srq,
6631 	.poll_cq = mlx5_ib_poll_cq,
6632 	.post_recv = mlx5_ib_post_recv,
6633 	.post_send = mlx5_ib_post_send,
6634 	.post_srq_recv = mlx5_ib_post_srq_recv,
6635 	.process_mad = mlx5_ib_process_mad,
6636 	.query_ah = mlx5_ib_query_ah,
6637 	.query_device = mlx5_ib_query_device,
6638 	.query_gid = mlx5_ib_query_gid,
6639 	.query_pkey = mlx5_ib_query_pkey,
6640 	.query_qp = mlx5_ib_query_qp,
6641 	.query_srq = mlx5_ib_query_srq,
6642 	.read_counters = mlx5_ib_read_counters,
6643 	.reg_user_mr = mlx5_ib_reg_user_mr,
6644 	.req_notify_cq = mlx5_ib_arm_cq,
6645 	.rereg_user_mr = mlx5_ib_rereg_user_mr,
6646 	.resize_cq = mlx5_ib_resize_cq,
6647 
6648 	INIT_RDMA_OBJ_SIZE(ib_ah, mlx5_ib_ah, ibah),
6649 	INIT_RDMA_OBJ_SIZE(ib_cq, mlx5_ib_cq, ibcq),
6650 	INIT_RDMA_OBJ_SIZE(ib_pd, mlx5_ib_pd, ibpd),
6651 	INIT_RDMA_OBJ_SIZE(ib_srq, mlx5_ib_srq, ibsrq),
6652 	INIT_RDMA_OBJ_SIZE(ib_ucontext, mlx5_ib_ucontext, ibucontext),
6653 };
6654 
6655 static const struct ib_device_ops mlx5_ib_dev_flow_ipsec_ops = {
6656 	.create_flow_action_esp = mlx5_ib_create_flow_action_esp,
6657 	.modify_flow_action_esp = mlx5_ib_modify_flow_action_esp,
6658 };
6659 
6660 static const struct ib_device_ops mlx5_ib_dev_ipoib_enhanced_ops = {
6661 	.rdma_netdev_get_params = mlx5_ib_rn_get_params,
6662 };
6663 
6664 static const struct ib_device_ops mlx5_ib_dev_sriov_ops = {
6665 	.get_vf_config = mlx5_ib_get_vf_config,
6666 	.get_vf_guid = mlx5_ib_get_vf_guid,
6667 	.get_vf_stats = mlx5_ib_get_vf_stats,
6668 	.set_vf_guid = mlx5_ib_set_vf_guid,
6669 	.set_vf_link_state = mlx5_ib_set_vf_link_state,
6670 };
6671 
6672 static const struct ib_device_ops mlx5_ib_dev_mw_ops = {
6673 	.alloc_mw = mlx5_ib_alloc_mw,
6674 	.dealloc_mw = mlx5_ib_dealloc_mw,
6675 };
6676 
6677 static const struct ib_device_ops mlx5_ib_dev_xrc_ops = {
6678 	.alloc_xrcd = mlx5_ib_alloc_xrcd,
6679 	.dealloc_xrcd = mlx5_ib_dealloc_xrcd,
6680 };
6681 
6682 static const struct ib_device_ops mlx5_ib_dev_dm_ops = {
6683 	.alloc_dm = mlx5_ib_alloc_dm,
6684 	.dealloc_dm = mlx5_ib_dealloc_dm,
6685 	.reg_dm_mr = mlx5_ib_reg_dm_mr,
6686 };
6687 
6688 static int mlx5_ib_init_var_table(struct mlx5_ib_dev *dev)
6689 {
6690 	struct mlx5_core_dev *mdev = dev->mdev;
6691 	struct mlx5_var_table *var_table = &dev->var_table;
6692 	u8 log_doorbell_bar_size;
6693 	u8 log_doorbell_stride;
6694 	u64 bar_size;
6695 
6696 	log_doorbell_bar_size = MLX5_CAP_DEV_VDPA_EMULATION(mdev,
6697 					log_doorbell_bar_size);
6698 	log_doorbell_stride = MLX5_CAP_DEV_VDPA_EMULATION(mdev,
6699 					log_doorbell_stride);
6700 	var_table->hw_start_addr = dev->mdev->bar_addr +
6701 				MLX5_CAP64_DEV_VDPA_EMULATION(mdev,
6702 					doorbell_bar_offset);
6703 	bar_size = (1ULL << log_doorbell_bar_size) * 4096;
6704 	var_table->stride_size = 1ULL << log_doorbell_stride;
6705 	var_table->num_var_hw_entries = div_u64(bar_size,
6706 						var_table->stride_size);
6707 	mutex_init(&var_table->bitmap_lock);
6708 	var_table->bitmap = bitmap_zalloc(var_table->num_var_hw_entries,
6709 					  GFP_KERNEL);
6710 	return (var_table->bitmap) ? 0 : -ENOMEM;
6711 }
6712 
6713 static void mlx5_ib_stage_caps_cleanup(struct mlx5_ib_dev *dev)
6714 {
6715 	bitmap_free(dev->var_table.bitmap);
6716 }
6717 
6718 static int mlx5_ib_stage_caps_init(struct mlx5_ib_dev *dev)
6719 {
6720 	struct mlx5_core_dev *mdev = dev->mdev;
6721 	int err;
6722 
6723 	dev->ib_dev.uverbs_cmd_mask	=
6724 		(1ull << IB_USER_VERBS_CMD_GET_CONTEXT)		|
6725 		(1ull << IB_USER_VERBS_CMD_QUERY_DEVICE)	|
6726 		(1ull << IB_USER_VERBS_CMD_QUERY_PORT)		|
6727 		(1ull << IB_USER_VERBS_CMD_ALLOC_PD)		|
6728 		(1ull << IB_USER_VERBS_CMD_DEALLOC_PD)		|
6729 		(1ull << IB_USER_VERBS_CMD_CREATE_AH)		|
6730 		(1ull << IB_USER_VERBS_CMD_DESTROY_AH)		|
6731 		(1ull << IB_USER_VERBS_CMD_REG_MR)		|
6732 		(1ull << IB_USER_VERBS_CMD_REREG_MR)		|
6733 		(1ull << IB_USER_VERBS_CMD_DEREG_MR)		|
6734 		(1ull << IB_USER_VERBS_CMD_CREATE_COMP_CHANNEL)	|
6735 		(1ull << IB_USER_VERBS_CMD_CREATE_CQ)		|
6736 		(1ull << IB_USER_VERBS_CMD_RESIZE_CQ)		|
6737 		(1ull << IB_USER_VERBS_CMD_DESTROY_CQ)		|
6738 		(1ull << IB_USER_VERBS_CMD_CREATE_QP)		|
6739 		(1ull << IB_USER_VERBS_CMD_MODIFY_QP)		|
6740 		(1ull << IB_USER_VERBS_CMD_QUERY_QP)		|
6741 		(1ull << IB_USER_VERBS_CMD_DESTROY_QP)		|
6742 		(1ull << IB_USER_VERBS_CMD_ATTACH_MCAST)	|
6743 		(1ull << IB_USER_VERBS_CMD_DETACH_MCAST)	|
6744 		(1ull << IB_USER_VERBS_CMD_CREATE_SRQ)		|
6745 		(1ull << IB_USER_VERBS_CMD_MODIFY_SRQ)		|
6746 		(1ull << IB_USER_VERBS_CMD_QUERY_SRQ)		|
6747 		(1ull << IB_USER_VERBS_CMD_DESTROY_SRQ)		|
6748 		(1ull << IB_USER_VERBS_CMD_CREATE_XSRQ)		|
6749 		(1ull << IB_USER_VERBS_CMD_OPEN_QP);
6750 	dev->ib_dev.uverbs_ex_cmd_mask =
6751 		(1ull << IB_USER_VERBS_EX_CMD_QUERY_DEVICE)	|
6752 		(1ull << IB_USER_VERBS_EX_CMD_CREATE_CQ)	|
6753 		(1ull << IB_USER_VERBS_EX_CMD_CREATE_QP)	|
6754 		(1ull << IB_USER_VERBS_EX_CMD_MODIFY_QP)	|
6755 		(1ull << IB_USER_VERBS_EX_CMD_MODIFY_CQ)	|
6756 		(1ull << IB_USER_VERBS_EX_CMD_CREATE_FLOW)	|
6757 		(1ull << IB_USER_VERBS_EX_CMD_DESTROY_FLOW);
6758 
6759 	if (MLX5_CAP_GEN(mdev, ipoib_enhanced_offloads) &&
6760 	    IS_ENABLED(CONFIG_MLX5_CORE_IPOIB))
6761 		ib_set_device_ops(&dev->ib_dev,
6762 				  &mlx5_ib_dev_ipoib_enhanced_ops);
6763 
6764 	if (mlx5_core_is_pf(mdev))
6765 		ib_set_device_ops(&dev->ib_dev, &mlx5_ib_dev_sriov_ops);
6766 
6767 	dev->umr_fence = mlx5_get_umr_fence(MLX5_CAP_GEN(mdev, umr_fence));
6768 
6769 	if (MLX5_CAP_GEN(mdev, imaicl)) {
6770 		dev->ib_dev.uverbs_cmd_mask |=
6771 			(1ull << IB_USER_VERBS_CMD_ALLOC_MW)	|
6772 			(1ull << IB_USER_VERBS_CMD_DEALLOC_MW);
6773 		ib_set_device_ops(&dev->ib_dev, &mlx5_ib_dev_mw_ops);
6774 	}
6775 
6776 	if (MLX5_CAP_GEN(mdev, xrc)) {
6777 		dev->ib_dev.uverbs_cmd_mask |=
6778 			(1ull << IB_USER_VERBS_CMD_OPEN_XRCD) |
6779 			(1ull << IB_USER_VERBS_CMD_CLOSE_XRCD);
6780 		ib_set_device_ops(&dev->ib_dev, &mlx5_ib_dev_xrc_ops);
6781 	}
6782 
6783 	if (MLX5_CAP_DEV_MEM(mdev, memic) ||
6784 	    MLX5_CAP_GEN_64(dev->mdev, general_obj_types) &
6785 	    MLX5_GENERAL_OBJ_TYPES_CAP_SW_ICM)
6786 		ib_set_device_ops(&dev->ib_dev, &mlx5_ib_dev_dm_ops);
6787 
6788 	if (mlx5_accel_ipsec_device_caps(dev->mdev) &
6789 	    MLX5_ACCEL_IPSEC_CAP_DEVICE)
6790 		ib_set_device_ops(&dev->ib_dev, &mlx5_ib_dev_flow_ipsec_ops);
6791 	ib_set_device_ops(&dev->ib_dev, &mlx5_ib_dev_ops);
6792 
6793 	if (IS_ENABLED(CONFIG_INFINIBAND_USER_ACCESS))
6794 		dev->ib_dev.driver_def = mlx5_ib_defs;
6795 
6796 	err = init_node_data(dev);
6797 	if (err)
6798 		return err;
6799 
6800 	if ((MLX5_CAP_GEN(dev->mdev, port_type) == MLX5_CAP_PORT_TYPE_ETH) &&
6801 	    (MLX5_CAP_GEN(dev->mdev, disable_local_lb_uc) ||
6802 	     MLX5_CAP_GEN(dev->mdev, disable_local_lb_mc)))
6803 		mutex_init(&dev->lb.mutex);
6804 
6805 	if (MLX5_CAP_GEN_64(dev->mdev, general_obj_types) &
6806 			MLX5_GENERAL_OBJ_TYPES_CAP_VIRTIO_NET_Q) {
6807 		err = mlx5_ib_init_var_table(dev);
6808 		if (err)
6809 			return err;
6810 	}
6811 
6812 	dev->ib_dev.use_cq_dim = true;
6813 
6814 	return 0;
6815 }
6816 
6817 static const struct ib_device_ops mlx5_ib_dev_port_ops = {
6818 	.get_port_immutable = mlx5_port_immutable,
6819 	.query_port = mlx5_ib_query_port,
6820 };
6821 
6822 static int mlx5_ib_stage_non_default_cb(struct mlx5_ib_dev *dev)
6823 {
6824 	ib_set_device_ops(&dev->ib_dev, &mlx5_ib_dev_port_ops);
6825 	return 0;
6826 }
6827 
6828 static const struct ib_device_ops mlx5_ib_dev_port_rep_ops = {
6829 	.get_port_immutable = mlx5_port_rep_immutable,
6830 	.query_port = mlx5_ib_rep_query_port,
6831 };
6832 
6833 static int mlx5_ib_stage_raw_eth_non_default_cb(struct mlx5_ib_dev *dev)
6834 {
6835 	ib_set_device_ops(&dev->ib_dev, &mlx5_ib_dev_port_rep_ops);
6836 	return 0;
6837 }
6838 
6839 static const struct ib_device_ops mlx5_ib_dev_common_roce_ops = {
6840 	.create_rwq_ind_table = mlx5_ib_create_rwq_ind_table,
6841 	.create_wq = mlx5_ib_create_wq,
6842 	.destroy_rwq_ind_table = mlx5_ib_destroy_rwq_ind_table,
6843 	.destroy_wq = mlx5_ib_destroy_wq,
6844 	.get_netdev = mlx5_ib_get_netdev,
6845 	.modify_wq = mlx5_ib_modify_wq,
6846 };
6847 
6848 static int mlx5_ib_stage_common_roce_init(struct mlx5_ib_dev *dev)
6849 {
6850 	u8 port_num;
6851 
6852 	dev->ib_dev.uverbs_ex_cmd_mask |=
6853 			(1ull << IB_USER_VERBS_EX_CMD_CREATE_WQ) |
6854 			(1ull << IB_USER_VERBS_EX_CMD_MODIFY_WQ) |
6855 			(1ull << IB_USER_VERBS_EX_CMD_DESTROY_WQ) |
6856 			(1ull << IB_USER_VERBS_EX_CMD_CREATE_RWQ_IND_TBL) |
6857 			(1ull << IB_USER_VERBS_EX_CMD_DESTROY_RWQ_IND_TBL);
6858 	ib_set_device_ops(&dev->ib_dev, &mlx5_ib_dev_common_roce_ops);
6859 
6860 	port_num = mlx5_core_native_port_num(dev->mdev) - 1;
6861 
6862 	/* Register only for native ports */
6863 	return mlx5_add_netdev_notifier(dev, port_num);
6864 }
6865 
6866 static void mlx5_ib_stage_common_roce_cleanup(struct mlx5_ib_dev *dev)
6867 {
6868 	u8 port_num = mlx5_core_native_port_num(dev->mdev) - 1;
6869 
6870 	mlx5_remove_netdev_notifier(dev, port_num);
6871 }
6872 
6873 static int mlx5_ib_stage_raw_eth_roce_init(struct mlx5_ib_dev *dev)
6874 {
6875 	struct mlx5_core_dev *mdev = dev->mdev;
6876 	enum rdma_link_layer ll;
6877 	int port_type_cap;
6878 	int err = 0;
6879 
6880 	port_type_cap = MLX5_CAP_GEN(mdev, port_type);
6881 	ll = mlx5_port_type_cap_to_rdma_ll(port_type_cap);
6882 
6883 	if (ll == IB_LINK_LAYER_ETHERNET)
6884 		err = mlx5_ib_stage_common_roce_init(dev);
6885 
6886 	return err;
6887 }
6888 
6889 static void mlx5_ib_stage_raw_eth_roce_cleanup(struct mlx5_ib_dev *dev)
6890 {
6891 	mlx5_ib_stage_common_roce_cleanup(dev);
6892 }
6893 
6894 static int mlx5_ib_stage_roce_init(struct mlx5_ib_dev *dev)
6895 {
6896 	struct mlx5_core_dev *mdev = dev->mdev;
6897 	enum rdma_link_layer ll;
6898 	int port_type_cap;
6899 	int err;
6900 
6901 	port_type_cap = MLX5_CAP_GEN(mdev, port_type);
6902 	ll = mlx5_port_type_cap_to_rdma_ll(port_type_cap);
6903 
6904 	if (ll == IB_LINK_LAYER_ETHERNET) {
6905 		err = mlx5_ib_stage_common_roce_init(dev);
6906 		if (err)
6907 			return err;
6908 
6909 		err = mlx5_enable_eth(dev);
6910 		if (err)
6911 			goto cleanup;
6912 	}
6913 
6914 	return 0;
6915 cleanup:
6916 	mlx5_ib_stage_common_roce_cleanup(dev);
6917 
6918 	return err;
6919 }
6920 
6921 static void mlx5_ib_stage_roce_cleanup(struct mlx5_ib_dev *dev)
6922 {
6923 	struct mlx5_core_dev *mdev = dev->mdev;
6924 	enum rdma_link_layer ll;
6925 	int port_type_cap;
6926 
6927 	port_type_cap = MLX5_CAP_GEN(mdev, port_type);
6928 	ll = mlx5_port_type_cap_to_rdma_ll(port_type_cap);
6929 
6930 	if (ll == IB_LINK_LAYER_ETHERNET) {
6931 		mlx5_disable_eth(dev);
6932 		mlx5_ib_stage_common_roce_cleanup(dev);
6933 	}
6934 }
6935 
6936 static int mlx5_ib_stage_dev_res_init(struct mlx5_ib_dev *dev)
6937 {
6938 	return create_dev_resources(&dev->devr);
6939 }
6940 
6941 static void mlx5_ib_stage_dev_res_cleanup(struct mlx5_ib_dev *dev)
6942 {
6943 	destroy_dev_resources(&dev->devr);
6944 }
6945 
6946 static int mlx5_ib_stage_odp_init(struct mlx5_ib_dev *dev)
6947 {
6948 	return mlx5_ib_odp_init_one(dev);
6949 }
6950 
6951 static void mlx5_ib_stage_odp_cleanup(struct mlx5_ib_dev *dev)
6952 {
6953 	mlx5_ib_odp_cleanup_one(dev);
6954 }
6955 
6956 static const struct ib_device_ops mlx5_ib_dev_hw_stats_ops = {
6957 	.alloc_hw_stats = mlx5_ib_alloc_hw_stats,
6958 	.get_hw_stats = mlx5_ib_get_hw_stats,
6959 	.counter_bind_qp = mlx5_ib_counter_bind_qp,
6960 	.counter_unbind_qp = mlx5_ib_counter_unbind_qp,
6961 	.counter_dealloc = mlx5_ib_counter_dealloc,
6962 	.counter_alloc_stats = mlx5_ib_counter_alloc_stats,
6963 	.counter_update_stats = mlx5_ib_counter_update_stats,
6964 };
6965 
6966 static int mlx5_ib_stage_counters_init(struct mlx5_ib_dev *dev)
6967 {
6968 	if (MLX5_CAP_GEN(dev->mdev, max_qp_cnt)) {
6969 		ib_set_device_ops(&dev->ib_dev, &mlx5_ib_dev_hw_stats_ops);
6970 
6971 		return mlx5_ib_alloc_counters(dev);
6972 	}
6973 
6974 	return 0;
6975 }
6976 
6977 static void mlx5_ib_stage_counters_cleanup(struct mlx5_ib_dev *dev)
6978 {
6979 	if (MLX5_CAP_GEN(dev->mdev, max_qp_cnt))
6980 		mlx5_ib_dealloc_counters(dev);
6981 }
6982 
6983 static int mlx5_ib_stage_cong_debugfs_init(struct mlx5_ib_dev *dev)
6984 {
6985 	mlx5_ib_init_cong_debugfs(dev,
6986 				  mlx5_core_native_port_num(dev->mdev) - 1);
6987 	return 0;
6988 }
6989 
6990 static void mlx5_ib_stage_cong_debugfs_cleanup(struct mlx5_ib_dev *dev)
6991 {
6992 	mlx5_ib_cleanup_cong_debugfs(dev,
6993 				     mlx5_core_native_port_num(dev->mdev) - 1);
6994 }
6995 
6996 static int mlx5_ib_stage_uar_init(struct mlx5_ib_dev *dev)
6997 {
6998 	dev->mdev->priv.uar = mlx5_get_uars_page(dev->mdev);
6999 	return PTR_ERR_OR_ZERO(dev->mdev->priv.uar);
7000 }
7001 
7002 static void mlx5_ib_stage_uar_cleanup(struct mlx5_ib_dev *dev)
7003 {
7004 	mlx5_put_uars_page(dev->mdev, dev->mdev->priv.uar);
7005 }
7006 
7007 static int mlx5_ib_stage_bfrag_init(struct mlx5_ib_dev *dev)
7008 {
7009 	int err;
7010 
7011 	err = mlx5_alloc_bfreg(dev->mdev, &dev->bfreg, false, false);
7012 	if (err)
7013 		return err;
7014 
7015 	err = mlx5_alloc_bfreg(dev->mdev, &dev->fp_bfreg, false, true);
7016 	if (err)
7017 		mlx5_free_bfreg(dev->mdev, &dev->fp_bfreg);
7018 
7019 	return err;
7020 }
7021 
7022 static void mlx5_ib_stage_bfrag_cleanup(struct mlx5_ib_dev *dev)
7023 {
7024 	mlx5_free_bfreg(dev->mdev, &dev->fp_bfreg);
7025 	mlx5_free_bfreg(dev->mdev, &dev->bfreg);
7026 }
7027 
7028 static int mlx5_ib_stage_ib_reg_init(struct mlx5_ib_dev *dev)
7029 {
7030 	const char *name;
7031 
7032 	rdma_set_device_sysfs_group(&dev->ib_dev, &mlx5_attr_group);
7033 	if (!mlx5_lag_is_roce(dev->mdev))
7034 		name = "mlx5_%d";
7035 	else
7036 		name = "mlx5_bond_%d";
7037 	return ib_register_device(&dev->ib_dev, name);
7038 }
7039 
7040 static void mlx5_ib_stage_pre_ib_reg_umr_cleanup(struct mlx5_ib_dev *dev)
7041 {
7042 	destroy_umrc_res(dev);
7043 }
7044 
7045 static void mlx5_ib_stage_ib_reg_cleanup(struct mlx5_ib_dev *dev)
7046 {
7047 	ib_unregister_device(&dev->ib_dev);
7048 }
7049 
7050 static int mlx5_ib_stage_post_ib_reg_umr_init(struct mlx5_ib_dev *dev)
7051 {
7052 	return create_umr_res(dev);
7053 }
7054 
7055 static int mlx5_ib_stage_delay_drop_init(struct mlx5_ib_dev *dev)
7056 {
7057 	init_delay_drop(dev);
7058 
7059 	return 0;
7060 }
7061 
7062 static void mlx5_ib_stage_delay_drop_cleanup(struct mlx5_ib_dev *dev)
7063 {
7064 	cancel_delay_drop(dev);
7065 }
7066 
7067 static int mlx5_ib_stage_dev_notifier_init(struct mlx5_ib_dev *dev)
7068 {
7069 	dev->mdev_events.notifier_call = mlx5_ib_event;
7070 	mlx5_notifier_register(dev->mdev, &dev->mdev_events);
7071 	return 0;
7072 }
7073 
7074 static void mlx5_ib_stage_dev_notifier_cleanup(struct mlx5_ib_dev *dev)
7075 {
7076 	mlx5_notifier_unregister(dev->mdev, &dev->mdev_events);
7077 }
7078 
7079 static int mlx5_ib_stage_devx_init(struct mlx5_ib_dev *dev)
7080 {
7081 	int uid;
7082 
7083 	uid = mlx5_ib_devx_create(dev, false);
7084 	if (uid > 0) {
7085 		dev->devx_whitelist_uid = uid;
7086 		mlx5_ib_devx_init_event_table(dev);
7087 	}
7088 
7089 	return 0;
7090 }
7091 static void mlx5_ib_stage_devx_cleanup(struct mlx5_ib_dev *dev)
7092 {
7093 	if (dev->devx_whitelist_uid) {
7094 		mlx5_ib_devx_cleanup_event_table(dev);
7095 		mlx5_ib_devx_destroy(dev, dev->devx_whitelist_uid);
7096 	}
7097 }
7098 
7099 int mlx5_ib_enable_driver(struct ib_device *dev)
7100 {
7101 	struct mlx5_ib_dev *mdev = to_mdev(dev);
7102 	int ret;
7103 
7104 	ret = mlx5_ib_test_wc(mdev);
7105 	mlx5_ib_dbg(mdev, "Write-Combining %s",
7106 		    mdev->wc_support ? "supported" : "not supported");
7107 
7108 	return ret;
7109 }
7110 
7111 void __mlx5_ib_remove(struct mlx5_ib_dev *dev,
7112 		      const struct mlx5_ib_profile *profile,
7113 		      int stage)
7114 {
7115 	dev->ib_active = false;
7116 
7117 	/* Number of stages to cleanup */
7118 	while (stage) {
7119 		stage--;
7120 		if (profile->stage[stage].cleanup)
7121 			profile->stage[stage].cleanup(dev);
7122 	}
7123 
7124 	kfree(dev->port);
7125 	ib_dealloc_device(&dev->ib_dev);
7126 }
7127 
7128 void *__mlx5_ib_add(struct mlx5_ib_dev *dev,
7129 		    const struct mlx5_ib_profile *profile)
7130 {
7131 	int err;
7132 	int i;
7133 
7134 	for (i = 0; i < MLX5_IB_STAGE_MAX; i++) {
7135 		if (profile->stage[i].init) {
7136 			err = profile->stage[i].init(dev);
7137 			if (err)
7138 				goto err_out;
7139 		}
7140 	}
7141 
7142 	dev->profile = profile;
7143 	dev->ib_active = true;
7144 
7145 	return dev;
7146 
7147 err_out:
7148 	__mlx5_ib_remove(dev, profile, i);
7149 
7150 	return NULL;
7151 }
7152 
7153 static const struct mlx5_ib_profile pf_profile = {
7154 	STAGE_CREATE(MLX5_IB_STAGE_INIT,
7155 		     mlx5_ib_stage_init_init,
7156 		     mlx5_ib_stage_init_cleanup),
7157 	STAGE_CREATE(MLX5_IB_STAGE_FLOW_DB,
7158 		     mlx5_ib_stage_flow_db_init,
7159 		     mlx5_ib_stage_flow_db_cleanup),
7160 	STAGE_CREATE(MLX5_IB_STAGE_CAPS,
7161 		     mlx5_ib_stage_caps_init,
7162 		     mlx5_ib_stage_caps_cleanup),
7163 	STAGE_CREATE(MLX5_IB_STAGE_NON_DEFAULT_CB,
7164 		     mlx5_ib_stage_non_default_cb,
7165 		     NULL),
7166 	STAGE_CREATE(MLX5_IB_STAGE_ROCE,
7167 		     mlx5_ib_stage_roce_init,
7168 		     mlx5_ib_stage_roce_cleanup),
7169 	STAGE_CREATE(MLX5_IB_STAGE_QP,
7170 		     mlx5_init_qp_table,
7171 		     mlx5_cleanup_qp_table),
7172 	STAGE_CREATE(MLX5_IB_STAGE_SRQ,
7173 		     mlx5_init_srq_table,
7174 		     mlx5_cleanup_srq_table),
7175 	STAGE_CREATE(MLX5_IB_STAGE_DEVICE_RESOURCES,
7176 		     mlx5_ib_stage_dev_res_init,
7177 		     mlx5_ib_stage_dev_res_cleanup),
7178 	STAGE_CREATE(MLX5_IB_STAGE_DEVICE_NOTIFIER,
7179 		     mlx5_ib_stage_dev_notifier_init,
7180 		     mlx5_ib_stage_dev_notifier_cleanup),
7181 	STAGE_CREATE(MLX5_IB_STAGE_ODP,
7182 		     mlx5_ib_stage_odp_init,
7183 		     mlx5_ib_stage_odp_cleanup),
7184 	STAGE_CREATE(MLX5_IB_STAGE_COUNTERS,
7185 		     mlx5_ib_stage_counters_init,
7186 		     mlx5_ib_stage_counters_cleanup),
7187 	STAGE_CREATE(MLX5_IB_STAGE_CONG_DEBUGFS,
7188 		     mlx5_ib_stage_cong_debugfs_init,
7189 		     mlx5_ib_stage_cong_debugfs_cleanup),
7190 	STAGE_CREATE(MLX5_IB_STAGE_UAR,
7191 		     mlx5_ib_stage_uar_init,
7192 		     mlx5_ib_stage_uar_cleanup),
7193 	STAGE_CREATE(MLX5_IB_STAGE_BFREG,
7194 		     mlx5_ib_stage_bfrag_init,
7195 		     mlx5_ib_stage_bfrag_cleanup),
7196 	STAGE_CREATE(MLX5_IB_STAGE_PRE_IB_REG_UMR,
7197 		     NULL,
7198 		     mlx5_ib_stage_pre_ib_reg_umr_cleanup),
7199 	STAGE_CREATE(MLX5_IB_STAGE_WHITELIST_UID,
7200 		     mlx5_ib_stage_devx_init,
7201 		     mlx5_ib_stage_devx_cleanup),
7202 	STAGE_CREATE(MLX5_IB_STAGE_IB_REG,
7203 		     mlx5_ib_stage_ib_reg_init,
7204 		     mlx5_ib_stage_ib_reg_cleanup),
7205 	STAGE_CREATE(MLX5_IB_STAGE_POST_IB_REG_UMR,
7206 		     mlx5_ib_stage_post_ib_reg_umr_init,
7207 		     NULL),
7208 	STAGE_CREATE(MLX5_IB_STAGE_DELAY_DROP,
7209 		     mlx5_ib_stage_delay_drop_init,
7210 		     mlx5_ib_stage_delay_drop_cleanup),
7211 };
7212 
7213 const struct mlx5_ib_profile raw_eth_profile = {
7214 	STAGE_CREATE(MLX5_IB_STAGE_INIT,
7215 		     mlx5_ib_stage_init_init,
7216 		     mlx5_ib_stage_init_cleanup),
7217 	STAGE_CREATE(MLX5_IB_STAGE_FLOW_DB,
7218 		     mlx5_ib_stage_flow_db_init,
7219 		     mlx5_ib_stage_flow_db_cleanup),
7220 	STAGE_CREATE(MLX5_IB_STAGE_CAPS,
7221 		     mlx5_ib_stage_caps_init,
7222 		     mlx5_ib_stage_caps_cleanup),
7223 	STAGE_CREATE(MLX5_IB_STAGE_NON_DEFAULT_CB,
7224 		     mlx5_ib_stage_raw_eth_non_default_cb,
7225 		     NULL),
7226 	STAGE_CREATE(MLX5_IB_STAGE_ROCE,
7227 		     mlx5_ib_stage_raw_eth_roce_init,
7228 		     mlx5_ib_stage_raw_eth_roce_cleanup),
7229 	STAGE_CREATE(MLX5_IB_STAGE_QP,
7230 		     mlx5_init_qp_table,
7231 		     mlx5_cleanup_qp_table),
7232 	STAGE_CREATE(MLX5_IB_STAGE_SRQ,
7233 		     mlx5_init_srq_table,
7234 		     mlx5_cleanup_srq_table),
7235 	STAGE_CREATE(MLX5_IB_STAGE_DEVICE_RESOURCES,
7236 		     mlx5_ib_stage_dev_res_init,
7237 		     mlx5_ib_stage_dev_res_cleanup),
7238 	STAGE_CREATE(MLX5_IB_STAGE_DEVICE_NOTIFIER,
7239 		     mlx5_ib_stage_dev_notifier_init,
7240 		     mlx5_ib_stage_dev_notifier_cleanup),
7241 	STAGE_CREATE(MLX5_IB_STAGE_COUNTERS,
7242 		     mlx5_ib_stage_counters_init,
7243 		     mlx5_ib_stage_counters_cleanup),
7244 	STAGE_CREATE(MLX5_IB_STAGE_CONG_DEBUGFS,
7245 		     mlx5_ib_stage_cong_debugfs_init,
7246 		     mlx5_ib_stage_cong_debugfs_cleanup),
7247 	STAGE_CREATE(MLX5_IB_STAGE_UAR,
7248 		     mlx5_ib_stage_uar_init,
7249 		     mlx5_ib_stage_uar_cleanup),
7250 	STAGE_CREATE(MLX5_IB_STAGE_BFREG,
7251 		     mlx5_ib_stage_bfrag_init,
7252 		     mlx5_ib_stage_bfrag_cleanup),
7253 	STAGE_CREATE(MLX5_IB_STAGE_PRE_IB_REG_UMR,
7254 		     NULL,
7255 		     mlx5_ib_stage_pre_ib_reg_umr_cleanup),
7256 	STAGE_CREATE(MLX5_IB_STAGE_WHITELIST_UID,
7257 		     mlx5_ib_stage_devx_init,
7258 		     mlx5_ib_stage_devx_cleanup),
7259 	STAGE_CREATE(MLX5_IB_STAGE_IB_REG,
7260 		     mlx5_ib_stage_ib_reg_init,
7261 		     mlx5_ib_stage_ib_reg_cleanup),
7262 	STAGE_CREATE(MLX5_IB_STAGE_POST_IB_REG_UMR,
7263 		     mlx5_ib_stage_post_ib_reg_umr_init,
7264 		     NULL),
7265 };
7266 
7267 static void *mlx5_ib_add_slave_port(struct mlx5_core_dev *mdev)
7268 {
7269 	struct mlx5_ib_multiport_info *mpi;
7270 	struct mlx5_ib_dev *dev;
7271 	bool bound = false;
7272 	int err;
7273 
7274 	mpi = kzalloc(sizeof(*mpi), GFP_KERNEL);
7275 	if (!mpi)
7276 		return NULL;
7277 
7278 	mpi->mdev = mdev;
7279 
7280 	err = mlx5_query_nic_vport_system_image_guid(mdev,
7281 						     &mpi->sys_image_guid);
7282 	if (err) {
7283 		kfree(mpi);
7284 		return NULL;
7285 	}
7286 
7287 	mutex_lock(&mlx5_ib_multiport_mutex);
7288 	list_for_each_entry(dev, &mlx5_ib_dev_list, ib_dev_list) {
7289 		if (dev->sys_image_guid == mpi->sys_image_guid)
7290 			bound = mlx5_ib_bind_slave_port(dev, mpi);
7291 
7292 		if (bound) {
7293 			rdma_roce_rescan_device(&dev->ib_dev);
7294 			break;
7295 		}
7296 	}
7297 
7298 	if (!bound) {
7299 		list_add_tail(&mpi->list, &mlx5_ib_unaffiliated_port_list);
7300 		dev_dbg(mdev->device,
7301 			"no suitable IB device found to bind to, added to unaffiliated list.\n");
7302 	}
7303 	mutex_unlock(&mlx5_ib_multiport_mutex);
7304 
7305 	return mpi;
7306 }
7307 
7308 static void *mlx5_ib_add(struct mlx5_core_dev *mdev)
7309 {
7310 	const struct mlx5_ib_profile *profile;
7311 	enum rdma_link_layer ll;
7312 	struct mlx5_ib_dev *dev;
7313 	int port_type_cap;
7314 	int num_ports;
7315 
7316 	printk_once(KERN_INFO "%s", mlx5_version);
7317 
7318 	if (MLX5_ESWITCH_MANAGER(mdev) &&
7319 	    mlx5_ib_eswitch_mode(mdev->priv.eswitch) == MLX5_ESWITCH_OFFLOADS) {
7320 		if (!mlx5_core_mp_enabled(mdev))
7321 			mlx5_ib_register_vport_reps(mdev);
7322 		return mdev;
7323 	}
7324 
7325 	port_type_cap = MLX5_CAP_GEN(mdev, port_type);
7326 	ll = mlx5_port_type_cap_to_rdma_ll(port_type_cap);
7327 
7328 	if (mlx5_core_is_mp_slave(mdev) && ll == IB_LINK_LAYER_ETHERNET)
7329 		return mlx5_ib_add_slave_port(mdev);
7330 
7331 	num_ports = max(MLX5_CAP_GEN(mdev, num_ports),
7332 			MLX5_CAP_GEN(mdev, num_vhca_ports));
7333 	dev = ib_alloc_device(mlx5_ib_dev, ib_dev);
7334 	if (!dev)
7335 		return NULL;
7336 	dev->port = kcalloc(num_ports, sizeof(*dev->port),
7337 			     GFP_KERNEL);
7338 	if (!dev->port) {
7339 		ib_dealloc_device(&dev->ib_dev);
7340 		return NULL;
7341 	}
7342 
7343 	dev->mdev = mdev;
7344 	dev->num_ports = num_ports;
7345 
7346 	if (ll == IB_LINK_LAYER_ETHERNET && !mlx5_is_roce_enabled(mdev))
7347 		profile = &raw_eth_profile;
7348 	else
7349 		profile = &pf_profile;
7350 
7351 	return __mlx5_ib_add(dev, profile);
7352 }
7353 
7354 static void mlx5_ib_remove(struct mlx5_core_dev *mdev, void *context)
7355 {
7356 	struct mlx5_ib_multiport_info *mpi;
7357 	struct mlx5_ib_dev *dev;
7358 
7359 	if (MLX5_ESWITCH_MANAGER(mdev) && context == mdev) {
7360 		mlx5_ib_unregister_vport_reps(mdev);
7361 		return;
7362 	}
7363 
7364 	if (mlx5_core_is_mp_slave(mdev)) {
7365 		mpi = context;
7366 		mutex_lock(&mlx5_ib_multiport_mutex);
7367 		if (mpi->ibdev)
7368 			mlx5_ib_unbind_slave_port(mpi->ibdev, mpi);
7369 		list_del(&mpi->list);
7370 		mutex_unlock(&mlx5_ib_multiport_mutex);
7371 		kfree(mpi);
7372 		return;
7373 	}
7374 
7375 	dev = context;
7376 	__mlx5_ib_remove(dev, dev->profile, MLX5_IB_STAGE_MAX);
7377 }
7378 
7379 static struct mlx5_interface mlx5_ib_interface = {
7380 	.add            = mlx5_ib_add,
7381 	.remove         = mlx5_ib_remove,
7382 	.protocol	= MLX5_INTERFACE_PROTOCOL_IB,
7383 };
7384 
7385 unsigned long mlx5_ib_get_xlt_emergency_page(void)
7386 {
7387 	mutex_lock(&xlt_emergency_page_mutex);
7388 	return xlt_emergency_page;
7389 }
7390 
7391 void mlx5_ib_put_xlt_emergency_page(void)
7392 {
7393 	mutex_unlock(&xlt_emergency_page_mutex);
7394 }
7395 
7396 static int __init mlx5_ib_init(void)
7397 {
7398 	int err;
7399 
7400 	xlt_emergency_page = __get_free_page(GFP_KERNEL);
7401 	if (!xlt_emergency_page)
7402 		return -ENOMEM;
7403 
7404 	mutex_init(&xlt_emergency_page_mutex);
7405 
7406 	mlx5_ib_event_wq = alloc_ordered_workqueue("mlx5_ib_event_wq", 0);
7407 	if (!mlx5_ib_event_wq) {
7408 		free_page(xlt_emergency_page);
7409 		return -ENOMEM;
7410 	}
7411 
7412 	mlx5_ib_odp_init();
7413 
7414 	err = mlx5_register_interface(&mlx5_ib_interface);
7415 
7416 	return err;
7417 }
7418 
7419 static void __exit mlx5_ib_cleanup(void)
7420 {
7421 	mlx5_unregister_interface(&mlx5_ib_interface);
7422 	destroy_workqueue(mlx5_ib_event_wq);
7423 	mutex_destroy(&xlt_emergency_page_mutex);
7424 	free_page(xlt_emergency_page);
7425 }
7426 
7427 module_init(mlx5_ib_init);
7428 module_exit(mlx5_ib_cleanup);
7429