Merge tag 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/rdma/rdma
[linux-2.6-block.git] / drivers / infiniband / core / verbs.c
1 /*
2  * Copyright (c) 2004 Mellanox Technologies Ltd.  All rights reserved.
3  * Copyright (c) 2004 Infinicon Corporation.  All rights reserved.
4  * Copyright (c) 2004 Intel Corporation.  All rights reserved.
5  * Copyright (c) 2004 Topspin Corporation.  All rights reserved.
6  * Copyright (c) 2004 Voltaire Corporation.  All rights reserved.
7  * Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
8  * Copyright (c) 2005, 2006 Cisco Systems.  All rights reserved.
9  *
10  * This software is available to you under a choice of one of two
11  * licenses.  You may choose to be licensed under the terms of the GNU
12  * General Public License (GPL) Version 2, available from the file
13  * COPYING in the main directory of this source tree, or the
14  * OpenIB.org BSD license below:
15  *
16  *     Redistribution and use in source and binary forms, with or
17  *     without modification, are permitted provided that the following
18  *     conditions are met:
19  *
20  *      - Redistributions of source code must retain the above
21  *        copyright notice, this list of conditions and the following
22  *        disclaimer.
23  *
24  *      - Redistributions in binary form must reproduce the above
25  *        copyright notice, this list of conditions and the following
26  *        disclaimer in the documentation and/or other materials
27  *        provided with the distribution.
28  *
29  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
30  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
31  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
32  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
33  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
34  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
35  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
36  * SOFTWARE.
37  */
38
39 #include <linux/errno.h>
40 #include <linux/err.h>
41 #include <linux/export.h>
42 #include <linux/string.h>
43 #include <linux/slab.h>
44 #include <linux/in.h>
45 #include <linux/in6.h>
46 #include <net/addrconf.h>
47 #include <linux/security.h>
48
49 #include <rdma/ib_verbs.h>
50 #include <rdma/ib_cache.h>
51 #include <rdma/ib_addr.h>
52 #include <rdma/rw.h>
53
54 #include "core_priv.h"
55
56 static int ib_resolve_eth_dmac(struct ib_device *device,
57                                struct rdma_ah_attr *ah_attr);
58
59 static const char * const ib_events[] = {
60         [IB_EVENT_CQ_ERR]               = "CQ error",
61         [IB_EVENT_QP_FATAL]             = "QP fatal error",
62         [IB_EVENT_QP_REQ_ERR]           = "QP request error",
63         [IB_EVENT_QP_ACCESS_ERR]        = "QP access error",
64         [IB_EVENT_COMM_EST]             = "communication established",
65         [IB_EVENT_SQ_DRAINED]           = "send queue drained",
66         [IB_EVENT_PATH_MIG]             = "path migration successful",
67         [IB_EVENT_PATH_MIG_ERR]         = "path migration error",
68         [IB_EVENT_DEVICE_FATAL]         = "device fatal error",
69         [IB_EVENT_PORT_ACTIVE]          = "port active",
70         [IB_EVENT_PORT_ERR]             = "port error",
71         [IB_EVENT_LID_CHANGE]           = "LID change",
72         [IB_EVENT_PKEY_CHANGE]          = "P_key change",
73         [IB_EVENT_SM_CHANGE]            = "SM change",
74         [IB_EVENT_SRQ_ERR]              = "SRQ error",
75         [IB_EVENT_SRQ_LIMIT_REACHED]    = "SRQ limit reached",
76         [IB_EVENT_QP_LAST_WQE_REACHED]  = "last WQE reached",
77         [IB_EVENT_CLIENT_REREGISTER]    = "client reregister",
78         [IB_EVENT_GID_CHANGE]           = "GID changed",
79 };
80
81 const char *__attribute_const__ ib_event_msg(enum ib_event_type event)
82 {
83         size_t index = event;
84
85         return (index < ARRAY_SIZE(ib_events) && ib_events[index]) ?
86                         ib_events[index] : "unrecognized event";
87 }
88 EXPORT_SYMBOL(ib_event_msg);
89
90 static const char * const wc_statuses[] = {
91         [IB_WC_SUCCESS]                 = "success",
92         [IB_WC_LOC_LEN_ERR]             = "local length error",
93         [IB_WC_LOC_QP_OP_ERR]           = "local QP operation error",
94         [IB_WC_LOC_EEC_OP_ERR]          = "local EE context operation error",
95         [IB_WC_LOC_PROT_ERR]            = "local protection error",
96         [IB_WC_WR_FLUSH_ERR]            = "WR flushed",
97         [IB_WC_MW_BIND_ERR]             = "memory management operation error",
98         [IB_WC_BAD_RESP_ERR]            = "bad response error",
99         [IB_WC_LOC_ACCESS_ERR]          = "local access error",
100         [IB_WC_REM_INV_REQ_ERR]         = "invalid request error",
101         [IB_WC_REM_ACCESS_ERR]          = "remote access error",
102         [IB_WC_REM_OP_ERR]              = "remote operation error",
103         [IB_WC_RETRY_EXC_ERR]           = "transport retry counter exceeded",
104         [IB_WC_RNR_RETRY_EXC_ERR]       = "RNR retry counter exceeded",
105         [IB_WC_LOC_RDD_VIOL_ERR]        = "local RDD violation error",
106         [IB_WC_REM_INV_RD_REQ_ERR]      = "remote invalid RD request",
107         [IB_WC_REM_ABORT_ERR]           = "operation aborted",
108         [IB_WC_INV_EECN_ERR]            = "invalid EE context number",
109         [IB_WC_INV_EEC_STATE_ERR]       = "invalid EE context state",
110         [IB_WC_FATAL_ERR]               = "fatal error",
111         [IB_WC_RESP_TIMEOUT_ERR]        = "response timeout error",
112         [IB_WC_GENERAL_ERR]             = "general error",
113 };
114
115 const char *__attribute_const__ ib_wc_status_msg(enum ib_wc_status status)
116 {
117         size_t index = status;
118
119         return (index < ARRAY_SIZE(wc_statuses) && wc_statuses[index]) ?
120                         wc_statuses[index] : "unrecognized status";
121 }
122 EXPORT_SYMBOL(ib_wc_status_msg);
123
124 __attribute_const__ int ib_rate_to_mult(enum ib_rate rate)
125 {
126         switch (rate) {
127         case IB_RATE_2_5_GBPS: return   1;
128         case IB_RATE_5_GBPS:   return   2;
129         case IB_RATE_10_GBPS:  return   4;
130         case IB_RATE_20_GBPS:  return   8;
131         case IB_RATE_30_GBPS:  return  12;
132         case IB_RATE_40_GBPS:  return  16;
133         case IB_RATE_60_GBPS:  return  24;
134         case IB_RATE_80_GBPS:  return  32;
135         case IB_RATE_120_GBPS: return  48;
136         case IB_RATE_14_GBPS:  return   6;
137         case IB_RATE_56_GBPS:  return  22;
138         case IB_RATE_112_GBPS: return  45;
139         case IB_RATE_168_GBPS: return  67;
140         case IB_RATE_25_GBPS:  return  10;
141         case IB_RATE_100_GBPS: return  40;
142         case IB_RATE_200_GBPS: return  80;
143         case IB_RATE_300_GBPS: return 120;
144         default:               return  -1;
145         }
146 }
147 EXPORT_SYMBOL(ib_rate_to_mult);
148
149 __attribute_const__ enum ib_rate mult_to_ib_rate(int mult)
150 {
151         switch (mult) {
152         case 1:   return IB_RATE_2_5_GBPS;
153         case 2:   return IB_RATE_5_GBPS;
154         case 4:   return IB_RATE_10_GBPS;
155         case 8:   return IB_RATE_20_GBPS;
156         case 12:  return IB_RATE_30_GBPS;
157         case 16:  return IB_RATE_40_GBPS;
158         case 24:  return IB_RATE_60_GBPS;
159         case 32:  return IB_RATE_80_GBPS;
160         case 48:  return IB_RATE_120_GBPS;
161         case 6:   return IB_RATE_14_GBPS;
162         case 22:  return IB_RATE_56_GBPS;
163         case 45:  return IB_RATE_112_GBPS;
164         case 67:  return IB_RATE_168_GBPS;
165         case 10:  return IB_RATE_25_GBPS;
166         case 40:  return IB_RATE_100_GBPS;
167         case 80:  return IB_RATE_200_GBPS;
168         case 120: return IB_RATE_300_GBPS;
169         default:  return IB_RATE_PORT_CURRENT;
170         }
171 }
172 EXPORT_SYMBOL(mult_to_ib_rate);
173
174 __attribute_const__ int ib_rate_to_mbps(enum ib_rate rate)
175 {
176         switch (rate) {
177         case IB_RATE_2_5_GBPS: return 2500;
178         case IB_RATE_5_GBPS:   return 5000;
179         case IB_RATE_10_GBPS:  return 10000;
180         case IB_RATE_20_GBPS:  return 20000;
181         case IB_RATE_30_GBPS:  return 30000;
182         case IB_RATE_40_GBPS:  return 40000;
183         case IB_RATE_60_GBPS:  return 60000;
184         case IB_RATE_80_GBPS:  return 80000;
185         case IB_RATE_120_GBPS: return 120000;
186         case IB_RATE_14_GBPS:  return 14062;
187         case IB_RATE_56_GBPS:  return 56250;
188         case IB_RATE_112_GBPS: return 112500;
189         case IB_RATE_168_GBPS: return 168750;
190         case IB_RATE_25_GBPS:  return 25781;
191         case IB_RATE_100_GBPS: return 103125;
192         case IB_RATE_200_GBPS: return 206250;
193         case IB_RATE_300_GBPS: return 309375;
194         default:               return -1;
195         }
196 }
197 EXPORT_SYMBOL(ib_rate_to_mbps);
198
199 __attribute_const__ enum rdma_transport_type
200 rdma_node_get_transport(enum rdma_node_type node_type)
201 {
202
203         if (node_type == RDMA_NODE_USNIC)
204                 return RDMA_TRANSPORT_USNIC;
205         if (node_type == RDMA_NODE_USNIC_UDP)
206                 return RDMA_TRANSPORT_USNIC_UDP;
207         if (node_type == RDMA_NODE_RNIC)
208                 return RDMA_TRANSPORT_IWARP;
209
210         return RDMA_TRANSPORT_IB;
211 }
212 EXPORT_SYMBOL(rdma_node_get_transport);
213
214 enum rdma_link_layer rdma_port_get_link_layer(struct ib_device *device, u8 port_num)
215 {
216         enum rdma_transport_type lt;
217         if (device->get_link_layer)
218                 return device->get_link_layer(device, port_num);
219
220         lt = rdma_node_get_transport(device->node_type);
221         if (lt == RDMA_TRANSPORT_IB)
222                 return IB_LINK_LAYER_INFINIBAND;
223
224         return IB_LINK_LAYER_ETHERNET;
225 }
226 EXPORT_SYMBOL(rdma_port_get_link_layer);
227
228 /* Protection domains */
229
230 /**
231  * ib_alloc_pd - Allocates an unused protection domain.
232  * @device: The device on which to allocate the protection domain.
233  *
234  * A protection domain object provides an association between QPs, shared
235  * receive queues, address handles, memory regions, and memory windows.
236  *
237  * Every PD has a local_dma_lkey which can be used as the lkey value for local
238  * memory operations.
239  */
240 struct ib_pd *__ib_alloc_pd(struct ib_device *device, unsigned int flags,
241                 const char *caller)
242 {
243         struct ib_pd *pd;
244         int mr_access_flags = 0;
245
246         pd = device->alloc_pd(device, NULL, NULL);
247         if (IS_ERR(pd))
248                 return pd;
249
250         pd->device = device;
251         pd->uobject = NULL;
252         pd->__internal_mr = NULL;
253         atomic_set(&pd->usecnt, 0);
254         pd->flags = flags;
255
256         if (device->attrs.device_cap_flags & IB_DEVICE_LOCAL_DMA_LKEY)
257                 pd->local_dma_lkey = device->local_dma_lkey;
258         else
259                 mr_access_flags |= IB_ACCESS_LOCAL_WRITE;
260
261         if (flags & IB_PD_UNSAFE_GLOBAL_RKEY) {
262                 pr_warn("%s: enabling unsafe global rkey\n", caller);
263                 mr_access_flags |= IB_ACCESS_REMOTE_READ | IB_ACCESS_REMOTE_WRITE;
264         }
265
266         pd->res.type = RDMA_RESTRACK_PD;
267         rdma_restrack_set_task(&pd->res, caller);
268         rdma_restrack_add(&pd->res);
269
270         if (mr_access_flags) {
271                 struct ib_mr *mr;
272
273                 mr = pd->device->get_dma_mr(pd, mr_access_flags);
274                 if (IS_ERR(mr)) {
275                         ib_dealloc_pd(pd);
276                         return ERR_CAST(mr);
277                 }
278
279                 mr->device      = pd->device;
280                 mr->pd          = pd;
281                 mr->uobject     = NULL;
282                 mr->need_inval  = false;
283
284                 pd->__internal_mr = mr;
285
286                 if (!(device->attrs.device_cap_flags & IB_DEVICE_LOCAL_DMA_LKEY))
287                         pd->local_dma_lkey = pd->__internal_mr->lkey;
288
289                 if (flags & IB_PD_UNSAFE_GLOBAL_RKEY)
290                         pd->unsafe_global_rkey = pd->__internal_mr->rkey;
291         }
292
293         return pd;
294 }
295 EXPORT_SYMBOL(__ib_alloc_pd);
296
297 /**
298  * ib_dealloc_pd - Deallocates a protection domain.
299  * @pd: The protection domain to deallocate.
300  *
301  * It is an error to call this function while any resources in the pd still
302  * exist.  The caller is responsible to synchronously destroy them and
303  * guarantee no new allocations will happen.
304  */
305 void ib_dealloc_pd(struct ib_pd *pd)
306 {
307         int ret;
308
309         if (pd->__internal_mr) {
310                 ret = pd->device->dereg_mr(pd->__internal_mr);
311                 WARN_ON(ret);
312                 pd->__internal_mr = NULL;
313         }
314
315         /* uverbs manipulates usecnt with proper locking, while the kabi
316            requires the caller to guarantee we can't race here. */
317         WARN_ON(atomic_read(&pd->usecnt));
318
319         rdma_restrack_del(&pd->res);
320         /* Making delalloc_pd a void return is a WIP, no driver should return
321            an error here. */
322         ret = pd->device->dealloc_pd(pd);
323         WARN_ONCE(ret, "Infiniband HW driver failed dealloc_pd");
324 }
325 EXPORT_SYMBOL(ib_dealloc_pd);
326
327 /* Address handles */
328
329 /**
330  * rdma_copy_ah_attr - Copy rdma ah attribute from source to destination.
331  * @dest:       Pointer to destination ah_attr. Contents of the destination
332  *              pointer is assumed to be invalid and attribute are overwritten.
333  * @src:        Pointer to source ah_attr.
334  */
335 void rdma_copy_ah_attr(struct rdma_ah_attr *dest,
336                        const struct rdma_ah_attr *src)
337 {
338         *dest = *src;
339         if (dest->grh.sgid_attr)
340                 rdma_hold_gid_attr(dest->grh.sgid_attr);
341 }
342 EXPORT_SYMBOL(rdma_copy_ah_attr);
343
344 /**
345  * rdma_replace_ah_attr - Replace valid ah_attr with new new one.
346  * @old:        Pointer to existing ah_attr which needs to be replaced.
347  *              old is assumed to be valid or zero'd
348  * @new:        Pointer to the new ah_attr.
349  *
350  * rdma_replace_ah_attr() first releases any reference in the old ah_attr if
351  * old the ah_attr is valid; after that it copies the new attribute and holds
352  * the reference to the replaced ah_attr.
353  */
354 void rdma_replace_ah_attr(struct rdma_ah_attr *old,
355                           const struct rdma_ah_attr *new)
356 {
357         rdma_destroy_ah_attr(old);
358         *old = *new;
359         if (old->grh.sgid_attr)
360                 rdma_hold_gid_attr(old->grh.sgid_attr);
361 }
362 EXPORT_SYMBOL(rdma_replace_ah_attr);
363
364 /**
365  * rdma_move_ah_attr - Move ah_attr pointed by source to destination.
366  * @dest:       Pointer to destination ah_attr to copy to.
367  *              dest is assumed to be valid or zero'd
368  * @src:        Pointer to the new ah_attr.
369  *
370  * rdma_move_ah_attr() first releases any reference in the destination ah_attr
371  * if it is valid. This also transfers ownership of internal references from
372  * src to dest, making src invalid in the process. No new reference of the src
373  * ah_attr is taken.
374  */
375 void rdma_move_ah_attr(struct rdma_ah_attr *dest, struct rdma_ah_attr *src)
376 {
377         rdma_destroy_ah_attr(dest);
378         *dest = *src;
379         src->grh.sgid_attr = NULL;
380 }
381 EXPORT_SYMBOL(rdma_move_ah_attr);
382
383 /*
384  * Validate that the rdma_ah_attr is valid for the device before passing it
385  * off to the driver.
386  */
387 static int rdma_check_ah_attr(struct ib_device *device,
388                               struct rdma_ah_attr *ah_attr)
389 {
390         if (!rdma_is_port_valid(device, ah_attr->port_num))
391                 return -EINVAL;
392
393         if ((rdma_is_grh_required(device, ah_attr->port_num) ||
394              ah_attr->type == RDMA_AH_ATTR_TYPE_ROCE) &&
395             !(ah_attr->ah_flags & IB_AH_GRH))
396                 return -EINVAL;
397
398         if (ah_attr->grh.sgid_attr) {
399                 /*
400                  * Make sure the passed sgid_attr is consistent with the
401                  * parameters
402                  */
403                 if (ah_attr->grh.sgid_attr->index != ah_attr->grh.sgid_index ||
404                     ah_attr->grh.sgid_attr->port_num != ah_attr->port_num)
405                         return -EINVAL;
406         }
407         return 0;
408 }
409
410 /*
411  * If the ah requires a GRH then ensure that sgid_attr pointer is filled in.
412  * On success the caller is responsible to call rdma_unfill_sgid_attr().
413  */
414 static int rdma_fill_sgid_attr(struct ib_device *device,
415                                struct rdma_ah_attr *ah_attr,
416                                const struct ib_gid_attr **old_sgid_attr)
417 {
418         const struct ib_gid_attr *sgid_attr;
419         struct ib_global_route *grh;
420         int ret;
421
422         *old_sgid_attr = ah_attr->grh.sgid_attr;
423
424         ret = rdma_check_ah_attr(device, ah_attr);
425         if (ret)
426                 return ret;
427
428         if (!(ah_attr->ah_flags & IB_AH_GRH))
429                 return 0;
430
431         grh = rdma_ah_retrieve_grh(ah_attr);
432         if (grh->sgid_attr)
433                 return 0;
434
435         sgid_attr =
436                 rdma_get_gid_attr(device, ah_attr->port_num, grh->sgid_index);
437         if (IS_ERR(sgid_attr))
438                 return PTR_ERR(sgid_attr);
439
440         /* Move ownerhip of the kref into the ah_attr */
441         grh->sgid_attr = sgid_attr;
442         return 0;
443 }
444
445 static void rdma_unfill_sgid_attr(struct rdma_ah_attr *ah_attr,
446                                   const struct ib_gid_attr *old_sgid_attr)
447 {
448         /*
449          * Fill didn't change anything, the caller retains ownership of
450          * whatever it passed
451          */
452         if (ah_attr->grh.sgid_attr == old_sgid_attr)
453                 return;
454
455         /*
456          * Otherwise, we need to undo what rdma_fill_sgid_attr so the caller
457          * doesn't see any change in the rdma_ah_attr. If we get here
458          * old_sgid_attr is NULL.
459          */
460         rdma_destroy_ah_attr(ah_attr);
461 }
462
463 static const struct ib_gid_attr *
464 rdma_update_sgid_attr(struct rdma_ah_attr *ah_attr,
465                       const struct ib_gid_attr *old_attr)
466 {
467         if (old_attr)
468                 rdma_put_gid_attr(old_attr);
469         if (ah_attr->ah_flags & IB_AH_GRH) {
470                 rdma_hold_gid_attr(ah_attr->grh.sgid_attr);
471                 return ah_attr->grh.sgid_attr;
472         }
473         return NULL;
474 }
475
476 static struct ib_ah *_rdma_create_ah(struct ib_pd *pd,
477                                      struct rdma_ah_attr *ah_attr,
478                                      struct ib_udata *udata)
479 {
480         struct ib_ah *ah;
481
482         if (!pd->device->create_ah)
483                 return ERR_PTR(-EOPNOTSUPP);
484
485         ah = pd->device->create_ah(pd, ah_attr, udata);
486
487         if (!IS_ERR(ah)) {
488                 ah->device  = pd->device;
489                 ah->pd      = pd;
490                 ah->uobject = NULL;
491                 ah->type    = ah_attr->type;
492                 ah->sgid_attr = rdma_update_sgid_attr(ah_attr, NULL);
493
494                 atomic_inc(&pd->usecnt);
495         }
496
497         return ah;
498 }
499
500 /**
501  * rdma_create_ah - Creates an address handle for the
502  * given address vector.
503  * @pd: The protection domain associated with the address handle.
504  * @ah_attr: The attributes of the address vector.
505  *
506  * It returns 0 on success and returns appropriate error code on error.
507  * The address handle is used to reference a local or global destination
508  * in all UD QP post sends.
509  */
510 struct ib_ah *rdma_create_ah(struct ib_pd *pd, struct rdma_ah_attr *ah_attr)
511 {
512         const struct ib_gid_attr *old_sgid_attr;
513         struct ib_ah *ah;
514         int ret;
515
516         ret = rdma_fill_sgid_attr(pd->device, ah_attr, &old_sgid_attr);
517         if (ret)
518                 return ERR_PTR(ret);
519
520         ah = _rdma_create_ah(pd, ah_attr, NULL);
521
522         rdma_unfill_sgid_attr(ah_attr, old_sgid_attr);
523         return ah;
524 }
525 EXPORT_SYMBOL(rdma_create_ah);
526
527 /**
528  * rdma_create_user_ah - Creates an address handle for the
529  * given address vector.
530  * It resolves destination mac address for ah attribute of RoCE type.
531  * @pd: The protection domain associated with the address handle.
532  * @ah_attr: The attributes of the address vector.
533  * @udata: pointer to user's input output buffer information need by
534  *         provider driver.
535  *
536  * It returns 0 on success and returns appropriate error code on error.
537  * The address handle is used to reference a local or global destination
538  * in all UD QP post sends.
539  */
540 struct ib_ah *rdma_create_user_ah(struct ib_pd *pd,
541                                   struct rdma_ah_attr *ah_attr,
542                                   struct ib_udata *udata)
543 {
544         const struct ib_gid_attr *old_sgid_attr;
545         struct ib_ah *ah;
546         int err;
547
548         err = rdma_fill_sgid_attr(pd->device, ah_attr, &old_sgid_attr);
549         if (err)
550                 return ERR_PTR(err);
551
552         if (ah_attr->type == RDMA_AH_ATTR_TYPE_ROCE) {
553                 err = ib_resolve_eth_dmac(pd->device, ah_attr);
554                 if (err) {
555                         ah = ERR_PTR(err);
556                         goto out;
557                 }
558         }
559
560         ah = _rdma_create_ah(pd, ah_attr, udata);
561
562 out:
563         rdma_unfill_sgid_attr(ah_attr, old_sgid_attr);
564         return ah;
565 }
566 EXPORT_SYMBOL(rdma_create_user_ah);
567
568 int ib_get_rdma_header_version(const union rdma_network_hdr *hdr)
569 {
570         const struct iphdr *ip4h = (struct iphdr *)&hdr->roce4grh;
571         struct iphdr ip4h_checked;
572         const struct ipv6hdr *ip6h = (struct ipv6hdr *)&hdr->ibgrh;
573
574         /* If it's IPv6, the version must be 6, otherwise, the first
575          * 20 bytes (before the IPv4 header) are garbled.
576          */
577         if (ip6h->version != 6)
578                 return (ip4h->version == 4) ? 4 : 0;
579         /* version may be 6 or 4 because the first 20 bytes could be garbled */
580
581         /* RoCE v2 requires no options, thus header length
582          * must be 5 words
583          */
584         if (ip4h->ihl != 5)
585                 return 6;
586
587         /* Verify checksum.
588          * We can't write on scattered buffers so we need to copy to
589          * temp buffer.
590          */
591         memcpy(&ip4h_checked, ip4h, sizeof(ip4h_checked));
592         ip4h_checked.check = 0;
593         ip4h_checked.check = ip_fast_csum((u8 *)&ip4h_checked, 5);
594         /* if IPv4 header checksum is OK, believe it */
595         if (ip4h->check == ip4h_checked.check)
596                 return 4;
597         return 6;
598 }
599 EXPORT_SYMBOL(ib_get_rdma_header_version);
600
601 static enum rdma_network_type ib_get_net_type_by_grh(struct ib_device *device,
602                                                      u8 port_num,
603                                                      const struct ib_grh *grh)
604 {
605         int grh_version;
606
607         if (rdma_protocol_ib(device, port_num))
608                 return RDMA_NETWORK_IB;
609
610         grh_version = ib_get_rdma_header_version((union rdma_network_hdr *)grh);
611
612         if (grh_version == 4)
613                 return RDMA_NETWORK_IPV4;
614
615         if (grh->next_hdr == IPPROTO_UDP)
616                 return RDMA_NETWORK_IPV6;
617
618         return RDMA_NETWORK_ROCE_V1;
619 }
620
621 struct find_gid_index_context {
622         u16 vlan_id;
623         enum ib_gid_type gid_type;
624 };
625
626 static bool find_gid_index(const union ib_gid *gid,
627                            const struct ib_gid_attr *gid_attr,
628                            void *context)
629 {
630         struct find_gid_index_context *ctx = context;
631
632         if (ctx->gid_type != gid_attr->gid_type)
633                 return false;
634
635         if ((!!(ctx->vlan_id != 0xffff) == !is_vlan_dev(gid_attr->ndev)) ||
636             (is_vlan_dev(gid_attr->ndev) &&
637              vlan_dev_vlan_id(gid_attr->ndev) != ctx->vlan_id))
638                 return false;
639
640         return true;
641 }
642
643 static const struct ib_gid_attr *
644 get_sgid_attr_from_eth(struct ib_device *device, u8 port_num,
645                        u16 vlan_id, const union ib_gid *sgid,
646                        enum ib_gid_type gid_type)
647 {
648         struct find_gid_index_context context = {.vlan_id = vlan_id,
649                                                  .gid_type = gid_type};
650
651         return rdma_find_gid_by_filter(device, sgid, port_num, find_gid_index,
652                                        &context);
653 }
654
655 int ib_get_gids_from_rdma_hdr(const union rdma_network_hdr *hdr,
656                               enum rdma_network_type net_type,
657                               union ib_gid *sgid, union ib_gid *dgid)
658 {
659         struct sockaddr_in  src_in;
660         struct sockaddr_in  dst_in;
661         __be32 src_saddr, dst_saddr;
662
663         if (!sgid || !dgid)
664                 return -EINVAL;
665
666         if (net_type == RDMA_NETWORK_IPV4) {
667                 memcpy(&src_in.sin_addr.s_addr,
668                        &hdr->roce4grh.saddr, 4);
669                 memcpy(&dst_in.sin_addr.s_addr,
670                        &hdr->roce4grh.daddr, 4);
671                 src_saddr = src_in.sin_addr.s_addr;
672                 dst_saddr = dst_in.sin_addr.s_addr;
673                 ipv6_addr_set_v4mapped(src_saddr,
674                                        (struct in6_addr *)sgid);
675                 ipv6_addr_set_v4mapped(dst_saddr,
676                                        (struct in6_addr *)dgid);
677                 return 0;
678         } else if (net_type == RDMA_NETWORK_IPV6 ||
679                    net_type == RDMA_NETWORK_IB) {
680                 *dgid = hdr->ibgrh.dgid;
681                 *sgid = hdr->ibgrh.sgid;
682                 return 0;
683         } else {
684                 return -EINVAL;
685         }
686 }
687 EXPORT_SYMBOL(ib_get_gids_from_rdma_hdr);
688
689 /* Resolve destination mac address and hop limit for unicast destination
690  * GID entry, considering the source GID entry as well.
691  * ah_attribute must have have valid port_num, sgid_index.
692  */
693 static int ib_resolve_unicast_gid_dmac(struct ib_device *device,
694                                        struct rdma_ah_attr *ah_attr)
695 {
696         struct ib_global_route *grh = rdma_ah_retrieve_grh(ah_attr);
697         const struct ib_gid_attr *sgid_attr = grh->sgid_attr;
698         int hop_limit = 0xff;
699         int ret = 0;
700
701         /* If destination is link local and source GID is RoCEv1,
702          * IP stack is not used.
703          */
704         if (rdma_link_local_addr((struct in6_addr *)grh->dgid.raw) &&
705             sgid_attr->gid_type == IB_GID_TYPE_ROCE) {
706                 rdma_get_ll_mac((struct in6_addr *)grh->dgid.raw,
707                                 ah_attr->roce.dmac);
708                 return ret;
709         }
710
711         ret = rdma_addr_find_l2_eth_by_grh(&sgid_attr->gid, &grh->dgid,
712                                            ah_attr->roce.dmac,
713                                            sgid_attr, &hop_limit);
714
715         grh->hop_limit = hop_limit;
716         return ret;
717 }
718
719 /*
720  * This function initializes address handle attributes from the incoming packet.
721  * Incoming packet has dgid of the receiver node on which this code is
722  * getting executed and, sgid contains the GID of the sender.
723  *
724  * When resolving mac address of destination, the arrived dgid is used
725  * as sgid and, sgid is used as dgid because sgid contains destinations
726  * GID whom to respond to.
727  *
728  * On success the caller is responsible to call rdma_destroy_ah_attr on the
729  * attr.
730  */
731 int ib_init_ah_attr_from_wc(struct ib_device *device, u8 port_num,
732                             const struct ib_wc *wc, const struct ib_grh *grh,
733                             struct rdma_ah_attr *ah_attr)
734 {
735         u32 flow_class;
736         int ret;
737         enum rdma_network_type net_type = RDMA_NETWORK_IB;
738         enum ib_gid_type gid_type = IB_GID_TYPE_IB;
739         const struct ib_gid_attr *sgid_attr;
740         int hoplimit = 0xff;
741         union ib_gid dgid;
742         union ib_gid sgid;
743
744         might_sleep();
745
746         memset(ah_attr, 0, sizeof *ah_attr);
747         ah_attr->type = rdma_ah_find_type(device, port_num);
748         if (rdma_cap_eth_ah(device, port_num)) {
749                 if (wc->wc_flags & IB_WC_WITH_NETWORK_HDR_TYPE)
750                         net_type = wc->network_hdr_type;
751                 else
752                         net_type = ib_get_net_type_by_grh(device, port_num, grh);
753                 gid_type = ib_network_to_gid_type(net_type);
754         }
755         ret = ib_get_gids_from_rdma_hdr((union rdma_network_hdr *)grh, net_type,
756                                         &sgid, &dgid);
757         if (ret)
758                 return ret;
759
760         rdma_ah_set_sl(ah_attr, wc->sl);
761         rdma_ah_set_port_num(ah_attr, port_num);
762
763         if (rdma_protocol_roce(device, port_num)) {
764                 u16 vlan_id = wc->wc_flags & IB_WC_WITH_VLAN ?
765                                 wc->vlan_id : 0xffff;
766
767                 if (!(wc->wc_flags & IB_WC_GRH))
768                         return -EPROTOTYPE;
769
770                 sgid_attr = get_sgid_attr_from_eth(device, port_num,
771                                                    vlan_id, &dgid,
772                                                    gid_type);
773                 if (IS_ERR(sgid_attr))
774                         return PTR_ERR(sgid_attr);
775
776                 flow_class = be32_to_cpu(grh->version_tclass_flow);
777                 rdma_move_grh_sgid_attr(ah_attr,
778                                         &sgid,
779                                         flow_class & 0xFFFFF,
780                                         hoplimit,
781                                         (flow_class >> 20) & 0xFF,
782                                         sgid_attr);
783
784                 ret = ib_resolve_unicast_gid_dmac(device, ah_attr);
785                 if (ret)
786                         rdma_destroy_ah_attr(ah_attr);
787
788                 return ret;
789         } else {
790                 rdma_ah_set_dlid(ah_attr, wc->slid);
791                 rdma_ah_set_path_bits(ah_attr, wc->dlid_path_bits);
792
793                 if ((wc->wc_flags & IB_WC_GRH) == 0)
794                         return 0;
795
796                 if (dgid.global.interface_id !=
797                                         cpu_to_be64(IB_SA_WELL_KNOWN_GUID)) {
798                         sgid_attr = rdma_find_gid_by_port(
799                                 device, &dgid, IB_GID_TYPE_IB, port_num, NULL);
800                 } else
801                         sgid_attr = rdma_get_gid_attr(device, port_num, 0);
802
803                 if (IS_ERR(sgid_attr))
804                         return PTR_ERR(sgid_attr);
805                 flow_class = be32_to_cpu(grh->version_tclass_flow);
806                 rdma_move_grh_sgid_attr(ah_attr,
807                                         &sgid,
808                                         flow_class & 0xFFFFF,
809                                         hoplimit,
810                                         (flow_class >> 20) & 0xFF,
811                                         sgid_attr);
812
813                 return 0;
814         }
815 }
816 EXPORT_SYMBOL(ib_init_ah_attr_from_wc);
817
818 /**
819  * rdma_move_grh_sgid_attr - Sets the sgid attribute of GRH, taking ownership
820  * of the reference
821  *
822  * @attr:       Pointer to AH attribute structure
823  * @dgid:       Destination GID
824  * @flow_label: Flow label
825  * @hop_limit:  Hop limit
826  * @traffic_class: traffic class
827  * @sgid_attr:  Pointer to SGID attribute
828  *
829  * This takes ownership of the sgid_attr reference. The caller must ensure
830  * rdma_destroy_ah_attr() is called before destroying the rdma_ah_attr after
831  * calling this function.
832  */
833 void rdma_move_grh_sgid_attr(struct rdma_ah_attr *attr, union ib_gid *dgid,
834                              u32 flow_label, u8 hop_limit, u8 traffic_class,
835                              const struct ib_gid_attr *sgid_attr)
836 {
837         rdma_ah_set_grh(attr, dgid, flow_label, sgid_attr->index, hop_limit,
838                         traffic_class);
839         attr->grh.sgid_attr = sgid_attr;
840 }
841 EXPORT_SYMBOL(rdma_move_grh_sgid_attr);
842
843 /**
844  * rdma_destroy_ah_attr - Release reference to SGID attribute of
845  * ah attribute.
846  * @ah_attr: Pointer to ah attribute
847  *
848  * Release reference to the SGID attribute of the ah attribute if it is
849  * non NULL. It is safe to call this multiple times, and safe to call it on
850  * a zero initialized ah_attr.
851  */
852 void rdma_destroy_ah_attr(struct rdma_ah_attr *ah_attr)
853 {
854         if (ah_attr->grh.sgid_attr) {
855                 rdma_put_gid_attr(ah_attr->grh.sgid_attr);
856                 ah_attr->grh.sgid_attr = NULL;
857         }
858 }
859 EXPORT_SYMBOL(rdma_destroy_ah_attr);
860
861 struct ib_ah *ib_create_ah_from_wc(struct ib_pd *pd, const struct ib_wc *wc,
862                                    const struct ib_grh *grh, u8 port_num)
863 {
864         struct rdma_ah_attr ah_attr;
865         struct ib_ah *ah;
866         int ret;
867
868         ret = ib_init_ah_attr_from_wc(pd->device, port_num, wc, grh, &ah_attr);
869         if (ret)
870                 return ERR_PTR(ret);
871
872         ah = rdma_create_ah(pd, &ah_attr);
873
874         rdma_destroy_ah_attr(&ah_attr);
875         return ah;
876 }
877 EXPORT_SYMBOL(ib_create_ah_from_wc);
878
879 int rdma_modify_ah(struct ib_ah *ah, struct rdma_ah_attr *ah_attr)
880 {
881         const struct ib_gid_attr *old_sgid_attr;
882         int ret;
883
884         if (ah->type != ah_attr->type)
885                 return -EINVAL;
886
887         ret = rdma_fill_sgid_attr(ah->device, ah_attr, &old_sgid_attr);
888         if (ret)
889                 return ret;
890
891         ret = ah->device->modify_ah ?
892                 ah->device->modify_ah(ah, ah_attr) :
893                 -EOPNOTSUPP;
894
895         ah->sgid_attr = rdma_update_sgid_attr(ah_attr, ah->sgid_attr);
896         rdma_unfill_sgid_attr(ah_attr, old_sgid_attr);
897         return ret;
898 }
899 EXPORT_SYMBOL(rdma_modify_ah);
900
901 int rdma_query_ah(struct ib_ah *ah, struct rdma_ah_attr *ah_attr)
902 {
903         ah_attr->grh.sgid_attr = NULL;
904
905         return ah->device->query_ah ?
906                 ah->device->query_ah(ah, ah_attr) :
907                 -EOPNOTSUPP;
908 }
909 EXPORT_SYMBOL(rdma_query_ah);
910
911 int rdma_destroy_ah(struct ib_ah *ah)
912 {
913         const struct ib_gid_attr *sgid_attr = ah->sgid_attr;
914         struct ib_pd *pd;
915         int ret;
916
917         pd = ah->pd;
918         ret = ah->device->destroy_ah(ah);
919         if (!ret) {
920                 atomic_dec(&pd->usecnt);
921                 if (sgid_attr)
922                         rdma_put_gid_attr(sgid_attr);
923         }
924
925         return ret;
926 }
927 EXPORT_SYMBOL(rdma_destroy_ah);
928
929 /* Shared receive queues */
930
931 struct ib_srq *ib_create_srq(struct ib_pd *pd,
932                              struct ib_srq_init_attr *srq_init_attr)
933 {
934         struct ib_srq *srq;
935
936         if (!pd->device->create_srq)
937                 return ERR_PTR(-EOPNOTSUPP);
938
939         srq = pd->device->create_srq(pd, srq_init_attr, NULL);
940
941         if (!IS_ERR(srq)) {
942                 srq->device        = pd->device;
943                 srq->pd            = pd;
944                 srq->uobject       = NULL;
945                 srq->event_handler = srq_init_attr->event_handler;
946                 srq->srq_context   = srq_init_attr->srq_context;
947                 srq->srq_type      = srq_init_attr->srq_type;
948                 if (ib_srq_has_cq(srq->srq_type)) {
949                         srq->ext.cq   = srq_init_attr->ext.cq;
950                         atomic_inc(&srq->ext.cq->usecnt);
951                 }
952                 if (srq->srq_type == IB_SRQT_XRC) {
953                         srq->ext.xrc.xrcd = srq_init_attr->ext.xrc.xrcd;
954                         atomic_inc(&srq->ext.xrc.xrcd->usecnt);
955                 }
956                 atomic_inc(&pd->usecnt);
957                 atomic_set(&srq->usecnt, 0);
958         }
959
960         return srq;
961 }
962 EXPORT_SYMBOL(ib_create_srq);
963
964 int ib_modify_srq(struct ib_srq *srq,
965                   struct ib_srq_attr *srq_attr,
966                   enum ib_srq_attr_mask srq_attr_mask)
967 {
968         return srq->device->modify_srq ?
969                 srq->device->modify_srq(srq, srq_attr, srq_attr_mask, NULL) :
970                 -EOPNOTSUPP;
971 }
972 EXPORT_SYMBOL(ib_modify_srq);
973
974 int ib_query_srq(struct ib_srq *srq,
975                  struct ib_srq_attr *srq_attr)
976 {
977         return srq->device->query_srq ?
978                 srq->device->query_srq(srq, srq_attr) : -EOPNOTSUPP;
979 }
980 EXPORT_SYMBOL(ib_query_srq);
981
982 int ib_destroy_srq(struct ib_srq *srq)
983 {
984         struct ib_pd *pd;
985         enum ib_srq_type srq_type;
986         struct ib_xrcd *uninitialized_var(xrcd);
987         struct ib_cq *uninitialized_var(cq);
988         int ret;
989
990         if (atomic_read(&srq->usecnt))
991                 return -EBUSY;
992
993         pd = srq->pd;
994         srq_type = srq->srq_type;
995         if (ib_srq_has_cq(srq_type))
996                 cq = srq->ext.cq;
997         if (srq_type == IB_SRQT_XRC)
998                 xrcd = srq->ext.xrc.xrcd;
999
1000         ret = srq->device->destroy_srq(srq);
1001         if (!ret) {
1002                 atomic_dec(&pd->usecnt);
1003                 if (srq_type == IB_SRQT_XRC)
1004                         atomic_dec(&xrcd->usecnt);
1005                 if (ib_srq_has_cq(srq_type))
1006                         atomic_dec(&cq->usecnt);
1007         }
1008
1009         return ret;
1010 }
1011 EXPORT_SYMBOL(ib_destroy_srq);
1012
1013 /* Queue pairs */
1014
1015 static void __ib_shared_qp_event_handler(struct ib_event *event, void *context)
1016 {
1017         struct ib_qp *qp = context;
1018         unsigned long flags;
1019
1020         spin_lock_irqsave(&qp->device->event_handler_lock, flags);
1021         list_for_each_entry(event->element.qp, &qp->open_list, open_list)
1022                 if (event->element.qp->event_handler)
1023                         event->element.qp->event_handler(event, event->element.qp->qp_context);
1024         spin_unlock_irqrestore(&qp->device->event_handler_lock, flags);
1025 }
1026
1027 static void __ib_insert_xrcd_qp(struct ib_xrcd *xrcd, struct ib_qp *qp)
1028 {
1029         mutex_lock(&xrcd->tgt_qp_mutex);
1030         list_add(&qp->xrcd_list, &xrcd->tgt_qp_list);
1031         mutex_unlock(&xrcd->tgt_qp_mutex);
1032 }
1033
1034 static struct ib_qp *__ib_open_qp(struct ib_qp *real_qp,
1035                                   void (*event_handler)(struct ib_event *, void *),
1036                                   void *qp_context)
1037 {
1038         struct ib_qp *qp;
1039         unsigned long flags;
1040         int err;
1041
1042         qp = kzalloc(sizeof *qp, GFP_KERNEL);
1043         if (!qp)
1044                 return ERR_PTR(-ENOMEM);
1045
1046         qp->real_qp = real_qp;
1047         err = ib_open_shared_qp_security(qp, real_qp->device);
1048         if (err) {
1049                 kfree(qp);
1050                 return ERR_PTR(err);
1051         }
1052
1053         qp->real_qp = real_qp;
1054         atomic_inc(&real_qp->usecnt);
1055         qp->device = real_qp->device;
1056         qp->event_handler = event_handler;
1057         qp->qp_context = qp_context;
1058         qp->qp_num = real_qp->qp_num;
1059         qp->qp_type = real_qp->qp_type;
1060
1061         spin_lock_irqsave(&real_qp->device->event_handler_lock, flags);
1062         list_add(&qp->open_list, &real_qp->open_list);
1063         spin_unlock_irqrestore(&real_qp->device->event_handler_lock, flags);
1064
1065         return qp;
1066 }
1067
1068 struct ib_qp *ib_open_qp(struct ib_xrcd *xrcd,
1069                          struct ib_qp_open_attr *qp_open_attr)
1070 {
1071         struct ib_qp *qp, *real_qp;
1072
1073         if (qp_open_attr->qp_type != IB_QPT_XRC_TGT)
1074                 return ERR_PTR(-EINVAL);
1075
1076         qp = ERR_PTR(-EINVAL);
1077         mutex_lock(&xrcd->tgt_qp_mutex);
1078         list_for_each_entry(real_qp, &xrcd->tgt_qp_list, xrcd_list) {
1079                 if (real_qp->qp_num == qp_open_attr->qp_num) {
1080                         qp = __ib_open_qp(real_qp, qp_open_attr->event_handler,
1081                                           qp_open_attr->qp_context);
1082                         break;
1083                 }
1084         }
1085         mutex_unlock(&xrcd->tgt_qp_mutex);
1086         return qp;
1087 }
1088 EXPORT_SYMBOL(ib_open_qp);
1089
1090 static struct ib_qp *ib_create_xrc_qp(struct ib_qp *qp,
1091                 struct ib_qp_init_attr *qp_init_attr)
1092 {
1093         struct ib_qp *real_qp = qp;
1094
1095         qp->event_handler = __ib_shared_qp_event_handler;
1096         qp->qp_context = qp;
1097         qp->pd = NULL;
1098         qp->send_cq = qp->recv_cq = NULL;
1099         qp->srq = NULL;
1100         qp->xrcd = qp_init_attr->xrcd;
1101         atomic_inc(&qp_init_attr->xrcd->usecnt);
1102         INIT_LIST_HEAD(&qp->open_list);
1103
1104         qp = __ib_open_qp(real_qp, qp_init_attr->event_handler,
1105                           qp_init_attr->qp_context);
1106         if (!IS_ERR(qp))
1107                 __ib_insert_xrcd_qp(qp_init_attr->xrcd, real_qp);
1108         else
1109                 real_qp->device->destroy_qp(real_qp);
1110         return qp;
1111 }
1112
1113 struct ib_qp *ib_create_qp(struct ib_pd *pd,
1114                            struct ib_qp_init_attr *qp_init_attr)
1115 {
1116         struct ib_device *device = pd ? pd->device : qp_init_attr->xrcd->device;
1117         struct ib_qp *qp;
1118         int ret;
1119
1120         if (qp_init_attr->rwq_ind_tbl &&
1121             (qp_init_attr->recv_cq ||
1122             qp_init_attr->srq || qp_init_attr->cap.max_recv_wr ||
1123             qp_init_attr->cap.max_recv_sge))
1124                 return ERR_PTR(-EINVAL);
1125
1126         /*
1127          * If the callers is using the RDMA API calculate the resources
1128          * needed for the RDMA READ/WRITE operations.
1129          *
1130          * Note that these callers need to pass in a port number.
1131          */
1132         if (qp_init_attr->cap.max_rdma_ctxs)
1133                 rdma_rw_init_qp(device, qp_init_attr);
1134
1135         qp = _ib_create_qp(device, pd, qp_init_attr, NULL, NULL);
1136         if (IS_ERR(qp))
1137                 return qp;
1138
1139         ret = ib_create_qp_security(qp, device);
1140         if (ret) {
1141                 ib_destroy_qp(qp);
1142                 return ERR_PTR(ret);
1143         }
1144
1145         qp->real_qp    = qp;
1146         qp->qp_type    = qp_init_attr->qp_type;
1147         qp->rwq_ind_tbl = qp_init_attr->rwq_ind_tbl;
1148
1149         atomic_set(&qp->usecnt, 0);
1150         qp->mrs_used = 0;
1151         spin_lock_init(&qp->mr_lock);
1152         INIT_LIST_HEAD(&qp->rdma_mrs);
1153         INIT_LIST_HEAD(&qp->sig_mrs);
1154         qp->port = 0;
1155
1156         if (qp_init_attr->qp_type == IB_QPT_XRC_TGT)
1157                 return ib_create_xrc_qp(qp, qp_init_attr);
1158
1159         qp->event_handler = qp_init_attr->event_handler;
1160         qp->qp_context = qp_init_attr->qp_context;
1161         if (qp_init_attr->qp_type == IB_QPT_XRC_INI) {
1162                 qp->recv_cq = NULL;
1163                 qp->srq = NULL;
1164         } else {
1165                 qp->recv_cq = qp_init_attr->recv_cq;
1166                 if (qp_init_attr->recv_cq)
1167                         atomic_inc(&qp_init_attr->recv_cq->usecnt);
1168                 qp->srq = qp_init_attr->srq;
1169                 if (qp->srq)
1170                         atomic_inc(&qp_init_attr->srq->usecnt);
1171         }
1172
1173         qp->send_cq = qp_init_attr->send_cq;
1174         qp->xrcd    = NULL;
1175
1176         atomic_inc(&pd->usecnt);
1177         if (qp_init_attr->send_cq)
1178                 atomic_inc(&qp_init_attr->send_cq->usecnt);
1179         if (qp_init_attr->rwq_ind_tbl)
1180                 atomic_inc(&qp->rwq_ind_tbl->usecnt);
1181
1182         if (qp_init_attr->cap.max_rdma_ctxs) {
1183                 ret = rdma_rw_init_mrs(qp, qp_init_attr);
1184                 if (ret) {
1185                         pr_err("failed to init MR pool ret= %d\n", ret);
1186                         ib_destroy_qp(qp);
1187                         return ERR_PTR(ret);
1188                 }
1189         }
1190
1191         /*
1192          * Note: all hw drivers guarantee that max_send_sge is lower than
1193          * the device RDMA WRITE SGE limit but not all hw drivers ensure that
1194          * max_send_sge <= max_sge_rd.
1195          */
1196         qp->max_write_sge = qp_init_attr->cap.max_send_sge;
1197         qp->max_read_sge = min_t(u32, qp_init_attr->cap.max_send_sge,
1198                                  device->attrs.max_sge_rd);
1199
1200         return qp;
1201 }
1202 EXPORT_SYMBOL(ib_create_qp);
1203
1204 static const struct {
1205         int                     valid;
1206         enum ib_qp_attr_mask    req_param[IB_QPT_MAX];
1207         enum ib_qp_attr_mask    opt_param[IB_QPT_MAX];
1208 } qp_state_table[IB_QPS_ERR + 1][IB_QPS_ERR + 1] = {
1209         [IB_QPS_RESET] = {
1210                 [IB_QPS_RESET] = { .valid = 1 },
1211                 [IB_QPS_INIT]  = {
1212                         .valid = 1,
1213                         .req_param = {
1214                                 [IB_QPT_UD]  = (IB_QP_PKEY_INDEX                |
1215                                                 IB_QP_PORT                      |
1216                                                 IB_QP_QKEY),
1217                                 [IB_QPT_RAW_PACKET] = IB_QP_PORT,
1218                                 [IB_QPT_UC]  = (IB_QP_PKEY_INDEX                |
1219                                                 IB_QP_PORT                      |
1220                                                 IB_QP_ACCESS_FLAGS),
1221                                 [IB_QPT_RC]  = (IB_QP_PKEY_INDEX                |
1222                                                 IB_QP_PORT                      |
1223                                                 IB_QP_ACCESS_FLAGS),
1224                                 [IB_QPT_XRC_INI] = (IB_QP_PKEY_INDEX            |
1225                                                 IB_QP_PORT                      |
1226                                                 IB_QP_ACCESS_FLAGS),
1227                                 [IB_QPT_XRC_TGT] = (IB_QP_PKEY_INDEX            |
1228                                                 IB_QP_PORT                      |
1229                                                 IB_QP_ACCESS_FLAGS),
1230                                 [IB_QPT_SMI] = (IB_QP_PKEY_INDEX                |
1231                                                 IB_QP_QKEY),
1232                                 [IB_QPT_GSI] = (IB_QP_PKEY_INDEX                |
1233                                                 IB_QP_QKEY),
1234                         }
1235                 },
1236         },
1237         [IB_QPS_INIT]  = {
1238                 [IB_QPS_RESET] = { .valid = 1 },
1239                 [IB_QPS_ERR] =   { .valid = 1 },
1240                 [IB_QPS_INIT]  = {
1241                         .valid = 1,
1242                         .opt_param = {
1243                                 [IB_QPT_UD]  = (IB_QP_PKEY_INDEX                |
1244                                                 IB_QP_PORT                      |
1245                                                 IB_QP_QKEY),
1246                                 [IB_QPT_UC]  = (IB_QP_PKEY_INDEX                |
1247                                                 IB_QP_PORT                      |
1248                                                 IB_QP_ACCESS_FLAGS),
1249                                 [IB_QPT_RC]  = (IB_QP_PKEY_INDEX                |
1250                                                 IB_QP_PORT                      |
1251                                                 IB_QP_ACCESS_FLAGS),
1252                                 [IB_QPT_XRC_INI] = (IB_QP_PKEY_INDEX            |
1253                                                 IB_QP_PORT                      |
1254                                                 IB_QP_ACCESS_FLAGS),
1255                                 [IB_QPT_XRC_TGT] = (IB_QP_PKEY_INDEX            |
1256                                                 IB_QP_PORT                      |
1257                                                 IB_QP_ACCESS_FLAGS),
1258                                 [IB_QPT_SMI] = (IB_QP_PKEY_INDEX                |
1259                                                 IB_QP_QKEY),
1260                                 [IB_QPT_GSI] = (IB_QP_PKEY_INDEX                |
1261                                                 IB_QP_QKEY),
1262                         }
1263                 },
1264                 [IB_QPS_RTR]   = {
1265                         .valid = 1,
1266                         .req_param = {
1267                                 [IB_QPT_UC]  = (IB_QP_AV                        |
1268                                                 IB_QP_PATH_MTU                  |
1269                                                 IB_QP_DEST_QPN                  |
1270                                                 IB_QP_RQ_PSN),
1271                                 [IB_QPT_RC]  = (IB_QP_AV                        |
1272                                                 IB_QP_PATH_MTU                  |
1273                                                 IB_QP_DEST_QPN                  |
1274                                                 IB_QP_RQ_PSN                    |
1275                                                 IB_QP_MAX_DEST_RD_ATOMIC        |
1276                                                 IB_QP_MIN_RNR_TIMER),
1277                                 [IB_QPT_XRC_INI] = (IB_QP_AV                    |
1278                                                 IB_QP_PATH_MTU                  |
1279                                                 IB_QP_DEST_QPN                  |
1280                                                 IB_QP_RQ_PSN),
1281                                 [IB_QPT_XRC_TGT] = (IB_QP_AV                    |
1282                                                 IB_QP_PATH_MTU                  |
1283                                                 IB_QP_DEST_QPN                  |
1284                                                 IB_QP_RQ_PSN                    |
1285                                                 IB_QP_MAX_DEST_RD_ATOMIC        |
1286                                                 IB_QP_MIN_RNR_TIMER),
1287                         },
1288                         .opt_param = {
1289                                  [IB_QPT_UD]  = (IB_QP_PKEY_INDEX               |
1290                                                  IB_QP_QKEY),
1291                                  [IB_QPT_UC]  = (IB_QP_ALT_PATH                 |
1292                                                  IB_QP_ACCESS_FLAGS             |
1293                                                  IB_QP_PKEY_INDEX),
1294                                  [IB_QPT_RC]  = (IB_QP_ALT_PATH                 |
1295                                                  IB_QP_ACCESS_FLAGS             |
1296                                                  IB_QP_PKEY_INDEX),
1297                                  [IB_QPT_XRC_INI] = (IB_QP_ALT_PATH             |
1298                                                  IB_QP_ACCESS_FLAGS             |
1299                                                  IB_QP_PKEY_INDEX),
1300                                  [IB_QPT_XRC_TGT] = (IB_QP_ALT_PATH             |
1301                                                  IB_QP_ACCESS_FLAGS             |
1302                                                  IB_QP_PKEY_INDEX),
1303                                  [IB_QPT_SMI] = (IB_QP_PKEY_INDEX               |
1304                                                  IB_QP_QKEY),
1305                                  [IB_QPT_GSI] = (IB_QP_PKEY_INDEX               |
1306                                                  IB_QP_QKEY),
1307                          },
1308                 },
1309         },
1310         [IB_QPS_RTR]   = {
1311                 [IB_QPS_RESET] = { .valid = 1 },
1312                 [IB_QPS_ERR] =   { .valid = 1 },
1313                 [IB_QPS_RTS]   = {
1314                         .valid = 1,
1315                         .req_param = {
1316                                 [IB_QPT_UD]  = IB_QP_SQ_PSN,
1317                                 [IB_QPT_UC]  = IB_QP_SQ_PSN,
1318                                 [IB_QPT_RC]  = (IB_QP_TIMEOUT                   |
1319                                                 IB_QP_RETRY_CNT                 |
1320                                                 IB_QP_RNR_RETRY                 |
1321                                                 IB_QP_SQ_PSN                    |
1322                                                 IB_QP_MAX_QP_RD_ATOMIC),
1323                                 [IB_QPT_XRC_INI] = (IB_QP_TIMEOUT               |
1324                                                 IB_QP_RETRY_CNT                 |
1325                                                 IB_QP_RNR_RETRY                 |
1326                                                 IB_QP_SQ_PSN                    |
1327                                                 IB_QP_MAX_QP_RD_ATOMIC),
1328                                 [IB_QPT_XRC_TGT] = (IB_QP_TIMEOUT               |
1329                                                 IB_QP_SQ_PSN),
1330                                 [IB_QPT_SMI] = IB_QP_SQ_PSN,
1331                                 [IB_QPT_GSI] = IB_QP_SQ_PSN,
1332                         },
1333                         .opt_param = {
1334                                  [IB_QPT_UD]  = (IB_QP_CUR_STATE                |
1335                                                  IB_QP_QKEY),
1336                                  [IB_QPT_UC]  = (IB_QP_CUR_STATE                |
1337                                                  IB_QP_ALT_PATH                 |
1338                                                  IB_QP_ACCESS_FLAGS             |
1339                                                  IB_QP_PATH_MIG_STATE),
1340                                  [IB_QPT_RC]  = (IB_QP_CUR_STATE                |
1341                                                  IB_QP_ALT_PATH                 |
1342                                                  IB_QP_ACCESS_FLAGS             |
1343                                                  IB_QP_MIN_RNR_TIMER            |
1344                                                  IB_QP_PATH_MIG_STATE),
1345                                  [IB_QPT_XRC_INI] = (IB_QP_CUR_STATE            |
1346                                                  IB_QP_ALT_PATH                 |
1347                                                  IB_QP_ACCESS_FLAGS             |
1348                                                  IB_QP_PATH_MIG_STATE),
1349                                  [IB_QPT_XRC_TGT] = (IB_QP_CUR_STATE            |
1350                                                  IB_QP_ALT_PATH                 |
1351                                                  IB_QP_ACCESS_FLAGS             |
1352                                                  IB_QP_MIN_RNR_TIMER            |
1353                                                  IB_QP_PATH_MIG_STATE),
1354                                  [IB_QPT_SMI] = (IB_QP_CUR_STATE                |
1355                                                  IB_QP_QKEY),
1356                                  [IB_QPT_GSI] = (IB_QP_CUR_STATE                |
1357                                                  IB_QP_QKEY),
1358                                  [IB_QPT_RAW_PACKET] = IB_QP_RATE_LIMIT,
1359                          }
1360                 }
1361         },
1362         [IB_QPS_RTS]   = {
1363                 [IB_QPS_RESET] = { .valid = 1 },
1364                 [IB_QPS_ERR] =   { .valid = 1 },
1365                 [IB_QPS_RTS]   = {
1366                         .valid = 1,
1367                         .opt_param = {
1368                                 [IB_QPT_UD]  = (IB_QP_CUR_STATE                 |
1369                                                 IB_QP_QKEY),
1370                                 [IB_QPT_UC]  = (IB_QP_CUR_STATE                 |
1371                                                 IB_QP_ACCESS_FLAGS              |
1372                                                 IB_QP_ALT_PATH                  |
1373                                                 IB_QP_PATH_MIG_STATE),
1374                                 [IB_QPT_RC]  = (IB_QP_CUR_STATE                 |
1375                                                 IB_QP_ACCESS_FLAGS              |
1376                                                 IB_QP_ALT_PATH                  |
1377                                                 IB_QP_PATH_MIG_STATE            |
1378                                                 IB_QP_MIN_RNR_TIMER),
1379                                 [IB_QPT_XRC_INI] = (IB_QP_CUR_STATE             |
1380                                                 IB_QP_ACCESS_FLAGS              |
1381                                                 IB_QP_ALT_PATH                  |
1382                                                 IB_QP_PATH_MIG_STATE),
1383                                 [IB_QPT_XRC_TGT] = (IB_QP_CUR_STATE             |
1384                                                 IB_QP_ACCESS_FLAGS              |
1385                                                 IB_QP_ALT_PATH                  |
1386                                                 IB_QP_PATH_MIG_STATE            |
1387                                                 IB_QP_MIN_RNR_TIMER),
1388                                 [IB_QPT_SMI] = (IB_QP_CUR_STATE                 |
1389                                                 IB_QP_QKEY),
1390                                 [IB_QPT_GSI] = (IB_QP_CUR_STATE                 |
1391                                                 IB_QP_QKEY),
1392                                 [IB_QPT_RAW_PACKET] = IB_QP_RATE_LIMIT,
1393                         }
1394                 },
1395                 [IB_QPS_SQD]   = {
1396                         .valid = 1,
1397                         .opt_param = {
1398                                 [IB_QPT_UD]  = IB_QP_EN_SQD_ASYNC_NOTIFY,
1399                                 [IB_QPT_UC]  = IB_QP_EN_SQD_ASYNC_NOTIFY,
1400                                 [IB_QPT_RC]  = IB_QP_EN_SQD_ASYNC_NOTIFY,
1401                                 [IB_QPT_XRC_INI] = IB_QP_EN_SQD_ASYNC_NOTIFY,
1402                                 [IB_QPT_XRC_TGT] = IB_QP_EN_SQD_ASYNC_NOTIFY, /* ??? */
1403                                 [IB_QPT_SMI] = IB_QP_EN_SQD_ASYNC_NOTIFY,
1404                                 [IB_QPT_GSI] = IB_QP_EN_SQD_ASYNC_NOTIFY
1405                         }
1406                 },
1407         },
1408         [IB_QPS_SQD]   = {
1409                 [IB_QPS_RESET] = { .valid = 1 },
1410                 [IB_QPS_ERR] =   { .valid = 1 },
1411                 [IB_QPS_RTS]   = {
1412                         .valid = 1,
1413                         .opt_param = {
1414                                 [IB_QPT_UD]  = (IB_QP_CUR_STATE                 |
1415                                                 IB_QP_QKEY),
1416                                 [IB_QPT_UC]  = (IB_QP_CUR_STATE                 |
1417                                                 IB_QP_ALT_PATH                  |
1418                                                 IB_QP_ACCESS_FLAGS              |
1419                                                 IB_QP_PATH_MIG_STATE),
1420                                 [IB_QPT_RC]  = (IB_QP_CUR_STATE                 |
1421                                                 IB_QP_ALT_PATH                  |
1422                                                 IB_QP_ACCESS_FLAGS              |
1423                                                 IB_QP_MIN_RNR_TIMER             |
1424                                                 IB_QP_PATH_MIG_STATE),
1425                                 [IB_QPT_XRC_INI] = (IB_QP_CUR_STATE             |
1426                                                 IB_QP_ALT_PATH                  |
1427                                                 IB_QP_ACCESS_FLAGS              |
1428                                                 IB_QP_PATH_MIG_STATE),
1429                                 [IB_QPT_XRC_TGT] = (IB_QP_CUR_STATE             |
1430                                                 IB_QP_ALT_PATH                  |
1431                                                 IB_QP_ACCESS_FLAGS              |
1432                                                 IB_QP_MIN_RNR_TIMER             |
1433                                                 IB_QP_PATH_MIG_STATE),
1434                                 [IB_QPT_SMI] = (IB_QP_CUR_STATE                 |
1435                                                 IB_QP_QKEY),
1436                                 [IB_QPT_GSI] = (IB_QP_CUR_STATE                 |
1437                                                 IB_QP_QKEY),
1438                         }
1439                 },
1440                 [IB_QPS_SQD]   = {
1441                         .valid = 1,
1442                         .opt_param = {
1443                                 [IB_QPT_UD]  = (IB_QP_PKEY_INDEX                |
1444                                                 IB_QP_QKEY),
1445                                 [IB_QPT_UC]  = (IB_QP_AV                        |
1446                                                 IB_QP_ALT_PATH                  |
1447                                                 IB_QP_ACCESS_FLAGS              |
1448                                                 IB_QP_PKEY_INDEX                |
1449                                                 IB_QP_PATH_MIG_STATE),
1450                                 [IB_QPT_RC]  = (IB_QP_PORT                      |
1451                                                 IB_QP_AV                        |
1452                                                 IB_QP_TIMEOUT                   |
1453                                                 IB_QP_RETRY_CNT                 |
1454                                                 IB_QP_RNR_RETRY                 |
1455                                                 IB_QP_MAX_QP_RD_ATOMIC          |
1456                                                 IB_QP_MAX_DEST_RD_ATOMIC        |
1457                                                 IB_QP_ALT_PATH                  |
1458                                                 IB_QP_ACCESS_FLAGS              |
1459                                                 IB_QP_PKEY_INDEX                |
1460                                                 IB_QP_MIN_RNR_TIMER             |
1461                                                 IB_QP_PATH_MIG_STATE),
1462                                 [IB_QPT_XRC_INI] = (IB_QP_PORT                  |
1463                                                 IB_QP_AV                        |
1464                                                 IB_QP_TIMEOUT                   |
1465                                                 IB_QP_RETRY_CNT                 |
1466                                                 IB_QP_RNR_RETRY                 |
1467                                                 IB_QP_MAX_QP_RD_ATOMIC          |
1468                                                 IB_QP_ALT_PATH                  |
1469                                                 IB_QP_ACCESS_FLAGS              |
1470                                                 IB_QP_PKEY_INDEX                |
1471                                                 IB_QP_PATH_MIG_STATE),
1472                                 [IB_QPT_XRC_TGT] = (IB_QP_PORT                  |
1473                                                 IB_QP_AV                        |
1474                                                 IB_QP_TIMEOUT                   |
1475                                                 IB_QP_MAX_DEST_RD_ATOMIC        |
1476                                                 IB_QP_ALT_PATH                  |
1477                                                 IB_QP_ACCESS_FLAGS              |
1478                                                 IB_QP_PKEY_INDEX                |
1479                                                 IB_QP_MIN_RNR_TIMER             |
1480                                                 IB_QP_PATH_MIG_STATE),
1481                                 [IB_QPT_SMI] = (IB_QP_PKEY_INDEX                |
1482                                                 IB_QP_QKEY),
1483                                 [IB_QPT_GSI] = (IB_QP_PKEY_INDEX                |
1484                                                 IB_QP_QKEY),
1485                         }
1486                 }
1487         },
1488         [IB_QPS_SQE]   = {
1489                 [IB_QPS_RESET] = { .valid = 1 },
1490                 [IB_QPS_ERR] =   { .valid = 1 },
1491                 [IB_QPS_RTS]   = {
1492                         .valid = 1,
1493                         .opt_param = {
1494                                 [IB_QPT_UD]  = (IB_QP_CUR_STATE                 |
1495                                                 IB_QP_QKEY),
1496                                 [IB_QPT_UC]  = (IB_QP_CUR_STATE                 |
1497                                                 IB_QP_ACCESS_FLAGS),
1498                                 [IB_QPT_SMI] = (IB_QP_CUR_STATE                 |
1499                                                 IB_QP_QKEY),
1500                                 [IB_QPT_GSI] = (IB_QP_CUR_STATE                 |
1501                                                 IB_QP_QKEY),
1502                         }
1503                 }
1504         },
1505         [IB_QPS_ERR] = {
1506                 [IB_QPS_RESET] = { .valid = 1 },
1507                 [IB_QPS_ERR] =   { .valid = 1 }
1508         }
1509 };
1510
1511 bool ib_modify_qp_is_ok(enum ib_qp_state cur_state, enum ib_qp_state next_state,
1512                         enum ib_qp_type type, enum ib_qp_attr_mask mask)
1513 {
1514         enum ib_qp_attr_mask req_param, opt_param;
1515
1516         if (mask & IB_QP_CUR_STATE  &&
1517             cur_state != IB_QPS_RTR && cur_state != IB_QPS_RTS &&
1518             cur_state != IB_QPS_SQD && cur_state != IB_QPS_SQE)
1519                 return false;
1520
1521         if (!qp_state_table[cur_state][next_state].valid)
1522                 return false;
1523
1524         req_param = qp_state_table[cur_state][next_state].req_param[type];
1525         opt_param = qp_state_table[cur_state][next_state].opt_param[type];
1526
1527         if ((mask & req_param) != req_param)
1528                 return false;
1529
1530         if (mask & ~(req_param | opt_param | IB_QP_STATE))
1531                 return false;
1532
1533         return true;
1534 }
1535 EXPORT_SYMBOL(ib_modify_qp_is_ok);
1536
1537 /**
1538  * ib_resolve_eth_dmac - Resolve destination mac address
1539  * @device:             Device to consider
1540  * @ah_attr:            address handle attribute which describes the
1541  *                      source and destination parameters
1542  * ib_resolve_eth_dmac() resolves destination mac address and L3 hop limit It
1543  * returns 0 on success or appropriate error code. It initializes the
1544  * necessary ah_attr fields when call is successful.
1545  */
1546 static int ib_resolve_eth_dmac(struct ib_device *device,
1547                                struct rdma_ah_attr *ah_attr)
1548 {
1549         int ret = 0;
1550
1551         if (rdma_is_multicast_addr((struct in6_addr *)ah_attr->grh.dgid.raw)) {
1552                 if (ipv6_addr_v4mapped((struct in6_addr *)ah_attr->grh.dgid.raw)) {
1553                         __be32 addr = 0;
1554
1555                         memcpy(&addr, ah_attr->grh.dgid.raw + 12, 4);
1556                         ip_eth_mc_map(addr, (char *)ah_attr->roce.dmac);
1557                 } else {
1558                         ipv6_eth_mc_map((struct in6_addr *)ah_attr->grh.dgid.raw,
1559                                         (char *)ah_attr->roce.dmac);
1560                 }
1561         } else {
1562                 ret = ib_resolve_unicast_gid_dmac(device, ah_attr);
1563         }
1564         return ret;
1565 }
1566
1567 static bool is_qp_type_connected(const struct ib_qp *qp)
1568 {
1569         return (qp->qp_type == IB_QPT_UC ||
1570                 qp->qp_type == IB_QPT_RC ||
1571                 qp->qp_type == IB_QPT_XRC_INI ||
1572                 qp->qp_type == IB_QPT_XRC_TGT);
1573 }
1574
1575 /**
1576  * IB core internal function to perform QP attributes modification.
1577  */
1578 static int _ib_modify_qp(struct ib_qp *qp, struct ib_qp_attr *attr,
1579                          int attr_mask, struct ib_udata *udata)
1580 {
1581         u8 port = attr_mask & IB_QP_PORT ? attr->port_num : qp->port;
1582         const struct ib_gid_attr *old_sgid_attr_av;
1583         const struct ib_gid_attr *old_sgid_attr_alt_av;
1584         int ret;
1585
1586         if (attr_mask & IB_QP_AV) {
1587                 ret = rdma_fill_sgid_attr(qp->device, &attr->ah_attr,
1588                                           &old_sgid_attr_av);
1589                 if (ret)
1590                         return ret;
1591         }
1592         if (attr_mask & IB_QP_ALT_PATH) {
1593                 /*
1594                  * FIXME: This does not track the migration state, so if the
1595                  * user loads a new alternate path after the HW has migrated
1596                  * from primary->alternate we will keep the wrong
1597                  * references. This is OK for IB because the reference
1598                  * counting does not serve any functional purpose.
1599                  */
1600                 ret = rdma_fill_sgid_attr(qp->device, &attr->alt_ah_attr,
1601                                           &old_sgid_attr_alt_av);
1602                 if (ret)
1603                         goto out_av;
1604
1605                 /*
1606                  * Today the core code can only handle alternate paths and APM
1607                  * for IB. Ban them in roce mode.
1608                  */
1609                 if (!(rdma_protocol_ib(qp->device,
1610                                        attr->alt_ah_attr.port_num) &&
1611                       rdma_protocol_ib(qp->device, port))) {
1612                         ret = EINVAL;
1613                         goto out;
1614                 }
1615         }
1616
1617         /*
1618          * If the user provided the qp_attr then we have to resolve it. Kernel
1619          * users have to provide already resolved rdma_ah_attr's
1620          */
1621         if (udata && (attr_mask & IB_QP_AV) &&
1622             attr->ah_attr.type == RDMA_AH_ATTR_TYPE_ROCE &&
1623             is_qp_type_connected(qp)) {
1624                 ret = ib_resolve_eth_dmac(qp->device, &attr->ah_attr);
1625                 if (ret)
1626                         goto out;
1627         }
1628
1629         if (rdma_ib_or_roce(qp->device, port)) {
1630                 if (attr_mask & IB_QP_RQ_PSN && attr->rq_psn & ~0xffffff) {
1631                         dev_warn(&qp->device->dev,
1632                                  "%s rq_psn overflow, masking to 24 bits\n",
1633                                  __func__);
1634                         attr->rq_psn &= 0xffffff;
1635                 }
1636
1637                 if (attr_mask & IB_QP_SQ_PSN && attr->sq_psn & ~0xffffff) {
1638                         dev_warn(&qp->device->dev,
1639                                  " %s sq_psn overflow, masking to 24 bits\n",
1640                                  __func__);
1641                         attr->sq_psn &= 0xffffff;
1642                 }
1643         }
1644
1645         ret = ib_security_modify_qp(qp, attr, attr_mask, udata);
1646         if (ret)
1647                 goto out;
1648
1649         if (attr_mask & IB_QP_PORT)
1650                 qp->port = attr->port_num;
1651         if (attr_mask & IB_QP_AV)
1652                 qp->av_sgid_attr =
1653                         rdma_update_sgid_attr(&attr->ah_attr, qp->av_sgid_attr);
1654         if (attr_mask & IB_QP_ALT_PATH)
1655                 qp->alt_path_sgid_attr = rdma_update_sgid_attr(
1656                         &attr->alt_ah_attr, qp->alt_path_sgid_attr);
1657
1658 out:
1659         if (attr_mask & IB_QP_ALT_PATH)
1660                 rdma_unfill_sgid_attr(&attr->alt_ah_attr, old_sgid_attr_alt_av);
1661 out_av:
1662         if (attr_mask & IB_QP_AV)
1663                 rdma_unfill_sgid_attr(&attr->ah_attr, old_sgid_attr_av);
1664         return ret;
1665 }
1666
1667 /**
1668  * ib_modify_qp_with_udata - Modifies the attributes for the specified QP.
1669  * @ib_qp: The QP to modify.
1670  * @attr: On input, specifies the QP attributes to modify.  On output,
1671  *   the current values of selected QP attributes are returned.
1672  * @attr_mask: A bit-mask used to specify which attributes of the QP
1673  *   are being modified.
1674  * @udata: pointer to user's input output buffer information
1675  *   are being modified.
1676  * It returns 0 on success and returns appropriate error code on error.
1677  */
1678 int ib_modify_qp_with_udata(struct ib_qp *ib_qp, struct ib_qp_attr *attr,
1679                             int attr_mask, struct ib_udata *udata)
1680 {
1681         return _ib_modify_qp(ib_qp->real_qp, attr, attr_mask, udata);
1682 }
1683 EXPORT_SYMBOL(ib_modify_qp_with_udata);
1684
1685 int ib_get_eth_speed(struct ib_device *dev, u8 port_num, u8 *speed, u8 *width)
1686 {
1687         int rc;
1688         u32 netdev_speed;
1689         struct net_device *netdev;
1690         struct ethtool_link_ksettings lksettings;
1691
1692         if (rdma_port_get_link_layer(dev, port_num) != IB_LINK_LAYER_ETHERNET)
1693                 return -EINVAL;
1694
1695         if (!dev->get_netdev)
1696                 return -EOPNOTSUPP;
1697
1698         netdev = dev->get_netdev(dev, port_num);
1699         if (!netdev)
1700                 return -ENODEV;
1701
1702         rtnl_lock();
1703         rc = __ethtool_get_link_ksettings(netdev, &lksettings);
1704         rtnl_unlock();
1705
1706         dev_put(netdev);
1707
1708         if (!rc) {
1709                 netdev_speed = lksettings.base.speed;
1710         } else {
1711                 netdev_speed = SPEED_1000;
1712                 pr_warn("%s speed is unknown, defaulting to %d\n", netdev->name,
1713                         netdev_speed);
1714         }
1715
1716         if (netdev_speed <= SPEED_1000) {
1717                 *width = IB_WIDTH_1X;
1718                 *speed = IB_SPEED_SDR;
1719         } else if (netdev_speed <= SPEED_10000) {
1720                 *width = IB_WIDTH_1X;
1721                 *speed = IB_SPEED_FDR10;
1722         } else if (netdev_speed <= SPEED_20000) {
1723                 *width = IB_WIDTH_4X;
1724                 *speed = IB_SPEED_DDR;
1725         } else if (netdev_speed <= SPEED_25000) {
1726                 *width = IB_WIDTH_1X;
1727                 *speed = IB_SPEED_EDR;
1728         } else if (netdev_speed <= SPEED_40000) {
1729                 *width = IB_WIDTH_4X;
1730                 *speed = IB_SPEED_FDR10;
1731         } else {
1732                 *width = IB_WIDTH_4X;
1733                 *speed = IB_SPEED_EDR;
1734         }
1735
1736         return 0;
1737 }
1738 EXPORT_SYMBOL(ib_get_eth_speed);
1739
1740 int ib_modify_qp(struct ib_qp *qp,
1741                  struct ib_qp_attr *qp_attr,
1742                  int qp_attr_mask)
1743 {
1744         return _ib_modify_qp(qp->real_qp, qp_attr, qp_attr_mask, NULL);
1745 }
1746 EXPORT_SYMBOL(ib_modify_qp);
1747
1748 int ib_query_qp(struct ib_qp *qp,
1749                 struct ib_qp_attr *qp_attr,
1750                 int qp_attr_mask,
1751                 struct ib_qp_init_attr *qp_init_attr)
1752 {
1753         qp_attr->ah_attr.grh.sgid_attr = NULL;
1754         qp_attr->alt_ah_attr.grh.sgid_attr = NULL;
1755
1756         return qp->device->query_qp ?
1757                 qp->device->query_qp(qp->real_qp, qp_attr, qp_attr_mask, qp_init_attr) :
1758                 -EOPNOTSUPP;
1759 }
1760 EXPORT_SYMBOL(ib_query_qp);
1761
1762 int ib_close_qp(struct ib_qp *qp)
1763 {
1764         struct ib_qp *real_qp;
1765         unsigned long flags;
1766
1767         real_qp = qp->real_qp;
1768         if (real_qp == qp)
1769                 return -EINVAL;
1770
1771         spin_lock_irqsave(&real_qp->device->event_handler_lock, flags);
1772         list_del(&qp->open_list);
1773         spin_unlock_irqrestore(&real_qp->device->event_handler_lock, flags);
1774
1775         atomic_dec(&real_qp->usecnt);
1776         if (qp->qp_sec)
1777                 ib_close_shared_qp_security(qp->qp_sec);
1778         kfree(qp);
1779
1780         return 0;
1781 }
1782 EXPORT_SYMBOL(ib_close_qp);
1783
1784 static int __ib_destroy_shared_qp(struct ib_qp *qp)
1785 {
1786         struct ib_xrcd *xrcd;
1787         struct ib_qp *real_qp;
1788         int ret;
1789
1790         real_qp = qp->real_qp;
1791         xrcd = real_qp->xrcd;
1792
1793         mutex_lock(&xrcd->tgt_qp_mutex);
1794         ib_close_qp(qp);
1795         if (atomic_read(&real_qp->usecnt) == 0)
1796                 list_del(&real_qp->xrcd_list);
1797         else
1798                 real_qp = NULL;
1799         mutex_unlock(&xrcd->tgt_qp_mutex);
1800
1801         if (real_qp) {
1802                 ret = ib_destroy_qp(real_qp);
1803                 if (!ret)
1804                         atomic_dec(&xrcd->usecnt);
1805                 else
1806                         __ib_insert_xrcd_qp(xrcd, real_qp);
1807         }
1808
1809         return 0;
1810 }
1811
1812 int ib_destroy_qp(struct ib_qp *qp)
1813 {
1814         const struct ib_gid_attr *alt_path_sgid_attr = qp->alt_path_sgid_attr;
1815         const struct ib_gid_attr *av_sgid_attr = qp->av_sgid_attr;
1816         struct ib_pd *pd;
1817         struct ib_cq *scq, *rcq;
1818         struct ib_srq *srq;
1819         struct ib_rwq_ind_table *ind_tbl;
1820         struct ib_qp_security *sec;
1821         int ret;
1822
1823         WARN_ON_ONCE(qp->mrs_used > 0);
1824
1825         if (atomic_read(&qp->usecnt))
1826                 return -EBUSY;
1827
1828         if (qp->real_qp != qp)
1829                 return __ib_destroy_shared_qp(qp);
1830
1831         pd   = qp->pd;
1832         scq  = qp->send_cq;
1833         rcq  = qp->recv_cq;
1834         srq  = qp->srq;
1835         ind_tbl = qp->rwq_ind_tbl;
1836         sec  = qp->qp_sec;
1837         if (sec)
1838                 ib_destroy_qp_security_begin(sec);
1839
1840         if (!qp->uobject)
1841                 rdma_rw_cleanup_mrs(qp);
1842
1843         rdma_restrack_del(&qp->res);
1844         ret = qp->device->destroy_qp(qp);
1845         if (!ret) {
1846                 if (alt_path_sgid_attr)
1847                         rdma_put_gid_attr(alt_path_sgid_attr);
1848                 if (av_sgid_attr)
1849                         rdma_put_gid_attr(av_sgid_attr);
1850                 if (pd)
1851                         atomic_dec(&pd->usecnt);
1852                 if (scq)
1853                         atomic_dec(&scq->usecnt);
1854                 if (rcq)
1855                         atomic_dec(&rcq->usecnt);
1856                 if (srq)
1857                         atomic_dec(&srq->usecnt);
1858                 if (ind_tbl)
1859                         atomic_dec(&ind_tbl->usecnt);
1860                 if (sec)
1861                         ib_destroy_qp_security_end(sec);
1862         } else {
1863                 if (sec)
1864                         ib_destroy_qp_security_abort(sec);
1865         }
1866
1867         return ret;
1868 }
1869 EXPORT_SYMBOL(ib_destroy_qp);
1870
1871 /* Completion queues */
1872
1873 struct ib_cq *__ib_create_cq(struct ib_device *device,
1874                              ib_comp_handler comp_handler,
1875                              void (*event_handler)(struct ib_event *, void *),
1876                              void *cq_context,
1877                              const struct ib_cq_init_attr *cq_attr,
1878                              const char *caller)
1879 {
1880         struct ib_cq *cq;
1881
1882         cq = device->create_cq(device, cq_attr, NULL, NULL);
1883
1884         if (!IS_ERR(cq)) {
1885                 cq->device        = device;
1886                 cq->uobject       = NULL;
1887                 cq->comp_handler  = comp_handler;
1888                 cq->event_handler = event_handler;
1889                 cq->cq_context    = cq_context;
1890                 atomic_set(&cq->usecnt, 0);
1891                 cq->res.type = RDMA_RESTRACK_CQ;
1892                 rdma_restrack_set_task(&cq->res, caller);
1893                 rdma_restrack_add(&cq->res);
1894         }
1895
1896         return cq;
1897 }
1898 EXPORT_SYMBOL(__ib_create_cq);
1899
1900 int rdma_set_cq_moderation(struct ib_cq *cq, u16 cq_count, u16 cq_period)
1901 {
1902         return cq->device->modify_cq ?
1903                 cq->device->modify_cq(cq, cq_count, cq_period) : -EOPNOTSUPP;
1904 }
1905 EXPORT_SYMBOL(rdma_set_cq_moderation);
1906
1907 int ib_destroy_cq(struct ib_cq *cq)
1908 {
1909         if (atomic_read(&cq->usecnt))
1910                 return -EBUSY;
1911
1912         rdma_restrack_del(&cq->res);
1913         return cq->device->destroy_cq(cq);
1914 }
1915 EXPORT_SYMBOL(ib_destroy_cq);
1916
1917 int ib_resize_cq(struct ib_cq *cq, int cqe)
1918 {
1919         return cq->device->resize_cq ?
1920                 cq->device->resize_cq(cq, cqe, NULL) : -EOPNOTSUPP;
1921 }
1922 EXPORT_SYMBOL(ib_resize_cq);
1923
1924 /* Memory regions */
1925
1926 int ib_dereg_mr(struct ib_mr *mr)
1927 {
1928         struct ib_pd *pd = mr->pd;
1929         struct ib_dm *dm = mr->dm;
1930         int ret;
1931
1932         rdma_restrack_del(&mr->res);
1933         ret = mr->device->dereg_mr(mr);
1934         if (!ret) {
1935                 atomic_dec(&pd->usecnt);
1936                 if (dm)
1937                         atomic_dec(&dm->usecnt);
1938         }
1939
1940         return ret;
1941 }
1942 EXPORT_SYMBOL(ib_dereg_mr);
1943
1944 /**
1945  * ib_alloc_mr() - Allocates a memory region
1946  * @pd:            protection domain associated with the region
1947  * @mr_type:       memory region type
1948  * @max_num_sg:    maximum sg entries available for registration.
1949  *
1950  * Notes:
1951  * Memory registeration page/sg lists must not exceed max_num_sg.
1952  * For mr_type IB_MR_TYPE_MEM_REG, the total length cannot exceed
1953  * max_num_sg * used_page_size.
1954  *
1955  */
1956 struct ib_mr *ib_alloc_mr(struct ib_pd *pd,
1957                           enum ib_mr_type mr_type,
1958                           u32 max_num_sg)
1959 {
1960         struct ib_mr *mr;
1961
1962         if (!pd->device->alloc_mr)
1963                 return ERR_PTR(-EOPNOTSUPP);
1964
1965         mr = pd->device->alloc_mr(pd, mr_type, max_num_sg);
1966         if (!IS_ERR(mr)) {
1967                 mr->device  = pd->device;
1968                 mr->pd      = pd;
1969                 mr->dm      = NULL;
1970                 mr->uobject = NULL;
1971                 atomic_inc(&pd->usecnt);
1972                 mr->need_inval = false;
1973                 mr->res.type = RDMA_RESTRACK_MR;
1974                 rdma_restrack_add(&mr->res);
1975         }
1976
1977         return mr;
1978 }
1979 EXPORT_SYMBOL(ib_alloc_mr);
1980
1981 /* "Fast" memory regions */
1982
1983 struct ib_fmr *ib_alloc_fmr(struct ib_pd *pd,
1984                             int mr_access_flags,
1985                             struct ib_fmr_attr *fmr_attr)
1986 {
1987         struct ib_fmr *fmr;
1988
1989         if (!pd->device->alloc_fmr)
1990                 return ERR_PTR(-EOPNOTSUPP);
1991
1992         fmr = pd->device->alloc_fmr(pd, mr_access_flags, fmr_attr);
1993         if (!IS_ERR(fmr)) {
1994                 fmr->device = pd->device;
1995                 fmr->pd     = pd;
1996                 atomic_inc(&pd->usecnt);
1997         }
1998
1999         return fmr;
2000 }
2001 EXPORT_SYMBOL(ib_alloc_fmr);
2002
2003 int ib_unmap_fmr(struct list_head *fmr_list)
2004 {
2005         struct ib_fmr *fmr;
2006
2007         if (list_empty(fmr_list))
2008                 return 0;
2009
2010         fmr = list_entry(fmr_list->next, struct ib_fmr, list);
2011         return fmr->device->unmap_fmr(fmr_list);
2012 }
2013 EXPORT_SYMBOL(ib_unmap_fmr);
2014
2015 int ib_dealloc_fmr(struct ib_fmr *fmr)
2016 {
2017         struct ib_pd *pd;
2018         int ret;
2019
2020         pd = fmr->pd;
2021         ret = fmr->device->dealloc_fmr(fmr);
2022         if (!ret)
2023                 atomic_dec(&pd->usecnt);
2024
2025         return ret;
2026 }
2027 EXPORT_SYMBOL(ib_dealloc_fmr);
2028
2029 /* Multicast groups */
2030
2031 static bool is_valid_mcast_lid(struct ib_qp *qp, u16 lid)
2032 {
2033         struct ib_qp_init_attr init_attr = {};
2034         struct ib_qp_attr attr = {};
2035         int num_eth_ports = 0;
2036         int port;
2037
2038         /* If QP state >= init, it is assigned to a port and we can check this
2039          * port only.
2040          */
2041         if (!ib_query_qp(qp, &attr, IB_QP_STATE | IB_QP_PORT, &init_attr)) {
2042                 if (attr.qp_state >= IB_QPS_INIT) {
2043                         if (rdma_port_get_link_layer(qp->device, attr.port_num) !=
2044                             IB_LINK_LAYER_INFINIBAND)
2045                                 return true;
2046                         goto lid_check;
2047                 }
2048         }
2049
2050         /* Can't get a quick answer, iterate over all ports */
2051         for (port = 0; port < qp->device->phys_port_cnt; port++)
2052                 if (rdma_port_get_link_layer(qp->device, port) !=
2053                     IB_LINK_LAYER_INFINIBAND)
2054                         num_eth_ports++;
2055
2056         /* If we have at lease one Ethernet port, RoCE annex declares that
2057          * multicast LID should be ignored. We can't tell at this step if the
2058          * QP belongs to an IB or Ethernet port.
2059          */
2060         if (num_eth_ports)
2061                 return true;
2062
2063         /* If all the ports are IB, we can check according to IB spec. */
2064 lid_check:
2065         return !(lid < be16_to_cpu(IB_MULTICAST_LID_BASE) ||
2066                  lid == be16_to_cpu(IB_LID_PERMISSIVE));
2067 }
2068
2069 int ib_attach_mcast(struct ib_qp *qp, union ib_gid *gid, u16 lid)
2070 {
2071         int ret;
2072
2073         if (!qp->device->attach_mcast)
2074                 return -EOPNOTSUPP;
2075
2076         if (!rdma_is_multicast_addr((struct in6_addr *)gid->raw) ||
2077             qp->qp_type != IB_QPT_UD || !is_valid_mcast_lid(qp, lid))
2078                 return -EINVAL;
2079
2080         ret = qp->device->attach_mcast(qp, gid, lid);
2081         if (!ret)
2082                 atomic_inc(&qp->usecnt);
2083         return ret;
2084 }
2085 EXPORT_SYMBOL(ib_attach_mcast);
2086
2087 int ib_detach_mcast(struct ib_qp *qp, union ib_gid *gid, u16 lid)
2088 {
2089         int ret;
2090
2091         if (!qp->device->detach_mcast)
2092                 return -EOPNOTSUPP;
2093
2094         if (!rdma_is_multicast_addr((struct in6_addr *)gid->raw) ||
2095             qp->qp_type != IB_QPT_UD || !is_valid_mcast_lid(qp, lid))
2096                 return -EINVAL;
2097
2098         ret = qp->device->detach_mcast(qp, gid, lid);
2099         if (!ret)
2100                 atomic_dec(&qp->usecnt);
2101         return ret;
2102 }
2103 EXPORT_SYMBOL(ib_detach_mcast);
2104
2105 struct ib_xrcd *__ib_alloc_xrcd(struct ib_device *device, const char *caller)
2106 {
2107         struct ib_xrcd *xrcd;
2108
2109         if (!device->alloc_xrcd)
2110                 return ERR_PTR(-EOPNOTSUPP);
2111
2112         xrcd = device->alloc_xrcd(device, NULL, NULL);
2113         if (!IS_ERR(xrcd)) {
2114                 xrcd->device = device;
2115                 xrcd->inode = NULL;
2116                 atomic_set(&xrcd->usecnt, 0);
2117                 mutex_init(&xrcd->tgt_qp_mutex);
2118                 INIT_LIST_HEAD(&xrcd->tgt_qp_list);
2119         }
2120
2121         return xrcd;
2122 }
2123 EXPORT_SYMBOL(__ib_alloc_xrcd);
2124
2125 int ib_dealloc_xrcd(struct ib_xrcd *xrcd)
2126 {
2127         struct ib_qp *qp;
2128         int ret;
2129
2130         if (atomic_read(&xrcd->usecnt))
2131                 return -EBUSY;
2132
2133         while (!list_empty(&xrcd->tgt_qp_list)) {
2134                 qp = list_entry(xrcd->tgt_qp_list.next, struct ib_qp, xrcd_list);
2135                 ret = ib_destroy_qp(qp);
2136                 if (ret)
2137                         return ret;
2138         }
2139
2140         return xrcd->device->dealloc_xrcd(xrcd);
2141 }
2142 EXPORT_SYMBOL(ib_dealloc_xrcd);
2143
2144 /**
2145  * ib_create_wq - Creates a WQ associated with the specified protection
2146  * domain.
2147  * @pd: The protection domain associated with the WQ.
2148  * @wq_attr: A list of initial attributes required to create the
2149  * WQ. If WQ creation succeeds, then the attributes are updated to
2150  * the actual capabilities of the created WQ.
2151  *
2152  * wq_attr->max_wr and wq_attr->max_sge determine
2153  * the requested size of the WQ, and set to the actual values allocated
2154  * on return.
2155  * If ib_create_wq() succeeds, then max_wr and max_sge will always be
2156  * at least as large as the requested values.
2157  */
2158 struct ib_wq *ib_create_wq(struct ib_pd *pd,
2159                            struct ib_wq_init_attr *wq_attr)
2160 {
2161         struct ib_wq *wq;
2162
2163         if (!pd->device->create_wq)
2164                 return ERR_PTR(-EOPNOTSUPP);
2165
2166         wq = pd->device->create_wq(pd, wq_attr, NULL);
2167         if (!IS_ERR(wq)) {
2168                 wq->event_handler = wq_attr->event_handler;
2169                 wq->wq_context = wq_attr->wq_context;
2170                 wq->wq_type = wq_attr->wq_type;
2171                 wq->cq = wq_attr->cq;
2172                 wq->device = pd->device;
2173                 wq->pd = pd;
2174                 wq->uobject = NULL;
2175                 atomic_inc(&pd->usecnt);
2176                 atomic_inc(&wq_attr->cq->usecnt);
2177                 atomic_set(&wq->usecnt, 0);
2178         }
2179         return wq;
2180 }
2181 EXPORT_SYMBOL(ib_create_wq);
2182
2183 /**
2184  * ib_destroy_wq - Destroys the specified WQ.
2185  * @wq: The WQ to destroy.
2186  */
2187 int ib_destroy_wq(struct ib_wq *wq)
2188 {
2189         int err;
2190         struct ib_cq *cq = wq->cq;
2191         struct ib_pd *pd = wq->pd;
2192
2193         if (atomic_read(&wq->usecnt))
2194                 return -EBUSY;
2195
2196         err = wq->device->destroy_wq(wq);
2197         if (!err) {
2198                 atomic_dec(&pd->usecnt);
2199                 atomic_dec(&cq->usecnt);
2200         }
2201         return err;
2202 }
2203 EXPORT_SYMBOL(ib_destroy_wq);
2204
2205 /**
2206  * ib_modify_wq - Modifies the specified WQ.
2207  * @wq: The WQ to modify.
2208  * @wq_attr: On input, specifies the WQ attributes to modify.
2209  * @wq_attr_mask: A bit-mask used to specify which attributes of the WQ
2210  *   are being modified.
2211  * On output, the current values of selected WQ attributes are returned.
2212  */
2213 int ib_modify_wq(struct ib_wq *wq, struct ib_wq_attr *wq_attr,
2214                  u32 wq_attr_mask)
2215 {
2216         int err;
2217
2218         if (!wq->device->modify_wq)
2219                 return -EOPNOTSUPP;
2220
2221         err = wq->device->modify_wq(wq, wq_attr, wq_attr_mask, NULL);
2222         return err;
2223 }
2224 EXPORT_SYMBOL(ib_modify_wq);
2225
2226 /*
2227  * ib_create_rwq_ind_table - Creates a RQ Indirection Table.
2228  * @device: The device on which to create the rwq indirection table.
2229  * @ib_rwq_ind_table_init_attr: A list of initial attributes required to
2230  * create the Indirection Table.
2231  *
2232  * Note: The life time of ib_rwq_ind_table_init_attr->ind_tbl is not less
2233  *      than the created ib_rwq_ind_table object and the caller is responsible
2234  *      for its memory allocation/free.
2235  */
2236 struct ib_rwq_ind_table *ib_create_rwq_ind_table(struct ib_device *device,
2237                                                  struct ib_rwq_ind_table_init_attr *init_attr)
2238 {
2239         struct ib_rwq_ind_table *rwq_ind_table;
2240         int i;
2241         u32 table_size;
2242
2243         if (!device->create_rwq_ind_table)
2244                 return ERR_PTR(-EOPNOTSUPP);
2245
2246         table_size = (1 << init_attr->log_ind_tbl_size);
2247         rwq_ind_table = device->create_rwq_ind_table(device,
2248                                 init_attr, NULL);
2249         if (IS_ERR(rwq_ind_table))
2250                 return rwq_ind_table;
2251
2252         rwq_ind_table->ind_tbl = init_attr->ind_tbl;
2253         rwq_ind_table->log_ind_tbl_size = init_attr->log_ind_tbl_size;
2254         rwq_ind_table->device = device;
2255         rwq_ind_table->uobject = NULL;
2256         atomic_set(&rwq_ind_table->usecnt, 0);
2257
2258         for (i = 0; i < table_size; i++)
2259                 atomic_inc(&rwq_ind_table->ind_tbl[i]->usecnt);
2260
2261         return rwq_ind_table;
2262 }
2263 EXPORT_SYMBOL(ib_create_rwq_ind_table);
2264
2265 /*
2266  * ib_destroy_rwq_ind_table - Destroys the specified Indirection Table.
2267  * @wq_ind_table: The Indirection Table to destroy.
2268 */
2269 int ib_destroy_rwq_ind_table(struct ib_rwq_ind_table *rwq_ind_table)
2270 {
2271         int err, i;
2272         u32 table_size = (1 << rwq_ind_table->log_ind_tbl_size);
2273         struct ib_wq **ind_tbl = rwq_ind_table->ind_tbl;
2274
2275         if (atomic_read(&rwq_ind_table->usecnt))
2276                 return -EBUSY;
2277
2278         err = rwq_ind_table->device->destroy_rwq_ind_table(rwq_ind_table);
2279         if (!err) {
2280                 for (i = 0; i < table_size; i++)
2281                         atomic_dec(&ind_tbl[i]->usecnt);
2282         }
2283
2284         return err;
2285 }
2286 EXPORT_SYMBOL(ib_destroy_rwq_ind_table);
2287
2288 int ib_check_mr_status(struct ib_mr *mr, u32 check_mask,
2289                        struct ib_mr_status *mr_status)
2290 {
2291         return mr->device->check_mr_status ?
2292                 mr->device->check_mr_status(mr, check_mask, mr_status) : -EOPNOTSUPP;
2293 }
2294 EXPORT_SYMBOL(ib_check_mr_status);
2295
2296 int ib_set_vf_link_state(struct ib_device *device, int vf, u8 port,
2297                          int state)
2298 {
2299         if (!device->set_vf_link_state)
2300                 return -EOPNOTSUPP;
2301
2302         return device->set_vf_link_state(device, vf, port, state);
2303 }
2304 EXPORT_SYMBOL(ib_set_vf_link_state);
2305
2306 int ib_get_vf_config(struct ib_device *device, int vf, u8 port,
2307                      struct ifla_vf_info *info)
2308 {
2309         if (!device->get_vf_config)
2310                 return -EOPNOTSUPP;
2311
2312         return device->get_vf_config(device, vf, port, info);
2313 }
2314 EXPORT_SYMBOL(ib_get_vf_config);
2315
2316 int ib_get_vf_stats(struct ib_device *device, int vf, u8 port,
2317                     struct ifla_vf_stats *stats)
2318 {
2319         if (!device->get_vf_stats)
2320                 return -EOPNOTSUPP;
2321
2322         return device->get_vf_stats(device, vf, port, stats);
2323 }
2324 EXPORT_SYMBOL(ib_get_vf_stats);
2325
2326 int ib_set_vf_guid(struct ib_device *device, int vf, u8 port, u64 guid,
2327                    int type)
2328 {
2329         if (!device->set_vf_guid)
2330                 return -EOPNOTSUPP;
2331
2332         return device->set_vf_guid(device, vf, port, guid, type);
2333 }
2334 EXPORT_SYMBOL(ib_set_vf_guid);
2335
2336 /**
2337  * ib_map_mr_sg() - Map the largest prefix of a dma mapped SG list
2338  *     and set it the memory region.
2339  * @mr:            memory region
2340  * @sg:            dma mapped scatterlist
2341  * @sg_nents:      number of entries in sg
2342  * @sg_offset:     offset in bytes into sg
2343  * @page_size:     page vector desired page size
2344  *
2345  * Constraints:
2346  * - The first sg element is allowed to have an offset.
2347  * - Each sg element must either be aligned to page_size or virtually
2348  *   contiguous to the previous element. In case an sg element has a
2349  *   non-contiguous offset, the mapping prefix will not include it.
2350  * - The last sg element is allowed to have length less than page_size.
2351  * - If sg_nents total byte length exceeds the mr max_num_sge * page_size
2352  *   then only max_num_sg entries will be mapped.
2353  * - If the MR was allocated with type IB_MR_TYPE_SG_GAPS, none of these
2354  *   constraints holds and the page_size argument is ignored.
2355  *
2356  * Returns the number of sg elements that were mapped to the memory region.
2357  *
2358  * After this completes successfully, the  memory region
2359  * is ready for registration.
2360  */
2361 int ib_map_mr_sg(struct ib_mr *mr, struct scatterlist *sg, int sg_nents,
2362                  unsigned int *sg_offset, unsigned int page_size)
2363 {
2364         if (unlikely(!mr->device->map_mr_sg))
2365                 return -EOPNOTSUPP;
2366
2367         mr->page_size = page_size;
2368
2369         return mr->device->map_mr_sg(mr, sg, sg_nents, sg_offset);
2370 }
2371 EXPORT_SYMBOL(ib_map_mr_sg);
2372
2373 /**
2374  * ib_sg_to_pages() - Convert the largest prefix of a sg list
2375  *     to a page vector
2376  * @mr:            memory region
2377  * @sgl:           dma mapped scatterlist
2378  * @sg_nents:      number of entries in sg
2379  * @sg_offset_p:   IN:  start offset in bytes into sg
2380  *                 OUT: offset in bytes for element n of the sg of the first
2381  *                      byte that has not been processed where n is the return
2382  *                      value of this function.
2383  * @set_page:      driver page assignment function pointer
2384  *
2385  * Core service helper for drivers to convert the largest
2386  * prefix of given sg list to a page vector. The sg list
2387  * prefix converted is the prefix that meet the requirements
2388  * of ib_map_mr_sg.
2389  *
2390  * Returns the number of sg elements that were assigned to
2391  * a page vector.
2392  */
2393 int ib_sg_to_pages(struct ib_mr *mr, struct scatterlist *sgl, int sg_nents,
2394                 unsigned int *sg_offset_p, int (*set_page)(struct ib_mr *, u64))
2395 {
2396         struct scatterlist *sg;
2397         u64 last_end_dma_addr = 0;
2398         unsigned int sg_offset = sg_offset_p ? *sg_offset_p : 0;
2399         unsigned int last_page_off = 0;
2400         u64 page_mask = ~((u64)mr->page_size - 1);
2401         int i, ret;
2402
2403         if (unlikely(sg_nents <= 0 || sg_offset > sg_dma_len(&sgl[0])))
2404                 return -EINVAL;
2405
2406         mr->iova = sg_dma_address(&sgl[0]) + sg_offset;
2407         mr->length = 0;
2408
2409         for_each_sg(sgl, sg, sg_nents, i) {
2410                 u64 dma_addr = sg_dma_address(sg) + sg_offset;
2411                 u64 prev_addr = dma_addr;
2412                 unsigned int dma_len = sg_dma_len(sg) - sg_offset;
2413                 u64 end_dma_addr = dma_addr + dma_len;
2414                 u64 page_addr = dma_addr & page_mask;
2415
2416                 /*
2417                  * For the second and later elements, check whether either the
2418                  * end of element i-1 or the start of element i is not aligned
2419                  * on a page boundary.
2420                  */
2421                 if (i && (last_page_off != 0 || page_addr != dma_addr)) {
2422                         /* Stop mapping if there is a gap. */
2423                         if (last_end_dma_addr != dma_addr)
2424                                 break;
2425
2426                         /*
2427                          * Coalesce this element with the last. If it is small
2428                          * enough just update mr->length. Otherwise start
2429                          * mapping from the next page.
2430                          */
2431                         goto next_page;
2432                 }
2433
2434                 do {
2435                         ret = set_page(mr, page_addr);
2436                         if (unlikely(ret < 0)) {
2437                                 sg_offset = prev_addr - sg_dma_address(sg);
2438                                 mr->length += prev_addr - dma_addr;
2439                                 if (sg_offset_p)
2440                                         *sg_offset_p = sg_offset;
2441                                 return i || sg_offset ? i : ret;
2442                         }
2443                         prev_addr = page_addr;
2444 next_page:
2445                         page_addr += mr->page_size;
2446                 } while (page_addr < end_dma_addr);
2447
2448                 mr->length += dma_len;
2449                 last_end_dma_addr = end_dma_addr;
2450                 last_page_off = end_dma_addr & ~page_mask;
2451
2452                 sg_offset = 0;
2453         }
2454
2455         if (sg_offset_p)
2456                 *sg_offset_p = 0;
2457         return i;
2458 }
2459 EXPORT_SYMBOL(ib_sg_to_pages);
2460
2461 struct ib_drain_cqe {
2462         struct ib_cqe cqe;
2463         struct completion done;
2464 };
2465
2466 static void ib_drain_qp_done(struct ib_cq *cq, struct ib_wc *wc)
2467 {
2468         struct ib_drain_cqe *cqe = container_of(wc->wr_cqe, struct ib_drain_cqe,
2469                                                 cqe);
2470
2471         complete(&cqe->done);
2472 }
2473
2474 /*
2475  * Post a WR and block until its completion is reaped for the SQ.
2476  */
2477 static void __ib_drain_sq(struct ib_qp *qp)
2478 {
2479         struct ib_cq *cq = qp->send_cq;
2480         struct ib_qp_attr attr = { .qp_state = IB_QPS_ERR };
2481         struct ib_drain_cqe sdrain;
2482         struct ib_rdma_wr swr = {
2483                 .wr = {
2484                         .next = NULL,
2485                         { .wr_cqe       = &sdrain.cqe, },
2486                         .opcode = IB_WR_RDMA_WRITE,
2487                 },
2488         };
2489         int ret;
2490
2491         ret = ib_modify_qp(qp, &attr, IB_QP_STATE);
2492         if (ret) {
2493                 WARN_ONCE(ret, "failed to drain send queue: %d\n", ret);
2494                 return;
2495         }
2496
2497         sdrain.cqe.done = ib_drain_qp_done;
2498         init_completion(&sdrain.done);
2499
2500         ret = ib_post_send(qp, &swr.wr, NULL);
2501         if (ret) {
2502                 WARN_ONCE(ret, "failed to drain send queue: %d\n", ret);
2503                 return;
2504         }
2505
2506         if (cq->poll_ctx == IB_POLL_DIRECT)
2507                 while (wait_for_completion_timeout(&sdrain.done, HZ / 10) <= 0)
2508                         ib_process_cq_direct(cq, -1);
2509         else
2510                 wait_for_completion(&sdrain.done);
2511 }
2512
2513 /*
2514  * Post a WR and block until its completion is reaped for the RQ.
2515  */
2516 static void __ib_drain_rq(struct ib_qp *qp)
2517 {
2518         struct ib_cq *cq = qp->recv_cq;
2519         struct ib_qp_attr attr = { .qp_state = IB_QPS_ERR };
2520         struct ib_drain_cqe rdrain;
2521         struct ib_recv_wr rwr = {};
2522         int ret;
2523
2524         ret = ib_modify_qp(qp, &attr, IB_QP_STATE);
2525         if (ret) {
2526                 WARN_ONCE(ret, "failed to drain recv queue: %d\n", ret);
2527                 return;
2528         }
2529
2530         rwr.wr_cqe = &rdrain.cqe;
2531         rdrain.cqe.done = ib_drain_qp_done;
2532         init_completion(&rdrain.done);
2533
2534         ret = ib_post_recv(qp, &rwr, NULL);
2535         if (ret) {
2536                 WARN_ONCE(ret, "failed to drain recv queue: %d\n", ret);
2537                 return;
2538         }
2539
2540         if (cq->poll_ctx == IB_POLL_DIRECT)
2541                 while (wait_for_completion_timeout(&rdrain.done, HZ / 10) <= 0)
2542                         ib_process_cq_direct(cq, -1);
2543         else
2544                 wait_for_completion(&rdrain.done);
2545 }
2546
2547 /**
2548  * ib_drain_sq() - Block until all SQ CQEs have been consumed by the
2549  *                 application.
2550  * @qp:            queue pair to drain
2551  *
2552  * If the device has a provider-specific drain function, then
2553  * call that.  Otherwise call the generic drain function
2554  * __ib_drain_sq().
2555  *
2556  * The caller must:
2557  *
2558  * ensure there is room in the CQ and SQ for the drain work request and
2559  * completion.
2560  *
2561  * allocate the CQ using ib_alloc_cq().
2562  *
2563  * ensure that there are no other contexts that are posting WRs concurrently.
2564  * Otherwise the drain is not guaranteed.
2565  */
2566 void ib_drain_sq(struct ib_qp *qp)
2567 {
2568         if (qp->device->drain_sq)
2569                 qp->device->drain_sq(qp);
2570         else
2571                 __ib_drain_sq(qp);
2572 }
2573 EXPORT_SYMBOL(ib_drain_sq);
2574
2575 /**
2576  * ib_drain_rq() - Block until all RQ CQEs have been consumed by the
2577  *                 application.
2578  * @qp:            queue pair to drain
2579  *
2580  * If the device has a provider-specific drain function, then
2581  * call that.  Otherwise call the generic drain function
2582  * __ib_drain_rq().
2583  *
2584  * The caller must:
2585  *
2586  * ensure there is room in the CQ and RQ for the drain work request and
2587  * completion.
2588  *
2589  * allocate the CQ using ib_alloc_cq().
2590  *
2591  * ensure that there are no other contexts that are posting WRs concurrently.
2592  * Otherwise the drain is not guaranteed.
2593  */
2594 void ib_drain_rq(struct ib_qp *qp)
2595 {
2596         if (qp->device->drain_rq)
2597                 qp->device->drain_rq(qp);
2598         else
2599                 __ib_drain_rq(qp);
2600 }
2601 EXPORT_SYMBOL(ib_drain_rq);
2602
2603 /**
2604  * ib_drain_qp() - Block until all CQEs have been consumed by the
2605  *                 application on both the RQ and SQ.
2606  * @qp:            queue pair to drain
2607  *
2608  * The caller must:
2609  *
2610  * ensure there is room in the CQ(s), SQ, and RQ for drain work requests
2611  * and completions.
2612  *
2613  * allocate the CQs using ib_alloc_cq().
2614  *
2615  * ensure that there are no other contexts that are posting WRs concurrently.
2616  * Otherwise the drain is not guaranteed.
2617  */
2618 void ib_drain_qp(struct ib_qp *qp)
2619 {
2620         ib_drain_sq(qp);
2621         if (!qp->srq)
2622                 ib_drain_rq(qp);
2623 }
2624 EXPORT_SYMBOL(ib_drain_qp);
2625
2626 struct net_device *rdma_alloc_netdev(struct ib_device *device, u8 port_num,
2627                                      enum rdma_netdev_t type, const char *name,
2628                                      unsigned char name_assign_type,
2629                                      void (*setup)(struct net_device *))
2630 {
2631         struct rdma_netdev_alloc_params params;
2632         struct net_device *netdev;
2633         int rc;
2634
2635         if (!device->rdma_netdev_get_params)
2636                 return ERR_PTR(-EOPNOTSUPP);
2637
2638         rc = device->rdma_netdev_get_params(device, port_num, type, &params);
2639         if (rc)
2640                 return ERR_PTR(rc);
2641
2642         netdev = alloc_netdev_mqs(params.sizeof_priv, name, name_assign_type,
2643                                   setup, params.txqs, params.rxqs);
2644         if (!netdev)
2645                 return ERR_PTR(-ENOMEM);
2646
2647         return netdev;
2648 }
2649 EXPORT_SYMBOL(rdma_alloc_netdev);
2650
2651 int rdma_init_netdev(struct ib_device *device, u8 port_num,
2652                      enum rdma_netdev_t type, const char *name,
2653                      unsigned char name_assign_type,
2654                      void (*setup)(struct net_device *),
2655                      struct net_device *netdev)
2656 {
2657         struct rdma_netdev_alloc_params params;
2658         int rc;
2659
2660         if (!device->rdma_netdev_get_params)
2661                 return -EOPNOTSUPP;
2662
2663         rc = device->rdma_netdev_get_params(device, port_num, type, &params);
2664         if (rc)
2665                 return rc;
2666
2667         return params.initialize_rdma_netdev(device, port_num,
2668                                              netdev, params.param);
2669 }
2670 EXPORT_SYMBOL(rdma_init_netdev);