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