xref: /netbsd-src/sys/netinet/sctp_pcb.c (revision 946379e7b37692fc43f68eb0d1c10daa0a7f3b6c)
1 /* $KAME: sctp_pcb.c,v 1.39 2005/06/16 18:29:25 jinmei Exp $ */
2 /* $NetBSD: sctp_pcb.c,v 1.1 2015/10/13 21:28:35 rjs Exp $ */
3 
4 /*
5  * Copyright (c) 2001, 2002, 2003, 2004 Cisco Systems, Inc.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by Cisco Systems, Inc.
19  * 4. Neither the name of the project nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY CISCO SYSTEMS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL CISCO SYSTEMS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 #include <sys/cdefs.h>
36 __KERNEL_RCSID(0, "$NetBSD: sctp_pcb.c,v 1.1 2015/10/13 21:28:35 rjs Exp $");
37 
38 #ifdef _KERNEL_OPT
39 #include "opt_inet.h"
40 #include "opt_sctp.h"
41 #endif /* _KERNEL_OPT */
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #include <sys/domain.h>
48 #include <sys/protosw.h>
49 #include <sys/socket.h>
50 #include <sys/socketvar.h>
51 #include <sys/proc.h>
52 #include <sys/kauth.h>
53 #include <sys/kernel.h>
54 #include <sys/sysctl.h>
55 #include <sys/rnd.h>
56 #include <sys/callout.h>
57 
58 #include <machine/limits.h>
59 #include <machine/cpu.h>
60 
61 #include <net/if.h>
62 #include <net/if_types.h>
63 #include <net/route.h>
64 #include <netinet/in.h>
65 #include <netinet/in_systm.h>
66 #include <netinet/ip.h>
67 #include <netinet/in_pcb.h>
68 #include <netinet/in_var.h>
69 #include <netinet/ip_var.h>
70 
71 #ifdef INET6
72 #include <netinet/ip6.h>
73 #include <netinet6/ip6_var.h>
74 #include <netinet6/scope6_var.h>
75 #include <netinet6/in6_pcb.h>
76 #endif /* INET6 */
77 
78 #ifdef IPSEC
79 #include <netinet6/ipsec.h>
80 #include <netkey/key.h>
81 #endif /* IPSEC */
82 
83 #include <netinet/sctp_var.h>
84 #include <netinet/sctp_pcb.h>
85 #include <netinet/sctputil.h>
86 #include <netinet/sctp.h>
87 #include <netinet/sctp_header.h>
88 #include <netinet/sctp_asconf.h>
89 #include <netinet/sctp_output.h>
90 #include <netinet/sctp_timer.h>
91 
92 #ifndef SCTP_PCBHASHSIZE
93 /* default number of association hash buckets in each endpoint */
94 #define SCTP_PCBHASHSIZE 256
95 #endif
96 
97 #ifdef SCTP_DEBUG
98 u_int32_t sctp_debug_on = SCTP_DEBUG_ALL;
99 #endif /* SCTP_DEBUG */
100 
101 u_int32_t sctp_pegs[SCTP_NUMBER_OF_PEGS];
102 
103 int sctp_pcbtblsize = SCTP_PCBHASHSIZE;
104 
105 struct sctp_epinfo sctppcbinfo;
106 
107 /* FIX: we don't handle multiple link local scopes */
108 /* "scopeless" replacement IN6_ARE_ADDR_EQUAL */
109 int
110 SCTP6_ARE_ADDR_EQUAL(const struct in6_addr *a, const struct in6_addr *b)
111 {
112 	struct in6_addr tmp_a, tmp_b;
113 	/* use a copy of a and b */
114 	tmp_a = *a;
115 	tmp_b = *b;
116 	in6_clearscope(&tmp_a);
117 	in6_clearscope(&tmp_b);
118 	return (IN6_ARE_ADDR_EQUAL(&tmp_a, &tmp_b));
119 }
120 
121 #if defined(__FreeBSD__) && __FreeBSD_version > 500000
122 
123 #ifndef xyzzy
124 void sctp_validate_no_locks(void);
125 
126 void
127 SCTP_INP_RLOCK(struct sctp_inpcb *inp)
128 {
129 	struct sctp_tcb *stcb;
130 	LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
131 		if (mtx_owned(&(stcb)->tcb_mtx))
132 			panic("I own TCB lock?");
133 	}
134         if (mtx_owned(&(inp)->inp_mtx))
135 		panic("INP Recursive Lock-R");
136         mtx_lock(&(inp)->inp_mtx);
137 }
138 
139 void
140 SCTP_INP_WLOCK(struct sctp_inpcb *inp)
141 {
142 	SCTP_INP_RLOCK(inp);
143 }
144 
145 void
146 SCTP_INP_INFO_RLOCK()
147 {
148 	struct sctp_inpcb *inp;
149 	struct sctp_tcb *stcb;
150 	LIST_FOREACH(inp, &sctppcbinfo.listhead, sctp_list) {
151 		if (mtx_owned(&(inp)->inp_mtx))
152 			panic("info-lock and own inp lock?");
153 		LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
154 			if (mtx_owned(&(stcb)->tcb_mtx))
155 				panic("Info lock and own a tcb lock?");
156 		}
157 	}
158 	if (mtx_owned(&sctppcbinfo.ipi_ep_mtx))
159 		panic("INP INFO Recursive Lock-R");
160 	mtx_lock(&sctppcbinfo.ipi_ep_mtx);
161 }
162 
163 void
164 SCTP_INP_INFO_WLOCK()
165 {
166 	SCTP_INP_INFO_RLOCK();
167 }
168 
169 
170 void sctp_validate_no_locks()
171 {
172 	struct sctp_inpcb *inp;
173 	struct sctp_tcb *stcb;
174 
175 	if (mtx_owned(&sctppcbinfo.ipi_ep_mtx))
176 		panic("INP INFO lock is owned?");
177 
178 	LIST_FOREACH(inp, &sctppcbinfo.listhead, sctp_list) {
179 		if (mtx_owned(&(inp)->inp_mtx))
180 			panic("You own an INP lock?");
181 		LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
182 			if (mtx_owned(&(stcb)->tcb_mtx))
183 				panic("You own a TCB lock?");
184 		}
185 	}
186 }
187 
188 #endif
189 #endif
190 
191 void
192 sctp_fill_pcbinfo(struct sctp_pcbinfo *spcb)
193 {
194 	/* We really don't need
195 	 * to lock this, but I will
196 	 * just because it does not hurt.
197 	 */
198 	SCTP_INP_INFO_RLOCK();
199 	spcb->ep_count = sctppcbinfo.ipi_count_ep;
200 	spcb->asoc_count = sctppcbinfo.ipi_count_asoc;
201 	spcb->laddr_count = sctppcbinfo.ipi_count_laddr;
202 	spcb->raddr_count = sctppcbinfo.ipi_count_raddr;
203 	spcb->chk_count = sctppcbinfo.ipi_count_chunk;
204 	spcb->sockq_count = sctppcbinfo.ipi_count_sockq;
205 	spcb->mbuf_track = sctppcbinfo.mbuf_track;
206 	SCTP_INP_INFO_RUNLOCK();
207 }
208 
209 
210 /*
211  * Notes on locks for FreeBSD 5 and up. All association
212  * lookups that have a definte ep, the INP structure is
213  * assumed to be locked for reading. If we need to go
214  * find the INP (ususally when a **inp is passed) then
215  * we must lock the INFO structure first and if needed
216  * lock the INP too. Note that if we lock it we must
217  *
218  */
219 
220 
221 /*
222  * Given a endpoint, look and find in its association list any association
223  * with the "to" address given. This can be a "from" address, too, for
224  * inbound packets. For outbound packets it is a true "to" address.
225  */
226 static struct sctp_tcb *
227 sctp_tcb_special_locate(struct sctp_inpcb **inp_p, struct sockaddr *from,
228 			struct sockaddr *to, struct sctp_nets **netp)
229 {
230 	/**** ASSUMSES THE CALLER holds the INP_INFO_RLOCK */
231 
232 	/*
233 	 * Note for this module care must be taken when observing what to is
234 	 * for. In most of the rest of the code the TO field represents my
235 	 * peer and the FROM field represents my address. For this module it
236 	 * is reversed of that.
237 	 */
238 	/*
239 	 * If we support the TCP model, then we must now dig through to
240 	 * see if we can find our endpoint in the list of tcp ep's.
241 	 */
242 	uint16_t lport, rport;
243 	struct sctppcbhead *ephead;
244 	struct sctp_inpcb *inp;
245 	struct sctp_laddr *laddr;
246 	struct sctp_tcb *stcb;
247 	struct sctp_nets *net;
248 
249 	if ((to == NULL) || (from == NULL)) {
250 		return (NULL);
251 	}
252 
253 	if (to->sa_family == AF_INET && from->sa_family == AF_INET) {
254 		lport = ((struct sockaddr_in *)to)->sin_port;
255 		rport = ((struct sockaddr_in *)from)->sin_port;
256 	} else if (to->sa_family == AF_INET6 && from->sa_family == AF_INET6) {
257 		lport = ((struct sockaddr_in6 *)to)->sin6_port;
258 		rport = ((struct sockaddr_in6 *)from)->sin6_port;
259 	} else {
260 		return NULL;
261 	}
262 	ephead = &sctppcbinfo.sctp_tcpephash[SCTP_PCBHASH_ALLADDR(
263 						     (lport + rport), sctppcbinfo.hashtcpmark)];
264 	/*
265 	 * Ok now for each of the guys in this bucket we must look
266 	 * and see:
267 	 *  - Does the remote port match.
268 	 *  - Does there single association's addresses match this
269 	 *    address (to).
270 	 * If so we update p_ep to point to this ep and return the
271 	 * tcb from it.
272 	 */
273 	LIST_FOREACH(inp, ephead, sctp_hash) {
274 		if (lport != inp->sctp_lport) {
275 			continue;
276 		}
277 		SCTP_INP_RLOCK(inp);
278 		/* check to see if the ep has one of the addresses */
279 		if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) {
280 			/* We are NOT bound all, so look further */
281 			int match = 0;
282 
283 			LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
284 				if (laddr->ifa == NULL) {
285 #ifdef SCTP_DEBUG
286 					if (sctp_debug_on & SCTP_DEBUG_PCB1) {
287 						printf("An ounce of prevention is worth a pound of cure\n");
288 					}
289 #endif
290 					continue;
291 				}
292 				if (laddr->ifa->ifa_addr == NULL) {
293 #ifdef SCTP_DEBUG
294 					if (sctp_debug_on & SCTP_DEBUG_PCB1) {
295 						printf("ifa with a NULL address\n");
296 					}
297 #endif
298 					continue;
299 				}
300 				if (laddr->ifa->ifa_addr->sa_family ==
301 				    to->sa_family) {
302 					/* see if it matches */
303 					struct sockaddr_in *intf_addr, *sin;
304 					intf_addr = (struct sockaddr_in *)
305 						laddr->ifa->ifa_addr;
306 					sin = (struct sockaddr_in *)to;
307 					if (from->sa_family == AF_INET) {
308 						if (sin->sin_addr.s_addr ==
309 						    intf_addr->sin_addr.s_addr) {
310 							match = 1;
311 							SCTP_INP_RUNLOCK(inp);
312 							break;
313 						}
314 					} else {
315 						struct sockaddr_in6 *intf_addr6;
316 						struct sockaddr_in6 *sin6;
317 						sin6 = (struct sockaddr_in6 *)
318 							to;
319 						intf_addr6 = (struct sockaddr_in6 *)
320 							laddr->ifa->ifa_addr;
321 
322 						if (SCTP6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
323 									 &intf_addr6->sin6_addr)) {
324 							match = 1;
325 							SCTP_INP_RUNLOCK(inp);
326 							break;
327 						}
328 					}
329 				}
330 			}
331 			if (match == 0) {
332 				/* This endpoint does not have this address */
333 				SCTP_INP_RUNLOCK(inp);
334 				continue;
335 			}
336 		}
337 		/*
338 		 * Ok if we hit here the ep has the address, does it hold the
339 		 * tcb?
340 		 */
341 
342 		stcb = LIST_FIRST(&inp->sctp_asoc_list);
343 		if (stcb == NULL) {
344 			SCTP_INP_RUNLOCK(inp);
345 			continue;
346 		}
347 		SCTP_TCB_LOCK(stcb);
348 		if (stcb->rport != rport) {
349 			/* remote port does not match. */
350 			SCTP_TCB_UNLOCK(stcb);
351 			SCTP_INP_RUNLOCK(inp);
352 			continue;
353 		}
354 		/* Does this TCB have a matching address? */
355 		TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
356 			if (sctp_cmpaddr(from, rtcache_getdst(&net->ro))) {
357 				/* found it */
358 				if (netp != NULL) {
359 					*netp = net;
360 				}
361 				/* Update the endpoint pointer */
362 				*inp_p = inp;
363 				SCTP_INP_RUNLOCK(inp);
364 				return (stcb);
365 			}
366 		}
367 		SCTP_TCB_UNLOCK(stcb);
368 
369 		SCTP_INP_RUNLOCK(inp);
370 	}
371 	return (NULL);
372 }
373 
374 struct sctp_tcb *
375 sctp_findassociation_ep_asconf(struct mbuf *m, int iphlen, int offset,
376     struct sctphdr *sh, struct sctp_inpcb **inp_p, struct sctp_nets **netp)
377 {
378 	struct sctp_tcb *stcb;
379 	struct sockaddr_in *sin;
380 	struct sockaddr_in6 *sin6;
381 	struct sockaddr_storage local_store, remote_store;
382 	struct ip *iph;
383 	struct sctp_paramhdr parm_buf, *phdr;
384 	int ptype;
385 
386 	memset(&local_store, 0, sizeof(local_store));
387 	memset(&remote_store, 0, sizeof(remote_store));
388 
389 	/* First get the destination address setup too. */
390 	iph = mtod(m, struct ip *);
391 	if (iph->ip_v == IPVERSION) {
392 		/* its IPv4 */
393 		sin = (struct sockaddr_in *)&local_store;
394 		sin->sin_family = AF_INET;
395 		sin->sin_len = sizeof(*sin);
396 		sin->sin_port = sh->dest_port;
397 		sin->sin_addr.s_addr = iph->ip_dst.s_addr ;
398 	} else if (iph->ip_v == (IPV6_VERSION >> 4)) {
399 		/* its IPv6 */
400 		struct ip6_hdr *ip6;
401 		ip6 = mtod(m, struct ip6_hdr *);
402 		sin6 = (struct sockaddr_in6 *)&local_store;
403 		sin6->sin6_family = AF_INET6;
404 		sin6->sin6_len = sizeof(*sin6);
405 		sin6->sin6_port = sh->dest_port;
406 		sin6->sin6_addr = ip6->ip6_dst;
407 	} else {
408 		return NULL;
409 	}
410 
411 	phdr = sctp_get_next_param(m, offset + sizeof(struct sctp_asconf_chunk),
412 	    &parm_buf, sizeof(struct sctp_paramhdr));
413 	if (phdr == NULL) {
414 #ifdef SCTP_DEBUG
415 		if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
416 			printf("sctp_process_control: failed to get asconf lookup addr\n");
417 		}
418 #endif /* SCTP_DEBUG */
419 		return NULL;
420 	}
421 	ptype = (int)((u_int)ntohs(phdr->param_type));
422 	/* get the correlation address */
423 	if (ptype == SCTP_IPV6_ADDRESS) {
424 		/* ipv6 address param */
425 		struct sctp_ipv6addr_param *p6, p6_buf;
426 		if (ntohs(phdr->param_length) != sizeof(struct sctp_ipv6addr_param)) {
427 			return NULL;
428 		}
429 
430 		p6 = (struct sctp_ipv6addr_param *)sctp_get_next_param(m,
431 		    offset + sizeof(struct sctp_asconf_chunk),
432 		    &p6_buf.ph, sizeof(*p6));
433 		if (p6 == NULL) {
434 #ifdef SCTP_DEBUG
435 			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
436 				printf("sctp_process_control: failed to get asconf v6 lookup addr\n");
437 			}
438 #endif /* SCTP_DEBUG */
439 			return (NULL);
440 		}
441 		sin6 = (struct sockaddr_in6 *)&remote_store;
442 		sin6->sin6_family = AF_INET6;
443 		sin6->sin6_len = sizeof(*sin6);
444 		sin6->sin6_port = sh->src_port;
445 		memcpy(&sin6->sin6_addr, &p6->addr, sizeof(struct in6_addr));
446 	} else if (ptype == SCTP_IPV4_ADDRESS) {
447 		/* ipv4 address param */
448 		struct sctp_ipv4addr_param *p4, p4_buf;
449 		if (ntohs(phdr->param_length) != sizeof(struct sctp_ipv4addr_param)) {
450 			return NULL;
451 		}
452 
453 		p4 = (struct sctp_ipv4addr_param *)sctp_get_next_param(m,
454 		    offset + sizeof(struct sctp_asconf_chunk),
455 		    &p4_buf.ph, sizeof(*p4));
456 		if (p4 == NULL) {
457 #ifdef SCTP_DEBUG
458 			if (sctp_debug_on & SCTP_DEBUG_INPUT3) {
459 				printf("sctp_process_control: failed to get asconf v4 lookup addr\n");
460 			}
461 #endif /* SCTP_DEBUG */
462 			return (NULL);
463 		}
464 		sin = (struct sockaddr_in *)&remote_store;
465 		sin->sin_family = AF_INET;
466 		sin->sin_len = sizeof(*sin);
467 		sin->sin_port = sh->src_port;
468 		memcpy(&sin->sin_addr, &p4->addr, sizeof(struct in_addr));
469 	} else {
470 		/* invalid address param type */
471 		return NULL;
472 	}
473 
474 	stcb = sctp_findassociation_ep_addr(inp_p,
475 	    (struct sockaddr *)&remote_store, netp,
476 	    (struct sockaddr *)&local_store, NULL);
477 	return (stcb);
478 }
479 
480 struct sctp_tcb *
481 sctp_findassociation_ep_addr(struct sctp_inpcb **inp_p, struct sockaddr *remote,
482     struct sctp_nets **netp, struct sockaddr *local, struct sctp_tcb *locked_tcb)
483 {
484 	struct sctpasochead *head;
485 	struct sctp_inpcb *inp;
486 	struct sctp_tcb *stcb;
487 	struct sctp_nets *net;
488 	uint16_t rport;
489 
490 	inp = *inp_p;
491 	if (remote->sa_family == AF_INET) {
492 		rport = (((struct sockaddr_in *)remote)->sin_port);
493 	} else if (remote->sa_family == AF_INET6) {
494 		rport = (((struct sockaddr_in6 *)remote)->sin6_port);
495 	} else {
496 		return (NULL);
497 	}
498 	if (locked_tcb) {
499 		/* UN-lock so we can do proper locking here
500 		 * this occurs when called from load_addresses_from_init.
501 		 */
502 		SCTP_TCB_UNLOCK(locked_tcb);
503 	}
504 	SCTP_INP_INFO_RLOCK();
505 	if (inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) {
506 		/*
507 		 * Now either this guy is our listner or it's the connector.
508 		 * If it is the one that issued the connect, then it's only
509 		 * chance is to be the first TCB in the list. If it is the
510 		 * acceptor, then do the special_lookup to hash and find the
511 		 * real inp.
512 		 */
513 		if (inp->sctp_flags & SCTP_PCB_FLAGS_ACCEPTING) {
514 			/* to is peer addr, from is my addr */
515 			stcb = sctp_tcb_special_locate(inp_p, remote, local,
516 						       netp);
517 			if ((stcb != NULL) && (locked_tcb == NULL)){
518 				/* we have a locked tcb, lower refcount */
519 				SCTP_INP_WLOCK(inp);
520 				SCTP_INP_DECR_REF(inp);
521 				SCTP_INP_WUNLOCK(inp);
522 			}
523 			if (locked_tcb != NULL) {
524 				SCTP_INP_RLOCK(locked_tcb->sctp_ep);
525 				SCTP_TCB_LOCK(locked_tcb);
526 				SCTP_INP_RUNLOCK(locked_tcb->sctp_ep);
527 				if (stcb != NULL) {
528 					SCTP_TCB_UNLOCK(stcb);
529 				}
530 			}
531 			SCTP_INP_INFO_RUNLOCK();
532 			return (stcb);
533 		} else {
534 			SCTP_INP_WLOCK(inp);
535 			stcb = LIST_FIRST(&inp->sctp_asoc_list);
536 			if (stcb == NULL) {
537 				goto null_return;
538 			}
539 			SCTP_TCB_LOCK(stcb);
540 			if (stcb->rport != rport) {
541 				/* remote port does not match. */
542 				SCTP_TCB_UNLOCK(stcb);
543 				goto null_return;
544 			}
545 			/* now look at the list of remote addresses */
546 			TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
547 				if (sctp_cmpaddr(remote, rtcache_getdst(&net->ro))) {
548 					/* found it */
549 					if (netp != NULL) {
550 						*netp = net;
551 					}
552 					if (locked_tcb == NULL) {
553 						SCTP_INP_DECR_REF(inp);
554 					}
555 					SCTP_INP_WUNLOCK(inp);
556 					SCTP_INP_INFO_RUNLOCK();
557 					return (stcb);
558 				}
559 			}
560 			SCTP_TCB_UNLOCK(stcb);
561 		}
562 	} else {
563 		SCTP_INP_WLOCK(inp);
564 		head = &inp->sctp_tcbhash[SCTP_PCBHASH_ALLADDR(rport,
565 							       inp->sctp_hashmark)];
566 		if (head == NULL) {
567 			goto null_return;
568 		}
569 		LIST_FOREACH(stcb, head, sctp_tcbhash) {
570 			if (stcb->rport != rport) {
571 				/* remote port does not match */
572 				continue;
573 			}
574 			/* now look at the list of remote addresses */
575 			SCTP_TCB_LOCK(stcb);
576 			TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
577 				if (sctp_cmpaddr(remote, rtcache_getdst(&net->ro))) {
578 					/* found it */
579 					if (netp != NULL) {
580 						*netp = net;
581 					}
582 					if (locked_tcb == NULL) {
583 						SCTP_INP_DECR_REF(inp);
584 					}
585 					SCTP_INP_WUNLOCK(inp);
586 					SCTP_INP_INFO_RUNLOCK();
587 					return (stcb);
588 				}
589 			}
590 			SCTP_TCB_UNLOCK(stcb);
591 		}
592 	}
593  null_return:
594 	/* clean up for returning null */
595 	if (locked_tcb){
596 		if (locked_tcb->sctp_ep != inp) {
597 			SCTP_INP_RLOCK(locked_tcb->sctp_ep);
598 			SCTP_TCB_LOCK(locked_tcb);
599 			SCTP_INP_RUNLOCK(locked_tcb->sctp_ep);
600 		} else {
601 			SCTP_TCB_LOCK(locked_tcb);
602 		}
603 	}
604 	SCTP_INP_WUNLOCK(inp);
605 	SCTP_INP_INFO_RUNLOCK();
606 	/* not found */
607 	return (NULL);
608 }
609 
610 /*
611  * Find an association for a specific endpoint using the association id
612  * given out in the COMM_UP notification
613  */
614 struct sctp_tcb *
615 sctp_findassociation_ep_asocid(struct sctp_inpcb *inp, vaddr_t asoc_id)
616 {
617 	/*
618 	 * Use my the assoc_id to find a endpoint
619 	 */
620 	struct sctpasochead *head;
621 	struct sctp_tcb *stcb;
622 	u_int32_t vtag;
623 
624 	if (asoc_id == 0 || inp == NULL) {
625 		return (NULL);
626 	}
627 	SCTP_INP_INFO_RLOCK();
628 	vtag = (u_int32_t)asoc_id;
629 	head = &sctppcbinfo.sctp_asochash[SCTP_PCBHASH_ASOC(vtag,
630 	    sctppcbinfo.hashasocmark)];
631 	if (head == NULL) {
632 		/* invalid vtag */
633 		SCTP_INP_INFO_RUNLOCK();
634 		return (NULL);
635 	}
636 	LIST_FOREACH(stcb, head, sctp_asocs) {
637 		SCTP_INP_RLOCK(stcb->sctp_ep);
638 		SCTP_TCB_LOCK(stcb);
639 		SCTP_INP_RUNLOCK(stcb->sctp_ep);
640 		if (stcb->asoc.my_vtag == vtag) {
641 			/* candidate */
642 			if (inp != stcb->sctp_ep) {
643 				/* some other guy has the
644 				 * same vtag active (vtag collision).
645 				 */
646 				sctp_pegs[SCTP_VTAG_BOGUS]++;
647 				SCTP_TCB_UNLOCK(stcb);
648 				continue;
649 			}
650 			sctp_pegs[SCTP_VTAG_EXPR]++;
651 			SCTP_INP_INFO_RUNLOCK();
652 			return (stcb);
653 		}
654 		SCTP_TCB_UNLOCK(stcb);
655 	}
656 	SCTP_INP_INFO_RUNLOCK();
657 	return (NULL);
658 }
659 
660 static struct sctp_inpcb *
661 sctp_endpoint_probe(struct sockaddr *nam, struct sctppcbhead *head,
662 		    uint16_t lport)
663 {
664 	struct sctp_inpcb *inp;
665 	struct sockaddr_in *sin;
666 	struct sockaddr_in6 *sin6;
667 	struct sctp_laddr *laddr;
668 
669 	/* Endpoing probe expects
670 	 * that the INP_INFO is locked.
671 	 */
672 	if (nam->sa_family == AF_INET) {
673 		sin = (struct sockaddr_in *)nam;
674 		sin6 = NULL;
675 	} else if (nam->sa_family == AF_INET6) {
676 		sin6 = (struct sockaddr_in6 *)nam;
677 		sin = NULL;
678 	} else {
679 		/* unsupported family */
680 		return (NULL);
681 	}
682 	if (head == NULL)
683 		return (NULL);
684 
685 	LIST_FOREACH(inp, head, sctp_hash) {
686 		SCTP_INP_RLOCK(inp);
687 
688 		if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) &&
689 		    (inp->sctp_lport == lport)) {
690 			/* got it */
691 			if ((nam->sa_family == AF_INET) &&
692 			    (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
693 #if defined(__FreeBSD__) || defined(__APPLE__)
694 			    (((struct inpcb *)inp)->inp_flags & IN6P_IPV6_V6ONLY)
695 #else
696 #if defined(__OpenBSD__)
697 			    (0)	/* For open bsd we do dual bind only */
698 #else
699 			    (((struct in6pcb *)inp)->in6p_flags & IN6P_IPV6_V6ONLY)
700 #endif
701 #endif
702 				) {
703 				/* IPv4 on a IPv6 socket with ONLY IPv6 set */
704 				SCTP_INP_RUNLOCK(inp);
705 				continue;
706 			}
707 			/* A V6 address and the endpoint is NOT bound V6 */
708 			if (nam->sa_family == AF_INET6 &&
709 			   (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) {
710 				SCTP_INP_RUNLOCK(inp);
711 				continue;
712 			}
713 			SCTP_INP_RUNLOCK(inp);
714 			return (inp);
715 		}
716 		SCTP_INP_RUNLOCK(inp);
717 	}
718 
719 	if ((nam->sa_family == AF_INET) &&
720 	    (sin->sin_addr.s_addr == INADDR_ANY)) {
721 		/* Can't hunt for one that has no address specified */
722 		return (NULL);
723 	} else if ((nam->sa_family == AF_INET6) &&
724 		   (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))) {
725 		/* Can't hunt for one that has no address specified */
726 		return (NULL);
727 	}
728 	/*
729 	 * ok, not bound to all so see if we can find a EP bound to this
730 	 * address.
731 	 */
732 #ifdef SCTP_DEBUG
733 	if (sctp_debug_on & SCTP_DEBUG_PCB1) {
734 		printf("Ok, there is NO bound-all available for port:%x\n", ntohs(lport));
735 	}
736 #endif
737 	LIST_FOREACH(inp, head, sctp_hash) {
738 		SCTP_INP_RLOCK(inp);
739 		if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL)) {
740 			SCTP_INP_RUNLOCK(inp);
741 			continue;
742 		}
743 		/*
744 		 * Ok this could be a likely candidate, look at all of
745 		 * its addresses
746 		 */
747 		if (inp->sctp_lport != lport) {
748 			SCTP_INP_RUNLOCK(inp);
749 			continue;
750 		}
751 #ifdef SCTP_DEBUG
752 		if (sctp_debug_on & SCTP_DEBUG_PCB1) {
753 			printf("Ok, found maching local port\n");
754 		}
755 #endif
756 		LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
757 			if (laddr->ifa == NULL) {
758 #ifdef SCTP_DEBUG
759 				if (sctp_debug_on & SCTP_DEBUG_PCB1) {
760 					printf("An ounce of prevention is worth a pound of cure\n");
761 				}
762 #endif
763 				continue;
764 			}
765 #ifdef SCTP_DEBUG
766 			if (sctp_debug_on & SCTP_DEBUG_PCB1) {
767 				printf("Ok laddr->ifa:%p is possible, ",
768 				    laddr->ifa);
769 			}
770 #endif
771 			if (laddr->ifa->ifa_addr == NULL) {
772 #ifdef SCTP_DEBUG
773 				if (sctp_debug_on & SCTP_DEBUG_PCB1) {
774 					printf("Huh IFA as an ifa_addr=NULL, ");
775 				}
776 #endif
777 				continue;
778 			}
779 #ifdef SCTP_DEBUG
780 			if (sctp_debug_on & SCTP_DEBUG_PCB1) {
781 				printf("Ok laddr->ifa:%p is possible, ",
782 				    laddr->ifa->ifa_addr);
783 				sctp_print_address(laddr->ifa->ifa_addr);
784 				printf("looking for ");
785 				sctp_print_address(nam);
786 			}
787 #endif
788 			if (laddr->ifa->ifa_addr->sa_family == nam->sa_family) {
789 				/* possible, see if it matches */
790 				struct sockaddr_in *intf_addr;
791 				intf_addr = (struct sockaddr_in *)
792 				    laddr->ifa->ifa_addr;
793 				if (nam->sa_family == AF_INET) {
794 					if (sin->sin_addr.s_addr ==
795 					    intf_addr->sin_addr.s_addr) {
796 #ifdef SCTP_DEBUG
797 						if (sctp_debug_on & SCTP_DEBUG_PCB1) {
798 							printf("YES, return ep:%p\n", inp);
799 						}
800 #endif
801 						SCTP_INP_RUNLOCK(inp);
802 						return (inp);
803 					}
804 				} else if (nam->sa_family == AF_INET6) {
805 					struct sockaddr_in6 *intf_addr6;
806 					intf_addr6 = (struct sockaddr_in6 *)
807 					    laddr->ifa->ifa_addr;
808 					if (SCTP6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
809 				 	    &intf_addr6->sin6_addr)) {
810 #ifdef SCTP_DEBUG
811 						if (sctp_debug_on & SCTP_DEBUG_PCB1) {
812 							printf("YES, return ep:%p\n", inp);
813 						}
814 #endif
815 						SCTP_INP_RUNLOCK(inp);
816 						return (inp);
817 					}
818 				}
819 			}
820 			SCTP_INP_RUNLOCK(inp);
821 		}
822 	}
823 #ifdef SCTP_DEBUG
824 	if (sctp_debug_on & SCTP_DEBUG_PCB1) {
825 		printf("NO, Falls out to NULL\n");
826 	}
827 #endif
828 	return (NULL);
829 }
830 
831 
832 struct sctp_inpcb *
833 sctp_pcb_findep(struct sockaddr *nam, int find_tcp_pool, int have_lock)
834 {
835 	/*
836 	 * First we check the hash table to see if someone has this port
837 	 * bound with just the port.
838 	 */
839 	struct sctp_inpcb *inp;
840 	struct sctppcbhead *head;
841 	int lport;
842 #ifdef SCTP_DEBUG
843 	if (sctp_debug_on & SCTP_DEBUG_PCB1) {
844 		printf("Looking for endpoint %d :",
845 		       ntohs(((struct sockaddr_in *)nam)->sin_port));
846 		sctp_print_address(nam);
847 	}
848 #endif
849 	if (nam->sa_family == AF_INET) {
850 		lport = ((struct sockaddr_in *)nam)->sin_port;
851 	} else if (nam->sa_family == AF_INET6) {
852 		lport = ((struct sockaddr_in6 *)nam)->sin6_port;
853 	} else {
854 		/* unsupported family */
855 		return (NULL);
856 	}
857 	/*
858 	 * I could cheat here and just cast to one of the types but we will
859 	 * do it right. It also provides the check against an Unsupported
860 	 * type too.
861 	 */
862 	/* Find the head of the ALLADDR chain */
863 	if (have_lock == 0) {
864 		SCTP_INP_INFO_RLOCK();
865 	}
866 	head = &sctppcbinfo.sctp_ephash[SCTP_PCBHASH_ALLADDR(lport,
867 							     sctppcbinfo.hashmark)];
868 #ifdef SCTP_DEBUG
869 	if (sctp_debug_on & SCTP_DEBUG_PCB1) {
870 		printf("Main hash to lookup at head:%p\n", head);
871 	}
872 #endif
873  	inp = sctp_endpoint_probe(nam, head, lport);
874 
875 	/*
876 	 * If the TCP model exists it could be that the main listening
877 	 * endpoint is gone but there exists a connected socket for this
878 	 * guy yet. If so we can return the first one that we find. This
879 	 * may NOT be the correct one but the sctp_findassociation_ep_addr
880 	 * has further code to look at all TCP models.
881 	 */
882 	if (inp == NULL && find_tcp_pool) {
883 		unsigned int i;
884 #ifdef SCTP_DEBUG
885 		if (sctp_debug_on & SCTP_DEBUG_PCB1) {
886 			printf("EP was NULL and TCP model is supported\n");
887 		}
888 #endif
889 		for (i = 0; i < sctppcbinfo.hashtblsize; i++) {
890 			/*
891 			 * This is real gross, but we do NOT have a remote
892 			 * port at this point depending on who is calling. We
893 			 * must therefore look for ANY one that matches our
894 			 * local port :/
895 			 */
896 			head = &sctppcbinfo.sctp_tcpephash[i];
897 			if (LIST_FIRST(head)) {
898 				inp = sctp_endpoint_probe(nam, head, lport);
899 				if (inp) {
900 					/* Found one */
901 					break;
902 				}
903 			}
904 		}
905 	}
906 #ifdef SCTP_DEBUG
907 	if (sctp_debug_on & SCTP_DEBUG_PCB1) {
908 		printf("EP to return is %p\n", inp);
909 	}
910 #endif
911 	if (have_lock == 0) {
912 		if (inp) {
913 			SCTP_INP_WLOCK(inp);
914 			SCTP_INP_INCR_REF(inp);
915 			SCTP_INP_WUNLOCK(inp);
916 		}
917 		SCTP_INP_INFO_RUNLOCK();
918 	} else {
919 		if (inp) {
920 			SCTP_INP_WLOCK(inp);
921 			SCTP_INP_INCR_REF(inp);
922 			SCTP_INP_WUNLOCK(inp);
923 		}
924 	}
925 	return (inp);
926 }
927 
928 /*
929  * Find an association for an endpoint with the pointer to whom you want
930  * to send to and the endpoint pointer. The address can be IPv4 or IPv6.
931  * We may need to change the *to to some other struct like a mbuf...
932  */
933 struct sctp_tcb *
934 sctp_findassociation_addr_sa(struct sockaddr *to, struct sockaddr *from,
935     struct sctp_inpcb **inp_p, struct sctp_nets **netp, int find_tcp_pool)
936 {
937 	struct sctp_inpcb *inp;
938 	struct sctp_tcb *retval;
939 
940 	SCTP_INP_INFO_RLOCK();
941 	if (find_tcp_pool) {
942 		if (inp_p != NULL) {
943 			retval = sctp_tcb_special_locate(inp_p, from, to, netp);
944 		} else {
945 			retval = sctp_tcb_special_locate(&inp, from, to, netp);
946 		}
947 		if (retval != NULL) {
948 			SCTP_INP_INFO_RUNLOCK();
949 			return (retval);
950 		}
951 	}
952 	inp = sctp_pcb_findep(to, 0, 1);
953 	if (inp_p != NULL) {
954 		*inp_p = inp;
955 	}
956 	SCTP_INP_INFO_RUNLOCK();
957 
958 	if (inp == NULL) {
959 		return (NULL);
960 	}
961 
962 	/*
963 	 * ok, we have an endpoint, now lets find the assoc for it (if any)
964 	 * we now place the source address or from in the to of the find
965 	 * endpoint call. Since in reality this chain is used from the
966 	 * inbound packet side.
967 	 */
968 	if (inp_p != NULL) {
969 		return (sctp_findassociation_ep_addr(inp_p, from, netp, to, NULL));
970 	} else {
971 		return (sctp_findassociation_ep_addr(&inp, from, netp, to, NULL));
972 	}
973 }
974 
975 
976 /*
977  * This routine will grub through the mbuf that is a INIT or INIT-ACK and
978  * find all addresses that the sender has specified in any address list.
979  * Each address will be used to lookup the TCB and see if one exits.
980  */
981 static struct sctp_tcb *
982 sctp_findassociation_special_addr(struct mbuf *m, int iphlen, int offset,
983     struct sctphdr *sh, struct sctp_inpcb **inp_p, struct sctp_nets **netp,
984     struct sockaddr *dest)
985 {
986 	struct sockaddr_in sin4;
987 	struct sockaddr_in6 sin6;
988 	struct sctp_paramhdr *phdr, parm_buf;
989 	struct sctp_tcb *retval;
990 	u_int32_t ptype, plen;
991 
992 	memset(&sin4, 0, sizeof(sin4));
993 	memset(&sin6, 0, sizeof(sin6));
994 	sin4.sin_len = sizeof(sin4);
995 	sin4.sin_family = AF_INET;
996 	sin4.sin_port = sh->src_port;
997 	sin6.sin6_len = sizeof(sin6);
998 	sin6.sin6_family = AF_INET6;
999 	sin6.sin6_port = sh->src_port;
1000 
1001 	retval = NULL;
1002 	offset += sizeof(struct sctp_init_chunk);
1003 
1004 	phdr = sctp_get_next_param(m, offset, &parm_buf, sizeof(parm_buf));
1005 	while (phdr != NULL) {
1006 		/* now we must see if we want the parameter */
1007 		ptype = ntohs(phdr->param_type);
1008 		plen = ntohs(phdr->param_length);
1009 		if (plen == 0) {
1010 #ifdef SCTP_DEBUG
1011 			if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1012 				printf("sctp_findassociation_special_addr: Impossible length in parameter\n");
1013 			}
1014 #endif /* SCTP_DEBUG */
1015 			break;
1016 		}
1017 		if (ptype == SCTP_IPV4_ADDRESS &&
1018 		    plen == sizeof(struct sctp_ipv4addr_param)) {
1019 			/* Get the rest of the address */
1020 			struct sctp_ipv4addr_param ip4_parm, *p4;
1021 
1022 			phdr = sctp_get_next_param(m, offset,
1023 			    (struct sctp_paramhdr *)&ip4_parm, plen);
1024 			if (phdr == NULL) {
1025 				return (NULL);
1026 			}
1027 			p4 = (struct sctp_ipv4addr_param *)phdr;
1028 			memcpy(&sin4.sin_addr, &p4->addr, sizeof(p4->addr));
1029 			/* look it up */
1030 			retval = sctp_findassociation_ep_addr(inp_p,
1031 			    (struct sockaddr *)&sin4, netp, dest, NULL);
1032 			if (retval != NULL) {
1033 				return (retval);
1034 			}
1035 		} else if (ptype == SCTP_IPV6_ADDRESS &&
1036 		    plen == sizeof(struct sctp_ipv6addr_param)) {
1037 			/* Get the rest of the address */
1038 			struct sctp_ipv6addr_param ip6_parm, *p6;
1039 
1040 			phdr = sctp_get_next_param(m, offset,
1041 			    (struct sctp_paramhdr *)&ip6_parm, plen);
1042 			if (phdr == NULL) {
1043 				return (NULL);
1044 			}
1045 			p6 = (struct sctp_ipv6addr_param *)phdr;
1046 			memcpy(&sin6.sin6_addr, &p6->addr, sizeof(p6->addr));
1047 			/* look it up */
1048 			retval = sctp_findassociation_ep_addr(inp_p,
1049 			    (struct sockaddr *)&sin6, netp, dest, NULL);
1050 			if (retval != NULL) {
1051 				return (retval);
1052 			}
1053 		}
1054 		offset += SCTP_SIZE32(plen);
1055 		phdr = sctp_get_next_param(m, offset, &parm_buf,
1056 		    sizeof(parm_buf));
1057 	}
1058 	return (NULL);
1059 }
1060 
1061 static struct sctp_tcb *
1062 sctp_findassoc_by_vtag(struct sockaddr *from, uint32_t vtag,
1063     struct sctp_inpcb **inp_p, struct sctp_nets **netp, uint16_t rport,
1064     uint16_t lport)
1065 {
1066 	/*
1067 	 * Use my vtag to hash. If we find it we then verify the source addr
1068 	 * is in the assoc. If all goes well we save a bit on rec of a packet.
1069 	 */
1070 	struct sctpasochead *head;
1071 	struct sctp_nets *net;
1072 	struct sctp_tcb *stcb;
1073 
1074 	SCTP_INP_INFO_RLOCK();
1075 	head = &sctppcbinfo.sctp_asochash[SCTP_PCBHASH_ASOC(vtag,
1076 	    sctppcbinfo.hashasocmark)];
1077 	if (head == NULL) {
1078 		/* invalid vtag */
1079 		SCTP_INP_INFO_RUNLOCK();
1080 		return (NULL);
1081 	}
1082 	LIST_FOREACH(stcb, head, sctp_asocs) {
1083 		SCTP_INP_RLOCK(stcb->sctp_ep);
1084 		SCTP_TCB_LOCK(stcb);
1085 		SCTP_INP_RUNLOCK(stcb->sctp_ep);
1086 		if (stcb->asoc.my_vtag == vtag) {
1087 			/* candidate */
1088 			if (stcb->rport != rport) {
1089 				/*
1090 				 * we could remove this if vtags are unique
1091 				 * across the system.
1092 				 */
1093 				SCTP_TCB_UNLOCK(stcb);
1094 				continue;
1095 			}
1096 			if (stcb->sctp_ep->sctp_lport != lport) {
1097 				/*
1098 				 * we could remove this if vtags are unique
1099 				 * across the system.
1100 				 */
1101 				SCTP_TCB_UNLOCK(stcb);
1102 				continue;
1103 			}
1104 			net = sctp_findnet(stcb, from);
1105 			if (net) {
1106 				/* yep its him. */
1107 				*netp = net;
1108 				sctp_pegs[SCTP_VTAG_EXPR]++;
1109 				*inp_p = stcb->sctp_ep;
1110 				SCTP_INP_INFO_RUNLOCK();
1111 				return (stcb);
1112 			} else {
1113  				/* not him, this should only
1114  				 * happen in rare cases so
1115  				 * I peg it.
1116   				 */
1117  				sctp_pegs[SCTP_VTAG_BOGUS]++;
1118 			}
1119 		}
1120 		SCTP_TCB_UNLOCK(stcb);
1121 	}
1122 	SCTP_INP_INFO_RUNLOCK();
1123 	return (NULL);
1124 }
1125 
1126 /*
1127  * Find an association with the pointer to the inbound IP packet. This
1128  * can be a IPv4 or IPv6 packet.
1129  */
1130 struct sctp_tcb *
1131 sctp_findassociation_addr(struct mbuf *m, int iphlen, int offset,
1132     struct sctphdr *sh, struct sctp_chunkhdr *ch,
1133     struct sctp_inpcb **inp_p, struct sctp_nets **netp)
1134 {
1135 	int find_tcp_pool;
1136 	struct ip *iph;
1137 	struct sctp_tcb *retval;
1138 	struct sockaddr_storage to_store, from_store;
1139 	struct sockaddr *to = (struct sockaddr *)&to_store;
1140 	struct sockaddr *from = (struct sockaddr *)&from_store;
1141 	struct sctp_inpcb *inp;
1142 
1143 
1144 	iph = mtod(m, struct ip *);
1145 	if (iph->ip_v == IPVERSION) {
1146 		/* its IPv4 */
1147 		struct sockaddr_in *to4, *from4;
1148 
1149 		to4 = (struct sockaddr_in *)&to_store;
1150 		from4 = (struct sockaddr_in *)&from_store;
1151 		memset(to4, 0, sizeof(*to4));
1152 		memset(from4, 0, sizeof(*from4));
1153 		from4->sin_family = to4->sin_family = AF_INET;
1154 		from4->sin_len = to4->sin_len = sizeof(struct sockaddr_in);
1155 		from4->sin_addr.s_addr  = iph->ip_src.s_addr;
1156 		to4->sin_addr.s_addr = iph->ip_dst.s_addr ;
1157 		from4->sin_port = sh->src_port;
1158 		to4->sin_port = sh->dest_port;
1159 	} else if (iph->ip_v == (IPV6_VERSION >> 4)) {
1160 		/* its IPv6 */
1161 		struct ip6_hdr *ip6;
1162 		struct sockaddr_in6 *to6, *from6;
1163 
1164 		ip6 = mtod(m, struct ip6_hdr *);
1165 		to6 = (struct sockaddr_in6 *)&to_store;
1166 		from6 = (struct sockaddr_in6 *)&from_store;
1167 		memset(to6, 0, sizeof(*to6));
1168 		memset(from6, 0, sizeof(*from6));
1169 		from6->sin6_family = to6->sin6_family = AF_INET6;
1170 		from6->sin6_len = to6->sin6_len = sizeof(struct sockaddr_in6);
1171 		from6->sin6_addr = ip6->ip6_src;
1172 		to6->sin6_addr = ip6->ip6_dst;
1173 		from6->sin6_port = sh->src_port;
1174 		to6->sin6_port = sh->dest_port;
1175 		/* Get the scopes in properly to the sin6 addr's */
1176 #if defined(SCTP_BASE_FREEBSD) || defined(__APPLE__)
1177 		/* We probably don't need this operation (jinmei@kame) */
1178 		(void)in6_recoverscope(to6, &to6->sin6_addr, NULL);
1179 		(void)in6_embedscope(&to6->sin6_addr, to6, NULL, NULL);
1180 
1181 		(void)in6_recoverscope(from6, &from6->sin6_addr, NULL);
1182 		(void)in6_embedscope(&from6->sin6_addr, from6, NULL, NULL);
1183 #endif
1184 	} else {
1185 		/* Currently not supported. */
1186 		return (NULL);
1187 	}
1188 #ifdef SCTP_DEBUG
1189 	if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1190 		printf("Looking for port %d address :",
1191 		       ntohs(((struct sockaddr_in *)to)->sin_port));
1192 		sctp_print_address(to);
1193 		printf("From for port %d address :",
1194 		       ntohs(((struct sockaddr_in *)from)->sin_port));
1195 		sctp_print_address(from);
1196 	}
1197 #endif
1198 
1199 	if (sh->v_tag) {
1200 		/* we only go down this path if vtag is non-zero */
1201 		retval = sctp_findassoc_by_vtag(from, ntohl(sh->v_tag),
1202 		    inp_p, netp, sh->src_port, sh->dest_port);
1203 		if (retval) {
1204 			return (retval);
1205 		}
1206 	}
1207 	find_tcp_pool = 0;
1208 	if ((ch->chunk_type != SCTP_INITIATION) &&
1209 	    (ch->chunk_type != SCTP_INITIATION_ACK) &&
1210 	    (ch->chunk_type != SCTP_COOKIE_ACK) &&
1211 	    (ch->chunk_type != SCTP_COOKIE_ECHO)) {
1212 		/* Other chunk types go to the tcp pool. */
1213 		find_tcp_pool = 1;
1214 	}
1215 	if (inp_p) {
1216 		retval = sctp_findassociation_addr_sa(to, from, inp_p, netp,
1217 		    find_tcp_pool);
1218 		inp = *inp_p;
1219 	} else {
1220 		retval = sctp_findassociation_addr_sa(to, from, &inp, netp,
1221 		    find_tcp_pool);
1222 	}
1223 #ifdef SCTP_DEBUG
1224 	if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1225 		printf("retval:%p inp:%p\n", retval, inp);
1226 	}
1227 #endif
1228 	if (retval == NULL && inp) {
1229 		/* Found a EP but not this address */
1230 #ifdef SCTP_DEBUG
1231 		if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1232 			printf("Found endpoint %p but no asoc - ep state:%x\n",
1233 			    inp, inp->sctp_flags);
1234 		}
1235 #endif
1236 		if ((ch->chunk_type == SCTP_INITIATION) ||
1237 		    (ch->chunk_type == SCTP_INITIATION_ACK)) {
1238 			/*
1239 			 * special hook, we do NOT return linp or an
1240 			 * association that is linked to an existing
1241 			 * association that is under the TCP pool (i.e. no
1242 			 * listener exists). The endpoint finding routine
1243 			 * will always find a listner before examining the
1244 			 * TCP pool.
1245 			 */
1246 			if (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) {
1247 #ifdef SCTP_DEBUG
1248 				if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1249 					printf("Gak, its in the TCP pool... return NULL");
1250 				}
1251 #endif
1252 				if (inp_p) {
1253 					*inp_p = NULL;
1254 				}
1255 				return (NULL);
1256 			}
1257 #ifdef SCTP_DEBUG
1258 			if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1259 				printf("Now doing SPECIAL find\n");
1260 			}
1261 #endif
1262 			retval = sctp_findassociation_special_addr(m, iphlen,
1263 			    offset, sh, inp_p, netp, to);
1264 		}
1265 	}
1266 #ifdef SCTP_DEBUG
1267 	if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1268 	    printf("retval is %p\n", retval);
1269 	}
1270 #endif
1271 	return (retval);
1272 }
1273 
1274 extern int sctp_max_burst_default;
1275 
1276 extern unsigned int sctp_delayed_sack_time_default;
1277 extern unsigned int sctp_heartbeat_interval_default;
1278 extern unsigned int sctp_pmtu_raise_time_default;
1279 extern unsigned int sctp_shutdown_guard_time_default;
1280 extern unsigned int sctp_secret_lifetime_default;
1281 
1282 extern unsigned int sctp_rto_max_default;
1283 extern unsigned int sctp_rto_min_default;
1284 extern unsigned int sctp_rto_initial_default;
1285 extern unsigned int sctp_init_rto_max_default;
1286 extern unsigned int sctp_valid_cookie_life_default;
1287 extern unsigned int sctp_init_rtx_max_default;
1288 extern unsigned int sctp_assoc_rtx_max_default;
1289 extern unsigned int sctp_path_rtx_max_default;
1290 extern unsigned int sctp_nr_outgoing_streams_default;
1291 
1292 /*
1293  * allocate a sctp_inpcb and setup a temporary binding to a port/all
1294  * addresses. This way if we don't get a bind we by default pick a ephemeral
1295  * port with all addresses bound.
1296  */
1297 int
1298 sctp_inpcb_alloc(struct socket *so)
1299 {
1300 	/*
1301 	 * we get called when a new endpoint starts up. We need to allocate
1302 	 * the sctp_inpcb structure from the zone and init it. Mark it as
1303 	 * unbound and find a port that we can use as an ephemeral with
1304 	 * INADDR_ANY. If the user binds later no problem we can then add
1305 	 * in the specific addresses. And setup the default parameters for
1306 	 * the EP.
1307 	 */
1308 	int i, error;
1309 	struct sctp_inpcb *inp, *n_inp;
1310 	struct sctp_pcb *m;
1311 	struct timeval time;
1312 
1313 	error = 0;
1314 
1315 	printf("sctp_inpcb_alloc: starting\n");
1316         /* Hack alert:
1317 	 *
1318 	 * This code audits the entire INP list to see if
1319 	 * any ep's that are in the GONE state are now
1320 	 * all free. This should not happen really since when
1321 	 * the last association if freed we should end up deleting
1322 	 * the inpcb. This code including the locks should
1323 	 * be taken out ... since the last set of fixes I
1324 	 * have not seen the "Found a GONE on list" has not
1325 	 * came out. But i am paranoid and we will leave this
1326 	 * in at the cost of efficency on allocation of PCB's.
1327 	 * Probably we should move this to the invariant
1328 	 * compile options
1329 	 */
1330 /* #ifdef INVARIANTS*/
1331 	SCTP_INP_INFO_RLOCK();
1332 	inp = LIST_FIRST(&sctppcbinfo.listhead);
1333 	while (inp) {
1334 		n_inp = LIST_NEXT(inp, sctp_list);
1335 		if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
1336 			if (LIST_FIRST(&inp->sctp_asoc_list) == NULL) {
1337 				/* finish the job now */
1338 				printf("Found a GONE on list\n");
1339 				SCTP_INP_INFO_RUNLOCK();
1340 				sctp_inpcb_free(inp, 1);
1341 				SCTP_INP_INFO_RLOCK();
1342 			}
1343 		}
1344 		inp = n_inp;
1345 	}
1346 	SCTP_INP_INFO_RUNLOCK();
1347 /* #endif INVARIANTS*/
1348 
1349 	SCTP_INP_INFO_WLOCK();
1350 	inp = (struct sctp_inpcb *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_ep);
1351 	if (inp == NULL) {
1352 		printf("Out of SCTP-INPCB structures - no resources\n");
1353 		SCTP_INP_INFO_WUNLOCK();
1354 		return (ENOBUFS);
1355 	}
1356 
1357 	/* zap it */
1358 	memset(inp, 0, sizeof(*inp));
1359 
1360 	/* bump generations */
1361 	inp->ip_inp.inp.inp_socket = so;
1362 
1363 	/* setup socket pointers */
1364 	inp->sctp_socket = so;
1365 
1366 	/* setup inpcb socket too */
1367 	inp->ip_inp.inp.inp_socket = so;
1368 	inp->sctp_frag_point = SCTP_DEFAULT_MAXSEGMENT;
1369 #ifdef IPSEC
1370 #if !(defined(__OpenBSD__) || defined(__APPLE__))
1371 	{
1372 		struct inpcbpolicy *pcb_sp = NULL;
1373 		error = ipsec_init_pcbpolicy(so, &pcb_sp);
1374 		/* Arrange to share the policy */
1375 		inp->ip_inp.inp.inp_sp = pcb_sp;
1376 		((struct in6pcb *)(&inp->ip_inp.inp))->in6p_sp = pcb_sp;
1377 	}
1378 #else
1379 	/* not sure what to do for openbsd here */
1380 	error = 0;
1381 #endif
1382 	if (error != 0) {
1383 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_ep, inp);
1384 		SCTP_INP_INFO_WUNLOCK();
1385 		return error;
1386 	}
1387 #endif /* IPSEC */
1388 	sctppcbinfo.ipi_count_ep++;
1389 #if defined(__FreeBSD__) || defined(__APPLE__)
1390 	inp->ip_inp.inp.inp_gencnt = ++sctppcbinfo.ipi_gencnt_ep;
1391 	inp->ip_inp.inp.inp_ip_ttl = ip_defttl;
1392 #else
1393 	inp->inp_ip_ttl = ip_defttl;
1394 	inp->inp_ip_tos = 0;
1395 #endif
1396 
1397 	so->so_pcb = (void *)inp;
1398 
1399 	if ((so->so_type == SOCK_DGRAM) ||
1400 	    (so->so_type == SOCK_SEQPACKET)) {
1401 		/* UDP style socket */
1402 		inp->sctp_flags = (SCTP_PCB_FLAGS_UDPTYPE |
1403 		    SCTP_PCB_FLAGS_UNBOUND);
1404 		inp->sctp_flags |= (SCTP_PCB_FLAGS_RECVDATAIOEVNT);
1405 		/* Be sure it is NON-BLOCKING IO for UDP */
1406 		/*so->so_state |= SS_NBIO;*/
1407 	} else if (so->so_type == SOCK_STREAM) {
1408 		/* TCP style socket */
1409 		inp->sctp_flags = (SCTP_PCB_FLAGS_TCPTYPE |
1410 		    SCTP_PCB_FLAGS_UNBOUND);
1411 		inp->sctp_flags |= (SCTP_PCB_FLAGS_RECVDATAIOEVNT);
1412 		/* Be sure we have blocking IO bu default */
1413 		so->so_state &= ~SS_NBIO;
1414 	} else {
1415 		/*
1416 		 * unsupported socket type (RAW, etc)- in case we missed
1417 		 * it in protosw
1418 		 */
1419 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_ep, inp);
1420 		SCTP_INP_INFO_WUNLOCK();
1421 		return (EOPNOTSUPP);
1422 	}
1423 	inp->sctp_tcbhash = SCTP_ZONE_GET(sctppcbinfo.ipi_zone_hash);
1424 	if (inp->sctp_tcbhash == NULL) {
1425 		printf("Out of SCTP-INPCB->hashinit - no resources\n");
1426 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_ep, inp);
1427 		SCTP_INP_INFO_WUNLOCK();
1428 		return (ENOBUFS);
1429 	} else {
1430 		for (i = 0; i < sctp_pcbtblsize; i++)
1431 			LIST_INIT(&inp->sctp_tcbhash[i]);
1432 		for (i = 1; i < sctp_pcbtblsize; i <<= 1)
1433 			continue;
1434 		inp->sctp_hashmark = i - 1;
1435 	}
1436         /* LOCK init's */
1437 	SCTP_INP_LOCK_INIT(inp);
1438 	SCTP_ASOC_CREATE_LOCK_INIT(inp);
1439 	/* lock the new ep */
1440 	SCTP_INP_WLOCK(inp);
1441 
1442 	/* add it to the info area */
1443 	LIST_INSERT_HEAD(&sctppcbinfo.listhead, inp, sctp_list);
1444 	SCTP_INP_INFO_WUNLOCK();
1445 
1446 	LIST_INIT(&inp->sctp_addr_list);
1447 	LIST_INIT(&inp->sctp_asoc_list);
1448 	TAILQ_INIT(&inp->sctp_queue_list);
1449 	/* Init the timer structure for signature change */
1450 	callout_init(&inp->sctp_ep.signature_change.timer, 0);
1451 	inp->sctp_ep.signature_change.type = SCTP_TIMER_TYPE_NEWCOOKIE;
1452 
1453 	/* now init the actual endpoint default data */
1454 	m = &inp->sctp_ep;
1455 
1456 	/* setup the base timeout information */
1457 	m->sctp_timeoutticks[SCTP_TIMER_SEND] = SEC_TO_TICKS(SCTP_SEND_SEC); /* needed ? */
1458 	m->sctp_timeoutticks[SCTP_TIMER_INIT] = SEC_TO_TICKS(SCTP_INIT_SEC); /* needed ? */
1459 	m->sctp_timeoutticks[SCTP_TIMER_RECV] = MSEC_TO_TICKS(sctp_delayed_sack_time_default);
1460 	m->sctp_timeoutticks[SCTP_TIMER_HEARTBEAT] = sctp_heartbeat_interval_default; /* this is in MSEC */
1461 	m->sctp_timeoutticks[SCTP_TIMER_PMTU] = SEC_TO_TICKS(sctp_pmtu_raise_time_default);
1462 	m->sctp_timeoutticks[SCTP_TIMER_MAXSHUTDOWN] = SEC_TO_TICKS(sctp_shutdown_guard_time_default);
1463 	m->sctp_timeoutticks[SCTP_TIMER_SIGNATURE] = SEC_TO_TICKS(sctp_secret_lifetime_default);
1464 	/* all max/min max are in ms */
1465 	m->sctp_maxrto = sctp_rto_max_default;
1466 	m->sctp_minrto = sctp_rto_min_default;
1467 	m->initial_rto = sctp_rto_initial_default;
1468 	m->initial_init_rto_max = sctp_init_rto_max_default;
1469 
1470 	m->max_open_streams_intome = MAX_SCTP_STREAMS;
1471 
1472 	m->max_init_times = sctp_init_rtx_max_default;
1473 	m->max_send_times = sctp_assoc_rtx_max_default;
1474 	m->def_net_failure = sctp_path_rtx_max_default;
1475 	m->sctp_sws_sender = SCTP_SWS_SENDER_DEF;
1476 	m->sctp_sws_receiver = SCTP_SWS_RECEIVER_DEF;
1477 	m->max_burst = sctp_max_burst_default;
1478 	/* number of streams to pre-open on a association */
1479 	m->pre_open_stream_count = sctp_nr_outgoing_streams_default;
1480 
1481 	/* Add adaption cookie */
1482 	m->adaption_layer_indicator = 0x504C5253;
1483 
1484 	/* seed random number generator */
1485 	m->random_counter = 1;
1486 	m->store_at = SCTP_SIGNATURE_SIZE;
1487 #if defined(__FreeBSD__) && (__FreeBSD_version < 500000)
1488 	read_random_unlimited(m->random_numbers, sizeof(m->random_numbers));
1489 #elif defined(__APPLE__) || (__FreeBSD_version > 500000)
1490 	read_random(m->random_numbers, sizeof(m->random_numbers));
1491 #elif defined(__OpenBSD__)
1492 	get_random_bytes(m->random_numbers, sizeof(m->random_numbers));
1493 #elif defined(__NetBSD__) && NRND > 0
1494 	rnd_extract_data(m->random_numbers, sizeof(m->random_numbers),
1495 			 RND_EXTRACT_ANY);
1496 #else
1497 	{
1498 		u_int32_t *ranm, *ranp;
1499 		ranp = (u_int32_t *)&m->random_numbers;
1500 		ranm = ranp + (SCTP_SIGNATURE_ALOC_SIZE/sizeof(u_int32_t));
1501 		if ((u_long)ranp % 4) {
1502 			/* not a even boundary? */
1503 			ranp = (u_int32_t *)SCTP_SIZE32((u_long)ranp);
1504 		}
1505 		while (ranp < ranm) {
1506 			*ranp = random();
1507 			ranp++;
1508 		}
1509 	}
1510 #endif
1511 	sctp_fill_random_store(m);
1512 
1513 	/* Minimum cookie size */
1514 	m->size_of_a_cookie = (sizeof(struct sctp_init_msg) * 2) +
1515 		sizeof(struct sctp_state_cookie);
1516 	m->size_of_a_cookie += SCTP_SIGNATURE_SIZE;
1517 
1518 	/* Setup the initial secret */
1519 	SCTP_GETTIME_TIMEVAL(&time);
1520 	m->time_of_secret_change = time.tv_sec;
1521 
1522 	for (i = 0; i < SCTP_NUMBER_OF_SECRETS; i++) {
1523 		m->secret_key[0][i] = sctp_select_initial_TSN(m);
1524 	}
1525 	sctp_timer_start(SCTP_TIMER_TYPE_NEWCOOKIE, inp, NULL, NULL);
1526 
1527 	/* How long is a cookie good for ? */
1528 	m->def_cookie_life = sctp_valid_cookie_life_default;
1529 	SCTP_INP_WUNLOCK(inp);
1530 	return (error);
1531 }
1532 
1533 
1534 void
1535 sctp_move_pcb_and_assoc(struct sctp_inpcb *old_inp, struct sctp_inpcb *new_inp,
1536     struct sctp_tcb *stcb)
1537 {
1538 	uint16_t lport, rport;
1539 	struct sctppcbhead *head;
1540 	struct sctp_laddr *laddr, *oladdr;
1541 
1542 	SCTP_TCB_UNLOCK(stcb);
1543 	SCTP_INP_INFO_WLOCK();
1544 	SCTP_INP_WLOCK(old_inp);
1545 	SCTP_INP_WLOCK(new_inp);
1546 	SCTP_TCB_LOCK(stcb);
1547 
1548 	new_inp->sctp_ep.time_of_secret_change =
1549 	    old_inp->sctp_ep.time_of_secret_change;
1550 	memcpy(new_inp->sctp_ep.secret_key, old_inp->sctp_ep.secret_key,
1551 	    sizeof(old_inp->sctp_ep.secret_key));
1552 	new_inp->sctp_ep.current_secret_number =
1553 	    old_inp->sctp_ep.current_secret_number;
1554 	new_inp->sctp_ep.last_secret_number =
1555 	    old_inp->sctp_ep.last_secret_number;
1556 	new_inp->sctp_ep.size_of_a_cookie = old_inp->sctp_ep.size_of_a_cookie;
1557 
1558 	/* Copy the port across */
1559 	lport = new_inp->sctp_lport = old_inp->sctp_lport;
1560 	rport = stcb->rport;
1561 	/* Pull the tcb from the old association */
1562 	LIST_REMOVE(stcb, sctp_tcbhash);
1563 	LIST_REMOVE(stcb, sctp_tcblist);
1564 
1565 	/* Now insert the new_inp into the TCP connected hash */
1566 	head = &sctppcbinfo.sctp_tcpephash[SCTP_PCBHASH_ALLADDR((lport + rport),
1567 	    sctppcbinfo.hashtcpmark)];
1568 
1569 	LIST_INSERT_HEAD(head, new_inp, sctp_hash);
1570 
1571 	/* Now move the tcb into the endpoint list */
1572 	LIST_INSERT_HEAD(&new_inp->sctp_asoc_list, stcb, sctp_tcblist);
1573 	/*
1574 	 * Question, do we even need to worry about the ep-hash since
1575 	 * we only have one connection? Probably not :> so lets
1576 	 * get rid of it and not suck up any kernel memory in that.
1577 	 */
1578 	SCTP_INP_INFO_WUNLOCK();
1579 	stcb->sctp_socket = new_inp->sctp_socket;
1580 	stcb->sctp_ep = new_inp;
1581 	if (new_inp->sctp_tcbhash != NULL) {
1582 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_hash,
1583 			      new_inp->sctp_tcbhash);
1584 		new_inp->sctp_tcbhash = NULL;
1585 	}
1586 	if ((new_inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) {
1587 		/* Subset bound, so copy in the laddr list from the old_inp */
1588 		LIST_FOREACH(oladdr, &old_inp->sctp_addr_list, sctp_nxt_addr) {
1589 			laddr = (struct sctp_laddr *)SCTP_ZONE_GET(
1590 			    sctppcbinfo.ipi_zone_laddr);
1591 			if (laddr == NULL) {
1592 				/*
1593 				 * Gak, what can we do? This assoc is really
1594 				 * HOSED. We probably should send an abort
1595 				 * here.
1596 				 */
1597 #ifdef SCTP_DEBUG
1598 				if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1599 					printf("Association hosed in TCP model, out of laddr memory\n");
1600 				}
1601 #endif /* SCTP_DEBUG */
1602 				continue;
1603 			}
1604 			sctppcbinfo.ipi_count_laddr++;
1605 			sctppcbinfo.ipi_gencnt_laddr++;
1606 			memset(laddr, 0, sizeof(*laddr));
1607 			laddr->ifa = oladdr->ifa;
1608 			LIST_INSERT_HEAD(&new_inp->sctp_addr_list, laddr,
1609 			    sctp_nxt_addr);
1610 			new_inp->laddr_count++;
1611 		}
1612 	}
1613 	SCTP_INP_WUNLOCK(new_inp);
1614 	SCTP_INP_WUNLOCK(old_inp);
1615 }
1616 
1617 static int
1618 sctp_isport_inuse(struct sctp_inpcb *inp, uint16_t lport)
1619 {
1620 	struct sctppcbhead *head;
1621 	struct sctp_inpcb *t_inp;
1622 
1623 	head = &sctppcbinfo.sctp_ephash[SCTP_PCBHASH_ALLADDR(lport,
1624 	    sctppcbinfo.hashmark)];
1625 	LIST_FOREACH(t_inp, head, sctp_hash) {
1626 		if (t_inp->sctp_lport != lport) {
1627 			continue;
1628 		}
1629 		/* This one is in use. */
1630 		/* check the v6/v4 binding issue */
1631 		if ((t_inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
1632 #if defined(__FreeBSD__)
1633 		    (((struct inpcb *)t_inp)->inp_flags & IN6P_IPV6_V6ONLY)
1634 #else
1635 #if defined(__OpenBSD__)
1636 		    (0)	/* For open bsd we do dual bind only */
1637 #else
1638 		    (((struct in6pcb *)t_inp)->in6p_flags & IN6P_IPV6_V6ONLY)
1639 #endif
1640 #endif
1641 			) {
1642 			if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
1643 				/* collision in V6 space */
1644 				return (1);
1645 			} else {
1646 				/* inp is BOUND_V4 no conflict */
1647 				continue;
1648 			}
1649 		} else if (t_inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
1650 			/* t_inp is bound v4 and v6, conflict always */
1651 			return (1);
1652 		} else {
1653 			/* t_inp is bound only V4 */
1654 			if ((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) &&
1655 #if defined(__FreeBSD__)
1656 			    (((struct inpcb *)inp)->inp_flags & IN6P_IPV6_V6ONLY)
1657 #else
1658 #if defined(__OpenBSD__)
1659 			    (0)	/* For open bsd we do dual bind only */
1660 #else
1661 			    (((struct in6pcb *)inp)->in6p_flags & IN6P_IPV6_V6ONLY)
1662 #endif
1663 #endif
1664 				) {
1665 				/* no conflict */
1666 				continue;
1667 			}
1668 			/* else fall through to conflict */
1669 		}
1670 		return (1);
1671 	}
1672 	return (0);
1673 }
1674 
1675 #if !(defined(__FreeBSD__) || defined(__APPLE__))
1676 /*
1677  * Don't know why, but without this there is an unknown reference when
1678  * compiling NetBSD... hmm
1679  */
1680 extern void in6_sin6_2_sin (struct sockaddr_in *, struct sockaddr_in6 *sin6);
1681 #endif
1682 
1683 
1684 int
1685 sctp_inpcb_bind(struct socket *so, struct sockaddr *addr, struct lwp *l)
1686 {
1687 	/* bind a ep to a socket address */
1688 	struct sctppcbhead *head;
1689 	struct sctp_inpcb *inp, *inp_tmp;
1690 	int bindall;
1691 	uint16_t lport;
1692 	int error;
1693 
1694 	lport = 0;
1695 	error = 0;
1696 	bindall = 1;
1697 	inp = (struct sctp_inpcb *)so->so_pcb;
1698 #ifdef SCTP_DEBUG
1699 	if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1700 		if (addr) {
1701 			printf("Bind called port:%d\n",
1702 			       ntohs(((struct sockaddr_in *)addr)->sin_port));
1703 			printf("Addr :");
1704 			sctp_print_address(addr);
1705 		}
1706 	}
1707 #endif /* SCTP_DEBUG */
1708 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) == 0) {
1709 		/* already did a bind, subsequent binds NOT allowed ! */
1710 		return (EINVAL);
1711 	}
1712 
1713 	if (addr != NULL) {
1714 		if (addr->sa_family == AF_INET) {
1715 			struct sockaddr_in *sin;
1716 
1717 			/* IPV6_V6ONLY socket? */
1718 			if (((struct in6pcb *)inp)->in6p_flags & IN6P_IPV6_V6ONLY) {
1719 				return (EINVAL);
1720 			}
1721 
1722 			if (addr->sa_len != sizeof(*sin))
1723 				return (EINVAL);
1724 
1725 			sin = (struct sockaddr_in *)addr;
1726 			lport = sin->sin_port;
1727 
1728 			if (sin->sin_addr.s_addr != INADDR_ANY) {
1729 				bindall = 0;
1730 			}
1731 		} else if (addr->sa_family == AF_INET6) {
1732 			/* Only for pure IPv6 Address. (No IPv4 Mapped!) */
1733 			struct sockaddr_in6 *sin6;
1734 
1735 			sin6 = (struct sockaddr_in6 *)addr;
1736 
1737 			if (addr->sa_len != sizeof(*sin6))
1738 				return (EINVAL);
1739 
1740 			lport = sin6->sin6_port;
1741 			if (!IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
1742 				bindall = 0;
1743 				/* KAME hack: embed scopeid */
1744 				error = sa6_embedscope(sin6, ip6_use_defzone);
1745 				if (error != 0)
1746 					return (error);
1747 			}
1748 #ifndef SCOPEDROUTING
1749 			/* this must be cleared for ifa_ifwithaddr() */
1750 			sin6->sin6_scope_id = 0;
1751 #endif /* SCOPEDROUTING */
1752 		} else {
1753 			return (EAFNOSUPPORT);
1754 		}
1755 	}
1756 	SCTP_INP_INFO_WLOCK();
1757 #ifdef SCTP_DEBUG
1758 	if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1759 		printf("sctp_inpcb_bind: after SCTP_INP_INFO_WLOCK\n");
1760 	}
1761 #endif /* SCTP_DEBUG */
1762 	SCTP_INP_WLOCK(inp);
1763 	/* increase our count due to the unlock we do */
1764 	SCTP_INP_INCR_REF(inp);
1765 	if (lport) {
1766 		enum kauth_network_req req;
1767 		/*
1768 		 * Did the caller specify a port? if so we must see if a
1769 		 * ep already has this one bound.
1770 		 */
1771 		if (ntohs(lport) < IPPORT_RESERVED)
1772 			req = KAUTH_REQ_NETWORK_BIND_PRIVPORT;
1773 		else
1774 			req = KAUTH_REQ_NETWORK_BIND_PORT;
1775 
1776 		error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_BIND,
1777 		    req, so, addr, NULL);
1778 		if (error) {
1779 			SCTP_INP_DECR_REF(inp);
1780 			SCTP_INP_WUNLOCK(inp);
1781 			SCTP_INP_INFO_WUNLOCK();
1782 			return (EACCES);
1783 		}
1784 		SCTP_INP_WUNLOCK(inp);
1785 		inp_tmp = sctp_pcb_findep(addr, 0, 1);
1786 		if (inp_tmp != NULL) {
1787 			/* lock guy returned and lower count
1788 			 * note that we are not bound so inp_tmp
1789 			 * should NEVER be inp. And it is this
1790 			 * inp (inp_tmp) that gets the reference
1791 			 * bump, so we must lower it.
1792 			 */
1793 			SCTP_INP_WLOCK(inp_tmp);
1794 			SCTP_INP_DECR_REF(inp_tmp);
1795 			SCTP_INP_WUNLOCK(inp_tmp);
1796 
1797 			/* unlock info */
1798 			SCTP_INP_INFO_WUNLOCK();
1799 			return (EADDRNOTAVAIL);
1800 		}
1801 		SCTP_INP_WLOCK(inp);
1802 		if (bindall) {
1803 			/* verify that no lport is not used by a singleton */
1804 			if (sctp_isport_inuse(inp, lport)) {
1805 				/* Sorry someone already has this one bound */
1806 				SCTP_INP_DECR_REF(inp);
1807 				SCTP_INP_WUNLOCK(inp);
1808 				SCTP_INP_INFO_WUNLOCK();
1809 				return (EADDRNOTAVAIL);
1810 			}
1811 		}
1812 	} else {
1813 		/*
1814 		 * get any port but lets make sure no one has any address
1815 		 * with this port bound
1816 		 */
1817 
1818 		/*
1819 		 * setup the inp to the top (I could use the union but this
1820 		 * is just as easy
1821 		 */
1822 		uint32_t port_guess;
1823 		uint16_t port_attempt;
1824 		int not_done=1;
1825 
1826 		while (not_done) {
1827 			port_guess = sctp_select_initial_TSN(&inp->sctp_ep);
1828 			port_attempt = (port_guess &  0x0000ffff);
1829 			if (port_attempt == 0) {
1830 				goto next_half;
1831 			}
1832 			if (port_attempt < IPPORT_RESERVED) {
1833 				port_attempt += IPPORT_RESERVED;
1834 			}
1835 
1836 			if (sctp_isport_inuse(inp, htons(port_attempt)) == 0) {
1837 				/* got a port we can use */
1838 				not_done = 0;
1839 				continue;
1840 			}
1841 			/* try upper half */
1842 		next_half:
1843 			port_attempt = ((port_guess >> 16) &  0x0000ffff);
1844 			if (port_attempt == 0) {
1845 				goto last_try;
1846 			}
1847 			if (port_attempt < IPPORT_RESERVED) {
1848 				port_attempt += IPPORT_RESERVED;
1849 			}
1850 			if (sctp_isport_inuse(inp, htons(port_attempt)) == 0) {
1851 				/* got a port we can use */
1852 				not_done = 0;
1853 				continue;
1854 			}
1855 			/* try two half's added together */
1856 		last_try:
1857 			port_attempt = (((port_guess >> 16) &  0x0000ffff) + (port_guess & 0x0000ffff));
1858 			if (port_attempt == 0) {
1859 				/* get a new random number */
1860 				continue;
1861 			}
1862 			if (port_attempt < IPPORT_RESERVED) {
1863 				port_attempt += IPPORT_RESERVED;
1864 			}
1865 			if (sctp_isport_inuse(inp, htons(port_attempt)) == 0) {
1866 				/* got a port we can use */
1867 				not_done = 0;
1868 				continue;
1869 			}
1870 		}
1871 		/* we don't get out of the loop until we have a port */
1872 		lport = htons(port_attempt);
1873 	}
1874 	SCTP_INP_DECR_REF(inp);
1875 	if (inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
1876 		/* this really should not happen. The guy
1877 		 * did a non-blocking bind and then did a close
1878 		 * at the same time.
1879 		 */
1880 		SCTP_INP_WUNLOCK(inp);
1881 		SCTP_INP_INFO_WUNLOCK();
1882 		return (EINVAL);
1883 	}
1884 	/* ok we look clear to give out this port, so lets setup the binding */
1885 	if (bindall) {
1886 		/* binding to all addresses, so just set in the proper flags */
1887 		inp->sctp_flags |= (SCTP_PCB_FLAGS_BOUNDALL |
1888 		    SCTP_PCB_FLAGS_DO_ASCONF);
1889 		/* set the automatic addr changes from kernel flag */
1890 		if (sctp_auto_asconf == 0) {
1891 			inp->sctp_flags &= ~SCTP_PCB_FLAGS_AUTO_ASCONF;
1892 		} else {
1893 			inp->sctp_flags |= SCTP_PCB_FLAGS_AUTO_ASCONF;
1894 		}
1895 	} else {
1896 		/*
1897 		 * bind specific, make sure flags is off and add a new address
1898 		 * structure to the sctp_addr_list inside the ep structure.
1899 		 *
1900 		 * We will need to allocate one and insert it at the head.
1901 		 * The socketopt call can just insert new addresses in there
1902 		 * as well. It will also have to do the embed scope kame hack
1903 		 * too (before adding).
1904 		 */
1905 		struct ifaddr *ifa;
1906 		struct sockaddr_storage store_sa;
1907 
1908 		memset(&store_sa, 0, sizeof(store_sa));
1909 		if (addr->sa_family == AF_INET) {
1910 			struct sockaddr_in *sin;
1911 
1912 			sin = (struct sockaddr_in *)&store_sa;
1913 			memcpy(sin, addr, sizeof(struct sockaddr_in));
1914 			sin->sin_port = 0;
1915 		} else if (addr->sa_family == AF_INET6) {
1916 			struct sockaddr_in6 *sin6;
1917 
1918 			sin6 = (struct sockaddr_in6 *)&store_sa;
1919 			memcpy(sin6, addr, sizeof(struct sockaddr_in6));
1920 			sin6->sin6_port = 0;
1921 		}
1922 		/*
1923 		 * first find the interface with the bound address
1924 		 * need to zero out the port to find the address! yuck!
1925 		 * can't do this earlier since need port for sctp_pcb_findep()
1926 		 */
1927 		ifa = sctp_find_ifa_by_addr((struct sockaddr *)&store_sa);
1928 		if (ifa == NULL) {
1929 			/* Can't find an interface with that address */
1930 			SCTP_INP_WUNLOCK(inp);
1931 			SCTP_INP_INFO_WUNLOCK();
1932 			return (EADDRNOTAVAIL);
1933 		}
1934 		if (addr->sa_family == AF_INET6) {
1935 			struct in6_ifaddr *ifa6;
1936 			ifa6 = (struct in6_ifaddr *)ifa;
1937 			/*
1938 			 * allow binding of deprecated addresses as per
1939 			 * RFC 2462 and ipng discussion
1940 			 */
1941 			if (ifa6->ia6_flags & (IN6_IFF_DETACHED |
1942 			    IN6_IFF_ANYCAST |
1943 			    IN6_IFF_NOTREADY)) {
1944 				/* Can't bind a non-existent addr. */
1945 				SCTP_INP_WUNLOCK(inp);
1946 				SCTP_INP_INFO_WUNLOCK();
1947 				return (EINVAL);
1948 			}
1949 		}
1950 		/* we're not bound all */
1951 		inp->sctp_flags &= ~SCTP_PCB_FLAGS_BOUNDALL;
1952 #if 0 /* use sysctl now */
1953 		/* don't allow automatic addr changes from kernel */
1954 		inp->sctp_flags &= ~SCTP_PCB_FLAGS_AUTO_ASCONF;
1955 #endif
1956 		/* set the automatic addr changes from kernel flag */
1957 		if (sctp_auto_asconf == 0) {
1958 			inp->sctp_flags &= ~SCTP_PCB_FLAGS_AUTO_ASCONF;
1959 		} else {
1960 			inp->sctp_flags |= SCTP_PCB_FLAGS_AUTO_ASCONF;
1961 		}
1962 		/* allow bindx() to send ASCONF's for binding changes */
1963 		inp->sctp_flags |= SCTP_PCB_FLAGS_DO_ASCONF;
1964 		/* add this address to the endpoint list */
1965 		error = sctp_insert_laddr(&inp->sctp_addr_list, ifa);
1966 		if (error != 0) {
1967 			SCTP_INP_WUNLOCK(inp);
1968 			SCTP_INP_INFO_WUNLOCK();
1969 			return (error);
1970 		}
1971 		inp->laddr_count++;
1972 	}
1973 	/* find the bucket */
1974 	head = &sctppcbinfo.sctp_ephash[SCTP_PCBHASH_ALLADDR(lport,
1975 	    sctppcbinfo.hashmark)];
1976 	/* put it in the bucket */
1977 	LIST_INSERT_HEAD(head, inp, sctp_hash);
1978 #ifdef SCTP_DEBUG
1979 	if (sctp_debug_on & SCTP_DEBUG_PCB1) {
1980 		printf("Main hash to bind at head:%p, bound port:%d\n", head, ntohs(lport));
1981 	}
1982 #endif
1983 	/* set in the port */
1984 	inp->sctp_lport = lport;
1985 
1986 	/* turn off just the unbound flag */
1987 	inp->sctp_flags &= ~SCTP_PCB_FLAGS_UNBOUND;
1988 	SCTP_INP_WUNLOCK(inp);
1989 	SCTP_INP_INFO_WUNLOCK();
1990 	return (0);
1991 }
1992 
1993 
1994 static void
1995 sctp_iterator_inp_being_freed(struct sctp_inpcb *inp, struct sctp_inpcb *inp_next)
1996 {
1997 	struct sctp_iterator *it;
1998 	/* We enter with the only the ITERATOR_LOCK in place and
1999 	 * A write lock on the inp_info stuff.
2000 	 */
2001 
2002 	/* Go through all iterators, we must do this since
2003 	 * it is possible that some iterator does NOT have
2004 	 * the lock, but is waiting for it. And the one that
2005 	 * had the lock has either moved in the last iteration
2006 	 * or we just cleared it above. We need to find all
2007 	 * of those guys. The list of iterators should never
2008 	 * be very big though.
2009 	 */
2010  	LIST_FOREACH(it, &sctppcbinfo.iteratorhead, sctp_nxt_itr) {
2011 		if (it == inp->inp_starting_point_for_iterator)
2012 			/* skip this guy, he's special */
2013 			continue;
2014  		if (it->inp == inp) {
2015 			/* This is tricky and we DON'T lock the iterator.
2016 			 * Reason is he's running but waiting for me since
2017 			 * inp->inp_starting_point_for_iterator has the lock
2018 			 * on me (the guy above we skipped). This tells us
2019 			 * its is not running but waiting for inp->inp_starting_point_for_iterator
2020 			 * to be released by the guy that does have our INP in a lock.
2021 			 */
2022 			if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) {
2023 				it->inp = NULL;
2024 				it->stcb = NULL;
2025 			} else {
2026 				/* set him up to do the next guy not me */
2027 				it->inp = inp_next;
2028 				it->stcb = NULL;
2029 			}
2030 		}
2031 	}
2032 	it = inp->inp_starting_point_for_iterator;
2033 	if (it) {
2034 		if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) {
2035 			it->inp = NULL;
2036 		} else {
2037 			it->inp = inp_next;
2038 		}
2039 		it->stcb = NULL;
2040 	}
2041 }
2042 
2043 /* release sctp_inpcb unbind the port */
2044 void
2045 sctp_inpcb_free(struct sctp_inpcb *inp, int immediate)
2046 {
2047 	/*
2048 	 * Here we free a endpoint. We must find it (if it is in the Hash
2049 	 * table) and remove it from there. Then we must also find it in
2050 	 * the overall list and remove it from there. After all removals are
2051 	 * complete then any timer has to be stopped. Then start the actual
2052 	 * freeing.
2053 	 * a) Any local lists.
2054 	 * b) Any associations.
2055 	 * c) The hash of all associations.
2056 	 * d) finally the ep itself.
2057 	 */
2058 	struct sctp_inpcb *inp_save;
2059 	struct sctp_tcb *asoc, *nasoc;
2060 	struct sctp_laddr *laddr, *nladdr;
2061 	struct inpcb *ip_pcb;
2062 	struct socket *so;
2063 	struct sctp_socket_q_list *sq;
2064 	int s, cnt;
2065 
2066 	s = splsoftnet();
2067 	SCTP_ASOC_CREATE_LOCK(inp);
2068 	SCTP_INP_WLOCK(inp);
2069 
2070 	if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) {
2071 		/* been here before */
2072 		splx(s);
2073 		printf("Endpoint was all gone (dup free)?\n");
2074 		SCTP_INP_WUNLOCK(inp);
2075 		SCTP_ASOC_CREATE_UNLOCK(inp);
2076 		return;
2077 	}
2078 	sctp_timer_stop(SCTP_TIMER_TYPE_NEWCOOKIE, inp, NULL, NULL);
2079 
2080 	if (inp->control) {
2081 		sctp_m_freem(inp->control);
2082 		inp->control = NULL;
2083 	}
2084 	if (inp->pkt) {
2085 		sctp_m_freem(inp->pkt);
2086 		inp->pkt = NULL;
2087 	}
2088 	so  = inp->sctp_socket;
2089 	ip_pcb = &inp->ip_inp.inp; /* we could just cast the main
2090 				   * pointer here but I will
2091 				   * be nice :> (i.e. ip_pcb = ep;)
2092 				   */
2093 
2094 	if (immediate == 0) {
2095 		int cnt_in_sd;
2096 		cnt_in_sd = 0;
2097 		for ((asoc = LIST_FIRST(&inp->sctp_asoc_list)); asoc != NULL;
2098 		     asoc = nasoc) {
2099 			nasoc = LIST_NEXT(asoc, sctp_tcblist);
2100 			if ((SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_COOKIE_WAIT) ||
2101 			    (SCTP_GET_STATE(&asoc->asoc) == SCTP_STATE_COOKIE_ECHOED)) {
2102 				/* Just abandon things in the front states */
2103 				SCTP_TCB_LOCK(asoc);
2104 				SCTP_INP_WUNLOCK(inp);
2105 				sctp_free_assoc(inp, asoc);
2106 				SCTP_INP_WLOCK(inp);
2107 				continue;
2108 			} else {
2109 				asoc->asoc.state |= SCTP_STATE_CLOSED_SOCKET;
2110 			}
2111 			if ((asoc->asoc.size_on_delivery_queue  > 0) ||
2112 			    (asoc->asoc.size_on_reasm_queue > 0) ||
2113 			    (asoc->asoc.size_on_all_streams > 0) ||
2114 			    (so && (so->so_rcv.sb_cc > 0))
2115 				) {
2116 				/* Left with Data unread */
2117 				struct mbuf *op_err;
2118 				MGET(op_err, M_DONTWAIT, MT_DATA);
2119 				if (op_err) {
2120 					/* Fill in the user initiated abort */
2121 					struct sctp_paramhdr *ph;
2122 					op_err->m_len =
2123 					    sizeof(struct sctp_paramhdr);
2124 					ph = mtod(op_err,
2125 					    struct sctp_paramhdr *);
2126 					ph->param_type = htons(
2127 					    SCTP_CAUSE_USER_INITIATED_ABT);
2128 					ph->param_length = htons(op_err->m_len);
2129 				}
2130 				SCTP_TCB_LOCK(asoc);
2131 				sctp_send_abort_tcb(asoc, op_err);
2132 
2133 				SCTP_INP_WUNLOCK(inp);
2134 				sctp_free_assoc(inp, asoc);
2135 				SCTP_INP_WLOCK(inp);
2136 				continue;
2137 			} else if (TAILQ_EMPTY(&asoc->asoc.send_queue) &&
2138 			    TAILQ_EMPTY(&asoc->asoc.sent_queue)) {
2139 				if ((SCTP_GET_STATE(&asoc->asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
2140 				    (SCTP_GET_STATE(&asoc->asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
2141 					/* there is nothing queued to send, so I send shutdown */
2142 					SCTP_TCB_LOCK(asoc);
2143 					sctp_send_shutdown(asoc, asoc->asoc.primary_destination);
2144 					asoc->asoc.state = SCTP_STATE_SHUTDOWN_SENT;
2145 					sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, asoc->sctp_ep, asoc,
2146 							 asoc->asoc.primary_destination);
2147 					sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, asoc->sctp_ep, asoc,
2148 							 asoc->asoc.primary_destination);
2149 					sctp_chunk_output(inp, asoc, 1);
2150 					SCTP_TCB_UNLOCK(asoc);
2151 				}
2152 			} else {
2153 				/* mark into shutdown pending */
2154 				asoc->asoc.state |= SCTP_STATE_SHUTDOWN_PENDING;
2155 			}
2156 			cnt_in_sd++;
2157 		}
2158 		/* now is there some left in our SHUTDOWN state? */
2159 		if (cnt_in_sd) {
2160 			inp->sctp_flags |= SCTP_PCB_FLAGS_SOCKET_GONE;
2161 			splx(s);
2162 			SCTP_INP_WUNLOCK(inp);
2163 			SCTP_ASOC_CREATE_UNLOCK(inp);
2164 			return;
2165 		}
2166 	}
2167 #if defined(__FreeBSD__) && __FreeBSD_version >= 503000
2168 	if (inp->refcount) {
2169 		sctp_timer_start(SCTP_TIMER_TYPE_INPKILL, inp, NULL, NULL);
2170 		SCTP_INP_WUNLOCK(inp);
2171 		SCTP_ASOC_CREATE_UNLOCK(inp);
2172 		return;
2173 	}
2174 #endif
2175 	inp->sctp_flags |= SCTP_PCB_FLAGS_SOCKET_ALLGONE;
2176 
2177 	rtcache_validate(&ip_pcb->inp_route);
2178 
2179 	callout_stop(&inp->sctp_ep.signature_change.timer);
2180 	callout_destroy(&inp->sctp_ep.signature_change.timer);
2181 
2182 	if (so) {
2183 	/* First take care of socket level things */
2184 #ifdef IPSEC
2185 		ipsec4_delete_pcbpolicy(ip_pcb);
2186 #endif /*IPSEC*/
2187 		so->so_pcb = 0;
2188 		sofree(so);
2189 	}
2190 
2191 	if (ip_pcb->inp_options) {
2192 		(void)m_free(ip_pcb->inp_options);
2193 		ip_pcb->inp_options = 0;
2194 	}
2195 	rtcache_free(&ip_pcb->inp_route);
2196 	if (ip_pcb->inp_moptions) {
2197 		ip_freemoptions(ip_pcb->inp_moptions);
2198 		ip_pcb->inp_moptions = 0;
2199 	}
2200 #if !(defined(__FreeBSD__) || defined(__APPLE__))
2201 	inp->inp_vflag = 0;
2202 #else
2203 	ip_pcb->inp_vflag = 0;
2204 #endif
2205 
2206 	/* Now the sctp_pcb things */
2207 	/*
2208 	 * free each asoc if it is not already closed/free. we can't use
2209 	 * the macro here since le_next will get freed as part of the
2210 	 * sctp_free_assoc() call.
2211 	 */
2212 	cnt = 0;
2213 	for ((asoc = LIST_FIRST(&inp->sctp_asoc_list)); asoc != NULL;
2214 	     asoc = nasoc) {
2215 		nasoc = LIST_NEXT(asoc, sctp_tcblist);
2216 		SCTP_TCB_LOCK(asoc);
2217 		if (SCTP_GET_STATE(&asoc->asoc) != SCTP_STATE_COOKIE_WAIT) {
2218 			struct mbuf *op_err;
2219 			MGET(op_err, M_DONTWAIT, MT_DATA);
2220 			if (op_err) {
2221 				/* Fill in the user initiated abort */
2222 				struct sctp_paramhdr *ph;
2223 				op_err->m_len = sizeof(struct sctp_paramhdr);
2224 				ph = mtod(op_err, struct sctp_paramhdr *);
2225 				ph->param_type = htons(
2226 				    SCTP_CAUSE_USER_INITIATED_ABT);
2227 				ph->param_length = htons(op_err->m_len);
2228 			}
2229 			sctp_send_abort_tcb(asoc, op_err);
2230 		}
2231 		cnt++;
2232 		/*
2233 		 * sctp_free_assoc() will call sctp_inpcb_free(),
2234 		 * if SCTP_PCB_FLAGS_SOCKET_GONE set.
2235 		 * So, we clear it before sctp_free_assoc() making sure
2236 		 * no double sctp_inpcb_free().
2237 		 */
2238 		inp->sctp_flags &= ~SCTP_PCB_FLAGS_SOCKET_GONE;
2239 		SCTP_INP_WUNLOCK(inp);
2240 		sctp_free_assoc(inp, asoc);
2241 		SCTP_INP_WLOCK(inp);
2242 	}
2243 	while ((sq = TAILQ_FIRST(&inp->sctp_queue_list)) != NULL) {
2244 		TAILQ_REMOVE(&inp->sctp_queue_list, sq, next_sq);
2245 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_sockq, sq);
2246 		sctppcbinfo.ipi_count_sockq--;
2247 		sctppcbinfo.ipi_gencnt_sockq++;
2248 	}
2249 	inp->sctp_socket = 0;
2250 	/* Now first we remove ourselves from the overall list of all EP's */
2251 
2252 	/* Unlock inp first, need correct order */
2253 	SCTP_INP_WUNLOCK(inp);
2254 	/* now iterator lock */
2255 	SCTP_ITERATOR_LOCK();
2256 	/* now info lock */
2257 	SCTP_INP_INFO_WLOCK();
2258 	/* now reget the inp lock */
2259 	SCTP_INP_WLOCK(inp);
2260 
2261 	inp_save = LIST_NEXT(inp, sctp_list);
2262 	LIST_REMOVE(inp, sctp_list);
2263 	/*
2264 	 * Now the question comes as to if this EP was ever bound at all.
2265 	 * If it was, then we must pull it out of the EP hash list.
2266 	 */
2267 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) !=
2268 	    SCTP_PCB_FLAGS_UNBOUND) {
2269 		/*
2270 		 * ok, this guy has been bound. It's port is somewhere
2271 		 * in the sctppcbinfo hash table. Remove it!
2272 		 */
2273 		LIST_REMOVE(inp, sctp_hash);
2274 	}
2275         /* fix any iterators only after out of the list */
2276 	sctp_iterator_inp_being_freed(inp, inp_save);
2277 	SCTP_ITERATOR_UNLOCK();
2278 	/*
2279 	 * if we have an address list the following will free the list of
2280 	 * ifaddr's that are set into this ep. Again macro limitations here,
2281 	 * since the LIST_FOREACH could be a bad idea.
2282 	 */
2283 	for ((laddr = LIST_FIRST(&inp->sctp_addr_list)); laddr != NULL;
2284 	     laddr = nladdr) {
2285 		nladdr = LIST_NEXT(laddr, sctp_nxt_addr);
2286 		LIST_REMOVE(laddr, sctp_nxt_addr);
2287 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_laddr, laddr);
2288 		sctppcbinfo.ipi_gencnt_laddr++;
2289 		sctppcbinfo.ipi_count_laddr--;
2290 	}
2291 
2292 	/* Now lets see about freeing the EP hash table. */
2293 	if (inp->sctp_tcbhash != NULL) {
2294 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_hash, inp->sctp_tcbhash);
2295 		inp->sctp_tcbhash = NULL;
2296 	}
2297 	SCTP_INP_WUNLOCK(inp);
2298 	SCTP_ASOC_CREATE_UNLOCK(inp);
2299 	SCTP_INP_LOCK_DESTROY(inp);
2300 	SCTP_ASOC_CREATE_LOCK_DESTROY(inp);
2301 
2302 	/* Now we must put the ep memory back into the zone pool */
2303 	SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_ep, inp);
2304 	sctppcbinfo.ipi_count_ep--;
2305 
2306 	SCTP_INP_INFO_WUNLOCK();
2307 	splx(s);
2308 }
2309 
2310 
2311 struct sctp_nets *
2312 sctp_findnet(struct sctp_tcb *stcb, struct sockaddr *addr)
2313 {
2314 	struct sctp_nets *net;
2315 
2316 	/* use the peer's/remote port for lookup if unspecified */
2317 #if 0 /* why do we need to check the port for a nets list on an assoc? */
2318 	if (stcb->rport != sin->sin_port) {
2319 		/* we cheat and just a sin for this test */
2320 		return (NULL);
2321 	}
2322 #endif
2323 	/* locate the address */
2324 	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
2325 		if (sctp_cmpaddr(addr, rtcache_getdst(&net->ro)))
2326 			return (net);
2327 	}
2328 	return (NULL);
2329 }
2330 
2331 
2332 /*
2333  * add's a remote endpoint address, done with the INIT/INIT-ACK
2334  * as well as when a ASCONF arrives that adds it. It will also
2335  * initialize all the cwnd stats of stuff.
2336  */
2337 int
2338 sctp_is_address_on_local_host(struct sockaddr *addr)
2339 {
2340 	struct ifnet *ifn;
2341 	struct ifaddr *ifa;
2342 	TAILQ_FOREACH(ifn, &ifnet_list, if_list) {
2343 		TAILQ_FOREACH(ifa, &ifn->if_addrlist, ifa_list) {
2344 			if (addr->sa_family == ifa->ifa_addr->sa_family) {
2345 				/* same family */
2346 				if (addr->sa_family == AF_INET) {
2347 					struct sockaddr_in *sin, *sin_c;
2348 					sin = (struct sockaddr_in *)addr;
2349 					sin_c = (struct sockaddr_in *)
2350 					    ifa->ifa_addr;
2351 					if (sin->sin_addr.s_addr ==
2352 					    sin_c->sin_addr.s_addr) {
2353 						/* we are on the same machine */
2354 						return (1);
2355 					}
2356 				} else if (addr->sa_family == AF_INET6) {
2357 					struct sockaddr_in6 *sin6, *sin_c6;
2358 					sin6 = (struct sockaddr_in6 *)addr;
2359 					sin_c6 = (struct sockaddr_in6 *)
2360 					    ifa->ifa_addr;
2361 					if (SCTP6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
2362 					    &sin_c6->sin6_addr)) {
2363 						/* we are on the same machine */
2364 						return (1);
2365 					}
2366 				}
2367 			}
2368 		}
2369 	}
2370 	return (0);
2371 }
2372 
2373 int
2374 sctp_add_remote_addr(struct sctp_tcb *stcb, struct sockaddr *newaddr,
2375     int set_scope, int from)
2376 {
2377 	/*
2378 	 * The following is redundant to the same lines in the
2379 	 * sctp_aloc_assoc() but is needed since other's call the add
2380 	 * address function
2381 	 */
2382 	struct sctp_nets *net, *netfirst;
2383 	struct rtentry *rt, *netfirst_rt;
2384 	int addr_inscope;
2385 
2386 #ifdef SCTP_DEBUG
2387 	if (sctp_debug_on & SCTP_DEBUG_PCB1) {
2388 		printf("Adding an address (from:%d) to the peer: ", from);
2389 		sctp_print_address(newaddr);
2390 	}
2391 #endif
2392 	netfirst = sctp_findnet(stcb, newaddr);
2393 	if (netfirst) {
2394 		/*
2395 		 * Lie and return ok, we don't want to make the association
2396 		 * go away for this behavior. It will happen in the TCP model
2397 		 * in a connected socket. It does not reach the hash table
2398 		 * until after the association is built so it can't be found.
2399 		 * Mark as reachable, since the initial creation will have
2400 		 * been cleared and the NOT_IN_ASSOC flag will have been
2401 		 * added... and we don't want to end up removing it back out.
2402 		 */
2403 		if (netfirst->dest_state & SCTP_ADDR_UNCONFIRMED) {
2404 			netfirst->dest_state = (SCTP_ADDR_REACHABLE|
2405 			    SCTP_ADDR_UNCONFIRMED);
2406 		} else {
2407 			netfirst->dest_state = SCTP_ADDR_REACHABLE;
2408 		}
2409 
2410 		return (0);
2411 	}
2412 	addr_inscope = 1;
2413 	if (newaddr->sa_family == AF_INET) {
2414 		struct sockaddr_in *sin;
2415 		sin = (struct sockaddr_in *)newaddr;
2416 		if (sin->sin_addr.s_addr == 0) {
2417 			/* Invalid address */
2418 			return (-1);
2419 		}
2420 		/* zero out the bzero area */
2421 		memset(&sin->sin_zero, 0, sizeof(sin->sin_zero));
2422 
2423 		/* assure len is set */
2424 		sin->sin_len = sizeof(struct sockaddr_in);
2425 		if (set_scope) {
2426 #ifdef SCTP_DONT_DO_PRIVADDR_SCOPE
2427 			stcb->ipv4_local_scope = 1;
2428 #else
2429 			if (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) {
2430 				stcb->asoc.ipv4_local_scope = 1;
2431 			}
2432 #endif /* SCTP_DONT_DO_PRIVADDR_SCOPE */
2433 
2434 			if (sctp_is_address_on_local_host(newaddr)) {
2435 				stcb->asoc.loopback_scope = 1;
2436 				stcb->asoc.ipv4_local_scope = 1;
2437 				stcb->asoc.local_scope = 1;
2438 				stcb->asoc.site_scope = 1;
2439 			}
2440 		} else {
2441 			if (from == 8) {
2442 				/* From connectx */
2443 				if (sctp_is_address_on_local_host(newaddr)) {
2444 					stcb->asoc.loopback_scope = 1;
2445 					stcb->asoc.ipv4_local_scope = 1;
2446 					stcb->asoc.local_scope = 1;
2447 					stcb->asoc.site_scope = 1;
2448 				}
2449 			}
2450 			/* Validate the address is in scope */
2451 			if ((IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) &&
2452 			    (stcb->asoc.ipv4_local_scope == 0)) {
2453 				addr_inscope = 0;
2454 			}
2455 		}
2456 	} else if (newaddr->sa_family == AF_INET6) {
2457 		struct sockaddr_in6 *sin6;
2458 		sin6 = (struct sockaddr_in6 *)newaddr;
2459 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
2460 			/* Invalid address */
2461 			return (-1);
2462 		}
2463 		/* assure len is set */
2464 		sin6->sin6_len = sizeof(struct sockaddr_in6);
2465 		if (set_scope) {
2466 			if (sctp_is_address_on_local_host(newaddr)) {
2467 				stcb->asoc.loopback_scope = 1;
2468 				stcb->asoc.local_scope = 1;
2469 				stcb->asoc.ipv4_local_scope = 1;
2470 				stcb->asoc.site_scope = 1;
2471 			} else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
2472 				/*
2473 				 * If the new destination is a LINK_LOCAL
2474 				 * we must have common site scope. Don't set
2475 				 * the local scope since we may not share all
2476 				 * links, only loopback can do this.
2477  				 * Links on the local network would also
2478  				 * be on our private network for v4 too.
2479 				 */
2480  				stcb->asoc.ipv4_local_scope = 1;
2481 				stcb->asoc.site_scope = 1;
2482 			} else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr)) {
2483 				/*
2484 				 * If the new destination is SITE_LOCAL
2485 				 * then we must have site scope in common.
2486 				 */
2487 				stcb->asoc.site_scope = 1;
2488 			}
2489 		} else {
2490 			if (from == 8) {
2491 				/* From connectx */
2492 				if (sctp_is_address_on_local_host(newaddr)) {
2493 					stcb->asoc.loopback_scope = 1;
2494 					stcb->asoc.ipv4_local_scope = 1;
2495 					stcb->asoc.local_scope = 1;
2496 					stcb->asoc.site_scope = 1;
2497 				}
2498 			}
2499 			/* Validate the address is in scope */
2500 			if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr) &&
2501 			    (stcb->asoc.loopback_scope == 0)) {
2502 				addr_inscope = 0;
2503 			} else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr) &&
2504 				   (stcb->asoc.local_scope == 0)) {
2505 				addr_inscope = 0;
2506 			} else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr) &&
2507 				   (stcb->asoc.site_scope == 0)) {
2508 				addr_inscope = 0;
2509 			}
2510 		}
2511 	} else {
2512 		/* not supported family type */
2513 		return (-1);
2514 	}
2515 	net = (struct sctp_nets *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_net);
2516 	if (net == NULL) {
2517 		return (-1);
2518 	}
2519 	sctppcbinfo.ipi_count_raddr++;
2520 	sctppcbinfo.ipi_gencnt_raddr++;
2521 	memset(net, 0, sizeof(*net));
2522 	if (newaddr->sa_family == AF_INET) {
2523 		((struct sockaddr_in *)newaddr)->sin_port = stcb->rport;
2524 	} else if (newaddr->sa_family == AF_INET6) {
2525 		((struct sockaddr_in6 *)newaddr)->sin6_port = stcb->rport;
2526 	}
2527 	net->addr_is_local = sctp_is_address_on_local_host(newaddr);
2528 	net->failure_threshold = stcb->asoc.def_net_failure;
2529 	if (addr_inscope == 0) {
2530 #ifdef SCTP_DEBUG
2531 		if (sctp_debug_on & SCTP_DEBUG_PCB1) {
2532 			printf("Adding an address which is OUT OF SCOPE\n");
2533 		}
2534 #endif /* SCTP_DEBUG */
2535 		net->dest_state = (SCTP_ADDR_REACHABLE |
2536 		    SCTP_ADDR_OUT_OF_SCOPE);
2537 	} else {
2538 		if (from == 8)
2539 			/* 8 is passed by connect_x */
2540 			net->dest_state = SCTP_ADDR_REACHABLE;
2541 		else
2542 			net->dest_state = SCTP_ADDR_REACHABLE |
2543 			    SCTP_ADDR_UNCONFIRMED;
2544 	}
2545 	net->RTO = stcb->asoc.initial_rto;
2546 	stcb->asoc.numnets++;
2547 	net->ref_count = 1;
2548 
2549 	/* Init the timer structure */
2550 	callout_init(&net->rxt_timer.timer, 0);
2551 	callout_init(&net->pmtu_timer.timer, 0);
2552 
2553 	/* Now generate a route for this guy */
2554 	/* KAME hack: embed scope zone ID */
2555 	if (newaddr->sa_family == AF_INET6) {
2556 		struct sockaddr_in6 *sin6;
2557 		sin6 = (struct sockaddr_in6 *)newaddr;
2558 		if (sa6_embedscope(sin6, ip6_use_defzone) != 0)
2559 			return (-1);
2560 	}
2561 	rt = rtcache_lookup(&net->ro, newaddr);
2562 	if (rt) {
2563 		net->mtu = rt->rt_ifp->if_mtu;
2564 		if (from == 1) {
2565 			stcb->asoc.smallest_mtu = net->mtu;
2566 		}
2567 		/* start things off to match mtu of interface please. */
2568 		rt->rt_rmx.rmx_mtu = rt->rt_ifp->if_mtu;
2569 	} else {
2570 		net->mtu = stcb->asoc.smallest_mtu;
2571 	}
2572 #ifdef SCTP_DEBUG
2573 	printf("After lookup\n");
2574 #endif
2575 	if (stcb->asoc.smallest_mtu > net->mtu) {
2576 		stcb->asoc.smallest_mtu = net->mtu;
2577 	}
2578 	/* We take the max of the burst limit times a MTU or the INITIAL_CWND.
2579 	 * We then limit this to 4 MTU's of sending.
2580 	 */
2581  	net->cwnd = min((net->mtu * 4), max((stcb->asoc.max_burst * net->mtu), SCTP_INITIAL_CWND));
2582 
2583 	/* we always get at LEAST 2 MTU's */
2584 	if (net->cwnd < (2 * net->mtu)) {
2585 		net->cwnd = 2 * net->mtu;
2586 	}
2587 
2588 	net->ssthresh = stcb->asoc.peers_rwnd;
2589 
2590 	net->src_addr_selected = 0;
2591 	netfirst = TAILQ_FIRST(&stcb->asoc.nets);
2592 	if (rt == NULL) {
2593 		/* Since we have no route put it at the back */
2594 		TAILQ_INSERT_TAIL(&stcb->asoc.nets, net, sctp_next);
2595 	} else if (netfirst == NULL) {
2596 		/* We are the first one in the pool. */
2597 		TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
2598 	} else if ((netfirst_rt = rtcache_validate(&netfirst->ro)) == NULL) {
2599 		/*
2600 		 * First one has NO route. Place this one ahead of the
2601 		 * first one.
2602 		 */
2603 		TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
2604 	} else if (rt->rt_ifp != netfirst_rt->rt_ifp) {
2605 		/*
2606 		 * This one has a different interface than the one at the
2607 		 * top of the list. Place it ahead.
2608 		 */
2609 		TAILQ_INSERT_HEAD(&stcb->asoc.nets, net, sctp_next);
2610 	} else {
2611 		/*
2612 		 * Ok we have the same interface as the first one. Move
2613 		 * forward until we find either
2614 		 *   a) one with a NULL route... insert ahead of that
2615 		 *   b) one with a different ifp.. insert after that.
2616 		 *   c) end of the list.. insert at the tail.
2617 		 */
2618 		struct sctp_nets *netlook;
2619 		struct rtentry *netlook_rt;
2620 		do {
2621 			netlook = TAILQ_NEXT(netfirst, sctp_next);
2622 			if (netlook == NULL) {
2623 				/* End of the list */
2624 				TAILQ_INSERT_TAIL(&stcb->asoc.nets, net,
2625 				    sctp_next);
2626 				break;
2627 			} else if ((netlook_rt = rtcache_validate(&netlook->ro)) == NULL) {
2628 				/* next one has NO route */
2629 				TAILQ_INSERT_BEFORE(netfirst, net, sctp_next);
2630 				break;
2631 			} else if (netlook_rt->rt_ifp != rt->rt_ifp) {
2632 				TAILQ_INSERT_AFTER(&stcb->asoc.nets, netlook,
2633 				    net, sctp_next);
2634 				break;
2635 			}
2636 			/* Shift forward */
2637 			netfirst = netlook;
2638 		} while (netlook != NULL);
2639 	}
2640 	/* got to have a primary set */
2641 	if (stcb->asoc.primary_destination == 0) {
2642 		stcb->asoc.primary_destination = net;
2643 	} else if (!rtcache_validate(&stcb->asoc.primary_destination->ro)) {
2644 		/* No route to current primary adopt new primary */
2645 		stcb->asoc.primary_destination = net;
2646 	}
2647 	sctp_timer_start(SCTP_TIMER_TYPE_PATHMTURAISE, stcb->sctp_ep, stcb,
2648 	    net);
2649 
2650 	return (0);
2651 }
2652 
2653 
2654 /*
2655  * allocate an association and add it to the endpoint. The caller must
2656  * be careful to add all additional addresses once they are know right
2657  * away or else the assoc will be may experience a blackout scenario.
2658  */
2659 struct sctp_tcb *
2660 sctp_aloc_assoc(struct sctp_inpcb *inp, struct sockaddr *firstaddr,
2661     int for_a_init, int *error,  uint32_t override_tag)
2662 {
2663 	struct sctp_tcb *stcb;
2664 	struct sctp_association *asoc;
2665 	struct sctpasochead *head;
2666 	uint16_t rport;
2667 	int err;
2668 
2669 	/*
2670 	 * Assumption made here:
2671 	 *  Caller has done a sctp_findassociation_ep_addr(ep, addr's);
2672 	 *  to make sure the address does not exist already.
2673 	 */
2674 	if (sctppcbinfo.ipi_count_asoc >= SCTP_MAX_NUM_OF_ASOC) {
2675 		/* Hit max assoc, sorry no more */
2676 		*error = ENOBUFS;
2677 		return (NULL);
2678 	}
2679 	SCTP_INP_RLOCK(inp);
2680 	if (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) {
2681 		/*
2682 		 * If its in the TCP pool, its NOT allowed to create an
2683 		 * association. The parent listener needs to call
2684 		 * sctp_aloc_assoc.. or the one-2-many socket. If a
2685 		 * peeled off, or connected one does this.. its an error.
2686 		 */
2687 		SCTP_INP_RUNLOCK(inp);
2688 		*error = EINVAL;
2689 		return (NULL);
2690  	}
2691 
2692 #ifdef SCTP_DEBUG
2693 	if (sctp_debug_on & SCTP_DEBUG_PCB3) {
2694 		printf("Allocate an association for peer:");
2695 		if (firstaddr)
2696 			sctp_print_address(firstaddr);
2697 		else
2698 			printf("None\n");
2699 		printf("Port:%d\n",
2700 		       ntohs(((struct sockaddr_in *)firstaddr)->sin_port));
2701 	}
2702 #endif /* SCTP_DEBUG */
2703 	if (firstaddr->sa_family == AF_INET) {
2704 		struct sockaddr_in *sin;
2705 		sin = (struct sockaddr_in *)firstaddr;
2706 		if ((sin->sin_port == 0) || (sin->sin_addr.s_addr == 0)) {
2707 			/* Invalid address */
2708 #ifdef SCTP_DEBUG
2709 			if (sctp_debug_on & SCTP_DEBUG_PCB3) {
2710 				printf("peer address invalid\n");
2711 			}
2712 #endif
2713 			SCTP_INP_RUNLOCK(inp);
2714 			*error = EINVAL;
2715 			return (NULL);
2716 		}
2717 		rport = sin->sin_port;
2718 	} else if (firstaddr->sa_family == AF_INET6) {
2719 		struct sockaddr_in6 *sin6;
2720 		sin6 = (struct sockaddr_in6 *)firstaddr;
2721 		if ((sin6->sin6_port == 0) ||
2722 		    (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))) {
2723 			/* Invalid address */
2724 #ifdef SCTP_DEBUG
2725 			if (sctp_debug_on & SCTP_DEBUG_PCB3) {
2726 				printf("peer address invalid\n");
2727 			}
2728 #endif
2729 			SCTP_INP_RUNLOCK(inp);
2730 			*error = EINVAL;
2731 			return (NULL);
2732 		}
2733 		rport = sin6->sin6_port;
2734 	} else {
2735 		/* not supported family type */
2736 #ifdef SCTP_DEBUG
2737 		if (sctp_debug_on & SCTP_DEBUG_PCB3) {
2738 			printf("BAD family %d\n", firstaddr->sa_family);
2739 		}
2740 #endif
2741 		SCTP_INP_RUNLOCK(inp);
2742 		*error = EINVAL;
2743 		return (NULL);
2744 	}
2745 	SCTP_INP_RUNLOCK(inp);
2746 	if (inp->sctp_flags & SCTP_PCB_FLAGS_UNBOUND) {
2747 		/*
2748 		 * If you have not performed a bind, then we need to do
2749 		 * the ephemerial bind for you.
2750 		 */
2751 #ifdef SCTP_DEBUG
2752 		if (sctp_debug_on & SCTP_DEBUG_PCB3) {
2753 			printf("Doing implicit BIND\n");
2754 		}
2755 #endif
2756 
2757 		if ((err = sctp_inpcb_bind(inp->sctp_socket,
2758 		    (struct sockaddr *)NULL, (struct lwp *)NULL))){
2759 			/* bind error, probably perm */
2760 #ifdef SCTP_DEBUG
2761 			if (sctp_debug_on & SCTP_DEBUG_PCB3) {
2762 				printf("BIND FAILS ret:%d\n", err);
2763 			}
2764 #endif
2765 
2766 			*error = err;
2767 			return (NULL);
2768 		}
2769 	}
2770 	stcb = (struct sctp_tcb *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_asoc);
2771 	if (stcb == NULL) {
2772 		/* out of memory? */
2773 #ifdef SCTP_DEBUG
2774 		if (sctp_debug_on & SCTP_DEBUG_PCB3) {
2775 			printf("aloc_assoc: no assoc mem left, stcb=NULL\n");
2776 		}
2777 #endif
2778 		*error = ENOMEM;
2779 		return (NULL);
2780 	}
2781 	sctppcbinfo.ipi_count_asoc++;
2782 	sctppcbinfo.ipi_gencnt_asoc++;
2783 
2784 	memset(stcb, 0, sizeof(*stcb));
2785 	asoc = &stcb->asoc;
2786 	SCTP_TCB_LOCK_INIT(stcb);
2787 	/* setup back pointers */
2788 #ifdef SCTP_DEBUG
2789 	printf("Before back pointers\n");
2790 #endif
2791 	stcb->sctp_ep = inp;
2792 	stcb->sctp_socket = inp->sctp_socket;
2793 	if ((err = sctp_init_asoc(inp, asoc, for_a_init, override_tag))) {
2794 		/* failed */
2795 		SCTP_TCB_LOCK_DESTROY (stcb);
2796 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_asoc, stcb);
2797 		sctppcbinfo.ipi_count_asoc--;
2798 #ifdef SCTP_DEBUG
2799 		if (sctp_debug_on & SCTP_DEBUG_PCB3) {
2800 			printf("aloc_assoc: couldn't init asoc, out of mem?!\n");
2801 		}
2802 #endif
2803 		*error = err;
2804 		return (NULL);
2805 	}
2806 	/* and the port */
2807 	stcb->rport = rport;
2808 	SCTP_INP_INFO_WLOCK();
2809 	SCTP_INP_WLOCK(inp);
2810 	if (inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
2811 		/* inpcb freed while alloc going on */
2812 		SCTP_TCB_LOCK_DESTROY (stcb);
2813 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_asoc, stcb);
2814 		SCTP_INP_WUNLOCK(inp);
2815 		SCTP_INP_INFO_WUNLOCK();
2816 		sctppcbinfo.ipi_count_asoc--;
2817 #ifdef SCTP_DEBUG
2818 		if (sctp_debug_on & SCTP_DEBUG_PCB3) {
2819 			printf("aloc_assoc: couldn't init asoc, out of mem?!\n");
2820 		}
2821 #endif
2822 		*error = EINVAL;
2823 		return (NULL);
2824 	}
2825 	SCTP_TCB_LOCK(stcb);
2826 
2827 	/* now that my_vtag is set, add it to the  hash */
2828 	head = &sctppcbinfo.sctp_asochash[SCTP_PCBHASH_ASOC(stcb->asoc.my_vtag,
2829 	     sctppcbinfo.hashasocmark)];
2830 	/* put it in the bucket in the vtag hash of assoc's for the system */
2831 	LIST_INSERT_HEAD(head, stcb, sctp_asocs);
2832 	SCTP_INP_INFO_WUNLOCK();
2833 
2834 
2835 	if ((err = sctp_add_remote_addr(stcb, firstaddr, 1, 1))) {
2836 		/* failure.. memory error? */
2837 		if (asoc->strmout)
2838 			free(asoc->strmout, M_PCB);
2839 		if (asoc->mapping_array)
2840 			free(asoc->mapping_array, M_PCB);
2841 
2842 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_asoc, stcb);
2843 		sctppcbinfo.ipi_count_asoc--;
2844 #ifdef SCTP_DEBUG
2845 		if (sctp_debug_on & SCTP_DEBUG_PCB3) {
2846 			printf("aloc_assoc: couldn't add remote addr!\n");
2847 		}
2848 #endif
2849 		SCTP_TCB_LOCK_DESTROY (stcb);
2850 		*error = ENOBUFS;
2851 		return (NULL);
2852 	}
2853 	/* Init all the timers */
2854 	callout_init(&asoc->hb_timer.timer, 0);
2855 	callout_init(&asoc->dack_timer.timer, 0);
2856 	callout_init(&asoc->asconf_timer.timer, 0);
2857 	callout_init(&asoc->shut_guard_timer.timer, 0);
2858 	callout_init(&asoc->autoclose_timer.timer, 0);
2859 	callout_init(&asoc->delayed_event_timer.timer, 0);
2860 	LIST_INSERT_HEAD(&inp->sctp_asoc_list, stcb, sctp_tcblist);
2861 	/* now file the port under the hash as well */
2862 #ifdef SCTP_DEBUG
2863 	printf("Before hashing %ld size %d\n",
2864 		inp->sctp_hashmark, sctp_pcbtblsize);
2865 #endif
2866 	if (inp->sctp_tcbhash != NULL) {
2867 		head = &inp->sctp_tcbhash[SCTP_PCBHASH_ALLADDR(stcb->rport,
2868 		   inp->sctp_hashmark)];
2869 		LIST_INSERT_HEAD(head, stcb, sctp_tcbhash);
2870 	}
2871 #ifdef SCTP_DEBUG
2872 	printf("After hashing\n");
2873 #endif
2874 	SCTP_INP_WUNLOCK(inp);
2875 #ifdef SCTP_DEBUG
2876 	if (sctp_debug_on & SCTP_DEBUG_PCB1) {
2877 		printf("Association %p now allocated\n", stcb);
2878 	}
2879 #endif
2880 	return (stcb);
2881 }
2882 
2883 void
2884 sctp_free_remote_addr(struct sctp_nets *net)
2885 {
2886 	if (net == NULL)
2887 		return;
2888 	net->ref_count--;
2889 	if (net->ref_count <= 0) {
2890 		/* stop timer if running */
2891 		callout_stop(&net->rxt_timer.timer);
2892 		callout_stop(&net->pmtu_timer.timer);
2893 		callout_destroy(&net->rxt_timer.timer);
2894 		callout_destroy(&net->pmtu_timer.timer);
2895 		net->dest_state = SCTP_ADDR_NOT_REACHABLE;
2896 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_net, net);
2897 		sctppcbinfo.ipi_count_raddr--;
2898 	}
2899 }
2900 
2901 /*
2902  * remove a remote endpoint address from an association, it
2903  * will fail if the address does not exist.
2904  */
2905 int
2906 sctp_del_remote_addr(struct sctp_tcb *stcb, struct sockaddr *remaddr)
2907 {
2908 	/*
2909 	 * Here we need to remove a remote address. This is quite simple, we
2910 	 * first find it in the list of address for the association
2911 	 * (tasoc->asoc.nets) and then if it is there, we do a LIST_REMOVE on
2912 	 * that item.
2913 	 * Note we do not allow it to be removed if there are no other
2914 	 * addresses.
2915 	 */
2916 	struct sctp_association *asoc;
2917 	struct sctp_nets *net, *net_tmp;
2918 	asoc = &stcb->asoc;
2919 	if (asoc->numnets < 2) {
2920 		/* Must have at LEAST two remote addresses */
2921 		return (-1);
2922 	}
2923 	/* locate the address */
2924 	for (net = TAILQ_FIRST(&asoc->nets); net != NULL; net = net_tmp) {
2925 		net_tmp = TAILQ_NEXT(net, sctp_next);
2926 		if (rtcache_getdst(&net->ro)->sa_family != remaddr->sa_family) {
2927 			continue;
2928 		}
2929 		if (sctp_cmpaddr(rtcache_getdst(&net->ro), remaddr)) {
2930 			/* we found the guy */
2931 			asoc->numnets--;
2932 			TAILQ_REMOVE(&asoc->nets, net, sctp_next);
2933 			sctp_free_remote_addr(net);
2934 			if (net == asoc->primary_destination) {
2935 				/* Reset primary */
2936 				struct sctp_nets *lnet;
2937 				lnet = TAILQ_FIRST(&asoc->nets);
2938 				/* Try to find a confirmed primary */
2939 				asoc->primary_destination =
2940 				    sctp_find_alternate_net(stcb, lnet);
2941 			}
2942 			if (net == asoc->last_data_chunk_from) {
2943 				/* Reset primary */
2944 				asoc->last_data_chunk_from =
2945 				    TAILQ_FIRST(&asoc->nets);
2946 			}
2947 			if (net == asoc->last_control_chunk_from) {
2948 				/* Reset primary */
2949 				asoc->last_control_chunk_from =
2950 				    TAILQ_FIRST(&asoc->nets);
2951 			}
2952 			if (net == asoc->asconf_last_sent_to) {
2953 				/* Reset primary */
2954 				asoc->asconf_last_sent_to =
2955 				    TAILQ_FIRST(&asoc->nets);
2956 			}
2957 			return (0);
2958 		}
2959 	}
2960 	/* not found. */
2961 	return (-2);
2962 }
2963 
2964 
2965 static void
2966 sctp_add_vtag_to_timewait(struct sctp_inpcb *inp, u_int32_t tag)
2967 {
2968 	struct sctpvtaghead *chain;
2969 	struct sctp_tagblock *twait_block;
2970 	struct timeval now;
2971 	int set, i;
2972 	SCTP_GETTIME_TIMEVAL(&now);
2973 	chain = &sctppcbinfo.vtag_timewait[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
2974 	set = 0;
2975 	if (!LIST_EMPTY(chain)) {
2976 		/* Block(s) present, lets find space, and expire on the fly */
2977 		LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
2978 			for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
2979 				if ((twait_block->vtag_block[i].v_tag == 0) &&
2980 				    !set) {
2981 					twait_block->vtag_block[0].tv_sec_at_expire =
2982 					    now.tv_sec + SCTP_TIME_WAIT;
2983 					twait_block->vtag_block[0].v_tag = tag;
2984 					set = 1;
2985 				} else if ((twait_block->vtag_block[i].v_tag) &&
2986 				    ((long)twait_block->vtag_block[i].tv_sec_at_expire >
2987 				    now.tv_sec)) {
2988 					/* Audit expires this guy */
2989 					twait_block->vtag_block[i].tv_sec_at_expire = 0;
2990 					twait_block->vtag_block[i].v_tag = 0;
2991 					if (set == 0) {
2992 						/* Reuse it for my new tag */
2993 						twait_block->vtag_block[0].tv_sec_at_expire = now.tv_sec + SCTP_TIME_WAIT;
2994 						twait_block->vtag_block[0].v_tag = tag;
2995 						set = 1;
2996 					}
2997 				}
2998 			}
2999 			if (set) {
3000 				/*
3001 				 * We only do up to the block where we can
3002 				 * place our tag for audits
3003 				 */
3004 				break;
3005 			}
3006 		}
3007 	}
3008 	/* Need to add a new block to chain */
3009 	if (!set) {
3010 		twait_block = malloc(sizeof(struct sctp_tagblock), M_PCB, M_NOWAIT);
3011 		if (twait_block == NULL) {
3012 			return;
3013 		}
3014 		memset(twait_block, 0, sizeof(struct sctp_timewait));
3015 		LIST_INSERT_HEAD(chain, twait_block, sctp_nxt_tagblock);
3016 		twait_block->vtag_block[0].tv_sec_at_expire = now.tv_sec +
3017 		    SCTP_TIME_WAIT;
3018 		twait_block->vtag_block[0].v_tag = tag;
3019 	}
3020 }
3021 
3022 
3023 static void
3024 sctp_iterator_asoc_being_freed(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
3025 {
3026 	struct sctp_iterator *it;
3027 
3028 
3029 
3030 	/* Unlock the tcb lock we do this so
3031 	 * we avoid a dead lock scenario where
3032 	 * the iterator is waiting on the TCB lock
3033 	 * and the TCB lock is waiting on the iterator
3034 	 * lock.
3035 	 */
3036 	SCTP_ITERATOR_LOCK();
3037 	SCTP_INP_INFO_WLOCK();
3038 	SCTP_INP_WLOCK(inp);
3039 	SCTP_TCB_LOCK(stcb);
3040 
3041 	it = stcb->asoc.stcb_starting_point_for_iterator;
3042 	if (it == NULL) {
3043 		return;
3044 	}
3045 	if (it->inp != stcb->sctp_ep) {
3046 		/* hm, focused on the wrong one? */
3047 		return;
3048 	}
3049 	if (it->stcb != stcb) {
3050 		return;
3051 	}
3052 	it->stcb = LIST_NEXT(stcb, sctp_tcblist);
3053 	if (it->stcb == NULL) {
3054 		/* done with all asoc's in this assoc */
3055 		if (it->iterator_flags & SCTP_ITERATOR_DO_SINGLE_INP) {
3056 			it->inp = NULL;
3057 		} else {
3058 
3059 			it->inp = LIST_NEXT(inp, sctp_list);
3060 		}
3061 	}
3062 }
3063 
3064 /*
3065  * Free the association after un-hashing the remote port.
3066  */
3067 void
3068 sctp_free_assoc(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
3069 {
3070 	struct sctp_association *asoc;
3071 	struct sctp_nets *net, *prev;
3072 	struct sctp_laddr *laddr;
3073 	struct sctp_tmit_chunk *chk;
3074 	struct sctp_asconf_addr *aparam;
3075 	struct sctp_socket_q_list *sq;
3076 	int s;
3077 
3078 	/* first, lets purge the entry from the hash table. */
3079 	s = splsoftnet();
3080 	if (stcb->asoc.state == 0) {
3081 		printf("Freeing already free association:%p - huh??\n",
3082 		    stcb);
3083 		splx(s);
3084 		return;
3085 	}
3086 	asoc = &stcb->asoc;
3087 	asoc->state = 0;
3088 	/* now clean up any other timers */
3089 	callout_stop(&asoc->hb_timer.timer);
3090 	callout_destroy(&asoc->hb_timer.timer);
3091 	callout_stop(&asoc->dack_timer.timer);
3092 	callout_destroy(&asoc->dack_timer.timer);
3093 	callout_stop(&asoc->asconf_timer.timer);
3094 	callout_destroy(&asoc->asconf_timer.timer);
3095 	callout_stop(&asoc->shut_guard_timer.timer);
3096 	callout_destroy(&asoc->shut_guard_timer.timer);
3097 	callout_stop(&asoc->autoclose_timer.timer);
3098 	callout_destroy(&asoc->autoclose_timer.timer);
3099 	callout_stop(&asoc->delayed_event_timer.timer);
3100 	callout_destroy(&asoc->delayed_event_timer.timer);
3101 	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
3102 		callout_stop(&net->rxt_timer.timer);
3103 		callout_stop(&net->pmtu_timer.timer);
3104 		callout_destroy(&net->rxt_timer.timer);
3105 		callout_destroy(&net->pmtu_timer.timer);
3106 	}
3107 
3108 	/* Iterator asoc being freed we send an
3109 	 * unlocked TCB. It returns with INP_INFO
3110 	 * and INP write locked and the TCB locked
3111 	 * too and of course the iterator lock
3112 	 * in place as well..
3113 	 */
3114 	SCTP_TCB_UNLOCK(stcb);
3115 	sctp_iterator_asoc_being_freed(inp, stcb);
3116 
3117 	/* Null all of my entry's on the socket q */
3118 	TAILQ_FOREACH(sq, &inp->sctp_queue_list, next_sq) {
3119 		if (sq->tcb == stcb) {
3120 			sq->tcb = NULL;
3121 		}
3122 	}
3123 
3124 	if (inp->sctp_tcb_at_block == (void *)stcb) {
3125 		inp->error_on_block = ECONNRESET;
3126 	}
3127 
3128 	if (inp->sctp_tcbhash) {
3129 		LIST_REMOVE(stcb, sctp_tcbhash);
3130 	}
3131 	/* Now lets remove it from the list of ALL associations in the EP */
3132 	LIST_REMOVE(stcb, sctp_tcblist);
3133 	SCTP_INP_WUNLOCK(inp);
3134 	SCTP_ITERATOR_UNLOCK();
3135 
3136 
3137 	/* pull from vtag hash */
3138 	LIST_REMOVE(stcb, sctp_asocs);
3139 
3140 	/*
3141 	 * Now before we can free the assoc, we must  remove all of the
3142 	 * networks and any other allocated space.. i.e. add removes here
3143 	 * before the SCTP_ZONE_FREE() of the tasoc entry.
3144 	 */
3145 
3146 	sctp_add_vtag_to_timewait(inp, asoc->my_vtag);
3147 	SCTP_INP_INFO_WUNLOCK();
3148 	prev = NULL;
3149 	while (!TAILQ_EMPTY(&asoc->nets)) {
3150 		net = TAILQ_FIRST(&asoc->nets);
3151 		/* pull from list */
3152 		if ((sctppcbinfo.ipi_count_raddr == 0) || (prev == net)) {
3153 			break;
3154 		}
3155 		prev = net;
3156 		TAILQ_REMOVE(&asoc->nets, net, sctp_next);
3157 		/* free it */
3158 		net->ref_count = 0;
3159 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_net, net);
3160 		sctppcbinfo.ipi_count_raddr--;
3161 	}
3162 	/*
3163 	 * The chunk lists and such SHOULD be empty but we check them
3164 	 * just in case.
3165 	 */
3166 	/* anything on the wheel needs to be removed */
3167 	while (!TAILQ_EMPTY(&asoc->out_wheel)) {
3168 		struct sctp_stream_out *outs;
3169 		outs = TAILQ_FIRST(&asoc->out_wheel);
3170 		TAILQ_REMOVE(&asoc->out_wheel, outs, next_spoke);
3171 		/* now clean up any chunks here */
3172 		chk = TAILQ_FIRST(&outs->outqueue);
3173 		while (chk) {
3174 			TAILQ_REMOVE(&outs->outqueue, chk, sctp_next);
3175 			if (chk->data) {
3176 				sctp_m_freem(chk->data);
3177 				chk->data = NULL;
3178 			}
3179 			chk->whoTo = NULL;
3180 			chk->asoc = NULL;
3181 			/* Free the chunk */
3182 			SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
3183 			sctppcbinfo.ipi_count_chunk--;
3184 			sctppcbinfo.ipi_gencnt_chunk++;
3185 			if ((int)sctppcbinfo.ipi_count_chunk < 0) {
3186 				panic("Chunk count is negative");
3187 			}
3188 			chk = TAILQ_FIRST(&outs->outqueue);
3189 		}
3190 		outs = TAILQ_FIRST(&asoc->out_wheel);
3191 	}
3192 
3193 	if (asoc->pending_reply) {
3194 		free(asoc->pending_reply, M_PCB);
3195 		asoc->pending_reply = NULL;
3196 	}
3197 	chk = TAILQ_FIRST(&asoc->pending_reply_queue);
3198 	while (chk) {
3199 		TAILQ_REMOVE(&asoc->pending_reply_queue, chk, sctp_next);
3200 		if (chk->data) {
3201 			sctp_m_freem(chk->data);
3202 			chk->data = NULL;
3203 		}
3204 		chk->whoTo = NULL;
3205 		chk->asoc = NULL;
3206 		/* Free the chunk */
3207 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
3208 		sctppcbinfo.ipi_count_chunk--;
3209 		sctppcbinfo.ipi_gencnt_chunk++;
3210 		if ((int)sctppcbinfo.ipi_count_chunk < 0) {
3211 			panic("Chunk count is negative");
3212 		}
3213 		chk = TAILQ_FIRST(&asoc->pending_reply_queue);
3214 	}
3215 	/* pending send queue SHOULD be empty */
3216 	if (!TAILQ_EMPTY(&asoc->send_queue)) {
3217 		chk = TAILQ_FIRST(&asoc->send_queue);
3218 		while (chk) {
3219 			TAILQ_REMOVE(&asoc->send_queue, chk, sctp_next);
3220 			if (chk->data) {
3221 				sctp_m_freem(chk->data);
3222 				chk->data = NULL;
3223 			}
3224 			SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
3225 			sctppcbinfo.ipi_count_chunk--;
3226 			if ((int)sctppcbinfo.ipi_count_chunk < 0) {
3227 				panic("Chunk count is negative");
3228 			}
3229 			sctppcbinfo.ipi_gencnt_chunk++;
3230 			chk = TAILQ_FIRST(&asoc->send_queue);
3231 		}
3232 	}
3233 	/* sent queue SHOULD be empty */
3234 	if (!TAILQ_EMPTY(&asoc->sent_queue)) {
3235 		chk = TAILQ_FIRST(&asoc->sent_queue);
3236 		while (chk) {
3237 			TAILQ_REMOVE(&asoc->sent_queue, chk, sctp_next);
3238 			if (chk->data) {
3239 				sctp_m_freem(chk->data);
3240 				chk->data = NULL;
3241 			}
3242 			SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
3243 			sctppcbinfo.ipi_count_chunk--;
3244 			if ((int)sctppcbinfo.ipi_count_chunk < 0) {
3245 				panic("Chunk count is negative");
3246 			}
3247 			sctppcbinfo.ipi_gencnt_chunk++;
3248 			chk = TAILQ_FIRST(&asoc->sent_queue);
3249 		}
3250 	}
3251 	/* control queue MAY not be empty */
3252 	if (!TAILQ_EMPTY(&asoc->control_send_queue)) {
3253 		chk = TAILQ_FIRST(&asoc->control_send_queue);
3254 		while (chk) {
3255 			TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
3256 			if (chk->data) {
3257 				sctp_m_freem(chk->data);
3258 				chk->data = NULL;
3259 			}
3260 			SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
3261 			sctppcbinfo.ipi_count_chunk--;
3262 			if ((int)sctppcbinfo.ipi_count_chunk < 0) {
3263 				panic("Chunk count is negative");
3264 			}
3265 			sctppcbinfo.ipi_gencnt_chunk++;
3266 			chk = TAILQ_FIRST(&asoc->control_send_queue);
3267 		}
3268 	}
3269 	if (!TAILQ_EMPTY(&asoc->reasmqueue)) {
3270 		chk = TAILQ_FIRST(&asoc->reasmqueue);
3271 		while (chk) {
3272 			TAILQ_REMOVE(&asoc->reasmqueue, chk, sctp_next);
3273 			if (chk->data) {
3274 				sctp_m_freem(chk->data);
3275 				chk->data = NULL;
3276 			}
3277 			SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
3278 			sctppcbinfo.ipi_count_chunk--;
3279 			if ((int)sctppcbinfo.ipi_count_chunk < 0) {
3280 				panic("Chunk count is negative");
3281 			}
3282 			sctppcbinfo.ipi_gencnt_chunk++;
3283 			chk = TAILQ_FIRST(&asoc->reasmqueue);
3284 		}
3285 	}
3286 	if (!TAILQ_EMPTY(&asoc->delivery_queue)) {
3287 		chk = TAILQ_FIRST(&asoc->delivery_queue);
3288 		while (chk) {
3289 			TAILQ_REMOVE(&asoc->delivery_queue, chk, sctp_next);
3290 			if (chk->data) {
3291 				sctp_m_freem(chk->data);
3292 				chk->data = NULL;
3293 			}
3294 			SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
3295 			sctppcbinfo.ipi_count_chunk--;
3296 			if ((int)sctppcbinfo.ipi_count_chunk < 0) {
3297 				panic("Chunk count is negative");
3298 			}
3299 			sctppcbinfo.ipi_gencnt_chunk++;
3300 			chk = TAILQ_FIRST(&asoc->delivery_queue);
3301 		}
3302 	}
3303 	if (asoc->mapping_array) {
3304 		free(asoc->mapping_array, M_PCB);
3305 		asoc->mapping_array = NULL;
3306 	}
3307 
3308 	/* the stream outs */
3309 	if (asoc->strmout) {
3310 		free(asoc->strmout, M_PCB);
3311 		asoc->strmout = NULL;
3312 	}
3313 	asoc->streamoutcnt = 0;
3314 	if (asoc->strmin) {
3315 		int i;
3316 		for (i = 0; i < asoc->streamincnt; i++) {
3317 			if (!TAILQ_EMPTY(&asoc->strmin[i].inqueue)) {
3318 				/* We have somethings on the streamin queue */
3319 				chk = TAILQ_FIRST(&asoc->strmin[i].inqueue);
3320 				while (chk) {
3321 					TAILQ_REMOVE(&asoc->strmin[i].inqueue,
3322 					    chk, sctp_next);
3323 					if (chk->data) {
3324 						sctp_m_freem(chk->data);
3325 						chk->data = NULL;
3326 					}
3327 					SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk,
3328 					    chk);
3329 					sctppcbinfo.ipi_count_chunk--;
3330 					if ((int)sctppcbinfo.ipi_count_chunk < 0) {
3331 						panic("Chunk count is negative");
3332 					}
3333 					sctppcbinfo.ipi_gencnt_chunk++;
3334 					chk = TAILQ_FIRST(&asoc->strmin[i].inqueue);
3335 				}
3336 			}
3337 		}
3338 		free(asoc->strmin, M_PCB);
3339 		asoc->strmin = NULL;
3340 	}
3341 	asoc->streamincnt = 0;
3342 	/* local addresses, if any */
3343 	while (!LIST_EMPTY(&asoc->sctp_local_addr_list)) {
3344 		laddr = LIST_FIRST(&asoc->sctp_local_addr_list);
3345 		LIST_REMOVE(laddr, sctp_nxt_addr);
3346 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_laddr, laddr);
3347 		sctppcbinfo.ipi_count_laddr--;
3348 	}
3349 	/* pending asconf (address) parameters */
3350 	while (!TAILQ_EMPTY(&asoc->asconf_queue)) {
3351 		aparam = TAILQ_FIRST(&asoc->asconf_queue);
3352 		TAILQ_REMOVE(&asoc->asconf_queue, aparam, next);
3353 		free(aparam, M_PCB);
3354 	}
3355 	if (asoc->last_asconf_ack_sent != NULL) {
3356 		sctp_m_freem(asoc->last_asconf_ack_sent);
3357 		asoc->last_asconf_ack_sent = NULL;
3358 	}
3359 	/* Insert new items here :> */
3360 
3361 	/* Get rid of LOCK */
3362 	SCTP_TCB_LOCK_DESTROY(stcb);
3363 
3364 	/* now clean up the tasoc itself */
3365 	SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_asoc, stcb);
3366 	sctppcbinfo.ipi_count_asoc--;
3367 	if ((inp->sctp_socket->so_snd.sb_cc) ||
3368 	    (inp->sctp_socket->so_snd.sb_mbcnt)) {
3369 		/* This will happen when a abort is done */
3370 		inp->sctp_socket->so_snd.sb_cc = 0;
3371 		inp->sctp_socket->so_snd.sb_mbcnt = 0;
3372 	}
3373 	if (inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) {
3374 		if ((inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) == 0) {
3375 			if (inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) {
3376 				/*
3377 				 * For the base fd, that is NOT in TCP pool we
3378 				 * turn off the connected flag. This allows
3379 				 * non-listening endpoints to connect/shutdown/
3380 				 * connect.
3381 				 */
3382 				inp->sctp_flags &= ~SCTP_PCB_FLAGS_CONNECTED;
3383 				soisdisconnected(inp->sctp_socket);
3384 			}
3385 			/*
3386 			 * For those that are in the TCP pool we just leave
3387 			 * so it cannot be used. When they close the fd we
3388 			 * will free it all.
3389 			 */
3390 		}
3391 	}
3392 	if (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) {
3393 		sctp_inpcb_free(inp, 0);
3394 	}
3395 	splx(s);
3396 }
3397 
3398 
3399 /*
3400  * determine if a destination is "reachable" based upon the addresses
3401  * bound to the current endpoint (e.g. only v4 or v6 currently bound)
3402  */
3403 /*
3404  * FIX: if we allow assoc-level bindx(), then this needs to be fixed
3405  * to use assoc level v4/v6 flags, as the assoc *may* not have the
3406  * same address types bound as its endpoint
3407  */
3408 int
3409 sctp_destination_is_reachable(struct sctp_tcb *stcb, const struct sockaddr *destaddr)
3410 {
3411 	struct sctp_inpcb *inp;
3412 	int answer;
3413 
3414 	/* No locks here, the TCB, in all cases is already
3415 	 * locked and an assoc is up. There is either a
3416 	 * INP lock by the caller applied (in asconf case when
3417 	 * deleting an address) or NOT in the HB case, however
3418 	 * if HB then the INP increment is up and the INP
3419 	 * will not be removed (on top of the fact that
3420 	 * we have a TCB lock). So we only want to
3421 	 * read the sctp_flags, which is either bound-all
3422 	 * or not.. no protection needed since once an
3423 	 * assoc is up you can't be changing your binding.
3424 	 */
3425 	inp = stcb->sctp_ep;
3426 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
3427 		/* if bound all, destination is not restricted */
3428 		/* RRS: Question during lock work: Is this
3429 		 * correct? If you are bound-all you still
3430 		 * might need to obey the V4--V6 flags???
3431 		 * IMO this bound-all stuff needs to be removed!
3432 		 */
3433 		return (1);
3434 	}
3435 	/* NOTE: all "scope" checks are done when local addresses are added */
3436 	if (destaddr->sa_family == AF_INET6) {
3437 #if !(defined(__FreeBSD__) || defined(__APPLE__))
3438 		answer = inp->inp_vflag & INP_IPV6;
3439 #else
3440 		answer = inp->ip_inp.inp.inp_vflag & INP_IPV6;
3441 #endif
3442 	} else if (destaddr->sa_family == AF_INET) {
3443 #if !(defined(__FreeBSD__) || defined(__APPLE__))
3444 		answer = inp->inp_vflag & INP_IPV4;
3445 #else
3446 		answer = inp->ip_inp.inp.inp_vflag & INP_IPV4;
3447 #endif
3448 	} else {
3449 		/* invalid family, so it's unreachable */
3450 		answer = 0;
3451 	}
3452 	return (answer);
3453 }
3454 
3455 /*
3456  * update the inp_vflags on an endpoint
3457  */
3458 static void
3459 sctp_update_ep_vflag(struct sctp_inpcb *inp) {
3460 	struct sctp_laddr *laddr;
3461 
3462 	/* first clear the flag */
3463 #if !(defined(__FreeBSD__) || defined(__APPLE__))
3464 	inp->inp_vflag = 0;
3465 #else
3466 	inp->ip_inp.inp.inp_vflag = 0;
3467 #endif
3468 	/* set the flag based on addresses on the ep list */
3469 	LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
3470 		if (laddr->ifa == NULL) {
3471 #ifdef SCTP_DEBUG
3472 			if (sctp_debug_on & SCTP_DEBUG_PCB1) {
3473 				printf("An ounce of prevention is worth a pound of cure\n");
3474 			}
3475 #endif /* SCTP_DEBUG */
3476 			continue;
3477 		}
3478 		if (laddr->ifa->ifa_addr) {
3479 			continue;
3480 		}
3481 		if (laddr->ifa->ifa_addr->sa_family == AF_INET6) {
3482 #if !(defined(__FreeBSD__) || defined(__APPLE__))
3483 			inp->inp_vflag |= INP_IPV6;
3484 #else
3485 			inp->ip_inp.inp.inp_vflag |= INP_IPV6;
3486 #endif
3487 		} else if (laddr->ifa->ifa_addr->sa_family == AF_INET) {
3488 #if !(defined(__FreeBSD__) || defined(__APPLE__))
3489 			inp->inp_vflag |= INP_IPV4;
3490 #else
3491 			inp->ip_inp.inp.inp_vflag |= INP_IPV4;
3492 #endif
3493 		}
3494 	}
3495 }
3496 
3497 /*
3498  * Add the address to the endpoint local address list
3499  * There is nothing to be done if we are bound to all addresses
3500  */
3501 int
3502 sctp_add_local_addr_ep(struct sctp_inpcb *inp, struct ifaddr *ifa)
3503 {
3504 	struct sctp_laddr *laddr;
3505 	int fnd, error;
3506 	fnd = 0;
3507 
3508 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
3509 		/* You are already bound to all. You have it already */
3510 		return (0);
3511 	}
3512 	if (ifa->ifa_addr->sa_family == AF_INET6) {
3513 		struct in6_ifaddr *ifa6;
3514 		ifa6 = (struct in6_ifaddr *)ifa;
3515 		if (ifa6->ia6_flags & (IN6_IFF_DETACHED |
3516 		    IN6_IFF_DEPRECATED | IN6_IFF_ANYCAST | IN6_IFF_NOTREADY))
3517 			/* Can't bind a non-existent addr. */
3518 			return (-1);
3519 	}
3520 	/* first, is it already present? */
3521 	LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
3522 		if (laddr->ifa == ifa) {
3523 			fnd = 1;
3524 			break;
3525 		}
3526 	}
3527 
3528 	if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) && (fnd == 0)) {
3529 		/* Not bound to all */
3530 		error = sctp_insert_laddr(&inp->sctp_addr_list, ifa);
3531 		if (error != 0)
3532 			return (error);
3533 		inp->laddr_count++;
3534 		/* update inp_vflag flags */
3535 		if (ifa->ifa_addr->sa_family == AF_INET6) {
3536 #if !(defined(__FreeBSD__) || defined(__APPLE__))
3537 			inp->inp_vflag |= INP_IPV6;
3538 #else
3539 			inp->ip_inp.inp.inp_vflag |= INP_IPV6;
3540 #endif
3541 		} else if (ifa->ifa_addr->sa_family == AF_INET) {
3542 #if !(defined(__FreeBSD__) || defined(__APPLE__))
3543 			inp->inp_vflag |= INP_IPV4;
3544 #else
3545 			inp->ip_inp.inp.inp_vflag |= INP_IPV4;
3546 #endif
3547 		}
3548 	}
3549 	return (0);
3550 }
3551 
3552 
3553 /*
3554  * select a new (hopefully reachable) destination net
3555  * (should only be used when we deleted an ep addr that is the
3556  * only usable source address to reach the destination net)
3557  */
3558 static void
3559 sctp_select_primary_destination(struct sctp_tcb *stcb)
3560 {
3561 	struct sctp_nets *net;
3562 
3563 	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
3564 		/* for now, we'll just pick the first reachable one we find */
3565 		if (net->dest_state & SCTP_ADDR_UNCONFIRMED)
3566 			continue;
3567 		if (sctp_destination_is_reachable(stcb,
3568 			rtcache_getdst(&net->ro))) {
3569 			/* found a reachable destination */
3570 			stcb->asoc.primary_destination = net;
3571 		}
3572 	}
3573 	/* I can't there from here! ...we're gonna die shortly... */
3574 }
3575 
3576 
3577 /*
3578  * Delete the address from the endpoint local address list
3579  * There is nothing to be done if we are bound to all addresses
3580  */
3581 int
3582 sctp_del_local_addr_ep(struct sctp_inpcb *inp, struct ifaddr *ifa)
3583 {
3584 	struct sctp_laddr *laddr;
3585 	int fnd;
3586 	fnd = 0;
3587 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
3588 		/* You are already bound to all. You have it already */
3589 		return (EINVAL);
3590 	}
3591 
3592 	LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
3593 		if (laddr->ifa == ifa) {
3594 			fnd = 1;
3595 			break;
3596 		}
3597 	}
3598 	if (fnd && (inp->laddr_count < 2)) {
3599 		/* can't delete unless there are at LEAST 2 addresses */
3600 		return (-1);
3601 	}
3602 	if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) && (fnd)) {
3603 		/*
3604 		 * clean up any use of this address
3605 		 * go through our associations and clear any
3606 		 *  last_used_address that match this one
3607 		 * for each assoc, see if a new primary_destination is needed
3608 		 */
3609 		struct sctp_tcb *stcb;
3610 
3611 		/* clean up "next_addr_touse" */
3612 		if (inp->next_addr_touse == laddr)
3613 			/* delete this address */
3614 			inp->next_addr_touse = NULL;
3615 
3616 		/* clean up "last_used_address" */
3617 		LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
3618 			if (stcb->asoc.last_used_address == laddr)
3619 				/* delete this address */
3620 				stcb->asoc.last_used_address = NULL;
3621 		} /* for each tcb */
3622 
3623 		/* remove it from the ep list */
3624 		sctp_remove_laddr(laddr);
3625 		inp->laddr_count--;
3626 		/* update inp_vflag flags */
3627 		sctp_update_ep_vflag(inp);
3628 		/* select a new primary destination if needed */
3629 		LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
3630 			/* presume caller (sctp_asconf.c) already owns INP lock */
3631 			SCTP_TCB_LOCK(stcb);
3632 			if (sctp_destination_is_reachable(stcb,
3633 			    rtcache_getdst(&stcb->asoc.primary_destination->ro)) == 0) {
3634 				sctp_select_primary_destination(stcb);
3635 			}
3636 			SCTP_TCB_UNLOCK(stcb);
3637 		} /* for each tcb */
3638 	}
3639 	return (0);
3640 }
3641 
3642 /*
3643  * Add the addr to the TCB local address list
3644  * For the BOUNDALL or dynamic case, this is a "pending" address list
3645  * (eg. addresses waiting for an ASCONF-ACK response)
3646  * For the subset binding, static case, this is a "valid" address list
3647  */
3648 int
3649 sctp_add_local_addr_assoc(struct sctp_tcb *stcb, struct ifaddr *ifa)
3650 {
3651 	struct sctp_laddr *laddr;
3652 	int error;
3653 
3654 	/* Assumes TCP is locked.. and possiblye
3655 	 * the INP. May need to confirm/fix that if
3656 	 * we need it and is not the case.
3657 	 */
3658 	if (ifa->ifa_addr->sa_family == AF_INET6) {
3659 		struct in6_ifaddr *ifa6;
3660 		ifa6 = (struct in6_ifaddr *)ifa;
3661 		if (ifa6->ia6_flags & (IN6_IFF_DETACHED |
3662 		    /* IN6_IFF_DEPRECATED | */
3663 		    IN6_IFF_ANYCAST |
3664 		    IN6_IFF_NOTREADY))
3665 			/* Can't bind a non-existent addr. */
3666 			return (-1);
3667 	}
3668 	/* does the address already exist? */
3669 	LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list, sctp_nxt_addr) {
3670 		if (laddr->ifa == ifa) {
3671 			return (-1);
3672 		}
3673 	}
3674 
3675 	/* add to the list */
3676 	error = sctp_insert_laddr(&stcb->asoc.sctp_local_addr_list, ifa);
3677 	if (error != 0)
3678 		return (error);
3679 	return (0);
3680 }
3681 
3682 /*
3683  * insert an laddr entry with the given ifa for the desired list
3684  */
3685 int
3686 sctp_insert_laddr(struct sctpladdr *list, struct ifaddr *ifa) {
3687 	struct sctp_laddr *laddr;
3688 	int s;
3689 
3690 	s = splsoftnet();
3691 
3692 	laddr = (struct sctp_laddr *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_laddr);
3693 	if (laddr == NULL) {
3694 		/* out of memory? */
3695 		splx(s);
3696 		return (EINVAL);
3697 	}
3698 	sctppcbinfo.ipi_count_laddr++;
3699 	sctppcbinfo.ipi_gencnt_laddr++;
3700 	memset(laddr, 0, sizeof(*laddr));
3701 	laddr->ifa = ifa;
3702 	/* insert it */
3703 	LIST_INSERT_HEAD(list, laddr, sctp_nxt_addr);
3704 
3705 	splx(s);
3706 	return (0);
3707 }
3708 
3709 /*
3710  * Remove an laddr entry from the local address list (on an assoc)
3711  */
3712 void
3713 sctp_remove_laddr(struct sctp_laddr *laddr)
3714 {
3715 	int s;
3716 	s = splsoftnet();
3717 	/* remove from the list */
3718 	LIST_REMOVE(laddr, sctp_nxt_addr);
3719 	SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_laddr, laddr);
3720 	sctppcbinfo.ipi_count_laddr--;
3721 	sctppcbinfo.ipi_gencnt_laddr++;
3722 
3723 	splx(s);
3724 }
3725 
3726 /*
3727  * Remove an address from the TCB local address list
3728  */
3729 int
3730 sctp_del_local_addr_assoc(struct sctp_tcb *stcb, struct ifaddr *ifa)
3731 {
3732 	struct sctp_inpcb *inp;
3733 	struct sctp_laddr *laddr;
3734 
3735 	/* This is called by asconf work. It is assumed that
3736 	 * a) The TCB is locked
3737 	 * and
3738 	 * b) The INP is locked.
3739 	 * This is true in as much as I can trace through
3740 	 * the entry asconf code where I did these locks.
3741 	 * Again, the ASCONF code is a bit different in
3742 	 * that it does lock the INP during its work often
3743 	 * times. This must be since we don't want other
3744 	 * proc's looking up things while what they are
3745 	 * looking up is changing :-D
3746 	 */
3747 
3748 	inp = stcb->sctp_ep;
3749 	/* if subset bound and don't allow ASCONF's, can't delete last */
3750 	if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) &&
3751 	    ((inp->sctp_flags & SCTP_PCB_FLAGS_DO_ASCONF) == 0)) {
3752 		if (stcb->asoc.numnets < 2) {
3753 			/* can't delete last address */
3754 			return (-1);
3755 		}
3756 	}
3757 
3758 	LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list, sctp_nxt_addr) {
3759 		/* remove the address if it exists */
3760 		if (laddr->ifa == NULL)
3761 			continue;
3762 		if (laddr->ifa == ifa) {
3763 			sctp_remove_laddr(laddr);
3764 			return (0);
3765 		}
3766 	}
3767 
3768 	/* address not found! */
3769 	return (-1);
3770 }
3771 
3772 /*
3773  * Remove an address from the TCB local address list
3774  * lookup using a sockaddr addr
3775  */
3776 int
3777 sctp_del_local_addr_assoc_sa(struct sctp_tcb *stcb, struct sockaddr *sa)
3778 {
3779 	struct sctp_inpcb *inp;
3780 	struct sctp_laddr *laddr;
3781 	struct sockaddr *l_sa;
3782 
3783         /*
3784          * This function I find does not seem to have a caller.
3785 	 * As such we NEED TO DELETE this code. If we do
3786 	 * find a caller, the caller MUST have locked the TCB
3787 	 * at the least and probably the INP as well.
3788          */
3789 	inp = stcb->sctp_ep;
3790 	/* if subset bound and don't allow ASCONF's, can't delete last */
3791 	if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) &&
3792 	    ((inp->sctp_flags & SCTP_PCB_FLAGS_DO_ASCONF) == 0)) {
3793 		if (stcb->asoc.numnets < 2) {
3794 			/* can't delete last address */
3795 			return (-1);
3796 		}
3797 	}
3798 
3799 	LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list, sctp_nxt_addr) {
3800 		/* make sure the address exists */
3801 		if (laddr->ifa == NULL)
3802 			continue;
3803 		if (laddr->ifa->ifa_addr == NULL)
3804 			continue;
3805 
3806 		l_sa = laddr->ifa->ifa_addr;
3807 		if (l_sa->sa_family == AF_INET6) {
3808 			/* IPv6 address */
3809 			struct sockaddr_in6 *sin1, *sin2;
3810 			sin1 = (struct sockaddr_in6 *)l_sa;
3811 			sin2 = (struct sockaddr_in6 *)sa;
3812 			if (memcmp(&sin1->sin6_addr, &sin2->sin6_addr,
3813 			    sizeof(struct in6_addr)) == 0) {
3814 				/* matched */
3815 				sctp_remove_laddr(laddr);
3816 				return (0);
3817 			}
3818 		} else if (l_sa->sa_family == AF_INET) {
3819 			/* IPv4 address */
3820 			struct sockaddr_in *sin1, *sin2;
3821 			sin1 = (struct sockaddr_in *)l_sa;
3822 			sin2 = (struct sockaddr_in *)sa;
3823 			if (sin1->sin_addr.s_addr == sin2->sin_addr.s_addr) {
3824 				/* matched */
3825 				sctp_remove_laddr(laddr);
3826 				return (0);
3827 			}
3828 		} else {
3829 			/* invalid family */
3830 			return (-1);
3831 		}
3832 	} /* end foreach */
3833 	/* address not found! */
3834 	return (-1);
3835 }
3836 
3837 static char sctp_pcb_initialized = 0;
3838 
3839 #if defined(__FreeBSD__) || defined(__APPLE__)
3840 /* sysctl */
3841 static int sctp_max_number_of_assoc = SCTP_MAX_NUM_OF_ASOC;
3842 static int sctp_scale_up_for_address = SCTP_SCALE_FOR_ADDR;
3843 
3844 #endif /* FreeBSD || APPLE */
3845 
3846 #ifndef SCTP_TCBHASHSIZE
3847 #define SCTP_TCBHASHSIZE 1024
3848 #endif
3849 
3850 #ifndef SCTP_CHUNKQUEUE_SCALE
3851 #define SCTP_CHUNKQUEUE_SCALE 10
3852 #endif
3853 
3854 void
3855 sctp_pcb_init(void)
3856 {
3857 	/*
3858 	 * SCTP initialization for the PCB structures
3859 	 * should be called by the sctp_init() funciton.
3860 	 */
3861 	int i;
3862 	int hashtblsize = SCTP_TCBHASHSIZE;
3863 
3864 #if defined(__FreeBSD__) || defined(__APPLE__)
3865 	int sctp_chunkscale = SCTP_CHUNKQUEUE_SCALE;
3866 #endif
3867 
3868 	if (sctp_pcb_initialized != 0) {
3869 		/* error I was called twice */
3870 		return;
3871 	}
3872 	sctp_pcb_initialized = 1;
3873 
3874 	/* Init all peg counts */
3875 	for (i = 0; i < SCTP_NUMBER_OF_PEGS; i++) {
3876 		sctp_pegs[i] = 0;
3877 	}
3878 
3879 	/* init the empty list of (All) Endpoints */
3880 	LIST_INIT(&sctppcbinfo.listhead);
3881 
3882 	/* init the iterator head */
3883 	LIST_INIT(&sctppcbinfo.iteratorhead);
3884 
3885 	/* init the hash table of endpoints */
3886 #if defined(__FreeBSD__)
3887 #if defined(__FreeBSD_cc_version) && __FreeBSD_cc_version >= 440000
3888 	TUNABLE_INT_FETCH("net.inet.sctp.tcbhashsize", &hashtblsize);
3889 	TUNABLE_INT_FETCH("net.inet.sctp.pcbhashsize", &sctp_pcbtblsize);
3890 	TUNABLE_INT_FETCH("net.inet.sctp.chunkscale", &sctp_chunkscale);
3891 #else
3892 	TUNABLE_INT_FETCH("net.inet.sctp.tcbhashsize", SCTP_TCBHASHSIZE,
3893 	    hashtblsize);
3894 	TUNABLE_INT_FETCH("net.inet.sctp.pcbhashsize", SCTP_PCBHASHSIZE,
3895 	    sctp_pcbtblsize);
3896 	TUNABLE_INT_FETCH("net.inet.sctp.chunkscale", SCTP_CHUNKQUEUE_SCALE,
3897 	    sctp_chunkscale);
3898 #endif
3899 #endif
3900 
3901 	sctppcbinfo.sctp_asochash = hashinit((hashtblsize * 31), HASH_LIST,
3902 			M_WAITOK, &sctppcbinfo.hashasocmark);
3903 
3904 	sctppcbinfo.sctp_ephash = hashinit(hashtblsize, HASH_LIST,
3905 			M_WAITOK, &sctppcbinfo.hashmark);
3906 
3907 	sctppcbinfo.sctp_tcpephash = hashinit(hashtblsize, HASH_LIST,
3908 			M_WAITOK, &sctppcbinfo.hashtcpmark);
3909 
3910 	sctppcbinfo.hashtblsize = hashtblsize;
3911 
3912 	/* init the zones */
3913 	/*
3914 	 * FIX ME: Should check for NULL returns, but if it does fail we
3915 	 * are doomed to panic anyways... add later maybe.
3916 	 */
3917 	SCTP_ZONE_INIT(sctppcbinfo.ipi_zone_ep, "sctp_ep",
3918 	    sizeof(struct sctp_inpcb), maxsockets);
3919 
3920 	SCTP_ZONE_INIT(sctppcbinfo.ipi_zone_asoc, "sctp_asoc",
3921 	    sizeof(struct sctp_tcb), sctp_max_number_of_assoc);
3922 
3923 	SCTP_ZONE_INIT(sctppcbinfo.ipi_zone_laddr, "sctp_laddr",
3924 	    sizeof(struct sctp_laddr),
3925 	    (sctp_max_number_of_assoc * sctp_scale_up_for_address));
3926 
3927 	SCTP_ZONE_INIT(sctppcbinfo.ipi_zone_net, "sctp_raddr",
3928 	    sizeof(struct sctp_nets),
3929 	    (sctp_max_number_of_assoc * sctp_scale_up_for_address));
3930 
3931 	SCTP_ZONE_INIT(sctppcbinfo.ipi_zone_chunk, "sctp_chunk",
3932 	    sizeof(struct sctp_tmit_chunk),
3933 	    (sctp_max_number_of_assoc * sctp_scale_up_for_address *
3934 	    sctp_chunkscale));
3935 
3936 	SCTP_ZONE_INIT(sctppcbinfo.ipi_zone_sockq, "sctp_sockq",
3937 	    sizeof(struct sctp_socket_q_list),
3938 	    (sctp_max_number_of_assoc * sctp_scale_up_for_address *
3939 	    sctp_chunkscale));
3940 
3941 	SCTP_ZONE_INIT(sctppcbinfo.ipi_zone_hash, "sctp_hash",
3942 		       sizeof(void *) * sctp_pcbtblsize, maxsockets);
3943 
3944         /* Master Lock INIT for info structure */
3945 	SCTP_INP_INFO_LOCK_INIT();
3946 	SCTP_ITERATOR_LOCK_INIT();
3947 	/* not sure if we need all the counts */
3948 	sctppcbinfo.ipi_count_ep = 0;
3949 	sctppcbinfo.ipi_gencnt_ep = 0;
3950 	/* assoc/tcb zone info */
3951 	sctppcbinfo.ipi_count_asoc = 0;
3952 	sctppcbinfo.ipi_gencnt_asoc = 0;
3953 	/* local addrlist zone info */
3954 	sctppcbinfo.ipi_count_laddr = 0;
3955 	sctppcbinfo.ipi_gencnt_laddr = 0;
3956 	/* remote addrlist zone info */
3957 	sctppcbinfo.ipi_count_raddr = 0;
3958 	sctppcbinfo.ipi_gencnt_raddr = 0;
3959 	/* chunk info */
3960 	sctppcbinfo.ipi_count_chunk = 0;
3961 	sctppcbinfo.ipi_gencnt_chunk = 0;
3962 
3963 	/* socket queue zone info */
3964 	sctppcbinfo.ipi_count_sockq = 0;
3965 	sctppcbinfo.ipi_gencnt_sockq = 0;
3966 
3967 	/* mbuf tracker */
3968 	sctppcbinfo.mbuf_track = 0;
3969 	/* port stuff */
3970 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
3971 	sctppcbinfo.lastlow = ipport_firstauto;
3972 #else
3973 	sctppcbinfo.lastlow = anonportmin;
3974 #endif
3975 	/* Init the TIMEWAIT list */
3976 	for (i = 0; i < SCTP_STACK_VTAG_HASH_SIZE; i++) {
3977 		LIST_INIT(&sctppcbinfo.vtag_timewait[i]);
3978 	}
3979 
3980 #if defined(_SCTP_NEEDS_CALLOUT_) && !defined(__APPLE__)
3981 	TAILQ_INIT(&sctppcbinfo.callqueue);
3982 #endif
3983 
3984 }
3985 
3986 int
3987 sctp_load_addresses_from_init(struct sctp_tcb *stcb, struct mbuf *m,
3988     int iphlen, int offset, int limit, struct sctphdr *sh,
3989     struct sockaddr *altsa)
3990 {
3991 	/*
3992 	 * grub through the INIT pulling addresses and
3993 	 * loading them to the nets structure in the asoc.
3994 	 * The from address in the mbuf should also be loaded
3995 	 * (if it is not already). This routine can be called
3996 	 * with either INIT or INIT-ACK's as long as the
3997 	 * m points to the IP packet and the offset points
3998 	 * to the beginning of the parameters.
3999 	 */
4000 	struct sctp_inpcb *inp, *l_inp;
4001 	struct sctp_nets *net, *net_tmp;
4002 	struct ip *iph;
4003 	struct sctp_paramhdr *phdr, parm_buf;
4004 	struct sctp_tcb *stcb_tmp;
4005 	u_int16_t ptype, plen;
4006 	struct sockaddr *sa;
4007 	struct sockaddr_storage dest_store;
4008 	struct sockaddr *local_sa = (struct sockaddr *)&dest_store;
4009 	struct sockaddr_in sin;
4010 	struct sockaddr_in6 sin6;
4011 
4012 	/* First get the destination address setup too. */
4013 	memset(&sin, 0, sizeof(sin));
4014 	memset(&sin6, 0, sizeof(sin6));
4015 
4016 	sin.sin_family = AF_INET;
4017 	sin.sin_len = sizeof(sin);
4018 	sin.sin_port = stcb->rport;
4019 
4020 	sin6.sin6_family = AF_INET6;
4021 	sin6.sin6_len = sizeof(struct sockaddr_in6);
4022 	sin6.sin6_port = stcb->rport;
4023 	if (altsa == NULL) {
4024 		iph = mtod(m, struct ip *);
4025 		if (iph->ip_v == IPVERSION) {
4026 			/* its IPv4 */
4027 			struct sockaddr_in *sin_2;
4028 			sin_2 = (struct sockaddr_in *)(local_sa);
4029 			memset(sin_2, 0, sizeof(sin));
4030 			sin_2->sin_family = AF_INET;
4031 			sin_2->sin_len = sizeof(sin);
4032 			sin_2->sin_port = sh->dest_port;
4033 			sin_2->sin_addr.s_addr = iph->ip_dst.s_addr ;
4034 			sin.sin_addr = iph->ip_src;
4035 			sa = (struct sockaddr *)&sin;
4036 		} else if (iph->ip_v == (IPV6_VERSION >> 4)) {
4037 			/* its IPv6 */
4038 			struct ip6_hdr *ip6;
4039 			struct sockaddr_in6 *sin6_2;
4040 
4041 			ip6 = mtod(m, struct ip6_hdr *);
4042 			sin6_2 = (struct sockaddr_in6 *)(local_sa);
4043 			memset(sin6_2, 0, sizeof(sin6));
4044 			sin6_2->sin6_family = AF_INET6;
4045 			sin6_2->sin6_len = sizeof(struct sockaddr_in6);
4046 			sin6_2->sin6_port = sh->dest_port;
4047 			sin6.sin6_addr = ip6->ip6_src;
4048 			sa = (struct sockaddr *)&sin6;
4049 		} else {
4050 			sa = NULL;
4051 		}
4052 	} else {
4053 		/*
4054 		 * For cookies we use the src address NOT from the packet
4055 		 * but from the original INIT
4056 		 */
4057 		sa = altsa;
4058 	}
4059 	/* Turn off ECN until we get through all params */
4060 	stcb->asoc.ecn_allowed = 0;
4061 
4062 	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
4063 		/* mark all addresses that we have currently on the list */
4064 		net->dest_state |= SCTP_ADDR_NOT_IN_ASSOC;
4065 	}
4066 	/* does the source address already exist? if so skip it */
4067 	l_inp = inp = stcb->sctp_ep;
4068 	stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net_tmp, local_sa, stcb);
4069 	if ((stcb_tmp == NULL && inp == stcb->sctp_ep) || inp == NULL) {
4070 		/* we must add the source address */
4071 		/* no scope set here since we have a tcb already. */
4072 		if ((sa->sa_family == AF_INET) &&
4073 		    (stcb->asoc.ipv4_addr_legal)) {
4074 			if (sctp_add_remote_addr(stcb, sa, 0, 2)) {
4075 				return (-1);
4076 			}
4077 		} else if ((sa->sa_family == AF_INET6) &&
4078 		    (stcb->asoc.ipv6_addr_legal)) {
4079 			if (sctp_add_remote_addr(stcb, sa, 0, 3)) {
4080 				return (-1);
4081 			}
4082 		}
4083 	} else {
4084 		if (net_tmp != NULL && stcb_tmp == stcb) {
4085 			net_tmp->dest_state &= ~SCTP_ADDR_NOT_IN_ASSOC;
4086 		} else if (stcb_tmp != stcb) {
4087 			/* It belongs to another association? */
4088 			return (-1);
4089 		}
4090 	}
4091 	/* since a unlock occured we must check the
4092 	 * TCB's state and the pcb's gone flags.
4093 	 */
4094 	if (l_inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
4095 		/* the user freed the ep */
4096 		return (-1);
4097 	}
4098 	if (stcb->asoc.state == 0) {
4099 		/* the assoc was freed? */
4100 		return (-1);
4101 	}
4102 
4103 	/* now we must go through each of the params. */
4104 	phdr = sctp_get_next_param(m, offset, &parm_buf, sizeof(parm_buf));
4105 	while (phdr) {
4106 		ptype = ntohs(phdr->param_type);
4107 		plen = ntohs(phdr->param_length);
4108 		/*printf("ptype => %d, plen => %d\n", ptype, plen);*/
4109 		if (offset + plen > limit) {
4110 			break;
4111 		}
4112 		if (plen == 0) {
4113 			break;
4114 		}
4115 		if ((ptype == SCTP_IPV4_ADDRESS) &&
4116 		    (stcb->asoc.ipv4_addr_legal)) {
4117 			struct sctp_ipv4addr_param *p4, p4_buf;
4118 			/* ok get the v4 address and check/add */
4119 			phdr = sctp_get_next_param(m, offset,
4120 			    (struct sctp_paramhdr *)&p4_buf, sizeof(p4_buf));
4121 			if (plen != sizeof(struct sctp_ipv4addr_param) ||
4122 			    phdr == NULL) {
4123 				return (-1);
4124 			}
4125 			p4 = (struct sctp_ipv4addr_param *)phdr;
4126 			sin.sin_addr.s_addr = p4->addr;
4127 			sa = (struct sockaddr *)&sin;
4128 			inp = stcb->sctp_ep;
4129 			stcb_tmp = sctp_findassociation_ep_addr(&inp, sa, &net,
4130 			    local_sa, stcb);
4131 
4132 			if ((stcb_tmp== NULL && inp == stcb->sctp_ep) ||
4133 			    inp == NULL) {
4134 				/* we must add the source address */
4135 				/* no scope set since we have a tcb already */
4136 
4137 				/* we must validate the state again here */
4138 				if (l_inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
4139 					/* the user freed the ep */
4140 					return (-1);
4141 				}
4142 				if (stcb->asoc.state == 0) {
4143 					/* the assoc was freed? */
4144 					return (-1);
4145 				}
4146 				if (sctp_add_remote_addr(stcb, sa, 0, 4)) {
4147 					return (-1);
4148 				}
4149 			} else if (stcb_tmp == stcb) {
4150 				if (l_inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
4151 					/* the user freed the ep */
4152 					return (-1);
4153 				}
4154 				if (stcb->asoc.state == 0) {
4155 					/* the assoc was freed? */
4156 					return (-1);
4157 				}
4158 				if (net != NULL) {
4159 					/* clear flag */
4160 					net->dest_state &=
4161 					    ~SCTP_ADDR_NOT_IN_ASSOC;
4162 				}
4163 			} else {
4164 				/* strange, address is in another assoc?
4165 				 * straighten out locks.
4166 				 */
4167 				SCTP_TCB_UNLOCK(stcb_tmp);
4168 				SCTP_INP_RLOCK(inp);
4169 				if (l_inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
4170 					/* the user freed the ep */
4171 					SCTP_INP_RUNLOCK(l_inp);
4172 					return (-1);
4173 				}
4174 				if (stcb->asoc.state == 0) {
4175 					/* the assoc was freed? */
4176 					SCTP_INP_RUNLOCK(l_inp);
4177 					return (-1);
4178 				}
4179 				SCTP_TCB_LOCK(stcb);
4180 				SCTP_INP_RUNLOCK(stcb->sctp_ep);
4181 				return (-1);
4182 			}
4183 		} else if ((ptype == SCTP_IPV6_ADDRESS) &&
4184 		    (stcb->asoc.ipv6_addr_legal)) {
4185 			/* ok get the v6 address and check/add */
4186 			struct sctp_ipv6addr_param *p6, p6_buf;
4187 			phdr = sctp_get_next_param(m, offset,
4188 			    (struct sctp_paramhdr *)&p6_buf, sizeof(p6_buf));
4189 			if (plen != sizeof(struct sctp_ipv6addr_param) ||
4190 			    phdr == NULL) {
4191 				return (-1);
4192 			}
4193 			p6 = (struct sctp_ipv6addr_param *)phdr;
4194 			memcpy((void *)&sin6.sin6_addr, p6->addr,
4195 			    sizeof(p6->addr));
4196 			sa = (struct sockaddr *)&sin6;
4197 			inp = stcb->sctp_ep;
4198 			stcb_tmp= sctp_findassociation_ep_addr(&inp, sa, &net,
4199 			    local_sa, stcb);
4200 			if (stcb_tmp == NULL && (inp == stcb->sctp_ep ||
4201 			    inp == NULL)) {
4202 				/* we must validate the state again here */
4203 				if (l_inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
4204 					/* the user freed the ep */
4205 					return (-1);
4206 				}
4207 				if (stcb->asoc.state == 0) {
4208 					/* the assoc was freed? */
4209 					return (-1);
4210 				}
4211 				/* we must add the address, no scope set */
4212 				if (sctp_add_remote_addr(stcb, sa, 0, 5)) {
4213 					return (-1);
4214 				}
4215 			} else if (stcb_tmp == stcb) {
4216 				/* we must validate the state again here */
4217 				if (l_inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
4218 					/* the user freed the ep */
4219 					return (-1);
4220 				}
4221 				if (stcb->asoc.state == 0) {
4222 					/* the assoc was freed? */
4223 					return (-1);
4224 				}
4225 				if (net != NULL) {
4226 					/* clear flag */
4227 					net->dest_state &=
4228 					    ~SCTP_ADDR_NOT_IN_ASSOC;
4229 				}
4230 			} else {
4231 				/* strange, address is in another assoc?
4232 				 * straighten out locks.
4233 				 */
4234 				SCTP_TCB_UNLOCK(stcb_tmp);
4235 				SCTP_INP_RLOCK(l_inp);
4236 				/* we must validate the state again here */
4237 				if (l_inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
4238 					/* the user freed the ep */
4239 					SCTP_INP_RUNLOCK(l_inp);
4240 					return (-1);
4241 				}
4242 				if (stcb->asoc.state == 0) {
4243 					/* the assoc was freed? */
4244 					SCTP_INP_RUNLOCK(l_inp);
4245 					return (-1);
4246 				}
4247 				SCTP_TCB_LOCK(stcb);
4248 				SCTP_INP_RUNLOCK(l_inp);
4249 				return (-1);
4250 			}
4251 		} else if (ptype == SCTP_ECN_CAPABLE) {
4252 			stcb->asoc.ecn_allowed = 1;
4253 		} else if (ptype == SCTP_ULP_ADAPTION) {
4254 			if (stcb->asoc.state != SCTP_STATE_OPEN) {
4255 				struct sctp_adaption_layer_indication ai, *aip;
4256 
4257 				phdr = sctp_get_next_param(m, offset,
4258 							   (struct sctp_paramhdr *)&ai, sizeof(ai));
4259 				aip = (struct sctp_adaption_layer_indication *)phdr;
4260 				sctp_ulp_notify(SCTP_NOTIFY_ADAPTION_INDICATION,
4261 						stcb, ntohl(aip->indication), NULL);
4262 			}
4263 		} else if (ptype == SCTP_SET_PRIM_ADDR) {
4264 			struct sctp_asconf_addr_param lstore, *fee;
4265 			struct sctp_asconf_addrv4_param *fii;
4266 			int lptype;
4267 			struct sockaddr *lsa = NULL;
4268 
4269 			stcb->asoc.peer_supports_asconf = 1;
4270 			stcb->asoc.peer_supports_asconf_setprim = 1;
4271 			if (plen > sizeof(lstore)) {
4272 				return (-1);
4273 			}
4274 			phdr = sctp_get_next_param(m, offset,
4275     			    (struct sctp_paramhdr *)&lstore, plen);
4276 			if (phdr == NULL) {
4277 				return (-1);
4278 			}
4279 
4280 			fee  = (struct sctp_asconf_addr_param *)phdr;
4281 			lptype = ntohs(fee->addrp.ph.param_type);
4282 			if (lptype == SCTP_IPV4_ADDRESS) {
4283 				if (plen !=
4284 				    sizeof(struct sctp_asconf_addrv4_param)) {
4285 					printf("Sizeof setprim in init/init ack not %d but %d - ignored\n",
4286 				           (int)sizeof(struct sctp_asconf_addrv4_param),
4287 				           plen);
4288 				} else {
4289 					fii = (struct sctp_asconf_addrv4_param *)fee;
4290 					sin.sin_addr.s_addr = fii->addrp.addr;
4291 					lsa = (struct sockaddr *)&sin;
4292 				}
4293 			} else if (lptype == SCTP_IPV6_ADDRESS) {
4294 				if (plen !=
4295 				    sizeof(struct sctp_asconf_addr_param)) {
4296 					printf("Sizeof setprim (v6) in init/init ack not %d but %d - ignored\n",
4297 				           (int)sizeof(struct sctp_asconf_addr_param),
4298 				           plen);
4299 				} else {
4300 					memcpy(sin6.sin6_addr.s6_addr,
4301 					    fee->addrp.addr,
4302 					    sizeof(fee->addrp.addr));
4303 					lsa = (struct sockaddr *)&sin6;
4304 				}
4305 			}
4306 			if (lsa) {
4307 				sctp_set_primary_addr(stcb, sa, NULL);
4308 			}
4309 
4310 		} else if (ptype == SCTP_PRSCTP_SUPPORTED) {
4311 			/* Peer supports pr-sctp */
4312 			stcb->asoc.peer_supports_prsctp = 1;
4313 		} else if (ptype == SCTP_SUPPORTED_CHUNK_EXT) {
4314 			/* A supported extension chunk */
4315 			struct sctp_supported_chunk_types_param *pr_supported;
4316 			uint8_t local_store[128];
4317 			int num_ent, i;
4318 
4319 			phdr = sctp_get_next_param(m, offset,
4320     			    (struct sctp_paramhdr *)&local_store, plen);
4321 			if (phdr == NULL) {
4322 				return (-1);
4323 			}
4324 			stcb->asoc.peer_supports_asconf = 0;
4325 			stcb->asoc.peer_supports_asconf_setprim = 0;
4326 			stcb->asoc.peer_supports_prsctp = 0;
4327 			stcb->asoc.peer_supports_pktdrop = 0;
4328 			stcb->asoc.peer_supports_strreset = 0;
4329 			pr_supported = (struct sctp_supported_chunk_types_param *)phdr;
4330 			num_ent = plen - sizeof(struct sctp_paramhdr);
4331 			for (i=0; i<num_ent; i++) {
4332 				switch (pr_supported->chunk_types[i]) {
4333 				case SCTP_ASCONF:
4334 					stcb->asoc.peer_supports_asconf = 1;
4335 					stcb->asoc.peer_supports_asconf_setprim = 1;
4336 					break;
4337 				case SCTP_ASCONF_ACK:
4338 					stcb->asoc.peer_supports_asconf = 1;
4339 					stcb->asoc.peer_supports_asconf_setprim = 1;
4340 					break;
4341 				case SCTP_FORWARD_CUM_TSN:
4342 					stcb->asoc.peer_supports_prsctp = 1;
4343 					break;
4344 				case SCTP_PACKET_DROPPED:
4345 					stcb->asoc.peer_supports_pktdrop = 1;
4346 					break;
4347 				case SCTP_STREAM_RESET:
4348 					stcb->asoc.peer_supports_strreset = 1;
4349 					break;
4350 				default:
4351 					/* one I have not learned yet */
4352 					break;
4353 
4354 				}
4355 			}
4356 		} else if (ptype == SCTP_ECN_NONCE_SUPPORTED) {
4357 			/* Peer supports ECN-nonce */
4358 			stcb->asoc.peer_supports_ecn_nonce = 1;
4359 			stcb->asoc.ecn_nonce_allowed = 1;
4360 		} else if ((ptype == SCTP_HEARTBEAT_INFO) ||
4361 			   (ptype == SCTP_STATE_COOKIE) ||
4362 			   (ptype == SCTP_UNRECOG_PARAM) ||
4363 			   (ptype == SCTP_COOKIE_PRESERVE) ||
4364 			   (ptype == SCTP_SUPPORTED_ADDRTYPE) ||
4365 			   (ptype == SCTP_ADD_IP_ADDRESS) ||
4366 			   (ptype == SCTP_DEL_IP_ADDRESS) ||
4367 			   (ptype == SCTP_ERROR_CAUSE_IND) ||
4368 			   (ptype == SCTP_SUCCESS_REPORT)) {
4369 			/* don't care */;
4370 		} else {
4371 			if ((ptype & 0x8000) == 0x0000) {
4372 				/* must stop processing the rest of
4373 				 * the param's. Any report bits were
4374 				 * handled with the call to sctp_arethere_unrecognized_parameters()
4375 				 * when the INIT or INIT-ACK was first seen.
4376 				 */
4377 				break;
4378 			}
4379 		}
4380 		offset += SCTP_SIZE32(plen);
4381 		if (offset >= limit) {
4382 			break;
4383 		}
4384 		phdr = sctp_get_next_param(m, offset, &parm_buf,
4385 		    sizeof(parm_buf));
4386 	}
4387 	/* Now check to see if we need to purge any addresses */
4388 	for (net = TAILQ_FIRST(&stcb->asoc.nets); net != NULL; net = net_tmp) {
4389 		net_tmp = TAILQ_NEXT(net, sctp_next);
4390 		if ((net->dest_state & SCTP_ADDR_NOT_IN_ASSOC) ==
4391 		    SCTP_ADDR_NOT_IN_ASSOC) {
4392 			/* This address has been removed from the asoc */
4393 			/* remove and free it */
4394 			stcb->asoc.numnets--;
4395 			TAILQ_REMOVE(&stcb->asoc.nets, net, sctp_next);
4396 			sctp_free_remote_addr(net);
4397 			if (net == stcb->asoc.primary_destination) {
4398 				stcb->asoc.primary_destination = NULL;
4399 				sctp_select_primary_destination(stcb);
4400 			}
4401 		}
4402 	}
4403 	return (0);
4404 }
4405 
4406 int
4407 sctp_set_primary_addr(struct sctp_tcb *stcb, struct sockaddr *sa,
4408     struct sctp_nets *net)
4409 {
4410 	/* make sure the requested primary address exists in the assoc */
4411 	if (net == NULL && sa)
4412 		net = sctp_findnet(stcb, sa);
4413 
4414 	if (net == NULL) {
4415 		/* didn't find the requested primary address! */
4416 		return (-1);
4417 	} else {
4418 		/* set the primary address */
4419 		if (net->dest_state & SCTP_ADDR_UNCONFIRMED) {
4420 			/* Must be confirmed */
4421 			return (-1);
4422 		}
4423 		stcb->asoc.primary_destination = net;
4424 		net->dest_state &= ~SCTP_ADDR_WAS_PRIMARY;
4425 		return (0);
4426 	}
4427 }
4428 
4429 
4430 int
4431 sctp_is_vtag_good(struct sctp_inpcb *inp, u_int32_t tag, struct timeval *now)
4432 {
4433 	/*
4434 	 * This function serves two purposes. It will see if a TAG can be
4435 	 * re-used and return 1 for yes it is ok and 0 for don't use that
4436 	 * tag.
4437 	 * A secondary function it will do is purge out old tags that can
4438 	 * be removed.
4439 	 */
4440 	struct sctpasochead *head;
4441 	struct sctpvtaghead *chain;
4442 	struct sctp_tagblock *twait_block;
4443 	struct sctp_tcb *stcb;
4444 
4445 	int i;
4446 	SCTP_INP_INFO_WLOCK();
4447 	chain = &sctppcbinfo.vtag_timewait[(tag % SCTP_STACK_VTAG_HASH_SIZE)];
4448 	/* First is the vtag in use ? */
4449 
4450 	head = &sctppcbinfo.sctp_asochash[SCTP_PCBHASH_ASOC(tag,
4451 	    sctppcbinfo.hashasocmark)];
4452 	if (head == NULL) {
4453 		SCTP_INP_INFO_WUNLOCK();
4454 		return (0);
4455 	}
4456 	LIST_FOREACH(stcb, head, sctp_asocs) {
4457 		if (stcb->asoc.my_vtag == tag) {
4458 			/* We should remove this if and
4459 			 * return 0 always if we want vtags
4460 			 * unique across all endpoints. For
4461 			 * now within a endpoint is ok.
4462 			 */
4463  			if (inp == stcb->sctp_ep) {
4464 				/* bad tag, in use */
4465 				SCTP_INP_INFO_WUNLOCK();
4466 				return (0);
4467 			}
4468 		}
4469 	}
4470 	if (!LIST_EMPTY(chain)) {
4471 		/*
4472 		 * Block(s) are present, lets see if we have this tag in
4473 		 * the list
4474 		 */
4475 		LIST_FOREACH(twait_block, chain, sctp_nxt_tagblock) {
4476 			for (i = 0; i < SCTP_NUMBER_IN_VTAG_BLOCK; i++) {
4477 				if (twait_block->vtag_block[i].v_tag == 0) {
4478 					/* not used */
4479 					continue;
4480 				} else if ((long)twait_block->vtag_block[i].tv_sec_at_expire >
4481 				    now->tv_sec) {
4482 					/* Audit expires this guy */
4483 					twait_block->vtag_block[i].tv_sec_at_expire = 0;
4484 					twait_block->vtag_block[i].v_tag = 0;
4485 				} else if (twait_block->vtag_block[i].v_tag ==
4486 				    tag) {
4487 					/* Bad tag, sorry :< */
4488 					SCTP_INP_INFO_WUNLOCK();
4489 					return (0);
4490 				}
4491 			}
4492 		}
4493 	}
4494 	/* Not found, ok to use the tag */
4495 	SCTP_INP_INFO_WUNLOCK();
4496 	return (1);
4497 }
4498 
4499 
4500 /*
4501  * Delete the address from the endpoint local address list
4502  * Lookup using a sockaddr address (ie. not an ifaddr)
4503  */
4504 int
4505 sctp_del_local_addr_ep_sa(struct sctp_inpcb *inp, struct sockaddr *sa)
4506 {
4507 	struct sctp_laddr *laddr;
4508 	struct sockaddr *l_sa;
4509 	int found = 0;
4510 	/* Here is another function I cannot find a
4511 	 * caller for. As such we SHOULD delete it
4512 	 * if we have no users. If we find a user that
4513 	 * user MUST have the INP locked.
4514 	 *
4515 	 */
4516 
4517 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
4518 		/* You are already bound to all. You have it already */
4519 		return (EINVAL);
4520 	}
4521 
4522 	LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
4523 		/* make sure the address exists */
4524 		if (laddr->ifa == NULL)
4525 			continue;
4526 		if (laddr->ifa->ifa_addr == NULL)
4527 			continue;
4528 
4529 		l_sa = laddr->ifa->ifa_addr;
4530 		if (l_sa->sa_family == AF_INET6) {
4531 			/* IPv6 address */
4532 			struct sockaddr_in6 *sin1, *sin2;
4533 			sin1 = (struct sockaddr_in6 *)l_sa;
4534 			sin2 = (struct sockaddr_in6 *)sa;
4535 			if (memcmp(&sin1->sin6_addr, &sin2->sin6_addr,
4536 			    sizeof(struct in6_addr)) == 0) {
4537 				/* matched */
4538 				found = 1;
4539 				break;
4540 			}
4541 		} else if (l_sa->sa_family == AF_INET) {
4542 			/* IPv4 address */
4543 			struct sockaddr_in *sin1, *sin2;
4544 			sin1 = (struct sockaddr_in *)l_sa;
4545 			sin2 = (struct sockaddr_in *)sa;
4546 			if (sin1->sin_addr.s_addr == sin2->sin_addr.s_addr) {
4547 				/* matched */
4548 				found = 1;
4549 				break;
4550 			}
4551 		} else {
4552 			/* invalid family */
4553 			return (-1);
4554 		}
4555 	}
4556 
4557 	if (found && inp->laddr_count < 2) {
4558 		/* can't delete unless there are at LEAST 2 addresses */
4559 		return (-1);
4560 	}
4561 
4562 	if (found && (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) == 0) {
4563 		/*
4564 		 * remove it from the ep list, this should NOT be
4565 		 * done until its really gone from the interface list and
4566 		 * we won't be receiving more of these. Probably right
4567 		 * away. If we do allow a removal of an address from
4568 		 * an association (sub-set bind) than this should NOT
4569 		 * be called until the all ASCONF come back from this
4570 		 * association.
4571 		 */
4572 		sctp_remove_laddr(laddr);
4573 		return (0);
4574 	} else {
4575 		return (-1);
4576 	}
4577 }
4578 
4579 static void
4580 sctp_drain_mbufs(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
4581 {
4582 	/*
4583 	 * We must hunt this association for MBUF's past the cumack
4584 	 * (i.e. out of order data that we can renege on).
4585 	 */
4586 	struct sctp_association *asoc;
4587 	struct sctp_tmit_chunk *chk, *nchk;
4588 	u_int32_t cumulative_tsn_p1, tsn;
4589 	int cnt, strmat, gap;
4590 	/* We look for anything larger than the cum-ack + 1 */
4591 
4592 	asoc = &stcb->asoc;
4593 	cumulative_tsn_p1 = asoc->cumulative_tsn + 1;
4594 	cnt = 0;
4595 	/* First look in the re-assembly queue */
4596 	chk = TAILQ_FIRST(&asoc->reasmqueue);
4597 	while (chk) {
4598 		/* Get the next one */
4599 		nchk = TAILQ_NEXT(chk, sctp_next);
4600 		if (compare_with_wrap(chk->rec.data.TSN_seq,
4601 		    cumulative_tsn_p1, MAX_TSN)) {
4602 			/* Yep it is above cum-ack */
4603 			cnt++;
4604 			tsn = chk->rec.data.TSN_seq;
4605 			if (tsn >= asoc->mapping_array_base_tsn) {
4606 				gap  = tsn - asoc->mapping_array_base_tsn;
4607 			} else {
4608 				gap = (MAX_TSN - asoc->mapping_array_base_tsn) +
4609 				    tsn + 1;
4610 			}
4611 			asoc->size_on_reasm_queue -= chk->send_size;
4612 			asoc->cnt_on_reasm_queue--;
4613 			SCTP_UNSET_TSN_PRESENT(asoc->mapping_array, gap);
4614 			TAILQ_REMOVE(&asoc->reasmqueue, chk, sctp_next);
4615 			if (chk->data) {
4616 				sctp_m_freem(chk->data);
4617 				chk->data = NULL;
4618 			}
4619 			SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
4620 			sctppcbinfo.ipi_count_chunk--;
4621 			if ((int)sctppcbinfo.ipi_count_chunk < 0) {
4622 				panic("Chunk count is negative");
4623 			}
4624 			sctppcbinfo.ipi_gencnt_chunk++;
4625 		}
4626 		chk = nchk;
4627 	}
4628 	/* Ok that was fun, now we will drain all the inbound streams? */
4629 	for (strmat = 0; strmat < asoc->streamincnt; strmat++) {
4630 		chk = TAILQ_FIRST(&asoc->strmin[strmat].inqueue);
4631 		while (chk) {
4632 			nchk = TAILQ_NEXT(chk, sctp_next);
4633 			if (compare_with_wrap(chk->rec.data.TSN_seq,
4634 			    cumulative_tsn_p1, MAX_TSN)) {
4635 				/* Yep it is above cum-ack */
4636 				cnt++;
4637 				tsn = chk->rec.data.TSN_seq;
4638 				if (tsn >= asoc->mapping_array_base_tsn) {
4639 					gap = tsn -
4640 					    asoc->mapping_array_base_tsn;
4641 				} else {
4642 					gap = (MAX_TSN -
4643 					    asoc->mapping_array_base_tsn) +
4644 					    tsn + 1;
4645 				}
4646 				asoc->size_on_all_streams -= chk->send_size;
4647 				asoc->cnt_on_all_streams--;
4648 
4649 				SCTP_UNSET_TSN_PRESENT(asoc->mapping_array,
4650 				    gap);
4651 				TAILQ_REMOVE(&asoc->strmin[strmat].inqueue,
4652 				    chk, sctp_next);
4653 				if (chk->data) {
4654 					sctp_m_freem(chk->data);
4655 					chk->data = NULL;
4656 				}
4657 				SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
4658 				sctppcbinfo.ipi_count_chunk--;
4659 				if ((int)sctppcbinfo.ipi_count_chunk < 0) {
4660 					panic("Chunk count is negative");
4661 				}
4662 				sctppcbinfo.ipi_gencnt_chunk++;
4663 			}
4664 			chk = nchk;
4665 		}
4666 	}
4667 	/*
4668 	 * Question, should we go through the delivery queue?
4669 	 * The only reason things are on here is the app not reading OR a
4670 	 * p-d-api up. An attacker COULD send enough in to initiate the
4671 	 * PD-API and then send a bunch of stuff to other streams... these
4672 	 * would wind up on the delivery queue.. and then we would not get
4673 	 * to them. But in order to do this I then have to back-track and
4674 	 * un-deliver sequence numbers in streams.. el-yucko. I think for
4675 	 * now we will NOT look at the delivery queue and leave it to be
4676 	 * something to consider later. An alternative would be to abort
4677 	 * the P-D-API with a notification and then deliver the data....
4678 	 * Or another method might be to keep track of how many times the
4679 	 * situation occurs and if we see a possible attack underway just
4680 	 * abort the association.
4681 	 */
4682 #ifdef SCTP_DEBUG
4683 	if (sctp_debug_on & SCTP_DEBUG_PCB1) {
4684 		if (cnt) {
4685 			printf("Freed %d chunks from reneg harvest\n", cnt);
4686 		}
4687 	}
4688 #endif /* SCTP_DEBUG */
4689 
4690 	/*
4691 	 * Another issue, in un-setting the TSN's in the mapping array we
4692 	 * DID NOT adjust the higest_tsn marker.  This will cause one of
4693 	 * two things to occur. It may cause us to do extra work in checking
4694 	 * for our mapping array movement. More importantly it may cause us
4695 	 * to SACK every datagram. This may not be a bad thing though since
4696 	 * we will recover once we get our cum-ack above and all this stuff
4697 	 * we dumped recovered.
4698 	 */
4699 }
4700 
4701 void
4702 sctp_drain(void)
4703 {
4704 	/*
4705 	 * We must walk the PCB lists for ALL associations here. The system
4706 	 * is LOW on MBUF's and needs help. This is where reneging will
4707 	 * occur. We really hope this does NOT happen!
4708 	 */
4709 	struct sctp_inpcb *inp;
4710 	struct sctp_tcb *stcb;
4711 
4712 	SCTP_INP_INFO_RLOCK();
4713 	LIST_FOREACH(inp, &sctppcbinfo.listhead, sctp_list) {
4714 		/* For each endpoint */
4715 		SCTP_INP_RLOCK(inp);
4716 		LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
4717 			/* For each association */
4718 			SCTP_TCB_LOCK(stcb);
4719 			sctp_drain_mbufs(inp, stcb);
4720 			SCTP_TCB_UNLOCK(stcb);
4721 		}
4722 		SCTP_INP_RUNLOCK(inp);
4723 	}
4724 	SCTP_INP_INFO_RUNLOCK();
4725 }
4726 
4727 int
4728 sctp_add_to_socket_q(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
4729 {
4730 	struct sctp_socket_q_list *sq;
4731 
4732 	/* write lock on INP assumed */
4733 	if ((inp == NULL) || (stcb == NULL)) {
4734 		/* I am paranoid */
4735 		return (0);
4736 	}
4737 	sq = (struct sctp_socket_q_list *)SCTP_ZONE_GET(
4738 	    sctppcbinfo.ipi_zone_sockq);
4739 	if (sq == NULL) {
4740 		/* out of sq structs */
4741 		return (0);
4742 	}
4743 	sctppcbinfo.ipi_count_sockq++;
4744 	sctppcbinfo.ipi_gencnt_sockq++;
4745 	if (stcb)
4746 		stcb->asoc.cnt_msg_on_sb++;
4747 	sq->tcb = stcb;
4748 	TAILQ_INSERT_TAIL(&inp->sctp_queue_list, sq, next_sq);
4749 	return (1);
4750 }
4751 
4752 
4753 struct sctp_tcb *
4754 sctp_remove_from_socket_q(struct sctp_inpcb *inp)
4755 {
4756 	struct sctp_tcb *stcb = NULL;
4757 	struct sctp_socket_q_list *sq;
4758 
4759 	/* W-Lock on INP assumed held */
4760 	sq = TAILQ_FIRST(&inp->sctp_queue_list);
4761 	if (sq == NULL)
4762 		return (NULL);
4763 
4764 	stcb = sq->tcb;
4765 	TAILQ_REMOVE(&inp->sctp_queue_list, sq, next_sq);
4766 	SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_sockq, sq);
4767 	sctppcbinfo.ipi_count_sockq--;
4768 	sctppcbinfo.ipi_gencnt_sockq++;
4769 	if (stcb) {
4770 		stcb->asoc.cnt_msg_on_sb--;
4771 	}
4772 	return (stcb);
4773 }
4774 
4775 int
4776 sctp_initiate_iterator(asoc_func af, uint32_t pcb_state, uint32_t asoc_state,
4777 		       void *argp, uint32_t argi, end_func ef,
4778 		       struct sctp_inpcb *s_inp)
4779 {
4780 	struct sctp_iterator *it=NULL;
4781 	int s;
4782 	if (af == NULL) {
4783 		return (-1);
4784 	}
4785 	it = malloc(sizeof(struct sctp_iterator), M_PCB, M_WAITOK);
4786 	if (it == NULL) {
4787 		return (ENOMEM);
4788 	}
4789 	memset(it, 0, sizeof(*it));
4790 	it->function_toapply = af;
4791 	it->function_atend = ef;
4792 	it->pointer = argp;
4793 	it->val = argi;
4794 	it->pcb_flags = pcb_state;
4795 	it->asoc_state = asoc_state;
4796 	if (s_inp) {
4797 		it->inp = s_inp;
4798 		it->iterator_flags = SCTP_ITERATOR_DO_SINGLE_INP;
4799 	} else {
4800 		SCTP_INP_INFO_RLOCK();
4801 		it->inp = LIST_FIRST(&sctppcbinfo.listhead);
4802 		SCTP_INP_INFO_RUNLOCK();
4803 		it->iterator_flags = SCTP_ITERATOR_DO_ALL_INP;
4804 
4805 	}
4806 	/* Init the timer */
4807 	callout_init(&it->tmr.timer, 0);
4808 	/* add to the list of all iterators */
4809 	SCTP_INP_INFO_WLOCK();
4810 	LIST_INSERT_HEAD(&sctppcbinfo.iteratorhead, it, sctp_nxt_itr);
4811 	SCTP_INP_INFO_WUNLOCK();
4812 	s = splsoftnet();
4813 	sctp_iterator_timer(it);
4814 	splx(s);
4815 	return (0);
4816 }
4817 
4818 
4819