xref: /freebsd/sys/dev/mlx5/mlx5_ib/mlx5_ib_main.c (revision ebacd8013fe5f7fdf9f6a5b286f6680dd2891036)
1 /*-
2  * Copyright (c) 2013-2021, Mellanox Technologies, Ltd.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS `AS IS' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  *
25  * $FreeBSD$
26  */
27 
28 #include "opt_rss.h"
29 #include "opt_ratelimit.h"
30 
31 #include <linux/module.h>
32 #include <linux/errno.h>
33 #include <linux/pci.h>
34 #include <linux/dma-mapping.h>
35 #include <linux/slab.h>
36 #if defined(CONFIG_X86)
37 #include <asm/pat.h>
38 #endif
39 #include <linux/sched.h>
40 #include <linux/delay.h>
41 #include <linux/fs.h>
42 #undef inode
43 #include <rdma/ib_user_verbs.h>
44 #include <rdma/ib_addr.h>
45 #include <rdma/ib_cache.h>
46 #include <dev/mlx5/port.h>
47 #include <dev/mlx5/vport.h>
48 #include <linux/list.h>
49 #include <rdma/ib_smi.h>
50 #include <rdma/ib_umem.h>
51 #include <rdma/uverbs_ioctl.h>
52 #include <linux/in.h>
53 #include <linux/etherdevice.h>
54 #include <dev/mlx5/fs.h>
55 #include <dev/mlx5/mlx5_ib/mlx5_ib.h>
56 
57 MODULE_DESCRIPTION("Mellanox Connect-IB HCA IB driver");
58 MODULE_LICENSE("Dual BSD/GPL");
59 MODULE_DEPEND(mlx5ib, linuxkpi, 1, 1, 1);
60 MODULE_DEPEND(mlx5ib, mlx5, 1, 1, 1);
61 MODULE_DEPEND(mlx5ib, ibcore, 1, 1, 1);
62 MODULE_VERSION(mlx5ib, 1);
63 
64 enum {
65 	MLX5_ATOMIC_SIZE_QP_8BYTES = 1 << 3,
66 };
67 
68 static enum rdma_link_layer
69 mlx5_port_type_cap_to_rdma_ll(int port_type_cap)
70 {
71 	switch (port_type_cap) {
72 	case MLX5_CAP_PORT_TYPE_IB:
73 		return IB_LINK_LAYER_INFINIBAND;
74 	case MLX5_CAP_PORT_TYPE_ETH:
75 		return IB_LINK_LAYER_ETHERNET;
76 	default:
77 		return IB_LINK_LAYER_UNSPECIFIED;
78 	}
79 }
80 
81 static enum rdma_link_layer
82 mlx5_ib_port_link_layer(struct ib_device *device, u8 port_num)
83 {
84 	struct mlx5_ib_dev *dev = to_mdev(device);
85 	int port_type_cap = MLX5_CAP_GEN(dev->mdev, port_type);
86 
87 	return mlx5_port_type_cap_to_rdma_ll(port_type_cap);
88 }
89 
90 static bool mlx5_netdev_match(if_t ndev,
91 			      struct mlx5_core_dev *mdev,
92 			      const char *dname)
93 {
94 	return if_gettype(ndev) == IFT_ETHER &&
95 	  if_getdname(ndev) != NULL &&
96 	  strcmp(if_getdname(ndev), dname) == 0 &&
97 	  if_getsoftc(ndev) != NULL &&
98 	  *(struct mlx5_core_dev **)if_getsoftc(ndev) == mdev;
99 }
100 
101 static int mlx5_netdev_event(struct notifier_block *this,
102 			     unsigned long event, void *ptr)
103 {
104 	if_t ndev = netdev_notifier_info_to_ifp(ptr);
105 	struct mlx5_ib_dev *ibdev = container_of(this, struct mlx5_ib_dev,
106 						 roce.nb);
107 
108 	switch (event) {
109 	case NETDEV_REGISTER:
110 	case NETDEV_UNREGISTER:
111 		write_lock(&ibdev->roce.netdev_lock);
112 		/* check if network interface belongs to mlx5en */
113 		if (mlx5_netdev_match(ndev, ibdev->mdev, "mce"))
114 			ibdev->roce.netdev = (event == NETDEV_UNREGISTER) ?
115 					     NULL : ndev;
116 		write_unlock(&ibdev->roce.netdev_lock);
117 		break;
118 
119 	case NETDEV_UP:
120 	case NETDEV_DOWN: {
121 		if_t upper = NULL;
122 
123 		if ((upper == ndev || (!upper && ndev == ibdev->roce.netdev))
124 		    && ibdev->ib_active) {
125 			struct ib_event ibev = {0};
126 
127 			ibev.device = &ibdev->ib_dev;
128 			ibev.event = (event == NETDEV_UP) ?
129 				     IB_EVENT_PORT_ACTIVE : IB_EVENT_PORT_ERR;
130 			ibev.element.port_num = 1;
131 			ib_dispatch_event(&ibev);
132 		}
133 		break;
134 	}
135 
136 	default:
137 		break;
138 	}
139 
140 	return NOTIFY_DONE;
141 }
142 
143 static if_t mlx5_ib_get_netdev(struct ib_device *device,
144 					     u8 port_num)
145 {
146 	struct mlx5_ib_dev *ibdev = to_mdev(device);
147 	if_t ndev;
148 
149 	/* Ensure ndev does not disappear before we invoke if_ref()
150 	 */
151 	read_lock(&ibdev->roce.netdev_lock);
152 	ndev = ibdev->roce.netdev;
153 	if (ndev)
154 		if_ref(ndev);
155 	read_unlock(&ibdev->roce.netdev_lock);
156 
157 	return ndev;
158 }
159 
160 static int translate_eth_proto_oper(u32 eth_proto_oper, u8 *active_speed,
161 				    u8 *active_width)
162 {
163 	switch (eth_proto_oper) {
164 	case MLX5E_PROT_MASK(MLX5E_1000BASE_CX_SGMII):
165 	case MLX5E_PROT_MASK(MLX5E_1000BASE_KX):
166 	case MLX5E_PROT_MASK(MLX5E_100BASE_TX):
167 	case MLX5E_PROT_MASK(MLX5E_1000BASE_T):
168 		*active_width = IB_WIDTH_1X;
169 		*active_speed = IB_SPEED_SDR;
170 		break;
171 	case MLX5E_PROT_MASK(MLX5E_10GBASE_T):
172 	case MLX5E_PROT_MASK(MLX5E_10GBASE_CX4):
173 	case MLX5E_PROT_MASK(MLX5E_10GBASE_KX4):
174 	case MLX5E_PROT_MASK(MLX5E_10GBASE_KR):
175 	case MLX5E_PROT_MASK(MLX5E_10GBASE_CR):
176 	case MLX5E_PROT_MASK(MLX5E_10GBASE_SR):
177 	case MLX5E_PROT_MASK(MLX5E_10GBASE_ER_LR):
178 		*active_width = IB_WIDTH_1X;
179 		*active_speed = IB_SPEED_QDR;
180 		break;
181 	case MLX5E_PROT_MASK(MLX5E_25GBASE_CR):
182 	case MLX5E_PROT_MASK(MLX5E_25GBASE_KR):
183 	case MLX5E_PROT_MASK(MLX5E_25GBASE_SR):
184 		*active_width = IB_WIDTH_1X;
185 		*active_speed = IB_SPEED_EDR;
186 		break;
187 	case MLX5E_PROT_MASK(MLX5E_40GBASE_CR4):
188 	case MLX5E_PROT_MASK(MLX5E_40GBASE_KR4):
189 	case MLX5E_PROT_MASK(MLX5E_40GBASE_SR4):
190 	case MLX5E_PROT_MASK(MLX5E_40GBASE_LR4_ER4):
191 		*active_width = IB_WIDTH_4X;
192 		*active_speed = IB_SPEED_QDR;
193 		break;
194 	case MLX5E_PROT_MASK(MLX5E_50GBASE_CR2):
195 	case MLX5E_PROT_MASK(MLX5E_50GBASE_KR2):
196 	case MLX5E_PROT_MASK(MLX5E_50GBASE_KR4):
197 	case MLX5E_PROT_MASK(MLX5E_50GBASE_SR2):
198 		*active_width = IB_WIDTH_1X;
199 		*active_speed = IB_SPEED_HDR;
200 		break;
201 	case MLX5E_PROT_MASK(MLX5E_56GBASE_R4):
202 		*active_width = IB_WIDTH_4X;
203 		*active_speed = IB_SPEED_FDR;
204 		break;
205 	case MLX5E_PROT_MASK(MLX5E_100GBASE_CR4):
206 	case MLX5E_PROT_MASK(MLX5E_100GBASE_SR4):
207 	case MLX5E_PROT_MASK(MLX5E_100GBASE_KR4):
208 	case MLX5E_PROT_MASK(MLX5E_100GBASE_LR4):
209 		*active_width = IB_WIDTH_4X;
210 		*active_speed = IB_SPEED_EDR;
211 		break;
212 	default:
213 		*active_width = IB_WIDTH_4X;
214 		*active_speed = IB_SPEED_QDR;
215 		return -EINVAL;
216 	}
217 
218 	return 0;
219 }
220 
221 static int translate_eth_ext_proto_oper(u32 eth_proto_oper, u8 *active_speed,
222 					u8 *active_width)
223 {
224 	switch (eth_proto_oper) {
225 	case MLX5E_PROT_MASK(MLX5E_SGMII_100M):
226 	case MLX5E_PROT_MASK(MLX5E_1000BASE_X_SGMII):
227 		*active_width = IB_WIDTH_1X;
228 		*active_speed = IB_SPEED_SDR;
229 		break;
230 	case MLX5E_PROT_MASK(MLX5E_5GBASE_R):
231 		*active_width = IB_WIDTH_1X;
232 		*active_speed = IB_SPEED_DDR;
233 		break;
234 	case MLX5E_PROT_MASK(MLX5E_10GBASE_XFI_XAUI_1):
235 		*active_width = IB_WIDTH_1X;
236 		*active_speed = IB_SPEED_QDR;
237 		break;
238 	case MLX5E_PROT_MASK(MLX5E_40GBASE_XLAUI_4_XLPPI_4):
239 		*active_width = IB_WIDTH_4X;
240 		*active_speed = IB_SPEED_QDR;
241 		break;
242 	case MLX5E_PROT_MASK(MLX5E_25GAUI_1_25GBASE_CR_KR):
243 		*active_width = IB_WIDTH_1X;
244 		*active_speed = IB_SPEED_EDR;
245 		break;
246 	case MLX5E_PROT_MASK(MLX5E_50GAUI_2_LAUI_2_50GBASE_CR2_KR2):
247 		*active_width = IB_WIDTH_2X;
248 		*active_speed = IB_SPEED_EDR;
249 		break;
250 	case MLX5E_PROT_MASK(MLX5E_50GAUI_1_LAUI_1_50GBASE_CR_KR):
251 		*active_width = IB_WIDTH_1X;
252 		*active_speed = IB_SPEED_HDR;
253 		break;
254 	case MLX5E_PROT_MASK(MLX5E_CAUI_4_100GBASE_CR4_KR4):
255 		*active_width = IB_WIDTH_4X;
256 		*active_speed = IB_SPEED_EDR;
257 		break;
258 	case MLX5E_PROT_MASK(MLX5E_100GAUI_2_100GBASE_CR2_KR2):
259 		*active_width = IB_WIDTH_2X;
260 		*active_speed = IB_SPEED_HDR;
261 		break;
262 	case MLX5E_PROT_MASK(MLX5E_100GAUI_1_100GBASE_CR_KR):
263 		*active_width = IB_WIDTH_1X;
264 		*active_speed = IB_SPEED_NDR;
265 		break;
266 	case MLX5E_PROT_MASK(MLX5E_200GAUI_4_200GBASE_CR4_KR4):
267 		*active_width = IB_WIDTH_4X;
268 		*active_speed = IB_SPEED_HDR;
269 		break;
270 	case MLX5E_PROT_MASK(MLX5E_200GAUI_2_200GBASE_CR2_KR2):
271 		*active_width = IB_WIDTH_2X;
272 		*active_speed = IB_SPEED_NDR;
273 		break;
274 	case MLX5E_PROT_MASK(MLX5E_400GAUI_4_400GBASE_CR4_KR4):
275 		*active_width = IB_WIDTH_4X;
276 		*active_speed = IB_SPEED_NDR;
277 		break;
278 	default:
279 		*active_width = IB_WIDTH_4X;
280 		*active_speed = IB_SPEED_QDR;
281 		return -EINVAL;
282 	}
283 
284 	return 0;
285 }
286 
287 static int mlx5_query_port_roce(struct ib_device *device, u8 port_num,
288 				struct ib_port_attr *props)
289 {
290 	struct mlx5_ib_dev *dev = to_mdev(device);
291 	u32 out[MLX5_ST_SZ_DW(ptys_reg)] = {};
292 	if_t ndev;
293 	enum ib_mtu ndev_ib_mtu;
294 	u16 qkey_viol_cntr;
295 	u32 eth_prot_oper;
296 	bool ext;
297 	int err;
298 
299 	memset(props, 0, sizeof(*props));
300 
301 	/* Possible bad flows are checked before filling out props so in case
302 	 * of an error it will still be zeroed out.
303 	 */
304 	err = mlx5_query_port_ptys(dev->mdev, out, sizeof(out), MLX5_PTYS_EN,
305 	    port_num);
306 	if (err)
307 		return err;
308 
309 	ext = MLX5_CAP_PCAM_FEATURE(dev->mdev, ptys_extended_ethernet);
310 	eth_prot_oper = MLX5_GET_ETH_PROTO(ptys_reg, out, ext, eth_proto_oper);
311 
312 	if (ext)
313 		translate_eth_ext_proto_oper(eth_prot_oper, &props->active_speed,
314 		    &props->active_width);
315 	else
316 		translate_eth_proto_oper(eth_prot_oper, &props->active_speed,
317 		    &props->active_width);
318 
319 	props->port_cap_flags  |= IB_PORT_CM_SUP;
320 	props->port_cap_flags  |= IB_PORT_IP_BASED_GIDS;
321 
322 	props->gid_tbl_len      = MLX5_CAP_ROCE(dev->mdev,
323 						roce_address_table_size);
324 	props->max_mtu          = IB_MTU_4096;
325 	props->max_msg_sz       = 1 << MLX5_CAP_GEN(dev->mdev, log_max_msg);
326 	props->pkey_tbl_len     = 1;
327 	props->state            = IB_PORT_DOWN;
328 	props->phys_state       = IB_PORT_PHYS_STATE_DISABLED;
329 
330 	mlx5_query_nic_vport_qkey_viol_cntr(dev->mdev, &qkey_viol_cntr);
331 	props->qkey_viol_cntr = qkey_viol_cntr;
332 
333 	ndev = mlx5_ib_get_netdev(device, port_num);
334 	if (!ndev)
335 		return 0;
336 
337 	if (if_getdrvflags(ndev) & IFF_DRV_RUNNING &&
338 	    if_getlinkstate(ndev) == LINK_STATE_UP) {
339 		props->state      = IB_PORT_ACTIVE;
340 		props->phys_state = IB_PORT_PHYS_STATE_LINK_UP;
341 	}
342 
343 	ndev_ib_mtu = iboe_get_mtu(if_getmtu(ndev));
344 
345 	if_rele(ndev);
346 
347 	props->active_mtu	= min(props->max_mtu, ndev_ib_mtu);
348 	return 0;
349 }
350 
351 static void ib_gid_to_mlx5_roce_addr(const union ib_gid *gid,
352 				     const struct ib_gid_attr *attr,
353 				     void *mlx5_addr)
354 {
355 #define MLX5_SET_RA(p, f, v) MLX5_SET(roce_addr_layout, p, f, v)
356 	char *mlx5_addr_l3_addr	= MLX5_ADDR_OF(roce_addr_layout, mlx5_addr,
357 					       source_l3_address);
358 	void *mlx5_addr_mac	= MLX5_ADDR_OF(roce_addr_layout, mlx5_addr,
359 					       source_mac_47_32);
360 	u16 vlan_id;
361 
362 	if (!gid)
363 		return;
364 	ether_addr_copy(mlx5_addr_mac, if_getlladdr(attr->ndev));
365 
366 	vlan_id = rdma_vlan_dev_vlan_id(attr->ndev);
367 	if (vlan_id != 0xffff) {
368 		MLX5_SET_RA(mlx5_addr, vlan_valid, 1);
369 		MLX5_SET_RA(mlx5_addr, vlan_id, vlan_id);
370 	}
371 
372 	switch (attr->gid_type) {
373 	case IB_GID_TYPE_IB:
374 		MLX5_SET_RA(mlx5_addr, roce_version, MLX5_ROCE_VERSION_1);
375 		break;
376 	case IB_GID_TYPE_ROCE_UDP_ENCAP:
377 		MLX5_SET_RA(mlx5_addr, roce_version, MLX5_ROCE_VERSION_2);
378 		break;
379 
380 	default:
381 		WARN_ON(true);
382 	}
383 
384 	if (attr->gid_type != IB_GID_TYPE_IB) {
385 		if (ipv6_addr_v4mapped((void *)gid))
386 			MLX5_SET_RA(mlx5_addr, roce_l3_type,
387 				    MLX5_ROCE_L3_TYPE_IPV4);
388 		else
389 			MLX5_SET_RA(mlx5_addr, roce_l3_type,
390 				    MLX5_ROCE_L3_TYPE_IPV6);
391 	}
392 
393 	if ((attr->gid_type == IB_GID_TYPE_IB) ||
394 	    !ipv6_addr_v4mapped((void *)gid))
395 		memcpy(mlx5_addr_l3_addr, gid, sizeof(*gid));
396 	else
397 		memcpy(&mlx5_addr_l3_addr[12], &gid->raw[12], 4);
398 }
399 
400 static int set_roce_addr(struct ib_device *device, u8 port_num,
401 			 unsigned int index,
402 			 const union ib_gid *gid,
403 			 const struct ib_gid_attr *attr)
404 {
405 	struct mlx5_ib_dev *dev = to_mdev(device);
406 	u32  in[MLX5_ST_SZ_DW(set_roce_address_in)]  = {0};
407 	u32 out[MLX5_ST_SZ_DW(set_roce_address_out)] = {0};
408 	void *in_addr = MLX5_ADDR_OF(set_roce_address_in, in, roce_address);
409 	enum rdma_link_layer ll = mlx5_ib_port_link_layer(device, port_num);
410 
411 	if (ll != IB_LINK_LAYER_ETHERNET)
412 		return -EINVAL;
413 
414 	ib_gid_to_mlx5_roce_addr(gid, attr, in_addr);
415 
416 	MLX5_SET(set_roce_address_in, in, roce_address_index, index);
417 	MLX5_SET(set_roce_address_in, in, opcode, MLX5_CMD_OP_SET_ROCE_ADDRESS);
418 	return mlx5_cmd_exec(dev->mdev, in, sizeof(in), out, sizeof(out));
419 }
420 
421 static int mlx5_ib_add_gid(struct ib_device *device, u8 port_num,
422 			   unsigned int index, const union ib_gid *gid,
423 			   const struct ib_gid_attr *attr,
424 			   __always_unused void **context)
425 {
426 	return set_roce_addr(device, port_num, index, gid, attr);
427 }
428 
429 static int mlx5_ib_del_gid(struct ib_device *device, u8 port_num,
430 			   unsigned int index, __always_unused void **context)
431 {
432 	return set_roce_addr(device, port_num, index, NULL, NULL);
433 }
434 
435 __be16 mlx5_get_roce_udp_sport(struct mlx5_ib_dev *dev, u8 port_num,
436 			       int index)
437 {
438 	struct ib_gid_attr attr;
439 	union ib_gid gid;
440 
441 	if (ib_get_cached_gid(&dev->ib_dev, port_num, index, &gid, &attr))
442 		return 0;
443 
444 	if (!attr.ndev)
445 		return 0;
446 
447 	if_rele(attr.ndev);
448 
449 	if (attr.gid_type != IB_GID_TYPE_ROCE_UDP_ENCAP)
450 		return 0;
451 
452 	return cpu_to_be16(MLX5_CAP_ROCE(dev->mdev, r_roce_min_src_udp_port));
453 }
454 
455 int mlx5_get_roce_gid_type(struct mlx5_ib_dev *dev, u8 port_num,
456 			   int index, enum ib_gid_type *gid_type)
457 {
458 	struct ib_gid_attr attr;
459 	union ib_gid gid;
460 	int ret;
461 
462 	ret = ib_get_cached_gid(&dev->ib_dev, port_num, index, &gid, &attr);
463 	if (ret)
464 		return ret;
465 
466 	if (!attr.ndev)
467 		return -ENODEV;
468 
469 	if_rele(attr.ndev);
470 
471 	*gid_type = attr.gid_type;
472 
473 	return 0;
474 }
475 
476 static int mlx5_use_mad_ifc(struct mlx5_ib_dev *dev)
477 {
478 	if (MLX5_CAP_GEN(dev->mdev, port_type) == MLX5_CAP_PORT_TYPE_IB)
479 		return !MLX5_CAP_GEN(dev->mdev, ib_virt);
480 	return 0;
481 }
482 
483 enum {
484 	MLX5_VPORT_ACCESS_METHOD_MAD,
485 	MLX5_VPORT_ACCESS_METHOD_HCA,
486 	MLX5_VPORT_ACCESS_METHOD_NIC,
487 };
488 
489 static int mlx5_get_vport_access_method(struct ib_device *ibdev)
490 {
491 	if (mlx5_use_mad_ifc(to_mdev(ibdev)))
492 		return MLX5_VPORT_ACCESS_METHOD_MAD;
493 
494 	if (mlx5_ib_port_link_layer(ibdev, 1) ==
495 	    IB_LINK_LAYER_ETHERNET)
496 		return MLX5_VPORT_ACCESS_METHOD_NIC;
497 
498 	return MLX5_VPORT_ACCESS_METHOD_HCA;
499 }
500 
501 static void get_atomic_caps(struct mlx5_ib_dev *dev,
502 			    struct ib_device_attr *props)
503 {
504 	u8 tmp;
505 	u8 atomic_operations = MLX5_CAP_ATOMIC(dev->mdev, atomic_operations);
506 	u8 atomic_size_qp = MLX5_CAP_ATOMIC(dev->mdev, atomic_size_qp);
507 	u8 atomic_req_8B_endianness_mode =
508 		MLX5_CAP_ATOMIC(dev->mdev, atomic_req_8B_endianess_mode);
509 
510 	/* Check if HW supports 8 bytes standard atomic operations and capable
511 	 * of host endianness respond
512 	 */
513 	tmp = MLX5_ATOMIC_OPS_CMP_SWAP | MLX5_ATOMIC_OPS_FETCH_ADD;
514 	if (((atomic_operations & tmp) == tmp) &&
515 	    (atomic_size_qp & MLX5_ATOMIC_SIZE_QP_8BYTES) &&
516 	    (atomic_req_8B_endianness_mode)) {
517 		props->atomic_cap = IB_ATOMIC_HCA;
518 	} else {
519 		props->atomic_cap = IB_ATOMIC_NONE;
520 	}
521 }
522 
523 static int mlx5_query_system_image_guid(struct ib_device *ibdev,
524 					__be64 *sys_image_guid)
525 {
526 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
527 	struct mlx5_core_dev *mdev = dev->mdev;
528 	u64 tmp;
529 	int err;
530 
531 	switch (mlx5_get_vport_access_method(ibdev)) {
532 	case MLX5_VPORT_ACCESS_METHOD_MAD:
533 		return mlx5_query_mad_ifc_system_image_guid(ibdev,
534 							    sys_image_guid);
535 
536 	case MLX5_VPORT_ACCESS_METHOD_HCA:
537 		err = mlx5_query_hca_vport_system_image_guid(mdev, &tmp);
538 		break;
539 
540 	case MLX5_VPORT_ACCESS_METHOD_NIC:
541 		err = mlx5_query_nic_vport_system_image_guid(mdev, &tmp);
542 		break;
543 
544 	default:
545 		return -EINVAL;
546 	}
547 
548 	if (!err)
549 		*sys_image_guid = cpu_to_be64(tmp);
550 
551 	return err;
552 
553 }
554 
555 static int mlx5_query_max_pkeys(struct ib_device *ibdev,
556 				u16 *max_pkeys)
557 {
558 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
559 	struct mlx5_core_dev *mdev = dev->mdev;
560 
561 	switch (mlx5_get_vport_access_method(ibdev)) {
562 	case MLX5_VPORT_ACCESS_METHOD_MAD:
563 		return mlx5_query_mad_ifc_max_pkeys(ibdev, max_pkeys);
564 
565 	case MLX5_VPORT_ACCESS_METHOD_HCA:
566 	case MLX5_VPORT_ACCESS_METHOD_NIC:
567 		*max_pkeys = mlx5_to_sw_pkey_sz(MLX5_CAP_GEN(mdev,
568 						pkey_table_size));
569 		return 0;
570 
571 	default:
572 		return -EINVAL;
573 	}
574 }
575 
576 static int mlx5_query_vendor_id(struct ib_device *ibdev,
577 				u32 *vendor_id)
578 {
579 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
580 
581 	switch (mlx5_get_vport_access_method(ibdev)) {
582 	case MLX5_VPORT_ACCESS_METHOD_MAD:
583 		return mlx5_query_mad_ifc_vendor_id(ibdev, vendor_id);
584 
585 	case MLX5_VPORT_ACCESS_METHOD_HCA:
586 	case MLX5_VPORT_ACCESS_METHOD_NIC:
587 		return mlx5_core_query_vendor_id(dev->mdev, vendor_id);
588 
589 	default:
590 		return -EINVAL;
591 	}
592 }
593 
594 static int mlx5_query_node_guid(struct mlx5_ib_dev *dev,
595 				__be64 *node_guid)
596 {
597 	u64 tmp;
598 	int err;
599 
600 	switch (mlx5_get_vport_access_method(&dev->ib_dev)) {
601 	case MLX5_VPORT_ACCESS_METHOD_MAD:
602 		return mlx5_query_mad_ifc_node_guid(dev, node_guid);
603 
604 	case MLX5_VPORT_ACCESS_METHOD_HCA:
605 		err = mlx5_query_hca_vport_node_guid(dev->mdev, &tmp);
606 		break;
607 
608 	case MLX5_VPORT_ACCESS_METHOD_NIC:
609 		err = mlx5_query_nic_vport_node_guid(dev->mdev, &tmp);
610 		break;
611 
612 	default:
613 		return -EINVAL;
614 	}
615 
616 	if (!err)
617 		*node_guid = cpu_to_be64(tmp);
618 
619 	return err;
620 }
621 
622 struct mlx5_reg_node_desc {
623 	u8	desc[IB_DEVICE_NODE_DESC_MAX];
624 };
625 
626 static int mlx5_query_node_desc(struct mlx5_ib_dev *dev, char *node_desc)
627 {
628 	struct mlx5_reg_node_desc in;
629 
630 	if (mlx5_use_mad_ifc(dev))
631 		return mlx5_query_mad_ifc_node_desc(dev, node_desc);
632 
633 	memset(&in, 0, sizeof(in));
634 
635 	return mlx5_core_access_reg(dev->mdev, &in, sizeof(in), node_desc,
636 				    sizeof(struct mlx5_reg_node_desc),
637 				    MLX5_REG_NODE_DESC, 0, 0);
638 }
639 
640 static int mlx5_ib_query_device(struct ib_device *ibdev,
641 				struct ib_device_attr *props,
642 				struct ib_udata *uhw)
643 {
644 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
645 	struct mlx5_core_dev *mdev = dev->mdev;
646 	int err = -ENOMEM;
647 	int max_sq_desc;
648 	int max_rq_sg;
649 	int max_sq_sg;
650 	u64 min_page_size = 1ull << MLX5_CAP_GEN(mdev, log_pg_sz);
651 	struct mlx5_ib_query_device_resp resp = {};
652 	size_t resp_len;
653 	u64 max_tso;
654 
655 	resp_len = sizeof(resp.comp_mask) + sizeof(resp.response_length);
656 	if (uhw->outlen && uhw->outlen < resp_len)
657 		return -EINVAL;
658 	else
659 		resp.response_length = resp_len;
660 
661 	if (uhw->inlen && !ib_is_udata_cleared(uhw, 0, uhw->inlen))
662 		return -EINVAL;
663 
664 	memset(props, 0, sizeof(*props));
665 	err = mlx5_query_system_image_guid(ibdev,
666 					   &props->sys_image_guid);
667 	if (err)
668 		return err;
669 
670 	err = mlx5_query_max_pkeys(ibdev, &props->max_pkeys);
671 	if (err)
672 		return err;
673 
674 	err = mlx5_query_vendor_id(ibdev, &props->vendor_id);
675 	if (err)
676 		return err;
677 
678 	props->fw_ver = ((u64)fw_rev_maj(dev->mdev) << 32) |
679 		((u32)fw_rev_min(dev->mdev) << 16) |
680 		fw_rev_sub(dev->mdev);
681 	props->device_cap_flags    = IB_DEVICE_CHANGE_PHY_PORT |
682 		IB_DEVICE_PORT_ACTIVE_EVENT		|
683 		IB_DEVICE_SYS_IMAGE_GUID		|
684 		IB_DEVICE_RC_RNR_NAK_GEN		|
685 		IB_DEVICE_KNOWSEPOCH;
686 
687 	if (MLX5_CAP_GEN(mdev, pkv))
688 		props->device_cap_flags |= IB_DEVICE_BAD_PKEY_CNTR;
689 	if (MLX5_CAP_GEN(mdev, qkv))
690 		props->device_cap_flags |= IB_DEVICE_BAD_QKEY_CNTR;
691 	if (MLX5_CAP_GEN(mdev, apm))
692 		props->device_cap_flags |= IB_DEVICE_AUTO_PATH_MIG;
693 	if (MLX5_CAP_GEN(mdev, xrc))
694 		props->device_cap_flags |= IB_DEVICE_XRC;
695 	if (MLX5_CAP_GEN(mdev, imaicl)) {
696 		props->device_cap_flags |= IB_DEVICE_MEM_WINDOW |
697 					   IB_DEVICE_MEM_WINDOW_TYPE_2B;
698 		props->max_mw = 1 << MLX5_CAP_GEN(mdev, log_max_mkey);
699 		/* We support 'Gappy' memory registration too */
700 		props->device_cap_flags |= IB_DEVICE_SG_GAPS_REG;
701 	}
702 	props->device_cap_flags |= IB_DEVICE_MEM_MGT_EXTENSIONS;
703 	if (MLX5_CAP_GEN(mdev, sho)) {
704 		props->device_cap_flags |= IB_DEVICE_SIGNATURE_HANDOVER;
705 		/* At this stage no support for signature handover */
706 		props->sig_prot_cap = IB_PROT_T10DIF_TYPE_1 |
707 				      IB_PROT_T10DIF_TYPE_2 |
708 				      IB_PROT_T10DIF_TYPE_3;
709 		props->sig_guard_cap = IB_GUARD_T10DIF_CRC |
710 				       IB_GUARD_T10DIF_CSUM;
711 	}
712 	if (MLX5_CAP_GEN(mdev, block_lb_mc))
713 		props->device_cap_flags |= IB_DEVICE_BLOCK_MULTICAST_LOOPBACK;
714 
715 	if (MLX5_CAP_GEN(dev->mdev, eth_net_offloads)) {
716 		if (MLX5_CAP_ETH(mdev, csum_cap))
717 			props->device_cap_flags |= IB_DEVICE_RAW_IP_CSUM;
718 
719 		if (field_avail(typeof(resp), tso_caps, uhw->outlen)) {
720 			max_tso = MLX5_CAP_ETH(mdev, max_lso_cap);
721 			if (max_tso) {
722 				resp.tso_caps.max_tso = 1 << max_tso;
723 				resp.tso_caps.supported_qpts |=
724 					1 << IB_QPT_RAW_PACKET;
725 				resp.response_length += sizeof(resp.tso_caps);
726 			}
727 		}
728 
729 		if (field_avail(typeof(resp), rss_caps, uhw->outlen)) {
730 			resp.rss_caps.rx_hash_function =
731 						MLX5_RX_HASH_FUNC_TOEPLITZ;
732 			resp.rss_caps.rx_hash_fields_mask =
733 						MLX5_RX_HASH_SRC_IPV4 |
734 						MLX5_RX_HASH_DST_IPV4 |
735 						MLX5_RX_HASH_SRC_IPV6 |
736 						MLX5_RX_HASH_DST_IPV6 |
737 						MLX5_RX_HASH_SRC_PORT_TCP |
738 						MLX5_RX_HASH_DST_PORT_TCP |
739 						MLX5_RX_HASH_SRC_PORT_UDP |
740 						MLX5_RX_HASH_DST_PORT_UDP;
741 			resp.response_length += sizeof(resp.rss_caps);
742 		}
743 	} else {
744 		if (field_avail(typeof(resp), tso_caps, uhw->outlen))
745 			resp.response_length += sizeof(resp.tso_caps);
746 		if (field_avail(typeof(resp), rss_caps, uhw->outlen))
747 			resp.response_length += sizeof(resp.rss_caps);
748 	}
749 
750 	if (MLX5_CAP_GEN(mdev, ipoib_ipoib_offloads)) {
751 		props->device_cap_flags |= IB_DEVICE_UD_IP_CSUM;
752 		props->device_cap_flags |= IB_DEVICE_UD_TSO;
753 	}
754 
755 	if (MLX5_CAP_GEN(dev->mdev, eth_net_offloads) &&
756 	    MLX5_CAP_ETH(dev->mdev, scatter_fcs))
757 		props->device_cap_flags |= IB_DEVICE_RAW_SCATTER_FCS;
758 
759 	if (mlx5_get_flow_namespace(dev->mdev, MLX5_FLOW_NAMESPACE_BYPASS))
760 		props->device_cap_flags |= IB_DEVICE_MANAGED_FLOW_STEERING;
761 
762 	props->vendor_part_id	   = mdev->pdev->device;
763 	props->hw_ver		   = mdev->pdev->revision;
764 
765 	props->max_mr_size	   = ~0ull;
766 	props->page_size_cap	   = ~(min_page_size - 1);
767 	props->max_qp		   = 1 << MLX5_CAP_GEN(mdev, log_max_qp);
768 	props->max_qp_wr	   = 1 << MLX5_CAP_GEN(mdev, log_max_qp_sz);
769 	max_rq_sg =  MLX5_CAP_GEN(mdev, max_wqe_sz_rq) /
770 		     sizeof(struct mlx5_wqe_data_seg);
771 	max_sq_desc = min_t(int, MLX5_CAP_GEN(mdev, max_wqe_sz_sq), 512);
772 	max_sq_sg = (max_sq_desc - sizeof(struct mlx5_wqe_ctrl_seg) -
773 		     sizeof(struct mlx5_wqe_raddr_seg)) /
774 		sizeof(struct mlx5_wqe_data_seg);
775 	props->max_sge = min(max_rq_sg, max_sq_sg);
776 	props->max_sge_rd	   = MLX5_MAX_SGE_RD;
777 	props->max_cq		   = 1 << MLX5_CAP_GEN(mdev, log_max_cq);
778 	props->max_cqe = (1 << MLX5_CAP_GEN(mdev, log_max_cq_sz)) - 1;
779 	props->max_mr		   = 1 << MLX5_CAP_GEN(mdev, log_max_mkey);
780 	props->max_pd		   = 1 << MLX5_CAP_GEN(mdev, log_max_pd);
781 	props->max_qp_rd_atom	   = 1 << MLX5_CAP_GEN(mdev, log_max_ra_req_qp);
782 	props->max_qp_init_rd_atom = 1 << MLX5_CAP_GEN(mdev, log_max_ra_res_qp);
783 	props->max_srq		   = 1 << MLX5_CAP_GEN(mdev, log_max_srq);
784 	props->max_srq_wr = (1 << MLX5_CAP_GEN(mdev, log_max_srq_sz)) - 1;
785 	props->local_ca_ack_delay  = MLX5_CAP_GEN(mdev, local_ca_ack_delay);
786 	props->max_res_rd_atom	   = props->max_qp_rd_atom * props->max_qp;
787 	props->max_srq_sge	   = max_rq_sg - 1;
788 	props->max_fast_reg_page_list_len =
789 		1 << MLX5_CAP_GEN(mdev, log_max_klm_list_size);
790 	get_atomic_caps(dev, props);
791 	props->masked_atomic_cap   = IB_ATOMIC_NONE;
792 	props->max_mcast_grp	   = 1 << MLX5_CAP_GEN(mdev, log_max_mcg);
793 	props->max_mcast_qp_attach = MLX5_CAP_GEN(mdev, max_qp_mcg);
794 	props->max_total_mcast_qp_attach = props->max_mcast_qp_attach *
795 					   props->max_mcast_grp;
796 	props->max_map_per_fmr = INT_MAX; /* no limit in ConnectIB */
797 	props->hca_core_clock = MLX5_CAP_GEN(mdev, device_frequency_khz);
798 	props->timestamp_mask = 0x7FFFFFFFFFFFFFFFULL;
799 
800 #ifdef CONFIG_INFINIBAND_ON_DEMAND_PAGING
801 	if (MLX5_CAP_GEN(mdev, pg))
802 		props->device_cap_flags |= IB_DEVICE_ON_DEMAND_PAGING;
803 	props->odp_caps = dev->odp_caps;
804 #endif
805 
806 	if (MLX5_CAP_GEN(mdev, cd))
807 		props->device_cap_flags |= IB_DEVICE_CROSS_CHANNEL;
808 
809 	if (!mlx5_core_is_pf(mdev))
810 		props->device_cap_flags |= IB_DEVICE_VIRTUAL_FUNCTION;
811 
812 	if (mlx5_ib_port_link_layer(ibdev, 1) ==
813 	    IB_LINK_LAYER_ETHERNET) {
814 		props->rss_caps.max_rwq_indirection_tables =
815 			1 << MLX5_CAP_GEN(dev->mdev, log_max_rqt);
816 		props->rss_caps.max_rwq_indirection_table_size =
817 			1 << MLX5_CAP_GEN(dev->mdev, log_max_rqt_size);
818 		props->rss_caps.supported_qpts = 1 << IB_QPT_RAW_PACKET;
819 		props->max_wq_type_rq =
820 			1 << MLX5_CAP_GEN(dev->mdev, log_max_rq);
821 	}
822 
823 	if (uhw->outlen) {
824 		err = ib_copy_to_udata(uhw, &resp, resp.response_length);
825 
826 		if (err)
827 			return err;
828 	}
829 
830 	return 0;
831 }
832 
833 enum mlx5_ib_width {
834 	MLX5_IB_WIDTH_1X	= 1 << 0,
835 	MLX5_IB_WIDTH_2X	= 1 << 1,
836 	MLX5_IB_WIDTH_4X	= 1 << 2,
837 	MLX5_IB_WIDTH_8X	= 1 << 3,
838 	MLX5_IB_WIDTH_12X	= 1 << 4
839 };
840 
841 static int translate_active_width(struct ib_device *ibdev, u8 active_width,
842 				  u8 *ib_width)
843 {
844 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
845 	int err = 0;
846 
847 	if (active_width & MLX5_IB_WIDTH_1X) {
848 		*ib_width = IB_WIDTH_1X;
849 	} else if (active_width & MLX5_IB_WIDTH_2X) {
850 		*ib_width = IB_WIDTH_2X;
851 	} else if (active_width & MLX5_IB_WIDTH_4X) {
852 		*ib_width = IB_WIDTH_4X;
853 	} else if (active_width & MLX5_IB_WIDTH_8X) {
854 		*ib_width = IB_WIDTH_8X;
855 	} else if (active_width & MLX5_IB_WIDTH_12X) {
856 		*ib_width = IB_WIDTH_12X;
857 	} else {
858 		mlx5_ib_dbg(dev, "Invalid active_width %d\n",
859 			    (int)active_width);
860 		err = -EINVAL;
861 	}
862 
863 	return err;
864 }
865 
866 enum ib_max_vl_num {
867 	__IB_MAX_VL_0		= 1,
868 	__IB_MAX_VL_0_1		= 2,
869 	__IB_MAX_VL_0_3		= 3,
870 	__IB_MAX_VL_0_7		= 4,
871 	__IB_MAX_VL_0_14	= 5,
872 };
873 
874 enum mlx5_vl_hw_cap {
875 	MLX5_VL_HW_0	= 1,
876 	MLX5_VL_HW_0_1	= 2,
877 	MLX5_VL_HW_0_2	= 3,
878 	MLX5_VL_HW_0_3	= 4,
879 	MLX5_VL_HW_0_4	= 5,
880 	MLX5_VL_HW_0_5	= 6,
881 	MLX5_VL_HW_0_6	= 7,
882 	MLX5_VL_HW_0_7	= 8,
883 	MLX5_VL_HW_0_14	= 15
884 };
885 
886 static int translate_max_vl_num(struct ib_device *ibdev, u8 vl_hw_cap,
887 				u8 *max_vl_num)
888 {
889 	switch (vl_hw_cap) {
890 	case MLX5_VL_HW_0:
891 		*max_vl_num = __IB_MAX_VL_0;
892 		break;
893 	case MLX5_VL_HW_0_1:
894 		*max_vl_num = __IB_MAX_VL_0_1;
895 		break;
896 	case MLX5_VL_HW_0_3:
897 		*max_vl_num = __IB_MAX_VL_0_3;
898 		break;
899 	case MLX5_VL_HW_0_7:
900 		*max_vl_num = __IB_MAX_VL_0_7;
901 		break;
902 	case MLX5_VL_HW_0_14:
903 		*max_vl_num = __IB_MAX_VL_0_14;
904 		break;
905 
906 	default:
907 		return -EINVAL;
908 	}
909 
910 	return 0;
911 }
912 
913 static int mlx5_query_hca_port(struct ib_device *ibdev, u8 port,
914 			       struct ib_port_attr *props)
915 {
916 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
917 	struct mlx5_core_dev *mdev = dev->mdev;
918 	u32 *rep;
919 	int replen = MLX5_ST_SZ_BYTES(query_hca_vport_context_out);
920 	struct mlx5_ptys_reg *ptys;
921 	struct mlx5_pmtu_reg *pmtu;
922 	struct mlx5_pvlc_reg pvlc;
923 	void *ctx;
924 	int err;
925 
926 	rep = mlx5_vzalloc(replen);
927 	ptys = kzalloc(sizeof(*ptys), GFP_KERNEL);
928 	pmtu = kzalloc(sizeof(*pmtu), GFP_KERNEL);
929 	if (!rep || !ptys || !pmtu) {
930 		err = -ENOMEM;
931 		goto out;
932 	}
933 
934 	memset(props, 0, sizeof(*props));
935 
936 	err = mlx5_query_hca_vport_context(mdev, port, 0, rep, replen);
937 	if (err)
938 		goto out;
939 
940 	ctx = MLX5_ADDR_OF(query_hca_vport_context_out, rep, hca_vport_context);
941 
942 	props->lid		= MLX5_GET(hca_vport_context, ctx, lid);
943 	props->lmc		= MLX5_GET(hca_vport_context, ctx, lmc);
944 	props->sm_lid		= MLX5_GET(hca_vport_context, ctx, sm_lid);
945 	props->sm_sl		= MLX5_GET(hca_vport_context, ctx, sm_sl);
946 	props->state		= MLX5_GET(hca_vport_context, ctx, vport_state);
947 	props->phys_state	= MLX5_GET(hca_vport_context, ctx,
948 					port_physical_state);
949 	props->port_cap_flags	= MLX5_GET(hca_vport_context, ctx, cap_mask1);
950 	props->gid_tbl_len	= mlx5_get_gid_table_len(MLX5_CAP_GEN(mdev, gid_table_size));
951 	props->max_msg_sz	= 1 << MLX5_CAP_GEN(mdev, log_max_msg);
952 	props->pkey_tbl_len	= mlx5_to_sw_pkey_sz(MLX5_CAP_GEN(mdev, pkey_table_size));
953 	props->bad_pkey_cntr	= MLX5_GET(hca_vport_context, ctx,
954 					pkey_violation_counter);
955 	props->qkey_viol_cntr	= MLX5_GET(hca_vport_context, ctx,
956 					qkey_violation_counter);
957 	props->subnet_timeout	= MLX5_GET(hca_vport_context, ctx,
958 					subnet_timeout);
959 	props->init_type_reply	= MLX5_GET(hca_vport_context, ctx,
960 					init_type_reply);
961 	props->grh_required	= MLX5_GET(hca_vport_context, ctx, grh_required);
962 
963 	ptys->proto_mask |= MLX5_PTYS_IB;
964 	ptys->local_port = port;
965 	err = mlx5_core_access_ptys(mdev, ptys, 0);
966 	if (err)
967 		goto out;
968 
969 	err = translate_active_width(ibdev, ptys->ib_link_width_oper,
970 				     &props->active_width);
971 	if (err)
972 		goto out;
973 
974 	props->active_speed	= (u8)ptys->ib_proto_oper;
975 
976 	pmtu->local_port = port;
977 	err = mlx5_core_access_pmtu(mdev, pmtu, 0);
978 	if (err)
979 		goto out;
980 
981 	props->max_mtu		= pmtu->max_mtu;
982 	props->active_mtu	= pmtu->oper_mtu;
983 
984 	memset(&pvlc, 0, sizeof(pvlc));
985 	pvlc.local_port = port;
986 	err = mlx5_core_access_pvlc(mdev, &pvlc, 0);
987 	if (err)
988 		goto out;
989 
990 	err = translate_max_vl_num(ibdev, pvlc.vl_hw_cap,
991 				   &props->max_vl_num);
992 out:
993 	kvfree(rep);
994 	kfree(ptys);
995 	kfree(pmtu);
996 	return err;
997 }
998 
999 int mlx5_ib_query_port(struct ib_device *ibdev, u8 port,
1000 		       struct ib_port_attr *props)
1001 {
1002 	switch (mlx5_get_vport_access_method(ibdev)) {
1003 	case MLX5_VPORT_ACCESS_METHOD_MAD:
1004 		return mlx5_query_mad_ifc_port(ibdev, port, props);
1005 
1006 	case MLX5_VPORT_ACCESS_METHOD_HCA:
1007 		return mlx5_query_hca_port(ibdev, port, props);
1008 
1009 	case MLX5_VPORT_ACCESS_METHOD_NIC:
1010 		return mlx5_query_port_roce(ibdev, port, props);
1011 
1012 	default:
1013 		return -EINVAL;
1014 	}
1015 }
1016 
1017 static int mlx5_ib_query_gid(struct ib_device *ibdev, u8 port, int index,
1018 			     union ib_gid *gid)
1019 {
1020 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
1021 	struct mlx5_core_dev *mdev = dev->mdev;
1022 
1023 	switch (mlx5_get_vport_access_method(ibdev)) {
1024 	case MLX5_VPORT_ACCESS_METHOD_MAD:
1025 		return mlx5_query_mad_ifc_gids(ibdev, port, index, gid);
1026 
1027 	case MLX5_VPORT_ACCESS_METHOD_HCA:
1028 		return mlx5_query_hca_vport_gid(mdev, port, 0, index, gid);
1029 
1030 	default:
1031 		return -EINVAL;
1032 	}
1033 
1034 }
1035 
1036 static int mlx5_ib_query_pkey(struct ib_device *ibdev, u8 port, u16 index,
1037 			      u16 *pkey)
1038 {
1039 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
1040 	struct mlx5_core_dev *mdev = dev->mdev;
1041 
1042 	switch (mlx5_get_vport_access_method(ibdev)) {
1043 	case MLX5_VPORT_ACCESS_METHOD_MAD:
1044 		return mlx5_query_mad_ifc_pkey(ibdev, port, index, pkey);
1045 
1046 	case MLX5_VPORT_ACCESS_METHOD_HCA:
1047 	case MLX5_VPORT_ACCESS_METHOD_NIC:
1048 		return mlx5_query_hca_vport_pkey(mdev, 0, port,  0, index,
1049 						 pkey);
1050 	default:
1051 		return -EINVAL;
1052 	}
1053 }
1054 
1055 static int mlx5_ib_modify_device(struct ib_device *ibdev, int mask,
1056 				 struct ib_device_modify *props)
1057 {
1058 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
1059 	struct mlx5_reg_node_desc in;
1060 	struct mlx5_reg_node_desc out;
1061 	int err;
1062 
1063 	if (mask & ~IB_DEVICE_MODIFY_NODE_DESC)
1064 		return -EOPNOTSUPP;
1065 
1066 	if (!(mask & IB_DEVICE_MODIFY_NODE_DESC))
1067 		return 0;
1068 
1069 	/*
1070 	 * If possible, pass node desc to FW, so it can generate
1071 	 * a 144 trap.  If cmd fails, just ignore.
1072 	 */
1073 	memcpy(&in, props->node_desc, IB_DEVICE_NODE_DESC_MAX);
1074 	err = mlx5_core_access_reg(dev->mdev, &in, sizeof(in), &out,
1075 				   sizeof(out), MLX5_REG_NODE_DESC, 0, 1);
1076 	if (err)
1077 		return err;
1078 
1079 	memcpy(ibdev->node_desc, props->node_desc, IB_DEVICE_NODE_DESC_MAX);
1080 
1081 	return err;
1082 }
1083 
1084 static int mlx5_ib_modify_port(struct ib_device *ibdev, u8 port, int mask,
1085 			       struct ib_port_modify *props)
1086 {
1087 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
1088 	struct ib_port_attr attr;
1089 	u32 tmp;
1090 	int err;
1091 
1092 	/*
1093 	 * CM layer calls ib_modify_port() regardless of the link
1094 	 * layer. For Ethernet ports, qkey violation and Port
1095 	 * capabilities are meaningless.
1096 	 */
1097 	if (mlx5_ib_port_link_layer(ibdev, port) == IB_LINK_LAYER_ETHERNET)
1098 		return 0;
1099 
1100 	mutex_lock(&dev->cap_mask_mutex);
1101 
1102 	err = mlx5_ib_query_port(ibdev, port, &attr);
1103 	if (err)
1104 		goto out;
1105 
1106 	tmp = (attr.port_cap_flags | props->set_port_cap_mask) &
1107 		~props->clr_port_cap_mask;
1108 
1109 	err = mlx5_set_port_caps(dev->mdev, port, tmp);
1110 
1111 out:
1112 	mutex_unlock(&dev->cap_mask_mutex);
1113 	return err;
1114 }
1115 
1116 static void print_lib_caps(struct mlx5_ib_dev *dev, u64 caps)
1117 {
1118 	mlx5_ib_dbg(dev, "MLX5_LIB_CAP_4K_UAR = %s\n",
1119 		    caps & MLX5_LIB_CAP_4K_UAR ? "y" : "n");
1120 }
1121 
1122 static u16 calc_dynamic_bfregs(int uars_per_sys_page)
1123 {
1124 	/* Large page with non 4k uar support might limit the dynamic size */
1125 	if (uars_per_sys_page == 1  && PAGE_SIZE > 4096)
1126 		return MLX5_MIN_DYN_BFREGS;
1127 
1128 	return MLX5_MAX_DYN_BFREGS;
1129 }
1130 
1131 static int calc_total_bfregs(struct mlx5_ib_dev *dev, bool lib_uar_4k,
1132 			     struct mlx5_ib_alloc_ucontext_req_v2 *req,
1133 			     struct mlx5_bfreg_info *bfregi)
1134 {
1135 	int uars_per_sys_page;
1136 	int bfregs_per_sys_page;
1137 	int ref_bfregs = req->total_num_bfregs;
1138 
1139 	if (req->total_num_bfregs == 0)
1140 		return -EINVAL;
1141 
1142 	BUILD_BUG_ON(MLX5_MAX_BFREGS % MLX5_NON_FP_BFREGS_IN_PAGE);
1143 	BUILD_BUG_ON(MLX5_MAX_BFREGS < MLX5_NON_FP_BFREGS_IN_PAGE);
1144 
1145 	if (req->total_num_bfregs > MLX5_MAX_BFREGS)
1146 		return -ENOMEM;
1147 
1148 	uars_per_sys_page = get_uars_per_sys_page(dev, lib_uar_4k);
1149 	bfregs_per_sys_page = uars_per_sys_page * MLX5_NON_FP_BFREGS_PER_UAR;
1150 	/* This holds the required static allocation asked by the user */
1151 	req->total_num_bfregs = ALIGN(req->total_num_bfregs, bfregs_per_sys_page);
1152 	if (req->num_low_latency_bfregs > req->total_num_bfregs - 1)
1153 		return -EINVAL;
1154 
1155 	bfregi->num_static_sys_pages = req->total_num_bfregs / bfregs_per_sys_page;
1156 	bfregi->num_dyn_bfregs = ALIGN(calc_dynamic_bfregs(uars_per_sys_page), bfregs_per_sys_page);
1157 	bfregi->total_num_bfregs = req->total_num_bfregs + bfregi->num_dyn_bfregs;
1158 	bfregi->num_sys_pages = bfregi->total_num_bfregs / bfregs_per_sys_page;
1159 
1160 	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",
1161 		    MLX5_CAP_GEN(dev->mdev, uar_4k) ? "yes" : "no",
1162 		    lib_uar_4k ? "yes" : "no", ref_bfregs,
1163 		    req->total_num_bfregs, bfregi->total_num_bfregs,
1164 		    bfregi->num_sys_pages);
1165 
1166 	return 0;
1167 }
1168 
1169 static int allocate_uars(struct mlx5_ib_dev *dev, struct mlx5_ib_ucontext *context)
1170 {
1171 	struct mlx5_bfreg_info *bfregi;
1172 	int err;
1173 	int i;
1174 
1175 	bfregi = &context->bfregi;
1176 	for (i = 0; i < bfregi->num_static_sys_pages; i++) {
1177 		err = mlx5_cmd_alloc_uar(dev->mdev, &bfregi->sys_pages[i]);
1178 		if (err)
1179 			goto error;
1180 
1181 		mlx5_ib_dbg(dev, "allocated uar %d\n", bfregi->sys_pages[i]);
1182 	}
1183 
1184 	for (i = bfregi->num_static_sys_pages; i < bfregi->num_sys_pages; i++)
1185 		bfregi->sys_pages[i] = MLX5_IB_INVALID_UAR_INDEX;
1186 
1187 	return 0;
1188 
1189 error:
1190 	for (--i; i >= 0; i--)
1191 		if (mlx5_cmd_free_uar(dev->mdev, bfregi->sys_pages[i]))
1192 			mlx5_ib_warn(dev, "failed to free uar %d\n", i);
1193 
1194 	return err;
1195 }
1196 
1197 static void deallocate_uars(struct mlx5_ib_dev *dev,
1198 			    struct mlx5_ib_ucontext *context)
1199 {
1200 	struct mlx5_bfreg_info *bfregi;
1201 	int i;
1202 
1203 	bfregi = &context->bfregi;
1204 	for (i = 0; i < bfregi->num_sys_pages; i++)
1205 		if (i < bfregi->num_static_sys_pages ||
1206 		    bfregi->sys_pages[i] != MLX5_IB_INVALID_UAR_INDEX)
1207 			mlx5_cmd_free_uar(dev->mdev, bfregi->sys_pages[i]);
1208 }
1209 
1210 static int mlx5_ib_alloc_transport_domain(struct mlx5_ib_dev *dev, u32 *tdn,
1211 					  u16 uid)
1212 {
1213 	int err;
1214 
1215 	if (!MLX5_CAP_GEN(dev->mdev, log_max_transport_domain))
1216 		return 0;
1217 
1218 	err = mlx5_alloc_transport_domain(dev->mdev, tdn, uid);
1219 	if (err)
1220 		return err;
1221 
1222 	if ((MLX5_CAP_GEN(dev->mdev, port_type) != MLX5_CAP_PORT_TYPE_ETH) ||
1223 	    (!MLX5_CAP_GEN(dev->mdev, disable_local_lb_uc) &&
1224 	     !MLX5_CAP_GEN(dev->mdev, disable_local_lb_mc)))
1225 		return 0;
1226 
1227 	mutex_lock(&dev->lb_mutex);
1228 	dev->user_td++;
1229 
1230 	if (dev->user_td == 2)
1231 		err = mlx5_nic_vport_update_local_lb(dev->mdev, true);
1232 
1233 	mutex_unlock(&dev->lb_mutex);
1234 
1235 	if (err != 0)
1236 		mlx5_dealloc_transport_domain(dev->mdev, *tdn, uid);
1237 	return err;
1238 }
1239 
1240 static void mlx5_ib_dealloc_transport_domain(struct mlx5_ib_dev *dev, u32 tdn,
1241 					     u16 uid)
1242 {
1243 	if (!MLX5_CAP_GEN(dev->mdev, log_max_transport_domain))
1244 		return;
1245 
1246 	mlx5_dealloc_transport_domain(dev->mdev, tdn, uid);
1247 
1248 	if ((MLX5_CAP_GEN(dev->mdev, port_type) != MLX5_CAP_PORT_TYPE_ETH) ||
1249 	    (!MLX5_CAP_GEN(dev->mdev, disable_local_lb_uc) &&
1250 	     !MLX5_CAP_GEN(dev->mdev, disable_local_lb_mc)))
1251 		return;
1252 
1253 	mutex_lock(&dev->lb_mutex);
1254 	dev->user_td--;
1255 
1256 	if (dev->user_td < 2)
1257 		mlx5_nic_vport_update_local_lb(dev->mdev, false);
1258 
1259 	mutex_unlock(&dev->lb_mutex);
1260 }
1261 
1262 static int mlx5_ib_alloc_ucontext(struct ib_ucontext *uctx,
1263 				  struct ib_udata *udata)
1264 {
1265 	struct ib_device *ibdev = uctx->device;
1266 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
1267 	struct mlx5_ib_alloc_ucontext_req_v2 req = {};
1268 	struct mlx5_ib_alloc_ucontext_resp resp = {};
1269 	struct mlx5_ib_ucontext *context = to_mucontext(uctx);
1270 	struct mlx5_bfreg_info *bfregi;
1271 	int ver;
1272 	int err;
1273 	size_t min_req_v2 = offsetof(struct mlx5_ib_alloc_ucontext_req_v2,
1274 				     max_cqe_version);
1275 	bool lib_uar_4k;
1276 	bool lib_uar_dyn;
1277 
1278 	if (!dev->ib_active)
1279 		return -EAGAIN;
1280 
1281 	if (udata->inlen == sizeof(struct mlx5_ib_alloc_ucontext_req))
1282 		ver = 0;
1283 	else if (udata->inlen >= min_req_v2)
1284 		ver = 2;
1285 	else
1286 		return -EINVAL;
1287 
1288 	err = ib_copy_from_udata(&req, udata, min(udata->inlen, sizeof(req)));
1289 	if (err)
1290 		return err;
1291 
1292 	if (req.flags & ~MLX5_IB_ALLOC_UCTX_DEVX)
1293 		return -EOPNOTSUPP;
1294 
1295 	if (req.comp_mask || req.reserved0 || req.reserved1 || req.reserved2)
1296 		return -EOPNOTSUPP;
1297 
1298 	req.total_num_bfregs = ALIGN(req.total_num_bfregs,
1299 				    MLX5_NON_FP_BFREGS_PER_UAR);
1300 	if (req.num_low_latency_bfregs > req.total_num_bfregs - 1)
1301 		return -EINVAL;
1302 
1303 	resp.qp_tab_size = 1 << MLX5_CAP_GEN(dev->mdev, log_max_qp);
1304 	if (mlx5_core_is_pf(dev->mdev) && MLX5_CAP_GEN(dev->mdev, bf))
1305 		resp.bf_reg_size = 1 << MLX5_CAP_GEN(dev->mdev, log_bf_reg_size);
1306 	resp.cache_line_size = cache_line_size();
1307 	resp.max_sq_desc_sz = MLX5_CAP_GEN(dev->mdev, max_wqe_sz_sq);
1308 	resp.max_rq_desc_sz = MLX5_CAP_GEN(dev->mdev, max_wqe_sz_rq);
1309 	resp.max_send_wqebb = 1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz);
1310 	resp.max_recv_wr = 1 << MLX5_CAP_GEN(dev->mdev, log_max_qp_sz);
1311 	resp.max_srq_recv_wr = 1 << MLX5_CAP_GEN(dev->mdev, log_max_srq_sz);
1312 	resp.cqe_version = min_t(__u8,
1313 				 (__u8)MLX5_CAP_GEN(dev->mdev, cqe_version),
1314 				 req.max_cqe_version);
1315 	resp.log_uar_size = MLX5_CAP_GEN(dev->mdev, uar_4k) ?
1316 				MLX5_ADAPTER_PAGE_SHIFT : PAGE_SHIFT;
1317 	resp.num_uars_per_page = MLX5_CAP_GEN(dev->mdev, uar_4k) ?
1318 					MLX5_CAP_GEN(dev->mdev, num_of_uars_per_page) : 1;
1319 	resp.response_length = min(offsetof(typeof(resp), response_length) +
1320 				   sizeof(resp.response_length), udata->outlen);
1321 
1322 	lib_uar_4k = req.lib_caps & MLX5_LIB_CAP_4K_UAR;
1323 	lib_uar_dyn = req.lib_caps & MLX5_LIB_CAP_DYN_UAR;
1324 	bfregi = &context->bfregi;
1325 
1326 	if (lib_uar_dyn) {
1327 		bfregi->lib_uar_dyn = lib_uar_dyn;
1328 		goto uar_done;
1329 	}
1330 
1331 	/* updates req->total_num_bfregs */
1332 	err = calc_total_bfregs(dev, lib_uar_4k, &req, bfregi);
1333 	if (err)
1334 		goto out_ctx;
1335 
1336 	mutex_init(&bfregi->lock);
1337 	bfregi->lib_uar_4k = lib_uar_4k;
1338 	bfregi->count = kcalloc(bfregi->total_num_bfregs, sizeof(*bfregi->count),
1339 				GFP_KERNEL);
1340 	if (!bfregi->count) {
1341 		err = -ENOMEM;
1342 		goto out_ctx;
1343 	}
1344 
1345 	bfregi->sys_pages = kcalloc(bfregi->num_sys_pages,
1346 				    sizeof(*bfregi->sys_pages),
1347 				    GFP_KERNEL);
1348 	if (!bfregi->sys_pages) {
1349 		err = -ENOMEM;
1350 		goto out_count;
1351 	}
1352 
1353 	err = allocate_uars(dev, context);
1354 	if (err)
1355 		goto out_sys_pages;
1356 
1357 uar_done:
1358 	if (req.flags & MLX5_IB_ALLOC_UCTX_DEVX) {
1359 		err = mlx5_ib_devx_create(dev, true);
1360 		if (err < 0)
1361 			goto out_uars;
1362 		context->devx_uid = err;
1363 	}
1364 
1365 	err = mlx5_ib_alloc_transport_domain(dev, &context->tdn,
1366 					     context->devx_uid);
1367 	if (err)
1368 		goto out_devx;
1369 
1370 	INIT_LIST_HEAD(&context->db_page_list);
1371 	mutex_init(&context->db_page_mutex);
1372 
1373 	resp.tot_bfregs = lib_uar_dyn ? 0 : req.total_num_bfregs;
1374 	resp.num_ports = MLX5_CAP_GEN(dev->mdev, num_ports);
1375 
1376 	if (field_avail(typeof(resp), cqe_version, udata->outlen))
1377 		resp.response_length += sizeof(resp.cqe_version);
1378 
1379 	if (field_avail(typeof(resp), cmds_supp_uhw, udata->outlen)) {
1380 		resp.cmds_supp_uhw |= MLX5_USER_CMDS_SUPP_UHW_QUERY_DEVICE |
1381 				      MLX5_USER_CMDS_SUPP_UHW_CREATE_AH;
1382 		resp.response_length += sizeof(resp.cmds_supp_uhw);
1383 	}
1384 
1385 	/*
1386 	 * We don't want to expose information from the PCI bar that is located
1387 	 * after 4096 bytes, so if the arch only supports larger pages, let's
1388 	 * pretend we don't support reading the HCA's core clock. This is also
1389 	 * forced by mmap function.
1390 	 */
1391 	if (offsetofend(typeof(resp), hca_core_clock_offset) <= udata->outlen) {
1392 		if (PAGE_SIZE <= 4096) {
1393 			resp.comp_mask |=
1394 				MLX5_IB_ALLOC_UCONTEXT_RESP_MASK_CORE_CLOCK_OFFSET;
1395 			resp.hca_core_clock_offset =
1396 				offsetof(struct mlx5_init_seg, internal_timer_h) % PAGE_SIZE;
1397 		}
1398 		resp.response_length += sizeof(resp.hca_core_clock_offset);
1399 	}
1400 
1401 	if (offsetofend(typeof(resp), log_uar_size) <= udata->outlen)
1402 		resp.response_length += sizeof(resp.log_uar_size);
1403 
1404 	if (offsetofend(typeof(resp), num_uars_per_page) <= udata->outlen)
1405 		resp.response_length += sizeof(resp.num_uars_per_page);
1406 
1407 	if (offsetofend(typeof(resp), num_dyn_bfregs) <= udata->outlen) {
1408 		resp.num_dyn_bfregs = bfregi->num_dyn_bfregs;
1409 		resp.response_length += sizeof(resp.num_dyn_bfregs);
1410 	}
1411 
1412 	err = ib_copy_to_udata(udata, &resp, resp.response_length);
1413 	if (err)
1414 		goto out_mdev;
1415 
1416 	bfregi->ver = ver;
1417 	bfregi->num_low_latency_bfregs = req.num_low_latency_bfregs;
1418 	context->cqe_version = resp.cqe_version;
1419 	context->lib_caps = req.lib_caps;
1420 	print_lib_caps(dev, context->lib_caps);
1421 
1422 	return 0;
1423 
1424 out_mdev:
1425 	mlx5_ib_dealloc_transport_domain(dev, context->tdn, context->devx_uid);
1426 out_devx:
1427 	if (req.flags & MLX5_IB_ALLOC_UCTX_DEVX)
1428 		mlx5_ib_devx_destroy(dev, context->devx_uid);
1429 
1430 out_uars:
1431 	deallocate_uars(dev, context);
1432 
1433 out_sys_pages:
1434 	kfree(bfregi->sys_pages);
1435 
1436 out_count:
1437 	kfree(bfregi->count);
1438 
1439 out_ctx:
1440 	return err;
1441 }
1442 
1443 static void mlx5_ib_dealloc_ucontext(struct ib_ucontext *ibcontext)
1444 {
1445 	struct mlx5_ib_ucontext *context = to_mucontext(ibcontext);
1446 	struct mlx5_ib_dev *dev = to_mdev(ibcontext->device);
1447 	struct mlx5_bfreg_info *bfregi;
1448 
1449 	bfregi = &context->bfregi;
1450 	mlx5_ib_dealloc_transport_domain(dev, context->tdn, context->devx_uid);
1451 
1452 	if (context->devx_uid)
1453 		mlx5_ib_devx_destroy(dev, context->devx_uid);
1454 
1455 	deallocate_uars(dev, context);
1456 	kfree(bfregi->sys_pages);
1457 	kfree(bfregi->count);
1458 }
1459 
1460 static phys_addr_t uar_index2pfn(struct mlx5_ib_dev *dev,
1461 				 int uar_idx)
1462 {
1463 	int fw_uars_per_page;
1464 
1465 	fw_uars_per_page = MLX5_CAP_GEN(dev->mdev, uar_4k) ? MLX5_UARS_IN_PAGE : 1;
1466 
1467 	return (pci_resource_start(dev->mdev->pdev, 0) >> PAGE_SHIFT) + uar_idx / fw_uars_per_page;
1468 }
1469 
1470 static int get_command(unsigned long offset)
1471 {
1472 	return (offset >> MLX5_IB_MMAP_CMD_SHIFT) & MLX5_IB_MMAP_CMD_MASK;
1473 }
1474 
1475 static int get_arg(unsigned long offset)
1476 {
1477 	return offset & ((1 << MLX5_IB_MMAP_CMD_SHIFT) - 1);
1478 }
1479 
1480 static int get_index(unsigned long offset)
1481 {
1482 	return get_arg(offset);
1483 }
1484 
1485 /* Index resides in an extra byte to enable larger values than 255 */
1486 static int get_extended_index(unsigned long offset)
1487 {
1488 	return get_arg(offset) | ((offset >> 16) & 0xff) << 8;
1489 }
1490 
1491 
1492 static void mlx5_ib_disassociate_ucontext(struct ib_ucontext *ibcontext)
1493 {
1494 }
1495 
1496 static inline char *mmap_cmd2str(enum mlx5_ib_mmap_cmd cmd)
1497 {
1498 	switch (cmd) {
1499 	case MLX5_IB_MMAP_WC_PAGE:
1500 		return "WC";
1501 	case MLX5_IB_MMAP_REGULAR_PAGE:
1502 		return "best effort WC";
1503 	case MLX5_IB_MMAP_NC_PAGE:
1504 		return "NC";
1505 	default:
1506 		return NULL;
1507 	}
1508 }
1509 
1510 static int mlx5_ib_mmap_clock_info_page(struct mlx5_ib_dev *dev,
1511 					struct vm_area_struct *vma,
1512 					struct mlx5_ib_ucontext *context)
1513 {
1514 	if ((vma->vm_end - vma->vm_start != PAGE_SIZE) ||
1515 	    !(vma->vm_flags & VM_SHARED))
1516 		return -EINVAL;
1517 
1518 	if (get_index(vma->vm_pgoff) != MLX5_IB_CLOCK_INFO_V1)
1519 		return -EOPNOTSUPP;
1520 
1521 	if (vma->vm_flags & (VM_WRITE | VM_EXEC))
1522 		return -EPERM;
1523 
1524 	return -EOPNOTSUPP;
1525 }
1526 
1527 static void mlx5_ib_mmap_free(struct rdma_user_mmap_entry *entry)
1528 {
1529 	struct mlx5_user_mmap_entry *mentry = to_mmmap(entry);
1530 	struct mlx5_ib_dev *dev = to_mdev(entry->ucontext->device);
1531 
1532 	switch (mentry->mmap_flag) {
1533 	case MLX5_IB_MMAP_TYPE_UAR_WC:
1534 	case MLX5_IB_MMAP_TYPE_UAR_NC:
1535 		mlx5_cmd_free_uar(dev->mdev, mentry->page_idx);
1536 		kfree(mentry);
1537 		break;
1538 	default:
1539 		WARN_ON(true);
1540 	}
1541 }
1542 
1543 static int uar_mmap(struct mlx5_ib_dev *dev, enum mlx5_ib_mmap_cmd cmd,
1544 		    struct vm_area_struct *vma,
1545 		    struct mlx5_ib_ucontext *context)
1546 {
1547 	struct mlx5_bfreg_info *bfregi = &context->bfregi;
1548 	int err;
1549 	unsigned long idx;
1550 	phys_addr_t pfn;
1551 	pgprot_t prot;
1552 	u32 bfreg_dyn_idx = 0;
1553 	u32 uar_index;
1554 	int dyn_uar = (cmd == MLX5_IB_MMAP_ALLOC_WC);
1555 	int max_valid_idx = dyn_uar ? bfregi->num_sys_pages :
1556 				bfregi->num_static_sys_pages;
1557 
1558 	if (bfregi->lib_uar_dyn)
1559 		return -EINVAL;
1560 
1561 	if (vma->vm_end - vma->vm_start != PAGE_SIZE)
1562 		return -EINVAL;
1563 
1564 	if (dyn_uar)
1565 		idx = get_extended_index(vma->vm_pgoff) + bfregi->num_static_sys_pages;
1566 	else
1567 		idx = get_index(vma->vm_pgoff);
1568 
1569 	if (idx >= max_valid_idx) {
1570 		mlx5_ib_warn(dev, "invalid uar index %lu, max=%d\n",
1571 			     idx, max_valid_idx);
1572 		return -EINVAL;
1573 	}
1574 
1575 	switch (cmd) {
1576 	case MLX5_IB_MMAP_WC_PAGE:
1577 	case MLX5_IB_MMAP_ALLOC_WC:
1578 	case MLX5_IB_MMAP_REGULAR_PAGE:
1579 		/* For MLX5_IB_MMAP_REGULAR_PAGE do the best effort to get WC */
1580 		prot = pgprot_writecombine(vma->vm_page_prot);
1581 		break;
1582 	case MLX5_IB_MMAP_NC_PAGE:
1583 		prot = pgprot_noncached(vma->vm_page_prot);
1584 		break;
1585 	default:
1586 		return -EINVAL;
1587 	}
1588 
1589 	if (dyn_uar) {
1590 		int uars_per_page;
1591 
1592 		uars_per_page = get_uars_per_sys_page(dev, bfregi->lib_uar_4k);
1593 		bfreg_dyn_idx = idx * (uars_per_page * MLX5_NON_FP_BFREGS_PER_UAR);
1594 		if (bfreg_dyn_idx >= bfregi->total_num_bfregs) {
1595 			mlx5_ib_warn(dev, "invalid bfreg_dyn_idx %u, max=%u\n",
1596 				     bfreg_dyn_idx, bfregi->total_num_bfregs);
1597 			return -EINVAL;
1598 		}
1599 
1600 		mutex_lock(&bfregi->lock);
1601 		/* Fail if uar already allocated, first bfreg index of each
1602 		 * page holds its count.
1603 		 */
1604 		if (bfregi->count[bfreg_dyn_idx]) {
1605 			mlx5_ib_warn(dev, "wrong offset, idx %lu is busy, bfregn=%u\n", idx, bfreg_dyn_idx);
1606 			mutex_unlock(&bfregi->lock);
1607 			return -EINVAL;
1608 		}
1609 
1610 		bfregi->count[bfreg_dyn_idx]++;
1611 		mutex_unlock(&bfregi->lock);
1612 
1613 		err = mlx5_cmd_alloc_uar(dev->mdev, &uar_index);
1614 		if (err) {
1615 			mlx5_ib_warn(dev, "UAR alloc failed\n");
1616 			goto free_bfreg;
1617 		}
1618 	} else {
1619 		uar_index = bfregi->sys_pages[idx];
1620 	}
1621 
1622 	pfn = uar_index2pfn(dev, uar_index);
1623 	mlx5_ib_dbg(dev, "uar idx 0x%lx, pfn %pa\n", idx, &pfn);
1624 
1625 	err = rdma_user_mmap_io(&context->ibucontext, vma, pfn, PAGE_SIZE,
1626 				prot, NULL);
1627 	if (err) {
1628 		mlx5_ib_err(dev,
1629 			    "rdma_user_mmap_io failed with error=%d, mmap_cmd=%s\n",
1630 			    err, mmap_cmd2str(cmd));
1631 		goto err;
1632 	}
1633 
1634 	if (dyn_uar)
1635 		bfregi->sys_pages[idx] = uar_index;
1636 	return 0;
1637 
1638 err:
1639 	if (!dyn_uar)
1640 		return err;
1641 
1642 	mlx5_cmd_free_uar(dev->mdev, idx);
1643 
1644 free_bfreg:
1645 	mlx5_ib_free_bfreg(dev, bfregi, bfreg_dyn_idx);
1646 
1647 	return err;
1648 }
1649 
1650 static unsigned long mlx5_vma_to_pgoff(struct vm_area_struct *vma)
1651 {
1652 	unsigned long idx;
1653 	u8 command;
1654 
1655 	command = get_command(vma->vm_pgoff);
1656 	idx = get_extended_index(vma->vm_pgoff);
1657 
1658 	return (command << 16 | idx);
1659 }
1660 
1661 static int mlx5_ib_mmap_offset(struct mlx5_ib_dev *dev,
1662 			       struct vm_area_struct *vma,
1663 			       struct ib_ucontext *ucontext)
1664 {
1665 	struct mlx5_user_mmap_entry *mentry;
1666 	struct rdma_user_mmap_entry *entry;
1667 	unsigned long pgoff;
1668 	pgprot_t prot;
1669 	phys_addr_t pfn;
1670 	int ret;
1671 
1672 	pgoff = mlx5_vma_to_pgoff(vma);
1673 	entry = rdma_user_mmap_entry_get_pgoff(ucontext, pgoff);
1674 	if (!entry)
1675 		return -EINVAL;
1676 
1677 	mentry = to_mmmap(entry);
1678 	pfn = (mentry->address >> PAGE_SHIFT);
1679 	if (mentry->mmap_flag == MLX5_IB_MMAP_TYPE_VAR ||
1680 	    mentry->mmap_flag == MLX5_IB_MMAP_TYPE_UAR_NC)
1681 		prot = pgprot_noncached(vma->vm_page_prot);
1682 	else
1683 		prot = pgprot_writecombine(vma->vm_page_prot);
1684 	ret = rdma_user_mmap_io(ucontext, vma, pfn,
1685 				entry->npages * PAGE_SIZE,
1686 				prot,
1687 				entry);
1688 	rdma_user_mmap_entry_put(&mentry->rdma_entry);
1689 	return ret;
1690 }
1691 
1692 static int mlx5_ib_mmap(struct ib_ucontext *ibcontext, struct vm_area_struct *vma)
1693 {
1694 	struct mlx5_ib_ucontext *context = to_mucontext(ibcontext);
1695 	struct mlx5_ib_dev *dev = to_mdev(ibcontext->device);
1696 	unsigned long command;
1697 	phys_addr_t pfn;
1698 
1699 	command = get_command(vma->vm_pgoff);
1700 	switch (command) {
1701 	case MLX5_IB_MMAP_WC_PAGE:
1702 	case MLX5_IB_MMAP_ALLOC_WC:
1703 		if (!dev->wc_support)
1704 			return -EPERM;
1705 		/* FALLTHROUGH */
1706 	case MLX5_IB_MMAP_NC_PAGE:
1707 	case MLX5_IB_MMAP_REGULAR_PAGE:
1708 		return uar_mmap(dev, command, vma, context);
1709 
1710 	case MLX5_IB_MMAP_GET_CONTIGUOUS_PAGES:
1711 		return -ENOSYS;
1712 
1713 	case MLX5_IB_MMAP_CORE_CLOCK:
1714 		if (vma->vm_end - vma->vm_start != PAGE_SIZE)
1715 			return -EINVAL;
1716 
1717 		if (vma->vm_flags & VM_WRITE)
1718 			return -EPERM;
1719 
1720 		/* Don't expose to user-space information it shouldn't have */
1721 		if (PAGE_SIZE > 4096)
1722 			return -EOPNOTSUPP;
1723 
1724 		pfn = (dev->mdev->iseg_base +
1725 		       offsetof(struct mlx5_init_seg, internal_timer_h)) >>
1726 			PAGE_SHIFT;
1727 		return rdma_user_mmap_io(&context->ibucontext, vma, pfn,
1728 					 PAGE_SIZE,
1729 					 pgprot_noncached(vma->vm_page_prot),
1730 					 NULL);
1731 	case MLX5_IB_MMAP_CLOCK_INFO:
1732 		return mlx5_ib_mmap_clock_info_page(dev, vma, context);
1733 
1734 	default:
1735 		return mlx5_ib_mmap_offset(dev, vma, ibcontext);
1736 	}
1737 
1738 	return 0;
1739 }
1740 
1741 static int mlx5_ib_alloc_pd(struct ib_pd *ibpd, struct ib_udata *udata)
1742 {
1743 	struct mlx5_ib_pd *pd = to_mpd(ibpd);
1744 	struct ib_device *ibdev = ibpd->device;
1745 	struct mlx5_ib_alloc_pd_resp resp;
1746 	int err;
1747 	struct mlx5_ib_ucontext *context = rdma_udata_to_drv_context(
1748 		udata, struct mlx5_ib_ucontext, ibucontext);
1749 	u16 uid = context ? context->devx_uid : 0;
1750 
1751 	err = mlx5_core_alloc_pd(to_mdev(ibdev)->mdev, &pd->pdn, uid);
1752 	if (err)
1753 		return (err);
1754 
1755 	pd->uid = uid;
1756 	if (udata) {
1757 		resp.pdn = pd->pdn;
1758 		if (ib_copy_to_udata(udata, &resp, sizeof(resp))) {
1759 			mlx5_core_dealloc_pd(to_mdev(ibdev)->mdev, pd->pdn, uid);
1760 			return -EFAULT;
1761 		}
1762 	}
1763 
1764 	return 0;
1765 }
1766 
1767 static void mlx5_ib_dealloc_pd(struct ib_pd *pd, struct ib_udata *udata)
1768 {
1769 	struct mlx5_ib_dev *mdev = to_mdev(pd->device);
1770 	struct mlx5_ib_pd *mpd = to_mpd(pd);
1771 
1772 	mlx5_core_dealloc_pd(mdev->mdev, mpd->pdn, mpd->uid);
1773 }
1774 
1775 enum {
1776 	MATCH_CRITERIA_ENABLE_OUTER_BIT,
1777 	MATCH_CRITERIA_ENABLE_MISC_BIT,
1778 	MATCH_CRITERIA_ENABLE_INNER_BIT
1779 };
1780 
1781 #define HEADER_IS_ZERO(match_criteria, headers)			           \
1782 	!(memchr_inv(MLX5_ADDR_OF(fte_match_param, match_criteria, headers), \
1783 		    0, MLX5_FLD_SZ_BYTES(fte_match_param, headers)))       \
1784 
1785 static u8 get_match_criteria_enable(u32 *match_criteria)
1786 {
1787 	u8 match_criteria_enable;
1788 
1789 	match_criteria_enable =
1790 		(!HEADER_IS_ZERO(match_criteria, outer_headers)) <<
1791 		MATCH_CRITERIA_ENABLE_OUTER_BIT;
1792 	match_criteria_enable |=
1793 		(!HEADER_IS_ZERO(match_criteria, misc_parameters)) <<
1794 		MATCH_CRITERIA_ENABLE_MISC_BIT;
1795 	match_criteria_enable |=
1796 		(!HEADER_IS_ZERO(match_criteria, inner_headers)) <<
1797 		MATCH_CRITERIA_ENABLE_INNER_BIT;
1798 
1799 	return match_criteria_enable;
1800 }
1801 
1802 static void set_proto(void *outer_c, void *outer_v, u8 mask, u8 val)
1803 {
1804 	MLX5_SET(fte_match_set_lyr_2_4, outer_c, ip_protocol, mask);
1805 	MLX5_SET(fte_match_set_lyr_2_4, outer_v, ip_protocol, val);
1806 }
1807 
1808 static void set_tos(void *outer_c, void *outer_v, u8 mask, u8 val)
1809 {
1810 	MLX5_SET(fte_match_set_lyr_2_4, outer_c, ip_ecn, mask);
1811 	MLX5_SET(fte_match_set_lyr_2_4, outer_v, ip_ecn, val);
1812 	MLX5_SET(fte_match_set_lyr_2_4, outer_c, ip_dscp, mask >> 2);
1813 	MLX5_SET(fte_match_set_lyr_2_4, outer_v, ip_dscp, val >> 2);
1814 }
1815 
1816 #define LAST_ETH_FIELD vlan_tag
1817 #define LAST_IB_FIELD sl
1818 #define LAST_IPV4_FIELD tos
1819 #define LAST_IPV6_FIELD traffic_class
1820 #define LAST_TCP_UDP_FIELD src_port
1821 
1822 /* Field is the last supported field */
1823 #define FIELDS_NOT_SUPPORTED(filter, field)\
1824 	memchr_inv((void *)&filter.field  +\
1825 		   sizeof(filter.field), 0,\
1826 		   sizeof(filter) -\
1827 		   offsetof(typeof(filter), field) -\
1828 		   sizeof(filter.field))
1829 
1830 static int parse_flow_attr(u32 *match_c, u32 *match_v,
1831 			   const union ib_flow_spec *ib_spec)
1832 {
1833 	void *outer_headers_c = MLX5_ADDR_OF(fte_match_param, match_c,
1834 					     outer_headers);
1835 	void *outer_headers_v = MLX5_ADDR_OF(fte_match_param, match_v,
1836 					     outer_headers);
1837 	void *misc_params_c = MLX5_ADDR_OF(fte_match_param, match_c,
1838 					   misc_parameters);
1839 	void *misc_params_v = MLX5_ADDR_OF(fte_match_param, match_v,
1840 					   misc_parameters);
1841 
1842 	switch (ib_spec->type) {
1843 	case IB_FLOW_SPEC_ETH:
1844 		if (FIELDS_NOT_SUPPORTED(ib_spec->eth.mask, LAST_ETH_FIELD))
1845 			return -ENOTSUPP;
1846 
1847 		ether_addr_copy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, outer_headers_c,
1848 					     dmac_47_16),
1849 				ib_spec->eth.mask.dst_mac);
1850 		ether_addr_copy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, outer_headers_v,
1851 					     dmac_47_16),
1852 				ib_spec->eth.val.dst_mac);
1853 
1854 		ether_addr_copy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, outer_headers_c,
1855 					     smac_47_16),
1856 				ib_spec->eth.mask.src_mac);
1857 		ether_addr_copy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, outer_headers_v,
1858 					     smac_47_16),
1859 				ib_spec->eth.val.src_mac);
1860 
1861 		if (ib_spec->eth.mask.vlan_tag) {
1862 			MLX5_SET(fte_match_set_lyr_2_4, outer_headers_c,
1863 				 cvlan_tag, 1);
1864 			MLX5_SET(fte_match_set_lyr_2_4, outer_headers_v,
1865 				 cvlan_tag, 1);
1866 
1867 			MLX5_SET(fte_match_set_lyr_2_4, outer_headers_c,
1868 				 first_vid, ntohs(ib_spec->eth.mask.vlan_tag));
1869 			MLX5_SET(fte_match_set_lyr_2_4, outer_headers_v,
1870 				 first_vid, ntohs(ib_spec->eth.val.vlan_tag));
1871 
1872 			MLX5_SET(fte_match_set_lyr_2_4, outer_headers_c,
1873 				 first_cfi,
1874 				 ntohs(ib_spec->eth.mask.vlan_tag) >> 12);
1875 			MLX5_SET(fte_match_set_lyr_2_4, outer_headers_v,
1876 				 first_cfi,
1877 				 ntohs(ib_spec->eth.val.vlan_tag) >> 12);
1878 
1879 			MLX5_SET(fte_match_set_lyr_2_4, outer_headers_c,
1880 				 first_prio,
1881 				 ntohs(ib_spec->eth.mask.vlan_tag) >> 13);
1882 			MLX5_SET(fte_match_set_lyr_2_4, outer_headers_v,
1883 				 first_prio,
1884 				 ntohs(ib_spec->eth.val.vlan_tag) >> 13);
1885 		}
1886 		MLX5_SET(fte_match_set_lyr_2_4, outer_headers_c,
1887 			 ethertype, ntohs(ib_spec->eth.mask.ether_type));
1888 		MLX5_SET(fte_match_set_lyr_2_4, outer_headers_v,
1889 			 ethertype, ntohs(ib_spec->eth.val.ether_type));
1890 		break;
1891 	case IB_FLOW_SPEC_IPV4:
1892 		if (FIELDS_NOT_SUPPORTED(ib_spec->ipv4.mask, LAST_IPV4_FIELD))
1893 			return -ENOTSUPP;
1894 
1895 		MLX5_SET(fte_match_set_lyr_2_4, outer_headers_c,
1896 			 ethertype, 0xffff);
1897 		MLX5_SET(fte_match_set_lyr_2_4, outer_headers_v,
1898 			 ethertype, ETH_P_IP);
1899 
1900 		memcpy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, outer_headers_c,
1901 				    src_ipv4_src_ipv6.ipv4_layout.ipv4),
1902 		       &ib_spec->ipv4.mask.src_ip,
1903 		       sizeof(ib_spec->ipv4.mask.src_ip));
1904 		memcpy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, outer_headers_v,
1905 				    src_ipv4_src_ipv6.ipv4_layout.ipv4),
1906 		       &ib_spec->ipv4.val.src_ip,
1907 		       sizeof(ib_spec->ipv4.val.src_ip));
1908 		memcpy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, outer_headers_c,
1909 				    dst_ipv4_dst_ipv6.ipv4_layout.ipv4),
1910 		       &ib_spec->ipv4.mask.dst_ip,
1911 		       sizeof(ib_spec->ipv4.mask.dst_ip));
1912 		memcpy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, outer_headers_v,
1913 				    dst_ipv4_dst_ipv6.ipv4_layout.ipv4),
1914 		       &ib_spec->ipv4.val.dst_ip,
1915 		       sizeof(ib_spec->ipv4.val.dst_ip));
1916 
1917 		set_tos(outer_headers_c, outer_headers_v,
1918 			ib_spec->ipv4.mask.tos, ib_spec->ipv4.val.tos);
1919 
1920 		set_proto(outer_headers_c, outer_headers_v,
1921 			  ib_spec->ipv4.mask.proto, ib_spec->ipv4.val.proto);
1922 		break;
1923 	case IB_FLOW_SPEC_IPV6:
1924 		if (FIELDS_NOT_SUPPORTED(ib_spec->ipv6.mask, LAST_IPV6_FIELD))
1925 			return -ENOTSUPP;
1926 
1927 		MLX5_SET(fte_match_set_lyr_2_4, outer_headers_c,
1928 			 ethertype, 0xffff);
1929 		MLX5_SET(fte_match_set_lyr_2_4, outer_headers_v,
1930 			 ethertype, IPPROTO_IPV6);
1931 
1932 		memcpy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, outer_headers_c,
1933 				    src_ipv4_src_ipv6.ipv6_layout.ipv6),
1934 		       &ib_spec->ipv6.mask.src_ip,
1935 		       sizeof(ib_spec->ipv6.mask.src_ip));
1936 		memcpy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, outer_headers_v,
1937 				    src_ipv4_src_ipv6.ipv6_layout.ipv6),
1938 		       &ib_spec->ipv6.val.src_ip,
1939 		       sizeof(ib_spec->ipv6.val.src_ip));
1940 		memcpy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, outer_headers_c,
1941 				    dst_ipv4_dst_ipv6.ipv6_layout.ipv6),
1942 		       &ib_spec->ipv6.mask.dst_ip,
1943 		       sizeof(ib_spec->ipv6.mask.dst_ip));
1944 		memcpy(MLX5_ADDR_OF(fte_match_set_lyr_2_4, outer_headers_v,
1945 				    dst_ipv4_dst_ipv6.ipv6_layout.ipv6),
1946 		       &ib_spec->ipv6.val.dst_ip,
1947 		       sizeof(ib_spec->ipv6.val.dst_ip));
1948 
1949 		set_tos(outer_headers_c, outer_headers_v,
1950 			ib_spec->ipv6.mask.traffic_class,
1951 			ib_spec->ipv6.val.traffic_class);
1952 
1953 		set_proto(outer_headers_c, outer_headers_v,
1954 			  ib_spec->ipv6.mask.next_hdr,
1955 			  ib_spec->ipv6.val.next_hdr);
1956 
1957 		MLX5_SET(fte_match_set_misc, misc_params_c,
1958 			 outer_ipv6_flow_label,
1959 			 ntohl(ib_spec->ipv6.mask.flow_label));
1960 		MLX5_SET(fte_match_set_misc, misc_params_v,
1961 			 outer_ipv6_flow_label,
1962 			 ntohl(ib_spec->ipv6.val.flow_label));
1963 		break;
1964 	case IB_FLOW_SPEC_TCP:
1965 		if (FIELDS_NOT_SUPPORTED(ib_spec->tcp_udp.mask,
1966 					 LAST_TCP_UDP_FIELD))
1967 			return -ENOTSUPP;
1968 
1969 		MLX5_SET(fte_match_set_lyr_2_4, outer_headers_c, ip_protocol,
1970 			 0xff);
1971 		MLX5_SET(fte_match_set_lyr_2_4, outer_headers_v, ip_protocol,
1972 			 IPPROTO_TCP);
1973 
1974 		MLX5_SET(fte_match_set_lyr_2_4, outer_headers_c, tcp_sport,
1975 			 ntohs(ib_spec->tcp_udp.mask.src_port));
1976 		MLX5_SET(fte_match_set_lyr_2_4, outer_headers_v, tcp_sport,
1977 			 ntohs(ib_spec->tcp_udp.val.src_port));
1978 
1979 		MLX5_SET(fte_match_set_lyr_2_4, outer_headers_c, tcp_dport,
1980 			 ntohs(ib_spec->tcp_udp.mask.dst_port));
1981 		MLX5_SET(fte_match_set_lyr_2_4, outer_headers_v, tcp_dport,
1982 			 ntohs(ib_spec->tcp_udp.val.dst_port));
1983 		break;
1984 	case IB_FLOW_SPEC_UDP:
1985 		if (FIELDS_NOT_SUPPORTED(ib_spec->tcp_udp.mask,
1986 					 LAST_TCP_UDP_FIELD))
1987 			return -ENOTSUPP;
1988 
1989 		MLX5_SET(fte_match_set_lyr_2_4, outer_headers_c, ip_protocol,
1990 			 0xff);
1991 		MLX5_SET(fte_match_set_lyr_2_4, outer_headers_v, ip_protocol,
1992 			 IPPROTO_UDP);
1993 
1994 		MLX5_SET(fte_match_set_lyr_2_4, outer_headers_c, udp_sport,
1995 			 ntohs(ib_spec->tcp_udp.mask.src_port));
1996 		MLX5_SET(fte_match_set_lyr_2_4, outer_headers_v, udp_sport,
1997 			 ntohs(ib_spec->tcp_udp.val.src_port));
1998 
1999 		MLX5_SET(fte_match_set_lyr_2_4, outer_headers_c, udp_dport,
2000 			 ntohs(ib_spec->tcp_udp.mask.dst_port));
2001 		MLX5_SET(fte_match_set_lyr_2_4, outer_headers_v, udp_dport,
2002 			 ntohs(ib_spec->tcp_udp.val.dst_port));
2003 		break;
2004 	default:
2005 		return -EINVAL;
2006 	}
2007 
2008 	return 0;
2009 }
2010 
2011 /* If a flow could catch both multicast and unicast packets,
2012  * it won't fall into the multicast flow steering table and this rule
2013  * could steal other multicast packets.
2014  */
2015 static bool flow_is_multicast_only(struct ib_flow_attr *ib_attr)
2016 {
2017 	struct ib_flow_spec_eth *eth_spec;
2018 
2019 	if (ib_attr->type != IB_FLOW_ATTR_NORMAL ||
2020 	    ib_attr->size < sizeof(struct ib_flow_attr) +
2021 	    sizeof(struct ib_flow_spec_eth) ||
2022 	    ib_attr->num_of_specs < 1)
2023 		return false;
2024 
2025 	eth_spec = (struct ib_flow_spec_eth *)(ib_attr + 1);
2026 	if (eth_spec->type != IB_FLOW_SPEC_ETH ||
2027 	    eth_spec->size != sizeof(*eth_spec))
2028 		return false;
2029 
2030 	return is_multicast_ether_addr(eth_spec->mask.dst_mac) &&
2031 	       is_multicast_ether_addr(eth_spec->val.dst_mac);
2032 }
2033 
2034 static bool is_valid_attr(const struct ib_flow_attr *flow_attr)
2035 {
2036 	union ib_flow_spec *ib_spec = (union ib_flow_spec *)(flow_attr + 1);
2037 	bool has_ipv4_spec = false;
2038 	bool eth_type_ipv4 = true;
2039 	unsigned int spec_index;
2040 
2041 	/* Validate that ethertype is correct */
2042 	for (spec_index = 0; spec_index < flow_attr->num_of_specs; spec_index++) {
2043 		if (ib_spec->type == IB_FLOW_SPEC_ETH &&
2044 		    ib_spec->eth.mask.ether_type) {
2045 			if (!((ib_spec->eth.mask.ether_type == htons(0xffff)) &&
2046 			      ib_spec->eth.val.ether_type == htons(ETH_P_IP)))
2047 				eth_type_ipv4 = false;
2048 		} else if (ib_spec->type == IB_FLOW_SPEC_IPV4) {
2049 			has_ipv4_spec = true;
2050 		}
2051 		ib_spec = (void *)ib_spec + ib_spec->size;
2052 	}
2053 	return !has_ipv4_spec || eth_type_ipv4;
2054 }
2055 
2056 static void put_flow_table(struct mlx5_ib_dev *dev,
2057 			   struct mlx5_ib_flow_prio *prio, bool ft_added)
2058 {
2059 	prio->refcount -= !!ft_added;
2060 	if (!prio->refcount) {
2061 		mlx5_destroy_flow_table(prio->flow_table);
2062 		prio->flow_table = NULL;
2063 	}
2064 }
2065 
2066 static int mlx5_ib_destroy_flow(struct ib_flow *flow_id)
2067 {
2068 	struct mlx5_ib_dev *dev = to_mdev(flow_id->qp->device);
2069 	struct mlx5_ib_flow_handler *handler = container_of(flow_id,
2070 							  struct mlx5_ib_flow_handler,
2071 							  ibflow);
2072 	struct mlx5_ib_flow_handler *iter, *tmp;
2073 
2074 	mutex_lock(&dev->flow_db.lock);
2075 
2076 	list_for_each_entry_safe(iter, tmp, &handler->list, list) {
2077 		mlx5_del_flow_rule(&iter->rule);
2078 		put_flow_table(dev, iter->prio, true);
2079 		list_del(&iter->list);
2080 		kfree(iter);
2081 	}
2082 
2083 	mlx5_del_flow_rule(&handler->rule);
2084 	put_flow_table(dev, handler->prio, true);
2085 	mutex_unlock(&dev->flow_db.lock);
2086 
2087 	kfree(handler);
2088 
2089 	return 0;
2090 }
2091 
2092 static int ib_prio_to_core_prio(unsigned int priority, bool dont_trap)
2093 {
2094 	priority *= 2;
2095 	if (!dont_trap)
2096 		priority++;
2097 	return priority;
2098 }
2099 
2100 enum flow_table_type {
2101 	MLX5_IB_FT_RX,
2102 	MLX5_IB_FT_TX
2103 };
2104 
2105 #define MLX5_FS_MAX_TYPES	 10
2106 #define MLX5_FS_MAX_ENTRIES	 32000UL
2107 static struct mlx5_ib_flow_prio *get_flow_table(struct mlx5_ib_dev *dev,
2108 						struct ib_flow_attr *flow_attr,
2109 						enum flow_table_type ft_type)
2110 {
2111 	bool dont_trap = flow_attr->flags & IB_FLOW_ATTR_FLAGS_DONT_TRAP;
2112 	struct mlx5_flow_namespace *ns = NULL;
2113 	struct mlx5_ib_flow_prio *prio;
2114 	struct mlx5_flow_table *ft;
2115 	int num_entries;
2116 	int num_groups;
2117 	int priority;
2118 	int err = 0;
2119 
2120 	if (flow_attr->type == IB_FLOW_ATTR_NORMAL) {
2121 		if (flow_is_multicast_only(flow_attr) &&
2122 		    !dont_trap)
2123 			priority = MLX5_IB_FLOW_MCAST_PRIO;
2124 		else
2125 			priority = ib_prio_to_core_prio(flow_attr->priority,
2126 							dont_trap);
2127 		ns = mlx5_get_flow_namespace(dev->mdev,
2128 					     MLX5_FLOW_NAMESPACE_BYPASS);
2129 		num_entries = MLX5_FS_MAX_ENTRIES;
2130 		num_groups = MLX5_FS_MAX_TYPES;
2131 		prio = &dev->flow_db.prios[priority];
2132 	} else if (flow_attr->type == IB_FLOW_ATTR_ALL_DEFAULT ||
2133 		   flow_attr->type == IB_FLOW_ATTR_MC_DEFAULT) {
2134 		ns = mlx5_get_flow_namespace(dev->mdev,
2135 					     MLX5_FLOW_NAMESPACE_LEFTOVERS);
2136 		build_leftovers_ft_param("bypass", &priority,
2137 					 &num_entries,
2138 					 &num_groups);
2139 		prio = &dev->flow_db.prios[MLX5_IB_FLOW_LEFTOVERS_PRIO];
2140 	} else if (flow_attr->type == IB_FLOW_ATTR_SNIFFER) {
2141 		if (!MLX5_CAP_FLOWTABLE(dev->mdev,
2142 					allow_sniffer_and_nic_rx_shared_tir))
2143 			return ERR_PTR(-ENOTSUPP);
2144 
2145 		ns = mlx5_get_flow_namespace(dev->mdev, ft_type == MLX5_IB_FT_RX ?
2146 					     MLX5_FLOW_NAMESPACE_SNIFFER_RX :
2147 					     MLX5_FLOW_NAMESPACE_SNIFFER_TX);
2148 
2149 		prio = &dev->flow_db.sniffer[ft_type];
2150 		priority = 0;
2151 		num_entries = 1;
2152 		num_groups = 1;
2153 	}
2154 
2155 	if (!ns)
2156 		return ERR_PTR(-ENOTSUPP);
2157 
2158 	ft = prio->flow_table;
2159 	if (!ft) {
2160 		ft = mlx5_create_auto_grouped_flow_table(ns, priority, "bypass",
2161 							 num_entries,
2162 							 num_groups);
2163 
2164 		if (!IS_ERR(ft)) {
2165 			prio->refcount = 0;
2166 			prio->flow_table = ft;
2167 		} else {
2168 			err = PTR_ERR(ft);
2169 		}
2170 	}
2171 
2172 	return err ? ERR_PTR(err) : prio;
2173 }
2174 
2175 static struct mlx5_ib_flow_handler *create_flow_rule(struct mlx5_ib_dev *dev,
2176 						     struct mlx5_ib_flow_prio *ft_prio,
2177 						     const struct ib_flow_attr *flow_attr,
2178 						     struct mlx5_flow_destination *dst)
2179 {
2180 	struct mlx5_flow_table	*ft = ft_prio->flow_table;
2181 	struct mlx5_ib_flow_handler *handler;
2182 	struct mlx5_flow_spec *spec;
2183 	const void *ib_flow = (const void *)flow_attr + sizeof(*flow_attr);
2184 	unsigned int spec_index;
2185 	u32 action;
2186 	int err = 0;
2187 
2188 	if (!is_valid_attr(flow_attr))
2189 		return ERR_PTR(-EINVAL);
2190 
2191 	spec = mlx5_vzalloc(sizeof(*spec));
2192 	handler = kzalloc(sizeof(*handler), GFP_KERNEL);
2193 	if (!handler || !spec) {
2194 		err = -ENOMEM;
2195 		goto free;
2196 	}
2197 
2198 	INIT_LIST_HEAD(&handler->list);
2199 
2200 	for (spec_index = 0; spec_index < flow_attr->num_of_specs; spec_index++) {
2201 		err = parse_flow_attr(spec->match_criteria,
2202 				      spec->match_value, ib_flow);
2203 		if (err < 0)
2204 			goto free;
2205 
2206 		ib_flow += ((union ib_flow_spec *)ib_flow)->size;
2207 	}
2208 
2209 	spec->match_criteria_enable = get_match_criteria_enable(spec->match_criteria);
2210 	action = dst ? MLX5_FLOW_CONTEXT_ACTION_FWD_DEST :
2211 		MLX5_FLOW_CONTEXT_ACTION_FWD_NEXT_PRIO;
2212 	handler->rule = mlx5_add_flow_rule(ft, spec->match_criteria_enable,
2213 					   spec->match_criteria,
2214 					   spec->match_value,
2215 					   action,
2216 					   MLX5_FS_DEFAULT_FLOW_TAG,
2217 					   dst);
2218 
2219 	if (IS_ERR(handler->rule)) {
2220 		err = PTR_ERR(handler->rule);
2221 		goto free;
2222 	}
2223 
2224 	ft_prio->refcount++;
2225 	handler->prio = ft_prio;
2226 
2227 	ft_prio->flow_table = ft;
2228 free:
2229 	if (err)
2230 		kfree(handler);
2231 	kvfree(spec);
2232 	return err ? ERR_PTR(err) : handler;
2233 }
2234 
2235 static struct mlx5_ib_flow_handler *create_dont_trap_rule(struct mlx5_ib_dev *dev,
2236 							  struct mlx5_ib_flow_prio *ft_prio,
2237 							  struct ib_flow_attr *flow_attr,
2238 							  struct mlx5_flow_destination *dst)
2239 {
2240 	struct mlx5_ib_flow_handler *handler_dst = NULL;
2241 	struct mlx5_ib_flow_handler *handler = NULL;
2242 
2243 	handler = create_flow_rule(dev, ft_prio, flow_attr, NULL);
2244 	if (!IS_ERR(handler)) {
2245 		handler_dst = create_flow_rule(dev, ft_prio,
2246 					       flow_attr, dst);
2247 		if (IS_ERR(handler_dst)) {
2248 			mlx5_del_flow_rule(&handler->rule);
2249 			ft_prio->refcount--;
2250 			kfree(handler);
2251 			handler = handler_dst;
2252 		} else {
2253 			list_add(&handler_dst->list, &handler->list);
2254 		}
2255 	}
2256 
2257 	return handler;
2258 }
2259 enum {
2260 	LEFTOVERS_MC,
2261 	LEFTOVERS_UC,
2262 };
2263 
2264 static struct mlx5_ib_flow_handler *create_leftovers_rule(struct mlx5_ib_dev *dev,
2265 							  struct mlx5_ib_flow_prio *ft_prio,
2266 							  struct ib_flow_attr *flow_attr,
2267 							  struct mlx5_flow_destination *dst)
2268 {
2269 	struct mlx5_ib_flow_handler *handler_ucast = NULL;
2270 	struct mlx5_ib_flow_handler *handler = NULL;
2271 
2272 	static struct {
2273 		struct ib_flow_attr	flow_attr;
2274 		struct ib_flow_spec_eth eth_flow;
2275 	} leftovers_specs[] = {
2276 		[LEFTOVERS_MC] = {
2277 			.flow_attr = {
2278 				.num_of_specs = 1,
2279 				.size = sizeof(leftovers_specs[0])
2280 			},
2281 			.eth_flow = {
2282 				.type = IB_FLOW_SPEC_ETH,
2283 				.size = sizeof(struct ib_flow_spec_eth),
2284 				.mask = {.dst_mac = {0x1} },
2285 				.val =  {.dst_mac = {0x1} }
2286 			}
2287 		},
2288 		[LEFTOVERS_UC] = {
2289 			.flow_attr = {
2290 				.num_of_specs = 1,
2291 				.size = sizeof(leftovers_specs[0])
2292 			},
2293 			.eth_flow = {
2294 				.type = IB_FLOW_SPEC_ETH,
2295 				.size = sizeof(struct ib_flow_spec_eth),
2296 				.mask = {.dst_mac = {0x1} },
2297 				.val = {.dst_mac = {} }
2298 			}
2299 		}
2300 	};
2301 
2302 	handler = create_flow_rule(dev, ft_prio,
2303 				   &leftovers_specs[LEFTOVERS_MC].flow_attr,
2304 				   dst);
2305 	if (!IS_ERR(handler) &&
2306 	    flow_attr->type == IB_FLOW_ATTR_ALL_DEFAULT) {
2307 		handler_ucast = create_flow_rule(dev, ft_prio,
2308 						 &leftovers_specs[LEFTOVERS_UC].flow_attr,
2309 						 dst);
2310 		if (IS_ERR(handler_ucast)) {
2311 			mlx5_del_flow_rule(&handler->rule);
2312 			ft_prio->refcount--;
2313 			kfree(handler);
2314 			handler = handler_ucast;
2315 		} else {
2316 			list_add(&handler_ucast->list, &handler->list);
2317 		}
2318 	}
2319 
2320 	return handler;
2321 }
2322 
2323 static struct mlx5_ib_flow_handler *create_sniffer_rule(struct mlx5_ib_dev *dev,
2324 							struct mlx5_ib_flow_prio *ft_rx,
2325 							struct mlx5_ib_flow_prio *ft_tx,
2326 							struct mlx5_flow_destination *dst)
2327 {
2328 	struct mlx5_ib_flow_handler *handler_rx;
2329 	struct mlx5_ib_flow_handler *handler_tx;
2330 	int err;
2331 	static const struct ib_flow_attr flow_attr  = {
2332 		.num_of_specs = 0,
2333 		.type = IB_FLOW_ATTR_SNIFFER,
2334 		.size = sizeof(flow_attr)
2335 	};
2336 
2337 	handler_rx = create_flow_rule(dev, ft_rx, &flow_attr, dst);
2338 	if (IS_ERR(handler_rx)) {
2339 		err = PTR_ERR(handler_rx);
2340 		goto err;
2341 	}
2342 
2343 	handler_tx = create_flow_rule(dev, ft_tx, &flow_attr, dst);
2344 	if (IS_ERR(handler_tx)) {
2345 		err = PTR_ERR(handler_tx);
2346 		goto err_tx;
2347 	}
2348 
2349 	list_add(&handler_tx->list, &handler_rx->list);
2350 
2351 	return handler_rx;
2352 
2353 err_tx:
2354 	mlx5_del_flow_rule(&handler_rx->rule);
2355 	ft_rx->refcount--;
2356 	kfree(handler_rx);
2357 err:
2358 	return ERR_PTR(err);
2359 }
2360 
2361 static struct ib_flow *mlx5_ib_create_flow(struct ib_qp *qp,
2362 					   struct ib_flow_attr *flow_attr,
2363 					   int domain,
2364 					   struct ib_udata *udata)
2365 {
2366 	struct mlx5_ib_dev *dev = to_mdev(qp->device);
2367 	struct mlx5_ib_qp *mqp = to_mqp(qp);
2368 	struct mlx5_ib_flow_handler *handler = NULL;
2369 	struct mlx5_flow_destination *dst = NULL;
2370 	struct mlx5_ib_flow_prio *ft_prio_tx = NULL;
2371 	struct mlx5_ib_flow_prio *ft_prio;
2372 	struct mlx5_ib_create_flow *ucmd = NULL, ucmd_hdr;
2373 	size_t min_ucmd_sz, required_ucmd_sz;
2374 	int err;
2375 
2376 	if (udata && udata->inlen) {
2377 		min_ucmd_sz = offsetofend(struct mlx5_ib_create_flow, reserved);
2378 		if (udata->inlen < min_ucmd_sz)
2379 			return ERR_PTR(-EOPNOTSUPP);
2380 
2381 		err = ib_copy_from_udata(&ucmd_hdr, udata, min_ucmd_sz);
2382 		if (err)
2383 			return ERR_PTR(err);
2384 
2385 		/* currently supports only one counters data */
2386 		if (ucmd_hdr.ncounters_data > 1)
2387 			return ERR_PTR(-EINVAL);
2388 
2389 		required_ucmd_sz = min_ucmd_sz +
2390 			sizeof(struct mlx5_ib_flow_counters_data) *
2391 			ucmd_hdr.ncounters_data;
2392 		if (udata->inlen > required_ucmd_sz &&
2393 		    !ib_is_udata_cleared(udata, required_ucmd_sz,
2394 					 udata->inlen - required_ucmd_sz))
2395 			return ERR_PTR(-EOPNOTSUPP);
2396 
2397 		ucmd = kzalloc(required_ucmd_sz, GFP_KERNEL);
2398 		if (!ucmd)
2399 			return ERR_PTR(-ENOMEM);
2400 
2401 		err = ib_copy_from_udata(ucmd, udata, required_ucmd_sz);
2402 		if (err)
2403 			goto free_ucmd;
2404 	}
2405 
2406 	if (flow_attr->priority > MLX5_IB_FLOW_LAST_PRIO) {
2407 		err = -ENOMEM;
2408 		goto free_ucmd;
2409 	}
2410 
2411 	if (flow_attr->flags & ~IB_FLOW_ATTR_FLAGS_DONT_TRAP) {
2412 		err = -EINVAL;
2413 		goto free_ucmd;
2414 	}
2415 
2416 	dst = kzalloc(sizeof(*dst), GFP_KERNEL);
2417 	if (!dst) {
2418 		err = -ENOMEM;
2419 		goto free_ucmd;
2420 	}
2421 
2422 	mutex_lock(&dev->flow_db.lock);
2423 
2424 	ft_prio = get_flow_table(dev, flow_attr, MLX5_IB_FT_RX);
2425 	if (IS_ERR(ft_prio)) {
2426 		err = PTR_ERR(ft_prio);
2427 		goto unlock;
2428 	}
2429 	if (flow_attr->type == IB_FLOW_ATTR_SNIFFER) {
2430 		ft_prio_tx = get_flow_table(dev, flow_attr, MLX5_IB_FT_TX);
2431 		if (IS_ERR(ft_prio_tx)) {
2432 			err = PTR_ERR(ft_prio_tx);
2433 			ft_prio_tx = NULL;
2434 			goto destroy_ft;
2435 		}
2436 	}
2437 
2438 	dst->type = MLX5_FLOW_DESTINATION_TYPE_TIR;
2439 	if (mqp->flags & MLX5_IB_QP_RSS)
2440 		dst->tir_num = mqp->rss_qp.tirn;
2441 	else
2442 		dst->tir_num = mqp->raw_packet_qp.rq.tirn;
2443 
2444 	switch (flow_attr->type) {
2445 	case IB_FLOW_ATTR_NORMAL:
2446 		if (mqp->flags & IB_QP_CREATE_SOURCE_QPN) {
2447 			err = -EOPNOTSUPP;
2448 			goto destroy_ft;
2449 		}
2450 		if (flow_attr->flags & IB_FLOW_ATTR_FLAGS_DONT_TRAP) {
2451 			handler = create_dont_trap_rule(dev, ft_prio, flow_attr, dst);
2452 		} else {
2453 			handler = create_flow_rule(dev, ft_prio, flow_attr, dst);
2454 		}
2455 		break;
2456 	case IB_FLOW_ATTR_ALL_DEFAULT:
2457 	case IB_FLOW_ATTR_MC_DEFAULT:
2458 		handler = create_leftovers_rule(dev, ft_prio, flow_attr, dst);
2459 		break;
2460 	case IB_FLOW_ATTR_SNIFFER:
2461 		handler = create_sniffer_rule(dev, ft_prio, ft_prio_tx, dst);
2462 		break;
2463 	default:
2464 		err = -EINVAL;
2465 		goto destroy_ft;
2466 	}
2467 
2468 	if (IS_ERR(handler)) {
2469 		err = PTR_ERR(handler);
2470 		handler = NULL;
2471 		goto destroy_ft;
2472 	}
2473 
2474 	mutex_unlock(&dev->flow_db.lock);
2475 	kfree(dst);
2476 	kfree(ucmd);
2477 
2478 	return &handler->ibflow;
2479 
2480 destroy_ft:
2481 	put_flow_table(dev, ft_prio, false);
2482 	if (ft_prio_tx)
2483 		put_flow_table(dev, ft_prio_tx, false);
2484 unlock:
2485 	mutex_unlock(&dev->flow_db.lock);
2486 	kfree(dst);
2487 free_ucmd:
2488 	kfree(ucmd);
2489 	return ERR_PTR(err);
2490 }
2491 
2492 static int mlx5_ib_mcg_attach(struct ib_qp *ibqp, union ib_gid *gid, u16 lid)
2493 {
2494 	struct mlx5_ib_dev *dev = to_mdev(ibqp->device);
2495 	int err;
2496 
2497 	err = mlx5_core_attach_mcg(dev->mdev, gid, ibqp->qp_num);
2498 	if (err)
2499 		mlx5_ib_warn(dev, "failed attaching QPN 0x%x, MGID %pI6\n",
2500 			     ibqp->qp_num, gid->raw);
2501 
2502 	return err;
2503 }
2504 
2505 static int mlx5_ib_mcg_detach(struct ib_qp *ibqp, union ib_gid *gid, u16 lid)
2506 {
2507 	struct mlx5_ib_dev *dev = to_mdev(ibqp->device);
2508 	int err;
2509 
2510 	err = mlx5_core_detach_mcg(dev->mdev, gid, ibqp->qp_num);
2511 	if (err)
2512 		mlx5_ib_warn(dev, "failed detaching QPN 0x%x, MGID %pI6\n",
2513 			     ibqp->qp_num, gid->raw);
2514 
2515 	return err;
2516 }
2517 
2518 static int init_node_data(struct mlx5_ib_dev *dev)
2519 {
2520 	int err;
2521 
2522 	err = mlx5_query_node_desc(dev, dev->ib_dev.node_desc);
2523 	if (err)
2524 		return err;
2525 
2526 	return mlx5_query_node_guid(dev, &dev->ib_dev.node_guid);
2527 }
2528 
2529 static ssize_t show_fw_pages(struct device *device, struct device_attribute *attr,
2530 			     char *buf)
2531 {
2532 	struct mlx5_ib_dev *dev =
2533 		container_of(device, struct mlx5_ib_dev, ib_dev.dev);
2534 
2535 	return sprintf(buf, "%lld\n", (long long)dev->mdev->priv.fw_pages);
2536 }
2537 
2538 static ssize_t show_reg_pages(struct device *device,
2539 			      struct device_attribute *attr, char *buf)
2540 {
2541 	struct mlx5_ib_dev *dev =
2542 		container_of(device, struct mlx5_ib_dev, ib_dev.dev);
2543 
2544 	return sprintf(buf, "%d\n", atomic_read(&dev->mdev->priv.reg_pages));
2545 }
2546 
2547 static ssize_t show_hca(struct device *device, struct device_attribute *attr,
2548 			char *buf)
2549 {
2550 	struct mlx5_ib_dev *dev =
2551 		container_of(device, struct mlx5_ib_dev, ib_dev.dev);
2552 	return sprintf(buf, "MT%d\n", dev->mdev->pdev->device);
2553 }
2554 
2555 static ssize_t show_rev(struct device *device, struct device_attribute *attr,
2556 			char *buf)
2557 {
2558 	struct mlx5_ib_dev *dev =
2559 		container_of(device, struct mlx5_ib_dev, ib_dev.dev);
2560 	return sprintf(buf, "%x\n", dev->mdev->pdev->revision);
2561 }
2562 
2563 static ssize_t show_board(struct device *device, struct device_attribute *attr,
2564 			  char *buf)
2565 {
2566 	struct mlx5_ib_dev *dev =
2567 		container_of(device, struct mlx5_ib_dev, ib_dev.dev);
2568 	return sprintf(buf, "%.*s\n", MLX5_BOARD_ID_LEN,
2569 		       dev->mdev->board_id);
2570 }
2571 
2572 static DEVICE_ATTR(hw_rev,   S_IRUGO, show_rev,    NULL);
2573 static DEVICE_ATTR(hca_type, S_IRUGO, show_hca,    NULL);
2574 static DEVICE_ATTR(board_id, S_IRUGO, show_board,  NULL);
2575 static DEVICE_ATTR(fw_pages, S_IRUGO, show_fw_pages, NULL);
2576 static DEVICE_ATTR(reg_pages, S_IRUGO, show_reg_pages, NULL);
2577 
2578 static struct device_attribute *mlx5_class_attributes[] = {
2579 	&dev_attr_hw_rev,
2580 	&dev_attr_hca_type,
2581 	&dev_attr_board_id,
2582 	&dev_attr_fw_pages,
2583 	&dev_attr_reg_pages,
2584 };
2585 
2586 static void pkey_change_handler(struct work_struct *work)
2587 {
2588 	struct mlx5_ib_port_resources *ports =
2589 		container_of(work, struct mlx5_ib_port_resources,
2590 			     pkey_change_work);
2591 
2592 	mutex_lock(&ports->devr->mutex);
2593 	mlx5_ib_gsi_pkey_change(ports->gsi);
2594 	mutex_unlock(&ports->devr->mutex);
2595 }
2596 
2597 static void mlx5_ib_handle_internal_error(struct mlx5_ib_dev *ibdev)
2598 {
2599 	struct mlx5_ib_qp *mqp;
2600 	struct mlx5_ib_cq *send_mcq, *recv_mcq;
2601 	struct mlx5_core_cq *mcq;
2602 	struct list_head cq_armed_list;
2603 	unsigned long flags_qp;
2604 	unsigned long flags_cq;
2605 	unsigned long flags;
2606 
2607 	INIT_LIST_HEAD(&cq_armed_list);
2608 
2609 	/* Go over qp list reside on that ibdev, sync with create/destroy qp.*/
2610 	spin_lock_irqsave(&ibdev->reset_flow_resource_lock, flags);
2611 	list_for_each_entry(mqp, &ibdev->qp_list, qps_list) {
2612 		spin_lock_irqsave(&mqp->sq.lock, flags_qp);
2613 		if (mqp->sq.tail != mqp->sq.head) {
2614 			send_mcq = to_mcq(mqp->ibqp.send_cq);
2615 			spin_lock_irqsave(&send_mcq->lock, flags_cq);
2616 			if (send_mcq->mcq.comp &&
2617 			    mqp->ibqp.send_cq->comp_handler) {
2618 				if (!send_mcq->mcq.reset_notify_added) {
2619 					send_mcq->mcq.reset_notify_added = 1;
2620 					list_add_tail(&send_mcq->mcq.reset_notify,
2621 						      &cq_armed_list);
2622 				}
2623 			}
2624 			spin_unlock_irqrestore(&send_mcq->lock, flags_cq);
2625 		}
2626 		spin_unlock_irqrestore(&mqp->sq.lock, flags_qp);
2627 		spin_lock_irqsave(&mqp->rq.lock, flags_qp);
2628 		/* no handling is needed for SRQ */
2629 		if (!mqp->ibqp.srq) {
2630 			if (mqp->rq.tail != mqp->rq.head) {
2631 				recv_mcq = to_mcq(mqp->ibqp.recv_cq);
2632 				spin_lock_irqsave(&recv_mcq->lock, flags_cq);
2633 				if (recv_mcq->mcq.comp &&
2634 				    mqp->ibqp.recv_cq->comp_handler) {
2635 					if (!recv_mcq->mcq.reset_notify_added) {
2636 						recv_mcq->mcq.reset_notify_added = 1;
2637 						list_add_tail(&recv_mcq->mcq.reset_notify,
2638 							      &cq_armed_list);
2639 					}
2640 				}
2641 				spin_unlock_irqrestore(&recv_mcq->lock,
2642 						       flags_cq);
2643 			}
2644 		}
2645 		spin_unlock_irqrestore(&mqp->rq.lock, flags_qp);
2646 	}
2647 	/*At that point all inflight post send were put to be executed as of we
2648 	 * lock/unlock above locks Now need to arm all involved CQs.
2649 	 */
2650 	list_for_each_entry(mcq, &cq_armed_list, reset_notify) {
2651 		mcq->comp(mcq, NULL);
2652 	}
2653 	spin_unlock_irqrestore(&ibdev->reset_flow_resource_lock, flags);
2654 }
2655 
2656 static void mlx5_ib_event(struct mlx5_core_dev *dev, void *context,
2657 			  enum mlx5_dev_event event, unsigned long param)
2658 {
2659 	struct mlx5_ib_dev *ibdev = (struct mlx5_ib_dev *)context;
2660 	struct ib_event ibev;
2661 	bool fatal = false;
2662 	u8 port = (u8)param;
2663 
2664 	switch (event) {
2665 	case MLX5_DEV_EVENT_SYS_ERROR:
2666 		ibev.event = IB_EVENT_DEVICE_FATAL;
2667 		mlx5_ib_handle_internal_error(ibdev);
2668 		fatal = true;
2669 		break;
2670 
2671 	case MLX5_DEV_EVENT_PORT_UP:
2672 	case MLX5_DEV_EVENT_PORT_DOWN:
2673 	case MLX5_DEV_EVENT_PORT_INITIALIZED:
2674 		/* In RoCE, port up/down events are handled in
2675 		 * mlx5_netdev_event().
2676 		 */
2677 		if (mlx5_ib_port_link_layer(&ibdev->ib_dev, port) ==
2678 			IB_LINK_LAYER_ETHERNET)
2679 			return;
2680 
2681 		ibev.event = (event == MLX5_DEV_EVENT_PORT_UP) ?
2682 			     IB_EVENT_PORT_ACTIVE : IB_EVENT_PORT_ERR;
2683 		break;
2684 
2685 	case MLX5_DEV_EVENT_LID_CHANGE:
2686 		ibev.event = IB_EVENT_LID_CHANGE;
2687 		break;
2688 
2689 	case MLX5_DEV_EVENT_PKEY_CHANGE:
2690 		ibev.event = IB_EVENT_PKEY_CHANGE;
2691 
2692 		schedule_work(&ibdev->devr.ports[port - 1].pkey_change_work);
2693 		break;
2694 
2695 	case MLX5_DEV_EVENT_GUID_CHANGE:
2696 		ibev.event = IB_EVENT_GID_CHANGE;
2697 		break;
2698 
2699 	case MLX5_DEV_EVENT_CLIENT_REREG:
2700 		ibev.event = IB_EVENT_CLIENT_REREGISTER;
2701 		break;
2702 
2703 	default:
2704 		/* unsupported event */
2705 		return;
2706 	}
2707 
2708 	ibev.device	      = &ibdev->ib_dev;
2709 	ibev.element.port_num = port;
2710 
2711 	if (!rdma_is_port_valid(&ibdev->ib_dev, port)) {
2712 		mlx5_ib_warn(ibdev, "warning: event(%d) on port %d\n", event, port);
2713 		return;
2714 	}
2715 
2716 	if (ibdev->ib_active)
2717 		ib_dispatch_event(&ibev);
2718 
2719 	if (fatal)
2720 		ibdev->ib_active = false;
2721 }
2722 
2723 static void get_ext_port_caps(struct mlx5_ib_dev *dev)
2724 {
2725 	int port;
2726 
2727 	for (port = 1; port <= MLX5_CAP_GEN(dev->mdev, num_ports); port++)
2728 		mlx5_query_ext_port_caps(dev, port);
2729 }
2730 
2731 static int get_port_caps(struct mlx5_ib_dev *dev)
2732 {
2733 	struct ib_device_attr *dprops = NULL;
2734 	struct ib_port_attr *pprops = NULL;
2735 	int err = -ENOMEM;
2736 	int port;
2737 	struct ib_udata uhw = {.inlen = 0, .outlen = 0};
2738 
2739 	pprops = kmalloc(sizeof(*pprops), GFP_KERNEL);
2740 	if (!pprops)
2741 		goto out;
2742 
2743 	dprops = kmalloc(sizeof(*dprops), GFP_KERNEL);
2744 	if (!dprops)
2745 		goto out;
2746 
2747 	err = mlx5_ib_query_device(&dev->ib_dev, dprops, &uhw);
2748 	if (err) {
2749 		mlx5_ib_warn(dev, "query_device failed %d\n", err);
2750 		goto out;
2751 	}
2752 
2753 	for (port = 1; port <= MLX5_CAP_GEN(dev->mdev, num_ports); port++) {
2754 		err = mlx5_ib_query_port(&dev->ib_dev, port, pprops);
2755 		if (err) {
2756 			mlx5_ib_warn(dev, "query_port %d failed %d\n",
2757 				     port, err);
2758 			break;
2759 		}
2760 		dev->mdev->port_caps[port - 1].pkey_table_len =
2761 						dprops->max_pkeys;
2762 		dev->mdev->port_caps[port - 1].gid_table_len =
2763 						pprops->gid_tbl_len;
2764 		mlx5_ib_dbg(dev, "pkey_table_len %d, gid_table_len %d\n",
2765 			    dprops->max_pkeys, pprops->gid_tbl_len);
2766 	}
2767 
2768 out:
2769 	kfree(pprops);
2770 	kfree(dprops);
2771 
2772 	return err;
2773 }
2774 
2775 static void destroy_umrc_res(struct mlx5_ib_dev *dev)
2776 {
2777 	int err;
2778 
2779 	err = mlx5_mr_cache_cleanup(dev);
2780 	if (err)
2781 		mlx5_ib_warn(dev, "mr cache cleanup failed\n");
2782 
2783 	if (dev->umrc.qp)
2784 		mlx5_ib_destroy_qp(dev->umrc.qp, NULL);
2785 	if (dev->umrc.cq)
2786 		ib_free_cq(dev->umrc.cq);
2787 	if (dev->umrc.pd)
2788 		ib_dealloc_pd(dev->umrc.pd);
2789 }
2790 
2791 enum {
2792 	MAX_UMR_WR = 128,
2793 };
2794 
2795 static int create_umr_res(struct mlx5_ib_dev *dev)
2796 {
2797 	struct ib_qp_init_attr *init_attr = NULL;
2798 	struct ib_qp_attr *attr = NULL;
2799 	struct ib_pd *pd;
2800 	struct ib_cq *cq;
2801 	struct ib_qp *qp;
2802 	int ret;
2803 
2804 	attr = kzalloc(sizeof(*attr), GFP_KERNEL);
2805 	init_attr = kzalloc(sizeof(*init_attr), GFP_KERNEL);
2806 	if (!attr || !init_attr) {
2807 		ret = -ENOMEM;
2808 		goto error_0;
2809 	}
2810 
2811 	pd = ib_alloc_pd(&dev->ib_dev, 0);
2812 	if (IS_ERR(pd)) {
2813 		mlx5_ib_dbg(dev, "Couldn't create PD for sync UMR QP\n");
2814 		ret = PTR_ERR(pd);
2815 		goto error_0;
2816 	}
2817 
2818 	cq = ib_alloc_cq(&dev->ib_dev, NULL, 128, 0, IB_POLL_SOFTIRQ);
2819 	if (IS_ERR(cq)) {
2820 		mlx5_ib_dbg(dev, "Couldn't create CQ for sync UMR QP\n");
2821 		ret = PTR_ERR(cq);
2822 		goto error_2;
2823 	}
2824 
2825 	init_attr->send_cq = cq;
2826 	init_attr->recv_cq = cq;
2827 	init_attr->sq_sig_type = IB_SIGNAL_ALL_WR;
2828 	init_attr->cap.max_send_wr = MAX_UMR_WR;
2829 	init_attr->cap.max_send_sge = 1;
2830 	init_attr->qp_type = MLX5_IB_QPT_REG_UMR;
2831 	init_attr->port_num = 1;
2832 	qp = mlx5_ib_create_qp(pd, init_attr, NULL);
2833 	if (IS_ERR(qp)) {
2834 		mlx5_ib_dbg(dev, "Couldn't create sync UMR QP\n");
2835 		ret = PTR_ERR(qp);
2836 		goto error_3;
2837 	}
2838 	qp->device     = &dev->ib_dev;
2839 	qp->real_qp    = qp;
2840 	qp->uobject    = NULL;
2841 	qp->qp_type    = MLX5_IB_QPT_REG_UMR;
2842 
2843 	attr->qp_state = IB_QPS_INIT;
2844 	attr->port_num = 1;
2845 	ret = mlx5_ib_modify_qp(qp, attr, IB_QP_STATE | IB_QP_PKEY_INDEX |
2846 				IB_QP_PORT, NULL);
2847 	if (ret) {
2848 		mlx5_ib_dbg(dev, "Couldn't modify UMR QP\n");
2849 		goto error_4;
2850 	}
2851 
2852 	memset(attr, 0, sizeof(*attr));
2853 	attr->qp_state = IB_QPS_RTR;
2854 	attr->path_mtu = IB_MTU_256;
2855 
2856 	ret = mlx5_ib_modify_qp(qp, attr, IB_QP_STATE, NULL);
2857 	if (ret) {
2858 		mlx5_ib_dbg(dev, "Couldn't modify umr QP to rtr\n");
2859 		goto error_4;
2860 	}
2861 
2862 	memset(attr, 0, sizeof(*attr));
2863 	attr->qp_state = IB_QPS_RTS;
2864 	ret = mlx5_ib_modify_qp(qp, attr, IB_QP_STATE, NULL);
2865 	if (ret) {
2866 		mlx5_ib_dbg(dev, "Couldn't modify umr QP to rts\n");
2867 		goto error_4;
2868 	}
2869 
2870 	dev->umrc.qp = qp;
2871 	dev->umrc.cq = cq;
2872 	dev->umrc.pd = pd;
2873 
2874 	sema_init(&dev->umrc.sem, MAX_UMR_WR);
2875 	ret = mlx5_mr_cache_init(dev);
2876 	if (ret) {
2877 		mlx5_ib_warn(dev, "mr cache init failed %d\n", ret);
2878 		goto error_4;
2879 	}
2880 
2881 	kfree(attr);
2882 	kfree(init_attr);
2883 
2884 	return 0;
2885 
2886 error_4:
2887 	mlx5_ib_destroy_qp(qp, NULL);
2888 	dev->umrc.qp = NULL;
2889 
2890 error_3:
2891 	ib_free_cq(cq);
2892 	dev->umrc.cq = NULL;
2893 
2894 error_2:
2895 	ib_dealloc_pd(pd);
2896 	dev->umrc.pd = NULL;
2897 
2898 error_0:
2899 	kfree(attr);
2900 	kfree(init_attr);
2901 	return ret;
2902 }
2903 
2904 static int create_dev_resources(struct mlx5_ib_resources *devr)
2905 {
2906 	struct ib_srq_init_attr attr;
2907 	struct mlx5_ib_dev *dev;
2908 	struct ib_device *ibdev;
2909 	struct ib_cq_init_attr cq_attr = {.cqe = 1};
2910 	int port;
2911 	int ret = 0;
2912 
2913 	dev = container_of(devr, struct mlx5_ib_dev, devr);
2914 	ibdev = &dev->ib_dev;
2915 
2916 	mutex_init(&devr->mutex);
2917 
2918 	devr->p0 = rdma_zalloc_drv_obj(ibdev, ib_pd);
2919 	if (!devr->p0)
2920 		return -ENOMEM;
2921 
2922 	devr->p0->device  = ibdev;
2923 	devr->p0->uobject = NULL;
2924 	atomic_set(&devr->p0->usecnt, 0);
2925 
2926 	ret = mlx5_ib_alloc_pd(devr->p0, NULL);
2927 	if (ret)
2928 		goto error0;
2929 
2930 	devr->c0 = rdma_zalloc_drv_obj(ibdev, ib_cq);
2931 	if (!devr->c0) {
2932 		ret = -ENOMEM;
2933 		goto error1;
2934 	}
2935 
2936 	devr->c0->device = &dev->ib_dev;
2937 	atomic_set(&devr->c0->usecnt, 0);
2938 
2939 	ret = mlx5_ib_create_cq(devr->c0, &cq_attr, NULL);
2940 	if (ret)
2941 		goto err_create_cq;
2942 
2943 	devr->x0 = mlx5_ib_alloc_xrcd(&dev->ib_dev, NULL);
2944 	if (IS_ERR(devr->x0)) {
2945 		ret = PTR_ERR(devr->x0);
2946 		goto error2;
2947 	}
2948 	devr->x0->device = &dev->ib_dev;
2949 	devr->x0->inode = NULL;
2950 	atomic_set(&devr->x0->usecnt, 0);
2951 	mutex_init(&devr->x0->tgt_qp_mutex);
2952 	INIT_LIST_HEAD(&devr->x0->tgt_qp_list);
2953 
2954 	devr->x1 = mlx5_ib_alloc_xrcd(&dev->ib_dev, NULL);
2955 	if (IS_ERR(devr->x1)) {
2956 		ret = PTR_ERR(devr->x1);
2957 		goto error3;
2958 	}
2959 	devr->x1->device = &dev->ib_dev;
2960 	devr->x1->inode = NULL;
2961 	atomic_set(&devr->x1->usecnt, 0);
2962 	mutex_init(&devr->x1->tgt_qp_mutex);
2963 	INIT_LIST_HEAD(&devr->x1->tgt_qp_list);
2964 
2965 	memset(&attr, 0, sizeof(attr));
2966 	attr.attr.max_sge = 1;
2967 	attr.attr.max_wr = 1;
2968 	attr.srq_type = IB_SRQT_XRC;
2969 	attr.ext.cq = devr->c0;
2970 	attr.ext.xrc.xrcd = devr->x0;
2971 
2972 	devr->s0 = rdma_zalloc_drv_obj(ibdev, ib_srq);
2973 	if (!devr->s0) {
2974 		ret = -ENOMEM;
2975 		goto error4;
2976 	}
2977 
2978 	devr->s0->device	= &dev->ib_dev;
2979 	devr->s0->pd		= devr->p0;
2980 	devr->s0->srq_type      = IB_SRQT_XRC;
2981 	devr->s0->ext.xrc.xrcd	= devr->x0;
2982 	devr->s0->ext.cq	= devr->c0;
2983 	ret = mlx5_ib_create_srq(devr->s0, &attr, NULL);
2984 	if (ret)
2985 		goto err_create;
2986 
2987 	atomic_inc(&devr->s0->ext.xrc.xrcd->usecnt);
2988 	atomic_inc(&devr->s0->ext.cq->usecnt);
2989 	atomic_inc(&devr->p0->usecnt);
2990 	atomic_set(&devr->s0->usecnt, 0);
2991 
2992 	memset(&attr, 0, sizeof(attr));
2993 	attr.attr.max_sge = 1;
2994 	attr.attr.max_wr = 1;
2995 	attr.srq_type = IB_SRQT_BASIC;
2996 	devr->s1 = rdma_zalloc_drv_obj(ibdev, ib_srq);
2997 	if (!devr->s1) {
2998 		ret = -ENOMEM;
2999 		goto error5;
3000 	}
3001 
3002 	devr->s1->device	= &dev->ib_dev;
3003 	devr->s1->pd		= devr->p0;
3004 	devr->s1->srq_type      = IB_SRQT_BASIC;
3005 	devr->s1->ext.cq	= devr->c0;
3006 
3007 	ret = mlx5_ib_create_srq(devr->s1, &attr, NULL);
3008 	if (ret)
3009 		goto error6;
3010 
3011 	atomic_inc(&devr->p0->usecnt);
3012 	atomic_set(&devr->s1->usecnt, 0);
3013 
3014 	for (port = 0; port < ARRAY_SIZE(devr->ports); ++port) {
3015 		INIT_WORK(&devr->ports[port].pkey_change_work,
3016 			  pkey_change_handler);
3017 		devr->ports[port].devr = devr;
3018 	}
3019 
3020 	return 0;
3021 
3022 error6:
3023 	kfree(devr->s1);
3024 error5:
3025 	mlx5_ib_destroy_srq(devr->s0, NULL);
3026 err_create:
3027 	kfree(devr->s0);
3028 error4:
3029 	mlx5_ib_dealloc_xrcd(devr->x1, NULL);
3030 error3:
3031 	mlx5_ib_dealloc_xrcd(devr->x0, NULL);
3032 error2:
3033 	mlx5_ib_destroy_cq(devr->c0, NULL);
3034 err_create_cq:
3035 	kfree(devr->c0);
3036 error1:
3037 	mlx5_ib_dealloc_pd(devr->p0, NULL);
3038 error0:
3039 	kfree(devr->p0);
3040 	return ret;
3041 }
3042 
3043 static void destroy_dev_resources(struct mlx5_ib_resources *devr)
3044 {
3045 	int port;
3046 
3047 	mlx5_ib_destroy_srq(devr->s1, NULL);
3048 	kfree(devr->s1);
3049 	mlx5_ib_destroy_srq(devr->s0, NULL);
3050 	kfree(devr->s0);
3051 	mlx5_ib_dealloc_xrcd(devr->x0, NULL);
3052 	mlx5_ib_dealloc_xrcd(devr->x1, NULL);
3053 	mlx5_ib_destroy_cq(devr->c0, NULL);
3054 	kfree(devr->c0);
3055 	mlx5_ib_dealloc_pd(devr->p0, NULL);
3056 	kfree(devr->p0);
3057 
3058 	/* Make sure no change P_Key work items are still executing */
3059 	for (port = 0; port < ARRAY_SIZE(devr->ports); ++port)
3060 		cancel_work_sync(&devr->ports[port].pkey_change_work);
3061 }
3062 
3063 static u32 get_core_cap_flags(struct ib_device *ibdev)
3064 {
3065 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
3066 	enum rdma_link_layer ll = mlx5_ib_port_link_layer(ibdev, 1);
3067 	u8 l3_type_cap = MLX5_CAP_ROCE(dev->mdev, l3_type);
3068 	u8 roce_version_cap = MLX5_CAP_ROCE(dev->mdev, roce_version);
3069 	u32 ret = 0;
3070 
3071 	if (ll == IB_LINK_LAYER_INFINIBAND)
3072 		return RDMA_CORE_PORT_IBA_IB;
3073 
3074 	if (!(l3_type_cap & MLX5_ROCE_L3_TYPE_IPV4_CAP))
3075 		return 0;
3076 
3077 	if (!(l3_type_cap & MLX5_ROCE_L3_TYPE_IPV6_CAP))
3078 		return 0;
3079 
3080 	if (roce_version_cap & MLX5_ROCE_VERSION_1_CAP)
3081 		ret |= RDMA_CORE_PORT_IBA_ROCE;
3082 
3083 	if (roce_version_cap & MLX5_ROCE_VERSION_2_CAP)
3084 		ret |= RDMA_CORE_PORT_IBA_ROCE_UDP_ENCAP;
3085 
3086 	return ret;
3087 }
3088 
3089 static int mlx5_port_immutable(struct ib_device *ibdev, u8 port_num,
3090 			       struct ib_port_immutable *immutable)
3091 {
3092 	struct ib_port_attr attr;
3093 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
3094 	enum rdma_link_layer ll = mlx5_ib_port_link_layer(ibdev, port_num);
3095 	int err;
3096 
3097 	err = mlx5_ib_query_port(ibdev, port_num, &attr);
3098 	if (err)
3099 		return err;
3100 
3101 	immutable->pkey_tbl_len = attr.pkey_tbl_len;
3102 	immutable->gid_tbl_len = attr.gid_tbl_len;
3103 	immutable->core_cap_flags = get_core_cap_flags(ibdev);
3104 	if ((ll == IB_LINK_LAYER_INFINIBAND) || MLX5_CAP_GEN(dev->mdev, roce))
3105 		immutable->max_mad_size = IB_MGMT_MAD_SIZE;
3106 
3107 	return 0;
3108 }
3109 
3110 static void get_dev_fw_str(struct ib_device *ibdev, char *str,
3111 			   size_t str_len)
3112 {
3113 	struct mlx5_ib_dev *dev =
3114 		container_of(ibdev, struct mlx5_ib_dev, ib_dev);
3115 	snprintf(str, str_len, "%d.%d.%04d", fw_rev_maj(dev->mdev),
3116 		       fw_rev_min(dev->mdev), fw_rev_sub(dev->mdev));
3117 }
3118 
3119 static int mlx5_roce_lag_init(struct mlx5_ib_dev *dev)
3120 {
3121 	return 0;
3122 }
3123 
3124 static void mlx5_roce_lag_cleanup(struct mlx5_ib_dev *dev)
3125 {
3126 }
3127 
3128 static void mlx5_remove_roce_notifier(struct mlx5_ib_dev *dev)
3129 {
3130 	if (dev->roce.nb.notifier_call) {
3131 		unregister_netdevice_notifier(&dev->roce.nb);
3132 		dev->roce.nb.notifier_call = NULL;
3133 	}
3134 }
3135 
3136 static int
3137 mlx5_enable_roce_if_cb(if_t ifp, void *arg)
3138 {
3139 	struct mlx5_ib_dev *dev = arg;
3140 
3141 	/* check if network interface belongs to mlx5en */
3142 	if (!mlx5_netdev_match(ifp, dev->mdev, "mce"))
3143 		return (0);
3144 
3145 	write_lock(&dev->roce.netdev_lock);
3146 	dev->roce.netdev = ifp;
3147 	write_unlock(&dev->roce.netdev_lock);
3148 
3149 	return (0);
3150 }
3151 
3152 static int mlx5_enable_roce(struct mlx5_ib_dev *dev)
3153 {
3154 	struct epoch_tracker et;
3155 	VNET_ITERATOR_DECL(vnet_iter);
3156 	int err;
3157 
3158 	/* Check if mlx5en net device already exists */
3159 	VNET_LIST_RLOCK();
3160 	NET_EPOCH_ENTER(et);
3161 	VNET_FOREACH(vnet_iter) {
3162 		CURVNET_SET_QUIET(vnet_iter);
3163 		if_foreach(mlx5_enable_roce_if_cb, dev);
3164 		CURVNET_RESTORE();
3165 	}
3166 	NET_EPOCH_EXIT(et);
3167 	VNET_LIST_RUNLOCK();
3168 
3169 	dev->roce.nb.notifier_call = mlx5_netdev_event;
3170 	err = register_netdevice_notifier(&dev->roce.nb);
3171 	if (err) {
3172 		dev->roce.nb.notifier_call = NULL;
3173 		return err;
3174 	}
3175 
3176 	if (MLX5_CAP_GEN(dev->mdev, roce)) {
3177 		err = mlx5_nic_vport_enable_roce(dev->mdev);
3178 		if (err)
3179 			goto err_unregister_netdevice_notifier;
3180 	}
3181 
3182 	err = mlx5_roce_lag_init(dev);
3183 	if (err)
3184 		goto err_disable_roce;
3185 
3186 	return 0;
3187 
3188 err_disable_roce:
3189 	if (MLX5_CAP_GEN(dev->mdev, roce))
3190 		mlx5_nic_vport_disable_roce(dev->mdev);
3191 
3192 err_unregister_netdevice_notifier:
3193 	mlx5_remove_roce_notifier(dev);
3194 	return err;
3195 }
3196 
3197 static void mlx5_disable_roce(struct mlx5_ib_dev *dev)
3198 {
3199 	mlx5_roce_lag_cleanup(dev);
3200 	if (MLX5_CAP_GEN(dev->mdev, roce))
3201 		mlx5_nic_vport_disable_roce(dev->mdev);
3202 }
3203 
3204 static void mlx5_ib_dealloc_q_port_counter(struct mlx5_ib_dev *dev, u8 port_num)
3205 {
3206 	mlx5_vport_dealloc_q_counter(dev->mdev,
3207 				     MLX5_INTERFACE_PROTOCOL_IB,
3208 				     dev->port[port_num].q_cnt_id);
3209 	dev->port[port_num].q_cnt_id = 0;
3210 }
3211 
3212 static void mlx5_ib_dealloc_q_counters(struct mlx5_ib_dev *dev)
3213 {
3214 	unsigned int i;
3215 
3216 	for (i = 0; i < dev->num_ports; i++)
3217 		mlx5_ib_dealloc_q_port_counter(dev, i);
3218 }
3219 
3220 static int mlx5_ib_alloc_q_counters(struct mlx5_ib_dev *dev)
3221 {
3222 	int i;
3223 	int ret;
3224 
3225 	for (i = 0; i < dev->num_ports; i++) {
3226 		ret = mlx5_vport_alloc_q_counter(dev->mdev,
3227 						 MLX5_INTERFACE_PROTOCOL_IB,
3228 						 &dev->port[i].q_cnt_id);
3229 		if (ret) {
3230 			mlx5_ib_warn(dev,
3231 				     "couldn't allocate queue counter for port %d, err %d\n",
3232 				     i + 1, ret);
3233 			goto dealloc_counters;
3234 		}
3235 	}
3236 
3237 	return 0;
3238 
3239 dealloc_counters:
3240 	while (--i >= 0)
3241 		mlx5_ib_dealloc_q_port_counter(dev, i);
3242 
3243 	return ret;
3244 }
3245 
3246 static const char * const names[] = {
3247 	"rx_write_requests",
3248 	"rx_read_requests",
3249 	"rx_atomic_requests",
3250 	"out_of_buffer",
3251 	"out_of_sequence",
3252 	"duplicate_request",
3253 	"rnr_nak_retry_err",
3254 	"packet_seq_err",
3255 	"implied_nak_seq_err",
3256 	"local_ack_timeout_err",
3257 };
3258 
3259 static const size_t stats_offsets[] = {
3260 	MLX5_BYTE_OFF(query_q_counter_out, rx_write_requests),
3261 	MLX5_BYTE_OFF(query_q_counter_out, rx_read_requests),
3262 	MLX5_BYTE_OFF(query_q_counter_out, rx_atomic_requests),
3263 	MLX5_BYTE_OFF(query_q_counter_out, out_of_buffer),
3264 	MLX5_BYTE_OFF(query_q_counter_out, out_of_sequence),
3265 	MLX5_BYTE_OFF(query_q_counter_out, duplicate_request),
3266 	MLX5_BYTE_OFF(query_q_counter_out, rnr_nak_retry_err),
3267 	MLX5_BYTE_OFF(query_q_counter_out, packet_seq_err),
3268 	MLX5_BYTE_OFF(query_q_counter_out, implied_nak_seq_err),
3269 	MLX5_BYTE_OFF(query_q_counter_out, local_ack_timeout_err),
3270 };
3271 
3272 static struct rdma_hw_stats *mlx5_ib_alloc_hw_stats(struct ib_device *ibdev,
3273 						    u8 port_num)
3274 {
3275 	BUILD_BUG_ON(ARRAY_SIZE(names) != ARRAY_SIZE(stats_offsets));
3276 
3277 	/* We support only per port stats */
3278 	if (port_num == 0)
3279 		return NULL;
3280 
3281 	return rdma_alloc_hw_stats_struct(names, ARRAY_SIZE(names),
3282 					  RDMA_HW_STATS_DEFAULT_LIFESPAN);
3283 }
3284 
3285 static int mlx5_ib_get_hw_stats(struct ib_device *ibdev,
3286 				struct rdma_hw_stats *stats,
3287 				u8 port, int index)
3288 {
3289 	struct mlx5_ib_dev *dev = to_mdev(ibdev);
3290 	int outlen = MLX5_ST_SZ_BYTES(query_q_counter_out);
3291 	void *out;
3292 	__be32 val;
3293 	int ret;
3294 	int i;
3295 
3296 	if (!port || !stats)
3297 		return -ENOSYS;
3298 
3299 	out = mlx5_vzalloc(outlen);
3300 	if (!out)
3301 		return -ENOMEM;
3302 
3303 	ret = mlx5_vport_query_q_counter(dev->mdev,
3304 					dev->port[port - 1].q_cnt_id, 0,
3305 					out, outlen);
3306 	if (ret)
3307 		goto free;
3308 
3309 	for (i = 0; i < ARRAY_SIZE(names); i++) {
3310 		val = *(__be32 *)(out + stats_offsets[i]);
3311 		stats->value[i] = (u64)be32_to_cpu(val);
3312 	}
3313 free:
3314 	kvfree(out);
3315 	return ARRAY_SIZE(names);
3316 }
3317 
3318 static int mlx5_ib_stage_bfreg_init(struct mlx5_ib_dev *dev)
3319 {
3320 	int err;
3321 
3322 	err = mlx5_alloc_bfreg(dev->mdev, &dev->bfreg, false, false);
3323 	if (err)
3324 		return err;
3325 
3326 	err = mlx5_alloc_bfreg(dev->mdev, &dev->fp_bfreg, false, true);
3327 	if (err) {
3328 		mlx5_free_bfreg(dev->mdev, &dev->bfreg);
3329 		return err;
3330 	}
3331 
3332 	err = mlx5_alloc_bfreg(dev->mdev, &dev->wc_bfreg, true, false);
3333 	if (err) {
3334 		mlx5_free_bfreg(dev->mdev, &dev->fp_bfreg);
3335 		mlx5_free_bfreg(dev->mdev, &dev->bfreg);
3336 	}
3337 
3338 	return err;
3339 }
3340 
3341 static void mlx5_ib_stage_bfreg_cleanup(struct mlx5_ib_dev *dev)
3342 {
3343 	mlx5_free_bfreg(dev->mdev, &dev->wc_bfreg);
3344 	mlx5_free_bfreg(dev->mdev, &dev->fp_bfreg);
3345 	mlx5_free_bfreg(dev->mdev, &dev->bfreg);
3346 }
3347 
3348 static void *mlx5_ib_add(struct mlx5_core_dev *mdev)
3349 {
3350 	struct mlx5_ib_dev *dev;
3351 	enum rdma_link_layer ll;
3352 	int port_type_cap;
3353 	int err;
3354 	int i;
3355 
3356 	port_type_cap = MLX5_CAP_GEN(mdev, port_type);
3357 	ll = mlx5_port_type_cap_to_rdma_ll(port_type_cap);
3358 
3359 	dev = (struct mlx5_ib_dev *)ib_alloc_device(sizeof(*dev));
3360 	if (!dev)
3361 		return NULL;
3362 
3363 	dev->mdev = mdev;
3364 
3365 	dev->port = kcalloc(MLX5_CAP_GEN(mdev, num_ports), sizeof(*dev->port),
3366 			    GFP_KERNEL);
3367 	if (!dev->port)
3368 		goto err_dealloc;
3369 
3370 	rwlock_init(&dev->roce.netdev_lock);
3371 	err = get_port_caps(dev);
3372 	if (err)
3373 		goto err_free_port;
3374 
3375 	if (mlx5_use_mad_ifc(dev))
3376 		get_ext_port_caps(dev);
3377 
3378 	MLX5_INIT_DOORBELL_LOCK(&dev->uar_lock);
3379 
3380 	mutex_init(&dev->lb_mutex);
3381 
3382 	INIT_IB_DEVICE_OPS(&dev->ib_dev.ops, mlx5, MLX5);
3383 	snprintf(dev->ib_dev.name, IB_DEVICE_NAME_MAX, "mlx5_%d", device_get_unit(mdev->pdev->dev.bsddev));
3384 	dev->ib_dev.owner		= THIS_MODULE;
3385 	dev->ib_dev.node_type		= RDMA_NODE_IB_CA;
3386 	dev->ib_dev.local_dma_lkey	= 0 /* not supported for now */;
3387 	dev->num_ports		= MLX5_CAP_GEN(mdev, num_ports);
3388 	dev->ib_dev.phys_port_cnt     = dev->num_ports;
3389 	dev->ib_dev.num_comp_vectors    =
3390 		dev->mdev->priv.eq_table.num_comp_vectors;
3391 	dev->ib_dev.dma_device	= &mdev->pdev->dev;
3392 
3393 	dev->ib_dev.uverbs_abi_ver	= MLX5_IB_UVERBS_ABI_VERSION;
3394 	dev->ib_dev.uverbs_cmd_mask	=
3395 		(1ull << IB_USER_VERBS_CMD_GET_CONTEXT)		|
3396 		(1ull << IB_USER_VERBS_CMD_QUERY_DEVICE)	|
3397 		(1ull << IB_USER_VERBS_CMD_QUERY_PORT)		|
3398 		(1ull << IB_USER_VERBS_CMD_ALLOC_PD)		|
3399 		(1ull << IB_USER_VERBS_CMD_DEALLOC_PD)		|
3400 		(1ull << IB_USER_VERBS_CMD_CREATE_AH)		|
3401 		(1ull << IB_USER_VERBS_CMD_DESTROY_AH)		|
3402 		(1ull << IB_USER_VERBS_CMD_REG_MR)		|
3403 		(1ull << IB_USER_VERBS_CMD_REREG_MR)		|
3404 		(1ull << IB_USER_VERBS_CMD_DEREG_MR)		|
3405 		(1ull << IB_USER_VERBS_CMD_CREATE_COMP_CHANNEL)	|
3406 		(1ull << IB_USER_VERBS_CMD_CREATE_CQ)		|
3407 		(1ull << IB_USER_VERBS_CMD_RESIZE_CQ)		|
3408 		(1ull << IB_USER_VERBS_CMD_DESTROY_CQ)		|
3409 		(1ull << IB_USER_VERBS_CMD_CREATE_QP)		|
3410 		(1ull << IB_USER_VERBS_CMD_MODIFY_QP)		|
3411 		(1ull << IB_USER_VERBS_CMD_QUERY_QP)		|
3412 		(1ull << IB_USER_VERBS_CMD_DESTROY_QP)		|
3413 		(1ull << IB_USER_VERBS_CMD_ATTACH_MCAST)	|
3414 		(1ull << IB_USER_VERBS_CMD_DETACH_MCAST)	|
3415 		(1ull << IB_USER_VERBS_CMD_CREATE_SRQ)		|
3416 		(1ull << IB_USER_VERBS_CMD_MODIFY_SRQ)		|
3417 		(1ull << IB_USER_VERBS_CMD_QUERY_SRQ)		|
3418 		(1ull << IB_USER_VERBS_CMD_DESTROY_SRQ)		|
3419 		(1ull << IB_USER_VERBS_CMD_CREATE_XSRQ)		|
3420 		(1ull << IB_USER_VERBS_CMD_OPEN_QP);
3421 	dev->ib_dev.uverbs_ex_cmd_mask =
3422 		(1ull << IB_USER_VERBS_EX_CMD_QUERY_DEVICE)	|
3423 		(1ull << IB_USER_VERBS_EX_CMD_CREATE_CQ)	|
3424 		(1ull << IB_USER_VERBS_EX_CMD_CREATE_QP);
3425 
3426 	dev->ib_dev.query_device	= mlx5_ib_query_device;
3427 	dev->ib_dev.query_port		= mlx5_ib_query_port;
3428 	dev->ib_dev.get_link_layer	= mlx5_ib_port_link_layer;
3429 	if (ll == IB_LINK_LAYER_ETHERNET)
3430 		dev->ib_dev.get_netdev	= mlx5_ib_get_netdev;
3431 	dev->ib_dev.query_gid		= mlx5_ib_query_gid;
3432 	dev->ib_dev.add_gid		= mlx5_ib_add_gid;
3433 	dev->ib_dev.del_gid		= mlx5_ib_del_gid;
3434 	dev->ib_dev.query_pkey		= mlx5_ib_query_pkey;
3435 	dev->ib_dev.modify_device	= mlx5_ib_modify_device;
3436 	dev->ib_dev.modify_port		= mlx5_ib_modify_port;
3437 	dev->ib_dev.alloc_ucontext	= mlx5_ib_alloc_ucontext;
3438 	dev->ib_dev.dealloc_ucontext	= mlx5_ib_dealloc_ucontext;
3439 	dev->ib_dev.mmap		= mlx5_ib_mmap;
3440 	dev->ib_dev.mmap_free		= mlx5_ib_mmap_free;
3441 	dev->ib_dev.alloc_pd		= mlx5_ib_alloc_pd;
3442 	dev->ib_dev.dealloc_pd		= mlx5_ib_dealloc_pd;
3443 	dev->ib_dev.create_ah		= mlx5_ib_create_ah;
3444 	dev->ib_dev.query_ah		= mlx5_ib_query_ah;
3445 	dev->ib_dev.destroy_ah		= mlx5_ib_destroy_ah;
3446 	dev->ib_dev.create_srq		= mlx5_ib_create_srq;
3447 	dev->ib_dev.modify_srq		= mlx5_ib_modify_srq;
3448 	dev->ib_dev.query_srq		= mlx5_ib_query_srq;
3449 	dev->ib_dev.destroy_srq		= mlx5_ib_destroy_srq;
3450 	dev->ib_dev.post_srq_recv	= mlx5_ib_post_srq_recv;
3451 	dev->ib_dev.create_qp		= mlx5_ib_create_qp;
3452 	dev->ib_dev.modify_qp		= mlx5_ib_modify_qp;
3453 	dev->ib_dev.query_qp		= mlx5_ib_query_qp;
3454 	dev->ib_dev.destroy_qp		= mlx5_ib_destroy_qp;
3455 	dev->ib_dev.post_send		= mlx5_ib_post_send;
3456 	dev->ib_dev.post_recv		= mlx5_ib_post_recv;
3457 	dev->ib_dev.create_cq		= mlx5_ib_create_cq;
3458 	dev->ib_dev.modify_cq		= mlx5_ib_modify_cq;
3459 	dev->ib_dev.resize_cq		= mlx5_ib_resize_cq;
3460 	dev->ib_dev.destroy_cq		= mlx5_ib_destroy_cq;
3461 	dev->ib_dev.poll_cq		= mlx5_ib_poll_cq;
3462 	dev->ib_dev.req_notify_cq	= mlx5_ib_arm_cq;
3463 	dev->ib_dev.get_dma_mr		= mlx5_ib_get_dma_mr;
3464 	dev->ib_dev.reg_user_mr		= mlx5_ib_reg_user_mr;
3465 	dev->ib_dev.rereg_user_mr	= mlx5_ib_rereg_user_mr;
3466 	dev->ib_dev.dereg_mr		= mlx5_ib_dereg_mr;
3467 	dev->ib_dev.attach_mcast	= mlx5_ib_mcg_attach;
3468 	dev->ib_dev.detach_mcast	= mlx5_ib_mcg_detach;
3469 	dev->ib_dev.process_mad		= mlx5_ib_process_mad;
3470 	dev->ib_dev.alloc_mr		= mlx5_ib_alloc_mr;
3471 	dev->ib_dev.map_mr_sg		= mlx5_ib_map_mr_sg;
3472 	dev->ib_dev.check_mr_status	= mlx5_ib_check_mr_status;
3473 	dev->ib_dev.get_port_immutable  = mlx5_port_immutable;
3474 	dev->ib_dev.get_dev_fw_str      = get_dev_fw_str;
3475 	if (mlx5_core_is_pf(mdev)) {
3476 		dev->ib_dev.get_vf_config	= mlx5_ib_get_vf_config;
3477 		dev->ib_dev.set_vf_link_state	= mlx5_ib_set_vf_link_state;
3478 		dev->ib_dev.get_vf_stats	= mlx5_ib_get_vf_stats;
3479 		dev->ib_dev.set_vf_guid		= mlx5_ib_set_vf_guid;
3480 	}
3481 
3482 	dev->ib_dev.disassociate_ucontext = mlx5_ib_disassociate_ucontext;
3483 
3484 	mlx5_ib_internal_fill_odp_caps(dev);
3485 
3486 	if (MLX5_CAP_GEN(mdev, imaicl)) {
3487 		dev->ib_dev.alloc_mw		= mlx5_ib_alloc_mw;
3488 		dev->ib_dev.dealloc_mw		= mlx5_ib_dealloc_mw;
3489 		dev->ib_dev.uverbs_cmd_mask |=
3490 			(1ull << IB_USER_VERBS_CMD_ALLOC_MW)	|
3491 			(1ull << IB_USER_VERBS_CMD_DEALLOC_MW);
3492 	}
3493 
3494 	if (MLX5_CAP_GEN(dev->mdev, out_of_seq_cnt) &&
3495 	    MLX5_CAP_GEN(dev->mdev, retransmission_q_counters)) {
3496 		dev->ib_dev.get_hw_stats	= mlx5_ib_get_hw_stats;
3497 		dev->ib_dev.alloc_hw_stats	= mlx5_ib_alloc_hw_stats;
3498 	}
3499 
3500 	if (MLX5_CAP_GEN(mdev, xrc)) {
3501 		dev->ib_dev.alloc_xrcd = mlx5_ib_alloc_xrcd;
3502 		dev->ib_dev.dealloc_xrcd = mlx5_ib_dealloc_xrcd;
3503 		dev->ib_dev.uverbs_cmd_mask |=
3504 			(1ull << IB_USER_VERBS_CMD_OPEN_XRCD) |
3505 			(1ull << IB_USER_VERBS_CMD_CLOSE_XRCD);
3506 	}
3507 
3508 	if (mlx5_ib_port_link_layer(&dev->ib_dev, 1) ==
3509 	    IB_LINK_LAYER_ETHERNET) {
3510 		dev->ib_dev.create_flow	= mlx5_ib_create_flow;
3511 		dev->ib_dev.destroy_flow = mlx5_ib_destroy_flow;
3512 		dev->ib_dev.create_wq	 = mlx5_ib_create_wq;
3513 		dev->ib_dev.modify_wq	 = mlx5_ib_modify_wq;
3514 		dev->ib_dev.destroy_wq	 = mlx5_ib_destroy_wq;
3515 		dev->ib_dev.create_rwq_ind_table = mlx5_ib_create_rwq_ind_table;
3516 		dev->ib_dev.destroy_rwq_ind_table = mlx5_ib_destroy_rwq_ind_table;
3517 		dev->ib_dev.uverbs_ex_cmd_mask |=
3518 			(1ull << IB_USER_VERBS_EX_CMD_CREATE_FLOW) |
3519 			(1ull << IB_USER_VERBS_EX_CMD_DESTROY_FLOW) |
3520 			(1ull << IB_USER_VERBS_EX_CMD_CREATE_WQ) |
3521 			(1ull << IB_USER_VERBS_EX_CMD_MODIFY_WQ) |
3522 			(1ull << IB_USER_VERBS_EX_CMD_DESTROY_WQ) |
3523 			(1ull << IB_USER_VERBS_EX_CMD_CREATE_RWQ_IND_TBL) |
3524 			(1ull << IB_USER_VERBS_EX_CMD_DESTROY_RWQ_IND_TBL);
3525 	}
3526 	err = init_node_data(dev);
3527 	if (err)
3528 		goto err_free_port;
3529 
3530 	mutex_init(&dev->flow_db.lock);
3531 	mutex_init(&dev->cap_mask_mutex);
3532 	INIT_LIST_HEAD(&dev->qp_list);
3533 	spin_lock_init(&dev->reset_flow_resource_lock);
3534 
3535 	if (ll == IB_LINK_LAYER_ETHERNET) {
3536 		err = mlx5_enable_roce(dev);
3537 		if (err)
3538 			goto err_free_port;
3539 	}
3540 
3541 	err = create_dev_resources(&dev->devr);
3542 	if (err)
3543 		goto err_disable_roce;
3544 
3545 	err = mlx5_ib_odp_init_one(dev);
3546 	if (err)
3547 		goto err_rsrc;
3548 
3549 	err = mlx5_ib_alloc_q_counters(dev);
3550 	if (err)
3551 		goto err_odp;
3552 
3553 	err = mlx5_ib_stage_bfreg_init(dev);
3554 	if (err)
3555 		goto err_q_cnt;
3556 
3557 	err = ib_register_device(&dev->ib_dev, NULL);
3558 	if (err)
3559 		goto err_bfreg;
3560 
3561 	err = create_umr_res(dev);
3562 	if (err)
3563 		goto err_dev;
3564 
3565 	for (i = 0; i < ARRAY_SIZE(mlx5_class_attributes); i++) {
3566 		err = device_create_file(&dev->ib_dev.dev,
3567 					 mlx5_class_attributes[i]);
3568 		if (err)
3569 			goto err_umrc;
3570 	}
3571 
3572 	err = mlx5_ib_init_congestion(dev);
3573 	if (err)
3574 		goto err_umrc;
3575 
3576 	dev->ib_active = true;
3577 
3578 	return dev;
3579 
3580 err_umrc:
3581 	destroy_umrc_res(dev);
3582 
3583 err_dev:
3584 	ib_unregister_device(&dev->ib_dev);
3585 
3586 err_bfreg:
3587 	mlx5_ib_stage_bfreg_cleanup(dev);
3588 
3589 err_q_cnt:
3590 	mlx5_ib_dealloc_q_counters(dev);
3591 
3592 err_odp:
3593 	mlx5_ib_odp_remove_one(dev);
3594 
3595 err_rsrc:
3596 	destroy_dev_resources(&dev->devr);
3597 
3598 err_disable_roce:
3599 	if (ll == IB_LINK_LAYER_ETHERNET) {
3600 		mlx5_disable_roce(dev);
3601 		mlx5_remove_roce_notifier(dev);
3602 	}
3603 
3604 err_free_port:
3605 	kfree(dev->port);
3606 
3607 err_dealloc:
3608 	ib_dealloc_device((struct ib_device *)dev);
3609 
3610 	return NULL;
3611 }
3612 
3613 static void mlx5_ib_remove(struct mlx5_core_dev *mdev, void *context)
3614 {
3615 	struct mlx5_ib_dev *dev = context;
3616 	enum rdma_link_layer ll = mlx5_ib_port_link_layer(&dev->ib_dev, 1);
3617 
3618 	mlx5_ib_cleanup_congestion(dev);
3619 	mlx5_remove_roce_notifier(dev);
3620 	ib_unregister_device(&dev->ib_dev);
3621 	mlx5_ib_stage_bfreg_cleanup(dev);
3622 	mlx5_ib_dealloc_q_counters(dev);
3623 	destroy_umrc_res(dev);
3624 	mlx5_ib_odp_remove_one(dev);
3625 	destroy_dev_resources(&dev->devr);
3626 	if (ll == IB_LINK_LAYER_ETHERNET)
3627 		mlx5_disable_roce(dev);
3628 	kfree(dev->port);
3629 	ib_dealloc_device(&dev->ib_dev);
3630 }
3631 
3632 static struct mlx5_interface mlx5_ib_interface = {
3633 	.add            = mlx5_ib_add,
3634 	.remove         = mlx5_ib_remove,
3635 	.event          = mlx5_ib_event,
3636 	.protocol	= MLX5_INTERFACE_PROTOCOL_IB,
3637 };
3638 
3639 static int __init mlx5_ib_init(void)
3640 {
3641 	int err;
3642 
3643 	err = mlx5_ib_odp_init();
3644 	if (err)
3645 		return err;
3646 
3647 	err = mlx5_register_interface(&mlx5_ib_interface);
3648 	if (err)
3649 		goto clean_odp;
3650 
3651 	return err;
3652 
3653 clean_odp:
3654 	mlx5_ib_odp_cleanup();
3655 	return err;
3656 }
3657 
3658 static void __exit mlx5_ib_cleanup(void)
3659 {
3660 	mlx5_unregister_interface(&mlx5_ib_interface);
3661 	mlx5_ib_odp_cleanup();
3662 }
3663 
3664 module_init_order(mlx5_ib_init, SI_ORDER_SEVENTH);
3665 module_exit_order(mlx5_ib_cleanup, SI_ORDER_SEVENTH);
3666