1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* SCTP kernel implementation
3  * (C) Copyright IBM Corp. 2001, 2004
4  * Copyright (c) 1999-2000 Cisco, Inc.
5  * Copyright (c) 1999-2001 Motorola, Inc.
6  * Copyright (c) 2001 Intel Corp.
7  * Copyright (c) 2001 La Monte H.P. Yarroll
8  *
9  * This file is part of the SCTP kernel implementation
10  *
11  * This module provides the abstraction for an SCTP association.
12  *
13  * Please send any bug reports or fixes you make to the
14  * email address(es):
15  *    lksctp developers <linux-sctp@vger.kernel.org>
16  *
17  * Written or modified by:
18  *    La Monte H.P. Yarroll <piggy@acm.org>
19  *    Karl Knutson          <karl@athena.chicago.il.us>
20  *    Jon Grimm             <jgrimm@us.ibm.com>
21  *    Xingang Guo           <xingang.guo@intel.com>
22  *    Hui Huang             <hui.huang@nokia.com>
23  *    Sridhar Samudrala	    <sri@us.ibm.com>
24  *    Daisy Chang	    <daisyc@us.ibm.com>
25  *    Ryan Layer	    <rmlayer@us.ibm.com>
26  *    Kevin Gao             <kevin.gao@intel.com>
27  */
28 
29 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
30 
31 #include <linux/types.h>
32 #include <linux/fcntl.h>
33 #include <linux/poll.h>
34 #include <linux/init.h>
35 
36 #include <linux/slab.h>
37 #include <linux/in.h>
38 #include <net/ipv6.h>
39 #include <net/sctp/sctp.h>
40 #include <net/sctp/sm.h>
41 
42 /* Forward declarations for internal functions. */
43 static void sctp_select_active_and_retran_path(struct sctp_association *asoc);
44 static void sctp_assoc_bh_rcv(struct work_struct *work);
45 static void sctp_assoc_free_asconf_acks(struct sctp_association *asoc);
46 static void sctp_assoc_free_asconf_queue(struct sctp_association *asoc);
47 
48 /* 1st Level Abstractions. */
49 
50 /* Initialize a new association from provided memory. */
51 static struct sctp_association *sctp_association_init(
52 					struct sctp_association *asoc,
53 					const struct sctp_endpoint *ep,
54 					const struct sock *sk,
55 					enum sctp_scope scope, gfp_t gfp)
56 {
57 	struct sctp_sock *sp;
58 	struct sctp_paramhdr *p;
59 	int i;
60 
61 	/* Retrieve the SCTP per socket area.  */
62 	sp = sctp_sk((struct sock *)sk);
63 
64 	/* Discarding const is appropriate here.  */
65 	asoc->ep = (struct sctp_endpoint *)ep;
66 	asoc->base.sk = (struct sock *)sk;
67 	asoc->base.net = sock_net(sk);
68 
69 	sctp_endpoint_hold(asoc->ep);
70 	sock_hold(asoc->base.sk);
71 
72 	/* Initialize the common base substructure.  */
73 	asoc->base.type = SCTP_EP_TYPE_ASSOCIATION;
74 
75 	/* Initialize the object handling fields.  */
76 	refcount_set(&asoc->base.refcnt, 1);
77 
78 	/* Initialize the bind addr area.  */
79 	sctp_bind_addr_init(&asoc->base.bind_addr, ep->base.bind_addr.port);
80 
81 	asoc->state = SCTP_STATE_CLOSED;
82 	asoc->cookie_life = ms_to_ktime(sp->assocparams.sasoc_cookie_life);
83 	asoc->user_frag = sp->user_frag;
84 
85 	/* Set the association max_retrans and RTO values from the
86 	 * socket values.
87 	 */
88 	asoc->max_retrans = sp->assocparams.sasoc_asocmaxrxt;
89 	asoc->pf_retrans  = sp->pf_retrans;
90 	asoc->ps_retrans  = sp->ps_retrans;
91 	asoc->pf_expose   = sp->pf_expose;
92 
93 	asoc->rto_initial = msecs_to_jiffies(sp->rtoinfo.srto_initial);
94 	asoc->rto_max = msecs_to_jiffies(sp->rtoinfo.srto_max);
95 	asoc->rto_min = msecs_to_jiffies(sp->rtoinfo.srto_min);
96 
97 	/* Initialize the association's heartbeat interval based on the
98 	 * sock configured value.
99 	 */
100 	asoc->hbinterval = msecs_to_jiffies(sp->hbinterval);
101 	asoc->probe_interval = msecs_to_jiffies(sp->probe_interval);
102 
103 	asoc->encap_port = sp->encap_port;
104 
105 	/* Initialize path max retrans value. */
106 	asoc->pathmaxrxt = sp->pathmaxrxt;
107 
108 	asoc->flowlabel = sp->flowlabel;
109 	asoc->dscp = sp->dscp;
110 
111 	/* Set association default SACK delay */
112 	asoc->sackdelay = msecs_to_jiffies(sp->sackdelay);
113 	asoc->sackfreq = sp->sackfreq;
114 
115 	/* Set the association default flags controlling
116 	 * Heartbeat, SACK delay, and Path MTU Discovery.
117 	 */
118 	asoc->param_flags = sp->param_flags;
119 
120 	/* Initialize the maximum number of new data packets that can be sent
121 	 * in a burst.
122 	 */
123 	asoc->max_burst = sp->max_burst;
124 
125 	asoc->subscribe = sp->subscribe;
126 
127 	/* initialize association timers */
128 	asoc->timeouts[SCTP_EVENT_TIMEOUT_T1_COOKIE] = asoc->rto_initial;
129 	asoc->timeouts[SCTP_EVENT_TIMEOUT_T1_INIT] = asoc->rto_initial;
130 	asoc->timeouts[SCTP_EVENT_TIMEOUT_T2_SHUTDOWN] = asoc->rto_initial;
131 
132 	/* sctpimpguide Section 2.12.2
133 	 * If the 'T5-shutdown-guard' timer is used, it SHOULD be set to the
134 	 * recommended value of 5 times 'RTO.Max'.
135 	 */
136 	asoc->timeouts[SCTP_EVENT_TIMEOUT_T5_SHUTDOWN_GUARD]
137 		= 5 * asoc->rto_max;
138 
139 	asoc->timeouts[SCTP_EVENT_TIMEOUT_SACK] = asoc->sackdelay;
140 	asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE] =
141 		(unsigned long)sp->autoclose * HZ;
142 
143 	/* Initializes the timers */
144 	for (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i)
145 		timer_setup(&asoc->timers[i], sctp_timer_events[i], 0);
146 
147 	/* Pull default initialization values from the sock options.
148 	 * Note: This assumes that the values have already been
149 	 * validated in the sock.
150 	 */
151 	asoc->c.sinit_max_instreams = sp->initmsg.sinit_max_instreams;
152 	asoc->c.sinit_num_ostreams  = sp->initmsg.sinit_num_ostreams;
153 	asoc->max_init_attempts	= sp->initmsg.sinit_max_attempts;
154 
155 	asoc->max_init_timeo =
156 		 msecs_to_jiffies(sp->initmsg.sinit_max_init_timeo);
157 
158 	/* Set the local window size for receive.
159 	 * This is also the rcvbuf space per association.
160 	 * RFC 6 - A SCTP receiver MUST be able to receive a minimum of
161 	 * 1500 bytes in one SCTP packet.
162 	 */
163 	if ((sk->sk_rcvbuf/2) < SCTP_DEFAULT_MINWINDOW)
164 		asoc->rwnd = SCTP_DEFAULT_MINWINDOW;
165 	else
166 		asoc->rwnd = sk->sk_rcvbuf/2;
167 
168 	asoc->a_rwnd = asoc->rwnd;
169 
170 	/* Use my own max window until I learn something better.  */
171 	asoc->peer.rwnd = SCTP_DEFAULT_MAXWINDOW;
172 
173 	/* Initialize the receive memory counter */
174 	atomic_set(&asoc->rmem_alloc, 0);
175 
176 	init_waitqueue_head(&asoc->wait);
177 
178 	asoc->c.my_vtag = sctp_generate_tag(ep);
179 	asoc->c.my_port = ep->base.bind_addr.port;
180 
181 	asoc->c.initial_tsn = sctp_generate_tsn(ep);
182 
183 	asoc->next_tsn = asoc->c.initial_tsn;
184 
185 	asoc->ctsn_ack_point = asoc->next_tsn - 1;
186 	asoc->adv_peer_ack_point = asoc->ctsn_ack_point;
187 	asoc->highest_sacked = asoc->ctsn_ack_point;
188 	asoc->last_cwr_tsn = asoc->ctsn_ack_point;
189 
190 	/* ADDIP Section 4.1 Asconf Chunk Procedures
191 	 *
192 	 * When an endpoint has an ASCONF signaled change to be sent to the
193 	 * remote endpoint it should do the following:
194 	 * ...
195 	 * A2) a serial number should be assigned to the chunk. The serial
196 	 * number SHOULD be a monotonically increasing number. The serial
197 	 * numbers SHOULD be initialized at the start of the
198 	 * association to the same value as the initial TSN.
199 	 */
200 	asoc->addip_serial = asoc->c.initial_tsn;
201 	asoc->strreset_outseq = asoc->c.initial_tsn;
202 
203 	INIT_LIST_HEAD(&asoc->addip_chunk_list);
204 	INIT_LIST_HEAD(&asoc->asconf_ack_list);
205 
206 	/* Make an empty list of remote transport addresses.  */
207 	INIT_LIST_HEAD(&asoc->peer.transport_addr_list);
208 
209 	/* RFC 2960 5.1 Normal Establishment of an Association
210 	 *
211 	 * After the reception of the first data chunk in an
212 	 * association the endpoint must immediately respond with a
213 	 * sack to acknowledge the data chunk.  Subsequent
214 	 * acknowledgements should be done as described in Section
215 	 * 6.2.
216 	 *
217 	 * [We implement this by telling a new association that it
218 	 * already received one packet.]
219 	 */
220 	asoc->peer.sack_needed = 1;
221 	asoc->peer.sack_generation = 1;
222 
223 	/* Create an input queue.  */
224 	sctp_inq_init(&asoc->base.inqueue);
225 	sctp_inq_set_th_handler(&asoc->base.inqueue, sctp_assoc_bh_rcv);
226 
227 	/* Create an output queue.  */
228 	sctp_outq_init(asoc, &asoc->outqueue);
229 
230 	sctp_ulpq_init(&asoc->ulpq, asoc);
231 
232 	if (sctp_stream_init(&asoc->stream, asoc->c.sinit_num_ostreams, 0, gfp))
233 		goto stream_free;
234 
235 	/* Initialize default path MTU. */
236 	asoc->pathmtu = sp->pathmtu;
237 	sctp_assoc_update_frag_point(asoc);
238 
239 	/* Assume that peer would support both address types unless we are
240 	 * told otherwise.
241 	 */
242 	asoc->peer.ipv4_address = 1;
243 	if (asoc->base.sk->sk_family == PF_INET6)
244 		asoc->peer.ipv6_address = 1;
245 	INIT_LIST_HEAD(&asoc->asocs);
246 
247 	asoc->default_stream = sp->default_stream;
248 	asoc->default_ppid = sp->default_ppid;
249 	asoc->default_flags = sp->default_flags;
250 	asoc->default_context = sp->default_context;
251 	asoc->default_timetolive = sp->default_timetolive;
252 	asoc->default_rcv_context = sp->default_rcv_context;
253 
254 	/* AUTH related initializations */
255 	INIT_LIST_HEAD(&asoc->endpoint_shared_keys);
256 	if (sctp_auth_asoc_copy_shkeys(ep, asoc, gfp))
257 		goto stream_free;
258 
259 	asoc->active_key_id = ep->active_key_id;
260 	asoc->strreset_enable = ep->strreset_enable;
261 
262 	/* Save the hmacs and chunks list into this association */
263 	if (ep->auth_hmacs_list)
264 		memcpy(asoc->c.auth_hmacs, ep->auth_hmacs_list,
265 			ntohs(ep->auth_hmacs_list->param_hdr.length));
266 	if (ep->auth_chunk_list)
267 		memcpy(asoc->c.auth_chunks, ep->auth_chunk_list,
268 			ntohs(ep->auth_chunk_list->param_hdr.length));
269 
270 	/* Get the AUTH random number for this association */
271 	p = (struct sctp_paramhdr *)asoc->c.auth_random;
272 	p->type = SCTP_PARAM_RANDOM;
273 	p->length = htons(sizeof(*p) + SCTP_AUTH_RANDOM_LENGTH);
274 	get_random_bytes(p+1, SCTP_AUTH_RANDOM_LENGTH);
275 
276 	return asoc;
277 
278 stream_free:
279 	sctp_stream_free(&asoc->stream);
280 	sock_put(asoc->base.sk);
281 	sctp_endpoint_put(asoc->ep);
282 	return NULL;
283 }
284 
285 /* Allocate and initialize a new association */
286 struct sctp_association *sctp_association_new(const struct sctp_endpoint *ep,
287 					      const struct sock *sk,
288 					      enum sctp_scope scope, gfp_t gfp)
289 {
290 	struct sctp_association *asoc;
291 
292 	asoc = kzalloc(sizeof(*asoc), gfp);
293 	if (!asoc)
294 		goto fail;
295 
296 	if (!sctp_association_init(asoc, ep, sk, scope, gfp))
297 		goto fail_init;
298 
299 	SCTP_DBG_OBJCNT_INC(assoc);
300 
301 	pr_debug("Created asoc %p\n", asoc);
302 
303 	return asoc;
304 
305 fail_init:
306 	kfree(asoc);
307 fail:
308 	return NULL;
309 }
310 
311 /* Free this association if possible.  There may still be users, so
312  * the actual deallocation may be delayed.
313  */
314 void sctp_association_free(struct sctp_association *asoc)
315 {
316 	struct sock *sk = asoc->base.sk;
317 	struct sctp_transport *transport;
318 	struct list_head *pos, *temp;
319 	int i;
320 
321 	/* Only real associations count against the endpoint, so
322 	 * don't bother for if this is a temporary association.
323 	 */
324 	if (!list_empty(&asoc->asocs)) {
325 		list_del(&asoc->asocs);
326 
327 		/* Decrement the backlog value for a TCP-style listening
328 		 * socket.
329 		 */
330 		if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
331 			sk_acceptq_removed(sk);
332 	}
333 
334 	/* Mark as dead, so other users can know this structure is
335 	 * going away.
336 	 */
337 	asoc->base.dead = true;
338 
339 	/* Dispose of any data lying around in the outqueue. */
340 	sctp_outq_free(&asoc->outqueue);
341 
342 	/* Dispose of any pending messages for the upper layer. */
343 	sctp_ulpq_free(&asoc->ulpq);
344 
345 	/* Dispose of any pending chunks on the inqueue. */
346 	sctp_inq_free(&asoc->base.inqueue);
347 
348 	sctp_tsnmap_free(&asoc->peer.tsn_map);
349 
350 	/* Free stream information. */
351 	sctp_stream_free(&asoc->stream);
352 
353 	if (asoc->strreset_chunk)
354 		sctp_chunk_free(asoc->strreset_chunk);
355 
356 	/* Clean up the bound address list. */
357 	sctp_bind_addr_free(&asoc->base.bind_addr);
358 
359 	/* Do we need to go through all of our timers and
360 	 * delete them?   To be safe we will try to delete all, but we
361 	 * should be able to go through and make a guess based
362 	 * on our state.
363 	 */
364 	for (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i) {
365 		if (timer_delete(&asoc->timers[i]))
366 			sctp_association_put(asoc);
367 	}
368 
369 	/* Free peer's cached cookie. */
370 	kfree(asoc->peer.cookie);
371 	kfree(asoc->peer.peer_random);
372 	kfree(asoc->peer.peer_chunks);
373 	kfree(asoc->peer.peer_hmacs);
374 
375 	/* Release the transport structures. */
376 	list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
377 		transport = list_entry(pos, struct sctp_transport, transports);
378 		list_del_rcu(pos);
379 		sctp_unhash_transport(transport);
380 		sctp_transport_free(transport);
381 	}
382 
383 	asoc->peer.transport_count = 0;
384 
385 	sctp_asconf_queue_teardown(asoc);
386 
387 	/* Free pending address space being deleted */
388 	kfree(asoc->asconf_addr_del_pending);
389 
390 	/* AUTH - Free the endpoint shared keys */
391 	sctp_auth_destroy_keys(&asoc->endpoint_shared_keys);
392 
393 	/* AUTH - Free the association shared key */
394 	sctp_auth_key_put(asoc->asoc_shared_key);
395 
396 	sctp_association_put(asoc);
397 }
398 
399 /* Cleanup and free up an association. */
400 static void sctp_association_destroy(struct sctp_association *asoc)
401 {
402 	if (unlikely(!asoc->base.dead)) {
403 		WARN(1, "Attempt to destroy undead association %p!\n", asoc);
404 		return;
405 	}
406 
407 	sctp_endpoint_put(asoc->ep);
408 	sock_put(asoc->base.sk);
409 
410 	if (asoc->assoc_id != 0) {
411 		spin_lock_bh(&sctp_assocs_id_lock);
412 		idr_remove(&sctp_assocs_id, asoc->assoc_id);
413 		spin_unlock_bh(&sctp_assocs_id_lock);
414 	}
415 
416 	WARN_ON(atomic_read(&asoc->rmem_alloc));
417 
418 	kfree_rcu(asoc, rcu);
419 	SCTP_DBG_OBJCNT_DEC(assoc);
420 }
421 
422 /* Change the primary destination address for the peer. */
423 void sctp_assoc_set_primary(struct sctp_association *asoc,
424 			    struct sctp_transport *transport)
425 {
426 	int changeover = 0;
427 
428 	/* it's a changeover only if we already have a primary path
429 	 * that we are changing
430 	 */
431 	if (asoc->peer.primary_path != NULL &&
432 	    asoc->peer.primary_path != transport)
433 		changeover = 1 ;
434 
435 	asoc->peer.primary_path = transport;
436 	sctp_ulpevent_notify_peer_addr_change(transport,
437 					      SCTP_ADDR_MADE_PRIM, 0);
438 
439 	/* Set a default msg_name for events. */
440 	memcpy(&asoc->peer.primary_addr, &transport->ipaddr,
441 	       sizeof(union sctp_addr));
442 
443 	/* If the primary path is changing, assume that the
444 	 * user wants to use this new path.
445 	 */
446 	if ((transport->state == SCTP_ACTIVE) ||
447 	    (transport->state == SCTP_UNKNOWN))
448 		asoc->peer.active_path = transport;
449 
450 	/*
451 	 * SFR-CACC algorithm:
452 	 * Upon the receipt of a request to change the primary
453 	 * destination address, on the data structure for the new
454 	 * primary destination, the sender MUST do the following:
455 	 *
456 	 * 1) If CHANGEOVER_ACTIVE is set, then there was a switch
457 	 * to this destination address earlier. The sender MUST set
458 	 * CYCLING_CHANGEOVER to indicate that this switch is a
459 	 * double switch to the same destination address.
460 	 *
461 	 * Really, only bother is we have data queued or outstanding on
462 	 * the association.
463 	 */
464 	if (!asoc->outqueue.outstanding_bytes && !asoc->outqueue.out_qlen)
465 		return;
466 
467 	if (transport->cacc.changeover_active)
468 		transport->cacc.cycling_changeover = changeover;
469 
470 	/* 2) The sender MUST set CHANGEOVER_ACTIVE to indicate that
471 	 * a changeover has occurred.
472 	 */
473 	transport->cacc.changeover_active = changeover;
474 
475 	/* 3) The sender MUST store the next TSN to be sent in
476 	 * next_tsn_at_change.
477 	 */
478 	transport->cacc.next_tsn_at_change = asoc->next_tsn;
479 }
480 
481 /* Remove a transport from an association.  */
482 void sctp_assoc_rm_peer(struct sctp_association *asoc,
483 			struct sctp_transport *peer)
484 {
485 	struct sctp_transport *transport;
486 	struct list_head *pos;
487 	struct sctp_chunk *ch;
488 
489 	pr_debug("%s: association:%p addr:%pISpc\n",
490 		 __func__, asoc, &peer->ipaddr.sa);
491 
492 	/* If we are to remove the current retran_path, update it
493 	 * to the next peer before removing this peer from the list.
494 	 */
495 	if (asoc->peer.retran_path == peer)
496 		sctp_assoc_update_retran_path(asoc);
497 
498 	/* Remove this peer from the list. */
499 	list_del_rcu(&peer->transports);
500 	/* Remove this peer from the transport hashtable */
501 	sctp_unhash_transport(peer);
502 
503 	/* Get the first transport of asoc. */
504 	pos = asoc->peer.transport_addr_list.next;
505 	transport = list_entry(pos, struct sctp_transport, transports);
506 
507 	/* Update any entries that match the peer to be deleted. */
508 	if (asoc->peer.primary_path == peer)
509 		sctp_assoc_set_primary(asoc, transport);
510 	if (asoc->peer.active_path == peer)
511 		asoc->peer.active_path = transport;
512 	if (asoc->peer.retran_path == peer)
513 		asoc->peer.retran_path = transport;
514 	if (asoc->peer.last_data_from == peer)
515 		asoc->peer.last_data_from = transport;
516 
517 	if (asoc->strreset_chunk &&
518 	    asoc->strreset_chunk->transport == peer) {
519 		asoc->strreset_chunk->transport = transport;
520 		sctp_transport_reset_reconf_timer(transport);
521 	}
522 
523 	/* If we remove the transport an INIT was last sent to, set it to
524 	 * NULL. Combined with the update of the retran path above, this
525 	 * will cause the next INIT to be sent to the next available
526 	 * transport, maintaining the cycle.
527 	 */
528 	if (asoc->init_last_sent_to == peer)
529 		asoc->init_last_sent_to = NULL;
530 
531 	/* If we remove the transport an SHUTDOWN was last sent to, set it
532 	 * to NULL. Combined with the update of the retran path above, this
533 	 * will cause the next SHUTDOWN to be sent to the next available
534 	 * transport, maintaining the cycle.
535 	 */
536 	if (asoc->shutdown_last_sent_to == peer)
537 		asoc->shutdown_last_sent_to = NULL;
538 
539 	/* If we remove the transport an ASCONF was last sent to, set it to
540 	 * NULL.
541 	 */
542 	if (asoc->addip_last_asconf &&
543 	    asoc->addip_last_asconf->transport == peer)
544 		asoc->addip_last_asconf->transport = NULL;
545 
546 	/* If we have something on the transmitted list, we have to
547 	 * save it off.  The best place is the active path.
548 	 */
549 	if (!list_empty(&peer->transmitted)) {
550 		struct sctp_transport *active = asoc->peer.active_path;
551 
552 		/* Reset the transport of each chunk on this list */
553 		list_for_each_entry(ch, &peer->transmitted,
554 					transmitted_list) {
555 			ch->transport = NULL;
556 			ch->rtt_in_progress = 0;
557 		}
558 
559 		list_splice_tail_init(&peer->transmitted,
560 					&active->transmitted);
561 
562 		/* Start a T3 timer here in case it wasn't running so
563 		 * that these migrated packets have a chance to get
564 		 * retransmitted.
565 		 */
566 		if (!timer_pending(&active->T3_rtx_timer))
567 			if (!mod_timer(&active->T3_rtx_timer,
568 					jiffies + active->rto))
569 				sctp_transport_hold(active);
570 	}
571 
572 	list_for_each_entry(ch, &asoc->outqueue.out_chunk_list, list)
573 		if (ch->transport == peer)
574 			ch->transport = NULL;
575 
576 	asoc->peer.transport_count--;
577 
578 	sctp_ulpevent_notify_peer_addr_change(peer, SCTP_ADDR_REMOVED, 0);
579 	sctp_transport_free(peer);
580 }
581 
582 /* Add a transport address to an association.  */
583 struct sctp_transport *sctp_assoc_add_peer(struct sctp_association *asoc,
584 					   const union sctp_addr *addr,
585 					   const gfp_t gfp,
586 					   const int peer_state)
587 {
588 	struct sctp_transport *peer;
589 	struct sctp_sock *sp;
590 	unsigned short port;
591 
592 	sp = sctp_sk(asoc->base.sk);
593 
594 	/* AF_INET and AF_INET6 share common port field. */
595 	port = ntohs(addr->v4.sin_port);
596 
597 	pr_debug("%s: association:%p addr:%pISpc state:%d\n", __func__,
598 		 asoc, &addr->sa, peer_state);
599 
600 	/* Set the port if it has not been set yet.  */
601 	if (0 == asoc->peer.port)
602 		asoc->peer.port = port;
603 
604 	/* Check to see if this is a duplicate. */
605 	peer = sctp_assoc_lookup_paddr(asoc, addr);
606 	if (peer) {
607 		/* An UNKNOWN state is only set on transports added by
608 		 * user in sctp_connectx() call.  Such transports should be
609 		 * considered CONFIRMED per RFC 4960, Section 5.4.
610 		 */
611 		if (peer->state == SCTP_UNKNOWN) {
612 			peer->state = SCTP_ACTIVE;
613 		}
614 		return peer;
615 	}
616 
617 	peer = sctp_transport_new(asoc->base.net, addr, gfp);
618 	if (!peer)
619 		return NULL;
620 
621 	sctp_transport_set_owner(peer, asoc);
622 
623 	/* Initialize the peer's heartbeat interval based on the
624 	 * association configured value.
625 	 */
626 	peer->hbinterval = asoc->hbinterval;
627 	peer->probe_interval = asoc->probe_interval;
628 
629 	peer->encap_port = asoc->encap_port;
630 
631 	/* Set the path max_retrans.  */
632 	peer->pathmaxrxt = asoc->pathmaxrxt;
633 
634 	/* And the partial failure retrans threshold */
635 	peer->pf_retrans = asoc->pf_retrans;
636 	/* And the primary path switchover retrans threshold */
637 	peer->ps_retrans = asoc->ps_retrans;
638 
639 	/* Initialize the peer's SACK delay timeout based on the
640 	 * association configured value.
641 	 */
642 	peer->sackdelay = asoc->sackdelay;
643 	peer->sackfreq = asoc->sackfreq;
644 
645 	if (addr->sa.sa_family == AF_INET6) {
646 		__be32 info = addr->v6.sin6_flowinfo;
647 
648 		if (info) {
649 			peer->flowlabel = ntohl(info & IPV6_FLOWLABEL_MASK);
650 			peer->flowlabel |= SCTP_FLOWLABEL_SET_MASK;
651 		} else {
652 			peer->flowlabel = asoc->flowlabel;
653 		}
654 	}
655 	peer->dscp = asoc->dscp;
656 
657 	/* Enable/disable heartbeat, SACK delay, and path MTU discovery
658 	 * based on association setting.
659 	 */
660 	peer->param_flags = asoc->param_flags;
661 
662 	/* Initialize the pmtu of the transport. */
663 	sctp_transport_route(peer, NULL, sp);
664 
665 	/* If this is the first transport addr on this association,
666 	 * initialize the association PMTU to the peer's PMTU.
667 	 * If not and the current association PMTU is higher than the new
668 	 * peer's PMTU, reset the association PMTU to the new peer's PMTU.
669 	 */
670 	sctp_assoc_set_pmtu(asoc, asoc->pathmtu ?
671 				  min_t(int, peer->pathmtu, asoc->pathmtu) :
672 				  peer->pathmtu);
673 
674 	peer->pmtu_pending = 0;
675 
676 	/* The asoc->peer.port might not be meaningful yet, but
677 	 * initialize the packet structure anyway.
678 	 */
679 	sctp_packet_init(&peer->packet, peer, asoc->base.bind_addr.port,
680 			 asoc->peer.port);
681 
682 	/* 7.2.1 Slow-Start
683 	 *
684 	 * o The initial cwnd before DATA transmission or after a sufficiently
685 	 *   long idle period MUST be set to
686 	 *      min(4*MTU, max(2*MTU, 4380 bytes))
687 	 *
688 	 * o The initial value of ssthresh MAY be arbitrarily high
689 	 *   (for example, implementations MAY use the size of the
690 	 *   receiver advertised window).
691 	 */
692 	peer->cwnd = min(4*asoc->pathmtu, max_t(__u32, 2*asoc->pathmtu, 4380));
693 
694 	/* At this point, we may not have the receiver's advertised window,
695 	 * so initialize ssthresh to the default value and it will be set
696 	 * later when we process the INIT.
697 	 */
698 	peer->ssthresh = SCTP_DEFAULT_MAXWINDOW;
699 
700 	peer->partial_bytes_acked = 0;
701 	peer->flight_size = 0;
702 	peer->burst_limited = 0;
703 
704 	/* Set the transport's RTO.initial value */
705 	peer->rto = asoc->rto_initial;
706 	sctp_max_rto(asoc, peer);
707 
708 	/* Set the peer's active state. */
709 	peer->state = peer_state;
710 
711 	/* Add this peer into the transport hashtable */
712 	if (sctp_hash_transport(peer)) {
713 		sctp_transport_free(peer);
714 		return NULL;
715 	}
716 
717 	sctp_transport_pl_reset(peer);
718 
719 	/* Attach the remote transport to our asoc.  */
720 	list_add_tail_rcu(&peer->transports, &asoc->peer.transport_addr_list);
721 	asoc->peer.transport_count++;
722 
723 	sctp_ulpevent_notify_peer_addr_change(peer, SCTP_ADDR_ADDED, 0);
724 
725 	/* If we do not yet have a primary path, set one.  */
726 	if (!asoc->peer.primary_path) {
727 		sctp_assoc_set_primary(asoc, peer);
728 		asoc->peer.retran_path = peer;
729 	}
730 
731 	if (asoc->peer.active_path == asoc->peer.retran_path &&
732 	    peer->state != SCTP_UNCONFIRMED) {
733 		asoc->peer.retran_path = peer;
734 	}
735 
736 	return peer;
737 }
738 
739 /* Lookup a transport by address. */
740 struct sctp_transport *sctp_assoc_lookup_paddr(
741 					const struct sctp_association *asoc,
742 					const union sctp_addr *address)
743 {
744 	struct sctp_transport *t;
745 
746 	/* Cycle through all transports searching for a peer address. */
747 
748 	list_for_each_entry(t, &asoc->peer.transport_addr_list,
749 			transports) {
750 		if (sctp_cmp_addr_exact(address, &t->ipaddr))
751 			return t;
752 	}
753 
754 	return NULL;
755 }
756 
757 /* Remove all transports except a give one */
758 void sctp_assoc_del_nonprimary_peers(struct sctp_association *asoc,
759 				     struct sctp_transport *primary)
760 {
761 	struct sctp_transport	*temp;
762 	struct sctp_transport	*t;
763 
764 	list_for_each_entry_safe(t, temp, &asoc->peer.transport_addr_list,
765 				 transports) {
766 		/* if the current transport is not the primary one, delete it */
767 		if (t != primary)
768 			sctp_assoc_rm_peer(asoc, t);
769 	}
770 }
771 
772 /* Engage in transport control operations.
773  * Mark the transport up or down and send a notification to the user.
774  * Select and update the new active and retran paths.
775  */
776 void sctp_assoc_control_transport(struct sctp_association *asoc,
777 				  struct sctp_transport *transport,
778 				  enum sctp_transport_cmd command,
779 				  sctp_sn_error_t error)
780 {
781 	int spc_state = SCTP_ADDR_AVAILABLE;
782 	bool ulp_notify = true;
783 
784 	/* Record the transition on the transport.  */
785 	switch (command) {
786 	case SCTP_TRANSPORT_UP:
787 		/* If we are moving from UNCONFIRMED state due
788 		 * to heartbeat success, report the SCTP_ADDR_CONFIRMED
789 		 * state to the user, otherwise report SCTP_ADDR_AVAILABLE.
790 		 */
791 		if (transport->state == SCTP_PF &&
792 		    asoc->pf_expose != SCTP_PF_EXPOSE_ENABLE)
793 			ulp_notify = false;
794 		else if (transport->state == SCTP_UNCONFIRMED &&
795 			 error == SCTP_HEARTBEAT_SUCCESS)
796 			spc_state = SCTP_ADDR_CONFIRMED;
797 
798 		transport->state = SCTP_ACTIVE;
799 		sctp_transport_pl_reset(transport);
800 		break;
801 
802 	case SCTP_TRANSPORT_DOWN:
803 		/* If the transport was never confirmed, do not transition it
804 		 * to inactive state.  Also, release the cached route since
805 		 * there may be a better route next time.
806 		 */
807 		if (transport->state != SCTP_UNCONFIRMED) {
808 			transport->state = SCTP_INACTIVE;
809 			sctp_transport_pl_reset(transport);
810 			spc_state = SCTP_ADDR_UNREACHABLE;
811 		} else {
812 			sctp_transport_dst_release(transport);
813 			ulp_notify = false;
814 		}
815 		break;
816 
817 	case SCTP_TRANSPORT_PF:
818 		transport->state = SCTP_PF;
819 		if (asoc->pf_expose != SCTP_PF_EXPOSE_ENABLE)
820 			ulp_notify = false;
821 		else
822 			spc_state = SCTP_ADDR_POTENTIALLY_FAILED;
823 		break;
824 
825 	default:
826 		return;
827 	}
828 
829 	/* Generate and send a SCTP_PEER_ADDR_CHANGE notification
830 	 * to the user.
831 	 */
832 	if (ulp_notify)
833 		sctp_ulpevent_notify_peer_addr_change(transport,
834 						      spc_state, error);
835 
836 	/* Select new active and retran paths. */
837 	sctp_select_active_and_retran_path(asoc);
838 }
839 
840 /* Hold a reference to an association. */
841 void sctp_association_hold(struct sctp_association *asoc)
842 {
843 	refcount_inc(&asoc->base.refcnt);
844 }
845 
846 /* Release a reference to an association and cleanup
847  * if there are no more references.
848  */
849 void sctp_association_put(struct sctp_association *asoc)
850 {
851 	if (refcount_dec_and_test(&asoc->base.refcnt))
852 		sctp_association_destroy(asoc);
853 }
854 
855 /* Allocate the next TSN, Transmission Sequence Number, for the given
856  * association.
857  */
858 __u32 sctp_association_get_next_tsn(struct sctp_association *asoc)
859 {
860 	/* From Section 1.6 Serial Number Arithmetic:
861 	 * Transmission Sequence Numbers wrap around when they reach
862 	 * 2**32 - 1.  That is, the next TSN a DATA chunk MUST use
863 	 * after transmitting TSN = 2*32 - 1 is TSN = 0.
864 	 */
865 	__u32 retval = asoc->next_tsn;
866 	asoc->next_tsn++;
867 	asoc->unack_data++;
868 
869 	return retval;
870 }
871 
872 /* Compare two addresses to see if they match.  Wildcard addresses
873  * only match themselves.
874  */
875 int sctp_cmp_addr_exact(const union sctp_addr *ss1,
876 			const union sctp_addr *ss2)
877 {
878 	struct sctp_af *af;
879 
880 	af = sctp_get_af_specific(ss1->sa.sa_family);
881 	if (unlikely(!af))
882 		return 0;
883 
884 	return af->cmp_addr(ss1, ss2);
885 }
886 
887 /* Return an ecne chunk to get prepended to a packet.
888  * Note:  We are sly and return a shared, prealloced chunk.  FIXME:
889  * No we don't, but we could/should.
890  */
891 struct sctp_chunk *sctp_get_ecne_prepend(struct sctp_association *asoc)
892 {
893 	if (!asoc->need_ecne)
894 		return NULL;
895 
896 	/* Send ECNE if needed.
897 	 * Not being able to allocate a chunk here is not deadly.
898 	 */
899 	return sctp_make_ecne(asoc, asoc->last_ecne_tsn);
900 }
901 
902 /*
903  * Find which transport this TSN was sent on.
904  */
905 struct sctp_transport *sctp_assoc_lookup_tsn(struct sctp_association *asoc,
906 					     __u32 tsn)
907 {
908 	struct sctp_transport *active;
909 	struct sctp_transport *match;
910 	struct sctp_transport *transport;
911 	struct sctp_chunk *chunk;
912 	__be32 key = htonl(tsn);
913 
914 	match = NULL;
915 
916 	/*
917 	 * FIXME: In general, find a more efficient data structure for
918 	 * searching.
919 	 */
920 
921 	/*
922 	 * The general strategy is to search each transport's transmitted
923 	 * list.   Return which transport this TSN lives on.
924 	 *
925 	 * Let's be hopeful and check the active_path first.
926 	 * Another optimization would be to know if there is only one
927 	 * outbound path and not have to look for the TSN at all.
928 	 *
929 	 */
930 
931 	active = asoc->peer.active_path;
932 
933 	list_for_each_entry(chunk, &active->transmitted,
934 			transmitted_list) {
935 
936 		if (key == chunk->subh.data_hdr->tsn) {
937 			match = active;
938 			goto out;
939 		}
940 	}
941 
942 	/* If not found, go search all the other transports. */
943 	list_for_each_entry(transport, &asoc->peer.transport_addr_list,
944 			transports) {
945 
946 		if (transport == active)
947 			continue;
948 		list_for_each_entry(chunk, &transport->transmitted,
949 				transmitted_list) {
950 			if (key == chunk->subh.data_hdr->tsn) {
951 				match = transport;
952 				goto out;
953 			}
954 		}
955 	}
956 out:
957 	return match;
958 }
959 
960 /* Do delayed input processing.  This is scheduled by sctp_rcv(). */
961 static void sctp_assoc_bh_rcv(struct work_struct *work)
962 {
963 	struct sctp_association *asoc =
964 		container_of(work, struct sctp_association,
965 			     base.inqueue.immediate);
966 	struct net *net = asoc->base.net;
967 	union sctp_subtype subtype;
968 	struct sctp_endpoint *ep;
969 	struct sctp_chunk *chunk;
970 	struct sctp_inq *inqueue;
971 	int first_time = 1;	/* is this the first time through the loop */
972 	int error = 0;
973 	int state;
974 
975 	/* The association should be held so we should be safe. */
976 	ep = asoc->ep;
977 
978 	inqueue = &asoc->base.inqueue;
979 	sctp_association_hold(asoc);
980 	while (NULL != (chunk = sctp_inq_pop(inqueue))) {
981 		state = asoc->state;
982 		subtype = SCTP_ST_CHUNK(chunk->chunk_hdr->type);
983 
984 		/* If the first chunk in the packet is AUTH, do special
985 		 * processing specified in Section 6.3 of SCTP-AUTH spec
986 		 */
987 		if (first_time && subtype.chunk == SCTP_CID_AUTH) {
988 			struct sctp_chunkhdr *next_hdr;
989 
990 			next_hdr = sctp_inq_peek(inqueue);
991 			if (!next_hdr)
992 				goto normal;
993 
994 			/* If the next chunk is COOKIE-ECHO, skip the AUTH
995 			 * chunk while saving a pointer to it so we can do
996 			 * Authentication later (during cookie-echo
997 			 * processing).
998 			 */
999 			if (next_hdr->type == SCTP_CID_COOKIE_ECHO) {
1000 				chunk->auth_chunk = skb_clone(chunk->skb,
1001 							      GFP_ATOMIC);
1002 				chunk->auth = 1;
1003 				continue;
1004 			}
1005 		}
1006 
1007 normal:
1008 		/* SCTP-AUTH, Section 6.3:
1009 		 *    The receiver has a list of chunk types which it expects
1010 		 *    to be received only after an AUTH-chunk.  This list has
1011 		 *    been sent to the peer during the association setup.  It
1012 		 *    MUST silently discard these chunks if they are not placed
1013 		 *    after an AUTH chunk in the packet.
1014 		 */
1015 		if (sctp_auth_recv_cid(subtype.chunk, asoc) && !chunk->auth)
1016 			continue;
1017 
1018 		/* Remember where the last DATA chunk came from so we
1019 		 * know where to send the SACK.
1020 		 */
1021 		if (sctp_chunk_is_data(chunk))
1022 			asoc->peer.last_data_from = chunk->transport;
1023 		else {
1024 			SCTP_INC_STATS(net, SCTP_MIB_INCTRLCHUNKS);
1025 			asoc->stats.ictrlchunks++;
1026 			if (chunk->chunk_hdr->type == SCTP_CID_SACK)
1027 				asoc->stats.isacks++;
1028 		}
1029 
1030 		if (chunk->transport)
1031 			chunk->transport->last_time_heard = ktime_get();
1032 
1033 		/* Run through the state machine. */
1034 		error = sctp_do_sm(net, SCTP_EVENT_T_CHUNK, subtype,
1035 				   state, ep, asoc, chunk, GFP_ATOMIC);
1036 
1037 		/* Check to see if the association is freed in response to
1038 		 * the incoming chunk.  If so, get out of the while loop.
1039 		 */
1040 		if (asoc->base.dead)
1041 			break;
1042 
1043 		/* If there is an error on chunk, discard this packet. */
1044 		if (error && chunk)
1045 			chunk->pdiscard = 1;
1046 
1047 		if (first_time)
1048 			first_time = 0;
1049 	}
1050 	sctp_association_put(asoc);
1051 }
1052 
1053 /* This routine moves an association from its old sk to a new sk.  */
1054 void sctp_assoc_migrate(struct sctp_association *assoc, struct sock *newsk)
1055 {
1056 	struct sctp_sock *newsp = sctp_sk(newsk);
1057 	struct sock *oldsk = assoc->base.sk;
1058 
1059 	/* Delete the association from the old endpoint's list of
1060 	 * associations.
1061 	 */
1062 	list_del_init(&assoc->asocs);
1063 
1064 	/* Decrement the backlog value for a TCP-style socket. */
1065 	if (sctp_style(oldsk, TCP))
1066 		sk_acceptq_removed(oldsk);
1067 
1068 	/* Release references to the old endpoint and the sock.  */
1069 	sctp_endpoint_put(assoc->ep);
1070 	sock_put(assoc->base.sk);
1071 
1072 	/* Get a reference to the new endpoint.  */
1073 	assoc->ep = newsp->ep;
1074 	sctp_endpoint_hold(assoc->ep);
1075 
1076 	/* Get a reference to the new sock.  */
1077 	assoc->base.sk = newsk;
1078 	sock_hold(assoc->base.sk);
1079 
1080 	/* Add the association to the new endpoint's list of associations.  */
1081 	sctp_endpoint_add_asoc(newsp->ep, assoc);
1082 }
1083 
1084 /* Update an association (possibly from unexpected COOKIE-ECHO processing).  */
1085 int sctp_assoc_update(struct sctp_association *asoc,
1086 		      struct sctp_association *new)
1087 {
1088 	struct sctp_transport *trans;
1089 	struct list_head *pos, *temp;
1090 
1091 	/* Copy in new parameters of peer. */
1092 	asoc->c = new->c;
1093 	asoc->peer.rwnd = new->peer.rwnd;
1094 	asoc->peer.sack_needed = new->peer.sack_needed;
1095 	asoc->peer.auth_capable = new->peer.auth_capable;
1096 	asoc->peer.i = new->peer.i;
1097 
1098 	if (!sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,
1099 			      asoc->peer.i.initial_tsn, GFP_ATOMIC))
1100 		return -ENOMEM;
1101 
1102 	/* Remove any peer addresses not present in the new association. */
1103 	list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
1104 		trans = list_entry(pos, struct sctp_transport, transports);
1105 		if (!sctp_assoc_lookup_paddr(new, &trans->ipaddr)) {
1106 			sctp_assoc_rm_peer(asoc, trans);
1107 			continue;
1108 		}
1109 
1110 		if (asoc->state >= SCTP_STATE_ESTABLISHED)
1111 			sctp_transport_reset(trans);
1112 	}
1113 
1114 	/* If the case is A (association restart), use
1115 	 * initial_tsn as next_tsn. If the case is B, use
1116 	 * current next_tsn in case data sent to peer
1117 	 * has been discarded and needs retransmission.
1118 	 */
1119 	if (asoc->state >= SCTP_STATE_ESTABLISHED) {
1120 		asoc->next_tsn = new->next_tsn;
1121 		asoc->ctsn_ack_point = new->ctsn_ack_point;
1122 		asoc->adv_peer_ack_point = new->adv_peer_ack_point;
1123 
1124 		/* Reinitialize SSN for both local streams
1125 		 * and peer's streams.
1126 		 */
1127 		sctp_stream_clear(&asoc->stream);
1128 
1129 		/* Flush the ULP reassembly and ordered queue.
1130 		 * Any data there will now be stale and will
1131 		 * cause problems.
1132 		 */
1133 		sctp_ulpq_flush(&asoc->ulpq);
1134 
1135 		/* reset the overall association error count so
1136 		 * that the restarted association doesn't get torn
1137 		 * down on the next retransmission timer.
1138 		 */
1139 		asoc->overall_error_count = 0;
1140 
1141 	} else {
1142 		/* Add any peer addresses from the new association. */
1143 		list_for_each_entry(trans, &new->peer.transport_addr_list,
1144 				    transports)
1145 			if (!sctp_assoc_add_peer(asoc, &trans->ipaddr,
1146 						 GFP_ATOMIC, trans->state))
1147 				return -ENOMEM;
1148 
1149 		asoc->ctsn_ack_point = asoc->next_tsn - 1;
1150 		asoc->adv_peer_ack_point = asoc->ctsn_ack_point;
1151 
1152 		if (sctp_state(asoc, COOKIE_WAIT))
1153 			sctp_stream_update(&asoc->stream, &new->stream);
1154 
1155 		/* get a new assoc id if we don't have one yet. */
1156 		if (sctp_assoc_set_id(asoc, GFP_ATOMIC))
1157 			return -ENOMEM;
1158 	}
1159 
1160 	/* SCTP-AUTH: Save the peer parameters from the new associations
1161 	 * and also move the association shared keys over
1162 	 */
1163 	kfree(asoc->peer.peer_random);
1164 	asoc->peer.peer_random = new->peer.peer_random;
1165 	new->peer.peer_random = NULL;
1166 
1167 	kfree(asoc->peer.peer_chunks);
1168 	asoc->peer.peer_chunks = new->peer.peer_chunks;
1169 	new->peer.peer_chunks = NULL;
1170 
1171 	kfree(asoc->peer.peer_hmacs);
1172 	asoc->peer.peer_hmacs = new->peer.peer_hmacs;
1173 	new->peer.peer_hmacs = NULL;
1174 
1175 	return sctp_auth_asoc_init_active_key(asoc, GFP_ATOMIC);
1176 }
1177 
1178 /* Update the retran path for sending a retransmitted packet.
1179  * See also RFC4960, 6.4. Multi-Homed SCTP Endpoints:
1180  *
1181  *   When there is outbound data to send and the primary path
1182  *   becomes inactive (e.g., due to failures), or where the
1183  *   SCTP user explicitly requests to send data to an
1184  *   inactive destination transport address, before reporting
1185  *   an error to its ULP, the SCTP endpoint should try to send
1186  *   the data to an alternate active destination transport
1187  *   address if one exists.
1188  *
1189  *   When retransmitting data that timed out, if the endpoint
1190  *   is multihomed, it should consider each source-destination
1191  *   address pair in its retransmission selection policy.
1192  *   When retransmitting timed-out data, the endpoint should
1193  *   attempt to pick the most divergent source-destination
1194  *   pair from the original source-destination pair to which
1195  *   the packet was transmitted.
1196  *
1197  *   Note: Rules for picking the most divergent source-destination
1198  *   pair are an implementation decision and are not specified
1199  *   within this document.
1200  *
1201  * Our basic strategy is to round-robin transports in priorities
1202  * according to sctp_trans_score() e.g., if no such
1203  * transport with state SCTP_ACTIVE exists, round-robin through
1204  * SCTP_UNKNOWN, etc. You get the picture.
1205  */
1206 static u8 sctp_trans_score(const struct sctp_transport *trans)
1207 {
1208 	switch (trans->state) {
1209 	case SCTP_ACTIVE:
1210 		return 3;	/* best case */
1211 	case SCTP_UNKNOWN:
1212 		return 2;
1213 	case SCTP_PF:
1214 		return 1;
1215 	default: /* case SCTP_INACTIVE */
1216 		return 0;	/* worst case */
1217 	}
1218 }
1219 
1220 static struct sctp_transport *sctp_trans_elect_tie(struct sctp_transport *trans1,
1221 						   struct sctp_transport *trans2)
1222 {
1223 	if (trans1->error_count > trans2->error_count) {
1224 		return trans2;
1225 	} else if (trans1->error_count == trans2->error_count &&
1226 		   ktime_after(trans2->last_time_heard,
1227 			       trans1->last_time_heard)) {
1228 		return trans2;
1229 	} else {
1230 		return trans1;
1231 	}
1232 }
1233 
1234 static struct sctp_transport *sctp_trans_elect_best(struct sctp_transport *curr,
1235 						    struct sctp_transport *best)
1236 {
1237 	u8 score_curr, score_best;
1238 
1239 	if (best == NULL || curr == best)
1240 		return curr;
1241 
1242 	score_curr = sctp_trans_score(curr);
1243 	score_best = sctp_trans_score(best);
1244 
1245 	/* First, try a score-based selection if both transport states
1246 	 * differ. If we're in a tie, lets try to make a more clever
1247 	 * decision here based on error counts and last time heard.
1248 	 */
1249 	if (score_curr > score_best)
1250 		return curr;
1251 	else if (score_curr == score_best)
1252 		return sctp_trans_elect_tie(best, curr);
1253 	else
1254 		return best;
1255 }
1256 
1257 void sctp_assoc_update_retran_path(struct sctp_association *asoc)
1258 {
1259 	struct sctp_transport *trans = asoc->peer.retran_path;
1260 	struct sctp_transport *trans_next = NULL;
1261 
1262 	/* We're done as we only have the one and only path. */
1263 	if (asoc->peer.transport_count == 1)
1264 		return;
1265 	/* If active_path and retran_path are the same and active,
1266 	 * then this is the only active path. Use it.
1267 	 */
1268 	if (asoc->peer.active_path == asoc->peer.retran_path &&
1269 	    asoc->peer.active_path->state == SCTP_ACTIVE)
1270 		return;
1271 
1272 	/* Iterate from retran_path's successor back to retran_path. */
1273 	for (trans = list_next_entry(trans, transports); 1;
1274 	     trans = list_next_entry(trans, transports)) {
1275 		/* Manually skip the head element. */
1276 		if (&trans->transports == &asoc->peer.transport_addr_list)
1277 			continue;
1278 		if (trans->state == SCTP_UNCONFIRMED)
1279 			continue;
1280 		trans_next = sctp_trans_elect_best(trans, trans_next);
1281 		/* Active is good enough for immediate return. */
1282 		if (trans_next->state == SCTP_ACTIVE)
1283 			break;
1284 		/* We've reached the end, time to update path. */
1285 		if (trans == asoc->peer.retran_path)
1286 			break;
1287 	}
1288 
1289 	asoc->peer.retran_path = trans_next;
1290 
1291 	pr_debug("%s: association:%p updated new path to addr:%pISpc\n",
1292 		 __func__, asoc, &asoc->peer.retran_path->ipaddr.sa);
1293 }
1294 
1295 static void sctp_select_active_and_retran_path(struct sctp_association *asoc)
1296 {
1297 	struct sctp_transport *trans, *trans_pri = NULL, *trans_sec = NULL;
1298 	struct sctp_transport *trans_pf = NULL;
1299 
1300 	/* Look for the two most recently used active transports. */
1301 	list_for_each_entry(trans, &asoc->peer.transport_addr_list,
1302 			    transports) {
1303 		/* Skip uninteresting transports. */
1304 		if (trans->state == SCTP_INACTIVE ||
1305 		    trans->state == SCTP_UNCONFIRMED)
1306 			continue;
1307 		/* Keep track of the best PF transport from our
1308 		 * list in case we don't find an active one.
1309 		 */
1310 		if (trans->state == SCTP_PF) {
1311 			trans_pf = sctp_trans_elect_best(trans, trans_pf);
1312 			continue;
1313 		}
1314 		/* For active transports, pick the most recent ones. */
1315 		if (trans_pri == NULL ||
1316 		    ktime_after(trans->last_time_heard,
1317 				trans_pri->last_time_heard)) {
1318 			trans_sec = trans_pri;
1319 			trans_pri = trans;
1320 		} else if (trans_sec == NULL ||
1321 			   ktime_after(trans->last_time_heard,
1322 				       trans_sec->last_time_heard)) {
1323 			trans_sec = trans;
1324 		}
1325 	}
1326 
1327 	/* RFC 2960 6.4 Multi-Homed SCTP Endpoints
1328 	 *
1329 	 * By default, an endpoint should always transmit to the primary
1330 	 * path, unless the SCTP user explicitly specifies the
1331 	 * destination transport address (and possibly source transport
1332 	 * address) to use. [If the primary is active but not most recent,
1333 	 * bump the most recently used transport.]
1334 	 */
1335 	if ((asoc->peer.primary_path->state == SCTP_ACTIVE ||
1336 	     asoc->peer.primary_path->state == SCTP_UNKNOWN) &&
1337 	     asoc->peer.primary_path != trans_pri) {
1338 		trans_sec = trans_pri;
1339 		trans_pri = asoc->peer.primary_path;
1340 	}
1341 
1342 	/* We did not find anything useful for a possible retransmission
1343 	 * path; either primary path that we found is the same as
1344 	 * the current one, or we didn't generally find an active one.
1345 	 */
1346 	if (trans_sec == NULL)
1347 		trans_sec = trans_pri;
1348 
1349 	/* If we failed to find a usable transport, just camp on the
1350 	 * active or pick a PF iff it's the better choice.
1351 	 */
1352 	if (trans_pri == NULL) {
1353 		trans_pri = sctp_trans_elect_best(asoc->peer.active_path, trans_pf);
1354 		trans_sec = trans_pri;
1355 	}
1356 
1357 	/* Set the active and retran transports. */
1358 	asoc->peer.active_path = trans_pri;
1359 	asoc->peer.retran_path = trans_sec;
1360 }
1361 
1362 struct sctp_transport *
1363 sctp_assoc_choose_alter_transport(struct sctp_association *asoc,
1364 				  struct sctp_transport *last_sent_to)
1365 {
1366 	/* If this is the first time packet is sent, use the active path,
1367 	 * else use the retran path. If the last packet was sent over the
1368 	 * retran path, update the retran path and use it.
1369 	 */
1370 	if (last_sent_to == NULL) {
1371 		return asoc->peer.active_path;
1372 	} else {
1373 		if (last_sent_to == asoc->peer.retran_path)
1374 			sctp_assoc_update_retran_path(asoc);
1375 
1376 		return asoc->peer.retran_path;
1377 	}
1378 }
1379 
1380 void sctp_assoc_update_frag_point(struct sctp_association *asoc)
1381 {
1382 	int frag = sctp_mtu_payload(sctp_sk(asoc->base.sk), asoc->pathmtu,
1383 				    sctp_datachk_len(&asoc->stream));
1384 
1385 	if (asoc->user_frag)
1386 		frag = min_t(int, frag, asoc->user_frag);
1387 
1388 	frag = min_t(int, frag, SCTP_MAX_CHUNK_LEN -
1389 				sctp_datachk_len(&asoc->stream));
1390 
1391 	asoc->frag_point = SCTP_TRUNC4(frag);
1392 }
1393 
1394 void sctp_assoc_set_pmtu(struct sctp_association *asoc, __u32 pmtu)
1395 {
1396 	if (asoc->pathmtu != pmtu) {
1397 		asoc->pathmtu = pmtu;
1398 		sctp_assoc_update_frag_point(asoc);
1399 	}
1400 
1401 	pr_debug("%s: asoc:%p, pmtu:%d, frag_point:%d\n", __func__, asoc,
1402 		 asoc->pathmtu, asoc->frag_point);
1403 }
1404 
1405 /* Update the association's pmtu and frag_point by going through all the
1406  * transports. This routine is called when a transport's PMTU has changed.
1407  */
1408 void sctp_assoc_sync_pmtu(struct sctp_association *asoc)
1409 {
1410 	struct sctp_transport *t;
1411 	__u32 pmtu = 0;
1412 
1413 	if (!asoc)
1414 		return;
1415 
1416 	/* Get the lowest pmtu of all the transports. */
1417 	list_for_each_entry(t, &asoc->peer.transport_addr_list, transports) {
1418 		if (t->pmtu_pending && t->dst) {
1419 			sctp_transport_update_pmtu(t,
1420 						   atomic_read(&t->mtu_info));
1421 			t->pmtu_pending = 0;
1422 		}
1423 		if (!pmtu || (t->pathmtu < pmtu))
1424 			pmtu = t->pathmtu;
1425 	}
1426 
1427 	sctp_assoc_set_pmtu(asoc, pmtu);
1428 }
1429 
1430 /* Should we send a SACK to update our peer? */
1431 static inline bool sctp_peer_needs_update(struct sctp_association *asoc)
1432 {
1433 	struct net *net = asoc->base.net;
1434 
1435 	switch (asoc->state) {
1436 	case SCTP_STATE_ESTABLISHED:
1437 	case SCTP_STATE_SHUTDOWN_PENDING:
1438 	case SCTP_STATE_SHUTDOWN_RECEIVED:
1439 	case SCTP_STATE_SHUTDOWN_SENT:
1440 		if ((asoc->rwnd > asoc->a_rwnd) &&
1441 		    ((asoc->rwnd - asoc->a_rwnd) >= max_t(__u32,
1442 			   (asoc->base.sk->sk_rcvbuf >> net->sctp.rwnd_upd_shift),
1443 			   asoc->pathmtu)))
1444 			return true;
1445 		break;
1446 	default:
1447 		break;
1448 	}
1449 	return false;
1450 }
1451 
1452 /* Increase asoc's rwnd by len and send any window update SACK if needed. */
1453 void sctp_assoc_rwnd_increase(struct sctp_association *asoc, unsigned int len)
1454 {
1455 	struct sctp_chunk *sack;
1456 	struct timer_list *timer;
1457 
1458 	if (asoc->rwnd_over) {
1459 		if (asoc->rwnd_over >= len) {
1460 			asoc->rwnd_over -= len;
1461 		} else {
1462 			asoc->rwnd += (len - asoc->rwnd_over);
1463 			asoc->rwnd_over = 0;
1464 		}
1465 	} else {
1466 		asoc->rwnd += len;
1467 	}
1468 
1469 	/* If we had window pressure, start recovering it
1470 	 * once our rwnd had reached the accumulated pressure
1471 	 * threshold.  The idea is to recover slowly, but up
1472 	 * to the initial advertised window.
1473 	 */
1474 	if (asoc->rwnd_press) {
1475 		int change = min(asoc->pathmtu, asoc->rwnd_press);
1476 		asoc->rwnd += change;
1477 		asoc->rwnd_press -= change;
1478 	}
1479 
1480 	pr_debug("%s: asoc:%p rwnd increased by %d to (%u, %u) - %u\n",
1481 		 __func__, asoc, len, asoc->rwnd, asoc->rwnd_over,
1482 		 asoc->a_rwnd);
1483 
1484 	/* Send a window update SACK if the rwnd has increased by at least the
1485 	 * minimum of the association's PMTU and half of the receive buffer.
1486 	 * The algorithm used is similar to the one described in
1487 	 * Section 4.2.3.3 of RFC 1122.
1488 	 */
1489 	if (sctp_peer_needs_update(asoc)) {
1490 		asoc->a_rwnd = asoc->rwnd;
1491 
1492 		pr_debug("%s: sending window update SACK- asoc:%p rwnd:%u "
1493 			 "a_rwnd:%u\n", __func__, asoc, asoc->rwnd,
1494 			 asoc->a_rwnd);
1495 
1496 		sack = sctp_make_sack(asoc);
1497 		if (!sack)
1498 			return;
1499 
1500 		asoc->peer.sack_needed = 0;
1501 
1502 		sctp_outq_tail(&asoc->outqueue, sack, GFP_ATOMIC);
1503 
1504 		/* Stop the SACK timer.  */
1505 		timer = &asoc->timers[SCTP_EVENT_TIMEOUT_SACK];
1506 		if (timer_delete(timer))
1507 			sctp_association_put(asoc);
1508 	}
1509 }
1510 
1511 /* Decrease asoc's rwnd by len. */
1512 void sctp_assoc_rwnd_decrease(struct sctp_association *asoc, unsigned int len)
1513 {
1514 	int rx_count;
1515 	int over = 0;
1516 
1517 	if (unlikely(!asoc->rwnd || asoc->rwnd_over))
1518 		pr_debug("%s: association:%p has asoc->rwnd:%u, "
1519 			 "asoc->rwnd_over:%u!\n", __func__, asoc,
1520 			 asoc->rwnd, asoc->rwnd_over);
1521 
1522 	if (asoc->ep->rcvbuf_policy)
1523 		rx_count = atomic_read(&asoc->rmem_alloc);
1524 	else
1525 		rx_count = atomic_read(&asoc->base.sk->sk_rmem_alloc);
1526 
1527 	/* If we've reached or overflowed our receive buffer, announce
1528 	 * a 0 rwnd if rwnd would still be positive.  Store the
1529 	 * potential pressure overflow so that the window can be restored
1530 	 * back to original value.
1531 	 */
1532 	if (rx_count >= asoc->base.sk->sk_rcvbuf)
1533 		over = 1;
1534 
1535 	if (asoc->rwnd >= len) {
1536 		asoc->rwnd -= len;
1537 		if (over) {
1538 			asoc->rwnd_press += asoc->rwnd;
1539 			asoc->rwnd = 0;
1540 		}
1541 	} else {
1542 		asoc->rwnd_over += len - asoc->rwnd;
1543 		asoc->rwnd = 0;
1544 	}
1545 
1546 	pr_debug("%s: asoc:%p rwnd decreased by %d to (%u, %u, %u)\n",
1547 		 __func__, asoc, len, asoc->rwnd, asoc->rwnd_over,
1548 		 asoc->rwnd_press);
1549 }
1550 
1551 /* Build the bind address list for the association based on info from the
1552  * local endpoint and the remote peer.
1553  */
1554 int sctp_assoc_set_bind_addr_from_ep(struct sctp_association *asoc,
1555 				     enum sctp_scope scope, gfp_t gfp)
1556 {
1557 	struct sock *sk = asoc->base.sk;
1558 	int flags;
1559 
1560 	/* Use scoping rules to determine the subset of addresses from
1561 	 * the endpoint.
1562 	 */
1563 	flags = (PF_INET6 == sk->sk_family) ? SCTP_ADDR6_ALLOWED : 0;
1564 	if (!inet_v6_ipv6only(sk))
1565 		flags |= SCTP_ADDR4_ALLOWED;
1566 	if (asoc->peer.ipv4_address)
1567 		flags |= SCTP_ADDR4_PEERSUPP;
1568 	if (asoc->peer.ipv6_address)
1569 		flags |= SCTP_ADDR6_PEERSUPP;
1570 
1571 	return sctp_bind_addr_copy(asoc->base.net,
1572 				   &asoc->base.bind_addr,
1573 				   &asoc->ep->base.bind_addr,
1574 				   scope, gfp, flags);
1575 }
1576 
1577 /* Build the association's bind address list from the cookie.  */
1578 int sctp_assoc_set_bind_addr_from_cookie(struct sctp_association *asoc,
1579 					 struct sctp_cookie *cookie,
1580 					 gfp_t gfp)
1581 {
1582 	struct sctp_init_chunk *peer_init = (struct sctp_init_chunk *)(cookie + 1);
1583 	int var_size2 = ntohs(peer_init->chunk_hdr.length);
1584 	int var_size3 = cookie->raw_addr_list_len;
1585 	__u8 *raw = (__u8 *)peer_init + var_size2;
1586 
1587 	return sctp_raw_to_bind_addrs(&asoc->base.bind_addr, raw, var_size3,
1588 				      asoc->ep->base.bind_addr.port, gfp);
1589 }
1590 
1591 /* Lookup laddr in the bind address list of an association. */
1592 int sctp_assoc_lookup_laddr(struct sctp_association *asoc,
1593 			    const union sctp_addr *laddr)
1594 {
1595 	int found = 0;
1596 
1597 	if ((asoc->base.bind_addr.port == ntohs(laddr->v4.sin_port)) &&
1598 	    sctp_bind_addr_match(&asoc->base.bind_addr, laddr,
1599 				 sctp_sk(asoc->base.sk)))
1600 		found = 1;
1601 
1602 	return found;
1603 }
1604 
1605 /* Set an association id for a given association */
1606 int sctp_assoc_set_id(struct sctp_association *asoc, gfp_t gfp)
1607 {
1608 	bool preload = gfpflags_allow_blocking(gfp);
1609 	int ret;
1610 
1611 	/* If the id is already assigned, keep it. */
1612 	if (asoc->assoc_id)
1613 		return 0;
1614 
1615 	if (preload)
1616 		idr_preload(gfp);
1617 	spin_lock_bh(&sctp_assocs_id_lock);
1618 	/* 0, 1, 2 are used as SCTP_FUTURE_ASSOC, SCTP_CURRENT_ASSOC and
1619 	 * SCTP_ALL_ASSOC, so an available id must be > SCTP_ALL_ASSOC.
1620 	 */
1621 	ret = idr_alloc_cyclic(&sctp_assocs_id, asoc, SCTP_ALL_ASSOC + 1, 0,
1622 			       GFP_NOWAIT);
1623 	spin_unlock_bh(&sctp_assocs_id_lock);
1624 	if (preload)
1625 		idr_preload_end();
1626 	if (ret < 0)
1627 		return ret;
1628 
1629 	asoc->assoc_id = (sctp_assoc_t)ret;
1630 	return 0;
1631 }
1632 
1633 /* Free the ASCONF queue */
1634 static void sctp_assoc_free_asconf_queue(struct sctp_association *asoc)
1635 {
1636 	struct sctp_chunk *asconf;
1637 	struct sctp_chunk *tmp;
1638 
1639 	list_for_each_entry_safe(asconf, tmp, &asoc->addip_chunk_list, list) {
1640 		list_del_init(&asconf->list);
1641 		sctp_chunk_free(asconf);
1642 	}
1643 }
1644 
1645 /* Free asconf_ack cache */
1646 static void sctp_assoc_free_asconf_acks(struct sctp_association *asoc)
1647 {
1648 	struct sctp_chunk *ack;
1649 	struct sctp_chunk *tmp;
1650 
1651 	list_for_each_entry_safe(ack, tmp, &asoc->asconf_ack_list,
1652 				transmitted_list) {
1653 		list_del_init(&ack->transmitted_list);
1654 		sctp_chunk_free(ack);
1655 	}
1656 }
1657 
1658 /* Clean up the ASCONF_ACK queue */
1659 void sctp_assoc_clean_asconf_ack_cache(const struct sctp_association *asoc)
1660 {
1661 	struct sctp_chunk *ack;
1662 	struct sctp_chunk *tmp;
1663 
1664 	/* We can remove all the entries from the queue up to
1665 	 * the "Peer-Sequence-Number".
1666 	 */
1667 	list_for_each_entry_safe(ack, tmp, &asoc->asconf_ack_list,
1668 				transmitted_list) {
1669 		if (ack->subh.addip_hdr->serial ==
1670 				htonl(asoc->peer.addip_serial))
1671 			break;
1672 
1673 		list_del_init(&ack->transmitted_list);
1674 		sctp_chunk_free(ack);
1675 	}
1676 }
1677 
1678 /* Find the ASCONF_ACK whose serial number matches ASCONF */
1679 struct sctp_chunk *sctp_assoc_lookup_asconf_ack(
1680 					const struct sctp_association *asoc,
1681 					__be32 serial)
1682 {
1683 	struct sctp_chunk *ack;
1684 
1685 	/* Walk through the list of cached ASCONF-ACKs and find the
1686 	 * ack chunk whose serial number matches that of the request.
1687 	 */
1688 	list_for_each_entry(ack, &asoc->asconf_ack_list, transmitted_list) {
1689 		if (sctp_chunk_pending(ack))
1690 			continue;
1691 		if (ack->subh.addip_hdr->serial == serial) {
1692 			sctp_chunk_hold(ack);
1693 			return ack;
1694 		}
1695 	}
1696 
1697 	return NULL;
1698 }
1699 
1700 void sctp_asconf_queue_teardown(struct sctp_association *asoc)
1701 {
1702 	/* Free any cached ASCONF_ACK chunk. */
1703 	sctp_assoc_free_asconf_acks(asoc);
1704 
1705 	/* Free the ASCONF queue. */
1706 	sctp_assoc_free_asconf_queue(asoc);
1707 
1708 	/* Free any cached ASCONF chunk. */
1709 	if (asoc->addip_last_asconf)
1710 		sctp_chunk_free(asoc->addip_last_asconf);
1711 }
1712