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