xref: /linux/drivers/infiniband/core/cm.c (revision 9b2207bc5cdb955bdae34b3eec80f04979e17081)
1 // SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB
2 /*
3  * Copyright (c) 2004-2007 Intel Corporation.  All rights reserved.
4  * Copyright (c) 2004 Topspin Corporation.  All rights reserved.
5  * Copyright (c) 2004, 2005 Voltaire Corporation.  All rights reserved.
6  * Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
7  * Copyright (c) 2019, Mellanox Technologies inc.  All rights reserved.
8  */
9 
10 #include <linux/completion.h>
11 #include <linux/dma-mapping.h>
12 #include <linux/device.h>
13 #include <linux/module.h>
14 #include <linux/err.h>
15 #include <linux/idr.h>
16 #include <linux/interrupt.h>
17 #include <linux/random.h>
18 #include <linux/rbtree.h>
19 #include <linux/spinlock.h>
20 #include <linux/slab.h>
21 #include <linux/sysfs.h>
22 #include <linux/workqueue.h>
23 #include <linux/kdev_t.h>
24 #include <linux/etherdevice.h>
25 
26 #include <rdma/ib_cache.h>
27 #include <rdma/ib_cm.h>
28 #include <rdma/ib_sysfs.h>
29 #include "cm_msgs.h"
30 #include "core_priv.h"
31 #include "cm_trace.h"
32 
33 MODULE_AUTHOR("Sean Hefty");
34 MODULE_DESCRIPTION("InfiniBand CM");
35 MODULE_LICENSE("Dual BSD/GPL");
36 
37 #define CM_DIRECT_RETRY_CTX ((void *) 1UL)
38 #define CM_MRA_SETTING 24 /* 4.096us * 2^24 = ~68.7 seconds */
39 
40 static const char * const ibcm_rej_reason_strs[] = {
41 	[IB_CM_REJ_NO_QP]			= "no QP",
42 	[IB_CM_REJ_NO_EEC]			= "no EEC",
43 	[IB_CM_REJ_NO_RESOURCES]		= "no resources",
44 	[IB_CM_REJ_TIMEOUT]			= "timeout",
45 	[IB_CM_REJ_UNSUPPORTED]			= "unsupported",
46 	[IB_CM_REJ_INVALID_COMM_ID]		= "invalid comm ID",
47 	[IB_CM_REJ_INVALID_COMM_INSTANCE]	= "invalid comm instance",
48 	[IB_CM_REJ_INVALID_SERVICE_ID]		= "invalid service ID",
49 	[IB_CM_REJ_INVALID_TRANSPORT_TYPE]	= "invalid transport type",
50 	[IB_CM_REJ_STALE_CONN]			= "stale conn",
51 	[IB_CM_REJ_RDC_NOT_EXIST]		= "RDC not exist",
52 	[IB_CM_REJ_INVALID_GID]			= "invalid GID",
53 	[IB_CM_REJ_INVALID_LID]			= "invalid LID",
54 	[IB_CM_REJ_INVALID_SL]			= "invalid SL",
55 	[IB_CM_REJ_INVALID_TRAFFIC_CLASS]	= "invalid traffic class",
56 	[IB_CM_REJ_INVALID_HOP_LIMIT]		= "invalid hop limit",
57 	[IB_CM_REJ_INVALID_PACKET_RATE]		= "invalid packet rate",
58 	[IB_CM_REJ_INVALID_ALT_GID]		= "invalid alt GID",
59 	[IB_CM_REJ_INVALID_ALT_LID]		= "invalid alt LID",
60 	[IB_CM_REJ_INVALID_ALT_SL]		= "invalid alt SL",
61 	[IB_CM_REJ_INVALID_ALT_TRAFFIC_CLASS]	= "invalid alt traffic class",
62 	[IB_CM_REJ_INVALID_ALT_HOP_LIMIT]	= "invalid alt hop limit",
63 	[IB_CM_REJ_INVALID_ALT_PACKET_RATE]	= "invalid alt packet rate",
64 	[IB_CM_REJ_PORT_CM_REDIRECT]		= "port CM redirect",
65 	[IB_CM_REJ_PORT_REDIRECT]		= "port redirect",
66 	[IB_CM_REJ_INVALID_MTU]			= "invalid MTU",
67 	[IB_CM_REJ_INSUFFICIENT_RESP_RESOURCES]	= "insufficient resp resources",
68 	[IB_CM_REJ_CONSUMER_DEFINED]		= "consumer defined",
69 	[IB_CM_REJ_INVALID_RNR_RETRY]		= "invalid RNR retry",
70 	[IB_CM_REJ_DUPLICATE_LOCAL_COMM_ID]	= "duplicate local comm ID",
71 	[IB_CM_REJ_INVALID_CLASS_VERSION]	= "invalid class version",
72 	[IB_CM_REJ_INVALID_FLOW_LABEL]		= "invalid flow label",
73 	[IB_CM_REJ_INVALID_ALT_FLOW_LABEL]	= "invalid alt flow label",
74 	[IB_CM_REJ_VENDOR_OPTION_NOT_SUPPORTED] =
75 		"vendor option is not supported",
76 };
77 
78 const char *__attribute_const__ ibcm_reject_msg(int reason)
79 {
80 	size_t index = reason;
81 
82 	if (index < ARRAY_SIZE(ibcm_rej_reason_strs) &&
83 	    ibcm_rej_reason_strs[index])
84 		return ibcm_rej_reason_strs[index];
85 	else
86 		return "unrecognized reason";
87 }
88 EXPORT_SYMBOL(ibcm_reject_msg);
89 
90 struct cm_id_private;
91 struct cm_work;
92 static int cm_add_one(struct ib_device *device);
93 static void cm_remove_one(struct ib_device *device, void *client_data);
94 static void cm_process_work(struct cm_id_private *cm_id_priv,
95 			    struct cm_work *work);
96 static int cm_send_sidr_rep_locked(struct cm_id_private *cm_id_priv,
97 				   struct ib_cm_sidr_rep_param *param);
98 static void cm_issue_dreq(struct cm_id_private *cm_id_priv);
99 static int cm_send_drep_locked(struct cm_id_private *cm_id_priv,
100 			       void *private_data, u8 private_data_len);
101 static int cm_send_rej_locked(struct cm_id_private *cm_id_priv,
102 			      enum ib_cm_rej_reason reason, void *ari,
103 			      u8 ari_length, const void *private_data,
104 			      u8 private_data_len);
105 
106 static struct ib_client cm_client = {
107 	.name   = "cm",
108 	.add    = cm_add_one,
109 	.remove = cm_remove_one
110 };
111 
112 static struct ib_cm {
113 	spinlock_t lock;
114 	struct list_head device_list;
115 	rwlock_t device_lock;
116 	struct rb_root listen_service_table;
117 	u64 listen_service_id;
118 	/* struct rb_root peer_service_table; todo: fix peer to peer */
119 	struct rb_root remote_qp_table;
120 	struct rb_root remote_id_table;
121 	struct rb_root remote_sidr_table;
122 	struct xarray local_id_table;
123 	u32 local_id_next;
124 	__be32 random_id_operand;
125 	struct list_head timewait_list;
126 	struct workqueue_struct *wq;
127 } cm;
128 
129 /* Counter indexes ordered by attribute ID */
130 enum {
131 	CM_REQ_COUNTER,
132 	CM_MRA_COUNTER,
133 	CM_REJ_COUNTER,
134 	CM_REP_COUNTER,
135 	CM_RTU_COUNTER,
136 	CM_DREQ_COUNTER,
137 	CM_DREP_COUNTER,
138 	CM_SIDR_REQ_COUNTER,
139 	CM_SIDR_REP_COUNTER,
140 	CM_LAP_COUNTER,
141 	CM_APR_COUNTER,
142 	CM_ATTR_COUNT,
143 	CM_ATTR_ID_OFFSET = 0x0010,
144 };
145 
146 enum {
147 	CM_XMIT,
148 	CM_XMIT_RETRIES,
149 	CM_RECV,
150 	CM_RECV_DUPLICATES,
151 	CM_COUNTER_GROUPS
152 };
153 
154 struct cm_counter_attribute {
155 	struct ib_port_attribute attr;
156 	unsigned short group;
157 	unsigned short index;
158 };
159 
160 struct cm_port {
161 	struct cm_device *cm_dev;
162 	struct ib_mad_agent *mad_agent;
163 	struct ib_mad_agent *rep_agent;
164 	u32 port_num;
165 	atomic_long_t counters[CM_COUNTER_GROUPS][CM_ATTR_COUNT];
166 };
167 
168 struct cm_device {
169 	struct kref kref;
170 	struct list_head list;
171 	rwlock_t mad_agent_lock;
172 	struct ib_device *ib_device;
173 	u8 ack_delay;
174 	int going_down;
175 	struct cm_port *port[];
176 };
177 
178 struct cm_av {
179 	struct cm_port *port;
180 	struct rdma_ah_attr ah_attr;
181 	u16 dlid_datapath;
182 	u16 pkey_index;
183 	u8 timeout;
184 };
185 
186 struct cm_work {
187 	struct delayed_work work;
188 	struct list_head list;
189 	struct cm_port *port;
190 	struct ib_mad_recv_wc *mad_recv_wc;	/* Received MADs */
191 	__be32 local_id;			/* Established / timewait */
192 	__be32 remote_id;
193 	struct ib_cm_event cm_event;
194 	struct sa_path_rec path[];
195 };
196 
197 struct cm_timewait_info {
198 	struct cm_work work;
199 	struct list_head list;
200 	struct rb_node remote_qp_node;
201 	struct rb_node remote_id_node;
202 	__be64 remote_ca_guid;
203 	__be32 remote_qpn;
204 	u8 inserted_remote_qp;
205 	u8 inserted_remote_id;
206 };
207 
208 struct cm_id_private {
209 	struct ib_cm_id	id;
210 
211 	struct rb_node service_node;
212 	struct rb_node sidr_id_node;
213 	u32 sidr_slid;
214 	spinlock_t lock;	/* Do not acquire inside cm.lock */
215 	struct completion comp;
216 	refcount_t refcount;
217 	/* Number of clients sharing this ib_cm_id. Only valid for listeners.
218 	 * Protected by the cm.lock spinlock.
219 	 */
220 	int listen_sharecount;
221 	struct rcu_head rcu;
222 
223 	struct ib_mad_send_buf *msg;
224 	struct cm_timewait_info *timewait_info;
225 	/* todo: use alternate port on send failure */
226 	struct cm_av av;
227 	struct cm_av alt_av;
228 
229 	void *private_data;
230 	__be64 tid;
231 	__be32 local_qpn;
232 	__be32 remote_qpn;
233 	enum ib_qp_type qp_type;
234 	__be32 sq_psn;
235 	__be32 rq_psn;
236 	int timeout_ms;
237 	enum ib_mtu path_mtu;
238 	__be16 pkey;
239 	u8 private_data_len;
240 	u8 max_cm_retries;
241 	u8 responder_resources;
242 	u8 initiator_depth;
243 	u8 retry_count;
244 	u8 rnr_retry_count;
245 	u8 target_ack_delay;
246 
247 	struct list_head work_list;
248 	atomic_t work_count;
249 
250 	struct rdma_ucm_ece ece;
251 };
252 
253 static void cm_dev_release(struct kref *kref)
254 {
255 	struct cm_device *cm_dev = container_of(kref, struct cm_device, kref);
256 	u32 i;
257 
258 	rdma_for_each_port(cm_dev->ib_device, i)
259 		kfree(cm_dev->port[i - 1]);
260 
261 	kfree(cm_dev);
262 }
263 
264 static void cm_device_put(struct cm_device *cm_dev)
265 {
266 	kref_put(&cm_dev->kref, cm_dev_release);
267 }
268 
269 static void cm_work_handler(struct work_struct *work);
270 
271 static inline void cm_deref_id(struct cm_id_private *cm_id_priv)
272 {
273 	if (refcount_dec_and_test(&cm_id_priv->refcount))
274 		complete(&cm_id_priv->comp);
275 }
276 
277 static struct ib_mad_send_buf *
278 cm_alloc_msg_agent(struct cm_id_private *cm_id_priv, bool rep_agent)
279 {
280 	struct ib_mad_agent *mad_agent;
281 	struct ib_mad_send_buf *m;
282 	struct ib_ah *ah;
283 
284 	lockdep_assert_held(&cm_id_priv->lock);
285 
286 	if (!cm_id_priv->av.port)
287 		return ERR_PTR(-EINVAL);
288 
289 	read_lock(&cm_id_priv->av.port->cm_dev->mad_agent_lock);
290 	mad_agent = rep_agent ? cm_id_priv->av.port->rep_agent :
291 				cm_id_priv->av.port->mad_agent;
292 	if (!mad_agent) {
293 		m = ERR_PTR(-EINVAL);
294 		goto out;
295 	}
296 
297 	ah = rdma_create_ah(mad_agent->qp->pd, &cm_id_priv->av.ah_attr, 0);
298 	if (IS_ERR(ah)) {
299 		m = ERR_CAST(ah);
300 		goto out;
301 	}
302 
303 	m = ib_create_send_mad(mad_agent, cm_id_priv->id.remote_cm_qpn,
304 			       cm_id_priv->av.pkey_index,
305 			       0, IB_MGMT_MAD_HDR, IB_MGMT_MAD_DATA,
306 			       GFP_ATOMIC,
307 			       IB_MGMT_BASE_VERSION);
308 	if (IS_ERR(m)) {
309 		rdma_destroy_ah(ah, 0);
310 		goto out;
311 	}
312 
313 	m->ah = ah;
314 
315 out:
316 	read_unlock(&cm_id_priv->av.port->cm_dev->mad_agent_lock);
317 	return m;
318 }
319 
320 static struct ib_mad_send_buf *cm_alloc_msg(struct cm_id_private *cm_id_priv)
321 {
322 	return cm_alloc_msg_agent(cm_id_priv, false);
323 }
324 
325 static void cm_free_msg(struct ib_mad_send_buf *msg)
326 {
327 	if (msg->ah)
328 		rdma_destroy_ah(msg->ah, 0);
329 	ib_free_send_mad(msg);
330 }
331 
332 static struct ib_mad_send_buf *
333 cm_alloc_priv_msg_rep(struct cm_id_private *cm_id_priv, enum ib_cm_state state,
334 		      bool rep_agent)
335 {
336 	struct ib_mad_send_buf *msg;
337 
338 	lockdep_assert_held(&cm_id_priv->lock);
339 
340 	msg = cm_alloc_msg_agent(cm_id_priv, rep_agent);
341 	if (IS_ERR(msg))
342 		return msg;
343 
344 	cm_id_priv->msg = msg;
345 	refcount_inc(&cm_id_priv->refcount);
346 	msg->context[0] = cm_id_priv;
347 	msg->context[1] = (void *) (unsigned long) state;
348 
349 	msg->retries = cm_id_priv->max_cm_retries;
350 	msg->timeout_ms = cm_id_priv->timeout_ms;
351 
352 	return msg;
353 }
354 
355 static struct ib_mad_send_buf *
356 cm_alloc_priv_msg(struct cm_id_private *cm_id_priv, enum ib_cm_state state)
357 {
358 	return cm_alloc_priv_msg_rep(cm_id_priv, state, false);
359 }
360 
361 static void cm_free_priv_msg(struct ib_mad_send_buf *msg)
362 {
363 	struct cm_id_private *cm_id_priv = msg->context[0];
364 
365 	lockdep_assert_held(&cm_id_priv->lock);
366 
367 	if (!WARN_ON(cm_id_priv->msg != msg))
368 		cm_id_priv->msg = NULL;
369 
370 	if (msg->ah)
371 		rdma_destroy_ah(msg->ah, 0);
372 	cm_deref_id(cm_id_priv);
373 	ib_free_send_mad(msg);
374 }
375 
376 static struct ib_mad_send_buf *
377 cm_alloc_response_msg_no_ah(struct cm_port *port,
378 			    struct ib_mad_recv_wc *mad_recv_wc,
379 			    bool direct_retry)
380 {
381 	struct ib_mad_send_buf *m;
382 
383 	m = ib_create_send_mad(port->mad_agent, 1, mad_recv_wc->wc->pkey_index,
384 			       0, IB_MGMT_MAD_HDR, IB_MGMT_MAD_DATA,
385 			       GFP_ATOMIC, IB_MGMT_BASE_VERSION);
386 	if (!IS_ERR(m))
387 		m->context[0] = direct_retry ? CM_DIRECT_RETRY_CTX : NULL;
388 
389 	return m;
390 }
391 
392 static int cm_create_response_msg_ah(struct cm_port *port,
393 				     struct ib_mad_recv_wc *mad_recv_wc,
394 				     struct ib_mad_send_buf *msg)
395 {
396 	struct ib_ah *ah;
397 
398 	ah = ib_create_ah_from_wc(port->mad_agent->qp->pd, mad_recv_wc->wc,
399 				  mad_recv_wc->recv_buf.grh, port->port_num);
400 	if (IS_ERR(ah))
401 		return PTR_ERR(ah);
402 
403 	msg->ah = ah;
404 	return 0;
405 }
406 
407 static int cm_alloc_response_msg(struct cm_port *port,
408 				 struct ib_mad_recv_wc *mad_recv_wc,
409 				 bool direct_retry,
410 				 struct ib_mad_send_buf **msg)
411 {
412 	struct ib_mad_send_buf *m;
413 	int ret;
414 
415 	m = cm_alloc_response_msg_no_ah(port, mad_recv_wc, direct_retry);
416 	if (IS_ERR(m))
417 		return PTR_ERR(m);
418 
419 	ret = cm_create_response_msg_ah(port, mad_recv_wc, m);
420 	if (ret) {
421 		ib_free_send_mad(m);
422 		return ret;
423 	}
424 
425 	*msg = m;
426 	return 0;
427 }
428 
429 static void *cm_copy_private_data(const void *private_data, u8 private_data_len)
430 {
431 	void *data;
432 
433 	if (!private_data || !private_data_len)
434 		return NULL;
435 
436 	data = kmemdup(private_data, private_data_len, GFP_KERNEL);
437 	if (!data)
438 		return ERR_PTR(-ENOMEM);
439 
440 	return data;
441 }
442 
443 static void cm_set_private_data(struct cm_id_private *cm_id_priv,
444 				 void *private_data, u8 private_data_len)
445 {
446 	if (cm_id_priv->private_data && cm_id_priv->private_data_len)
447 		kfree(cm_id_priv->private_data);
448 
449 	cm_id_priv->private_data = private_data;
450 	cm_id_priv->private_data_len = private_data_len;
451 }
452 
453 static void cm_set_av_port(struct cm_av *av, struct cm_port *port)
454 {
455 	struct cm_port *old_port = av->port;
456 
457 	if (old_port == port)
458 		return;
459 
460 	av->port = port;
461 	if (old_port)
462 		cm_device_put(old_port->cm_dev);
463 	if (port)
464 		kref_get(&port->cm_dev->kref);
465 }
466 
467 static void cm_init_av_for_lap(struct cm_port *port, struct ib_wc *wc,
468 			       struct rdma_ah_attr *ah_attr, struct cm_av *av)
469 {
470 	cm_set_av_port(av, port);
471 	av->pkey_index = wc->pkey_index;
472 	rdma_move_ah_attr(&av->ah_attr, ah_attr);
473 }
474 
475 static int cm_init_av_for_response(struct cm_port *port, struct ib_wc *wc,
476 				   struct ib_grh *grh, struct cm_av *av)
477 {
478 	cm_set_av_port(av, port);
479 	av->pkey_index = wc->pkey_index;
480 	return ib_init_ah_attr_from_wc(port->cm_dev->ib_device,
481 				       port->port_num, wc,
482 				       grh, &av->ah_attr);
483 }
484 
485 static struct cm_port *
486 get_cm_port_from_path(struct sa_path_rec *path, const struct ib_gid_attr *attr)
487 {
488 	struct cm_device *cm_dev;
489 	struct cm_port *port = NULL;
490 	unsigned long flags;
491 
492 	if (attr) {
493 		read_lock_irqsave(&cm.device_lock, flags);
494 		list_for_each_entry(cm_dev, &cm.device_list, list) {
495 			if (cm_dev->ib_device == attr->device) {
496 				port = cm_dev->port[attr->port_num - 1];
497 				break;
498 			}
499 		}
500 		read_unlock_irqrestore(&cm.device_lock, flags);
501 	} else {
502 		/* SGID attribute can be NULL in following
503 		 * conditions.
504 		 * (a) Alternative path
505 		 * (b) IB link layer without GRH
506 		 * (c) LAP send messages
507 		 */
508 		read_lock_irqsave(&cm.device_lock, flags);
509 		list_for_each_entry(cm_dev, &cm.device_list, list) {
510 			attr = rdma_find_gid(cm_dev->ib_device,
511 					     &path->sgid,
512 					     sa_conv_pathrec_to_gid_type(path),
513 					     NULL);
514 			if (!IS_ERR(attr)) {
515 				port = cm_dev->port[attr->port_num - 1];
516 				break;
517 			}
518 		}
519 		read_unlock_irqrestore(&cm.device_lock, flags);
520 		if (port)
521 			rdma_put_gid_attr(attr);
522 	}
523 	return port;
524 }
525 
526 static int cm_init_av_by_path(struct sa_path_rec *path,
527 			      const struct ib_gid_attr *sgid_attr,
528 			      struct cm_av *av)
529 {
530 	struct rdma_ah_attr new_ah_attr;
531 	struct cm_device *cm_dev;
532 	struct cm_port *port;
533 	u16 pkey_index;
534 	int ret;
535 
536 	port = get_cm_port_from_path(path, sgid_attr);
537 	if (!port)
538 		return -EINVAL;
539 	cm_dev = port->cm_dev;
540 
541 	ret = ib_find_cached_pkey(cm_dev->ib_device, port->port_num,
542 				  be16_to_cpu(path->pkey), &pkey_index);
543 	if (ret)
544 		return ret;
545 
546 	/*
547 	 * av->ah_attr might be initialized based on wc or during
548 	 * request processing time which might have reference to sgid_attr.
549 	 * So initialize a new ah_attr on stack.
550 	 * If initialization fails, old ah_attr is used for sending any
551 	 * responses. If initialization is successful, than new ah_attr
552 	 * is used by overwriting the old one. So that right ah_attr
553 	 * can be used to return an error response.
554 	 */
555 	ret = ib_init_ah_attr_from_path(cm_dev->ib_device, port->port_num, path,
556 					&new_ah_attr, sgid_attr);
557 	if (ret)
558 		return ret;
559 
560 	av->pkey_index = pkey_index;
561 	cm_set_av_port(av, port);
562 	av->timeout = path->packet_life_time + 1;
563 	rdma_move_ah_attr(&av->ah_attr, &new_ah_attr);
564 	return 0;
565 }
566 
567 /* Move av created by cm_init_av_by_path(), so av.dgid is not moved */
568 static void cm_move_av_from_path(struct cm_av *dest, struct cm_av *src)
569 {
570 	cm_set_av_port(dest, src->port);
571 	cm_set_av_port(src, NULL);
572 	dest->pkey_index = src->pkey_index;
573 	rdma_move_ah_attr(&dest->ah_attr, &src->ah_attr);
574 	dest->timeout = src->timeout;
575 }
576 
577 static void cm_destroy_av(struct cm_av *av)
578 {
579 	rdma_destroy_ah_attr(&av->ah_attr);
580 	cm_set_av_port(av, NULL);
581 }
582 
583 static u32 cm_local_id(__be32 local_id)
584 {
585 	return (__force u32) (local_id ^ cm.random_id_operand);
586 }
587 
588 static struct cm_id_private *cm_acquire_id(__be32 local_id, __be32 remote_id)
589 {
590 	struct cm_id_private *cm_id_priv;
591 
592 	rcu_read_lock();
593 	cm_id_priv = xa_load(&cm.local_id_table, cm_local_id(local_id));
594 	if (!cm_id_priv || cm_id_priv->id.remote_id != remote_id ||
595 	    !refcount_inc_not_zero(&cm_id_priv->refcount))
596 		cm_id_priv = NULL;
597 	rcu_read_unlock();
598 
599 	return cm_id_priv;
600 }
601 
602 /*
603  * Trivial helpers to strip endian annotation and compare; the
604  * endianness doesn't actually matter since we just need a stable
605  * order for the RB tree.
606  */
607 static int be32_lt(__be32 a, __be32 b)
608 {
609 	return (__force u32) a < (__force u32) b;
610 }
611 
612 static int be32_gt(__be32 a, __be32 b)
613 {
614 	return (__force u32) a > (__force u32) b;
615 }
616 
617 static int be64_lt(__be64 a, __be64 b)
618 {
619 	return (__force u64) a < (__force u64) b;
620 }
621 
622 static int be64_gt(__be64 a, __be64 b)
623 {
624 	return (__force u64) a > (__force u64) b;
625 }
626 
627 /*
628  * Inserts a new cm_id_priv into the listen_service_table. Returns cm_id_priv
629  * if the new ID was inserted, NULL if it could not be inserted due to a
630  * collision, or the existing cm_id_priv ready for shared usage.
631  */
632 static struct cm_id_private *cm_insert_listen(struct cm_id_private *cm_id_priv,
633 					      ib_cm_handler shared_handler)
634 {
635 	struct rb_node **link = &cm.listen_service_table.rb_node;
636 	struct rb_node *parent = NULL;
637 	struct cm_id_private *cur_cm_id_priv;
638 	__be64 service_id = cm_id_priv->id.service_id;
639 	unsigned long flags;
640 
641 	spin_lock_irqsave(&cm.lock, flags);
642 	while (*link) {
643 		parent = *link;
644 		cur_cm_id_priv = rb_entry(parent, struct cm_id_private,
645 					  service_node);
646 
647 		if (cm_id_priv->id.device < cur_cm_id_priv->id.device)
648 			link = &(*link)->rb_left;
649 		else if (cm_id_priv->id.device > cur_cm_id_priv->id.device)
650 			link = &(*link)->rb_right;
651 		else if (be64_lt(service_id, cur_cm_id_priv->id.service_id))
652 			link = &(*link)->rb_left;
653 		else if (be64_gt(service_id, cur_cm_id_priv->id.service_id))
654 			link = &(*link)->rb_right;
655 		else {
656 			/*
657 			 * Sharing an ib_cm_id with different handlers is not
658 			 * supported
659 			 */
660 			if (cur_cm_id_priv->id.cm_handler != shared_handler ||
661 			    cur_cm_id_priv->id.context ||
662 			    WARN_ON(!cur_cm_id_priv->id.cm_handler)) {
663 				spin_unlock_irqrestore(&cm.lock, flags);
664 				return NULL;
665 			}
666 			refcount_inc(&cur_cm_id_priv->refcount);
667 			cur_cm_id_priv->listen_sharecount++;
668 			spin_unlock_irqrestore(&cm.lock, flags);
669 			return cur_cm_id_priv;
670 		}
671 	}
672 	cm_id_priv->listen_sharecount++;
673 	rb_link_node(&cm_id_priv->service_node, parent, link);
674 	rb_insert_color(&cm_id_priv->service_node, &cm.listen_service_table);
675 	spin_unlock_irqrestore(&cm.lock, flags);
676 	return cm_id_priv;
677 }
678 
679 static struct cm_id_private *cm_find_listen(struct ib_device *device,
680 					    __be64 service_id)
681 {
682 	struct rb_node *node = cm.listen_service_table.rb_node;
683 	struct cm_id_private *cm_id_priv;
684 
685 	while (node) {
686 		cm_id_priv = rb_entry(node, struct cm_id_private, service_node);
687 
688 		if (device < cm_id_priv->id.device)
689 			node = node->rb_left;
690 		else if (device > cm_id_priv->id.device)
691 			node = node->rb_right;
692 		else if (be64_lt(service_id, cm_id_priv->id.service_id))
693 			node = node->rb_left;
694 		else if (be64_gt(service_id, cm_id_priv->id.service_id))
695 			node = node->rb_right;
696 		else {
697 			refcount_inc(&cm_id_priv->refcount);
698 			return cm_id_priv;
699 		}
700 	}
701 	return NULL;
702 }
703 
704 static struct cm_timewait_info *
705 cm_insert_remote_id(struct cm_timewait_info *timewait_info)
706 {
707 	struct rb_node **link = &cm.remote_id_table.rb_node;
708 	struct rb_node *parent = NULL;
709 	struct cm_timewait_info *cur_timewait_info;
710 	__be64 remote_ca_guid = timewait_info->remote_ca_guid;
711 	__be32 remote_id = timewait_info->work.remote_id;
712 
713 	while (*link) {
714 		parent = *link;
715 		cur_timewait_info = rb_entry(parent, struct cm_timewait_info,
716 					     remote_id_node);
717 		if (be32_lt(remote_id, cur_timewait_info->work.remote_id))
718 			link = &(*link)->rb_left;
719 		else if (be32_gt(remote_id, cur_timewait_info->work.remote_id))
720 			link = &(*link)->rb_right;
721 		else if (be64_lt(remote_ca_guid, cur_timewait_info->remote_ca_guid))
722 			link = &(*link)->rb_left;
723 		else if (be64_gt(remote_ca_guid, cur_timewait_info->remote_ca_guid))
724 			link = &(*link)->rb_right;
725 		else
726 			return cur_timewait_info;
727 	}
728 	timewait_info->inserted_remote_id = 1;
729 	rb_link_node(&timewait_info->remote_id_node, parent, link);
730 	rb_insert_color(&timewait_info->remote_id_node, &cm.remote_id_table);
731 	return NULL;
732 }
733 
734 static struct cm_id_private *cm_find_remote_id(__be64 remote_ca_guid,
735 					       __be32 remote_id)
736 {
737 	struct rb_node *node = cm.remote_id_table.rb_node;
738 	struct cm_timewait_info *timewait_info;
739 	struct cm_id_private *res = NULL;
740 
741 	spin_lock_irq(&cm.lock);
742 	while (node) {
743 		timewait_info = rb_entry(node, struct cm_timewait_info,
744 					 remote_id_node);
745 		if (be32_lt(remote_id, timewait_info->work.remote_id))
746 			node = node->rb_left;
747 		else if (be32_gt(remote_id, timewait_info->work.remote_id))
748 			node = node->rb_right;
749 		else if (be64_lt(remote_ca_guid, timewait_info->remote_ca_guid))
750 			node = node->rb_left;
751 		else if (be64_gt(remote_ca_guid, timewait_info->remote_ca_guid))
752 			node = node->rb_right;
753 		else {
754 			res = cm_acquire_id(timewait_info->work.local_id,
755 					     timewait_info->work.remote_id);
756 			break;
757 		}
758 	}
759 	spin_unlock_irq(&cm.lock);
760 	return res;
761 }
762 
763 static struct cm_timewait_info *
764 cm_insert_remote_qpn(struct cm_timewait_info *timewait_info)
765 {
766 	struct rb_node **link = &cm.remote_qp_table.rb_node;
767 	struct rb_node *parent = NULL;
768 	struct cm_timewait_info *cur_timewait_info;
769 	__be64 remote_ca_guid = timewait_info->remote_ca_guid;
770 	__be32 remote_qpn = timewait_info->remote_qpn;
771 
772 	while (*link) {
773 		parent = *link;
774 		cur_timewait_info = rb_entry(parent, struct cm_timewait_info,
775 					     remote_qp_node);
776 		if (be32_lt(remote_qpn, cur_timewait_info->remote_qpn))
777 			link = &(*link)->rb_left;
778 		else if (be32_gt(remote_qpn, cur_timewait_info->remote_qpn))
779 			link = &(*link)->rb_right;
780 		else if (be64_lt(remote_ca_guid, cur_timewait_info->remote_ca_guid))
781 			link = &(*link)->rb_left;
782 		else if (be64_gt(remote_ca_guid, cur_timewait_info->remote_ca_guid))
783 			link = &(*link)->rb_right;
784 		else
785 			return cur_timewait_info;
786 	}
787 	timewait_info->inserted_remote_qp = 1;
788 	rb_link_node(&timewait_info->remote_qp_node, parent, link);
789 	rb_insert_color(&timewait_info->remote_qp_node, &cm.remote_qp_table);
790 	return NULL;
791 }
792 
793 static struct cm_id_private *
794 cm_insert_remote_sidr(struct cm_id_private *cm_id_priv)
795 {
796 	struct rb_node **link = &cm.remote_sidr_table.rb_node;
797 	struct rb_node *parent = NULL;
798 	struct cm_id_private *cur_cm_id_priv;
799 	__be32 remote_id = cm_id_priv->id.remote_id;
800 
801 	while (*link) {
802 		parent = *link;
803 		cur_cm_id_priv = rb_entry(parent, struct cm_id_private,
804 					  sidr_id_node);
805 		if (be32_lt(remote_id, cur_cm_id_priv->id.remote_id))
806 			link = &(*link)->rb_left;
807 		else if (be32_gt(remote_id, cur_cm_id_priv->id.remote_id))
808 			link = &(*link)->rb_right;
809 		else {
810 			if (cur_cm_id_priv->sidr_slid < cm_id_priv->sidr_slid)
811 				link = &(*link)->rb_left;
812 			else if (cur_cm_id_priv->sidr_slid > cm_id_priv->sidr_slid)
813 				link = &(*link)->rb_right;
814 			else
815 				return cur_cm_id_priv;
816 		}
817 	}
818 	rb_link_node(&cm_id_priv->sidr_id_node, parent, link);
819 	rb_insert_color(&cm_id_priv->sidr_id_node, &cm.remote_sidr_table);
820 	return NULL;
821 }
822 
823 static struct cm_id_private *cm_alloc_id_priv(struct ib_device *device,
824 					      ib_cm_handler cm_handler,
825 					      void *context)
826 {
827 	struct cm_id_private *cm_id_priv;
828 	u32 id;
829 	int ret;
830 
831 	cm_id_priv = kzalloc_obj(*cm_id_priv);
832 	if (!cm_id_priv)
833 		return ERR_PTR(-ENOMEM);
834 
835 	cm_id_priv->id.state = IB_CM_IDLE;
836 	cm_id_priv->id.device = device;
837 	cm_id_priv->id.cm_handler = cm_handler;
838 	cm_id_priv->id.context = context;
839 	cm_id_priv->id.remote_cm_qpn = 1;
840 
841 	RB_CLEAR_NODE(&cm_id_priv->service_node);
842 	RB_CLEAR_NODE(&cm_id_priv->sidr_id_node);
843 	spin_lock_init(&cm_id_priv->lock);
844 	init_completion(&cm_id_priv->comp);
845 	INIT_LIST_HEAD(&cm_id_priv->work_list);
846 	atomic_set(&cm_id_priv->work_count, -1);
847 	refcount_set(&cm_id_priv->refcount, 1);
848 
849 	ret = xa_alloc_cyclic(&cm.local_id_table, &id, NULL, xa_limit_32b,
850 			      &cm.local_id_next, GFP_KERNEL);
851 	if (ret < 0)
852 		goto error;
853 	cm_id_priv->id.local_id = (__force __be32)id ^ cm.random_id_operand;
854 
855 	return cm_id_priv;
856 
857 error:
858 	kfree(cm_id_priv);
859 	return ERR_PTR(ret);
860 }
861 
862 /*
863  * Make the ID visible to the MAD handlers and other threads that use the
864  * xarray.
865  */
866 static void cm_finalize_id(struct cm_id_private *cm_id_priv)
867 {
868 	xa_store(&cm.local_id_table, cm_local_id(cm_id_priv->id.local_id),
869 		 cm_id_priv, GFP_ATOMIC);
870 }
871 
872 struct ib_cm_id *ib_create_cm_id(struct ib_device *device,
873 				 ib_cm_handler cm_handler,
874 				 void *context)
875 {
876 	struct cm_id_private *cm_id_priv;
877 
878 	cm_id_priv = cm_alloc_id_priv(device, cm_handler, context);
879 	if (IS_ERR(cm_id_priv))
880 		return ERR_CAST(cm_id_priv);
881 
882 	cm_finalize_id(cm_id_priv);
883 	return &cm_id_priv->id;
884 }
885 EXPORT_SYMBOL(ib_create_cm_id);
886 
887 static struct cm_work *cm_dequeue_work(struct cm_id_private *cm_id_priv)
888 {
889 	struct cm_work *work;
890 
891 	if (list_empty(&cm_id_priv->work_list))
892 		return NULL;
893 
894 	work = list_entry(cm_id_priv->work_list.next, struct cm_work, list);
895 	list_del(&work->list);
896 	return work;
897 }
898 
899 static void cm_free_work(struct cm_work *work)
900 {
901 	if (work->mad_recv_wc)
902 		ib_free_recv_mad(work->mad_recv_wc);
903 	kfree(work);
904 }
905 
906 static void cm_queue_work_unlock(struct cm_id_private *cm_id_priv,
907 				 struct cm_work *work)
908 	__releases(&cm_id_priv->lock)
909 {
910 	bool immediate;
911 
912 	/*
913 	 * To deliver the event to the user callback we have the drop the
914 	 * spinlock, however, we need to ensure that the user callback is single
915 	 * threaded and receives events in the temporal order. If there are
916 	 * already events being processed then thread new events onto a list,
917 	 * the thread currently processing will pick them up.
918 	 */
919 	immediate = atomic_inc_and_test(&cm_id_priv->work_count);
920 	if (!immediate) {
921 		list_add_tail(&work->list, &cm_id_priv->work_list);
922 		/*
923 		 * This routine always consumes incoming reference. Once queued
924 		 * to the work_list then a reference is held by the thread
925 		 * currently running cm_process_work() and this reference is not
926 		 * needed.
927 		 */
928 		cm_deref_id(cm_id_priv);
929 	}
930 	spin_unlock_irq(&cm_id_priv->lock);
931 
932 	if (immediate)
933 		cm_process_work(cm_id_priv, work);
934 }
935 
936 static inline int cm_convert_to_ms(int iba_time)
937 {
938 	/* approximate conversion to ms from 4.096us x 2^iba_time */
939 	return 1 << max(iba_time - 8, 0);
940 }
941 
942 /*
943  * calculate: 4.096x2^ack_timeout = 4.096x2^ack_delay + 2x4.096x2^life_time
944  * Because of how ack_timeout is stored, adding one doubles the timeout.
945  * To avoid large timeouts, select the max(ack_delay, life_time + 1), and
946  * increment it (round up) only if the other is within 50%.
947  */
948 static u8 cm_ack_timeout(u8 ca_ack_delay, u8 packet_life_time)
949 {
950 	int ack_timeout = packet_life_time + 1;
951 
952 	if (ack_timeout >= ca_ack_delay)
953 		ack_timeout += (ca_ack_delay >= (ack_timeout - 1));
954 	else
955 		ack_timeout = ca_ack_delay +
956 			      (ack_timeout >= (ca_ack_delay - 1));
957 
958 	return min(31, ack_timeout);
959 }
960 
961 static void cm_remove_remote(struct cm_id_private *cm_id_priv)
962 {
963 	struct cm_timewait_info *timewait_info = cm_id_priv->timewait_info;
964 
965 	if (timewait_info->inserted_remote_id) {
966 		rb_erase(&timewait_info->remote_id_node, &cm.remote_id_table);
967 		timewait_info->inserted_remote_id = 0;
968 	}
969 
970 	if (timewait_info->inserted_remote_qp) {
971 		rb_erase(&timewait_info->remote_qp_node, &cm.remote_qp_table);
972 		timewait_info->inserted_remote_qp = 0;
973 	}
974 }
975 
976 static struct cm_timewait_info *cm_create_timewait_info(__be32 local_id)
977 {
978 	struct cm_timewait_info *timewait_info;
979 
980 	timewait_info = kzalloc_obj(*timewait_info);
981 	if (!timewait_info)
982 		return ERR_PTR(-ENOMEM);
983 
984 	timewait_info->work.local_id = local_id;
985 	INIT_DELAYED_WORK(&timewait_info->work.work, cm_work_handler);
986 	timewait_info->work.cm_event.event = IB_CM_TIMEWAIT_EXIT;
987 	return timewait_info;
988 }
989 
990 static void cm_enter_timewait(struct cm_id_private *cm_id_priv)
991 {
992 	int wait_time;
993 	unsigned long flags;
994 	struct cm_device *cm_dev;
995 
996 	lockdep_assert_held(&cm_id_priv->lock);
997 
998 	cm_dev = ib_get_client_data(cm_id_priv->id.device, &cm_client);
999 	if (!cm_dev)
1000 		return;
1001 
1002 	spin_lock_irqsave(&cm.lock, flags);
1003 	cm_remove_remote(cm_id_priv);
1004 	list_add_tail(&cm_id_priv->timewait_info->list, &cm.timewait_list);
1005 	spin_unlock_irqrestore(&cm.lock, flags);
1006 
1007 	/*
1008 	 * The cm_id could be destroyed by the user before we exit timewait.
1009 	 * To protect against this, we search for the cm_id after exiting
1010 	 * timewait before notifying the user that we've exited timewait.
1011 	 */
1012 	cm_id_priv->id.state = IB_CM_TIMEWAIT;
1013 	wait_time = cm_convert_to_ms(cm_id_priv->av.timeout);
1014 
1015 	/* Check if the device started its remove_one */
1016 	spin_lock_irqsave(&cm.lock, flags);
1017 	if (!cm_dev->going_down)
1018 		queue_delayed_work(cm.wq, &cm_id_priv->timewait_info->work.work,
1019 				   msecs_to_jiffies(wait_time));
1020 	spin_unlock_irqrestore(&cm.lock, flags);
1021 
1022 	/*
1023 	 * The timewait_info is converted into a work and gets freed during
1024 	 * cm_free_work() in cm_timewait_handler().
1025 	 */
1026 	BUILD_BUG_ON(offsetof(struct cm_timewait_info, work) != 0);
1027 	cm_id_priv->timewait_info = NULL;
1028 }
1029 
1030 static void cm_reset_to_idle(struct cm_id_private *cm_id_priv)
1031 {
1032 	unsigned long flags;
1033 
1034 	lockdep_assert_held(&cm_id_priv->lock);
1035 
1036 	cm_id_priv->id.state = IB_CM_IDLE;
1037 	if (cm_id_priv->timewait_info) {
1038 		spin_lock_irqsave(&cm.lock, flags);
1039 		cm_remove_remote(cm_id_priv);
1040 		spin_unlock_irqrestore(&cm.lock, flags);
1041 		kfree(cm_id_priv->timewait_info);
1042 		cm_id_priv->timewait_info = NULL;
1043 	}
1044 }
1045 
1046 static noinline void cm_destroy_id_wait_timeout(struct ib_cm_id *cm_id,
1047 						enum ib_cm_state old_state)
1048 {
1049 	struct cm_id_private *cm_id_priv;
1050 
1051 	cm_id_priv = container_of(cm_id, struct cm_id_private, id);
1052 	pr_err_ratelimited("%s: cm_id=%p timed out. state %d -> %d, refcnt=%d\n", __func__,
1053 			   cm_id, old_state, cm_id->state, refcount_read(&cm_id_priv->refcount));
1054 }
1055 
1056 static void cm_destroy_id(struct ib_cm_id *cm_id, int err)
1057 {
1058 	struct cm_id_private *cm_id_priv;
1059 	enum ib_cm_state old_state;
1060 	unsigned long timeout;
1061 	struct cm_work *work;
1062 	int ret;
1063 
1064 	cm_id_priv = container_of(cm_id, struct cm_id_private, id);
1065 	spin_lock_irq(&cm_id_priv->lock);
1066 	old_state = cm_id->state;
1067 retest:
1068 	switch (cm_id->state) {
1069 	case IB_CM_LISTEN:
1070 		spin_lock(&cm.lock);
1071 		if (--cm_id_priv->listen_sharecount > 0) {
1072 			/* The id is still shared. */
1073 			WARN_ON(refcount_read(&cm_id_priv->refcount) == 1);
1074 			spin_unlock(&cm.lock);
1075 			spin_unlock_irq(&cm_id_priv->lock);
1076 			cm_deref_id(cm_id_priv);
1077 			return;
1078 		}
1079 		cm_id->state = IB_CM_IDLE;
1080 		rb_erase(&cm_id_priv->service_node, &cm.listen_service_table);
1081 		RB_CLEAR_NODE(&cm_id_priv->service_node);
1082 		spin_unlock(&cm.lock);
1083 		break;
1084 	case IB_CM_SIDR_REQ_SENT:
1085 		cm_id->state = IB_CM_IDLE;
1086 		ib_cancel_mad(cm_id_priv->msg);
1087 		break;
1088 	case IB_CM_SIDR_REQ_RCVD:
1089 		cm_send_sidr_rep_locked(cm_id_priv,
1090 					&(struct ib_cm_sidr_rep_param){
1091 						.status = IB_SIDR_REJECT });
1092 		/* cm_send_sidr_rep_locked will not move to IDLE if it fails */
1093 		cm_id->state = IB_CM_IDLE;
1094 		break;
1095 	case IB_CM_REQ_SENT:
1096 	case IB_CM_MRA_REQ_RCVD:
1097 		ib_cancel_mad(cm_id_priv->msg);
1098 		cm_send_rej_locked(cm_id_priv, IB_CM_REJ_TIMEOUT,
1099 				   &cm_id_priv->id.device->node_guid,
1100 				   sizeof(cm_id_priv->id.device->node_guid),
1101 				   NULL, 0);
1102 		break;
1103 	case IB_CM_REQ_RCVD:
1104 		if (err == -ENOMEM) {
1105 			/* Do not reject to allow future retries. */
1106 			cm_reset_to_idle(cm_id_priv);
1107 		} else {
1108 			cm_send_rej_locked(cm_id_priv,
1109 					   IB_CM_REJ_CONSUMER_DEFINED, NULL, 0,
1110 					   NULL, 0);
1111 		}
1112 		break;
1113 	case IB_CM_REP_SENT:
1114 	case IB_CM_MRA_REP_RCVD:
1115 		ib_cancel_mad(cm_id_priv->msg);
1116 		cm_send_rej_locked(cm_id_priv, IB_CM_REJ_CONSUMER_DEFINED, NULL,
1117 				   0, NULL, 0);
1118 		goto retest;
1119 	case IB_CM_MRA_REQ_SENT:
1120 	case IB_CM_REP_RCVD:
1121 	case IB_CM_MRA_REP_SENT:
1122 		cm_send_rej_locked(cm_id_priv, IB_CM_REJ_CONSUMER_DEFINED, NULL,
1123 				   0, NULL, 0);
1124 		break;
1125 	case IB_CM_ESTABLISHED:
1126 		if (cm_id_priv->qp_type == IB_QPT_XRC_TGT) {
1127 			cm_id->state = IB_CM_IDLE;
1128 			break;
1129 		}
1130 		cm_issue_dreq(cm_id_priv);
1131 		cm_enter_timewait(cm_id_priv);
1132 		goto retest;
1133 	case IB_CM_DREQ_SENT:
1134 		ib_cancel_mad(cm_id_priv->msg);
1135 		cm_enter_timewait(cm_id_priv);
1136 		goto retest;
1137 	case IB_CM_DREQ_RCVD:
1138 		cm_send_drep_locked(cm_id_priv, NULL, 0);
1139 		WARN_ON(cm_id->state != IB_CM_TIMEWAIT);
1140 		goto retest;
1141 	case IB_CM_TIMEWAIT:
1142 		/*
1143 		 * The cm_acquire_id in cm_timewait_handler will stop working
1144 		 * once we do xa_erase below, so just move to idle here for
1145 		 * consistency.
1146 		 */
1147 		cm_id->state = IB_CM_IDLE;
1148 		break;
1149 	case IB_CM_IDLE:
1150 		break;
1151 	}
1152 	WARN_ON(cm_id->state != IB_CM_IDLE);
1153 
1154 	spin_lock(&cm.lock);
1155 	/* Required for cleanup paths related cm_req_handler() */
1156 	if (cm_id_priv->timewait_info) {
1157 		cm_remove_remote(cm_id_priv);
1158 		kfree(cm_id_priv->timewait_info);
1159 		cm_id_priv->timewait_info = NULL;
1160 	}
1161 
1162 	WARN_ON(cm_id_priv->listen_sharecount);
1163 	WARN_ON(!RB_EMPTY_NODE(&cm_id_priv->service_node));
1164 	if (!RB_EMPTY_NODE(&cm_id_priv->sidr_id_node))
1165 		rb_erase(&cm_id_priv->sidr_id_node, &cm.remote_sidr_table);
1166 	spin_unlock(&cm.lock);
1167 	spin_unlock_irq(&cm_id_priv->lock);
1168 
1169 	xa_erase(&cm.local_id_table, cm_local_id(cm_id->local_id));
1170 	cm_deref_id(cm_id_priv);
1171 	timeout = msecs_to_jiffies((cm_id_priv->max_cm_retries * cm_id_priv->timeout_ms * 5) / 4);
1172 	do {
1173 		ret = wait_for_completion_timeout(&cm_id_priv->comp, timeout);
1174 		if (!ret) /* timeout happened */
1175 			cm_destroy_id_wait_timeout(cm_id, old_state);
1176 	} while (!ret);
1177 
1178 	while ((work = cm_dequeue_work(cm_id_priv)) != NULL)
1179 		cm_free_work(work);
1180 
1181 	cm_destroy_av(&cm_id_priv->av);
1182 	cm_destroy_av(&cm_id_priv->alt_av);
1183 	kfree(cm_id_priv->private_data);
1184 	kfree_rcu(cm_id_priv, rcu);
1185 }
1186 
1187 void ib_destroy_cm_id(struct ib_cm_id *cm_id)
1188 {
1189 	cm_destroy_id(cm_id, 0);
1190 }
1191 EXPORT_SYMBOL(ib_destroy_cm_id);
1192 
1193 static int cm_init_listen(struct cm_id_private *cm_id_priv, __be64 service_id)
1194 {
1195 	if ((service_id & IB_SERVICE_ID_AGN_MASK) == IB_CM_ASSIGN_SERVICE_ID &&
1196 	    (service_id != IB_CM_ASSIGN_SERVICE_ID))
1197 		return -EINVAL;
1198 
1199 	if (service_id == IB_CM_ASSIGN_SERVICE_ID)
1200 		cm_id_priv->id.service_id = cpu_to_be64(cm.listen_service_id++);
1201 	else
1202 		cm_id_priv->id.service_id = service_id;
1203 
1204 	return 0;
1205 }
1206 
1207 /**
1208  * ib_cm_listen - Initiates listening on the specified service ID for
1209  *   connection and service ID resolution requests.
1210  * @cm_id: Connection identifier associated with the listen request.
1211  * @service_id: Service identifier matched against incoming connection
1212  *   and service ID resolution requests.  The service ID should be specified
1213  *   network-byte order.  If set to IB_CM_ASSIGN_SERVICE_ID, the CM will
1214  *   assign a service ID to the caller.
1215  */
1216 int ib_cm_listen(struct ib_cm_id *cm_id, __be64 service_id)
1217 {
1218 	struct cm_id_private *cm_id_priv =
1219 		container_of(cm_id, struct cm_id_private, id);
1220 	unsigned long flags;
1221 	int ret;
1222 
1223 	spin_lock_irqsave(&cm_id_priv->lock, flags);
1224 	if (cm_id_priv->id.state != IB_CM_IDLE) {
1225 		ret = -EINVAL;
1226 		goto out;
1227 	}
1228 
1229 	ret = cm_init_listen(cm_id_priv, service_id);
1230 	if (ret)
1231 		goto out;
1232 
1233 	if (!cm_insert_listen(cm_id_priv, NULL)) {
1234 		ret = -EBUSY;
1235 		goto out;
1236 	}
1237 
1238 	cm_id_priv->id.state = IB_CM_LISTEN;
1239 	ret = 0;
1240 
1241 out:
1242 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
1243 	return ret;
1244 }
1245 EXPORT_SYMBOL(ib_cm_listen);
1246 
1247 /**
1248  * ib_cm_insert_listen - Create a new listening ib_cm_id and listen on
1249  *			 the given service ID.
1250  *
1251  * If there's an existing ID listening on that same device and service ID,
1252  * return it.
1253  *
1254  * @device: Device associated with the cm_id.  All related communication will
1255  * be associated with the specified device.
1256  * @cm_handler: Callback invoked to notify the user of CM events.
1257  * @service_id: Service identifier matched against incoming connection
1258  *   and service ID resolution requests.  The service ID should be specified
1259  *   network-byte order.  If set to IB_CM_ASSIGN_SERVICE_ID, the CM will
1260  *   assign a service ID to the caller.
1261  *
1262  * Callers should call ib_destroy_cm_id when done with the listener ID.
1263  */
1264 struct ib_cm_id *ib_cm_insert_listen(struct ib_device *device,
1265 				     ib_cm_handler cm_handler,
1266 				     __be64 service_id)
1267 {
1268 	struct cm_id_private *listen_id_priv;
1269 	struct cm_id_private *cm_id_priv;
1270 	int err = 0;
1271 
1272 	/* Create an ID in advance, since the creation may sleep */
1273 	cm_id_priv = cm_alloc_id_priv(device, cm_handler, NULL);
1274 	if (IS_ERR(cm_id_priv))
1275 		return ERR_CAST(cm_id_priv);
1276 
1277 	err = cm_init_listen(cm_id_priv, service_id);
1278 	if (err) {
1279 		ib_destroy_cm_id(&cm_id_priv->id);
1280 		return ERR_PTR(err);
1281 	}
1282 
1283 	spin_lock_irq(&cm_id_priv->lock);
1284 	listen_id_priv = cm_insert_listen(cm_id_priv, cm_handler);
1285 	if (listen_id_priv != cm_id_priv) {
1286 		spin_unlock_irq(&cm_id_priv->lock);
1287 		ib_destroy_cm_id(&cm_id_priv->id);
1288 		if (!listen_id_priv)
1289 			return ERR_PTR(-EINVAL);
1290 		return &listen_id_priv->id;
1291 	}
1292 	cm_id_priv->id.state = IB_CM_LISTEN;
1293 	spin_unlock_irq(&cm_id_priv->lock);
1294 
1295 	/*
1296 	 * A listen ID does not need to be in the xarray since it does not
1297 	 * receive mads, is not placed in the remote_id or remote_qpn rbtree,
1298 	 * and does not enter timewait.
1299 	 */
1300 
1301 	return &cm_id_priv->id;
1302 }
1303 EXPORT_SYMBOL(ib_cm_insert_listen);
1304 
1305 static __be64 cm_form_tid(struct cm_id_private *cm_id_priv)
1306 {
1307 	u64 hi_tid = 0, low_tid;
1308 
1309 	lockdep_assert_held(&cm_id_priv->lock);
1310 
1311 	low_tid = (u64)cm_id_priv->id.local_id;
1312 	if (!cm_id_priv->av.port)
1313 		return cpu_to_be64(low_tid);
1314 
1315 	read_lock(&cm_id_priv->av.port->cm_dev->mad_agent_lock);
1316 	if (cm_id_priv->av.port->mad_agent)
1317 		hi_tid = ((u64)cm_id_priv->av.port->mad_agent->hi_tid) << 32;
1318 	read_unlock(&cm_id_priv->av.port->cm_dev->mad_agent_lock);
1319 	return cpu_to_be64(hi_tid | low_tid);
1320 }
1321 
1322 static void cm_format_mad_hdr(struct ib_mad_hdr *hdr,
1323 			      __be16 attr_id, __be64 tid)
1324 {
1325 	hdr->base_version  = IB_MGMT_BASE_VERSION;
1326 	hdr->mgmt_class	   = IB_MGMT_CLASS_CM;
1327 	hdr->class_version = IB_CM_CLASS_VERSION;
1328 	hdr->method	   = IB_MGMT_METHOD_SEND;
1329 	hdr->attr_id	   = attr_id;
1330 	hdr->tid	   = tid;
1331 }
1332 
1333 static void cm_format_mad_ece_hdr(struct ib_mad_hdr *hdr, __be16 attr_id,
1334 				  __be64 tid, u32 attr_mod)
1335 {
1336 	cm_format_mad_hdr(hdr, attr_id, tid);
1337 	hdr->attr_mod = cpu_to_be32(attr_mod);
1338 }
1339 
1340 static void cm_format_req(struct cm_req_msg *req_msg,
1341 			  struct cm_id_private *cm_id_priv,
1342 			  struct ib_cm_req_param *param)
1343 {
1344 	struct sa_path_rec *pri_path = param->primary_path;
1345 	struct sa_path_rec *alt_path = param->alternate_path;
1346 	bool pri_ext = false;
1347 	__be16 lid;
1348 
1349 	if (pri_path->rec_type == SA_PATH_REC_TYPE_OPA)
1350 		pri_ext = opa_is_extended_lid(pri_path->opa.dlid,
1351 					      pri_path->opa.slid);
1352 
1353 	cm_format_mad_ece_hdr(&req_msg->hdr, CM_REQ_ATTR_ID,
1354 			      cm_form_tid(cm_id_priv), param->ece.attr_mod);
1355 
1356 	IBA_SET(CM_REQ_LOCAL_COMM_ID, req_msg,
1357 		be32_to_cpu(cm_id_priv->id.local_id));
1358 	IBA_SET(CM_REQ_SERVICE_ID, req_msg, be64_to_cpu(param->service_id));
1359 	IBA_SET(CM_REQ_LOCAL_CA_GUID, req_msg,
1360 		be64_to_cpu(cm_id_priv->id.device->node_guid));
1361 	IBA_SET(CM_REQ_LOCAL_QPN, req_msg, param->qp_num);
1362 	IBA_SET(CM_REQ_INITIATOR_DEPTH, req_msg, param->initiator_depth);
1363 	IBA_SET(CM_REQ_REMOTE_CM_RESPONSE_TIMEOUT, req_msg,
1364 		param->remote_cm_response_timeout);
1365 	cm_req_set_qp_type(req_msg, param->qp_type);
1366 	IBA_SET(CM_REQ_END_TO_END_FLOW_CONTROL, req_msg, param->flow_control);
1367 	IBA_SET(CM_REQ_STARTING_PSN, req_msg, param->starting_psn);
1368 	IBA_SET(CM_REQ_LOCAL_CM_RESPONSE_TIMEOUT, req_msg,
1369 		param->local_cm_response_timeout);
1370 	IBA_SET(CM_REQ_PARTITION_KEY, req_msg,
1371 		be16_to_cpu(param->primary_path->pkey));
1372 	IBA_SET(CM_REQ_PATH_PACKET_PAYLOAD_MTU, req_msg,
1373 		param->primary_path->mtu);
1374 	IBA_SET(CM_REQ_MAX_CM_RETRIES, req_msg, param->max_cm_retries);
1375 
1376 	if (param->qp_type != IB_QPT_XRC_INI) {
1377 		IBA_SET(CM_REQ_RESPONDER_RESOURCES, req_msg,
1378 			param->responder_resources);
1379 		IBA_SET(CM_REQ_RETRY_COUNT, req_msg, param->retry_count);
1380 		IBA_SET(CM_REQ_RNR_RETRY_COUNT, req_msg,
1381 			param->rnr_retry_count);
1382 		IBA_SET(CM_REQ_SRQ, req_msg, param->srq);
1383 	}
1384 
1385 	*IBA_GET_MEM_PTR(CM_REQ_PRIMARY_LOCAL_PORT_GID, req_msg) =
1386 		pri_path->sgid;
1387 	*IBA_GET_MEM_PTR(CM_REQ_PRIMARY_REMOTE_PORT_GID, req_msg) =
1388 		pri_path->dgid;
1389 	if (pri_ext) {
1390 		IBA_GET_MEM_PTR(CM_REQ_PRIMARY_LOCAL_PORT_GID, req_msg)
1391 			->global.interface_id =
1392 			OPA_MAKE_ID(be32_to_cpu(pri_path->opa.slid));
1393 		IBA_GET_MEM_PTR(CM_REQ_PRIMARY_REMOTE_PORT_GID, req_msg)
1394 			->global.interface_id =
1395 			OPA_MAKE_ID(be32_to_cpu(pri_path->opa.dlid));
1396 	}
1397 	if (pri_path->hop_limit <= 1) {
1398 		IBA_SET(CM_REQ_PRIMARY_LOCAL_PORT_LID, req_msg,
1399 			be16_to_cpu(pri_ext ? 0 :
1400 					      htons(ntohl(sa_path_get_slid(
1401 						      pri_path)))));
1402 		IBA_SET(CM_REQ_PRIMARY_REMOTE_PORT_LID, req_msg,
1403 			be16_to_cpu(pri_ext ? 0 :
1404 					      htons(ntohl(sa_path_get_dlid(
1405 						      pri_path)))));
1406 	} else {
1407 
1408 		if (param->primary_path_inbound) {
1409 			lid = param->primary_path_inbound->ib.dlid;
1410 			IBA_SET(CM_REQ_PRIMARY_LOCAL_PORT_LID, req_msg,
1411 				be16_to_cpu(lid));
1412 		} else
1413 			IBA_SET(CM_REQ_PRIMARY_LOCAL_PORT_LID, req_msg,
1414 				be16_to_cpu(IB_LID_PERMISSIVE));
1415 
1416 		/* Work-around until there's a way to obtain remote LID info */
1417 		IBA_SET(CM_REQ_PRIMARY_REMOTE_PORT_LID, req_msg,
1418 			be16_to_cpu(IB_LID_PERMISSIVE));
1419 	}
1420 	IBA_SET(CM_REQ_PRIMARY_FLOW_LABEL, req_msg,
1421 		be32_to_cpu(pri_path->flow_label));
1422 	IBA_SET(CM_REQ_PRIMARY_PACKET_RATE, req_msg, pri_path->rate);
1423 	IBA_SET(CM_REQ_PRIMARY_TRAFFIC_CLASS, req_msg, pri_path->traffic_class);
1424 	IBA_SET(CM_REQ_PRIMARY_HOP_LIMIT, req_msg, pri_path->hop_limit);
1425 	IBA_SET(CM_REQ_PRIMARY_SL, req_msg, pri_path->sl);
1426 	IBA_SET(CM_REQ_PRIMARY_SUBNET_LOCAL, req_msg,
1427 		(pri_path->hop_limit <= 1));
1428 	IBA_SET(CM_REQ_PRIMARY_LOCAL_ACK_TIMEOUT, req_msg,
1429 		cm_ack_timeout(cm_id_priv->av.port->cm_dev->ack_delay,
1430 			       pri_path->packet_life_time));
1431 
1432 	if (alt_path) {
1433 		bool alt_ext = false;
1434 
1435 		if (alt_path->rec_type == SA_PATH_REC_TYPE_OPA)
1436 			alt_ext = opa_is_extended_lid(alt_path->opa.dlid,
1437 						      alt_path->opa.slid);
1438 
1439 		*IBA_GET_MEM_PTR(CM_REQ_ALTERNATE_LOCAL_PORT_GID, req_msg) =
1440 			alt_path->sgid;
1441 		*IBA_GET_MEM_PTR(CM_REQ_ALTERNATE_REMOTE_PORT_GID, req_msg) =
1442 			alt_path->dgid;
1443 		if (alt_ext) {
1444 			IBA_GET_MEM_PTR(CM_REQ_ALTERNATE_LOCAL_PORT_GID,
1445 					req_msg)
1446 				->global.interface_id =
1447 				OPA_MAKE_ID(be32_to_cpu(alt_path->opa.slid));
1448 			IBA_GET_MEM_PTR(CM_REQ_ALTERNATE_REMOTE_PORT_GID,
1449 					req_msg)
1450 				->global.interface_id =
1451 				OPA_MAKE_ID(be32_to_cpu(alt_path->opa.dlid));
1452 		}
1453 		if (alt_path->hop_limit <= 1) {
1454 			IBA_SET(CM_REQ_ALTERNATE_LOCAL_PORT_LID, req_msg,
1455 				be16_to_cpu(
1456 					alt_ext ? 0 :
1457 						  htons(ntohl(sa_path_get_slid(
1458 							  alt_path)))));
1459 			IBA_SET(CM_REQ_ALTERNATE_REMOTE_PORT_LID, req_msg,
1460 				be16_to_cpu(
1461 					alt_ext ? 0 :
1462 						  htons(ntohl(sa_path_get_dlid(
1463 							  alt_path)))));
1464 		} else {
1465 			IBA_SET(CM_REQ_ALTERNATE_LOCAL_PORT_LID, req_msg,
1466 				be16_to_cpu(IB_LID_PERMISSIVE));
1467 			IBA_SET(CM_REQ_ALTERNATE_REMOTE_PORT_LID, req_msg,
1468 				be16_to_cpu(IB_LID_PERMISSIVE));
1469 		}
1470 		IBA_SET(CM_REQ_ALTERNATE_FLOW_LABEL, req_msg,
1471 			be32_to_cpu(alt_path->flow_label));
1472 		IBA_SET(CM_REQ_ALTERNATE_PACKET_RATE, req_msg, alt_path->rate);
1473 		IBA_SET(CM_REQ_ALTERNATE_TRAFFIC_CLASS, req_msg,
1474 			alt_path->traffic_class);
1475 		IBA_SET(CM_REQ_ALTERNATE_HOP_LIMIT, req_msg,
1476 			alt_path->hop_limit);
1477 		IBA_SET(CM_REQ_ALTERNATE_SL, req_msg, alt_path->sl);
1478 		IBA_SET(CM_REQ_ALTERNATE_SUBNET_LOCAL, req_msg,
1479 			(alt_path->hop_limit <= 1));
1480 		IBA_SET(CM_REQ_ALTERNATE_LOCAL_ACK_TIMEOUT, req_msg,
1481 			cm_ack_timeout(cm_id_priv->av.port->cm_dev->ack_delay,
1482 				       alt_path->packet_life_time));
1483 	}
1484 	IBA_SET(CM_REQ_VENDOR_ID, req_msg, param->ece.vendor_id);
1485 
1486 	if (param->private_data && param->private_data_len)
1487 		IBA_SET_MEM(CM_REQ_PRIVATE_DATA, req_msg, param->private_data,
1488 			    param->private_data_len);
1489 }
1490 
1491 static int cm_validate_req_param(struct ib_cm_req_param *param)
1492 {
1493 	if (!param->primary_path)
1494 		return -EINVAL;
1495 
1496 	if (param->qp_type != IB_QPT_RC && param->qp_type != IB_QPT_UC &&
1497 	    param->qp_type != IB_QPT_XRC_INI)
1498 		return -EINVAL;
1499 
1500 	if (param->private_data &&
1501 	    param->private_data_len > IB_CM_REQ_PRIVATE_DATA_SIZE)
1502 		return -EINVAL;
1503 
1504 	if (param->alternate_path &&
1505 	    (param->alternate_path->pkey != param->primary_path->pkey ||
1506 	     param->alternate_path->mtu != param->primary_path->mtu))
1507 		return -EINVAL;
1508 
1509 	return 0;
1510 }
1511 
1512 int ib_send_cm_req(struct ib_cm_id *cm_id,
1513 		   struct ib_cm_req_param *param)
1514 {
1515 	struct cm_av av = {}, alt_av = {};
1516 	struct cm_id_private *cm_id_priv;
1517 	struct ib_mad_send_buf *msg;
1518 	struct cm_req_msg *req_msg;
1519 	unsigned long flags;
1520 	int ret;
1521 
1522 	ret = cm_validate_req_param(param);
1523 	if (ret)
1524 		return ret;
1525 
1526 	/* Verify that we're not in timewait. */
1527 	cm_id_priv = container_of(cm_id, struct cm_id_private, id);
1528 	spin_lock_irqsave(&cm_id_priv->lock, flags);
1529 	if (cm_id->state != IB_CM_IDLE || WARN_ON(cm_id_priv->timewait_info)) {
1530 		spin_unlock_irqrestore(&cm_id_priv->lock, flags);
1531 		return -EINVAL;
1532 	}
1533 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
1534 
1535 	cm_id_priv->timewait_info = cm_create_timewait_info(cm_id_priv->
1536 							    id.local_id);
1537 	if (IS_ERR(cm_id_priv->timewait_info)) {
1538 		ret = PTR_ERR(cm_id_priv->timewait_info);
1539 		cm_id_priv->timewait_info = NULL;
1540 		return ret;
1541 	}
1542 
1543 	ret = cm_init_av_by_path(param->primary_path,
1544 				 param->ppath_sgid_attr, &av);
1545 	if (ret)
1546 		return ret;
1547 	if (param->alternate_path) {
1548 		ret = cm_init_av_by_path(param->alternate_path, NULL,
1549 					 &alt_av);
1550 		if (ret) {
1551 			cm_destroy_av(&av);
1552 			return ret;
1553 		}
1554 	}
1555 	cm_id->service_id = param->service_id;
1556 	cm_id_priv->timeout_ms = cm_convert_to_ms(
1557 				    param->primary_path->packet_life_time) * 2 +
1558 				 cm_convert_to_ms(
1559 				    param->remote_cm_response_timeout);
1560 	cm_id_priv->max_cm_retries = param->max_cm_retries;
1561 	cm_id_priv->initiator_depth = param->initiator_depth;
1562 	cm_id_priv->responder_resources = param->responder_resources;
1563 	cm_id_priv->retry_count = param->retry_count;
1564 	cm_id_priv->path_mtu = param->primary_path->mtu;
1565 	cm_id_priv->pkey = param->primary_path->pkey;
1566 	cm_id_priv->qp_type = param->qp_type;
1567 
1568 	spin_lock_irqsave(&cm_id_priv->lock, flags);
1569 
1570 	cm_move_av_from_path(&cm_id_priv->av, &av);
1571 	if (param->primary_path_outbound)
1572 		cm_id_priv->av.dlid_datapath =
1573 			be16_to_cpu(param->primary_path_outbound->ib.dlid);
1574 
1575 	if (param->alternate_path)
1576 		cm_move_av_from_path(&cm_id_priv->alt_av, &alt_av);
1577 
1578 	msg = cm_alloc_priv_msg(cm_id_priv, IB_CM_REQ_SENT);
1579 	if (IS_ERR(msg)) {
1580 		ret = PTR_ERR(msg);
1581 		goto out_unlock;
1582 	}
1583 
1584 	req_msg = (struct cm_req_msg *)msg->mad;
1585 	cm_format_req(req_msg, cm_id_priv, param);
1586 	cm_id_priv->tid = req_msg->hdr.tid;
1587 
1588 	cm_id_priv->local_qpn = cpu_to_be32(IBA_GET(CM_REQ_LOCAL_QPN, req_msg));
1589 	cm_id_priv->rq_psn = cpu_to_be32(IBA_GET(CM_REQ_STARTING_PSN, req_msg));
1590 
1591 	trace_icm_send_req(&cm_id_priv->id);
1592 	ret = ib_post_send_mad(msg, NULL);
1593 	if (ret)
1594 		goto out_free;
1595 	BUG_ON(cm_id->state != IB_CM_IDLE);
1596 	cm_id->state = IB_CM_REQ_SENT;
1597 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
1598 	return 0;
1599 out_free:
1600 	cm_free_priv_msg(msg);
1601 out_unlock:
1602 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
1603 	return ret;
1604 }
1605 EXPORT_SYMBOL(ib_send_cm_req);
1606 
1607 static int cm_issue_rej(struct cm_port *port,
1608 			struct ib_mad_recv_wc *mad_recv_wc,
1609 			enum ib_cm_rej_reason reason,
1610 			enum cm_msg_response msg_rejected,
1611 			void *ari, u8 ari_length)
1612 {
1613 	struct ib_mad_send_buf *msg = NULL;
1614 	struct cm_rej_msg *rej_msg, *rcv_msg;
1615 	int ret;
1616 
1617 	ret = cm_alloc_response_msg(port, mad_recv_wc, false, &msg);
1618 	if (ret)
1619 		return ret;
1620 
1621 	/* We just need common CM header information.  Cast to any message. */
1622 	rcv_msg = (struct cm_rej_msg *) mad_recv_wc->recv_buf.mad;
1623 	rej_msg = (struct cm_rej_msg *) msg->mad;
1624 
1625 	cm_format_mad_hdr(&rej_msg->hdr, CM_REJ_ATTR_ID, rcv_msg->hdr.tid);
1626 	IBA_SET(CM_REJ_REMOTE_COMM_ID, rej_msg,
1627 		IBA_GET(CM_REJ_LOCAL_COMM_ID, rcv_msg));
1628 	IBA_SET(CM_REJ_LOCAL_COMM_ID, rej_msg,
1629 		IBA_GET(CM_REJ_REMOTE_COMM_ID, rcv_msg));
1630 	IBA_SET(CM_REJ_MESSAGE_REJECTED, rej_msg, msg_rejected);
1631 	IBA_SET(CM_REJ_REASON, rej_msg, reason);
1632 
1633 	if (ari && ari_length) {
1634 		IBA_SET(CM_REJ_REJECTED_INFO_LENGTH, rej_msg, ari_length);
1635 		IBA_SET_MEM(CM_REJ_ARI, rej_msg, ari, ari_length);
1636 	}
1637 
1638 	trace_icm_issue_rej(
1639 		IBA_GET(CM_REJ_LOCAL_COMM_ID, rcv_msg),
1640 		IBA_GET(CM_REJ_REMOTE_COMM_ID, rcv_msg));
1641 	ret = ib_post_send_mad(msg, NULL);
1642 	if (ret)
1643 		cm_free_msg(msg);
1644 
1645 	return ret;
1646 }
1647 
1648 static bool cm_req_has_alt_path(struct cm_req_msg *req_msg)
1649 {
1650 	return ((cpu_to_be16(
1651 			IBA_GET(CM_REQ_ALTERNATE_LOCAL_PORT_LID, req_msg))) ||
1652 		(ib_is_opa_gid(IBA_GET_MEM_PTR(CM_REQ_ALTERNATE_LOCAL_PORT_GID,
1653 					       req_msg))));
1654 }
1655 
1656 static void cm_path_set_rec_type(struct ib_device *ib_device, u32 port_num,
1657 				 struct sa_path_rec *path, union ib_gid *gid)
1658 {
1659 	if (ib_is_opa_gid(gid) && rdma_cap_opa_ah(ib_device, port_num))
1660 		path->rec_type = SA_PATH_REC_TYPE_OPA;
1661 	else
1662 		path->rec_type = SA_PATH_REC_TYPE_IB;
1663 }
1664 
1665 static void cm_format_path_lid_from_req(struct cm_req_msg *req_msg,
1666 					struct sa_path_rec *primary_path,
1667 					struct sa_path_rec *alt_path,
1668 					struct ib_wc *wc)
1669 {
1670 	u32 lid;
1671 
1672 	if (primary_path->rec_type != SA_PATH_REC_TYPE_OPA) {
1673 		sa_path_set_dlid(primary_path, wc->slid);
1674 		sa_path_set_slid(primary_path,
1675 				 IBA_GET(CM_REQ_PRIMARY_REMOTE_PORT_LID,
1676 					 req_msg));
1677 	} else {
1678 		lid = opa_get_lid_from_gid(IBA_GET_MEM_PTR(
1679 			CM_REQ_PRIMARY_LOCAL_PORT_GID, req_msg));
1680 		sa_path_set_dlid(primary_path, lid);
1681 
1682 		lid = opa_get_lid_from_gid(IBA_GET_MEM_PTR(
1683 			CM_REQ_PRIMARY_REMOTE_PORT_GID, req_msg));
1684 		sa_path_set_slid(primary_path, lid);
1685 	}
1686 
1687 	if (!cm_req_has_alt_path(req_msg))
1688 		return;
1689 
1690 	if (alt_path->rec_type != SA_PATH_REC_TYPE_OPA) {
1691 		sa_path_set_dlid(alt_path,
1692 				 IBA_GET(CM_REQ_ALTERNATE_LOCAL_PORT_LID,
1693 					 req_msg));
1694 		sa_path_set_slid(alt_path,
1695 				 IBA_GET(CM_REQ_ALTERNATE_REMOTE_PORT_LID,
1696 					 req_msg));
1697 	} else {
1698 		lid = opa_get_lid_from_gid(IBA_GET_MEM_PTR(
1699 			CM_REQ_ALTERNATE_LOCAL_PORT_GID, req_msg));
1700 		sa_path_set_dlid(alt_path, lid);
1701 
1702 		lid = opa_get_lid_from_gid(IBA_GET_MEM_PTR(
1703 			CM_REQ_ALTERNATE_REMOTE_PORT_GID, req_msg));
1704 		sa_path_set_slid(alt_path, lid);
1705 	}
1706 }
1707 
1708 static void cm_format_paths_from_req(struct cm_req_msg *req_msg,
1709 				     struct sa_path_rec *primary_path,
1710 				     struct sa_path_rec *alt_path,
1711 				     struct ib_wc *wc)
1712 {
1713 	primary_path->dgid =
1714 		*IBA_GET_MEM_PTR(CM_REQ_PRIMARY_LOCAL_PORT_GID, req_msg);
1715 	primary_path->sgid =
1716 		*IBA_GET_MEM_PTR(CM_REQ_PRIMARY_REMOTE_PORT_GID, req_msg);
1717 	primary_path->flow_label =
1718 		cpu_to_be32(IBA_GET(CM_REQ_PRIMARY_FLOW_LABEL, req_msg));
1719 	primary_path->hop_limit = IBA_GET(CM_REQ_PRIMARY_HOP_LIMIT, req_msg);
1720 	primary_path->traffic_class =
1721 		IBA_GET(CM_REQ_PRIMARY_TRAFFIC_CLASS, req_msg);
1722 	primary_path->reversible = 1;
1723 	primary_path->pkey =
1724 		cpu_to_be16(IBA_GET(CM_REQ_PARTITION_KEY, req_msg));
1725 	primary_path->sl = IBA_GET(CM_REQ_PRIMARY_SL, req_msg);
1726 	primary_path->mtu_selector = IB_SA_EQ;
1727 	primary_path->mtu = IBA_GET(CM_REQ_PATH_PACKET_PAYLOAD_MTU, req_msg);
1728 	primary_path->rate_selector = IB_SA_EQ;
1729 	primary_path->rate = IBA_GET(CM_REQ_PRIMARY_PACKET_RATE, req_msg);
1730 	primary_path->packet_life_time_selector = IB_SA_EQ;
1731 	primary_path->packet_life_time =
1732 		IBA_GET(CM_REQ_PRIMARY_LOCAL_ACK_TIMEOUT, req_msg);
1733 	primary_path->packet_life_time -= (primary_path->packet_life_time > 0);
1734 	primary_path->service_id =
1735 		cpu_to_be64(IBA_GET(CM_REQ_SERVICE_ID, req_msg));
1736 	if (sa_path_is_roce(primary_path))
1737 		primary_path->roce.route_resolved = false;
1738 
1739 	if (cm_req_has_alt_path(req_msg)) {
1740 		alt_path->dgid = *IBA_GET_MEM_PTR(
1741 			CM_REQ_ALTERNATE_LOCAL_PORT_GID, req_msg);
1742 		alt_path->sgid = *IBA_GET_MEM_PTR(
1743 			CM_REQ_ALTERNATE_REMOTE_PORT_GID, req_msg);
1744 		alt_path->flow_label = cpu_to_be32(
1745 			IBA_GET(CM_REQ_ALTERNATE_FLOW_LABEL, req_msg));
1746 		alt_path->hop_limit =
1747 			IBA_GET(CM_REQ_ALTERNATE_HOP_LIMIT, req_msg);
1748 		alt_path->traffic_class =
1749 			IBA_GET(CM_REQ_ALTERNATE_TRAFFIC_CLASS, req_msg);
1750 		alt_path->reversible = 1;
1751 		alt_path->pkey =
1752 			cpu_to_be16(IBA_GET(CM_REQ_PARTITION_KEY, req_msg));
1753 		alt_path->sl = IBA_GET(CM_REQ_ALTERNATE_SL, req_msg);
1754 		alt_path->mtu_selector = IB_SA_EQ;
1755 		alt_path->mtu =
1756 			IBA_GET(CM_REQ_PATH_PACKET_PAYLOAD_MTU, req_msg);
1757 		alt_path->rate_selector = IB_SA_EQ;
1758 		alt_path->rate = IBA_GET(CM_REQ_ALTERNATE_PACKET_RATE, req_msg);
1759 		alt_path->packet_life_time_selector = IB_SA_EQ;
1760 		alt_path->packet_life_time =
1761 			IBA_GET(CM_REQ_ALTERNATE_LOCAL_ACK_TIMEOUT, req_msg);
1762 		alt_path->packet_life_time -= (alt_path->packet_life_time > 0);
1763 		alt_path->service_id =
1764 			cpu_to_be64(IBA_GET(CM_REQ_SERVICE_ID, req_msg));
1765 
1766 		if (sa_path_is_roce(alt_path))
1767 			alt_path->roce.route_resolved = false;
1768 	}
1769 	cm_format_path_lid_from_req(req_msg, primary_path, alt_path, wc);
1770 }
1771 
1772 static u16 cm_get_bth_pkey(struct cm_work *work)
1773 {
1774 	struct ib_device *ib_dev = work->port->cm_dev->ib_device;
1775 	u32 port_num = work->port->port_num;
1776 	u16 pkey_index = work->mad_recv_wc->wc->pkey_index;
1777 	u16 pkey;
1778 	int ret;
1779 
1780 	ret = ib_get_cached_pkey(ib_dev, port_num, pkey_index, &pkey);
1781 	if (ret) {
1782 		dev_warn_ratelimited(&ib_dev->dev, "ib_cm: Couldn't retrieve pkey for incoming request (port %u, pkey index %u). %d\n",
1783 				     port_num, pkey_index, ret);
1784 		return 0;
1785 	}
1786 
1787 	return pkey;
1788 }
1789 
1790 /**
1791  * cm_opa_to_ib_sgid - Convert OPA SGID to IB SGID
1792  * ULPs (such as IPoIB) do not understand OPA GIDs and will
1793  * reject them as the local_gid will not match the sgid. Therefore,
1794  * change the pathrec's SGID to an IB SGID.
1795  *
1796  * @work: Work completion
1797  * @path: Path record
1798  */
1799 static void cm_opa_to_ib_sgid(struct cm_work *work,
1800 			      struct sa_path_rec *path)
1801 {
1802 	struct ib_device *dev = work->port->cm_dev->ib_device;
1803 	u32 port_num = work->port->port_num;
1804 
1805 	if (rdma_cap_opa_ah(dev, port_num) &&
1806 	    (ib_is_opa_gid(&path->sgid))) {
1807 		union ib_gid sgid;
1808 
1809 		if (rdma_query_gid(dev, port_num, 0, &sgid)) {
1810 			dev_warn(&dev->dev,
1811 				 "Error updating sgid in CM request\n");
1812 			return;
1813 		}
1814 
1815 		path->sgid = sgid;
1816 	}
1817 }
1818 
1819 static void cm_format_req_event(struct cm_work *work,
1820 				struct cm_id_private *cm_id_priv,
1821 				struct ib_cm_id *listen_id)
1822 {
1823 	struct cm_req_msg *req_msg;
1824 	struct ib_cm_req_event_param *param;
1825 
1826 	req_msg = (struct cm_req_msg *)work->mad_recv_wc->recv_buf.mad;
1827 	param = &work->cm_event.param.req_rcvd;
1828 	param->listen_id = listen_id;
1829 	param->bth_pkey = cm_get_bth_pkey(work);
1830 	param->port = cm_id_priv->av.port->port_num;
1831 	param->primary_path = &work->path[0];
1832 	cm_opa_to_ib_sgid(work, param->primary_path);
1833 	if (cm_req_has_alt_path(req_msg)) {
1834 		param->alternate_path = &work->path[1];
1835 		cm_opa_to_ib_sgid(work, param->alternate_path);
1836 	} else {
1837 		param->alternate_path = NULL;
1838 	}
1839 	param->remote_ca_guid =
1840 		cpu_to_be64(IBA_GET(CM_REQ_LOCAL_CA_GUID, req_msg));
1841 	param->remote_qkey = IBA_GET(CM_REQ_LOCAL_Q_KEY, req_msg);
1842 	param->remote_qpn = IBA_GET(CM_REQ_LOCAL_QPN, req_msg);
1843 	param->qp_type = cm_req_get_qp_type(req_msg);
1844 	param->starting_psn = IBA_GET(CM_REQ_STARTING_PSN, req_msg);
1845 	param->responder_resources = IBA_GET(CM_REQ_INITIATOR_DEPTH, req_msg);
1846 	param->initiator_depth = IBA_GET(CM_REQ_RESPONDER_RESOURCES, req_msg);
1847 	param->local_cm_response_timeout =
1848 		IBA_GET(CM_REQ_REMOTE_CM_RESPONSE_TIMEOUT, req_msg);
1849 	param->flow_control = IBA_GET(CM_REQ_END_TO_END_FLOW_CONTROL, req_msg);
1850 	param->remote_cm_response_timeout =
1851 		IBA_GET(CM_REQ_LOCAL_CM_RESPONSE_TIMEOUT, req_msg);
1852 	param->retry_count = IBA_GET(CM_REQ_RETRY_COUNT, req_msg);
1853 	param->rnr_retry_count = IBA_GET(CM_REQ_RNR_RETRY_COUNT, req_msg);
1854 	param->srq = IBA_GET(CM_REQ_SRQ, req_msg);
1855 	param->ppath_sgid_attr = cm_id_priv->av.ah_attr.grh.sgid_attr;
1856 	param->ece.vendor_id = IBA_GET(CM_REQ_VENDOR_ID, req_msg);
1857 	param->ece.attr_mod = be32_to_cpu(req_msg->hdr.attr_mod);
1858 
1859 	work->cm_event.private_data =
1860 		IBA_GET_MEM_PTR(CM_REQ_PRIVATE_DATA, req_msg);
1861 }
1862 
1863 static void cm_process_work(struct cm_id_private *cm_id_priv,
1864 			    struct cm_work *work)
1865 {
1866 	int ret;
1867 
1868 	/* We will typically only have the current event to report. */
1869 	ret = cm_id_priv->id.cm_handler(&cm_id_priv->id, &work->cm_event);
1870 	cm_free_work(work);
1871 
1872 	while (!ret && !atomic_add_negative(-1, &cm_id_priv->work_count)) {
1873 		spin_lock_irq(&cm_id_priv->lock);
1874 		work = cm_dequeue_work(cm_id_priv);
1875 		spin_unlock_irq(&cm_id_priv->lock);
1876 		if (!work)
1877 			return;
1878 
1879 		ret = cm_id_priv->id.cm_handler(&cm_id_priv->id,
1880 						&work->cm_event);
1881 		cm_free_work(work);
1882 	}
1883 	cm_deref_id(cm_id_priv);
1884 	if (ret)
1885 		cm_destroy_id(&cm_id_priv->id, ret);
1886 }
1887 
1888 static void cm_format_mra(struct cm_mra_msg *mra_msg,
1889 			  struct cm_id_private *cm_id_priv,
1890 			  enum cm_msg_response msg_mraed,
1891 			  const void *private_data, u8 private_data_len)
1892 {
1893 	cm_format_mad_hdr(&mra_msg->hdr, CM_MRA_ATTR_ID, cm_id_priv->tid);
1894 	IBA_SET(CM_MRA_MESSAGE_MRAED, mra_msg, msg_mraed);
1895 	IBA_SET(CM_MRA_LOCAL_COMM_ID, mra_msg,
1896 		be32_to_cpu(cm_id_priv->id.local_id));
1897 	IBA_SET(CM_MRA_REMOTE_COMM_ID, mra_msg,
1898 		be32_to_cpu(cm_id_priv->id.remote_id));
1899 	IBA_SET(CM_MRA_SERVICE_TIMEOUT, mra_msg, CM_MRA_SETTING);
1900 
1901 	if (private_data && private_data_len)
1902 		IBA_SET_MEM(CM_MRA_PRIVATE_DATA, mra_msg, private_data,
1903 			    private_data_len);
1904 }
1905 
1906 static void cm_format_rej(struct cm_rej_msg *rej_msg,
1907 			  struct cm_id_private *cm_id_priv,
1908 			  enum ib_cm_rej_reason reason, void *ari,
1909 			  u8 ari_length, const void *private_data,
1910 			  u8 private_data_len, enum ib_cm_state state)
1911 {
1912 	lockdep_assert_held(&cm_id_priv->lock);
1913 
1914 	cm_format_mad_hdr(&rej_msg->hdr, CM_REJ_ATTR_ID, cm_id_priv->tid);
1915 	IBA_SET(CM_REJ_REMOTE_COMM_ID, rej_msg,
1916 		be32_to_cpu(cm_id_priv->id.remote_id));
1917 
1918 	switch (state) {
1919 	case IB_CM_REQ_RCVD:
1920 		IBA_SET(CM_REJ_LOCAL_COMM_ID, rej_msg, be32_to_cpu(0));
1921 		IBA_SET(CM_REJ_MESSAGE_REJECTED, rej_msg, CM_MSG_RESPONSE_REQ);
1922 		break;
1923 	case IB_CM_MRA_REQ_SENT:
1924 		IBA_SET(CM_REJ_LOCAL_COMM_ID, rej_msg,
1925 			be32_to_cpu(cm_id_priv->id.local_id));
1926 		IBA_SET(CM_REJ_MESSAGE_REJECTED, rej_msg, CM_MSG_RESPONSE_REQ);
1927 		break;
1928 	case IB_CM_REP_RCVD:
1929 	case IB_CM_MRA_REP_SENT:
1930 		IBA_SET(CM_REJ_LOCAL_COMM_ID, rej_msg,
1931 			be32_to_cpu(cm_id_priv->id.local_id));
1932 		IBA_SET(CM_REJ_MESSAGE_REJECTED, rej_msg, CM_MSG_RESPONSE_REP);
1933 		break;
1934 	default:
1935 		IBA_SET(CM_REJ_LOCAL_COMM_ID, rej_msg,
1936 			be32_to_cpu(cm_id_priv->id.local_id));
1937 		IBA_SET(CM_REJ_MESSAGE_REJECTED, rej_msg,
1938 			CM_MSG_RESPONSE_OTHER);
1939 		break;
1940 	}
1941 
1942 	IBA_SET(CM_REJ_REASON, rej_msg, reason);
1943 	if (ari && ari_length) {
1944 		IBA_SET(CM_REJ_REJECTED_INFO_LENGTH, rej_msg, ari_length);
1945 		IBA_SET_MEM(CM_REJ_ARI, rej_msg, ari, ari_length);
1946 	}
1947 
1948 	if (private_data && private_data_len)
1949 		IBA_SET_MEM(CM_REJ_PRIVATE_DATA, rej_msg, private_data,
1950 			    private_data_len);
1951 }
1952 
1953 static void cm_dup_req_handler(struct cm_work *work,
1954 			       struct cm_id_private *cm_id_priv)
1955 {
1956 	struct ib_mad_send_buf *msg = NULL;
1957 	int ret;
1958 
1959 	atomic_long_inc(
1960 		&work->port->counters[CM_RECV_DUPLICATES][CM_REQ_COUNTER]);
1961 
1962 	/* Quick state check to discard duplicate REQs. */
1963 	spin_lock_irq(&cm_id_priv->lock);
1964 	if (cm_id_priv->id.state == IB_CM_REQ_RCVD) {
1965 		spin_unlock_irq(&cm_id_priv->lock);
1966 		return;
1967 	}
1968 	spin_unlock_irq(&cm_id_priv->lock);
1969 
1970 	ret = cm_alloc_response_msg(work->port, work->mad_recv_wc, true, &msg);
1971 	if (ret)
1972 		return;
1973 
1974 	spin_lock_irq(&cm_id_priv->lock);
1975 	switch (cm_id_priv->id.state) {
1976 	case IB_CM_MRA_REQ_SENT:
1977 		cm_format_mra((struct cm_mra_msg *) msg->mad, cm_id_priv,
1978 			      CM_MSG_RESPONSE_REQ,
1979 			      cm_id_priv->private_data,
1980 			      cm_id_priv->private_data_len);
1981 		break;
1982 	case IB_CM_TIMEWAIT:
1983 		cm_format_rej((struct cm_rej_msg *)msg->mad, cm_id_priv,
1984 			      IB_CM_REJ_STALE_CONN, NULL, 0, NULL, 0,
1985 			      IB_CM_TIMEWAIT);
1986 		break;
1987 	default:
1988 		goto unlock;
1989 	}
1990 	spin_unlock_irq(&cm_id_priv->lock);
1991 
1992 	trace_icm_send_dup_req(&cm_id_priv->id);
1993 	ret = ib_post_send_mad(msg, NULL);
1994 	if (ret)
1995 		goto free;
1996 	return;
1997 
1998 unlock:	spin_unlock_irq(&cm_id_priv->lock);
1999 free:	cm_free_msg(msg);
2000 }
2001 
2002 static struct cm_id_private *cm_match_req(struct cm_work *work,
2003 					  struct cm_id_private *cm_id_priv)
2004 {
2005 	struct cm_id_private *listen_cm_id_priv, *cur_cm_id_priv;
2006 	struct cm_timewait_info *timewait_info;
2007 	struct cm_req_msg *req_msg;
2008 
2009 	req_msg = (struct cm_req_msg *)work->mad_recv_wc->recv_buf.mad;
2010 
2011 	/* Check for possible duplicate REQ. */
2012 	spin_lock_irq(&cm.lock);
2013 	timewait_info = cm_insert_remote_id(cm_id_priv->timewait_info);
2014 	if (timewait_info) {
2015 		cur_cm_id_priv = cm_acquire_id(timewait_info->work.local_id,
2016 					   timewait_info->work.remote_id);
2017 		spin_unlock_irq(&cm.lock);
2018 		if (cur_cm_id_priv) {
2019 			cm_dup_req_handler(work, cur_cm_id_priv);
2020 			cm_deref_id(cur_cm_id_priv);
2021 		}
2022 		return NULL;
2023 	}
2024 
2025 	/* Check for stale connections. */
2026 	timewait_info = cm_insert_remote_qpn(cm_id_priv->timewait_info);
2027 	if (timewait_info) {
2028 		cm_remove_remote(cm_id_priv);
2029 		cur_cm_id_priv = cm_acquire_id(timewait_info->work.local_id,
2030 					   timewait_info->work.remote_id);
2031 
2032 		spin_unlock_irq(&cm.lock);
2033 		cm_issue_rej(work->port, work->mad_recv_wc,
2034 			     IB_CM_REJ_STALE_CONN, CM_MSG_RESPONSE_REQ,
2035 			     NULL, 0);
2036 		if (cur_cm_id_priv) {
2037 			ib_send_cm_dreq(&cur_cm_id_priv->id, NULL, 0);
2038 			cm_deref_id(cur_cm_id_priv);
2039 		}
2040 		return NULL;
2041 	}
2042 
2043 	/* Find matching listen request. */
2044 	listen_cm_id_priv = cm_find_listen(
2045 		cm_id_priv->id.device,
2046 		cpu_to_be64(IBA_GET(CM_REQ_SERVICE_ID, req_msg)));
2047 	if (!listen_cm_id_priv) {
2048 		cm_remove_remote(cm_id_priv);
2049 		spin_unlock_irq(&cm.lock);
2050 		cm_issue_rej(work->port, work->mad_recv_wc,
2051 			     IB_CM_REJ_INVALID_SERVICE_ID, CM_MSG_RESPONSE_REQ,
2052 			     NULL, 0);
2053 		return NULL;
2054 	}
2055 	spin_unlock_irq(&cm.lock);
2056 	return listen_cm_id_priv;
2057 }
2058 
2059 /*
2060  * Work-around for inter-subnet connections.  If the LIDs are permissive,
2061  * we need to override the LID/SL data in the REQ with the LID information
2062  * in the work completion.
2063  */
2064 static void cm_process_routed_req(struct cm_req_msg *req_msg, struct ib_wc *wc)
2065 {
2066 	if (!IBA_GET(CM_REQ_PRIMARY_SUBNET_LOCAL, req_msg)) {
2067 		if (cpu_to_be16(IBA_GET(CM_REQ_PRIMARY_LOCAL_PORT_LID,
2068 					req_msg)) == IB_LID_PERMISSIVE) {
2069 			IBA_SET(CM_REQ_PRIMARY_LOCAL_PORT_LID, req_msg,
2070 				be16_to_cpu(ib_lid_be16(wc->slid)));
2071 			IBA_SET(CM_REQ_PRIMARY_SL, req_msg, wc->sl);
2072 		}
2073 
2074 		if (cpu_to_be16(IBA_GET(CM_REQ_PRIMARY_REMOTE_PORT_LID,
2075 					req_msg)) == IB_LID_PERMISSIVE)
2076 			IBA_SET(CM_REQ_PRIMARY_REMOTE_PORT_LID, req_msg,
2077 				wc->dlid_path_bits);
2078 	}
2079 
2080 	if (!IBA_GET(CM_REQ_ALTERNATE_SUBNET_LOCAL, req_msg)) {
2081 		if (cpu_to_be16(IBA_GET(CM_REQ_ALTERNATE_LOCAL_PORT_LID,
2082 					req_msg)) == IB_LID_PERMISSIVE) {
2083 			IBA_SET(CM_REQ_ALTERNATE_LOCAL_PORT_LID, req_msg,
2084 				be16_to_cpu(ib_lid_be16(wc->slid)));
2085 			IBA_SET(CM_REQ_ALTERNATE_SL, req_msg, wc->sl);
2086 		}
2087 
2088 		if (cpu_to_be16(IBA_GET(CM_REQ_ALTERNATE_REMOTE_PORT_LID,
2089 					req_msg)) == IB_LID_PERMISSIVE)
2090 			IBA_SET(CM_REQ_ALTERNATE_REMOTE_PORT_LID, req_msg,
2091 				wc->dlid_path_bits);
2092 	}
2093 }
2094 
2095 static int cm_req_handler(struct cm_work *work)
2096 {
2097 	struct cm_id_private *cm_id_priv, *listen_cm_id_priv;
2098 	struct cm_req_msg *req_msg;
2099 	const struct ib_global_route *grh;
2100 	const struct ib_gid_attr *gid_attr;
2101 	int ret;
2102 
2103 	req_msg = (struct cm_req_msg *)work->mad_recv_wc->recv_buf.mad;
2104 
2105 	cm_id_priv =
2106 		cm_alloc_id_priv(work->port->cm_dev->ib_device, NULL, NULL);
2107 	if (IS_ERR(cm_id_priv))
2108 		return PTR_ERR(cm_id_priv);
2109 
2110 	cm_id_priv->id.remote_id =
2111 		cpu_to_be32(IBA_GET(CM_REQ_LOCAL_COMM_ID, req_msg));
2112 	cm_id_priv->id.service_id =
2113 		cpu_to_be64(IBA_GET(CM_REQ_SERVICE_ID, req_msg));
2114 	cm_id_priv->tid = req_msg->hdr.tid;
2115 	cm_id_priv->timeout_ms = cm_convert_to_ms(
2116 		IBA_GET(CM_REQ_LOCAL_CM_RESPONSE_TIMEOUT, req_msg));
2117 	cm_id_priv->max_cm_retries = IBA_GET(CM_REQ_MAX_CM_RETRIES, req_msg);
2118 	cm_id_priv->remote_qpn =
2119 		cpu_to_be32(IBA_GET(CM_REQ_LOCAL_QPN, req_msg));
2120 	cm_id_priv->initiator_depth =
2121 		IBA_GET(CM_REQ_RESPONDER_RESOURCES, req_msg);
2122 	cm_id_priv->responder_resources =
2123 		IBA_GET(CM_REQ_INITIATOR_DEPTH, req_msg);
2124 	cm_id_priv->path_mtu = IBA_GET(CM_REQ_PATH_PACKET_PAYLOAD_MTU, req_msg);
2125 	cm_id_priv->pkey = cpu_to_be16(IBA_GET(CM_REQ_PARTITION_KEY, req_msg));
2126 	cm_id_priv->sq_psn = cpu_to_be32(IBA_GET(CM_REQ_STARTING_PSN, req_msg));
2127 	cm_id_priv->retry_count = IBA_GET(CM_REQ_RETRY_COUNT, req_msg);
2128 	cm_id_priv->rnr_retry_count = IBA_GET(CM_REQ_RNR_RETRY_COUNT, req_msg);
2129 	cm_id_priv->qp_type = cm_req_get_qp_type(req_msg);
2130 
2131 	ret = cm_init_av_for_response(work->port, work->mad_recv_wc->wc,
2132 				      work->mad_recv_wc->recv_buf.grh,
2133 				      &cm_id_priv->av);
2134 	if (ret)
2135 		goto destroy;
2136 	cm_id_priv->timewait_info = cm_create_timewait_info(cm_id_priv->
2137 							    id.local_id);
2138 	if (IS_ERR(cm_id_priv->timewait_info)) {
2139 		ret = PTR_ERR(cm_id_priv->timewait_info);
2140 		cm_id_priv->timewait_info = NULL;
2141 		goto destroy;
2142 	}
2143 	cm_id_priv->timewait_info->work.remote_id = cm_id_priv->id.remote_id;
2144 	cm_id_priv->timewait_info->remote_ca_guid =
2145 		cpu_to_be64(IBA_GET(CM_REQ_LOCAL_CA_GUID, req_msg));
2146 	cm_id_priv->timewait_info->remote_qpn = cm_id_priv->remote_qpn;
2147 
2148 	/*
2149 	 * Note that the ID pointer is not in the xarray at this point,
2150 	 * so this set is only visible to the local thread.
2151 	 */
2152 	cm_id_priv->id.state = IB_CM_REQ_RCVD;
2153 
2154 	listen_cm_id_priv = cm_match_req(work, cm_id_priv);
2155 	if (!listen_cm_id_priv) {
2156 		trace_icm_no_listener_err(&cm_id_priv->id);
2157 		cm_id_priv->id.state = IB_CM_IDLE;
2158 		ret = -EINVAL;
2159 		goto destroy;
2160 	}
2161 
2162 	memset(&work->path[0], 0, sizeof(work->path[0]));
2163 	if (cm_req_has_alt_path(req_msg))
2164 		memset(&work->path[1], 0, sizeof(work->path[1]));
2165 	grh = rdma_ah_read_grh(&cm_id_priv->av.ah_attr);
2166 	gid_attr = grh->sgid_attr;
2167 
2168 	if (cm_id_priv->av.ah_attr.type == RDMA_AH_ATTR_TYPE_ROCE) {
2169 		work->path[0].rec_type =
2170 			sa_conv_gid_to_pathrec_type(gid_attr->gid_type);
2171 	} else {
2172 		cm_process_routed_req(req_msg, work->mad_recv_wc->wc);
2173 		cm_path_set_rec_type(
2174 			work->port->cm_dev->ib_device, work->port->port_num,
2175 			&work->path[0],
2176 			IBA_GET_MEM_PTR(CM_REQ_PRIMARY_LOCAL_PORT_GID,
2177 					req_msg));
2178 	}
2179 	if (cm_req_has_alt_path(req_msg))
2180 		work->path[1].rec_type = work->path[0].rec_type;
2181 	cm_format_paths_from_req(req_msg, &work->path[0],
2182 				 &work->path[1], work->mad_recv_wc->wc);
2183 	if (cm_id_priv->av.ah_attr.type == RDMA_AH_ATTR_TYPE_ROCE)
2184 		sa_path_set_dmac(&work->path[0],
2185 				 cm_id_priv->av.ah_attr.roce.dmac);
2186 	work->path[0].hop_limit = grh->hop_limit;
2187 
2188 	/*
2189 	 * cm_init_av_by_path() will internally pair with the above
2190 	 * cm_init_av_for_response() if it succeeds.
2191 	 */
2192 	ret = cm_init_av_by_path(&work->path[0], gid_attr, &cm_id_priv->av);
2193 	if (ret) {
2194 		int err;
2195 
2196 		err = rdma_query_gid(work->port->cm_dev->ib_device,
2197 				     work->port->port_num, 0,
2198 				     &work->path[0].sgid);
2199 		if (err)
2200 			ib_send_cm_rej(&cm_id_priv->id, IB_CM_REJ_INVALID_GID,
2201 				       NULL, 0, NULL, 0);
2202 		else
2203 			ib_send_cm_rej(&cm_id_priv->id, IB_CM_REJ_INVALID_GID,
2204 				       &work->path[0].sgid,
2205 				       sizeof(work->path[0].sgid),
2206 				       NULL, 0);
2207 		goto rejected;
2208 	}
2209 	if (cm_id_priv->av.ah_attr.type == RDMA_AH_ATTR_TYPE_IB)
2210 		cm_id_priv->av.dlid_datapath =
2211 			IBA_GET(CM_REQ_PRIMARY_LOCAL_PORT_LID, req_msg);
2212 
2213 	if (cm_req_has_alt_path(req_msg)) {
2214 		ret = cm_init_av_by_path(&work->path[1], NULL,
2215 					 &cm_id_priv->alt_av);
2216 		if (ret) {
2217 			ib_send_cm_rej(&cm_id_priv->id,
2218 				       IB_CM_REJ_INVALID_ALT_GID,
2219 				       &work->path[0].sgid,
2220 				       sizeof(work->path[0].sgid), NULL, 0);
2221 			goto rejected;
2222 		}
2223 	}
2224 
2225 	cm_id_priv->id.cm_handler = listen_cm_id_priv->id.cm_handler;
2226 	cm_id_priv->id.context = listen_cm_id_priv->id.context;
2227 	cm_format_req_event(work, cm_id_priv, &listen_cm_id_priv->id);
2228 
2229 	/* Now MAD handlers can see the new ID */
2230 	spin_lock_irq(&cm_id_priv->lock);
2231 	cm_finalize_id(cm_id_priv);
2232 
2233 	/* Refcount belongs to the event, pairs with cm_process_work() */
2234 	refcount_inc(&cm_id_priv->refcount);
2235 	cm_queue_work_unlock(cm_id_priv, work);
2236 	/*
2237 	 * Since this ID was just created and was not made visible to other MAD
2238 	 * handlers until the cm_finalize_id() above we know that the
2239 	 * cm_process_work() will deliver the event and the listen_cm_id
2240 	 * embedded in the event can be derefed here.
2241 	 */
2242 	cm_deref_id(listen_cm_id_priv);
2243 	return 0;
2244 
2245 rejected:
2246 	cm_deref_id(listen_cm_id_priv);
2247 destroy:
2248 	ib_destroy_cm_id(&cm_id_priv->id);
2249 	return ret;
2250 }
2251 
2252 static void cm_format_rep(struct cm_rep_msg *rep_msg,
2253 			  struct cm_id_private *cm_id_priv,
2254 			  struct ib_cm_rep_param *param)
2255 {
2256 	cm_format_mad_ece_hdr(&rep_msg->hdr, CM_REP_ATTR_ID, cm_id_priv->tid,
2257 			      param->ece.attr_mod);
2258 	IBA_SET(CM_REP_LOCAL_COMM_ID, rep_msg,
2259 		be32_to_cpu(cm_id_priv->id.local_id));
2260 	IBA_SET(CM_REP_REMOTE_COMM_ID, rep_msg,
2261 		be32_to_cpu(cm_id_priv->id.remote_id));
2262 	IBA_SET(CM_REP_STARTING_PSN, rep_msg, param->starting_psn);
2263 	IBA_SET(CM_REP_RESPONDER_RESOURCES, rep_msg,
2264 		param->responder_resources);
2265 	IBA_SET(CM_REP_TARGET_ACK_DELAY, rep_msg,
2266 		cm_id_priv->av.port->cm_dev->ack_delay);
2267 	IBA_SET(CM_REP_FAILOVER_ACCEPTED, rep_msg, param->failover_accepted);
2268 	IBA_SET(CM_REP_RNR_RETRY_COUNT, rep_msg, param->rnr_retry_count);
2269 	IBA_SET(CM_REP_LOCAL_CA_GUID, rep_msg,
2270 		be64_to_cpu(cm_id_priv->id.device->node_guid));
2271 
2272 	if (cm_id_priv->qp_type != IB_QPT_XRC_TGT) {
2273 		IBA_SET(CM_REP_INITIATOR_DEPTH, rep_msg,
2274 			param->initiator_depth);
2275 		IBA_SET(CM_REP_END_TO_END_FLOW_CONTROL, rep_msg,
2276 			param->flow_control);
2277 		IBA_SET(CM_REP_SRQ, rep_msg, param->srq);
2278 		IBA_SET(CM_REP_LOCAL_QPN, rep_msg, param->qp_num);
2279 	} else {
2280 		IBA_SET(CM_REP_SRQ, rep_msg, 1);
2281 		IBA_SET(CM_REP_LOCAL_EE_CONTEXT_NUMBER, rep_msg, param->qp_num);
2282 	}
2283 
2284 	IBA_SET(CM_REP_VENDOR_ID_L, rep_msg, param->ece.vendor_id);
2285 	IBA_SET(CM_REP_VENDOR_ID_M, rep_msg, param->ece.vendor_id >> 8);
2286 	IBA_SET(CM_REP_VENDOR_ID_H, rep_msg, param->ece.vendor_id >> 16);
2287 
2288 	if (param->private_data && param->private_data_len)
2289 		IBA_SET_MEM(CM_REP_PRIVATE_DATA, rep_msg, param->private_data,
2290 			    param->private_data_len);
2291 }
2292 
2293 int ib_send_cm_rep(struct ib_cm_id *cm_id,
2294 		   struct ib_cm_rep_param *param)
2295 {
2296 	struct cm_id_private *cm_id_priv;
2297 	struct ib_mad_send_buf *msg;
2298 	struct cm_rep_msg *rep_msg;
2299 	unsigned long flags;
2300 	int ret;
2301 
2302 	if (param->private_data &&
2303 	    param->private_data_len > IB_CM_REP_PRIVATE_DATA_SIZE)
2304 		return -EINVAL;
2305 
2306 	cm_id_priv = container_of(cm_id, struct cm_id_private, id);
2307 	spin_lock_irqsave(&cm_id_priv->lock, flags);
2308 	if (cm_id->state != IB_CM_REQ_RCVD &&
2309 	    cm_id->state != IB_CM_MRA_REQ_SENT) {
2310 		trace_icm_send_rep_err(cm_id_priv->id.local_id, cm_id->state);
2311 		ret = -EINVAL;
2312 		goto out;
2313 	}
2314 
2315 	msg = cm_alloc_priv_msg_rep(cm_id_priv, IB_CM_REP_SENT, true);
2316 	if (IS_ERR(msg)) {
2317 		ret = PTR_ERR(msg);
2318 		goto out;
2319 	}
2320 
2321 	rep_msg = (struct cm_rep_msg *) msg->mad;
2322 	cm_format_rep(rep_msg, cm_id_priv, param);
2323 
2324 	trace_icm_send_rep(cm_id);
2325 	ret = ib_post_send_mad(msg, NULL);
2326 	if (ret)
2327 		goto out_free;
2328 
2329 	cm_id->state = IB_CM_REP_SENT;
2330 	cm_id_priv->initiator_depth = param->initiator_depth;
2331 	cm_id_priv->responder_resources = param->responder_resources;
2332 	cm_id_priv->rq_psn = cpu_to_be32(IBA_GET(CM_REP_STARTING_PSN, rep_msg));
2333 	WARN_ONCE(param->qp_num & 0xFF000000,
2334 		  "IBTA declares QPN to be 24 bits, but it is 0x%X\n",
2335 		  param->qp_num);
2336 	cm_id_priv->local_qpn = cpu_to_be32(param->qp_num & 0xFFFFFF);
2337 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
2338 	return 0;
2339 
2340 out_free:
2341 	cm_free_priv_msg(msg);
2342 out:
2343 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
2344 	return ret;
2345 }
2346 EXPORT_SYMBOL(ib_send_cm_rep);
2347 
2348 static void cm_format_rtu(struct cm_rtu_msg *rtu_msg,
2349 			  struct cm_id_private *cm_id_priv,
2350 			  const void *private_data,
2351 			  u8 private_data_len)
2352 {
2353 	cm_format_mad_hdr(&rtu_msg->hdr, CM_RTU_ATTR_ID, cm_id_priv->tid);
2354 	IBA_SET(CM_RTU_LOCAL_COMM_ID, rtu_msg,
2355 		be32_to_cpu(cm_id_priv->id.local_id));
2356 	IBA_SET(CM_RTU_REMOTE_COMM_ID, rtu_msg,
2357 		be32_to_cpu(cm_id_priv->id.remote_id));
2358 
2359 	if (private_data && private_data_len)
2360 		IBA_SET_MEM(CM_RTU_PRIVATE_DATA, rtu_msg, private_data,
2361 			    private_data_len);
2362 }
2363 
2364 int ib_send_cm_rtu(struct ib_cm_id *cm_id,
2365 		   const void *private_data,
2366 		   u8 private_data_len)
2367 {
2368 	struct cm_id_private *cm_id_priv;
2369 	struct ib_mad_send_buf *msg;
2370 	unsigned long flags;
2371 	void *data;
2372 	int ret;
2373 
2374 	if (private_data && private_data_len > IB_CM_RTU_PRIVATE_DATA_SIZE)
2375 		return -EINVAL;
2376 
2377 	data = cm_copy_private_data(private_data, private_data_len);
2378 	if (IS_ERR(data))
2379 		return PTR_ERR(data);
2380 
2381 	cm_id_priv = container_of(cm_id, struct cm_id_private, id);
2382 	spin_lock_irqsave(&cm_id_priv->lock, flags);
2383 	if (cm_id->state != IB_CM_REP_RCVD &&
2384 	    cm_id->state != IB_CM_MRA_REP_SENT) {
2385 		trace_icm_send_cm_rtu_err(cm_id);
2386 		ret = -EINVAL;
2387 		goto error;
2388 	}
2389 
2390 	msg = cm_alloc_msg(cm_id_priv);
2391 	if (IS_ERR(msg)) {
2392 		ret = PTR_ERR(msg);
2393 		goto error;
2394 	}
2395 
2396 	cm_format_rtu((struct cm_rtu_msg *) msg->mad, cm_id_priv,
2397 		      private_data, private_data_len);
2398 
2399 	trace_icm_send_rtu(cm_id);
2400 	ret = ib_post_send_mad(msg, NULL);
2401 	if (ret) {
2402 		spin_unlock_irqrestore(&cm_id_priv->lock, flags);
2403 		cm_free_msg(msg);
2404 		kfree(data);
2405 		return ret;
2406 	}
2407 
2408 	cm_id->state = IB_CM_ESTABLISHED;
2409 	cm_set_private_data(cm_id_priv, data, private_data_len);
2410 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
2411 	return 0;
2412 
2413 error:	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
2414 	kfree(data);
2415 	return ret;
2416 }
2417 EXPORT_SYMBOL(ib_send_cm_rtu);
2418 
2419 static void cm_format_rep_event(struct cm_work *work, enum ib_qp_type qp_type)
2420 {
2421 	struct cm_rep_msg *rep_msg;
2422 	struct ib_cm_rep_event_param *param;
2423 
2424 	rep_msg = (struct cm_rep_msg *)work->mad_recv_wc->recv_buf.mad;
2425 	param = &work->cm_event.param.rep_rcvd;
2426 	param->remote_ca_guid =
2427 		cpu_to_be64(IBA_GET(CM_REP_LOCAL_CA_GUID, rep_msg));
2428 	param->remote_qkey = IBA_GET(CM_REP_LOCAL_Q_KEY, rep_msg);
2429 	param->remote_qpn = be32_to_cpu(cm_rep_get_qpn(rep_msg, qp_type));
2430 	param->starting_psn = IBA_GET(CM_REP_STARTING_PSN, rep_msg);
2431 	param->responder_resources = IBA_GET(CM_REP_INITIATOR_DEPTH, rep_msg);
2432 	param->initiator_depth = IBA_GET(CM_REP_RESPONDER_RESOURCES, rep_msg);
2433 	param->target_ack_delay = IBA_GET(CM_REP_TARGET_ACK_DELAY, rep_msg);
2434 	param->failover_accepted = IBA_GET(CM_REP_FAILOVER_ACCEPTED, rep_msg);
2435 	param->flow_control = IBA_GET(CM_REP_END_TO_END_FLOW_CONTROL, rep_msg);
2436 	param->rnr_retry_count = IBA_GET(CM_REP_RNR_RETRY_COUNT, rep_msg);
2437 	param->srq = IBA_GET(CM_REP_SRQ, rep_msg);
2438 	param->ece.vendor_id = IBA_GET(CM_REP_VENDOR_ID_H, rep_msg) << 16;
2439 	param->ece.vendor_id |= IBA_GET(CM_REP_VENDOR_ID_M, rep_msg) << 8;
2440 	param->ece.vendor_id |= IBA_GET(CM_REP_VENDOR_ID_L, rep_msg);
2441 	param->ece.attr_mod = be32_to_cpu(rep_msg->hdr.attr_mod);
2442 
2443 	work->cm_event.private_data =
2444 		IBA_GET_MEM_PTR(CM_REP_PRIVATE_DATA, rep_msg);
2445 }
2446 
2447 static void cm_dup_rep_handler(struct cm_work *work)
2448 {
2449 	struct cm_id_private *cm_id_priv;
2450 	struct cm_rep_msg *rep_msg;
2451 	struct ib_mad_send_buf *msg = NULL;
2452 	int ret;
2453 
2454 	rep_msg = (struct cm_rep_msg *) work->mad_recv_wc->recv_buf.mad;
2455 	cm_id_priv = cm_acquire_id(
2456 		cpu_to_be32(IBA_GET(CM_REP_REMOTE_COMM_ID, rep_msg)),
2457 		cpu_to_be32(IBA_GET(CM_REP_LOCAL_COMM_ID, rep_msg)));
2458 	if (!cm_id_priv)
2459 		return;
2460 
2461 	atomic_long_inc(
2462 		&work->port->counters[CM_RECV_DUPLICATES][CM_REP_COUNTER]);
2463 	ret = cm_alloc_response_msg(work->port, work->mad_recv_wc, true, &msg);
2464 	if (ret)
2465 		goto deref;
2466 
2467 	spin_lock_irq(&cm_id_priv->lock);
2468 	if (cm_id_priv->id.state == IB_CM_ESTABLISHED)
2469 		cm_format_rtu((struct cm_rtu_msg *) msg->mad, cm_id_priv,
2470 			      cm_id_priv->private_data,
2471 			      cm_id_priv->private_data_len);
2472 	else if (cm_id_priv->id.state == IB_CM_MRA_REP_SENT)
2473 		cm_format_mra((struct cm_mra_msg *) msg->mad, cm_id_priv,
2474 			      CM_MSG_RESPONSE_REP,
2475 			      cm_id_priv->private_data,
2476 			      cm_id_priv->private_data_len);
2477 	else
2478 		goto unlock;
2479 	spin_unlock_irq(&cm_id_priv->lock);
2480 
2481 	trace_icm_send_dup_rep(&cm_id_priv->id);
2482 	ret = ib_post_send_mad(msg, NULL);
2483 	if (ret)
2484 		goto free;
2485 	goto deref;
2486 
2487 unlock:	spin_unlock_irq(&cm_id_priv->lock);
2488 free:	cm_free_msg(msg);
2489 deref:	cm_deref_id(cm_id_priv);
2490 }
2491 
2492 static int cm_rep_handler(struct cm_work *work)
2493 {
2494 	struct cm_id_private *cm_id_priv;
2495 	struct cm_rep_msg *rep_msg;
2496 	int ret;
2497 	struct cm_id_private *cur_cm_id_priv;
2498 	struct cm_timewait_info *timewait_info;
2499 
2500 	rep_msg = (struct cm_rep_msg *)work->mad_recv_wc->recv_buf.mad;
2501 	cm_id_priv = cm_acquire_id(
2502 		cpu_to_be32(IBA_GET(CM_REP_REMOTE_COMM_ID, rep_msg)), 0);
2503 	if (!cm_id_priv) {
2504 		cm_dup_rep_handler(work);
2505 		trace_icm_remote_no_priv_err(
2506 			 IBA_GET(CM_REP_REMOTE_COMM_ID, rep_msg));
2507 		return -EINVAL;
2508 	}
2509 
2510 	cm_format_rep_event(work, cm_id_priv->qp_type);
2511 
2512 	spin_lock_irq(&cm_id_priv->lock);
2513 	switch (cm_id_priv->id.state) {
2514 	case IB_CM_REQ_SENT:
2515 	case IB_CM_MRA_REQ_RCVD:
2516 		break;
2517 	default:
2518 		ret = -EINVAL;
2519 		trace_icm_rep_unknown_err(
2520 			IBA_GET(CM_REP_LOCAL_COMM_ID, rep_msg),
2521 			IBA_GET(CM_REP_REMOTE_COMM_ID, rep_msg),
2522 			cm_id_priv->id.state);
2523 		spin_unlock_irq(&cm_id_priv->lock);
2524 		goto error;
2525 	}
2526 
2527 	cm_id_priv->timewait_info->work.remote_id =
2528 		cpu_to_be32(IBA_GET(CM_REP_LOCAL_COMM_ID, rep_msg));
2529 	cm_id_priv->timewait_info->remote_ca_guid =
2530 		cpu_to_be64(IBA_GET(CM_REP_LOCAL_CA_GUID, rep_msg));
2531 	cm_id_priv->timewait_info->remote_qpn = cm_rep_get_qpn(rep_msg, cm_id_priv->qp_type);
2532 
2533 	spin_lock(&cm.lock);
2534 	/* Check for duplicate REP. */
2535 	if (cm_insert_remote_id(cm_id_priv->timewait_info)) {
2536 		spin_unlock(&cm.lock);
2537 		spin_unlock_irq(&cm_id_priv->lock);
2538 		ret = -EINVAL;
2539 		trace_icm_insert_failed_err(
2540 			 IBA_GET(CM_REP_REMOTE_COMM_ID, rep_msg));
2541 		goto error;
2542 	}
2543 	/* Check for a stale connection. */
2544 	timewait_info = cm_insert_remote_qpn(cm_id_priv->timewait_info);
2545 	if (timewait_info) {
2546 		cm_remove_remote(cm_id_priv);
2547 		cur_cm_id_priv = cm_acquire_id(timewait_info->work.local_id,
2548 					   timewait_info->work.remote_id);
2549 
2550 		spin_unlock(&cm.lock);
2551 		spin_unlock_irq(&cm_id_priv->lock);
2552 		cm_issue_rej(work->port, work->mad_recv_wc,
2553 			     IB_CM_REJ_STALE_CONN, CM_MSG_RESPONSE_REP,
2554 			     NULL, 0);
2555 		ret = -EINVAL;
2556 		trace_icm_staleconn_err(
2557 			IBA_GET(CM_REP_LOCAL_COMM_ID, rep_msg),
2558 			IBA_GET(CM_REP_REMOTE_COMM_ID, rep_msg));
2559 
2560 		if (cur_cm_id_priv) {
2561 			ib_send_cm_dreq(&cur_cm_id_priv->id, NULL, 0);
2562 			cm_deref_id(cur_cm_id_priv);
2563 		}
2564 
2565 		goto error;
2566 	}
2567 	spin_unlock(&cm.lock);
2568 
2569 	cm_id_priv->id.state = IB_CM_REP_RCVD;
2570 	cm_id_priv->id.remote_id =
2571 		cpu_to_be32(IBA_GET(CM_REP_LOCAL_COMM_ID, rep_msg));
2572 	cm_id_priv->remote_qpn = cm_rep_get_qpn(rep_msg, cm_id_priv->qp_type);
2573 	cm_id_priv->initiator_depth =
2574 		IBA_GET(CM_REP_RESPONDER_RESOURCES, rep_msg);
2575 	cm_id_priv->responder_resources =
2576 		IBA_GET(CM_REP_INITIATOR_DEPTH, rep_msg);
2577 	cm_id_priv->sq_psn = cpu_to_be32(IBA_GET(CM_REP_STARTING_PSN, rep_msg));
2578 	cm_id_priv->rnr_retry_count = IBA_GET(CM_REP_RNR_RETRY_COUNT, rep_msg);
2579 	cm_id_priv->target_ack_delay =
2580 		IBA_GET(CM_REP_TARGET_ACK_DELAY, rep_msg);
2581 	cm_id_priv->av.timeout =
2582 			cm_ack_timeout(cm_id_priv->target_ack_delay,
2583 				       cm_id_priv->av.timeout - 1);
2584 	cm_id_priv->alt_av.timeout =
2585 			cm_ack_timeout(cm_id_priv->target_ack_delay,
2586 				       cm_id_priv->alt_av.timeout - 1);
2587 
2588 	ib_cancel_mad(cm_id_priv->msg);
2589 	cm_queue_work_unlock(cm_id_priv, work);
2590 	return 0;
2591 
2592 error:
2593 	cm_deref_id(cm_id_priv);
2594 	return ret;
2595 }
2596 
2597 static int cm_establish_handler(struct cm_work *work)
2598 {
2599 	struct cm_id_private *cm_id_priv;
2600 
2601 	/* See comment in cm_establish about lookup. */
2602 	cm_id_priv = cm_acquire_id(work->local_id, work->remote_id);
2603 	if (!cm_id_priv)
2604 		return -EINVAL;
2605 
2606 	spin_lock_irq(&cm_id_priv->lock);
2607 	if (cm_id_priv->id.state != IB_CM_ESTABLISHED) {
2608 		spin_unlock_irq(&cm_id_priv->lock);
2609 		goto out;
2610 	}
2611 
2612 	ib_cancel_mad(cm_id_priv->msg);
2613 	cm_queue_work_unlock(cm_id_priv, work);
2614 	return 0;
2615 out:
2616 	cm_deref_id(cm_id_priv);
2617 	return -EINVAL;
2618 }
2619 
2620 static int cm_rtu_handler(struct cm_work *work)
2621 {
2622 	struct cm_id_private *cm_id_priv;
2623 	struct cm_rtu_msg *rtu_msg;
2624 
2625 	rtu_msg = (struct cm_rtu_msg *)work->mad_recv_wc->recv_buf.mad;
2626 	cm_id_priv = cm_acquire_id(
2627 		cpu_to_be32(IBA_GET(CM_RTU_REMOTE_COMM_ID, rtu_msg)),
2628 		cpu_to_be32(IBA_GET(CM_RTU_LOCAL_COMM_ID, rtu_msg)));
2629 	if (!cm_id_priv)
2630 		return -EINVAL;
2631 
2632 	work->cm_event.private_data =
2633 		IBA_GET_MEM_PTR(CM_RTU_PRIVATE_DATA, rtu_msg);
2634 
2635 	spin_lock_irq(&cm_id_priv->lock);
2636 	if (cm_id_priv->id.state != IB_CM_REP_SENT &&
2637 	    cm_id_priv->id.state != IB_CM_MRA_REP_RCVD) {
2638 		spin_unlock_irq(&cm_id_priv->lock);
2639 		atomic_long_inc(&work->port->counters[CM_RECV_DUPLICATES]
2640 						     [CM_RTU_COUNTER]);
2641 		goto out;
2642 	}
2643 	cm_id_priv->id.state = IB_CM_ESTABLISHED;
2644 
2645 	ib_cancel_mad(cm_id_priv->msg);
2646 	cm_queue_work_unlock(cm_id_priv, work);
2647 	return 0;
2648 out:
2649 	cm_deref_id(cm_id_priv);
2650 	return -EINVAL;
2651 }
2652 
2653 static void cm_format_dreq(struct cm_dreq_msg *dreq_msg,
2654 			  struct cm_id_private *cm_id_priv,
2655 			  const void *private_data,
2656 			  u8 private_data_len)
2657 {
2658 	cm_format_mad_hdr(&dreq_msg->hdr, CM_DREQ_ATTR_ID,
2659 			  cm_form_tid(cm_id_priv));
2660 	IBA_SET(CM_DREQ_LOCAL_COMM_ID, dreq_msg,
2661 		be32_to_cpu(cm_id_priv->id.local_id));
2662 	IBA_SET(CM_DREQ_REMOTE_COMM_ID, dreq_msg,
2663 		be32_to_cpu(cm_id_priv->id.remote_id));
2664 	IBA_SET(CM_DREQ_REMOTE_QPN_EECN, dreq_msg,
2665 		be32_to_cpu(cm_id_priv->remote_qpn));
2666 
2667 	if (private_data && private_data_len)
2668 		IBA_SET_MEM(CM_DREQ_PRIVATE_DATA, dreq_msg, private_data,
2669 			    private_data_len);
2670 }
2671 
2672 static void cm_issue_dreq(struct cm_id_private *cm_id_priv)
2673 {
2674 	struct ib_mad_send_buf *msg;
2675 	int ret;
2676 
2677 	lockdep_assert_held(&cm_id_priv->lock);
2678 
2679 	msg = cm_alloc_msg(cm_id_priv);
2680 	if (IS_ERR(msg))
2681 		return;
2682 
2683 	cm_format_dreq((struct cm_dreq_msg *) msg->mad, cm_id_priv, NULL, 0);
2684 
2685 	trace_icm_send_dreq(&cm_id_priv->id);
2686 	ret = ib_post_send_mad(msg, NULL);
2687 	if (ret)
2688 		cm_free_msg(msg);
2689 }
2690 
2691 int ib_send_cm_dreq(struct ib_cm_id *cm_id, const void *private_data,
2692 		    u8 private_data_len)
2693 {
2694 	struct cm_id_private *cm_id_priv =
2695 		container_of(cm_id, struct cm_id_private, id);
2696 	struct ib_mad_send_buf *msg;
2697 	unsigned long flags;
2698 	int ret;
2699 
2700 	if (private_data && private_data_len > IB_CM_DREQ_PRIVATE_DATA_SIZE)
2701 		return -EINVAL;
2702 
2703 	spin_lock_irqsave(&cm_id_priv->lock, flags);
2704 	if (cm_id_priv->id.state != IB_CM_ESTABLISHED) {
2705 		trace_icm_dreq_skipped(&cm_id_priv->id);
2706 		ret = -EINVAL;
2707 		goto unlock;
2708 	}
2709 
2710 	if (cm_id_priv->id.lap_state == IB_CM_LAP_SENT ||
2711 	    cm_id_priv->id.lap_state == IB_CM_MRA_LAP_RCVD)
2712 		ib_cancel_mad(cm_id_priv->msg);
2713 
2714 	msg = cm_alloc_priv_msg(cm_id_priv, IB_CM_DREQ_SENT);
2715 	if (IS_ERR(msg)) {
2716 		cm_enter_timewait(cm_id_priv);
2717 		ret = PTR_ERR(msg);
2718 		goto unlock;
2719 	}
2720 
2721 	cm_format_dreq((struct cm_dreq_msg *) msg->mad, cm_id_priv,
2722 		       private_data, private_data_len);
2723 
2724 	trace_icm_send_dreq(&cm_id_priv->id);
2725 	ret = ib_post_send_mad(msg, NULL);
2726 	if (ret) {
2727 		cm_enter_timewait(cm_id_priv);
2728 		cm_free_priv_msg(msg);
2729 		goto unlock;
2730 	}
2731 
2732 	cm_id_priv->id.state = IB_CM_DREQ_SENT;
2733 unlock:
2734 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
2735 	return ret;
2736 }
2737 EXPORT_SYMBOL(ib_send_cm_dreq);
2738 
2739 static void cm_format_drep(struct cm_drep_msg *drep_msg,
2740 			  struct cm_id_private *cm_id_priv,
2741 			  const void *private_data,
2742 			  u8 private_data_len)
2743 {
2744 	cm_format_mad_hdr(&drep_msg->hdr, CM_DREP_ATTR_ID, cm_id_priv->tid);
2745 	IBA_SET(CM_DREP_LOCAL_COMM_ID, drep_msg,
2746 		be32_to_cpu(cm_id_priv->id.local_id));
2747 	IBA_SET(CM_DREP_REMOTE_COMM_ID, drep_msg,
2748 		be32_to_cpu(cm_id_priv->id.remote_id));
2749 
2750 	if (private_data && private_data_len)
2751 		IBA_SET_MEM(CM_DREP_PRIVATE_DATA, drep_msg, private_data,
2752 			    private_data_len);
2753 }
2754 
2755 static int cm_send_drep_locked(struct cm_id_private *cm_id_priv,
2756 			       void *private_data, u8 private_data_len)
2757 {
2758 	struct ib_mad_send_buf *msg;
2759 	int ret;
2760 
2761 	lockdep_assert_held(&cm_id_priv->lock);
2762 
2763 	if (private_data && private_data_len > IB_CM_DREP_PRIVATE_DATA_SIZE)
2764 		return -EINVAL;
2765 
2766 	if (cm_id_priv->id.state != IB_CM_DREQ_RCVD) {
2767 		trace_icm_send_drep_err(&cm_id_priv->id);
2768 		kfree(private_data);
2769 		return -EINVAL;
2770 	}
2771 
2772 	cm_set_private_data(cm_id_priv, private_data, private_data_len);
2773 	cm_enter_timewait(cm_id_priv);
2774 
2775 	msg = cm_alloc_msg(cm_id_priv);
2776 	if (IS_ERR(msg))
2777 		return PTR_ERR(msg);
2778 
2779 	cm_format_drep((struct cm_drep_msg *) msg->mad, cm_id_priv,
2780 		       private_data, private_data_len);
2781 
2782 	trace_icm_send_drep(&cm_id_priv->id);
2783 	ret = ib_post_send_mad(msg, NULL);
2784 	if (ret) {
2785 		cm_free_msg(msg);
2786 		return ret;
2787 	}
2788 	return 0;
2789 }
2790 
2791 int ib_send_cm_drep(struct ib_cm_id *cm_id, const void *private_data,
2792 		    u8 private_data_len)
2793 {
2794 	struct cm_id_private *cm_id_priv =
2795 		container_of(cm_id, struct cm_id_private, id);
2796 	unsigned long flags;
2797 	void *data;
2798 	int ret;
2799 
2800 	data = cm_copy_private_data(private_data, private_data_len);
2801 	if (IS_ERR(data))
2802 		return PTR_ERR(data);
2803 
2804 	spin_lock_irqsave(&cm_id_priv->lock, flags);
2805 	ret = cm_send_drep_locked(cm_id_priv, data, private_data_len);
2806 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
2807 	return ret;
2808 }
2809 EXPORT_SYMBOL(ib_send_cm_drep);
2810 
2811 static int cm_issue_drep(struct cm_port *port,
2812 			 struct ib_mad_recv_wc *mad_recv_wc)
2813 {
2814 	struct ib_mad_send_buf *msg = NULL;
2815 	struct cm_dreq_msg *dreq_msg;
2816 	struct cm_drep_msg *drep_msg;
2817 	int ret;
2818 
2819 	ret = cm_alloc_response_msg(port, mad_recv_wc, true, &msg);
2820 	if (ret)
2821 		return ret;
2822 
2823 	dreq_msg = (struct cm_dreq_msg *) mad_recv_wc->recv_buf.mad;
2824 	drep_msg = (struct cm_drep_msg *) msg->mad;
2825 
2826 	cm_format_mad_hdr(&drep_msg->hdr, CM_DREP_ATTR_ID, dreq_msg->hdr.tid);
2827 	IBA_SET(CM_DREP_REMOTE_COMM_ID, drep_msg,
2828 		IBA_GET(CM_DREQ_LOCAL_COMM_ID, dreq_msg));
2829 	IBA_SET(CM_DREP_LOCAL_COMM_ID, drep_msg,
2830 		IBA_GET(CM_DREQ_REMOTE_COMM_ID, dreq_msg));
2831 
2832 	trace_icm_issue_drep(
2833 		IBA_GET(CM_DREQ_LOCAL_COMM_ID, dreq_msg),
2834 		IBA_GET(CM_DREQ_REMOTE_COMM_ID, dreq_msg));
2835 	ret = ib_post_send_mad(msg, NULL);
2836 	if (ret)
2837 		cm_free_msg(msg);
2838 
2839 	return ret;
2840 }
2841 
2842 static int cm_dreq_handler(struct cm_work *work)
2843 {
2844 	struct cm_id_private *cm_id_priv;
2845 	struct cm_dreq_msg *dreq_msg;
2846 	struct ib_mad_send_buf *msg = NULL;
2847 
2848 	dreq_msg = (struct cm_dreq_msg *)work->mad_recv_wc->recv_buf.mad;
2849 	cm_id_priv = cm_acquire_id(
2850 		cpu_to_be32(IBA_GET(CM_DREQ_REMOTE_COMM_ID, dreq_msg)),
2851 		cpu_to_be32(IBA_GET(CM_DREQ_LOCAL_COMM_ID, dreq_msg)));
2852 	if (!cm_id_priv) {
2853 		atomic_long_inc(&work->port->counters[CM_RECV_DUPLICATES]
2854 						     [CM_DREQ_COUNTER]);
2855 		cm_issue_drep(work->port, work->mad_recv_wc);
2856 		trace_icm_no_priv_err(
2857 			IBA_GET(CM_DREQ_LOCAL_COMM_ID, dreq_msg),
2858 			IBA_GET(CM_DREQ_REMOTE_COMM_ID, dreq_msg));
2859 		return -EINVAL;
2860 	}
2861 
2862 	work->cm_event.private_data =
2863 		IBA_GET_MEM_PTR(CM_DREQ_PRIVATE_DATA, dreq_msg);
2864 
2865 	spin_lock_irq(&cm_id_priv->lock);
2866 	if (cm_id_priv->local_qpn !=
2867 	    cpu_to_be32(IBA_GET(CM_DREQ_REMOTE_QPN_EECN, dreq_msg)))
2868 		goto unlock;
2869 
2870 	switch (cm_id_priv->id.state) {
2871 	case IB_CM_REP_SENT:
2872 	case IB_CM_DREQ_SENT:
2873 	case IB_CM_MRA_REP_RCVD:
2874 		ib_cancel_mad(cm_id_priv->msg);
2875 		break;
2876 	case IB_CM_ESTABLISHED:
2877 		if (cm_id_priv->id.lap_state == IB_CM_LAP_SENT ||
2878 		    cm_id_priv->id.lap_state == IB_CM_MRA_LAP_RCVD)
2879 			ib_cancel_mad(cm_id_priv->msg);
2880 		break;
2881 	case IB_CM_TIMEWAIT:
2882 		atomic_long_inc(&work->port->counters[CM_RECV_DUPLICATES]
2883 						     [CM_DREQ_COUNTER]);
2884 		msg = cm_alloc_response_msg_no_ah(work->port, work->mad_recv_wc,
2885 						  true);
2886 		if (IS_ERR(msg))
2887 			goto unlock;
2888 
2889 		cm_format_drep((struct cm_drep_msg *) msg->mad, cm_id_priv,
2890 			       cm_id_priv->private_data,
2891 			       cm_id_priv->private_data_len);
2892 		spin_unlock_irq(&cm_id_priv->lock);
2893 
2894 		if (cm_create_response_msg_ah(work->port, work->mad_recv_wc, msg) ||
2895 		    ib_post_send_mad(msg, NULL))
2896 			cm_free_msg(msg);
2897 		goto deref;
2898 	case IB_CM_DREQ_RCVD:
2899 		atomic_long_inc(&work->port->counters[CM_RECV_DUPLICATES]
2900 						     [CM_DREQ_COUNTER]);
2901 		goto unlock;
2902 	default:
2903 		trace_icm_dreq_unknown_err(&cm_id_priv->id);
2904 		goto unlock;
2905 	}
2906 	cm_id_priv->id.state = IB_CM_DREQ_RCVD;
2907 	cm_id_priv->tid = dreq_msg->hdr.tid;
2908 	cm_queue_work_unlock(cm_id_priv, work);
2909 	return 0;
2910 
2911 unlock:	spin_unlock_irq(&cm_id_priv->lock);
2912 deref:	cm_deref_id(cm_id_priv);
2913 	return -EINVAL;
2914 }
2915 
2916 static int cm_drep_handler(struct cm_work *work)
2917 {
2918 	struct cm_id_private *cm_id_priv;
2919 	struct cm_drep_msg *drep_msg;
2920 
2921 	drep_msg = (struct cm_drep_msg *)work->mad_recv_wc->recv_buf.mad;
2922 	cm_id_priv = cm_acquire_id(
2923 		cpu_to_be32(IBA_GET(CM_DREP_REMOTE_COMM_ID, drep_msg)),
2924 		cpu_to_be32(IBA_GET(CM_DREP_LOCAL_COMM_ID, drep_msg)));
2925 	if (!cm_id_priv)
2926 		return -EINVAL;
2927 
2928 	work->cm_event.private_data =
2929 		IBA_GET_MEM_PTR(CM_DREP_PRIVATE_DATA, drep_msg);
2930 
2931 	spin_lock_irq(&cm_id_priv->lock);
2932 	if (cm_id_priv->id.state != IB_CM_DREQ_SENT &&
2933 	    cm_id_priv->id.state != IB_CM_DREQ_RCVD) {
2934 		spin_unlock_irq(&cm_id_priv->lock);
2935 		goto out;
2936 	}
2937 	cm_enter_timewait(cm_id_priv);
2938 
2939 	ib_cancel_mad(cm_id_priv->msg);
2940 	cm_queue_work_unlock(cm_id_priv, work);
2941 	return 0;
2942 out:
2943 	cm_deref_id(cm_id_priv);
2944 	return -EINVAL;
2945 }
2946 
2947 static int cm_send_rej_locked(struct cm_id_private *cm_id_priv,
2948 			      enum ib_cm_rej_reason reason, void *ari,
2949 			      u8 ari_length, const void *private_data,
2950 			      u8 private_data_len)
2951 {
2952 	enum ib_cm_state state = cm_id_priv->id.state;
2953 	struct ib_mad_send_buf *msg;
2954 	int ret;
2955 
2956 	lockdep_assert_held(&cm_id_priv->lock);
2957 
2958 	if ((private_data && private_data_len > IB_CM_REJ_PRIVATE_DATA_SIZE) ||
2959 	    (ari && ari_length > IB_CM_REJ_ARI_LENGTH))
2960 		return -EINVAL;
2961 
2962 	trace_icm_send_rej(&cm_id_priv->id, reason);
2963 
2964 	switch (state) {
2965 	case IB_CM_REQ_SENT:
2966 	case IB_CM_MRA_REQ_RCVD:
2967 	case IB_CM_REQ_RCVD:
2968 	case IB_CM_MRA_REQ_SENT:
2969 	case IB_CM_REP_RCVD:
2970 	case IB_CM_MRA_REP_SENT:
2971 		cm_reset_to_idle(cm_id_priv);
2972 		msg = cm_alloc_msg(cm_id_priv);
2973 		if (IS_ERR(msg))
2974 			return PTR_ERR(msg);
2975 		cm_format_rej((struct cm_rej_msg *)msg->mad, cm_id_priv, reason,
2976 			      ari, ari_length, private_data, private_data_len,
2977 			      state);
2978 		break;
2979 	case IB_CM_REP_SENT:
2980 	case IB_CM_MRA_REP_RCVD:
2981 		cm_enter_timewait(cm_id_priv);
2982 		msg = cm_alloc_msg(cm_id_priv);
2983 		if (IS_ERR(msg))
2984 			return PTR_ERR(msg);
2985 		cm_format_rej((struct cm_rej_msg *)msg->mad, cm_id_priv, reason,
2986 			      ari, ari_length, private_data, private_data_len,
2987 			      state);
2988 		break;
2989 	default:
2990 		trace_icm_send_unknown_rej_err(&cm_id_priv->id);
2991 		return -EINVAL;
2992 	}
2993 
2994 	ret = ib_post_send_mad(msg, NULL);
2995 	if (ret) {
2996 		cm_free_msg(msg);
2997 		return ret;
2998 	}
2999 
3000 	return 0;
3001 }
3002 
3003 int ib_send_cm_rej(struct ib_cm_id *cm_id, enum ib_cm_rej_reason reason,
3004 		   void *ari, u8 ari_length, const void *private_data,
3005 		   u8 private_data_len)
3006 {
3007 	struct cm_id_private *cm_id_priv =
3008 		container_of(cm_id, struct cm_id_private, id);
3009 	unsigned long flags;
3010 	int ret;
3011 
3012 	spin_lock_irqsave(&cm_id_priv->lock, flags);
3013 	ret = cm_send_rej_locked(cm_id_priv, reason, ari, ari_length,
3014 				 private_data, private_data_len);
3015 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
3016 	return ret;
3017 }
3018 EXPORT_SYMBOL(ib_send_cm_rej);
3019 
3020 static void cm_format_rej_event(struct cm_work *work)
3021 {
3022 	struct cm_rej_msg *rej_msg;
3023 	struct ib_cm_rej_event_param *param;
3024 
3025 	rej_msg = (struct cm_rej_msg *)work->mad_recv_wc->recv_buf.mad;
3026 	param = &work->cm_event.param.rej_rcvd;
3027 	param->ari = IBA_GET_MEM_PTR(CM_REJ_ARI, rej_msg);
3028 	param->ari_length = IBA_GET(CM_REJ_REJECTED_INFO_LENGTH, rej_msg);
3029 	param->reason = IBA_GET(CM_REJ_REASON, rej_msg);
3030 	work->cm_event.private_data =
3031 		IBA_GET_MEM_PTR(CM_REJ_PRIVATE_DATA, rej_msg);
3032 }
3033 
3034 static struct cm_id_private *cm_acquire_rejected_id(struct cm_rej_msg *rej_msg)
3035 {
3036 	struct cm_id_private *cm_id_priv;
3037 	__be32 remote_id;
3038 
3039 	remote_id = cpu_to_be32(IBA_GET(CM_REJ_LOCAL_COMM_ID, rej_msg));
3040 
3041 	if (IBA_GET(CM_REJ_REASON, rej_msg) == IB_CM_REJ_TIMEOUT) {
3042 		cm_id_priv = cm_find_remote_id(
3043 			*((__be64 *)IBA_GET_MEM_PTR(CM_REJ_ARI, rej_msg)),
3044 			remote_id);
3045 	} else if (IBA_GET(CM_REJ_MESSAGE_REJECTED, rej_msg) ==
3046 		   CM_MSG_RESPONSE_REQ)
3047 		cm_id_priv = cm_acquire_id(
3048 			cpu_to_be32(IBA_GET(CM_REJ_REMOTE_COMM_ID, rej_msg)),
3049 			0);
3050 	else
3051 		cm_id_priv = cm_acquire_id(
3052 			cpu_to_be32(IBA_GET(CM_REJ_REMOTE_COMM_ID, rej_msg)),
3053 			remote_id);
3054 
3055 	return cm_id_priv;
3056 }
3057 
3058 static int cm_rej_handler(struct cm_work *work)
3059 {
3060 	struct cm_id_private *cm_id_priv;
3061 	struct cm_rej_msg *rej_msg;
3062 
3063 	rej_msg = (struct cm_rej_msg *)work->mad_recv_wc->recv_buf.mad;
3064 	cm_id_priv = cm_acquire_rejected_id(rej_msg);
3065 	if (!cm_id_priv)
3066 		return -EINVAL;
3067 
3068 	cm_format_rej_event(work);
3069 
3070 	spin_lock_irq(&cm_id_priv->lock);
3071 	switch (cm_id_priv->id.state) {
3072 	case IB_CM_REQ_SENT:
3073 	case IB_CM_MRA_REQ_RCVD:
3074 	case IB_CM_REP_SENT:
3075 	case IB_CM_MRA_REP_RCVD:
3076 		ib_cancel_mad(cm_id_priv->msg);
3077 		fallthrough;
3078 	case IB_CM_REQ_RCVD:
3079 	case IB_CM_MRA_REQ_SENT:
3080 		if (IBA_GET(CM_REJ_REASON, rej_msg) == IB_CM_REJ_STALE_CONN)
3081 			cm_enter_timewait(cm_id_priv);
3082 		else
3083 			cm_reset_to_idle(cm_id_priv);
3084 		break;
3085 	case IB_CM_DREQ_SENT:
3086 		ib_cancel_mad(cm_id_priv->msg);
3087 		fallthrough;
3088 	case IB_CM_REP_RCVD:
3089 	case IB_CM_MRA_REP_SENT:
3090 		cm_enter_timewait(cm_id_priv);
3091 		break;
3092 	case IB_CM_ESTABLISHED:
3093 		if (cm_id_priv->id.lap_state == IB_CM_LAP_UNINIT ||
3094 		    cm_id_priv->id.lap_state == IB_CM_LAP_SENT) {
3095 			if (cm_id_priv->id.lap_state == IB_CM_LAP_SENT)
3096 				ib_cancel_mad(cm_id_priv->msg);
3097 			cm_enter_timewait(cm_id_priv);
3098 			break;
3099 		}
3100 		fallthrough;
3101 	default:
3102 		trace_icm_rej_unknown_err(&cm_id_priv->id);
3103 		spin_unlock_irq(&cm_id_priv->lock);
3104 		goto out;
3105 	}
3106 
3107 	cm_queue_work_unlock(cm_id_priv, work);
3108 	return 0;
3109 out:
3110 	cm_deref_id(cm_id_priv);
3111 	return -EINVAL;
3112 }
3113 
3114 int ib_prepare_cm_mra(struct ib_cm_id *cm_id)
3115 {
3116 	struct cm_id_private *cm_id_priv;
3117 	enum ib_cm_state cm_state;
3118 	enum ib_cm_lap_state lap_state;
3119 	unsigned long flags;
3120 	int ret = 0;
3121 
3122 	cm_id_priv = container_of(cm_id, struct cm_id_private, id);
3123 
3124 	spin_lock_irqsave(&cm_id_priv->lock, flags);
3125 	switch (cm_id_priv->id.state) {
3126 	case IB_CM_REQ_RCVD:
3127 		cm_state = IB_CM_MRA_REQ_SENT;
3128 		lap_state = cm_id->lap_state;
3129 		break;
3130 	case IB_CM_REP_RCVD:
3131 		cm_state = IB_CM_MRA_REP_SENT;
3132 		lap_state = cm_id->lap_state;
3133 		break;
3134 	case IB_CM_ESTABLISHED:
3135 		if (cm_id->lap_state == IB_CM_LAP_RCVD) {
3136 			cm_state = cm_id->state;
3137 			lap_state = IB_CM_MRA_LAP_SENT;
3138 			break;
3139 		}
3140 		fallthrough;
3141 	default:
3142 		trace_icm_prepare_mra_unknown_err(&cm_id_priv->id);
3143 		ret = -EINVAL;
3144 		goto error_unlock;
3145 	}
3146 
3147 	cm_id->state = cm_state;
3148 	cm_id->lap_state = lap_state;
3149 	cm_set_private_data(cm_id_priv, NULL, 0);
3150 
3151 error_unlock:
3152 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
3153 	return ret;
3154 }
3155 EXPORT_SYMBOL(ib_prepare_cm_mra);
3156 
3157 static struct cm_id_private *cm_acquire_mraed_id(struct cm_mra_msg *mra_msg)
3158 {
3159 	switch (IBA_GET(CM_MRA_MESSAGE_MRAED, mra_msg)) {
3160 	case CM_MSG_RESPONSE_REQ:
3161 		return cm_acquire_id(
3162 			cpu_to_be32(IBA_GET(CM_MRA_REMOTE_COMM_ID, mra_msg)),
3163 			0);
3164 	case CM_MSG_RESPONSE_REP:
3165 	case CM_MSG_RESPONSE_OTHER:
3166 		return cm_acquire_id(
3167 			cpu_to_be32(IBA_GET(CM_MRA_REMOTE_COMM_ID, mra_msg)),
3168 			cpu_to_be32(IBA_GET(CM_MRA_LOCAL_COMM_ID, mra_msg)));
3169 	default:
3170 		return NULL;
3171 	}
3172 }
3173 
3174 static int cm_mra_handler(struct cm_work *work)
3175 {
3176 	struct cm_id_private *cm_id_priv;
3177 	struct cm_mra_msg *mra_msg;
3178 	int timeout;
3179 
3180 	mra_msg = (struct cm_mra_msg *)work->mad_recv_wc->recv_buf.mad;
3181 	cm_id_priv = cm_acquire_mraed_id(mra_msg);
3182 	if (!cm_id_priv)
3183 		return -EINVAL;
3184 
3185 	work->cm_event.private_data =
3186 		IBA_GET_MEM_PTR(CM_MRA_PRIVATE_DATA, mra_msg);
3187 	work->cm_event.param.mra_rcvd.service_timeout =
3188 		IBA_GET(CM_MRA_SERVICE_TIMEOUT, mra_msg);
3189 	timeout = cm_convert_to_ms(IBA_GET(CM_MRA_SERVICE_TIMEOUT, mra_msg)) +
3190 		  cm_convert_to_ms(cm_id_priv->av.timeout);
3191 
3192 	spin_lock_irq(&cm_id_priv->lock);
3193 	switch (cm_id_priv->id.state) {
3194 	case IB_CM_REQ_SENT:
3195 		if (IBA_GET(CM_MRA_MESSAGE_MRAED, mra_msg) !=
3196 			    CM_MSG_RESPONSE_REQ ||
3197 		    ib_modify_mad(cm_id_priv->msg, timeout))
3198 			goto out;
3199 		cm_id_priv->id.state = IB_CM_MRA_REQ_RCVD;
3200 		break;
3201 	case IB_CM_REP_SENT:
3202 		if (IBA_GET(CM_MRA_MESSAGE_MRAED, mra_msg) !=
3203 			    CM_MSG_RESPONSE_REP ||
3204 		    ib_modify_mad(cm_id_priv->msg, timeout))
3205 			goto out;
3206 		cm_id_priv->id.state = IB_CM_MRA_REP_RCVD;
3207 		break;
3208 	case IB_CM_ESTABLISHED:
3209 		if (IBA_GET(CM_MRA_MESSAGE_MRAED, mra_msg) !=
3210 			    CM_MSG_RESPONSE_OTHER ||
3211 		    cm_id_priv->id.lap_state != IB_CM_LAP_SENT ||
3212 		    ib_modify_mad(cm_id_priv->msg, timeout)) {
3213 			if (cm_id_priv->id.lap_state == IB_CM_MRA_LAP_RCVD)
3214 				atomic_long_inc(
3215 					&work->port->counters[CM_RECV_DUPLICATES]
3216 							     [CM_MRA_COUNTER]);
3217 			goto out;
3218 		}
3219 		cm_id_priv->id.lap_state = IB_CM_MRA_LAP_RCVD;
3220 		break;
3221 	case IB_CM_MRA_REQ_RCVD:
3222 	case IB_CM_MRA_REP_RCVD:
3223 		atomic_long_inc(&work->port->counters[CM_RECV_DUPLICATES]
3224 						     [CM_MRA_COUNTER]);
3225 		fallthrough;
3226 	default:
3227 		trace_icm_mra_unknown_err(&cm_id_priv->id);
3228 		goto out;
3229 	}
3230 
3231 	cm_id_priv->msg->context[1] = (void *) (unsigned long)
3232 				      cm_id_priv->id.state;
3233 	cm_queue_work_unlock(cm_id_priv, work);
3234 	return 0;
3235 out:
3236 	spin_unlock_irq(&cm_id_priv->lock);
3237 	cm_deref_id(cm_id_priv);
3238 	return -EINVAL;
3239 }
3240 
3241 static void cm_format_path_lid_from_lap(struct cm_lap_msg *lap_msg,
3242 					struct sa_path_rec *path)
3243 {
3244 	u32 lid;
3245 
3246 	if (path->rec_type != SA_PATH_REC_TYPE_OPA) {
3247 		sa_path_set_dlid(path, IBA_GET(CM_LAP_ALTERNATE_LOCAL_PORT_LID,
3248 					       lap_msg));
3249 		sa_path_set_slid(path, IBA_GET(CM_LAP_ALTERNATE_REMOTE_PORT_LID,
3250 					       lap_msg));
3251 	} else {
3252 		lid = opa_get_lid_from_gid(IBA_GET_MEM_PTR(
3253 			CM_LAP_ALTERNATE_LOCAL_PORT_GID, lap_msg));
3254 		sa_path_set_dlid(path, lid);
3255 
3256 		lid = opa_get_lid_from_gid(IBA_GET_MEM_PTR(
3257 			CM_LAP_ALTERNATE_REMOTE_PORT_GID, lap_msg));
3258 		sa_path_set_slid(path, lid);
3259 	}
3260 }
3261 
3262 static void cm_format_path_from_lap(struct cm_id_private *cm_id_priv,
3263 				    struct sa_path_rec *path,
3264 				    struct cm_lap_msg *lap_msg)
3265 {
3266 	path->dgid = *IBA_GET_MEM_PTR(CM_LAP_ALTERNATE_LOCAL_PORT_GID, lap_msg);
3267 	path->sgid =
3268 		*IBA_GET_MEM_PTR(CM_LAP_ALTERNATE_REMOTE_PORT_GID, lap_msg);
3269 	path->flow_label =
3270 		cpu_to_be32(IBA_GET(CM_LAP_ALTERNATE_FLOW_LABEL, lap_msg));
3271 	path->hop_limit = IBA_GET(CM_LAP_ALTERNATE_HOP_LIMIT, lap_msg);
3272 	path->traffic_class = IBA_GET(CM_LAP_ALTERNATE_TRAFFIC_CLASS, lap_msg);
3273 	path->reversible = 1;
3274 	path->pkey = cm_id_priv->pkey;
3275 	path->sl = IBA_GET(CM_LAP_ALTERNATE_SL, lap_msg);
3276 	path->mtu_selector = IB_SA_EQ;
3277 	path->mtu = cm_id_priv->path_mtu;
3278 	path->rate_selector = IB_SA_EQ;
3279 	path->rate = IBA_GET(CM_LAP_ALTERNATE_PACKET_RATE, lap_msg);
3280 	path->packet_life_time_selector = IB_SA_EQ;
3281 	path->packet_life_time =
3282 		IBA_GET(CM_LAP_ALTERNATE_LOCAL_ACK_TIMEOUT, lap_msg);
3283 	path->packet_life_time -= (path->packet_life_time > 0);
3284 	cm_format_path_lid_from_lap(lap_msg, path);
3285 }
3286 
3287 static int cm_lap_handler(struct cm_work *work)
3288 {
3289 	struct cm_id_private *cm_id_priv;
3290 	struct cm_lap_msg *lap_msg;
3291 	struct ib_cm_lap_event_param *param;
3292 	struct ib_mad_send_buf *msg = NULL;
3293 	struct rdma_ah_attr ah_attr;
3294 	struct cm_av alt_av = {};
3295 	int ret;
3296 
3297 	/* Currently Alternate path messages are not supported for
3298 	 * RoCE link layer.
3299 	 */
3300 	if (rdma_protocol_roce(work->port->cm_dev->ib_device,
3301 			       work->port->port_num))
3302 		return -EINVAL;
3303 
3304 	/* todo: verify LAP request and send reject APR if invalid. */
3305 	lap_msg = (struct cm_lap_msg *)work->mad_recv_wc->recv_buf.mad;
3306 	cm_id_priv = cm_acquire_id(
3307 		cpu_to_be32(IBA_GET(CM_LAP_REMOTE_COMM_ID, lap_msg)),
3308 		cpu_to_be32(IBA_GET(CM_LAP_LOCAL_COMM_ID, lap_msg)));
3309 	if (!cm_id_priv)
3310 		return -EINVAL;
3311 
3312 	param = &work->cm_event.param.lap_rcvd;
3313 	memset(&work->path[0], 0, sizeof(work->path[1]));
3314 	cm_path_set_rec_type(work->port->cm_dev->ib_device,
3315 			     work->port->port_num, &work->path[0],
3316 			     IBA_GET_MEM_PTR(CM_LAP_ALTERNATE_LOCAL_PORT_GID,
3317 					     lap_msg));
3318 	param->alternate_path = &work->path[0];
3319 	cm_format_path_from_lap(cm_id_priv, param->alternate_path, lap_msg);
3320 	work->cm_event.private_data =
3321 		IBA_GET_MEM_PTR(CM_LAP_PRIVATE_DATA, lap_msg);
3322 
3323 	ret = ib_init_ah_attr_from_wc(work->port->cm_dev->ib_device,
3324 				      work->port->port_num,
3325 				      work->mad_recv_wc->wc,
3326 				      work->mad_recv_wc->recv_buf.grh,
3327 				      &ah_attr);
3328 	if (ret)
3329 		goto deref;
3330 
3331 	ret = cm_init_av_by_path(param->alternate_path, NULL, &alt_av);
3332 	if (ret) {
3333 		rdma_destroy_ah_attr(&ah_attr);
3334 		goto deref;
3335 	}
3336 
3337 	spin_lock_irq(&cm_id_priv->lock);
3338 	cm_init_av_for_lap(work->port, work->mad_recv_wc->wc,
3339 			   &ah_attr, &cm_id_priv->av);
3340 	cm_move_av_from_path(&cm_id_priv->alt_av, &alt_av);
3341 
3342 	if (cm_id_priv->id.state != IB_CM_ESTABLISHED)
3343 		goto unlock;
3344 
3345 	switch (cm_id_priv->id.lap_state) {
3346 	case IB_CM_LAP_UNINIT:
3347 	case IB_CM_LAP_IDLE:
3348 		break;
3349 	case IB_CM_MRA_LAP_SENT:
3350 		atomic_long_inc(&work->port->counters[CM_RECV_DUPLICATES]
3351 						     [CM_LAP_COUNTER]);
3352 		msg = cm_alloc_response_msg_no_ah(work->port, work->mad_recv_wc,
3353 						  true);
3354 		if (IS_ERR(msg))
3355 			goto unlock;
3356 
3357 		cm_format_mra((struct cm_mra_msg *) msg->mad, cm_id_priv,
3358 			      CM_MSG_RESPONSE_OTHER,
3359 			      cm_id_priv->private_data,
3360 			      cm_id_priv->private_data_len);
3361 		spin_unlock_irq(&cm_id_priv->lock);
3362 
3363 		if (cm_create_response_msg_ah(work->port, work->mad_recv_wc, msg) ||
3364 		    ib_post_send_mad(msg, NULL))
3365 			cm_free_msg(msg);
3366 		goto deref;
3367 	case IB_CM_LAP_RCVD:
3368 		atomic_long_inc(&work->port->counters[CM_RECV_DUPLICATES]
3369 						     [CM_LAP_COUNTER]);
3370 		goto unlock;
3371 	default:
3372 		goto unlock;
3373 	}
3374 
3375 	cm_id_priv->id.lap_state = IB_CM_LAP_RCVD;
3376 	cm_id_priv->tid = lap_msg->hdr.tid;
3377 	cm_queue_work_unlock(cm_id_priv, work);
3378 	return 0;
3379 
3380 unlock:	spin_unlock_irq(&cm_id_priv->lock);
3381 deref:	cm_deref_id(cm_id_priv);
3382 	return -EINVAL;
3383 }
3384 
3385 static int cm_apr_handler(struct cm_work *work)
3386 {
3387 	struct cm_id_private *cm_id_priv;
3388 	struct cm_apr_msg *apr_msg;
3389 
3390 	/* Currently Alternate path messages are not supported for
3391 	 * RoCE link layer.
3392 	 */
3393 	if (rdma_protocol_roce(work->port->cm_dev->ib_device,
3394 			       work->port->port_num))
3395 		return -EINVAL;
3396 
3397 	apr_msg = (struct cm_apr_msg *)work->mad_recv_wc->recv_buf.mad;
3398 	cm_id_priv = cm_acquire_id(
3399 		cpu_to_be32(IBA_GET(CM_APR_REMOTE_COMM_ID, apr_msg)),
3400 		cpu_to_be32(IBA_GET(CM_APR_LOCAL_COMM_ID, apr_msg)));
3401 	if (!cm_id_priv)
3402 		return -EINVAL; /* Unmatched reply. */
3403 
3404 	work->cm_event.param.apr_rcvd.ap_status =
3405 		IBA_GET(CM_APR_AR_STATUS, apr_msg);
3406 	work->cm_event.param.apr_rcvd.apr_info =
3407 		IBA_GET_MEM_PTR(CM_APR_ADDITIONAL_INFORMATION, apr_msg);
3408 	work->cm_event.param.apr_rcvd.info_len =
3409 		IBA_GET(CM_APR_ADDITIONAL_INFORMATION_LENGTH, apr_msg);
3410 	work->cm_event.private_data =
3411 		IBA_GET_MEM_PTR(CM_APR_PRIVATE_DATA, apr_msg);
3412 
3413 	spin_lock_irq(&cm_id_priv->lock);
3414 	if (cm_id_priv->id.state != IB_CM_ESTABLISHED ||
3415 	    (cm_id_priv->id.lap_state != IB_CM_LAP_SENT &&
3416 	     cm_id_priv->id.lap_state != IB_CM_MRA_LAP_RCVD)) {
3417 		spin_unlock_irq(&cm_id_priv->lock);
3418 		goto out;
3419 	}
3420 	cm_id_priv->id.lap_state = IB_CM_LAP_IDLE;
3421 	ib_cancel_mad(cm_id_priv->msg);
3422 	cm_queue_work_unlock(cm_id_priv, work);
3423 	return 0;
3424 out:
3425 	cm_deref_id(cm_id_priv);
3426 	return -EINVAL;
3427 }
3428 
3429 static int cm_timewait_handler(struct cm_work *work)
3430 {
3431 	struct cm_timewait_info *timewait_info;
3432 	struct cm_id_private *cm_id_priv;
3433 
3434 	timewait_info = container_of(work, struct cm_timewait_info, work);
3435 	spin_lock_irq(&cm.lock);
3436 	list_del(&timewait_info->list);
3437 	spin_unlock_irq(&cm.lock);
3438 
3439 	cm_id_priv = cm_acquire_id(timewait_info->work.local_id,
3440 				   timewait_info->work.remote_id);
3441 	if (!cm_id_priv)
3442 		return -EINVAL;
3443 
3444 	spin_lock_irq(&cm_id_priv->lock);
3445 	if (cm_id_priv->id.state != IB_CM_TIMEWAIT ||
3446 	    cm_id_priv->remote_qpn != timewait_info->remote_qpn) {
3447 		spin_unlock_irq(&cm_id_priv->lock);
3448 		goto out;
3449 	}
3450 	cm_id_priv->id.state = IB_CM_IDLE;
3451 	cm_queue_work_unlock(cm_id_priv, work);
3452 	return 0;
3453 out:
3454 	cm_deref_id(cm_id_priv);
3455 	return -EINVAL;
3456 }
3457 
3458 static void cm_format_sidr_req(struct cm_sidr_req_msg *sidr_req_msg,
3459 			       struct cm_id_private *cm_id_priv,
3460 			       struct ib_cm_sidr_req_param *param)
3461 {
3462 	cm_format_mad_hdr(&sidr_req_msg->hdr, CM_SIDR_REQ_ATTR_ID,
3463 			  cm_form_tid(cm_id_priv));
3464 	IBA_SET(CM_SIDR_REQ_REQUESTID, sidr_req_msg,
3465 		be32_to_cpu(cm_id_priv->id.local_id));
3466 	IBA_SET(CM_SIDR_REQ_PARTITION_KEY, sidr_req_msg,
3467 		be16_to_cpu(param->path->pkey));
3468 	IBA_SET(CM_SIDR_REQ_SERVICEID, sidr_req_msg,
3469 		be64_to_cpu(param->service_id));
3470 
3471 	if (param->private_data && param->private_data_len)
3472 		IBA_SET_MEM(CM_SIDR_REQ_PRIVATE_DATA, sidr_req_msg,
3473 			    param->private_data, param->private_data_len);
3474 }
3475 
3476 int ib_send_cm_sidr_req(struct ib_cm_id *cm_id,
3477 			struct ib_cm_sidr_req_param *param)
3478 {
3479 	struct cm_id_private *cm_id_priv;
3480 	struct ib_mad_send_buf *msg;
3481 	struct cm_av av = {};
3482 	unsigned long flags;
3483 	int ret;
3484 
3485 	if (!param->path || (param->private_data &&
3486 	     param->private_data_len > IB_CM_SIDR_REQ_PRIVATE_DATA_SIZE))
3487 		return -EINVAL;
3488 
3489 	cm_id_priv = container_of(cm_id, struct cm_id_private, id);
3490 	ret = cm_init_av_by_path(param->path, param->sgid_attr, &av);
3491 	if (ret)
3492 		return ret;
3493 
3494 	spin_lock_irqsave(&cm_id_priv->lock, flags);
3495 	cm_move_av_from_path(&cm_id_priv->av, &av);
3496 	cm_id->service_id = param->service_id;
3497 	cm_id_priv->timeout_ms = param->timeout_ms;
3498 	cm_id_priv->max_cm_retries = param->max_cm_retries;
3499 	if (cm_id->state != IB_CM_IDLE) {
3500 		ret = -EINVAL;
3501 		goto out_unlock;
3502 	}
3503 
3504 	msg = cm_alloc_priv_msg(cm_id_priv, IB_CM_SIDR_REQ_SENT);
3505 	if (IS_ERR(msg)) {
3506 		ret = PTR_ERR(msg);
3507 		goto out_unlock;
3508 	}
3509 
3510 	cm_format_sidr_req((struct cm_sidr_req_msg *)msg->mad, cm_id_priv,
3511 			   param);
3512 
3513 	trace_icm_send_sidr_req(&cm_id_priv->id);
3514 	ret = ib_post_send_mad(msg, NULL);
3515 	if (ret)
3516 		goto out_free;
3517 	cm_id->state = IB_CM_SIDR_REQ_SENT;
3518 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
3519 	return 0;
3520 out_free:
3521 	cm_free_priv_msg(msg);
3522 out_unlock:
3523 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
3524 	return ret;
3525 }
3526 EXPORT_SYMBOL(ib_send_cm_sidr_req);
3527 
3528 static void cm_format_sidr_req_event(struct cm_work *work,
3529 				     const struct cm_id_private *rx_cm_id,
3530 				     struct ib_cm_id *listen_id)
3531 {
3532 	struct cm_sidr_req_msg *sidr_req_msg;
3533 	struct ib_cm_sidr_req_event_param *param;
3534 
3535 	sidr_req_msg = (struct cm_sidr_req_msg *)
3536 				work->mad_recv_wc->recv_buf.mad;
3537 	param = &work->cm_event.param.sidr_req_rcvd;
3538 	param->pkey = IBA_GET(CM_SIDR_REQ_PARTITION_KEY, sidr_req_msg);
3539 	param->listen_id = listen_id;
3540 	param->service_id =
3541 		cpu_to_be64(IBA_GET(CM_SIDR_REQ_SERVICEID, sidr_req_msg));
3542 	param->bth_pkey = cm_get_bth_pkey(work);
3543 	param->port = work->port->port_num;
3544 	param->sgid_attr = rx_cm_id->av.ah_attr.grh.sgid_attr;
3545 	work->cm_event.private_data =
3546 		IBA_GET_MEM_PTR(CM_SIDR_REQ_PRIVATE_DATA, sidr_req_msg);
3547 }
3548 
3549 static int cm_sidr_req_handler(struct cm_work *work)
3550 {
3551 	struct cm_id_private *cm_id_priv, *listen_cm_id_priv;
3552 	struct cm_sidr_req_msg *sidr_req_msg;
3553 	struct ib_wc *wc;
3554 	int ret;
3555 
3556 	cm_id_priv =
3557 		cm_alloc_id_priv(work->port->cm_dev->ib_device, NULL, NULL);
3558 	if (IS_ERR(cm_id_priv))
3559 		return PTR_ERR(cm_id_priv);
3560 
3561 	/* Record SGID/SLID and request ID for lookup. */
3562 	sidr_req_msg = (struct cm_sidr_req_msg *)
3563 				work->mad_recv_wc->recv_buf.mad;
3564 
3565 	cm_id_priv->id.remote_id =
3566 		cpu_to_be32(IBA_GET(CM_SIDR_REQ_REQUESTID, sidr_req_msg));
3567 	cm_id_priv->id.service_id =
3568 		cpu_to_be64(IBA_GET(CM_SIDR_REQ_SERVICEID, sidr_req_msg));
3569 	cm_id_priv->tid = sidr_req_msg->hdr.tid;
3570 
3571 	wc = work->mad_recv_wc->wc;
3572 	cm_id_priv->sidr_slid = wc->slid;
3573 	ret = cm_init_av_for_response(work->port, work->mad_recv_wc->wc,
3574 				      work->mad_recv_wc->recv_buf.grh,
3575 				      &cm_id_priv->av);
3576 	if (ret)
3577 		goto out;
3578 
3579 	spin_lock_irq(&cm.lock);
3580 	listen_cm_id_priv = cm_insert_remote_sidr(cm_id_priv);
3581 	if (listen_cm_id_priv) {
3582 		spin_unlock_irq(&cm.lock);
3583 		atomic_long_inc(&work->port->counters[CM_RECV_DUPLICATES]
3584 						     [CM_SIDR_REQ_COUNTER]);
3585 		goto out; /* Duplicate message. */
3586 	}
3587 	cm_id_priv->id.state = IB_CM_SIDR_REQ_RCVD;
3588 	listen_cm_id_priv = cm_find_listen(cm_id_priv->id.device,
3589 					   cm_id_priv->id.service_id);
3590 	if (!listen_cm_id_priv) {
3591 		spin_unlock_irq(&cm.lock);
3592 		ib_send_cm_sidr_rep(&cm_id_priv->id,
3593 				    &(struct ib_cm_sidr_rep_param){
3594 					    .status = IB_SIDR_UNSUPPORTED });
3595 		goto out; /* No match. */
3596 	}
3597 	spin_unlock_irq(&cm.lock);
3598 
3599 	cm_id_priv->id.cm_handler = listen_cm_id_priv->id.cm_handler;
3600 	cm_id_priv->id.context = listen_cm_id_priv->id.context;
3601 
3602 	/*
3603 	 * A SIDR ID does not need to be in the xarray since it does not receive
3604 	 * mads, is not placed in the remote_id or remote_qpn rbtree, and does
3605 	 * not enter timewait.
3606 	 */
3607 
3608 	cm_format_sidr_req_event(work, cm_id_priv, &listen_cm_id_priv->id);
3609 	ret = cm_id_priv->id.cm_handler(&cm_id_priv->id, &work->cm_event);
3610 	cm_free_work(work);
3611 	/*
3612 	 * A pointer to the listen_cm_id is held in the event, so this deref
3613 	 * must be after the event is delivered above.
3614 	 */
3615 	cm_deref_id(listen_cm_id_priv);
3616 	if (ret)
3617 		cm_destroy_id(&cm_id_priv->id, ret);
3618 	return 0;
3619 out:
3620 	ib_destroy_cm_id(&cm_id_priv->id);
3621 	return -EINVAL;
3622 }
3623 
3624 static void cm_format_sidr_rep(struct cm_sidr_rep_msg *sidr_rep_msg,
3625 			       struct cm_id_private *cm_id_priv,
3626 			       struct ib_cm_sidr_rep_param *param)
3627 {
3628 	cm_format_mad_ece_hdr(&sidr_rep_msg->hdr, CM_SIDR_REP_ATTR_ID,
3629 			      cm_id_priv->tid, param->ece.attr_mod);
3630 	IBA_SET(CM_SIDR_REP_REQUESTID, sidr_rep_msg,
3631 		be32_to_cpu(cm_id_priv->id.remote_id));
3632 	IBA_SET(CM_SIDR_REP_STATUS, sidr_rep_msg, param->status);
3633 	IBA_SET(CM_SIDR_REP_QPN, sidr_rep_msg, param->qp_num);
3634 	IBA_SET(CM_SIDR_REP_SERVICEID, sidr_rep_msg,
3635 		be64_to_cpu(cm_id_priv->id.service_id));
3636 	IBA_SET(CM_SIDR_REP_Q_KEY, sidr_rep_msg, param->qkey);
3637 	IBA_SET(CM_SIDR_REP_VENDOR_ID_L, sidr_rep_msg,
3638 		param->ece.vendor_id & 0xFF);
3639 	IBA_SET(CM_SIDR_REP_VENDOR_ID_H, sidr_rep_msg,
3640 		(param->ece.vendor_id >> 8) & 0xFF);
3641 
3642 	if (param->info && param->info_length)
3643 		IBA_SET_MEM(CM_SIDR_REP_ADDITIONAL_INFORMATION, sidr_rep_msg,
3644 			    param->info, param->info_length);
3645 
3646 	if (param->private_data && param->private_data_len)
3647 		IBA_SET_MEM(CM_SIDR_REP_PRIVATE_DATA, sidr_rep_msg,
3648 			    param->private_data, param->private_data_len);
3649 }
3650 
3651 static int cm_send_sidr_rep_locked(struct cm_id_private *cm_id_priv,
3652 				   struct ib_cm_sidr_rep_param *param)
3653 {
3654 	struct ib_mad_send_buf *msg;
3655 	unsigned long flags;
3656 	int ret;
3657 
3658 	lockdep_assert_held(&cm_id_priv->lock);
3659 
3660 	if ((param->info && param->info_length > IB_CM_SIDR_REP_INFO_LENGTH) ||
3661 	    (param->private_data &&
3662 	     param->private_data_len > IB_CM_SIDR_REP_PRIVATE_DATA_SIZE))
3663 		return -EINVAL;
3664 
3665 	if (cm_id_priv->id.state != IB_CM_SIDR_REQ_RCVD)
3666 		return -EINVAL;
3667 
3668 	msg = cm_alloc_msg(cm_id_priv);
3669 	if (IS_ERR(msg))
3670 		return PTR_ERR(msg);
3671 
3672 	cm_format_sidr_rep((struct cm_sidr_rep_msg *) msg->mad, cm_id_priv,
3673 			   param);
3674 	trace_icm_send_sidr_rep(&cm_id_priv->id);
3675 	ret = ib_post_send_mad(msg, NULL);
3676 	if (ret) {
3677 		cm_free_msg(msg);
3678 		return ret;
3679 	}
3680 	cm_id_priv->id.state = IB_CM_IDLE;
3681 	spin_lock_irqsave(&cm.lock, flags);
3682 	if (!RB_EMPTY_NODE(&cm_id_priv->sidr_id_node)) {
3683 		rb_erase(&cm_id_priv->sidr_id_node, &cm.remote_sidr_table);
3684 		RB_CLEAR_NODE(&cm_id_priv->sidr_id_node);
3685 	}
3686 	spin_unlock_irqrestore(&cm.lock, flags);
3687 	return 0;
3688 }
3689 
3690 int ib_send_cm_sidr_rep(struct ib_cm_id *cm_id,
3691 			struct ib_cm_sidr_rep_param *param)
3692 {
3693 	struct cm_id_private *cm_id_priv =
3694 		container_of(cm_id, struct cm_id_private, id);
3695 	unsigned long flags;
3696 	int ret;
3697 
3698 	spin_lock_irqsave(&cm_id_priv->lock, flags);
3699 	ret = cm_send_sidr_rep_locked(cm_id_priv, param);
3700 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
3701 	return ret;
3702 }
3703 EXPORT_SYMBOL(ib_send_cm_sidr_rep);
3704 
3705 static void cm_format_sidr_rep_event(struct cm_work *work,
3706 				     const struct cm_id_private *cm_id_priv)
3707 {
3708 	struct cm_sidr_rep_msg *sidr_rep_msg;
3709 	struct ib_cm_sidr_rep_event_param *param;
3710 
3711 	sidr_rep_msg = (struct cm_sidr_rep_msg *)
3712 				work->mad_recv_wc->recv_buf.mad;
3713 	param = &work->cm_event.param.sidr_rep_rcvd;
3714 	param->status = IBA_GET(CM_SIDR_REP_STATUS, sidr_rep_msg);
3715 	param->qkey = IBA_GET(CM_SIDR_REP_Q_KEY, sidr_rep_msg);
3716 	param->qpn = IBA_GET(CM_SIDR_REP_QPN, sidr_rep_msg);
3717 	param->info = IBA_GET_MEM_PTR(CM_SIDR_REP_ADDITIONAL_INFORMATION,
3718 				      sidr_rep_msg);
3719 	param->info_len = IBA_GET(CM_SIDR_REP_ADDITIONAL_INFORMATION_LENGTH,
3720 				  sidr_rep_msg);
3721 	param->sgid_attr = cm_id_priv->av.ah_attr.grh.sgid_attr;
3722 	work->cm_event.private_data =
3723 		IBA_GET_MEM_PTR(CM_SIDR_REP_PRIVATE_DATA, sidr_rep_msg);
3724 }
3725 
3726 static int cm_sidr_rep_handler(struct cm_work *work)
3727 {
3728 	struct cm_sidr_rep_msg *sidr_rep_msg;
3729 	struct cm_id_private *cm_id_priv;
3730 
3731 	sidr_rep_msg = (struct cm_sidr_rep_msg *)
3732 				work->mad_recv_wc->recv_buf.mad;
3733 	cm_id_priv = cm_acquire_id(
3734 		cpu_to_be32(IBA_GET(CM_SIDR_REP_REQUESTID, sidr_rep_msg)), 0);
3735 	if (!cm_id_priv)
3736 		return -EINVAL; /* Unmatched reply. */
3737 
3738 	spin_lock_irq(&cm_id_priv->lock);
3739 	if (cm_id_priv->id.state != IB_CM_SIDR_REQ_SENT) {
3740 		spin_unlock_irq(&cm_id_priv->lock);
3741 		goto out;
3742 	}
3743 	cm_id_priv->id.state = IB_CM_IDLE;
3744 	ib_cancel_mad(cm_id_priv->msg);
3745 	spin_unlock_irq(&cm_id_priv->lock);
3746 
3747 	cm_format_sidr_rep_event(work, cm_id_priv);
3748 	cm_process_work(cm_id_priv, work);
3749 	return 0;
3750 out:
3751 	cm_deref_id(cm_id_priv);
3752 	return -EINVAL;
3753 }
3754 
3755 static void cm_process_send_error(struct cm_id_private *cm_id_priv,
3756 				  struct ib_mad_send_buf *msg,
3757 				  enum ib_wc_status wc_status)
3758 {
3759 	enum ib_cm_state state = (unsigned long) msg->context[1];
3760 	struct ib_cm_event cm_event = {};
3761 	int ret;
3762 
3763 	/* Discard old sends. */
3764 	spin_lock_irq(&cm_id_priv->lock);
3765 	if (msg != cm_id_priv->msg) {
3766 		spin_unlock_irq(&cm_id_priv->lock);
3767 		cm_free_msg(msg);
3768 		cm_deref_id(cm_id_priv);
3769 		return;
3770 	}
3771 	cm_free_priv_msg(msg);
3772 
3773 	if (state != cm_id_priv->id.state || wc_status == IB_WC_SUCCESS ||
3774 	    wc_status == IB_WC_WR_FLUSH_ERR)
3775 		goto out_unlock;
3776 
3777 	trace_icm_mad_send_err(state, wc_status);
3778 	switch (state) {
3779 	case IB_CM_REQ_SENT:
3780 	case IB_CM_MRA_REQ_RCVD:
3781 		cm_reset_to_idle(cm_id_priv);
3782 		cm_event.event = IB_CM_REQ_ERROR;
3783 		break;
3784 	case IB_CM_REP_SENT:
3785 	case IB_CM_MRA_REP_RCVD:
3786 		cm_reset_to_idle(cm_id_priv);
3787 		cm_event.event = IB_CM_REP_ERROR;
3788 		break;
3789 	case IB_CM_DREQ_SENT:
3790 		cm_enter_timewait(cm_id_priv);
3791 		cm_event.event = IB_CM_DREQ_ERROR;
3792 		break;
3793 	case IB_CM_SIDR_REQ_SENT:
3794 		cm_id_priv->id.state = IB_CM_IDLE;
3795 		cm_event.event = IB_CM_SIDR_REQ_ERROR;
3796 		break;
3797 	default:
3798 		goto out_unlock;
3799 	}
3800 	spin_unlock_irq(&cm_id_priv->lock);
3801 	cm_event.param.send_status = wc_status;
3802 
3803 	/* No other events can occur on the cm_id at this point. */
3804 	ret = cm_id_priv->id.cm_handler(&cm_id_priv->id, &cm_event);
3805 	if (ret)
3806 		ib_destroy_cm_id(&cm_id_priv->id);
3807 	return;
3808 out_unlock:
3809 	spin_unlock_irq(&cm_id_priv->lock);
3810 }
3811 
3812 static void cm_send_handler(struct ib_mad_agent *mad_agent,
3813 			    struct ib_mad_send_wc *mad_send_wc)
3814 {
3815 	struct ib_mad_send_buf *msg = mad_send_wc->send_buf;
3816 	struct cm_id_private *cm_id_priv;
3817 	struct cm_port *port;
3818 	u16 attr_index;
3819 
3820 	port = mad_agent->context;
3821 	attr_index = be16_to_cpu(((struct ib_mad_hdr *)
3822 				  msg->mad)->attr_id) - CM_ATTR_ID_OFFSET;
3823 
3824 	if (msg->context[0] == CM_DIRECT_RETRY_CTX) {
3825 		msg->retries = 1;
3826 		cm_id_priv = NULL;
3827 	} else {
3828 		cm_id_priv = msg->context[0];
3829 	}
3830 
3831 	atomic_long_add(1 + msg->retries, &port->counters[CM_XMIT][attr_index]);
3832 	if (msg->retries)
3833 		atomic_long_add(msg->retries,
3834 				&port->counters[CM_XMIT_RETRIES][attr_index]);
3835 
3836 	if (cm_id_priv)
3837 		cm_process_send_error(cm_id_priv, msg, mad_send_wc->status);
3838 	else
3839 		cm_free_msg(msg);
3840 }
3841 
3842 static void cm_work_handler(struct work_struct *_work)
3843 {
3844 	struct cm_work *work = container_of(_work, struct cm_work, work.work);
3845 	int ret;
3846 
3847 	switch (work->cm_event.event) {
3848 	case IB_CM_REQ_RECEIVED:
3849 		ret = cm_req_handler(work);
3850 		break;
3851 	case IB_CM_MRA_RECEIVED:
3852 		ret = cm_mra_handler(work);
3853 		break;
3854 	case IB_CM_REJ_RECEIVED:
3855 		ret = cm_rej_handler(work);
3856 		break;
3857 	case IB_CM_REP_RECEIVED:
3858 		ret = cm_rep_handler(work);
3859 		break;
3860 	case IB_CM_RTU_RECEIVED:
3861 		ret = cm_rtu_handler(work);
3862 		break;
3863 	case IB_CM_USER_ESTABLISHED:
3864 		ret = cm_establish_handler(work);
3865 		break;
3866 	case IB_CM_DREQ_RECEIVED:
3867 		ret = cm_dreq_handler(work);
3868 		break;
3869 	case IB_CM_DREP_RECEIVED:
3870 		ret = cm_drep_handler(work);
3871 		break;
3872 	case IB_CM_SIDR_REQ_RECEIVED:
3873 		ret = cm_sidr_req_handler(work);
3874 		break;
3875 	case IB_CM_SIDR_REP_RECEIVED:
3876 		ret = cm_sidr_rep_handler(work);
3877 		break;
3878 	case IB_CM_LAP_RECEIVED:
3879 		ret = cm_lap_handler(work);
3880 		break;
3881 	case IB_CM_APR_RECEIVED:
3882 		ret = cm_apr_handler(work);
3883 		break;
3884 	case IB_CM_TIMEWAIT_EXIT:
3885 		ret = cm_timewait_handler(work);
3886 		break;
3887 	default:
3888 		trace_icm_handler_err(work->cm_event.event);
3889 		ret = -EINVAL;
3890 		break;
3891 	}
3892 	if (ret)
3893 		cm_free_work(work);
3894 }
3895 
3896 static int cm_establish(struct ib_cm_id *cm_id)
3897 {
3898 	struct cm_id_private *cm_id_priv;
3899 	struct cm_work *work;
3900 	unsigned long flags;
3901 	int ret = 0;
3902 	struct cm_device *cm_dev;
3903 
3904 	cm_dev = ib_get_client_data(cm_id->device, &cm_client);
3905 	if (!cm_dev)
3906 		return -ENODEV;
3907 
3908 	work = kmalloc_obj(*work, GFP_ATOMIC);
3909 	if (!work)
3910 		return -ENOMEM;
3911 
3912 	cm_id_priv = container_of(cm_id, struct cm_id_private, id);
3913 	spin_lock_irqsave(&cm_id_priv->lock, flags);
3914 	switch (cm_id->state) {
3915 	case IB_CM_REP_SENT:
3916 	case IB_CM_MRA_REP_RCVD:
3917 		cm_id->state = IB_CM_ESTABLISHED;
3918 		break;
3919 	case IB_CM_ESTABLISHED:
3920 		ret = -EISCONN;
3921 		break;
3922 	default:
3923 		trace_icm_establish_err(cm_id);
3924 		ret = -EINVAL;
3925 		break;
3926 	}
3927 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
3928 
3929 	if (ret) {
3930 		kfree(work);
3931 		goto out;
3932 	}
3933 
3934 	/*
3935 	 * The CM worker thread may try to destroy the cm_id before it
3936 	 * can execute this work item.  To prevent potential deadlock,
3937 	 * we need to find the cm_id once we're in the context of the
3938 	 * worker thread, rather than holding a reference on it.
3939 	 */
3940 	INIT_DELAYED_WORK(&work->work, cm_work_handler);
3941 	work->local_id = cm_id->local_id;
3942 	work->remote_id = cm_id->remote_id;
3943 	work->mad_recv_wc = NULL;
3944 	work->cm_event.event = IB_CM_USER_ESTABLISHED;
3945 
3946 	/* Check if the device started its remove_one */
3947 	spin_lock_irqsave(&cm.lock, flags);
3948 	if (!cm_dev->going_down) {
3949 		queue_delayed_work(cm.wq, &work->work, 0);
3950 	} else {
3951 		kfree(work);
3952 		ret = -ENODEV;
3953 	}
3954 	spin_unlock_irqrestore(&cm.lock, flags);
3955 
3956 out:
3957 	return ret;
3958 }
3959 
3960 static int cm_migrate(struct ib_cm_id *cm_id)
3961 {
3962 	struct cm_id_private *cm_id_priv;
3963 	unsigned long flags;
3964 	int ret = 0;
3965 
3966 	cm_id_priv = container_of(cm_id, struct cm_id_private, id);
3967 	spin_lock_irqsave(&cm_id_priv->lock, flags);
3968 	if (cm_id->state == IB_CM_ESTABLISHED &&
3969 	    (cm_id->lap_state == IB_CM_LAP_UNINIT ||
3970 	     cm_id->lap_state == IB_CM_LAP_IDLE)) {
3971 		cm_id->lap_state = IB_CM_LAP_IDLE;
3972 		cm_id_priv->av = cm_id_priv->alt_av;
3973 	} else
3974 		ret = -EINVAL;
3975 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
3976 
3977 	return ret;
3978 }
3979 
3980 int ib_cm_notify(struct ib_cm_id *cm_id, enum ib_event_type event)
3981 {
3982 	int ret;
3983 
3984 	switch (event) {
3985 	case IB_EVENT_COMM_EST:
3986 		ret = cm_establish(cm_id);
3987 		break;
3988 	case IB_EVENT_PATH_MIG:
3989 		ret = cm_migrate(cm_id);
3990 		break;
3991 	default:
3992 		ret = -EINVAL;
3993 	}
3994 	return ret;
3995 }
3996 EXPORT_SYMBOL(ib_cm_notify);
3997 
3998 static void cm_recv_handler(struct ib_mad_agent *mad_agent,
3999 			    struct ib_mad_send_buf *send_buf,
4000 			    struct ib_mad_recv_wc *mad_recv_wc)
4001 {
4002 	struct cm_port *port = mad_agent->context;
4003 	struct cm_work *work;
4004 	enum ib_cm_event_type event;
4005 	bool alt_path = false;
4006 	u16 attr_id;
4007 	int paths = 0;
4008 	int going_down = 0;
4009 
4010 	switch (mad_recv_wc->recv_buf.mad->mad_hdr.attr_id) {
4011 	case CM_REQ_ATTR_ID:
4012 		alt_path = cm_req_has_alt_path((struct cm_req_msg *)
4013 						mad_recv_wc->recv_buf.mad);
4014 		paths = 1 + (alt_path != 0);
4015 		event = IB_CM_REQ_RECEIVED;
4016 		break;
4017 	case CM_MRA_ATTR_ID:
4018 		event = IB_CM_MRA_RECEIVED;
4019 		break;
4020 	case CM_REJ_ATTR_ID:
4021 		event = IB_CM_REJ_RECEIVED;
4022 		break;
4023 	case CM_REP_ATTR_ID:
4024 		event = IB_CM_REP_RECEIVED;
4025 		break;
4026 	case CM_RTU_ATTR_ID:
4027 		event = IB_CM_RTU_RECEIVED;
4028 		break;
4029 	case CM_DREQ_ATTR_ID:
4030 		event = IB_CM_DREQ_RECEIVED;
4031 		break;
4032 	case CM_DREP_ATTR_ID:
4033 		event = IB_CM_DREP_RECEIVED;
4034 		break;
4035 	case CM_SIDR_REQ_ATTR_ID:
4036 		event = IB_CM_SIDR_REQ_RECEIVED;
4037 		break;
4038 	case CM_SIDR_REP_ATTR_ID:
4039 		event = IB_CM_SIDR_REP_RECEIVED;
4040 		break;
4041 	case CM_LAP_ATTR_ID:
4042 		paths = 1;
4043 		event = IB_CM_LAP_RECEIVED;
4044 		break;
4045 	case CM_APR_ATTR_ID:
4046 		event = IB_CM_APR_RECEIVED;
4047 		break;
4048 	default:
4049 		ib_free_recv_mad(mad_recv_wc);
4050 		return;
4051 	}
4052 
4053 	attr_id = be16_to_cpu(mad_recv_wc->recv_buf.mad->mad_hdr.attr_id);
4054 	atomic_long_inc(&port->counters[CM_RECV][attr_id - CM_ATTR_ID_OFFSET]);
4055 
4056 	work = kmalloc_flex(*work, path, paths);
4057 	if (!work) {
4058 		ib_free_recv_mad(mad_recv_wc);
4059 		return;
4060 	}
4061 
4062 	INIT_DELAYED_WORK(&work->work, cm_work_handler);
4063 	work->cm_event.event = event;
4064 	work->mad_recv_wc = mad_recv_wc;
4065 	work->port = port;
4066 
4067 	/* Check if the device started its remove_one */
4068 	spin_lock_irq(&cm.lock);
4069 	if (!port->cm_dev->going_down)
4070 		queue_delayed_work(cm.wq, &work->work, 0);
4071 	else
4072 		going_down = 1;
4073 	spin_unlock_irq(&cm.lock);
4074 
4075 	if (going_down) {
4076 		kfree(work);
4077 		ib_free_recv_mad(mad_recv_wc);
4078 	}
4079 }
4080 
4081 static int cm_init_qp_init_attr(struct cm_id_private *cm_id_priv,
4082 				struct ib_qp_attr *qp_attr,
4083 				int *qp_attr_mask)
4084 {
4085 	unsigned long flags;
4086 	int ret;
4087 
4088 	spin_lock_irqsave(&cm_id_priv->lock, flags);
4089 	switch (cm_id_priv->id.state) {
4090 	case IB_CM_REQ_SENT:
4091 	case IB_CM_MRA_REQ_RCVD:
4092 	case IB_CM_REQ_RCVD:
4093 	case IB_CM_MRA_REQ_SENT:
4094 	case IB_CM_REP_RCVD:
4095 	case IB_CM_MRA_REP_SENT:
4096 	case IB_CM_REP_SENT:
4097 	case IB_CM_MRA_REP_RCVD:
4098 	case IB_CM_ESTABLISHED:
4099 		*qp_attr_mask = IB_QP_STATE | IB_QP_ACCESS_FLAGS |
4100 				IB_QP_PKEY_INDEX | IB_QP_PORT;
4101 		qp_attr->qp_access_flags = IB_ACCESS_REMOTE_WRITE;
4102 		if (cm_id_priv->responder_resources) {
4103 			struct ib_device *ib_dev = cm_id_priv->id.device;
4104 			u64 support_flush = ib_dev->attrs.device_cap_flags &
4105 			  (IB_DEVICE_FLUSH_GLOBAL | IB_DEVICE_FLUSH_PERSISTENT);
4106 			u32 flushable = support_flush ?
4107 					(IB_ACCESS_FLUSH_GLOBAL |
4108 					 IB_ACCESS_FLUSH_PERSISTENT) : 0;
4109 
4110 			qp_attr->qp_access_flags |= IB_ACCESS_REMOTE_READ |
4111 						    IB_ACCESS_REMOTE_ATOMIC |
4112 						    flushable;
4113 		}
4114 		qp_attr->pkey_index = cm_id_priv->av.pkey_index;
4115 		if (cm_id_priv->av.port)
4116 			qp_attr->port_num = cm_id_priv->av.port->port_num;
4117 		ret = 0;
4118 		break;
4119 	default:
4120 		trace_icm_qp_init_err(&cm_id_priv->id);
4121 		ret = -EINVAL;
4122 		break;
4123 	}
4124 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
4125 	return ret;
4126 }
4127 
4128 static int cm_init_qp_rtr_attr(struct cm_id_private *cm_id_priv,
4129 			       struct ib_qp_attr *qp_attr,
4130 			       int *qp_attr_mask)
4131 {
4132 	unsigned long flags;
4133 	int ret;
4134 
4135 	spin_lock_irqsave(&cm_id_priv->lock, flags);
4136 	switch (cm_id_priv->id.state) {
4137 	case IB_CM_REQ_RCVD:
4138 	case IB_CM_MRA_REQ_SENT:
4139 	case IB_CM_REP_RCVD:
4140 	case IB_CM_MRA_REP_SENT:
4141 	case IB_CM_REP_SENT:
4142 	case IB_CM_MRA_REP_RCVD:
4143 	case IB_CM_ESTABLISHED:
4144 		*qp_attr_mask = IB_QP_STATE | IB_QP_AV | IB_QP_PATH_MTU |
4145 				IB_QP_DEST_QPN | IB_QP_RQ_PSN;
4146 		qp_attr->ah_attr = cm_id_priv->av.ah_attr;
4147 		if ((qp_attr->ah_attr.type == RDMA_AH_ATTR_TYPE_IB) &&
4148 		    cm_id_priv->av.dlid_datapath &&
4149 		    (cm_id_priv->av.dlid_datapath != 0xffff))
4150 			qp_attr->ah_attr.ib.dlid = cm_id_priv->av.dlid_datapath;
4151 		qp_attr->path_mtu = cm_id_priv->path_mtu;
4152 		qp_attr->dest_qp_num = be32_to_cpu(cm_id_priv->remote_qpn);
4153 		qp_attr->rq_psn = be32_to_cpu(cm_id_priv->rq_psn);
4154 		if (cm_id_priv->qp_type == IB_QPT_RC ||
4155 		    cm_id_priv->qp_type == IB_QPT_XRC_TGT) {
4156 			*qp_attr_mask |= IB_QP_MAX_DEST_RD_ATOMIC |
4157 					 IB_QP_MIN_RNR_TIMER;
4158 			qp_attr->max_dest_rd_atomic =
4159 					cm_id_priv->responder_resources;
4160 			qp_attr->min_rnr_timer = 0;
4161 		}
4162 		if (rdma_ah_get_dlid(&cm_id_priv->alt_av.ah_attr) &&
4163 		    cm_id_priv->alt_av.port) {
4164 			*qp_attr_mask |= IB_QP_ALT_PATH;
4165 			qp_attr->alt_port_num = cm_id_priv->alt_av.port->port_num;
4166 			qp_attr->alt_pkey_index = cm_id_priv->alt_av.pkey_index;
4167 			qp_attr->alt_timeout = cm_id_priv->alt_av.timeout;
4168 			qp_attr->alt_ah_attr = cm_id_priv->alt_av.ah_attr;
4169 		}
4170 		ret = 0;
4171 		break;
4172 	default:
4173 		trace_icm_qp_rtr_err(&cm_id_priv->id);
4174 		ret = -EINVAL;
4175 		break;
4176 	}
4177 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
4178 	return ret;
4179 }
4180 
4181 static int cm_init_qp_rts_attr(struct cm_id_private *cm_id_priv,
4182 			       struct ib_qp_attr *qp_attr,
4183 			       int *qp_attr_mask)
4184 {
4185 	unsigned long flags;
4186 	int ret;
4187 
4188 	spin_lock_irqsave(&cm_id_priv->lock, flags);
4189 	switch (cm_id_priv->id.state) {
4190 	/* Allow transition to RTS before sending REP */
4191 	case IB_CM_REQ_RCVD:
4192 	case IB_CM_MRA_REQ_SENT:
4193 
4194 	case IB_CM_REP_RCVD:
4195 	case IB_CM_MRA_REP_SENT:
4196 	case IB_CM_REP_SENT:
4197 	case IB_CM_MRA_REP_RCVD:
4198 	case IB_CM_ESTABLISHED:
4199 		if (cm_id_priv->id.lap_state == IB_CM_LAP_UNINIT) {
4200 			*qp_attr_mask = IB_QP_STATE | IB_QP_SQ_PSN;
4201 			qp_attr->sq_psn = be32_to_cpu(cm_id_priv->sq_psn);
4202 			switch (cm_id_priv->qp_type) {
4203 			case IB_QPT_RC:
4204 			case IB_QPT_XRC_INI:
4205 				*qp_attr_mask |= IB_QP_RETRY_CNT | IB_QP_RNR_RETRY |
4206 						 IB_QP_MAX_QP_RD_ATOMIC;
4207 				qp_attr->retry_cnt = cm_id_priv->retry_count;
4208 				qp_attr->rnr_retry = cm_id_priv->rnr_retry_count;
4209 				qp_attr->max_rd_atomic = cm_id_priv->initiator_depth;
4210 				fallthrough;
4211 			case IB_QPT_XRC_TGT:
4212 				*qp_attr_mask |= IB_QP_TIMEOUT;
4213 				qp_attr->timeout = cm_id_priv->av.timeout;
4214 				break;
4215 			default:
4216 				break;
4217 			}
4218 			if (rdma_ah_get_dlid(&cm_id_priv->alt_av.ah_attr)) {
4219 				*qp_attr_mask |= IB_QP_PATH_MIG_STATE;
4220 				qp_attr->path_mig_state = IB_MIG_REARM;
4221 			}
4222 		} else {
4223 			*qp_attr_mask = IB_QP_ALT_PATH | IB_QP_PATH_MIG_STATE;
4224 			if (cm_id_priv->alt_av.port)
4225 				qp_attr->alt_port_num =
4226 					cm_id_priv->alt_av.port->port_num;
4227 			qp_attr->alt_pkey_index = cm_id_priv->alt_av.pkey_index;
4228 			qp_attr->alt_timeout = cm_id_priv->alt_av.timeout;
4229 			qp_attr->alt_ah_attr = cm_id_priv->alt_av.ah_attr;
4230 			qp_attr->path_mig_state = IB_MIG_REARM;
4231 		}
4232 		ret = 0;
4233 		break;
4234 	default:
4235 		trace_icm_qp_rts_err(&cm_id_priv->id);
4236 		ret = -EINVAL;
4237 		break;
4238 	}
4239 	spin_unlock_irqrestore(&cm_id_priv->lock, flags);
4240 	return ret;
4241 }
4242 
4243 int ib_cm_init_qp_attr(struct ib_cm_id *cm_id,
4244 		       struct ib_qp_attr *qp_attr,
4245 		       int *qp_attr_mask)
4246 {
4247 	struct cm_id_private *cm_id_priv;
4248 	int ret;
4249 
4250 	cm_id_priv = container_of(cm_id, struct cm_id_private, id);
4251 	switch (qp_attr->qp_state) {
4252 	case IB_QPS_INIT:
4253 		ret = cm_init_qp_init_attr(cm_id_priv, qp_attr, qp_attr_mask);
4254 		break;
4255 	case IB_QPS_RTR:
4256 		ret = cm_init_qp_rtr_attr(cm_id_priv, qp_attr, qp_attr_mask);
4257 		break;
4258 	case IB_QPS_RTS:
4259 		ret = cm_init_qp_rts_attr(cm_id_priv, qp_attr, qp_attr_mask);
4260 		break;
4261 	default:
4262 		ret = -EINVAL;
4263 		break;
4264 	}
4265 	return ret;
4266 }
4267 EXPORT_SYMBOL(ib_cm_init_qp_attr);
4268 
4269 static ssize_t cm_show_counter(struct ib_device *ibdev, u32 port_num,
4270 			       struct ib_port_attribute *attr, char *buf)
4271 {
4272 	struct cm_counter_attribute *cm_attr =
4273 		container_of(attr, struct cm_counter_attribute, attr);
4274 	struct cm_device *cm_dev = ib_get_client_data(ibdev, &cm_client);
4275 
4276 	if (WARN_ON(!cm_dev))
4277 		return -EINVAL;
4278 
4279 	return sysfs_emit(
4280 		buf, "%ld\n",
4281 		atomic_long_read(
4282 			&cm_dev->port[port_num - 1]
4283 				 ->counters[cm_attr->group][cm_attr->index]));
4284 }
4285 
4286 #define CM_COUNTER_ATTR(_name, _group, _index)                                 \
4287 	{                                                                      \
4288 		.attr = __ATTR(_name, 0444, cm_show_counter, NULL),            \
4289 		.group = _group, .index = _index                               \
4290 	}
4291 
4292 #define CM_COUNTER_GROUP(_group, _name)                                        \
4293 	static struct cm_counter_attribute cm_counter_attr_##_group[] = {      \
4294 		CM_COUNTER_ATTR(req, _group, CM_REQ_COUNTER),                  \
4295 		CM_COUNTER_ATTR(mra, _group, CM_MRA_COUNTER),                  \
4296 		CM_COUNTER_ATTR(rej, _group, CM_REJ_COUNTER),                  \
4297 		CM_COUNTER_ATTR(rep, _group, CM_REP_COUNTER),                  \
4298 		CM_COUNTER_ATTR(rtu, _group, CM_RTU_COUNTER),                  \
4299 		CM_COUNTER_ATTR(dreq, _group, CM_DREQ_COUNTER),                \
4300 		CM_COUNTER_ATTR(drep, _group, CM_DREP_COUNTER),                \
4301 		CM_COUNTER_ATTR(sidr_req, _group, CM_SIDR_REQ_COUNTER),        \
4302 		CM_COUNTER_ATTR(sidr_rep, _group, CM_SIDR_REP_COUNTER),        \
4303 		CM_COUNTER_ATTR(lap, _group, CM_LAP_COUNTER),                  \
4304 		CM_COUNTER_ATTR(apr, _group, CM_APR_COUNTER),                  \
4305 	};                                                                     \
4306 	static struct attribute *cm_counter_attrs_##_group[] = {               \
4307 		&cm_counter_attr_##_group[0].attr.attr,                        \
4308 		&cm_counter_attr_##_group[1].attr.attr,                        \
4309 		&cm_counter_attr_##_group[2].attr.attr,                        \
4310 		&cm_counter_attr_##_group[3].attr.attr,                        \
4311 		&cm_counter_attr_##_group[4].attr.attr,                        \
4312 		&cm_counter_attr_##_group[5].attr.attr,                        \
4313 		&cm_counter_attr_##_group[6].attr.attr,                        \
4314 		&cm_counter_attr_##_group[7].attr.attr,                        \
4315 		&cm_counter_attr_##_group[8].attr.attr,                        \
4316 		&cm_counter_attr_##_group[9].attr.attr,                        \
4317 		&cm_counter_attr_##_group[10].attr.attr,                       \
4318 		NULL,                                                          \
4319 	};                                                                     \
4320 	static const struct attribute_group cm_counter_group_##_group = {      \
4321 		.name = _name,                                                 \
4322 		.attrs = cm_counter_attrs_##_group,                            \
4323 	};
4324 
4325 CM_COUNTER_GROUP(CM_XMIT, "cm_tx_msgs")
4326 CM_COUNTER_GROUP(CM_XMIT_RETRIES, "cm_tx_retries")
4327 CM_COUNTER_GROUP(CM_RECV, "cm_rx_msgs")
4328 CM_COUNTER_GROUP(CM_RECV_DUPLICATES, "cm_rx_duplicates")
4329 
4330 static const struct attribute_group *cm_counter_groups[] = {
4331 	&cm_counter_group_CM_XMIT,
4332 	&cm_counter_group_CM_XMIT_RETRIES,
4333 	&cm_counter_group_CM_RECV,
4334 	&cm_counter_group_CM_RECV_DUPLICATES,
4335 	NULL,
4336 };
4337 
4338 static int cm_add_one(struct ib_device *ib_device)
4339 {
4340 	struct cm_device *cm_dev;
4341 	struct cm_port *port;
4342 	struct ib_mad_reg_req reg_req = {
4343 		.mgmt_class = IB_MGMT_CLASS_CM,
4344 		.mgmt_class_version = IB_CM_CLASS_VERSION,
4345 	};
4346 	struct ib_port_modify port_modify = {
4347 		.set_port_cap_mask = IB_PORT_CM_SUP
4348 	};
4349 	unsigned long flags;
4350 	int ret;
4351 	int count = 0;
4352 	u32 i;
4353 
4354 	cm_dev = kzalloc_flex(*cm_dev, port, ib_device->phys_port_cnt);
4355 	if (!cm_dev)
4356 		return -ENOMEM;
4357 
4358 	kref_init(&cm_dev->kref);
4359 	rwlock_init(&cm_dev->mad_agent_lock);
4360 	cm_dev->ib_device = ib_device;
4361 	cm_dev->ack_delay = ib_device->attrs.local_ca_ack_delay;
4362 	cm_dev->going_down = 0;
4363 
4364 	ib_set_client_data(ib_device, &cm_client, cm_dev);
4365 
4366 	set_bit(IB_MGMT_METHOD_SEND, reg_req.method_mask);
4367 	rdma_for_each_port (ib_device, i) {
4368 		if (!rdma_cap_ib_cm(ib_device, i))
4369 			continue;
4370 
4371 		port = kzalloc_obj(*port);
4372 		if (!port) {
4373 			ret = -ENOMEM;
4374 			goto error1;
4375 		}
4376 
4377 		cm_dev->port[i-1] = port;
4378 		port->cm_dev = cm_dev;
4379 		port->port_num = i;
4380 
4381 		ret = ib_port_register_client_groups(ib_device, i,
4382 						     cm_counter_groups);
4383 		if (ret)
4384 			goto error1;
4385 
4386 		port->mad_agent = ib_register_mad_agent(ib_device, i,
4387 							IB_QPT_GSI,
4388 							&reg_req,
4389 							0,
4390 							cm_send_handler,
4391 							cm_recv_handler,
4392 							port,
4393 							0);
4394 		if (IS_ERR(port->mad_agent)) {
4395 			ret = PTR_ERR(port->mad_agent);
4396 			goto error2;
4397 		}
4398 
4399 		port->rep_agent = ib_register_mad_agent(ib_device, i,
4400 							IB_QPT_GSI,
4401 							NULL,
4402 							0,
4403 							cm_send_handler,
4404 							NULL,
4405 							port,
4406 							0);
4407 		if (IS_ERR(port->rep_agent)) {
4408 			ret = PTR_ERR(port->rep_agent);
4409 			goto error3;
4410 		}
4411 
4412 		ret = ib_modify_port(ib_device, i, 0, &port_modify);
4413 		if (ret)
4414 			goto error4;
4415 
4416 		count++;
4417 	}
4418 
4419 	if (!count) {
4420 		ret = -EOPNOTSUPP;
4421 		goto free;
4422 	}
4423 
4424 	write_lock_irqsave(&cm.device_lock, flags);
4425 	list_add_tail(&cm_dev->list, &cm.device_list);
4426 	write_unlock_irqrestore(&cm.device_lock, flags);
4427 	return 0;
4428 
4429 error4:
4430 	ib_unregister_mad_agent(port->rep_agent);
4431 error3:
4432 	ib_unregister_mad_agent(port->mad_agent);
4433 error2:
4434 	ib_port_unregister_client_groups(ib_device, i, cm_counter_groups);
4435 error1:
4436 	port_modify.set_port_cap_mask = 0;
4437 	port_modify.clr_port_cap_mask = IB_PORT_CM_SUP;
4438 	while (--i) {
4439 		if (!rdma_cap_ib_cm(ib_device, i))
4440 			continue;
4441 
4442 		port = cm_dev->port[i-1];
4443 		ib_modify_port(ib_device, port->port_num, 0, &port_modify);
4444 		ib_unregister_mad_agent(port->rep_agent);
4445 		ib_unregister_mad_agent(port->mad_agent);
4446 		ib_port_unregister_client_groups(ib_device, i,
4447 						 cm_counter_groups);
4448 	}
4449 free:
4450 	cm_device_put(cm_dev);
4451 	return ret;
4452 }
4453 
4454 static void cm_remove_one(struct ib_device *ib_device, void *client_data)
4455 {
4456 	struct cm_device *cm_dev = client_data;
4457 	struct cm_port *port;
4458 	struct ib_port_modify port_modify = {
4459 		.clr_port_cap_mask = IB_PORT_CM_SUP
4460 	};
4461 	unsigned long flags;
4462 	u32 i;
4463 
4464 	write_lock_irqsave(&cm.device_lock, flags);
4465 	list_del(&cm_dev->list);
4466 	write_unlock_irqrestore(&cm.device_lock, flags);
4467 
4468 	spin_lock_irq(&cm.lock);
4469 	cm_dev->going_down = 1;
4470 	spin_unlock_irq(&cm.lock);
4471 
4472 	rdma_for_each_port (ib_device, i) {
4473 		struct ib_mad_agent *mad_agent;
4474 		struct ib_mad_agent *rep_agent;
4475 
4476 		if (!rdma_cap_ib_cm(ib_device, i))
4477 			continue;
4478 
4479 		port = cm_dev->port[i-1];
4480 		mad_agent = port->mad_agent;
4481 		rep_agent = port->rep_agent;
4482 		ib_modify_port(ib_device, port->port_num, 0, &port_modify);
4483 		/*
4484 		 * We flush the queue here after the going_down set, this
4485 		 * verify that no new works will be queued in the recv handler,
4486 		 * after that we can call the unregister_mad_agent
4487 		 */
4488 		flush_workqueue(cm.wq);
4489 		/*
4490 		 * The above ensures no call paths from the work are running,
4491 		 * the remaining paths all take the mad_agent_lock.
4492 		 */
4493 		write_lock(&cm_dev->mad_agent_lock);
4494 		port->mad_agent = NULL;
4495 		port->rep_agent = NULL;
4496 		write_unlock(&cm_dev->mad_agent_lock);
4497 		ib_unregister_mad_agent(mad_agent);
4498 		ib_unregister_mad_agent(rep_agent);
4499 		ib_port_unregister_client_groups(ib_device, i,
4500 						 cm_counter_groups);
4501 	}
4502 
4503 	cm_device_put(cm_dev);
4504 }
4505 
4506 static int __init ib_cm_init(void)
4507 {
4508 	int ret;
4509 
4510 	INIT_LIST_HEAD(&cm.device_list);
4511 	rwlock_init(&cm.device_lock);
4512 	spin_lock_init(&cm.lock);
4513 	cm.listen_service_table = RB_ROOT;
4514 	cm.listen_service_id = be64_to_cpu(IB_CM_ASSIGN_SERVICE_ID);
4515 	cm.remote_id_table = RB_ROOT;
4516 	cm.remote_qp_table = RB_ROOT;
4517 	cm.remote_sidr_table = RB_ROOT;
4518 	xa_init_flags(&cm.local_id_table, XA_FLAGS_ALLOC);
4519 	get_random_bytes(&cm.random_id_operand, sizeof cm.random_id_operand);
4520 	INIT_LIST_HEAD(&cm.timewait_list);
4521 
4522 	cm.wq = alloc_workqueue("ib_cm", WQ_PERCPU, 1);
4523 	if (!cm.wq) {
4524 		ret = -ENOMEM;
4525 		goto error2;
4526 	}
4527 
4528 	ret = ib_register_client(&cm_client);
4529 	if (ret)
4530 		goto error3;
4531 
4532 	return 0;
4533 error3:
4534 	destroy_workqueue(cm.wq);
4535 error2:
4536 	return ret;
4537 }
4538 
4539 static void __exit ib_cm_cleanup(void)
4540 {
4541 	struct cm_timewait_info *timewait_info, *tmp;
4542 
4543 	spin_lock_irq(&cm.lock);
4544 	list_for_each_entry(timewait_info, &cm.timewait_list, list)
4545 		cancel_delayed_work(&timewait_info->work.work);
4546 	spin_unlock_irq(&cm.lock);
4547 
4548 	ib_unregister_client(&cm_client);
4549 	destroy_workqueue(cm.wq);
4550 
4551 	list_for_each_entry_safe(timewait_info, tmp, &cm.timewait_list, list) {
4552 		list_del(&timewait_info->list);
4553 		kfree(timewait_info);
4554 	}
4555 
4556 	WARN_ON(!xa_empty(&cm.local_id_table));
4557 }
4558 
4559 module_init(ib_cm_init);
4560 module_exit(ib_cm_cleanup);
4561