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