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