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