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