xref: /freebsd/sys/netinet/sctp_pcb.c (revision d0b2dbfa0ecf2bbc9709efc5e20baf8e4b44bbbf)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2001-2008, by Cisco Systems, Inc. All rights reserved.
5  * Copyright (c) 2008-2012, by Randall Stewart. All rights reserved.
6  * Copyright (c) 2008-2012, by Michael Tuexen. All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * a) Redistributions of source code must retain the above copyright notice,
12  *    this list of conditions and the following disclaimer.
13  *
14  * b) Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the distribution.
17  *
18  * c) Neither the name of Cisco Systems, Inc. nor the names of its
19  *    contributors may be used to endorse or promote products derived
20  *    from this software without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
24  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
26  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
32  * THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #include <netinet/sctp_os.h>
37 #include <sys/proc.h>
38 #include <netinet/sctp_var.h>
39 #include <netinet/sctp_sysctl.h>
40 #include <netinet/sctp_pcb.h>
41 #include <netinet/sctputil.h>
42 #include <netinet/sctp.h>
43 #include <netinet/sctp_header.h>
44 #include <netinet/sctp_asconf.h>
45 #include <netinet/sctp_output.h>
46 #include <netinet/sctp_timer.h>
47 #include <netinet/sctp_bsd_addr.h>
48 #if defined(INET) || defined(INET6)
49 #include <netinet/udp.h>
50 #endif
51 #ifdef INET6
52 #include <netinet6/ip6_var.h>
53 #endif
54 #include <sys/sched.h>
55 #include <sys/smp.h>
56 #include <sys/unistd.h>
57 
58 /* FIX: we don't handle multiple link local scopes */
59 /* "scopeless" replacement IN6_ARE_ADDR_EQUAL */
60 #ifdef INET6
61 int
62 SCTP6_ARE_ADDR_EQUAL(struct sockaddr_in6 *a, struct sockaddr_in6 *b)
63 {
64 	struct sockaddr_in6 tmp_a, tmp_b;
65 
66 	memcpy(&tmp_a, a, sizeof(struct sockaddr_in6));
67 	if (sa6_embedscope(&tmp_a, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
68 		return (0);
69 	}
70 	memcpy(&tmp_b, b, sizeof(struct sockaddr_in6));
71 	if (sa6_embedscope(&tmp_b, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
72 		return (0);
73 	}
74 	return (IN6_ARE_ADDR_EQUAL(&tmp_a.sin6_addr, &tmp_b.sin6_addr));
75 }
76 #endif
77 
78 void
79 sctp_fill_pcbinfo(struct sctp_pcbinfo *spcb)
80 {
81 	/*
82 	 * We really don't need to lock this, but I will just because it
83 	 * does not hurt.
84 	 */
85 	SCTP_INP_INFO_RLOCK();
86 	spcb->ep_count = SCTP_BASE_INFO(ipi_count_ep);
87 	spcb->asoc_count = SCTP_BASE_INFO(ipi_count_asoc);
88 	spcb->laddr_count = SCTP_BASE_INFO(ipi_count_laddr);
89 	spcb->raddr_count = SCTP_BASE_INFO(ipi_count_raddr);
90 	spcb->chk_count = SCTP_BASE_INFO(ipi_count_chunk);
91 	spcb->readq_count = SCTP_BASE_INFO(ipi_count_readq);
92 	spcb->stream_oque = SCTP_BASE_INFO(ipi_count_strmoq);
93 	spcb->free_chunks = SCTP_BASE_INFO(ipi_free_chunks);
94 	SCTP_INP_INFO_RUNLOCK();
95 }
96 
97 /*-
98  * Addresses are added to VRF's (Virtual Router's). For BSD we
99  * have only the default VRF 0. We maintain a hash list of
100  * VRF's. Each VRF has its own list of sctp_ifn's. Each of
101  * these has a list of addresses. When we add a new address
102  * to a VRF we lookup the ifn/ifn_index, if the ifn does
103  * not exist we create it and add it to the list of IFN's
104  * within the VRF. Once we have the sctp_ifn, we add the
105  * address to the list. So we look something like:
106  *
107  * hash-vrf-table
108  *   vrf-> ifn-> ifn -> ifn
109  *   vrf    |
110  *    ...   +--ifa-> ifa -> ifa
111  *   vrf
112  *
113  * We keep these separate lists since the SCTP subsystem will
114  * point to these from its source address selection nets structure.
115  * When an address is deleted it does not happen right away on
116  * the SCTP side, it gets scheduled. What we do when a
117  * delete happens is immediately remove the address from
118  * the master list and decrement the refcount. As our
119  * addip iterator works through and frees the src address
120  * selection pointing to the sctp_ifa, eventually the refcount
121  * will reach 0 and we will delete it. Note that it is assumed
122  * that any locking on system level ifn/ifa is done at the
123  * caller of these functions and these routines will only
124  * lock the SCTP structures as they add or delete things.
125  *
126  * Other notes on VRF concepts.
127  *  - An endpoint can be in multiple VRF's
128  *  - An association lives within a VRF and only one VRF.
129  *  - Any incoming packet we can deduce the VRF for by
130  *    looking at the mbuf/pak inbound (for BSD its VRF=0 :D)
131  *  - Any downward send call or connect call must supply the
132  *    VRF via ancillary data or via some sort of set default
133  *    VRF socket option call (again for BSD no brainer since
134  *    the VRF is always 0).
135  *  - An endpoint may add multiple VRF's to it.
136  *  - Listening sockets can accept associations in any
137  *    of the VRF's they are in but the assoc will end up
138  *    in only one VRF (gotten from the packet or connect/send).
139  *
140  */
141 
142 struct sctp_vrf *
143 sctp_allocate_vrf(int vrf_id)
144 {
145 	struct sctp_vrf *vrf = NULL;
146 	struct sctp_vrflist *bucket;
147 
148 	/* First allocate the VRF structure */
149 	vrf = sctp_find_vrf(vrf_id);
150 	if (vrf) {
151 		/* Already allocated */
152 		return (vrf);
153 	}
154 	SCTP_MALLOC(vrf, struct sctp_vrf *, sizeof(struct sctp_vrf),
155 	    SCTP_M_VRF);
156 	if (vrf == NULL) {
157 		/* No memory */
158 #ifdef INVARIANTS
159 		panic("No memory for VRF:%d", vrf_id);
160 #endif
161 		return (NULL);
162 	}
163 	/* setup the VRF */
164 	memset(vrf, 0, sizeof(struct sctp_vrf));
165 	vrf->vrf_id = vrf_id;
166 	LIST_INIT(&vrf->ifnlist);
167 	vrf->total_ifa_count = 0;
168 	vrf->refcount = 0;
169 	/* now also setup table ids */
170 	SCTP_INIT_VRF_TABLEID(vrf);
171 	/* Init the HASH of addresses */
172 	vrf->vrf_addr_hash = SCTP_HASH_INIT(SCTP_VRF_ADDR_HASH_SIZE,
173 	    &vrf->vrf_addr_hashmark);
174 	if (vrf->vrf_addr_hash == NULL) {
175 		/* No memory */
176 #ifdef INVARIANTS
177 		panic("No memory for VRF:%d", vrf_id);
178 #endif
179 		SCTP_FREE(vrf, SCTP_M_VRF);
180 		return (NULL);
181 	}
182 
183 	/* Add it to the hash table */
184 	bucket = &SCTP_BASE_INFO(sctp_vrfhash)[(vrf_id & SCTP_BASE_INFO(hashvrfmark))];
185 	LIST_INSERT_HEAD(bucket, vrf, next_vrf);
186 	atomic_add_int(&SCTP_BASE_INFO(ipi_count_vrfs), 1);
187 	return (vrf);
188 }
189 
190 struct sctp_ifn *
191 sctp_find_ifn(void *ifn, uint32_t ifn_index)
192 {
193 	struct sctp_ifn *sctp_ifnp;
194 	struct sctp_ifnlist *hash_ifn_head;
195 
196 	/*
197 	 * We assume the lock is held for the addresses if that's wrong
198 	 * problems could occur :-)
199 	 */
200 	SCTP_IPI_ADDR_LOCK_ASSERT();
201 	hash_ifn_head = &SCTP_BASE_INFO(vrf_ifn_hash)[(ifn_index & SCTP_BASE_INFO(vrf_ifn_hashmark))];
202 	LIST_FOREACH(sctp_ifnp, hash_ifn_head, next_bucket) {
203 		if (sctp_ifnp->ifn_index == ifn_index) {
204 			return (sctp_ifnp);
205 		}
206 		if (sctp_ifnp->ifn_p && ifn && (sctp_ifnp->ifn_p == ifn)) {
207 			return (sctp_ifnp);
208 		}
209 	}
210 	return (NULL);
211 }
212 
213 struct sctp_vrf *
214 sctp_find_vrf(uint32_t vrf_id)
215 {
216 	struct sctp_vrflist *bucket;
217 	struct sctp_vrf *liste;
218 
219 	bucket = &SCTP_BASE_INFO(sctp_vrfhash)[(vrf_id & SCTP_BASE_INFO(hashvrfmark))];
220 	LIST_FOREACH(liste, bucket, next_vrf) {
221 		if (vrf_id == liste->vrf_id) {
222 			return (liste);
223 		}
224 	}
225 	return (NULL);
226 }
227 
228 void
229 sctp_free_vrf(struct sctp_vrf *vrf)
230 {
231 	if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&vrf->refcount)) {
232 		if (vrf->vrf_addr_hash) {
233 			SCTP_HASH_FREE(vrf->vrf_addr_hash, vrf->vrf_addr_hashmark);
234 			vrf->vrf_addr_hash = NULL;
235 		}
236 		/* We zero'd the count */
237 		LIST_REMOVE(vrf, next_vrf);
238 		SCTP_FREE(vrf, SCTP_M_VRF);
239 		atomic_subtract_int(&SCTP_BASE_INFO(ipi_count_vrfs), 1);
240 	}
241 }
242 
243 void
244 sctp_free_ifn(struct sctp_ifn *sctp_ifnp)
245 {
246 	if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&sctp_ifnp->refcount)) {
247 		/* We zero'd the count */
248 		if (sctp_ifnp->vrf) {
249 			sctp_free_vrf(sctp_ifnp->vrf);
250 		}
251 		SCTP_FREE(sctp_ifnp, SCTP_M_IFN);
252 		atomic_subtract_int(&SCTP_BASE_INFO(ipi_count_ifns), 1);
253 	}
254 }
255 
256 void
257 sctp_update_ifn_mtu(uint32_t ifn_index, uint32_t mtu)
258 {
259 	struct sctp_ifn *sctp_ifnp;
260 
261 	sctp_ifnp = sctp_find_ifn((void *)NULL, ifn_index);
262 	if (sctp_ifnp != NULL) {
263 		sctp_ifnp->ifn_mtu = mtu;
264 	}
265 }
266 
267 void
268 sctp_free_ifa(struct sctp_ifa *sctp_ifap)
269 {
270 	if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&sctp_ifap->refcount)) {
271 		/* We zero'd the count */
272 		if (sctp_ifap->ifn_p) {
273 			sctp_free_ifn(sctp_ifap->ifn_p);
274 		}
275 		SCTP_FREE(sctp_ifap, SCTP_M_IFA);
276 		atomic_subtract_int(&SCTP_BASE_INFO(ipi_count_ifas), 1);
277 	}
278 }
279 
280 static void
281 sctp_delete_ifn(struct sctp_ifn *sctp_ifnp, int hold_addr_lock)
282 {
283 	struct sctp_ifn *found;
284 
285 	found = sctp_find_ifn(sctp_ifnp->ifn_p, sctp_ifnp->ifn_index);
286 	if (found == NULL) {
287 		/* Not in the list.. sorry */
288 		return;
289 	}
290 	if (hold_addr_lock == 0) {
291 		SCTP_IPI_ADDR_WLOCK();
292 	} else {
293 		SCTP_IPI_ADDR_WLOCK_ASSERT();
294 	}
295 	LIST_REMOVE(sctp_ifnp, next_bucket);
296 	LIST_REMOVE(sctp_ifnp, next_ifn);
297 	if (hold_addr_lock == 0) {
298 		SCTP_IPI_ADDR_WUNLOCK();
299 	}
300 	/* Take away the reference, and possibly free it */
301 	sctp_free_ifn(sctp_ifnp);
302 }
303 
304 void
305 sctp_mark_ifa_addr_down(uint32_t vrf_id, struct sockaddr *addr,
306     const char *if_name, uint32_t ifn_index)
307 {
308 	struct sctp_vrf *vrf;
309 	struct sctp_ifa *sctp_ifap;
310 
311 	SCTP_IPI_ADDR_RLOCK();
312 	vrf = sctp_find_vrf(vrf_id);
313 	if (vrf == NULL) {
314 		SCTPDBG(SCTP_DEBUG_PCB4, "Can't find vrf_id 0x%x\n", vrf_id);
315 		goto out;
316 	}
317 	sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
318 	if (sctp_ifap == NULL) {
319 		SCTPDBG(SCTP_DEBUG_PCB4, "Can't find sctp_ifap for address\n");
320 		goto out;
321 	}
322 	if (sctp_ifap->ifn_p == NULL) {
323 		SCTPDBG(SCTP_DEBUG_PCB4, "IFA has no IFN - can't mark unusable\n");
324 		goto out;
325 	}
326 	if (if_name) {
327 		if (strncmp(if_name, sctp_ifap->ifn_p->ifn_name, SCTP_IFNAMSIZ) != 0) {
328 			SCTPDBG(SCTP_DEBUG_PCB4, "IFN %s of IFA not the same as %s\n",
329 			    sctp_ifap->ifn_p->ifn_name, if_name);
330 			goto out;
331 		}
332 	} else {
333 		if (sctp_ifap->ifn_p->ifn_index != ifn_index) {
334 			SCTPDBG(SCTP_DEBUG_PCB4, "IFA owned by ifn_index:%d down command for ifn_index:%d - ignored\n",
335 			    sctp_ifap->ifn_p->ifn_index, ifn_index);
336 			goto out;
337 		}
338 	}
339 
340 	sctp_ifap->localifa_flags &= (~SCTP_ADDR_VALID);
341 	sctp_ifap->localifa_flags |= SCTP_ADDR_IFA_UNUSEABLE;
342 out:
343 	SCTP_IPI_ADDR_RUNLOCK();
344 }
345 
346 void
347 sctp_mark_ifa_addr_up(uint32_t vrf_id, struct sockaddr *addr,
348     const char *if_name, uint32_t ifn_index)
349 {
350 	struct sctp_vrf *vrf;
351 	struct sctp_ifa *sctp_ifap;
352 
353 	SCTP_IPI_ADDR_RLOCK();
354 	vrf = sctp_find_vrf(vrf_id);
355 	if (vrf == NULL) {
356 		SCTPDBG(SCTP_DEBUG_PCB4, "Can't find vrf_id 0x%x\n", vrf_id);
357 		goto out;
358 	}
359 	sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
360 	if (sctp_ifap == NULL) {
361 		SCTPDBG(SCTP_DEBUG_PCB4, "Can't find sctp_ifap for address\n");
362 		goto out;
363 	}
364 	if (sctp_ifap->ifn_p == NULL) {
365 		SCTPDBG(SCTP_DEBUG_PCB4, "IFA has no IFN - can't mark unusable\n");
366 		goto out;
367 	}
368 	if (if_name) {
369 		if (strncmp(if_name, sctp_ifap->ifn_p->ifn_name, SCTP_IFNAMSIZ) != 0) {
370 			SCTPDBG(SCTP_DEBUG_PCB4, "IFN %s of IFA not the same as %s\n",
371 			    sctp_ifap->ifn_p->ifn_name, if_name);
372 			goto out;
373 		}
374 	} else {
375 		if (sctp_ifap->ifn_p->ifn_index != ifn_index) {
376 			SCTPDBG(SCTP_DEBUG_PCB4, "IFA owned by ifn_index:%d down command for ifn_index:%d - ignored\n",
377 			    sctp_ifap->ifn_p->ifn_index, ifn_index);
378 			goto out;
379 		}
380 	}
381 
382 	sctp_ifap->localifa_flags &= (~SCTP_ADDR_IFA_UNUSEABLE);
383 	sctp_ifap->localifa_flags |= SCTP_ADDR_VALID;
384 out:
385 	SCTP_IPI_ADDR_RUNLOCK();
386 }
387 
388 /*-
389  * Add an ifa to an ifn.
390  * Register the interface as necessary.
391  * NOTE: ADDR write lock MUST be held.
392  */
393 static void
394 sctp_add_ifa_to_ifn(struct sctp_ifn *sctp_ifnp, struct sctp_ifa *sctp_ifap)
395 {
396 	int ifa_af;
397 
398 	LIST_INSERT_HEAD(&sctp_ifnp->ifalist, sctp_ifap, next_ifa);
399 	sctp_ifap->ifn_p = sctp_ifnp;
400 	atomic_add_int(&sctp_ifap->ifn_p->refcount, 1);
401 	/* update address counts */
402 	sctp_ifnp->ifa_count++;
403 	ifa_af = sctp_ifap->address.sa.sa_family;
404 	switch (ifa_af) {
405 #ifdef INET
406 	case AF_INET:
407 		sctp_ifnp->num_v4++;
408 		break;
409 #endif
410 #ifdef INET6
411 	case AF_INET6:
412 		sctp_ifnp->num_v6++;
413 		break;
414 #endif
415 	default:
416 		break;
417 	}
418 	if (sctp_ifnp->ifa_count == 1) {
419 		/* register the new interface */
420 		sctp_ifnp->registered_af = ifa_af;
421 	}
422 }
423 
424 /*-
425  * Remove an ifa from its ifn.
426  * If no more addresses exist, remove the ifn too. Otherwise, re-register
427  * the interface based on the remaining address families left.
428  * NOTE: ADDR write lock MUST be held.
429  */
430 static void
431 sctp_remove_ifa_from_ifn(struct sctp_ifa *sctp_ifap)
432 {
433 	LIST_REMOVE(sctp_ifap, next_ifa);
434 	if (sctp_ifap->ifn_p) {
435 		/* update address counts */
436 		sctp_ifap->ifn_p->ifa_count--;
437 		switch (sctp_ifap->address.sa.sa_family) {
438 #ifdef INET
439 		case AF_INET:
440 			sctp_ifap->ifn_p->num_v4--;
441 			break;
442 #endif
443 #ifdef INET6
444 		case AF_INET6:
445 			sctp_ifap->ifn_p->num_v6--;
446 			break;
447 #endif
448 		default:
449 			break;
450 		}
451 
452 		if (LIST_EMPTY(&sctp_ifap->ifn_p->ifalist)) {
453 			/* remove the ifn, possibly freeing it */
454 			sctp_delete_ifn(sctp_ifap->ifn_p, SCTP_ADDR_LOCKED);
455 		} else {
456 			/* re-register address family type, if needed */
457 			if ((sctp_ifap->ifn_p->num_v6 == 0) &&
458 			    (sctp_ifap->ifn_p->registered_af == AF_INET6)) {
459 				sctp_ifap->ifn_p->registered_af = AF_INET;
460 			} else if ((sctp_ifap->ifn_p->num_v4 == 0) &&
461 			    (sctp_ifap->ifn_p->registered_af == AF_INET)) {
462 				sctp_ifap->ifn_p->registered_af = AF_INET6;
463 			}
464 			/* free the ifn refcount */
465 			sctp_free_ifn(sctp_ifap->ifn_p);
466 		}
467 		sctp_ifap->ifn_p = NULL;
468 	}
469 }
470 
471 struct sctp_ifa *
472 sctp_add_addr_to_vrf(uint32_t vrf_id, void *ifn, uint32_t ifn_index,
473     uint32_t ifn_type, const char *if_name, void *ifa,
474     struct sockaddr *addr, uint32_t ifa_flags,
475     int dynamic_add)
476 {
477 	struct sctp_vrf *vrf;
478 	struct sctp_ifn *sctp_ifnp, *new_sctp_ifnp;
479 	struct sctp_ifa *sctp_ifap, *new_sctp_ifap;
480 	struct sctp_ifalist *hash_addr_head;
481 	struct sctp_ifnlist *hash_ifn_head;
482 	uint32_t hash_of_addr;
483 	int new_ifn_af = 0;
484 
485 #ifdef SCTP_DEBUG
486 	SCTPDBG(SCTP_DEBUG_PCB4, "vrf_id 0x%x: adding address: ", vrf_id);
487 	SCTPDBG_ADDR(SCTP_DEBUG_PCB4, addr);
488 #endif
489 	SCTP_MALLOC(new_sctp_ifnp, struct sctp_ifn *,
490 	    sizeof(struct sctp_ifn), SCTP_M_IFN);
491 	if (new_sctp_ifnp == NULL) {
492 #ifdef INVARIANTS
493 		panic("No memory for IFN");
494 #endif
495 		return (NULL);
496 	}
497 	SCTP_MALLOC(new_sctp_ifap, struct sctp_ifa *, sizeof(struct sctp_ifa), SCTP_M_IFA);
498 	if (new_sctp_ifap == NULL) {
499 #ifdef INVARIANTS
500 		panic("No memory for IFA");
501 #endif
502 		SCTP_FREE(new_sctp_ifnp, SCTP_M_IFN);
503 		return (NULL);
504 	}
505 
506 	SCTP_IPI_ADDR_WLOCK();
507 	sctp_ifnp = sctp_find_ifn(ifn, ifn_index);
508 	if (sctp_ifnp) {
509 		vrf = sctp_ifnp->vrf;
510 	} else {
511 		vrf = sctp_find_vrf(vrf_id);
512 		if (vrf == NULL) {
513 			vrf = sctp_allocate_vrf(vrf_id);
514 			if (vrf == NULL) {
515 				SCTP_IPI_ADDR_WUNLOCK();
516 				SCTP_FREE(new_sctp_ifnp, SCTP_M_IFN);
517 				SCTP_FREE(new_sctp_ifap, SCTP_M_IFA);
518 				return (NULL);
519 			}
520 		}
521 	}
522 	if (sctp_ifnp == NULL) {
523 		/*
524 		 * build one and add it, can't hold lock until after malloc
525 		 * done though.
526 		 */
527 		sctp_ifnp = new_sctp_ifnp;
528 		new_sctp_ifnp = NULL;
529 		memset(sctp_ifnp, 0, sizeof(struct sctp_ifn));
530 		sctp_ifnp->ifn_index = ifn_index;
531 		sctp_ifnp->ifn_p = ifn;
532 		sctp_ifnp->ifn_type = ifn_type;
533 		sctp_ifnp->refcount = 0;
534 		sctp_ifnp->vrf = vrf;
535 		atomic_add_int(&vrf->refcount, 1);
536 		sctp_ifnp->ifn_mtu = SCTP_GATHER_MTU_FROM_IFN_INFO(ifn, ifn_index);
537 		if (if_name != NULL) {
538 			SCTP_SNPRINTF(sctp_ifnp->ifn_name, SCTP_IFNAMSIZ, "%s", if_name);
539 		} else {
540 			SCTP_SNPRINTF(sctp_ifnp->ifn_name, SCTP_IFNAMSIZ, "%s", "unknown");
541 		}
542 		hash_ifn_head = &SCTP_BASE_INFO(vrf_ifn_hash)[(ifn_index & SCTP_BASE_INFO(vrf_ifn_hashmark))];
543 		LIST_INIT(&sctp_ifnp->ifalist);
544 		LIST_INSERT_HEAD(hash_ifn_head, sctp_ifnp, next_bucket);
545 		LIST_INSERT_HEAD(&vrf->ifnlist, sctp_ifnp, next_ifn);
546 		atomic_add_int(&SCTP_BASE_INFO(ipi_count_ifns), 1);
547 		new_ifn_af = 1;
548 	}
549 	sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
550 	if (sctp_ifap) {
551 		/* Hmm, it already exists? */
552 		if ((sctp_ifap->ifn_p) &&
553 		    (sctp_ifap->ifn_p->ifn_index == ifn_index)) {
554 			SCTPDBG(SCTP_DEBUG_PCB4, "Using existing ifn %s (0x%x) for ifa %p\n",
555 			    sctp_ifap->ifn_p->ifn_name, ifn_index,
556 			    (void *)sctp_ifap);
557 			if (new_ifn_af) {
558 				/* Remove the created one that we don't want */
559 				sctp_delete_ifn(sctp_ifnp, SCTP_ADDR_LOCKED);
560 			}
561 			if (sctp_ifap->localifa_flags & SCTP_BEING_DELETED) {
562 				/* easy to solve, just switch back to active */
563 				SCTPDBG(SCTP_DEBUG_PCB4, "Clearing deleted ifa flag\n");
564 				sctp_ifap->localifa_flags = SCTP_ADDR_VALID;
565 				sctp_ifap->ifn_p = sctp_ifnp;
566 				atomic_add_int(&sctp_ifap->ifn_p->refcount, 1);
567 			}
568 	exit_stage_left:
569 			SCTP_IPI_ADDR_WUNLOCK();
570 			if (new_sctp_ifnp != NULL) {
571 				SCTP_FREE(new_sctp_ifnp, SCTP_M_IFN);
572 			}
573 			SCTP_FREE(new_sctp_ifap, SCTP_M_IFA);
574 			return (sctp_ifap);
575 		} else {
576 			if (sctp_ifap->ifn_p) {
577 				/*
578 				 * The last IFN gets the address, remove the
579 				 * old one
580 				 */
581 				SCTPDBG(SCTP_DEBUG_PCB4, "Moving ifa %p from %s (0x%x) to %s (0x%x)\n",
582 				    (void *)sctp_ifap, sctp_ifap->ifn_p->ifn_name,
583 				    sctp_ifap->ifn_p->ifn_index, if_name,
584 				    ifn_index);
585 				/* remove the address from the old ifn */
586 				sctp_remove_ifa_from_ifn(sctp_ifap);
587 				/* move the address over to the new ifn */
588 				sctp_add_ifa_to_ifn(sctp_ifnp, sctp_ifap);
589 				goto exit_stage_left;
590 			} else {
591 				/* repair ifnp which was NULL ? */
592 				sctp_ifap->localifa_flags = SCTP_ADDR_VALID;
593 				SCTPDBG(SCTP_DEBUG_PCB4, "Repairing ifn %p for ifa %p\n",
594 				    (void *)sctp_ifnp, (void *)sctp_ifap);
595 				sctp_add_ifa_to_ifn(sctp_ifnp, sctp_ifap);
596 			}
597 			goto exit_stage_left;
598 		}
599 	}
600 	sctp_ifap = new_sctp_ifap;
601 	memset(sctp_ifap, 0, sizeof(struct sctp_ifa));
602 	sctp_ifap->ifn_p = sctp_ifnp;
603 	atomic_add_int(&sctp_ifnp->refcount, 1);
604 	sctp_ifap->vrf_id = vrf_id;
605 	sctp_ifap->ifa = ifa;
606 	memcpy(&sctp_ifap->address, addr, addr->sa_len);
607 	sctp_ifap->localifa_flags = SCTP_ADDR_VALID | SCTP_ADDR_DEFER_USE;
608 	sctp_ifap->flags = ifa_flags;
609 	/* Set scope */
610 	switch (sctp_ifap->address.sa.sa_family) {
611 #ifdef INET
612 	case AF_INET:
613 		{
614 			struct sockaddr_in *sin;
615 
616 			sin = &sctp_ifap->address.sin;
617 			if (SCTP_IFN_IS_IFT_LOOP(sctp_ifap->ifn_p) ||
618 			    (IN4_ISLOOPBACK_ADDRESS(&sin->sin_addr))) {
619 				sctp_ifap->src_is_loop = 1;
620 			}
621 			if ((IN4_ISPRIVATE_ADDRESS(&sin->sin_addr))) {
622 				sctp_ifap->src_is_priv = 1;
623 			}
624 			sctp_ifnp->num_v4++;
625 			if (new_ifn_af)
626 				new_ifn_af = AF_INET;
627 			break;
628 		}
629 #endif
630 #ifdef INET6
631 	case AF_INET6:
632 		{
633 			/* ok to use deprecated addresses? */
634 			struct sockaddr_in6 *sin6;
635 
636 			sin6 = &sctp_ifap->address.sin6;
637 			if (SCTP_IFN_IS_IFT_LOOP(sctp_ifap->ifn_p) ||
638 			    (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))) {
639 				sctp_ifap->src_is_loop = 1;
640 			}
641 			if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
642 				sctp_ifap->src_is_priv = 1;
643 			}
644 			sctp_ifnp->num_v6++;
645 			if (new_ifn_af)
646 				new_ifn_af = AF_INET6;
647 			break;
648 		}
649 #endif
650 	default:
651 		new_ifn_af = 0;
652 		break;
653 	}
654 	hash_of_addr = sctp_get_ifa_hash_val(&sctp_ifap->address.sa);
655 
656 	if ((sctp_ifap->src_is_priv == 0) &&
657 	    (sctp_ifap->src_is_loop == 0)) {
658 		sctp_ifap->src_is_glob = 1;
659 	}
660 	hash_addr_head = &vrf->vrf_addr_hash[(hash_of_addr & vrf->vrf_addr_hashmark)];
661 	LIST_INSERT_HEAD(hash_addr_head, sctp_ifap, next_bucket);
662 	sctp_ifap->refcount = 1;
663 	LIST_INSERT_HEAD(&sctp_ifnp->ifalist, sctp_ifap, next_ifa);
664 	sctp_ifnp->ifa_count++;
665 	vrf->total_ifa_count++;
666 	atomic_add_int(&SCTP_BASE_INFO(ipi_count_ifas), 1);
667 	if (new_ifn_af) {
668 		sctp_ifnp->registered_af = new_ifn_af;
669 	}
670 	SCTP_IPI_ADDR_WUNLOCK();
671 	if (new_sctp_ifnp != NULL) {
672 		SCTP_FREE(new_sctp_ifnp, SCTP_M_IFN);
673 	}
674 
675 	if (dynamic_add) {
676 		/*
677 		 * Bump up the refcount so that when the timer completes it
678 		 * will drop back down.
679 		 */
680 		struct sctp_laddr *wi;
681 
682 		atomic_add_int(&sctp_ifap->refcount, 1);
683 		wi = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
684 		if (wi == NULL) {
685 			/*
686 			 * Gak, what can we do? We have lost an address
687 			 * change can you say HOSED?
688 			 */
689 			SCTPDBG(SCTP_DEBUG_PCB4, "Lost an address change?\n");
690 			/* Opps, must decrement the count */
691 			sctp_del_addr_from_vrf(vrf_id, addr, ifn_index,
692 			    if_name);
693 			return (NULL);
694 		}
695 		SCTP_INCR_LADDR_COUNT();
696 		memset(wi, 0, sizeof(*wi));
697 		(void)SCTP_GETTIME_TIMEVAL(&wi->start_time);
698 		wi->ifa = sctp_ifap;
699 		wi->action = SCTP_ADD_IP_ADDRESS;
700 
701 		SCTP_WQ_ADDR_LOCK();
702 		LIST_INSERT_HEAD(&SCTP_BASE_INFO(addr_wq), wi, sctp_nxt_addr);
703 		sctp_timer_start(SCTP_TIMER_TYPE_ADDR_WQ,
704 		    (struct sctp_inpcb *)NULL,
705 		    (struct sctp_tcb *)NULL,
706 		    (struct sctp_nets *)NULL);
707 		SCTP_WQ_ADDR_UNLOCK();
708 	} else {
709 		/* it's ready for use */
710 		sctp_ifap->localifa_flags &= ~SCTP_ADDR_DEFER_USE;
711 	}
712 	return (sctp_ifap);
713 }
714 
715 void
716 sctp_del_addr_from_vrf(uint32_t vrf_id, struct sockaddr *addr,
717     uint32_t ifn_index, const char *if_name)
718 {
719 	struct sctp_vrf *vrf;
720 	struct sctp_ifa *sctp_ifap = NULL;
721 
722 	SCTP_IPI_ADDR_WLOCK();
723 	vrf = sctp_find_vrf(vrf_id);
724 	if (vrf == NULL) {
725 		SCTPDBG(SCTP_DEBUG_PCB4, "Can't find vrf_id 0x%x\n", vrf_id);
726 		goto out_now;
727 	}
728 
729 #ifdef SCTP_DEBUG
730 	SCTPDBG(SCTP_DEBUG_PCB4, "vrf_id 0x%x: deleting address:", vrf_id);
731 	SCTPDBG_ADDR(SCTP_DEBUG_PCB4, addr);
732 #endif
733 	sctp_ifap = sctp_find_ifa_by_addr(addr, vrf->vrf_id, SCTP_ADDR_LOCKED);
734 	if (sctp_ifap) {
735 		/* Validate the delete */
736 		if (sctp_ifap->ifn_p) {
737 			int valid = 0;
738 
739 			/*-
740 			 * The name has priority over the ifn_index
741 			 * if its given.
742 			 */
743 			if (if_name) {
744 				if (strncmp(if_name, sctp_ifap->ifn_p->ifn_name, SCTP_IFNAMSIZ) == 0) {
745 					/* They match its a correct delete */
746 					valid = 1;
747 				}
748 			}
749 			if (!valid) {
750 				/* last ditch check ifn_index */
751 				if (ifn_index == sctp_ifap->ifn_p->ifn_index) {
752 					valid = 1;
753 				}
754 			}
755 			if (!valid) {
756 				SCTPDBG(SCTP_DEBUG_PCB4, "ifn:%d ifname:%s does not match addresses\n",
757 				    ifn_index, ((if_name == NULL) ? "NULL" : if_name));
758 				SCTPDBG(SCTP_DEBUG_PCB4, "ifn:%d ifname:%s - ignoring delete\n",
759 				    sctp_ifap->ifn_p->ifn_index, sctp_ifap->ifn_p->ifn_name);
760 				SCTP_IPI_ADDR_WUNLOCK();
761 				return;
762 			}
763 		}
764 		SCTPDBG(SCTP_DEBUG_PCB4, "Deleting ifa %p\n", (void *)sctp_ifap);
765 		sctp_ifap->localifa_flags &= SCTP_ADDR_VALID;
766 		/*
767 		 * We don't set the flag. This means that the structure will
768 		 * hang around in EP's that have bound specific to it until
769 		 * they close. This gives us TCP like behavior if someone
770 		 * removes an address (or for that matter adds it right
771 		 * back).
772 		 */
773 		/* sctp_ifap->localifa_flags |= SCTP_BEING_DELETED; */
774 		vrf->total_ifa_count--;
775 		LIST_REMOVE(sctp_ifap, next_bucket);
776 		sctp_remove_ifa_from_ifn(sctp_ifap);
777 	}
778 #ifdef SCTP_DEBUG
779 	else {
780 		SCTPDBG(SCTP_DEBUG_PCB4, "Del Addr-ifn:%d Could not find address:",
781 		    ifn_index);
782 		SCTPDBG_ADDR(SCTP_DEBUG_PCB1, addr);
783 	}
784 #endif
785 
786 out_now:
787 	SCTP_IPI_ADDR_WUNLOCK();
788 	if (sctp_ifap) {
789 		struct sctp_laddr *wi;
790 
791 		wi = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
792 		if (wi == NULL) {
793 			/*
794 			 * Gak, what can we do? We have lost an address
795 			 * change can you say HOSED?
796 			 */
797 			SCTPDBG(SCTP_DEBUG_PCB4, "Lost an address change?\n");
798 
799 			/* Oops, must decrement the count */
800 			sctp_free_ifa(sctp_ifap);
801 			return;
802 		}
803 		SCTP_INCR_LADDR_COUNT();
804 		memset(wi, 0, sizeof(*wi));
805 		(void)SCTP_GETTIME_TIMEVAL(&wi->start_time);
806 		wi->ifa = sctp_ifap;
807 		wi->action = SCTP_DEL_IP_ADDRESS;
808 		SCTP_WQ_ADDR_LOCK();
809 		/*
810 		 * Should this really be a tailq? As it is we will process
811 		 * the newest first :-0
812 		 */
813 		LIST_INSERT_HEAD(&SCTP_BASE_INFO(addr_wq), wi, sctp_nxt_addr);
814 		sctp_timer_start(SCTP_TIMER_TYPE_ADDR_WQ,
815 		    (struct sctp_inpcb *)NULL,
816 		    (struct sctp_tcb *)NULL,
817 		    (struct sctp_nets *)NULL);
818 		SCTP_WQ_ADDR_UNLOCK();
819 	}
820 	return;
821 }
822 
823 static int
824 sctp_does_stcb_own_this_addr(struct sctp_tcb *stcb, struct sockaddr *to)
825 {
826 	int loopback_scope;
827 #if defined(INET)
828 	int ipv4_local_scope, ipv4_addr_legal;
829 #endif
830 #if defined(INET6)
831 	int local_scope, site_scope, ipv6_addr_legal;
832 #endif
833 	struct sctp_vrf *vrf;
834 	struct sctp_ifn *sctp_ifn;
835 	struct sctp_ifa *sctp_ifa;
836 
837 	loopback_scope = stcb->asoc.scope.loopback_scope;
838 #if defined(INET)
839 	ipv4_local_scope = stcb->asoc.scope.ipv4_local_scope;
840 	ipv4_addr_legal = stcb->asoc.scope.ipv4_addr_legal;
841 #endif
842 #if defined(INET6)
843 	local_scope = stcb->asoc.scope.local_scope;
844 	site_scope = stcb->asoc.scope.site_scope;
845 	ipv6_addr_legal = stcb->asoc.scope.ipv6_addr_legal;
846 #endif
847 
848 	SCTP_IPI_ADDR_RLOCK();
849 	vrf = sctp_find_vrf(stcb->asoc.vrf_id);
850 	if (vrf == NULL) {
851 		/* no vrf, no addresses */
852 		SCTP_IPI_ADDR_RUNLOCK();
853 		return (0);
854 	}
855 
856 	if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
857 		LIST_FOREACH(sctp_ifn, &vrf->ifnlist, next_ifn) {
858 			if ((loopback_scope == 0) &&
859 			    SCTP_IFN_IS_IFT_LOOP(sctp_ifn)) {
860 				continue;
861 			}
862 			LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
863 				if (sctp_is_addr_restricted(stcb, sctp_ifa) &&
864 				    (!sctp_is_addr_pending(stcb, sctp_ifa))) {
865 					/*
866 					 * We allow pending addresses, where
867 					 * we have sent an asconf-add to be
868 					 * considered valid.
869 					 */
870 					continue;
871 				}
872 				if (sctp_ifa->address.sa.sa_family != to->sa_family) {
873 					continue;
874 				}
875 				switch (sctp_ifa->address.sa.sa_family) {
876 #ifdef INET
877 				case AF_INET:
878 					if (ipv4_addr_legal) {
879 						struct sockaddr_in *sin,
880 						           *rsin;
881 
882 						sin = &sctp_ifa->address.sin;
883 						rsin = (struct sockaddr_in *)to;
884 						if ((ipv4_local_scope == 0) &&
885 						    IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) {
886 							continue;
887 						}
888 						if (prison_check_ip4(stcb->sctp_ep->ip_inp.inp.inp_cred,
889 						    &sin->sin_addr) != 0) {
890 							continue;
891 						}
892 						if (sin->sin_addr.s_addr == rsin->sin_addr.s_addr) {
893 							SCTP_IPI_ADDR_RUNLOCK();
894 							return (1);
895 						}
896 					}
897 					break;
898 #endif
899 #ifdef INET6
900 				case AF_INET6:
901 					if (ipv6_addr_legal) {
902 						struct sockaddr_in6 *sin6,
903 						            *rsin6;
904 
905 						sin6 = &sctp_ifa->address.sin6;
906 						rsin6 = (struct sockaddr_in6 *)to;
907 						if (prison_check_ip6(stcb->sctp_ep->ip_inp.inp.inp_cred,
908 						    &sin6->sin6_addr) != 0) {
909 							continue;
910 						}
911 						if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
912 							if (local_scope == 0)
913 								continue;
914 							if (sin6->sin6_scope_id == 0) {
915 								if (sa6_recoverscope(sin6) != 0)
916 									continue;
917 							}
918 						}
919 						if ((site_scope == 0) &&
920 						    (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr))) {
921 							continue;
922 						}
923 						if (SCTP6_ARE_ADDR_EQUAL(sin6, rsin6)) {
924 							SCTP_IPI_ADDR_RUNLOCK();
925 							return (1);
926 						}
927 					}
928 					break;
929 #endif
930 				default:
931 					/* TSNH */
932 					break;
933 				}
934 			}
935 		}
936 	} else {
937 		struct sctp_laddr *laddr;
938 
939 		LIST_FOREACH(laddr, &stcb->sctp_ep->sctp_addr_list, sctp_nxt_addr) {
940 			if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
941 				SCTPDBG(SCTP_DEBUG_PCB1, "ifa being deleted\n");
942 				continue;
943 			}
944 			if (sctp_is_addr_restricted(stcb, laddr->ifa) &&
945 			    (!sctp_is_addr_pending(stcb, laddr->ifa))) {
946 				/*
947 				 * We allow pending addresses, where we have
948 				 * sent an asconf-add to be considered
949 				 * valid.
950 				 */
951 				continue;
952 			}
953 			if (laddr->ifa->address.sa.sa_family != to->sa_family) {
954 				continue;
955 			}
956 			switch (to->sa_family) {
957 #ifdef INET
958 			case AF_INET:
959 				{
960 					struct sockaddr_in *sin, *rsin;
961 
962 					sin = &laddr->ifa->address.sin;
963 					rsin = (struct sockaddr_in *)to;
964 					if (sin->sin_addr.s_addr == rsin->sin_addr.s_addr) {
965 						SCTP_IPI_ADDR_RUNLOCK();
966 						return (1);
967 					}
968 					break;
969 				}
970 #endif
971 #ifdef INET6
972 			case AF_INET6:
973 				{
974 					struct sockaddr_in6 *sin6, *rsin6;
975 
976 					sin6 = &laddr->ifa->address.sin6;
977 					rsin6 = (struct sockaddr_in6 *)to;
978 					if (SCTP6_ARE_ADDR_EQUAL(sin6, rsin6)) {
979 						SCTP_IPI_ADDR_RUNLOCK();
980 						return (1);
981 					}
982 					break;
983 				}
984 
985 #endif
986 			default:
987 				/* TSNH */
988 				break;
989 			}
990 		}
991 	}
992 	SCTP_IPI_ADDR_RUNLOCK();
993 	return (0);
994 }
995 
996 static struct sctp_tcb *
997 sctp_tcb_special_locate(struct sctp_inpcb **inp_p, struct sockaddr *from,
998     struct sockaddr *to, struct sctp_nets **netp, uint32_t vrf_id)
999 {
1000 	/**** ASSUMES THE CALLER holds the INP_INFO_RLOCK */
1001 	/*
1002 	 * If we support the TCP model, then we must now dig through to see
1003 	 * if we can find our endpoint in the list of tcp ep's.
1004 	 */
1005 	uint16_t lport, rport;
1006 	struct sctppcbhead *ephead;
1007 	struct sctp_inpcb *inp;
1008 	struct sctp_laddr *laddr;
1009 	struct sctp_tcb *stcb;
1010 	struct sctp_nets *net;
1011 
1012 	if ((to == NULL) || (from == NULL)) {
1013 		return (NULL);
1014 	}
1015 
1016 	switch (to->sa_family) {
1017 #ifdef INET
1018 	case AF_INET:
1019 		if (from->sa_family == AF_INET) {
1020 			lport = ((struct sockaddr_in *)to)->sin_port;
1021 			rport = ((struct sockaddr_in *)from)->sin_port;
1022 		} else {
1023 			return (NULL);
1024 		}
1025 		break;
1026 #endif
1027 #ifdef INET6
1028 	case AF_INET6:
1029 		if (from->sa_family == AF_INET6) {
1030 			lport = ((struct sockaddr_in6 *)to)->sin6_port;
1031 			rport = ((struct sockaddr_in6 *)from)->sin6_port;
1032 		} else {
1033 			return (NULL);
1034 		}
1035 		break;
1036 #endif
1037 	default:
1038 		return (NULL);
1039 	}
1040 	ephead = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR((lport | rport), SCTP_BASE_INFO(hashtcpmark))];
1041 	/*
1042 	 * Ok now for each of the guys in this bucket we must look and see:
1043 	 * - Does the remote port match. - Does there single association's
1044 	 * addresses match this address (to). If so we update p_ep to point
1045 	 * to this ep and return the tcb from it.
1046 	 */
1047 	LIST_FOREACH(inp, ephead, sctp_hash) {
1048 		SCTP_INP_RLOCK(inp);
1049 		if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
1050 			SCTP_INP_RUNLOCK(inp);
1051 			continue;
1052 		}
1053 		if (lport != inp->sctp_lport) {
1054 			SCTP_INP_RUNLOCK(inp);
1055 			continue;
1056 		}
1057 		switch (to->sa_family) {
1058 #ifdef INET
1059 		case AF_INET:
1060 			{
1061 				struct sockaddr_in *sin;
1062 
1063 				sin = (struct sockaddr_in *)to;
1064 				if (prison_check_ip4(inp->ip_inp.inp.inp_cred,
1065 				    &sin->sin_addr) != 0) {
1066 					SCTP_INP_RUNLOCK(inp);
1067 					continue;
1068 				}
1069 				break;
1070 			}
1071 #endif
1072 #ifdef INET6
1073 		case AF_INET6:
1074 			{
1075 				struct sockaddr_in6 *sin6;
1076 
1077 				sin6 = (struct sockaddr_in6 *)to;
1078 				if (prison_check_ip6(inp->ip_inp.inp.inp_cred,
1079 				    &sin6->sin6_addr) != 0) {
1080 					SCTP_INP_RUNLOCK(inp);
1081 					continue;
1082 				}
1083 				break;
1084 			}
1085 #endif
1086 		default:
1087 			SCTP_INP_RUNLOCK(inp);
1088 			continue;
1089 		}
1090 		if (inp->def_vrf_id != vrf_id) {
1091 			SCTP_INP_RUNLOCK(inp);
1092 			continue;
1093 		}
1094 		/* check to see if the ep has one of the addresses */
1095 		if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) {
1096 			/* We are NOT bound all, so look further */
1097 			int match = 0;
1098 
1099 			LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
1100 				if (laddr->ifa == NULL) {
1101 					SCTPDBG(SCTP_DEBUG_PCB1, "%s: NULL ifa\n", __func__);
1102 					continue;
1103 				}
1104 				if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
1105 					SCTPDBG(SCTP_DEBUG_PCB1, "ifa being deleted\n");
1106 					continue;
1107 				}
1108 				if (laddr->ifa->address.sa.sa_family ==
1109 				    to->sa_family) {
1110 					/* see if it matches */
1111 #ifdef INET
1112 					if (from->sa_family == AF_INET) {
1113 						struct sockaddr_in *intf_addr,
1114 						           *sin;
1115 
1116 						intf_addr = &laddr->ifa->address.sin;
1117 						sin = (struct sockaddr_in *)to;
1118 						if (sin->sin_addr.s_addr ==
1119 						    intf_addr->sin_addr.s_addr) {
1120 							match = 1;
1121 							break;
1122 						}
1123 					}
1124 #endif
1125 #ifdef INET6
1126 					if (from->sa_family == AF_INET6) {
1127 						struct sockaddr_in6 *intf_addr6;
1128 						struct sockaddr_in6 *sin6;
1129 
1130 						sin6 = (struct sockaddr_in6 *)
1131 						    to;
1132 						intf_addr6 = &laddr->ifa->address.sin6;
1133 
1134 						if (SCTP6_ARE_ADDR_EQUAL(sin6,
1135 						    intf_addr6)) {
1136 							match = 1;
1137 							break;
1138 						}
1139 					}
1140 #endif
1141 				}
1142 			}
1143 			if (match == 0) {
1144 				/* This endpoint does not have this address */
1145 				SCTP_INP_RUNLOCK(inp);
1146 				continue;
1147 			}
1148 		}
1149 		/*
1150 		 * Ok if we hit here the ep has the address, does it hold
1151 		 * the tcb?
1152 		 */
1153 		/* XXX: Why don't we TAILQ_FOREACH through sctp_asoc_list? */
1154 		stcb = LIST_FIRST(&inp->sctp_asoc_list);
1155 		if (stcb == NULL) {
1156 			SCTP_INP_RUNLOCK(inp);
1157 			continue;
1158 		}
1159 		SCTP_TCB_LOCK(stcb);
1160 		if (!sctp_does_stcb_own_this_addr(stcb, to)) {
1161 			SCTP_TCB_UNLOCK(stcb);
1162 			SCTP_INP_RUNLOCK(inp);
1163 			continue;
1164 		}
1165 		if (stcb->rport != rport) {
1166 			/* remote port does not match. */
1167 			SCTP_TCB_UNLOCK(stcb);
1168 			SCTP_INP_RUNLOCK(inp);
1169 			continue;
1170 		}
1171 		if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
1172 			SCTP_TCB_UNLOCK(stcb);
1173 			SCTP_INP_RUNLOCK(inp);
1174 			continue;
1175 		}
1176 		if (!sctp_does_stcb_own_this_addr(stcb, to)) {
1177 			SCTP_TCB_UNLOCK(stcb);
1178 			SCTP_INP_RUNLOCK(inp);
1179 			continue;
1180 		}
1181 		/* Does this TCB have a matching address? */
1182 		TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
1183 			if (net->ro._l_addr.sa.sa_family != from->sa_family) {
1184 				/* not the same family, can't be a match */
1185 				continue;
1186 			}
1187 			switch (from->sa_family) {
1188 #ifdef INET
1189 			case AF_INET:
1190 				{
1191 					struct sockaddr_in *sin, *rsin;
1192 
1193 					sin = (struct sockaddr_in *)&net->ro._l_addr;
1194 					rsin = (struct sockaddr_in *)from;
1195 					if (sin->sin_addr.s_addr ==
1196 					    rsin->sin_addr.s_addr) {
1197 						/* found it */
1198 						if (netp != NULL) {
1199 							*netp = net;
1200 						}
1201 						/*
1202 						 * Update the endpoint
1203 						 * pointer
1204 						 */
1205 						*inp_p = inp;
1206 						SCTP_INP_RUNLOCK(inp);
1207 						return (stcb);
1208 					}
1209 					break;
1210 				}
1211 #endif
1212 #ifdef INET6
1213 			case AF_INET6:
1214 				{
1215 					struct sockaddr_in6 *sin6, *rsin6;
1216 
1217 					sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
1218 					rsin6 = (struct sockaddr_in6 *)from;
1219 					if (SCTP6_ARE_ADDR_EQUAL(sin6,
1220 					    rsin6)) {
1221 						/* found it */
1222 						if (netp != NULL) {
1223 							*netp = net;
1224 						}
1225 						/*
1226 						 * Update the endpoint
1227 						 * pointer
1228 						 */
1229 						*inp_p = inp;
1230 						SCTP_INP_RUNLOCK(inp);
1231 						return (stcb);
1232 					}
1233 					break;
1234 				}
1235 #endif
1236 			default:
1237 				/* TSNH */
1238 				break;
1239 			}
1240 		}
1241 		SCTP_TCB_UNLOCK(stcb);
1242 		SCTP_INP_RUNLOCK(inp);
1243 	}
1244 	return (NULL);
1245 }
1246 
1247 /*
1248  * rules for use
1249  *
1250  * 1) If I return a NULL you must decrement any INP ref cnt. 2) If I find an
1251  * stcb, both will be locked (locked_tcb and stcb) but decrement will be done
1252  * (if locked == NULL). 3) Decrement happens on return ONLY if locked ==
1253  * NULL.
1254  */
1255 
1256 struct sctp_tcb *
1257 sctp_findassociation_ep_addr(struct sctp_inpcb **inp_p, struct sockaddr *remote,
1258     struct sctp_nets **netp, struct sockaddr *local, struct sctp_tcb *locked_tcb)
1259 {
1260 	struct sctpasochead *head;
1261 	struct sctp_inpcb *inp;
1262 	struct sctp_tcb *stcb = NULL;
1263 	struct sctp_nets *net;
1264 	uint16_t rport;
1265 
1266 	inp = *inp_p;
1267 	switch (remote->sa_family) {
1268 #ifdef INET
1269 	case AF_INET:
1270 		rport = (((struct sockaddr_in *)remote)->sin_port);
1271 		break;
1272 #endif
1273 #ifdef INET6
1274 	case AF_INET6:
1275 		rport = (((struct sockaddr_in6 *)remote)->sin6_port);
1276 		break;
1277 #endif
1278 	default:
1279 		return (NULL);
1280 	}
1281 	if (locked_tcb) {
1282 		/*
1283 		 * UN-lock so we can do proper locking here this occurs when
1284 		 * called from load_addresses_from_init.
1285 		 */
1286 		atomic_add_int(&locked_tcb->asoc.refcnt, 1);
1287 		SCTP_TCB_UNLOCK(locked_tcb);
1288 	}
1289 	SCTP_INP_INFO_RLOCK();
1290 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
1291 	    (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
1292 		/*-
1293 		 * Now either this guy is our listener or it's the
1294 		 * connector. If it is the one that issued the connect, then
1295 		 * it's only chance is to be the first TCB in the list. If
1296 		 * it is the acceptor, then do the special_lookup to hash
1297 		 * and find the real inp.
1298 		 */
1299 		if ((inp->sctp_socket) && SCTP_IS_LISTENING(inp)) {
1300 			/* to is peer addr, from is my addr */
1301 			stcb = sctp_tcb_special_locate(inp_p, remote, local,
1302 			    netp, inp->def_vrf_id);
1303 			if ((stcb != NULL) && (locked_tcb == NULL)) {
1304 				/* we have a locked tcb, lower refcount */
1305 				SCTP_INP_DECR_REF(inp);
1306 			}
1307 			if ((locked_tcb != NULL) && (locked_tcb != stcb)) {
1308 				SCTP_INP_RLOCK(locked_tcb->sctp_ep);
1309 				SCTP_TCB_LOCK(locked_tcb);
1310 				atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
1311 				SCTP_INP_RUNLOCK(locked_tcb->sctp_ep);
1312 			}
1313 			SCTP_INP_INFO_RUNLOCK();
1314 			return (stcb);
1315 		} else {
1316 			SCTP_INP_WLOCK(inp);
1317 			if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
1318 				goto null_return;
1319 			}
1320 			stcb = LIST_FIRST(&inp->sctp_asoc_list);
1321 			if (stcb == NULL) {
1322 				goto null_return;
1323 			}
1324 			SCTP_TCB_LOCK(stcb);
1325 
1326 			if (stcb->rport != rport) {
1327 				/* remote port does not match. */
1328 				SCTP_TCB_UNLOCK(stcb);
1329 				goto null_return;
1330 			}
1331 			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
1332 				SCTP_TCB_UNLOCK(stcb);
1333 				goto null_return;
1334 			}
1335 			if (local && !sctp_does_stcb_own_this_addr(stcb, local)) {
1336 				SCTP_TCB_UNLOCK(stcb);
1337 				goto null_return;
1338 			}
1339 			/* now look at the list of remote addresses */
1340 			TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
1341 #ifdef INVARIANTS
1342 				if (net == (TAILQ_NEXT(net, sctp_next))) {
1343 					panic("Corrupt net list");
1344 				}
1345 #endif
1346 				if (net->ro._l_addr.sa.sa_family !=
1347 				    remote->sa_family) {
1348 					/* not the same family */
1349 					continue;
1350 				}
1351 				switch (remote->sa_family) {
1352 #ifdef INET
1353 				case AF_INET:
1354 					{
1355 						struct sockaddr_in *sin,
1356 						           *rsin;
1357 
1358 						sin = (struct sockaddr_in *)
1359 						    &net->ro._l_addr;
1360 						rsin = (struct sockaddr_in *)remote;
1361 						if (sin->sin_addr.s_addr ==
1362 						    rsin->sin_addr.s_addr) {
1363 							/* found it */
1364 							if (netp != NULL) {
1365 								*netp = net;
1366 							}
1367 							if (locked_tcb == NULL) {
1368 								SCTP_INP_DECR_REF(inp);
1369 							} else if (locked_tcb != stcb) {
1370 								SCTP_TCB_LOCK(locked_tcb);
1371 							}
1372 							if (locked_tcb) {
1373 								atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
1374 							}
1375 
1376 							SCTP_INP_WUNLOCK(inp);
1377 							SCTP_INP_INFO_RUNLOCK();
1378 							return (stcb);
1379 						}
1380 						break;
1381 					}
1382 #endif
1383 #ifdef INET6
1384 				case AF_INET6:
1385 					{
1386 						struct sockaddr_in6 *sin6,
1387 						            *rsin6;
1388 
1389 						sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
1390 						rsin6 = (struct sockaddr_in6 *)remote;
1391 						if (SCTP6_ARE_ADDR_EQUAL(sin6,
1392 						    rsin6)) {
1393 							/* found it */
1394 							if (netp != NULL) {
1395 								*netp = net;
1396 							}
1397 							if (locked_tcb == NULL) {
1398 								SCTP_INP_DECR_REF(inp);
1399 							} else if (locked_tcb != stcb) {
1400 								SCTP_TCB_LOCK(locked_tcb);
1401 							}
1402 							if (locked_tcb) {
1403 								atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
1404 							}
1405 							SCTP_INP_WUNLOCK(inp);
1406 							SCTP_INP_INFO_RUNLOCK();
1407 							return (stcb);
1408 						}
1409 						break;
1410 					}
1411 #endif
1412 				default:
1413 					/* TSNH */
1414 					break;
1415 				}
1416 			}
1417 			SCTP_TCB_UNLOCK(stcb);
1418 		}
1419 	} else {
1420 		SCTP_INP_WLOCK(inp);
1421 		if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
1422 			goto null_return;
1423 		}
1424 		head = &inp->sctp_tcbhash[SCTP_PCBHASH_ALLADDR(rport,
1425 		    inp->sctp_hashmark)];
1426 		LIST_FOREACH(stcb, head, sctp_tcbhash) {
1427 			if (stcb->rport != rport) {
1428 				/* remote port does not match */
1429 				continue;
1430 			}
1431 			SCTP_TCB_LOCK(stcb);
1432 			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
1433 				SCTP_TCB_UNLOCK(stcb);
1434 				continue;
1435 			}
1436 			if (local && !sctp_does_stcb_own_this_addr(stcb, local)) {
1437 				SCTP_TCB_UNLOCK(stcb);
1438 				continue;
1439 			}
1440 			/* now look at the list of remote addresses */
1441 			TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
1442 #ifdef INVARIANTS
1443 				if (net == (TAILQ_NEXT(net, sctp_next))) {
1444 					panic("Corrupt net list");
1445 				}
1446 #endif
1447 				if (net->ro._l_addr.sa.sa_family !=
1448 				    remote->sa_family) {
1449 					/* not the same family */
1450 					continue;
1451 				}
1452 				switch (remote->sa_family) {
1453 #ifdef INET
1454 				case AF_INET:
1455 					{
1456 						struct sockaddr_in *sin,
1457 						           *rsin;
1458 
1459 						sin = (struct sockaddr_in *)
1460 						    &net->ro._l_addr;
1461 						rsin = (struct sockaddr_in *)remote;
1462 						if (sin->sin_addr.s_addr ==
1463 						    rsin->sin_addr.s_addr) {
1464 							/* found it */
1465 							if (netp != NULL) {
1466 								*netp = net;
1467 							}
1468 							if (locked_tcb == NULL) {
1469 								SCTP_INP_DECR_REF(inp);
1470 							} else if (locked_tcb != stcb) {
1471 								SCTP_TCB_LOCK(locked_tcb);
1472 							}
1473 							if (locked_tcb) {
1474 								atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
1475 							}
1476 							SCTP_INP_WUNLOCK(inp);
1477 							SCTP_INP_INFO_RUNLOCK();
1478 							return (stcb);
1479 						}
1480 						break;
1481 					}
1482 #endif
1483 #ifdef INET6
1484 				case AF_INET6:
1485 					{
1486 						struct sockaddr_in6 *sin6,
1487 						            *rsin6;
1488 
1489 						sin6 = (struct sockaddr_in6 *)
1490 						    &net->ro._l_addr;
1491 						rsin6 = (struct sockaddr_in6 *)remote;
1492 						if (SCTP6_ARE_ADDR_EQUAL(sin6,
1493 						    rsin6)) {
1494 							/* found it */
1495 							if (netp != NULL) {
1496 								*netp = net;
1497 							}
1498 							if (locked_tcb == NULL) {
1499 								SCTP_INP_DECR_REF(inp);
1500 							} else if (locked_tcb != stcb) {
1501 								SCTP_TCB_LOCK(locked_tcb);
1502 							}
1503 							if (locked_tcb) {
1504 								atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
1505 							}
1506 							SCTP_INP_WUNLOCK(inp);
1507 							SCTP_INP_INFO_RUNLOCK();
1508 							return (stcb);
1509 						}
1510 						break;
1511 					}
1512 #endif
1513 				default:
1514 					/* TSNH */
1515 					break;
1516 				}
1517 			}
1518 			SCTP_TCB_UNLOCK(stcb);
1519 		}
1520 	}
1521 null_return:
1522 	/* clean up for returning null */
1523 	if (locked_tcb) {
1524 		SCTP_TCB_LOCK(locked_tcb);
1525 		atomic_subtract_int(&locked_tcb->asoc.refcnt, 1);
1526 	}
1527 	SCTP_INP_WUNLOCK(inp);
1528 	SCTP_INP_INFO_RUNLOCK();
1529 	/* not found */
1530 	return (NULL);
1531 }
1532 
1533 /*
1534  * Find an association for a specific endpoint using the association id given
1535  * out in the COMM_UP notification
1536  */
1537 struct sctp_tcb *
1538 sctp_findasoc_ep_asocid_locked(struct sctp_inpcb *inp, sctp_assoc_t asoc_id, int want_lock)
1539 {
1540 	/*
1541 	 * Use my the assoc_id to find a endpoint
1542 	 */
1543 	struct sctpasochead *head;
1544 	struct sctp_tcb *stcb;
1545 	uint32_t id;
1546 
1547 	if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
1548 		SCTP_PRINTF("TSNH ep_associd0\n");
1549 		return (NULL);
1550 	}
1551 	id = (uint32_t)asoc_id;
1552 	head = &inp->sctp_asocidhash[SCTP_PCBHASH_ASOC(id, inp->hashasocidmark)];
1553 	if (head == NULL) {
1554 		/* invalid id TSNH */
1555 		SCTP_PRINTF("TSNH ep_associd1\n");
1556 		return (NULL);
1557 	}
1558 	LIST_FOREACH(stcb, head, sctp_tcbasocidhash) {
1559 		if (stcb->asoc.assoc_id == id) {
1560 			if (inp != stcb->sctp_ep) {
1561 				/*
1562 				 * some other guy has the same id active (id
1563 				 * collision ??).
1564 				 */
1565 				SCTP_PRINTF("TSNH ep_associd2\n");
1566 				continue;
1567 			}
1568 			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
1569 				continue;
1570 			}
1571 			if (want_lock) {
1572 				SCTP_TCB_LOCK(stcb);
1573 			}
1574 			return (stcb);
1575 		}
1576 	}
1577 	return (NULL);
1578 }
1579 
1580 struct sctp_tcb *
1581 sctp_findassociation_ep_asocid(struct sctp_inpcb *inp, sctp_assoc_t asoc_id, int want_lock)
1582 {
1583 	struct sctp_tcb *stcb;
1584 
1585 	SCTP_INP_RLOCK(inp);
1586 	stcb = sctp_findasoc_ep_asocid_locked(inp, asoc_id, want_lock);
1587 	SCTP_INP_RUNLOCK(inp);
1588 	return (stcb);
1589 }
1590 
1591 /*
1592  * Endpoint probe expects that the INP_INFO is locked.
1593  */
1594 static struct sctp_inpcb *
1595 sctp_endpoint_probe(struct sockaddr *nam, struct sctppcbhead *head,
1596     uint16_t lport, uint32_t vrf_id)
1597 {
1598 	struct sctp_inpcb *inp;
1599 	struct sctp_laddr *laddr;
1600 #ifdef INET
1601 	struct sockaddr_in *sin;
1602 #endif
1603 #ifdef INET6
1604 	struct sockaddr_in6 *sin6;
1605 	struct sockaddr_in6 *intf_addr6;
1606 #endif
1607 	int fnd;
1608 
1609 #ifdef INET
1610 	sin = NULL;
1611 #endif
1612 #ifdef INET6
1613 	sin6 = NULL;
1614 #endif
1615 	switch (nam->sa_family) {
1616 #ifdef INET
1617 	case AF_INET:
1618 		sin = (struct sockaddr_in *)nam;
1619 		break;
1620 #endif
1621 #ifdef INET6
1622 	case AF_INET6:
1623 		sin6 = (struct sockaddr_in6 *)nam;
1624 		break;
1625 #endif
1626 	default:
1627 		/* unsupported family */
1628 		return (NULL);
1629 	}
1630 
1631 	if (head == NULL)
1632 		return (NULL);
1633 
1634 	LIST_FOREACH(inp, head, sctp_hash) {
1635 		SCTP_INP_RLOCK(inp);
1636 		if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
1637 			SCTP_INP_RUNLOCK(inp);
1638 			continue;
1639 		}
1640 		if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) &&
1641 		    (inp->sctp_lport == lport)) {
1642 			/* got it */
1643 			switch (nam->sa_family) {
1644 #ifdef INET
1645 			case AF_INET:
1646 				if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
1647 				    SCTP_IPV6_V6ONLY(inp)) {
1648 					/*
1649 					 * IPv4 on a IPv6 socket with ONLY
1650 					 * IPv6 set
1651 					 */
1652 					SCTP_INP_RUNLOCK(inp);
1653 					continue;
1654 				}
1655 				if (prison_check_ip4(inp->ip_inp.inp.inp_cred,
1656 				    &sin->sin_addr) != 0) {
1657 					SCTP_INP_RUNLOCK(inp);
1658 					continue;
1659 				}
1660 				break;
1661 #endif
1662 #ifdef INET6
1663 			case AF_INET6:
1664 				/*
1665 				 * A V6 address and the endpoint is NOT
1666 				 * bound V6
1667 				 */
1668 				if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) {
1669 					SCTP_INP_RUNLOCK(inp);
1670 					continue;
1671 				}
1672 				if (prison_check_ip6(inp->ip_inp.inp.inp_cred,
1673 				    &sin6->sin6_addr) != 0) {
1674 					SCTP_INP_RUNLOCK(inp);
1675 					continue;
1676 				}
1677 				break;
1678 #endif
1679 			default:
1680 				break;
1681 			}
1682 			/* does a VRF id match? */
1683 			fnd = 0;
1684 			if (inp->def_vrf_id == vrf_id)
1685 				fnd = 1;
1686 
1687 			SCTP_INP_RUNLOCK(inp);
1688 			if (!fnd)
1689 				continue;
1690 			return (inp);
1691 		}
1692 		SCTP_INP_RUNLOCK(inp);
1693 	}
1694 	switch (nam->sa_family) {
1695 #ifdef INET
1696 	case AF_INET:
1697 		if (sin->sin_addr.s_addr == INADDR_ANY) {
1698 			/* Can't hunt for one that has no address specified */
1699 			return (NULL);
1700 		}
1701 		break;
1702 #endif
1703 #ifdef INET6
1704 	case AF_INET6:
1705 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
1706 			/* Can't hunt for one that has no address specified */
1707 			return (NULL);
1708 		}
1709 		break;
1710 #endif
1711 	default:
1712 		break;
1713 	}
1714 	/*
1715 	 * ok, not bound to all so see if we can find a EP bound to this
1716 	 * address.
1717 	 */
1718 	LIST_FOREACH(inp, head, sctp_hash) {
1719 		SCTP_INP_RLOCK(inp);
1720 		if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
1721 			SCTP_INP_RUNLOCK(inp);
1722 			continue;
1723 		}
1724 		if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL)) {
1725 			SCTP_INP_RUNLOCK(inp);
1726 			continue;
1727 		}
1728 		/*
1729 		 * Ok this could be a likely candidate, look at all of its
1730 		 * addresses
1731 		 */
1732 		if (inp->sctp_lport != lport) {
1733 			SCTP_INP_RUNLOCK(inp);
1734 			continue;
1735 		}
1736 		/* does a VRF id match? */
1737 		fnd = 0;
1738 		if (inp->def_vrf_id == vrf_id)
1739 			fnd = 1;
1740 
1741 		if (!fnd) {
1742 			SCTP_INP_RUNLOCK(inp);
1743 			continue;
1744 		}
1745 		LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
1746 			if (laddr->ifa == NULL) {
1747 				SCTPDBG(SCTP_DEBUG_PCB1, "%s: NULL ifa\n",
1748 				    __func__);
1749 				continue;
1750 			}
1751 			SCTPDBG(SCTP_DEBUG_PCB1, "Ok laddr->ifa:%p is possible, ",
1752 			    (void *)laddr->ifa);
1753 			if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
1754 				SCTPDBG(SCTP_DEBUG_PCB1, "Huh IFA being deleted\n");
1755 				continue;
1756 			}
1757 			if (laddr->ifa->address.sa.sa_family == nam->sa_family) {
1758 				/* possible, see if it matches */
1759 				switch (nam->sa_family) {
1760 #ifdef INET
1761 				case AF_INET:
1762 					if (sin->sin_addr.s_addr ==
1763 					    laddr->ifa->address.sin.sin_addr.s_addr) {
1764 						SCTP_INP_RUNLOCK(inp);
1765 						return (inp);
1766 					}
1767 					break;
1768 #endif
1769 #ifdef INET6
1770 				case AF_INET6:
1771 					intf_addr6 = &laddr->ifa->address.sin6;
1772 					if (SCTP6_ARE_ADDR_EQUAL(sin6,
1773 					    intf_addr6)) {
1774 						SCTP_INP_RUNLOCK(inp);
1775 						return (inp);
1776 					}
1777 					break;
1778 #endif
1779 				}
1780 			}
1781 		}
1782 		SCTP_INP_RUNLOCK(inp);
1783 	}
1784 	return (NULL);
1785 }
1786 
1787 static struct sctp_inpcb *
1788 sctp_isport_inuse(struct sctp_inpcb *inp, uint16_t lport, uint32_t vrf_id)
1789 {
1790 	struct sctppcbhead *head;
1791 	struct sctp_inpcb *t_inp;
1792 	int fnd;
1793 
1794 	head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(lport,
1795 	    SCTP_BASE_INFO(hashmark))];
1796 	LIST_FOREACH(t_inp, head, sctp_hash) {
1797 		if (t_inp->sctp_lport != lport) {
1798 			continue;
1799 		}
1800 		/* is it in the VRF in question */
1801 		fnd = 0;
1802 		if (t_inp->def_vrf_id == vrf_id)
1803 			fnd = 1;
1804 		if (!fnd)
1805 			continue;
1806 
1807 		/* This one is in use. */
1808 		/* check the v6/v4 binding issue */
1809 		if ((t_inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
1810 		    SCTP_IPV6_V6ONLY(t_inp)) {
1811 			if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
1812 				/* collision in V6 space */
1813 				return (t_inp);
1814 			} else {
1815 				/* inp is BOUND_V4 no conflict */
1816 				continue;
1817 			}
1818 		} else if (t_inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
1819 			/* t_inp is bound v4 and v6, conflict always */
1820 			return (t_inp);
1821 		} else {
1822 			/* t_inp is bound only V4 */
1823 			if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
1824 			    SCTP_IPV6_V6ONLY(inp)) {
1825 				/* no conflict */
1826 				continue;
1827 			}
1828 			/* else fall through to conflict */
1829 		}
1830 		return (t_inp);
1831 	}
1832 	return (NULL);
1833 }
1834 
1835 int
1836 sctp_swap_inpcb_for_listen(struct sctp_inpcb *inp)
1837 {
1838 	/* For 1-2-1 with port reuse */
1839 	struct sctppcbhead *head;
1840 	struct sctp_inpcb *tinp, *ninp;
1841 
1842 	SCTP_INP_INFO_WLOCK_ASSERT();
1843 	SCTP_INP_WLOCK_ASSERT(inp);
1844 
1845 	if (sctp_is_feature_off(inp, SCTP_PCB_FLAGS_PORTREUSE)) {
1846 		/* only works with port reuse on */
1847 		return (-1);
1848 	}
1849 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) == 0) {
1850 		return (0);
1851 	}
1852 	SCTP_INP_WUNLOCK(inp);
1853 	head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(inp->sctp_lport,
1854 	    SCTP_BASE_INFO(hashmark))];
1855 	/* Kick out all non-listeners to the TCP hash */
1856 	LIST_FOREACH_SAFE(tinp, head, sctp_hash, ninp) {
1857 		if (tinp->sctp_lport != inp->sctp_lport) {
1858 			continue;
1859 		}
1860 		if (tinp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
1861 			continue;
1862 		}
1863 		if (tinp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
1864 			continue;
1865 		}
1866 		if (SCTP_IS_LISTENING(tinp)) {
1867 			continue;
1868 		}
1869 		SCTP_INP_WLOCK(tinp);
1870 		LIST_REMOVE(tinp, sctp_hash);
1871 		head = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR(tinp->sctp_lport, SCTP_BASE_INFO(hashtcpmark))];
1872 		tinp->sctp_flags |= SCTP_PCB_FLAGS_IN_TCPPOOL;
1873 		LIST_INSERT_HEAD(head, tinp, sctp_hash);
1874 		SCTP_INP_WUNLOCK(tinp);
1875 	}
1876 	SCTP_INP_WLOCK(inp);
1877 	/* Pull from where he was */
1878 	LIST_REMOVE(inp, sctp_hash);
1879 	inp->sctp_flags &= ~SCTP_PCB_FLAGS_IN_TCPPOOL;
1880 	head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(inp->sctp_lport, SCTP_BASE_INFO(hashmark))];
1881 	LIST_INSERT_HEAD(head, inp, sctp_hash);
1882 	return (0);
1883 }
1884 
1885 struct sctp_inpcb *
1886 sctp_pcb_findep(struct sockaddr *nam, int find_tcp_pool, int have_lock,
1887     uint32_t vrf_id)
1888 {
1889 	/*
1890 	 * First we check the hash table to see if someone has this port
1891 	 * bound with just the port.
1892 	 */
1893 	struct sctp_inpcb *inp;
1894 	struct sctppcbhead *head;
1895 	int lport;
1896 	unsigned int i;
1897 #ifdef INET
1898 	struct sockaddr_in *sin;
1899 #endif
1900 #ifdef INET6
1901 	struct sockaddr_in6 *sin6;
1902 #endif
1903 
1904 	switch (nam->sa_family) {
1905 #ifdef INET
1906 	case AF_INET:
1907 		sin = (struct sockaddr_in *)nam;
1908 		lport = sin->sin_port;
1909 		break;
1910 #endif
1911 #ifdef INET6
1912 	case AF_INET6:
1913 		sin6 = (struct sockaddr_in6 *)nam;
1914 		lport = sin6->sin6_port;
1915 		break;
1916 #endif
1917 	default:
1918 		return (NULL);
1919 	}
1920 	/*
1921 	 * I could cheat here and just cast to one of the types but we will
1922 	 * do it right. It also provides the check against an Unsupported
1923 	 * type too.
1924 	 */
1925 	/* Find the head of the ALLADDR chain */
1926 	if (have_lock == 0) {
1927 		SCTP_INP_INFO_RLOCK();
1928 	}
1929 	head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(lport,
1930 	    SCTP_BASE_INFO(hashmark))];
1931 	inp = sctp_endpoint_probe(nam, head, lport, vrf_id);
1932 
1933 	/*
1934 	 * If the TCP model exists it could be that the main listening
1935 	 * endpoint is gone but there still exists a connected socket for
1936 	 * this guy. If so we can return the first one that we find. This
1937 	 * may NOT be the correct one so the caller should be wary on the
1938 	 * returned INP. Currently the only caller that sets find_tcp_pool
1939 	 * is in bindx where we are verifying that a user CAN bind the
1940 	 * address. He either has bound it already, or someone else has, or
1941 	 * its open to bind, so this is good enough.
1942 	 */
1943 	if (inp == NULL && find_tcp_pool) {
1944 		for (i = 0; i < SCTP_BASE_INFO(hashtcpmark) + 1; i++) {
1945 			head = &SCTP_BASE_INFO(sctp_tcpephash)[i];
1946 			inp = sctp_endpoint_probe(nam, head, lport, vrf_id);
1947 			if (inp) {
1948 				break;
1949 			}
1950 		}
1951 	}
1952 	if (inp) {
1953 		SCTP_INP_INCR_REF(inp);
1954 	}
1955 	if (have_lock == 0) {
1956 		SCTP_INP_INFO_RUNLOCK();
1957 	}
1958 	return (inp);
1959 }
1960 
1961 /*
1962  * Find an association for an endpoint with the pointer to whom you want to
1963  * send to and the endpoint pointer. The address can be IPv4 or IPv6. We may
1964  * need to change the *to to some other struct like a mbuf...
1965  */
1966 struct sctp_tcb *
1967 sctp_findassociation_addr_sa(struct sockaddr *from, struct sockaddr *to,
1968     struct sctp_inpcb **inp_p, struct sctp_nets **netp, int find_tcp_pool,
1969     uint32_t vrf_id)
1970 {
1971 	struct sctp_inpcb *inp = NULL;
1972 	struct sctp_tcb *stcb;
1973 
1974 	SCTP_INP_INFO_RLOCK();
1975 	if (find_tcp_pool) {
1976 		if (inp_p != NULL) {
1977 			stcb = sctp_tcb_special_locate(inp_p, from, to, netp,
1978 			    vrf_id);
1979 		} else {
1980 			stcb = sctp_tcb_special_locate(&inp, from, to, netp,
1981 			    vrf_id);
1982 		}
1983 		if (stcb != NULL) {
1984 			SCTP_INP_INFO_RUNLOCK();
1985 			return (stcb);
1986 		}
1987 	}
1988 	inp = sctp_pcb_findep(to, 0, 1, vrf_id);
1989 	if (inp_p != NULL) {
1990 		*inp_p = inp;
1991 	}
1992 	SCTP_INP_INFO_RUNLOCK();
1993 	if (inp == NULL) {
1994 		return (NULL);
1995 	}
1996 	/*
1997 	 * ok, we have an endpoint, now lets find the assoc for it (if any)
1998 	 * we now place the source address or from in the to of the find
1999 	 * endpoint call. Since in reality this chain is used from the
2000 	 * inbound packet side.
2001 	 */
2002 	if (inp_p != NULL) {
2003 		stcb = sctp_findassociation_ep_addr(inp_p, from, netp, to,
2004 		    NULL);
2005 	} else {
2006 		stcb = sctp_findassociation_ep_addr(&inp, from, netp, to,
2007 		    NULL);
2008 	}
2009 	return (stcb);
2010 }
2011 
2012 /*
2013  * This routine will grub through the mbuf that is a INIT or INIT-ACK and
2014  * find all addresses that the sender has specified in any address list. Each
2015  * address will be used to lookup the TCB and see if one exits.
2016  */
2017 static struct sctp_tcb *
2018 sctp_findassociation_special_addr(struct mbuf *m, int offset,
2019     struct sctphdr *sh, struct sctp_inpcb **inp_p, struct sctp_nets **netp,
2020     struct sockaddr *dst)
2021 {
2022 	struct sctp_paramhdr *phdr, param_buf;
2023 #if defined(INET) || defined(INET6)
2024 	struct sctp_tcb *stcb;
2025 	uint16_t ptype;
2026 #endif
2027 	uint16_t plen;
2028 #ifdef INET
2029 	struct sockaddr_in sin4;
2030 #endif
2031 #ifdef INET6
2032 	struct sockaddr_in6 sin6;
2033 #endif
2034 
2035 #ifdef INET
2036 	memset(&sin4, 0, sizeof(sin4));
2037 	sin4.sin_len = sizeof(sin4);
2038 	sin4.sin_family = AF_INET;
2039 	sin4.sin_port = sh->src_port;
2040 #endif
2041 #ifdef INET6
2042 	memset(&sin6, 0, sizeof(sin6));
2043 	sin6.sin6_len = sizeof(sin6);
2044 	sin6.sin6_family = AF_INET6;
2045 	sin6.sin6_port = sh->src_port;
2046 #endif
2047 
2048 	offset += sizeof(struct sctp_init_chunk);
2049 
2050 	phdr = sctp_get_next_param(m, offset, &param_buf, sizeof(param_buf));
2051 	while (phdr != NULL) {
2052 		/* now we must see if we want the parameter */
2053 #if defined(INET) || defined(INET6)
2054 		ptype = ntohs(phdr->param_type);
2055 #endif
2056 		plen = ntohs(phdr->param_length);
2057 		if (plen == 0) {
2058 			break;
2059 		}
2060 #ifdef INET
2061 		if (ptype == SCTP_IPV4_ADDRESS &&
2062 		    plen == sizeof(struct sctp_ipv4addr_param)) {
2063 			/* Get the rest of the address */
2064 			struct sctp_ipv4addr_param ip4_param, *p4;
2065 
2066 			phdr = sctp_get_next_param(m, offset,
2067 			    (struct sctp_paramhdr *)&ip4_param, sizeof(ip4_param));
2068 			if (phdr == NULL) {
2069 				return (NULL);
2070 			}
2071 			p4 = (struct sctp_ipv4addr_param *)phdr;
2072 			memcpy(&sin4.sin_addr, &p4->addr, sizeof(p4->addr));
2073 			/* look it up */
2074 			stcb = sctp_findassociation_ep_addr(inp_p,
2075 			    (struct sockaddr *)&sin4, netp, dst, NULL);
2076 			if (stcb != NULL) {
2077 				return (stcb);
2078 			}
2079 		}
2080 #endif
2081 #ifdef INET6
2082 		if (ptype == SCTP_IPV6_ADDRESS &&
2083 		    plen == sizeof(struct sctp_ipv6addr_param)) {
2084 			/* Get the rest of the address */
2085 			struct sctp_ipv6addr_param ip6_param, *p6;
2086 
2087 			phdr = sctp_get_next_param(m, offset,
2088 			    (struct sctp_paramhdr *)&ip6_param, sizeof(ip6_param));
2089 			if (phdr == NULL) {
2090 				return (NULL);
2091 			}
2092 			p6 = (struct sctp_ipv6addr_param *)phdr;
2093 			memcpy(&sin6.sin6_addr, &p6->addr, sizeof(p6->addr));
2094 			/* look it up */
2095 			stcb = sctp_findassociation_ep_addr(inp_p,
2096 			    (struct sockaddr *)&sin6, netp, dst, NULL);
2097 			if (stcb != NULL) {
2098 				return (stcb);
2099 			}
2100 		}
2101 #endif
2102 		offset += SCTP_SIZE32(plen);
2103 		phdr = sctp_get_next_param(m, offset, &param_buf,
2104 		    sizeof(param_buf));
2105 	}
2106 	return (NULL);
2107 }
2108 
2109 static struct sctp_tcb *
2110 sctp_findassoc_by_vtag(struct sockaddr *from, struct sockaddr *to, uint32_t vtag,
2111     struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint16_t rport,
2112     uint16_t lport, int skip_src_check, uint32_t vrf_id, uint32_t remote_tag)
2113 {
2114 	/*
2115 	 * Use my vtag to hash. If we find it we then verify the source addr
2116 	 * is in the assoc. If all goes well we save a bit on rec of a
2117 	 * packet.
2118 	 */
2119 	struct sctpasochead *head;
2120 	struct sctp_nets *net;
2121 	struct sctp_tcb *stcb;
2122 
2123 	SCTP_INP_INFO_RLOCK();
2124 	head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(vtag,
2125 	    SCTP_BASE_INFO(hashasocmark))];
2126 	LIST_FOREACH(stcb, head, sctp_asocs) {
2127 		SCTP_INP_RLOCK(stcb->sctp_ep);
2128 		if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
2129 			SCTP_INP_RUNLOCK(stcb->sctp_ep);
2130 			continue;
2131 		}
2132 		if (stcb->sctp_ep->def_vrf_id != vrf_id) {
2133 			SCTP_INP_RUNLOCK(stcb->sctp_ep);
2134 			continue;
2135 		}
2136 		SCTP_TCB_LOCK(stcb);
2137 		SCTP_INP_RUNLOCK(stcb->sctp_ep);
2138 		if (stcb->asoc.my_vtag == vtag) {
2139 			/* candidate */
2140 			if (stcb->rport != rport) {
2141 				SCTP_TCB_UNLOCK(stcb);
2142 				continue;
2143 			}
2144 			if (stcb->sctp_ep->sctp_lport != lport) {
2145 				SCTP_TCB_UNLOCK(stcb);
2146 				continue;
2147 			}
2148 			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
2149 				SCTP_TCB_UNLOCK(stcb);
2150 				continue;
2151 			}
2152 			/* RRS:Need toaddr check here */
2153 			if (sctp_does_stcb_own_this_addr(stcb, to) == 0) {
2154 				/* Endpoint does not own this address */
2155 				SCTP_TCB_UNLOCK(stcb);
2156 				continue;
2157 			}
2158 			if (remote_tag) {
2159 				/*
2160 				 * If we have both vtags that's all we match
2161 				 * on
2162 				 */
2163 				if (stcb->asoc.peer_vtag == remote_tag) {
2164 					/*
2165 					 * If both tags match we consider it
2166 					 * conclusive and check NO
2167 					 * source/destination addresses
2168 					 */
2169 					goto conclusive;
2170 				}
2171 			}
2172 			if (skip_src_check) {
2173 		conclusive:
2174 				if (from) {
2175 					*netp = sctp_findnet(stcb, from);
2176 				} else {
2177 					*netp = NULL;	/* unknown */
2178 				}
2179 				if (inp_p)
2180 					*inp_p = stcb->sctp_ep;
2181 				SCTP_INP_INFO_RUNLOCK();
2182 				return (stcb);
2183 			}
2184 			net = sctp_findnet(stcb, from);
2185 			if (net) {
2186 				/* yep its him. */
2187 				*netp = net;
2188 				SCTP_STAT_INCR(sctps_vtagexpress);
2189 				*inp_p = stcb->sctp_ep;
2190 				SCTP_INP_INFO_RUNLOCK();
2191 				return (stcb);
2192 			} else {
2193 				/*
2194 				 * not him, this should only happen in rare
2195 				 * cases so I peg it.
2196 				 */
2197 				SCTP_STAT_INCR(sctps_vtagbogus);
2198 			}
2199 		}
2200 		SCTP_TCB_UNLOCK(stcb);
2201 	}
2202 	SCTP_INP_INFO_RUNLOCK();
2203 	return (NULL);
2204 }
2205 
2206 /*
2207  * Find an association with the pointer to the inbound IP packet. This can be
2208  * a IPv4 or IPv6 packet.
2209  */
2210 struct sctp_tcb *
2211 sctp_findassociation_addr(struct mbuf *m, int offset,
2212     struct sockaddr *src, struct sockaddr *dst,
2213     struct sctphdr *sh, struct sctp_chunkhdr *ch,
2214     struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint32_t vrf_id)
2215 {
2216 	struct sctp_tcb *stcb;
2217 	struct sctp_inpcb *inp;
2218 
2219 	if (sh->v_tag) {
2220 		/* we only go down this path if vtag is non-zero */
2221 		stcb = sctp_findassoc_by_vtag(src, dst, ntohl(sh->v_tag),
2222 		    inp_p, netp, sh->src_port, sh->dest_port, 0, vrf_id, 0);
2223 		if (stcb) {
2224 			return (stcb);
2225 		}
2226 	}
2227 
2228 	if (inp_p) {
2229 		stcb = sctp_findassociation_addr_sa(src, dst, inp_p, netp,
2230 		    1, vrf_id);
2231 		inp = *inp_p;
2232 	} else {
2233 		stcb = sctp_findassociation_addr_sa(src, dst, &inp, netp,
2234 		    1, vrf_id);
2235 	}
2236 	SCTPDBG(SCTP_DEBUG_PCB1, "stcb:%p inp:%p\n", (void *)stcb, (void *)inp);
2237 	if (stcb == NULL && inp) {
2238 		/* Found a EP but not this address */
2239 		if ((ch->chunk_type == SCTP_INITIATION) ||
2240 		    (ch->chunk_type == SCTP_INITIATION_ACK)) {
2241 			/*-
2242 			 * special hook, we do NOT return linp or an
2243 			 * association that is linked to an existing
2244 			 * association that is under the TCP pool (i.e. no
2245 			 * listener exists). The endpoint finding routine
2246 			 * will always find a listener before examining the
2247 			 * TCP pool.
2248 			 */
2249 			if (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) {
2250 				if (inp_p) {
2251 					*inp_p = NULL;
2252 				}
2253 				return (NULL);
2254 			}
2255 			stcb = sctp_findassociation_special_addr(m,
2256 			    offset, sh, &inp, netp, dst);
2257 			if (inp_p != NULL) {
2258 				*inp_p = inp;
2259 			}
2260 		}
2261 	}
2262 	SCTPDBG(SCTP_DEBUG_PCB1, "stcb is %p\n", (void *)stcb);
2263 	return (stcb);
2264 }
2265 
2266 /*
2267  * lookup an association by an ASCONF lookup address.
2268  * if the lookup address is 0.0.0.0 or ::0, use the vtag to do the lookup
2269  */
2270 struct sctp_tcb *
2271 sctp_findassociation_ep_asconf(struct mbuf *m, int offset,
2272     struct sockaddr *dst, struct sctphdr *sh,
2273     struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint32_t vrf_id)
2274 {
2275 	struct sctp_tcb *stcb;
2276 	union sctp_sockstore remote_store;
2277 	struct sctp_paramhdr param_buf, *phdr;
2278 	int ptype;
2279 	int zero_address = 0;
2280 #ifdef INET
2281 	struct sockaddr_in *sin;
2282 #endif
2283 #ifdef INET6
2284 	struct sockaddr_in6 *sin6;
2285 #endif
2286 
2287 	memset(&remote_store, 0, sizeof(remote_store));
2288 	phdr = sctp_get_next_param(m, offset + sizeof(struct sctp_asconf_chunk),
2289 	    &param_buf, sizeof(struct sctp_paramhdr));
2290 	if (phdr == NULL) {
2291 		SCTPDBG(SCTP_DEBUG_INPUT3, "%s: failed to get asconf lookup addr\n",
2292 		    __func__);
2293 		return NULL;
2294 	}
2295 	ptype = (int)((uint32_t)ntohs(phdr->param_type));
2296 	/* get the correlation address */
2297 	switch (ptype) {
2298 #ifdef INET6
2299 	case SCTP_IPV6_ADDRESS:
2300 		{
2301 			/* ipv6 address param */
2302 			struct sctp_ipv6addr_param *p6, p6_buf;
2303 
2304 			if (ntohs(phdr->param_length) != sizeof(struct sctp_ipv6addr_param)) {
2305 				return NULL;
2306 			}
2307 			p6 = (struct sctp_ipv6addr_param *)sctp_get_next_param(m,
2308 			    offset + sizeof(struct sctp_asconf_chunk),
2309 			    &p6_buf.ph, sizeof(p6_buf));
2310 			if (p6 == NULL) {
2311 				SCTPDBG(SCTP_DEBUG_INPUT3, "%s: failed to get asconf v6 lookup addr\n",
2312 				    __func__);
2313 				return (NULL);
2314 			}
2315 			sin6 = &remote_store.sin6;
2316 			sin6->sin6_family = AF_INET6;
2317 			sin6->sin6_len = sizeof(*sin6);
2318 			sin6->sin6_port = sh->src_port;
2319 			memcpy(&sin6->sin6_addr, &p6->addr, sizeof(struct in6_addr));
2320 			if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
2321 				zero_address = 1;
2322 			break;
2323 		}
2324 #endif
2325 #ifdef INET
2326 	case SCTP_IPV4_ADDRESS:
2327 		{
2328 			/* ipv4 address param */
2329 			struct sctp_ipv4addr_param *p4, p4_buf;
2330 
2331 			if (ntohs(phdr->param_length) != sizeof(struct sctp_ipv4addr_param)) {
2332 				return NULL;
2333 			}
2334 			p4 = (struct sctp_ipv4addr_param *)sctp_get_next_param(m,
2335 			    offset + sizeof(struct sctp_asconf_chunk),
2336 			    &p4_buf.ph, sizeof(p4_buf));
2337 			if (p4 == NULL) {
2338 				SCTPDBG(SCTP_DEBUG_INPUT3, "%s: failed to get asconf v4 lookup addr\n",
2339 				    __func__);
2340 				return (NULL);
2341 			}
2342 			sin = &remote_store.sin;
2343 			sin->sin_family = AF_INET;
2344 			sin->sin_len = sizeof(*sin);
2345 			sin->sin_port = sh->src_port;
2346 			memcpy(&sin->sin_addr, &p4->addr, sizeof(struct in_addr));
2347 			if (sin->sin_addr.s_addr == INADDR_ANY)
2348 				zero_address = 1;
2349 			break;
2350 		}
2351 #endif
2352 	default:
2353 		/* invalid address param type */
2354 		return NULL;
2355 	}
2356 
2357 	if (zero_address) {
2358 		stcb = sctp_findassoc_by_vtag(NULL, dst, ntohl(sh->v_tag), inp_p,
2359 		    netp, sh->src_port, sh->dest_port, 1, vrf_id, 0);
2360 		if (stcb != NULL) {
2361 			SCTP_INP_DECR_REF(*inp_p);
2362 		}
2363 	} else {
2364 		stcb = sctp_findassociation_ep_addr(inp_p,
2365 		    &remote_store.sa, netp,
2366 		    dst, NULL);
2367 	}
2368 	return (stcb);
2369 }
2370 
2371 /*
2372  * allocate a sctp_inpcb and setup a temporary binding to a port/all
2373  * addresses. This way if we don't get a bind we by default pick a ephemeral
2374  * port with all addresses bound.
2375  */
2376 int
2377 sctp_inpcb_alloc(struct socket *so, uint32_t vrf_id)
2378 {
2379 	/*
2380 	 * we get called when a new endpoint starts up. We need to allocate
2381 	 * the sctp_inpcb structure from the zone and init it. Mark it as
2382 	 * unbound and find a port that we can use as an ephemeral with
2383 	 * INADDR_ANY. If the user binds later no problem we can then add in
2384 	 * the specific addresses. And setup the default parameters for the
2385 	 * EP.
2386 	 */
2387 	int i, error;
2388 	struct sctp_inpcb *inp;
2389 	struct sctp_pcb *m;
2390 	struct timeval time;
2391 	sctp_sharedkey_t *null_key;
2392 
2393 	error = 0;
2394 
2395 	SCTP_INP_INFO_WLOCK();
2396 	inp = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_ep), struct sctp_inpcb);
2397 	if (inp == NULL) {
2398 		SCTP_PRINTF("Out of SCTP-INPCB structures - no resources\n");
2399 		SCTP_INP_INFO_WUNLOCK();
2400 		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
2401 		return (ENOBUFS);
2402 	}
2403 	/* zap it */
2404 	memset(inp, 0, sizeof(*inp));
2405 
2406 	/* bump generations */
2407 	/* setup socket pointers */
2408 	inp->sctp_socket = so;
2409 	inp->ip_inp.inp.inp_socket = so;
2410 	inp->ip_inp.inp.inp_cred = crhold(so->so_cred);
2411 #ifdef INET6
2412 	if (INP_SOCKAF(so) == AF_INET6) {
2413 		if (MODULE_GLOBAL(ip6_auto_flowlabel)) {
2414 			inp->ip_inp.inp.inp_flags |= IN6P_AUTOFLOWLABEL;
2415 		}
2416 		if (MODULE_GLOBAL(ip6_v6only)) {
2417 			inp->ip_inp.inp.inp_flags |= IN6P_IPV6_V6ONLY;
2418 		}
2419 	}
2420 #endif
2421 	inp->sctp_associd_counter = 1;
2422 	inp->partial_delivery_point = SCTP_SB_LIMIT_RCV(so) >> SCTP_PARTIAL_DELIVERY_SHIFT;
2423 	inp->sctp_frag_point = 0;
2424 	inp->max_cwnd = 0;
2425 	inp->sctp_cmt_on_off = SCTP_BASE_SYSCTL(sctp_cmt_on_off);
2426 	inp->ecn_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_ecn_enable);
2427 	inp->prsctp_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_pr_enable);
2428 	inp->auth_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_auth_enable);
2429 	inp->asconf_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_asconf_enable);
2430 	inp->reconfig_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_reconfig_enable);
2431 	inp->nrsack_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_nrsack_enable);
2432 	inp->pktdrop_supported = (uint8_t)SCTP_BASE_SYSCTL(sctp_pktdrop_enable);
2433 	inp->idata_supported = 0;
2434 	inp->rcv_edmid = SCTP_EDMID_NONE;
2435 
2436 	inp->fibnum = so->so_fibnum;
2437 	/* init the small hash table we use to track asocid <-> tcb */
2438 	inp->sctp_asocidhash = SCTP_HASH_INIT(SCTP_STACK_VTAG_HASH_SIZE, &inp->hashasocidmark);
2439 	if (inp->sctp_asocidhash == NULL) {
2440 		crfree(inp->ip_inp.inp.inp_cred);
2441 		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
2442 		SCTP_INP_INFO_WUNLOCK();
2443 		return (ENOBUFS);
2444 	}
2445 	SCTP_INCR_EP_COUNT();
2446 	inp->ip_inp.inp.inp_ip_ttl = MODULE_GLOBAL(ip_defttl);
2447 	SCTP_INP_INFO_WUNLOCK();
2448 
2449 	so->so_pcb = (caddr_t)inp;
2450 
2451 	if (SCTP_SO_TYPE(so) == SOCK_SEQPACKET) {
2452 		/* UDP style socket */
2453 		inp->sctp_flags = (SCTP_PCB_FLAGS_UDPTYPE |
2454 		    SCTP_PCB_FLAGS_UNBOUND);
2455 		/* Be sure it is NON-BLOCKING IO for UDP */
2456 		/* SCTP_SET_SO_NBIO(so); */
2457 	} else if (SCTP_SO_TYPE(so) == SOCK_STREAM) {
2458 		/* TCP style socket */
2459 		inp->sctp_flags = (SCTP_PCB_FLAGS_TCPTYPE |
2460 		    SCTP_PCB_FLAGS_UNBOUND);
2461 		/* Be sure we have blocking IO by default */
2462 		SOCK_LOCK(so);
2463 		SCTP_CLEAR_SO_NBIO(so);
2464 		SOCK_UNLOCK(so);
2465 	} else {
2466 		/*
2467 		 * unsupported socket type (RAW, etc)- in case we missed it
2468 		 * in protosw
2469 		 */
2470 		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EOPNOTSUPP);
2471 		so->so_pcb = NULL;
2472 		crfree(inp->ip_inp.inp.inp_cred);
2473 		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
2474 		return (EOPNOTSUPP);
2475 	}
2476 	if (SCTP_BASE_SYSCTL(sctp_default_frag_interleave) == SCTP_FRAG_LEVEL_1) {
2477 		sctp_feature_on(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE);
2478 		sctp_feature_off(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS);
2479 	} else if (SCTP_BASE_SYSCTL(sctp_default_frag_interleave) == SCTP_FRAG_LEVEL_2) {
2480 		sctp_feature_on(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE);
2481 		sctp_feature_on(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS);
2482 	} else if (SCTP_BASE_SYSCTL(sctp_default_frag_interleave) == SCTP_FRAG_LEVEL_0) {
2483 		sctp_feature_off(inp, SCTP_PCB_FLAGS_FRAG_INTERLEAVE);
2484 		sctp_feature_off(inp, SCTP_PCB_FLAGS_INTERLEAVE_STRMS);
2485 	}
2486 	inp->sctp_tcbhash = SCTP_HASH_INIT(SCTP_BASE_SYSCTL(sctp_pcbtblsize),
2487 	    &inp->sctp_hashmark);
2488 	if (inp->sctp_tcbhash == NULL) {
2489 		SCTP_PRINTF("Out of SCTP-INPCB->hashinit - no resources\n");
2490 		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
2491 		so->so_pcb = NULL;
2492 		crfree(inp->ip_inp.inp.inp_cred);
2493 		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
2494 		return (ENOBUFS);
2495 	}
2496 	inp->def_vrf_id = vrf_id;
2497 
2498 	SCTP_INP_INFO_WLOCK();
2499 	SCTP_INP_LOCK_INIT(inp);
2500 	rw_init_flags(&inp->ip_inp.inp.inp_lock, "sctpinp",
2501 	    RW_RECURSE | RW_DUPOK);
2502 	SCTP_INP_READ_LOCK_INIT(inp);
2503 	SCTP_ASOC_CREATE_LOCK_INIT(inp);
2504 	/* lock the new ep */
2505 	SCTP_INP_WLOCK(inp);
2506 
2507 	/* add it to the info area */
2508 	LIST_INSERT_HEAD(&SCTP_BASE_INFO(listhead), inp, sctp_list);
2509 	SCTP_INP_INFO_WUNLOCK();
2510 
2511 	TAILQ_INIT(&inp->read_queue);
2512 	LIST_INIT(&inp->sctp_addr_list);
2513 
2514 	LIST_INIT(&inp->sctp_asoc_list);
2515 
2516 #ifdef SCTP_TRACK_FREED_ASOCS
2517 	/* TEMP CODE */
2518 	LIST_INIT(&inp->sctp_asoc_free_list);
2519 #endif
2520 	/* Init the timer structure for signature change */
2521 	SCTP_OS_TIMER_INIT(&inp->sctp_ep.signature_change.timer);
2522 	inp->sctp_ep.signature_change.type = SCTP_TIMER_TYPE_NEWCOOKIE;
2523 
2524 	/* now init the actual endpoint default data */
2525 	m = &inp->sctp_ep;
2526 
2527 	/* setup the base timeout information */
2528 	m->sctp_timeoutticks[SCTP_TIMER_SEND] = sctp_secs_to_ticks(SCTP_SEND_SEC);	/* needed ? */
2529 	m->sctp_timeoutticks[SCTP_TIMER_INIT] = sctp_secs_to_ticks(SCTP_INIT_SEC);	/* needed ? */
2530 	m->sctp_timeoutticks[SCTP_TIMER_RECV] = sctp_msecs_to_ticks(SCTP_BASE_SYSCTL(sctp_delayed_sack_time_default));
2531 	m->sctp_timeoutticks[SCTP_TIMER_HEARTBEAT] = sctp_msecs_to_ticks(SCTP_BASE_SYSCTL(sctp_heartbeat_interval_default));
2532 	m->sctp_timeoutticks[SCTP_TIMER_PMTU] = sctp_secs_to_ticks(SCTP_BASE_SYSCTL(sctp_pmtu_raise_time_default));
2533 	m->sctp_timeoutticks[SCTP_TIMER_MAXSHUTDOWN] = sctp_secs_to_ticks(SCTP_BASE_SYSCTL(sctp_shutdown_guard_time_default));
2534 	m->sctp_timeoutticks[SCTP_TIMER_SIGNATURE] = sctp_secs_to_ticks(SCTP_BASE_SYSCTL(sctp_secret_lifetime_default));
2535 	/* all max/min max are in ms */
2536 	m->sctp_maxrto = SCTP_BASE_SYSCTL(sctp_rto_max_default);
2537 	m->sctp_minrto = SCTP_BASE_SYSCTL(sctp_rto_min_default);
2538 	m->initial_rto = SCTP_BASE_SYSCTL(sctp_rto_initial_default);
2539 	m->initial_init_rto_max = SCTP_BASE_SYSCTL(sctp_init_rto_max_default);
2540 	m->sctp_sack_freq = SCTP_BASE_SYSCTL(sctp_sack_freq_default);
2541 	m->max_init_times = SCTP_BASE_SYSCTL(sctp_init_rtx_max_default);
2542 	m->max_send_times = SCTP_BASE_SYSCTL(sctp_assoc_rtx_max_default);
2543 	m->def_net_failure = SCTP_BASE_SYSCTL(sctp_path_rtx_max_default);
2544 	m->def_net_pf_threshold = SCTP_BASE_SYSCTL(sctp_path_pf_threshold);
2545 	m->sctp_sws_sender = SCTP_SWS_SENDER_DEF;
2546 	m->sctp_sws_receiver = SCTP_SWS_RECEIVER_DEF;
2547 	m->max_burst = SCTP_BASE_SYSCTL(sctp_max_burst_default);
2548 	m->fr_max_burst = SCTP_BASE_SYSCTL(sctp_fr_max_burst_default);
2549 
2550 	m->sctp_default_cc_module = SCTP_BASE_SYSCTL(sctp_default_cc_module);
2551 	m->sctp_default_ss_module = SCTP_BASE_SYSCTL(sctp_default_ss_module);
2552 	m->max_open_streams_intome = SCTP_BASE_SYSCTL(sctp_nr_incoming_streams_default);
2553 	/* number of streams to pre-open on a association */
2554 	m->pre_open_stream_count = SCTP_BASE_SYSCTL(sctp_nr_outgoing_streams_default);
2555 
2556 	m->default_mtu = 0;
2557 	/* Add adaptation cookie */
2558 	m->adaptation_layer_indicator = 0;
2559 	m->adaptation_layer_indicator_provided = 0;
2560 
2561 	/* seed random number generator */
2562 	m->random_counter = 1;
2563 	m->store_at = SCTP_SIGNATURE_SIZE;
2564 	SCTP_READ_RANDOM(m->random_numbers, sizeof(m->random_numbers));
2565 	sctp_fill_random_store(m);
2566 
2567 	/* Minimum cookie size */
2568 	m->size_of_a_cookie = (sizeof(struct sctp_init_msg) * 2) +
2569 	    sizeof(struct sctp_state_cookie);
2570 	m->size_of_a_cookie += SCTP_SIGNATURE_SIZE;
2571 
2572 	/* Setup the initial secret */
2573 	(void)SCTP_GETTIME_TIMEVAL(&time);
2574 	m->time_of_secret_change = (unsigned int)time.tv_sec;
2575 
2576 	for (i = 0; i < SCTP_NUMBER_OF_SECRETS; i++) {
2577 		m->secret_key[0][i] = sctp_select_initial_TSN(m);
2578 	}
2579 	sctp_timer_start(SCTP_TIMER_TYPE_NEWCOOKIE, inp, NULL, NULL);
2580 
2581 	/* How long is a cookie good for ? */
2582 	m->def_cookie_life = sctp_msecs_to_ticks(SCTP_BASE_SYSCTL(sctp_valid_cookie_life_default));
2583 	/*
2584 	 * Initialize authentication parameters
2585 	 */
2586 	m->local_hmacs = sctp_default_supported_hmaclist();
2587 	m->local_auth_chunks = sctp_alloc_chunklist();
2588 	if (inp->asconf_supported) {
2589 		sctp_auth_add_chunk(SCTP_ASCONF, m->local_auth_chunks);
2590 		sctp_auth_add_chunk(SCTP_ASCONF_ACK, m->local_auth_chunks);
2591 	}
2592 	m->default_dscp = 0;
2593 #ifdef INET6
2594 	m->default_flowlabel = 0;
2595 #endif
2596 	m->port = 0;		/* encapsulation disabled by default */
2597 	LIST_INIT(&m->shared_keys);
2598 	/* add default NULL key as key id 0 */
2599 	null_key = sctp_alloc_sharedkey();
2600 	sctp_insert_sharedkey(&m->shared_keys, null_key);
2601 	SCTP_INP_WUNLOCK(inp);
2602 #ifdef SCTP_LOG_CLOSING
2603 	sctp_log_closing(inp, NULL, 12);
2604 #endif
2605 	return (error);
2606 }
2607 
2608 void
2609 sctp_move_pcb_and_assoc(struct sctp_inpcb *old_inp, struct sctp_inpcb *new_inp,
2610     struct sctp_tcb *stcb)
2611 {
2612 	struct sctp_nets *net;
2613 	uint16_t lport, rport;
2614 	struct sctppcbhead *head;
2615 	struct sctp_laddr *laddr, *oladdr;
2616 
2617 	atomic_add_int(&stcb->asoc.refcnt, 1);
2618 	SCTP_TCB_UNLOCK(stcb);
2619 	SCTP_INP_INFO_WLOCK();
2620 	SCTP_INP_WLOCK(old_inp);
2621 	SCTP_INP_WLOCK(new_inp);
2622 	SCTP_TCB_LOCK(stcb);
2623 	atomic_subtract_int(&stcb->asoc.refcnt, 1);
2624 
2625 #ifdef INET6
2626 	if (old_inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
2627 		new_inp->ip_inp.inp.inp_flags |= old_inp->ip_inp.inp.inp_flags & INP_CONTROLOPTS;
2628 		if (old_inp->ip_inp.inp.in6p_outputopts) {
2629 			new_inp->ip_inp.inp.in6p_outputopts = ip6_copypktopts(old_inp->ip_inp.inp.in6p_outputopts, M_NOWAIT);
2630 		}
2631 	}
2632 #endif
2633 #if defined(INET) && defined(INET6)
2634 	else
2635 #endif
2636 #ifdef INET
2637 	{
2638 		new_inp->ip_inp.inp.inp_ip_tos = old_inp->ip_inp.inp.inp_ip_tos;
2639 		new_inp->ip_inp.inp.inp_ip_ttl = old_inp->ip_inp.inp.inp_ip_ttl;
2640 	}
2641 #endif
2642 	new_inp->sctp_ep.time_of_secret_change =
2643 	    old_inp->sctp_ep.time_of_secret_change;
2644 	memcpy(new_inp->sctp_ep.secret_key, old_inp->sctp_ep.secret_key,
2645 	    sizeof(old_inp->sctp_ep.secret_key));
2646 	new_inp->sctp_ep.current_secret_number =
2647 	    old_inp->sctp_ep.current_secret_number;
2648 	new_inp->sctp_ep.last_secret_number =
2649 	    old_inp->sctp_ep.last_secret_number;
2650 	new_inp->sctp_ep.size_of_a_cookie = old_inp->sctp_ep.size_of_a_cookie;
2651 
2652 	/* make it so new data pours into the new socket */
2653 	stcb->sctp_socket = new_inp->sctp_socket;
2654 	stcb->sctp_ep = new_inp;
2655 
2656 	/* Copy the port across */
2657 	lport = new_inp->sctp_lport = old_inp->sctp_lport;
2658 	rport = stcb->rport;
2659 	/* Pull the tcb from the old association */
2660 	LIST_REMOVE(stcb, sctp_tcbhash);
2661 	LIST_REMOVE(stcb, sctp_tcblist);
2662 	if (stcb->asoc.in_asocid_hash) {
2663 		LIST_REMOVE(stcb, sctp_tcbasocidhash);
2664 	}
2665 	/* Now insert the new_inp into the TCP connected hash */
2666 	head = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR((lport | rport), SCTP_BASE_INFO(hashtcpmark))];
2667 
2668 	LIST_INSERT_HEAD(head, new_inp, sctp_hash);
2669 	/* Its safe to access */
2670 	new_inp->sctp_flags &= ~SCTP_PCB_FLAGS_UNBOUND;
2671 
2672 	/* Now move the tcb into the endpoint list */
2673 	LIST_INSERT_HEAD(&new_inp->sctp_asoc_list, stcb, sctp_tcblist);
2674 	/*
2675 	 * Question, do we even need to worry about the ep-hash since we
2676 	 * only have one connection? Probably not :> so lets get rid of it
2677 	 * and not suck up any kernel memory in that.
2678 	 */
2679 	if (stcb->asoc.in_asocid_hash) {
2680 		struct sctpasochead *lhd;
2681 
2682 		lhd = &new_inp->sctp_asocidhash[SCTP_PCBHASH_ASOC(stcb->asoc.assoc_id,
2683 		    new_inp->hashasocidmark)];
2684 		LIST_INSERT_HEAD(lhd, stcb, sctp_tcbasocidhash);
2685 	}
2686 	/* Ok. Let's restart timer. */
2687 	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
2688 		sctp_timer_start(SCTP_TIMER_TYPE_PATHMTURAISE, new_inp,
2689 		    stcb, net);
2690 	}
2691 
2692 	SCTP_INP_INFO_WUNLOCK();
2693 	if (new_inp->sctp_tcbhash != NULL) {
2694 		SCTP_HASH_FREE(new_inp->sctp_tcbhash, new_inp->sctp_hashmark);
2695 		new_inp->sctp_tcbhash = NULL;
2696 	}
2697 	if ((new_inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) {
2698 		/* Subset bound, so copy in the laddr list from the old_inp */
2699 		LIST_FOREACH(oladdr, &old_inp->sctp_addr_list, sctp_nxt_addr) {
2700 			laddr = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
2701 			if (laddr == NULL) {
2702 				/*
2703 				 * Gak, what can we do? This assoc is really
2704 				 * HOSED. We probably should send an abort
2705 				 * here.
2706 				 */
2707 				SCTPDBG(SCTP_DEBUG_PCB1, "Association hosed in TCP model, out of laddr memory\n");
2708 				continue;
2709 			}
2710 			SCTP_INCR_LADDR_COUNT();
2711 			memset(laddr, 0, sizeof(*laddr));
2712 			(void)SCTP_GETTIME_TIMEVAL(&laddr->start_time);
2713 			laddr->ifa = oladdr->ifa;
2714 			atomic_add_int(&laddr->ifa->refcount, 1);
2715 			LIST_INSERT_HEAD(&new_inp->sctp_addr_list, laddr,
2716 			    sctp_nxt_addr);
2717 			new_inp->laddr_count++;
2718 			if (oladdr == stcb->asoc.last_used_address) {
2719 				stcb->asoc.last_used_address = laddr;
2720 			}
2721 		}
2722 	}
2723 	/* Now any running timers need to be adjusted. */
2724 	if (stcb->asoc.dack_timer.ep == old_inp) {
2725 		SCTP_INP_DECR_REF(old_inp);
2726 		stcb->asoc.dack_timer.ep = new_inp;
2727 		SCTP_INP_INCR_REF(new_inp);
2728 	}
2729 	if (stcb->asoc.asconf_timer.ep == old_inp) {
2730 		SCTP_INP_DECR_REF(old_inp);
2731 		stcb->asoc.asconf_timer.ep = new_inp;
2732 		SCTP_INP_INCR_REF(new_inp);
2733 	}
2734 	if (stcb->asoc.strreset_timer.ep == old_inp) {
2735 		SCTP_INP_DECR_REF(old_inp);
2736 		stcb->asoc.strreset_timer.ep = new_inp;
2737 		SCTP_INP_INCR_REF(new_inp);
2738 	}
2739 	if (stcb->asoc.shut_guard_timer.ep == old_inp) {
2740 		SCTP_INP_DECR_REF(old_inp);
2741 		stcb->asoc.shut_guard_timer.ep = new_inp;
2742 		SCTP_INP_INCR_REF(new_inp);
2743 	}
2744 	if (stcb->asoc.autoclose_timer.ep == old_inp) {
2745 		SCTP_INP_DECR_REF(old_inp);
2746 		stcb->asoc.autoclose_timer.ep = new_inp;
2747 		SCTP_INP_INCR_REF(new_inp);
2748 	}
2749 	if (stcb->asoc.delete_prim_timer.ep == old_inp) {
2750 		SCTP_INP_DECR_REF(old_inp);
2751 		stcb->asoc.delete_prim_timer.ep = new_inp;
2752 		SCTP_INP_INCR_REF(new_inp);
2753 	}
2754 	/* now what about the nets? */
2755 	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
2756 		if (net->pmtu_timer.ep == old_inp) {
2757 			SCTP_INP_DECR_REF(old_inp);
2758 			net->pmtu_timer.ep = new_inp;
2759 			SCTP_INP_INCR_REF(new_inp);
2760 		}
2761 		if (net->hb_timer.ep == old_inp) {
2762 			SCTP_INP_DECR_REF(old_inp);
2763 			net->hb_timer.ep = new_inp;
2764 			SCTP_INP_INCR_REF(new_inp);
2765 		}
2766 		if (net->rxt_timer.ep == old_inp) {
2767 			SCTP_INP_DECR_REF(old_inp);
2768 			net->rxt_timer.ep = new_inp;
2769 			SCTP_INP_INCR_REF(new_inp);
2770 		}
2771 	}
2772 	SCTP_INP_WUNLOCK(new_inp);
2773 	SCTP_INP_WUNLOCK(old_inp);
2774 }
2775 
2776 /*
2777  * insert an laddr entry with the given ifa for the desired list
2778  */
2779 static int
2780 sctp_insert_laddr(struct sctpladdr *list, struct sctp_ifa *ifa, uint32_t act)
2781 {
2782 	struct sctp_laddr *laddr;
2783 
2784 	laddr = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_laddr), struct sctp_laddr);
2785 	if (laddr == NULL) {
2786 		/* out of memory? */
2787 		SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
2788 		return (EINVAL);
2789 	}
2790 	SCTP_INCR_LADDR_COUNT();
2791 	memset(laddr, 0, sizeof(*laddr));
2792 	(void)SCTP_GETTIME_TIMEVAL(&laddr->start_time);
2793 	laddr->ifa = ifa;
2794 	laddr->action = act;
2795 	atomic_add_int(&ifa->refcount, 1);
2796 	/* insert it */
2797 	LIST_INSERT_HEAD(list, laddr, sctp_nxt_addr);
2798 
2799 	return (0);
2800 }
2801 
2802 /*
2803  * Remove an laddr entry from the local address list (on an assoc)
2804  */
2805 static void
2806 sctp_remove_laddr(struct sctp_laddr *laddr)
2807 {
2808 
2809 	/* remove from the list */
2810 	LIST_REMOVE(laddr, sctp_nxt_addr);
2811 	sctp_free_ifa(laddr->ifa);
2812 	SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_laddr), laddr);
2813 	SCTP_DECR_LADDR_COUNT();
2814 }
2815 
2816 /*
2817  * Bind the socket, with the PCB and global info locks held.  Note, if a
2818  * socket address is specified, the PCB lock may be dropped and re-acquired.
2819  *
2820  * sctp_ifap is used to bypass normal local address validation checks.
2821  */
2822 int
2823 sctp_inpcb_bind_locked(struct sctp_inpcb *inp, struct sockaddr *addr,
2824     struct sctp_ifa *sctp_ifap, struct thread *td)
2825 {
2826 	/* bind a ep to a socket address */
2827 	struct sctppcbhead *head;
2828 	struct sctp_inpcb *inp_tmp;
2829 	struct inpcb *ip_inp;
2830 	int port_reuse_active = 0;
2831 	int bindall;
2832 	uint16_t lport;
2833 	int error;
2834 	uint32_t vrf_id;
2835 
2836 	KASSERT(td != NULL, ("%s: null thread", __func__));
2837 
2838 	error = 0;
2839 	lport = 0;
2840 	bindall = 1;
2841 	ip_inp = &inp->ip_inp.inp;
2842 
2843 	SCTP_INP_INFO_WLOCK_ASSERT();
2844 	SCTP_INP_WLOCK_ASSERT(inp);
2845 
2846 #ifdef SCTP_DEBUG
2847 	if (addr) {
2848 		SCTPDBG(SCTP_DEBUG_PCB1, "Bind called port: %d\n",
2849 		    ntohs(((struct sockaddr_in *)addr)->sin_port));
2850 		SCTPDBG(SCTP_DEBUG_PCB1, "Addr: ");
2851 		SCTPDBG_ADDR(SCTP_DEBUG_PCB1, addr);
2852 	}
2853 #endif
2854 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) == 0) {
2855 		error = EINVAL;
2856 		/* already did a bind, subsequent binds NOT allowed ! */
2857 		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
2858 		goto out;
2859 	}
2860 	if (addr != NULL) {
2861 		switch (addr->sa_family) {
2862 #ifdef INET
2863 		case AF_INET:
2864 			{
2865 				struct sockaddr_in *sin;
2866 
2867 				/* IPV6_V6ONLY socket? */
2868 				if (SCTP_IPV6_V6ONLY(inp)) {
2869 					error = EINVAL;
2870 					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
2871 					goto out;
2872 				}
2873 				if (addr->sa_len != sizeof(*sin)) {
2874 					error = EINVAL;
2875 					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
2876 					goto out;
2877 				}
2878 
2879 				sin = (struct sockaddr_in *)addr;
2880 				lport = sin->sin_port;
2881 				/*
2882 				 * For LOOPBACK the prison_local_ip4() call
2883 				 * will transmute the ip address to the
2884 				 * proper value.
2885 				 */
2886 				if ((error = prison_local_ip4(td->td_ucred, &sin->sin_addr)) != 0) {
2887 					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
2888 					goto out;
2889 				}
2890 				if (sin->sin_addr.s_addr != INADDR_ANY) {
2891 					bindall = 0;
2892 				}
2893 				break;
2894 			}
2895 #endif
2896 #ifdef INET6
2897 		case AF_INET6:
2898 			{
2899 				/*
2900 				 * Only for pure IPv6 Address. (No IPv4
2901 				 * Mapped!)
2902 				 */
2903 				struct sockaddr_in6 *sin6;
2904 
2905 				sin6 = (struct sockaddr_in6 *)addr;
2906 				if (addr->sa_len != sizeof(*sin6)) {
2907 					error = EINVAL;
2908 					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
2909 					goto out;
2910 				}
2911 				lport = sin6->sin6_port;
2912 				/*
2913 				 * For LOOPBACK the prison_local_ip6() call
2914 				 * will transmute the ipv6 address to the
2915 				 * proper value.
2916 				 */
2917 				if ((error = prison_local_ip6(td->td_ucred, &sin6->sin6_addr,
2918 				    (SCTP_IPV6_V6ONLY(inp) != 0))) != 0) {
2919 					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
2920 					goto out;
2921 				}
2922 				if (!IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
2923 					bindall = 0;
2924 					/* KAME hack: embed scopeid */
2925 					if (sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
2926 						error = EINVAL;
2927 						SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
2928 						goto out;
2929 					}
2930 				}
2931 				/* this must be cleared for ifa_ifwithaddr() */
2932 				sin6->sin6_scope_id = 0;
2933 				break;
2934 			}
2935 #endif
2936 		default:
2937 			error = EAFNOSUPPORT;
2938 			SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
2939 			goto out;
2940 		}
2941 	}
2942 	/* Setup a vrf_id to be the default for the non-bind-all case. */
2943 	vrf_id = inp->def_vrf_id;
2944 
2945 	if (lport) {
2946 		/*
2947 		 * Did the caller specify a port? if so we must see if an ep
2948 		 * already has this one bound.
2949 		 */
2950 		/* got to be root to get at low ports */
2951 		if (ntohs(lport) < IPPORT_RESERVED &&
2952 		    (error = priv_check(td, PRIV_NETINET_RESERVEDPORT)) != 0) {
2953 			goto out;
2954 		}
2955 		SCTP_INP_INCR_REF(inp);
2956 		SCTP_INP_WUNLOCK(inp);
2957 		if (bindall) {
2958 			vrf_id = inp->def_vrf_id;
2959 			inp_tmp = sctp_pcb_findep(addr, 0, 1, vrf_id);
2960 			if (inp_tmp != NULL) {
2961 				/*
2962 				 * lock guy returned and lower count note
2963 				 * that we are not bound so inp_tmp should
2964 				 * NEVER be inp. And it is this inp
2965 				 * (inp_tmp) that gets the reference bump,
2966 				 * so we must lower it.
2967 				 */
2968 				SCTP_INP_DECR_REF(inp_tmp);
2969 				/* unlock info */
2970 				if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_PORTREUSE)) &&
2971 				    (sctp_is_feature_on(inp_tmp, SCTP_PCB_FLAGS_PORTREUSE))) {
2972 					/*
2973 					 * Ok, must be one-2-one and
2974 					 * allowing port re-use
2975 					 */
2976 					port_reuse_active = 1;
2977 					goto continue_anyway;
2978 				}
2979 				SCTP_INP_WLOCK(inp);
2980 				SCTP_INP_DECR_REF(inp);
2981 				error = EADDRINUSE;
2982 				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
2983 				goto out;
2984 			}
2985 		} else {
2986 			inp_tmp = sctp_pcb_findep(addr, 0, 1, vrf_id);
2987 			if (inp_tmp != NULL) {
2988 				/*
2989 				 * lock guy returned and lower count note
2990 				 * that we are not bound so inp_tmp should
2991 				 * NEVER be inp. And it is this inp
2992 				 * (inp_tmp) that gets the reference bump,
2993 				 * so we must lower it.
2994 				 */
2995 				SCTP_INP_DECR_REF(inp_tmp);
2996 				/* unlock info */
2997 				if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_PORTREUSE)) &&
2998 				    (sctp_is_feature_on(inp_tmp, SCTP_PCB_FLAGS_PORTREUSE))) {
2999 					/*
3000 					 * Ok, must be one-2-one and
3001 					 * allowing port re-use
3002 					 */
3003 					port_reuse_active = 1;
3004 					goto continue_anyway;
3005 				}
3006 				SCTP_INP_WLOCK(inp);
3007 				SCTP_INP_DECR_REF(inp);
3008 				error = EADDRINUSE;
3009 				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
3010 				goto out;
3011 			}
3012 		}
3013 continue_anyway:
3014 		SCTP_INP_WLOCK(inp);
3015 		SCTP_INP_DECR_REF(inp);
3016 		if (bindall) {
3017 			/* verify that no lport is not used by a singleton */
3018 			if ((port_reuse_active == 0) &&
3019 			    (inp_tmp = sctp_isport_inuse(inp, lport, vrf_id))) {
3020 				/* Sorry someone already has this one bound */
3021 				if ((sctp_is_feature_on(inp, SCTP_PCB_FLAGS_PORTREUSE)) &&
3022 				    (sctp_is_feature_on(inp_tmp, SCTP_PCB_FLAGS_PORTREUSE))) {
3023 					port_reuse_active = 1;
3024 				} else {
3025 					error = EADDRINUSE;
3026 					SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
3027 					goto out;
3028 				}
3029 			}
3030 		}
3031 	} else {
3032 		uint16_t first, last, candidate;
3033 		uint16_t count;
3034 
3035 		if (ip_inp->inp_flags & INP_HIGHPORT) {
3036 			first = MODULE_GLOBAL(ipport_hifirstauto);
3037 			last = MODULE_GLOBAL(ipport_hilastauto);
3038 		} else if (ip_inp->inp_flags & INP_LOWPORT) {
3039 			if ((error = priv_check(td, PRIV_NETINET_RESERVEDPORT)) != 0) {
3040 				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
3041 				goto out;
3042 			}
3043 			first = MODULE_GLOBAL(ipport_lowfirstauto);
3044 			last = MODULE_GLOBAL(ipport_lowlastauto);
3045 		} else {
3046 			first = MODULE_GLOBAL(ipport_firstauto);
3047 			last = MODULE_GLOBAL(ipport_lastauto);
3048 		}
3049 		if (first > last) {
3050 			uint16_t temp;
3051 
3052 			temp = first;
3053 			first = last;
3054 			last = temp;
3055 		}
3056 		count = last - first + 1;	/* number of candidates */
3057 		candidate = first + sctp_select_initial_TSN(&inp->sctp_ep) % (count);
3058 
3059 		for (;;) {
3060 			if (sctp_isport_inuse(inp, htons(candidate), inp->def_vrf_id) == NULL) {
3061 				lport = htons(candidate);
3062 				break;
3063 			}
3064 			if (--count == 0) {
3065 				error = EADDRINUSE;
3066 				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
3067 				goto out;
3068 			}
3069 			if (candidate == last)
3070 				candidate = first;
3071 			else
3072 				candidate = candidate + 1;
3073 		}
3074 	}
3075 	if (inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE |
3076 	    SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
3077 		/*
3078 		 * this really should not happen. The guy did a non-blocking
3079 		 * bind and then did a close at the same time.
3080 		 */
3081 		error = EINVAL;
3082 		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
3083 		goto out;
3084 	}
3085 	/* ok we look clear to give out this port, so lets setup the binding */
3086 	if (bindall) {
3087 		/* binding to all addresses, so just set in the proper flags */
3088 		inp->sctp_flags |= SCTP_PCB_FLAGS_BOUNDALL;
3089 		/* set the automatic addr changes from kernel flag */
3090 		if (SCTP_BASE_SYSCTL(sctp_auto_asconf) == 0) {
3091 			sctp_feature_off(inp, SCTP_PCB_FLAGS_DO_ASCONF);
3092 			sctp_feature_off(inp, SCTP_PCB_FLAGS_AUTO_ASCONF);
3093 		} else {
3094 			sctp_feature_on(inp, SCTP_PCB_FLAGS_DO_ASCONF);
3095 			sctp_feature_on(inp, SCTP_PCB_FLAGS_AUTO_ASCONF);
3096 		}
3097 		if (SCTP_BASE_SYSCTL(sctp_multiple_asconfs) == 0) {
3098 			sctp_feature_off(inp, SCTP_PCB_FLAGS_MULTIPLE_ASCONFS);
3099 		} else {
3100 			sctp_feature_on(inp, SCTP_PCB_FLAGS_MULTIPLE_ASCONFS);
3101 		}
3102 		/*
3103 		 * set the automatic mobility_base from kernel flag (by
3104 		 * micchie)
3105 		 */
3106 		if (SCTP_BASE_SYSCTL(sctp_mobility_base) == 0) {
3107 			sctp_mobility_feature_off(inp, SCTP_MOBILITY_BASE);
3108 			sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
3109 		} else {
3110 			sctp_mobility_feature_on(inp, SCTP_MOBILITY_BASE);
3111 			sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
3112 		}
3113 		/*
3114 		 * set the automatic mobility_fasthandoff from kernel flag
3115 		 * (by micchie)
3116 		 */
3117 		if (SCTP_BASE_SYSCTL(sctp_mobility_fasthandoff) == 0) {
3118 			sctp_mobility_feature_off(inp, SCTP_MOBILITY_FASTHANDOFF);
3119 			sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
3120 		} else {
3121 			sctp_mobility_feature_on(inp, SCTP_MOBILITY_FASTHANDOFF);
3122 			sctp_mobility_feature_off(inp, SCTP_MOBILITY_PRIM_DELETED);
3123 		}
3124 	} else {
3125 		/*
3126 		 * bind specific, make sure flags is off and add a new
3127 		 * address structure to the sctp_addr_list inside the ep
3128 		 * structure.
3129 		 *
3130 		 * We will need to allocate one and insert it at the head.
3131 		 * The socketopt call can just insert new addresses in there
3132 		 * as well. It will also have to do the embed scope kame
3133 		 * hack too (before adding).
3134 		 */
3135 		struct sctp_ifa *ifa;
3136 		union sctp_sockstore store;
3137 
3138 		memset(&store, 0, sizeof(store));
3139 		switch (addr->sa_family) {
3140 #ifdef INET
3141 		case AF_INET:
3142 			memcpy(&store.sin, addr, sizeof(struct sockaddr_in));
3143 			store.sin.sin_port = 0;
3144 			break;
3145 #endif
3146 #ifdef INET6
3147 		case AF_INET6:
3148 			memcpy(&store.sin6, addr, sizeof(struct sockaddr_in6));
3149 			store.sin6.sin6_port = 0;
3150 			break;
3151 #endif
3152 		default:
3153 			break;
3154 		}
3155 		/*
3156 		 * first find the interface with the bound address need to
3157 		 * zero out the port to find the address! yuck! can't do
3158 		 * this earlier since need port for sctp_pcb_findep()
3159 		 */
3160 		if (sctp_ifap != NULL) {
3161 			ifa = sctp_ifap;
3162 		} else {
3163 			/*
3164 			 * Note for BSD we hit here always other O/S's will
3165 			 * pass things in via the sctp_ifap argument.
3166 			 */
3167 			ifa = sctp_find_ifa_by_addr(&store.sa,
3168 			    vrf_id, SCTP_ADDR_NOT_LOCKED);
3169 		}
3170 		if (ifa == NULL) {
3171 			error = EADDRNOTAVAIL;
3172 			/* Can't find an interface with that address */
3173 			SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
3174 			goto out;
3175 		}
3176 #ifdef INET6
3177 		if (addr->sa_family == AF_INET6) {
3178 			/* GAK, more FIXME IFA lock? */
3179 			if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
3180 				/* Can't bind a non-existent addr. */
3181 				error = EINVAL;
3182 				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, error);
3183 				goto out;
3184 			}
3185 		}
3186 #endif
3187 		/* we're not bound all */
3188 		inp->sctp_flags &= ~SCTP_PCB_FLAGS_BOUNDALL;
3189 		/* allow bindx() to send ASCONF's for binding changes */
3190 		sctp_feature_on(inp, SCTP_PCB_FLAGS_DO_ASCONF);
3191 		/* clear automatic addr changes from kernel flag */
3192 		sctp_feature_off(inp, SCTP_PCB_FLAGS_AUTO_ASCONF);
3193 
3194 		/* add this address to the endpoint list */
3195 		error = sctp_insert_laddr(&inp->sctp_addr_list, ifa, 0);
3196 		if (error != 0)
3197 			goto out;
3198 		inp->laddr_count++;
3199 	}
3200 	/* find the bucket */
3201 	if (port_reuse_active) {
3202 		/* Put it into tcp 1-2-1 hash */
3203 		head = &SCTP_BASE_INFO(sctp_tcpephash)[SCTP_PCBHASH_ALLADDR(lport, SCTP_BASE_INFO(hashtcpmark))];
3204 		inp->sctp_flags |= SCTP_PCB_FLAGS_IN_TCPPOOL;
3205 	} else {
3206 		head = &SCTP_BASE_INFO(sctp_ephash)[SCTP_PCBHASH_ALLADDR(lport, SCTP_BASE_INFO(hashmark))];
3207 	}
3208 	/* put it in the bucket */
3209 	LIST_INSERT_HEAD(head, inp, sctp_hash);
3210 	SCTPDBG(SCTP_DEBUG_PCB1, "Main hash to bind at head:%p, bound port:%d - in tcp_pool=%d\n",
3211 	    (void *)head, ntohs(lport), port_reuse_active);
3212 	/* set in the port */
3213 	inp->sctp_lport = lport;
3214 
3215 	/* turn off just the unbound flag */
3216 	KASSERT((inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) != 0,
3217 	    ("%s: inp %p is already bound", __func__, inp));
3218 	inp->sctp_flags &= ~SCTP_PCB_FLAGS_UNBOUND;
3219 out:
3220 	return (error);
3221 }
3222 
3223 int
3224 sctp_inpcb_bind(struct socket *so, struct sockaddr *addr,
3225     struct sctp_ifa *sctp_ifap, struct thread *td)
3226 {
3227 	struct sctp_inpcb *inp;
3228 	int error;
3229 
3230 	inp = so->so_pcb;
3231 	SCTP_INP_INFO_WLOCK();
3232 	SCTP_INP_WLOCK(inp);
3233 	error = sctp_inpcb_bind_locked(inp, addr, sctp_ifap, td);
3234 	SCTP_INP_WUNLOCK(inp);
3235 	SCTP_INP_INFO_WUNLOCK();
3236 	return (error);
3237 }
3238 
3239 static void
3240 sctp_iterator_inp_being_freed(struct sctp_inpcb *inp)
3241 {
3242 	struct sctp_iterator *it, *nit;
3243 
3244 	/*
3245 	 * We enter with the only the ITERATOR_LOCK in place and a write
3246 	 * lock on the inp_info stuff.
3247 	 */
3248 	it = sctp_it_ctl.cur_it;
3249 	if (it && (it->vn != curvnet)) {
3250 		/* Its not looking at our VNET */
3251 		return;
3252 	}
3253 	if (it && (it->inp == inp)) {
3254 		/*
3255 		 * This is tricky and we hold the iterator lock, but when it
3256 		 * returns and gets the lock (when we release it) the
3257 		 * iterator will try to operate on inp. We need to stop that
3258 		 * from happening. But of course the iterator has a
3259 		 * reference on the stcb and inp. We can mark it and it will
3260 		 * stop.
3261 		 *
3262 		 * If its a single iterator situation, we set the end
3263 		 * iterator flag. Otherwise we set the iterator to go to the
3264 		 * next inp.
3265 		 *
3266 		 */
3267 		if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) {
3268 			sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_STOP_CUR_IT;
3269 		} else {
3270 			sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_STOP_CUR_INP;
3271 		}
3272 	}
3273 	/*
3274 	 * Now go through and remove any single reference to our inp that
3275 	 * may be still pending on the list
3276 	 */
3277 	SCTP_IPI_ITERATOR_WQ_LOCK();
3278 	TAILQ_FOREACH_SAFE(it, &sctp_it_ctl.iteratorhead, sctp_nxt_itr, nit) {
3279 		if (it->vn != curvnet) {
3280 			continue;
3281 		}
3282 		if (it->inp == inp) {
3283 			/* This one points to me is it inp specific? */
3284 			if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) {
3285 				/* Remove and free this one */
3286 				TAILQ_REMOVE(&sctp_it_ctl.iteratorhead,
3287 				    it, sctp_nxt_itr);
3288 				if (it->function_atend != NULL) {
3289 					(*it->function_atend) (it->pointer, it->val);
3290 				}
3291 				SCTP_FREE(it, SCTP_M_ITER);
3292 			} else {
3293 				it->inp = LIST_NEXT(it->inp, sctp_list);
3294 				if (it->inp) {
3295 					SCTP_INP_INCR_REF(it->inp);
3296 				}
3297 			}
3298 			/*
3299 			 * When its put in the refcnt is incremented so decr
3300 			 * it
3301 			 */
3302 			SCTP_INP_DECR_REF(inp);
3303 		}
3304 	}
3305 	SCTP_IPI_ITERATOR_WQ_UNLOCK();
3306 }
3307 
3308 /* release sctp_inpcb unbind the port */
3309 void
3310 sctp_inpcb_free(struct sctp_inpcb *inp, int immediate, int from)
3311 {
3312 	/*
3313 	 * Here we free a endpoint. We must find it (if it is in the Hash
3314 	 * table) and remove it from there. Then we must also find it in the
3315 	 * overall list and remove it from there. After all removals are
3316 	 * complete then any timer has to be stopped. Then start the actual
3317 	 * freeing. a) Any local lists. b) Any associations. c) The hash of
3318 	 * all associations. d) finally the ep itself.
3319 	 */
3320 	struct sctp_tcb *stcb, *nstcb;
3321 	struct sctp_laddr *laddr, *nladdr;
3322 	struct inpcb *ip_pcb;
3323 	struct socket *so;
3324 	int being_refed = 0;
3325 	struct sctp_queued_to_read *sq, *nsq;
3326 	int cnt;
3327 	sctp_sharedkey_t *shared_key, *nshared_key;
3328 
3329 #ifdef SCTP_LOG_CLOSING
3330 	sctp_log_closing(inp, NULL, 0);
3331 #endif
3332 	SCTP_ITERATOR_LOCK();
3333 	/* mark any iterators on the list or being processed */
3334 	sctp_iterator_inp_being_freed(inp);
3335 	SCTP_ITERATOR_UNLOCK();
3336 
3337 	SCTP_ASOC_CREATE_LOCK(inp);
3338 	SCTP_INP_INFO_WLOCK();
3339 	SCTP_INP_WLOCK(inp);
3340 	so = inp->sctp_socket;
3341 	KASSERT((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) != 0,
3342 	    ("%s: inp %p still has socket", __func__, inp));
3343 	KASSERT((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) == 0,
3344 	    ("%s: double free of inp %p", __func__, inp));
3345 	if (from == SCTP_CALLED_AFTER_CMPSET_OFCLOSE) {
3346 		inp->sctp_flags &= ~SCTP_PCB_FLAGS_CLOSE_IP;
3347 		/* socket is gone, so no more wakeups allowed */
3348 		inp->sctp_flags |= SCTP_PCB_FLAGS_DONT_WAKE;
3349 		inp->sctp_flags &= ~SCTP_PCB_FLAGS_WAKEINPUT;
3350 		inp->sctp_flags &= ~SCTP_PCB_FLAGS_WAKEOUTPUT;
3351 	}
3352 	/* First time through we have the socket lock, after that no more. */
3353 	sctp_timer_stop(SCTP_TIMER_TYPE_NEWCOOKIE, inp, NULL, NULL,
3354 	    SCTP_FROM_SCTP_PCB + SCTP_LOC_1);
3355 
3356 	if (inp->control) {
3357 		sctp_m_freem(inp->control);
3358 		inp->control = NULL;
3359 	}
3360 	if (inp->pkt) {
3361 		sctp_m_freem(inp->pkt);
3362 		inp->pkt = NULL;
3363 	}
3364 	ip_pcb = &inp->ip_inp.inp;	/* we could just cast the main pointer
3365 					 * here but I will be nice :> (i.e.
3366 					 * ip_pcb = ep;) */
3367 	if (immediate == SCTP_FREE_SHOULD_USE_GRACEFUL_CLOSE) {
3368 		int cnt_in_sd;
3369 
3370 		cnt_in_sd = 0;
3371 		LIST_FOREACH_SAFE(stcb, &inp->sctp_asoc_list, sctp_tcblist, nstcb) {
3372 			SCTP_TCB_LOCK(stcb);
3373 			/* Disconnect the socket please. */
3374 			stcb->sctp_socket = NULL;
3375 			SCTP_ADD_SUBSTATE(stcb, SCTP_STATE_CLOSED_SOCKET);
3376 			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
3377 				/* Skip guys being freed */
3378 				cnt_in_sd++;
3379 				if (stcb->asoc.state & SCTP_STATE_IN_ACCEPT_QUEUE) {
3380 					/*
3381 					 * Special case - we did not start a
3382 					 * kill timer on the asoc due to it
3383 					 * was not closed. So go ahead and
3384 					 * start it now.
3385 					 */
3386 					SCTP_CLEAR_SUBSTATE(stcb, SCTP_STATE_IN_ACCEPT_QUEUE);
3387 					sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL);
3388 				}
3389 				SCTP_TCB_UNLOCK(stcb);
3390 				continue;
3391 			}
3392 			if (((SCTP_GET_STATE(stcb) == SCTP_STATE_COOKIE_WAIT) ||
3393 			    (SCTP_GET_STATE(stcb) == SCTP_STATE_COOKIE_ECHOED)) &&
3394 			    (stcb->asoc.total_output_queue_size == 0)) {
3395 				/*
3396 				 * If we have data in queue, we don't want
3397 				 * to just free since the app may have done,
3398 				 * send()/close or connect/send/close. And
3399 				 * it wants the data to get across first.
3400 				 */
3401 				/* Just abandon things in the front states */
3402 				if (sctp_free_assoc(inp, stcb, SCTP_PCBFREE_NOFORCE,
3403 				    SCTP_FROM_SCTP_PCB + SCTP_LOC_2) == 0) {
3404 					cnt_in_sd++;
3405 				}
3406 				continue;
3407 			}
3408 			if ((stcb->asoc.size_on_reasm_queue > 0) ||
3409 			    (stcb->asoc.control_pdapi) ||
3410 			    (stcb->asoc.size_on_all_streams > 0) ||
3411 			    ((so != NULL) && (SCTP_SBAVAIL(&so->so_rcv) > 0))) {
3412 				/* Left with Data unread */
3413 				struct mbuf *op_err;
3414 
3415 				op_err = sctp_generate_cause(SCTP_CAUSE_USER_INITIATED_ABT, "");
3416 				stcb->sctp_ep->last_abort_code = SCTP_FROM_SCTP_PCB + SCTP_LOC_3;
3417 				sctp_send_abort_tcb(stcb, op_err, SCTP_SO_LOCKED);
3418 				SCTP_STAT_INCR_COUNTER32(sctps_aborted);
3419 				if ((SCTP_GET_STATE(stcb) == SCTP_STATE_OPEN) ||
3420 				    (SCTP_GET_STATE(stcb) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
3421 					SCTP_STAT_DECR_GAUGE32(sctps_currestab);
3422 				}
3423 				if (sctp_free_assoc(inp, stcb,
3424 				    SCTP_PCBFREE_NOFORCE, SCTP_FROM_SCTP_PCB + SCTP_LOC_4) == 0) {
3425 					cnt_in_sd++;
3426 				}
3427 				continue;
3428 			} else if (TAILQ_EMPTY(&stcb->asoc.send_queue) &&
3429 				    TAILQ_EMPTY(&stcb->asoc.sent_queue) &&
3430 			    (stcb->asoc.stream_queue_cnt == 0)) {
3431 				if ((*stcb->asoc.ss_functions.sctp_ss_is_user_msgs_incomplete) (stcb, &stcb->asoc)) {
3432 					goto abort_anyway;
3433 				}
3434 				if ((SCTP_GET_STATE(stcb) != SCTP_STATE_SHUTDOWN_SENT) &&
3435 				    (SCTP_GET_STATE(stcb) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
3436 					struct sctp_nets *netp;
3437 
3438 					/*
3439 					 * there is nothing queued to send,
3440 					 * so I send shutdown
3441 					 */
3442 					if ((SCTP_GET_STATE(stcb) == SCTP_STATE_OPEN) ||
3443 					    (SCTP_GET_STATE(stcb) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
3444 						SCTP_STAT_DECR_GAUGE32(sctps_currestab);
3445 					}
3446 					SCTP_SET_STATE(stcb, SCTP_STATE_SHUTDOWN_SENT);
3447 					sctp_stop_timers_for_shutdown(stcb);
3448 					if (stcb->asoc.alternate) {
3449 						netp = stcb->asoc.alternate;
3450 					} else {
3451 						netp = stcb->asoc.primary_destination;
3452 					}
3453 					sctp_send_shutdown(stcb, netp);
3454 					sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, stcb->sctp_ep, stcb,
3455 					    netp);
3456 					sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb, NULL);
3457 					sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_SHUT_TMR, SCTP_SO_LOCKED);
3458 				}
3459 			} else {
3460 				/* mark into shutdown pending */
3461 				SCTP_ADD_SUBSTATE(stcb, SCTP_STATE_SHUTDOWN_PENDING);
3462 				if ((*stcb->asoc.ss_functions.sctp_ss_is_user_msgs_incomplete) (stcb, &stcb->asoc)) {
3463 					SCTP_ADD_SUBSTATE(stcb, SCTP_STATE_PARTIAL_MSG_LEFT);
3464 				}
3465 				if (TAILQ_EMPTY(&stcb->asoc.send_queue) &&
3466 				    TAILQ_EMPTY(&stcb->asoc.sent_queue) &&
3467 				    (stcb->asoc.state & SCTP_STATE_PARTIAL_MSG_LEFT)) {
3468 					struct mbuf *op_err;
3469 
3470 			abort_anyway:
3471 					op_err = sctp_generate_cause(SCTP_CAUSE_USER_INITIATED_ABT, "");
3472 					stcb->sctp_ep->last_abort_code = SCTP_FROM_SCTP_PCB + SCTP_LOC_5;
3473 					sctp_send_abort_tcb(stcb, op_err, SCTP_SO_LOCKED);
3474 					SCTP_STAT_INCR_COUNTER32(sctps_aborted);
3475 					if ((SCTP_GET_STATE(stcb) == SCTP_STATE_OPEN) ||
3476 					    (SCTP_GET_STATE(stcb) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
3477 						SCTP_STAT_DECR_GAUGE32(sctps_currestab);
3478 					}
3479 					if (sctp_free_assoc(inp, stcb,
3480 					    SCTP_PCBFREE_NOFORCE,
3481 					    SCTP_FROM_SCTP_PCB + SCTP_LOC_6) == 0) {
3482 						cnt_in_sd++;
3483 					}
3484 					continue;
3485 				} else {
3486 					sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_CLOSING, SCTP_SO_LOCKED);
3487 				}
3488 			}
3489 			cnt_in_sd++;
3490 			SCTP_TCB_UNLOCK(stcb);
3491 		}
3492 		/* now is there some left in our SHUTDOWN state? */
3493 		if (cnt_in_sd) {
3494 #ifdef SCTP_LOG_CLOSING
3495 			sctp_log_closing(inp, NULL, 2);
3496 #endif
3497 			inp->sctp_socket = NULL;
3498 			SCTP_INP_WUNLOCK(inp);
3499 			SCTP_ASOC_CREATE_UNLOCK(inp);
3500 			SCTP_INP_INFO_WUNLOCK();
3501 			return;
3502 		}
3503 	}
3504 	inp->sctp_socket = NULL;
3505 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) == 0) {
3506 		/*
3507 		 * ok, this guy has been bound. It's port is somewhere in
3508 		 * the SCTP_BASE_INFO(hash table). Remove it!
3509 		 */
3510 		LIST_REMOVE(inp, sctp_hash);
3511 		inp->sctp_flags |= SCTP_PCB_FLAGS_UNBOUND;
3512 	}
3513 
3514 	/*
3515 	 * If there is a timer running to kill us, forget it, since it may
3516 	 * have a contest on the INP lock.. which would cause us to die ...
3517 	 */
3518 	cnt = 0;
3519 	LIST_FOREACH_SAFE(stcb, &inp->sctp_asoc_list, sctp_tcblist, nstcb) {
3520 		SCTP_TCB_LOCK(stcb);
3521 		if (immediate != SCTP_FREE_SHOULD_USE_GRACEFUL_CLOSE) {
3522 			/* Disconnect the socket please */
3523 			stcb->sctp_socket = NULL;
3524 			SCTP_ADD_SUBSTATE(stcb, SCTP_STATE_CLOSED_SOCKET);
3525 		}
3526 		if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
3527 			if (stcb->asoc.state & SCTP_STATE_IN_ACCEPT_QUEUE) {
3528 				SCTP_CLEAR_SUBSTATE(stcb, SCTP_STATE_IN_ACCEPT_QUEUE);
3529 				sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL);
3530 			}
3531 			cnt++;
3532 			SCTP_TCB_UNLOCK(stcb);
3533 			continue;
3534 		}
3535 		/* Free associations that are NOT killing us */
3536 		if ((SCTP_GET_STATE(stcb) != SCTP_STATE_COOKIE_WAIT) &&
3537 		    ((stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) == 0)) {
3538 			struct mbuf *op_err;
3539 
3540 			op_err = sctp_generate_cause(SCTP_CAUSE_USER_INITIATED_ABT, "");
3541 			stcb->sctp_ep->last_abort_code = SCTP_FROM_SCTP_PCB + SCTP_LOC_7;
3542 			sctp_send_abort_tcb(stcb, op_err, SCTP_SO_LOCKED);
3543 			SCTP_STAT_INCR_COUNTER32(sctps_aborted);
3544 		} else if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
3545 			cnt++;
3546 			SCTP_TCB_UNLOCK(stcb);
3547 			continue;
3548 		}
3549 		if ((SCTP_GET_STATE(stcb) == SCTP_STATE_OPEN) ||
3550 		    (SCTP_GET_STATE(stcb) == SCTP_STATE_SHUTDOWN_RECEIVED)) {
3551 			SCTP_STAT_DECR_GAUGE32(sctps_currestab);
3552 		}
3553 		if (sctp_free_assoc(inp, stcb, SCTP_PCBFREE_FORCE,
3554 		    SCTP_FROM_SCTP_PCB + SCTP_LOC_8) == 0) {
3555 			cnt++;
3556 		}
3557 	}
3558 	if (cnt) {
3559 		/* Ok we have someone out there that will kill us */
3560 #ifdef SCTP_LOG_CLOSING
3561 		sctp_log_closing(inp, NULL, 3);
3562 #endif
3563 		SCTP_INP_WUNLOCK(inp);
3564 		SCTP_ASOC_CREATE_UNLOCK(inp);
3565 		SCTP_INP_INFO_WUNLOCK();
3566 		return;
3567 	}
3568 	if (SCTP_INP_LOCK_CONTENDED(inp))
3569 		being_refed++;
3570 	if (SCTP_INP_READ_CONTENDED(inp))
3571 		being_refed++;
3572 	if (SCTP_ASOC_CREATE_LOCK_CONTENDED(inp))
3573 		being_refed++;
3574 	/* NOTE: 0 refcount also means no timers are referencing us. */
3575 	if ((inp->refcount) ||
3576 	    (being_refed) ||
3577 	    (inp->sctp_flags & SCTP_PCB_FLAGS_CLOSE_IP)) {
3578 #ifdef SCTP_LOG_CLOSING
3579 		sctp_log_closing(inp, NULL, 4);
3580 #endif
3581 		sctp_timer_start(SCTP_TIMER_TYPE_INPKILL, inp, NULL, NULL);
3582 		SCTP_INP_WUNLOCK(inp);
3583 		SCTP_ASOC_CREATE_UNLOCK(inp);
3584 		SCTP_INP_INFO_WUNLOCK();
3585 		return;
3586 	}
3587 	inp->sctp_ep.signature_change.type = 0;
3588 	inp->sctp_flags |= SCTP_PCB_FLAGS_SOCKET_ALLGONE;
3589 	/*
3590 	 * Remove it from the list .. last thing we need a lock for.
3591 	 */
3592 	LIST_REMOVE(inp, sctp_list);
3593 	SCTP_INP_WUNLOCK(inp);
3594 	SCTP_ASOC_CREATE_UNLOCK(inp);
3595 	SCTP_INP_INFO_WUNLOCK();
3596 
3597 #ifdef SCTP_LOG_CLOSING
3598 	sctp_log_closing(inp, NULL, 5);
3599 #endif
3600 	if ((inp->sctp_asocidhash) != NULL) {
3601 		SCTP_HASH_FREE(inp->sctp_asocidhash, inp->hashasocidmark);
3602 		inp->sctp_asocidhash = NULL;
3603 	}
3604 	/* sa_ignore FREED_MEMORY */
3605 	TAILQ_FOREACH_SAFE(sq, &inp->read_queue, next, nsq) {
3606 		/* Its only abandoned if it had data left */
3607 		if (sq->length)
3608 			SCTP_STAT_INCR(sctps_left_abandon);
3609 
3610 		TAILQ_REMOVE(&inp->read_queue, sq, next);
3611 		sctp_free_remote_addr(sq->whoFrom);
3612 		if (so)
3613 			SCTP_SB_DECR(&so->so_rcv, sq->length);
3614 		if (sq->data) {
3615 			sctp_m_freem(sq->data);
3616 			sq->data = NULL;
3617 		}
3618 		/*
3619 		 * no need to free the net count, since at this point all
3620 		 * assoc's are gone.
3621 		 */
3622 		sctp_free_a_readq(NULL, sq);
3623 	}
3624 	/* Now the sctp_pcb things */
3625 	/*
3626 	 * free each asoc if it is not already closed/free. we can't use the
3627 	 * macro here since le_next will get freed as part of the
3628 	 * sctp_free_assoc() call.
3629 	 */
3630 	if (ip_pcb->inp_options) {
3631 		(void)sctp_m_free(ip_pcb->inp_options);
3632 		ip_pcb->inp_options = 0;
3633 	}
3634 #ifdef INET6
3635 	if (ip_pcb->inp_vflag & INP_IPV6) {
3636 		ip6_freepcbopts(ip_pcb->in6p_outputopts);
3637 	}
3638 #endif				/* INET6 */
3639 	ip_pcb->inp_vflag = 0;
3640 	/* free up authentication fields */
3641 	if (inp->sctp_ep.local_auth_chunks != NULL)
3642 		sctp_free_chunklist(inp->sctp_ep.local_auth_chunks);
3643 	if (inp->sctp_ep.local_hmacs != NULL)
3644 		sctp_free_hmaclist(inp->sctp_ep.local_hmacs);
3645 
3646 	LIST_FOREACH_SAFE(shared_key, &inp->sctp_ep.shared_keys, next, nshared_key) {
3647 		LIST_REMOVE(shared_key, next);
3648 		sctp_free_sharedkey(shared_key);
3649 		/* sa_ignore FREED_MEMORY */
3650 	}
3651 
3652 	/*
3653 	 * if we have an address list the following will free the list of
3654 	 * ifaddr's that are set into this ep. Again macro limitations here,
3655 	 * since the LIST_FOREACH could be a bad idea.
3656 	 */
3657 	LIST_FOREACH_SAFE(laddr, &inp->sctp_addr_list, sctp_nxt_addr, nladdr) {
3658 		sctp_remove_laddr(laddr);
3659 	}
3660 
3661 #ifdef SCTP_TRACK_FREED_ASOCS
3662 	/* TEMP CODE */
3663 	LIST_FOREACH_SAFE(stcb, &inp->sctp_asoc_free_list, sctp_tcblist, nstcb) {
3664 		LIST_REMOVE(stcb, sctp_tcblist);
3665 		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
3666 		SCTP_DECR_ASOC_COUNT();
3667 	}
3668 	/* *** END TEMP CODE *** */
3669 #endif
3670 	/* Now lets see about freeing the EP hash table. */
3671 	if (inp->sctp_tcbhash != NULL) {
3672 		SCTP_HASH_FREE(inp->sctp_tcbhash, inp->sctp_hashmark);
3673 		inp->sctp_tcbhash = NULL;
3674 	}
3675 	/* Now we must put the ep memory back into the zone pool */
3676 	crfree(inp->ip_inp.inp.inp_cred);
3677 	INP_LOCK_DESTROY(&inp->ip_inp.inp);
3678 	SCTP_INP_LOCK_DESTROY(inp);
3679 	SCTP_INP_READ_LOCK_DESTROY(inp);
3680 	SCTP_ASOC_CREATE_LOCK_DESTROY(inp);
3681 	SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_ep), inp);
3682 	SCTP_DECR_EP_COUNT();
3683 }
3684 
3685 struct sctp_nets *
3686 sctp_findnet(struct sctp_tcb *stcb, struct sockaddr *addr)
3687 {
3688 	struct sctp_nets *net;
3689 
3690 	/* locate the address */
3691 	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
3692 		if (sctp_cmpaddr(addr, (struct sockaddr *)&net->ro._l_addr))
3693 			return (net);
3694 	}
3695 	return (NULL);
3696 }
3697 
3698 int
3699 sctp_is_address_on_local_host(struct sockaddr *addr, uint32_t vrf_id)
3700 {
3701 	struct sctp_ifa *sctp_ifa;
3702 
3703 	sctp_ifa = sctp_find_ifa_by_addr(addr, vrf_id, SCTP_ADDR_NOT_LOCKED);
3704 	if (sctp_ifa) {
3705 		return (1);
3706 	} else {
3707 		return (0);
3708 	}
3709 }
3710 
3711 /*
3712  * add's a remote endpoint address, done with the INIT/INIT-ACK as well as
3713  * when a ASCONF arrives that adds it. It will also initialize all the cwnd
3714  * stats of stuff.
3715  */
3716 int
3717 sctp_add_remote_addr(struct sctp_tcb *stcb, struct sockaddr *newaddr,
3718     struct sctp_nets **netp, uint16_t port, int set_scope, int from)
3719 {
3720 	/*
3721 	 * The following is redundant to the same lines in the
3722 	 * sctp_aloc_assoc() but is needed since others call the add address
3723 	 * function
3724 	 */
3725 	struct sctp_nets *net, *netfirst;
3726 	int addr_inscope;
3727 
3728 	SCTPDBG(SCTP_DEBUG_PCB1, "Adding an address (from:%d) to the peer: ",
3729 	    from);
3730 	SCTPDBG_ADDR(SCTP_DEBUG_PCB1, newaddr);
3731 
3732 	netfirst = sctp_findnet(stcb, newaddr);
3733 	if (netfirst) {
3734 		/*
3735 		 * Lie and return ok, we don't want to make the association
3736 		 * go away for this behavior. It will happen in the TCP
3737 		 * model in a connected socket. It does not reach the hash
3738 		 * table until after the association is built so it can't be
3739 		 * found. Mark as reachable, since the initial creation will
3740 		 * have been cleared and the NOT_IN_ASSOC flag will have
3741 		 * been added... and we don't want to end up removing it
3742 		 * back out.
3743 		 */
3744 		if (netfirst->dest_state & SCTP_ADDR_UNCONFIRMED) {
3745 			netfirst->dest_state = (SCTP_ADDR_REACHABLE |
3746 			    SCTP_ADDR_UNCONFIRMED);
3747 		} else {
3748 			netfirst->dest_state = SCTP_ADDR_REACHABLE;
3749 		}
3750 
3751 		return (0);
3752 	}
3753 	addr_inscope = 1;
3754 	switch (newaddr->sa_family) {
3755 #ifdef INET
3756 	case AF_INET:
3757 		{
3758 			struct sockaddr_in *sin;
3759 
3760 			sin = (struct sockaddr_in *)newaddr;
3761 			if (sin->sin_addr.s_addr == 0) {
3762 				/* Invalid address */
3763 				return (-1);
3764 			}
3765 			/* zero out the zero area */
3766 			memset(&sin->sin_zero, 0, sizeof(sin->sin_zero));
3767 
3768 			/* assure len is set */
3769 			sin->sin_len = sizeof(struct sockaddr_in);
3770 			if (set_scope) {
3771 				if (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) {
3772 					stcb->asoc.scope.ipv4_local_scope = 1;
3773 				}
3774 			} else {
3775 				/* Validate the address is in scope */
3776 				if ((IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) &&
3777 				    (stcb->asoc.scope.ipv4_local_scope == 0)) {
3778 					addr_inscope = 0;
3779 				}
3780 			}
3781 			break;
3782 		}
3783 #endif
3784 #ifdef INET6
3785 	case AF_INET6:
3786 		{
3787 			struct sockaddr_in6 *sin6;
3788 
3789 			sin6 = (struct sockaddr_in6 *)newaddr;
3790 			if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
3791 				/* Invalid address */
3792 				return (-1);
3793 			}
3794 			/* assure len is set */
3795 			sin6->sin6_len = sizeof(struct sockaddr_in6);
3796 			if (set_scope) {
3797 				if (sctp_is_address_on_local_host(newaddr, stcb->asoc.vrf_id)) {
3798 					stcb->asoc.scope.loopback_scope = 1;
3799 					stcb->asoc.scope.local_scope = 0;
3800 					stcb->asoc.scope.ipv4_local_scope = 1;
3801 					stcb->asoc.scope.site_scope = 1;
3802 				} else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
3803 					/*
3804 					 * If the new destination is a
3805 					 * LINK_LOCAL we must have common
3806 					 * site scope. Don't set the local
3807 					 * scope since we may not share all
3808 					 * links, only loopback can do this.
3809 					 * Links on the local network would
3810 					 * also be on our private network
3811 					 * for v4 too.
3812 					 */
3813 					stcb->asoc.scope.ipv4_local_scope = 1;
3814 					stcb->asoc.scope.site_scope = 1;
3815 				} else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr)) {
3816 					/*
3817 					 * If the new destination is
3818 					 * SITE_LOCAL then we must have site
3819 					 * scope in common.
3820 					 */
3821 					stcb->asoc.scope.site_scope = 1;
3822 				}
3823 			} else {
3824 				/* Validate the address is in scope */
3825 				if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr) &&
3826 				    (stcb->asoc.scope.loopback_scope == 0)) {
3827 					addr_inscope = 0;
3828 				} else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr) &&
3829 				    (stcb->asoc.scope.local_scope == 0)) {
3830 					addr_inscope = 0;
3831 				} else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr) &&
3832 				    (stcb->asoc.scope.site_scope == 0)) {
3833 					addr_inscope = 0;
3834 				}
3835 			}
3836 			break;
3837 		}
3838 #endif
3839 	default:
3840 		/* not supported family type */
3841 		return (-1);
3842 	}
3843 	net = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_net), struct sctp_nets);
3844 	if (net == NULL) {
3845 		return (-1);
3846 	}
3847 	SCTP_INCR_RADDR_COUNT();
3848 	memset(net, 0, sizeof(struct sctp_nets));
3849 	(void)SCTP_GETTIME_TIMEVAL(&net->start_time);
3850 	memcpy(&net->ro._l_addr, newaddr, newaddr->sa_len);
3851 	switch (newaddr->sa_family) {
3852 #ifdef INET
3853 	case AF_INET:
3854 		((struct sockaddr_in *)&net->ro._l_addr)->sin_port = stcb->rport;
3855 		break;
3856 #endif
3857 #ifdef INET6
3858 	case AF_INET6:
3859 		((struct sockaddr_in6 *)&net->ro._l_addr)->sin6_port = stcb->rport;
3860 		break;
3861 #endif
3862 	default:
3863 		break;
3864 	}
3865 	net->addr_is_local = sctp_is_address_on_local_host(newaddr, stcb->asoc.vrf_id);
3866 	if (net->addr_is_local && ((set_scope || (from == SCTP_ADDR_IS_CONFIRMED)))) {
3867 		stcb->asoc.scope.loopback_scope = 1;
3868 		stcb->asoc.scope.ipv4_local_scope = 1;
3869 		stcb->asoc.scope.local_scope = 0;
3870 		stcb->asoc.scope.site_scope = 1;
3871 		addr_inscope = 1;
3872 	}
3873 	net->failure_threshold = stcb->asoc.def_net_failure;
3874 	net->pf_threshold = stcb->asoc.def_net_pf_threshold;
3875 	if (addr_inscope == 0) {
3876 		net->dest_state = (SCTP_ADDR_REACHABLE |
3877 		    SCTP_ADDR_OUT_OF_SCOPE);
3878 	} else {
3879 		if (from == SCTP_ADDR_IS_CONFIRMED)
3880 			/* SCTP_ADDR_IS_CONFIRMED is passed by connect_x */
3881 			net->dest_state = SCTP_ADDR_REACHABLE;
3882 		else
3883 			net->dest_state = SCTP_ADDR_REACHABLE |
3884 			    SCTP_ADDR_UNCONFIRMED;
3885 	}
3886 	/*
3887 	 * We set this to 0, the timer code knows that this means its an
3888 	 * initial value
3889 	 */
3890 	net->rto_needed = 1;
3891 	net->RTO = 0;
3892 	net->RTO_measured = 0;
3893 	stcb->asoc.numnets++;
3894 	net->ref_count = 1;
3895 	net->cwr_window_tsn = net->last_cwr_tsn = stcb->asoc.sending_seq - 1;
3896 	net->port = port;
3897 	net->dscp = stcb->asoc.default_dscp;
3898 #ifdef INET6
3899 	net->flowlabel = stcb->asoc.default_flowlabel;
3900 #endif
3901 	if (sctp_stcb_is_feature_on(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_DONOT_HEARTBEAT)) {
3902 		net->dest_state |= SCTP_ADDR_NOHB;
3903 	} else {
3904 		net->dest_state &= ~SCTP_ADDR_NOHB;
3905 	}
3906 	if (sctp_stcb_is_feature_on(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_DO_NOT_PMTUD)) {
3907 		net->dest_state |= SCTP_ADDR_NO_PMTUD;
3908 	} else {
3909 		net->dest_state &= ~SCTP_ADDR_NO_PMTUD;
3910 	}
3911 	net->heart_beat_delay = stcb->asoc.heart_beat_delay;
3912 	/* Init the timer structure */
3913 	SCTP_OS_TIMER_INIT(&net->rxt_timer.timer);
3914 	SCTP_OS_TIMER_INIT(&net->pmtu_timer.timer);
3915 	SCTP_OS_TIMER_INIT(&net->hb_timer.timer);
3916 
3917 	/* Now generate a route for this guy */
3918 #ifdef INET6
3919 	/* KAME hack: embed scopeid */
3920 	if (newaddr->sa_family == AF_INET6) {
3921 		struct sockaddr_in6 *sin6;
3922 
3923 		sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
3924 		(void)sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone));
3925 		sin6->sin6_scope_id = 0;
3926 	}
3927 #endif
3928 	SCTP_RTALLOC((sctp_route_t *)&net->ro,
3929 	    stcb->asoc.vrf_id,
3930 	    stcb->sctp_ep->fibnum);
3931 
3932 	net->src_addr_selected = 0;
3933 	if (SCTP_ROUTE_HAS_VALID_IFN(&net->ro)) {
3934 		/* Get source address */
3935 		net->ro._s_addr = sctp_source_address_selection(stcb->sctp_ep,
3936 		    stcb,
3937 		    (sctp_route_t *)&net->ro,
3938 		    net,
3939 		    0,
3940 		    stcb->asoc.vrf_id);
3941 		if (stcb->asoc.default_mtu > 0) {
3942 			net->mtu = stcb->asoc.default_mtu;
3943 			switch (net->ro._l_addr.sa.sa_family) {
3944 #ifdef INET
3945 			case AF_INET:
3946 				net->mtu += SCTP_MIN_V4_OVERHEAD;
3947 				break;
3948 #endif
3949 #ifdef INET6
3950 			case AF_INET6:
3951 				net->mtu += SCTP_MIN_OVERHEAD;
3952 				break;
3953 #endif
3954 			default:
3955 				break;
3956 			}
3957 #if defined(INET) || defined(INET6)
3958 			if (net->port) {
3959 				net->mtu += (uint32_t)sizeof(struct udphdr);
3960 			}
3961 #endif
3962 		} else if (net->ro._s_addr != NULL) {
3963 			uint32_t imtu, rmtu, hcmtu;
3964 
3965 			net->src_addr_selected = 1;
3966 			/* Now get the interface MTU */
3967 			if (net->ro._s_addr->ifn_p != NULL) {
3968 				/*
3969 				 * XXX: Should we here just use
3970 				 * net->ro._s_addr->ifn_p->ifn_mtu
3971 				 */
3972 				imtu = SCTP_GATHER_MTU_FROM_IFN_INFO(net->ro._s_addr->ifn_p->ifn_p,
3973 				    net->ro._s_addr->ifn_p->ifn_index);
3974 			} else {
3975 				imtu = 0;
3976 			}
3977 			rmtu = SCTP_GATHER_MTU_FROM_ROUTE(net->ro._s_addr, &net->ro._l_addr.sa, net->ro.ro_nh);
3978 			hcmtu = sctp_hc_get_mtu(&net->ro._l_addr, stcb->sctp_ep->fibnum);
3979 			net->mtu = sctp_min_mtu(hcmtu, rmtu, imtu);
3980 		}
3981 	}
3982 	if (net->mtu == 0) {
3983 		if (stcb->asoc.default_mtu > 0) {
3984 			net->mtu = stcb->asoc.default_mtu;
3985 			switch (net->ro._l_addr.sa.sa_family) {
3986 #ifdef INET
3987 			case AF_INET:
3988 				net->mtu += SCTP_MIN_V4_OVERHEAD;
3989 				break;
3990 #endif
3991 #ifdef INET6
3992 			case AF_INET6:
3993 				net->mtu += SCTP_MIN_OVERHEAD;
3994 				break;
3995 #endif
3996 			default:
3997 				break;
3998 			}
3999 #if defined(INET) || defined(INET6)
4000 			if (net->port) {
4001 				net->mtu += (uint32_t)sizeof(struct udphdr);
4002 			}
4003 #endif
4004 		} else {
4005 			switch (newaddr->sa_family) {
4006 #ifdef INET
4007 			case AF_INET:
4008 				net->mtu = SCTP_DEFAULT_MTU;
4009 				break;
4010 #endif
4011 #ifdef INET6
4012 			case AF_INET6:
4013 				net->mtu = 1280;
4014 				break;
4015 #endif
4016 			default:
4017 				break;
4018 			}
4019 		}
4020 	}
4021 #if defined(INET) || defined(INET6)
4022 	if (net->port) {
4023 		net->mtu -= (uint32_t)sizeof(struct udphdr);
4024 	}
4025 #endif
4026 	if (from == SCTP_ALLOC_ASOC) {
4027 		stcb->asoc.smallest_mtu = net->mtu;
4028 	}
4029 	if (stcb->asoc.smallest_mtu > net->mtu) {
4030 		sctp_pathmtu_adjustment(stcb, net->mtu, true);
4031 	}
4032 #ifdef INET6
4033 	if (newaddr->sa_family == AF_INET6) {
4034 		struct sockaddr_in6 *sin6;
4035 
4036 		sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
4037 		(void)sa6_recoverscope(sin6);
4038 	}
4039 #endif
4040 
4041 	/* JRS - Use the congestion control given in the CC module */
4042 	if (stcb->asoc.cc_functions.sctp_set_initial_cc_param != NULL)
4043 		(*stcb->asoc.cc_functions.sctp_set_initial_cc_param) (stcb, net);
4044 
4045 	/*
4046 	 * CMT: CUC algo - set find_pseudo_cumack to TRUE (1) at beginning
4047 	 * of assoc (2005/06/27, iyengar@cis.udel.edu)
4048 	 */
4049 	net->find_pseudo_cumack = 1;
4050 	net->find_rtx_pseudo_cumack = 1;
4051 	/* Choose an initial flowid. */
4052 	net->flowid = stcb->asoc.my_vtag ^
4053 	    ntohs(stcb->rport) ^
4054 	    ntohs(stcb->sctp_ep->sctp_lport);
4055 	net->flowtype = M_HASHTYPE_OPAQUE_HASH;
4056 	if (netp) {
4057 		*netp = net;
4058 	}
4059 	netfirst = TAILQ_FIRST(&stcb->asoc.nets);
4060 	if (net->ro.ro_nh == NULL) {
4061 		/* Since we have no route put it at the back */
4062 		TAILQ_INSERT_TAIL(&stcb->asoc.nets, net, sctp_next);
4063 	} else if (netfirst == NULL) {
4064 		/* We are the first one in the pool. */
4065 		TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
4066 	} else if (netfirst->ro.ro_nh == NULL) {
4067 		/*
4068 		 * First one has NO route. Place this one ahead of the first
4069 		 * one.
4070 		 */
4071 		TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
4072 	} else if (net->ro.ro_nh->nh_ifp != netfirst->ro.ro_nh->nh_ifp) {
4073 		/*
4074 		 * This one has a different interface than the one at the
4075 		 * top of the list. Place it ahead.
4076 		 */
4077 		TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
4078 	} else {
4079 		/*
4080 		 * Ok we have the same interface as the first one. Move
4081 		 * forward until we find either a) one with a NULL route...
4082 		 * insert ahead of that b) one with a different ifp.. insert
4083 		 * after that. c) end of the list.. insert at the tail.
4084 		 */
4085 		struct sctp_nets *netlook;
4086 
4087 		do {
4088 			netlook = TAILQ_NEXT(netfirst, sctp_next);
4089 			if (netlook == NULL) {
4090 				/* End of the list */
4091 				TAILQ_INSERT_TAIL(&stcb->asoc.nets, net, sctp_next);
4092 				break;
4093 			} else if (netlook->ro.ro_nh == NULL) {
4094 				/* next one has NO route */
4095 				TAILQ_INSERT_BEFORE(netfirst, net, sctp_next);
4096 				break;
4097 			} else if (netlook->ro.ro_nh->nh_ifp != net->ro.ro_nh->nh_ifp) {
4098 				TAILQ_INSERT_AFTER(&stcb->asoc.nets, netlook,
4099 				    net, sctp_next);
4100 				break;
4101 			}
4102 			/* Shift forward */
4103 			netfirst = netlook;
4104 		} while (netlook != NULL);
4105 	}
4106 
4107 	/* got to have a primary set */
4108 	if (stcb->asoc.primary_destination == 0) {
4109 		stcb->asoc.primary_destination = net;
4110 	} else if ((stcb->asoc.primary_destination->ro.ro_nh == NULL) &&
4111 		    (net->ro.ro_nh) &&
4112 	    ((net->dest_state & SCTP_ADDR_UNCONFIRMED) == 0)) {
4113 		/* No route to current primary adopt new primary */
4114 		stcb->asoc.primary_destination = net;
4115 	}
4116 	/* Validate primary is first */
4117 	net = TAILQ_FIRST(&stcb->asoc.nets);
4118 	if ((net != stcb->asoc.primary_destination) &&
4119 	    (stcb->asoc.primary_destination)) {
4120 		/*
4121 		 * first one on the list is NOT the primary sctp_cmpaddr()
4122 		 * is much more efficient if the primary is the first on the
4123 		 * list, make it so.
4124 		 */
4125 		TAILQ_REMOVE(&stcb->asoc.nets,
4126 		    stcb->asoc.primary_destination, sctp_next);
4127 		TAILQ_INSERT_HEAD(&stcb->asoc.nets,
4128 		    stcb->asoc.primary_destination, sctp_next);
4129 	}
4130 	return (0);
4131 }
4132 
4133 static uint32_t
4134 sctp_aloc_a_assoc_id(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
4135 {
4136 	uint32_t id;
4137 	struct sctpasochead *head;
4138 	struct sctp_tcb *lstcb;
4139 
4140 try_again:
4141 	if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
4142 		/* TSNH */
4143 		return (0);
4144 	}
4145 	/*
4146 	 * We don't allow assoc id to be one of SCTP_FUTURE_ASSOC,
4147 	 * SCTP_CURRENT_ASSOC and SCTP_ALL_ASSOC.
4148 	 */
4149 	if (inp->sctp_associd_counter <= SCTP_ALL_ASSOC) {
4150 		inp->sctp_associd_counter = SCTP_ALL_ASSOC + 1;
4151 	}
4152 	id = inp->sctp_associd_counter;
4153 	inp->sctp_associd_counter++;
4154 	lstcb = sctp_findasoc_ep_asocid_locked(inp, (sctp_assoc_t)id, 0);
4155 	if (lstcb) {
4156 		goto try_again;
4157 	}
4158 	head = &inp->sctp_asocidhash[SCTP_PCBHASH_ASOC(id, inp->hashasocidmark)];
4159 	LIST_INSERT_HEAD(head, stcb, sctp_tcbasocidhash);
4160 	stcb->asoc.in_asocid_hash = 1;
4161 	return (id);
4162 }
4163 
4164 /*
4165  * allocate an association and add it to the endpoint. The caller must be
4166  * careful to add all additional addresses once they are know right away or
4167  * else the assoc will be may experience a blackout scenario.
4168  */
4169 static struct sctp_tcb *
4170 sctp_aloc_assoc_locked(struct sctp_inpcb *inp, struct sockaddr *firstaddr,
4171     int *error, uint32_t override_tag, uint32_t initial_tsn,
4172     uint32_t vrf_id, uint16_t o_streams, uint16_t port,
4173     struct thread *p,
4174     int initialize_auth_params)
4175 {
4176 	/* note the p argument is only valid in unbound sockets */
4177 
4178 	struct sctp_tcb *stcb;
4179 	struct sctp_association *asoc;
4180 	struct sctpasochead *head;
4181 	uint16_t rport;
4182 	int err;
4183 
4184 	SCTP_INP_INFO_WLOCK_ASSERT();
4185 	SCTP_INP_WLOCK_ASSERT(inp);
4186 
4187 	/*
4188 	 * Assumption made here: Caller has done a
4189 	 * sctp_findassociation_ep_addr(ep, addr's); to make sure the
4190 	 * address does not exist already.
4191 	 */
4192 	if (SCTP_BASE_INFO(ipi_count_asoc) >= SCTP_MAX_NUM_OF_ASOC) {
4193 		/* Hit max assoc, sorry no more */
4194 		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
4195 		*error = ENOBUFS;
4196 		return (NULL);
4197 	}
4198 	if (firstaddr == NULL) {
4199 		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
4200 		*error = EINVAL;
4201 		return (NULL);
4202 	}
4203 	if (inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE | SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
4204 		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
4205 		*error = EINVAL;
4206 		return (NULL);
4207 	}
4208 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) &&
4209 	    ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_PORTREUSE)) ||
4210 	    (inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED))) {
4211 		/*
4212 		 * If its in the TCP pool, its NOT allowed to create an
4213 		 * association. The parent listener needs to call
4214 		 * sctp_aloc_assoc.. or the one-2-many socket. If a peeled
4215 		 * off, or connected one does this.. its an error.
4216 		 */
4217 		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
4218 		*error = EINVAL;
4219 		return (NULL);
4220 	}
4221 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) ||
4222 	    (inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE)) {
4223 		if ((inp->sctp_flags & SCTP_PCB_FLAGS_WAS_CONNECTED) ||
4224 		    (inp->sctp_flags & SCTP_PCB_FLAGS_WAS_ABORTED)) {
4225 			SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
4226 			*error = EINVAL;
4227 			return (NULL);
4228 		}
4229 	}
4230 	SCTPDBG(SCTP_DEBUG_PCB3, "Allocate an association for peer:");
4231 #ifdef SCTP_DEBUG
4232 	if (firstaddr) {
4233 		SCTPDBG_ADDR(SCTP_DEBUG_PCB3, firstaddr);
4234 		switch (firstaddr->sa_family) {
4235 #ifdef INET
4236 		case AF_INET:
4237 			SCTPDBG(SCTP_DEBUG_PCB3, "Port:%d\n",
4238 			    ntohs(((struct sockaddr_in *)firstaddr)->sin_port));
4239 			break;
4240 #endif
4241 #ifdef INET6
4242 		case AF_INET6:
4243 			SCTPDBG(SCTP_DEBUG_PCB3, "Port:%d\n",
4244 			    ntohs(((struct sockaddr_in6 *)firstaddr)->sin6_port));
4245 			break;
4246 #endif
4247 		default:
4248 			break;
4249 		}
4250 	} else {
4251 		SCTPDBG(SCTP_DEBUG_PCB3, "None\n");
4252 	}
4253 #endif				/* SCTP_DEBUG */
4254 	switch (firstaddr->sa_family) {
4255 #ifdef INET
4256 	case AF_INET:
4257 		{
4258 			struct sockaddr_in *sin;
4259 
4260 			sin = (struct sockaddr_in *)firstaddr;
4261 			if ((ntohs(sin->sin_port) == 0) ||
4262 			    (sin->sin_addr.s_addr == INADDR_ANY) ||
4263 			    (sin->sin_addr.s_addr == INADDR_BROADCAST) ||
4264 			    IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) ||
4265 			    ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
4266 			    (SCTP_IPV6_V6ONLY(inp) != 0))) {
4267 				/* Invalid address */
4268 				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
4269 				*error = EINVAL;
4270 				return (NULL);
4271 			}
4272 			rport = sin->sin_port;
4273 			break;
4274 		}
4275 #endif
4276 #ifdef INET6
4277 	case AF_INET6:
4278 		{
4279 			struct sockaddr_in6 *sin6;
4280 
4281 			sin6 = (struct sockaddr_in6 *)firstaddr;
4282 			if ((ntohs(sin6->sin6_port) == 0) ||
4283 			    IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr) ||
4284 			    IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr) ||
4285 			    ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0)) {
4286 				/* Invalid address */
4287 				SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
4288 				*error = EINVAL;
4289 				return (NULL);
4290 			}
4291 			rport = sin6->sin6_port;
4292 			break;
4293 		}
4294 #endif
4295 	default:
4296 		/* not supported family type */
4297 		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, EINVAL);
4298 		*error = EINVAL;
4299 		return (NULL);
4300 	}
4301 	if (inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) {
4302 		/*
4303 		 * If you have not performed a bind, then we need to do the
4304 		 * ephemeral bind for you.
4305 		 */
4306 		if ((err = sctp_inpcb_bind_locked(inp, NULL, NULL, p))) {
4307 			/* bind error, probably perm */
4308 			*error = err;
4309 			return (NULL);
4310 		}
4311 	}
4312 	stcb = SCTP_ZONE_GET(SCTP_BASE_INFO(ipi_zone_asoc), struct sctp_tcb);
4313 	if (stcb == NULL) {
4314 		/* out of memory? */
4315 		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOMEM);
4316 		*error = ENOMEM;
4317 		return (NULL);
4318 	}
4319 	SCTP_INCR_ASOC_COUNT();
4320 
4321 	memset(stcb, 0, sizeof(*stcb));
4322 	asoc = &stcb->asoc;
4323 
4324 	SCTP_TCB_LOCK_INIT(stcb);
4325 	stcb->rport = rport;
4326 	/* setup back pointer's */
4327 	stcb->sctp_ep = inp;
4328 	stcb->sctp_socket = inp->sctp_socket;
4329 	if ((err = sctp_init_asoc(inp, stcb, override_tag, initial_tsn, vrf_id, o_streams))) {
4330 		/* failed */
4331 		SCTP_TCB_LOCK_DESTROY(stcb);
4332 		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
4333 		SCTP_DECR_ASOC_COUNT();
4334 		*error = err;
4335 		return (NULL);
4336 	}
4337 	SCTP_TCB_LOCK(stcb);
4338 
4339 	asoc->assoc_id = sctp_aloc_a_assoc_id(inp, stcb);
4340 	/* now that my_vtag is set, add it to the hash */
4341 	head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(stcb->asoc.my_vtag, SCTP_BASE_INFO(hashasocmark))];
4342 	/* put it in the bucket in the vtag hash of assoc's for the system */
4343 	LIST_INSERT_HEAD(head, stcb, sctp_asocs);
4344 
4345 	if (sctp_add_remote_addr(stcb, firstaddr, NULL, port, SCTP_DO_SETSCOPE, SCTP_ALLOC_ASOC)) {
4346 		/* failure.. memory error? */
4347 		if (asoc->strmout) {
4348 			SCTP_FREE(asoc->strmout, SCTP_M_STRMO);
4349 			asoc->strmout = NULL;
4350 		}
4351 		if (asoc->mapping_array) {
4352 			SCTP_FREE(asoc->mapping_array, SCTP_M_MAP);
4353 			asoc->mapping_array = NULL;
4354 		}
4355 		if (asoc->nr_mapping_array) {
4356 			SCTP_FREE(asoc->nr_mapping_array, SCTP_M_MAP);
4357 			asoc->nr_mapping_array = NULL;
4358 		}
4359 		SCTP_DECR_ASOC_COUNT();
4360 		SCTP_TCB_UNLOCK(stcb);
4361 		SCTP_TCB_LOCK_DESTROY(stcb);
4362 		LIST_REMOVE(stcb, sctp_asocs);
4363 		LIST_REMOVE(stcb, sctp_tcbasocidhash);
4364 		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
4365 		SCTP_INP_WUNLOCK(inp);
4366 		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOBUFS);
4367 		*error = ENOBUFS;
4368 		return (NULL);
4369 	}
4370 	/* Init all the timers */
4371 	SCTP_OS_TIMER_INIT(&asoc->dack_timer.timer);
4372 	SCTP_OS_TIMER_INIT(&asoc->strreset_timer.timer);
4373 	SCTP_OS_TIMER_INIT(&asoc->asconf_timer.timer);
4374 	SCTP_OS_TIMER_INIT(&asoc->shut_guard_timer.timer);
4375 	SCTP_OS_TIMER_INIT(&asoc->autoclose_timer.timer);
4376 	SCTP_OS_TIMER_INIT(&asoc->delete_prim_timer.timer);
4377 
4378 	LIST_INSERT_HEAD(&inp->sctp_asoc_list, stcb, sctp_tcblist);
4379 	/* now file the port under the hash as well */
4380 	if (inp->sctp_tcbhash != NULL) {
4381 		head = &inp->sctp_tcbhash[SCTP_PCBHASH_ALLADDR(stcb->rport,
4382 		    inp->sctp_hashmark)];
4383 		LIST_INSERT_HEAD(head, stcb, sctp_tcbhash);
4384 	}
4385 	if (initialize_auth_params == SCTP_INITIALIZE_AUTH_PARAMS) {
4386 		sctp_initialize_auth_params(inp, stcb);
4387 	}
4388 	SCTPDBG(SCTP_DEBUG_PCB1, "Association %p now allocated\n", (void *)stcb);
4389 	return (stcb);
4390 }
4391 
4392 struct sctp_tcb *
4393 sctp_aloc_assoc(struct sctp_inpcb *inp, struct sockaddr *firstaddr,
4394     int *error, uint32_t override_tag, uint32_t initial_tsn,
4395     uint32_t vrf_id, uint16_t o_streams, uint16_t port,
4396     struct thread *p,
4397     int initialize_auth_params)
4398 {
4399 	struct sctp_tcb *stcb;
4400 
4401 	SCTP_INP_INFO_WLOCK();
4402 	SCTP_INP_WLOCK(inp);
4403 	stcb = sctp_aloc_assoc_locked(inp, firstaddr, error, override_tag,
4404 	    initial_tsn, vrf_id, o_streams, port, p, initialize_auth_params);
4405 	SCTP_INP_INFO_WUNLOCK();
4406 	SCTP_INP_WUNLOCK(inp);
4407 	return (stcb);
4408 }
4409 
4410 struct sctp_tcb *
4411 sctp_aloc_assoc_connected(struct sctp_inpcb *inp, struct sockaddr *firstaddr,
4412     int *error, uint32_t override_tag, uint32_t initial_tsn,
4413     uint32_t vrf_id, uint16_t o_streams, uint16_t port,
4414     struct thread *p,
4415     int initialize_auth_params)
4416 {
4417 	struct sctp_tcb *stcb;
4418 
4419 	SCTP_INP_INFO_WLOCK();
4420 	SCTP_INP_WLOCK(inp);
4421 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) &&
4422 	    SCTP_IS_LISTENING(inp)) {
4423 		SCTP_INP_INFO_WUNLOCK();
4424 		SCTP_INP_WUNLOCK(inp);
4425 		*error = EINVAL;
4426 		return (NULL);
4427 	}
4428 	stcb = sctp_aloc_assoc_locked(inp, firstaddr, error, override_tag,
4429 	    initial_tsn, vrf_id, o_streams, port, p, initialize_auth_params);
4430 	SCTP_INP_INFO_WUNLOCK();
4431 	if (stcb != NULL && (inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE)) {
4432 		inp->sctp_flags |= SCTP_PCB_FLAGS_CONNECTED;
4433 		soisconnecting(inp->sctp_socket);
4434 	}
4435 	SCTP_INP_WUNLOCK(inp);
4436 	return (stcb);
4437 }
4438 
4439 void
4440 sctp_remove_net(struct sctp_tcb *stcb, struct sctp_nets *net)
4441 {
4442 	struct sctp_inpcb *inp;
4443 	struct sctp_association *asoc;
4444 
4445 	inp = stcb->sctp_ep;
4446 	asoc = &stcb->asoc;
4447 	asoc->numnets--;
4448 	TAILQ_REMOVE(&asoc->nets, net, sctp_next);
4449 	if (net == asoc->primary_destination) {
4450 		/* Reset primary */
4451 		struct sctp_nets *lnet;
4452 
4453 		lnet = TAILQ_FIRST(&asoc->nets);
4454 		/*
4455 		 * Mobility adaptation Ideally, if deleted destination is
4456 		 * the primary, it becomes a fast retransmission trigger by
4457 		 * the subsequent SET PRIMARY. (by micchie)
4458 		 */
4459 		if (sctp_is_mobility_feature_on(stcb->sctp_ep,
4460 		    SCTP_MOBILITY_BASE) ||
4461 		    sctp_is_mobility_feature_on(stcb->sctp_ep,
4462 		    SCTP_MOBILITY_FASTHANDOFF)) {
4463 			SCTPDBG(SCTP_DEBUG_ASCONF1, "remove_net: primary dst is deleting\n");
4464 			if (asoc->deleted_primary != NULL) {
4465 				SCTPDBG(SCTP_DEBUG_ASCONF1, "remove_net: deleted primary may be already stored\n");
4466 				goto out;
4467 			}
4468 			asoc->deleted_primary = net;
4469 			atomic_add_int(&net->ref_count, 1);
4470 			memset(&net->lastsa, 0, sizeof(net->lastsa));
4471 			memset(&net->lastsv, 0, sizeof(net->lastsv));
4472 			sctp_mobility_feature_on(stcb->sctp_ep,
4473 			    SCTP_MOBILITY_PRIM_DELETED);
4474 			sctp_timer_start(SCTP_TIMER_TYPE_PRIM_DELETED,
4475 			    stcb->sctp_ep, stcb, NULL);
4476 		}
4477 out:
4478 		/* Try to find a confirmed primary */
4479 		asoc->primary_destination = sctp_find_alternate_net(stcb, lnet, 0);
4480 	}
4481 	if (net == asoc->last_data_chunk_from) {
4482 		/* Reset primary */
4483 		asoc->last_data_chunk_from = TAILQ_FIRST(&asoc->nets);
4484 	}
4485 	if (net == asoc->last_control_chunk_from) {
4486 		/* Clear net */
4487 		asoc->last_control_chunk_from = NULL;
4488 	}
4489 	if (net == asoc->last_net_cmt_send_started) {
4490 		/* Clear net */
4491 		asoc->last_net_cmt_send_started = NULL;
4492 	}
4493 	if (net == stcb->asoc.alternate) {
4494 		sctp_free_remote_addr(stcb->asoc.alternate);
4495 		stcb->asoc.alternate = NULL;
4496 	}
4497 	sctp_timer_stop(SCTP_TIMER_TYPE_PATHMTURAISE, inp, stcb, net,
4498 	    SCTP_FROM_SCTP_PCB + SCTP_LOC_9);
4499 	sctp_timer_stop(SCTP_TIMER_TYPE_HEARTBEAT, inp, stcb, net,
4500 	    SCTP_FROM_SCTP_PCB + SCTP_LOC_10);
4501 	net->dest_state |= SCTP_ADDR_BEING_DELETED;
4502 	sctp_free_remote_addr(net);
4503 }
4504 
4505 /*
4506  * remove a remote endpoint address from an association, it will fail if the
4507  * address does not exist.
4508  */
4509 int
4510 sctp_del_remote_addr(struct sctp_tcb *stcb, struct sockaddr *remaddr)
4511 {
4512 	/*
4513 	 * Here we need to remove a remote address. This is quite simple, we
4514 	 * first find it in the list of address for the association
4515 	 * (tasoc->asoc.nets) and then if it is there, we do a LIST_REMOVE
4516 	 * on that item. Note we do not allow it to be removed if there are
4517 	 * no other addresses.
4518 	 */
4519 	struct sctp_association *asoc;
4520 	struct sctp_nets *net, *nnet;
4521 
4522 	asoc = &stcb->asoc;
4523 
4524 	/* locate the address */
4525 	TAILQ_FOREACH_SAFE(net, &asoc->nets, sctp_next, nnet) {
4526 		if (net->ro._l_addr.sa.sa_family != remaddr->sa_family) {
4527 			continue;
4528 		}
4529 		if (sctp_cmpaddr((struct sockaddr *)&net->ro._l_addr,
4530 		    remaddr)) {
4531 			/* we found the guy */
4532 			if (asoc->numnets < 2) {
4533 				/* Must have at LEAST two remote addresses */
4534 				return (-1);
4535 			} else {
4536 				sctp_remove_net(stcb, net);
4537 				return (0);
4538 			}
4539 		}
4540 	}
4541 	/* not found. */
4542 	return (-2);
4543 }
4544 
4545 static bool
4546 sctp_is_in_timewait(uint32_t tag, uint16_t lport, uint16_t rport, uint32_t now)
4547 {
4548 	struct sctpvtaghead *chain;
4549 	struct sctp_tagblock *twait_block;
4550 	int i;
4551 
4552 	SCTP_INP_INFO_LOCK_ASSERT();
4553 	chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
4554 	LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
4555 		for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
4556 			if ((twait_block->vtag_block[i].tv_sec_at_expire >= now) &&
4557 			    (twait_block->vtag_block[i].v_tag == tag) &&
4558 			    (twait_block->vtag_block[i].lport == lport) &&
4559 			    (twait_block->vtag_block[i].rport == rport)) {
4560 				return (true);
4561 			}
4562 		}
4563 	}
4564 	return (false);
4565 }
4566 
4567 static void
4568 sctp_set_vtag_block(struct sctp_timewait *vtag_block, uint32_t time,
4569     uint32_t tag, uint16_t lport, uint16_t rport)
4570 {
4571 	vtag_block->tv_sec_at_expire = time;
4572 	vtag_block->v_tag = tag;
4573 	vtag_block->lport = lport;
4574 	vtag_block->rport = rport;
4575 }
4576 
4577 static void
4578 sctp_add_vtag_to_timewait(uint32_t tag, uint16_t lport, uint16_t rport)
4579 {
4580 	struct sctpvtaghead *chain;
4581 	struct sctp_tagblock *twait_block;
4582 	struct timeval now;
4583 	uint32_t time;
4584 	int i;
4585 	bool set;
4586 
4587 	SCTP_INP_INFO_WLOCK_ASSERT();
4588 	(void)SCTP_GETTIME_TIMEVAL(&now);
4589 	time = (uint32_t)now.tv_sec + SCTP_BASE_SYSCTL(sctp_vtag_time_wait);
4590 	chain = &SCTP_BASE_INFO(vtag_timewait)[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
4591 	set = false;
4592 	LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
4593 		/* Block(s) present, lets find space, and expire on the fly */
4594 		for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
4595 			if ((twait_block->vtag_block[i].v_tag == 0) && !set) {
4596 				sctp_set_vtag_block(twait_block->vtag_block + i, time, tag, lport, rport);
4597 				set = true;
4598 				continue;
4599 			}
4600 			if ((twait_block->vtag_block[i].v_tag != 0) &&
4601 			    (twait_block->vtag_block[i].tv_sec_at_expire < (uint32_t)now.tv_sec)) {
4602 				if (set) {
4603 					/* Audit expires this guy */
4604 					sctp_set_vtag_block(twait_block->vtag_block + i, 0, 0, 0, 0);
4605 				} else {
4606 					/* Reuse it for the new tag */
4607 					sctp_set_vtag_block(twait_block->vtag_block + i, time, tag, lport, rport);
4608 					set = true;
4609 				}
4610 			}
4611 		}
4612 		if (set) {
4613 			/*
4614 			 * We only do up to the block where we can place our
4615 			 * tag for audits
4616 			 */
4617 			break;
4618 		}
4619 	}
4620 	/* Need to add a new block to chain */
4621 	if (!set) {
4622 		SCTP_MALLOC(twait_block, struct sctp_tagblock *,
4623 		    sizeof(struct sctp_tagblock), SCTP_M_TIMW);
4624 		if (twait_block == NULL) {
4625 			return;
4626 		}
4627 		memset(twait_block, 0, sizeof(struct sctp_tagblock));
4628 		LIST_INSERT_HEAD(chain, twait_block, sctp_nxt_tagblock);
4629 		sctp_set_vtag_block(twait_block->vtag_block, time, tag, lport, rport);
4630 	}
4631 }
4632 
4633 void
4634 sctp_clean_up_stream(struct sctp_tcb *stcb, struct sctp_readhead *rh)
4635 {
4636 	struct sctp_tmit_chunk *chk, *nchk;
4637 	struct sctp_queued_to_read *control, *ncontrol;
4638 
4639 	TAILQ_FOREACH_SAFE(control, rh, next_instrm, ncontrol) {
4640 		TAILQ_REMOVE(rh, control, next_instrm);
4641 		control->on_strm_q = 0;
4642 		if (control->on_read_q == 0) {
4643 			sctp_free_remote_addr(control->whoFrom);
4644 			if (control->data) {
4645 				sctp_m_freem(control->data);
4646 				control->data = NULL;
4647 			}
4648 		}
4649 		/* Reassembly free? */
4650 		TAILQ_FOREACH_SAFE(chk, &control->reasm, sctp_next, nchk) {
4651 			TAILQ_REMOVE(&control->reasm, chk, sctp_next);
4652 			if (chk->data) {
4653 				sctp_m_freem(chk->data);
4654 				chk->data = NULL;
4655 			}
4656 			if (chk->holds_key_ref)
4657 				sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
4658 			sctp_free_remote_addr(chk->whoTo);
4659 			SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
4660 			SCTP_DECR_CHK_COUNT();
4661 			/* sa_ignore FREED_MEMORY */
4662 		}
4663 		/*
4664 		 * We don't free the address here since all the net's were
4665 		 * freed above.
4666 		 */
4667 		if (control->on_read_q == 0) {
4668 			sctp_free_a_readq(stcb, control);
4669 		}
4670 	}
4671 }
4672 
4673 /*-
4674  * Free the association after un-hashing the remote port. This
4675  * function ALWAYS returns holding NO LOCK on the stcb. It DOES
4676  * expect that the input to this function IS a locked TCB.
4677  * It will return 0, if it did NOT destroy the association (instead
4678  * it unlocks it. It will return NON-zero if it either destroyed the
4679  * association OR the association is already destroyed.
4680  */
4681 int
4682 sctp_free_assoc(struct sctp_inpcb *inp, struct sctp_tcb *stcb, int from_inpcbfree, int from_location)
4683 {
4684 	int i;
4685 	struct sctp_association *asoc;
4686 	struct sctp_nets *net, *nnet;
4687 	struct sctp_laddr *laddr, *naddr;
4688 	struct sctp_tmit_chunk *chk, *nchk;
4689 	struct sctp_asconf_addr *aparam, *naparam;
4690 	struct sctp_asconf_ack *aack, *naack;
4691 	struct sctp_stream_reset_list *strrst, *nstrrst;
4692 	struct sctp_queued_to_read *sq, *nsq;
4693 	struct sctp_stream_queue_pending *sp, *nsp;
4694 	sctp_sharedkey_t *shared_key, *nshared_key;
4695 	struct socket *so;
4696 
4697 	/* first, lets purge the entry from the hash table. */
4698 	SCTP_TCB_LOCK_ASSERT(stcb);
4699 
4700 #ifdef SCTP_LOG_CLOSING
4701 	sctp_log_closing(inp, stcb, 6);
4702 #endif
4703 	if (stcb->asoc.state == 0) {
4704 #ifdef SCTP_LOG_CLOSING
4705 		sctp_log_closing(inp, NULL, 7);
4706 #endif
4707 		/* there is no asoc, really TSNH :-0 */
4708 		return (1);
4709 	}
4710 	if (stcb->asoc.alternate) {
4711 		sctp_free_remote_addr(stcb->asoc.alternate);
4712 		stcb->asoc.alternate = NULL;
4713 	}
4714 	/* TEMP CODE */
4715 	if (stcb->freed_from_where == 0) {
4716 		/* Only record the first place free happened from */
4717 		stcb->freed_from_where = from_location;
4718 	}
4719 	/* TEMP CODE */
4720 
4721 	asoc = &stcb->asoc;
4722 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
4723 	    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE))
4724 		/* nothing around */
4725 		so = NULL;
4726 	else
4727 		so = inp->sctp_socket;
4728 
4729 	/*
4730 	 * We used timer based freeing if a reader or writer is in the way.
4731 	 * So we first check if we are actually being called from a timer,
4732 	 * if so we abort early if a reader or writer is still in the way.
4733 	 */
4734 	if ((stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) &&
4735 	    (from_inpcbfree == SCTP_NORMAL_PROC)) {
4736 		/*
4737 		 * is it the timer driving us? if so are the reader/writers
4738 		 * gone?
4739 		 */
4740 		if (stcb->asoc.refcnt) {
4741 			/* nope, reader or writer in the way */
4742 			sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL);
4743 			/* no asoc destroyed */
4744 			SCTP_TCB_UNLOCK(stcb);
4745 #ifdef SCTP_LOG_CLOSING
4746 			sctp_log_closing(inp, stcb, 8);
4747 #endif
4748 			return (0);
4749 		}
4750 	}
4751 	/* Now clean up any other timers */
4752 	sctp_stop_association_timers(stcb, false);
4753 	/* Now the read queue needs to be cleaned up (only once) */
4754 	if ((stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) == 0) {
4755 		SCTP_ADD_SUBSTATE(stcb, SCTP_STATE_ABOUT_TO_BE_FREED);
4756 		SCTP_INP_READ_LOCK(inp);
4757 		TAILQ_FOREACH(sq, &inp->read_queue, next) {
4758 			if (sq->stcb == stcb) {
4759 				sq->do_not_ref_stcb = 1;
4760 				sq->sinfo_cumtsn = stcb->asoc.cumulative_tsn;
4761 				/*
4762 				 * If there is no end, there never will be
4763 				 * now.
4764 				 */
4765 				if (sq->end_added == 0) {
4766 					/* Held for PD-API clear that. */
4767 					sq->pdapi_aborted = 1;
4768 					sq->held_length = 0;
4769 					if (sctp_stcb_is_feature_on(inp, stcb, SCTP_PCB_FLAGS_PDAPIEVNT) && (so != NULL)) {
4770 						/*
4771 						 * Need to add a PD-API
4772 						 * aborted indication.
4773 						 * Setting the control_pdapi
4774 						 * assures that it will be
4775 						 * added right after this
4776 						 * msg.
4777 						 */
4778 						sctp_ulp_notify(SCTP_NOTIFY_PARTIAL_DELVIERY_INDICATION,
4779 						    stcb,
4780 						    SCTP_PARTIAL_DELIVERY_ABORTED,
4781 						    (void *)sq,
4782 						    SCTP_SO_LOCKED);
4783 					}
4784 					/* Add an end to wake them */
4785 					sq->end_added = 1;
4786 				}
4787 			}
4788 		}
4789 		SCTP_INP_READ_UNLOCK(inp);
4790 		if (stcb->block_entry) {
4791 			SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_PCB, ECONNRESET);
4792 			stcb->block_entry->error = ECONNRESET;
4793 			stcb->block_entry = NULL;
4794 		}
4795 	}
4796 	if ((stcb->asoc.refcnt) || (stcb->asoc.state & SCTP_STATE_IN_ACCEPT_QUEUE)) {
4797 		/*
4798 		 * Someone holds a reference OR the socket is unaccepted
4799 		 * yet.
4800 		 */
4801 		if ((stcb->asoc.refcnt) ||
4802 		    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
4803 		    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) {
4804 			SCTP_CLEAR_SUBSTATE(stcb, SCTP_STATE_IN_ACCEPT_QUEUE);
4805 			sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL);
4806 		}
4807 		if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
4808 		    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE))
4809 			/* nothing around */
4810 			so = NULL;
4811 		if (so) {
4812 			/* Wake any reader/writers */
4813 			sctp_sorwakeup(inp, so);
4814 			sctp_sowwakeup(inp, so);
4815 		}
4816 		SCTP_TCB_UNLOCK(stcb);
4817 
4818 #ifdef SCTP_LOG_CLOSING
4819 		sctp_log_closing(inp, stcb, 9);
4820 #endif
4821 		/* no asoc destroyed */
4822 		return (0);
4823 	}
4824 #ifdef SCTP_LOG_CLOSING
4825 	sctp_log_closing(inp, stcb, 10);
4826 #endif
4827 	/*
4828 	 * When I reach here, no others want to kill the assoc yet.. and I
4829 	 * own the lock. Now its possible an abort comes in when I do the
4830 	 * lock exchange below to grab all the locks to do the final take
4831 	 * out. to prevent this we increment the count, which will start a
4832 	 * timer and blow out above thus assuring us that we hold exclusive
4833 	 * killing of the asoc. Note that after getting back the TCB lock we
4834 	 * will go ahead and increment the counter back up and stop any
4835 	 * timer a passing stranger may have started :-S
4836 	 */
4837 	if (from_inpcbfree == SCTP_NORMAL_PROC) {
4838 		atomic_add_int(&stcb->asoc.refcnt, 1);
4839 
4840 		SCTP_TCB_UNLOCK(stcb);
4841 		SCTP_INP_INFO_WLOCK();
4842 		SCTP_INP_WLOCK(inp);
4843 		SCTP_TCB_LOCK(stcb);
4844 	}
4845 	/* Double check the GONE flag */
4846 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
4847 	    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE))
4848 		/* nothing around */
4849 		so = NULL;
4850 
4851 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
4852 	    (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
4853 		/*
4854 		 * For TCP type we need special handling when we are
4855 		 * connected. We also include the peel'ed off ones to.
4856 		 */
4857 		if (inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) {
4858 			inp->sctp_flags &= ~SCTP_PCB_FLAGS_CONNECTED;
4859 			inp->sctp_flags |= SCTP_PCB_FLAGS_WAS_CONNECTED;
4860 			if (so) {
4861 				SOCKBUF_LOCK(&so->so_rcv);
4862 				so->so_state &= ~(SS_ISCONNECTING |
4863 				    SS_ISDISCONNECTING |
4864 				    SS_ISCONFIRMING |
4865 				    SS_ISCONNECTED);
4866 				so->so_state |= SS_ISDISCONNECTED;
4867 				socantrcvmore_locked(so);
4868 				socantsendmore(so);
4869 				sctp_sowwakeup(inp, so);
4870 				sctp_sorwakeup(inp, so);
4871 				SCTP_SOWAKEUP(so);
4872 			}
4873 		}
4874 	}
4875 
4876 	/*
4877 	 * Make it invalid too, that way if its about to run it will abort
4878 	 * and return.
4879 	 */
4880 	/* re-increment the lock */
4881 	if (from_inpcbfree == SCTP_NORMAL_PROC) {
4882 		atomic_subtract_int(&stcb->asoc.refcnt, 1);
4883 	}
4884 	if (stcb->asoc.refcnt) {
4885 		SCTP_CLEAR_SUBSTATE(stcb, SCTP_STATE_IN_ACCEPT_QUEUE);
4886 		sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL);
4887 		if (from_inpcbfree == SCTP_NORMAL_PROC) {
4888 			SCTP_INP_INFO_WUNLOCK();
4889 			SCTP_INP_WUNLOCK(inp);
4890 		}
4891 		SCTP_TCB_UNLOCK(stcb);
4892 		return (0);
4893 	}
4894 	asoc->state = 0;
4895 	if (inp->sctp_tcbhash) {
4896 		LIST_REMOVE(stcb, sctp_tcbhash);
4897 	}
4898 	if (stcb->asoc.in_asocid_hash) {
4899 		LIST_REMOVE(stcb, sctp_tcbasocidhash);
4900 	}
4901 	if (inp->sctp_socket == NULL) {
4902 		stcb->sctp_socket = NULL;
4903 	}
4904 	/* Now lets remove it from the list of ALL associations in the EP */
4905 	LIST_REMOVE(stcb, sctp_tcblist);
4906 	if (from_inpcbfree == SCTP_NORMAL_PROC) {
4907 		SCTP_INP_INCR_REF(inp);
4908 		SCTP_INP_WUNLOCK(inp);
4909 	}
4910 	/* pull from vtag hash */
4911 	LIST_REMOVE(stcb, sctp_asocs);
4912 	sctp_add_vtag_to_timewait(asoc->my_vtag, inp->sctp_lport, stcb->rport);
4913 
4914 	/*
4915 	 * Now restop the timers to be sure this is paranoia at is finest!
4916 	 */
4917 	sctp_stop_association_timers(stcb, true);
4918 
4919 	/*
4920 	 * The chunk lists and such SHOULD be empty but we check them just
4921 	 * in case.
4922 	 */
4923 	/* anything on the wheel needs to be removed */
4924 	for (i = 0; i < asoc->streamoutcnt; i++) {
4925 		struct sctp_stream_out *outs;
4926 
4927 		outs = &asoc->strmout[i];
4928 		/* now clean up any chunks here */
4929 		TAILQ_FOREACH_SAFE(sp, &outs->outqueue, next, nsp) {
4930 			atomic_subtract_int(&asoc->stream_queue_cnt, 1);
4931 			TAILQ_REMOVE(&outs->outqueue, sp, next);
4932 			stcb->asoc.ss_functions.sctp_ss_remove_from_stream(stcb, asoc, outs, sp);
4933 			sctp_free_spbufspace(stcb, asoc, sp);
4934 			if (sp->data) {
4935 				if (so) {
4936 					/* Still an open socket - report */
4937 					sctp_ulp_notify(SCTP_NOTIFY_SPECIAL_SP_FAIL, stcb,
4938 					    0, (void *)sp, SCTP_SO_LOCKED);
4939 				}
4940 				if (sp->data) {
4941 					sctp_m_freem(sp->data);
4942 					sp->data = NULL;
4943 					sp->tail_mbuf = NULL;
4944 					sp->length = 0;
4945 				}
4946 			}
4947 			if (sp->net) {
4948 				sctp_free_remote_addr(sp->net);
4949 				sp->net = NULL;
4950 			}
4951 			sctp_free_a_strmoq(stcb, sp, SCTP_SO_LOCKED);
4952 		}
4953 	}
4954 	/* sa_ignore FREED_MEMORY */
4955 	TAILQ_FOREACH_SAFE(strrst, &asoc->resetHead, next_resp, nstrrst) {
4956 		TAILQ_REMOVE(&asoc->resetHead, strrst, next_resp);
4957 		SCTP_FREE(strrst, SCTP_M_STRESET);
4958 	}
4959 	TAILQ_FOREACH_SAFE(sq, &asoc->pending_reply_queue, next, nsq) {
4960 		TAILQ_REMOVE(&asoc->pending_reply_queue, sq, next);
4961 		if (sq->data) {
4962 			sctp_m_freem(sq->data);
4963 			sq->data = NULL;
4964 		}
4965 		sctp_free_remote_addr(sq->whoFrom);
4966 		sq->whoFrom = NULL;
4967 		sq->stcb = NULL;
4968 		/* Free the ctl entry */
4969 		sctp_free_a_readq(stcb, sq);
4970 		/* sa_ignore FREED_MEMORY */
4971 	}
4972 	TAILQ_FOREACH_SAFE(chk, &asoc->free_chunks, sctp_next, nchk) {
4973 		TAILQ_REMOVE(&asoc->free_chunks, chk, sctp_next);
4974 		if (chk->data) {
4975 			sctp_m_freem(chk->data);
4976 			chk->data = NULL;
4977 		}
4978 		if (chk->holds_key_ref)
4979 			sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
4980 		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
4981 		SCTP_DECR_CHK_COUNT();
4982 		atomic_subtract_int(&SCTP_BASE_INFO(ipi_free_chunks), 1);
4983 		asoc->free_chunk_cnt--;
4984 		/* sa_ignore FREED_MEMORY */
4985 	}
4986 	/* pending send queue SHOULD be empty */
4987 	TAILQ_FOREACH_SAFE(chk, &asoc->send_queue, sctp_next, nchk) {
4988 		if (asoc->strmout[chk->rec.data.sid].chunks_on_queues > 0) {
4989 			asoc->strmout[chk->rec.data.sid].chunks_on_queues--;
4990 #ifdef INVARIANTS
4991 		} else {
4992 			panic("No chunks on the queues for sid %u.", chk->rec.data.sid);
4993 #endif
4994 		}
4995 		TAILQ_REMOVE(&asoc->send_queue, chk, sctp_next);
4996 		if (chk->data) {
4997 			if (so) {
4998 				/* Still a socket? */
4999 				sctp_ulp_notify(SCTP_NOTIFY_UNSENT_DG_FAIL, stcb,
5000 				    0, chk, SCTP_SO_LOCKED);
5001 			}
5002 			if (chk->data) {
5003 				sctp_m_freem(chk->data);
5004 				chk->data = NULL;
5005 			}
5006 		}
5007 		if (chk->holds_key_ref)
5008 			sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
5009 		if (chk->whoTo) {
5010 			sctp_free_remote_addr(chk->whoTo);
5011 			chk->whoTo = NULL;
5012 		}
5013 		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
5014 		SCTP_DECR_CHK_COUNT();
5015 		/* sa_ignore FREED_MEMORY */
5016 	}
5017 	/* sent queue SHOULD be empty */
5018 	TAILQ_FOREACH_SAFE(chk, &asoc->sent_queue, sctp_next, nchk) {
5019 		if (chk->sent != SCTP_DATAGRAM_NR_ACKED) {
5020 			if (asoc->strmout[chk->rec.data.sid].chunks_on_queues > 0) {
5021 				asoc->strmout[chk->rec.data.sid].chunks_on_queues--;
5022 #ifdef INVARIANTS
5023 			} else {
5024 				panic("No chunks on the queues for sid %u.", chk->rec.data.sid);
5025 #endif
5026 			}
5027 		}
5028 		TAILQ_REMOVE(&asoc->sent_queue, chk, sctp_next);
5029 		if (chk->data) {
5030 			if (so) {
5031 				/* Still a socket? */
5032 				sctp_ulp_notify(SCTP_NOTIFY_SENT_DG_FAIL, stcb,
5033 				    0, chk, SCTP_SO_LOCKED);
5034 			}
5035 			if (chk->data) {
5036 				sctp_m_freem(chk->data);
5037 				chk->data = NULL;
5038 			}
5039 		}
5040 		if (chk->holds_key_ref)
5041 			sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
5042 		sctp_free_remote_addr(chk->whoTo);
5043 		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
5044 		SCTP_DECR_CHK_COUNT();
5045 		/* sa_ignore FREED_MEMORY */
5046 	}
5047 #ifdef INVARIANTS
5048 	for (i = 0; i < stcb->asoc.streamoutcnt; i++) {
5049 		if (stcb->asoc.strmout[i].chunks_on_queues > 0) {
5050 			panic("%u chunks left for stream %u.", stcb->asoc.strmout[i].chunks_on_queues, i);
5051 		}
5052 	}
5053 #endif
5054 	/* control queue MAY not be empty */
5055 	TAILQ_FOREACH_SAFE(chk, &asoc->control_send_queue, sctp_next, nchk) {
5056 		TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
5057 		if (chk->data) {
5058 			sctp_m_freem(chk->data);
5059 			chk->data = NULL;
5060 		}
5061 		if (chk->holds_key_ref)
5062 			sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
5063 		sctp_free_remote_addr(chk->whoTo);
5064 		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
5065 		SCTP_DECR_CHK_COUNT();
5066 		/* sa_ignore FREED_MEMORY */
5067 	}
5068 	/* ASCONF queue MAY not be empty */
5069 	TAILQ_FOREACH_SAFE(chk, &asoc->asconf_send_queue, sctp_next, nchk) {
5070 		TAILQ_REMOVE(&asoc->asconf_send_queue, chk, sctp_next);
5071 		if (chk->data) {
5072 			sctp_m_freem(chk->data);
5073 			chk->data = NULL;
5074 		}
5075 		if (chk->holds_key_ref)
5076 			sctp_auth_key_release(stcb, chk->auth_keyid, SCTP_SO_LOCKED);
5077 		sctp_free_remote_addr(chk->whoTo);
5078 		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_chunk), chk);
5079 		SCTP_DECR_CHK_COUNT();
5080 		/* sa_ignore FREED_MEMORY */
5081 	}
5082 	if (asoc->mapping_array) {
5083 		SCTP_FREE(asoc->mapping_array, SCTP_M_MAP);
5084 		asoc->mapping_array = NULL;
5085 	}
5086 	if (asoc->nr_mapping_array) {
5087 		SCTP_FREE(asoc->nr_mapping_array, SCTP_M_MAP);
5088 		asoc->nr_mapping_array = NULL;
5089 	}
5090 	/* the stream outs */
5091 	if (asoc->strmout) {
5092 		SCTP_FREE(asoc->strmout, SCTP_M_STRMO);
5093 		asoc->strmout = NULL;
5094 	}
5095 	asoc->strm_realoutsize = asoc->streamoutcnt = 0;
5096 	if (asoc->strmin) {
5097 		for (i = 0; i < asoc->streamincnt; i++) {
5098 			sctp_clean_up_stream(stcb, &asoc->strmin[i].inqueue);
5099 			sctp_clean_up_stream(stcb, &asoc->strmin[i].uno_inqueue);
5100 		}
5101 		SCTP_FREE(asoc->strmin, SCTP_M_STRMI);
5102 		asoc->strmin = NULL;
5103 	}
5104 	asoc->streamincnt = 0;
5105 	TAILQ_FOREACH_SAFE(net, &asoc->nets, sctp_next, nnet) {
5106 #ifdef INVARIANTS
5107 		if (SCTP_BASE_INFO(ipi_count_raddr) == 0) {
5108 			panic("no net's left alloc'ed, or list points to itself");
5109 		}
5110 #endif
5111 		TAILQ_REMOVE(&asoc->nets, net, sctp_next);
5112 		sctp_free_remote_addr(net);
5113 	}
5114 	LIST_FOREACH_SAFE(laddr, &asoc->sctp_restricted_addrs, sctp_nxt_addr, naddr) {
5115 		/* sa_ignore FREED_MEMORY */
5116 		sctp_remove_laddr(laddr);
5117 	}
5118 
5119 	/* pending asconf (address) parameters */
5120 	TAILQ_FOREACH_SAFE(aparam, &asoc->asconf_queue, next, naparam) {
5121 		/* sa_ignore FREED_MEMORY */
5122 		TAILQ_REMOVE(&asoc->asconf_queue, aparam, next);
5123 		SCTP_FREE(aparam, SCTP_M_ASC_ADDR);
5124 	}
5125 	TAILQ_FOREACH_SAFE(aack, &asoc->asconf_ack_sent, next, naack) {
5126 		/* sa_ignore FREED_MEMORY */
5127 		TAILQ_REMOVE(&asoc->asconf_ack_sent, aack, next);
5128 		if (aack->data != NULL) {
5129 			sctp_m_freem(aack->data);
5130 		}
5131 		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asconf_ack), aack);
5132 	}
5133 	/* clean up auth stuff */
5134 	if (asoc->local_hmacs)
5135 		sctp_free_hmaclist(asoc->local_hmacs);
5136 	if (asoc->peer_hmacs)
5137 		sctp_free_hmaclist(asoc->peer_hmacs);
5138 
5139 	if (asoc->local_auth_chunks)
5140 		sctp_free_chunklist(asoc->local_auth_chunks);
5141 	if (asoc->peer_auth_chunks)
5142 		sctp_free_chunklist(asoc->peer_auth_chunks);
5143 
5144 	sctp_free_authinfo(&asoc->authinfo);
5145 
5146 	LIST_FOREACH_SAFE(shared_key, &asoc->shared_keys, next, nshared_key) {
5147 		LIST_REMOVE(shared_key, next);
5148 		sctp_free_sharedkey(shared_key);
5149 		/* sa_ignore FREED_MEMORY */
5150 	}
5151 
5152 	/* Insert new items here :> */
5153 
5154 	/* Get rid of LOCK */
5155 	SCTP_TCB_UNLOCK(stcb);
5156 	SCTP_TCB_LOCK_DESTROY(stcb);
5157 	if (from_inpcbfree == SCTP_NORMAL_PROC) {
5158 		SCTP_INP_INFO_WUNLOCK();
5159 		SCTP_INP_RLOCK(inp);
5160 	}
5161 #ifdef SCTP_TRACK_FREED_ASOCS
5162 	if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
5163 		/* now clean up the tasoc itself */
5164 		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
5165 		SCTP_DECR_ASOC_COUNT();
5166 	} else {
5167 		LIST_INSERT_HEAD(&inp->sctp_asoc_free_list, stcb, sctp_tcblist);
5168 	}
5169 #else
5170 	SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_asoc), stcb);
5171 	SCTP_DECR_ASOC_COUNT();
5172 #endif
5173 	if (from_inpcbfree == SCTP_NORMAL_PROC) {
5174 		if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
5175 			/*
5176 			 * If its NOT the inp_free calling us AND sctp_close
5177 			 * as been called, we call back...
5178 			 */
5179 			SCTP_INP_RUNLOCK(inp);
5180 			/*
5181 			 * This will start the kill timer (if we are the
5182 			 * last one) since we hold an increment yet. But
5183 			 * this is the only safe way to do this since
5184 			 * otherwise if the socket closes at the same time
5185 			 * we are here we might collide in the cleanup.
5186 			 */
5187 			sctp_inpcb_free(inp,
5188 			    SCTP_FREE_SHOULD_USE_GRACEFUL_CLOSE,
5189 			    SCTP_CALLED_DIRECTLY_NOCMPSET);
5190 			SCTP_INP_DECR_REF(inp);
5191 		} else {
5192 			/* The socket is still open. */
5193 			SCTP_INP_DECR_REF(inp);
5194 			SCTP_INP_RUNLOCK(inp);
5195 		}
5196 	}
5197 	/* destroyed the asoc */
5198 #ifdef SCTP_LOG_CLOSING
5199 	sctp_log_closing(inp, NULL, 11);
5200 #endif
5201 	return (1);
5202 }
5203 
5204 /*
5205  * determine if a destination is "reachable" based upon the addresses bound
5206  * to the current endpoint (e.g. only v4 or v6 currently bound)
5207  */
5208 /*
5209  * FIX: if we allow assoc-level bindx(), then this needs to be fixed to use
5210  * assoc level v4/v6 flags, as the assoc *may* not have the same address
5211  * types bound as its endpoint
5212  */
5213 int
5214 sctp_destination_is_reachable(struct sctp_tcb *stcb, struct sockaddr *destaddr)
5215 {
5216 	struct sctp_inpcb *inp;
5217 	int answer;
5218 
5219 	/*
5220 	 * No locks here, the TCB, in all cases is already locked and an
5221 	 * assoc is up. There is either a INP lock by the caller applied (in
5222 	 * asconf case when deleting an address) or NOT in the HB case,
5223 	 * however if HB then the INP increment is up and the INP will not
5224 	 * be removed (on top of the fact that we have a TCB lock). So we
5225 	 * only want to read the sctp_flags, which is either bound-all or
5226 	 * not.. no protection needed since once an assoc is up you can't be
5227 	 * changing your binding.
5228 	 */
5229 	inp = stcb->sctp_ep;
5230 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
5231 		/* if bound all, destination is not restricted */
5232 		/*
5233 		 * RRS: Question during lock work: Is this correct? If you
5234 		 * are bound-all you still might need to obey the V4--V6
5235 		 * flags??? IMO this bound-all stuff needs to be removed!
5236 		 */
5237 		return (1);
5238 	}
5239 	/* NOTE: all "scope" checks are done when local addresses are added */
5240 	switch (destaddr->sa_family) {
5241 #ifdef INET6
5242 	case AF_INET6:
5243 		answer = inp->ip_inp.inp.inp_vflag & INP_IPV6;
5244 		break;
5245 #endif
5246 #ifdef INET
5247 	case AF_INET:
5248 		answer = inp->ip_inp.inp.inp_vflag & INP_IPV4;
5249 		break;
5250 #endif
5251 	default:
5252 		/* invalid family, so it's unreachable */
5253 		answer = 0;
5254 		break;
5255 	}
5256 	return (answer);
5257 }
5258 
5259 /*
5260  * update the inp_vflags on an endpoint
5261  */
5262 static void
5263 sctp_update_ep_vflag(struct sctp_inpcb *inp)
5264 {
5265 	struct sctp_laddr *laddr;
5266 
5267 	/* first clear the flag */
5268 	inp->ip_inp.inp.inp_vflag = 0;
5269 	/* set the flag based on addresses on the ep list */
5270 	LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
5271 		if (laddr->ifa == NULL) {
5272 			SCTPDBG(SCTP_DEBUG_PCB1, "%s: NULL ifa\n",
5273 			    __func__);
5274 			continue;
5275 		}
5276 
5277 		if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
5278 			continue;
5279 		}
5280 		switch (laddr->ifa->address.sa.sa_family) {
5281 #ifdef INET6
5282 		case AF_INET6:
5283 			inp->ip_inp.inp.inp_vflag |= INP_IPV6;
5284 			break;
5285 #endif
5286 #ifdef INET
5287 		case AF_INET:
5288 			inp->ip_inp.inp.inp_vflag |= INP_IPV4;
5289 			break;
5290 #endif
5291 		default:
5292 			break;
5293 		}
5294 	}
5295 }
5296 
5297 /*
5298  * Add the address to the endpoint local address list There is nothing to be
5299  * done if we are bound to all addresses
5300  */
5301 void
5302 sctp_add_local_addr_ep(struct sctp_inpcb *inp, struct sctp_ifa *ifa, uint32_t action)
5303 {
5304 	struct sctp_laddr *laddr;
5305 	struct sctp_tcb *stcb;
5306 	int fnd, error = 0;
5307 
5308 	fnd = 0;
5309 
5310 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
5311 		/* You are already bound to all. You have it already */
5312 		return;
5313 	}
5314 #ifdef INET6
5315 	if (ifa->address.sa.sa_family == AF_INET6) {
5316 		if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
5317 			/* Can't bind a non-useable addr. */
5318 			return;
5319 		}
5320 	}
5321 #endif
5322 	/* first, is it already present? */
5323 	LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
5324 		if (laddr->ifa == ifa) {
5325 			fnd = 1;
5326 			break;
5327 		}
5328 	}
5329 
5330 	if (fnd == 0) {
5331 		/* Not in the ep list */
5332 		error = sctp_insert_laddr(&inp->sctp_addr_list, ifa, action);
5333 		if (error != 0)
5334 			return;
5335 		inp->laddr_count++;
5336 		/* update inp_vflag flags */
5337 		switch (ifa->address.sa.sa_family) {
5338 #ifdef INET6
5339 		case AF_INET6:
5340 			inp->ip_inp.inp.inp_vflag |= INP_IPV6;
5341 			break;
5342 #endif
5343 #ifdef INET
5344 		case AF_INET:
5345 			inp->ip_inp.inp.inp_vflag |= INP_IPV4;
5346 			break;
5347 #endif
5348 		default:
5349 			break;
5350 		}
5351 		LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
5352 			sctp_add_local_addr_restricted(stcb, ifa);
5353 		}
5354 	}
5355 	return;
5356 }
5357 
5358 /*
5359  * select a new (hopefully reachable) destination net (should only be used
5360  * when we deleted an ep addr that is the only usable source address to reach
5361  * the destination net)
5362  */
5363 static void
5364 sctp_select_primary_destination(struct sctp_tcb *stcb)
5365 {
5366 	struct sctp_nets *net;
5367 
5368 	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
5369 		/* for now, we'll just pick the first reachable one we find */
5370 		if (net->dest_state & SCTP_ADDR_UNCONFIRMED)
5371 			continue;
5372 		if (sctp_destination_is_reachable(stcb,
5373 		    (struct sockaddr *)&net->ro._l_addr)) {
5374 			/* found a reachable destination */
5375 			stcb->asoc.primary_destination = net;
5376 		}
5377 	}
5378 	/* I can't there from here! ...we're gonna die shortly... */
5379 }
5380 
5381 /*
5382  * Delete the address from the endpoint local address list. There is nothing
5383  * to be done if we are bound to all addresses
5384  */
5385 void
5386 sctp_del_local_addr_ep(struct sctp_inpcb *inp, struct sctp_ifa *ifa)
5387 {
5388 	struct sctp_laddr *laddr;
5389 	int fnd;
5390 
5391 	fnd = 0;
5392 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
5393 		/* You are already bound to all. You have it already */
5394 		return;
5395 	}
5396 	LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
5397 		if (laddr->ifa == ifa) {
5398 			fnd = 1;
5399 			break;
5400 		}
5401 	}
5402 	if (fnd && (inp->laddr_count < 2)) {
5403 		/* can't delete unless there are at LEAST 2 addresses */
5404 		return;
5405 	}
5406 	if (fnd) {
5407 		/*
5408 		 * clean up any use of this address go through our
5409 		 * associations and clear any last_used_address that match
5410 		 * this one for each assoc, see if a new primary_destination
5411 		 * is needed
5412 		 */
5413 		struct sctp_tcb *stcb;
5414 
5415 		/* clean up "next_addr_touse" */
5416 		if (inp->next_addr_touse == laddr)
5417 			/* delete this address */
5418 			inp->next_addr_touse = NULL;
5419 
5420 		/* clean up "last_used_address" */
5421 		LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
5422 			struct sctp_nets *net;
5423 
5424 			SCTP_TCB_LOCK(stcb);
5425 			if (stcb->asoc.last_used_address == laddr)
5426 				/* delete this address */
5427 				stcb->asoc.last_used_address = NULL;
5428 			/*
5429 			 * Now spin through all the nets and purge any ref
5430 			 * to laddr
5431 			 */
5432 			TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
5433 				if (net->ro._s_addr == laddr->ifa) {
5434 					/* Yep, purge src address selected */
5435 					RO_NHFREE(&net->ro);
5436 					sctp_free_ifa(net->ro._s_addr);
5437 					net->ro._s_addr = NULL;
5438 					net->src_addr_selected = 0;
5439 				}
5440 			}
5441 			SCTP_TCB_UNLOCK(stcb);
5442 		}		/* for each tcb */
5443 		/* remove it from the ep list */
5444 		sctp_remove_laddr(laddr);
5445 		inp->laddr_count--;
5446 		/* update inp_vflag flags */
5447 		sctp_update_ep_vflag(inp);
5448 	}
5449 	return;
5450 }
5451 
5452 /*
5453  * Add the address to the TCB local address restricted list.
5454  * This is a "pending" address list (eg. addresses waiting for an
5455  * ASCONF-ACK response) and cannot be used as a valid source address.
5456  */
5457 void
5458 sctp_add_local_addr_restricted(struct sctp_tcb *stcb, struct sctp_ifa *ifa)
5459 {
5460 	struct sctp_laddr *laddr;
5461 	struct sctpladdr *list;
5462 
5463 	/*
5464 	 * Assumes TCB is locked.. and possibly the INP. May need to
5465 	 * confirm/fix that if we need it and is not the case.
5466 	 */
5467 	list = &stcb->asoc.sctp_restricted_addrs;
5468 
5469 #ifdef INET6
5470 	if (ifa->address.sa.sa_family == AF_INET6) {
5471 		if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
5472 			/* Can't bind a non-existent addr. */
5473 			return;
5474 		}
5475 	}
5476 #endif
5477 	/* does the address already exist? */
5478 	LIST_FOREACH(laddr, list, sctp_nxt_addr) {
5479 		if (laddr->ifa == ifa) {
5480 			return;
5481 		}
5482 	}
5483 
5484 	/* add to the list */
5485 	(void)sctp_insert_laddr(list, ifa, 0);
5486 	return;
5487 }
5488 
5489 /*
5490  * Remove a local address from the TCB local address restricted list
5491  */
5492 void
5493 sctp_del_local_addr_restricted(struct sctp_tcb *stcb, struct sctp_ifa *ifa)
5494 {
5495 	struct sctp_inpcb *inp;
5496 	struct sctp_laddr *laddr;
5497 
5498 	/*
5499 	 * This is called by asconf work. It is assumed that a) The TCB is
5500 	 * locked and b) The INP is locked. This is true in as much as I can
5501 	 * trace through the entry asconf code where I did these locks.
5502 	 * Again, the ASCONF code is a bit different in that it does lock
5503 	 * the INP during its work often times. This must be since we don't
5504 	 * want other proc's looking up things while what they are looking
5505 	 * up is changing :-D
5506 	 */
5507 
5508 	inp = stcb->sctp_ep;
5509 	/* if subset bound and don't allow ASCONF's, can't delete last */
5510 	if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) &&
5511 	    sctp_is_feature_off(inp, SCTP_PCB_FLAGS_DO_ASCONF)) {
5512 		if (stcb->sctp_ep->laddr_count < 2) {
5513 			/* can't delete last address */
5514 			return;
5515 		}
5516 	}
5517 	LIST_FOREACH(laddr, &stcb->asoc.sctp_restricted_addrs, sctp_nxt_addr) {
5518 		/* remove the address if it exists */
5519 		if (laddr->ifa == NULL)
5520 			continue;
5521 		if (laddr->ifa == ifa) {
5522 			sctp_remove_laddr(laddr);
5523 			return;
5524 		}
5525 	}
5526 
5527 	/* address not found! */
5528 	return;
5529 }
5530 
5531 /* sysctl */
5532 static int sctp_max_number_of_assoc = SCTP_MAX_NUM_OF_ASOC;
5533 static int sctp_scale_up_for_address = SCTP_SCALE_FOR_ADDR;
5534 
5535 #if defined(SCTP_MCORE_INPUT) && defined(SMP)
5536 struct sctp_mcore_ctrl *sctp_mcore_workers = NULL;
5537 int *sctp_cpuarry = NULL;
5538 
5539 void
5540 sctp_queue_to_mcore(struct mbuf *m, int off, int cpu_to_use)
5541 {
5542 	/* Queue a packet to a processor for the specified core */
5543 	struct sctp_mcore_queue *qent;
5544 	struct sctp_mcore_ctrl *wkq;
5545 	int need_wake = 0;
5546 
5547 	if (sctp_mcore_workers == NULL) {
5548 		/* Something went way bad during setup */
5549 		sctp_input_with_port(m, off, 0);
5550 		return;
5551 	}
5552 	SCTP_MALLOC(qent, struct sctp_mcore_queue *,
5553 	    (sizeof(struct sctp_mcore_queue)),
5554 	    SCTP_M_MCORE);
5555 	if (qent == NULL) {
5556 		/* This is trouble  */
5557 		sctp_input_with_port(m, off, 0);
5558 		return;
5559 	}
5560 	qent->vn = curvnet;
5561 	qent->m = m;
5562 	qent->off = off;
5563 	qent->v6 = 0;
5564 	wkq = &sctp_mcore_workers[cpu_to_use];
5565 	SCTP_MCORE_QLOCK(wkq);
5566 
5567 	TAILQ_INSERT_TAIL(&wkq->que, qent, next);
5568 	if (wkq->running == 0) {
5569 		need_wake = 1;
5570 	}
5571 	SCTP_MCORE_QUNLOCK(wkq);
5572 	if (need_wake) {
5573 		wakeup(&wkq->running);
5574 	}
5575 }
5576 
5577 static void
5578 sctp_mcore_thread(void *arg)
5579 {
5580 
5581 	struct sctp_mcore_ctrl *wkq;
5582 	struct sctp_mcore_queue *qent;
5583 
5584 	wkq = (struct sctp_mcore_ctrl *)arg;
5585 	struct mbuf *m;
5586 	int off, v6;
5587 
5588 	/* Wait for first tickle */
5589 	SCTP_MCORE_LOCK(wkq);
5590 	wkq->running = 0;
5591 	msleep(&wkq->running,
5592 	    &wkq->core_mtx,
5593 	    0, "wait for pkt", 0);
5594 	SCTP_MCORE_UNLOCK(wkq);
5595 
5596 	/* Bind to our cpu */
5597 	thread_lock(curthread);
5598 	sched_bind(curthread, wkq->cpuid);
5599 	thread_unlock(curthread);
5600 
5601 	/* Now lets start working */
5602 	SCTP_MCORE_LOCK(wkq);
5603 	/* Now grab lock and go */
5604 	for (;;) {
5605 		SCTP_MCORE_QLOCK(wkq);
5606 skip_sleep:
5607 		wkq->running = 1;
5608 		qent = TAILQ_FIRST(&wkq->que);
5609 		if (qent) {
5610 			TAILQ_REMOVE(&wkq->que, qent, next);
5611 			SCTP_MCORE_QUNLOCK(wkq);
5612 			CURVNET_SET(qent->vn);
5613 			m = qent->m;
5614 			off = qent->off;
5615 			v6 = qent->v6;
5616 			SCTP_FREE(qent, SCTP_M_MCORE);
5617 			if (v6 == 0) {
5618 				sctp_input_with_port(m, off, 0);
5619 			} else {
5620 				SCTP_PRINTF("V6 not yet supported\n");
5621 				sctp_m_freem(m);
5622 			}
5623 			CURVNET_RESTORE();
5624 			SCTP_MCORE_QLOCK(wkq);
5625 		}
5626 		wkq->running = 0;
5627 		if (!TAILQ_EMPTY(&wkq->que)) {
5628 			goto skip_sleep;
5629 		}
5630 		SCTP_MCORE_QUNLOCK(wkq);
5631 		msleep(&wkq->running,
5632 		    &wkq->core_mtx,
5633 		    0, "wait for pkt", 0);
5634 	}
5635 }
5636 
5637 static void
5638 sctp_startup_mcore_threads(void)
5639 {
5640 	int i, cpu;
5641 
5642 	if (mp_ncpus == 1)
5643 		return;
5644 
5645 	if (sctp_mcore_workers != NULL) {
5646 		/*
5647 		 * Already been here in some previous vnet?
5648 		 */
5649 		return;
5650 	}
5651 	SCTP_MALLOC(sctp_mcore_workers, struct sctp_mcore_ctrl *,
5652 	    ((mp_maxid + 1) * sizeof(struct sctp_mcore_ctrl)),
5653 	    SCTP_M_MCORE);
5654 	if (sctp_mcore_workers == NULL) {
5655 		/* TSNH I hope */
5656 		return;
5657 	}
5658 	memset(sctp_mcore_workers, 0, ((mp_maxid + 1) *
5659 	    sizeof(struct sctp_mcore_ctrl)));
5660 	/* Init the structures */
5661 	for (i = 0; i <= mp_maxid; i++) {
5662 		TAILQ_INIT(&sctp_mcore_workers[i].que);
5663 		SCTP_MCORE_LOCK_INIT(&sctp_mcore_workers[i]);
5664 		SCTP_MCORE_QLOCK_INIT(&sctp_mcore_workers[i]);
5665 		sctp_mcore_workers[i].cpuid = i;
5666 	}
5667 	if (sctp_cpuarry == NULL) {
5668 		SCTP_MALLOC(sctp_cpuarry, int *,
5669 		    (mp_ncpus * sizeof(int)),
5670 		    SCTP_M_MCORE);
5671 		i = 0;
5672 		CPU_FOREACH(cpu) {
5673 			sctp_cpuarry[i] = cpu;
5674 			i++;
5675 		}
5676 	}
5677 	/* Now start them all */
5678 	CPU_FOREACH(cpu) {
5679 		(void)kproc_create(sctp_mcore_thread,
5680 		    (void *)&sctp_mcore_workers[cpu],
5681 		    &sctp_mcore_workers[cpu].thread_proc,
5682 		    0,
5683 		    SCTP_KTHREAD_PAGES,
5684 		    SCTP_MCORE_NAME);
5685 	}
5686 }
5687 #endif
5688 
5689 void
5690 sctp_pcb_init(void)
5691 {
5692 	/*
5693 	 * SCTP initialization for the PCB structures should be called by
5694 	 * the sctp_init() function.
5695 	 */
5696 	int i;
5697 	struct timeval tv;
5698 
5699 	if (SCTP_BASE_VAR(sctp_pcb_initialized) != 0) {
5700 		/* error I was called twice */
5701 		return;
5702 	}
5703 	SCTP_BASE_VAR(sctp_pcb_initialized) = 1;
5704 
5705 #if defined(SCTP_LOCAL_TRACE_BUF)
5706 	memset(&SCTP_BASE_SYSCTL(sctp_log), 0, sizeof(struct sctp_log));
5707 #endif
5708 #if defined(SMP) && defined(SCTP_USE_PERCPU_STAT)
5709 	SCTP_MALLOC(SCTP_BASE_STATS, struct sctpstat *,
5710 	    ((mp_maxid + 1) * sizeof(struct sctpstat)),
5711 	    SCTP_M_MCORE);
5712 #endif
5713 	(void)SCTP_GETTIME_TIMEVAL(&tv);
5714 #if defined(SMP) && defined(SCTP_USE_PERCPU_STAT)
5715 	memset(SCTP_BASE_STATS, 0, sizeof(struct sctpstat) * (mp_maxid + 1));
5716 	SCTP_BASE_STATS[PCPU_GET(cpuid)].sctps_discontinuitytime.tv_sec = (uint32_t)tv.tv_sec;
5717 	SCTP_BASE_STATS[PCPU_GET(cpuid)].sctps_discontinuitytime.tv_usec = (uint32_t)tv.tv_usec;
5718 #else
5719 	memset(&SCTP_BASE_STATS, 0, sizeof(struct sctpstat));
5720 	SCTP_BASE_STAT(sctps_discontinuitytime).tv_sec = (uint32_t)tv.tv_sec;
5721 	SCTP_BASE_STAT(sctps_discontinuitytime).tv_usec = (uint32_t)tv.tv_usec;
5722 #endif
5723 	/* init the empty list of (All) Endpoints */
5724 	LIST_INIT(&SCTP_BASE_INFO(listhead));
5725 
5726 	/* init the hash table of endpoints */
5727 	TUNABLE_INT_FETCH("net.inet.sctp.tcbhashsize", &SCTP_BASE_SYSCTL(sctp_hashtblsize));
5728 	TUNABLE_INT_FETCH("net.inet.sctp.pcbhashsize", &SCTP_BASE_SYSCTL(sctp_pcbtblsize));
5729 	TUNABLE_INT_FETCH("net.inet.sctp.chunkscale", &SCTP_BASE_SYSCTL(sctp_chunkscale));
5730 	SCTP_BASE_INFO(sctp_asochash) = SCTP_HASH_INIT((SCTP_BASE_SYSCTL(sctp_hashtblsize) * 31),
5731 	    &SCTP_BASE_INFO(hashasocmark));
5732 	SCTP_BASE_INFO(sctp_ephash) = SCTP_HASH_INIT(SCTP_BASE_SYSCTL(sctp_hashtblsize),
5733 	    &SCTP_BASE_INFO(hashmark));
5734 	SCTP_BASE_INFO(sctp_tcpephash) = SCTP_HASH_INIT(SCTP_BASE_SYSCTL(sctp_hashtblsize),
5735 	    &SCTP_BASE_INFO(hashtcpmark));
5736 	SCTP_BASE_INFO(hashtblsize) = SCTP_BASE_SYSCTL(sctp_hashtblsize);
5737 	SCTP_BASE_INFO(sctp_vrfhash) = SCTP_HASH_INIT(SCTP_SIZE_OF_VRF_HASH,
5738 	    &SCTP_BASE_INFO(hashvrfmark));
5739 
5740 	SCTP_BASE_INFO(vrf_ifn_hash) = SCTP_HASH_INIT(SCTP_VRF_IFN_HASH_SIZE,
5741 	    &SCTP_BASE_INFO(vrf_ifn_hashmark));
5742 	/* init the zones */
5743 	/*
5744 	 * FIX ME: Should check for NULL returns, but if it does fail we are
5745 	 * doomed to panic anyways... add later maybe.
5746 	 */
5747 	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_ep), "sctp_ep",
5748 	    sizeof(struct sctp_inpcb), maxsockets);
5749 
5750 	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_asoc), "sctp_asoc",
5751 	    sizeof(struct sctp_tcb), sctp_max_number_of_assoc);
5752 
5753 	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_laddr), "sctp_laddr",
5754 	    sizeof(struct sctp_laddr),
5755 	    (sctp_max_number_of_assoc * sctp_scale_up_for_address));
5756 
5757 	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_net), "sctp_raddr",
5758 	    sizeof(struct sctp_nets),
5759 	    (sctp_max_number_of_assoc * sctp_scale_up_for_address));
5760 
5761 	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_chunk), "sctp_chunk",
5762 	    sizeof(struct sctp_tmit_chunk),
5763 	    (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
5764 
5765 	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_readq), "sctp_readq",
5766 	    sizeof(struct sctp_queued_to_read),
5767 	    (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
5768 
5769 	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_strmoq), "sctp_stream_msg_out",
5770 	    sizeof(struct sctp_stream_queue_pending),
5771 	    (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
5772 
5773 	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_asconf), "sctp_asconf",
5774 	    sizeof(struct sctp_asconf),
5775 	    (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
5776 
5777 	SCTP_ZONE_INIT(SCTP_BASE_INFO(ipi_zone_asconf_ack), "sctp_asconf_ack",
5778 	    sizeof(struct sctp_asconf_ack),
5779 	    (sctp_max_number_of_assoc * SCTP_BASE_SYSCTL(sctp_chunkscale)));
5780 
5781 	/* Master Lock INIT for info structure */
5782 	SCTP_INP_INFO_LOCK_INIT();
5783 	SCTP_STATLOG_INIT_LOCK();
5784 
5785 	SCTP_IPI_COUNT_INIT();
5786 	SCTP_IPI_ADDR_INIT();
5787 #ifdef SCTP_PACKET_LOGGING
5788 	SCTP_IP_PKTLOG_INIT();
5789 #endif
5790 	LIST_INIT(&SCTP_BASE_INFO(addr_wq));
5791 
5792 	SCTP_WQ_ADDR_INIT();
5793 	/* not sure if we need all the counts */
5794 	SCTP_BASE_INFO(ipi_count_ep) = 0;
5795 	/* assoc/tcb zone info */
5796 	SCTP_BASE_INFO(ipi_count_asoc) = 0;
5797 	/* local addrlist zone info */
5798 	SCTP_BASE_INFO(ipi_count_laddr) = 0;
5799 	/* remote addrlist zone info */
5800 	SCTP_BASE_INFO(ipi_count_raddr) = 0;
5801 	/* chunk info */
5802 	SCTP_BASE_INFO(ipi_count_chunk) = 0;
5803 
5804 	/* socket queue zone info */
5805 	SCTP_BASE_INFO(ipi_count_readq) = 0;
5806 
5807 	/* stream out queue cont */
5808 	SCTP_BASE_INFO(ipi_count_strmoq) = 0;
5809 
5810 	SCTP_BASE_INFO(ipi_free_strmoq) = 0;
5811 	SCTP_BASE_INFO(ipi_free_chunks) = 0;
5812 
5813 	SCTP_OS_TIMER_INIT(&SCTP_BASE_INFO(addr_wq_timer.timer));
5814 
5815 	/* Init the TIMEWAIT list */
5816 	for (i = 0; i < SCTP_STACK_VTAG_HASH_SIZE; i++) {
5817 		LIST_INIT(&SCTP_BASE_INFO(vtag_timewait)[i]);
5818 	}
5819 	sctp_startup_iterator();
5820 
5821 #if defined(SCTP_MCORE_INPUT) && defined(SMP)
5822 	sctp_startup_mcore_threads();
5823 #endif
5824 
5825 	/*
5826 	 * INIT the default VRF which for BSD is the only one, other O/S's
5827 	 * may have more. But initially they must start with one and then
5828 	 * add the VRF's as addresses are added.
5829 	 */
5830 	sctp_init_vrf_list(SCTP_DEFAULT_VRF);
5831 }
5832 
5833 /*
5834  * Assumes that the SCTP_BASE_INFO() lock is NOT held.
5835  */
5836 void
5837 sctp_pcb_finish(void)
5838 {
5839 	struct sctp_vrflist *vrf_bucket;
5840 	struct sctp_vrf *vrf, *nvrf;
5841 	struct sctp_ifn *ifn, *nifn;
5842 	struct sctp_ifa *ifa, *nifa;
5843 	struct sctpvtaghead *chain;
5844 	struct sctp_tagblock *twait_block, *prev_twait_block;
5845 	struct sctp_laddr *wi, *nwi;
5846 	int i;
5847 	struct sctp_iterator *it, *nit;
5848 
5849 	if (SCTP_BASE_VAR(sctp_pcb_initialized) == 0) {
5850 		SCTP_PRINTF("%s: race condition on teardown.\n", __func__);
5851 		return;
5852 	}
5853 	SCTP_BASE_VAR(sctp_pcb_initialized) = 0;
5854 	/*
5855 	 * In FreeBSD the iterator thread never exits but we do clean up.
5856 	 * The only way FreeBSD reaches here is if we have VRF's but we
5857 	 * still add the ifdef to make it compile on old versions.
5858 	 */
5859 retry:
5860 	SCTP_IPI_ITERATOR_WQ_LOCK();
5861 	/*
5862 	 * sctp_iterator_worker() might be working on an it entry without
5863 	 * holding the lock.  We won't find it on the list either and
5864 	 * continue and free/destroy it.  While holding the lock, spin, to
5865 	 * avoid the race condition as sctp_iterator_worker() will have to
5866 	 * wait to re-acquire the lock.
5867 	 */
5868 	if (sctp_it_ctl.iterator_running != 0 || sctp_it_ctl.cur_it != NULL) {
5869 		SCTP_IPI_ITERATOR_WQ_UNLOCK();
5870 		SCTP_PRINTF("%s: Iterator running while we held the lock. Retry. "
5871 		    "cur_it=%p\n", __func__, sctp_it_ctl.cur_it);
5872 		DELAY(10);
5873 		goto retry;
5874 	}
5875 	TAILQ_FOREACH_SAFE(it, &sctp_it_ctl.iteratorhead, sctp_nxt_itr, nit) {
5876 		if (it->vn != curvnet) {
5877 			continue;
5878 		}
5879 		TAILQ_REMOVE(&sctp_it_ctl.iteratorhead, it, sctp_nxt_itr);
5880 		if (it->function_atend != NULL) {
5881 			(*it->function_atend) (it->pointer, it->val);
5882 		}
5883 		SCTP_FREE(it, SCTP_M_ITER);
5884 	}
5885 	SCTP_IPI_ITERATOR_WQ_UNLOCK();
5886 	SCTP_ITERATOR_LOCK();
5887 	if ((sctp_it_ctl.cur_it) &&
5888 	    (sctp_it_ctl.cur_it->vn == curvnet)) {
5889 		sctp_it_ctl.iterator_flags |= SCTP_ITERATOR_STOP_CUR_IT;
5890 	}
5891 	SCTP_ITERATOR_UNLOCK();
5892 	SCTP_OS_TIMER_STOP_DRAIN(&SCTP_BASE_INFO(addr_wq_timer.timer));
5893 	SCTP_WQ_ADDR_LOCK();
5894 	LIST_FOREACH_SAFE(wi, &SCTP_BASE_INFO(addr_wq), sctp_nxt_addr, nwi) {
5895 		LIST_REMOVE(wi, sctp_nxt_addr);
5896 		SCTP_DECR_LADDR_COUNT();
5897 		if (wi->action == SCTP_DEL_IP_ADDRESS) {
5898 			SCTP_FREE(wi->ifa, SCTP_M_IFA);
5899 		}
5900 		SCTP_ZONE_FREE(SCTP_BASE_INFO(ipi_zone_laddr), wi);
5901 	}
5902 	SCTP_WQ_ADDR_UNLOCK();
5903 
5904 	/*
5905 	 * free the vrf/ifn/ifa lists and hashes (be sure address monitor is
5906 	 * destroyed first).
5907 	 */
5908 	SCTP_IPI_ADDR_WLOCK();
5909 	vrf_bucket = &SCTP_BASE_INFO(sctp_vrfhash)[(SCTP_DEFAULT_VRFID & SCTP_BASE_INFO(hashvrfmark))];
5910 	LIST_FOREACH_SAFE(vrf, vrf_bucket, next_vrf, nvrf) {
5911 		LIST_FOREACH_SAFE(ifn, &vrf->ifnlist, next_ifn, nifn) {
5912 			LIST_FOREACH_SAFE(ifa, &ifn->ifalist, next_ifa, nifa) {
5913 				/* free the ifa */
5914 				LIST_REMOVE(ifa, next_bucket);
5915 				LIST_REMOVE(ifa, next_ifa);
5916 				SCTP_FREE(ifa, SCTP_M_IFA);
5917 			}
5918 			/* free the ifn */
5919 			LIST_REMOVE(ifn, next_bucket);
5920 			LIST_REMOVE(ifn, next_ifn);
5921 			SCTP_FREE(ifn, SCTP_M_IFN);
5922 		}
5923 		SCTP_HASH_FREE(vrf->vrf_addr_hash, vrf->vrf_addr_hashmark);
5924 		/* free the vrf */
5925 		LIST_REMOVE(vrf, next_vrf);
5926 		SCTP_FREE(vrf, SCTP_M_VRF);
5927 	}
5928 	SCTP_IPI_ADDR_WUNLOCK();
5929 	/* free the vrf hashes */
5930 	SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_vrfhash), SCTP_BASE_INFO(hashvrfmark));
5931 	SCTP_HASH_FREE(SCTP_BASE_INFO(vrf_ifn_hash), SCTP_BASE_INFO(vrf_ifn_hashmark));
5932 
5933 	/*
5934 	 * free the TIMEWAIT list elements malloc'd in the function
5935 	 * sctp_add_vtag_to_timewait()...
5936 	 */
5937 	for (i = 0; i < SCTP_STACK_VTAG_HASH_SIZE; i++) {
5938 		chain = &SCTP_BASE_INFO(vtag_timewait)[i];
5939 		if (!LIST_EMPTY(chain)) {
5940 			prev_twait_block = NULL;
5941 			LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
5942 				if (prev_twait_block) {
5943 					SCTP_FREE(prev_twait_block, SCTP_M_TIMW);
5944 				}
5945 				prev_twait_block = twait_block;
5946 			}
5947 			SCTP_FREE(prev_twait_block, SCTP_M_TIMW);
5948 		}
5949 	}
5950 
5951 	/* free the locks and mutexes */
5952 #ifdef SCTP_PACKET_LOGGING
5953 	SCTP_IP_PKTLOG_DESTROY();
5954 #endif
5955 	SCTP_IPI_ADDR_DESTROY();
5956 	SCTP_STATLOG_DESTROY();
5957 	SCTP_INP_INFO_LOCK_DESTROY();
5958 
5959 	SCTP_WQ_ADDR_DESTROY();
5960 
5961 	/* Get rid of other stuff too. */
5962 	if (SCTP_BASE_INFO(sctp_asochash) != NULL)
5963 		SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_asochash), SCTP_BASE_INFO(hashasocmark));
5964 	if (SCTP_BASE_INFO(sctp_ephash) != NULL)
5965 		SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_ephash), SCTP_BASE_INFO(hashmark));
5966 	if (SCTP_BASE_INFO(sctp_tcpephash) != NULL)
5967 		SCTP_HASH_FREE(SCTP_BASE_INFO(sctp_tcpephash), SCTP_BASE_INFO(hashtcpmark));
5968 
5969 	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_ep));
5970 	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_asoc));
5971 	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_laddr));
5972 	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_net));
5973 	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_chunk));
5974 	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_readq));
5975 	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_strmoq));
5976 	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_asconf));
5977 	SCTP_ZONE_DESTROY(SCTP_BASE_INFO(ipi_zone_asconf_ack));
5978 #if defined(SMP) && defined(SCTP_USE_PERCPU_STAT)
5979 	SCTP_FREE(SCTP_BASE_STATS, SCTP_M_MCORE);
5980 #endif
5981 }
5982 
5983 int
5984 sctp_load_addresses_from_init(struct sctp_tcb *stcb, struct mbuf *m,
5985     int offset, int limit,
5986     struct sockaddr *src, struct sockaddr *dst,
5987     struct sockaddr *altsa, uint16_t port)
5988 {
5989 	/*
5990 	 * grub through the INIT pulling addresses and loading them to the
5991 	 * nets structure in the asoc. The from address in the mbuf should
5992 	 * also be loaded (if it is not already). This routine can be called
5993 	 * with either INIT or INIT-ACK's as long as the m points to the IP
5994 	 * packet and the offset points to the beginning of the parameters.
5995 	 */
5996 	struct sctp_inpcb *inp;
5997 	struct sctp_nets *net, *nnet, *net_tmp;
5998 	struct sctp_paramhdr *phdr, param_buf;
5999 	struct sctp_tcb *stcb_tmp;
6000 	uint16_t ptype, plen;
6001 	struct sockaddr *sa;
6002 	uint8_t random_store[SCTP_PARAM_BUFFER_SIZE];
6003 	struct sctp_auth_random *p_random = NULL;
6004 	uint16_t random_len = 0;
6005 	uint8_t hmacs_store[SCTP_PARAM_BUFFER_SIZE];
6006 	struct sctp_auth_hmac_algo *hmacs = NULL;
6007 	uint16_t hmacs_len = 0;
6008 	uint8_t saw_asconf = 0;
6009 	uint8_t saw_asconf_ack = 0;
6010 	uint8_t chunks_store[SCTP_PARAM_BUFFER_SIZE];
6011 	struct sctp_auth_chunk_list *chunks = NULL;
6012 	uint16_t num_chunks = 0;
6013 	sctp_key_t *new_key;
6014 	uint32_t keylen;
6015 	int got_random = 0, got_hmacs = 0, got_chklist = 0;
6016 	uint8_t peer_supports_ecn;
6017 	uint8_t peer_supports_prsctp;
6018 	uint8_t peer_supports_auth;
6019 	uint8_t peer_supports_asconf;
6020 	uint8_t peer_supports_asconf_ack;
6021 	uint8_t peer_supports_reconfig;
6022 	uint8_t peer_supports_nrsack;
6023 	uint8_t peer_supports_pktdrop;
6024 	uint8_t peer_supports_idata;
6025 #ifdef INET
6026 	struct sockaddr_in sin;
6027 #endif
6028 #ifdef INET6
6029 	struct sockaddr_in6 sin6;
6030 #endif
6031 
6032 	/* First get the destination address setup too. */
6033 #ifdef INET
6034 	memset(&sin, 0, sizeof(sin));
6035 	sin.sin_family = AF_INET;
6036 	sin.sin_len = sizeof(sin);
6037 	sin.sin_port = stcb->rport;
6038 #endif
6039 #ifdef INET6
6040 	memset(&sin6, 0, sizeof(sin6));
6041 	sin6.sin6_family = AF_INET6;
6042 	sin6.sin6_len = sizeof(struct sockaddr_in6);
6043 	sin6.sin6_port = stcb->rport;
6044 #endif
6045 	if (altsa) {
6046 		sa = altsa;
6047 	} else {
6048 		sa = src;
6049 	}
6050 	peer_supports_idata = 0;
6051 	peer_supports_ecn = 0;
6052 	peer_supports_prsctp = 0;
6053 	peer_supports_auth = 0;
6054 	peer_supports_asconf = 0;
6055 	peer_supports_asconf_ack = 0;
6056 	peer_supports_reconfig = 0;
6057 	peer_supports_nrsack = 0;
6058 	peer_supports_pktdrop = 0;
6059 	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
6060 		/* mark all addresses that we have currently on the list */
6061 		net->dest_state |= SCTP_ADDR_NOT_IN_ASSOC;
6062 	}
6063 	/* does the source address already exist? if so skip it */
6064 	inp = stcb->sctp_ep;
6065 	atomic_add_int(&stcb->asoc.refcnt, 1);
6066 	stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net_tmp, dst, stcb);
6067 	atomic_subtract_int(&stcb->asoc.refcnt, 1);
6068 
6069 	if ((stcb_tmp == NULL && inp == stcb->sctp_ep) || inp == NULL) {
6070 		/* we must add the source address */
6071 		/* no scope set here since we have a tcb already. */
6072 		switch (sa->sa_family) {
6073 #ifdef INET
6074 		case AF_INET:
6075 			if (stcb->asoc.scope.ipv4_addr_legal) {
6076 				if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_2)) {
6077 					return (-1);
6078 				}
6079 			}
6080 			break;
6081 #endif
6082 #ifdef INET6
6083 		case AF_INET6:
6084 			if (stcb->asoc.scope.ipv6_addr_legal) {
6085 				if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_3)) {
6086 					return (-2);
6087 				}
6088 			}
6089 			break;
6090 #endif
6091 		default:
6092 			break;
6093 		}
6094 	} else {
6095 		if (net_tmp != NULL && stcb_tmp == stcb) {
6096 			net_tmp->dest_state &= ~SCTP_ADDR_NOT_IN_ASSOC;
6097 		} else if (stcb_tmp != stcb) {
6098 			/* It belongs to another association? */
6099 			if (stcb_tmp)
6100 				SCTP_TCB_UNLOCK(stcb_tmp);
6101 			return (-3);
6102 		}
6103 	}
6104 	if (stcb->asoc.state == 0) {
6105 		/* the assoc was freed? */
6106 		return (-4);
6107 	}
6108 	/* now we must go through each of the params. */
6109 	phdr = sctp_get_next_param(m, offset, &param_buf, sizeof(param_buf));
6110 	while (phdr) {
6111 		ptype = ntohs(phdr->param_type);
6112 		plen = ntohs(phdr->param_length);
6113 		/*
6114 		 * SCTP_PRINTF("ptype => %0x, plen => %d\n",
6115 		 * (uint32_t)ptype, (int)plen);
6116 		 */
6117 		if (offset + plen > limit) {
6118 			break;
6119 		}
6120 		if (plen < sizeof(struct sctp_paramhdr)) {
6121 			break;
6122 		}
6123 #ifdef INET
6124 		if (ptype == SCTP_IPV4_ADDRESS) {
6125 			if (stcb->asoc.scope.ipv4_addr_legal) {
6126 				struct sctp_ipv4addr_param *p4, p4_buf;
6127 
6128 				/* ok get the v4 address and check/add */
6129 				phdr = sctp_get_next_param(m, offset,
6130 				    (struct sctp_paramhdr *)&p4_buf,
6131 				    sizeof(p4_buf));
6132 				if (plen != sizeof(struct sctp_ipv4addr_param) ||
6133 				    phdr == NULL) {
6134 					return (-5);
6135 				}
6136 				p4 = (struct sctp_ipv4addr_param *)phdr;
6137 				sin.sin_addr.s_addr = p4->addr;
6138 				if (IN_MULTICAST(ntohl(sin.sin_addr.s_addr))) {
6139 					/* Skip multi-cast addresses */
6140 					goto next_param;
6141 				}
6142 				if ((sin.sin_addr.s_addr == INADDR_BROADCAST) ||
6143 				    (sin.sin_addr.s_addr == INADDR_ANY)) {
6144 					goto next_param;
6145 				}
6146 				sa = (struct sockaddr *)&sin;
6147 				inp = stcb->sctp_ep;
6148 				atomic_add_int(&stcb->asoc.refcnt, 1);
6149 				stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net,
6150 				    dst, stcb);
6151 				atomic_subtract_int(&stcb->asoc.refcnt, 1);
6152 
6153 				if ((stcb_tmp == NULL && inp == stcb->sctp_ep) ||
6154 				    inp == NULL) {
6155 					/* we must add the source address */
6156 					/*
6157 					 * no scope set since we have a tcb
6158 					 * already
6159 					 */
6160 
6161 					/*
6162 					 * we must validate the state again
6163 					 * here
6164 					 */
6165 			add_it_now:
6166 					if (stcb->asoc.state == 0) {
6167 						/* the assoc was freed? */
6168 						return (-7);
6169 					}
6170 					if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_4)) {
6171 						return (-8);
6172 					}
6173 				} else if (stcb_tmp == stcb) {
6174 					if (stcb->asoc.state == 0) {
6175 						/* the assoc was freed? */
6176 						return (-10);
6177 					}
6178 					if (net != NULL) {
6179 						/* clear flag */
6180 						net->dest_state &=
6181 						    ~SCTP_ADDR_NOT_IN_ASSOC;
6182 					}
6183 				} else {
6184 					/*
6185 					 * strange, address is in another
6186 					 * assoc? straighten out locks.
6187 					 */
6188 					if (stcb_tmp) {
6189 						if (SCTP_GET_STATE(stcb_tmp) == SCTP_STATE_COOKIE_WAIT) {
6190 							struct mbuf *op_err;
6191 							char msg[SCTP_DIAG_INFO_LEN];
6192 
6193 							/*
6194 							 * in setup state we
6195 							 * abort this guy
6196 							 */
6197 							SCTP_SNPRINTF(msg, sizeof(msg),
6198 							    "%s:%d at %s", __FILE__, __LINE__, __func__);
6199 							op_err = sctp_generate_cause(SCTP_BASE_SYSCTL(sctp_diag_info_code),
6200 							    msg);
6201 							sctp_abort_an_association(stcb_tmp->sctp_ep,
6202 							    stcb_tmp, op_err, false,
6203 							    SCTP_SO_NOT_LOCKED);
6204 							goto add_it_now;
6205 						}
6206 						SCTP_TCB_UNLOCK(stcb_tmp);
6207 					}
6208 
6209 					if (stcb->asoc.state == 0) {
6210 						/* the assoc was freed? */
6211 						return (-12);
6212 					}
6213 					return (-13);
6214 				}
6215 			}
6216 		} else
6217 #endif
6218 #ifdef INET6
6219 		if (ptype == SCTP_IPV6_ADDRESS) {
6220 			if (stcb->asoc.scope.ipv6_addr_legal) {
6221 				/* ok get the v6 address and check/add */
6222 				struct sctp_ipv6addr_param *p6, p6_buf;
6223 
6224 				phdr = sctp_get_next_param(m, offset,
6225 				    (struct sctp_paramhdr *)&p6_buf,
6226 				    sizeof(p6_buf));
6227 				if (plen != sizeof(struct sctp_ipv6addr_param) ||
6228 				    phdr == NULL) {
6229 					return (-14);
6230 				}
6231 				p6 = (struct sctp_ipv6addr_param *)phdr;
6232 				memcpy((caddr_t)&sin6.sin6_addr, p6->addr,
6233 				    sizeof(p6->addr));
6234 				if (IN6_IS_ADDR_MULTICAST(&sin6.sin6_addr)) {
6235 					/* Skip multi-cast addresses */
6236 					goto next_param;
6237 				}
6238 				if (IN6_IS_ADDR_LINKLOCAL(&sin6.sin6_addr)) {
6239 					/*
6240 					 * Link local make no sense without
6241 					 * scope
6242 					 */
6243 					goto next_param;
6244 				}
6245 				sa = (struct sockaddr *)&sin6;
6246 				inp = stcb->sctp_ep;
6247 				atomic_add_int(&stcb->asoc.refcnt, 1);
6248 				stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net,
6249 				    dst, stcb);
6250 				atomic_subtract_int(&stcb->asoc.refcnt, 1);
6251 				if (stcb_tmp == NULL &&
6252 				    (inp == stcb->sctp_ep || inp == NULL)) {
6253 					/*
6254 					 * we must validate the state again
6255 					 * here
6256 					 */
6257 			add_it_now6:
6258 					if (stcb->asoc.state == 0) {
6259 						/* the assoc was freed? */
6260 						return (-16);
6261 					}
6262 					/*
6263 					 * we must add the address, no scope
6264 					 * set
6265 					 */
6266 					if (sctp_add_remote_addr(stcb, sa, NULL, port, SCTP_DONOT_SETSCOPE, SCTP_LOAD_ADDR_5)) {
6267 						return (-17);
6268 					}
6269 				} else if (stcb_tmp == stcb) {
6270 					/*
6271 					 * we must validate the state again
6272 					 * here
6273 					 */
6274 					if (stcb->asoc.state == 0) {
6275 						/* the assoc was freed? */
6276 						return (-19);
6277 					}
6278 					if (net != NULL) {
6279 						/* clear flag */
6280 						net->dest_state &=
6281 						    ~SCTP_ADDR_NOT_IN_ASSOC;
6282 					}
6283 				} else {
6284 					/*
6285 					 * strange, address is in another
6286 					 * assoc? straighten out locks.
6287 					 */
6288 					if (stcb_tmp) {
6289 						if (SCTP_GET_STATE(stcb_tmp) == SCTP_STATE_COOKIE_WAIT) {
6290 							struct mbuf *op_err;
6291 							char msg[SCTP_DIAG_INFO_LEN];
6292 
6293 							/*
6294 							 * in setup state we
6295 							 * abort this guy
6296 							 */
6297 							SCTP_SNPRINTF(msg, sizeof(msg),
6298 							    "%s:%d at %s", __FILE__, __LINE__, __func__);
6299 							op_err = sctp_generate_cause(SCTP_BASE_SYSCTL(sctp_diag_info_code),
6300 							    msg);
6301 							sctp_abort_an_association(stcb_tmp->sctp_ep,
6302 							    stcb_tmp, op_err, false,
6303 							    SCTP_SO_NOT_LOCKED);
6304 							goto add_it_now6;
6305 						}
6306 						SCTP_TCB_UNLOCK(stcb_tmp);
6307 					}
6308 					if (stcb->asoc.state == 0) {
6309 						/* the assoc was freed? */
6310 						return (-21);
6311 					}
6312 					return (-22);
6313 				}
6314 			}
6315 		} else
6316 #endif
6317 		if (ptype == SCTP_ECN_CAPABLE) {
6318 			peer_supports_ecn = 1;
6319 		} else if (ptype == SCTP_ULP_ADAPTATION) {
6320 			if (stcb->asoc.state != SCTP_STATE_OPEN) {
6321 				struct sctp_adaptation_layer_indication ai,
6322 				                                *aip;
6323 
6324 				phdr = sctp_get_next_param(m, offset,
6325 				    (struct sctp_paramhdr *)&ai, sizeof(ai));
6326 				aip = (struct sctp_adaptation_layer_indication *)phdr;
6327 				if (aip) {
6328 					stcb->asoc.peers_adaptation = ntohl(aip->indication);
6329 					stcb->asoc.adaptation_needed = 1;
6330 				}
6331 			}
6332 		} else if (ptype == SCTP_SET_PRIM_ADDR) {
6333 			struct sctp_asconf_addr_param lstore, *fee;
6334 			int lptype;
6335 			struct sockaddr *lsa = NULL;
6336 #ifdef INET
6337 			struct sctp_asconf_addrv4_param *fii;
6338 #endif
6339 
6340 			if (stcb->asoc.asconf_supported == 0) {
6341 				return (-100);
6342 			}
6343 			if (plen > sizeof(lstore)) {
6344 				return (-23);
6345 			}
6346 			if (plen < sizeof(struct sctp_asconf_addrv4_param)) {
6347 				return (-101);
6348 			}
6349 			phdr = sctp_get_next_param(m, offset,
6350 			    (struct sctp_paramhdr *)&lstore,
6351 			    plen);
6352 			if (phdr == NULL) {
6353 				return (-24);
6354 			}
6355 			fee = (struct sctp_asconf_addr_param *)phdr;
6356 			lptype = ntohs(fee->addrp.ph.param_type);
6357 			switch (lptype) {
6358 #ifdef INET
6359 			case SCTP_IPV4_ADDRESS:
6360 				if (plen !=
6361 				    sizeof(struct sctp_asconf_addrv4_param)) {
6362 					SCTP_PRINTF("Sizeof setprim in init/init ack not %d but %d - ignored\n",
6363 					    (int)sizeof(struct sctp_asconf_addrv4_param),
6364 					    plen);
6365 				} else {
6366 					fii = (struct sctp_asconf_addrv4_param *)fee;
6367 					sin.sin_addr.s_addr = fii->addrp.addr;
6368 					lsa = (struct sockaddr *)&sin;
6369 				}
6370 				break;
6371 #endif
6372 #ifdef INET6
6373 			case SCTP_IPV6_ADDRESS:
6374 				if (plen !=
6375 				    sizeof(struct sctp_asconf_addr_param)) {
6376 					SCTP_PRINTF("Sizeof setprim (v6) in init/init ack not %d but %d - ignored\n",
6377 					    (int)sizeof(struct sctp_asconf_addr_param),
6378 					    plen);
6379 				} else {
6380 					memcpy(sin6.sin6_addr.s6_addr,
6381 					    fee->addrp.addr,
6382 					    sizeof(fee->addrp.addr));
6383 					lsa = (struct sockaddr *)&sin6;
6384 				}
6385 				break;
6386 #endif
6387 			default:
6388 				break;
6389 			}
6390 			if (lsa) {
6391 				(void)sctp_set_primary_addr(stcb, sa, NULL);
6392 			}
6393 		} else if (ptype == SCTP_HAS_NAT_SUPPORT) {
6394 			stcb->asoc.peer_supports_nat = 1;
6395 		} else if (ptype == SCTP_PRSCTP_SUPPORTED) {
6396 			/* Peer supports pr-sctp */
6397 			peer_supports_prsctp = 1;
6398 		} else if (ptype == SCTP_ZERO_CHECKSUM_ACCEPTABLE) {
6399 			struct sctp_zero_checksum_acceptable zero_chksum,
6400 			                             *zero_chksum_p;
6401 
6402 			phdr = sctp_get_next_param(m, offset,
6403 			    (struct sctp_paramhdr *)&zero_chksum,
6404 			    sizeof(struct sctp_zero_checksum_acceptable));
6405 			if (phdr != NULL) {
6406 				/*
6407 				 * Only send zero checksums if the upper
6408 				 * layer has enabled the support for the
6409 				 * same method as allowed by the peer.
6410 				 */
6411 				zero_chksum_p = (struct sctp_zero_checksum_acceptable *)phdr;
6412 				if ((ntohl(zero_chksum_p->edmid) != SCTP_EDMID_NONE) &&
6413 				    (ntohl(zero_chksum_p->edmid) == stcb->asoc.rcv_edmid)) {
6414 					stcb->asoc.snd_edmid = stcb->asoc.rcv_edmid;
6415 				}
6416 			}
6417 		} else if (ptype == SCTP_SUPPORTED_CHUNK_EXT) {
6418 			/* A supported extension chunk */
6419 			struct sctp_supported_chunk_types_param *pr_supported;
6420 			uint8_t local_store[SCTP_PARAM_BUFFER_SIZE];
6421 			int num_ent, i;
6422 
6423 			if (plen > sizeof(local_store)) {
6424 				return (-35);
6425 			}
6426 			phdr = sctp_get_next_param(m, offset,
6427 			    (struct sctp_paramhdr *)&local_store, plen);
6428 			if (phdr == NULL) {
6429 				return (-25);
6430 			}
6431 			pr_supported = (struct sctp_supported_chunk_types_param *)phdr;
6432 			num_ent = plen - sizeof(struct sctp_paramhdr);
6433 			for (i = 0; i < num_ent; i++) {
6434 				switch (pr_supported->chunk_types[i]) {
6435 				case SCTP_ASCONF:
6436 					peer_supports_asconf = 1;
6437 					break;
6438 				case SCTP_ASCONF_ACK:
6439 					peer_supports_asconf_ack = 1;
6440 					break;
6441 				case SCTP_FORWARD_CUM_TSN:
6442 					peer_supports_prsctp = 1;
6443 					break;
6444 				case SCTP_PACKET_DROPPED:
6445 					peer_supports_pktdrop = 1;
6446 					break;
6447 				case SCTP_NR_SELECTIVE_ACK:
6448 					peer_supports_nrsack = 1;
6449 					break;
6450 				case SCTP_STREAM_RESET:
6451 					peer_supports_reconfig = 1;
6452 					break;
6453 				case SCTP_AUTHENTICATION:
6454 					peer_supports_auth = 1;
6455 					break;
6456 				case SCTP_IDATA:
6457 					peer_supports_idata = 1;
6458 					break;
6459 				default:
6460 					/* one I have not learned yet */
6461 					break;
6462 				}
6463 			}
6464 		} else if (ptype == SCTP_RANDOM) {
6465 			if (plen > sizeof(random_store))
6466 				break;
6467 			if (got_random) {
6468 				/* already processed a RANDOM */
6469 				goto next_param;
6470 			}
6471 			phdr = sctp_get_next_param(m, offset,
6472 			    (struct sctp_paramhdr *)random_store,
6473 			    plen);
6474 			if (phdr == NULL)
6475 				return (-26);
6476 			p_random = (struct sctp_auth_random *)phdr;
6477 			random_len = plen - sizeof(*p_random);
6478 			/* enforce the random length */
6479 			if (random_len != SCTP_AUTH_RANDOM_SIZE_REQUIRED) {
6480 				SCTPDBG(SCTP_DEBUG_AUTH1, "SCTP: invalid RANDOM len\n");
6481 				return (-27);
6482 			}
6483 			got_random = 1;
6484 		} else if (ptype == SCTP_HMAC_LIST) {
6485 			uint16_t num_hmacs;
6486 			uint16_t i;
6487 
6488 			if (plen > sizeof(hmacs_store))
6489 				break;
6490 			if (got_hmacs) {
6491 				/* already processed a HMAC list */
6492 				goto next_param;
6493 			}
6494 			phdr = sctp_get_next_param(m, offset,
6495 			    (struct sctp_paramhdr *)hmacs_store,
6496 			    plen);
6497 			if (phdr == NULL)
6498 				return (-28);
6499 			hmacs = (struct sctp_auth_hmac_algo *)phdr;
6500 			hmacs_len = plen - sizeof(*hmacs);
6501 			num_hmacs = hmacs_len / sizeof(hmacs->hmac_ids[0]);
6502 			/* validate the hmac list */
6503 			if (sctp_verify_hmac_param(hmacs, num_hmacs)) {
6504 				return (-29);
6505 			}
6506 			if (stcb->asoc.peer_hmacs != NULL)
6507 				sctp_free_hmaclist(stcb->asoc.peer_hmacs);
6508 			stcb->asoc.peer_hmacs = sctp_alloc_hmaclist(num_hmacs);
6509 			if (stcb->asoc.peer_hmacs != NULL) {
6510 				for (i = 0; i < num_hmacs; i++) {
6511 					(void)sctp_auth_add_hmacid(stcb->asoc.peer_hmacs,
6512 					    ntohs(hmacs->hmac_ids[i]));
6513 				}
6514 			}
6515 			got_hmacs = 1;
6516 		} else if (ptype == SCTP_CHUNK_LIST) {
6517 			int i;
6518 
6519 			if (plen > sizeof(chunks_store))
6520 				break;
6521 			if (got_chklist) {
6522 				/* already processed a Chunks list */
6523 				goto next_param;
6524 			}
6525 			phdr = sctp_get_next_param(m, offset,
6526 			    (struct sctp_paramhdr *)chunks_store,
6527 			    plen);
6528 			if (phdr == NULL)
6529 				return (-30);
6530 			chunks = (struct sctp_auth_chunk_list *)phdr;
6531 			num_chunks = plen - sizeof(*chunks);
6532 			if (stcb->asoc.peer_auth_chunks != NULL)
6533 				sctp_clear_chunklist(stcb->asoc.peer_auth_chunks);
6534 			else
6535 				stcb->asoc.peer_auth_chunks = sctp_alloc_chunklist();
6536 			for (i = 0; i < num_chunks; i++) {
6537 				(void)sctp_auth_add_chunk(chunks->chunk_types[i],
6538 				    stcb->asoc.peer_auth_chunks);
6539 				/* record asconf/asconf-ack if listed */
6540 				if (chunks->chunk_types[i] == SCTP_ASCONF)
6541 					saw_asconf = 1;
6542 				if (chunks->chunk_types[i] == SCTP_ASCONF_ACK)
6543 					saw_asconf_ack = 1;
6544 			}
6545 			got_chklist = 1;
6546 		} else if ((ptype == SCTP_HEARTBEAT_INFO) ||
6547 			    (ptype == SCTP_STATE_COOKIE) ||
6548 			    (ptype == SCTP_UNRECOG_PARAM) ||
6549 			    (ptype == SCTP_COOKIE_PRESERVE) ||
6550 			    (ptype == SCTP_SUPPORTED_ADDRTYPE) ||
6551 			    (ptype == SCTP_ADD_IP_ADDRESS) ||
6552 			    (ptype == SCTP_DEL_IP_ADDRESS) ||
6553 			    (ptype == SCTP_ERROR_CAUSE_IND) ||
6554 		    (ptype == SCTP_SUCCESS_REPORT)) {
6555 			/* don't care */
6556 		} else {
6557 			if ((ptype & 0x8000) == 0x0000) {
6558 				/*
6559 				 * must stop processing the rest of the
6560 				 * param's. Any report bits were handled
6561 				 * with the call to
6562 				 * sctp_arethere_unrecognized_parameters()
6563 				 * when the INIT or INIT-ACK was first seen.
6564 				 */
6565 				break;
6566 			}
6567 		}
6568 
6569 next_param:
6570 		offset += SCTP_SIZE32(plen);
6571 		if (offset >= limit) {
6572 			break;
6573 		}
6574 		phdr = sctp_get_next_param(m, offset, &param_buf,
6575 		    sizeof(param_buf));
6576 	}
6577 	/* Now check to see if we need to purge any addresses */
6578 	TAILQ_FOREACH_SAFE(net, &stcb->asoc.nets, sctp_next, nnet) {
6579 		if ((net->dest_state & SCTP_ADDR_NOT_IN_ASSOC) ==
6580 		    SCTP_ADDR_NOT_IN_ASSOC) {
6581 			/* This address has been removed from the asoc */
6582 			/* remove and free it */
6583 			stcb->asoc.numnets--;
6584 			TAILQ_REMOVE(&stcb->asoc.nets, net, sctp_next);
6585 			if (net == stcb->asoc.alternate) {
6586 				sctp_free_remote_addr(stcb->asoc.alternate);
6587 				stcb->asoc.alternate = NULL;
6588 			}
6589 			if (net == stcb->asoc.primary_destination) {
6590 				stcb->asoc.primary_destination = NULL;
6591 				sctp_select_primary_destination(stcb);
6592 			}
6593 			sctp_free_remote_addr(net);
6594 		}
6595 	}
6596 	if ((stcb->asoc.ecn_supported == 1) &&
6597 	    (peer_supports_ecn == 0)) {
6598 		stcb->asoc.ecn_supported = 0;
6599 	}
6600 	if ((stcb->asoc.prsctp_supported == 1) &&
6601 	    (peer_supports_prsctp == 0)) {
6602 		stcb->asoc.prsctp_supported = 0;
6603 	}
6604 	if ((stcb->asoc.auth_supported == 1) &&
6605 	    ((peer_supports_auth == 0) ||
6606 	    (got_random == 0) || (got_hmacs == 0))) {
6607 		stcb->asoc.auth_supported = 0;
6608 	}
6609 	if ((stcb->asoc.asconf_supported == 1) &&
6610 	    ((peer_supports_asconf == 0) || (peer_supports_asconf_ack == 0) ||
6611 	    (stcb->asoc.auth_supported == 0) ||
6612 	    (saw_asconf == 0) || (saw_asconf_ack == 0))) {
6613 		stcb->asoc.asconf_supported = 0;
6614 	}
6615 	if ((stcb->asoc.reconfig_supported == 1) &&
6616 	    (peer_supports_reconfig == 0)) {
6617 		stcb->asoc.reconfig_supported = 0;
6618 	}
6619 	if ((stcb->asoc.idata_supported == 1) &&
6620 	    (peer_supports_idata == 0)) {
6621 		stcb->asoc.idata_supported = 0;
6622 	}
6623 	if ((stcb->asoc.nrsack_supported == 1) &&
6624 	    (peer_supports_nrsack == 0)) {
6625 		stcb->asoc.nrsack_supported = 0;
6626 	}
6627 	if ((stcb->asoc.pktdrop_supported == 1) &&
6628 	    (peer_supports_pktdrop == 0)) {
6629 		stcb->asoc.pktdrop_supported = 0;
6630 	}
6631 	/* validate authentication required parameters */
6632 	if ((peer_supports_auth == 0) && (got_chklist == 1)) {
6633 		/* peer does not support auth but sent a chunks list? */
6634 		return (-31);
6635 	}
6636 	if ((peer_supports_asconf == 1) && (peer_supports_auth == 0)) {
6637 		/* peer supports asconf but not auth? */
6638 		return (-32);
6639 	} else if ((peer_supports_asconf == 1) &&
6640 		    (peer_supports_auth == 1) &&
6641 	    ((saw_asconf == 0) || (saw_asconf_ack == 0))) {
6642 		return (-33);
6643 	}
6644 	/* concatenate the full random key */
6645 	keylen = sizeof(*p_random) + random_len + sizeof(*hmacs) + hmacs_len;
6646 	if (chunks != NULL) {
6647 		keylen += sizeof(*chunks) + num_chunks;
6648 	}
6649 	new_key = sctp_alloc_key(keylen);
6650 	if (new_key != NULL) {
6651 		/* copy in the RANDOM */
6652 		if (p_random != NULL) {
6653 			keylen = sizeof(*p_random) + random_len;
6654 			memcpy(new_key->key, p_random, keylen);
6655 		} else {
6656 			keylen = 0;
6657 		}
6658 		/* append in the AUTH chunks */
6659 		if (chunks != NULL) {
6660 			memcpy(new_key->key + keylen, chunks,
6661 			    sizeof(*chunks) + num_chunks);
6662 			keylen += sizeof(*chunks) + num_chunks;
6663 		}
6664 		/* append in the HMACs */
6665 		if (hmacs != NULL) {
6666 			memcpy(new_key->key + keylen, hmacs,
6667 			    sizeof(*hmacs) + hmacs_len);
6668 		}
6669 	} else {
6670 		/* failed to get memory for the key */
6671 		return (-34);
6672 	}
6673 	if (stcb->asoc.authinfo.peer_random != NULL)
6674 		sctp_free_key(stcb->asoc.authinfo.peer_random);
6675 	stcb->asoc.authinfo.peer_random = new_key;
6676 	sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.assoc_keyid);
6677 	sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.recv_keyid);
6678 
6679 	return (0);
6680 }
6681 
6682 int
6683 sctp_set_primary_addr(struct sctp_tcb *stcb, struct sockaddr *sa,
6684     struct sctp_nets *net)
6685 {
6686 	/* make sure the requested primary address exists in the assoc */
6687 	if (net == NULL && sa)
6688 		net = sctp_findnet(stcb, sa);
6689 
6690 	if (net == NULL) {
6691 		/* didn't find the requested primary address! */
6692 		return (-1);
6693 	} else {
6694 		/* set the primary address */
6695 		if (net->dest_state & SCTP_ADDR_UNCONFIRMED) {
6696 			/* Must be confirmed, so queue to set */
6697 			net->dest_state |= SCTP_ADDR_REQ_PRIMARY;
6698 			return (0);
6699 		}
6700 		stcb->asoc.primary_destination = net;
6701 		if (((net->dest_state & SCTP_ADDR_PF) == 0) &&
6702 		    (stcb->asoc.alternate != NULL)) {
6703 			sctp_free_remote_addr(stcb->asoc.alternate);
6704 			stcb->asoc.alternate = NULL;
6705 		}
6706 		net = TAILQ_FIRST(&stcb->asoc.nets);
6707 		if (net != stcb->asoc.primary_destination) {
6708 			/*
6709 			 * first one on the list is NOT the primary
6710 			 * sctp_cmpaddr() is much more efficient if the
6711 			 * primary is the first on the list, make it so.
6712 			 */
6713 			TAILQ_REMOVE(&stcb->asoc.nets, stcb->asoc.primary_destination, sctp_next);
6714 			TAILQ_INSERT_HEAD(&stcb->asoc.nets, stcb->asoc.primary_destination, sctp_next);
6715 		}
6716 		return (0);
6717 	}
6718 }
6719 
6720 bool
6721 sctp_is_vtag_good(uint32_t tag, uint16_t lport, uint16_t rport, struct timeval *now)
6722 {
6723 	struct sctpasochead *head;
6724 	struct sctp_tcb *stcb;
6725 
6726 	SCTP_INP_INFO_LOCK_ASSERT();
6727 
6728 	head = &SCTP_BASE_INFO(sctp_asochash)[SCTP_PCBHASH_ASOC(tag, SCTP_BASE_INFO(hashasocmark))];
6729 	LIST_FOREACH(stcb, head, sctp_asocs) {
6730 		/*
6731 		 * We choose not to lock anything here. TCB's can't be
6732 		 * removed since we have the read lock, so they can't be
6733 		 * freed on us, same thing for the INP. I may be wrong with
6734 		 * this assumption, but we will go with it for now :-)
6735 		 */
6736 		if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
6737 			continue;
6738 		}
6739 		if (stcb->asoc.my_vtag == tag) {
6740 			/* candidate */
6741 			if (stcb->rport != rport) {
6742 				continue;
6743 			}
6744 			if (stcb->sctp_ep->sctp_lport != lport) {
6745 				continue;
6746 			}
6747 			/* The tag is currently used, so don't use it. */
6748 			return (false);
6749 		}
6750 	}
6751 	return (!sctp_is_in_timewait(tag, lport, rport, (uint32_t)now->tv_sec));
6752 }
6753 
6754 static void
6755 sctp_drain_mbufs(struct sctp_tcb *stcb)
6756 {
6757 	/*
6758 	 * We must hunt this association for MBUF's past the cumack (i.e.
6759 	 * out of order data that we can renege on).
6760 	 */
6761 	struct sctp_association *asoc;
6762 	struct sctp_tmit_chunk *chk, *nchk;
6763 	uint32_t cumulative_tsn_p1;
6764 	struct sctp_queued_to_read *control, *ncontrol;
6765 	int cnt, strmat;
6766 	uint32_t gap, i;
6767 	int fnd = 0;
6768 
6769 	/* We look for anything larger than the cum-ack + 1 */
6770 
6771 	asoc = &stcb->asoc;
6772 	if (asoc->cumulative_tsn == asoc->highest_tsn_inside_map) {
6773 		/* none we can reneg on. */
6774 		return;
6775 	}
6776 	SCTP_STAT_INCR(sctps_protocol_drains_done);
6777 	cumulative_tsn_p1 = asoc->cumulative_tsn + 1;
6778 	cnt = 0;
6779 	/* Ok that was fun, now we will drain all the inbound streams? */
6780 	for (strmat = 0; strmat < asoc->streamincnt; strmat++) {
6781 		TAILQ_FOREACH_SAFE(control, &asoc->strmin[strmat].inqueue, next_instrm, ncontrol) {
6782 #ifdef INVARIANTS
6783 			if (control->on_strm_q != SCTP_ON_ORDERED) {
6784 				panic("Huh control: %p on_q: %d -- not ordered?",
6785 				    control, control->on_strm_q);
6786 			}
6787 #endif
6788 			if (SCTP_TSN_GT(control->sinfo_tsn, cumulative_tsn_p1)) {
6789 				/* Yep it is above cum-ack */
6790 				cnt++;
6791 				SCTP_CALC_TSN_TO_GAP(gap, control->sinfo_tsn, asoc->mapping_array_base_tsn);
6792 				KASSERT(control->length > 0, ("control has zero length"));
6793 				if (asoc->size_on_all_streams >= control->length) {
6794 					asoc->size_on_all_streams -= control->length;
6795 				} else {
6796 #ifdef INVARIANTS
6797 					panic("size_on_all_streams = %u smaller than control length %u", asoc->size_on_all_streams, control->length);
6798 #else
6799 					asoc->size_on_all_streams = 0;
6800 #endif
6801 				}
6802 				sctp_ucount_decr(asoc->cnt_on_all_streams);
6803 				SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap);
6804 				if (control->on_read_q) {
6805 					TAILQ_REMOVE(&stcb->sctp_ep->read_queue, control, next);
6806 					control->on_read_q = 0;
6807 				}
6808 				TAILQ_REMOVE(&asoc->strmin[strmat].inqueue, control, next_instrm);
6809 				control->on_strm_q = 0;
6810 				if (control->data) {
6811 					sctp_m_freem(control->data);
6812 					control->data = NULL;
6813 				}
6814 				sctp_free_remote_addr(control->whoFrom);
6815 				/* Now its reasm? */
6816 				TAILQ_FOREACH_SAFE(chk, &control->reasm, sctp_next, nchk) {
6817 					cnt++;
6818 					SCTP_CALC_TSN_TO_GAP(gap, chk->rec.data.tsn, asoc->mapping_array_base_tsn);
6819 					KASSERT(chk->send_size > 0, ("chunk has zero length"));
6820 					if (asoc->size_on_reasm_queue >= chk->send_size) {
6821 						asoc->size_on_reasm_queue -= chk->send_size;
6822 					} else {
6823 #ifdef INVARIANTS
6824 						panic("size_on_reasm_queue = %u smaller than chunk length %u", asoc->size_on_reasm_queue, chk->send_size);
6825 #else
6826 						asoc->size_on_reasm_queue = 0;
6827 #endif
6828 					}
6829 					sctp_ucount_decr(asoc->cnt_on_reasm_queue);
6830 					SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap);
6831 					TAILQ_REMOVE(&control->reasm, chk, sctp_next);
6832 					if (chk->data) {
6833 						sctp_m_freem(chk->data);
6834 						chk->data = NULL;
6835 					}
6836 					sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
6837 				}
6838 				sctp_free_a_readq(stcb, control);
6839 			}
6840 		}
6841 		TAILQ_FOREACH_SAFE(control, &asoc->strmin[strmat].uno_inqueue, next_instrm, ncontrol) {
6842 #ifdef INVARIANTS
6843 			if (control->on_strm_q != SCTP_ON_UNORDERED) {
6844 				panic("Huh control: %p on_q: %d -- not unordered?",
6845 				    control, control->on_strm_q);
6846 			}
6847 #endif
6848 			if (SCTP_TSN_GT(control->sinfo_tsn, cumulative_tsn_p1)) {
6849 				/* Yep it is above cum-ack */
6850 				cnt++;
6851 				SCTP_CALC_TSN_TO_GAP(gap, control->sinfo_tsn, asoc->mapping_array_base_tsn);
6852 				KASSERT(control->length > 0, ("control has zero length"));
6853 				if (asoc->size_on_all_streams >= control->length) {
6854 					asoc->size_on_all_streams -= control->length;
6855 				} else {
6856 #ifdef INVARIANTS
6857 					panic("size_on_all_streams = %u smaller than control length %u", asoc->size_on_all_streams, control->length);
6858 #else
6859 					asoc->size_on_all_streams = 0;
6860 #endif
6861 				}
6862 				sctp_ucount_decr(asoc->cnt_on_all_streams);
6863 				SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap);
6864 				if (control->on_read_q) {
6865 					TAILQ_REMOVE(&stcb->sctp_ep->read_queue, control, next);
6866 					control->on_read_q = 0;
6867 				}
6868 				TAILQ_REMOVE(&asoc->strmin[strmat].uno_inqueue, control, next_instrm);
6869 				control->on_strm_q = 0;
6870 				if (control->data) {
6871 					sctp_m_freem(control->data);
6872 					control->data = NULL;
6873 				}
6874 				sctp_free_remote_addr(control->whoFrom);
6875 				/* Now its reasm? */
6876 				TAILQ_FOREACH_SAFE(chk, &control->reasm, sctp_next, nchk) {
6877 					cnt++;
6878 					SCTP_CALC_TSN_TO_GAP(gap, chk->rec.data.tsn, asoc->mapping_array_base_tsn);
6879 					KASSERT(chk->send_size > 0, ("chunk has zero length"));
6880 					if (asoc->size_on_reasm_queue >= chk->send_size) {
6881 						asoc->size_on_reasm_queue -= chk->send_size;
6882 					} else {
6883 #ifdef INVARIANTS
6884 						panic("size_on_reasm_queue = %u smaller than chunk length %u", asoc->size_on_reasm_queue, chk->send_size);
6885 #else
6886 						asoc->size_on_reasm_queue = 0;
6887 #endif
6888 					}
6889 					sctp_ucount_decr(asoc->cnt_on_reasm_queue);
6890 					SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap);
6891 					TAILQ_REMOVE(&control->reasm, chk, sctp_next);
6892 					if (chk->data) {
6893 						sctp_m_freem(chk->data);
6894 						chk->data = NULL;
6895 					}
6896 					sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
6897 				}
6898 				sctp_free_a_readq(stcb, control);
6899 			}
6900 		}
6901 	}
6902 	if (cnt) {
6903 		/* We must back down to see what the new highest is */
6904 		for (i = asoc->highest_tsn_inside_map; SCTP_TSN_GE(i, asoc->mapping_array_base_tsn); i--) {
6905 			SCTP_CALC_TSN_TO_GAP(gap, i, asoc->mapping_array_base_tsn);
6906 			if (SCTP_IS_TSN_PRESENT(asoc->mapping_array, gap)) {
6907 				asoc->highest_tsn_inside_map = i;
6908 				fnd = 1;
6909 				break;
6910 			}
6911 		}
6912 		if (!fnd) {
6913 			asoc->highest_tsn_inside_map = asoc->mapping_array_base_tsn - 1;
6914 		}
6915 
6916 		/*
6917 		 * Question, should we go through the delivery queue? The
6918 		 * only reason things are on here is the app not reading OR
6919 		 * a p-d-api up. An attacker COULD send enough in to
6920 		 * initiate the PD-API and then send a bunch of stuff to
6921 		 * other streams... these would wind up on the delivery
6922 		 * queue.. and then we would not get to them. But in order
6923 		 * to do this I then have to back-track and un-deliver
6924 		 * sequence numbers in streams.. el-yucko. I think for now
6925 		 * we will NOT look at the delivery queue and leave it to be
6926 		 * something to consider later. An alternative would be to
6927 		 * abort the P-D-API with a notification and then deliver
6928 		 * the data.... Or another method might be to keep track of
6929 		 * how many times the situation occurs and if we see a
6930 		 * possible attack underway just abort the association.
6931 		 */
6932 #ifdef SCTP_DEBUG
6933 		SCTPDBG(SCTP_DEBUG_PCB1, "Freed %d chunks from reneg harvest\n", cnt);
6934 #endif
6935 		/*
6936 		 * Now do we need to find a new
6937 		 * asoc->highest_tsn_inside_map?
6938 		 */
6939 		asoc->last_revoke_count = cnt;
6940 		sctp_timer_stop(SCTP_TIMER_TYPE_RECV, stcb->sctp_ep, stcb, NULL,
6941 		    SCTP_FROM_SCTP_PCB + SCTP_LOC_11);
6942 		/* sa_ignore NO_NULL_CHK */
6943 		sctp_send_sack(stcb, SCTP_SO_NOT_LOCKED);
6944 		sctp_chunk_output(stcb->sctp_ep, stcb, SCTP_OUTPUT_FROM_DRAIN, SCTP_SO_NOT_LOCKED);
6945 	}
6946 	/*
6947 	 * Another issue, in un-setting the TSN's in the mapping array we
6948 	 * DID NOT adjust the highest_tsn marker.  This will cause one of
6949 	 * two things to occur. It may cause us to do extra work in checking
6950 	 * for our mapping array movement. More importantly it may cause us
6951 	 * to SACK every datagram. This may not be a bad thing though since
6952 	 * we will recover once we get our cum-ack above and all this stuff
6953 	 * we dumped recovered.
6954 	 */
6955 }
6956 
6957 static void
6958 sctp_drain(void)
6959 {
6960 	struct epoch_tracker et;
6961 
6962 	VNET_ITERATOR_DECL(vnet_iter);
6963 
6964 	NET_EPOCH_ENTER(et);
6965 	/*
6966 	 * We must walk the PCB lists for ALL associations here. The system
6967 	 * is LOW on MBUF's and needs help. This is where reneging will
6968 	 * occur. We really hope this does NOT happen!
6969 	 */
6970 	VNET_LIST_RLOCK_NOSLEEP();
6971 	VNET_FOREACH(vnet_iter) {
6972 		CURVNET_SET(vnet_iter);
6973 		struct sctp_inpcb *inp;
6974 		struct sctp_tcb *stcb;
6975 
6976 		SCTP_STAT_INCR(sctps_protocol_drain_calls);
6977 		if (SCTP_BASE_SYSCTL(sctp_do_drain) == 0) {
6978 #ifdef VIMAGE
6979 			continue;
6980 #else
6981 			NET_EPOCH_EXIT(et);
6982 			return;
6983 #endif
6984 		}
6985 		SCTP_INP_INFO_RLOCK();
6986 		LIST_FOREACH(inp, &SCTP_BASE_INFO(listhead), sctp_list) {
6987 			/* For each endpoint */
6988 			SCTP_INP_RLOCK(inp);
6989 			LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
6990 				/* For each association */
6991 				SCTP_TCB_LOCK(stcb);
6992 				sctp_drain_mbufs(stcb);
6993 				SCTP_TCB_UNLOCK(stcb);
6994 			}
6995 			SCTP_INP_RUNLOCK(inp);
6996 		}
6997 		SCTP_INP_INFO_RUNLOCK();
6998 		CURVNET_RESTORE();
6999 	}
7000 	VNET_LIST_RUNLOCK_NOSLEEP();
7001 	NET_EPOCH_EXIT(et);
7002 }
7003 
7004 EVENTHANDLER_DEFINE(vm_lowmem, sctp_drain, NULL, LOWMEM_PRI_DEFAULT);
7005 EVENTHANDLER_DEFINE(mbuf_lowmem, sctp_drain, NULL, LOWMEM_PRI_DEFAULT);
7006 
7007 /*
7008  * start a new iterator
7009  * iterates through all endpoints and associations based on the pcb_state
7010  * flags and asoc_state.  "af" (mandatory) is executed for all matching
7011  * assocs and "ef" (optional) is executed when the iterator completes.
7012  * "inpf" (optional) is executed for each new endpoint as it is being
7013  * iterated through. inpe (optional) is called when the inp completes
7014  * its way through all the stcbs.
7015  */
7016 int
7017 sctp_initiate_iterator(inp_func inpf,
7018     asoc_func af,
7019     inp_func inpe,
7020     uint32_t pcb_state,
7021     uint32_t pcb_features,
7022     uint32_t asoc_state,
7023     void *argp,
7024     uint32_t argi,
7025     end_func ef,
7026     struct sctp_inpcb *s_inp,
7027     uint8_t chunk_output_off)
7028 {
7029 	struct sctp_iterator *it = NULL;
7030 
7031 	if (af == NULL) {
7032 		return (-1);
7033 	}
7034 	if (SCTP_BASE_VAR(sctp_pcb_initialized) == 0) {
7035 		SCTP_PRINTF("%s: abort on initialize being %d\n", __func__,
7036 		    SCTP_BASE_VAR(sctp_pcb_initialized));
7037 		return (-1);
7038 	}
7039 	SCTP_MALLOC(it, struct sctp_iterator *, sizeof(struct sctp_iterator),
7040 	    SCTP_M_ITER);
7041 	if (it == NULL) {
7042 		SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_PCB, ENOMEM);
7043 		return (-1);
7044 	}
7045 	memset(it, 0, sizeof(*it));
7046 	it->function_assoc = af;
7047 	it->function_inp = inpf;
7048 	if (inpf)
7049 		it->done_current_ep = 0;
7050 	else
7051 		it->done_current_ep = 1;
7052 	it->function_atend = ef;
7053 	it->pointer = argp;
7054 	it->val = argi;
7055 	it->pcb_flags = pcb_state;
7056 	it->pcb_features = pcb_features;
7057 	it->asoc_state = asoc_state;
7058 	it->function_inp_end = inpe;
7059 	it->no_chunk_output = chunk_output_off;
7060 	it->vn = curvnet;
7061 	if (s_inp) {
7062 		/* Assume lock is held here */
7063 		it->inp = s_inp;
7064 		SCTP_INP_INCR_REF(it->inp);
7065 		it->iterator_flags = SCTP_ITERATOR_DO_SINGLE_INP;
7066 	} else {
7067 		SCTP_INP_INFO_RLOCK();
7068 		it->inp = LIST_FIRST(&SCTP_BASE_INFO(listhead));
7069 		if (it->inp) {
7070 			SCTP_INP_INCR_REF(it->inp);
7071 		}
7072 		SCTP_INP_INFO_RUNLOCK();
7073 		it->iterator_flags = SCTP_ITERATOR_DO_ALL_INP;
7074 	}
7075 	SCTP_IPI_ITERATOR_WQ_LOCK();
7076 	if (SCTP_BASE_VAR(sctp_pcb_initialized) == 0) {
7077 		SCTP_IPI_ITERATOR_WQ_UNLOCK();
7078 		SCTP_PRINTF("%s: rollback on initialize being %d it=%p\n", __func__,
7079 		    SCTP_BASE_VAR(sctp_pcb_initialized), it);
7080 		SCTP_FREE(it, SCTP_M_ITER);
7081 		return (-1);
7082 	}
7083 	TAILQ_INSERT_TAIL(&sctp_it_ctl.iteratorhead, it, sctp_nxt_itr);
7084 	if (sctp_it_ctl.iterator_running == 0) {
7085 		sctp_wakeup_iterator();
7086 	}
7087 	SCTP_IPI_ITERATOR_WQ_UNLOCK();
7088 	/* sa_ignore MEMLEAK {memory is put on the tailq for the iterator} */
7089 	return (0);
7090 }
7091 
7092 /*
7093  * Atomically add flags to the sctp_flags of an inp.
7094  * To be used when the write lock of the inp is not held.
7095  */
7096 void
7097 sctp_pcb_add_flags(struct sctp_inpcb *inp, uint32_t flags)
7098 {
7099 	uint32_t old_flags, new_flags;
7100 
7101 	do {
7102 		old_flags = inp->sctp_flags;
7103 		new_flags = old_flags | flags;
7104 	} while (atomic_cmpset_int(&inp->sctp_flags, old_flags, new_flags) == 0);
7105 }
7106