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