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