xref: /netbsd-src/sys/netinet/sctp_output.c (revision 0e2e28bced52bda3788c857106bde6c44d2df3b8)
1 /*	$NetBSD: sctp_output.c,v 1.35 2024/02/09 22:08:37 andvar Exp $ */
2 /*	$KAME: sctp_output.c,v 1.48 2005/06/16 18:29:24 jinmei Exp $	*/
3 
4 /*
5  * Copyright (C) 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. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 #include <sys/cdefs.h>
33 __KERNEL_RCSID(0, "$NetBSD: sctp_output.c,v 1.35 2024/02/09 22:08:37 andvar Exp $");
34 
35 #ifdef _KERNEL_OPT
36 #include "opt_ipsec.h"
37 #include "opt_inet.h"
38 #include "opt_sctp.h"
39 #endif /* _KERNEL_OPT */
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/malloc.h>
44 #include <sys/mbuf.h>
45 #include <sys/domain.h>
46 #include <sys/protosw.h>
47 #include <sys/socket.h>
48 #include <sys/socketvar.h>
49 #include <sys/proc.h>
50 #include <sys/kernel.h>
51 #include <sys/sysctl.h>
52 #include <sys/resourcevar.h>
53 #include <sys/uio.h>
54 #ifdef INET6
55 #include <sys/domain.h>
56 #endif
57 
58 #include <machine/limits.h>
59 #include <machine/cpu.h>
60 
61 #include <net/if.h>
62 #include <net/if_types.h>
63 
64 #include <net/route.h>
65 
66 #include <netinet/in.h>
67 #include <netinet/in_systm.h>
68 #include <netinet/ip.h>
69 #include <netinet/in_pcb.h>
70 #include <netinet/in_var.h>
71 #include <netinet/ip_var.h>
72 
73 #ifdef INET6
74 #include <netinet/ip6.h>
75 #include <netinet6/ip6_var.h>
76 #include <netinet6/scope6_var.h>
77 #include <netinet6/nd6.h>
78 
79 #include <netinet6/in6_pcb.h>
80 
81 #include <netinet/icmp6.h>
82 
83 #endif /* INET6 */
84 
85 #if defined(HAVE_NRL_INPCB) || defined(__FreeBSD__)
86 #ifndef in6pcb
87 #define in6pcb		inpcb
88 #endif
89 #endif
90 
91 #include <netinet/sctp_pcb.h>
92 
93 #ifdef IPSEC
94 #include <netipsec/ipsec.h>
95 #include <netipsec/key.h>
96 #endif /* IPSEC */
97 
98 #include <netinet/sctp_var.h>
99 #include <netinet/sctp_header.h>
100 #include <netinet/sctputil.h>
101 #include <netinet/sctp_pcb.h>
102 #include <netinet/sctp_output.h>
103 #include <netinet/sctp_uio.h>
104 #include <netinet/sctputil.h>
105 #include <netinet/sctp_hashdriver.h>
106 #include <netinet/sctp_timer.h>
107 #include <netinet/sctp_asconf.h>
108 #include <netinet/sctp_indata.h>
109 
110 #ifdef SCTP_DEBUG
111 extern uint32_t sctp_debug_on;
112 #endif
113 
114 extern int sctp_peer_chunk_oh;
115 
116 static int
117 sctp_find_cmsg(int c_type, void *data, struct mbuf *control, int cpsize)
118 {
119 	struct cmsghdr cmh;
120 	int tlen, at;
121 
122 	tlen = control->m_len;
123 	at = 0;
124 	/*
125 	 * Independent of how many mbufs, find the c_type inside the control
126 	 * structure and copy out the data.
127 	 */
128 	while (at < tlen) {
129 		if ((tlen-at) < (int)CMSG_ALIGN(sizeof(cmh))) {
130 			/* not enough room for one more we are done. */
131 			return (0);
132 		}
133 		m_copydata(control, at, sizeof(cmh), (void *)&cmh);
134 		if ((cmh.cmsg_len + at) > tlen) {
135 			/*
136 			 * this is real messed up since there is not enough
137 			 * data here to cover the cmsg header. We are done.
138 			 */
139 			return (0);
140 		}
141 		if ((cmh.cmsg_level == IPPROTO_SCTP) &&
142 		    (c_type == cmh.cmsg_type)) {
143 			/* found the one we want, copy it out */
144 			at += CMSG_ALIGN(sizeof(struct cmsghdr));
145 			if ((int)(cmh.cmsg_len - CMSG_ALIGN(sizeof(struct cmsghdr))) < cpsize) {
146 				/*
147 				 * space of cmsg_len after header not
148 				 * big enough
149 				 */
150 				return (0);
151 			}
152 			m_copydata(control, at, cpsize, data);
153 			return (1);
154 		 } else {
155 			at += CMSG_ALIGN(cmh.cmsg_len);
156 			if (cmh.cmsg_len == 0) {
157 				break;
158 			}
159 		}
160 	}
161 	/* not found */
162 	return (0);
163 }
164 
165 static struct mbuf *
166 sctp_add_addr_to_mbuf(struct mbuf *m, struct ifaddr *ifa)
167 {
168 	struct sctp_paramhdr *parmh;
169 	struct mbuf *mret;
170 	int len;
171 	if (ifa->ifa_addr->sa_family == AF_INET) {
172 		len = sizeof(struct sctp_ipv4addr_param);
173 	} else if (ifa->ifa_addr->sa_family == AF_INET6) {
174 		len = sizeof(struct sctp_ipv6addr_param);
175 	} else {
176 		/* unknown type */
177 		return (m);
178 	}
179 
180 	if (M_TRAILINGSPACE(m) >= len) {
181 		/* easy side we just drop it on the end */
182 		parmh = (struct sctp_paramhdr *)(m->m_data + m->m_len);
183 		mret = m;
184 	} else {
185 		/* Need more space */
186 		mret = m;
187 		while (mret->m_next != NULL) {
188 			mret = mret->m_next;
189 		}
190 		MGET(mret->m_next, M_DONTWAIT, MT_DATA);
191 		if (mret->m_next == NULL) {
192 			/* We are hosed, can't add more addresses */
193 			return (m);
194 		}
195 		mret = mret->m_next;
196 		parmh = mtod(mret, struct sctp_paramhdr *);
197 	}
198 	/* now add the parameter */
199 	if (ifa->ifa_addr->sa_family == AF_INET) {
200 		struct sctp_ipv4addr_param *ipv4p;
201 		struct sockaddr_in *sin;
202 		sin = (struct sockaddr_in *)ifa->ifa_addr;
203 		ipv4p = (struct sctp_ipv4addr_param *)parmh;
204 		parmh->param_type = htons(SCTP_IPV4_ADDRESS);
205 		parmh->param_length = htons(len);
206 		ipv4p->addr = sin->sin_addr.s_addr;
207 		mret->m_len += len;
208 	} else if (ifa->ifa_addr->sa_family == AF_INET6) {
209 		struct sctp_ipv6addr_param *ipv6p;
210 		struct sockaddr_in6 *sin6;
211 		sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
212 		ipv6p = (struct sctp_ipv6addr_param *)parmh;
213 		parmh->param_type = htons(SCTP_IPV6_ADDRESS);
214 		parmh->param_length = htons(len);
215 		memcpy(ipv6p->addr, &sin6->sin6_addr,
216 		    sizeof(ipv6p->addr));
217 		/* clear embedded scope in the address */
218 		in6_clearscope((struct in6_addr *)ipv6p->addr);
219 		mret->m_len += len;
220 	} else {
221 		return (m);
222 	}
223 	return (mret);
224 }
225 
226 
227 
228 static struct mbuf *
229 sctp_add_cookie(struct sctp_inpcb *inp, struct mbuf *init, int init_offset,
230     struct mbuf *initack, int initack_offset, struct sctp_state_cookie *stc_in)
231 {
232 	struct mbuf *copy_init, *copy_initack, *m_at, *sig, *mret;
233 	struct sctp_state_cookie *stc;
234 	struct sctp_paramhdr *ph;
235 	uint8_t *signature;
236 	int sig_offset;
237 	uint16_t cookie_sz;
238 
239 	mret = NULL;
240 
241 	MGET(mret, M_DONTWAIT, MT_DATA);
242 	if (mret == NULL) {
243 		return (NULL);
244 	}
245 	copy_init = sctp_m_copym(init, init_offset, M_COPYALL, M_DONTWAIT);
246 	if (copy_init == NULL) {
247 		sctp_m_freem(mret);
248 		return (NULL);
249 	}
250 	copy_initack = sctp_m_copym(initack, initack_offset, M_COPYALL,
251 	    M_DONTWAIT);
252 	if (copy_initack == NULL) {
253 		sctp_m_freem(mret);
254 		sctp_m_freem(copy_init);
255 		return (NULL);
256 	}
257 	/* easy side we just drop it on the end */
258 	ph = mtod(mret, struct sctp_paramhdr *);
259 	mret->m_len = sizeof(struct sctp_state_cookie) +
260 	    sizeof(struct sctp_paramhdr);
261 	stc = (struct sctp_state_cookie *)((vaddr_t)ph +
262 	    sizeof(struct sctp_paramhdr));
263 	ph->param_type = htons(SCTP_STATE_COOKIE);
264 	ph->param_length = 0;	/* fill in at the end */
265 	/* Fill in the stc cookie data */
266 	*stc = *stc_in;
267 
268 	/* tack the INIT and then the INIT-ACK onto the chain */
269 	cookie_sz = 0;
270 	m_at = mret;
271 	for (m_at = mret; m_at; m_at = m_at->m_next) {
272 		cookie_sz += m_at->m_len;
273 		if (m_at->m_next == NULL) {
274 			m_at->m_next = copy_init;
275 			break;
276 		}
277 	}
278 
279 	for (m_at = copy_init; m_at; m_at = m_at->m_next) {
280 		cookie_sz += m_at->m_len;
281 		if (m_at->m_next == NULL) {
282 			m_at->m_next = copy_initack;
283 			break;
284 		}
285 	}
286 
287 	for (m_at = copy_initack; m_at; m_at = m_at->m_next) {
288 		cookie_sz += m_at->m_len;
289 		if (m_at->m_next == NULL) {
290 			break;
291 		}
292 	}
293 	MGET(sig, M_DONTWAIT, MT_DATA);
294 	if (sig == NULL) {
295 		/* no space */
296 		sctp_m_freem(mret);
297 		sctp_m_freem(copy_init);
298 		sctp_m_freem(copy_initack);
299 		return (NULL);
300 	}
301 	sig->m_len = 0;
302 	m_at->m_next = sig;
303 	sig_offset = 0;
304 	signature = (uint8_t *)(mtod(sig, vaddr_t) + sig_offset);
305 	/* Time to sign the cookie */
306 	sctp_hash_digest_m((char *)inp->sctp_ep.secret_key[
307 	    (int)(inp->sctp_ep.current_secret_number)],
308 	    SCTP_SECRET_SIZE, mret, sizeof(struct sctp_paramhdr),
309 	    (uint8_t *)signature);
310 	sig->m_len += SCTP_SIGNATURE_SIZE;
311 	cookie_sz += SCTP_SIGNATURE_SIZE;
312 
313 	ph->param_length = htons(cookie_sz);
314 	return (mret);
315 }
316 
317 
318 static struct sockaddr_in *
319 sctp_is_v4_ifa_addr_prefered (struct ifaddr *ifa, uint8_t loopscope, uint8_t ipv4_scope, uint8_t *sin_loop, uint8_t *sin_local)
320 {
321 	struct sockaddr_in *sin;
322 	/*
323 	 * Here we determine if its a prefered address. A
324 	 * prefered address means it is the same scope or
325 	 * higher scope then the destination.
326 	 *  L = loopback, P = private, G = global
327 	 * -----------------------------------------
328 	 *  src    |      dest     |    result
329 	 *-----------------------------------------
330 	 *   L     |       L       |    yes
331 	 *-----------------------------------------
332 	 *   P     |       L       |    yes
333 	 *-----------------------------------------
334 	 *   G     |       L       |    yes
335 	 *-----------------------------------------
336 	 *   L     |       P       |    no
337 	 *-----------------------------------------
338 	 *   P     |       P       |    yes
339 	 *-----------------------------------------
340 	 *   G     |       P       |    no
341 	 *-----------------------------------------
342 	 *   L     |       G       |    no
343 	 *-----------------------------------------
344 	 *   P     |       G       |    no
345 	 *-----------------------------------------
346 	 *   G     |       G       |    yes
347 	 *-----------------------------------------
348 	 */
349 
350 	if (ifa->ifa_addr->sa_family != AF_INET) {
351 		/* forget non-v4 */
352 		return (NULL);
353 	}
354 	/* Ok the address may be ok */
355 	sin = (struct sockaddr_in *)ifa->ifa_addr;
356 	if (sin->sin_addr.s_addr == 0) {
357 		return (NULL);
358 	}
359 	*sin_local = *sin_loop = 0;
360 	if ((ifa->ifa_ifp->if_type == IFT_LOOP) ||
361 	    (IN4_ISLOOPBACK_ADDRESS(&sin->sin_addr))) {
362 		*sin_loop = 1;
363 		*sin_local = 1;
364 	}
365 	if ((IN4_ISPRIVATE_ADDRESS(&sin->sin_addr))) {
366 		*sin_local = 1;
367 	}
368 	if (!loopscope && *sin_loop) {
369 		/* Its a loopback address and we don't have loop scope */
370 		return (NULL);
371 	}
372 	if (!ipv4_scope && *sin_local) {
373 		/* Its a private address, and we don't have private address scope */
374 		return (NULL);
375 	}
376 	if (((ipv4_scope == 0) && (loopscope == 0)) && (*sin_local)) {
377 		/* its a global src and a private dest */
378 		return (NULL);
379 	}
380 	/* its a prefered address */
381 	return (sin);
382 }
383 
384 static struct sockaddr_in *
385 sctp_is_v4_ifa_addr_acceptable (struct ifaddr *ifa, uint8_t loopscope, uint8_t ipv4_scope, uint8_t *sin_loop, uint8_t *sin_local)
386 {
387 	struct sockaddr_in *sin;
388 	/*
389 	 * Here we determine if its a acceptable address. A
390 	 * acceptable address means it is the same scope or
391 	 * higher scope but we can allow for NAT which means
392 	 * its ok to have a global dest and a private src.
393 	 *
394 	 *  L = loopback, P = private, G = global
395 	 * -----------------------------------------
396 	 *  src    |      dest     |    result
397 	 *-----------------------------------------
398 	 *   L     |       L       |    yes
399 	 *-----------------------------------------
400 	 *   P     |       L       |    yes
401 	 *-----------------------------------------
402 	 *   G     |       L       |    yes
403 	 *-----------------------------------------
404 	 *   L     |       P       |    no
405 	 *-----------------------------------------
406 	 *   P     |       P       |    yes
407 	 *-----------------------------------------
408 	 *   G     |       P       |    yes - probably this won't work.
409 	 *-----------------------------------------
410 	 *   L     |       G       |    no
411 	 *-----------------------------------------
412 	 *   P     |       G       |    yes
413 	 *-----------------------------------------
414 	 *   G     |       G       |    yes
415 	 *-----------------------------------------
416 	 */
417 
418 	if (ifa->ifa_addr->sa_family != AF_INET) {
419 		/* forget non-v4 */
420 		return (NULL);
421 	}
422 	/* Ok the address may be ok */
423 	sin = (struct sockaddr_in *)ifa->ifa_addr;
424 	if (sin->sin_addr.s_addr == 0) {
425 		return (NULL);
426 	}
427 	*sin_local = *sin_loop = 0;
428 	if ((ifa->ifa_ifp->if_type == IFT_LOOP) ||
429 	    (IN4_ISLOOPBACK_ADDRESS(&sin->sin_addr))) {
430 		*sin_loop = 1;
431 		*sin_local = 1;
432 	}
433 	if ((IN4_ISPRIVATE_ADDRESS(&sin->sin_addr))) {
434 		*sin_local = 1;
435 	}
436 	if (!loopscope && *sin_loop) {
437 		/* Its a loopback address and we don't have loop scope */
438 		return (NULL);
439 	}
440 	/* its an acceptable address */
441 	return (sin);
442 }
443 
444 /*
445  * This treats the address list on the ep as a restricted list
446  * (negative list). If a the passed address is listed, then
447  * the address is NOT allowed on the association.
448  */
449 int
450 sctp_is_addr_restricted(struct sctp_tcb *stcb, struct sockaddr *addr)
451 {
452 	struct sctp_laddr *laddr;
453 #ifdef SCTP_DEBUG
454 	int cnt=0;
455 #endif
456 	if (stcb == NULL) {
457 		/* There are no restrictions, no TCB :-) */
458 		return (0);
459 	}
460 #ifdef SCTP_DEBUG
461 	LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list, sctp_nxt_addr) {
462 		cnt++;
463 	}
464 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
465 		printf("There are %d addresses on the restricted list\n", cnt);
466 	}
467 	cnt = 0;
468 #endif
469 	LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list, sctp_nxt_addr) {
470 		if (laddr->ifa == NULL) {
471 #ifdef SCTP_DEBUG
472 			if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
473 				printf("Help I have fallen and I can't get up!\n");
474 			}
475 #endif
476 			continue;
477 		}
478 #ifdef SCTP_DEBUG
479 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
480 			cnt++;
481 			printf("Restricted address[%d]:", cnt);
482 			sctp_print_address(laddr->ifa->ifa_addr);
483 		}
484 #endif
485 		if (sctp_cmpaddr(addr, laddr->ifa->ifa_addr) == 1) {
486 			/* Yes it is on the list */
487 			return (1);
488 		}
489 	}
490 	return (0);
491 }
492 
493 static int
494 sctp_is_addr_in_ep(struct sctp_inpcb *inp, struct ifaddr *ifa)
495 {
496 	struct sctp_laddr *laddr;
497 
498 	if (ifa == NULL)
499 		return (0);
500 	LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
501 		if (laddr->ifa == NULL) {
502 #ifdef SCTP_DEBUG
503 			if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
504 				printf("Help I have fallen and I can't get up!\n");
505 			}
506 #endif
507 			continue;
508 		}
509 		if (laddr->ifa->ifa_addr == NULL)
510 			continue;
511 		if (laddr->ifa == ifa)
512 			/* same pointer */
513 			return (1);
514 		if (laddr->ifa->ifa_addr->sa_family != ifa->ifa_addr->sa_family) {
515 			/* skip non compatible address comparison */
516 			continue;
517 		}
518 		if (sctp_cmpaddr(ifa->ifa_addr, laddr->ifa->ifa_addr) == 1) {
519 			/* Yes it is restricted */
520 			return (1);
521 		}
522 	}
523 	return (0);
524 }
525 
526 
527 
528 static struct in_addr
529 sctp_choose_v4_boundspecific_inp(struct sctp_inpcb *inp,
530 				 struct rtentry *rt,
531 				 uint8_t ipv4_scope,
532 				 uint8_t loopscope)
533 {
534 	struct in_addr ans;
535 	struct sctp_laddr *laddr;
536 	struct sockaddr_in *sin;
537 	struct ifnet *ifn;
538 	struct ifaddr *ifa;
539 	uint8_t sin_loop, sin_local;
540 
541 	/* first question, is the ifn we will emit on
542 	 * in our list, if so, we want that one.
543 	 */
544 	ifn = rt->rt_ifp;
545 	if (ifn) {
546 		/* is a prefered one on the interface we route out? */
547 		IFADDR_READER_FOREACH(ifa, ifn) {
548 			sin = sctp_is_v4_ifa_addr_prefered (ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
549 			if (sin == NULL)
550 				continue;
551 			if (sctp_is_addr_in_ep(inp, ifa)) {
552 				return (sin->sin_addr);
553 			}
554 		}
555 		/* is an acceptable one on the interface we route out? */
556 		IFADDR_READER_FOREACH(ifa, ifn) {
557 			sin = sctp_is_v4_ifa_addr_acceptable (ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
558 			if (sin == NULL)
559 				continue;
560 			if (sctp_is_addr_in_ep(inp, ifa)) {
561 				return (sin->sin_addr);
562 			}
563 		}
564 	}
565 	/* ok, what about a prefered address in the inp */
566 	for (laddr = LIST_FIRST(&inp->sctp_addr_list);
567 	     laddr && (laddr != inp->next_addr_touse);
568 	     laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
569 		if (laddr->ifa == NULL) {
570 			/* address has been removed */
571 			continue;
572 		}
573 		sin = sctp_is_v4_ifa_addr_prefered (laddr->ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
574 		if (sin == NULL)
575 			continue;
576 		return (sin->sin_addr);
577 
578 	}
579 	/* ok, what about an acceptable address in the inp */
580 	for (laddr = LIST_FIRST(&inp->sctp_addr_list);
581 	     laddr && (laddr != inp->next_addr_touse);
582 	     laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
583 		if (laddr->ifa == NULL) {
584 			/* address has been removed */
585 			continue;
586 		}
587 		sin = sctp_is_v4_ifa_addr_acceptable (laddr->ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
588 		if (sin == NULL)
589 			continue;
590 		return (sin->sin_addr);
591 
592 	}
593 
594 	/* no address bound can be a source for the destination we are in trouble */
595 #ifdef SCTP_DEBUG
596 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
597 		printf("Src address selection for EP, no acceptable src address found for address\n");
598 	}
599 #endif
600 	memset(&ans, 0, sizeof(ans));
601 	return (ans);
602 }
603 
604 
605 
606 static struct in_addr
607 sctp_choose_v4_boundspecific_stcb(struct sctp_inpcb *inp,
608 				  struct sctp_tcb *stcb,
609 				  struct sctp_nets *net,
610 				  struct rtentry *rt,
611  			          uint8_t ipv4_scope,
612 				  uint8_t loopscope,
613 				  int non_asoc_addr_ok)
614 {
615 	/*
616 	 * Here we have two cases, bound all asconf
617 	 * allowed. bound all asconf not allowed.
618 	 *
619 	 */
620 	struct sctp_laddr *laddr, *starting_point;
621 	struct in_addr ans;
622 	struct ifnet *ifn;
623 	struct ifaddr *ifa;
624 	uint8_t sin_loop, sin_local, start_at_beginning=0;
625 	struct sockaddr_in *sin;
626 
627 	/* first question, is the ifn we will emit on
628 	 * in our list, if so, we want that one.
629 	 */
630 	ifn = rt->rt_ifp;
631 
632  	if (inp->sctp_flags & SCTP_PCB_FLAGS_DO_ASCONF) {
633 		/*
634 		 * Here we use the list of addresses on the endpoint. Then
635 		 * the addresses listed on the "restricted" list is just that,
636 		 * address that have not been added and can't be used (unless
637 		 * the non_asoc_addr_ok is set).
638 		 */
639 #ifdef SCTP_DEBUG
640 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
641 			printf("Have a STCB - asconf allowed, not bound all have a netgative list\n");
642 		}
643 #endif
644 		/* first question, is the ifn we will emit on
645 		 * in our list, if so, we want that one.
646 		 */
647 		if (ifn) {
648 			/* first try for an prefered address on the ep */
649 			IFADDR_READER_FOREACH(ifa, ifn) {
650 				if (sctp_is_addr_in_ep(inp, ifa)) {
651 					sin = sctp_is_v4_ifa_addr_prefered (ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
652 					if (sin == NULL)
653 						continue;
654 					if ((non_asoc_addr_ok == 0) &&
655 					    (sctp_is_addr_restricted(stcb, (struct sockaddr *)sin))) {
656 						/* on the no-no list */
657 						continue;
658 					}
659 					return (sin->sin_addr);
660 				}
661 			}
662 			/* next try for an acceptable address on the ep */
663 			IFADDR_READER_FOREACH(ifa, ifn) {
664 				if (sctp_is_addr_in_ep(inp, ifa)) {
665 					sin = sctp_is_v4_ifa_addr_acceptable (ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
666 					if (sin == NULL)
667 						continue;
668 					if ((non_asoc_addr_ok == 0) &&
669 					    (sctp_is_addr_restricted(stcb, (struct sockaddr *)sin))) {
670 						/* on the no-no list */
671 						continue;
672 					}
673 					return (sin->sin_addr);
674 				}
675 			}
676 
677 		}
678 		/* if we can't find one like that then we must
679 		 * look at all addresses bound to pick one at
680 		 * first prefereable then secondly acceptable.
681 		 */
682 		starting_point = stcb->asoc.last_used_address;
683 	sctpv4_from_the_top:
684 		if (stcb->asoc.last_used_address == NULL) {
685 			start_at_beginning=1;
686 			stcb->asoc.last_used_address = LIST_FIRST(&inp->sctp_addr_list);
687 		}
688 		/* search beginning with the last used address */
689 		for (laddr = stcb->asoc.last_used_address; laddr;
690 		     laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
691 			if (laddr->ifa == NULL) {
692 				/* address has been removed */
693 				continue;
694 			}
695 			sin = sctp_is_v4_ifa_addr_prefered (laddr->ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
696 			if (sin == NULL)
697 				continue;
698 			if ((non_asoc_addr_ok == 0) &&
699 			    (sctp_is_addr_restricted(stcb, (struct sockaddr *)sin))) {
700 				/* on the no-no list */
701 				continue;
702 			}
703 			return (sin->sin_addr);
704 
705 		}
706 		if (start_at_beginning == 0) {
707 			stcb->asoc.last_used_address = NULL;
708 			goto sctpv4_from_the_top;
709 		}
710 		/* now try for any higher scope than the destination */
711 		stcb->asoc.last_used_address = starting_point;
712 		start_at_beginning = 0;
713 	sctpv4_from_the_top2:
714 		if (stcb->asoc.last_used_address == NULL) {
715 			start_at_beginning=1;
716 			stcb->asoc.last_used_address = LIST_FIRST(&inp->sctp_addr_list);
717 		}
718 		/* search beginning with the last used address */
719 		for (laddr = stcb->asoc.last_used_address; laddr;
720 		     laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
721 			if (laddr->ifa == NULL) {
722 				/* address has been removed */
723 				continue;
724 			}
725 			sin = sctp_is_v4_ifa_addr_acceptable (laddr->ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
726 			if (sin == NULL)
727 				continue;
728 			if ((non_asoc_addr_ok == 0) &&
729 			    (sctp_is_addr_restricted(stcb, (struct sockaddr *)sin))) {
730 				/* on the no-no list */
731 				continue;
732 			}
733 			return (sin->sin_addr);
734 		}
735 		if (start_at_beginning == 0) {
736 			stcb->asoc.last_used_address = NULL;
737 			goto sctpv4_from_the_top2;
738 		}
739 	} else {
740 		/*
741 		 * Here we have an address list on the association, thats the
742 		 * only valid source addresses that we can use.
743 		 */
744 #ifdef SCTP_DEBUG
745 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
746 			printf("Have a STCB - no asconf allowed, not bound all have a positive list\n");
747 		}
748 #endif
749 		/* First look at all addresses for one that is on
750 		 * the interface we route out
751 		 */
752 		LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list,
753 			     sctp_nxt_addr) {
754 			if (laddr->ifa == NULL) {
755 				/* address has been removed */
756 				continue;
757 			}
758 			sin = sctp_is_v4_ifa_addr_prefered (laddr->ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
759 			if (sin == NULL)
760 				continue;
761 			/* first question, is laddr->ifa an address associated with the emit interface */
762 			if (ifn) {
763 				IFADDR_READER_FOREACH(ifa, ifn) {
764 					if (laddr->ifa == ifa) {
765 						sin = (struct sockaddr_in *)laddr->ifa->ifa_addr;
766 						return (sin->sin_addr);
767 					}
768 					if (sctp_cmpaddr(ifa->ifa_addr, laddr->ifa->ifa_addr) == 1) {
769 						sin = (struct sockaddr_in *)laddr->ifa->ifa_addr;
770 						return (sin->sin_addr);
771 					}
772 				}
773 			}
774 		}
775 		/* what about an acceptable one on the interface? */
776 		LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list,
777 			     sctp_nxt_addr) {
778 			if (laddr->ifa == NULL) {
779 				/* address has been removed */
780 				continue;
781 			}
782 			sin = sctp_is_v4_ifa_addr_acceptable (laddr->ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
783 			if (sin == NULL)
784 				continue;
785 			/* first question, is laddr->ifa an address associated with the emit interface */
786 			if (ifn) {
787 				IFADDR_READER_FOREACH(ifa, ifn) {
788 					if (laddr->ifa == ifa) {
789 						sin = (struct sockaddr_in *)laddr->ifa->ifa_addr;
790 						return (sin->sin_addr);
791 					}
792 					if (sctp_cmpaddr(ifa->ifa_addr, laddr->ifa->ifa_addr) == 1) {
793 						sin = (struct sockaddr_in *)laddr->ifa->ifa_addr;
794 						return (sin->sin_addr);
795 					}
796 				}
797 			}
798 		}
799 		/* ok, next one that is preferable in general */
800 		LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list,
801 			     sctp_nxt_addr) {
802 			if (laddr->ifa == NULL) {
803 				/* address has been removed */
804 				continue;
805 			}
806 			sin = sctp_is_v4_ifa_addr_prefered (laddr->ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
807 			if (sin == NULL)
808 				continue;
809 			return (sin->sin_addr);
810 		}
811 
812 		/* last, what about one that is acceptable */
813 		LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list,
814 			     sctp_nxt_addr) {
815 			if (laddr->ifa == NULL) {
816 				/* address has been removed */
817 				continue;
818 			}
819 			sin = sctp_is_v4_ifa_addr_acceptable (laddr->ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
820 			if (sin == NULL)
821 				continue;
822 			return (sin->sin_addr);
823 		}
824 	}
825 	memset(&ans, 0, sizeof(ans));
826 	return (ans);
827 }
828 
829 static struct sockaddr_in *
830 sctp_select_v4_nth_prefered_addr_from_ifn_boundall (struct ifnet *ifn, struct sctp_tcb *stcb, int non_asoc_addr_ok,
831 						    uint8_t loopscope, uint8_t ipv4_scope, int cur_addr_num)
832 {
833 	struct ifaddr *ifa;
834 	struct sockaddr_in *sin;
835 	uint8_t sin_loop, sin_local;
836 	int num_eligible_addr = 0;
837 	IFADDR_READER_FOREACH(ifa, ifn) {
838 		sin = sctp_is_v4_ifa_addr_prefered (ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
839 		if (sin == NULL)
840 			continue;
841 		if (stcb) {
842 			if ((non_asoc_addr_ok == 0) && sctp_is_addr_restricted(stcb, (struct sockaddr *)sin)) {
843 				/* It is restricted for some reason.. probably
844 				 * not yet added.
845 				 */
846 				continue;
847 			}
848 		}
849 		if (cur_addr_num == num_eligible_addr) {
850 			return (sin);
851 		}
852 	}
853 	return (NULL);
854 }
855 
856 
857 static int
858 sctp_count_v4_num_prefered_boundall (struct ifnet *ifn, struct sctp_tcb *stcb, int non_asoc_addr_ok,
859 				     uint8_t loopscope, uint8_t ipv4_scope, uint8_t *sin_loop, uint8_t *sin_local)
860 {
861 	struct ifaddr *ifa;
862 	struct sockaddr_in *sin;
863 	int num_eligible_addr = 0;
864 
865 	IFADDR_READER_FOREACH(ifa, ifn) {
866 		sin = sctp_is_v4_ifa_addr_prefered (ifa, loopscope, ipv4_scope, sin_loop, sin_local);
867 		if (sin == NULL)
868 			continue;
869 		if (stcb) {
870 			if ((non_asoc_addr_ok == 0) && sctp_is_addr_restricted(stcb, (struct sockaddr *)sin)) {
871 				/* It is restricted for some reason.. probably
872 				 * not yet added.
873 				 */
874 				continue;
875 			}
876 		}
877 		num_eligible_addr++;
878 	}
879 	return (num_eligible_addr);
880 
881 }
882 
883 static struct in_addr
884 sctp_choose_v4_boundall(struct sctp_inpcb *inp,
885 			struct sctp_tcb *stcb,
886 			struct sctp_nets *net,
887 			struct rtentry *rt,
888 			uint8_t ipv4_scope,
889 			uint8_t loopscope,
890 			int non_asoc_addr_ok)
891 {
892 	int cur_addr_num=0, num_prefered=0;
893 	uint8_t sin_loop, sin_local;
894 	struct ifnet *ifn;
895 	struct sockaddr_in *sin;
896 	struct in_addr ans;
897 	struct ifaddr *ifa;
898 	int s;
899 	/*
900 	 * For v4 we can use (in boundall) any address in the association. If
901 	 * non_asoc_addr_ok is set we can use any address (at least in theory).
902 	 * So we look for prefered addresses first. If we find one, we use it.
903 	 * Otherwise we next try to get an address on the interface, which we
904 	 * should be able to do (unless non_asoc_addr_ok is false and we are
905 	 * routed out that way). In these cases where we can't use the address
906 	 * of the interface we go through all the ifn's looking for an address
907 	 * we can use and fill that in. Punting means we send back address
908 	 * 0, which will probably cause problems actually since then IP will
909 	 * fill in the address of the route ifn, which means we probably already
910 	 * rejected it.. i.e. here comes an abort :-<.
911 	 */
912 	ifn = rt->rt_ifp;
913 	if (net) {
914 		cur_addr_num = net->indx_of_eligible_next_to_use;
915 	}
916 	if (ifn == NULL) {
917  		goto bound_all_v4_plan_c;
918 	}
919 	num_prefered = sctp_count_v4_num_prefered_boundall (ifn, stcb, non_asoc_addr_ok, loopscope, ipv4_scope, &sin_loop, &sin_local);
920 #ifdef SCTP_DEBUG
921 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
922 		printf("Found %d prefered source addresses\n", num_prefered);
923 	}
924 #endif
925 	if (num_prefered == 0) {
926 		/* no eligible addresses, we must use some other
927 		 * interface address if we can find one.
928 		 */
929  		goto bound_all_v4_plan_b;
930 	}
931 	/* Ok we have num_eligible_addr set with how many we can use,
932 	 * this may vary from call to call due to addresses being deprecated etc..
933 	 */
934 	if (cur_addr_num >= num_prefered) {
935 		cur_addr_num = 0;
936 	}
937 	/* select the nth address from the list (where cur_addr_num is the nth) and
938 	 * 0 is the first one, 1 is the second one etc...
939 	 */
940 #ifdef SCTP_DEBUG
941 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
942 		printf("cur_addr_num:%d\n", cur_addr_num);
943 	}
944 #endif
945 	sin = sctp_select_v4_nth_prefered_addr_from_ifn_boundall (ifn, stcb, non_asoc_addr_ok, loopscope,
946 								   ipv4_scope, cur_addr_num);
947 
948 	/* if sin is NULL something changed??, plan_a now */
949 	if (sin) {
950 		return (sin->sin_addr);
951 	}
952 
953 	/*
954 	 * plan_b: Look at the interface that we emit on
955 	 *         and see if we can find an acceptable address.
956 	 */
957  bound_all_v4_plan_b:
958 	IFADDR_READER_FOREACH(ifa, ifn) {
959 		sin = sctp_is_v4_ifa_addr_acceptable (ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
960 		if (sin == NULL)
961 			continue;
962 		if (stcb) {
963 			if ((non_asoc_addr_ok == 0) && sctp_is_addr_restricted(stcb, (struct sockaddr *)sin)) {
964 				/* It is restricted for some reason.. probably
965 				 * not yet added.
966 				 */
967 				continue;
968 			}
969 		}
970 		return (sin->sin_addr);
971 	}
972 	/*
973 	 * plan_c: Look at all interfaces and find a prefered
974 	 *         address. If we reache here we are in trouble I think.
975 	 */
976  bound_all_v4_plan_c:
977 	s = pserialize_read_enter();
978 	IFNET_READER_FOREACH(ifn) {
979 		if (ifn == inp->next_ifn_touse)
980 			break;
981 		if (loopscope == 0 && ifn->if_type == IFT_LOOP) {
982 			/* wrong base scope */
983 			continue;
984 		}
985 		if (ifn == rt->rt_ifp)
986 			/* already looked at this guy */
987 			continue;
988 		num_prefered = sctp_count_v4_num_prefered_boundall (ifn, stcb, non_asoc_addr_ok,
989 								    loopscope, ipv4_scope, &sin_loop, &sin_local);
990 #ifdef SCTP_DEBUG
991 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
992 			printf("Found ifn:%p %d prefered source addresses\n", ifn, num_prefered);
993 		}
994 #endif
995 		if (num_prefered == 0) {
996 			/*
997 			 * None on this interface.
998 			 */
999 			continue;
1000 		}
1001 		/* Ok we have num_eligible_addr set with how many we can use,
1002 		 * this may vary from call to call due to addresses being deprecated etc..
1003 		 */
1004 		if (cur_addr_num >= num_prefered) {
1005 			cur_addr_num = 0;
1006 		}
1007 		sin = sctp_select_v4_nth_prefered_addr_from_ifn_boundall (ifn, stcb, non_asoc_addr_ok, loopscope,
1008 									  ipv4_scope, cur_addr_num);
1009 		if (sin == NULL)
1010 			continue;
1011 		pserialize_read_exit(s);
1012 		return (sin->sin_addr);
1013 
1014 	}
1015 	pserialize_read_exit(s);
1016 
1017 	/*
1018 	 * plan_d: We are in deep trouble. No prefered address on
1019 	 *         any interface. And the emit interface does not
1020 	 *         even have an acceptable address. Take anything
1021 	 *         we can get! If this does not work we are
1022 	 *         probably going to emit a packet that will
1023 	 *         illicit an ABORT, falling through.
1024 	 */
1025 
1026 	s = pserialize_read_enter();
1027 	IFNET_READER_FOREACH(ifn) {
1028 		if (ifn == inp->next_ifn_touse)
1029 			break;
1030 		if (loopscope == 0 && ifn->if_type == IFT_LOOP) {
1031 			/* wrong base scope */
1032 			continue;
1033 		}
1034 		if (ifn == rt->rt_ifp)
1035 			/* already looked at this guy */
1036 			continue;
1037 
1038 		IFADDR_READER_FOREACH(ifa, ifn) {
1039 			sin = sctp_is_v4_ifa_addr_acceptable (ifa, loopscope, ipv4_scope, &sin_loop, &sin_local);
1040 			if (sin == NULL)
1041 				continue;
1042 			if (stcb) {
1043 				if ((non_asoc_addr_ok == 0) && sctp_is_addr_restricted(stcb, (struct sockaddr *)sin)) {
1044 					/* It is restricted for some reason.. probably
1045 					 * not yet added.
1046 					 */
1047 					continue;
1048 				}
1049 			}
1050 			pserialize_read_exit(s);
1051 			return (sin->sin_addr);
1052 		}
1053 	}
1054 	pserialize_read_exit(s);
1055 	/*
1056 	 * Ok we can find NO address to source from that is
1057 	 * not on our negative list. It is either the special
1058 	 * ASCONF case where we are sourceing from a intf that
1059 	 * has been ifconfig'd to a different address (i.e.
1060 	 * it holds a ADD/DEL/SET-PRIM and the proper lookup
1061 	 * address. OR we are hosed, and this baby is going
1062 	 * to abort the association.
1063 	 */
1064 	if (non_asoc_addr_ok) {
1065 		return (((struct sockaddr_in *)(rt->rt_ifa->ifa_addr))->sin_addr);
1066 	} else {
1067 		memset(&ans, 0, sizeof(ans));
1068 		return (ans);
1069 	}
1070 }
1071 
1072 
1073 
1074 /* tcb may be NULL */
1075 struct in_addr
1076 sctp_ipv4_source_address_selection(struct sctp_inpcb *inp,
1077     struct sctp_tcb *stcb, struct route *ro, struct sctp_nets *net,
1078     int non_asoc_addr_ok)
1079 {
1080 	struct in_addr ans;
1081 	const struct sockaddr_in *to;
1082 	struct rtentry *rt;
1083 	uint8_t ipv4_scope, loopscope;
1084 
1085 	/*
1086 	 * Rules:
1087 	 * - Find the route if needed, cache if I can.
1088 	 * - Look at interface address in route, Is it
1089 	 *   in the bound list. If so we have the best source.
1090 	 * - If not we must rotate amongst the addresses.
1091 	 *
1092 	 * Cavets and issues
1093 	 *
1094 	 * Do we need to pay attention to scope. We can have
1095 	 * a private address or a global address we are sourcing
1096 	 * or sending to. So if we draw it out
1097 	 *      source     *      dest   *  result
1098 	 *  ------------------------------------------
1099 	 *  a   Private    *     Global  *  NAT?
1100 	 *  ------------------------------------------
1101 	 *  b   Private    *     Private *  No problem
1102 	 *  ------------------------------------------
1103 	 *  c   Global     *     Private *  Huh, How will this work?
1104 	 *  ------------------------------------------
1105 	 *  d   Global     *     Global  *  No Problem
1106 	 *  ------------------------------------------
1107 	 *
1108 	 * And then we add to that what happens if there are multiple
1109 	 * addresses assigned to an interface. Remember the ifa on a
1110 	 * ifn is a linked list of addresses. So one interface can
1111 	 * have more than one IPv4 address. What happens if we
1112 	 * have both a private and a global address? Do we then
1113 	 * use context of destination to sort out which one is
1114 	 * best? And what about NAT's sending P->G may get you
1115 	 * a NAT translation, or should you select the G thats
1116 	 * on the interface in preference.
1117 	 *
1118 	 * Decisions:
1119 	 *
1120 	 *  - count the number of addresses on the interface.
1121 	 *  - if its one, no problem except case <c>. For <a>
1122 	 *    we will assume a NAT out there.
1123 	 *  - if there are more than one, then we need to worry
1124 	 *    about scope P or G. We should prefer G -> G and
1125 	 *    P -> P if possible. Then as a secondary fall back
1126 	 *    to mixed types G->P being a last ditch one.
1127 	 *  - The above all works for bound all, but bound
1128 	 *    specific we need to use the same concept but instead
1129 	 *    only consider the bound addresses. If the bound set
1130 	 *    is NOT assigned to the interface then we must use
1131 	 *    rotation amongst them.
1132 	 *
1133 	 * Notes: For v4, we can always punt and let ip_output
1134 	 * decide by sending back a source of 0.0.0.0
1135 	 */
1136 
1137 	/*
1138 	 * Need a route to cache.
1139 	 *
1140 	 */
1141 	rt = rtcache_validate(ro);
1142 	if (rt == NULL) {
1143 		/* No route to host .. punt */
1144 		memset(&ans, 0, sizeof(ans));
1145 		return (ans);
1146 	} else {
1147 		to = satocsin(rtcache_getdst(ro));
1148 	}
1149 	/* Setup our scopes */
1150 	if (stcb) {
1151 		ipv4_scope = stcb->asoc.ipv4_local_scope;
1152 		loopscope = stcb->asoc.loopback_scope;
1153 	} else {
1154 		/* Scope based on outbound address */
1155 		if ((IN4_ISPRIVATE_ADDRESS(&to->sin_addr))) {
1156 			ipv4_scope = 1;
1157 			loopscope = 0;
1158 		} else if (IN4_ISLOOPBACK_ADDRESS(&to->sin_addr)) {
1159 			ipv4_scope = 1;
1160 			loopscope = 1;
1161 		} else {
1162 			ipv4_scope = 0;
1163 			loopscope = 0;
1164 		}
1165 	}
1166 #ifdef SCTP_DEBUG
1167 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1168 		printf("Scope setup loop:%d ipv4_scope:%d\n",
1169 		       loopscope, ipv4_scope);
1170 	}
1171 #endif
1172 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
1173 		/*
1174 		 * When bound to all if the address list is set
1175 		 * it is a negative list. Addresses being added
1176 		 * by asconf.
1177 		 */
1178 		ans = sctp_choose_v4_boundall(inp, stcb, net, rt,
1179 		    ipv4_scope, loopscope, non_asoc_addr_ok);
1180 		goto out;
1181         }
1182 	/*
1183  	 * Three possiblities here:
1184 	 *
1185 	 * a) stcb is NULL, which means we operate only from
1186 	 *    the list of addresses (ifa's) bound to the assoc and
1187 	 *    we care not about the list.
1188 	 * b) stcb is NOT-NULL, which means we have an assoc structure and
1189 	 *    auto-asconf is on. This means that the list of addresses is
1190          *    a NOT list. We use the list from the inp, but any listed address
1191 	 *    in our list is NOT yet added. However if the non_asoc_addr_ok is
1192 	 *    set we CAN use an address NOT available (i.e. being added). Its
1193 	 *    a negative list.
1194 	 * c) stcb is NOT-NULL, which means we have an assoc structure and
1195 	 *    auto-asconf is off. This means that the list of addresses is
1196          *    the ONLY addresses I can use.. its positive.
1197 	 *
1198 	 *    Note we collapse b & c into the same function just like in
1199 	 *    the v6 address selection.
1200 	 */
1201 	if (stcb) {
1202 		ans = sctp_choose_v4_boundspecific_stcb(inp, stcb, net,
1203 		    rt, ipv4_scope, loopscope, non_asoc_addr_ok);
1204 		goto out;
1205 	} else {
1206 		ans = sctp_choose_v4_boundspecific_inp(inp, rt,
1207 		    ipv4_scope, loopscope);
1208 		goto out;
1209 	}
1210 	/* this should not be reached */
1211 	memset(&ans, 0, sizeof(ans));
1212 out:
1213 	rtcache_unref(rt, ro);
1214 	return ans;
1215 }
1216 
1217 
1218 
1219 static struct sockaddr_in6 *
1220 sctp_is_v6_ifa_addr_acceptable (struct ifaddr *ifa, int loopscope, int loc_scope, int *sin_loop, int *sin_local)
1221 {
1222 	struct in6_ifaddr *ifa6;
1223 	struct sockaddr_in6 *sin6;
1224 
1225 	if (ifa->ifa_addr->sa_family != AF_INET6) {
1226 		/* forget non-v6 */
1227 		return (NULL);
1228 	}
1229 	ifa6 = (struct in6_ifaddr *)ifa;
1230 	/* ok to use deprecated addresses? */
1231 	if (!ip6_use_deprecated) {
1232 		if (IFA6_IS_DEPRECATED(ifa6)) {
1233 			/* can't use this type */
1234 			return (NULL);
1235 		}
1236 	}
1237 	/* are we ok, with the current state of this address? */
1238 	if (ifa6->ia6_flags &
1239 	    (IN6_IFF_DETACHED | IN6_IFF_NOTREADY | IN6_IFF_ANYCAST)) {
1240 		/* Can't use these types */
1241 		return (NULL);
1242 	}
1243 	/* Ok the address may be ok */
1244 	sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
1245 	*sin_local = *sin_loop = 0;
1246 	if ((ifa->ifa_ifp->if_type == IFT_LOOP) ||
1247 	    (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr))) {
1248 		*sin_loop = 1;
1249 	}
1250 	if (!loopscope && *sin_loop) {
1251 		/* Its a loopback address and we don't have loop scope */
1252 		return (NULL);
1253 	}
1254 	if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
1255 		/* we skip unspecified addresses */
1256 		return (NULL);
1257 	}
1258 
1259 	if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
1260 		*sin_local = 1;
1261 	}
1262 	if (!loc_scope && *sin_local) {
1263 		/* Its a link local address, and we don't have link local scope */
1264 		return (NULL);
1265 	}
1266 	return (sin6);
1267 }
1268 
1269 
1270 static struct sockaddr_in6 *
1271 sctp_choose_v6_boundspecific_stcb(struct sctp_inpcb *inp,
1272 				  struct sctp_tcb *stcb,
1273 				  struct sctp_nets *net,
1274 				  struct rtentry *rt,
1275  			          uint8_t loc_scope,
1276 				  uint8_t loopscope,
1277 				  int non_asoc_addr_ok)
1278 {
1279 	/*
1280 	 *   Each endpoint has a list of local addresses associated
1281 	 *   with it. The address list is either a "negative list" i.e.
1282 	 *   those addresses that are NOT allowed to be used as a source OR
1283 	 *   a "positive list" i.e. those addresses that CAN be used.
1284 	 *
1285 	 *   Its a negative list if asconf is allowed. What we do
1286 	 *   in this case is use the ep address list BUT we have
1287 	 *   to cross check it against the negative list.
1288 	 *
1289 	 *   In the case where NO asconf is allowed, we have just
1290 	 *   a straight association level list that we must use to
1291 	 *   find a source address.
1292 	 */
1293 	struct sctp_laddr *laddr, *starting_point;
1294 	struct sockaddr_in6 *sin6;
1295 	int sin_loop, sin_local;
1296 	int start_at_beginning=0;
1297 	struct ifnet *ifn;
1298 	struct ifaddr *ifa;
1299 
1300 	ifn = rt->rt_ifp;
1301 	if (inp->sctp_flags & SCTP_PCB_FLAGS_DO_ASCONF) {
1302 #ifdef SCTP_DEBUG
1303 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1304 			printf("Have a STCB - asconf allowed, not bound all have a netgative list\n");
1305 		}
1306 #endif
1307 		/* first question, is the ifn we will emit on
1308 		 * in our list, if so, we want that one.
1309 		 */
1310 		if (ifn) {
1311 			IFADDR_READER_FOREACH(ifa, ifn) {
1312 				if (sctp_is_addr_in_ep(inp, ifa)) {
1313 					sin6 = sctp_is_v6_ifa_addr_acceptable (ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1314 					if (sin6 == NULL)
1315 						continue;
1316 					if ((non_asoc_addr_ok == 0) &&
1317 					    (sctp_is_addr_restricted(stcb, (struct sockaddr *)sin6))) {
1318 						/* on the no-no list */
1319 						continue;
1320 					}
1321 					return (sin6);
1322 				}
1323 			}
1324 		}
1325 		starting_point = stcb->asoc.last_used_address;
1326 		/* First try for matching scope */
1327 	sctp_from_the_top:
1328 		if (stcb->asoc.last_used_address == NULL) {
1329 			start_at_beginning=1;
1330 			stcb->asoc.last_used_address = LIST_FIRST(&inp->sctp_addr_list);
1331 		}
1332 		/* search beginning with the last used address */
1333 		for (laddr = stcb->asoc.last_used_address; laddr;
1334 		     laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
1335 			if (laddr->ifa == NULL) {
1336 				/* address has been removed */
1337 				continue;
1338 			}
1339 			sin6 = sctp_is_v6_ifa_addr_acceptable (laddr->ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1340 			if (sin6 == NULL)
1341 				continue;
1342 			if ((non_asoc_addr_ok == 0) && (sctp_is_addr_restricted(stcb, (struct sockaddr *)sin6))) {
1343 				/* on the no-no list */
1344 				continue;
1345 			}
1346 			/* is it of matching scope ? */
1347 			if ((loopscope == 0) &&
1348 			    (loc_scope == 0) &&
1349 			    (sin_loop == 0) &&
1350 			    (sin_local == 0)) {
1351 				/* all of global scope we are ok with it */
1352 				return (sin6);
1353 			}
1354 			if (loopscope && sin_loop)
1355 				/* both on the loopback, thats ok */
1356 				return (sin6);
1357 			if (loc_scope && sin_local)
1358 				/* both local scope */
1359 				return (sin6);
1360 
1361 		}
1362 		if (start_at_beginning == 0) {
1363 			stcb->asoc.last_used_address = NULL;
1364 			goto sctp_from_the_top;
1365 		}
1366 		/* now try for any higher scope than the destination */
1367 		stcb->asoc.last_used_address = starting_point;
1368 		start_at_beginning = 0;
1369 	sctp_from_the_top2:
1370 		if (stcb->asoc.last_used_address == NULL) {
1371 			start_at_beginning=1;
1372 			stcb->asoc.last_used_address = LIST_FIRST(&inp->sctp_addr_list);
1373 		}
1374 		/* search beginning with the last used address */
1375 		for (laddr = stcb->asoc.last_used_address; laddr;
1376 		     laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
1377 			if (laddr->ifa == NULL) {
1378 				/* address has been removed */
1379 				continue;
1380 			}
1381 			sin6 = sctp_is_v6_ifa_addr_acceptable (laddr->ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1382 			if (sin6 == NULL)
1383 				continue;
1384 			if ((non_asoc_addr_ok == 0) && (sctp_is_addr_restricted(stcb, (struct sockaddr *)sin6))) {
1385 				/* on the no-no list */
1386 				continue;
1387 			}
1388 			return (sin6);
1389 		}
1390 		if (start_at_beginning == 0) {
1391 			stcb->asoc.last_used_address = NULL;
1392 			goto sctp_from_the_top2;
1393 		}
1394 	} else {
1395 #ifdef SCTP_DEBUG
1396 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1397 			printf("Have a STCB - no asconf allowed, not bound all have a positive list\n");
1398 		}
1399 #endif
1400 		/* First try for interface output match */
1401 		LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list,
1402 			     sctp_nxt_addr) {
1403 			if (laddr->ifa == NULL) {
1404 				/* address has been removed */
1405 				continue;
1406 			}
1407 			sin6 = sctp_is_v6_ifa_addr_acceptable (laddr->ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1408 			if (sin6 == NULL)
1409 				continue;
1410 			/* first question, is laddr->ifa an address associated with the emit interface */
1411 			if (ifn) {
1412 				IFADDR_READER_FOREACH(ifa, ifn) {
1413 					if (laddr->ifa == ifa) {
1414 						sin6 = (struct sockaddr_in6 *)laddr->ifa->ifa_addr;
1415 						return (sin6);
1416 					}
1417 					if (sctp_cmpaddr(ifa->ifa_addr, laddr->ifa->ifa_addr) == 1) {
1418 						sin6 = (struct sockaddr_in6 *)laddr->ifa->ifa_addr;
1419 						return (sin6);
1420 					}
1421 				}
1422 			}
1423 		}
1424 		/* Next try for matching scope */
1425 		LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list,
1426 			     sctp_nxt_addr) {
1427 			if (laddr->ifa == NULL) {
1428 				/* address has been removed */
1429 				continue;
1430 			}
1431 			sin6 = sctp_is_v6_ifa_addr_acceptable (laddr->ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1432 			if (sin6 == NULL)
1433 				continue;
1434 
1435 			if ((loopscope == 0) &&
1436 			    (loc_scope == 0) &&
1437 			    (sin_loop == 0) &&
1438 			    (sin_local == 0)) {
1439 				/* all of global scope we are ok with it */
1440 				return (sin6);
1441 			}
1442 			if (loopscope && sin_loop)
1443 				/* both on the loopback, thats ok */
1444 				return (sin6);
1445 			if (loc_scope && sin_local)
1446 				/* both local scope */
1447 				return (sin6);
1448 		}
1449 		/* ok, now try for a higher scope in the source address */
1450 		/* First try for matching scope */
1451 		LIST_FOREACH(laddr, &stcb->asoc.sctp_local_addr_list,
1452 			     sctp_nxt_addr) {
1453 			if (laddr->ifa == NULL) {
1454 				/* address has been removed */
1455 				continue;
1456 			}
1457 			sin6 = sctp_is_v6_ifa_addr_acceptable (laddr->ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1458 			if (sin6 == NULL)
1459 				continue;
1460 			return (sin6);
1461 		}
1462 	}
1463 	return (NULL);
1464 }
1465 
1466 static struct sockaddr_in6 *
1467 sctp_choose_v6_boundspecific_inp(struct sctp_inpcb *inp,
1468 				 struct rtentry *rt,
1469 				 uint8_t loc_scope,
1470 				 uint8_t loopscope)
1471 {
1472 	/*
1473 	 * Here we are bound specific and have only
1474 	 * an inp. We must find an address that is bound
1475 	 * that we can give out as a src address. We
1476 	 * prefer two addresses of same scope if we can
1477 	 * find them that way.
1478 	 */
1479 	struct sctp_laddr *laddr;
1480 	struct sockaddr_in6 *sin6;
1481 	struct ifnet *ifn;
1482 	struct ifaddr *ifa;
1483 	int sin_loop, sin_local;
1484 
1485 	/* first question, is the ifn we will emit on
1486 	 * in our list, if so, we want that one.
1487 	 */
1488 
1489 	ifn = rt->rt_ifp;
1490 	if (ifn) {
1491 		IFADDR_READER_FOREACH(ifa, ifn) {
1492 			sin6 = sctp_is_v6_ifa_addr_acceptable (ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1493 			if (sin6 == NULL)
1494 				continue;
1495 			if (sctp_is_addr_in_ep(inp, ifa)) {
1496 				return (sin6);
1497 			}
1498 		}
1499 	}
1500 	for (laddr = LIST_FIRST(&inp->sctp_addr_list);
1501 	     laddr && (laddr != inp->next_addr_touse);
1502 	     laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
1503 		if (laddr->ifa == NULL) {
1504 			/* address has been removed */
1505 			continue;
1506 		}
1507 		sin6 = sctp_is_v6_ifa_addr_acceptable (laddr->ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1508 		if (sin6 == NULL)
1509 			continue;
1510 
1511 		if ((loopscope == 0) &&
1512 		    (loc_scope == 0) &&
1513 		    (sin_loop == 0) &&
1514 		    (sin_local == 0)) {
1515 			/* all of global scope we are ok with it */
1516 			return (sin6);
1517 		}
1518 		if (loopscope && sin_loop)
1519 			/* both on the loopback, thats ok */
1520 			return (sin6);
1521 		if (loc_scope && sin_local)
1522 			/* both local scope */
1523 			return (sin6);
1524 
1525 	}
1526 	/* if we reach here, we could not find two addresses
1527 	 * of the same scope to give out. Lets look for any higher level
1528 	 * scope for a source address.
1529 	 */
1530 	for (laddr = LIST_FIRST(&inp->sctp_addr_list);
1531 	     laddr && (laddr != inp->next_addr_touse);
1532 	     laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
1533 		if (laddr->ifa == NULL) {
1534 			/* address has been removed */
1535 			continue;
1536 		}
1537 		sin6 = sctp_is_v6_ifa_addr_acceptable (laddr->ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1538 		if (sin6 == NULL)
1539 			continue;
1540 		return (sin6);
1541 	}
1542 	/* no address bound can be a source for the destination */
1543 #ifdef SCTP_DEBUG
1544 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1545 		printf("Src address selection for EP, no acceptable src address found for address\n");
1546 	}
1547 #endif
1548 	return (NULL);
1549 }
1550 
1551 
1552 static struct sockaddr_in6 *
1553 sctp_select_v6_nth_addr_from_ifn_boundall (struct ifnet *ifn, struct sctp_tcb *stcb, int non_asoc_addr_ok, uint8_t loopscope,
1554 					   uint8_t loc_scope, int cur_addr_num, int match_scope)
1555 {
1556 	struct ifaddr *ifa;
1557 	struct sockaddr_in6 *sin6;
1558 	int sin_loop, sin_local;
1559 	int num_eligible_addr = 0;
1560 
1561 	IFADDR_READER_FOREACH(ifa, ifn) {
1562 		sin6 = sctp_is_v6_ifa_addr_acceptable (ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1563 		if (sin6 == NULL)
1564 			continue;
1565 		if (stcb) {
1566 			if ((non_asoc_addr_ok == 0) && sctp_is_addr_restricted(stcb, (struct sockaddr *)sin6)) {
1567 				/* It is restricted for some reason.. probably
1568 				 * not yet added.
1569 				 */
1570 				continue;
1571 			}
1572 		}
1573 		if (match_scope) {
1574 			/* Here we are asked to match scope if possible */
1575 			if (loopscope && sin_loop)
1576 				/* src and destination are loopback scope */
1577 				return (sin6);
1578 			if (loc_scope && sin_local)
1579 				/* src and destination are local scope */
1580 				return (sin6);
1581 			if ((loopscope == 0) &&
1582 			    (loc_scope == 0)  &&
1583 			    (sin_loop == 0) &&
1584 			    (sin_local == 0)) {
1585 				/* src and destination are global scope */
1586 				return (sin6);
1587 			}
1588 			continue;
1589 		}
1590 		if (num_eligible_addr == cur_addr_num) {
1591 			/* this is it */
1592 			return (sin6);
1593 		}
1594 		num_eligible_addr++;
1595 	}
1596 	return (NULL);
1597 }
1598 
1599 
1600 static int
1601 sctp_count_v6_num_eligible_boundall (struct ifnet *ifn, struct sctp_tcb *stcb,
1602 				     int non_asoc_addr_ok, uint8_t loopscope, uint8_t loc_scope)
1603 {
1604 	struct ifaddr *ifa;
1605 	struct sockaddr_in6 *sin6;
1606 	int num_eligible_addr = 0;
1607 	int sin_loop, sin_local;
1608 
1609 	IFADDR_READER_FOREACH(ifa, ifn) {
1610 		sin6 = sctp_is_v6_ifa_addr_acceptable (ifa, loopscope, loc_scope, &sin_loop, &sin_local);
1611 		if (sin6 == NULL)
1612 			continue;
1613 		if (stcb) {
1614 			if ((non_asoc_addr_ok == 0) && sctp_is_addr_restricted(stcb, (struct sockaddr *)sin6)) {
1615 				/* It is restricted for some reason.. probably
1616 				 * not yet added.
1617 				 */
1618 				continue;
1619 			}
1620 		}
1621 		num_eligible_addr++;
1622 	}
1623 	return (num_eligible_addr);
1624 }
1625 
1626 
1627 static struct sockaddr_in6 *
1628 sctp_choose_v6_boundall(struct sctp_inpcb *inp,
1629 			struct sctp_tcb *stcb,
1630 			struct sctp_nets *net,
1631 			struct rtentry *rt,
1632 			uint8_t loc_scope,
1633 			uint8_t loopscope,
1634 			int non_asoc_addr_ok)
1635 {
1636 	/* Ok, we are bound all SO any address
1637 	 * is ok to use as long as it is NOT in the negative
1638 	 * list.
1639 	 */
1640 	int num_eligible_addr;
1641 	int cur_addr_num=0;
1642 	int started_at_beginning=0;
1643 	int match_scope_prefered;
1644 	/* first question is, how many eligible addresses are
1645 	 * there for the destination ifn that we are using that
1646 	 * are within the proper scope?
1647 	 */
1648 	struct ifnet *ifn;
1649 	struct sockaddr_in6 *sin6;
1650 	int s;
1651 
1652 	ifn = rt->rt_ifp;
1653 	if (net) {
1654 		cur_addr_num = net->indx_of_eligible_next_to_use;
1655 	}
1656 	if (cur_addr_num == 0) {
1657 		match_scope_prefered = 1;
1658 	} else {
1659 		match_scope_prefered = 0;
1660 	}
1661 	num_eligible_addr = sctp_count_v6_num_eligible_boundall (ifn, stcb, non_asoc_addr_ok, loopscope, loc_scope);
1662 #ifdef SCTP_DEBUG
1663 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1664 		printf("Found %d eligible source addresses\n", num_eligible_addr);
1665 	}
1666 #endif
1667 	if (num_eligible_addr == 0) {
1668 		/* no eligible addresses, we must use some other
1669 		 * interface address if we can find one.
1670 		 */
1671  		goto bound_all_v6_plan_b;
1672 	}
1673 	/* Ok we have num_eligible_addr set with how many we can use,
1674 	 * this may vary from call to call due to addresses being deprecated etc..
1675 	 */
1676 	if (cur_addr_num >= num_eligible_addr) {
1677 		cur_addr_num = 0;
1678 	}
1679 	/* select the nth address from the list (where cur_addr_num is the nth) and
1680 	 * 0 is the first one, 1 is the second one etc...
1681 	 */
1682 #ifdef SCTP_DEBUG
1683 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1684 		printf("cur_addr_num:%d match_scope_prefered:%d select it\n",
1685 		       cur_addr_num, match_scope_prefered);
1686 	}
1687 #endif
1688 	sin6 = sctp_select_v6_nth_addr_from_ifn_boundall (ifn, stcb, non_asoc_addr_ok, loopscope,
1689 							  loc_scope, cur_addr_num, match_scope_prefered);
1690 	if (match_scope_prefered && (sin6 == NULL)) {
1691 		/* retry without the preference for matching scope */
1692 #ifdef SCTP_DEBUG
1693 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1694 		printf("retry with no match_scope_prefered\n");
1695 	}
1696 #endif
1697 		sin6 = sctp_select_v6_nth_addr_from_ifn_boundall (ifn, stcb, non_asoc_addr_ok, loopscope,
1698 								  loc_scope, cur_addr_num, 0);
1699 	}
1700 	if (sin6) {
1701 #ifdef SCTP_DEBUG
1702 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1703 			printf("Selected address %d ifn:%p for the route\n", cur_addr_num, ifn);
1704 		}
1705 #endif
1706 		if (net) {
1707 			/* store so we get the next one */
1708 			if (cur_addr_num < 255)
1709 				net->indx_of_eligible_next_to_use = cur_addr_num + 1;
1710 			else
1711 				net->indx_of_eligible_next_to_use = 0;
1712 		}
1713 		return (sin6);
1714 	}
1715 	num_eligible_addr = 0;
1716  bound_all_v6_plan_b:
1717 	/* ok, if we reach here we either fell through
1718 	 * due to something changing during an interrupt (unlikely)
1719 	 * or we have NO eligible source addresses for the ifn
1720 	 * of the route (most likely). We must look at all the other
1721 	 * interfaces EXCEPT rt->rt_ifp and do the same game.
1722 	 */
1723 #ifdef SCTP_DEBUG
1724 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1725 		printf("bound-all Plan B\n");
1726 	}
1727 #endif
1728 	if (inp->next_ifn_touse == NULL) {
1729 		started_at_beginning=1;
1730 		inp->next_ifn_touse = IFNET_READER_FIRST();
1731 #ifdef SCTP_DEBUG
1732 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1733 			printf("Start at first IFN:%p\n", inp->next_ifn_touse);
1734 		}
1735 #endif
1736 	} else {
1737 		inp->next_ifn_touse = IFNET_READER_NEXT(inp->next_ifn_touse);
1738 #ifdef SCTP_DEBUG
1739 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1740 			printf("Resume at IFN:%p\n", inp->next_ifn_touse);
1741 		}
1742 #endif
1743 		if (inp->next_ifn_touse == NULL) {
1744 #ifdef SCTP_DEBUG
1745 			if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1746 				printf("IFN Resets\n");
1747 			}
1748 #endif
1749 			started_at_beginning=1;
1750 			inp->next_ifn_touse = IFNET_READER_FIRST();
1751 		}
1752 	}
1753 
1754 	s = pserialize_read_enter();
1755 	IFNET_READER_FOREACH(ifn) {
1756 		if (loopscope == 0 && ifn->if_type == IFT_LOOP) {
1757 			/* wrong base scope */
1758 			continue;
1759 		}
1760 		if (loc_scope && (ifn->if_index != loc_scope)) {
1761 			/* by definition the scope (from to->sin6_scopeid)
1762 			 * must match that of the interface. If not then
1763 			 * we could pick a wrong scope for the address.
1764 			 * Usually we don't hit plan-b since the route
1765 			 * handles this. However we can hit plan-b when
1766 			 * we send to local-host so the route is the
1767 			 * loopback interface, but the destination is a
1768 			 * link local.
1769 			 */
1770 			continue;
1771 		}
1772 		if (ifn == rt->rt_ifp) {
1773 			/* already looked at this guy */
1774 			continue;
1775 		}
1776 		/* Address rotation will only work when we are not
1777 		 * rotating sourced interfaces and are using the interface
1778 		 * of the route. We would need to have a per interface index
1779 		 * in order to do proper rotation.
1780 		 */
1781 		num_eligible_addr = sctp_count_v6_num_eligible_boundall (ifn, stcb, non_asoc_addr_ok, loopscope, loc_scope);
1782 #ifdef SCTP_DEBUG
1783 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1784 			printf("IFN:%p has %d eligible\n", ifn, num_eligible_addr);
1785 		}
1786 #endif
1787 		if (num_eligible_addr == 0) {
1788 			/* none we can use */
1789 			continue;
1790 		}
1791 		/* Ok we have num_eligible_addr set with how many we can use,
1792 		 * this may vary from call to call due to addresses being deprecated etc..
1793 		 */
1794 		inp->next_ifn_touse = ifn;
1795 
1796 		/* select the first one we can find with perference for matching scope.
1797 		 */
1798 		sin6 = sctp_select_v6_nth_addr_from_ifn_boundall (ifn, stcb, non_asoc_addr_ok, loopscope, loc_scope, 0, 1);
1799 		if (sin6 == NULL) {
1800 			/* can't find one with matching scope how about a source with higher
1801 			 * scope
1802 			 */
1803  			sin6 = sctp_select_v6_nth_addr_from_ifn_boundall (ifn, stcb, non_asoc_addr_ok, loopscope, loc_scope, 0, 0);
1804 			if (sin6 == NULL)
1805 				/* Hmm, can't find one in the interface now */
1806 				continue;
1807 		}
1808 #ifdef SCTP_DEBUG
1809 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1810 			printf("Selected the %d'th address of ifn:%p\n",
1811 			       cur_addr_num, ifn);
1812 		}
1813 #endif
1814 		pserialize_read_exit(s);
1815 		return (sin6);
1816 	}
1817 	pserialize_read_exit(s);
1818 
1819 	if (started_at_beginning == 0) {
1820 		/* we have not been through all of them yet, force
1821 		 * us to go through them all.
1822 		 */
1823 #ifdef SCTP_DEBUG
1824 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1825 			printf("Force a recycle\n");
1826 		}
1827 #endif
1828 		inp->next_ifn_touse = NULL;
1829 		goto bound_all_v6_plan_b;
1830 	}
1831 	return (NULL);
1832 
1833 }
1834 
1835 /* stcb and net may be NULL */
1836 struct in6_addr
1837 sctp_ipv6_source_address_selection(struct sctp_inpcb *inp,
1838     struct sctp_tcb *stcb, struct route *ro, struct sctp_nets *net,
1839     int non_asoc_addr_ok)
1840 {
1841 	struct in6_addr ans;
1842 	struct sockaddr_in6 *rt_addr;
1843 	uint8_t loc_scope, loopscope;
1844 	struct sockaddr_in6 to;
1845 	struct rtentry *rt;
1846 
1847 	/*
1848 	 * This routine is tricky standard v6 src address
1849 	 * selection cannot take into account what we have
1850 	 * bound etc, so we can't use it.
1851 	 *
1852 	 * Instead here is what we must do:
1853 	 * 1) Make sure we have a route, if we
1854 	 *    don't have a route we can never reach the peer.
1855 	 * 2) Once we have a route, determine the scope of the
1856 	 *     route. Link local, loopback or global.
1857 	 * 3) Next we divide into three types. Either we
1858 	 *    are bound all.. which means we want to use
1859 	 *    one of the addresses of the interface we are
1860 	 *    going out. <or>
1861 	 * 4a) We have not stcb, which means we are using the
1862 	 *    specific addresses bound on an inp, in this
1863 	 *    case we are similar to the stcb case (4b below)
1864 	 *    accept the list is always a positive list.<or>
1865 	 * 4b) We are bound specific with a stcb, which means we have a
1866 	 *    list of bound addresses and we must see if the
1867 	 *    ifn of the route is actually one of the bound addresses.
1868 	 *    If not, then we must rotate addresses amongst properly
1869 	 *    scoped bound addresses, if so we use the address
1870 	 *    of the interface.
1871 	 * 5) Always, no matter which path we take through the above
1872 	 *    we must be sure the source address we use is allowed to
1873 	 *    be used. I.e.  IN6_IFF_DETACHED, IN6_IFF_NOTREADY, and IN6_IFF_ANYCAST
1874 	 *    addresses cannot be used.
1875 	 * 6) Addresses that are deprecated MAY be used
1876 	 * 		if (!ip6_use_deprecated) {
1877 	 *                    if (IFA6_IS_DEPRECATED(ifa6)) {
1878 	 *	                  skip the address
1879   	 *	              }
1880 	 *	        }
1881  	 */
1882 
1883 	/*** 1> determine route, if not already done */
1884 	rt = rtcache_validate(ro);
1885 	if (rt == NULL) {
1886 		/*
1887 		 * Need a route to cache.
1888 		 */
1889 		int scope_save;
1890 
1891 		memcpy(&to, rtcache_getdst(ro), sizeof(struct sockaddr));
1892 		scope_save = to.sin6_scope_id;
1893 		to.sin6_scope_id = 0;
1894 
1895 		rt = rtcache_lookup(ro, (struct sockaddr *)&to);
1896 		to.sin6_scope_id = scope_save;
1897 	}
1898 	if (rt == NULL) {
1899 		/*
1900 		 * no route to host. this packet is going no-where.
1901 		 * We probably should make sure we arrange to send back
1902 		 * an error.
1903 		 */
1904 #ifdef SCTP_DEBUG
1905 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1906 			printf("No route to host, this packet cannot be sent!\n");
1907 		}
1908 #endif
1909 		memset(&ans, 0, sizeof(ans));
1910 		return (ans);
1911 	}
1912 
1913 	/*** 2a> determine scope for outbound address/route */
1914 	loc_scope = loopscope = 0;
1915 	/*
1916 	 * We base our scope on the outbound packet scope and route,
1917 	 * NOT the TCB (if there is one). This way in local scope we will only
1918 	 * use a local scope src address when we send to a local address.
1919 	 */
1920 
1921 	if (IN6_IS_ADDR_LOOPBACK(&to.sin6_addr)) {
1922 		/* If the route goes to the loopback address OR
1923 		 * the address is a loopback address, we are loopback
1924 		 * scope.
1925 		 */
1926 #ifdef SCTP_DEBUG
1927 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1928 			printf("Loopback scope is set\n");
1929 		}
1930 #endif
1931 		loc_scope = 0;
1932 		loopscope = 1;
1933 		if (net != NULL) {
1934 			/* mark it as local */
1935 			net->addr_is_local = 1;
1936 		}
1937 
1938 	} else if (IN6_IS_ADDR_LINKLOCAL(&to.sin6_addr)) {
1939 #ifdef SCTP_DEBUG
1940 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1941 			printf("Link local scope is set, id:%d\n", to.sin6_scope_id);
1942 		}
1943 #endif
1944 		if (to.sin6_scope_id)
1945 			loc_scope = to.sin6_scope_id;
1946 		else {
1947 			loc_scope = 1;
1948 		}
1949 		loopscope = 0;
1950 	} else {
1951 #ifdef SCTP_DEBUG
1952 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1953 			printf("Global scope is set\n");
1954 		}
1955 #endif
1956 	}
1957 
1958 	/* now, depending on which way we are bound we call the appropriate
1959 	 * routine to do steps 3-6
1960 	 */
1961 #ifdef SCTP_DEBUG
1962 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1963 		printf("Destination address:");
1964 		sctp_print_address((struct sockaddr *)&to);
1965 	}
1966 #endif
1967 
1968 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
1969 #ifdef SCTP_DEBUG
1970 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1971 			printf("Calling bound-all src addr selection for v6\n");
1972 		}
1973 #endif
1974 		rt_addr = sctp_choose_v6_boundall(inp, stcb, net, rt, loc_scope, loopscope, non_asoc_addr_ok);
1975 	} else {
1976 #ifdef SCTP_DEBUG
1977 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1978 			printf("Calling bound-specific src addr selection for v6\n");
1979 		}
1980 #endif
1981 		if (stcb)
1982 			rt_addr = sctp_choose_v6_boundspecific_stcb(inp, stcb, net, rt, loc_scope, loopscope,  non_asoc_addr_ok);
1983 		else
1984 			/* we can't have a non-asoc address since we have no association */
1985 			rt_addr = sctp_choose_v6_boundspecific_inp(inp,  rt, loc_scope, loopscope);
1986 	}
1987 	rtcache_unref(rt, ro);
1988 	if (rt_addr == NULL) {
1989 		/* no suitable address? */
1990 		struct in6_addr in6;
1991 #ifdef SCTP_DEBUG
1992 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
1993 			printf("V6 packet will reach dead-end no suitable src address\n");
1994 		}
1995 #endif
1996 		memset(&in6, 0, sizeof(in6));
1997 		return (in6);
1998 	}
1999 #ifdef SCTP_DEBUG
2000 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
2001 		printf("Source address selected is:");
2002 		sctp_print_address((struct sockaddr *)rt_addr);
2003 	}
2004 #endif
2005 	return (rt_addr->sin6_addr);
2006 }
2007 
2008 static uint8_t
2009 sctp_get_ect(struct sctp_tcb *stcb,
2010 	     struct sctp_tmit_chunk *chk)
2011 {
2012 	uint8_t this_random;
2013 
2014 	/* Huh? */
2015 	if (sctp_ecn == 0)
2016 		return (0);
2017 
2018 	if (sctp_ecn_nonce == 0)
2019 		/* no nonce, always return ECT0 */
2020 		return (SCTP_ECT0_BIT);
2021 
2022 	if (stcb->asoc.peer_supports_ecn_nonce == 0) {
2023 		/* Peer does NOT support it, so we send a ECT0 only */
2024  		return (SCTP_ECT0_BIT);
2025 	}
2026 
2027 	if (chk == NULL)
2028 	   return (SCTP_ECT0_BIT);
2029 
2030 	if (((stcb->asoc.hb_random_idx == 3) &&
2031 	     (stcb->asoc.hb_ect_randombit > 7)) ||
2032 	     (stcb->asoc.hb_random_idx > 3)) {
2033 		uint32_t rndval;
2034 		rndval = sctp_select_initial_TSN(&stcb->sctp_ep->sctp_ep);
2035 		memcpy(stcb->asoc.hb_random_values, &rndval,
2036 		       sizeof(stcb->asoc.hb_random_values));
2037 		this_random = stcb->asoc.hb_random_values[0];
2038 		stcb->asoc.hb_random_idx = 0;
2039 		stcb->asoc.hb_ect_randombit = 0;
2040 	} else {
2041 		if (stcb->asoc.hb_ect_randombit > 7) {
2042 		  stcb->asoc.hb_ect_randombit = 0;
2043 		  stcb->asoc.hb_random_idx++;
2044 		}
2045 		this_random = stcb->asoc.hb_random_values[stcb->asoc.hb_random_idx];
2046 	}
2047 	if ((this_random >> stcb->asoc.hb_ect_randombit) & 0x01) {
2048 		if (chk != NULL)
2049 			/* ECN Nonce stuff */
2050 			chk->rec.data.ect_nonce = SCTP_ECT1_BIT;
2051 		stcb->asoc.hb_ect_randombit++;
2052 		return (SCTP_ECT1_BIT);
2053 	} else {
2054 		stcb->asoc.hb_ect_randombit++;
2055 		return (SCTP_ECT0_BIT);
2056 	}
2057 }
2058 
2059 extern int sctp_no_csum_on_loopback;
2060 
2061 static int
2062 sctp_lowlevel_chunk_output(struct sctp_inpcb *inp,
2063 			   struct sctp_tcb *stcb,    /* may be NULL */
2064 			   struct sctp_nets *net,
2065 			   const struct sockaddr *to,
2066 			   struct mbuf *m,
2067 			   int nofragment_flag,
2068 			   int ecn_ok,
2069 			   struct sctp_tmit_chunk *chk,
2070 			   int out_of_asoc_ok)
2071 	/* nofragment_flag to tell if IP_DF should be set (IPv4 only) */
2072 {
2073 	/*
2074 	 * Given a mbuf chain (via m_next) that holds a packet header
2075 	 * WITH a SCTPHDR but no IP header, endpoint inp and sa structure.
2076 	 * - calculate SCTP checksum and fill in
2077 	 * - prepend a IP address header
2078 	 * - if boundall use INADDR_ANY
2079 	 * - if boundspecific do source address selection
2080 	 * - set fragmentation option for ipV4
2081 	 * - On return from IP output, check/adjust mtu size
2082 	 * - of output interface and smallest_mtu size as well.
2083 	 */
2084 	struct sctphdr *sctphdr;
2085 	int o_flgs;
2086 	uint32_t csum;
2087 	int ret;
2088 	unsigned int have_mtu;
2089 	struct route *ro;
2090 	struct rtentry *rt;
2091 
2092 	if ((net) && (net->dest_state & SCTP_ADDR_OUT_OF_SCOPE)) {
2093 		sctp_m_freem(m);
2094 		return (EFAULT);
2095 	}
2096 	if ((m->m_flags & M_PKTHDR) == 0) {
2097 #ifdef SCTP_DEBUG
2098 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
2099 			printf("Software error: sctp_lowlevel_chunk_output() called with non pkthdr!\n");
2100 		}
2101 #endif
2102 		sctp_m_freem(m);
2103 		return (EFAULT);
2104 	}
2105 	/* Calculate the csum and fill in the length of the packet */
2106 	sctphdr = mtod(m, struct sctphdr *);
2107 	have_mtu = 0;
2108 	if (sctp_no_csum_on_loopback &&
2109 	     (stcb) &&
2110 	     (stcb->asoc.loopback_scope)) {
2111 		sctphdr->checksum = 0;
2112 		m->m_pkthdr.len = sctp_calculate_len(m);
2113 	} else {
2114 		sctphdr->checksum = 0;
2115 		csum = sctp_calculate_sum(m, &m->m_pkthdr.len, 0);
2116 		sctphdr->checksum = csum;
2117 	}
2118 	if (to->sa_family == AF_INET) {
2119 		struct ip *ip;
2120 		static struct route iproute;
2121 		M_PREPEND(m, sizeof(struct ip), M_DONTWAIT);
2122 		if (m == NULL) {
2123 			/* failed to prepend data, give up */
2124 			return (ENOMEM);
2125 		}
2126 		ip = mtod(m, struct ip *);
2127 		ip->ip_v = IPVERSION;
2128 		ip->ip_hl = (sizeof(struct ip) >> 2);
2129 		if (nofragment_flag) {
2130 			ip->ip_off = htons(IP_DF);
2131 		} else
2132 			ip->ip_off = 0;
2133 
2134 		ip->ip_id = htons(ip_newid(NULL));
2135 		ip->ip_ttl = inp->inp_ip_ttl;
2136 		ip->ip_len = htons(m->m_pkthdr.len);
2137 		if (stcb) {
2138 			if ((stcb->asoc.ecn_allowed) && ecn_ok) {
2139 				/* Enable ECN */
2140 				ip->ip_tos = (u_char)((in4p_ip(&inp->ip_inp.inp).ip_tos & 0x000000fc) |
2141 						      sctp_get_ect(stcb, chk));
2142 			} else {
2143 				/* No ECN */
2144 				ip->ip_tos = in4p_ip(&inp->ip_inp.inp).ip_tos;
2145 			}
2146 		} else {
2147 			/* no association at all */
2148 			ip->ip_tos = inp->inp_ip_tos;
2149 		}
2150 		ip->ip_p = IPPROTO_SCTP;
2151 		ip->ip_sum = 0;
2152 #ifdef SCTP_DEBUG
2153 		printf("chunk_output: net %p\n", net);
2154 #endif
2155 		if (net == NULL) {
2156 			ro = &iproute;
2157 			memset(&iproute, 0, sizeof(iproute));
2158 			/* XXX */
2159 			rt = rtcache_lookup(ro, to);
2160 			rtcache_unref(rt, ro);
2161 		} else {
2162 			ro = (struct route *)&net->ro;
2163 		}
2164 		/* Now the address selection part */
2165 		ip->ip_dst.s_addr = satocsin(to)->sin_addr.s_addr;
2166 
2167 		/* call the routine to select the src address */
2168 		if (net) {
2169 			if (net->src_addr_selected == 0) {
2170 				/* Cache the source address */
2171 				((struct sockaddr_in *)&net->_s_addr)->sin_addr = sctp_ipv4_source_address_selection(inp,
2172 				    stcb,
2173 				    ro, net, out_of_asoc_ok);
2174 				rt = rtcache_validate(ro);
2175 				if (rt != NULL) {
2176 					net->src_addr_selected = 1;
2177 				}
2178 				rtcache_unref(rt, ro);
2179 			}
2180 			ip->ip_src = ((struct sockaddr_in *)&net->_s_addr)->sin_addr;
2181 		} else {
2182 			ip->ip_src = sctp_ipv4_source_address_selection(inp,
2183 			    stcb, ro, net, out_of_asoc_ok);
2184 		}
2185 #ifdef SCTP_DEBUG
2186 		printf("src addr %x\n", ip->ip_src.s_addr);
2187 #endif
2188 		/*
2189 		 * If source address selection fails and we find no route then
2190 		 * the ip_output should fail as well with a NO_ROUTE_TO_HOST
2191 		 * type error. We probably should catch that somewhere and
2192 		 * abort the association right away (assuming this is an INIT
2193 		 * being sent).
2194 		 */
2195 		rt = rtcache_validate(ro);
2196 		if (rt == NULL) {
2197 			/*
2198 			 * src addr selection failed to find a route (or valid
2199 			 * source addr), so we can't get there from here!
2200 			 */
2201 #ifdef SCTP_DEBUG
2202 			if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
2203 				printf("low_level_output: dropped v4 packet- no valid source addr\n");
2204 				printf("Destination was %x\n", (u_int)(ntohl(ip->ip_dst.s_addr)));
2205 			}
2206 #endif /* SCTP_DEBUG */
2207 			if (net) {
2208 				if ((net->dest_state & SCTP_ADDR_REACHABLE) && stcb)
2209 					sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_DOWN,
2210 							stcb,
2211 							SCTP_FAILED_THRESHOLD,
2212 							(void *)net);
2213 				net->dest_state &= ~SCTP_ADDR_REACHABLE;
2214 				net->dest_state |= SCTP_ADDR_NOT_REACHABLE;
2215 				if (stcb) {
2216 					if (net == stcb->asoc.primary_destination) {
2217 						/* need a new primary */
2218 						struct sctp_nets *alt;
2219 						alt = sctp_find_alternate_net(stcb, net);
2220 						if (alt != net) {
2221 							if (sctp_set_primary_addr(stcb,
2222 									      (struct sockaddr *)NULL,
2223 										 alt) == 0) {
2224 								net->dest_state |= SCTP_ADDR_WAS_PRIMARY;
2225 								net->src_addr_selected = 0;
2226 							}
2227 						}
2228 					}
2229 				}
2230 			}
2231 			sctp_m_freem(m);
2232 			return (EHOSTUNREACH);
2233 		} else {
2234 			have_mtu = rt->rt_ifp->if_mtu;
2235 		}
2236 
2237 		o_flgs = (IP_RAWOUTPUT | (inp->sctp_socket->so_options & (SO_DONTROUTE | SO_BROADCAST)));
2238 #ifdef SCTP_DEBUG
2239 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
2240 			printf("Calling ipv4 output routine from low level src addr:%x\n",
2241 			       (u_int)(ntohl(ip->ip_src.s_addr)));
2242 			printf("Destination is %x\n", (u_int)(ntohl(ip->ip_dst.s_addr)));
2243 			printf("RTP route is %p through\n", rt);
2244 			printf("length %d\n", ntohs(ip->ip_len));
2245 		}
2246 #endif
2247 		if ((have_mtu) && (net) && (have_mtu > net->mtu)) {
2248 			rt->rt_ifp->if_mtu = net->mtu;
2249 		}
2250 		ret = ip_output(m, inp->ip_inp.inp.inp_options,
2251 				ro, o_flgs, inp->ip_inp.inp.inp_moptions,
2252                                 &inp->ip_inp.inp);
2253 		if ((rt) && (have_mtu) && (net) && (have_mtu > net->mtu)) {
2254 			rt->rt_ifp->if_mtu = have_mtu;
2255 		}
2256 		sctp_pegs[SCTP_DATAGRAMS_SENT]++;
2257 #ifdef SCTP_DEBUG
2258 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
2259 			printf("Ip output returns %d\n", ret);
2260 		}
2261 #endif
2262 		if (net == NULL) {
2263 		} else {
2264 			/* PMTU check versus smallest asoc MTU goes here */
2265 			if (rt != NULL) {
2266 				if (rt->rt_rmx.rmx_mtu &&
2267 				    (stcb->asoc.smallest_mtu > rt->rt_rmx.rmx_mtu)) {
2268 					sctp_mtu_size_reset(inp, &stcb->asoc,
2269 					    rt->rt_rmx.rmx_mtu);
2270 				}
2271 			} else {
2272 				/* route was freed */
2273 				net->src_addr_selected = 0;
2274 			}
2275 		}
2276 		rtcache_unref(rt, ro);
2277 		return (ret);
2278 	}
2279 #ifdef INET6
2280 	else if (to->sa_family == AF_INET6) {
2281 		struct ip6_hdr *ip6h;
2282 		static struct route ip6route;
2283 		struct ifnet *ifp;
2284 		u_char flowTop;
2285 		uint16_t flowBottom;
2286 		u_char tosBottom, tosTop;
2287 		struct sockaddr_in6 *sin6, tmp, *lsa6, lsa6_tmp;
2288 		int prev_scope=0;
2289 		u_short prev_port=0;
2290 
2291 		M_PREPEND(m, sizeof(struct ip6_hdr), M_DONTWAIT);
2292 		if (m == NULL) {
2293 			/* failed to prepend data, give up */
2294 			return (ENOMEM);
2295 		}
2296 		ip6h = mtod(m, struct ip6_hdr *);
2297 
2298 		/*
2299 		 * We assume here that inp_flow is in host byte order within
2300 		 * the TCB!
2301 		 */
2302 		flowBottom = in6p_flowinfo(inp) & 0x0000ffff;
2303 		flowTop = ((in6p_flowinfo(inp) & 0x000f0000) >> 16);
2304 
2305 		tosTop = (((in6p_flowinfo(inp) & 0xf0) >> 4) | IPV6_VERSION);
2306 
2307 		/* protect *sin6 from overwrite */
2308 		memcpy(&tmp, to, sizeof(struct sockaddr_in6));
2309 		sin6 = &tmp;
2310 
2311 		/* KAME hack: embed scopeid */
2312 #if defined(SCTP_BASE_FREEBSD) || defined(__APPLE__)
2313 		if (in6_embedscope(&sin6->sin6_addr, sin6, NULL, NULL) != 0)
2314 #else
2315 		/*
2316 		 * XXX: appropriate scope zone must be provided or otherwise
2317 		 * ip6_use_defzone must be 1.
2318 		 */
2319 		if (sa6_embedscope(sin6, ip6_use_defzone) != 0)
2320 #endif
2321 			return (EINVAL);
2322 		if (net == NULL) {
2323 			memset(&ip6route, 0, sizeof(ip6route));
2324 			ro = (struct route *)&ip6route;
2325 			/* XXX */
2326 			rt = rtcache_lookup(ro, (struct sockaddr *) sin6);
2327 			rtcache_unref(rt, ro);
2328 		} else {
2329 			ro = (struct route *)&net->ro;
2330 		}
2331 		if (stcb != NULL) {
2332 			if ((stcb->asoc.ecn_allowed) && ecn_ok) {
2333 				/* Enable ECN */
2334 				tosBottom = (((in6p_flowinfo(inp) & 0x0c) | sctp_get_ect(stcb, chk)) << 4);
2335 			} else {
2336 				/* No ECN */
2337 				tosBottom = ((in6p_flowinfo(inp) & 0x0c) << 4);
2338 			}
2339 		} else {
2340 			/* we could get no asoc if it is a O-O-T-B packet */
2341 			tosBottom = ((in6p_flowinfo(inp) & 0x0c) << 4);
2342 		}
2343 		ip6h->ip6_flow = htonl(((tosTop << 24) | ((tosBottom|flowTop) << 16) | flowBottom));
2344 		ip6h->ip6_nxt = IPPROTO_SCTP;
2345 		ip6h->ip6_plen = m->m_pkthdr.len;
2346 		ip6h->ip6_dst = sin6->sin6_addr;
2347 
2348 		/*
2349 		 * Add SRC address selection here:
2350 		 * we can only reuse to a limited degree the kame src-addr-sel,
2351 		 * since we can try their selection but it may not be bound.
2352 		 */
2353 		memset(&lsa6_tmp, 0, sizeof(lsa6_tmp));
2354 		lsa6_tmp.sin6_family = AF_INET6;
2355 		lsa6_tmp.sin6_len = sizeof(lsa6_tmp);
2356 		lsa6 = &lsa6_tmp;
2357 		rt = rtcache_validate(ro);
2358 		if (net) {
2359 			if (net->src_addr_selected == 0) {
2360 				/* Cache the source address */
2361 				((struct sockaddr_in6 *)&net->_s_addr)->sin6_addr = sctp_ipv6_source_address_selection(inp,
2362 				    stcb, ro, net, out_of_asoc_ok);
2363 
2364 				if (rt != NULL) {
2365 					net->src_addr_selected = 1;
2366 				}
2367 			}
2368 			lsa6->sin6_addr = ((struct sockaddr_in6 *)&net->_s_addr)->sin6_addr;
2369 		} else {
2370 			lsa6->sin6_addr = sctp_ipv6_source_address_selection(
2371 			    inp, stcb, ro, net, out_of_asoc_ok);
2372 		}
2373 		lsa6->sin6_port = inp->sctp_lport;
2374 
2375 		if (rt ==  NULL) {
2376 			/*
2377 			 * src addr selection failed to find a route (or valid
2378 			 * source addr), so we can't get there from here!
2379 			 */
2380 #ifdef SCTP_DEBUG
2381 			if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
2382 				printf("low_level_output: dropped v6 pkt- no valid source addr\n");
2383 			}
2384 #endif
2385 			sctp_m_freem(m);
2386 			if (net) {
2387 				if ((net->dest_state & SCTP_ADDR_REACHABLE) && stcb)
2388 					sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_DOWN,
2389 							stcb,
2390 							SCTP_FAILED_THRESHOLD,
2391 							(void *)net);
2392 				net->dest_state &= ~SCTP_ADDR_REACHABLE;
2393 				net->dest_state |= SCTP_ADDR_NOT_REACHABLE;
2394 				if (stcb) {
2395 					if (net == stcb->asoc.primary_destination) {
2396 						/* need a new primary */
2397 						struct sctp_nets *alt;
2398 						alt = sctp_find_alternate_net(stcb, net);
2399 						if (alt != net) {
2400 							if (sctp_set_primary_addr(stcb,
2401 									      (struct sockaddr *)NULL,
2402 										 alt) == 0) {
2403 								net->dest_state |= SCTP_ADDR_WAS_PRIMARY;
2404 								net->src_addr_selected = 0;
2405 							}
2406 						}
2407 					}
2408 				}
2409 			}
2410 			return (EHOSTUNREACH);
2411 		}
2412 
2413 		ip6h->ip6_src = lsa6->sin6_addr;
2414 
2415 		/*
2416 		 * We set the hop limit now since there is a good chance that
2417 		 * our ro pointer is now filled
2418 		 */
2419 		ip6h->ip6_hlim = in6pcb_selecthlim(&inp->ip_inp.inp,
2420 						(ro ?
2421 						 (rt ? (rt->rt_ifp) : (NULL)) :
2422 						 (NULL)));
2423 		o_flgs = 0;
2424 		ifp = rt->rt_ifp;
2425 #ifdef SCTP_DEBUG
2426 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
2427 			/* Copy to be sure something bad is not happening */
2428 			sin6->sin6_addr = ip6h->ip6_dst;
2429 			lsa6->sin6_addr = ip6h->ip6_src;
2430 
2431 			printf("Calling ipv6 output routine from low level\n");
2432 			printf("src: ");
2433 			sctp_print_address((struct sockaddr *)lsa6);
2434 			printf("dst: ");
2435 			sctp_print_address((struct sockaddr *)sin6);
2436 		}
2437 #endif /* SCTP_DEBUG */
2438 		if (net) {
2439 			sin6 = (struct sockaddr_in6 *)&net->ro.ro_sa;
2440 			/* preserve the port and scope for link local send */
2441 			prev_scope = sin6->sin6_scope_id;
2442 			prev_port = sin6->sin6_port;
2443 		}
2444 		/* XXX NOMPSAFE need to hold ifp here */
2445 		rtcache_unref(rt, ro);
2446 		ret = ip6_output(m, ((struct in6pcb *)inp)->in6p_outputopts,
2447 				 ro,
2448 				 o_flgs,
2449 				 ((struct in6pcb *)inp)->in6p_moptions,
2450 				 (struct inpcb *)inp,
2451 				 &ifp);
2452 		if (net) {
2453 			/* for link local this must be done */
2454 			sin6->sin6_scope_id = prev_scope;
2455 			sin6->sin6_port = prev_port;
2456 		}
2457 #ifdef SCTP_DEBUG
2458 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
2459 			printf("return from send is %d\n", ret);
2460 		}
2461 #endif /* SCTP_DEBUG_OUTPUT */
2462 		sctp_pegs[SCTP_DATAGRAMS_SENT]++;
2463 		if (net) {
2464 			/* PMTU check versus smallest asoc MTU goes here */
2465 			rt = rtcache_validate(ro);
2466 			if (rt == NULL) {
2467 				/* Route was freed */
2468 				net->src_addr_selected = 0;
2469 			}
2470 			if (rt != NULL) {
2471 				if (rt->rt_rmx.rmx_mtu &&
2472 				    (stcb->asoc.smallest_mtu > rt->rt_rmx.rmx_mtu)) {
2473 					sctp_mtu_size_reset(inp,
2474 							    &stcb->asoc,
2475 							    rt->rt_rmx.rmx_mtu);
2476 				}
2477 				rtcache_unref(rt, ro);
2478 			} else if (ifp) {
2479 				if (ifp->if_mtu &&
2480 				    (stcb->asoc.smallest_mtu > ifp->if_mtu)) {
2481 					sctp_mtu_size_reset(inp,
2482 							    &stcb->asoc,
2483 							    ifp->if_mtu);
2484 				}
2485 			}
2486 		}
2487 		return (ret);
2488 	}
2489 #endif
2490 	else {
2491 #ifdef SCTP_DEBUG
2492 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
2493 			printf("Unknown protocol (TSNH) type %d\n", ((const struct sockaddr *)to)->sa_family);
2494 		}
2495 #endif
2496 		sctp_m_freem(m);
2497 		return (EFAULT);
2498 	}
2499 }
2500 
2501 static
2502 int sctp_is_address_in_scope(struct ifaddr *ifa,
2503  			     int ipv4_addr_legal,
2504 			     int ipv6_addr_legal,
2505 			     int loopback_scope,
2506 			     int ipv4_local_scope,
2507 			     int local_scope,
2508 			     int site_scope)
2509 {
2510 	if ((loopback_scope == 0) && (ifa->ifa_ifp->if_type == IFT_LOOP)) {
2511 		/* skip loopback if not in scope *
2512 		 */
2513 		return (0);
2514 	}
2515 	if ((ifa->ifa_addr->sa_family == AF_INET) && ipv4_addr_legal) {
2516 		struct sockaddr_in *sin;
2517 		sin = (struct sockaddr_in *)ifa->ifa_addr;
2518 		if (sin->sin_addr.s_addr == 0) {
2519 			/* not in scope , unspecified */
2520 			return (0);
2521 		}
2522 		if ((ipv4_local_scope == 0) &&
2523 		    (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr))) {
2524 			/* private address not in scope */
2525 			return (0);
2526 		}
2527 	} else if ((ifa->ifa_addr->sa_family == AF_INET6) && ipv6_addr_legal) {
2528 		struct sockaddr_in6 *sin6;
2529 		struct in6_ifaddr *ifa6;
2530 
2531 		ifa6 = (struct in6_ifaddr *)ifa;
2532 		/* ok to use deprecated addresses? */
2533 		if (!ip6_use_deprecated) {
2534 			if (ifa6->ia6_flags &
2535 			    IN6_IFF_DEPRECATED) {
2536 				return (0);
2537 			}
2538 		}
2539 		if (ifa6->ia6_flags &
2540 		    (IN6_IFF_DETACHED |
2541 		     IN6_IFF_ANYCAST |
2542 		     IN6_IFF_NOTREADY)) {
2543 			return (0);
2544 		}
2545 		sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
2546 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
2547 			/* skip unspecified addresses */
2548 			return (0);
2549 		}
2550 		if (/*(local_scope == 0) && */
2551 		    (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr))) {
2552 			return (0);
2553 		}
2554 		if ((site_scope == 0) &&
2555 		    (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr))) {
2556 			return (0);
2557 		}
2558 	} else {
2559 		return (0);
2560 	}
2561 	return (1);
2562 }
2563 
2564 
2565 void
2566 sctp_send_initiate(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
2567 {
2568 	struct mbuf *m, *m_at, *m_last;
2569 	struct sctp_nets *net;
2570 	struct sctp_init_msg *initm;
2571 	struct sctp_supported_addr_param *sup_addr;
2572 	struct sctp_ecn_supported_param *ecn;
2573 	struct sctp_prsctp_supported_param *prsctp;
2574 	struct sctp_ecn_nonce_supported_param *ecn_nonce;
2575 	struct sctp_supported_chunk_types_param *pr_supported;
2576 	int cnt_inits_to=0;
2577 	int padval, ret;
2578 
2579 	/* INIT's always go to the primary (and usually ONLY address) */
2580 	m_last = NULL;
2581 	net = stcb->asoc.primary_destination;
2582 	if (net == NULL) {
2583 		net = TAILQ_FIRST(&stcb->asoc.nets);
2584 		if (net == NULL) {
2585 			/* TSNH */
2586 			return;
2587 		}
2588 		/* we confirm any address we send an INIT to */
2589 		net->dest_state &= ~SCTP_ADDR_UNCONFIRMED;
2590 		sctp_set_primary_addr(stcb, NULL, net);
2591 	} else {
2592 		/* we confirm any address we send an INIT to */
2593 		net->dest_state &= ~SCTP_ADDR_UNCONFIRMED;
2594 	}
2595 #ifdef SCTP_DEBUG
2596 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
2597 		printf("Sending INIT to ");
2598 		sctp_print_address (rtcache_getdst(&net->ro));
2599 	}
2600 #endif
2601 	if (rtcache_getdst(&net->ro)->sa_family == AF_INET6) {
2602 		/* special hook, if we are sending to link local
2603 		 * it will not show up in our private address count.
2604 		 */
2605 		if (IN6_IS_ADDR_LINKLOCAL((const struct in6_addr *) rtcache_getdst(&net->ro)->sa_data))
2606 			cnt_inits_to = 1;
2607 	}
2608 	if (callout_pending(&net->rxt_timer.timer)) {
2609 		/* This case should not happen */
2610 		return;
2611 	}
2612 	/* start the INIT timer */
2613 	if (sctp_timer_start(SCTP_TIMER_TYPE_INIT, inp, stcb, net)) {
2614 		/* we are hosed since I can't start the INIT timer? */
2615 		return;
2616 	}
2617 	MGETHDR(m, M_DONTWAIT, MT_HEADER);
2618 	if (m == NULL) {
2619 		/* No memory, INIT timer will re-attempt. */
2620 		return;
2621 	}
2622 	/* make it into a M_EXT */
2623 	MCLGET(m, M_DONTWAIT);
2624 	if ((m->m_flags & M_EXT) != M_EXT) {
2625 		/* Failed to get cluster buffer */
2626 		sctp_m_freem(m);
2627 		return;
2628 	}
2629 	m->m_data += SCTP_MIN_OVERHEAD;
2630 	m->m_len = sizeof(struct sctp_init_msg);
2631 	/* Now lets put the SCTP header in place */
2632 	initm = mtod(m, struct sctp_init_msg *);
2633 	initm->sh.src_port = inp->sctp_lport;
2634 	initm->sh.dest_port = stcb->rport;
2635 	initm->sh.v_tag = 0;
2636 	initm->sh.checksum = 0;	/* calculate later */
2637 	/* now the chunk header */
2638 	initm->msg.ch.chunk_type = SCTP_INITIATION;
2639 	initm->msg.ch.chunk_flags = 0;
2640 	/* fill in later from mbuf we build */
2641 	initm->msg.ch.chunk_length = 0;
2642 	/* place in my tag */
2643 	initm->msg.init.initiate_tag = htonl(stcb->asoc.my_vtag);
2644 	/* set up some of the credits. */
2645 	initm->msg.init.a_rwnd = htonl(uimax(inp->sctp_socket->so_rcv.sb_hiwat,
2646 	    SCTP_MINIMAL_RWND));
2647 
2648 	initm->msg.init.num_outbound_streams = htons(stcb->asoc.pre_open_streams);
2649 	initm->msg.init.num_inbound_streams = htons(stcb->asoc.max_inbound_streams);
2650 	initm->msg.init.initial_tsn = htonl(stcb->asoc.init_seq_number);
2651 	/* now the address restriction */
2652 	sup_addr = (struct sctp_supported_addr_param *)((vaddr_t)initm +
2653 	    sizeof(*initm));
2654 	sup_addr->ph.param_type = htons(SCTP_SUPPORTED_ADDRTYPE);
2655 	/* we support 2 types IPv6/IPv4 */
2656 	sup_addr->ph.param_length = htons(sizeof(*sup_addr) +
2657 					  sizeof(uint16_t));
2658 	sup_addr->addr_type[0] = htons(SCTP_IPV4_ADDRESS);
2659 	sup_addr->addr_type[1] = htons(SCTP_IPV6_ADDRESS);
2660 	m->m_len += sizeof(*sup_addr) + sizeof(uint16_t);
2661 
2662 /*	if (inp->sctp_flags & SCTP_PCB_FLAGS_ADAPTIONEVNT) {*/
2663 	if (inp->sctp_ep.adaption_layer_indicator) {
2664 		struct sctp_adaption_layer_indication *ali;
2665 		ali = (struct sctp_adaption_layer_indication *)(
2666 		    (vaddr_t)sup_addr + sizeof(*sup_addr) + sizeof(uint16_t));
2667 		ali->ph.param_type = htons(SCTP_ULP_ADAPTION);
2668 		ali->ph.param_length = htons(sizeof(*ali));
2669 		ali->indication = ntohl(inp->sctp_ep.adaption_layer_indicator);
2670 		m->m_len += sizeof(*ali);
2671 		ecn = (struct sctp_ecn_supported_param *)((vaddr_t)ali +
2672 		    sizeof(*ali));
2673 	} else {
2674 		ecn = (struct sctp_ecn_supported_param *)((vaddr_t)sup_addr +
2675 		    sizeof(*sup_addr) + sizeof(uint16_t));
2676 	}
2677 
2678 	/* now any cookie time extensions */
2679 	if (stcb->asoc.cookie_preserve_req) {
2680 		struct sctp_cookie_perserve_param *cookie_preserve;
2681 		cookie_preserve = (struct sctp_cookie_perserve_param *)(ecn);
2682 		cookie_preserve->ph.param_type = htons(SCTP_COOKIE_PRESERVE);
2683 		cookie_preserve->ph.param_length = htons(
2684 		    sizeof(*cookie_preserve));
2685 		cookie_preserve->time = htonl(stcb->asoc.cookie_preserve_req);
2686 		m->m_len += sizeof(*cookie_preserve);
2687 		ecn = (struct sctp_ecn_supported_param *)(
2688 		    (vaddr_t)cookie_preserve + sizeof(*cookie_preserve));
2689 		stcb->asoc.cookie_preserve_req = 0;
2690 	}
2691 
2692 	/* ECN parameter */
2693 	if (sctp_ecn == 1) {
2694 		ecn->ph.param_type = htons(SCTP_ECN_CAPABLE);
2695 		ecn->ph.param_length = htons(sizeof(*ecn));
2696 		m->m_len += sizeof(*ecn);
2697 		prsctp = (struct sctp_prsctp_supported_param *)((vaddr_t)ecn +
2698 		    sizeof(*ecn));
2699 	} else {
2700 		prsctp = (struct sctp_prsctp_supported_param *)((vaddr_t)ecn);
2701 	}
2702 	/* And now tell the peer we do pr-sctp */
2703 	prsctp->ph.param_type = htons(SCTP_PRSCTP_SUPPORTED);
2704 	prsctp->ph.param_length = htons(sizeof(*prsctp));
2705 	m->m_len += sizeof(*prsctp);
2706 
2707 
2708 	/* And now tell the peer we do all the extensions */
2709 	pr_supported = (struct sctp_supported_chunk_types_param *)((vaddr_t)prsctp +
2710 	   sizeof(*prsctp));
2711 
2712 	pr_supported->ph.param_type = htons(SCTP_SUPPORTED_CHUNK_EXT);
2713 	pr_supported->ph.param_length = htons(sizeof(*pr_supported) + SCTP_EXT_COUNT);
2714 	pr_supported->chunk_types[0] = SCTP_ASCONF;
2715 	pr_supported->chunk_types[1] = SCTP_ASCONF_ACK;
2716 	pr_supported->chunk_types[2] = SCTP_FORWARD_CUM_TSN;
2717 	pr_supported->chunk_types[3] = SCTP_PACKET_DROPPED;
2718 	pr_supported->chunk_types[4] = SCTP_STREAM_RESET;
2719 	pr_supported->chunk_types[5] = 0; /* pad */
2720 	pr_supported->chunk_types[6] = 0; /* pad */
2721 	pr_supported->chunk_types[7] = 0; /* pad */
2722 
2723 	m->m_len += (sizeof(*pr_supported) + SCTP_EXT_COUNT + SCTP_PAD_EXT_COUNT);
2724 	/* ECN nonce: And now tell the peer we support ECN nonce */
2725 
2726 	if (sctp_ecn_nonce) {
2727 		ecn_nonce = (struct sctp_ecn_nonce_supported_param *)((vaddr_t)pr_supported +
2728 		    sizeof(*pr_supported) + SCTP_EXT_COUNT + SCTP_PAD_EXT_COUNT);
2729 		ecn_nonce->ph.param_type = htons(SCTP_ECN_NONCE_SUPPORTED);
2730 		ecn_nonce->ph.param_length = htons(sizeof(*ecn_nonce));
2731 		m->m_len += sizeof(*ecn_nonce);
2732 	}
2733 
2734 	m_at = m;
2735 	/* now the addresses */
2736 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
2737 		struct ifnet *ifn;
2738 		struct ifaddr *ifa;
2739 		int cnt;
2740 		int s;
2741 
2742 		cnt = cnt_inits_to;
2743 		s = pserialize_read_enter();
2744 		IFNET_READER_FOREACH(ifn) {
2745 			if ((stcb->asoc.loopback_scope == 0) &&
2746 			    (ifn->if_type == IFT_LOOP)) {
2747 				/*
2748 				 * Skip loopback devices if loopback_scope
2749 				 * not set
2750 				 */
2751 				continue;
2752 			}
2753 			IFADDR_READER_FOREACH(ifa, ifn) {
2754 				if (sctp_is_address_in_scope(ifa,
2755 				    stcb->asoc.ipv4_addr_legal,
2756 				    stcb->asoc.ipv6_addr_legal,
2757 				    stcb->asoc.loopback_scope,
2758 				    stcb->asoc.ipv4_local_scope,
2759 				    stcb->asoc.local_scope,
2760 				    stcb->asoc.site_scope) == 0) {
2761 					continue;
2762 				}
2763 				cnt++;
2764 			}
2765 		}
2766 		pserialize_read_exit(s);
2767 
2768 		if (cnt > 1) {
2769 			s = pserialize_read_enter();
2770 			IFNET_READER_FOREACH(ifn) {
2771 				if ((stcb->asoc.loopback_scope == 0) &&
2772 				    (ifn->if_type == IFT_LOOP)) {
2773 					/*
2774 					 * Skip loopback devices if loopback_scope
2775 					 * not set
2776 					 */
2777 					continue;
2778 				}
2779 				IFADDR_READER_FOREACH(ifa, ifn) {
2780 					if (sctp_is_address_in_scope(ifa,
2781 					    stcb->asoc.ipv4_addr_legal,
2782 					    stcb->asoc.ipv6_addr_legal,
2783 					    stcb->asoc.loopback_scope,
2784 					    stcb->asoc.ipv4_local_scope,
2785 					    stcb->asoc.local_scope,
2786 					    stcb->asoc.site_scope) == 0) {
2787 						continue;
2788 					}
2789 					m_at = sctp_add_addr_to_mbuf(m_at, ifa);
2790 				}
2791 			}
2792 			pserialize_read_exit(s);
2793 		}
2794 	} else {
2795 		struct sctp_laddr *laddr;
2796 		int cnt;
2797 		cnt = cnt_inits_to;
2798 		/* First, how many ? */
2799 		LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
2800 			if (laddr->ifa == NULL) {
2801 				continue;
2802 			}
2803 			if (laddr->ifa->ifa_addr == NULL)
2804 				continue;
2805 			if (sctp_is_address_in_scope(laddr->ifa,
2806 			    stcb->asoc.ipv4_addr_legal,
2807 			    stcb->asoc.ipv6_addr_legal,
2808 			    stcb->asoc.loopback_scope,
2809 			    stcb->asoc.ipv4_local_scope,
2810 			    stcb->asoc.local_scope,
2811 			    stcb->asoc.site_scope) == 0) {
2812 				continue;
2813 			}
2814 			cnt++;
2815 		}
2816 		/* To get through a NAT we only list addresses if
2817 		 * we have more than one. That way if you just
2818 		 * bind a single address we let the source of the init
2819 		 * dictate our address.
2820 		 */
2821 		if (cnt > 1) {
2822 			LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
2823 				if (laddr->ifa == NULL) {
2824 					continue;
2825 				}
2826 				if (laddr->ifa->ifa_addr == NULL) {
2827 					continue;
2828 				}
2829 
2830 				if (sctp_is_address_in_scope(laddr->ifa,
2831 				    stcb->asoc.ipv4_addr_legal,
2832 				    stcb->asoc.ipv6_addr_legal,
2833 				    stcb->asoc.loopback_scope,
2834 				    stcb->asoc.ipv4_local_scope,
2835 				    stcb->asoc.local_scope,
2836 				    stcb->asoc.site_scope) == 0) {
2837 					continue;
2838 				}
2839 				m_at = sctp_add_addr_to_mbuf(m_at, laddr->ifa);
2840 			}
2841 		}
2842 	}
2843 	/* calulate the size and update pkt header and chunk header */
2844 	m->m_pkthdr.len = 0;
2845 	for (m_at = m; m_at; m_at = m_at->m_next) {
2846 		if (m_at->m_next == NULL)
2847 			m_last = m_at;
2848 		m->m_pkthdr.len += m_at->m_len;
2849 	}
2850 	initm->msg.ch.chunk_length = htons((m->m_pkthdr.len -
2851 	    sizeof(struct sctphdr)));
2852 #ifdef SCTP_DEBUG
2853 	printf("chunk_length %d\n", ntohs(initm->msg.ch.chunk_length));
2854 #endif
2855 	/* We pass 0 here to NOT set IP_DF if its IPv4, we
2856 	 * ignore the return here since the timer will drive
2857 	 * a retranmission.
2858 	 */
2859 
2860 	/* I don't expect this to execute but we will be safe here */
2861 	padval = m->m_pkthdr.len % 4;
2862 	if ((padval) && (m_last)) {
2863 		/* The compiler worries that m_last may not be
2864 		 * set even though I think it is impossible :->
2865 		 * however we add m_last here just in case.
2866 		 */
2867 		ret = sctp_add_pad_tombuf(m_last, (4-padval));
2868 		if (ret) {
2869 			/* Houston we have a problem, no space */
2870 			sctp_m_freem(m);
2871 			return;
2872 		}
2873 		m->m_pkthdr.len += padval;
2874 	}
2875 #ifdef SCTP_DEBUG
2876 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
2877 		printf("Calling lowlevel output stcb:%p net:%p\n",
2878 		       stcb, net);
2879 	}
2880 #endif
2881 	ret = sctp_lowlevel_chunk_output(inp, stcb, net,
2882 		  rtcache_getdst(&net->ro), m, 0, 0, NULL, 0);
2883 #ifdef SCTP_DEBUG
2884 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
2885 		printf("Low level output returns %d\n", ret);
2886 	}
2887 #endif
2888 	sctp_timer_start(SCTP_TIMER_TYPE_INIT, inp, stcb, net);
2889 	SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
2890 }
2891 
2892 struct mbuf *
2893 sctp_arethere_unrecognized_parameters(struct mbuf *in_initpkt,
2894     int param_offset, int *abort_processing, struct sctp_chunkhdr *cp)
2895 {
2896 	/* Given a mbuf containing an INIT or INIT-ACK
2897 	 * with the param_offset being equal to the
2898 	 * beginning of the params i.e. (iphlen + sizeof(struct sctp_init_msg)
2899 	 * parse through the parameters to the end of the mbuf verifying
2900 	 * that all parameters are known.
2901 	 *
2902 	 * For unknown parameters build and return a mbuf with
2903 	 * UNRECOGNIZED_PARAMETER errors. If the flags indicate
2904 	 * to stop processing this chunk stop, and set *abort_processing
2905 	 * to 1.
2906 	 *
2907 	 * By having param_offset be pre-set to where parameters begin
2908 	 * it is hoped that this routine may be reused in the future
2909 	 * by new features.
2910 	 */
2911 	struct sctp_paramhdr *phdr, params;
2912 
2913 	struct mbuf *mat, *op_err;
2914 	char tempbuf[2048];
2915 	int at, limit, pad_needed;
2916 	uint16_t ptype, plen;
2917 	int err_at;
2918 
2919 	*abort_processing = 0;
2920 	mat = in_initpkt;
2921 	err_at = 0;
2922 	limit = ntohs(cp->chunk_length) - sizeof(struct sctp_init_chunk);
2923 #ifdef SCTP_DEBUG
2924 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
2925 		printf("Limit is %d bytes\n", limit);
2926 	}
2927 #endif
2928 	at = param_offset;
2929 	op_err = NULL;
2930 
2931 	phdr = sctp_get_next_param(mat, at, &params, sizeof(params));
2932 	while ((phdr != NULL) && ((size_t)limit >= sizeof(struct sctp_paramhdr))) {
2933 		ptype = ntohs(phdr->param_type);
2934 		plen = ntohs(phdr->param_length);
2935 		limit -= SCTP_SIZE32(plen);
2936 		if (plen < sizeof(struct sctp_paramhdr)) {
2937 #ifdef SCTP_DEBUG
2938 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
2939 			printf("sctp_output.c:Impossible length in parameter < %d\n", plen);
2940 	}
2941 #endif
2942 			*abort_processing = 1;
2943 			break;
2944 		}
2945 		/* All parameters for all chunks that we
2946 		 * know/understand are listed here. We process
2947 		 * them other places and make appropriate
2948 		 * stop actions per the upper bits. However
2949 		 * this is the generic routine processor's can
2950 		 * call to get back an operr.. to either incorporate (init-ack)
2951 		 * or send.
2952 		 */
2953 		if ((ptype == SCTP_HEARTBEAT_INFO) ||
2954 		    (ptype == SCTP_IPV4_ADDRESS) ||
2955 		    (ptype == SCTP_IPV6_ADDRESS) ||
2956 		    (ptype == SCTP_STATE_COOKIE) ||
2957 		    (ptype == SCTP_UNRECOG_PARAM) ||
2958 		    (ptype == SCTP_COOKIE_PRESERVE) ||
2959 		    (ptype == SCTP_SUPPORTED_ADDRTYPE) ||
2960 		    (ptype == SCTP_PRSCTP_SUPPORTED) ||
2961 		    (ptype == SCTP_ADD_IP_ADDRESS) ||
2962 		    (ptype == SCTP_DEL_IP_ADDRESS) ||
2963 		    (ptype == SCTP_ECN_CAPABLE) ||
2964 		    (ptype == SCTP_ULP_ADAPTION) ||
2965 		    (ptype == SCTP_ERROR_CAUSE_IND) ||
2966 		    (ptype == SCTP_SET_PRIM_ADDR) ||
2967 		    (ptype == SCTP_SUCCESS_REPORT) ||
2968 		    (ptype == SCTP_ULP_ADAPTION) ||
2969 		    (ptype == SCTP_SUPPORTED_CHUNK_EXT) ||
2970 		    (ptype == SCTP_ECN_NONCE_SUPPORTED)
2971 			) {
2972 			/* no skip it */
2973 			at += SCTP_SIZE32(plen);
2974 		} else if (ptype == SCTP_HOSTNAME_ADDRESS) {
2975 			/* We can NOT handle HOST NAME addresses!! */
2976 #ifdef SCTP_DEBUG
2977 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
2978 		printf("Can't handle hostname addresses.. abort processing\n");
2979 	}
2980 #endif
2981 			*abort_processing = 1;
2982 			if (op_err == NULL) {
2983 				/* Ok need to try to get a mbuf */
2984 				MGETHDR(op_err, M_DONTWAIT, MT_DATA);
2985 				if (op_err) {
2986 					op_err->m_len = 0;
2987 					op_err->m_pkthdr.len = 0;
2988 					/* pre-reserve space for ip and sctp header  and chunk hdr*/
2989 					op_err->m_data += sizeof(struct ip6_hdr);
2990 					op_err->m_data += sizeof(struct sctphdr);
2991 					op_err->m_data += sizeof(struct sctp_chunkhdr);
2992 				}
2993 			}
2994 			if (op_err) {
2995 				/* If we have space */
2996 				struct sctp_paramhdr s;
2997 				if (err_at % 4) {
2998 					u_int32_t cpthis=0;
2999 					pad_needed = 4 - (err_at % 4);
3000 					m_copyback(op_err, err_at, pad_needed, (void *)&cpthis);
3001 					err_at += pad_needed;
3002 				}
3003 				s.param_type = htons(SCTP_CAUSE_UNRESOLV_ADDR);
3004 				s.param_length = htons(sizeof(s) + plen);
3005 				m_copyback(op_err, err_at, sizeof(s), (void *)&s);
3006 				err_at += sizeof(s);
3007 				phdr = sctp_get_next_param(mat, at, (struct sctp_paramhdr *)tempbuf, plen);
3008 				if (phdr == NULL) {
3009 					sctp_m_freem(op_err);
3010 					/* we are out of memory but we
3011 					 * still need to have a look at what to
3012 					 * do (the system is in trouble though).
3013 					 */
3014 					return (NULL);
3015 				}
3016 				m_copyback(op_err, err_at, plen, (void *)phdr);
3017 				err_at += plen;
3018 			}
3019 			return (op_err);
3020 		} else {
3021 			/* we do not recognize the parameter
3022 			 * figure out what we do.
3023 			 */
3024 #ifdef SCTP_DEBUG
3025 			if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
3026 				printf("Got parameter type %x - unknown\n",
3027 				       (u_int)ptype);
3028 			}
3029 #endif
3030 			if ((ptype & 0x4000) == 0x4000) {
3031 				/* Report bit is set?? */
3032 #ifdef SCTP_DEBUG
3033 				if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
3034 					printf("Report bit is set\n");
3035 				}
3036 #endif
3037 				if (op_err == NULL) {
3038 					/* Ok need to try to get an mbuf */
3039 					MGETHDR(op_err, M_DONTWAIT, MT_DATA);
3040 					if (op_err) {
3041 						op_err->m_len = 0;
3042 						op_err->m_pkthdr.len = 0;
3043 						op_err->m_data += sizeof(struct ip6_hdr);
3044 						op_err->m_data += sizeof(struct sctphdr);
3045 						op_err->m_data += sizeof(struct sctp_chunkhdr);
3046 					}
3047 				}
3048 				if (op_err) {
3049 					/* If we have space */
3050 					struct sctp_paramhdr s;
3051 					if (err_at % 4) {
3052 						u_int32_t cpthis=0;
3053 						pad_needed = 4 - (err_at % 4);
3054 						m_copyback(op_err, err_at, pad_needed, (void *)&cpthis);
3055 						err_at += pad_needed;
3056  					}
3057 					s.param_type = htons(SCTP_UNRECOG_PARAM);
3058 					s.param_length = htons(sizeof(s) + plen);
3059 					m_copyback(op_err, err_at, sizeof(s), (void *)&s);
3060 					err_at += sizeof(s);
3061 					if (plen > sizeof(tempbuf)) {
3062 						plen = sizeof(tempbuf);
3063 					}
3064 					phdr = sctp_get_next_param(mat, at, (struct sctp_paramhdr *)tempbuf, plen);
3065 					if (phdr == NULL) {
3066 						sctp_m_freem(op_err);
3067 						/* we are out of memory but we
3068 						 * still need to have a look at what to
3069 						 * do (the system is in trouble though).
3070 						 */
3071 						goto more_processing;
3072 					}
3073 					m_copyback(op_err, err_at, plen, (void *)phdr);
3074 					err_at += plen;
3075 				}
3076 			}
3077 		more_processing:
3078 			if ((ptype & 0x8000) == 0x0000) {
3079 #ifdef SCTP_DEBUG
3080 				if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
3081 					printf("Abort bit is now setting1\n");
3082 				}
3083 #endif
3084 				return (op_err);
3085 			} else {
3086 				/* skip this chunk and continue processing */
3087 				at += SCTP_SIZE32(plen);
3088 			}
3089 
3090 		}
3091 		phdr = sctp_get_next_param(mat, at, &params, sizeof(params));
3092 	}
3093 	return (op_err);
3094 }
3095 
3096 static int
3097 sctp_are_there_new_addresses(struct sctp_association *asoc,
3098     struct mbuf *in_initpkt, int iphlen, int offset)
3099 {
3100 	/*
3101 	 * Given a INIT packet, look through the packet to verify that
3102 	 * there are NO new addresses. As we go through the parameters
3103 	 * add reports of any un-understood parameters that require an
3104 	 * error.  Also we must return (1) to drop the packet if we see
3105 	 * a un-understood parameter that tells us to drop the chunk.
3106 	 */
3107 	struct sockaddr_in sin4, *sa4;
3108 	struct sockaddr_in6 sin6, *sa6;
3109 	struct sockaddr *sa_touse;
3110 	struct sockaddr *sa;
3111 	struct sctp_paramhdr *phdr, params;
3112 	struct ip *iph;
3113 	struct mbuf *mat;
3114 	uint16_t ptype, plen;
3115 	uint8_t fnd;
3116 	struct sctp_nets *net;
3117 
3118 	memset(&sin4, 0, sizeof(sin4));
3119 	memset(&sin6, 0, sizeof(sin6));
3120 	sin4.sin_family = AF_INET;
3121 	sin4.sin_len = sizeof(sin4);
3122 	sin6.sin6_family = AF_INET6;
3123 	sin6.sin6_len = sizeof(sin6);
3124 
3125 	sa_touse = NULL;
3126 	/* First what about the src address of the pkt ? */
3127 	iph = mtod(in_initpkt, struct ip *);
3128 	if (iph->ip_v == IPVERSION) {
3129 		/* source addr is IPv4 */
3130 		sin4.sin_addr = iph->ip_src;
3131 		sa_touse = (struct sockaddr *)&sin4;
3132 	} else if (iph->ip_v == (IPV6_VERSION >> 4)) {
3133 		/* source addr is IPv6 */
3134 		struct ip6_hdr *ip6h;
3135 		ip6h = mtod(in_initpkt, struct ip6_hdr *);
3136 		sin6.sin6_addr = ip6h->ip6_src;
3137 		sa_touse = (struct sockaddr *)&sin6;
3138 	} else {
3139 		return (1);
3140 	}
3141 
3142 	fnd = 0;
3143 	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
3144 		sa = (struct sockaddr *)&net->ro.ro_sa;
3145 		if (sa->sa_family == sa_touse->sa_family) {
3146 			if (sa->sa_family == AF_INET) {
3147 			    sa4 = (struct sockaddr_in *)sa;
3148 				if (sa4->sin_addr.s_addr ==
3149 				    sin4.sin_addr.s_addr) {
3150 					fnd = 1;
3151 					break;
3152 				}
3153 			} else if (sa->sa_family == AF_INET6) {
3154 				sa6 = (struct sockaddr_in6 *)sa;
3155 				if (SCTP6_ARE_ADDR_EQUAL(&sa6->sin6_addr,
3156 				    &sin6.sin6_addr)) {
3157 					fnd = 1;
3158 					break;
3159 				}
3160 			}
3161 		}
3162 	}
3163 	if (fnd == 0) {
3164 		/* New address added! no need to look further. */
3165 		return (1);
3166 	}
3167 	/* Ok so far lets munge through the rest of the packet */
3168 	mat = in_initpkt;
3169 	sa_touse = NULL;
3170 	offset += sizeof(struct sctp_init_chunk);
3171 	phdr = sctp_get_next_param(mat, offset, &params, sizeof(params));
3172 	while (phdr) {
3173 		ptype = ntohs(phdr->param_type);
3174 		plen = ntohs(phdr->param_length);
3175 		if (ptype == SCTP_IPV4_ADDRESS) {
3176 			struct sctp_ipv4addr_param *p4, p4_buf;
3177 
3178 			phdr = sctp_get_next_param(mat, offset,
3179 			    (struct sctp_paramhdr *)&p4_buf, sizeof(p4_buf));
3180 			if (plen != sizeof(struct sctp_ipv4addr_param) ||
3181 			    phdr == NULL) {
3182                                 return (1);
3183                         }
3184 			p4 = (struct sctp_ipv4addr_param *)phdr;
3185 			sin4.sin_addr.s_addr = p4->addr;
3186 			sa_touse = (struct sockaddr *)&sin4;
3187 		} else if (ptype == SCTP_IPV6_ADDRESS) {
3188 			struct sctp_ipv6addr_param *p6, p6_buf;
3189 
3190 			phdr = sctp_get_next_param(mat, offset,
3191 			    (struct sctp_paramhdr *)&p6_buf, sizeof(p6_buf));
3192 			if (plen != sizeof(struct sctp_ipv6addr_param) ||
3193 			    phdr == NULL) {
3194                                 return (1);
3195                         }
3196 			p6 = (struct sctp_ipv6addr_param *)phdr;
3197 			memcpy((void *)&sin6.sin6_addr, p6->addr,
3198 			    sizeof(p6->addr));
3199 			sa_touse = (struct sockaddr *)&sin4;
3200 		}
3201 
3202 		if (sa_touse) {
3203 			/* ok, sa_touse points to one to check */
3204 			fnd = 0;
3205 			TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
3206 				sa = (struct sockaddr *)&net->ro.ro_sa;
3207 				if (sa->sa_family != sa_touse->sa_family) {
3208 					continue;
3209 				}
3210 				if (sa->sa_family == AF_INET) {
3211 					sa4 = (struct sockaddr_in *)sa;
3212 					if (sa4->sin_addr.s_addr ==
3213 					    sin4.sin_addr.s_addr) {
3214 						fnd = 1;
3215 						break;
3216 					}
3217 				} else if (sa->sa_family == AF_INET6) {
3218 					sa6 = (struct sockaddr_in6 *)sa;
3219 					if (SCTP6_ARE_ADDR_EQUAL(
3220 					    &sa6->sin6_addr, &sin6.sin6_addr)) {
3221 						fnd = 1;
3222 						break;
3223 					}
3224 				}
3225 			}
3226 			if (!fnd) {
3227 				/* New addr added! no need to look further */
3228 				return (1);
3229 			}
3230 		}
3231 		offset += SCTP_SIZE32(plen);
3232 		phdr = sctp_get_next_param(mat, offset, &params, sizeof(params));
3233 	}
3234 	return (0);
3235 }
3236 
3237 /*
3238  * Given a MBUF chain that was sent into us containing an
3239  * INIT. Build a INIT-ACK with COOKIE and send back.
3240  * We assume that the in_initpkt has done a pullup to
3241  * include IPv6/4header, SCTP header and initial part of
3242  * INIT message (i.e. the struct sctp_init_msg).
3243  */
3244 void
3245 sctp_send_initiate_ack(struct sctp_inpcb *inp, struct sctp_tcb *stcb,
3246     struct mbuf *init_pkt, int iphlen, int offset, struct sctphdr *sh,
3247     struct sctp_init_chunk *init_chk)
3248 {
3249 	struct sctp_association *asoc;
3250 	struct mbuf *m, *m_at, *m_tmp, *m_cookie, *op_err, *m_last;
3251 	struct sctp_init_msg *initackm_out;
3252 	struct sctp_ecn_supported_param *ecn;
3253 	struct sctp_prsctp_supported_param *prsctp;
3254 	struct sctp_ecn_nonce_supported_param *ecn_nonce;
3255 	struct sctp_supported_chunk_types_param *pr_supported;
3256 	struct sockaddr_storage store;
3257 	struct sockaddr_in *sin;
3258 	struct sockaddr_in6 *sin6;
3259 	struct route *ro;
3260 	struct ip *iph;
3261 	struct ip6_hdr *ip6;
3262 	const struct sockaddr *to;
3263 	struct sctp_state_cookie stc;
3264 	struct sctp_nets *net=NULL;
3265 	int cnt_inits_to=0;
3266 	uint16_t his_limit, i_want;
3267 	int abort_flag, padval, sz_of;
3268 	struct rtentry *rt;
3269 
3270 	if (stcb) {
3271 		asoc = &stcb->asoc;
3272 	} else {
3273 		asoc = NULL;
3274 	}
3275 	m_last = NULL;
3276 	if ((asoc != NULL) &&
3277 	    (SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_WAIT) &&
3278 	    (sctp_are_there_new_addresses(asoc, init_pkt, iphlen, offset))) {
3279 		/* new addresses, out of here in non-cookie-wait states */
3280 		/*
3281 		 * Send a ABORT, we don't add the new address error clause though
3282 		 * we even set the T bit and copy in the 0 tag.. this looks no
3283 		 * different than if no listner was present.
3284 		 */
3285 		sctp_send_abort(init_pkt, iphlen, sh, 0, NULL);
3286 		return;
3287 	}
3288 	abort_flag = 0;
3289 	op_err = sctp_arethere_unrecognized_parameters(init_pkt,
3290 	    (offset+sizeof(struct sctp_init_chunk)),
3291 	    &abort_flag, (struct sctp_chunkhdr *)init_chk);
3292 	if (abort_flag) {
3293 		sctp_send_abort(init_pkt, iphlen, sh, init_chk->init.initiate_tag, op_err);
3294 		return;
3295 	}
3296 	MGETHDR(m, M_DONTWAIT, MT_HEADER);
3297 	if (m == NULL) {
3298 		/* No memory, INIT timer will re-attempt. */
3299 		if (op_err)
3300 			sctp_m_freem(op_err);
3301 		return;
3302 	}
3303 	MCLGET(m, M_DONTWAIT);
3304 	if ((m->m_flags & M_EXT) != M_EXT) {
3305 		/* Failed to get cluster buffer */
3306 		if (op_err)
3307 			sctp_m_freem(op_err);
3308 		sctp_m_freem(m);
3309 		return;
3310 	}
3311 	m->m_data += SCTP_MIN_OVERHEAD;
3312 	m_reset_rcvif(m);
3313 	m->m_len = sizeof(struct sctp_init_msg);
3314 
3315 	/* the time I built cookie */
3316 	SCTP_GETTIME_TIMEVAL(&stc.time_entered);
3317 
3318 	/* populate any tie tags */
3319 	if (asoc != NULL) {
3320 		/* unlock before tag selections */
3321 		SCTP_TCB_UNLOCK(stcb);
3322 		if (asoc->my_vtag_nonce == 0)
3323 			asoc->my_vtag_nonce = sctp_select_a_tag(inp);
3324 		stc.tie_tag_my_vtag = asoc->my_vtag_nonce;
3325 
3326 		if (asoc->peer_vtag_nonce == 0)
3327 			asoc->peer_vtag_nonce = sctp_select_a_tag(inp);
3328 		stc.tie_tag_peer_vtag = asoc->peer_vtag_nonce;
3329 
3330 		stc.cookie_life = asoc->cookie_life;
3331 		net = asoc->primary_destination;
3332 		/* now we must relock */
3333 		SCTP_INP_RLOCK(inp);
3334 		/* we may be in trouble here if the inp got freed
3335 		 * most likely this set of tests will protect
3336 		 * us but there is a chance not.
3337 		 */
3338 		if (inp->sctp_flags & (SCTP_PCB_FLAGS_SOCKET_GONE|SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
3339 			if (op_err)
3340 				sctp_m_freem(op_err);
3341 			sctp_m_freem(m);
3342 			sctp_send_abort(init_pkt, iphlen, sh, 0, NULL);
3343 			return;
3344 		}
3345 		SCTP_TCB_LOCK(stcb);
3346 		SCTP_INP_RUNLOCK(stcb->sctp_ep);
3347 	} else {
3348 		stc.tie_tag_my_vtag = 0;
3349 		stc.tie_tag_peer_vtag = 0;
3350 		/* life I will award this cookie */
3351 		stc.cookie_life = inp->sctp_ep.def_cookie_life;
3352 	}
3353 
3354 	/* copy in the ports for later check */
3355 	stc.myport = sh->dest_port;
3356 	stc.peerport = sh->src_port;
3357 
3358 	/*
3359 	 * If we wanted to honor cookie life extensions, we would add
3360 	 * to stc.cookie_life. For now we should NOT honor any extension
3361 	 */
3362 	stc.site_scope = stc.local_scope = stc.loopback_scope = 0;
3363 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
3364 		struct inpcb *in_inp;
3365 		/* Its a V6 socket */
3366 		in_inp = (struct inpcb *)inp;
3367 		stc.ipv6_addr_legal = 1;
3368 		/* Now look at the binding flag to see if V4 will be legal */
3369 		if (
3370 #if defined(__FreeBSD__) || defined(__APPLE__)
3371 		    (in_inp->inp_flags & IN6P_IPV6_V6ONLY)
3372 #elif defined(__OpenBSD__)
3373 		    (0)	/* For openbsd we do dual bind only */
3374 #else
3375 		    (((struct in6pcb *)in_inp)->in6p_flags & IN6P_IPV6_V6ONLY)
3376 #endif
3377 		    == 0) {
3378 			stc.ipv4_addr_legal = 1;
3379 		} else {
3380 			/* V4 addresses are NOT legal on the association */
3381 			stc.ipv4_addr_legal = 0;
3382 		}
3383 	} else {
3384 		/* Its a V4 socket, no - V6 */
3385 		stc.ipv4_addr_legal = 1;
3386 		stc.ipv6_addr_legal = 0;
3387 	}
3388 
3389 #ifdef SCTP_DONT_DO_PRIVADDR_SCOPE
3390 	stc.ipv4_scope = 1;
3391 #else
3392 	stc.ipv4_scope = 0;
3393 #endif
3394 	/* now for scope setup */
3395 	memset((void *)&store, 0, sizeof(store));
3396 	sin = (struct sockaddr_in *)&store;
3397 	sin6 = (struct sockaddr_in6 *)&store;
3398 	if (net == NULL) {
3399 		to = (struct sockaddr *)&store;
3400 		iph = mtod(init_pkt, struct ip *);
3401 		if (iph->ip_v == IPVERSION) {
3402 			struct in_addr addr;
3403 			static struct route iproute;
3404 
3405 			sin->sin_family = AF_INET;
3406 			sin->sin_len = sizeof(struct sockaddr_in);
3407 			sin->sin_port = sh->src_port;
3408 			sin->sin_addr = iph->ip_src;
3409 			/* lookup address */
3410 			stc.address[0] = sin->sin_addr.s_addr;
3411 			stc.address[1] = 0;
3412 			stc.address[2] = 0;
3413 			stc.address[3] = 0;
3414 			stc.addr_type = SCTP_IPV4_ADDRESS;
3415 			/* local from address */
3416 			memset(&iproute, 0, sizeof(iproute));
3417 			ro = &iproute;
3418 
3419 			/* XXX */
3420 			rt = rtcache_lookup(ro, (struct sockaddr *) sin);
3421 			rtcache_unref(rt, ro);
3422 			addr = sctp_ipv4_source_address_selection(inp, NULL,
3423 			    ro, NULL, 0);
3424 			stc.laddress[0] = addr.s_addr;
3425 			stc.laddress[1] = 0;
3426 			stc.laddress[2] = 0;
3427 			stc.laddress[3] = 0;
3428 			stc.laddr_type = SCTP_IPV4_ADDRESS;
3429 			/* scope_id is only for v6 */
3430 			stc.scope_id = 0;
3431 #ifndef SCTP_DONT_DO_PRIVADDR_SCOPE
3432 			if (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) {
3433 				stc.ipv4_scope = 1;
3434 			}
3435 #else
3436 			stc.ipv4_scope = 1;
3437 #endif /* SCTP_DONT_DO_PRIVADDR_SCOPE */
3438 			/* Must use the address in this case */
3439 			if (sctp_is_address_on_local_host((struct sockaddr *)sin)) {
3440 				stc.loopback_scope = 1;
3441 				stc.ipv4_scope = 1;
3442 				stc.site_scope = 1;
3443 				stc.local_scope = 1;
3444 			}
3445 		} else if (iph->ip_v == (IPV6_VERSION >> 4)) {
3446 			struct in6_addr addr;
3447                         static struct route iproute6;
3448 			ip6 = mtod(init_pkt, struct ip6_hdr *);
3449 			sin6->sin6_family = AF_INET6;
3450 			sin6->sin6_len = sizeof(struct sockaddr_in6);
3451 			sin6->sin6_port = sh->src_port;
3452 			sin6->sin6_addr = ip6->ip6_src;
3453 			/* lookup address */
3454 			memcpy(&stc.address, &sin6->sin6_addr,
3455 			    sizeof(struct in6_addr));
3456 			sin6->sin6_scope_id = 0;
3457 			stc.addr_type = SCTP_IPV6_ADDRESS;
3458 			stc.scope_id = 0;
3459 			if (sctp_is_address_on_local_host((struct sockaddr *)sin6)) {
3460 				stc.loopback_scope = 1;
3461 				stc.local_scope = 1;
3462 				stc.site_scope = 1;
3463 				stc.ipv4_scope = 1;
3464 			} else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
3465 				/*
3466 				 * If the new destination is a LINK_LOCAL
3467 				 * we must have common both site and local
3468 				 * scope. Don't set local scope though since
3469 				 * we must depend on the source to be added
3470 				 * implicitly. We cannot assure just because
3471 				 * we share one link that all links are common.
3472 				 *
3473 				 * XXX: never treat link-local case explicitly.
3474 				 * Use general routines defined in scope6.c.
3475 				 * (jinmei@kame)
3476 				 */
3477 				stc.local_scope = 0;
3478 				stc.site_scope = 1;
3479  				stc.ipv4_scope = 1;
3480 				/* we start counting for the private
3481 				 * address stuff at 1. since the link
3482 				 * local we source from won't show
3483 				 * up in our scoped count.
3484 				 */
3485 				cnt_inits_to=1;
3486 				/* pull out the scope_id from incoming pkt */
3487 #if defined(SCTP_BASE_FREEBSD) || defined(__APPLE__)
3488 				(void)in6_recoverscope(sin6, &in6_src,
3489 				    m_get_rcvif_NOMPSAFE(init_pkt));
3490 				in6_embedscope(&sin6->sin6_addr, sin6, NULL,
3491 				    NULL);
3492 #else
3493 				(void)sa6_recoverscope(sin6);
3494 #endif
3495 				stc.scope_id = sin6->sin6_scope_id;
3496 
3497 			} else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr)) {
3498 				/*
3499 				 * If the new destination is SITE_LOCAL
3500 				 * then we must have site scope in common.
3501 				 */
3502 				stc.site_scope = 1;
3503 			}
3504 			/* local from address */
3505 			memset(&iproute6, 0, sizeof(iproute6));
3506 			ro = (struct route *)&iproute6;
3507 			/* XXX */
3508 			rt = rtcache_lookup(ro, (struct sockaddr *) sin6);
3509 			rtcache_unref(rt, ro);
3510 			addr = sctp_ipv6_source_address_selection(inp, NULL,
3511 			    ro, NULL, 0);
3512 			memcpy(&stc.laddress, &addr, sizeof(struct in6_addr));
3513 			stc.laddr_type = SCTP_IPV6_ADDRESS;
3514 		}
3515 	} else {
3516 		/* set the scope per the existing tcb */
3517 		struct sctp_nets *lnet;
3518 
3519 		stc.loopback_scope = asoc->loopback_scope;
3520 		stc.ipv4_scope = asoc->ipv4_local_scope;
3521 		stc.site_scope = asoc->site_scope;
3522 		stc.local_scope = asoc->local_scope;
3523 		TAILQ_FOREACH(lnet, &asoc->nets, sctp_next) {
3524 			if (rtcache_getdst(&lnet->ro)->sa_family == AF_INET6) {
3525 				if (IN6_IS_ADDR_LINKLOCAL((const struct in6_addr *) rtcache_getdst(&lnet->ro)->sa_data)) {
3526 					/* if we have a LL address, start counting
3527 					 * at 1.
3528 					 */
3529  					cnt_inits_to = 1;
3530 				}
3531 			}
3532 		}
3533 
3534 		/* use the net pointer */
3535 		to = rtcache_getdst(&net->ro);
3536 		if (to->sa_family == AF_INET) {
3537 			memcpy(&stc.address[0], to, sizeof(struct in_addr));
3538 			stc.address[1] = 0;
3539 			stc.address[2] = 0;
3540 			stc.address[3] = 0;
3541 			stc.addr_type = SCTP_IPV4_ADDRESS;
3542 			if (net->src_addr_selected == 0) {
3543 				/* strange case here, the INIT
3544 				 * should have did the selection.
3545 				 */
3546 				net->_s_addr.sin.sin_addr =
3547 				    sctp_ipv4_source_address_selection(inp,
3548 				    stcb, &net->ro, net, 0);
3549 				net->src_addr_selected = 1;
3550 
3551 			}
3552 
3553 			stc.laddress[0] = net->_s_addr.sin.sin_addr.s_addr;
3554 			stc.laddress[1] = 0;
3555 			stc.laddress[2] = 0;
3556 			stc.laddress[3] = 0;
3557 			stc.laddr_type = SCTP_IPV4_ADDRESS;
3558 		} else if (to->sa_family == AF_INET6) {
3559 			memcpy(&stc.address, &to->sa_data,
3560 			    sizeof(struct in6_addr));
3561 			stc.addr_type = SCTP_IPV6_ADDRESS;
3562 			if (net->src_addr_selected == 0) {
3563 				/* strange case here, the INIT
3564 				 * should have did the selection.
3565 				 */
3566 				net->_s_addr.sin6.sin6_addr =
3567 				    sctp_ipv6_source_address_selection(inp,
3568 				    stcb, &net->ro, net, 0);
3569 				net->src_addr_selected = 1;
3570 			}
3571 			memcpy(&stc.laddress, &net->_s_addr.sin6.sin6_addr,
3572 			    sizeof(struct in6_addr));
3573 			stc.laddr_type = SCTP_IPV6_ADDRESS;
3574 		}
3575 	}
3576 	/* Now lets put the SCTP header in place */
3577 	initackm_out = mtod(m, struct sctp_init_msg *);
3578 	initackm_out->sh.src_port = inp->sctp_lport;
3579 	initackm_out->sh.dest_port = sh->src_port;
3580 	initackm_out->sh.v_tag = init_chk->init.initiate_tag;
3581 	/* Save it off for quick ref */
3582 	stc.peers_vtag = init_chk->init.initiate_tag;
3583 	initackm_out->sh.checksum = 0;	/* calculate later */
3584 	/* who are we */
3585 	strncpy(stc.identification, SCTP_VERSION_STRING,
3586 	   uimin(strlen(SCTP_VERSION_STRING), sizeof(stc.identification)));
3587 	/* now the chunk header */
3588 	initackm_out->msg.ch.chunk_type = SCTP_INITIATION_ACK;
3589 	initackm_out->msg.ch.chunk_flags = 0;
3590 	/* fill in later from mbuf we build */
3591 	initackm_out->msg.ch.chunk_length = 0;
3592 	/* place in my tag */
3593 	if ((asoc != NULL) &&
3594 	    ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
3595 	     (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED))) {
3596 		/* re-use the v-tags and init-seq here */
3597 		initackm_out->msg.init.initiate_tag = htonl(asoc->my_vtag);
3598 		initackm_out->msg.init.initial_tsn = htonl(asoc->init_seq_number);
3599 	} else {
3600 		initackm_out->msg.init.initiate_tag = htonl(sctp_select_a_tag(inp));
3601 		/* get a TSN to use too */
3602 		initackm_out->msg.init.initial_tsn = htonl(sctp_select_initial_TSN(&inp->sctp_ep));
3603 	}
3604 	/* save away my tag to */
3605 	stc.my_vtag = initackm_out->msg.init.initiate_tag;
3606 
3607 	/* set up some of the credits. */
3608 	initackm_out->msg.init.a_rwnd = htonl(uimax(inp->sctp_socket->so_rcv.sb_hiwat, SCTP_MINIMAL_RWND));
3609 	/* set what I want */
3610 	his_limit = ntohs(init_chk->init.num_inbound_streams);
3611 	/* choose what I want */
3612 	if (asoc != NULL) {
3613 		if (asoc->streamoutcnt > inp->sctp_ep.pre_open_stream_count) {
3614 			i_want = asoc->streamoutcnt;
3615 		} else {
3616 			i_want = inp->sctp_ep.pre_open_stream_count;
3617 		}
3618 	} else {
3619 		i_want = inp->sctp_ep.pre_open_stream_count;
3620 	}
3621 	if (his_limit < i_want) {
3622 		/* I Want more :< */
3623 		initackm_out->msg.init.num_outbound_streams = init_chk->init.num_inbound_streams;
3624 	} else {
3625 		/* I can have what I want :> */
3626 		initackm_out->msg.init.num_outbound_streams = htons(i_want);
3627 	}
3628 	/* tell him his limt. */
3629 	initackm_out->msg.init.num_inbound_streams =
3630 	    htons(inp->sctp_ep.max_open_streams_intome);
3631 	/* setup the ECN pointer */
3632 
3633 /*	if (inp->sctp_flags & SCTP_PCB_FLAGS_ADAPTIONEVNT) {*/
3634 	if (inp->sctp_ep.adaption_layer_indicator) {
3635 		struct sctp_adaption_layer_indication *ali;
3636 		ali = (struct sctp_adaption_layer_indication *)(
3637 		    (vaddr_t)initackm_out + sizeof(*initackm_out));
3638 		ali->ph.param_type = htons(SCTP_ULP_ADAPTION);
3639 		ali->ph.param_length = htons(sizeof(*ali));
3640 		ali->indication = ntohl(inp->sctp_ep.adaption_layer_indicator);
3641 		m->m_len += sizeof(*ali);
3642 		ecn = (struct sctp_ecn_supported_param *)((vaddr_t)ali +
3643 		    sizeof(*ali));
3644 	} else {
3645 		ecn = (struct sctp_ecn_supported_param*)(
3646 		    (vaddr_t)initackm_out + sizeof(*initackm_out));
3647 	}
3648 
3649 	/* ECN parameter */
3650 	if (sctp_ecn == 1) {
3651 		ecn->ph.param_type = htons(SCTP_ECN_CAPABLE);
3652 		ecn->ph.param_length = htons(sizeof(*ecn));
3653 		m->m_len += sizeof(*ecn);
3654 
3655 		prsctp = (struct sctp_prsctp_supported_param *)((vaddr_t)ecn +
3656 		    sizeof(*ecn));
3657 	} else {
3658 		prsctp = (struct sctp_prsctp_supported_param *)((vaddr_t)ecn);
3659 	}
3660 	/* And now tell the peer we do  pr-sctp */
3661 	prsctp->ph.param_type = htons(SCTP_PRSCTP_SUPPORTED);
3662 	prsctp->ph.param_length = htons(sizeof(*prsctp));
3663 	m->m_len += sizeof(*prsctp);
3664 
3665 
3666 	/* And now tell the peer we do all the extensions */
3667 	pr_supported = (struct sctp_supported_chunk_types_param *)((vaddr_t)prsctp +
3668 	   sizeof(*prsctp));
3669 
3670 	pr_supported->ph.param_type = htons(SCTP_SUPPORTED_CHUNK_EXT);
3671 	pr_supported->ph.param_length = htons(sizeof(*pr_supported) + SCTP_EXT_COUNT);
3672 	pr_supported->chunk_types[0] = SCTP_ASCONF;
3673 	pr_supported->chunk_types[1] = SCTP_ASCONF_ACK;
3674 	pr_supported->chunk_types[2] = SCTP_FORWARD_CUM_TSN;
3675 	pr_supported->chunk_types[3] = SCTP_PACKET_DROPPED;
3676 	pr_supported->chunk_types[4] = SCTP_STREAM_RESET;
3677 	pr_supported->chunk_types[5] = 0; /* pad */
3678 	pr_supported->chunk_types[6] = 0; /* pad */
3679 	pr_supported->chunk_types[7] = 0; /* pad */
3680 
3681 	m->m_len += (sizeof(*pr_supported) + SCTP_EXT_COUNT + SCTP_PAD_EXT_COUNT);
3682 	if (sctp_ecn_nonce) {
3683 		/* ECN nonce: And now tell the peer we support ECN nonce */
3684 		ecn_nonce = (struct sctp_ecn_nonce_supported_param *)((vaddr_t)pr_supported +
3685 		     sizeof(*pr_supported) + SCTP_EXT_COUNT + SCTP_PAD_EXT_COUNT);
3686 		ecn_nonce->ph.param_type = htons(SCTP_ECN_NONCE_SUPPORTED);
3687 		ecn_nonce->ph.param_length = htons(sizeof(*ecn_nonce));
3688 		m->m_len += sizeof(*ecn_nonce);
3689 	}
3690 
3691 	m_at = m;
3692 	/* now the addresses */
3693 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
3694 		struct ifnet *ifn;
3695 		struct ifaddr *ifa;
3696 		int cnt = cnt_inits_to;
3697 		int s;
3698 
3699 		s = pserialize_read_enter();
3700 		IFNET_READER_FOREACH(ifn) {
3701 			if ((stc.loopback_scope == 0) &&
3702 			    (ifn->if_type == IFT_LOOP)) {
3703 				/*
3704 				 * Skip loopback devices if loopback_scope
3705 				 * not set
3706 				 */
3707 				continue;
3708 			}
3709 			IFADDR_READER_FOREACH(ifa, ifn) {
3710 				if (sctp_is_address_in_scope(ifa,
3711 				    stc.ipv4_addr_legal, stc.ipv6_addr_legal,
3712 				    stc.loopback_scope, stc.ipv4_scope,
3713 				    stc.local_scope, stc.site_scope) == 0) {
3714 					continue;
3715 				}
3716 				cnt++;
3717 			}
3718 		}
3719 		pserialize_read_exit(s);
3720 
3721 		if (cnt > 1) {
3722 			s = pserialize_read_enter();
3723 			IFNET_READER_FOREACH(ifn) {
3724 				if ((stc.loopback_scope == 0) &&
3725 				    (ifn->if_type == IFT_LOOP)) {
3726 					/*
3727 					 * Skip loopback devices if
3728 					 * loopback_scope not set
3729 					 */
3730 					continue;
3731 				}
3732 				IFADDR_READER_FOREACH(ifa, ifn) {
3733 					if (sctp_is_address_in_scope(ifa,
3734 					    stc.ipv4_addr_legal,
3735 					    stc.ipv6_addr_legal,
3736 					    stc.loopback_scope, stc.ipv4_scope,
3737 					    stc.local_scope, stc.site_scope) == 0) {
3738 						continue;
3739 					}
3740 					m_at = sctp_add_addr_to_mbuf(m_at, ifa);
3741 				}
3742 			}
3743 			pserialize_read_exit(s);
3744 		}
3745 	} else {
3746 		struct sctp_laddr *laddr;
3747 		int cnt;
3748 		cnt = cnt_inits_to;
3749 		/* First, how many ? */
3750 		LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
3751 			if (laddr->ifa == NULL) {
3752 				continue;
3753 			}
3754 			if (laddr->ifa->ifa_addr == NULL)
3755 				continue;
3756 			if (sctp_is_address_in_scope(laddr->ifa,
3757 			    stc.ipv4_addr_legal, stc.ipv6_addr_legal,
3758 			    stc.loopback_scope, stc.ipv4_scope,
3759 			    stc.local_scope, stc.site_scope) == 0) {
3760 				continue;
3761 			}
3762 			cnt++;
3763 		}
3764 		/* If we bind a single address only we won't list
3765 		 * any. This way you can get through a NAT
3766 		 */
3767 		if (cnt > 1) {
3768 			LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
3769 				if (laddr->ifa == NULL) {
3770 #ifdef SCTP_DEBUG
3771 					if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
3772 						printf("Help I have fallen and I can't get up!\n");
3773 					}
3774 #endif
3775 					continue;
3776 				}
3777 				if (laddr->ifa->ifa_addr == NULL)
3778 					continue;
3779 				if (sctp_is_address_in_scope(laddr->ifa,
3780 				    stc.ipv4_addr_legal, stc.ipv6_addr_legal,
3781 				    stc.loopback_scope, stc.ipv4_scope,
3782 				    stc.local_scope, stc.site_scope) == 0) {
3783 					continue;
3784 				}
3785 				m_at = sctp_add_addr_to_mbuf(m_at, laddr->ifa);
3786 			}
3787 		}
3788 	}
3789 
3790 	/* tack on the operational error if present */
3791 	if (op_err) {
3792 		if (op_err->m_pkthdr.len % 4) {
3793 			/* must add a pad to the param */
3794 			u_int32_t cpthis=0;
3795 			int padlen;
3796 			padlen = 4 - (op_err->m_pkthdr.len % 4);
3797 			m_copyback(op_err, op_err->m_pkthdr.len, padlen, (void *)&cpthis);
3798 		}
3799 		while (m_at->m_next != NULL) {
3800 			m_at = m_at->m_next;
3801 		}
3802 		m_at->m_next = op_err;
3803 		while (m_at->m_next != NULL) {
3804 			m_at = m_at->m_next;
3805 		}
3806 	}
3807 	/* Get total size of init packet */
3808 	sz_of = SCTP_SIZE32(ntohs(init_chk->ch.chunk_length));
3809 	/* pre-calulate the size and update pkt header and chunk header */
3810 	m->m_pkthdr.len = 0;
3811 	for (m_tmp = m; m_tmp; m_tmp = m_tmp->m_next) {
3812 		m->m_pkthdr.len += m_tmp->m_len;
3813 		if (m_tmp->m_next == NULL) {
3814 			/* m_tmp should now point to last one */
3815 			break;
3816 		}
3817 	}
3818 	/*
3819 	 * Figure now the size of the cookie. We know the size of the
3820 	 * INIT-ACK. The Cookie is going to be the size of INIT, INIT-ACK,
3821 	 * COOKIE-STRUCTURE and SIGNATURE.
3822 	 */
3823 
3824 	/*
3825 	 * take our earlier INIT calc and add in the sz we just calculated
3826 	 * minus the size of the sctphdr (its not included in chunk size
3827 	 */
3828 
3829 	/* add once for the INIT-ACK */
3830 	sz_of += (m->m_pkthdr.len - sizeof(struct sctphdr));
3831 
3832 	/* add a second time for the INIT-ACK in the cookie */
3833 	sz_of += (m->m_pkthdr.len - sizeof(struct sctphdr));
3834 
3835 	/* Now add the cookie header and cookie message struct */
3836 	sz_of += sizeof(struct sctp_state_cookie_param);
3837 	/* ...and add the size of our signature */
3838 	sz_of += SCTP_SIGNATURE_SIZE;
3839 	initackm_out->msg.ch.chunk_length = htons(sz_of);
3840 
3841 	/* Now we must build a cookie */
3842 	m_cookie = sctp_add_cookie(inp, init_pkt, offset, m,
3843 	    sizeof(struct sctphdr), &stc);
3844 	if (m_cookie == NULL) {
3845 		/* memory problem */
3846 		sctp_m_freem(m);
3847 		return;
3848 	}
3849 	/* Now append the cookie to the end and update the space/size */
3850 	m_tmp->m_next = m_cookie;
3851 
3852 	/*
3853 	 * We pass 0 here to NOT set IP_DF if its IPv4, we ignore the
3854 	 * return here since the timer will drive a retranmission.
3855 	 */
3856 	padval = m->m_pkthdr.len % 4;
3857 	if ((padval) && (m_last)) {
3858 		/* see my previous comments on m_last */
3859 		int ret;
3860 		ret = sctp_add_pad_tombuf(m_last, (4-padval));
3861 		if (ret) {
3862 			/* Houston we have a problem, no space */
3863 			sctp_m_freem(m);
3864 			return;
3865 		}
3866 		m->m_pkthdr.len += padval;
3867 	}
3868 	sctp_lowlevel_chunk_output(inp, NULL, NULL, to, m, 0, 0, NULL, 0);
3869 }
3870 
3871 
3872 static void
3873 sctp_insert_on_wheel(struct sctp_association *asoc,
3874 		     struct sctp_stream_out *strq)
3875 {
3876 	struct sctp_stream_out *stre, *strn;
3877 	stre = TAILQ_FIRST(&asoc->out_wheel);
3878 	if (stre == NULL) {
3879 		/* only one on wheel */
3880 		TAILQ_INSERT_HEAD(&asoc->out_wheel, strq, next_spoke);
3881 		return;
3882 	}
3883 	for (; stre; stre = strn) {
3884 		strn = TAILQ_NEXT(stre, next_spoke);
3885 		if (stre->stream_no > strq->stream_no) {
3886 			TAILQ_INSERT_BEFORE(stre, strq, next_spoke);
3887 			return;
3888 		} else if (stre->stream_no == strq->stream_no) {
3889 			/* huh, should not happen */
3890 			return;
3891 		} else if (strn == NULL) {
3892 			/* next one is null */
3893 			TAILQ_INSERT_AFTER(&asoc->out_wheel, stre, strq,
3894 					   next_spoke);
3895 		}
3896 	}
3897 }
3898 
3899 static void
3900 sctp_remove_from_wheel(struct sctp_association *asoc,
3901 		       struct sctp_stream_out *strq)
3902 {
3903 	/* take off and then setup so we know it is not on the wheel */
3904 	TAILQ_REMOVE(&asoc->out_wheel, strq, next_spoke);
3905 	strq->next_spoke.tqe_next = NULL;
3906 	strq->next_spoke.tqe_prev = NULL;
3907 }
3908 
3909 
3910 static void
3911 sctp_prune_prsctp(struct sctp_tcb *stcb,
3912 		  struct sctp_association *asoc,
3913 		  struct sctp_sndrcvinfo *srcv,
3914 		  int dataout
3915 	)
3916 {
3917 	int freed_spc=0;
3918 	struct sctp_tmit_chunk *chk, *nchk;
3919 	if ((asoc->peer_supports_prsctp) && (asoc->sent_queue_cnt_removeable > 0)) {
3920 		TAILQ_FOREACH(chk, &asoc->sent_queue, sctp_next) {
3921 			/*
3922 			 * Look for chunks marked with the PR_SCTP
3923 			 * flag AND the buffer space flag. If the one
3924 			 * being sent is equal or greater priority then
3925 			 * purge the old one and free some space.
3926 			 */
3927 			if ((chk->flags & (SCTP_PR_SCTP_ENABLED |
3928 					   SCTP_PR_SCTP_BUFFER)) ==
3929 			    (SCTP_PR_SCTP_ENABLED|SCTP_PR_SCTP_BUFFER)) {
3930 				/*
3931 				 * This one is PR-SCTP AND buffer space
3932 				 * limited type
3933 				 */
3934 				if (chk->rec.data.timetodrop.tv_sec >= (long)srcv->sinfo_timetolive) {
3935 					/* Lower numbers equates to
3936 					 * higher priority so if the
3937 					 * one we are looking at has a
3938 					 * larger or equal priority we
3939 					 * want to drop the data and
3940 					 * NOT retransmit it.
3941 					 */
3942 					if (chk->data) {
3943 						/* We release the
3944 						 * book_size if the
3945 						 * mbuf is here
3946 						 */
3947 						int ret_spc;
3948 						int cause;
3949 						if (chk->sent > SCTP_DATAGRAM_UNSENT)
3950 							cause = SCTP_RESPONSE_TO_USER_REQ|SCTP_NOTIFY_DATAGRAM_SENT;
3951 						else
3952 							cause = SCTP_RESPONSE_TO_USER_REQ|SCTP_NOTIFY_DATAGRAM_UNSENT;
3953 						ret_spc  = sctp_release_pr_sctp_chunk(stcb, chk,
3954 										      cause,
3955 										      &asoc->sent_queue);
3956 						freed_spc += ret_spc;
3957 						if (freed_spc >= dataout) {
3958 							return;
3959 						}
3960 					} /* if chunk was present */
3961 				} /* if of sufficient priority */
3962 			} /* if chunk has enabled */
3963 		} /* tailqforeach */
3964 
3965 		chk = TAILQ_FIRST(&asoc->send_queue);
3966 		while (chk) {
3967 			nchk = TAILQ_NEXT(chk, sctp_next);
3968 			/* Here we must move to the sent queue and mark */
3969 			if ((chk->flags & (SCTP_PR_SCTP_ENABLED |
3970 					   SCTP_PR_SCTP_BUFFER)) ==
3971 			    (SCTP_PR_SCTP_ENABLED|SCTP_PR_SCTP_BUFFER)) {
3972 				if (chk->rec.data.timetodrop.tv_sec >= (long)srcv->sinfo_timetolive) {
3973 					if (chk->data) {
3974 						/* We release the
3975 						 * book_size if the
3976 						 * mbuf is here
3977 						 */
3978 						int ret_spc;
3979 						ret_spc  = sctp_release_pr_sctp_chunk(stcb, chk,
3980 						    SCTP_RESPONSE_TO_USER_REQ|SCTP_NOTIFY_DATAGRAM_UNSENT,
3981 						    &asoc->send_queue);
3982 
3983 						freed_spc += ret_spc;
3984 						if (freed_spc >= dataout) {
3985 							return;
3986 						}
3987 					} /* end if chk->data */
3988 				} /* end if right class */
3989 			} /* end if chk pr-sctp */
3990 			chk = nchk;
3991 		} /* end while (chk) */
3992 	} /* if enabled in asoc */
3993 }
3994 
3995 static void
3996 sctp_prepare_chunk(struct sctp_tmit_chunk *template,
3997 		   struct sctp_tcb *stcb,
3998 		   struct sctp_sndrcvinfo *srcv,
3999 		   struct sctp_stream_out *strq,
4000 		   struct sctp_nets *net)
4001 {
4002 	memset(template, 0, sizeof(struct sctp_tmit_chunk));
4003 	template->sent = SCTP_DATAGRAM_UNSENT;
4004 	if ((stcb->asoc.peer_supports_prsctp) &&
4005 	    (srcv->sinfo_flags & (SCTP_PR_SCTP_TTL|SCTP_PR_SCTP_BUF)) &&
4006 	    (srcv->sinfo_timetolive > 0)
4007 		) {
4008 		/* If:
4009 		 *  Peer supports PR-SCTP
4010 		 *  The flags is set against this send for PR-SCTP
4011 		 *  And timetolive is a positive value, zero is reserved
4012 		 *     to mean a reliable send for both buffer/time
4013 		 *     related one.
4014 		 */
4015 		if (srcv->sinfo_flags & SCTP_PR_SCTP_BUF) {
4016 			/*
4017 			 * Time to live is a priority stored in tv_sec
4018 			 * when doing the buffer drop thing.
4019 			 */
4020 			template->rec.data.timetodrop.tv_sec = srcv->sinfo_timetolive;
4021 		} else {
4022 			struct timeval tv;
4023 
4024 			SCTP_GETTIME_TIMEVAL(&template->rec.data.timetodrop);
4025 			tv.tv_sec = srcv->sinfo_timetolive / 1000;
4026 			tv.tv_usec = (srcv->sinfo_timetolive * 1000) % 1000000;
4027 #ifndef __FreeBSD__
4028 			timeradd(&template->rec.data.timetodrop, &tv,
4029 			    &template->rec.data.timetodrop);
4030 #else
4031 			timevaladd(&template->rec.data.timetodrop, &tv);
4032 #endif
4033 		}
4034 	}
4035 	if ((srcv->sinfo_flags & SCTP_UNORDERED) == 0) {
4036 		template->rec.data.stream_seq = strq->next_sequence_sent;
4037 	} else {
4038 		template->rec.data.stream_seq = 0;
4039 	}
4040 	template->rec.data.TSN_seq = 0;	/* not yet assigned */
4041 
4042 	template->rec.data.stream_number = srcv->sinfo_stream;
4043 	template->rec.data.payloadtype = srcv->sinfo_ppid;
4044 	template->rec.data.context = srcv->sinfo_context;
4045 	template->rec.data.doing_fast_retransmit = 0;
4046 	template->rec.data.ect_nonce = 0;   /* ECN Nonce */
4047 
4048 	if (srcv->sinfo_flags & SCTP_ADDR_OVER) {
4049 		template->whoTo = net;
4050 	} else {
4051 		if (stcb->asoc.primary_destination)
4052 			template->whoTo = stcb->asoc.primary_destination;
4053 		else {
4054 			/* TSNH */
4055 			template->whoTo = net;
4056 		}
4057 	}
4058 	/* the actual chunk flags */
4059 	if (srcv->sinfo_flags & SCTP_UNORDERED) {
4060 		template->rec.data.rcv_flags = SCTP_DATA_UNORDERED;
4061 	} else {
4062 		template->rec.data.rcv_flags = 0;
4063 	}
4064 	/* no flags yet, FRAGMENT_OK goes here */
4065 	template->flags = 0;
4066 	/* PR sctp flags */
4067 	if (stcb->asoc.peer_supports_prsctp) {
4068 		if (srcv->sinfo_timetolive > 0) {
4069 			/*
4070 			 * We only set the flag if timetolive (or
4071 			 * priority) was set to a positive number.
4072 			 * Zero is reserved specifically to be
4073 			 * EXCLUDED and sent reliable.
4074 			 */
4075 			if (srcv->sinfo_flags & SCTP_PR_SCTP_TTL) {
4076 				template->flags |= SCTP_PR_SCTP_ENABLED;
4077 			}
4078 			if (srcv->sinfo_flags & SCTP_PR_SCTP_BUF) {
4079 				template->flags |= SCTP_PR_SCTP_BUFFER;
4080 			}
4081 		}
4082 	}
4083 	template->asoc = &stcb->asoc;
4084 }
4085 
4086 
4087 int
4088 sctp_get_frag_point(struct sctp_tcb *stcb,
4089 		    struct sctp_association *asoc)
4090 {
4091 	int siz, ovh;
4092 
4093 	/* For endpoints that have both 6 and 4 addresses
4094 	 * we must reserver room for the 6 ip header, for
4095 	 * those that are only dealing with V4 we use
4096 	 * a larger frag point.
4097 	 */
4098  	if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
4099 		ovh = SCTP_MED_OVERHEAD;
4100 	} else {
4101 		ovh = SCTP_MED_V4_OVERHEAD;
4102 	}
4103 
4104 	if (stcb->sctp_ep->sctp_frag_point > asoc->smallest_mtu)
4105 		siz = asoc->smallest_mtu - ovh;
4106 	else
4107 		siz = (stcb->sctp_ep->sctp_frag_point - ovh);
4108 /*
4109   if (siz > (MCLBYTES-sizeof(struct sctp_data_chunk))) { */
4110 		/* A data chunk MUST fit in a cluster */
4111 /*		siz = (MCLBYTES - sizeof(struct sctp_data_chunk));*/
4112 /*	}*/
4113 
4114 	if (siz % 4) {
4115 		/* make it an even word boundary please */
4116 		siz -= (siz % 4);
4117 	}
4118 	return (siz);
4119 }
4120 extern unsigned int sctp_max_chunks_on_queue;
4121 
4122 #define   SBLOCKWAIT(f)   (((f)&MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
4123 
4124 static int
4125 sctp_msg_append(struct sctp_tcb *stcb,
4126 		struct sctp_nets *net,
4127 		struct mbuf *m,
4128 		struct sctp_sndrcvinfo *srcv,
4129 		int flags)
4130 {
4131 	struct socket *so;
4132 	struct sctp_association *asoc;
4133 	struct sctp_stream_out *strq;
4134 	struct sctp_tmit_chunk *chk;
4135 	struct sctpchunk_listhead tmp;
4136 	struct sctp_tmit_chunk template;
4137 	struct mbuf *n, *mnext;
4138 	struct mbuf *mm;
4139 	unsigned int dataout, siz;
4140 	int mbcnt = 0;
4141 	int mbcnt_e = 0;
4142 	int error = 0;
4143 
4144 	if ((stcb == NULL) || (net == NULL) || (m == NULL) || (srcv == NULL)) {
4145 		/* Software fault, you blew it on the call */
4146 #ifdef SCTP_DEBUG
4147 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
4148 			printf("software error in sctp_msg_append:1\n");
4149 			printf("stcb:%p net:%p m:%p srcv:%p\n",
4150 			       stcb, net, m, srcv);
4151 		}
4152 #endif
4153 		if (m)
4154 			sctp_m_freem(m);
4155 		return (EFAULT);
4156 	}
4157 	so = stcb->sctp_socket;
4158 	asoc = &stcb->asoc;
4159 	if (srcv->sinfo_flags & SCTP_ABORT) {
4160 		if ((SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_WAIT) &&
4161 		    (SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_ECHOED)) {
4162 			/* It has to be up before we abort */
4163 			/* how big is the user initiated abort? */
4164 			if ((m->m_flags & M_PKTHDR) && (m->m_pkthdr.len)) {
4165 				dataout = m->m_pkthdr.len;
4166 			} else {
4167 				/* we must count */
4168 				dataout = 0;
4169 				for (n = m; n; n = n->m_next) {
4170 					dataout += n->m_len;
4171 				}
4172 			}
4173 			M_PREPEND(m, sizeof(struct sctp_paramhdr), M_DONTWAIT);
4174 			if (m) {
4175 				struct sctp_paramhdr *ph;
4176 				m->m_len = sizeof(struct sctp_paramhdr) + dataout;
4177 				ph = mtod(m, struct sctp_paramhdr *);
4178 				ph->param_type = htons(SCTP_CAUSE_USER_INITIATED_ABT);
4179 				ph->param_length = htons(m->m_len);
4180 			}
4181 			sctp_abort_an_association(stcb->sctp_ep, stcb, SCTP_RESPONSE_TO_USER_REQ, m);
4182 			m = NULL;
4183 		} else {
4184 			/* Only free if we don't send an abort */
4185 			;
4186 		}
4187 		goto out;
4188 	}
4189 	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
4190 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
4191 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
4192 	    (asoc->state & SCTP_STATE_SHUTDOWN_PENDING)) {
4193 		/* got data while shutting down */
4194 		error = ECONNRESET;
4195 		goto out;
4196 	}
4197 
4198 	if (srcv->sinfo_stream >= asoc->streamoutcnt) {
4199 		/* Invalid stream number */
4200 		error = EINVAL;
4201 		goto out;
4202 	}
4203 	if (asoc->strmout == NULL) {
4204 		/* huh? software error */
4205 #ifdef SCTP_DEBUG
4206 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
4207 			printf("software error in sctp_msg_append:2\n");
4208 		}
4209 #endif
4210 		error = EFAULT;
4211 		goto out;
4212 	}
4213 	strq = &asoc->strmout[srcv->sinfo_stream];
4214 	/* how big is it ? */
4215 	if ((m->m_flags & M_PKTHDR) && (m->m_pkthdr.len)) {
4216 		dataout = m->m_pkthdr.len;
4217 	} else {
4218 		/* we must count */
4219 		dataout = 0;
4220 		for (n = m; n; n = n->m_next) {
4221 			dataout += n->m_len;
4222 		}
4223 	}
4224 #ifdef SCTP_DEBUG
4225 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
4226 		printf("Attempt to send out %d bytes\n",
4227 		       dataout);
4228 	}
4229 #endif
4230 
4231 	/* lock the socket buf */
4232 	error = sblock(&so->so_snd, SBLOCKWAIT(flags));
4233 	if (error)
4234 		goto out_locked;
4235 
4236 	if (dataout > so->so_snd.sb_hiwat) {
4237 		/* It will NEVER fit */
4238 		error = EMSGSIZE;
4239 		goto release;
4240 	}
4241 	if ((srcv->sinfo_flags & SCTP_EOF) &&
4242 	    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_UDPTYPE) &&
4243 	    (dataout == 0)
4244 		) {
4245 		goto zap_by_it_all;
4246 	}
4247 	if ((so->so_snd.sb_hiwat <
4248 	     (dataout + asoc->total_output_queue_size)) ||
4249 	    (asoc->chunks_on_out_queue > sctp_max_chunks_on_queue) ||
4250 	    (asoc->total_output_mbuf_queue_size >
4251 	     so->so_snd.sb_mbmax)
4252 		) {
4253 		/* XXX Buffer space hunt for data to skip */
4254 		if (asoc->peer_supports_prsctp) {
4255 			sctp_prune_prsctp(stcb, asoc, srcv, dataout);
4256 		}
4257 		while ((so->so_snd.sb_hiwat <
4258 		    (dataout + asoc->total_output_queue_size)) ||
4259 		    (asoc->chunks_on_out_queue > sctp_max_chunks_on_queue) ||
4260 		    (asoc->total_output_mbuf_queue_size >
4261 		    so->so_snd.sb_mbmax)) {
4262 			struct sctp_inpcb *inp;
4263 			/* Now did we free up enough room? */
4264 			if (so->so_state & SS_NBIO) {
4265 				/* Non-blocking io in place */
4266 				error = EWOULDBLOCK;
4267 				goto release;
4268 			}
4269 			/*
4270 			 * We store off a pointer to the endpoint.
4271 			 * Since on return from this we must check to
4272 			 * see if an so_error is set. If so we may have
4273 			 * been reset and our stcb destroyed. Returning
4274 			 * an error will cause the correct error return
4275 			 * through and fix this all.
4276 			 */
4277 			inp = stcb->sctp_ep;
4278 			/*
4279 			 * Not sure how else to do this since
4280 			 * the level we suspended at is not
4281 			 * known deep down where we are. I will
4282 			 * drop to spl0() so that others can
4283 			 * get in.
4284 			 */
4285 
4286 			inp->sctp_tcb_at_block = (void *)stcb;
4287 			inp->error_on_block = 0;
4288 			sbunlock(&so->so_snd);
4289 			error = sbwait(&so->so_snd);
4290 			/*
4291 			 * XXX: This is ugly but I have
4292 			 * recreated most of what goes on to
4293 			 * block in the sb. UGHH
4294 			 * May want to add the bit about being
4295 			 * no longer connected.. but this then
4296 			 * further dooms the UDP model NOT to
4297 			 * allow this.
4298 			 */
4299 			inp->sctp_tcb_at_block = 0;
4300 			if (inp->error_on_block)
4301 				error = inp->error_on_block;
4302 			if (so->so_error)
4303 				error = so->so_error;
4304 			if (error) {
4305 				goto out_locked;
4306 			}
4307 			error = sblock(&so->so_snd, M_WAITOK);
4308 			if (error)
4309 				goto out_locked;
4310 			/* Otherwise we cycle back and recheck
4311 			 * the space
4312 			 */
4313 #if defined(__FreeBSD__) && __FreeBSD_version >= 502115
4314 			if (so->so_rcv.sb_state & SBS_CANTSENDMORE) {
4315 #else
4316 			if (so->so_state & SS_CANTSENDMORE) {
4317 #endif
4318 				error = EPIPE;
4319 				goto release;
4320 			}
4321 			if (so->so_error) {
4322 				error = so->so_error;
4323 				goto release;
4324 			}
4325 		}
4326 	}
4327 	/* If we have a packet header fix it if it was broke */
4328 	if (m->m_flags & M_PKTHDR) {
4329 		m->m_pkthdr.len = dataout;
4330 	}
4331 	/* use the smallest one, user set value or
4332 	 * smallest mtu of the asoc
4333 	 */
4334 	siz = sctp_get_frag_point(stcb, asoc);
4335 	if ((dataout) && (dataout <= siz)) {
4336 		/* Fast path */
4337 		chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
4338 		if (chk == NULL) {
4339 			error = ENOMEM;
4340 			goto release;
4341 		}
4342 		sctp_prepare_chunk(chk, stcb, srcv, strq, net);
4343 		chk->whoTo->ref_count++;
4344 		chk->rec.data.rcv_flags |= SCTP_DATA_NOT_FRAG;
4345 
4346 		/* no flags yet, FRAGMENT_OK goes here */
4347 		sctppcbinfo.ipi_count_chunk++;
4348 		sctppcbinfo.ipi_gencnt_chunk++;
4349 		asoc->chunks_on_out_queue++;
4350 		chk->data = m;
4351 		m = NULL;
4352 		/* Total in the MSIZE */
4353 		for (mm = chk->data; mm; mm = mm->m_next) {
4354 			mbcnt += MSIZE;
4355 			if (mm->m_flags & M_EXT) {
4356 				mbcnt += chk->data->m_ext.ext_size;
4357 			}
4358 		}
4359 		/* fix up the send_size if it is not present */
4360 		chk->send_size = dataout;
4361 		chk->book_size = chk->send_size;
4362 		chk->mbcnt = mbcnt;
4363 		/* ok, we are committed */
4364 		if ((srcv->sinfo_flags & SCTP_UNORDERED) == 0) {
4365 			/* bump the ssn if we are unordered. */
4366 			strq->next_sequence_sent++;
4367 		}
4368 		chk->data->m_nextpkt = 0;
4369 		asoc->stream_queue_cnt++;
4370 		TAILQ_INSERT_TAIL(&strq->outqueue, chk, sctp_next);
4371 		/* now check if this stream is on the wheel */
4372 		if ((strq->next_spoke.tqe_next == NULL) &&
4373 		    (strq->next_spoke.tqe_prev == NULL)) {
4374 			/* Insert it on the wheel since it is not
4375 			 * on it currently
4376 			 */
4377 			sctp_insert_on_wheel(asoc, strq);
4378 		}
4379 	} else if ((dataout) && (dataout > siz)) {
4380 		/* Slow path */
4381 		if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_NO_FRAGMENT) &&
4382 		    (dataout > siz)) {
4383 			error = EMSGSIZE;
4384 			goto release;
4385 		}
4386 		/* setup the template */
4387 		sctp_prepare_chunk(&template, stcb, srcv, strq, net);
4388 
4389 		n = m;
4390 		while (dataout > siz) {
4391 			/*
4392 			 * We can wait since this is called from the user
4393 			 * send side
4394 			 */
4395 			n->m_nextpkt = m_split(n, siz, M_WAIT);
4396 			if (n->m_nextpkt == NULL) {
4397 				error = EFAULT;
4398 				goto release;
4399 			}
4400 			dataout -= siz;
4401 			n = n->m_nextpkt;
4402 		}
4403 		/*
4404 		 * ok, now we have a chain on m where m->m_nextpkt points to
4405 		 * the next chunk and m/m->m_next chain is the piece to send.
4406 		 * We must go through the chains and thread them on to
4407 		 * sctp_tmit_chunk chains and place them all on the stream
4408 		 * queue, breaking the m->m_nextpkt pointers as we go.
4409 		 */
4410 		n = m;
4411 		TAILQ_INIT(&tmp);
4412 		while (n) {
4413 			/*
4414 			 * first go through and allocate a sctp_tmit chunk
4415 			 * for each chunk piece
4416 			 */
4417 			chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
4418 			if (chk == NULL) {
4419 				/*
4420 				 * ok we must spin through and dump anything
4421 				 * we have allocated and then jump to the
4422 				 * no_membad
4423 				 */
4424 				chk = TAILQ_FIRST(&tmp);
4425 				while (chk) {
4426 					TAILQ_REMOVE(&tmp, chk, sctp_next);
4427 					SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
4428 					sctppcbinfo.ipi_count_chunk--;
4429 					asoc->chunks_on_out_queue--;
4430 					if ((int)sctppcbinfo.ipi_count_chunk < 0) {
4431 						panic("Chunk count is negative");
4432 					}
4433 					sctppcbinfo.ipi_gencnt_chunk++;
4434 					chk = TAILQ_FIRST(&tmp);
4435 				}
4436 				error = ENOMEM;
4437 				goto release;
4438 			}
4439 			sctppcbinfo.ipi_count_chunk++;
4440 			asoc->chunks_on_out_queue++;
4441 
4442 			sctppcbinfo.ipi_gencnt_chunk++;
4443 			*chk = template;
4444 			chk->whoTo->ref_count++;
4445 			chk->data = n;
4446 			/* Total in the MSIZE */
4447 			mbcnt_e = 0;
4448 			for (mm = chk->data; mm; mm = mm->m_next) {
4449 				mbcnt_e += MSIZE;
4450 				if (mm->m_flags & M_EXT) {
4451 					mbcnt_e += chk->data->m_ext.ext_size;
4452 				}
4453 			}
4454 			/* now fix the chk->send_size */
4455 			if (chk->data->m_flags & M_PKTHDR) {
4456 				chk->send_size = chk->data->m_pkthdr.len;
4457 			} else {
4458 				struct mbuf *nn;
4459 				chk->send_size = 0;
4460 				for (nn = chk->data; nn; nn = nn->m_next) {
4461 					chk->send_size += nn->m_len;
4462 				}
4463 			}
4464 			chk->book_size = chk->send_size;
4465 			chk->mbcnt = mbcnt_e;
4466 			mbcnt += mbcnt_e;
4467 			if (chk->flags & SCTP_PR_SCTP_BUFFER) {
4468 				asoc->sent_queue_cnt_removeable++;
4469 			}
4470 			n = n->m_nextpkt;
4471 			TAILQ_INSERT_TAIL(&tmp, chk, sctp_next);
4472 		}
4473 		m = NULL;
4474 		/* now that we have enough space for all de-couple the
4475 		 * chain of mbufs by going through our temp array
4476 		 * and breaking the pointers.
4477 		 */
4478 		/* ok, we are committed */
4479 		if ((srcv->sinfo_flags & SCTP_UNORDERED) == 0) {
4480 			/* bump the ssn if we are unordered. */
4481 			strq->next_sequence_sent++;
4482 		}
4483 		/* Mark the first/last flags. This will
4484 		 * result int a 3 for a single item on the list
4485 		 */
4486 		chk = TAILQ_FIRST(&tmp);
4487 		chk->rec.data.rcv_flags |= SCTP_DATA_FIRST_FRAG;
4488 		chk = TAILQ_LAST(&tmp, sctpchunk_listhead);
4489 		chk->rec.data.rcv_flags |= SCTP_DATA_LAST_FRAG;
4490 		/* now break any chains on the queue and
4491 		 * move it to the streams actual queue.
4492 		 */
4493 		chk = TAILQ_FIRST(&tmp);
4494 		while (chk) {
4495 			chk->data->m_nextpkt = 0;
4496 			TAILQ_REMOVE(&tmp, chk, sctp_next);
4497 			asoc->stream_queue_cnt++;
4498 			TAILQ_INSERT_TAIL(&strq->outqueue, chk, sctp_next);
4499 			chk = TAILQ_FIRST(&tmp);
4500 		}
4501 		/* now check if this stream is on the wheel */
4502 		if ((strq->next_spoke.tqe_next == NULL) &&
4503 		    (strq->next_spoke.tqe_prev == NULL)) {
4504 			/* Insert it on the wheel since it is not
4505 			 * on it currently
4506 			 */
4507 			sctp_insert_on_wheel(asoc, strq);
4508 		}
4509 	}
4510 	/* has a SHUTDOWN been (also) requested by the user on this asoc? */
4511 zap_by_it_all:
4512 
4513 	if ((srcv->sinfo_flags & SCTP_EOF) &&
4514 	    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_UDPTYPE)) {
4515 
4516 		int some_on_streamwheel = 0;
4517 
4518 		if (!TAILQ_EMPTY(&asoc->out_wheel)) {
4519 			/* Check to see if some data queued */
4520 			struct sctp_stream_out *outs;
4521 			TAILQ_FOREACH(outs, &asoc->out_wheel, next_spoke) {
4522 				if (!TAILQ_EMPTY(&outs->outqueue)) {
4523 					some_on_streamwheel = 1;
4524 					break;
4525 				}
4526 			}
4527 		}
4528 
4529 		if (TAILQ_EMPTY(&asoc->send_queue) &&
4530 		    TAILQ_EMPTY(&asoc->sent_queue) &&
4531 		    (some_on_streamwheel == 0)) {
4532 			/* there is nothing queued to send, so I'm done... */
4533 			if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
4534 			    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
4535 				/* only send SHUTDOWN the first time through */
4536 #ifdef SCTP_DEBUG
4537 				if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
4538 					printf("%s:%d sends a shutdown\n",
4539 					       __FILE__,
4540 					       __LINE__
4541 						);
4542 				}
4543 #endif
4544 				sctp_send_shutdown(stcb, stcb->asoc.primary_destination);
4545 				asoc->state = SCTP_STATE_SHUTDOWN_SENT;
4546 				sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, stcb->sctp_ep, stcb,
4547 						 asoc->primary_destination);
4548 				sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
4549 						 asoc->primary_destination);
4550 			}
4551 		} else {
4552 			/*
4553 			 * we still got (or just got) data to send, so set
4554 			 * SHUTDOWN_PENDING
4555 			 */
4556 			asoc->state |= SCTP_STATE_SHUTDOWN_PENDING;
4557 		}
4558 	}
4559 #ifdef SCTP_MBCNT_LOGGING
4560 	sctp_log_mbcnt(SCTP_LOG_MBCNT_INCREASE,
4561 		       asoc->total_output_queue_size,
4562 		       dataout,
4563 		       asoc->total_output_mbuf_queue_size,
4564 		       mbcnt);
4565 #endif
4566 	asoc->total_output_queue_size += dataout;
4567 	asoc->total_output_mbuf_queue_size += mbcnt;
4568 	if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
4569 	    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
4570 		so->so_snd.sb_cc += dataout;
4571 		so->so_snd.sb_mbcnt += mbcnt;
4572 	}
4573 
4574 #ifdef SCTP_DEBUG
4575 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT2) {
4576 		printf("++total out:%d total_mbuf_out:%d\n",
4577 		       (int)asoc->total_output_queue_size,
4578 		       (int)asoc->total_output_mbuf_queue_size);
4579 	}
4580 #endif
4581 
4582 release:
4583 	sbunlock(&so->so_snd);
4584 out_locked:
4585 
4586 out:
4587 	if (m && m->m_nextpkt) {
4588 		n = m;
4589 		while (n) {
4590 			mnext = n->m_nextpkt;
4591 			n->m_nextpkt = NULL;
4592 			sctp_m_freem(n);
4593 			n = mnext;
4594 		}
4595 	} else if (m)
4596 		sctp_m_freem(m);
4597 
4598 	return (error);
4599 }
4600 
4601 static struct mbuf *
4602 sctp_copy_mbufchain(struct mbuf *clonechain,
4603 		    struct mbuf *outchain)
4604 {
4605 	struct mbuf *appendchain;
4606 #if defined(__FreeBSD__) || defined(__NetBSD__)
4607 	/* Supposedly m_copypacket is an optimization, use it if we can */
4608 	if (clonechain->m_flags & M_PKTHDR) {
4609 		appendchain = m_copypacket(clonechain, M_DONTWAIT);
4610 		sctp_pegs[SCTP_CACHED_SRC]++;
4611 	} else
4612 		appendchain = m_copym(clonechain, 0, M_COPYALL, M_DONTWAIT);
4613 #elif defined(__APPLE__)
4614 	appendchain = sctp_m_copym(clonechain, 0, M_COPYALL, M_DONTWAIT);
4615 #else
4616 	appendchain = m_copy(clonechain, 0, M_COPYALL);
4617 #endif
4618 
4619 	if (appendchain == NULL) {
4620 		/* error */
4621 		if (outchain)
4622 			sctp_m_freem(outchain);
4623 		return (NULL);
4624 	}
4625 	if (outchain) {
4626 		/* tack on to the end */
4627 		struct mbuf *m;
4628 		m = outchain;
4629 		while (m) {
4630 			if (m->m_next == NULL) {
4631 				m->m_next = appendchain;
4632 				break;
4633 			}
4634 			m = m->m_next;
4635 		}
4636 		if (outchain->m_flags & M_PKTHDR) {
4637 			int append_tot;
4638 			struct mbuf *t;
4639 			t = appendchain;
4640 			append_tot = 0;
4641 			while (t) {
4642 				append_tot += t->m_len;
4643 				t = t->m_next;
4644 			}
4645 			outchain->m_pkthdr.len += append_tot;
4646 		}
4647 		return (outchain);
4648 	} else {
4649 		return (appendchain);
4650 	}
4651 }
4652 
4653 static void
4654 sctp_sendall_iterator(struct sctp_inpcb *inp, struct sctp_tcb *stcb, void *ptr, u_int32_t val)
4655 {
4656 	struct sctp_copy_all *ca;
4657 	struct mbuf *m;
4658 	int turned_on_nonblock=0, ret;
4659 
4660 	ca = (struct sctp_copy_all *)ptr;
4661 	if (ca->m == NULL) {
4662 		return;
4663 	}
4664 	if (ca->inp != inp) {
4665 		/* TSNH */
4666 		return;
4667 	}
4668 	m = sctp_copy_mbufchain(ca->m, NULL);
4669 	if (m == NULL) {
4670 		/* can't copy so we are done */
4671 		ca->cnt_failed++;
4672 		return;
4673 	}
4674 	if ((stcb->sctp_socket->so_state & SS_NBIO) == 0) {
4675 		/* we have to do this non-blocking */
4676 		turned_on_nonblock = 1;
4677 		stcb->sctp_socket->so_state |= SS_NBIO;
4678 	}
4679 	ret = sctp_msg_append(stcb, stcb->asoc.primary_destination, m, &ca->sndrcv, 0);
4680 	if (turned_on_nonblock) {
4681 		/* we turned on non-blocking so turn it off */
4682 		stcb->sctp_socket->so_state &= ~SS_NBIO;
4683 	}
4684 	if (ret) {
4685 		ca->cnt_failed++;
4686 	} else {
4687 		ca->cnt_sent++;
4688 	}
4689 }
4690 
4691 static void
4692 sctp_sendall_completes(void *ptr, u_int32_t val)
4693 {
4694 	struct sctp_copy_all *ca;
4695 	ca = (struct sctp_copy_all *)ptr;
4696 	/* Do a notify here?
4697 	 * Kacheong suggests that the notify
4698 	 * be done at the send time.. so you would
4699 	 * push up a notification if any send failed.
4700 	 * Don't know if this is feasible since the
4701 	 * only failures we have is "memory" related and
4702 	 * if you cannot get an mbuf to send the data
4703 	 * you surely can't get an mbuf to send up
4704 	 * to notify the user you can't send the data :->
4705 	 */
4706 
4707 	/* now free everything */
4708 	m_freem(ca->m);
4709 	free(ca, M_PCB);
4710 }
4711 
4712 
4713 #define	MC_ALIGN(m, len) do {						\
4714 	(m)->m_data += (MCLBYTES - (len)) & ~(sizeof(long) - 1);		\
4715 } while (0)
4716 
4717 
4718 
4719 static struct mbuf *
4720 sctp_copy_out_all(struct uio *uio, int len)
4721 {
4722 	struct mbuf *ret, *at;
4723 	int left, willcpy, cancpy, error;
4724 
4725 	MGETHDR(ret, M_WAIT, MT_HEADER);
4726 	if (ret == NULL) {
4727 		/* TSNH */
4728 		return (NULL);
4729 	}
4730 	left = len;
4731 	ret->m_len = 0;
4732 	ret->m_pkthdr.len = len;
4733 	MCLGET(ret, M_WAIT);
4734 	if (ret == NULL) {
4735 		return (NULL);
4736 	}
4737 	if ((ret->m_flags & M_EXT) == 0) {
4738 		m_freem (ret);
4739 		return (NULL);
4740 	}
4741 	cancpy = M_TRAILINGSPACE(ret);
4742 	willcpy = uimin(cancpy, left);
4743 	at = ret;
4744 	while (left > 0) {
4745 		/* Align data to the end */
4746 		MC_ALIGN(at, willcpy);
4747 		error = uiomove(mtod(at, void *), willcpy, uio);
4748 		if (error) {
4749 		err_out_now:
4750 			m_freem(ret);
4751 			return (NULL);
4752 		}
4753 		at->m_len = willcpy;
4754 		at->m_nextpkt = at->m_next = 0;
4755 		left -= willcpy;
4756 		if (left > 0) {
4757 			MGET(at->m_next, M_WAIT, MT_DATA);
4758 			if (at->m_next == NULL) {
4759 				goto err_out_now;
4760 			}
4761 			at = at->m_next;
4762 			at->m_len = 0;
4763 			MCLGET(at, M_WAIT);
4764 			if (at == NULL) {
4765 				goto err_out_now;
4766 			}
4767 			if ((at->m_flags & M_EXT) == 0) {
4768 				goto err_out_now;
4769 			}
4770 			cancpy = M_TRAILINGSPACE(at);
4771 			willcpy = uimin(cancpy, left);
4772 		}
4773 	}
4774 	return (ret);
4775 }
4776 
4777 static int
4778 sctp_sendall (struct sctp_inpcb *inp, struct uio *uio, struct mbuf *m, struct sctp_sndrcvinfo *srcv)
4779 {
4780 	int ret;
4781 	struct sctp_copy_all *ca;
4782 	ca = malloc(sizeof(struct sctp_copy_all), M_PCB, M_WAIT);
4783 	if (ca == NULL) {
4784 		m_freem(m);
4785 		return (ENOMEM);
4786 	}
4787 	memset (ca, 0, sizeof(struct sctp_copy_all));
4788 
4789 	ca->inp = inp;
4790 	ca->sndrcv = *srcv;
4791 	/* take off the sendall flag, it would
4792 	 * be bad if we failed to do this  :-0
4793 	 */
4794  	ca->sndrcv.sinfo_flags &= ~SCTP_SENDALL;
4795 
4796 	/* get length and mbuf chain */
4797 	if (uio) {
4798 		ca->sndlen = uio->uio_resid;
4799 		ca->m = sctp_copy_out_all(uio, ca->sndlen);
4800 		if (ca->m == NULL) {
4801 			free(ca, M_PCB);
4802 			return (ENOMEM);
4803 		}
4804 	} else {
4805 		if ((m->m_flags & M_PKTHDR) == 0) {
4806 			ca->sndlen = 0;
4807 			while(m) {
4808 				ca->sndlen += m->m_len;
4809 				m = m->m_next;
4810 			}
4811 		} else {
4812 			ca->sndlen = m->m_pkthdr.len;
4813 		}
4814 		ca->m = m;
4815 	}
4816 
4817 	ret = sctp_initiate_iterator(sctp_sendall_iterator, SCTP_PCB_ANY_FLAGS, SCTP_ASOC_ANY_STATE,
4818 				     (void *)ca, 0, sctp_sendall_completes, inp);
4819 	if (ret) {
4820 #ifdef SCTP_DEBUG
4821 		printf("Failed to initiate iterator to takeover associations\n");
4822 #endif
4823 		free(ca, M_PCB);
4824 		return (EFAULT);
4825 
4826 	}
4827 	return (0);
4828 }
4829 
4830 
4831 void
4832 sctp_toss_old_cookies(struct sctp_association *asoc)
4833 {
4834 	struct sctp_tmit_chunk *chk, *nchk;
4835 	chk = TAILQ_FIRST(&asoc->control_send_queue);
4836 	while (chk) {
4837 		nchk = TAILQ_NEXT(chk, sctp_next);
4838 		if (chk->rec.chunk_id == SCTP_COOKIE_ECHO) {
4839 			TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
4840 			if (chk->data) {
4841 				sctp_m_freem(chk->data);
4842 				chk->data = NULL;
4843 			}
4844 			asoc->ctrl_queue_cnt--;
4845 			if (chk->whoTo)
4846 				sctp_free_remote_addr(chk->whoTo);
4847 			SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
4848 			sctppcbinfo.ipi_count_chunk--;
4849 			if ((int)sctppcbinfo.ipi_count_chunk < 0) {
4850 				panic("Chunk count is negative");
4851 			}
4852 			sctppcbinfo.ipi_gencnt_chunk++;
4853 		}
4854 		chk = nchk;
4855 	}
4856 }
4857 
4858 void
4859 sctp_toss_old_asconf(struct sctp_tcb *stcb)
4860 {
4861 	struct sctp_association *asoc;
4862 	struct sctp_tmit_chunk *chk, *chk_tmp;
4863 
4864 	asoc = &stcb->asoc;
4865 	for (chk = TAILQ_FIRST(&asoc->control_send_queue); chk != NULL;
4866 	     chk = chk_tmp) {
4867 		/* get next chk */
4868 		chk_tmp = TAILQ_NEXT(chk, sctp_next);
4869 		/* find SCTP_ASCONF chunk in queue (only one ever in queue) */
4870 		if (chk->rec.chunk_id == SCTP_ASCONF) {
4871 			TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
4872 			if (chk->data) {
4873 				sctp_m_freem(chk->data);
4874 				chk->data = NULL;
4875 			}
4876 			asoc->ctrl_queue_cnt--;
4877 			if (chk->whoTo)
4878 				sctp_free_remote_addr(chk->whoTo);
4879 			SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
4880 			sctppcbinfo.ipi_count_chunk--;
4881 			if ((int)sctppcbinfo.ipi_count_chunk < 0) {
4882 				panic("Chunk count is negative");
4883 			}
4884 			sctppcbinfo.ipi_gencnt_chunk++;
4885 		}
4886 	}
4887 }
4888 
4889 
4890 static void
4891 sctp_clean_up_datalist(struct sctp_tcb *stcb,
4892 		       struct sctp_association *asoc,
4893 		       struct sctp_tmit_chunk **data_list,
4894 		       int bundle_at,
4895 		       struct sctp_nets *net)
4896 {
4897 	int i;
4898 	for (i = 0; i < bundle_at; i++) {
4899 		/* off of the send queue */
4900 		if (i) {
4901 			/* Any chunk NOT 0 you zap the time
4902 			 * chunk 0 gets zapped or set based on
4903 			 * if a RTO measurement is needed.
4904 			 */
4905 			data_list[i]->do_rtt = 0;
4906 		}
4907 		/* record time */
4908 		data_list[i]->sent_rcv_time = net->last_sent_time;
4909 		TAILQ_REMOVE(&asoc->send_queue,
4910 			     data_list[i],
4911 			     sctp_next);
4912 		/* on to the sent queue */
4913 		TAILQ_INSERT_TAIL(&asoc->sent_queue,
4914 				  data_list[i],
4915 				  sctp_next);
4916 		/* This does not lower until the cum-ack passes it */
4917 		asoc->sent_queue_cnt++;
4918 		asoc->send_queue_cnt--;
4919 		if ((asoc->peers_rwnd <= 0) &&
4920 		    (asoc->total_flight == 0) &&
4921 		    (bundle_at == 1)) {
4922 			/* Mark the chunk as being a window probe */
4923 #ifdef SCTP_DEBUG
4924 			if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
4925 				printf("WINDOW PROBE SET\n");
4926 			}
4927 #endif
4928 			sctp_pegs[SCTP_WINDOW_PROBES]++;
4929 			data_list[i]->rec.data.state_flags |= SCTP_WINDOW_PROBE;
4930 		} else {
4931 			data_list[i]->rec.data.state_flags &= ~SCTP_WINDOW_PROBE;
4932 		}
4933 #ifdef SCTP_AUDITING_ENABLED
4934 		sctp_audit_log(0xC2, 3);
4935 #endif
4936 		data_list[i]->sent = SCTP_DATAGRAM_SENT;
4937 		data_list[i]->snd_count = 1;
4938 		net->flight_size += data_list[i]->book_size;
4939 		asoc->total_flight += data_list[i]->book_size;
4940 		asoc->total_flight_count++;
4941 #ifdef SCTP_LOG_RWND
4942 		sctp_log_rwnd(SCTP_DECREASE_PEER_RWND,
4943 			      asoc->peers_rwnd , data_list[i]->send_size, sctp_peer_chunk_oh);
4944 #endif
4945 		asoc->peers_rwnd = sctp_sbspace_sub(asoc->peers_rwnd,
4946 						    (u_int32_t)(data_list[i]->send_size + sctp_peer_chunk_oh));
4947 		if (asoc->peers_rwnd < stcb->sctp_ep->sctp_ep.sctp_sws_sender) {
4948 			/* SWS sender side engages */
4949 			asoc->peers_rwnd = 0;
4950 		}
4951 	}
4952 }
4953 
4954 static void
4955 sctp_clean_up_ctl(struct sctp_association *asoc)
4956 {
4957 	struct sctp_tmit_chunk *chk, *nchk;
4958 	for (chk = TAILQ_FIRST(&asoc->control_send_queue);
4959 	    chk; chk = nchk) {
4960 		nchk = TAILQ_NEXT(chk, sctp_next);
4961 		if ((chk->rec.chunk_id == SCTP_SELECTIVE_ACK) ||
4962 		    (chk->rec.chunk_id == SCTP_HEARTBEAT_REQUEST) ||
4963 		    (chk->rec.chunk_id == SCTP_HEARTBEAT_ACK) ||
4964 		    (chk->rec.chunk_id == SCTP_SHUTDOWN) ||
4965 		    (chk->rec.chunk_id == SCTP_SHUTDOWN_ACK) ||
4966 		    (chk->rec.chunk_id == SCTP_OPERATION_ERROR) ||
4967 		    (chk->rec.chunk_id == SCTP_PACKET_DROPPED) ||
4968 		    (chk->rec.chunk_id == SCTP_COOKIE_ACK) ||
4969 		    (chk->rec.chunk_id == SCTP_ECN_CWR) ||
4970 		    (chk->rec.chunk_id == SCTP_ASCONF_ACK)) {
4971 			/* Stray chunks must be cleaned up */
4972 		clean_up_anyway:
4973 			TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
4974 			if (chk->data) {
4975 				sctp_m_freem(chk->data);
4976 				chk->data = NULL;
4977 			}
4978 			asoc->ctrl_queue_cnt--;
4979 			sctp_free_remote_addr(chk->whoTo);
4980 			SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
4981 			sctppcbinfo.ipi_count_chunk--;
4982 			if ((int)sctppcbinfo.ipi_count_chunk < 0) {
4983 				panic("Chunk count is negative");
4984 			}
4985 			sctppcbinfo.ipi_gencnt_chunk++;
4986 		} else if (chk->rec.chunk_id == SCTP_STREAM_RESET) {
4987 			struct sctp_stream_reset_req *strreq;
4988 			/* special handling, we must look into the param */
4989 			strreq = mtod(chk->data, struct sctp_stream_reset_req *);
4990 			if (strreq->sr_req.ph.param_type == ntohs(SCTP_STR_RESET_RESPONSE)) {
4991 				goto clean_up_anyway;
4992 			}
4993 		}
4994 	}
4995 }
4996 
4997 static int
4998 sctp_move_to_outqueue(struct sctp_tcb *stcb,
4999 		      struct sctp_stream_out *strq)
5000 {
5001 	/* Move from the stream to the send_queue keeping track of the total */
5002 	struct sctp_association *asoc;
5003 	int tot_moved = 0;
5004 	int failed = 0;
5005 	int padval;
5006 	struct sctp_tmit_chunk *chk, *nchk;
5007 	struct sctp_data_chunk *dchkh;
5008 	struct sctpchunk_listhead tmp;
5009 	struct mbuf *orig;
5010 
5011 	asoc = &stcb->asoc;
5012 	TAILQ_INIT(&tmp);
5013 	chk = TAILQ_FIRST(&strq->outqueue);
5014 	while (chk) {
5015 		nchk = TAILQ_NEXT(chk, sctp_next);
5016 		/* now put in the chunk header */
5017 		orig = chk->data;
5018 		M_PREPEND(chk->data, sizeof(struct sctp_data_chunk), M_DONTWAIT);
5019 		if (chk->data == NULL) {
5020 			/* HELP */
5021 			failed++;
5022 			break;
5023 		}
5024 		if (orig != chk->data) {
5025 			/* A new mbuf was added, account for it */
5026 			if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
5027 			    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
5028 				stcb->sctp_socket->so_snd.sb_mbcnt += MSIZE;
5029 			}
5030 #ifdef SCTP_MBCNT_LOGGING
5031 			sctp_log_mbcnt(SCTP_LOG_MBCNT_INCREASE,
5032 				       asoc->total_output_queue_size,
5033 				       0,
5034 				       asoc->total_output_mbuf_queue_size,
5035 				       MSIZE);
5036 #endif
5037 			stcb->asoc.total_output_mbuf_queue_size += MSIZE;
5038 			chk->mbcnt += MSIZE;
5039 		}
5040 		chk->send_size += sizeof(struct sctp_data_chunk);
5041 		/* This should NOT have to do anything, but
5042 		 * I would rather be cautious
5043 		 */
5044 		if (!failed && ((size_t)chk->data->m_len < sizeof(struct sctp_data_chunk))) {
5045 			m_pullup(chk->data, sizeof(struct sctp_data_chunk));
5046 			if (chk->data == NULL) {
5047 				failed++;
5048 				break;
5049 			}
5050 		}
5051 		dchkh = mtod(chk->data, struct sctp_data_chunk *);
5052 		dchkh->ch.chunk_length = htons(chk->send_size);
5053 		/* Chunks must be padded to even word boundary */
5054 		padval = chk->send_size % 4;
5055 		if (padval) {
5056 			/* For fragmented messages this should not
5057 			 * run except possibly on the last chunk
5058 			 */
5059 			if (sctp_pad_lastmbuf(chk->data, (4 - padval))) {
5060 				/* we are in big big trouble no mbufs :< */
5061 				failed++;
5062 				break;
5063 			}
5064 			chk->send_size += (4 - padval);
5065 		}
5066 		/* pull from stream queue */
5067 		TAILQ_REMOVE(&strq->outqueue, chk, sctp_next);
5068 		asoc->stream_queue_cnt--;
5069 		TAILQ_INSERT_TAIL(&tmp, chk, sctp_next);
5070 		/* add it in to the size of moved chunks */
5071 		if (chk->rec.data.rcv_flags & SCTP_DATA_LAST_FRAG) {
5072 			/* we pull only one message */
5073 			break;
5074 		}
5075 		chk = nchk;
5076 	}
5077 	if (failed) {
5078 		/* Gak, we just lost the user message */
5079 		chk = TAILQ_FIRST(&tmp);
5080 		while (chk) {
5081 			nchk = TAILQ_NEXT(chk, sctp_next);
5082 			TAILQ_REMOVE(&tmp, chk, sctp_next);
5083 
5084 			sctp_ulp_notify(SCTP_NOTIFY_DG_FAIL, stcb,
5085 					(SCTP_NOTIFY_DATAGRAM_UNSENT|SCTP_INTERNAL_ERROR),
5086 					chk);
5087 
5088 			if (chk->data) {
5089 				sctp_m_freem(chk->data);
5090 				chk->data = NULL;
5091 			}
5092 			if (chk->whoTo) {
5093 				sctp_free_remote_addr(chk->whoTo);
5094 				chk->whoTo = NULL;
5095 			}
5096 			SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
5097 			sctppcbinfo.ipi_count_chunk--;
5098 			if ((int)sctppcbinfo.ipi_count_chunk < 0) {
5099 				panic("Chunk count is negative");
5100 			}
5101 			sctppcbinfo.ipi_gencnt_chunk++;
5102 			chk = nchk;
5103 		}
5104 		return (0);
5105 	}
5106 	/* now pull them off of temp wheel */
5107 	chk = TAILQ_FIRST(&tmp);
5108 	while (chk) {
5109 		nchk = TAILQ_NEXT(chk, sctp_next);
5110 		/* insert on send_queue */
5111 		TAILQ_REMOVE(&tmp, chk, sctp_next);
5112 		TAILQ_INSERT_TAIL(&asoc->send_queue, chk, sctp_next);
5113 		asoc->send_queue_cnt++;
5114 		/* assign TSN */
5115 		chk->rec.data.TSN_seq = asoc->sending_seq++;
5116 
5117 		dchkh = mtod(chk->data, struct sctp_data_chunk *);
5118 		/* Put the rest of the things in place now. Size
5119 		 * was done earlier in previous loop prior to
5120 		 * padding.
5121 		 */
5122 		dchkh->ch.chunk_type = SCTP_DATA;
5123 		dchkh->ch.chunk_flags = chk->rec.data.rcv_flags;
5124 		dchkh->dp.tsn = htonl(chk->rec.data.TSN_seq);
5125 		dchkh->dp.stream_id = htons(strq->stream_no);
5126 		dchkh->dp.stream_sequence = htons(chk->rec.data.stream_seq);
5127 		dchkh->dp.protocol_id = chk->rec.data.payloadtype;
5128 		/* total count moved */
5129 		tot_moved += chk->send_size;
5130 		chk = nchk;
5131 	}
5132 	return (tot_moved);
5133 }
5134 
5135 static void
5136 sctp_fill_outqueue(struct sctp_tcb *stcb,
5137 		   struct sctp_nets *net)
5138 {
5139 	struct sctp_association *asoc;
5140 	struct sctp_tmit_chunk *chk;
5141 	struct sctp_stream_out *strq, *strqn;
5142 	int mtu_fromwheel, goal_mtu;
5143 	unsigned int moved, seenend, cnt_mvd=0;
5144 
5145 	asoc = &stcb->asoc;
5146 	/* Attempt to move at least 1 MTU's worth
5147 	 * onto the wheel for each destination address
5148 	 */
5149 	goal_mtu = net->cwnd - net->flight_size;
5150 	if ((unsigned int)goal_mtu < net->mtu) {
5151 		goal_mtu = net->mtu;
5152 	}
5153 	if (sctp_pegs[SCTP_MOVED_MTU] < (unsigned int)goal_mtu) {
5154 		sctp_pegs[SCTP_MOVED_MTU] = goal_mtu;
5155 	}
5156 	seenend = moved = mtu_fromwheel = 0;
5157 	if (asoc->last_out_stream == NULL) {
5158 		strq = asoc->last_out_stream = TAILQ_FIRST(&asoc->out_wheel);
5159 		if (asoc->last_out_stream == NULL) {
5160 			/* huh nothing on the wheel, TSNH */
5161 			return;
5162 		}
5163 		goto done_it;
5164 	}
5165 	strq = TAILQ_NEXT(asoc->last_out_stream, next_spoke);
5166  done_it:
5167 	if (strq == NULL) {
5168 		asoc->last_out_stream = TAILQ_FIRST(&asoc->out_wheel);
5169 	}
5170 	while (mtu_fromwheel < goal_mtu) {
5171 		if (strq == NULL) {
5172 			if (seenend == 0) {
5173 				seenend = 1;
5174 				strq = TAILQ_FIRST(&asoc->out_wheel);
5175 			} else if ((moved == 0) && (seenend)) {
5176 				/* none left on the wheel */
5177 				sctp_pegs[SCTP_MOVED_NLEF]++;
5178 				return;
5179 			} else if (moved) {
5180 				/*
5181 				 * clear the flags and rotate back through
5182 				 * again
5183 				 */
5184 				moved = 0;
5185 				seenend = 0;
5186 				strq = TAILQ_FIRST(&asoc->out_wheel);
5187 			}
5188 			if (strq == NULL)
5189 				break;
5190 			continue;
5191 		}
5192 		strqn = TAILQ_NEXT(strq, next_spoke);
5193 		if ((chk = TAILQ_FIRST(&strq->outqueue)) == NULL) {
5194 			/* none left on this queue, prune a spoke?  */
5195 			sctp_remove_from_wheel(asoc, strq);
5196 			if (strq == asoc->last_out_stream) {
5197 			    /* the last one we used went off the wheel */
5198 			    asoc->last_out_stream = NULL;
5199 			}
5200 			strq = strqn;
5201 			continue;
5202 		}
5203 		if (chk->whoTo != net) {
5204 			/* Skip this stream, first one on stream
5205 			 * does not head to our current destination.
5206 			 */
5207 			strq = strqn;
5208 			continue;
5209 		}
5210 		mtu_fromwheel += sctp_move_to_outqueue(stcb, strq);
5211 		cnt_mvd++;
5212 		moved++;
5213 		asoc->last_out_stream = strq;
5214 		strq = strqn;
5215 	}
5216 	sctp_pegs[SCTP_MOVED_MAX]++;
5217 #ifdef SCTP_DEBUG
5218 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5219 		printf("Ok we moved %d chunks to send queue\n",
5220 		       moved);
5221 	}
5222 #endif
5223 	if (sctp_pegs[SCTP_MOVED_QMAX] < cnt_mvd) {
5224 		sctp_pegs[SCTP_MOVED_QMAX] = cnt_mvd;
5225 	}
5226 }
5227 
5228 void
5229 sctp_fix_ecn_echo(struct sctp_association *asoc)
5230 {
5231 	struct sctp_tmit_chunk *chk;
5232 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
5233 		if (chk->rec.chunk_id == SCTP_ECN_ECHO) {
5234 			chk->sent = SCTP_DATAGRAM_UNSENT;
5235 		}
5236 	}
5237 }
5238 
5239 static void
5240 sctp_move_to_an_alt(struct sctp_tcb *stcb,
5241 		    struct sctp_association *asoc,
5242 		    struct sctp_nets *net)
5243 {
5244 	struct sctp_tmit_chunk *chk;
5245 	struct sctp_nets *a_net;
5246 	a_net = sctp_find_alternate_net(stcb, net);
5247 	if ((a_net != net) &&
5248 	    ((a_net->dest_state & SCTP_ADDR_REACHABLE) == SCTP_ADDR_REACHABLE)) {
5249 		/*
5250 		 * We only proceed if a valid alternate is found that is
5251 		 * not this one and is reachable. Here we must move all
5252 		 * chunks queued in the send queue off of the destination
5253 		 * address to our alternate.
5254 		 */
5255 		TAILQ_FOREACH(chk, &asoc->send_queue, sctp_next) {
5256 			if (chk->whoTo == net) {
5257 				/* Move the chunk to our alternate */
5258 				sctp_free_remote_addr(chk->whoTo);
5259 				chk->whoTo = a_net;
5260 				a_net->ref_count++;
5261 			}
5262 		}
5263 	}
5264 }
5265 
5266 static int sctp_from_user_send=0;
5267 
5268 static int
5269 sctp_med_chunk_output(struct sctp_inpcb *inp,
5270 		      struct sctp_tcb *stcb,
5271 		      struct sctp_association *asoc,
5272 		      int *num_out,
5273 		      int *reason_code,
5274 		      int control_only, int *cwnd_full, int from_where,
5275 		      struct timeval *now, int *now_filled)
5276 {
5277 	/*
5278 	 * Ok this is the generic chunk service queue.
5279 	 * we must do the following:
5280 	 *  - Service the stream queue that is next, moving any message
5281 	 *    (note I must get a complete message i.e. FIRST/MIDDLE and
5282 	 *    LAST to the out queue in one pass) and assigning TSN's
5283 	 *  - Check to see if the cwnd/rwnd allows any output, if so we
5284 	 *    go ahead and fomulate and send the low level chunks. Making
5285 	 *    sure to combine any control in the control chunk queue also.
5286 	 */
5287 	struct sctp_nets *net;
5288 	struct mbuf *outchain;
5289 	struct sctp_tmit_chunk *chk, *nchk;
5290 	struct sctphdr *shdr;
5291 	/* temp arrays for unlinking */
5292 	struct sctp_tmit_chunk *data_list[SCTP_MAX_DATA_BUNDLING];
5293 	int no_fragmentflg, error;
5294 	int one_chunk, hbflag;
5295 	int asconf, cookie, no_out_cnt;
5296 	int bundle_at, ctl_cnt, no_data_chunks, cwnd_full_ind;
5297         unsigned int mtu, r_mtu, omtu;
5298 	*num_out = 0;
5299 	cwnd_full_ind = 0;
5300 	ctl_cnt = no_out_cnt = asconf = cookie = 0;
5301 	/*
5302 	 * First lets prime the pump. For each destination, if there
5303 	 * is room in the flight size, attempt to pull an MTU's worth
5304 	 * out of the stream queues into the general send_queue
5305 	 */
5306 #ifdef SCTP_AUDITING_ENABLED
5307 	sctp_audit_log(0xC2, 2);
5308 #endif
5309 #ifdef SCTP_DEBUG
5310 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5311 		printf("***********************\n");
5312 	}
5313 #endif
5314 	hbflag = 0;
5315 	if (control_only)
5316 		no_data_chunks = 1;
5317 	else
5318 		no_data_chunks = 0;
5319 
5320 	/* Nothing to possible to send? */
5321 	if (TAILQ_EMPTY(&asoc->control_send_queue) &&
5322 	    TAILQ_EMPTY(&asoc->send_queue) &&
5323 	    TAILQ_EMPTY(&asoc->out_wheel)) {
5324 #ifdef SCTP_DEBUG
5325 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5326 			printf("All wheels empty\n");
5327 		}
5328 #endif
5329 		return (0);
5330 	}
5331 	if (asoc->peers_rwnd <= 0) {
5332 		/* No room in peers rwnd */
5333 		*cwnd_full = 1;
5334 		*reason_code = 1;
5335 		if (asoc->total_flight > 0) {
5336 			/* we are allowed one chunk in flight */
5337 			no_data_chunks = 1;
5338 			sctp_pegs[SCTP_RWND_BLOCKED]++;
5339 		}
5340 	}
5341 #ifdef SCTP_DEBUG
5342 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5343 		printf("Ok we have done the fillup no_data_chunk=%d tf=%d prw:%d\n",
5344 		       (int)no_data_chunks,
5345 		       (int)asoc->total_flight, (int)asoc->peers_rwnd);
5346 	}
5347 #endif
5348 	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
5349 #ifdef SCTP_DEBUG
5350 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5351 			printf("net:%p fs:%d  cwnd:%d\n",
5352 			       net, net->flight_size, net->cwnd);
5353 		}
5354 #endif
5355 		if (net->flight_size >= net->cwnd) {
5356 			/* skip this network, no room */
5357 			cwnd_full_ind++;
5358 #ifdef SCTP_DEBUG
5359 			if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5360 				printf("Ok skip fillup->fs:%d > cwnd:%d\n",
5361 				       net->flight_size,
5362 				       net->cwnd);
5363 			}
5364 #endif
5365 			sctp_pegs[SCTP_CWND_NOFILL]++;
5366 			continue;
5367 		}
5368 		/*
5369 		 * spin through the stream queues moving one message and
5370 		 * assign TSN's as appropriate.
5371 		 */
5372 		sctp_fill_outqueue(stcb, net);
5373 	}
5374 	*cwnd_full = cwnd_full_ind;
5375 	/* now service each destination and send out what we can for it */
5376 #ifdef SCTP_DEBUG
5377 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5378 		int chk_cnt = 0;
5379 		TAILQ_FOREACH(chk, &asoc->send_queue, sctp_next) {
5380 			chk_cnt++;
5381 		}
5382 		printf("We have %d chunks on the send_queue\n", chk_cnt);
5383 		chk_cnt = 0;
5384 		TAILQ_FOREACH(chk, &asoc->sent_queue, sctp_next) {
5385 			chk_cnt++;
5386 		}
5387 		printf("We have %d chunks on the sent_queue\n", chk_cnt);
5388 		TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
5389 			chk_cnt++;
5390 		}
5391 		printf("We have %d chunks on the control_queue\n", chk_cnt);
5392 	}
5393 #endif
5394 	/* If we have data to send, and DSACK is running, stop it
5395 	 * and build a SACK to dump on to bundle with output. This
5396 	 * actually MAY make it so the bundling does not occur if
5397 	 * the SACK is big but I think this is ok because basic SACK
5398 	 * space is pre-reserved in our fragmentation size choice.
5399 	 */
5400 	if ((TAILQ_FIRST(&asoc->send_queue) != NULL) &&
5401 	    (no_data_chunks == 0)) {
5402 		/* We will be sending something */
5403 		if (callout_pending(&stcb->asoc.dack_timer.timer)) {
5404 			/* Yep a callout is pending */
5405 			sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
5406 					stcb->sctp_ep,
5407 					stcb, NULL);
5408 			sctp_send_sack(stcb);
5409 		}
5410 	}
5411 	/* Nothing to send? */
5412 	if ((TAILQ_FIRST(&asoc->control_send_queue) == NULL) &&
5413 	    (TAILQ_FIRST(&asoc->send_queue) == NULL)) {
5414 		return (0);
5415 	}
5416 	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
5417 		struct rtentry *rt;
5418 		/* how much can we send? */
5419 		if (net->ref_count < 2) {
5420 			/* Ref-count of 1 so we cannot have data or control
5421 			 * queued to this address. Skip it.
5422 			 */
5423  			continue;
5424 		}
5425 		ctl_cnt = bundle_at = 0;
5426 		outchain = NULL;
5427 		no_fragmentflg = 1;
5428 		one_chunk = 0;
5429 
5430 		rt = rtcache_validate(&net->ro);
5431 		if (rt != NULL) {
5432 			/* if we have a route and an ifp
5433 			 * check to see if we have room to
5434 			 * send to this guy
5435 			 */
5436 			struct ifnet *ifp;
5437 			ifp = net->ro._ro_rt->rt_ifp;
5438 			if ((ifp->if_snd.ifq_len + 2) >= ifp->if_snd.ifq_maxlen) {
5439 				sctp_pegs[SCTP_IFP_QUEUE_FULL]++;
5440 #ifdef SCTP_LOG_MAXBURST
5441 				sctp_log_maxburst(net, ifp->if_snd.ifq_len, ifp->if_snd.ifq_maxlen, SCTP_MAX_IFP_APPLIED);
5442   #endif
5443 				rtcache_unref(rt, &net->ro);
5444 				continue;
5445 			}
5446 			rtcache_unref(rt, &net->ro);
5447 		}
5448 		if (((struct sockaddr *)&net->ro.ro_sa)->sa_family == AF_INET) {
5449 			mtu = net->mtu - (sizeof(struct ip) + sizeof(struct sctphdr));
5450 		} else {
5451 			mtu = net->mtu - (sizeof(struct ip6_hdr) + sizeof(struct sctphdr));
5452 		}
5453 		if (mtu > asoc->peers_rwnd) {
5454 			if (asoc->total_flight > 0) {
5455 				/* We have a packet in flight somewhere */
5456 				r_mtu = asoc->peers_rwnd;
5457 			} else {
5458 				/* We are always allowed to send one MTU out */
5459 				one_chunk = 1;
5460 				r_mtu = mtu;
5461 			}
5462 		} else {
5463 			r_mtu = mtu;
5464 		}
5465 #ifdef SCTP_DEBUG
5466 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5467 			printf("Ok r_mtu is %d mtu is %d for this net:%p one_chunk:%d\n",
5468 			       r_mtu, mtu, net, one_chunk);
5469 		}
5470 #endif
5471 		/************************/
5472 		/* Control transmission */
5473 		/************************/
5474 		/* Now first lets go through the control queue */
5475 		for (chk = TAILQ_FIRST(&asoc->control_send_queue);
5476 		     chk; chk = nchk) {
5477 			nchk = TAILQ_NEXT(chk, sctp_next);
5478 			if (chk->whoTo != net) {
5479 				/*
5480 				 * No, not sent to the network we are
5481 				 * looking at
5482 				 */
5483 				continue;
5484 			}
5485 			if (chk->data == NULL) {
5486 				continue;
5487 			}
5488 			if ((chk->data->m_flags & M_PKTHDR) == 0) {
5489 				/*
5490 				 * NOTE: the chk queue MUST have the PKTHDR
5491 				 * flag set on it with a total in the
5492 				 * m_pkthdr.len field!! else the chunk will
5493 				 * ALWAYS be skipped
5494 				 */
5495 				continue;
5496 			}
5497 			if (chk->sent != SCTP_DATAGRAM_UNSENT) {
5498 				/*
5499 				 * It must be unsent. Cookies and ASCONF's
5500 				 * hang around but there timers will force
5501 				 * when marked for resend.
5502 				 */
5503 				continue;
5504 			}
5505 			/* Here we do NOT factor the r_mtu */
5506 			if ((chk->data->m_pkthdr.len < (int)mtu) ||
5507 			    (chk->flags & CHUNK_FLAGS_FRAGMENT_OK)) {
5508 				/*
5509 				 * We probably should glom the mbuf chain from
5510 				 * the chk->data for control but the problem
5511 				 * is it becomes yet one more level of
5512 				 * tracking to do if for some reason output
5513 				 * fails. Then I have got to reconstruct the
5514 				 * merged control chain.. el yucko.. for now
5515 				 * we take the easy way and do the copy
5516 				 */
5517 				outchain = sctp_copy_mbufchain(chk->data,
5518 							       outchain);
5519 				if (outchain == NULL) {
5520 					return (ENOMEM);
5521 				}
5522 				/* update our MTU size */
5523 				if (mtu > chk->data->m_pkthdr.len)
5524 					mtu -= chk->data->m_pkthdr.len;
5525 				else
5526 					mtu = 0;
5527 				/* Do clear IP_DF ? */
5528 				if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
5529 					no_fragmentflg = 0;
5530 				}
5531 				/* Mark things to be removed, if needed */
5532 				if ((chk->rec.chunk_id == SCTP_SELECTIVE_ACK) ||
5533 				    (chk->rec.chunk_id == SCTP_HEARTBEAT_REQUEST) ||
5534 				    (chk->rec.chunk_id == SCTP_HEARTBEAT_ACK) ||
5535 				    (chk->rec.chunk_id == SCTP_SHUTDOWN) ||
5536 				    (chk->rec.chunk_id == SCTP_SHUTDOWN_ACK) ||
5537 				    (chk->rec.chunk_id == SCTP_OPERATION_ERROR) ||
5538 				    (chk->rec.chunk_id == SCTP_COOKIE_ACK) ||
5539 				    (chk->rec.chunk_id == SCTP_ECN_CWR) ||
5540 				    (chk->rec.chunk_id == SCTP_PACKET_DROPPED) ||
5541 				    (chk->rec.chunk_id == SCTP_ASCONF_ACK)) {
5542 
5543 					if (chk->rec.chunk_id == SCTP_HEARTBEAT_REQUEST)
5544 						hbflag = 1;
5545 					/* remove these chunks at the end */
5546 					if (chk->rec.chunk_id == SCTP_SELECTIVE_ACK) {
5547 						/* turn off the timer */
5548 						if (callout_pending(&stcb->asoc.dack_timer.timer)) {
5549 							sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
5550 									inp, stcb, net);
5551 						}
5552 					}
5553 					ctl_cnt++;
5554 				} else {
5555 					/*
5556 					 * Other chunks, since they have
5557 					 * timers running (i.e. COOKIE or
5558 					 * ASCONF) we just "trust" that it
5559 					 * gets sent or retransmitted.
5560 					 */
5561 					ctl_cnt++;
5562 					if (chk->rec.chunk_id == SCTP_COOKIE_ECHO) {
5563 						cookie = 1;
5564 						no_out_cnt = 1;
5565 					} else if (chk->rec.chunk_id == SCTP_ASCONF) {
5566 						/*
5567 						 * set hb flag since we can use
5568 						 * these for RTO
5569 						 */
5570 						hbflag = 1;
5571 						asconf = 1;
5572 					}
5573 					chk->sent = SCTP_DATAGRAM_SENT;
5574 					chk->snd_count++;
5575 				}
5576 				if (mtu == 0) {
5577 					/*
5578 					 * Ok we are out of room but we can
5579 					 * output without effecting the flight
5580 					 * size since this little guy is a
5581 					 * control only packet.
5582 					 */
5583 					if (asconf) {
5584 						sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp, stcb, net);
5585 						asconf = 0;
5586 					}
5587 					if (cookie) {
5588 						sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, inp, stcb, net);
5589 						cookie = 0;
5590 					}
5591 					if (outchain->m_len == 0) {
5592 						/*
5593 						 * Special case for when you
5594 						 * get a 0 len mbuf at the
5595 						 * head due to the lack of a
5596 						 * MHDR at the beginning.
5597 						 */
5598 						outchain->m_len = sizeof(struct sctphdr);
5599 					} else {
5600 						M_PREPEND(outchain, sizeof(struct sctphdr), M_DONTWAIT);
5601 						if (outchain == NULL) {
5602 							/* no memory */
5603 							error = ENOBUFS;
5604 							goto error_out_again;
5605 						}
5606 					}
5607 					shdr = mtod(outchain, struct sctphdr *);
5608 					shdr->src_port = inp->sctp_lport;
5609 					shdr->dest_port = stcb->rport;
5610 					shdr->v_tag = htonl(stcb->asoc.peer_vtag);
5611 					shdr->checksum = 0;
5612 
5613 					if ((error = sctp_lowlevel_chunk_output(inp, stcb, net,
5614 										rtcache_getdst(&net->ro),
5615 										outchain,
5616 										no_fragmentflg, 0, NULL, asconf))) {
5617 						if (error == ENOBUFS) {
5618 							asoc->ifp_had_enobuf = 1;
5619 						}
5620 						sctp_pegs[SCTP_DATA_OUT_ERR]++;
5621 						if (from_where == 0) {
5622 							sctp_pegs[SCTP_ERROUT_FRM_USR]++;
5623 						}
5624 					error_out_again:
5625 #ifdef SCTP_DEBUG
5626 						if (sctp_debug_on & SCTP_DEBUG_OUTPUT2) {
5627 							printf("Gak got ctrl error %d\n", error);
5628 						}
5629 #endif
5630 						/* error, could not output */
5631 						if (hbflag) {
5632 #ifdef SCTP_DEBUG
5633 							if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5634 								printf("Update HB anyway\n");
5635 							}
5636 #endif
5637 							if (*now_filled == 0) {
5638 								SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
5639 								*now_filled = 1;
5640 								*now = net->last_sent_time;
5641 							} else {
5642 								net->last_sent_time = *now;
5643 							}
5644 							hbflag = 0;
5645 						}
5646 						if (error == EHOSTUNREACH ||
5647 						    error == EHOSTDOWN) {
5648 							/*
5649 							 * Destination went
5650 							 * unreachable during
5651 							 * this send
5652 							 */
5653 #ifdef SCTP_DEBUG
5654 							if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5655 								printf("Moving data to an alterante\n");
5656 							}
5657 #endif
5658 							sctp_move_to_an_alt(stcb, asoc, net);
5659 						}
5660 						sctp_clean_up_ctl (asoc);
5661 						return (error);
5662 					} else
5663 						asoc->ifp_had_enobuf = 0;
5664 					/* Only HB or ASCONF advances time */
5665 					if (hbflag) {
5666 						if (*now_filled == 0) {
5667 							SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
5668 							*now_filled = 1;
5669 							*now = net->last_sent_time;
5670 						} else {
5671 							net->last_sent_time = *now;
5672 						}
5673 						hbflag = 0;
5674 					}
5675 					/*
5676 					 * increase the number we sent, if a
5677 					 * cookie is sent we don't tell them
5678 					 * any was sent out.
5679 					 */
5680 					if (!no_out_cnt)
5681 						*num_out +=  ctl_cnt;
5682 					/* recalc a clean slate and setup */
5683 					if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
5684 						mtu = (net->mtu - SCTP_MIN_OVERHEAD);
5685 					} else {
5686 						mtu = (net->mtu - SCTP_MIN_V4_OVERHEAD);
5687 					}
5688 					no_fragmentflg = 1;
5689 				}
5690 			}
5691 		}
5692 		/*********************/
5693 		/* Data transmission */
5694 		/*********************/
5695 		/* now lets add any data within the MTU constraints */
5696 		if (((struct sockaddr *)&net->ro.ro_sa)->sa_family == AF_INET) {
5697 			omtu = net->mtu - (sizeof(struct ip) + sizeof(struct sctphdr));
5698 		} else {
5699 			omtu = net->mtu - (sizeof(struct ip6_hdr) + sizeof(struct sctphdr));
5700 		}
5701 
5702 #ifdef SCTP_DEBUG
5703 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5704 			printf("Now to data transmission\n");
5705 		}
5706 #endif
5707 
5708 		if (((asoc->state & SCTP_STATE_OPEN) == SCTP_STATE_OPEN) ||
5709 		    (cookie)) {
5710 			for (chk = TAILQ_FIRST(&asoc->send_queue); chk; chk = nchk) {
5711 				if (no_data_chunks) {
5712 					/* let only control go out */
5713 #ifdef SCTP_DEBUG
5714 					if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5715 						printf("Either nothing to send or we are full\n");
5716 					}
5717 #endif
5718 					break;
5719 				}
5720 				if (net->flight_size >= net->cwnd) {
5721 					/* skip this net, no room for data */
5722 #ifdef SCTP_DEBUG
5723 					if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5724 						printf("fs:%d > cwnd:%d\n",
5725 						       net->flight_size, net->cwnd);
5726 					}
5727 #endif
5728 					sctp_pegs[SCTP_CWND_BLOCKED]++;
5729 					*reason_code = 2;
5730 					break;
5731 				}
5732 				nchk = TAILQ_NEXT(chk, sctp_next);
5733 				if (chk->whoTo != net) {
5734 					/* No, not sent to this net */
5735 #ifdef SCTP_DEBUG
5736 					if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5737 						printf("chk->whoTo:%p not %p\n",
5738 						       chk->whoTo, net);
5739 
5740 					}
5741 #endif
5742 					continue;
5743 				}
5744 #ifdef SCTP_DEBUG
5745 				if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5746 					printf("Can we pick up a chunk?\n");
5747 				}
5748 #endif
5749 				if ((chk->send_size > omtu) && ((chk->flags & CHUNK_FLAGS_FRAGMENT_OK) == 0)) {
5750 					/* strange, we have a chunk that is to bit
5751 					 * for its destination and yet no fragment ok flag.
5752 					 * Something went wrong when the PMTU changed...we did
5753 					 * not mark this chunk for some reason?? I will
5754 					 * fix it here by letting IP fragment it for now and
5755 					 * printing a warning. This really should not happen ...
5756 					 */
5757 /*#ifdef SCTP_DEBUG*/
5758 					printf("Warning chunk of %d bytes > mtu:%d and yet PMTU disc missed\n",
5759 					       chk->send_size, mtu);
5760 /*#endif*/
5761 					chk->flags |= CHUNK_FLAGS_FRAGMENT_OK;
5762 				}
5763 
5764 				if (((chk->send_size <= mtu) && (chk->send_size <= r_mtu)) ||
5765 				    ((chk->flags & CHUNK_FLAGS_FRAGMENT_OK) && (chk->send_size <= asoc->peers_rwnd))) {
5766 					/* ok we will add this one */
5767 #ifdef SCTP_DEBUG
5768 					if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5769 						printf("Picking up the chunk\n");
5770 					}
5771 #endif
5772 					outchain = sctp_copy_mbufchain(chk->data, outchain);
5773 					if (outchain == NULL) {
5774 #ifdef SCTP_DEBUG
5775 						if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5776 							printf("Gakk no memory\n");
5777 						}
5778 #endif
5779 						if (!callout_pending(&net->rxt_timer.timer)) {
5780 							sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
5781 						}
5782 						return (ENOMEM);
5783 					}
5784 					/* update our MTU size */
5785 					/* Do clear IP_DF ? */
5786 					if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
5787 						no_fragmentflg = 0;
5788 					}
5789 					mtu -= chk->send_size;
5790 					r_mtu -= chk->send_size;
5791 					data_list[bundle_at++] = chk;
5792 					if (bundle_at >= SCTP_MAX_DATA_BUNDLING) {
5793 						mtu = 0;
5794 						break;
5795 					}
5796 					if (mtu <= 0) {
5797 						mtu = 0;
5798 						break;
5799 					}
5800 					if ((r_mtu <= 0) || one_chunk) {
5801 						r_mtu = 0;
5802 						break;
5803 					}
5804 				} else {
5805 					/*
5806 					 * Must be sent in order of the TSN's
5807 					 * (on a network)
5808 					 */
5809 #ifdef SCTP_DEBUG
5810 					if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5811 						printf("ok no more chk:%d > mtu:%d || < r_mtu:%d\n",
5812 						       chk->send_size, mtu, r_mtu);
5813 					}
5814 #endif
5815 
5816 					break;
5817 				}
5818 			}/* for () */
5819 		} /* if asoc.state OPEN */
5820 		/* Is there something to send for this destination? */
5821 #ifdef SCTP_DEBUG
5822 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5823 			printf("ok now is chain assembled? %p\n",
5824 			       outchain);
5825 		}
5826 #endif
5827 
5828 		if (outchain) {
5829 			/* We may need to start a control timer or two */
5830 			if (asconf) {
5831 				sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp, stcb, net);
5832 				asconf = 0;
5833 			}
5834 			if (cookie) {
5835 				sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, inp, stcb, net);
5836 				cookie = 0;
5837 			}
5838 			/* must start a send timer if data is being sent */
5839 			if (bundle_at && (!callout_pending(&net->rxt_timer.timer))) {
5840 				/* no timer running on this destination
5841 				 * restart it.
5842 				 */
5843 #ifdef SCTP_DEBUG
5844 				if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5845 					printf("ok lets start a send timer .. we will transmit %p\n",
5846 					       outchain);
5847 				}
5848 #endif
5849 				sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
5850 			}
5851 			/* Now send it, if there is anything to send :> */
5852 			if ((outchain->m_flags & M_PKTHDR) == 0) {
5853 				struct mbuf *t;
5854 
5855 				MGETHDR(t, M_DONTWAIT, MT_HEADER);
5856 				if (t == NULL) {
5857 					sctp_m_freem(outchain);
5858 					return (ENOMEM);
5859 				}
5860 				t->m_next = outchain;
5861 				t->m_pkthdr.len = 0;
5862 				m_reset_rcvif(t);
5863 				t->m_len = 0;
5864 
5865 				outchain = t;
5866 				while (t) {
5867 					outchain->m_pkthdr.len += t->m_len;
5868 					t = t->m_next;
5869 				}
5870 			}
5871 			if (outchain->m_len == 0) {
5872 				/* Special case for when you get a 0 len
5873 				 * mbuf at the head due to the lack
5874 				 * of a MHDR at the beginning.
5875 				 */
5876 				m_align(outchain, sizeof(struct sctphdr));
5877 				outchain->m_len = sizeof(struct sctphdr);
5878 			} else {
5879 				M_PREPEND(outchain, sizeof(struct sctphdr), M_DONTWAIT);
5880 				if (outchain == NULL) {
5881 					/* out of mbufs */
5882 					error = ENOBUFS;
5883 					goto errored_send;
5884 				}
5885 			}
5886 			shdr = mtod(outchain, struct sctphdr *);
5887 			shdr->src_port = inp->sctp_lport;
5888 			shdr->dest_port = stcb->rport;
5889 			shdr->v_tag = htonl(stcb->asoc.peer_vtag);
5890 			shdr->checksum = 0;
5891 			if ((error = sctp_lowlevel_chunk_output(inp, stcb, net,
5892 								rtcache_getdst(&net->ro),
5893 								outchain,
5894 								no_fragmentflg, bundle_at, data_list[0], asconf))) {
5895 				/* error, we could not output */
5896 				if (error == ENOBUFS) {
5897 					asoc->ifp_had_enobuf = 1;
5898 				}
5899 				sctp_pegs[SCTP_DATA_OUT_ERR]++;
5900 				if (from_where == 0) {
5901 					sctp_pegs[SCTP_ERROUT_FRM_USR]++;
5902 				}
5903 
5904 			errored_send:
5905 #ifdef SCTP_DEBUG
5906 				if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5907 					printf("Gak send error %d\n", error);
5908 				}
5909 #endif
5910 				if (hbflag) {
5911 #ifdef SCTP_DEBUG
5912 					if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5913 						printf("Update HB time anyway\n");
5914 					}
5915 #endif
5916 					if (*now_filled == 0) {
5917 						SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
5918 						*now_filled = 1;
5919 						*now = net->last_sent_time;
5920 					} else {
5921 						net->last_sent_time = *now;
5922 					}
5923 					hbflag = 0;
5924 				}
5925 				if (error == EHOSTUNREACH ||
5926 				    error == EHOSTDOWN) {
5927 					/*
5928 					 * Destination went unreachable during
5929 					 * this send
5930 					 */
5931 #ifdef SCTP_DEBUG
5932 					if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
5933 						printf("Calling the movement routine\n");
5934 					}
5935 #endif
5936 					sctp_move_to_an_alt(stcb, asoc, net);
5937 				}
5938 				sctp_clean_up_ctl (asoc);
5939 				return (error);
5940 			} else {
5941 				asoc->ifp_had_enobuf = 0;
5942 			}
5943 			if (bundle_at || hbflag) {
5944 				/* For data/asconf and hb set time */
5945 				if (*now_filled == 0) {
5946 					SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
5947 					*now_filled = 1;
5948 					*now = net->last_sent_time;
5949 				} else {
5950 					net->last_sent_time = *now;
5951 				}
5952 			}
5953 
5954 			if (!no_out_cnt) {
5955 				*num_out += (ctl_cnt + bundle_at);
5956 			}
5957 			if (bundle_at) {
5958 				if (!net->rto_pending) {
5959 					/* setup for a RTO measurement */
5960 					net->rto_pending = 1;
5961 					data_list[0]->do_rtt = 1;
5962 				} else {
5963 					data_list[0]->do_rtt = 0;
5964 				}
5965 				sctp_pegs[SCTP_PEG_TSNS_SENT] += bundle_at;
5966 				sctp_clean_up_datalist(stcb, asoc, data_list, bundle_at, net);
5967 			}
5968 			if (one_chunk) {
5969 				break;
5970 			}
5971 		}
5972 	}
5973 	/* At the end there should be no NON timed
5974 	 * chunks hanging on this queue.
5975 	 */
5976 	if ((*num_out == 0) && (*reason_code == 0)) {
5977 		*reason_code = 3;
5978 	}
5979 	sctp_clean_up_ctl (asoc);
5980 	return (0);
5981 }
5982 
5983 void
5984 sctp_queue_op_err(struct sctp_tcb *stcb, struct mbuf *op_err)
5985 {
5986 	/* Prepend a OPERATIONAL_ERROR chunk header
5987 	 * and put on the end of the control chunk queue.
5988 	 */
5989 	/* Sender had better have gotten a MGETHDR or else
5990 	 * the control chunk will be forever skipped
5991 	 */
5992 	struct sctp_chunkhdr *hdr;
5993 	struct sctp_tmit_chunk *chk;
5994 	struct mbuf *mat;
5995 
5996 	chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
5997 	if (chk == NULL) {
5998 		/* no memory */
5999 		sctp_m_freem(op_err);
6000 		return;
6001 	}
6002 	sctppcbinfo.ipi_count_chunk++;
6003 	sctppcbinfo.ipi_gencnt_chunk++;
6004 	M_PREPEND(op_err, sizeof(struct sctp_chunkhdr), M_DONTWAIT);
6005 	if (op_err == NULL) {
6006 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
6007 		sctppcbinfo.ipi_count_chunk--;
6008 		if ((int)sctppcbinfo.ipi_count_chunk < 0) {
6009 			panic("Chunk count is negative");
6010 		}
6011 		sctppcbinfo.ipi_gencnt_chunk++;
6012 		return;
6013 	}
6014 	chk->send_size = 0;
6015 	mat = op_err;
6016 	while (mat != NULL) {
6017 		chk->send_size += mat->m_len;
6018 		mat = mat->m_next;
6019 	}
6020 	chk->rec.chunk_id = SCTP_OPERATION_ERROR;
6021 	chk->sent = SCTP_DATAGRAM_UNSENT;
6022 	chk->snd_count = 0;
6023 	chk->flags = 0;
6024 	chk->asoc = &stcb->asoc;
6025 	chk->data = op_err;
6026 	chk->whoTo = chk->asoc->primary_destination;
6027 	chk->whoTo->ref_count++;
6028 	hdr = mtod(op_err, struct sctp_chunkhdr *);
6029 	hdr->chunk_type = SCTP_OPERATION_ERROR;
6030 	hdr->chunk_flags = 0;
6031 	hdr->chunk_length = htons(chk->send_size);
6032 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue,
6033 			  chk,
6034 			  sctp_next);
6035 	chk->asoc->ctrl_queue_cnt++;
6036 }
6037 
6038 int
6039 sctp_send_cookie_echo(struct mbuf *m,
6040 		      int offset,
6041 		      struct sctp_tcb *stcb,
6042 		      struct sctp_nets *net)
6043 {
6044 	/*
6045 	 * pull out the cookie and put it at the front of the control
6046 	 * chunk queue.
6047 	 */
6048 	int at;
6049 	struct mbuf *cookie, *mat;
6050 	struct sctp_paramhdr parm, *phdr;
6051 	struct sctp_chunkhdr *hdr;
6052 	struct sctp_tmit_chunk *chk;
6053 	uint16_t ptype, plen;
6054 	/* First find the cookie in the param area */
6055 	cookie = NULL;
6056 	at = offset + sizeof(struct sctp_init_chunk);
6057 
6058 	do {
6059 		phdr = sctp_get_next_param(m, at, &parm, sizeof(parm));
6060 		if (phdr == NULL) {
6061 			return (-3);
6062 		}
6063 		ptype = ntohs(phdr->param_type);
6064 		plen = ntohs(phdr->param_length);
6065 		if (ptype == SCTP_STATE_COOKIE) {
6066 			int pad;
6067 			/* found the cookie */
6068 			if ((pad = (plen % 4))) {
6069 				plen += 4 - pad;
6070 			}
6071 			cookie = sctp_m_copym(m, at, plen, M_DONTWAIT);
6072 			if (cookie == NULL) {
6073 				/* No memory */
6074 				return (-2);
6075 			}
6076 			break;
6077 		}
6078 		at += SCTP_SIZE32(plen);
6079 	} while (phdr);
6080 	if (cookie == NULL) {
6081 		/* Did not find the cookie */
6082 		return (-3);
6083 	}
6084 	/* ok, we got the cookie lets change it into a cookie echo chunk */
6085 
6086 	/* first the change from param to cookie */
6087 	hdr = mtod(cookie, struct sctp_chunkhdr *);
6088 	hdr->chunk_type = SCTP_COOKIE_ECHO;
6089 	hdr->chunk_flags = 0;
6090 	/* now we MUST have a PKTHDR on it */
6091 	if ((cookie->m_flags & M_PKTHDR) != M_PKTHDR) {
6092 		/* we hope this happens rarely */
6093 		MGETHDR(mat, M_DONTWAIT, MT_HEADER);
6094 		if (mat == NULL) {
6095 			sctp_m_freem(cookie);
6096 			return (-4);
6097 		}
6098 		mat->m_len = 0;
6099 		m_reset_rcvif(mat);
6100 		mat->m_next = cookie;
6101 		cookie = mat;
6102 	}
6103 	cookie->m_pkthdr.len = plen;
6104 	/* get the chunk stuff now and place it in the FRONT of the queue */
6105 	chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
6106 	if (chk == NULL) {
6107 		/* no memory */
6108 		sctp_m_freem(cookie);
6109 		return (-5);
6110 	}
6111 	sctppcbinfo.ipi_count_chunk++;
6112 	sctppcbinfo.ipi_gencnt_chunk++;
6113 	chk->send_size = cookie->m_pkthdr.len;
6114 	chk->rec.chunk_id = SCTP_COOKIE_ECHO;
6115 	chk->sent = SCTP_DATAGRAM_UNSENT;
6116 	chk->snd_count = 0;
6117 	chk->flags = 0;
6118 	chk->asoc = &stcb->asoc;
6119 	chk->data = cookie;
6120 	chk->whoTo = chk->asoc->primary_destination;
6121 	chk->whoTo->ref_count++;
6122 	TAILQ_INSERT_HEAD(&chk->asoc->control_send_queue, chk, sctp_next);
6123 	chk->asoc->ctrl_queue_cnt++;
6124 	return (0);
6125 }
6126 
6127 void
6128 sctp_send_heartbeat_ack(struct sctp_tcb *stcb,
6129 			struct mbuf *m,
6130 			int offset,
6131 			int chk_length,
6132 			struct sctp_nets *net)
6133 {
6134 	/* take a HB request and make it into a
6135 	 * HB ack and send it.
6136 	 */
6137 	struct mbuf *outchain;
6138 	struct sctp_chunkhdr *chdr;
6139 	struct sctp_tmit_chunk *chk;
6140 
6141 
6142 	if (net == NULL)
6143 		/* must have a net pointer */
6144 		return;
6145 
6146 	outchain = sctp_m_copym(m, offset, chk_length, M_DONTWAIT);
6147 	if (outchain == NULL) {
6148 		/* gak out of memory */
6149 		return;
6150 	}
6151 	chdr = mtod(outchain, struct sctp_chunkhdr *);
6152 	chdr->chunk_type = SCTP_HEARTBEAT_ACK;
6153 	chdr->chunk_flags = 0;
6154 	if ((outchain->m_flags & M_PKTHDR) != M_PKTHDR) {
6155 		/* should not happen but we are cautious. */
6156 		struct mbuf *tmp;
6157 		MGETHDR(tmp, M_DONTWAIT, MT_HEADER);
6158 		if (tmp == NULL) {
6159 			return;
6160 		}
6161 		tmp->m_len = 0;
6162 		m_reset_rcvif(tmp);
6163 		tmp->m_next = outchain;
6164 		outchain = tmp;
6165 	}
6166 	outchain->m_pkthdr.len = chk_length;
6167 	if (chk_length % 4) {
6168 		/* need pad */
6169 		u_int32_t cpthis=0;
6170 		int padlen;
6171 		padlen = 4 - (outchain->m_pkthdr.len % 4);
6172 		m_copyback(outchain, outchain->m_pkthdr.len, padlen, (void *)&cpthis);
6173 	}
6174 	chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
6175 	if (chk == NULL) {
6176 		/* no memory */
6177 		sctp_m_freem(outchain);
6178 		return ;
6179 	}
6180 	sctppcbinfo.ipi_count_chunk++;
6181 	sctppcbinfo.ipi_gencnt_chunk++;
6182 
6183 	chk->send_size = chk_length;
6184 	chk->rec.chunk_id = SCTP_HEARTBEAT_ACK;
6185 	chk->sent = SCTP_DATAGRAM_UNSENT;
6186 	chk->snd_count = 0;
6187 	chk->flags = 0;
6188 	chk->asoc = &stcb->asoc;
6189 	chk->data = outchain;
6190 	chk->whoTo = net;
6191 	chk->whoTo->ref_count++;
6192 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
6193 	chk->asoc->ctrl_queue_cnt++;
6194 }
6195 
6196 int
6197 sctp_send_cookie_ack(struct sctp_tcb *stcb) {
6198 	/* formulate and queue a cookie-ack back to sender */
6199 	struct mbuf *cookie_ack;
6200 	struct sctp_chunkhdr *hdr;
6201 	struct sctp_tmit_chunk *chk;
6202 
6203 	cookie_ack = NULL;
6204 	MGETHDR(cookie_ack, M_DONTWAIT, MT_HEADER);
6205 	if (cookie_ack == NULL) {
6206 		/* no mbuf's */
6207 		return (-1);
6208 	}
6209  	cookie_ack->m_data += SCTP_MIN_OVERHEAD;
6210 	chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
6211 	if (chk == NULL) {
6212 		/* no memory */
6213 		sctp_m_freem(cookie_ack);
6214 		return (-1);
6215 	}
6216 	sctppcbinfo.ipi_count_chunk++;
6217 	sctppcbinfo.ipi_gencnt_chunk++;
6218 
6219 	chk->send_size = sizeof(struct sctp_chunkhdr);
6220 	chk->rec.chunk_id = SCTP_COOKIE_ACK;
6221 	chk->sent = SCTP_DATAGRAM_UNSENT;
6222 	chk->snd_count = 0;
6223 	chk->flags = 0;
6224 	chk->asoc = &stcb->asoc;
6225 	chk->data = cookie_ack;
6226 	if (chk->asoc->last_control_chunk_from != NULL) {
6227 		chk->whoTo = chk->asoc->last_control_chunk_from;
6228 	} else {
6229 		chk->whoTo = chk->asoc->primary_destination;
6230 	}
6231 	chk->whoTo->ref_count++;
6232 	hdr = mtod(cookie_ack, struct sctp_chunkhdr *);
6233 	hdr->chunk_type = SCTP_COOKIE_ACK;
6234 	hdr->chunk_flags = 0;
6235 	hdr->chunk_length = htons(chk->send_size);
6236 	cookie_ack->m_pkthdr.len = cookie_ack->m_len = chk->send_size;
6237 	m_reset_rcvif(cookie_ack);
6238 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
6239 	chk->asoc->ctrl_queue_cnt++;
6240 	return (0);
6241 }
6242 
6243 
6244 int
6245 sctp_send_shutdown_ack(struct sctp_tcb *stcb, struct sctp_nets *net)
6246 {
6247 	/* formulate and queue a SHUTDOWN-ACK back to the sender */
6248 	struct mbuf *m_shutdown_ack;
6249 	struct sctp_shutdown_ack_chunk *ack_cp;
6250 	struct sctp_tmit_chunk *chk;
6251 
6252 	m_shutdown_ack = NULL;
6253 	MGETHDR(m_shutdown_ack, M_DONTWAIT, MT_HEADER);
6254 	if (m_shutdown_ack == NULL) {
6255 		/* no mbuf's */
6256 		return (-1);
6257 	}
6258 	m_shutdown_ack->m_data += SCTP_MIN_OVERHEAD;
6259 	chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
6260 	if (chk == NULL) {
6261 		/* no memory */
6262 		sctp_m_freem(m_shutdown_ack);
6263 		return (-1);
6264 	}
6265 	sctppcbinfo.ipi_count_chunk++;
6266 	sctppcbinfo.ipi_gencnt_chunk++;
6267 
6268 	chk->send_size = sizeof(struct sctp_chunkhdr);
6269 	chk->rec.chunk_id = SCTP_SHUTDOWN_ACK;
6270 	chk->sent = SCTP_DATAGRAM_UNSENT;
6271 	chk->snd_count = 0;
6272 	chk->flags = 0;
6273 	chk->asoc = &stcb->asoc;
6274 	chk->data = m_shutdown_ack;
6275 	chk->whoTo = net;
6276 	net->ref_count++;
6277 
6278 	ack_cp = mtod(m_shutdown_ack, struct sctp_shutdown_ack_chunk *);
6279 	ack_cp->ch.chunk_type = SCTP_SHUTDOWN_ACK;
6280 	ack_cp->ch.chunk_flags = 0;
6281 	ack_cp->ch.chunk_length = htons(chk->send_size);
6282 	m_shutdown_ack->m_pkthdr.len = m_shutdown_ack->m_len = chk->send_size;
6283 	m_reset_rcvif(m_shutdown_ack);
6284 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
6285 	chk->asoc->ctrl_queue_cnt++;
6286 	return (0);
6287 }
6288 
6289 int
6290 sctp_send_shutdown(struct sctp_tcb *stcb, struct sctp_nets *net)
6291 {
6292 	/* formulate and queue a SHUTDOWN to the sender */
6293 	struct mbuf *m_shutdown;
6294 	struct sctp_shutdown_chunk *shutdown_cp;
6295 	struct sctp_tmit_chunk *chk;
6296 
6297 	m_shutdown = NULL;
6298 	MGETHDR(m_shutdown, M_DONTWAIT, MT_HEADER);
6299 	if (m_shutdown == NULL) {
6300 		/* no mbuf's */
6301 		return (-1);
6302 	}
6303 	m_shutdown->m_data += SCTP_MIN_OVERHEAD;
6304 	chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
6305 	if (chk == NULL) {
6306 		/* no memory */
6307 		sctp_m_freem(m_shutdown);
6308 		return (-1);
6309 	}
6310 	sctppcbinfo.ipi_count_chunk++;
6311 	sctppcbinfo.ipi_gencnt_chunk++;
6312 
6313 	chk->send_size = sizeof(struct sctp_shutdown_chunk);
6314 	chk->rec.chunk_id = SCTP_SHUTDOWN;
6315 	chk->sent = SCTP_DATAGRAM_UNSENT;
6316 	chk->snd_count = 0;
6317 	chk->flags = 0;
6318 	chk->asoc = &stcb->asoc;
6319 	chk->data = m_shutdown;
6320 	chk->whoTo = net;
6321 	net->ref_count++;
6322 
6323 	shutdown_cp = mtod(m_shutdown, struct sctp_shutdown_chunk *);
6324 	shutdown_cp->ch.chunk_type = SCTP_SHUTDOWN;
6325 	shutdown_cp->ch.chunk_flags = 0;
6326 	shutdown_cp->ch.chunk_length = htons(chk->send_size);
6327 	shutdown_cp->cumulative_tsn_ack = htonl(stcb->asoc.cumulative_tsn);
6328 	m_shutdown->m_pkthdr.len = m_shutdown->m_len = chk->send_size;
6329 	m_reset_rcvif(m_shutdown);
6330 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
6331 	chk->asoc->ctrl_queue_cnt++;
6332 
6333 	if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
6334 	    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
6335 		stcb->sctp_ep->sctp_socket->so_snd.sb_cc = 0;
6336 		soisdisconnecting(stcb->sctp_ep->sctp_socket);
6337 	}
6338 	return (0);
6339 }
6340 
6341 int
6342 sctp_send_asconf(struct sctp_tcb *stcb, struct sctp_nets *net)
6343 {
6344 	/*
6345 	 * formulate and queue an ASCONF to the peer
6346 	 * ASCONF parameters should be queued on the assoc queue
6347 	 */
6348 	struct sctp_tmit_chunk *chk;
6349 	struct mbuf *m_asconf;
6350 
6351 	/* compose an ASCONF chunk, maximum length is PMTU */
6352 	m_asconf = sctp_compose_asconf(stcb);
6353 	if (m_asconf == NULL) {
6354 		return (-1);
6355 	}
6356 	chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
6357 	if (chk == NULL) {
6358 		/* no memory */
6359 		sctp_m_freem(m_asconf);
6360 		return (-1);
6361 	}
6362 	sctppcbinfo.ipi_count_chunk++;
6363 	sctppcbinfo.ipi_gencnt_chunk++;
6364 
6365 	chk->data = m_asconf;
6366 	chk->send_size = m_asconf->m_pkthdr.len;
6367 	chk->rec.chunk_id = SCTP_ASCONF;
6368 	chk->sent = SCTP_DATAGRAM_UNSENT;
6369 	chk->snd_count = 0;
6370 	chk->flags = 0;
6371 	chk->asoc = &stcb->asoc;
6372 	chk->whoTo = chk->asoc->primary_destination;
6373 	chk->whoTo->ref_count++;
6374 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
6375 	chk->asoc->ctrl_queue_cnt++;
6376 	return (0);
6377 }
6378 
6379 int
6380 sctp_send_asconf_ack(struct sctp_tcb *stcb, uint32_t retrans)
6381 {
6382 	/*
6383 	 * formulate and queue a asconf-ack back to sender
6384 	 * the asconf-ack must be stored in the tcb
6385 	 */
6386 	struct sctp_tmit_chunk *chk;
6387 	struct mbuf *m_ack;
6388 
6389 	/* is there a asconf-ack mbuf chain to send? */
6390 	if (stcb->asoc.last_asconf_ack_sent == NULL) {
6391 		return (-1);
6392 	}
6393 
6394 	/* copy the asconf_ack */
6395 #if defined(__FreeBSD__) || defined(__NetBSD__)
6396 	/* Supposedly the m_copypacket is a optimzation,
6397 	 * use it if we can.
6398 	 */
6399 	if (stcb->asoc.last_asconf_ack_sent->m_flags & M_PKTHDR) {
6400 		m_ack = m_copypacket(stcb->asoc.last_asconf_ack_sent, M_DONTWAIT);
6401 		sctp_pegs[SCTP_CACHED_SRC]++;
6402 	} else
6403 		m_ack = m_copym(stcb->asoc.last_asconf_ack_sent, 0, M_COPYALL, M_DONTWAIT);
6404 #else
6405 		m_ack = m_copy(stcb->asoc.last_asconf_ack_sent, 0, M_COPYALL);
6406 #endif
6407 	if (m_ack == NULL) {
6408 		/* couldn't copy it */
6409 
6410 		return (-1);
6411 	}
6412 	chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
6413 	if (chk == NULL) {
6414 		/* no memory */
6415 		if (m_ack)
6416 			sctp_m_freem(m_ack);
6417 		return (-1);
6418 	}
6419 	sctppcbinfo.ipi_count_chunk++;
6420 	sctppcbinfo.ipi_gencnt_chunk++;
6421 
6422 	/* figure out where it goes to */
6423 	if (retrans) {
6424 		/* we're doing a retransmission */
6425 		if (stcb->asoc.used_alt_asconfack > 2) {
6426 			/* tried alternate nets already, go back */
6427 			chk->whoTo = NULL;
6428 		} else {
6429 			/* need to try and alternate net */
6430 			chk->whoTo = sctp_find_alternate_net(stcb, stcb->asoc.last_control_chunk_from);
6431 			stcb->asoc.used_alt_asconfack++;
6432 		}
6433 		if (chk->whoTo == NULL) {
6434 			/* no alternate */
6435 			if (stcb->asoc.last_control_chunk_from == NULL)
6436 				chk->whoTo = stcb->asoc.primary_destination;
6437 			else
6438 				chk->whoTo = stcb->asoc.last_control_chunk_from;
6439 			stcb->asoc.used_alt_asconfack = 0;
6440 		}
6441 	} else {
6442 		/* normal case */
6443 		if (stcb->asoc.last_control_chunk_from == NULL)
6444 			chk->whoTo = stcb->asoc.primary_destination;
6445 		else
6446 			chk->whoTo = stcb->asoc.last_control_chunk_from;
6447 		stcb->asoc.used_alt_asconfack = 0;
6448 	}
6449 	chk->data = m_ack;
6450 	chk->send_size = m_ack->m_pkthdr.len;
6451 	chk->rec.chunk_id = SCTP_ASCONF_ACK;
6452 	chk->sent = SCTP_DATAGRAM_UNSENT;
6453 	chk->snd_count = 0;
6454 	chk->flags = 0;
6455 	chk->asoc = &stcb->asoc;
6456 	chk->whoTo->ref_count++;
6457 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
6458 	chk->asoc->ctrl_queue_cnt++;
6459 	return (0);
6460 }
6461 
6462 
6463 static int
6464 sctp_chunk_retransmission(struct sctp_inpcb *inp,
6465 			  struct sctp_tcb *stcb,
6466 			  struct sctp_association *asoc,
6467 			  int *cnt_out, struct timeval *now, int *now_filled)
6468 {
6469 	/*
6470 	 * send out one MTU of retransmission.
6471 	 * If fast_retransmit is happening we ignore the cwnd.
6472 	 * Otherwise we obey the cwnd and rwnd.
6473 	 * For a Cookie or Asconf in the control chunk queue we retransmit
6474 	 * them by themselves.
6475 	 *
6476 	 * For data chunks we will pick out the lowest TSN's in the
6477 	 * sent_queue marked for resend and bundle them all together
6478 	 * (up to a MTU of destination). The address to send to should
6479 	 * have been selected/changed where the retransmission was
6480 	 * marked (i.e. in FR or t3-timeout routines).
6481 	 */
6482 	struct sctp_tmit_chunk *data_list[SCTP_MAX_DATA_BUNDLING];
6483 	struct sctp_tmit_chunk *chk, *fwd;
6484 	struct mbuf *m;
6485 	struct sctphdr *shdr;
6486 	int asconf;
6487 	struct sctp_nets *net;
6488 	int no_fragmentflg, bundle_at, cnt_thru;
6489 	unsigned int mtu;
6490 	int error, i, one_chunk, fwd_tsn, ctl_cnt, tmr_started;
6491 
6492 	tmr_started = ctl_cnt = bundle_at =  error = 0;
6493 	no_fragmentflg = 1;
6494 	asconf = 0;
6495 	fwd_tsn = 0;
6496 	*cnt_out = 0;
6497 	fwd = NULL;
6498 	m = NULL;
6499 #ifdef SCTP_AUDITING_ENABLED
6500 	sctp_audit_log(0xC3, 1);
6501 #endif
6502 	if (TAILQ_EMPTY(&asoc->sent_queue)) {
6503 #ifdef SCTP_DEBUG
6504 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
6505 			printf("SCTP hits empty queue with cnt set to %d?\n",
6506 			       asoc->sent_queue_retran_cnt);
6507 		}
6508 #endif
6509 		asoc->sent_queue_cnt = 0;
6510 		asoc->sent_queue_cnt_removeable = 0;
6511 	}
6512 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
6513 		if (chk->sent != SCTP_DATAGRAM_RESEND) {
6514 			/* we only worry about things marked for resend */
6515 			continue;
6516 		}
6517 		if ((chk->rec.chunk_id == SCTP_COOKIE_ECHO) ||
6518 		    (chk->rec.chunk_id == SCTP_ASCONF) ||
6519 		    (chk->rec.chunk_id == SCTP_STREAM_RESET) ||
6520 		    (chk->rec.chunk_id == SCTP_FORWARD_CUM_TSN)) {
6521 			if (chk->rec.chunk_id == SCTP_STREAM_RESET) {
6522 				/* For stream reset we only retran the request
6523 				 * not the response.
6524 				 */
6525 				struct sctp_stream_reset_req *strreq;
6526 				strreq = mtod(chk->data, struct sctp_stream_reset_req *);
6527 				if (strreq->sr_req.ph.param_type != ntohs(SCTP_STR_RESET_REQUEST)) {
6528 					continue;
6529 				}
6530 			}
6531 			ctl_cnt++;
6532 			if (chk->rec.chunk_id == SCTP_ASCONF) {
6533 				no_fragmentflg = 1;
6534 				asconf = 1;
6535 			}
6536 			if (chk->rec.chunk_id == SCTP_FORWARD_CUM_TSN) {
6537 				fwd_tsn = 1;
6538 				fwd = chk;
6539 			}
6540 			m = sctp_copy_mbufchain(chk->data, m);
6541 			break;
6542 		}
6543 	}
6544 	one_chunk = 0;
6545 	cnt_thru = 0;
6546 	/* do we have control chunks to retransmit? */
6547 	if (m != NULL) {
6548 		/* Start a timer no matter if we suceed or fail */
6549 		if (chk->rec.chunk_id == SCTP_COOKIE_ECHO) {
6550 			sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, inp, stcb, chk->whoTo);
6551 		} else if (chk->rec.chunk_id == SCTP_ASCONF)
6552 			sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp, stcb, chk->whoTo);
6553 
6554 		if (m->m_len == 0) {
6555 			/* Special case for when you get a 0 len
6556 			 * mbuf at the head due to the lack
6557 			 * of a MHDR at the beginning.
6558 			 */
6559 			m->m_len = sizeof(struct sctphdr);
6560 		} else {
6561 			M_PREPEND(m, sizeof(struct sctphdr), M_DONTWAIT);
6562 			if (m == NULL) {
6563 				return (ENOBUFS);
6564 			}
6565 		}
6566 		shdr = mtod(m, struct sctphdr *);
6567 		shdr->src_port = inp->sctp_lport;
6568 		shdr->dest_port = stcb->rport;
6569 		shdr->v_tag = htonl(stcb->asoc.peer_vtag);
6570 		shdr->checksum = 0;
6571 		chk->snd_count++;		/* update our count */
6572 
6573 		if ((error = sctp_lowlevel_chunk_output(inp, stcb, chk->whoTo,
6574 		    rtcache_getdst(&chk->whoTo->ro), m,
6575 		    no_fragmentflg, 0, NULL, asconf))) {
6576 			sctp_pegs[SCTP_DATA_OUT_ERR]++;
6577 			return (error);
6578 		}
6579 		/*
6580 		 *We don't want to mark the net->sent time here since this
6581 		 * we use this for HB and retrans cannot measure RTT
6582 		 */
6583 		/*    SCTP_GETTIME_TIMEVAL(&chk->whoTo->last_sent_time);*/
6584 		*cnt_out += 1;
6585 		chk->sent = SCTP_DATAGRAM_SENT;
6586 		sctp_ucount_decr(asoc->sent_queue_retran_cnt);
6587 		if (fwd_tsn == 0) {
6588 			return (0);
6589 		} else {
6590 			/* Clean up the fwd-tsn list */
6591 			sctp_clean_up_ctl (asoc);
6592 			return (0);
6593 		}
6594 	}
6595 	/* Ok, it is just data retransmission we need to do or
6596 	 * that and a fwd-tsn with it all.
6597 	 */
6598 	if (TAILQ_EMPTY(&asoc->sent_queue)) {
6599 		return (-1);
6600 	}
6601 #ifdef SCTP_DEBUG
6602 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
6603 		printf("Normal chunk retransmission cnt:%d\n",
6604 		       asoc->sent_queue_retran_cnt);
6605 	}
6606 #endif
6607 	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED) ||
6608 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT)) {
6609 		/* not yet open, resend the cookie and that is it */
6610 		return (1);
6611 	}
6612 
6613 
6614 #ifdef SCTP_AUDITING_ENABLED
6615 	sctp_auditing(20, inp, stcb, NULL);
6616 #endif
6617 	TAILQ_FOREACH(chk, &asoc->sent_queue, sctp_next) {
6618 		if (chk->sent != SCTP_DATAGRAM_RESEND) {
6619 			/* No, not sent to this net or not ready for rtx */
6620 			continue;
6621 
6622 		}
6623 		/* pick up the net */
6624 		net = chk->whoTo;
6625 		if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
6626 			mtu = (net->mtu - SCTP_MIN_OVERHEAD);
6627 		} else {
6628 			mtu = net->mtu- SCTP_MIN_V4_OVERHEAD;
6629 		}
6630 
6631 		if ((asoc->peers_rwnd < mtu) && (asoc->total_flight > 0)) {
6632 			/* No room in peers rwnd */
6633 			uint32_t tsn;
6634 			tsn = asoc->last_acked_seq + 1;
6635 			if (tsn == chk->rec.data.TSN_seq) {
6636 				/* we make a special exception for this case.
6637 				 * The peer has no rwnd but is missing the
6638 				 * lowest chunk.. which is probably what is
6639 				 * holding up the rwnd.
6640 				 */
6641 				goto one_chunk_around;
6642 			}
6643 #ifdef SCTP_DEBUG
6644 			if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
6645 				printf("blocked-peers_rwnd:%d tf:%d\n",
6646 				       (int)asoc->peers_rwnd,
6647 				       (int)asoc->total_flight);
6648 			}
6649 #endif
6650 			sctp_pegs[SCTP_RWND_BLOCKED]++;
6651 			return (1);
6652 		}
6653 	one_chunk_around:
6654 		if (asoc->peers_rwnd < mtu) {
6655 			one_chunk = 1;
6656 		}
6657 #ifdef SCTP_AUDITING_ENABLED
6658 		sctp_audit_log(0xC3, 2);
6659 #endif
6660 		bundle_at = 0;
6661 		m = NULL;
6662 		net->fast_retran_ip = 0;
6663 		if (chk->rec.data.doing_fast_retransmit == 0) {
6664 			/* if no FR in progress skip destination that
6665 			 * have flight_size > cwnd.
6666 			 */
6667 			if (net->flight_size >= net->cwnd) {
6668 				sctp_pegs[SCTP_CWND_BLOCKED]++;
6669 				continue;
6670 			}
6671 		} else {
6672 			/* Mark the destination net to have FR recovery
6673 			 * limits put on it.
6674 			 */
6675 			net->fast_retran_ip = 1;
6676 		}
6677 
6678 		if ((chk->send_size <= mtu) || (chk->flags & CHUNK_FLAGS_FRAGMENT_OK)) {
6679 			/* ok we will add this one */
6680 			m = sctp_copy_mbufchain(chk->data, m);
6681 			if (m == NULL) {
6682 				return (ENOMEM);
6683 			}
6684 			/* update our MTU size */
6685 			/* Do clear IP_DF ? */
6686 			if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
6687 				no_fragmentflg = 0;
6688 			}
6689 			mtu -= chk->send_size;
6690 			data_list[bundle_at++] = chk;
6691 			if (one_chunk && (asoc->total_flight <= 0)) {
6692 				sctp_pegs[SCTP_WINDOW_PROBES]++;
6693 				chk->rec.data.state_flags |= SCTP_WINDOW_PROBE;
6694 			}
6695 		}
6696 		if (one_chunk == 0) {
6697 			/* now are there anymore forward from chk to pick up?*/
6698 			fwd = TAILQ_NEXT(chk, sctp_next);
6699 			while (fwd) {
6700 				if (fwd->sent != SCTP_DATAGRAM_RESEND) {
6701 					/* Nope, not for retran */
6702 					fwd = TAILQ_NEXT(fwd, sctp_next);
6703 					continue;
6704 				}
6705 				if (fwd->whoTo != net) {
6706 					/* Nope, not the net in question */
6707 					fwd = TAILQ_NEXT(fwd, sctp_next);
6708 					continue;
6709 				}
6710 				if (fwd->send_size <= mtu) {
6711 					m = sctp_copy_mbufchain(fwd->data, m);
6712 					if (m == NULL) {
6713 						return (ENOMEM);
6714 					}
6715 					/* update our MTU size */
6716 					/* Do clear IP_DF ? */
6717 					if (fwd->flags & CHUNK_FLAGS_FRAGMENT_OK) {
6718 						no_fragmentflg = 0;
6719 					}
6720 					mtu -= fwd->send_size;
6721 					data_list[bundle_at++] = fwd;
6722 					if (bundle_at >= SCTP_MAX_DATA_BUNDLING) {
6723 						break;
6724 					}
6725 					fwd = TAILQ_NEXT(fwd, sctp_next);
6726 				} else {
6727 					/* can't fit so we are done */
6728 					break;
6729 				}
6730 			}
6731 		}
6732 		/* Is there something to send for this destination? */
6733 		if (m) {
6734 			/* No matter if we fail/or suceed we should
6735 			 * start a timer. A failure is like a lost
6736 			 * IP packet :-)
6737 			 */
6738 			if (!callout_pending(&net->rxt_timer.timer)) {
6739 				/* no timer running on this destination
6740 				 * restart it.
6741 				 */
6742 				sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
6743 				tmr_started = 1;
6744 			}
6745 			if (m->m_len == 0) {
6746 				/* Special case for when you get a 0 len
6747 				 * mbuf at the head due to the lack
6748 				 * of a MHDR at the beginning.
6749 				 */
6750 				m->m_len = sizeof(struct sctphdr);
6751 			} else {
6752 				M_PREPEND(m, sizeof(struct sctphdr), M_DONTWAIT);
6753 				if (m == NULL) {
6754 					return (ENOBUFS);
6755 				}
6756 			}
6757 			shdr = mtod(m, struct sctphdr *);
6758 			shdr->src_port = inp->sctp_lport;
6759 			shdr->dest_port = stcb->rport;
6760 			shdr->v_tag = htonl(stcb->asoc.peer_vtag);
6761 			shdr->checksum = 0;
6762 
6763 			/* Now lets send it, if there is anything to send :> */
6764 			if ((error = sctp_lowlevel_chunk_output(inp, stcb, net,
6765 							       rtcache_getdst(&net->ro),
6766 							       m,
6767 							       no_fragmentflg, 0, NULL, asconf))) {
6768 				/* error, we could not output */
6769 				sctp_pegs[SCTP_DATA_OUT_ERR]++;
6770 				return (error);
6771 			}
6772 			/* For HB's */
6773 			/*
6774 			 * We don't want to mark the net->sent time here since
6775 			 * this we use this for HB and retrans cannot measure
6776 			 * RTT
6777 			 */
6778 			/*      SCTP_GETTIME_TIMEVAL(&net->last_sent_time);*/
6779 
6780 			/* For auto-close */
6781 			cnt_thru++;
6782 			if (*now_filled == 0) {
6783 				SCTP_GETTIME_TIMEVAL(&asoc->time_last_sent);
6784 				*now = asoc->time_last_sent;
6785 				*now_filled = 1;
6786 			} else {
6787 				asoc->time_last_sent = *now;
6788 			}
6789 			*cnt_out += bundle_at;
6790 #ifdef SCTP_AUDITING_ENABLED
6791 			sctp_audit_log(0xC4, bundle_at);
6792 #endif
6793 			for (i = 0; i < bundle_at; i++) {
6794 				sctp_pegs[SCTP_RETRANTSN_SENT]++;
6795 				data_list[i]->sent = SCTP_DATAGRAM_SENT;
6796 				data_list[i]->snd_count++;
6797 				sctp_ucount_decr(asoc->sent_queue_retran_cnt);
6798 				/* record the time */
6799 				data_list[i]->sent_rcv_time = asoc->time_last_sent;
6800 				net->flight_size += data_list[i]->book_size;
6801 				asoc->total_flight += data_list[i]->book_size;
6802 				asoc->total_flight_count++;
6803 
6804 #ifdef SCTP_LOG_RWND
6805 				sctp_log_rwnd(SCTP_DECREASE_PEER_RWND,
6806 					      asoc->peers_rwnd , data_list[i]->send_size, sctp_peer_chunk_oh);
6807 #endif
6808 				asoc->peers_rwnd = sctp_sbspace_sub(asoc->peers_rwnd,
6809 								    (u_int32_t)(data_list[i]->send_size + sctp_peer_chunk_oh));
6810 				if (asoc->peers_rwnd < stcb->sctp_ep->sctp_ep.sctp_sws_sender) {
6811 					/* SWS sender side engages */
6812 					asoc->peers_rwnd = 0;
6813 				}
6814 
6815 				if ((i == 0) &&
6816 				    (data_list[i]->rec.data.doing_fast_retransmit)) {
6817 					sctp_pegs[SCTP_FAST_RETRAN]++;
6818 					if ((data_list[i] == TAILQ_FIRST(&asoc->sent_queue)) &&
6819 					    (tmr_started == 0)) {
6820 						/*
6821 						 * ok we just fast-retrans'd
6822 						 * the lowest TSN, i.e the
6823 						 * first on the list. In this
6824 						 * case we want to give some
6825 						 * more time to get a SACK
6826 						 * back without a t3-expiring.
6827 						 */
6828 						sctp_timer_stop(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
6829 						sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
6830 					}
6831 				}
6832 			}
6833 #ifdef SCTP_AUDITING_ENABLED
6834 			sctp_auditing(21, inp, stcb, NULL);
6835 #endif
6836 		} else {
6837 			/* None will fit */
6838 			return (1);
6839 		}
6840 		if (asoc->sent_queue_retran_cnt <= 0) {
6841 			/* all done we have no more to retran */
6842 			asoc->sent_queue_retran_cnt = 0;
6843 			break;
6844 		}
6845 		if (one_chunk) {
6846 			/* No more room in rwnd */
6847 			return (1);
6848 		}
6849 		/* stop the for loop here. we sent out a packet */
6850 		break;
6851 	}
6852 	return (0);
6853 }
6854 
6855 
6856 static int
6857 sctp_timer_validation(struct sctp_inpcb *inp,
6858 		      struct sctp_tcb *stcb,
6859 		      struct sctp_association *asoc,
6860 		      int ret)
6861 {
6862 	struct sctp_nets *net;
6863 	/* Validate that a timer is running somewhere */
6864 	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
6865 		if (callout_pending(&net->rxt_timer.timer)) {
6866 			/* Here is a timer */
6867 			return (ret);
6868 		}
6869 	}
6870 	/* Gak, we did not have a timer somewhere */
6871 #ifdef SCTP_DEBUG
6872 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
6873 		printf("Deadlock avoided starting timer on a dest at retran\n");
6874 	}
6875 #endif
6876 	sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, asoc->primary_destination);
6877 	return (ret);
6878 }
6879 
6880 int
6881 sctp_chunk_output(struct sctp_inpcb *inp,
6882 		  struct sctp_tcb *stcb,
6883 		  int from_where)
6884 {
6885 	/* Ok this is the generic chunk service queue.
6886 	 * we must do the following:
6887 	 *  - See if there are retransmits pending, if so we
6888 	 *   	must do these first and return.
6889 	 *  - Service the stream queue that is next,
6890 	 *    moving any message (note I must get a complete
6891 	 *    message i.e. FIRST/MIDDLE and LAST to the out
6892 	 *    queue in one pass) and assigning TSN's
6893 	 *  - Check to see if the cwnd/rwnd allows any output, if
6894 	 *	so we go ahead and fomulate and send the low level
6895 	 *    chunks. Making sure to combine any control in the
6896 	 *    control chunk queue also.
6897 	 */
6898 	struct sctp_association *asoc;
6899 	struct sctp_nets *net;
6900 	int error, num_out, tot_out, ret, reason_code, burst_cnt, burst_limit;
6901 	struct timeval now;
6902 	int now_filled=0;
6903 	int cwnd_full=0;
6904 	asoc = &stcb->asoc;
6905 	tot_out = 0;
6906 	num_out = 0;
6907 	reason_code = 0;
6908 	sctp_pegs[SCTP_CALLS_TO_CO]++;
6909 #ifdef SCTP_DEBUG
6910 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
6911 		printf("in co - retran count:%d\n", asoc->sent_queue_retran_cnt);
6912 	}
6913 #endif
6914 	while (asoc->sent_queue_retran_cnt) {
6915 		/* Ok, it is retransmission time only, we send out only ONE
6916 		 * packet with a single call off to the retran code.
6917 		 */
6918 		ret = sctp_chunk_retransmission(inp, stcb, asoc, &num_out, &now, &now_filled);
6919 		if (ret > 0) {
6920 			/* Can't send anymore */
6921 #ifdef SCTP_DEBUG
6922 			if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
6923 				printf("retransmission ret:%d -- full\n", ret);
6924 			}
6925 #endif
6926 			/*
6927 			 * now lets push out control by calling med-level
6928 			 * output once. this assures that we WILL send HB's
6929 			 * if queued too.
6930 			 */
6931 			(void)sctp_med_chunk_output(inp, stcb, asoc, &num_out, &reason_code, 1,
6932 						    &cwnd_full, from_where,
6933 						    &now, &now_filled);
6934 #ifdef SCTP_DEBUG
6935 			if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
6936 				printf("Control send outputs:%d@full\n", num_out);
6937 			}
6938 #endif
6939 #ifdef SCTP_AUDITING_ENABLED
6940 			sctp_auditing(8, inp, stcb, NULL);
6941 #endif
6942 			return (sctp_timer_validation(inp, stcb, asoc, ret));
6943 		}
6944 		if (ret < 0) {
6945 			/*
6946 			 * The count was off.. retran is not happening so do
6947 			 * the normal retransmission.
6948 			 */
6949 #ifdef SCTP_DEBUG
6950 			if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
6951 				printf("Done with retrans, none left fill up window\n");
6952 			}
6953 #endif
6954 #ifdef SCTP_AUDITING_ENABLED
6955 			sctp_auditing(9, inp, stcb, NULL);
6956 #endif
6957 			break;
6958 		}
6959 		if (from_where == 1) {
6960 			/* Only one transmission allowed out of a timeout */
6961 #ifdef SCTP_DEBUG
6962 			if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
6963 				printf("Only one packet allowed out\n");
6964 			}
6965 #endif
6966 #ifdef SCTP_AUDITING_ENABLED
6967 			sctp_auditing(10, inp, stcb, NULL);
6968 #endif
6969 			/* Push out any control */
6970 			(void)sctp_med_chunk_output(inp, stcb, asoc, &num_out, &reason_code, 1, &cwnd_full, from_where,
6971 						    &now, &now_filled);
6972 			return (ret);
6973 		}
6974 		if ((num_out == 0) && (ret == 0)) {
6975 			/* No more retrans to send */
6976 			break;
6977 		}
6978 	}
6979 #ifdef SCTP_AUDITING_ENABLED
6980 	sctp_auditing(12, inp, stcb, NULL);
6981 #endif
6982 	/* Check for bad destinations, if they exist move chunks around. */
6983 	burst_limit = asoc->max_burst;
6984 	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
6985 		if ((net->dest_state & SCTP_ADDR_NOT_REACHABLE) ==
6986 		    SCTP_ADDR_NOT_REACHABLE) {
6987 			/*
6988 			 * if possible move things off of this address
6989 			 * we still may send below due to the dormant state
6990 			 * but we try to find an alternate address to send
6991 			 * to and if we have one we move all queued data on
6992 			 * the out wheel to this alternate address.
6993 			 */
6994 			sctp_move_to_an_alt(stcb, asoc, net);
6995 		} else {
6996 			/*
6997 			if ((asoc->sat_network) || (net->addr_is_local)) {
6998 				burst_limit = asoc->max_burst * SCTP_SAT_NETWORK_BURST_INCR;
6999 			}
7000 			*/
7001 #ifdef SCTP_DEBUG
7002 			if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
7003 				printf("examined net:%p burst limit:%d\n", net, asoc->max_burst);
7004 			}
7005 #endif
7006 
7007 #ifdef SCTP_USE_ALLMAN_BURST
7008 			if ((net->flight_size+(burst_limit*net->mtu)) < net->cwnd) {
7009 				if (net->ssthresh < net->cwnd)
7010 					net->ssthresh = net->cwnd;
7011 				net->cwnd = (net->flight_size+(burst_limit*net->mtu));
7012 #ifdef SCTP_LOG_MAXBURST
7013 				sctp_log_maxburst(net, 0, burst_limit, SCTP_MAX_BURST_APPLIED);
7014 #endif
7015 				sctp_pegs[SCTP_MAX_BURST_APL]++;
7016 			}
7017 			net->fast_retran_ip = 0;
7018 #endif
7019 		}
7020 
7021 	}
7022 	/* Fill up what we can to the destination */
7023 	burst_cnt = 0;
7024 	cwnd_full = 0;
7025 	do {
7026 #ifdef SCTP_DEBUG
7027 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
7028 			printf("Burst count:%d - call m-c-o\n", burst_cnt);
7029 		}
7030 #endif
7031 		error = sctp_med_chunk_output(inp, stcb, asoc, &num_out,
7032 					      &reason_code, 0,  &cwnd_full, from_where,
7033 					      &now, &now_filled);
7034 		if (error) {
7035 #ifdef SCTP_DEBUG
7036 			if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
7037 				printf("Error %d was returned from med-c-op\n", error);
7038 			}
7039 #endif
7040 #ifdef SCTP_LOG_MAXBURST
7041 			sctp_log_maxburst(asoc->primary_destination, error , burst_cnt, SCTP_MAX_BURST_ERROR_STOP);
7042 #endif
7043 			break;
7044 		}
7045 #ifdef SCTP_DEBUG
7046 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT3) {
7047 			printf("m-c-o put out %d\n", num_out);
7048 		}
7049 #endif
7050 		tot_out += num_out;
7051 		burst_cnt++;
7052 	} while (num_out
7053 #ifndef SCTP_USE_ALLMAN_BURST
7054 		 &&  (burst_cnt < burst_limit)
7055 #endif
7056 		);
7057 #ifndef SCTP_USE_ALLMAN_BURST
7058 	if (burst_cnt >= burst_limit) {
7059 		sctp_pegs[SCTP_MAX_BURST_APL]++;
7060  		asoc->burst_limit_applied = 1;
7061 #ifdef SCTP_LOG_MAXBURST
7062 		sctp_log_maxburst(asoc->primary_destination, 0 , burst_cnt, SCTP_MAX_BURST_APPLIED);
7063 #endif
7064  	} else {
7065 		asoc->burst_limit_applied = 0;
7066  	}
7067 #endif
7068 
7069 #ifdef SCTP_DEBUG
7070 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
7071 		printf("Ok, we have put out %d chunks\n", tot_out);
7072 	}
7073 #endif
7074 	if (tot_out == 0) {
7075 		sctp_pegs[SCTP_CO_NODATASNT]++;
7076 		if (asoc->stream_queue_cnt > 0) {
7077 			sctp_pegs[SCTP_SOS_NOSNT]++;
7078 		} else {
7079 			sctp_pegs[SCTP_NOS_NOSNT]++;
7080 		}
7081 		if (asoc->send_queue_cnt > 0) {
7082 			sctp_pegs[SCTP_SOSE_NOSNT]++;
7083 		} else {
7084 			sctp_pegs[SCTP_NOSE_NOSNT]++;
7085 		}
7086 	}
7087 	/* Now we need to clean up the control chunk chain if
7088 	 * a ECNE is on it. It must be marked as UNSENT again
7089 	 * so next call will continue to send it until
7090 	 * such time that we get a CWR, to remove it.
7091 	 */
7092 	sctp_fix_ecn_echo(asoc);
7093 	return (error);
7094 }
7095 
7096 
7097 int
7098 sctp_output(struct sctp_inpcb *inp, struct mbuf *m,
7099      struct sockaddr *addr, struct mbuf *control, struct lwp *l, int flags)
7100 {
7101 	struct sctp_inpcb *t_inp;
7102  	struct sctp_tcb *stcb;
7103 	struct sctp_nets *net;
7104 	struct sctp_association *asoc;
7105 	int create_lock_applied = 0;
7106 	int queue_only, error = 0;
7107 	struct sctp_sndrcvinfo srcv;
7108 	int un_sent = 0;
7109 	int use_rcvinfo = 0;
7110 	t_inp = inp;
7111 	/*  struct route ro;*/
7112 
7113 	queue_only = 0;
7114 	stcb = NULL;
7115 	asoc = NULL;
7116 	net = NULL;
7117 
7118 #ifdef SCTP_DEBUG
7119 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
7120 		printf("USR Send BEGINS\n");
7121 	}
7122 #endif
7123 
7124 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) &&
7125 	    (inp->sctp_flags & SCTP_PCB_FLAGS_ACCEPTING)) {
7126 		/* The listner can NOT send */
7127 		if (control) {
7128 			sctppcbinfo.mbuf_track--;
7129 			sctp_m_freem(control);
7130 			control = NULL;
7131 		}
7132 		sctp_m_freem(m);
7133 		return (EFAULT);
7134 	}
7135 	/* Can't allow a V6 address on a non-v6 socket */
7136 	if (addr) {
7137 		SCTP_ASOC_CREATE_LOCK(inp);
7138 		if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
7139 		    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) {
7140 			/* Should I really unlock ? */
7141 			SCTP_ASOC_CREATE_UNLOCK(inp);
7142 			if (control) {
7143 				sctppcbinfo.mbuf_track--;
7144 				sctp_m_freem(control);
7145 				control = NULL;
7146 			}
7147 			sctp_m_freem(m);
7148 			return (EFAULT);
7149 		}
7150 		create_lock_applied = 1;
7151 		if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) &&
7152 		    (addr->sa_family == AF_INET6)) {
7153 			SCTP_ASOC_CREATE_UNLOCK(inp);
7154 			if (control) {
7155 				sctppcbinfo.mbuf_track--;
7156 				sctp_m_freem(control);
7157 				control = NULL;
7158 			}
7159 			sctp_m_freem(m);
7160 			return (EINVAL);
7161 		}
7162 	}
7163 	if (control) {
7164 		sctppcbinfo.mbuf_track++;
7165 		if (sctp_find_cmsg(SCTP_SNDRCV, (void *)&srcv, control,
7166 				   sizeof(srcv))) {
7167 			if (srcv.sinfo_flags & SCTP_SENDALL) {
7168 				/* its a sendall */
7169 				sctppcbinfo.mbuf_track--;
7170 				sctp_m_freem(control);
7171 				if (create_lock_applied) {
7172 					SCTP_ASOC_CREATE_UNLOCK(inp);
7173 					create_lock_applied = 0;
7174 				}
7175 				return (sctp_sendall(inp, NULL, m, &srcv));
7176 			}
7177 			if (srcv.sinfo_assoc_id) {
7178 				if (inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) {
7179 					SCTP_INP_RLOCK(inp);
7180 					stcb = LIST_FIRST(&inp->sctp_asoc_list);
7181 					if (stcb) {
7182 						SCTP_TCB_LOCK(stcb);
7183 					}
7184 					SCTP_INP_RUNLOCK(inp);
7185 
7186 					if (stcb == NULL) {
7187 						if (create_lock_applied) {
7188 							SCTP_ASOC_CREATE_UNLOCK(inp);
7189 							create_lock_applied = 0;
7190 						}
7191 						sctppcbinfo.mbuf_track--;
7192 						sctp_m_freem(control);
7193 						sctp_m_freem(m);
7194 						return (ENOTCONN);
7195 					}
7196 					net = stcb->asoc.primary_destination;
7197 				} else {
7198 					stcb = sctp_findassociation_ep_asocid(inp, srcv.sinfo_assoc_id);
7199 				}
7200 				/*
7201 				 * Question: Should I error here if the
7202 
7203 				 * assoc_id is no longer valid?
7204 				 * i.e. I can't find it?
7205 				 */
7206 				if ((stcb) &&
7207 				    (addr != NULL)) {
7208 					/* Must locate the net structure */
7209 					if (addr)
7210 						net = sctp_findnet(stcb, addr);
7211 				}
7212 				if (net == NULL)
7213 					net = stcb->asoc.primary_destination;
7214 			}
7215 			use_rcvinfo = 1;
7216 		}
7217 	}
7218 	if (stcb == NULL) {
7219 		if (inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) {
7220 			SCTP_INP_RLOCK(inp);
7221 			stcb = LIST_FIRST(&inp->sctp_asoc_list);
7222 			if (stcb) {
7223 				SCTP_TCB_LOCK(stcb);
7224 			}
7225 			SCTP_INP_RUNLOCK(inp);
7226 			if (stcb == NULL) {
7227 				if (create_lock_applied) {
7228 					SCTP_ASOC_CREATE_UNLOCK(inp);
7229 					create_lock_applied = 0;
7230 				}
7231 				if (control) {
7232 					sctppcbinfo.mbuf_track--;
7233 					sctp_m_freem(control);
7234 					control = NULL;
7235 				}
7236 				sctp_m_freem(m);
7237 				return (ENOTCONN);
7238 			}
7239 			if (addr == NULL) {
7240 				net = stcb->asoc.primary_destination;
7241 			} else {
7242 				net = sctp_findnet(stcb, addr);
7243 				if (net == NULL) {
7244 					net = stcb->asoc.primary_destination;
7245 				}
7246 			}
7247 		} else {
7248 			if (addr != NULL) {
7249 				SCTP_INP_WLOCK(inp);
7250 				SCTP_INP_INCR_REF(inp);
7251 				SCTP_INP_WUNLOCK(inp);
7252 				stcb = sctp_findassociation_ep_addr(&t_inp, addr, &net, NULL, NULL);
7253 				if (stcb == NULL) {
7254 					SCTP_INP_WLOCK(inp);
7255 					SCTP_INP_DECR_REF(inp);
7256 					SCTP_INP_WUNLOCK(inp);
7257 				}
7258 			}
7259 		}
7260 	}
7261 	if ((stcb == NULL) &&
7262 	    (inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE)) {
7263 		if (control) {
7264 			sctppcbinfo.mbuf_track--;
7265 			sctp_m_freem(control);
7266 			control = NULL;
7267 		}
7268 		if (create_lock_applied) {
7269 			SCTP_ASOC_CREATE_UNLOCK(inp);
7270 			create_lock_applied = 0;
7271 		}
7272 		sctp_m_freem(m);
7273 		return (ENOTCONN);
7274 	} else if ((stcb == NULL) &&
7275 		   (addr == NULL)) {
7276 		if (control) {
7277 			sctppcbinfo.mbuf_track--;
7278 			sctp_m_freem(control);
7279 			control = NULL;
7280 		}
7281 		if (create_lock_applied) {
7282 			SCTP_ASOC_CREATE_UNLOCK(inp);
7283 			create_lock_applied = 0;
7284 		}
7285 		sctp_m_freem(m);
7286 		return (ENOENT);
7287 	} else if (stcb == NULL) {
7288 		/* UDP mode, we must go ahead and start the INIT process */
7289 		if ((use_rcvinfo) && (srcv.sinfo_flags & SCTP_ABORT)) {
7290 			/* Strange user to do this */
7291 			if (control) {
7292 				sctppcbinfo.mbuf_track--;
7293 				sctp_m_freem(control);
7294 				control = NULL;
7295 			}
7296 			if (create_lock_applied) {
7297 				SCTP_ASOC_CREATE_UNLOCK(inp);
7298 				create_lock_applied = 0;
7299 			}
7300 			sctp_m_freem(m);
7301 			return (ENOENT);
7302 		}
7303 		stcb = sctp_aloc_assoc(inp, addr, 1, &error, 0);
7304 		if (stcb == NULL) {
7305 			if (control) {
7306 				sctppcbinfo.mbuf_track--;
7307 				sctp_m_freem(control);
7308 				control = NULL;
7309 			}
7310 			if (create_lock_applied) {
7311 				SCTP_ASOC_CREATE_UNLOCK(inp);
7312 				create_lock_applied = 0;
7313 			}
7314 			sctp_m_freem(m);
7315 			return (error);
7316 		}
7317 		if (create_lock_applied) {
7318 			SCTP_ASOC_CREATE_UNLOCK(inp);
7319 			create_lock_applied = 0;
7320 		} else {
7321 			printf("Huh-1, create lock should have been applied!\n");
7322 		}
7323 		queue_only = 1;
7324 		asoc = &stcb->asoc;
7325 		asoc->state = SCTP_STATE_COOKIE_WAIT;
7326 		SCTP_GETTIME_TIMEVAL(&asoc->time_entered);
7327 		if (control) {
7328 			/* see if a init structure exists in cmsg headers */
7329 			struct sctp_initmsg initm;
7330 			int i;
7331 			if (sctp_find_cmsg(SCTP_INIT, (void *)&initm, control,
7332 					   sizeof(initm))) {
7333 				/* we have an INIT override of the default */
7334 				if (initm.sinit_max_attempts)
7335 					asoc->max_init_times = initm.sinit_max_attempts;
7336 				if (initm.sinit_num_ostreams)
7337 					asoc->pre_open_streams = initm.sinit_num_ostreams;
7338 				if (initm.sinit_max_instreams)
7339 					asoc->max_inbound_streams = initm.sinit_max_instreams;
7340 				if (initm.sinit_max_init_timeo)
7341 					asoc->initial_init_rto_max = initm.sinit_max_init_timeo;
7342 			}
7343 			if (asoc->streamoutcnt < asoc->pre_open_streams) {
7344 				/* Default is NOT correct */
7345 #ifdef SCTP_DEBUG
7346 				if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
7347 					printf("Ok, defout:%d pre_open:%d\n",
7348 					       asoc->streamoutcnt, asoc->pre_open_streams);
7349 				}
7350 #endif
7351 				free(asoc->strmout, M_PCB);
7352 				asoc->strmout = NULL;
7353 				asoc->streamoutcnt = asoc->pre_open_streams;
7354 				asoc->strmout = malloc(asoc->streamoutcnt *
7355 				       sizeof(struct sctp_stream_out), M_PCB,
7356 				       M_WAIT);
7357 				for (i = 0; i < asoc->streamoutcnt; i++) {
7358 					/*
7359 					 * inbound side must be set to 0xffff,
7360 					 * also NOTE when we get the INIT-ACK
7361 					 * back (for INIT sender) we MUST
7362 					 * reduce the count (streamoutcnt) but
7363 					 * first check if we sent to any of the
7364 					 * upper streams that were dropped (if
7365 					 * some were). Those that were dropped
7366 					 * must be notified to the upper layer
7367 					 * as failed to send.
7368 					 */
7369 					asoc->strmout[i].next_sequence_sent = 0x0;
7370 					TAILQ_INIT(&asoc->strmout[i].outqueue);
7371 					asoc->strmout[i].stream_no = i;
7372 					asoc->strmout[i].next_spoke.tqe_next = 0;
7373 					asoc->strmout[i].next_spoke.tqe_prev = 0;
7374 				}
7375 			}
7376 		}
7377 		sctp_send_initiate(inp, stcb);
7378 		/*
7379 		 * we may want to dig in after this call and adjust the MTU
7380 		 * value. It defaulted to 1500 (constant) but the ro structure
7381 		 * may now have an update and thus we may need to change it
7382 		 * BEFORE we append the message.
7383 		 */
7384 		net = stcb->asoc.primary_destination;
7385 	} else {
7386 		if (create_lock_applied) {
7387 			SCTP_ASOC_CREATE_UNLOCK(inp);
7388 			create_lock_applied = 0;
7389 		}
7390 		asoc = &stcb->asoc;
7391 		if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
7392 		    (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)) {
7393 			queue_only = 1;
7394 		}
7395 		if ((SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
7396 		    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
7397 		    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
7398 		    (asoc->state & SCTP_STATE_SHUTDOWN_PENDING)) {
7399 			if (control) {
7400 				sctppcbinfo.mbuf_track--;
7401 				sctp_m_freem(control);
7402 				control = NULL;
7403 			}
7404 			if ((use_rcvinfo) &&
7405 			    (srcv.sinfo_flags & SCTP_ABORT)) {
7406 				sctp_msg_append(stcb, net, m, &srcv, flags);
7407 				error = 0;
7408 			} else {
7409 				if (m)
7410 					sctp_m_freem(m);
7411 				error = ECONNRESET;
7412 			}
7413 			SCTP_TCB_UNLOCK(stcb);
7414 			return (error);
7415 		}
7416 	}
7417 	if (create_lock_applied) {
7418 		/* we should never hit here with the create lock applied
7419 		 *
7420 		 */
7421 		SCTP_ASOC_CREATE_UNLOCK(inp);
7422 		create_lock_applied = 0;
7423 	}
7424 
7425 
7426 	if (use_rcvinfo == 0) {
7427 		srcv = stcb->asoc.def_send;
7428 	}
7429 #ifdef SCTP_DEBUG
7430 	else {
7431 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT5) {
7432 			printf("stream:%d\n", srcv.sinfo_stream);
7433 			printf("flags:%x\n", (u_int)srcv.sinfo_flags);
7434 			printf("ppid:%d\n", srcv.sinfo_ppid);
7435 			printf("context:%d\n", srcv.sinfo_context);
7436 		}
7437 	}
7438 #endif
7439 	if (control) {
7440 		sctppcbinfo.mbuf_track--;
7441 		sctp_m_freem(control);
7442 		control = NULL;
7443 	}
7444 	if (net && ((srcv.sinfo_flags & SCTP_ADDR_OVER))) {
7445 		/* we take the override or the unconfirmed */
7446 		;
7447 	} else {
7448 		net = stcb->asoc.primary_destination;
7449 	}
7450 	if ((error = sctp_msg_append(stcb, net, m, &srcv, flags))) {
7451 		SCTP_TCB_UNLOCK(stcb);
7452 		return (error);
7453 	}
7454 	if (net->flight_size > net->cwnd) {
7455 		sctp_pegs[SCTP_SENDTO_FULL_CWND]++;
7456 		queue_only = 1;
7457  	} else if (asoc->ifp_had_enobuf) {
7458 		sctp_pegs[SCTP_QUEONLY_BURSTLMT]++;
7459 	 	queue_only = 1;
7460  	} else {
7461 		un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
7462 			   ((stcb->asoc.chunks_on_out_queue - stcb->asoc.total_flight_count) * sizeof(struct sctp_data_chunk)) +
7463 			   SCTP_MED_OVERHEAD);
7464 
7465 		if (((inp->sctp_flags & SCTP_PCB_FLAGS_NODELAY) == 0) &&
7466 		    (stcb->asoc.total_flight > 0) &&
7467 		    (un_sent < (int)stcb->asoc.smallest_mtu)
7468 			) {
7469 
7470 			/* Ok, Nagle is set on and we have
7471 			 * data outstanding. Don't send anything
7472 			 * and let the SACK drive out the data.
7473 			 */
7474 			sctp_pegs[SCTP_NAGLE_NOQ]++;
7475 			queue_only = 1;
7476 		} else {
7477 			sctp_pegs[SCTP_NAGLE_OFF]++;
7478 		}
7479 	}
7480 	if ((queue_only == 0) && stcb->asoc.peers_rwnd) {
7481 		/* we can attempt to send too.*/
7482 #ifdef SCTP_DEBUG
7483 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
7484 			printf("USR Send calls sctp_chunk_output\n");
7485 		}
7486 #endif
7487 #ifdef SCTP_AUDITING_ENABLED
7488 		sctp_audit_log(0xC0, 1);
7489 		sctp_auditing(6, inp, stcb, net);
7490 #endif
7491 		sctp_pegs[SCTP_OUTPUT_FRM_SND]++;
7492 		sctp_chunk_output(inp, stcb, 0);
7493 #ifdef SCTP_AUDITING_ENABLED
7494 		sctp_audit_log(0xC0, 2);
7495 		sctp_auditing(7, inp, stcb, net);
7496 #endif
7497 
7498 	}
7499 #ifdef SCTP_DEBUG
7500 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
7501 		printf("USR Send complete qo:%d prw:%d\n", queue_only, stcb->asoc.peers_rwnd);
7502 	}
7503 #endif
7504 	SCTP_TCB_UNLOCK(stcb);
7505 	return (0);
7506 }
7507 
7508 void
7509 send_forward_tsn(struct sctp_tcb *stcb,
7510 		 struct sctp_association *asoc)
7511 {
7512 	struct sctp_tmit_chunk *chk;
7513 	struct sctp_forward_tsn_chunk *fwdtsn;
7514 
7515 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
7516 		if (chk->rec.chunk_id == SCTP_FORWARD_CUM_TSN) {
7517 			/* mark it to unsent */
7518 			chk->sent = SCTP_DATAGRAM_UNSENT;
7519 			chk->snd_count = 0;
7520 			/* Do we correct its output location? */
7521 			if (chk->whoTo != asoc->primary_destination) {
7522 				sctp_free_remote_addr(chk->whoTo);
7523 				chk->whoTo = asoc->primary_destination;
7524 				chk->whoTo->ref_count++;
7525 			}
7526 			goto sctp_fill_in_rest;
7527 		}
7528 	}
7529 	/* Ok if we reach here we must build one */
7530 	chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
7531 	if (chk == NULL) {
7532 		return;
7533 	}
7534 	sctppcbinfo.ipi_count_chunk++;
7535 	sctppcbinfo.ipi_gencnt_chunk++;
7536 	chk->rec.chunk_id = SCTP_FORWARD_CUM_TSN;
7537 	chk->asoc = asoc;
7538 	MGETHDR(chk->data, M_DONTWAIT, MT_DATA);
7539 	if (chk->data == NULL) {
7540 		chk->whoTo->ref_count--;
7541 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
7542 		sctppcbinfo.ipi_count_chunk--;
7543 		if ((int)sctppcbinfo.ipi_count_chunk < 0) {
7544 			panic("Chunk count is negative");
7545 		}
7546 		sctppcbinfo.ipi_gencnt_chunk++;
7547 		return;
7548 	}
7549 	chk->data->m_data += SCTP_MIN_OVERHEAD;
7550 	chk->sent = SCTP_DATAGRAM_UNSENT;
7551 	chk->snd_count = 0;
7552 	chk->whoTo = asoc->primary_destination;
7553 	chk->whoTo->ref_count++;
7554 	TAILQ_INSERT_TAIL(&asoc->control_send_queue, chk, sctp_next);
7555 	asoc->ctrl_queue_cnt++;
7556  sctp_fill_in_rest:
7557 	/* Here we go through and fill out the part that
7558 	 * deals with stream/seq of the ones we skip.
7559 	 */
7560 	chk->data->m_pkthdr.len = chk->data->m_len = 0;
7561 	{
7562 		struct sctp_tmit_chunk *at, *tp1, *last;
7563 		struct sctp_strseq *strseq;
7564 		unsigned int cnt_of_space, i, ovh;
7565 		unsigned int space_needed;
7566 		unsigned int cnt_of_skipped = 0;
7567 		TAILQ_FOREACH(at, &asoc->sent_queue, sctp_next) {
7568 			if (at->sent != SCTP_FORWARD_TSN_SKIP) {
7569 				/* no more to look at */
7570 				break;
7571 			}
7572 			if (at->rec.data.rcv_flags & SCTP_DATA_UNORDERED) {
7573 				/* We don't report these */
7574 				continue;
7575 			}
7576 			cnt_of_skipped++;
7577 		}
7578 		space_needed = (sizeof(struct sctp_forward_tsn_chunk) +
7579 				(cnt_of_skipped * sizeof(struct sctp_strseq)));
7580 		if ((M_TRAILINGSPACE(chk->data) < (int)space_needed) &&
7581 		    ((chk->data->m_flags & M_EXT) == 0)) {
7582 			/* Need a M_EXT, get one and move
7583 			 * fwdtsn to data area.
7584 			 */
7585 			MCLGET(chk->data, M_DONTWAIT);
7586 		}
7587 		cnt_of_space = M_TRAILINGSPACE(chk->data);
7588 
7589 		if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
7590 			ovh = SCTP_MIN_OVERHEAD;
7591 		} else {
7592 			ovh = SCTP_MIN_V4_OVERHEAD;
7593 		}
7594 		if (cnt_of_space > (asoc->smallest_mtu-ovh)) {
7595 			/* trim to a mtu size */
7596 			cnt_of_space = asoc->smallest_mtu - ovh;
7597 		}
7598 		if (cnt_of_space < space_needed) {
7599 			/* ok we must trim down the chunk by lowering
7600 			 * the advance peer ack point.
7601 			 */
7602 			cnt_of_skipped = (cnt_of_space-
7603 					  ((sizeof(struct sctp_forward_tsn_chunk))/
7604  					    sizeof(struct sctp_strseq)));
7605 			/* Go through and find the TSN that
7606 			 * will be the one we report.
7607 			 */
7608 			at = TAILQ_FIRST(&asoc->sent_queue);
7609 			for (i = 0; i < cnt_of_skipped; i++) {
7610 				tp1 = TAILQ_NEXT(at, sctp_next);
7611 				at = tp1;
7612 			}
7613 			last = at;
7614 			/* last now points to last one I can report, update peer ack point */
7615 			asoc->advanced_peer_ack_point = last->rec.data.TSN_seq;
7616 			space_needed -= (cnt_of_skipped * sizeof(struct sctp_strseq));
7617 		}
7618 		chk->send_size = space_needed;
7619 		/* Setup the chunk */
7620 		fwdtsn = mtod(chk->data, struct sctp_forward_tsn_chunk *);
7621 		fwdtsn->ch.chunk_length = htons(chk->send_size);
7622 		fwdtsn->ch.chunk_flags = 0;
7623 		fwdtsn->ch.chunk_type = SCTP_FORWARD_CUM_TSN;
7624 		fwdtsn->new_cumulative_tsn = htonl(asoc->advanced_peer_ack_point);
7625 		chk->send_size = (sizeof(struct sctp_forward_tsn_chunk) +
7626 				  (cnt_of_skipped * sizeof(struct sctp_strseq)));
7627 		chk->data->m_pkthdr.len = chk->data->m_len = chk->send_size;
7628 		fwdtsn++;
7629 		/* Move pointer to after the fwdtsn and transfer to
7630 		 * the strseq pointer.
7631 		 */
7632 		strseq = (struct sctp_strseq *)fwdtsn;
7633 		/*
7634 		 * Now populate the strseq list. This is done blindly
7635 		 * without pulling out duplicate stream info. This is
7636 		 * inefficent but won't harm the process since the peer
7637 		 * will look at these in sequence and will thus release
7638 		 * anything. It could mean we exceed the PMTU and chop
7639 		 * off some that we could have included.. but this is
7640 		 * unlikely (aka 1432/4 would mean 300+ stream seq's would
7641 		 * have to be reported in one FWD-TSN. With a bit of work
7642 		 * we can later FIX this to optimize and pull out duplcates..
7643 		 * but it does add more overhead. So for now... not!
7644 		 */
7645 		at = TAILQ_FIRST(&asoc->sent_queue);
7646 		for (i = 0; i < cnt_of_skipped; i++) {
7647 			tp1 = TAILQ_NEXT(at, sctp_next);
7648 			if (at->rec.data.rcv_flags & SCTP_DATA_UNORDERED) {
7649 				/* We don't report these */
7650 				i--;
7651 				at = tp1;
7652 				continue;
7653 			}
7654 			strseq->stream = ntohs(at->rec.data.stream_number);
7655 			strseq->sequence = ntohs(at->rec.data.stream_seq);
7656 			strseq++;
7657 			at = tp1;
7658 		}
7659 	}
7660 	return;
7661 
7662 }
7663 
7664 void
7665 sctp_send_sack(struct sctp_tcb *stcb)
7666 {
7667 	/*
7668 	 * Queue up a SACK in the control queue. We must first check to
7669 	 * see if a SACK is somehow on the control queue. If so, we will
7670 	 * take and remove the old one.
7671 	 */
7672 	struct sctp_association *asoc;
7673 	struct sctp_tmit_chunk *chk, *a_chk;
7674 	struct sctp_sack_chunk *sack;
7675 	struct sctp_gap_ack_block *gap_descriptor;
7676 	uint32_t *dup;
7677 	int start;
7678 	unsigned int i, maxi, seeing_ones, m_size;
7679 	unsigned int num_gap_blocks, space;
7680 
7681 	start = maxi = 0;
7682 	seeing_ones = 1;
7683 	a_chk = NULL;
7684 	asoc = &stcb->asoc;
7685 	if (asoc->last_data_chunk_from == NULL) {
7686 		/* Hmm we never received anything */
7687 		return;
7688 	}
7689 	sctp_set_rwnd(stcb, asoc);
7690 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
7691 		if (chk->rec.chunk_id == SCTP_SELECTIVE_ACK) {
7692 			/* Hmm, found a sack already on queue, remove it */
7693 			TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
7694 			asoc->ctrl_queue_cnt++;
7695 			a_chk = chk;
7696 			if (a_chk->data)
7697 				sctp_m_freem(a_chk->data);
7698 			a_chk->data = NULL;
7699 			sctp_free_remote_addr(a_chk->whoTo);
7700 			a_chk->whoTo = NULL;
7701 			break;
7702 		}
7703 	}
7704 	if (a_chk == NULL) {
7705 		a_chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
7706 		if (a_chk == NULL) {
7707 			/* No memory so we drop the idea, and set a timer */
7708 			sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
7709 					stcb->sctp_ep, stcb, NULL);
7710 			sctp_timer_start(SCTP_TIMER_TYPE_RECV,
7711 					 stcb->sctp_ep, stcb, NULL);
7712 			return;
7713 		}
7714 		sctppcbinfo.ipi_count_chunk++;
7715 		sctppcbinfo.ipi_gencnt_chunk++;
7716 		a_chk->rec.chunk_id = SCTP_SELECTIVE_ACK;
7717 	}
7718 	a_chk->asoc = asoc;
7719 	a_chk->snd_count = 0;
7720 	a_chk->send_size = 0;	/* fill in later */
7721 	a_chk->sent = SCTP_DATAGRAM_UNSENT;
7722 	m_size = (asoc->mapping_array_size << 3);
7723 
7724 	if ((asoc->numduptsns) ||
7725 	    (asoc->last_data_chunk_from->dest_state & SCTP_ADDR_NOT_REACHABLE)
7726 		) {
7727 		/* Ok, we have some duplicates or the destination for the
7728 		 * sack is unreachable, lets see if we can select an alternate
7729 		 * than asoc->last_data_chunk_from
7730 		 */
7731 		if ((!(asoc->last_data_chunk_from->dest_state &
7732 		      SCTP_ADDR_NOT_REACHABLE)) &&
7733 		    (asoc->used_alt_onsack > 2)) {
7734 			/* We used an alt last time, don't this time */
7735 			a_chk->whoTo = NULL;
7736 		} else {
7737 			asoc->used_alt_onsack++;
7738 			a_chk->whoTo = sctp_find_alternate_net(stcb, asoc->last_data_chunk_from);
7739 		}
7740 		if (a_chk->whoTo == NULL) {
7741 			/* Nope, no alternate */
7742 			a_chk->whoTo = asoc->last_data_chunk_from;
7743 			asoc->used_alt_onsack = 0;
7744 		}
7745 	} else {
7746 		/* No duplicates so we use the last
7747 		 * place we received data from.
7748 		 */
7749 #ifdef SCTP_DEBUG
7750 		if (asoc->last_data_chunk_from == NULL) {
7751 			printf("Huh, last_data_chunk_from is null when we want to sack??\n");
7752 		}
7753 #endif
7754 		asoc->used_alt_onsack = 0;
7755 		a_chk->whoTo = asoc->last_data_chunk_from;
7756 	}
7757 	if (a_chk->whoTo)
7758 		a_chk->whoTo->ref_count++;
7759 
7760 	/* Ok now lets formulate a MBUF with our sack */
7761 	MGETHDR(a_chk->data, M_DONTWAIT, MT_DATA);
7762 	if ((a_chk->data == NULL) ||
7763 	    (a_chk->whoTo == NULL)) {
7764 		/* rats, no mbuf memory */
7765 		if (a_chk->data) {
7766 			/* was a problem with the destination */
7767 			sctp_m_freem(a_chk->data);
7768 			a_chk->data = NULL;
7769 		}
7770 		a_chk->whoTo->ref_count--;
7771 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, a_chk);
7772 		sctppcbinfo.ipi_count_chunk--;
7773 		if ((int)sctppcbinfo.ipi_count_chunk < 0) {
7774 			panic("Chunk count is negative");
7775 		}
7776 		sctppcbinfo.ipi_gencnt_chunk++;
7777 		sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
7778 				stcb->sctp_ep, stcb, NULL);
7779 		sctp_timer_start(SCTP_TIMER_TYPE_RECV,
7780 				 stcb->sctp_ep, stcb, NULL);
7781 		return;
7782 	}
7783 	/* First count the number of gap ack blocks we need */
7784 	if (asoc->highest_tsn_inside_map == asoc->cumulative_tsn) {
7785 		/* We know if there are none above the cum-ack we
7786 		 * have everything with NO gaps
7787 		 */
7788 		num_gap_blocks = 0;
7789 	} else {
7790 		/* Ok we must count how many gaps we
7791 		 * have.
7792 		 */
7793 		num_gap_blocks = 0;
7794 		if (asoc->highest_tsn_inside_map >= asoc->mapping_array_base_tsn) {
7795 			maxi = (asoc->highest_tsn_inside_map - asoc->mapping_array_base_tsn);
7796 		} else {
7797 			maxi = (asoc->highest_tsn_inside_map  + (MAX_TSN - asoc->mapping_array_base_tsn) + 1);
7798 		}
7799 		if (maxi > m_size) {
7800 			/* impossible but who knows, someone is playing with us  :> */
7801 #ifdef SCTP_DEBUG
7802 			printf("GAK maxi:%d  > m_size:%d came out higher than allowed htsn:%u base:%u cumack:%u\n",
7803 			       maxi,
7804 			       m_size,
7805 			       asoc->highest_tsn_inside_map,
7806 			       asoc->mapping_array_base_tsn,
7807 			       asoc->cumulative_tsn
7808 			       );
7809 #endif
7810 			num_gap_blocks = 0;
7811 			goto no_gaps_now;
7812 		}
7813 		if (asoc->cumulative_tsn >= asoc->mapping_array_base_tsn) {
7814 			start = (asoc->cumulative_tsn - asoc->mapping_array_base_tsn);
7815 		} else {
7816 			/* Set it so we start at 0 */
7817 			start = -1;
7818 		}
7819 		/* Ok move start up one to look at the NEXT past the cum-ack */
7820 		start++;
7821 		for (i = start; i <= maxi; i++) {
7822 			if (seeing_ones) {
7823 				/* while seeing ones I must
7824 				 * transition back to 0 before
7825 				 * finding the next gap and
7826 				 * counting the segment.
7827 				 */
7828 				if (SCTP_IS_TSN_PRESENT(asoc->mapping_array, i) == 0) {
7829 					seeing_ones = 0;
7830 				}
7831 			} else {
7832 				if (SCTP_IS_TSN_PRESENT(asoc->mapping_array, i)) {
7833 					seeing_ones = 1;
7834 					num_gap_blocks++;
7835 				}
7836 			}
7837 		}
7838 	no_gaps_now:
7839 		if (num_gap_blocks == 0) {
7840 			/*
7841 			 * Traveled all of the bits and NO one,
7842 			 * must have reneged
7843 			 */
7844 			if (compare_with_wrap(asoc->cumulative_tsn, asoc->highest_tsn_inside_map, MAX_TSN)) {
7845 			   asoc->highest_tsn_inside_map = asoc->cumulative_tsn;
7846 #ifdef SCTP_MAP_LOGGING
7847 			   sctp_log_map(0, 4, asoc->highest_tsn_inside_map, SCTP_MAP_SLIDE_RESULT);
7848 #endif
7849 			}
7850 		}
7851 	}
7852 
7853 	/* Now calculate the space needed */
7854 	space = (sizeof(struct sctp_sack_chunk) +
7855 		 (num_gap_blocks * sizeof(struct sctp_gap_ack_block)) +
7856 		 (asoc->numduptsns * sizeof(int32_t))
7857 		);
7858 	if (space > (asoc->smallest_mtu-SCTP_MAX_OVERHEAD)) {
7859 		/* Reduce the size of the sack to fit */
7860 		int calc, fit;
7861 		calc = (asoc->smallest_mtu - SCTP_MAX_OVERHEAD);
7862 		calc -= sizeof(struct sctp_gap_ack_block);
7863 		fit = calc/sizeof(struct sctp_gap_ack_block);
7864 		if (fit > (int)num_gap_blocks) {
7865 			/* discard some dups */
7866 			asoc->numduptsns = (fit - num_gap_blocks);
7867 		} else {
7868 			/* discard all dups and some gaps */
7869 			num_gap_blocks = fit;
7870 			asoc->numduptsns = 0;
7871 		}
7872 		/* recalc space */
7873 		space = (sizeof(struct sctp_sack_chunk) +
7874 			 (num_gap_blocks * sizeof(struct sctp_gap_ack_block)) +
7875 			 (asoc->numduptsns * sizeof(int32_t))
7876 			);
7877 
7878 	}
7879 
7880 	if ((space+SCTP_MIN_OVERHEAD) > MHLEN) {
7881 		/* We need a cluster */
7882 		MCLGET(a_chk->data, M_DONTWAIT);
7883 		if ((a_chk->data->m_flags & M_EXT) != M_EXT) {
7884 			/* can't get a cluster
7885 			 * give up and try later.
7886 			 */
7887 			if (a_chk->data)
7888 				sctp_m_freem(a_chk->data);
7889 			a_chk->data = NULL;
7890 			a_chk->whoTo->ref_count--;
7891 			SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, a_chk);
7892 			sctppcbinfo.ipi_count_chunk--;
7893 			if ((int)sctppcbinfo.ipi_count_chunk < 0) {
7894 				panic("Chunk count is negative");
7895 			}
7896 			sctppcbinfo.ipi_gencnt_chunk++;
7897 			sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
7898 					stcb->sctp_ep, stcb, NULL);
7899 			sctp_timer_start(SCTP_TIMER_TYPE_RECV,
7900 					 stcb->sctp_ep, stcb, NULL);
7901 			return;
7902 		}
7903 	}
7904 
7905 	/* ok, lets go through and fill it in */
7906 	a_chk->data->m_data += SCTP_MIN_OVERHEAD;
7907 	sack = mtod(a_chk->data, struct sctp_sack_chunk *);
7908 	sack->ch.chunk_type = SCTP_SELECTIVE_ACK;
7909 	sack->ch.chunk_flags = asoc->receiver_nonce_sum & SCTP_SACK_NONCE_SUM;
7910 	sack->sack.cum_tsn_ack = htonl(asoc->cumulative_tsn);
7911 	sack->sack.a_rwnd = htonl(asoc->my_rwnd);
7912 	asoc->my_last_reported_rwnd = asoc->my_rwnd;
7913 	sack->sack.num_gap_ack_blks = htons(num_gap_blocks);
7914 	sack->sack.num_dup_tsns = htons(asoc->numduptsns);
7915 
7916 	a_chk->send_size = (sizeof(struct sctp_sack_chunk) +
7917 			    (num_gap_blocks * sizeof(struct sctp_gap_ack_block)) +
7918 			    (asoc->numduptsns * sizeof(int32_t)));
7919 	a_chk->data->m_pkthdr.len = a_chk->data->m_len = a_chk->send_size;
7920 	sack->ch.chunk_length = htons(a_chk->send_size);
7921 
7922 	gap_descriptor = (struct sctp_gap_ack_block *)((vaddr_t)sack + sizeof(struct sctp_sack_chunk));
7923 	seeing_ones = 0;
7924 	for (i = start; i <= maxi; i++) {
7925 		if (num_gap_blocks == 0) {
7926 			break;
7927 		}
7928 		if (seeing_ones) {
7929 			/* while seeing Ones I must
7930 			 * transition back to 0 before
7931 			 * finding the next gap
7932 			 */
7933 			if (SCTP_IS_TSN_PRESENT(asoc->mapping_array, i) == 0) {
7934 				gap_descriptor->end = htons(((uint16_t)(i-start)));
7935 				gap_descriptor++;
7936 				seeing_ones = 0;
7937 				num_gap_blocks--;
7938 			}
7939 		} else {
7940 			if (SCTP_IS_TSN_PRESENT(asoc->mapping_array, i)) {
7941 				gap_descriptor->start = htons(((uint16_t)(i+1-start)));
7942 				/* advance struct to next pointer */
7943 				seeing_ones = 1;
7944 			}
7945 		}
7946 	}
7947 	if (num_gap_blocks) {
7948 		/* special case where the array is all 1's
7949 		 * to the end of the array.
7950 		 */
7951 		gap_descriptor->end = htons(((uint16_t)((i-start))));
7952 		gap_descriptor++;
7953 	}
7954 	/* now we must add any dups we are going to report. */
7955 	if (asoc->numduptsns) {
7956 		dup = (uint32_t *)gap_descriptor;
7957 		for (i = 0; i < asoc->numduptsns; i++) {
7958 			*dup = htonl(asoc->dup_tsns[i]);
7959 			dup++;
7960 		}
7961 		asoc->numduptsns = 0;
7962 	}
7963 	/* now that the chunk is prepared queue it to the control
7964 	 * chunk queue.
7965 	 */
7966 	TAILQ_INSERT_TAIL(&asoc->control_send_queue, a_chk, sctp_next);
7967 	asoc->ctrl_queue_cnt++;
7968 	sctp_pegs[SCTP_PEG_SACKS_SENT]++;
7969 	return;
7970 }
7971 
7972 void
7973 sctp_send_abort_tcb(struct sctp_tcb *stcb, struct mbuf *operr)
7974 {
7975 	struct mbuf *m_abort;
7976 	struct sctp_abort_msg *abort_m;
7977 	int sz;
7978 	abort_m = NULL;
7979 	MGETHDR(m_abort, M_DONTWAIT, MT_HEADER);
7980 	if (m_abort == NULL) {
7981 		/* no mbuf's */
7982 		return;
7983 	}
7984 	m_abort->m_data += SCTP_MIN_OVERHEAD;
7985 	abort_m = mtod(m_abort, struct sctp_abort_msg *);
7986 	m_abort->m_len = sizeof(struct sctp_abort_msg);
7987 	m_abort->m_next = operr;
7988 	sz = 0;
7989 	if (operr) {
7990 		struct mbuf *n;
7991 		n = operr;
7992 		while (n) {
7993 			sz += n->m_len;
7994 			n = n->m_next;
7995 		}
7996 	}
7997 	abort_m->msg.ch.chunk_type = SCTP_ABORT_ASSOCIATION;
7998 	abort_m->msg.ch.chunk_flags = 0;
7999 	abort_m->msg.ch.chunk_length = htons(sizeof(struct sctp_abort_chunk) +
8000 					     sz);
8001 	abort_m->sh.src_port = stcb->sctp_ep->sctp_lport;
8002 	abort_m->sh.dest_port = stcb->rport;
8003 	abort_m->sh.v_tag = htonl(stcb->asoc.peer_vtag);
8004 	abort_m->sh.checksum = 0;
8005 	m_abort->m_pkthdr.len = m_abort->m_len + sz;
8006 	m_reset_rcvif(m_abort);
8007 	sctp_lowlevel_chunk_output(stcb->sctp_ep, stcb,
8008 	    stcb->asoc.primary_destination,
8009 	    rtcache_getdst(&stcb->asoc.primary_destination->ro),
8010 	    m_abort, 1, 0, NULL, 0);
8011 }
8012 
8013 int
8014 sctp_send_shutdown_complete(struct sctp_tcb *stcb,
8015 			    struct sctp_nets *net)
8016 
8017 {
8018 	/* formulate and SEND a SHUTDOWN-COMPLETE */
8019 	struct mbuf *m_shutdown_comp;
8020 	struct sctp_shutdown_complete_msg *comp_cp;
8021 
8022 	m_shutdown_comp = NULL;
8023 	MGETHDR(m_shutdown_comp, M_DONTWAIT, MT_HEADER);
8024 	if (m_shutdown_comp == NULL) {
8025 		/* no mbuf's */
8026 		return (-1);
8027 	}
8028 	m_shutdown_comp->m_data += sizeof(struct ip6_hdr);
8029 	comp_cp = mtod(m_shutdown_comp, struct sctp_shutdown_complete_msg *);
8030 	comp_cp->shut_cmp.ch.chunk_type = SCTP_SHUTDOWN_COMPLETE;
8031 	comp_cp->shut_cmp.ch.chunk_flags = 0;
8032 	comp_cp->shut_cmp.ch.chunk_length = htons(sizeof(struct sctp_shutdown_complete_chunk));
8033 	comp_cp->sh.src_port = stcb->sctp_ep->sctp_lport;
8034 	comp_cp->sh.dest_port = stcb->rport;
8035 	comp_cp->sh.v_tag = htonl(stcb->asoc.peer_vtag);
8036 	comp_cp->sh.checksum = 0;
8037 
8038 	m_shutdown_comp->m_pkthdr.len = m_shutdown_comp->m_len = sizeof(struct sctp_shutdown_complete_msg);
8039 	m_reset_rcvif(m_shutdown_comp);
8040 	sctp_lowlevel_chunk_output(stcb->sctp_ep, stcb, net,
8041 	    rtcache_getdst(&net->ro), m_shutdown_comp,
8042 	    1, 0, NULL, 0);
8043 	if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
8044 	    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
8045 		stcb->sctp_ep->sctp_flags &= ~SCTP_PCB_FLAGS_CONNECTED;
8046 		stcb->sctp_ep->sctp_socket->so_snd.sb_cc = 0;
8047 		soisdisconnected(stcb->sctp_ep->sctp_socket);
8048 	}
8049 	return (0);
8050 }
8051 
8052 int
8053 sctp_send_shutdown_complete2(struct mbuf *m, int iphlen, struct sctphdr *sh)
8054 {
8055 	/* formulate and SEND a SHUTDOWN-COMPLETE */
8056 	struct mbuf *mout;
8057 	struct ip *iph, *iph_out;
8058 	struct ip6_hdr *ip6, *ip6_out;
8059 	int offset_out;
8060 	struct sctp_shutdown_complete_msg *comp_cp;
8061 
8062 	MGETHDR(mout, M_DONTWAIT, MT_HEADER);
8063 	if (mout == NULL) {
8064 		/* no mbuf's */
8065 		return (-1);
8066 	}
8067 	iph = mtod(m, struct ip *);
8068 	iph_out = NULL;
8069 	ip6_out = NULL;
8070 	offset_out = 0;
8071 	if (iph->ip_v == IPVERSION) {
8072 		mout->m_len = sizeof(struct ip) +
8073 		    sizeof(struct sctp_shutdown_complete_msg);
8074 		mout->m_next = NULL;
8075 		iph_out = mtod(mout, struct ip *);
8076 
8077 		/* Fill in the IP header for the ABORT */
8078 		iph_out->ip_v = IPVERSION;
8079 		iph_out->ip_hl = (sizeof(struct ip)/4);
8080 		iph_out->ip_tos = (u_char)0;
8081 		iph_out->ip_id = 0;
8082 		iph_out->ip_off = 0;
8083 		iph_out->ip_ttl = MAXTTL;
8084 		iph_out->ip_p = IPPROTO_SCTP;
8085 		iph_out->ip_src.s_addr = iph->ip_dst.s_addr;
8086 		iph_out->ip_dst.s_addr = iph->ip_src.s_addr;
8087 
8088 		/* let IP layer calculate this */
8089 		iph_out->ip_sum = 0;
8090 		offset_out += sizeof(*iph_out);
8091 		comp_cp = (struct sctp_shutdown_complete_msg *)(
8092 		    (vaddr_t)iph_out + offset_out);
8093 	} else if (iph->ip_v == (IPV6_VERSION >> 4)) {
8094 		ip6 = (struct ip6_hdr *)iph;
8095 		mout->m_len = sizeof(struct ip6_hdr) +
8096 		    sizeof(struct sctp_shutdown_complete_msg);
8097 		mout->m_next = NULL;
8098 		ip6_out = mtod(mout, struct ip6_hdr *);
8099 
8100 		/* Fill in the IPv6 header for the ABORT */
8101 		ip6_out->ip6_flow = ip6->ip6_flow;
8102 		ip6_out->ip6_hlim = ip6_defhlim;
8103 		ip6_out->ip6_nxt = IPPROTO_SCTP;
8104 		ip6_out->ip6_src = ip6->ip6_dst;
8105 		ip6_out->ip6_dst = ip6->ip6_src;
8106  		ip6_out->ip6_plen = mout->m_len;
8107 		offset_out += sizeof(*ip6_out);
8108 		comp_cp = (struct sctp_shutdown_complete_msg *)(
8109 		    (vaddr_t)ip6_out + offset_out);
8110 	} else {
8111 		/* Currently not supported. */
8112 		return (-1);
8113 	}
8114 
8115 	/* Now copy in and fill in the ABORT tags etc. */
8116 	comp_cp->sh.src_port = sh->dest_port;
8117 	comp_cp->sh.dest_port = sh->src_port;
8118 	comp_cp->sh.checksum = 0;
8119 	comp_cp->sh.v_tag = sh->v_tag;
8120 	comp_cp->shut_cmp.ch.chunk_flags = SCTP_HAD_NO_TCB;
8121 	comp_cp->shut_cmp.ch.chunk_type = SCTP_SHUTDOWN_COMPLETE;
8122 	comp_cp->shut_cmp.ch.chunk_length = htons(sizeof(struct sctp_shutdown_complete_chunk));
8123 
8124 	mout->m_pkthdr.len = mout->m_len;
8125 	/* add checksum */
8126 	if ((sctp_no_csum_on_loopback) && m_get_rcvif_NOMPSAFE(m) != NULL &&
8127 	    m_get_rcvif_NOMPSAFE(m)->if_type == IFT_LOOP) {
8128 		comp_cp->sh.checksum =  0;
8129 	} else {
8130 		comp_cp->sh.checksum = sctp_calculate_sum(mout, NULL, offset_out);
8131 	}
8132 
8133 	/* zap the rcvif, it should be null */
8134 	m_reset_rcvif(mout);
8135 	/* zap the stack pointer to the route */
8136 	if (iph_out != NULL) {
8137 		struct route ro;
8138 
8139 		memset(&ro, 0, sizeof ro);
8140 #ifdef SCTP_DEBUG
8141 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT2) {
8142 			printf("sctp_shutdown_complete2 calling ip_output:\n");
8143 			sctp_print_address_pkt(iph_out, &comp_cp->sh);
8144 		}
8145 #endif
8146 		/* set IPv4 length */
8147 		iph_out->ip_len = htons(mout->m_pkthdr.len);
8148 		/* out it goes */
8149 		ip_output(mout, 0, &ro, IP_RAWOUTPUT, NULL, NULL);
8150 	} else if (ip6_out != NULL) {
8151 		struct route ro;
8152 
8153 		memset(&ro, 0, sizeof(ro));
8154 #ifdef SCTP_DEBUG
8155 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT2) {
8156 			printf("sctp_shutdown_complete2 calling ip6_output:\n");
8157 			sctp_print_address_pkt((struct ip *)ip6_out,
8158 			    &comp_cp->sh);
8159 		}
8160 #endif
8161 		ip6_output(mout, NULL, &ro, 0, NULL, NULL, NULL);
8162 	}
8163 	sctp_pegs[SCTP_DATAGRAMS_SENT]++;
8164 	return (0);
8165 }
8166 
8167 static struct sctp_nets *
8168 sctp_select_hb_destination(struct sctp_tcb *stcb, struct timeval *now)
8169 {
8170 	struct sctp_nets *net, *hnet;
8171 	int ms_goneby, highest_ms, state_override=0;
8172 
8173 	SCTP_GETTIME_TIMEVAL(now);
8174 	highest_ms = 0;
8175 	hnet = NULL;
8176 	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
8177 		if (
8178 			((net->dest_state & SCTP_ADDR_NOHB) && ((net->dest_state & SCTP_ADDR_UNCONFIRMED) == 0)) ||
8179 			(net->dest_state & SCTP_ADDR_OUT_OF_SCOPE)
8180 			) {
8181 			/* Skip this guy from consideration if HB is off AND its confirmed*/
8182 #ifdef SCTP_DEBUG
8183 			if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
8184 				printf("Skipping net:%p state:%d nohb/out-of-scope\n",
8185 				       net, net->dest_state);
8186 			}
8187 #endif
8188 			continue;
8189 		}
8190 		if (sctp_destination_is_reachable(stcb, (struct sockaddr *)&net->ro.ro_sa) == 0) {
8191 			/* skip this dest net from consideration */
8192 #ifdef SCTP_DEBUG
8193 			if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
8194 				printf("Skipping net:%p reachable NOT\n",
8195 				       net);
8196 			}
8197 #endif
8198 			continue;
8199 		}
8200 		if (net->last_sent_time.tv_sec) {
8201 			/* Sent to so we subtract */
8202 			ms_goneby = (now->tv_sec - net->last_sent_time.tv_sec) * 1000;
8203 		} else
8204 			/* Never been sent to */
8205 			ms_goneby = 0x7fffffff;
8206 #ifdef SCTP_DEBUG
8207 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
8208 			printf("net:%p ms_goneby:%d\n",
8209 			       net, ms_goneby);
8210 		}
8211 #endif
8212 		/* When the address state is unconfirmed but still considered reachable, we
8213 		 * HB at a higher rate. Once it goes confirmed OR reaches the "unreachable"
8214 		 * state, then we cut it back to HB at a more normal pace.
8215 		 */
8216 		if ((net->dest_state & (SCTP_ADDR_UNCONFIRMED|SCTP_ADDR_NOT_REACHABLE)) == SCTP_ADDR_UNCONFIRMED) {
8217 			state_override = 1;
8218 		} else {
8219 			state_override = 0;
8220 		}
8221 
8222 		if ((((unsigned int)ms_goneby >= net->RTO) || (state_override)) &&
8223 		    (ms_goneby > highest_ms)) {
8224 			highest_ms = ms_goneby;
8225 			hnet = net;
8226 #ifdef SCTP_DEBUG
8227 			if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
8228 				printf("net:%p is the new high\n",
8229 				       net);
8230 			}
8231 #endif
8232 		}
8233 	}
8234 	if (hnet &&
8235 	   ((hnet->dest_state & (SCTP_ADDR_UNCONFIRMED|SCTP_ADDR_NOT_REACHABLE)) == SCTP_ADDR_UNCONFIRMED)) {
8236 		state_override = 1;
8237 	} else {
8238 		state_override = 0;
8239 	}
8240 
8241 	if (highest_ms && (((unsigned int)highest_ms >= hnet->RTO) || state_override)) {
8242 		/* Found the one with longest delay bounds
8243 		 * OR it is unconfirmed and still not marked
8244 		 * unreachable.
8245 		 */
8246 #ifdef SCTP_DEBUG
8247 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
8248 			printf("net:%p is the hb winner -",
8249 				hnet);
8250 			if (hnet)
8251 				sctp_print_address((struct sockaddr *)&hnet->ro.ro_sa);
8252 			else
8253 				printf(" none\n");
8254 		}
8255 #endif
8256 		/* update the timer now */
8257 		hnet->last_sent_time = *now;
8258 		return (hnet);
8259 	}
8260 	/* Nothing to HB */
8261 	return (NULL);
8262 }
8263 
8264 int
8265 sctp_send_hb(struct sctp_tcb *stcb, int user_req, struct sctp_nets *u_net)
8266 {
8267 	struct sctp_tmit_chunk *chk;
8268 	struct sctp_nets *net;
8269 	struct sctp_heartbeat_chunk *hb;
8270 	struct timeval now;
8271 	struct sockaddr_in *sin;
8272 	struct sockaddr_in6 *sin6;
8273 
8274 	if (user_req == 0) {
8275 		net = sctp_select_hb_destination(stcb, &now);
8276 		if (net == NULL) {
8277 			/* All our busy none to send to, just
8278 			 * start the timer again.
8279 			 */
8280 			if (stcb->asoc.state == 0) {
8281 				return (0);
8282 			}
8283 			sctp_timer_start(SCTP_TIMER_TYPE_HEARTBEAT,
8284 					 stcb->sctp_ep,
8285 					 stcb,
8286 					 net);
8287 			return (0);
8288 		}
8289 #ifndef SCTP_USE_ALLMAN_BURST
8290 		else {
8291 			/* found one idle.. decay cwnd on this one
8292 			 * by 1/2 if none outstanding.
8293 			 */
8294 
8295 			if (net->flight_size == 0) {
8296 				net->cwnd /= 2;
8297 				if (net->addr_is_local) {
8298 					if (net->cwnd < (net->mtu *4)) {
8299 						net->cwnd = net->mtu * 4;
8300 					}
8301 				} else {
8302 					if (net->cwnd < (net->mtu * 2)) {
8303 						net->cwnd = net->mtu * 2;
8304 					}
8305 				}
8306 
8307 			}
8308 
8309 		}
8310 #endif
8311 	} else {
8312 		net = u_net;
8313 		if (net == NULL) {
8314 			return (0);
8315 		}
8316 		SCTP_GETTIME_TIMEVAL(&now);
8317 	}
8318 	sin = (struct sockaddr_in *)&net->ro.ro_sa;
8319 	if (sin->sin_family != AF_INET) {
8320 		if (sin->sin_family != AF_INET6) {
8321 			/* huh */
8322 			return (0);
8323 		}
8324 	}
8325 	chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
8326 	if (chk == NULL) {
8327 #ifdef SCTP_DEBUG
8328 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
8329 			printf("Gak, can't get a chunk for hb\n");
8330 		}
8331 #endif
8332 		return (0);
8333 	}
8334 	sctppcbinfo.ipi_gencnt_chunk++;
8335 	sctppcbinfo.ipi_count_chunk++;
8336 	chk->rec.chunk_id = SCTP_HEARTBEAT_REQUEST;
8337 	chk->asoc = &stcb->asoc;
8338 	chk->send_size = sizeof(struct sctp_heartbeat_chunk);
8339 	MGETHDR(chk->data, M_DONTWAIT, MT_DATA);
8340 	if (chk->data == NULL) {
8341 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
8342 		sctppcbinfo.ipi_count_chunk--;
8343 		if ((int)sctppcbinfo.ipi_count_chunk < 0) {
8344 			panic("Chunk count is negative");
8345 		}
8346 		sctppcbinfo.ipi_gencnt_chunk++;
8347 		return (0);
8348 	}
8349 	chk->data->m_data += SCTP_MIN_OVERHEAD;
8350 	chk->data->m_pkthdr.len = chk->data->m_len = chk->send_size;
8351 	chk->sent = SCTP_DATAGRAM_UNSENT;
8352 	chk->snd_count = 0;
8353 	chk->whoTo = net;
8354 	chk->whoTo->ref_count++;
8355 	/* Now we have a mbuf that we can fill in with the details */
8356 	hb = mtod(chk->data, struct sctp_heartbeat_chunk *);
8357 
8358 	/* fill out chunk header */
8359 	hb->ch.chunk_type = SCTP_HEARTBEAT_REQUEST;
8360 	hb->ch.chunk_flags = 0;
8361 	hb->ch.chunk_length = htons(chk->send_size);
8362 	/* Fill out hb parameter */
8363 	hb->heartbeat.hb_info.ph.param_type = htons(SCTP_HEARTBEAT_INFO);
8364 	hb->heartbeat.hb_info.ph.param_length = htons(sizeof(struct sctp_heartbeat_info_param));
8365 	hb->heartbeat.hb_info.time_value_1 = now.tv_sec;
8366 	hb->heartbeat.hb_info.time_value_2 = now.tv_usec;
8367 	/* Did our user request this one, put it in */
8368 	hb->heartbeat.hb_info.user_req = user_req;
8369 	hb->heartbeat.hb_info.addr_family = sin->sin_family;
8370 	hb->heartbeat.hb_info.addr_len = sin->sin_len;
8371 	if (net->dest_state & SCTP_ADDR_UNCONFIRMED) {
8372 		/* we only take from the entropy pool if the address is
8373 		 * not confirmed.
8374 		 */
8375  		net->heartbeat_random1 = hb->heartbeat.hb_info.random_value1 = sctp_select_initial_TSN(&stcb->sctp_ep->sctp_ep);
8376  		net->heartbeat_random2 = hb->heartbeat.hb_info.random_value2 = sctp_select_initial_TSN(&stcb->sctp_ep->sctp_ep);
8377 	} else {
8378 		net->heartbeat_random1 = hb->heartbeat.hb_info.random_value1 = 0;
8379 		net->heartbeat_random2 = hb->heartbeat.hb_info.random_value2 = 0;
8380 	}
8381 	if (sin->sin_family == AF_INET) {
8382 		memcpy(hb->heartbeat.hb_info.address, &sin->sin_addr, sizeof(sin->sin_addr));
8383 	} else if (sin->sin_family == AF_INET6) {
8384 		/* We leave the scope the way it is in our lookup table. */
8385 		sin6 = (struct sockaddr_in6 *)&net->ro.ro_sa;
8386 		memcpy(hb->heartbeat.hb_info.address, &sin6->sin6_addr, sizeof(sin6->sin6_addr));
8387 	} else {
8388 		/* huh compiler bug */
8389 #ifdef SCTP_DEBUG
8390 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
8391 			printf("Compiler bug bleeds a mbuf and a chunk\n");
8392 		}
8393 #endif
8394 		return (0);
8395 	}
8396 	/* ok we have a destination that needs a beat */
8397 	/* lets do the theshold management Qiaobing style */
8398 	if (user_req == 0) {
8399 		if (sctp_threshold_management(stcb->sctp_ep, stcb, net,
8400 					      stcb->asoc.max_send_times)) {
8401 			/* we have lost the association, in a way this
8402 			 * is quite bad since we really are one less time
8403 			 * since we really did not send yet. This is the
8404 			 * down side to the Q's style as defined in the RFC
8405 			 * and not my alternate style defined in the RFC.
8406 			 */
8407 			if (chk->data != NULL) {
8408 				sctp_m_freem(chk->data);
8409 				chk->data = NULL;
8410 			}
8411 			SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
8412 			sctppcbinfo.ipi_count_chunk--;
8413 			if ((int)sctppcbinfo.ipi_count_chunk < 0) {
8414 				panic("Chunk count is negative");
8415 			}
8416 			sctppcbinfo.ipi_gencnt_chunk++;
8417 			return (-1);
8418 		}
8419 	}
8420 	net->hb_responded = 0;
8421 #ifdef SCTP_DEBUG
8422 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
8423 		printf("Inserting chunk for HB\n");
8424 	}
8425 #endif
8426 	TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
8427 	stcb->asoc.ctrl_queue_cnt++;
8428 	sctp_pegs[SCTP_HB_SENT]++;
8429 	/*
8430 	 * Call directly med level routine to put out the chunk. It will
8431 	 * always tumble out control chunks aka HB but it may even tumble
8432 	 * out data too.
8433 	 */
8434 	if (user_req == 0) {
8435 		/* Ok now lets start the HB timer if it is NOT a user req */
8436 		sctp_timer_start(SCTP_TIMER_TYPE_HEARTBEAT, stcb->sctp_ep,
8437 				 stcb, net);
8438 	}
8439 	return (1);
8440 }
8441 
8442 void
8443 sctp_send_ecn_echo(struct sctp_tcb *stcb, struct sctp_nets *net,
8444 		   uint32_t high_tsn)
8445 {
8446 	struct sctp_association *asoc;
8447 	struct sctp_ecne_chunk *ecne;
8448 	struct sctp_tmit_chunk *chk;
8449 	asoc = &stcb->asoc;
8450 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
8451 		if (chk->rec.chunk_id == SCTP_ECN_ECHO) {
8452 			/* found a previous ECN_ECHO update it if needed */
8453 			ecne = mtod(chk->data, struct sctp_ecne_chunk *);
8454 			ecne->tsn = htonl(high_tsn);
8455 			return;
8456 		}
8457 	}
8458 	/* nope could not find one to update so we must build one */
8459 	chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
8460 	if (chk == NULL) {
8461 		return;
8462 	}
8463 	sctp_pegs[SCTP_ECNE_SENT]++;
8464 	sctppcbinfo.ipi_count_chunk++;
8465 	sctppcbinfo.ipi_gencnt_chunk++;
8466 	chk->rec.chunk_id = SCTP_ECN_ECHO;
8467 	chk->asoc = &stcb->asoc;
8468 	chk->send_size = sizeof(struct sctp_ecne_chunk);
8469 	MGETHDR(chk->data, M_DONTWAIT, MT_DATA);
8470 	if (chk->data == NULL) {
8471 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
8472 		sctppcbinfo.ipi_count_chunk--;
8473 		if ((int)sctppcbinfo.ipi_count_chunk < 0) {
8474 			panic("Chunk count is negative");
8475 		}
8476 		sctppcbinfo.ipi_gencnt_chunk++;
8477 		return;
8478 	}
8479 	chk->data->m_data += SCTP_MIN_OVERHEAD;
8480 	chk->data->m_pkthdr.len = chk->data->m_len = chk->send_size;
8481 	chk->sent = SCTP_DATAGRAM_UNSENT;
8482 	chk->snd_count = 0;
8483 	chk->whoTo = net;
8484 	chk->whoTo->ref_count++;
8485 	ecne = mtod(chk->data, struct sctp_ecne_chunk *);
8486 	ecne->ch.chunk_type = SCTP_ECN_ECHO;
8487 	ecne->ch.chunk_flags = 0;
8488 	ecne->ch.chunk_length = htons(sizeof(struct sctp_ecne_chunk));
8489 	ecne->tsn = htonl(high_tsn);
8490 	TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
8491 	asoc->ctrl_queue_cnt++;
8492 }
8493 
8494 void
8495 sctp_send_packet_dropped(struct sctp_tcb *stcb, struct sctp_nets *net,
8496 			 struct mbuf *m, int iphlen, int bad_crc)
8497 {
8498 	struct sctp_association *asoc;
8499 	struct sctp_pktdrop_chunk *drp;
8500 	struct sctp_tmit_chunk *chk;
8501 	uint8_t *datap;
8502 	int len;
8503 	unsigned int small_one;
8504 	struct ip *iph;
8505 
8506 	long spc;
8507 	asoc = &stcb->asoc;
8508 	if (asoc->peer_supports_pktdrop == 0) {
8509 		/* peer must declare support before I
8510 		 * send one.
8511 		 */
8512 		return;
8513 	}
8514 	chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
8515 	if (chk == NULL) {
8516 		return;
8517 	}
8518 	sctppcbinfo.ipi_count_chunk++;
8519 	sctppcbinfo.ipi_gencnt_chunk++;
8520 
8521 	iph = mtod(m, struct ip *);
8522 	if (iph == NULL) {
8523 		return;
8524 	}
8525 	if (iph->ip_v == IPVERSION) {
8526 		/* IPv4 */
8527 #if defined(__FreeBSD__)
8528 		len = chk->send_size = iph->ip_len;
8529 #else
8530 		len = chk->send_size = (iph->ip_len - iphlen);
8531 #endif
8532 	} else {
8533 		struct ip6_hdr *ip6h;
8534 		/* IPv6 */
8535 		ip6h = mtod(m, struct ip6_hdr *);
8536 		len = chk->send_size = htons(ip6h->ip6_plen);
8537 	}
8538 	if ((len+iphlen) > m->m_pkthdr.len) {
8539 		/* huh */
8540 		chk->send_size = len = m->m_pkthdr.len - iphlen;
8541 	}
8542 	chk->asoc = &stcb->asoc;
8543 	MGETHDR(chk->data, M_DONTWAIT, MT_DATA);
8544 	if (chk->data == NULL) {
8545 	jump_out:
8546 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
8547 		sctppcbinfo.ipi_count_chunk--;
8548 		if ((int)sctppcbinfo.ipi_count_chunk < 0) {
8549 			panic("Chunk count is negative");
8550 		}
8551 		sctppcbinfo.ipi_gencnt_chunk++;
8552 		return;
8553 	}
8554 	if ((chk->send_size+sizeof(struct sctp_pktdrop_chunk)+SCTP_MIN_OVERHEAD) > MHLEN) {
8555 		MCLGET(chk->data, M_DONTWAIT);
8556 		if ((chk->data->m_flags & M_EXT) == 0) {
8557 			/* Give up */
8558 			sctp_m_freem(chk->data);
8559 			chk->data = NULL;
8560 			goto jump_out;
8561 		}
8562 	}
8563 	chk->data->m_data += SCTP_MIN_OVERHEAD;
8564 	drp = mtod(chk->data, struct sctp_pktdrop_chunk *);
8565 	if (drp == NULL) {
8566 		sctp_m_freem(chk->data);
8567 		chk->data = NULL;
8568 		goto jump_out;
8569 	}
8570 	small_one = asoc->smallest_mtu;
8571 	if (small_one > MCLBYTES) {
8572 		/* Only one cluster worth of data MAX */
8573 		small_one = MCLBYTES;
8574 	}
8575 	chk->book_size = (chk->send_size + sizeof(struct sctp_pktdrop_chunk) +
8576 			  sizeof(struct sctphdr) + SCTP_MED_OVERHEAD);
8577 	if (chk->book_size > small_one) {
8578 		drp->ch.chunk_flags = SCTP_PACKET_TRUNCATED;
8579 		drp->trunc_len = htons(chk->send_size);
8580 		chk->send_size = small_one - (SCTP_MED_OVERHEAD +
8581 					     sizeof(struct sctp_pktdrop_chunk) +
8582 					     sizeof(struct sctphdr));
8583 		len = chk->send_size;
8584 	} else {
8585 		/* no truncation needed */
8586 		drp->ch.chunk_flags = 0;
8587 		drp->trunc_len = htons(0);
8588 	}
8589 	if (bad_crc) {
8590 		drp->ch.chunk_flags |= SCTP_BADCRC;
8591 	}
8592 	chk->send_size += sizeof(struct sctp_pktdrop_chunk);
8593 	chk->data->m_pkthdr.len = chk->data->m_len = chk->send_size;
8594 	chk->sent = SCTP_DATAGRAM_UNSENT;
8595 	chk->snd_count = 0;
8596 	if (net) {
8597 		/* we should hit here */
8598 		chk->whoTo = net;
8599 	} else {
8600 		chk->whoTo = asoc->primary_destination;
8601 	}
8602 	chk->whoTo->ref_count++;
8603 	chk->rec.chunk_id = SCTP_PACKET_DROPPED;
8604 	drp->ch.chunk_type = SCTP_PACKET_DROPPED;
8605 	drp->ch.chunk_length = htons(chk->send_size);
8606 	spc = stcb->sctp_socket->so_rcv.sb_hiwat;
8607 	if (spc < 0) {
8608 		spc = 0;
8609 	}
8610 	drp->bottle_bw = htonl(spc);
8611 	drp->current_onq = htonl(asoc->size_on_delivery_queue +
8612 				 asoc->size_on_reasm_queue +
8613 				 asoc->size_on_all_streams +
8614 				 asoc->my_rwnd_control_len +
8615 		                 stcb->sctp_socket->so_rcv.sb_cc);
8616 	drp->reserved = 0;
8617 	datap = drp->data;
8618         m_copydata(m, iphlen, len, datap);
8619 	TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
8620 	asoc->ctrl_queue_cnt++;
8621 }
8622 
8623 void
8624 sctp_send_cwr(struct sctp_tcb *stcb, struct sctp_nets *net, uint32_t high_tsn)
8625 {
8626 	struct sctp_association *asoc;
8627 	struct sctp_cwr_chunk *cwr;
8628 	struct sctp_tmit_chunk *chk;
8629 
8630 	asoc = &stcb->asoc;
8631 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
8632 		if (chk->rec.chunk_id == SCTP_ECN_CWR) {
8633 			/* found a previous ECN_CWR update it if needed */
8634 			cwr = mtod(chk->data, struct sctp_cwr_chunk *);
8635 			if (compare_with_wrap(high_tsn, ntohl(cwr->tsn),
8636 					      MAX_TSN)) {
8637 				cwr->tsn = htonl(high_tsn);
8638 			}
8639 			return;
8640 		}
8641 	}
8642 	/* nope could not find one to update so we must build one */
8643 	chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
8644 	if (chk == NULL) {
8645 		return;
8646 	}
8647 	sctppcbinfo.ipi_count_chunk++;
8648 	sctppcbinfo.ipi_gencnt_chunk++;
8649 	chk->rec.chunk_id = SCTP_ECN_CWR;
8650 	chk->asoc = &stcb->asoc;
8651 	chk->send_size = sizeof(struct sctp_cwr_chunk);
8652 	MGETHDR(chk->data, M_DONTWAIT, MT_DATA);
8653 	if (chk->data == NULL) {
8654 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
8655 		sctppcbinfo.ipi_count_chunk--;
8656 		if ((int)sctppcbinfo.ipi_count_chunk < 0) {
8657 			panic("Chunk count is negative");
8658 		}
8659 		sctppcbinfo.ipi_gencnt_chunk++;
8660 		return;
8661 	}
8662 	chk->data->m_data += SCTP_MIN_OVERHEAD;
8663 	chk->data->m_pkthdr.len = chk->data->m_len = chk->send_size;
8664 	chk->sent = SCTP_DATAGRAM_UNSENT;
8665 	chk->snd_count = 0;
8666 	chk->whoTo = net;
8667 	chk->whoTo->ref_count++;
8668 	cwr = mtod(chk->data, struct sctp_cwr_chunk *);
8669 	cwr->ch.chunk_type = SCTP_ECN_CWR;
8670 	cwr->ch.chunk_flags = 0;
8671 	cwr->ch.chunk_length = htons(sizeof(struct sctp_cwr_chunk));
8672 	cwr->tsn = htonl(high_tsn);
8673 	TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
8674 	asoc->ctrl_queue_cnt++;
8675 }
8676 static void
8677 sctp_reset_the_streams(struct sctp_tcb *stcb,
8678      struct sctp_stream_reset_request *req, int number_entries, uint16_t *list)
8679 {
8680 	int i;
8681 
8682 	if (req->reset_flags & SCTP_RESET_ALL) {
8683 		for (i=0; i<stcb->asoc.streamoutcnt; i++) {
8684 			stcb->asoc.strmout[i].next_sequence_sent = 0;
8685 		}
8686 	} else if (number_entries) {
8687 		for (i=0; i<number_entries; i++) {
8688 			if (list[i] >= stcb->asoc.streamoutcnt) {
8689 				/* no such stream */
8690 				continue;
8691 			}
8692 			stcb->asoc.strmout[(list[i])].next_sequence_sent = 0;
8693 		}
8694 	}
8695 	sctp_ulp_notify(SCTP_NOTIFY_STR_RESET_SEND, stcb, number_entries, (void *)list);
8696 }
8697 
8698 void
8699 sctp_send_str_reset_ack(struct sctp_tcb *stcb,
8700      struct sctp_stream_reset_request *req)
8701 {
8702 	struct sctp_association *asoc;
8703 	struct sctp_stream_reset_resp *strack;
8704 	struct sctp_tmit_chunk *chk;
8705 	uint32_t seq;
8706 	int number_entries, i;
8707 	uint8_t two_way=0, not_peer=0;
8708 	uint16_t *list=NULL;
8709 
8710 	asoc = &stcb->asoc;
8711 	if (req->reset_flags & SCTP_RESET_ALL)
8712 		number_entries = 0;
8713 	else
8714 		number_entries = (ntohs(req->ph.param_length) - sizeof(struct sctp_stream_reset_request)) / sizeof(uint16_t);
8715 
8716 	chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
8717 	if (chk == NULL) {
8718 		return;
8719 	}
8720 	sctppcbinfo.ipi_count_chunk++;
8721 	sctppcbinfo.ipi_gencnt_chunk++;
8722 	chk->rec.chunk_id = SCTP_STREAM_RESET;
8723 	chk->asoc = &stcb->asoc;
8724 	chk->send_size = sizeof(struct sctp_stream_reset_resp) + (number_entries * sizeof(uint16_t));
8725 	MGETHDR(chk->data, M_DONTWAIT, MT_DATA);
8726 	if (chk->data == NULL) {
8727 	strresp_jump_out:
8728 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
8729 		sctppcbinfo.ipi_count_chunk--;
8730 		if ((int)sctppcbinfo.ipi_count_chunk < 0) {
8731 			panic("Chunk count is negative");
8732 		}
8733 		sctppcbinfo.ipi_gencnt_chunk++;
8734 		return;
8735 	}
8736 	chk->data->m_data += SCTP_MIN_OVERHEAD;
8737 	chk->data->m_pkthdr.len = chk->data->m_len = SCTP_SIZE32(chk->send_size);
8738 	if (M_TRAILINGSPACE(chk->data) < (int)SCTP_SIZE32(chk->send_size)) {
8739 		MCLGET(chk->data, M_DONTWAIT);
8740 		if ((chk->data->m_flags & M_EXT) == 0) {
8741 			/* Give up */
8742 			sctp_m_freem(chk->data);
8743 			chk->data = NULL;
8744 			goto strresp_jump_out;
8745 		}
8746 		chk->data->m_data += SCTP_MIN_OVERHEAD;
8747 	}
8748 	if (M_TRAILINGSPACE(chk->data) < (int)SCTP_SIZE32(chk->send_size)) {
8749 		/* can't do it, no room */
8750 		/* Give up */
8751 		sctp_m_freem(chk->data);
8752 		chk->data = NULL;
8753 		goto strresp_jump_out;
8754 
8755 	}
8756 	chk->sent = SCTP_DATAGRAM_UNSENT;
8757 	chk->snd_count = 0;
8758 	chk->whoTo = asoc->primary_destination;
8759 	chk->whoTo->ref_count++;
8760 	strack = mtod(chk->data, struct sctp_stream_reset_resp *);
8761 
8762 	strack->ch.chunk_type = SCTP_STREAM_RESET;
8763 	strack->ch.chunk_flags = 0;
8764 	strack->ch.chunk_length = htons(chk->send_size);
8765 
8766 	memset(strack->sr_resp.reset_pad, 0, sizeof(strack->sr_resp.reset_pad));
8767 
8768 	strack->sr_resp.ph.param_type = ntohs(SCTP_STR_RESET_RESPONSE);
8769 	strack->sr_resp.ph.param_length = htons((chk->send_size - sizeof(struct sctp_chunkhdr)));
8770 
8771 
8772 
8773 	if (chk->send_size % 4) {
8774 		/* need a padding for the end */
8775 		int pad;
8776 		uint8_t *end;
8777 		end = (uint8_t *)((vaddr_t)strack + chk->send_size);
8778 		pad = chk->send_size % 4;
8779 		for (i = 0; i < pad; i++) {
8780 			end[i] = 0;
8781 		}
8782 		chk->send_size += pad;
8783 	}
8784 
8785         /* actual response */
8786 	if (req->reset_flags & SCTP_RESET_YOUR) {
8787 		strack->sr_resp.reset_flags = SCTP_RESET_PERFORMED;
8788 	} else {
8789 		strack->sr_resp.reset_flags = 0;
8790 	}
8791 
8792 	/* copied from reset request */
8793 	strack->sr_resp.reset_req_seq_resp = req->reset_req_seq;
8794 	seq = ntohl(req->reset_req_seq);
8795 
8796 	list = req->list_of_streams;
8797 	/* copy the un-converted network byte order streams */
8798 	for (i=0; i<number_entries; i++) {
8799 		strack->sr_resp.list_of_streams[i] = list[i];
8800 	}
8801 	if (asoc->str_reset_seq_in == seq) {
8802 		/* is it the next expected? */
8803 		asoc->str_reset_seq_in++;
8804 		strack->sr_resp.reset_at_tsn = htonl(asoc->sending_seq);
8805 		asoc->str_reset_sending_seq = asoc->sending_seq;
8806 		if (number_entries) {
8807 			uint16_t temp;
8808 			/* convert them to host byte order */
8809 			for (i=0 ; i<number_entries; i++) {
8810 				temp = ntohs(list[i]);
8811 				list[i] = temp;
8812 			}
8813 		}
8814 		if (req->reset_flags & SCTP_RESET_YOUR) {
8815 			/* reset my outbound streams */
8816 			sctp_reset_the_streams(stcb, req , number_entries, list);
8817 		}
8818 		if (req->reset_flags & SCTP_RECIPRICAL) {
8819 			/* reset peer too */
8820 			sctp_send_str_reset_req(stcb, number_entries, list, two_way, not_peer);
8821 		}
8822 
8823 	} else {
8824 		/* no its a retran so I must just ack and do nothing */
8825 		strack->sr_resp.reset_at_tsn = htonl(asoc->str_reset_sending_seq);
8826 	}
8827 	strack->sr_resp.cumulative_tsn = htonl(asoc->cumulative_tsn);
8828 	TAILQ_INSERT_TAIL(&asoc->control_send_queue,
8829 			  chk,
8830 			  sctp_next);
8831 	asoc->ctrl_queue_cnt++;
8832 }
8833 
8834 
8835 void
8836 sctp_send_str_reset_req(struct sctp_tcb *stcb,
8837      int number_entrys, uint16_t *list, uint8_t two_way, uint8_t not_peer)
8838 {
8839 	/* Send a stream reset request. The number_entrys may be 0 and list NULL
8840 	 * if the request is to reset all streams. If two_way is true then we
8841 	 * not only request a RESET of the received streams but we also
8842 	 * request the peer to send a reset req to us too.
8843 	 * Flag combinations in table:
8844 	 *
8845 	 *       two_way | not_peer  | = | Flags
8846 	 *       ------------------------------
8847 	 *         0     |    0      | = | SCTP_RESET_YOUR (just the peer)
8848 	 *         1     |    0      | = | SCTP_RESET_YOUR | SCTP_RECIPRICAL (both sides)
8849 	 *         0     |    1      | = | Not a Valid Request (not anyone)
8850 	 *         1     |    1      | = | SCTP_RESET_RECIPRICAL (Just local host)
8851 	 */
8852 	struct sctp_association *asoc;
8853 	struct sctp_stream_reset_req *strreq;
8854 	struct sctp_tmit_chunk *chk;
8855 
8856 
8857 	asoc = &stcb->asoc;
8858 	if (asoc->stream_reset_outstanding) {
8859 		/* Already one pending, must get ACK back
8860 		 * to clear the flag.
8861 		 */
8862 		return;
8863 	}
8864 
8865 	if ((two_way == 0) && (not_peer == 1)) {
8866 		/* not a valid request */
8867 		return;
8868 	}
8869 
8870 	chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
8871 	if (chk == NULL) {
8872 		return;
8873 	}
8874 	sctppcbinfo.ipi_count_chunk++;
8875 	sctppcbinfo.ipi_gencnt_chunk++;
8876 	chk->rec.chunk_id = SCTP_STREAM_RESET;
8877 	chk->asoc = &stcb->asoc;
8878 	chk->send_size = sizeof(struct sctp_stream_reset_req) + (number_entrys * sizeof(uint16_t));
8879 	MGETHDR(chk->data, M_DONTWAIT, MT_DATA);
8880 	if (chk->data == NULL) {
8881 	strreq_jump_out:
8882 		SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
8883 		sctppcbinfo.ipi_count_chunk--;
8884 		if ((int)sctppcbinfo.ipi_count_chunk < 0) {
8885 			panic("Chunk count is negative");
8886 		}
8887 		sctppcbinfo.ipi_gencnt_chunk++;
8888 		return;
8889 	}
8890 	chk->data->m_data += SCTP_MIN_OVERHEAD;
8891 	chk->data->m_pkthdr.len = chk->data->m_len = SCTP_SIZE32(chk->send_size);
8892 	if (M_TRAILINGSPACE(chk->data) < (int)SCTP_SIZE32(chk->send_size)) {
8893 		MCLGET(chk->data, M_DONTWAIT);
8894 		if ((chk->data->m_flags & M_EXT) == 0) {
8895 			/* Give up */
8896 			sctp_m_freem(chk->data);
8897 			chk->data = NULL;
8898 			goto strreq_jump_out;
8899 		}
8900 		chk->data->m_data += SCTP_MIN_OVERHEAD;
8901 	}
8902 	if (M_TRAILINGSPACE(chk->data) < (int)SCTP_SIZE32(chk->send_size)) {
8903 		/* can't do it, no room */
8904 		/* Give up */
8905 		sctp_m_freem(chk->data);
8906 		chk->data = NULL;
8907 		goto strreq_jump_out;
8908 	}
8909 	chk->sent = SCTP_DATAGRAM_UNSENT;
8910 	chk->snd_count = 0;
8911 	chk->whoTo = asoc->primary_destination;
8912 	chk->whoTo->ref_count++;
8913 
8914 	strreq = mtod(chk->data, struct sctp_stream_reset_req *);
8915 	strreq->ch.chunk_type = SCTP_STREAM_RESET;
8916 	strreq->ch.chunk_flags = 0;
8917 	strreq->ch.chunk_length = htons(chk->send_size);
8918 
8919 	strreq->sr_req.ph.param_type = ntohs(SCTP_STR_RESET_REQUEST);
8920 	strreq->sr_req.ph.param_length = htons((chk->send_size - sizeof(struct sctp_chunkhdr)));
8921 
8922 	if (chk->send_size % 4) {
8923 		/* need a padding for the end */
8924 		int pad, i;
8925 		uint8_t *end;
8926 		end = (uint8_t *)((vaddr_t)strreq + chk->send_size);
8927 		pad = chk->send_size % 4;
8928 		for (i=0; i<pad; i++) {
8929 			end[i] = 0;
8930 		}
8931 		chk->send_size += pad;
8932 	}
8933 
8934 	strreq->sr_req.reset_flags = 0;
8935 	if (number_entrys == 0) {
8936 		strreq->sr_req.reset_flags |= SCTP_RESET_ALL;
8937 	}
8938 	if (two_way == 0) {
8939 		strreq->sr_req.reset_flags |= SCTP_RESET_YOUR;
8940 	} else {
8941 		if (not_peer == 0) {
8942 			strreq->sr_req.reset_flags |= SCTP_RECIPRICAL | SCTP_RESET_YOUR;
8943 		} else {
8944 			strreq->sr_req.reset_flags |= SCTP_RECIPRICAL;
8945 		}
8946 	}
8947 	memset(strreq->sr_req.reset_pad, 0, sizeof(strreq->sr_req.reset_pad));
8948 	strreq->sr_req.reset_req_seq = htonl(asoc->str_reset_seq_out);
8949 	if (number_entrys) {
8950 		/* populate the specific entry's */
8951 		int i;
8952 		for (i=0; i < number_entrys; i++) {
8953 			strreq->sr_req.list_of_streams[i] = htons(list[i]);
8954 		}
8955 	}
8956 	TAILQ_INSERT_TAIL(&asoc->control_send_queue,
8957 			  chk,
8958 			  sctp_next);
8959 	asoc->ctrl_queue_cnt++;
8960 	sctp_timer_start(SCTP_TIMER_TYPE_STRRESET, stcb->sctp_ep, stcb, chk->whoTo);
8961 	asoc->stream_reset_outstanding = 1;
8962 }
8963 
8964 void
8965 sctp_send_abort(struct mbuf *m, int iphlen, struct sctphdr *sh, uint32_t vtag,
8966     struct mbuf *err_cause)
8967 {
8968 	/*
8969 	 * Formulate the abort message, and send it back down.
8970 	 */
8971 	struct mbuf *mout;
8972 	struct sctp_abort_msg *abm;
8973 	struct ip *iph, *iph_out;
8974 	struct ip6_hdr *ip6, *ip6_out;
8975 	int iphlen_out;
8976 
8977 	/* don't respond to ABORT with ABORT */
8978 	if (sctp_is_there_an_abort_here(m, iphlen, &vtag)) {
8979 		if (err_cause)
8980 			sctp_m_freem(err_cause);
8981 		return;
8982 	}
8983 	MGETHDR(mout, M_DONTWAIT, MT_HEADER);
8984 	if (mout == NULL) {
8985 		if (err_cause)
8986 			sctp_m_freem(err_cause);
8987 		return;
8988 	}
8989 	iph = mtod(m, struct ip *);
8990 	iph_out = NULL;
8991 	ip6_out = NULL;
8992 	if (iph->ip_v == IPVERSION) {
8993 		iph_out = mtod(mout, struct ip *);
8994 		mout->m_len = sizeof(*iph_out) + sizeof(*abm);
8995 		mout->m_next = err_cause;
8996 
8997 		/* Fill in the IP header for the ABORT */
8998 		iph_out->ip_v = IPVERSION;
8999 		iph_out->ip_hl = (sizeof(struct ip) / 4);
9000 		iph_out->ip_tos = (u_char)0;
9001 		iph_out->ip_id = 0;
9002 		iph_out->ip_off = 0;
9003 		iph_out->ip_ttl = MAXTTL;
9004 		iph_out->ip_p = IPPROTO_SCTP;
9005 		iph_out->ip_src.s_addr = iph->ip_dst.s_addr;
9006 		iph_out->ip_dst.s_addr = iph->ip_src.s_addr;
9007 		/* let IP layer calculate this */
9008 		iph_out->ip_sum = 0;
9009 
9010 		iphlen_out = sizeof(*iph_out);
9011 		abm = (struct sctp_abort_msg *)((vaddr_t)iph_out + iphlen_out);
9012 	} else if (iph->ip_v == (IPV6_VERSION >> 4)) {
9013 		ip6 = (struct ip6_hdr *)iph;
9014 		ip6_out = mtod(mout, struct ip6_hdr *);
9015 		mout->m_len = sizeof(*ip6_out) + sizeof(*abm);
9016 		mout->m_next = err_cause;
9017 
9018 		/* Fill in the IP6 header for the ABORT */
9019 		ip6_out->ip6_flow = ip6->ip6_flow;
9020 		ip6_out->ip6_hlim = ip6_defhlim;
9021 		ip6_out->ip6_nxt = IPPROTO_SCTP;
9022 		ip6_out->ip6_src = ip6->ip6_dst;
9023 		ip6_out->ip6_dst = ip6->ip6_src;
9024 
9025 		iphlen_out = sizeof(*ip6_out);
9026 		abm = (struct sctp_abort_msg *)((vaddr_t)ip6_out + iphlen_out);
9027 	} else {
9028 		/* Currently not supported */
9029 		return;
9030 	}
9031 
9032 	abm->sh.src_port = sh->dest_port;
9033 	abm->sh.dest_port = sh->src_port;
9034 	abm->sh.checksum = 0;
9035 	if (vtag == 0) {
9036 		abm->sh.v_tag = sh->v_tag;
9037 		abm->msg.ch.chunk_flags = SCTP_HAD_NO_TCB;
9038 	} else {
9039 		abm->sh.v_tag = htonl(vtag);
9040 		abm->msg.ch.chunk_flags = 0;
9041 	}
9042 	abm->msg.ch.chunk_type = SCTP_ABORT_ASSOCIATION;
9043 
9044 	if (err_cause) {
9045 		struct mbuf *m_tmp = err_cause;
9046 		int err_len = 0;
9047 		/* get length of the err_cause chain */
9048 		while (m_tmp != NULL) {
9049 			err_len += m_tmp->m_len;
9050 			m_tmp = m_tmp->m_next;
9051 		}
9052 		mout->m_pkthdr.len = mout->m_len + err_len;
9053 		if (err_len % 4) {
9054 			/* need pad at end of chunk */
9055 			u_int32_t cpthis=0;
9056 			int padlen;
9057 			padlen = 4 - (mout->m_pkthdr.len % 4);
9058 			m_copyback(mout, mout->m_pkthdr.len, padlen, (void *)&cpthis);
9059 		}
9060 		abm->msg.ch.chunk_length = htons(sizeof(abm->msg.ch) + err_len);
9061 	} else {
9062 		mout->m_pkthdr.len = mout->m_len;
9063 		abm->msg.ch.chunk_length = htons(sizeof(abm->msg.ch));
9064 	}
9065 
9066 	/* add checksum */
9067 	if ((sctp_no_csum_on_loopback) && m_get_rcvif_NOMPSAFE(m) != NULL &&
9068 	    m_get_rcvif_NOMPSAFE(m)->if_type == IFT_LOOP) {
9069 		abm->sh.checksum =  0;
9070 	} else {
9071 		abm->sh.checksum = sctp_calculate_sum(mout, NULL, iphlen_out);
9072 	}
9073 
9074 	/* zap the rcvif, it should be null */
9075 	m_reset_rcvif(mout);
9076 	if (iph_out != NULL) {
9077 		struct route ro;
9078 
9079 		/* zap the stack pointer to the route */
9080 		memset(&ro, 0, sizeof ro);
9081 #ifdef SCTP_DEBUG
9082 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT2) {
9083                         printf("sctp_send_abort calling ip_output:\n");
9084 			sctp_print_address_pkt(iph_out, &abm->sh);
9085                 }
9086 #endif
9087 		/* set IPv4 length */
9088 		iph_out->ip_len = htons(mout->m_pkthdr.len);
9089 		/* out it goes */
9090 		(void)ip_output(mout, 0, &ro, IP_RAWOUTPUT, NULL, NULL);
9091 	} else if (ip6_out != NULL) {
9092 		struct route ro;
9093 
9094 		/* zap the stack pointer to the route */
9095 		memset(&ro, 0, sizeof(ro));
9096 #ifdef SCTP_DEBUG
9097 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT2) {
9098                         printf("sctp_send_abort calling ip6_output:\n");
9099 			sctp_print_address_pkt((struct ip *)ip6_out, &abm->sh);
9100                 }
9101 #endif
9102 		ip6_output(mout, NULL, &ro, 0, NULL, NULL, NULL);
9103 	}
9104         sctp_pegs[SCTP_DATAGRAMS_SENT]++;
9105 }
9106 
9107 void
9108 sctp_send_operr_to(struct mbuf *m, int iphlen,
9109 		   struct mbuf *scm,
9110 		   uint32_t vtag)
9111 {
9112 	struct sctphdr *ihdr;
9113 	struct sctphdr *ohdr;
9114 	struct sctp_chunkhdr *ophdr;
9115 
9116 	struct ip *iph;
9117 #ifdef SCTP_DEBUG
9118 	struct sockaddr_in6 lsa6, fsa6;
9119 #endif
9120 	uint32_t val;
9121 	iph = mtod(m, struct ip *);
9122 	ihdr = (struct sctphdr *)((vaddr_t)iph + iphlen);
9123 	if (!(scm->m_flags & M_PKTHDR)) {
9124 		/* must be a pkthdr */
9125 		printf("Huh, not a packet header in send_operr\n");
9126 		m_freem(scm);
9127 		return;
9128 	}
9129 	M_PREPEND(scm, (sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr)), M_DONTWAIT);
9130 	if (scm == NULL) {
9131 		/* can't send because we can't add a mbuf */
9132 		return;
9133 	}
9134 	ohdr = mtod(scm, struct sctphdr *);
9135 	ohdr->src_port = ihdr->dest_port;
9136 	ohdr->dest_port = ihdr->src_port;
9137 	ohdr->v_tag = vtag;
9138 	ohdr->checksum = 0;
9139 	ophdr = (struct sctp_chunkhdr *)(ohdr + 1);
9140 	ophdr->chunk_type = SCTP_OPERATION_ERROR;
9141 	ophdr->chunk_flags = 0;
9142 	ophdr->chunk_length = htons(scm->m_pkthdr.len - sizeof(struct sctphdr));
9143 	if (scm->m_pkthdr.len % 4) {
9144 		/* need padding */
9145 		u_int32_t cpthis=0;
9146 		int padlen;
9147 		padlen = 4 - (scm->m_pkthdr.len % 4);
9148 		m_copyback(scm, scm->m_pkthdr.len, padlen, (void *)&cpthis);
9149 	}
9150 	if ((sctp_no_csum_on_loopback) && m_get_rcvif_NOMPSAFE(m) != NULL &&
9151 	    m_get_rcvif_NOMPSAFE(m)->if_type == IFT_LOOP) {
9152 		val = 0;
9153 	} else {
9154 		val = sctp_calculate_sum(scm, NULL, 0);
9155 	}
9156 	ohdr->checksum = val;
9157 	if (iph->ip_v == IPVERSION) {
9158 		/* V4 */
9159 		struct ip *out;
9160 		struct route ro;
9161 		M_PREPEND(scm, sizeof(struct ip), M_DONTWAIT);
9162 		if (scm == NULL)
9163 			return;
9164 		memset(&ro, 0, sizeof ro);
9165 		out = mtod(scm, struct ip *);
9166 		out->ip_v = iph->ip_v;
9167 		out->ip_hl = (sizeof(struct ip)/4);
9168 		out->ip_tos = iph->ip_tos;
9169 		out->ip_id = iph->ip_id;
9170 		out->ip_off = 0;
9171 		out->ip_ttl = MAXTTL;
9172 		out->ip_p = IPPROTO_SCTP;
9173 		out->ip_sum = 0;
9174 		out->ip_src = iph->ip_dst;
9175 		out->ip_dst = iph->ip_src;
9176 		out->ip_len = htons(scm->m_pkthdr.len);
9177 		ip_output(scm, 0, &ro, IP_RAWOUTPUT, NULL, NULL);
9178 		sctp_pegs[SCTP_DATAGRAMS_SENT]++;
9179 	} else {
9180 		/* V6 */
9181 		struct route ro;
9182 		struct ip6_hdr *out6, *in6;
9183 
9184 		M_PREPEND(scm, sizeof(struct ip6_hdr), M_DONTWAIT);
9185 		if (scm == NULL)
9186 			return;
9187 		memset(&ro, 0, sizeof ro);
9188 		in6 = mtod(m, struct ip6_hdr *);
9189 		out6 = mtod(scm, struct ip6_hdr *);
9190 		out6->ip6_flow = in6->ip6_flow;
9191 		out6->ip6_hlim = ip6_defhlim;
9192 		out6->ip6_nxt = IPPROTO_SCTP;
9193 		out6->ip6_src = in6->ip6_dst;
9194 		out6->ip6_dst = in6->ip6_src;
9195 
9196 #ifdef SCTP_DEBUG
9197 		memset(&lsa6, 0, sizeof(lsa6));
9198 		lsa6.sin6_len = sizeof(lsa6);
9199 		lsa6.sin6_family = AF_INET6;
9200 		lsa6.sin6_addr = out6->ip6_src;
9201 		memset(&fsa6, 0, sizeof(fsa6));
9202 		fsa6.sin6_len = sizeof(fsa6);
9203 		fsa6.sin6_family = AF_INET6;
9204 		fsa6.sin6_addr = out6->ip6_dst;
9205 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT2) {
9206 			printf("sctp_operr_to calling ipv6 output:\n");
9207 			printf("src: ");
9208 			sctp_print_address((struct sockaddr *)&lsa6);
9209 			printf("dst ");
9210 			sctp_print_address((struct sockaddr *)&fsa6);
9211 		}
9212 #endif /* SCTP_DEBUG */
9213 		ip6_output(scm, NULL, &ro, 0, NULL, NULL, NULL);
9214 		sctp_pegs[SCTP_DATAGRAMS_SENT]++;
9215 	}
9216 }
9217 
9218 static int
9219 sctp_copy_one(struct mbuf *m, struct uio *uio, int cpsz, int resv_upfront, int *mbcnt)
9220 {
9221 	int left, cancpy, willcpy, error;
9222 	left = cpsz;
9223 
9224 	if (m == NULL) {
9225 		/* TSNH */
9226 		*mbcnt = 0;
9227 		return (ENOMEM);
9228 	}
9229 	m->m_len = 0;
9230 	if ((left+resv_upfront) > (int)MHLEN) {
9231 		MCLGET(m, M_WAIT);
9232 		if (m == NULL) {
9233 			*mbcnt = 0;
9234 			return (ENOMEM);
9235 		}
9236 		if ((m->m_flags & M_EXT) == 0) {
9237 			*mbcnt = 0;
9238 			return (ENOMEM);
9239 		}
9240 		*mbcnt += m->m_ext.ext_size;
9241 	}
9242 	*mbcnt += MSIZE;
9243 	cancpy = M_TRAILINGSPACE(m);
9244 	willcpy = uimin(cancpy, left);
9245 	if ((willcpy + resv_upfront) > cancpy) {
9246 		willcpy -= resv_upfront;
9247 	}
9248 	while (left > 0) {
9249 		/* Align data to the end */
9250 		if ((m->m_flags & M_EXT) == 0) {
9251 			m_align(m, willcpy);
9252 		} else {
9253 			MC_ALIGN(m, willcpy);
9254 		}
9255 		error = uiomove(mtod(m, void *), willcpy, uio);
9256 		if (error) {
9257 			return (error);
9258 		}
9259 		m->m_len = willcpy;
9260 		m->m_nextpkt = 0;
9261 		left -= willcpy;
9262 		if (left > 0) {
9263 			MGET(m->m_next, M_WAIT, MT_DATA);
9264 			if (m->m_next == NULL) {
9265 				*mbcnt = 0;
9266 				return (ENOMEM);
9267 			}
9268 			m = m->m_next;
9269 			m->m_len = 0;
9270 			*mbcnt += MSIZE;
9271 			if (left > (int)MHLEN) {
9272 				MCLGET(m, M_WAIT);
9273 				if (m == NULL) {
9274 					*mbcnt = 0;
9275 					return (ENOMEM);
9276 				}
9277 				if ((m->m_flags & M_EXT) == 0) {
9278 					*mbcnt = 0;
9279 					return (ENOMEM);
9280 				}
9281 				*mbcnt += m->m_ext.ext_size;
9282 			}
9283 			cancpy = M_TRAILINGSPACE(m);
9284 			willcpy = uimin(cancpy, left);
9285 		}
9286 	}
9287 	return (0);
9288 }
9289 
9290 static int
9291 sctp_copy_it_in(struct sctp_inpcb *inp,
9292 		struct sctp_tcb *stcb,
9293 		struct sctp_association *asoc,
9294 		struct sctp_nets *net,
9295 		struct sctp_sndrcvinfo *srcv,
9296 		struct uio *uio,
9297 		int flags)
9298 {
9299 	/* This routine must be very careful in
9300 	 * its work. Protocol processing is
9301 	 * up and running so care must be taken to
9302 	 * spl...() when you need to do something
9303 	 * that may effect the stcb/asoc. The sb is
9304 	 * locked however. When data is copied the
9305 	 * protocol processing should be enabled since
9306 	 * this is a slower operation...
9307 	 */
9308 	struct socket *so;
9309 	int error = 0;
9310 	int frag_size, mbcnt = 0, mbcnt_e = 0;
9311 	unsigned int sndlen;
9312 	unsigned int tot_demand;
9313 	int tot_out, dataout;
9314 	struct sctp_tmit_chunk *chk;
9315 	struct mbuf *mm;
9316 	struct sctp_stream_out *strq;
9317 	uint32_t my_vtag;
9318 	int resv_in_first;
9319 
9320 	so = stcb->sctp_socket;
9321 	solock(so);
9322 	chk = NULL;
9323 	mm = NULL;
9324 
9325 	sndlen = uio->uio_resid;
9326 	/* lock the socket buf */
9327 	error = sblock(&so->so_snd, SBLOCKWAIT(flags));
9328 	if (error)
9329 		goto out_locked;
9330 
9331 #ifdef SCTP_DEBUG
9332 	printf("sctp_copy_it_in: %d\n", sndlen);
9333 #endif
9334 	/* will it ever fit ? */
9335 	if (sndlen > so->so_snd.sb_hiwat) {
9336 		/* It will NEVER fit */
9337 		error = EMSGSIZE;
9338 		goto release;
9339 	}
9340 	/* Do I need to block? */
9341 	if ((so->so_snd.sb_hiwat <
9342 	    (sndlen + asoc->total_output_queue_size)) ||
9343 	    (asoc->chunks_on_out_queue > sctp_max_chunks_on_queue) ||
9344 	    (asoc->total_output_mbuf_queue_size >
9345 	    so->so_snd.sb_mbmax)
9346 	) {
9347 		/* prune any prsctp bufs out */
9348 		if (asoc->peer_supports_prsctp) {
9349 			sctp_prune_prsctp(stcb, asoc, srcv, sndlen);
9350 		}
9351 		/*
9352 		 * We store off a pointer to the endpoint.
9353 		 * Since on return from this we must check to
9354 		 * see if an so_error is set. If so we may have
9355 		 * been reset and our stcb destroyed. Returning
9356 		 * an error will flow back to the user...
9357 		 */
9358 		while ((so->so_snd.sb_hiwat <
9359 		    (sndlen + asoc->total_output_queue_size)) ||
9360 		    (asoc->chunks_on_out_queue >
9361 		    sctp_max_chunks_on_queue) ||
9362 		    (asoc->total_output_mbuf_queue_size >
9363 		    so->so_snd.sb_mbmax)
9364 		) {
9365 			if ((so->so_state & SS_NBIO)
9366 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
9367 			    || (flags & MSG_NBIO)
9368 #endif
9369 				) {
9370 				/* Non-blocking io in place */
9371 				error = EWOULDBLOCK;
9372 				goto release;
9373 			}
9374 			inp->sctp_tcb_at_block = (void *)stcb;
9375 			inp->error_on_block = 0;
9376 #ifdef SCTP_BLK_LOGGING
9377 			sctp_log_block(SCTP_BLOCK_LOG_INTO_BLK,
9378 			    so, asoc);
9379 #endif
9380 			sbunlock(&so->so_snd);
9381 			SCTP_TCB_UNLOCK(stcb);
9382 			error = sbwait(&so->so_snd);
9383 			SCTP_INP_RLOCK(inp);
9384 			if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
9385 			    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) {
9386 				/* Should I really unlock ? */
9387 				SCTP_INP_RUNLOCK(inp);
9388 				error = EFAULT;
9389 				goto out_locked;
9390 			}
9391 			SCTP_TCB_LOCK(stcb);
9392 			SCTP_INP_RUNLOCK(inp);
9393 
9394 			inp->sctp_tcb_at_block = 0;
9395 #ifdef SCTP_BLK_LOGGING
9396 			sctp_log_block(SCTP_BLOCK_LOG_OUTOF_BLK,
9397 			    so, asoc);
9398 #endif
9399 			if (inp->error_on_block) {
9400 				/*
9401 				 * if our asoc was killed, the free code
9402 				 * (in sctp_pcb.c) will save a error in
9403 				 * here for us
9404 				 */
9405  				error = inp->error_on_block;
9406 				goto out_locked;
9407 			}
9408 			if (error) {
9409 				goto out_locked;
9410 			}
9411 			/* did we encounter a socket error? */
9412 			if (so->so_error) {
9413 				error = so->so_error;
9414 				goto out_locked;
9415 			}
9416 			error = sblock(&so->so_snd, M_WAITOK);
9417 			if (error) {
9418 				/* Can't acquire the lock */
9419 				goto out_locked;
9420 			}
9421 #if defined(__FreeBSD__) && __FreeBSD_version >= 502115
9422 			if (so->so_rcv.sb_state & SBS_CANTSENDMORE) {
9423 #else
9424 			if (so->so_state & SS_CANTSENDMORE) {
9425 #endif
9426 				/* The socket is now set not to sendmore.. its gone */
9427 				error = EPIPE;
9428 				goto release;
9429 			}
9430 			if (so->so_error) {
9431 				error = so->so_error;
9432 				goto release;
9433 			}
9434 			if (asoc->peer_supports_prsctp) {
9435 				sctp_prune_prsctp(stcb, asoc, srcv, sndlen);
9436 			}
9437 		}
9438 	}
9439 	dataout = tot_out = uio->uio_resid;
9440  	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
9441 		resv_in_first = SCTP_MED_OVERHEAD;
9442 	} else {
9443 		resv_in_first = SCTP_MED_V4_OVERHEAD;
9444 	}
9445 
9446 	/* Are we aborting? */
9447 	if (srcv->sinfo_flags & SCTP_ABORT) {
9448 		if ((SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_WAIT) &&
9449 		    (SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_ECHOED)) {
9450 			/* It has to be up before we abort */
9451 			/* how big is the user initiated abort? */
9452 
9453 			/* I wonder about doing a MGET without a splnet set.
9454 			 * it is done that way in the sosend code so I guess
9455 			 * it is ok :-0
9456 			 */
9457  			MGETHDR(mm, M_WAIT, MT_DATA);
9458 			if (mm) {
9459 				struct sctp_paramhdr *ph;
9460 
9461 				tot_demand = (tot_out + sizeof(struct sctp_paramhdr));
9462 				if (tot_demand > MHLEN) {
9463 					if (tot_demand > MCLBYTES) {
9464 						/* truncate user data */
9465 						tot_demand = MCLBYTES;
9466 						tot_out = tot_demand - sizeof(struct sctp_paramhdr);
9467 					}
9468 					MCLGET(mm, M_WAIT);
9469 					if ((mm->m_flags & M_EXT) == 0) {
9470 						/* truncate further */
9471 						tot_demand = MHLEN;
9472 						tot_out = tot_demand - sizeof(struct sctp_paramhdr);
9473 					}
9474 				}
9475 				/* now move forward the data pointer */
9476 				ph = mtod(mm, struct sctp_paramhdr *);
9477 				ph->param_type = htons(SCTP_CAUSE_USER_INITIATED_ABT);
9478 				ph->param_length = htons((sizeof(struct sctp_paramhdr) + tot_out));
9479 				ph++;
9480 				mm->m_pkthdr.len = tot_out + sizeof(struct sctp_paramhdr);
9481 				mm->m_len = mm->m_pkthdr.len;
9482 				error = uiomove((void *)ph, (int)tot_out, uio);
9483 				if (error) {
9484 					/*
9485 					 * Here if we can't get his data we
9486 					 * still abort we just don't get to
9487 					 * send the users note :-0
9488 					 */
9489 					sctp_m_freem(mm);
9490 					mm = NULL;
9491 				}
9492 			}
9493 			sbunlock(&so->so_snd);
9494 			sctp_abort_an_association(stcb->sctp_ep, stcb,
9495 						  SCTP_RESPONSE_TO_USER_REQ,
9496 						  mm);
9497 			mm = NULL;
9498 			goto out_locked;
9499 		}
9500 		goto release;
9501 	}
9502 
9503 	/* Now can we send this? */
9504 	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
9505 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
9506 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
9507 	    (asoc->state & SCTP_STATE_SHUTDOWN_PENDING)) {
9508 		/* got data while shutting down */
9509 		error = ECONNRESET;
9510 		goto release;
9511  	}
9512  	/* Is the stream no. valid? */
9513 	if (srcv->sinfo_stream >= asoc->streamoutcnt) {
9514  		/* Invalid stream number */
9515 		error = EINVAL;
9516 		goto release;
9517  	}
9518 	if (asoc->strmout == NULL) {
9519 		/* huh? software error */
9520 #ifdef SCTP_DEBUG
9521  		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
9522  			printf("software error in sctp_copy_it_in\n");
9523  		}
9524 #endif
9525 		error = EFAULT;
9526 		goto release;
9527 	}
9528 	if ((srcv->sinfo_flags & SCTP_EOF) &&
9529 	    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_UDPTYPE) &&
9530 	    (tot_out == 0)) {
9531 		sounlock(so);
9532 		goto zap_by_it_now;
9533 	}
9534  	if (tot_out == 0) {
9535  		/* not allowed */
9536  		error = EMSGSIZE;
9537 		goto release;
9538  	}
9539 	/* save off the tag */
9540 	my_vtag = asoc->my_vtag;
9541 	strq = &asoc->strmout[srcv->sinfo_stream];
9542 	/* First lets figure out the "chunking" point */
9543 	frag_size = sctp_get_frag_point(stcb, asoc);
9544 
9545 	/* two choices here, it all fits in one chunk or
9546 	 * we need multiple chunks.
9547 	 */
9548 	sounlock(so);
9549 	if (tot_out <= frag_size) {
9550 		/* no need to setup a template */
9551 		chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
9552 		if (chk == NULL) {
9553 			error = ENOMEM;
9554 			goto release;
9555 		}
9556 		sctppcbinfo.ipi_count_chunk++;
9557 		sctppcbinfo.ipi_gencnt_chunk++;
9558 		asoc->chunks_on_out_queue++;
9559 		MGETHDR(mm, M_WAIT, MT_DATA);
9560 		if (mm == NULL) {
9561 			error = ENOMEM;
9562 			goto clean_up;
9563 		}
9564 		error = sctp_copy_one(mm, uio, tot_out, resv_in_first, &mbcnt_e);
9565 		if (error)
9566 			goto clean_up;
9567 		sctp_prepare_chunk(chk, stcb, srcv, strq, net);
9568 		chk->mbcnt = mbcnt_e;
9569 		mbcnt += mbcnt_e;
9570 		mbcnt_e = 0;
9571 		mm->m_pkthdr.len = tot_out;
9572 		chk->data = mm;
9573 		mm = NULL;
9574 
9575 		/* the actual chunk flags */
9576 		chk->rec.data.rcv_flags |= SCTP_DATA_NOT_FRAG;
9577 		chk->whoTo->ref_count++;
9578 
9579 		/* fix up the send_size if it is not present */
9580 		chk->send_size = tot_out;
9581 		chk->book_size = chk->send_size;
9582 		/* ok, we are committed */
9583 		if ((srcv->sinfo_flags & SCTP_UNORDERED) == 0) {
9584 			/* bump the ssn if we are unordered. */
9585 			strq->next_sequence_sent++;
9586 		}
9587 		if (chk->flags & SCTP_PR_SCTP_BUFFER) {
9588 			asoc->sent_queue_cnt_removeable++;
9589 		}
9590 		solock(so);
9591 		if ((asoc->state == 0) ||
9592 		    (my_vtag != asoc->my_vtag) ||
9593 		    (so != inp->sctp_socket) ||
9594 		    (inp->sctp_socket == 0)) {
9595 			/* connection was aborted */
9596 			sounlock(so);
9597 			error = ECONNRESET;
9598 			goto clean_up;
9599 		}
9600 		asoc->stream_queue_cnt++;
9601 		TAILQ_INSERT_TAIL(&strq->outqueue, chk, sctp_next);
9602 		/* now check if this stream is on the wheel */
9603 		if ((strq->next_spoke.tqe_next == NULL) &&
9604 		    (strq->next_spoke.tqe_prev == NULL)) {
9605 			/* Insert it on the wheel since it is not
9606 			 * on it currently
9607 			 */
9608 			sctp_insert_on_wheel(asoc, strq);
9609 		}
9610 		sounlock(so);
9611 clean_up:
9612 		if (error) {
9613 			SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
9614 			sctppcbinfo.ipi_count_chunk--;
9615 			if ((int)sctppcbinfo.ipi_count_chunk < 0) {
9616 				panic("Chunk count is negative");
9617 			}
9618 			goto release;
9619 		}
9620 	} else {
9621 		/* we need to setup a template */
9622 		struct sctp_tmit_chunk template;
9623 		struct sctpchunk_listhead tmp;
9624 
9625 		/* setup the template */
9626 		sctp_prepare_chunk(&template, stcb, srcv, strq, net);
9627 
9628 		/* Prepare the temp list */
9629 		TAILQ_INIT(&tmp);
9630 
9631 		/* Template is complete, now time for the work */
9632 		while (tot_out > 0) {
9633 			/* Get a chunk */
9634  			chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
9635 			if (chk == NULL) {
9636 				/*
9637 				 * ok we must spin through and dump anything
9638 				 * we have allocated and then jump to the
9639 				 * no_membad
9640 				 */
9641 				error = ENOMEM;
9642 			}
9643 			sctppcbinfo.ipi_count_chunk++;
9644 			asoc->chunks_on_out_queue++;
9645 
9646 			sctppcbinfo.ipi_gencnt_chunk++;
9647 			*chk = template;
9648 			chk->whoTo->ref_count++;
9649 			MGETHDR(chk->data, M_WAIT, MT_DATA);
9650 			if (chk->data == NULL) {
9651 				error = ENOMEM;
9652 				goto temp_clean_up;
9653 			}
9654 			tot_demand = uimin(tot_out, frag_size);
9655 			error = sctp_copy_one(chk->data, uio, tot_demand , resv_in_first, &mbcnt_e);
9656 			if (error)
9657 				goto temp_clean_up;
9658 			/* now fix the chk->send_size */
9659 			chk->mbcnt = mbcnt_e;
9660 			mbcnt += mbcnt_e;
9661 			mbcnt_e = 0;
9662 			chk->send_size = tot_demand;
9663 			chk->data->m_pkthdr.len = tot_demand;
9664 			chk->book_size = chk->send_size;
9665 			if (chk->flags & SCTP_PR_SCTP_BUFFER) {
9666 				asoc->sent_queue_cnt_removeable++;
9667 			}
9668 			TAILQ_INSERT_TAIL(&tmp, chk, sctp_next);
9669 			tot_out -= tot_demand;
9670 		}
9671 		/* Now the tmp list holds all chunks and data */
9672 		if ((srcv->sinfo_flags & SCTP_UNORDERED) == 0) {
9673 			/* bump the ssn if we are unordered. */
9674 			strq->next_sequence_sent++;
9675 		}
9676 		/* Mark the first/last flags. This will
9677 		 * result int a 3 for a single item on the list
9678 		 */
9679 		chk = TAILQ_FIRST(&tmp);
9680 		chk->rec.data.rcv_flags |= SCTP_DATA_FIRST_FRAG;
9681 		chk = TAILQ_LAST(&tmp, sctpchunk_listhead);
9682 		chk->rec.data.rcv_flags |= SCTP_DATA_LAST_FRAG;
9683 
9684 		/* now move it to the streams actual queue */
9685 		/* first stop protocol processing */
9686 		mutex_enter(softnet_lock);
9687 		if ((asoc->state == 0) ||
9688 		    (my_vtag != asoc->my_vtag) ||
9689 		    (so != inp->sctp_socket) ||
9690 		    (inp->sctp_socket == 0)) {
9691 			/* connection was aborted */
9692 			mutex_exit(softnet_lock);
9693 			error = ECONNRESET;
9694 			goto temp_clean_up;
9695 		}
9696 		chk = TAILQ_FIRST(&tmp);
9697 		while (chk) {
9698 			chk->data->m_nextpkt = 0;
9699 			TAILQ_REMOVE(&tmp, chk, sctp_next);
9700 			asoc->stream_queue_cnt++;
9701 			TAILQ_INSERT_TAIL(&strq->outqueue, chk, sctp_next);
9702 			chk = TAILQ_FIRST(&tmp);
9703 		}
9704 		/* now check if this stream is on the wheel */
9705 		if ((strq->next_spoke.tqe_next == NULL) &&
9706 		    (strq->next_spoke.tqe_prev == NULL)) {
9707 			/* Insert it on the wheel since it is not
9708 			 * on it currently
9709 			 */
9710 			sctp_insert_on_wheel(asoc, strq);
9711 		}
9712 		/* Ok now we can allow pping */
9713 		mutex_exit(softnet_lock);
9714 temp_clean_up:
9715 		if (error) {
9716 			chk = TAILQ_FIRST(&tmp);
9717 			while (chk) {
9718 				if (chk->data) {
9719 					sctp_m_freem(chk->data);
9720 					chk->data = NULL;
9721 				}
9722 				TAILQ_REMOVE(&tmp, chk, sctp_next);
9723 				SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
9724 				sctppcbinfo.ipi_count_chunk--;
9725 				asoc->chunks_on_out_queue--;
9726 				if ((int)sctppcbinfo.ipi_count_chunk < 0) {
9727 					panic("Chunk count is negative");
9728 				}
9729 				sctppcbinfo.ipi_gencnt_chunk++;
9730 				chk = TAILQ_FIRST(&tmp);
9731 			}
9732 			goto release;
9733 		}
9734 	}
9735 zap_by_it_now:
9736 #ifdef SCTP_MBCNT_LOGGING
9737 	sctp_log_mbcnt(SCTP_LOG_MBCNT_INCREASE,
9738 		       asoc->total_output_queue_size,
9739 		       dataout,
9740 		       asoc->total_output_mbuf_queue_size,
9741 		       mbcnt);
9742 #endif
9743 	solock(so);
9744 	asoc->total_output_queue_size += dataout;
9745 	asoc->total_output_mbuf_queue_size += mbcnt;
9746 	if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
9747 	    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
9748 		so->so_snd.sb_cc += dataout;
9749 		so->so_snd.sb_mbcnt += mbcnt;
9750 	}
9751 	if ((srcv->sinfo_flags & SCTP_EOF) &&
9752 	    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_UDPTYPE)
9753 		) {
9754 		int some_on_streamwheel = 0;
9755 		error = 0;
9756 		if (!TAILQ_EMPTY(&asoc->out_wheel)) {
9757 			/* Check to see if some data queued */
9758 			struct sctp_stream_out *outs;
9759 			TAILQ_FOREACH(outs, &asoc->out_wheel, next_spoke) {
9760 				if (!TAILQ_EMPTY(&outs->outqueue)) {
9761 					some_on_streamwheel = 1;
9762 					break;
9763 				}
9764 			}
9765 		}
9766 		if (TAILQ_EMPTY(&asoc->send_queue) &&
9767 		    TAILQ_EMPTY(&asoc->sent_queue) &&
9768 		    (some_on_streamwheel == 0)) {
9769 			/* there is nothing queued to send, so I'm done... */
9770 			if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
9771 			    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
9772 				/* only send SHUTDOWN the first time through */
9773 #ifdef SCTP_DEBUG
9774 				if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
9775 					printf("%s:%d sends a shutdown\n",
9776 					       __FILE__,
9777 					       __LINE__
9778 						);
9779 				}
9780 #endif
9781 				sctp_send_shutdown(stcb, stcb->asoc.primary_destination);
9782 				asoc->state = SCTP_STATE_SHUTDOWN_SENT;
9783 				sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, stcb->sctp_ep, stcb,
9784 						 asoc->primary_destination);
9785 				sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
9786 						 asoc->primary_destination);
9787 			}
9788 		} else {
9789 			/*
9790 			 * we still got (or just got) data to send, so set
9791 			 * SHUTDOWN_PENDING
9792 			 */
9793 			/*
9794 			 * XXX sockets draft says that SCTP_EOF should be sent
9795 			 * with no data.  currently, we will allow user data
9796 			 * to be sent first and move to SHUTDOWN-PENDING
9797 			 */
9798 			asoc->state |= SCTP_STATE_SHUTDOWN_PENDING;
9799 		}
9800 	}
9801 #ifdef SCTP_DEBUG
9802 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT2) {
9803 		printf("++total out:%d total_mbuf_out:%d\n",
9804 		       (int)asoc->total_output_queue_size,
9805 		       (int)asoc->total_output_mbuf_queue_size);
9806 	}
9807 #endif
9808 
9809 release:
9810 	sbunlock(&so->so_snd);
9811 out_locked:
9812 	sounlock(so);
9813 
9814 	if (mm)
9815 		sctp_m_freem(mm);
9816 	return (error);
9817 }
9818 
9819 
9820 int
9821 sctp_sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
9822 	    struct mbuf *top, struct mbuf *control, int flags, struct lwp *p)
9823 {
9824 	int error, use_rcvinfo;
9825 	int queue_only = 0, queue_only_for_init=0;
9826 	int un_sent = 0;
9827 	int now_filled=0;
9828 	struct sctp_inpcb *inp;
9829  	struct sctp_tcb *stcb=NULL;
9830 	struct sctp_sndrcvinfo srcv;
9831 	struct timeval now;
9832 	struct sctp_nets *net;
9833 	struct sctp_association *asoc;
9834 	struct sctp_inpcb *t_inp;
9835 	int create_lock_applied = 0;
9836 
9837 	error = use_rcvinfo = 0;
9838 	net = NULL;
9839 	stcb = NULL;
9840 	asoc = NULL;
9841 	t_inp = inp = (struct sctp_inpcb *)so->so_pcb;
9842 
9843 	solock(so);
9844 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) &&
9845 	    (inp->sctp_flags & SCTP_PCB_FLAGS_ACCEPTING)) {
9846 		/* The listner can NOT send */
9847 		error = EFAULT;
9848 		sounlock(so);
9849 		goto out;
9850 	}
9851 	if (addr) {
9852 		SCTP_ASOC_CREATE_LOCK(inp);
9853 		if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
9854 		    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) {
9855 			/* Should I really unlock ? */
9856 			error = EFAULT;
9857 			sounlock(so);
9858 			goto out;
9859 
9860 		}
9861 		create_lock_applied = 1;
9862 		if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) &&
9863 		    (addr->sa_family == AF_INET6)) {
9864 			error = EINVAL;
9865 			sounlock(so);
9866 			goto out;
9867 		}
9868 	}
9869 	/* now we must find the assoc */
9870 	if (inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) {
9871 		SCTP_INP_RLOCK(inp);
9872 		stcb = LIST_FIRST(&inp->sctp_asoc_list);
9873 		if (stcb == NULL) {
9874 			SCTP_INP_RUNLOCK(inp);
9875 			error = ENOTCONN;
9876 			sounlock(so);
9877 			goto out;
9878 		}
9879 		SCTP_TCB_LOCK(stcb);
9880 		SCTP_INP_RUNLOCK(inp);
9881 		net = stcb->asoc.primary_destination;
9882 	}
9883 #ifdef SCTP_DEBUG
9884 	printf("sctp_sosend: get control\n");
9885 #endif
9886 	/* get control */
9887 	if (control) {
9888 		/* process cmsg snd/rcv info (maybe a assoc-id) */
9889 		if (sctp_find_cmsg(SCTP_SNDRCV, (void *)&srcv, control,
9890 				   sizeof(srcv))) {
9891 			/* got one */
9892 			if (srcv.sinfo_flags & SCTP_SENDALL) {
9893 				/* its a sendall */
9894 				sctppcbinfo.mbuf_track--;
9895 				sctp_m_freem(control);
9896 
9897 				if (create_lock_applied) {
9898 					SCTP_ASOC_CREATE_UNLOCK(inp);
9899 					create_lock_applied = 0;
9900 				}
9901 				return (sctp_sendall(inp, uio, top, &srcv));
9902 			}
9903 			use_rcvinfo = 1;
9904 		}
9905 	}
9906 #ifdef SCTP_DEBUG
9907 	printf("sctp_sosend: doing lookup\n");
9908 #endif
9909 	if (stcb == NULL) {
9910 		/* Need to do a lookup */
9911 		if (use_rcvinfo && srcv.sinfo_assoc_id) {
9912 			stcb = sctp_findassociation_ep_asocid(inp, srcv.sinfo_assoc_id);
9913 			/*
9914 			 * Question: Should I error here if the assoc_id is
9915 			 * no longer valid? i.e. I can't find it?
9916 			 */
9917 			if ((stcb) &&
9918 			    (addr != NULL)) {
9919 				/* Must locate the net structure */
9920 				net = sctp_findnet(stcb, addr);
9921 			}
9922 		}
9923 		if (stcb == NULL) {
9924 			if (addr != NULL) {
9925 				/* Since we did not use findep we must
9926 				 * increment it, and if we don't find a
9927 				 * tcb decrement it.
9928 				 */
9929 				SCTP_INP_WLOCK(inp);
9930 				SCTP_INP_INCR_REF(inp);
9931 				SCTP_INP_WUNLOCK(inp);
9932 				stcb = sctp_findassociation_ep_addr(&t_inp, addr, &net, NULL, NULL);
9933 				if (stcb == NULL) {
9934 					SCTP_INP_WLOCK(inp);
9935 					SCTP_INP_DECR_REF(inp);
9936 					SCTP_INP_WUNLOCK(inp);
9937 				}
9938 			}
9939 		}
9940 	}
9941 	if ((stcb == NULL) &&
9942 	    (inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE)) {
9943 		error = ENOTCONN;
9944 		sounlock(so);
9945 		goto out;
9946 	} else if ((stcb == NULL) && (addr == NULL)) {
9947 		error = ENOENT;
9948 		sounlock(so);
9949 		goto out;
9950 	} else if (stcb == NULL) {
9951 		/* UDP style, we must go ahead and start the INIT process */
9952 		if ((use_rcvinfo) &&
9953 		    (srcv.sinfo_flags & SCTP_ABORT)) {
9954 			/* User asks to abort a non-existent asoc */
9955 			error = ENOENT;
9956 			sounlock(so);
9957 			goto out;
9958 		}
9959 		/* get an asoc/stcb struct */
9960 		stcb = sctp_aloc_assoc(inp, addr, 1, &error, 0);
9961 		if (stcb == NULL) {
9962 			/* Error is setup for us in the call */
9963 			sounlock(so);
9964 			goto out;
9965 		}
9966 		if (create_lock_applied) {
9967 			SCTP_ASOC_CREATE_UNLOCK(inp);
9968 			create_lock_applied = 0;
9969 		} else {
9970 			printf("Huh-3? create lock should have been on??\n");
9971 		}
9972 		/* Turn on queue only flag to prevent data from being sent */
9973  		queue_only = 1;
9974 		asoc = &stcb->asoc;
9975 		asoc->state = SCTP_STATE_COOKIE_WAIT;
9976 		SCTP_GETTIME_TIMEVAL(&asoc->time_entered);
9977 		if (control) {
9978 			/* see if a init structure exists in cmsg headers */
9979 			struct sctp_initmsg initm;
9980 			int i;
9981 			if (sctp_find_cmsg(SCTP_INIT, (void *)&initm, control, sizeof(initm))) {
9982 				/* we have an INIT override of the default */
9983 				if (initm.sinit_max_attempts)
9984 					asoc->max_init_times = initm.sinit_max_attempts;
9985 				if (initm.sinit_num_ostreams)
9986 					asoc->pre_open_streams = initm.sinit_num_ostreams;
9987 				if (initm.sinit_max_instreams)
9988 					asoc->max_inbound_streams = initm.sinit_max_instreams;
9989 				if (initm.sinit_max_init_timeo)
9990 					asoc->initial_init_rto_max = initm.sinit_max_init_timeo;
9991 				if (asoc->streamoutcnt < asoc->pre_open_streams) {
9992 					/* Default is NOT correct */
9993 #ifdef SCTP_DEBUG
9994 					if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
9995 						printf("Ok, defout:%d pre_open:%d\n",
9996 						       asoc->streamoutcnt, asoc->pre_open_streams);
9997 					}
9998 #endif
9999 					free(asoc->strmout, M_PCB);
10000 					asoc->strmout = NULL;
10001 					asoc->streamoutcnt = asoc->pre_open_streams;
10002 
10003 					/* What happesn if this fails? .. we panic ...*/
10004 					asoc->strmout = malloc(
10005 					       asoc->streamoutcnt *
10006 					       sizeof(struct sctp_stream_out),
10007 					       M_PCB, M_WAIT);
10008 					for (i = 0; i < asoc->streamoutcnt; i++) {
10009 						/*
10010 						 * inbound side must be set to 0xffff,
10011 						 * also NOTE when we get the INIT-ACK
10012 						 * back (for INIT sender) we MUST
10013 						 * reduce the count (streamoutcnt) but
10014 						 * first check if we sent to any of the
10015 						 * upper streams that were dropped (if
10016 						 * some were). Those that were dropped
10017 						 * must be notified to the upper layer
10018 						 * as failed to send.
10019 						 */
10020 						asoc->strmout[i].next_sequence_sent = 0x0;
10021 						TAILQ_INIT(&asoc->strmout[i].outqueue);
10022 						asoc->strmout[i].stream_no = i;
10023 						asoc->strmout[i].next_spoke.tqe_next = 0;
10024 						asoc->strmout[i].next_spoke.tqe_prev = 0;
10025 					}
10026 				}
10027 			}
10028 
10029 		}
10030 		/* out with the INIT */
10031 		queue_only_for_init = 1;
10032 		sctp_send_initiate(inp, stcb);
10033 		/*
10034 		 * we may want to dig in after this call and adjust the MTU
10035 		 * value. It defaulted to 1500 (constant) but the ro structure
10036 		 * may now have an update and thus we may need to change it
10037 		 * BEFORE we append the message.
10038 		 */
10039 		net = stcb->asoc.primary_destination;
10040 		asoc = &stcb->asoc;
10041 	} else {
10042 		asoc = &stcb->asoc;
10043 	}
10044 	if (create_lock_applied) {
10045 		SCTP_ASOC_CREATE_UNLOCK(inp);
10046 		create_lock_applied = 0;
10047 	}
10048 	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
10049 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)) {
10050 		queue_only = 1;
10051 	}
10052 	if (use_rcvinfo == 0) {
10053 		/* Grab the default stuff from the asoc */
10054 		srcv = stcb->asoc.def_send;
10055 	}
10056 	/* we are now done with all control */
10057 	if (control) {
10058 		sctp_m_freem(control);
10059 		control = NULL;
10060 	}
10061 
10062 	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
10063 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
10064 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
10065 	    (asoc->state & SCTP_STATE_SHUTDOWN_PENDING)) {
10066 		if ((use_rcvinfo) &&
10067 		    (srcv.sinfo_flags & SCTP_ABORT)) {
10068 			;
10069 		} else {
10070 			error = ECONNRESET;
10071 			sounlock(so);
10072 			goto out;
10073 		}
10074 	}
10075 	/* Ok, we will attempt a msgsnd :> */
10076 #if 0	/* XXX */
10077 	if (p)
10078 		p->p_stats->p_ru.ru_msgsnd++;
10079 #endif
10080 
10081 	if (stcb) {
10082 		if (net && ((srcv.sinfo_flags & SCTP_ADDR_OVER))) {
10083 			/* we take the override or the unconfirmed */
10084 			;
10085 		} else {
10086 			net = stcb->asoc.primary_destination;
10087 		}
10088 	}
10089 
10090 #ifdef SCTP_DEBUG
10091 	printf("sctp_sosend: before copying in %p\n", top);
10092 #endif
10093 	if (top == NULL) {
10094 		/* Must copy it all in from user land. The
10095 		 * socket buf is locked but we don't suspend
10096 		 * protocol processing until we are ready to
10097 		 * send/queue it.
10098 		 */
10099 		sounlock(so);
10100 #ifdef SCTP_DEBUG
10101 		printf("sctp_sosend: before cii\n");
10102 #endif
10103 		error = sctp_copy_it_in(inp, stcb, asoc, net, &srcv, uio, flags);
10104 #ifdef SCTP_DEBUG
10105 		printf("sctp_sosend: after cii\n");
10106 #endif
10107 		if (error)
10108 			goto out;
10109 	} else {
10110 		/* Here we must either pull in the user data to chunk
10111 		 * buffers, or use top to do a msg_append.
10112 		 */
10113  		error = sctp_msg_append(stcb, net, top, &srcv, flags);
10114 		sounlock(so);
10115 		if (error)
10116 			goto out;
10117 		/* zap the top since it is now being used */
10118 		top = 0;
10119 	}
10120 #ifdef SCTP_DEBUG
10121 	printf("sctp_sosend: after copying in\n");
10122 #endif
10123 	if (net->flight_size > net->cwnd) {
10124 		sctp_pegs[SCTP_SENDTO_FULL_CWND]++;
10125 		queue_only = 1;
10126 
10127 	} else if (asoc->ifp_had_enobuf) {
10128 		sctp_pegs[SCTP_QUEONLY_BURSTLMT]++;
10129 		queue_only = 1;
10130  	} else {
10131 		un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
10132 			   ((stcb->asoc.chunks_on_out_queue - stcb->asoc.total_flight_count) * sizeof(struct sctp_data_chunk)) +
10133 			   SCTP_MED_OVERHEAD);
10134 
10135 		if (((inp->sctp_flags & SCTP_PCB_FLAGS_NODELAY) == 0) &&
10136 		    (stcb->asoc.total_flight > 0) &&
10137 		    (un_sent < (int)stcb->asoc.smallest_mtu)) {
10138 
10139 			/* Ok, Nagle is set on and we have data outstanding. Don't
10140 			 * send anything and let SACKs drive out the data unless we
10141 			 * have a "full" segment to send.
10142 			 */
10143 			sctp_pegs[SCTP_NAGLE_NOQ]++;
10144 			queue_only = 1;
10145 		} else {
10146 			sctp_pegs[SCTP_NAGLE_OFF]++;
10147 		}
10148 	}
10149 	if (queue_only_for_init) {
10150 		/* It is possible to have a turn around of the
10151 		 * INIT/INIT-ACK/COOKIE before I have a chance to
10152 		 * copy in the data. In such a case I DO want to
10153 		 * send it out by reversing the queue only flag.
10154 		 */
10155 		if ((SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_WAIT) ||
10156 		    (SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_ECHOED)) {
10157 			/* yep, reverse it */
10158 			queue_only = 0;
10159 		}
10160  	}
10161 
10162 #ifdef SCTP_DEBUG
10163 	printf("sctp_sosend: before sending chunk\n");
10164 #endif
10165 	if ((queue_only == 0) && (stcb->asoc.peers_rwnd  && un_sent)) {
10166 		/* we can attempt to send too.*/
10167 #ifdef SCTP_DEBUG
10168 		if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
10169 			printf("USR Send calls sctp_chunk_output\n");
10170 		}
10171 #endif
10172 		solock(so);
10173 		sctp_pegs[SCTP_OUTPUT_FRM_SND]++;
10174 		sctp_chunk_output(inp, stcb, 0);
10175 		sounlock(so);
10176 	} else if ((queue_only == 0) &&
10177 		   (stcb->asoc.peers_rwnd == 0) &&
10178 		   (stcb->asoc.total_flight == 0)) {
10179 		/* We get to have a probe outstanding */
10180 		solock(so);
10181 		sctp_from_user_send = 1;
10182 		sctp_chunk_output(inp, stcb, 0);
10183 		sctp_from_user_send = 0;
10184 		sounlock(so);
10185 
10186 	} else if (!TAILQ_EMPTY(&stcb->asoc.control_send_queue)) {
10187 		int num_out, reason, cwnd_full;
10188 		/* Here we do control only */
10189 		solock(so);
10190 		sctp_med_chunk_output(inp, stcb, &stcb->asoc, &num_out,
10191 				      &reason, 1, &cwnd_full, 1, &now, &now_filled);
10192 		sounlock(so);
10193 	}
10194 #ifdef SCTP_DEBUG
10195 	if (sctp_debug_on & SCTP_DEBUG_OUTPUT1) {
10196 		printf("USR Send complete qo:%d prw:%d unsent:%d tf:%d cooq:%d toqs:%d \n",
10197 		       queue_only, stcb->asoc.peers_rwnd, un_sent,
10198 		       stcb->asoc.total_flight, stcb->asoc.chunks_on_out_queue,
10199 		       stcb->asoc.total_output_queue_size);
10200 	}
10201 #endif
10202  out:
10203 	if (create_lock_applied) {
10204 		SCTP_ASOC_CREATE_UNLOCK(inp);
10205 		create_lock_applied = 0;
10206 	}
10207 	if (stcb) {
10208 		SCTP_TCB_UNLOCK(stcb);
10209 	}
10210 	if (top)
10211 		sctp_m_freem(top);
10212 	if (control)
10213 		sctp_m_freem(control);
10214 	return (error);
10215 }
10216