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