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