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