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