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