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