Add DragonFly to the #ifdef mess.
[dragonfly.git] / sys / netinet / sctp_indata.c
1 /*      $KAME: sctp_indata.c,v 1.35 2004/08/17 04:06:17 itojun Exp $    */
2 /*      $DragonFly: src/sys/netinet/sctp_indata.c,v 1.2 2005/07/15 15:02:02 eirikn Exp $        */
3
4 /*
5  * Copyright (C) 2002, 2003, 2004 Cisco Systems Inc,
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 #if !(defined(__OpenBSD__) || defined(__APPLE__))
34 #include "opt_ipsec.h"
35 #endif
36 #if defined(__FreeBSD__) || defined(__DragonFly__)
37 #include "opt_inet6.h"
38 #include "opt_inet.h"
39 #endif
40 #if defined(__NetBSD__)
41 #include "opt_inet.h"
42 #endif
43
44 #ifdef __APPLE__
45 #include <sctp.h>
46 #elif !defined(__OpenBSD__)
47 #include "opt_sctp.h"
48 #endif
49
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/mbuf.h>
53 #include <sys/malloc.h>
54 #include <sys/socket.h>
55 #include <sys/socketvar.h>
56 #include <sys/sysctl.h>
57
58 #include <net/if.h>
59 #include <net/route.h>
60
61
62 #if defined(__FreeBSD__) && __FreeBSD_version >= 500000
63 #include <sys/limits.h>
64 #else
65 #include <machine/limits.h>
66 #endif
67 #include <machine/cpu.h>
68
69 #include <netinet/in.h>
70 #include <netinet/in_systm.h>
71 #include <netinet/ip.h>
72 #ifdef INET6
73 #include <netinet/ip6.h>
74 #endif /* INET6 */
75 #include <netinet/in_pcb.h>
76 #include <netinet/in_var.h>
77 #include <netinet/ip_var.h>
78 #ifdef INET6
79 #include <netinet6/ip6_var.h>
80 #endif /* INET6 */
81 #include <netinet/ip_icmp.h>
82 #include <netinet/icmp_var.h>
83 #include <netinet/sctp_var.h>
84 #include <netinet/sctp_pcb.h>
85 #include <netinet/sctp_header.h>
86 #include <netinet/sctputil.h>
87 #include <netinet/sctp_output.h>
88 #include <netinet/sctp_input.h>
89 #include <netinet/sctp_hashdriver.h>
90 #include <netinet/sctp_indata.h>
91 #include <netinet/sctp_uio.h>
92 #include <netinet/sctp_timer.h>
93 #ifdef IPSEC
94 #ifndef __OpenBSD__
95 #include <netinet6/ipsec.h>
96 #include <netkey/key.h>
97 #else
98 #undef IPSEC
99 #endif
100 #endif /*IPSEC*/
101
102 #include <net/net_osdep.h>
103
104 #ifdef SCTP_DEBUG
105 extern u_int32_t sctp_debug_on;
106 #endif
107
108 /*
109  * NOTES: On the outbound side of things I need to check the sack timer to
110  * see if I should generate a sack into the chunk queue (if I have data to
111  * send that is and will be sending it .. for bundling.
112  *
113  * The callback in sctp_usrreq.c will get called when the socket is read
114  * from. This will cause sctp_service_queues() to get called on the top
115  * entry in the list.
116  */
117
118 extern int sctp_strict_sacks;
119
120 void
121 sctp_set_rwnd(struct sctp_tcb *stcb, struct sctp_association *asoc)
122 {
123         u_int32_t calc, calc_w_oh;
124
125 #ifdef SCTP_DEBUG
126         if (sctp_debug_on & SCTP_DEBUG_INDATA4) {
127                 printf("cc:%lu hiwat:%lu lowat:%lu mbcnt:%lu mbmax:%lu\n",
128                        (u_long)stcb->sctp_socket->so_rcv.sb_cc,
129                        (u_long)stcb->sctp_socket->so_rcv.sb_hiwat,
130                        (u_long)stcb->sctp_socket->so_rcv.sb_lowat,
131                        (u_long)stcb->sctp_socket->so_rcv.sb_mbcnt,
132                        (u_long)stcb->sctp_socket->so_rcv.sb_mbmax);
133                 printf("Setting rwnd to: sb:%ld - (del:%d + reasm:%d str:%d)\n",
134                        sctp_sbspace(&stcb->sctp_socket->so_rcv),
135                        asoc->size_on_delivery_queue,
136                        asoc->size_on_reasm_queue,
137                        asoc->size_on_all_streams);
138         }
139 #endif
140         if (stcb->sctp_socket->so_rcv.sb_cc == 0 &&
141             asoc->size_on_delivery_queue == 0 &&
142             asoc->size_on_reasm_queue == 0 &&
143             asoc->size_on_all_streams == 0) {
144                 /* Full rwnd granted */
145                 asoc->my_rwnd = max(stcb->sctp_socket->so_rcv.sb_hiwat,
146                                     SCTP_MINIMAL_RWND);
147                 return;
148         }
149         /* get actual space */
150         calc = (u_int32_t)sctp_sbspace(&stcb->sctp_socket->so_rcv);
151
152         /* take out what has NOT been put on socket queue and
153          * we yet hold for putting up.
154          */
155         calc = sctp_sbspace_sub(calc, (u_int32_t)asoc->size_on_delivery_queue);
156         calc = sctp_sbspace_sub(calc, (u_int32_t)asoc->size_on_reasm_queue);
157         calc = sctp_sbspace_sub(calc, (u_int32_t)asoc->size_on_all_streams);
158
159         /* what is the overhead of all these rwnd's */
160         calc_w_oh = sctp_sbspace_sub(calc, stcb->asoc.my_rwnd_control_len);
161
162         asoc->my_rwnd = calc;
163         if (calc_w_oh == 0) {
164                 /* If our overhead is greater than the advertised
165                  * rwnd, we clamp the rwnd to 1. This lets us
166                  * still accept inbound segments, but hopefully will
167                  * shut the sender down when he finally gets the message.
168                  */
169                 asoc->my_rwnd = 1;
170         } else {
171                 /* SWS threshold */
172                 if (asoc->my_rwnd &&
173                     (asoc->my_rwnd < stcb->sctp_ep->sctp_ep.sctp_sws_receiver)) {
174                         /* SWS engaged, tell peer none left */
175                         asoc->my_rwnd = 1;
176 #ifdef SCTP_DEBUG
177                         if (sctp_debug_on & SCTP_DEBUG_INDATA4) {
178                                 printf(" - SWS zeros\n");
179                         }
180                 } else {
181                         if (sctp_debug_on & SCTP_DEBUG_INDATA4) {
182                                 printf("\n");
183                         }
184 #endif
185                 }
186         }
187 }
188
189 /*
190  * Take a chk structure and build it into an mbuf. Hmm should we change things
191  * so that instead we store the data side in a chunk?
192  */
193 static struct mbuf *
194 sctp_build_ctl_nchunk(struct sctp_tcb *stcb, uint32_t tsn, uint32_t ppid,
195     uint32_t context, uint16_t stream_no, uint16_t stream_seq, uint8_t flags)
196 {
197         struct sctp_sndrcvinfo *outinfo;
198         struct cmsghdr *cmh;
199         struct mbuf *ret;
200
201         if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_RECVDATAIOEVNT) == 0) {
202                 /* user does not want the sndrcv ctl */
203                 return (NULL);
204         }
205
206         MGETHDR(ret, M_DONTWAIT, MT_CONTROL);
207         if (ret == NULL) {
208                 /* No space */
209                 return (ret);
210         }
211         /* We need a CMSG header followed by the struct  */
212         cmh = mtod(ret, struct cmsghdr *);
213         outinfo = (struct sctp_sndrcvinfo *)CMSG_DATA(cmh);
214         cmh->cmsg_level = IPPROTO_SCTP;
215         cmh->cmsg_type = SCTP_SNDRCV;
216         cmh->cmsg_len = CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
217         outinfo->sinfo_stream = stream_no;
218         outinfo->sinfo_ssn = stream_seq;
219         if (flags & SCTP_DATA_UNORDERED) {
220                 outinfo->sinfo_flags = MSG_UNORDERED;
221         } else {
222                 outinfo->sinfo_flags = 0;
223         }
224         outinfo->sinfo_ppid = ppid;
225         outinfo->sinfo_context = context;
226         outinfo->sinfo_assoc_id = sctp_get_associd(stcb);
227         outinfo->sinfo_tsn = tsn;
228         outinfo->sinfo_cumtsn = stcb->asoc.cumulative_tsn;
229         ret->m_len = cmh->cmsg_len;
230         ret->m_pkthdr.len = ret->m_len;
231         /*
232          * We track how many control len's have gone upon the sb
233          * and do not count these in the rwnd calculation.
234          */
235         stcb->asoc.my_rwnd_control_len +=
236             CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
237
238         return (ret);
239 }
240
241 /*
242  * Take a chk structure and build it into an mbuf.  Should we change things
243  * so that instead we store the data side in a chunk?
244  */
245 static
246 struct mbuf *
247 sctp_build_ctl(struct sctp_tcb *stcb, struct sctp_tmit_chunk *chk)
248 {
249         struct sctp_sndrcvinfo *outinfo;
250         struct cmsghdr *cmh;
251         struct mbuf *ret;
252         if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_RECVDATAIOEVNT) == 0) {
253                 /* user does not want the sndrcv ctl */
254                 return (NULL);
255         }
256         MGET(ret, M_DONTWAIT, MT_CONTROL);
257         if (ret == NULL) {
258                 /* No space */
259                 return (ret);
260         }
261
262         /* We need a CMSG header followed by the struct  */
263         cmh = mtod(ret, struct cmsghdr *);
264         outinfo = (struct sctp_sndrcvinfo *)CMSG_DATA(cmh);
265         cmh->cmsg_level = IPPROTO_SCTP;
266         cmh->cmsg_type = SCTP_SNDRCV;
267         cmh->cmsg_len = CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
268         outinfo->sinfo_stream = chk->rec.data.stream_number;
269         outinfo->sinfo_ssn = chk->rec.data.stream_seq;
270         if (chk->rec.data.rcv_flags & SCTP_DATA_UNORDERED) {
271                 outinfo->sinfo_flags = MSG_UNORDERED;
272         } else {
273                 outinfo->sinfo_flags = 0;
274         }
275         outinfo->sinfo_ppid = chk->rec.data.payloadtype;
276         outinfo->sinfo_context = chk->rec.data.context;
277         outinfo->sinfo_assoc_id = sctp_get_associd(stcb);
278         outinfo->sinfo_tsn = chk->rec.data.TSN_seq;
279         outinfo->sinfo_cumtsn = stcb->asoc.cumulative_tsn;
280         ret->m_len = cmh->cmsg_len;
281         stcb->asoc.my_rwnd_control_len +=
282             CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
283
284         return (ret);
285 }
286
287 int
288 sctp_deliver_data(struct sctp_tcb *stcb, struct sctp_association *asoc,
289     struct sctp_tmit_chunk *chk, int hold_locks)
290 {
291         struct mbuf *control, *m;
292         int free_it;
293         struct sockaddr_in6 sin6;
294         struct sockaddr *to;
295
296 #ifdef SCTP_DEBUG
297         if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
298                 printf("I am now in Deliver data! (%p)\n", chk);
299         }
300 #endif
301         /* get a write lock on the inp if not already */
302         if (hold_locks == 0) {
303                 SCTP_TCB_UNLOCK(stcb);
304                 SCTP_INP_WLOCK(stcb->sctp_ep);
305                 SCTP_TCB_LOCK(stcb);
306         }
307         free_it = 0;
308         /* We always add it to the queue */
309         if (stcb && (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) {
310                 /* socket above is long gone */
311 #ifdef SCTP_DEBUG
312                 if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
313                         printf("gone is gone!\n");
314                 }
315 #endif
316                 if (chk != NULL) {
317                         if (chk->data)
318                                 sctp_m_freem(chk->data);
319                         chk->data = NULL;
320                         sctp_free_remote_addr(chk->whoTo);
321                         SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
322                         sctppcbinfo.ipi_count_chunk--;
323                         if ((int)sctppcbinfo.ipi_count_chunk < 0) {
324                                 panic("Chunk count is negative");
325                         }
326                         sctppcbinfo.ipi_gencnt_chunk++;
327                 }
328                 TAILQ_FOREACH(chk, &asoc->delivery_queue, sctp_next) {
329                         asoc->size_on_delivery_queue -= chk->send_size;
330                         asoc->cnt_on_delivery_queue--;
331                         /*
332                          * Lose the data pointer, since its in the socket buffer
333                          */
334                         if (chk->data)
335                                 sctp_m_freem(chk->data);
336                         chk->data = NULL;
337                         /* Now free the address and data */
338                         sctp_free_remote_addr(chk->whoTo);
339                         SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
340                         sctppcbinfo.ipi_count_chunk--;
341                         if ((int)sctppcbinfo.ipi_count_chunk < 0) {
342                                 panic("Chunk count is negative");
343                         }
344                         sctppcbinfo.ipi_gencnt_chunk++;
345                 }
346                 if (hold_locks == 0)
347                         SCTP_INP_WUNLOCK(stcb->sctp_ep);
348                 return (0);
349         }
350         if (chk != NULL) {
351                 TAILQ_INSERT_TAIL(&asoc->delivery_queue, chk, sctp_next);
352                 asoc->size_on_delivery_queue += chk->send_size;
353                 asoc->cnt_on_delivery_queue++;
354         }
355         if (asoc->fragmented_delivery_inprogress) {
356                 /*
357                  * oh oh, fragmented delivery in progress
358                  * return out of here.
359                  */
360 #ifdef SCTP_DEBUG
361                 if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
362                         printf("Fragmented delivery in progress?\n");
363                 }
364 #endif
365                 if (hold_locks == 0)
366                         SCTP_INP_WUNLOCK(stcb->sctp_ep);
367                 return (0);
368         }
369         /* Now grab the first one  */
370         chk = TAILQ_FIRST(&asoc->delivery_queue);
371         if (chk == NULL) {
372                 /* Nothing in queue */
373 #ifdef SCTP_DEBUG
374                 if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
375                         printf("Nothing in queue?\n");
376                 }
377 #endif
378                 asoc->size_on_delivery_queue = 0;
379                 asoc->cnt_on_delivery_queue = 0;
380                 if (hold_locks == 0)
381                         SCTP_INP_WUNLOCK(stcb->sctp_ep);
382                 return (0);
383         }
384
385         if (stcb->sctp_socket->so_rcv.sb_cc >= stcb->sctp_socket->so_rcv.sb_hiwat) {
386                 /* Boy, there really is NO room */
387                 if (hold_locks == 0)
388                         SCTP_INP_WUNLOCK(stcb->sctp_ep);
389                 return (0);
390         }
391 #ifdef SCTP_DEBUG
392         if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
393                 printf("Now to the delivery with chk(%p)!\n", chk);
394         }
395 #endif
396         /* XXX need to append PKTHDR to the socket buffer first */
397         if ((chk->data->m_flags & M_PKTHDR) == 0) {
398                 MGETHDR(m, M_DONTWAIT, MT_DATA);
399                 if (m == NULL) {
400                         /* no room! */
401                         if (hold_locks == 0)
402                                 SCTP_INP_WUNLOCK(stcb->sctp_ep);
403                         return (0);
404                 }
405                 m->m_pkthdr.len = chk->send_size;
406                 m->m_len = 0;
407                 m->m_next = chk->data;
408                 chk->data = m;
409         }
410         if (chk->rec.data.rcv_flags & SCTP_DATA_LAST_FRAG) {
411                 if (chk->data->m_next == NULL) {
412                         /* hopefully we hit here most of the time */
413                         chk->data->m_flags |= M_EOR;
414                 } else {
415                         /* Add the flag to the LAST mbuf in the chain */
416                         m = chk->data;
417                         while (m->m_next != NULL) {
418                                 m = m->m_next;
419                         }
420                         m->m_flags |= M_EOR;
421                 }
422         }
423
424         if (chk->rec.data.rcv_flags & SCTP_DATA_FIRST_FRAG) {
425                 struct sockaddr_in6 lsa6;
426
427                 control = sctp_build_ctl(stcb, chk);
428                 to = (struct sockaddr *)&chk->whoTo->ro._l_addr;
429                 if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_NEEDS_MAPPED_V4) &&
430                     to->sa_family == AF_INET) {
431                         struct sockaddr_in *sin;
432
433                         sin = (struct sockaddr_in *)to;
434                         bzero(&sin6, sizeof(sin6));
435                         sin6.sin6_family = AF_INET6;
436                         sin6.sin6_len = sizeof(struct sockaddr_in6);
437                         sin6.sin6_addr.s6_addr16[2] = 0xffff;
438                         bcopy(&sin->sin_addr, &sin6.sin6_addr.s6_addr16[3],
439                             sizeof(sin6.sin6_addr.s6_addr16[3]));
440                         sin6.sin6_port = sin->sin_port;
441                         to = (struct sockaddr *)&sin6;
442                 }
443                 /* check and strip embedded scope junk */
444                 to = (struct sockaddr *)sctp_recover_scope((struct sockaddr_in6 *)to,
445                     &lsa6);
446                 if (((struct sockaddr_in *)to)->sin_port == 0) {
447                         printf("Huh a, port is %d not net:%x %d?\n",
448                                ((struct sockaddr_in *)to)->sin_port,
449                                (u_int)chk->whoTo,
450                                (int)(ntohs(stcb->rport)));
451                         ((struct sockaddr_in *)to)->sin_port = stcb->rport;
452                 }
453                 if (sctp_sbspace(&stcb->sctp_socket->so_rcv) < (long)chk->send_size) {
454                         /* Gak not enough room */
455                         if (control) {
456                                 sctp_m_freem(control);
457                                 stcb->asoc.my_rwnd_control_len -=
458                                     CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
459                         }
460                         goto skip;
461                 }
462                 if (!sbappendaddr_nocheck(&stcb->sctp_socket->so_rcv,
463                     to, chk->data, control, stcb->asoc.my_vtag,
464                     stcb->sctp_ep)) {
465                         /* Gak not enough room */
466                         if (control) {
467                                 sctp_m_freem(control);
468                                 stcb->asoc.my_rwnd_control_len -=
469                                     CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
470                         }
471                 } else {
472                         if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) == 0) {
473                                 if (sctp_add_to_socket_q(stcb->sctp_ep, stcb)) {
474                                         stcb->asoc.my_rwnd_control_len +=
475                                                 sizeof(struct mbuf);
476                                 }
477                         } else {
478                                 stcb->asoc.my_rwnd_control_len += sizeof(struct mbuf);
479                         }
480                         free_it = 1;
481                 }
482         } else {
483                 /* append to a already started message. */
484                 if (sctp_sbspace(&stcb->sctp_socket->so_rcv) >=
485                     (long)chk->send_size) {
486                         sbappend(&stcb->sctp_socket->so_rcv, chk->data);
487                         free_it = 1;
488                 }
489         }
490  skip:
491         if (hold_locks == 0)
492                 SCTP_INP_WUNLOCK(stcb->sctp_ep);
493         /* free up the one we inserted */
494         if (free_it) {
495                 /* Pull it off the queue */
496 #ifdef SCTP_DEBUG
497                 if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
498                         printf("Free_it true, doing tickle wakeup\n");
499                 }
500 #endif
501                 sctp_sorwakeup(stcb->sctp_ep, stcb->sctp_socket);
502                 TAILQ_REMOVE(&asoc->delivery_queue, chk, sctp_next);
503                 asoc->size_on_delivery_queue -= chk->send_size;
504                 asoc->cnt_on_delivery_queue--;
505                 /* Lose the data pointer, since its in the socket buffer */
506                 chk->data = NULL;
507                 /* Now free the address and data */
508                 sctp_free_remote_addr(chk->whoTo);
509                 SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
510                 sctppcbinfo.ipi_count_chunk--;
511                 if ((int)sctppcbinfo.ipi_count_chunk < 0) {
512                         panic("Chunk count is negative");
513                 }
514                 sctppcbinfo.ipi_gencnt_chunk++;
515         }
516         return (free_it);
517 }
518
519 /*
520  * We are delivering currently from the reassembly queue. We must continue to
521  * deliver until we either:
522  * 1) run out of space.
523  * 2) run out of sequential TSN's
524  * 3) hit the SCTP_DATA_LAST_FRAG flag.
525  */
526 static void
527 sctp_service_reassembly(struct sctp_tcb *stcb, struct sctp_association *asoc, int hold_locks)
528 {
529         struct sockaddr *to;
530         struct sockaddr_in6 sin6;
531         struct sctp_tmit_chunk *chk, *at;
532         struct mbuf *control, *m;
533         u_int16_t nxt_todel;
534         u_int16_t stream_no;
535         int cntDel;
536         cntDel = stream_no = 0;
537         if (hold_locks == 0) {
538                 /*
539                  * you always have the TCB lock, we need
540                  * to have the inp write lock as well.
541                  */
542                 SCTP_TCB_UNLOCK(stcb);
543                 SCTP_INP_WLOCK(stcb->sctp_ep);
544                 SCTP_TCB_LOCK(stcb);
545         }
546         if (stcb && (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) {
547                 /* socket above is long gone */
548                 asoc->fragmented_delivery_inprogress = 0;
549                 TAILQ_FOREACH(chk, &asoc->reasmqueue, sctp_next) {
550                         asoc->size_on_delivery_queue -= chk->send_size;
551                         asoc->cnt_on_delivery_queue--;
552                         /*
553                          * Lose the data pointer, since its in the socket buffer
554                          */
555                         if (chk->data)
556                                 sctp_m_freem(chk->data);
557                         chk->data = NULL;
558                         /* Now free the address and data */
559                         sctp_free_remote_addr(chk->whoTo);
560                         SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
561                         sctppcbinfo.ipi_count_chunk--;
562                         if ((int)sctppcbinfo.ipi_count_chunk < 0) {
563                                 panic("Chunk count is negative");
564                         }
565                         sctppcbinfo.ipi_gencnt_chunk++;
566                 }
567                 if (hold_locks == 0)
568                         SCTP_INP_WUNLOCK(stcb->sctp_ep);
569                 return;
570         }
571         do {
572                 if (stcb->sctp_socket->so_rcv.sb_cc >=
573                     stcb->sctp_socket->so_rcv.sb_hiwat) {
574                         if (cntDel) {
575                                 sctp_sorwakeup(stcb->sctp_ep,
576                                                stcb->sctp_socket);
577                         }
578                         if (hold_locks == 0)
579                                 SCTP_INP_WUNLOCK(stcb->sctp_ep);
580                         return;
581                 }
582                 chk = TAILQ_FIRST(&asoc->reasmqueue);
583                 if (chk == NULL) {
584                         if (cntDel) {
585                                 sctp_sorwakeup(stcb->sctp_ep,
586                                                stcb->sctp_socket);
587                         }
588                         if (hold_locks == 0)
589                                 SCTP_INP_WUNLOCK(stcb->sctp_ep);
590                         return;
591                 }
592                 if (chk->rec.data.TSN_seq != (asoc->tsn_last_delivered + 1)) {
593                         /* Can't deliver more :< */
594                         if (cntDel) {
595                                 sctp_sorwakeup(stcb->sctp_ep,
596                                                stcb->sctp_socket);
597                         }
598                         if (hold_locks == 0)
599                                 SCTP_INP_WUNLOCK(stcb->sctp_ep);
600                         return;
601                 }
602                 stream_no = chk->rec.data.stream_number;
603                 nxt_todel = asoc->strmin[stream_no].last_sequence_delivered + 1;
604                 if (nxt_todel != chk->rec.data.stream_seq &&
605                     (chk->rec.data.rcv_flags & SCTP_DATA_UNORDERED) == 0) {
606                         /*
607                          * Not the next sequence to deliver in its stream OR
608                          * unordered
609                          */
610                         if (cntDel) {
611                                 sctp_sorwakeup(stcb->sctp_ep,
612                                                stcb->sctp_socket);
613                         }
614                         if (hold_locks == 0)
615                                 SCTP_INP_WUNLOCK(stcb->sctp_ep);
616                         return;
617                 }
618
619                 if ((chk->data->m_flags & M_PKTHDR) == 0) {
620                         MGETHDR(m, M_DONTWAIT, MT_DATA);
621                         if (m == NULL) {
622                                 /* no room! */
623                                 if (hold_locks == 0)
624                                         SCTP_INP_WUNLOCK(stcb->sctp_ep);
625                                 return;
626                         }
627                         m->m_pkthdr.len = chk->send_size;
628                         m->m_len = 0;
629                         m->m_next = chk->data;
630                         chk->data = m;
631                 }
632                 if (chk->rec.data.rcv_flags & SCTP_DATA_LAST_FRAG) {
633                         if (chk->data->m_next == NULL) {
634                                 /* hopefully we hit here most of the time */
635                                 chk->data->m_flags |= M_EOR;
636                         } else {
637                                 /* Add the flag to the LAST mbuf in the chain */
638                                 m = chk->data;
639                                 while (m->m_next != NULL) {
640                                         m = m->m_next;
641                                 }
642                                 m->m_flags |= M_EOR;
643                         }
644                 }
645                 if (chk->rec.data.rcv_flags & SCTP_DATA_FIRST_FRAG) {
646                         struct sockaddr_in6 lsa6;
647
648                         control = sctp_build_ctl(stcb, chk);
649                         to = (struct sockaddr *)&chk->whoTo->ro._l_addr;
650                         if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_NEEDS_MAPPED_V4) &&
651                             to->sa_family == AF_INET) {
652                                 struct sockaddr_in *sin;
653                                 sin = (struct sockaddr_in *)to;
654                                 bzero(&sin6, sizeof(sin6));
655                                 sin6.sin6_family = AF_INET6;
656                                 sin6.sin6_len = sizeof(struct sockaddr_in6);
657                                 sin6.sin6_addr.s6_addr16[2] = 0xffff;
658                                 bcopy(&sin->sin_addr,
659                                       &sin6.sin6_addr.s6_addr16[3],
660                                       sizeof(sin6.sin6_addr.s6_addr16[3]));
661                                 sin6.sin6_port = sin->sin_port;
662                                 to = (struct sockaddr *)&sin6;
663                         }
664                         /* check and strip embedded scope junk */
665                         to = (struct sockaddr *)sctp_recover_scope((struct sockaddr_in6 *)to,
666                                                                    &lsa6);
667                         if (((struct sockaddr_in *)to)->sin_port == 0) {
668                                 printf("Huh b, port is %d not net:%x %d?\n",
669                                        ((struct sockaddr_in *)to)->sin_port,
670                                        (u_int)chk->whoTo,
671                                        (int)(ntohs(stcb->rport)));
672                                 ((struct sockaddr_in *)to)->sin_port = stcb->rport;
673                         }
674                         if (sctp_sbspace(&stcb->sctp_socket->so_rcv) <
675                             (long)chk->send_size) {
676                                 if (control) {
677                                         sctp_m_freem(control);
678                                         stcb->asoc.my_rwnd_control_len -=
679                                                 CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
680                                 }
681                                 sctp_sorwakeup(stcb->sctp_ep,
682                                                stcb->sctp_socket);
683                                 if (hold_locks == 0)
684                                         SCTP_INP_WUNLOCK(stcb->sctp_ep);
685                                 return;
686                         }
687                         if (!sbappendaddr_nocheck(&stcb->sctp_socket->so_rcv,
688                                                   to, chk->data, control, stcb->asoc.my_vtag,
689                                                   stcb->sctp_ep)) {
690                                 /* Gak not enough room */
691                                 if (control) {
692                                         sctp_m_freem(control);
693                                         stcb->asoc.my_rwnd_control_len -=
694                                                 CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
695                                 }
696                                 sctp_sorwakeup(stcb->sctp_ep,
697                                                stcb->sctp_socket);
698                                 if (hold_locks == 0)
699                                         SCTP_INP_WUNLOCK(stcb->sctp_ep);
700                                 return;
701                         }
702                         if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) == 0) {
703                                 if (sctp_add_to_socket_q(stcb->sctp_ep, stcb)) {
704                                         stcb->asoc.my_rwnd_control_len +=
705                                                 sizeof(struct mbuf);
706                                 }
707                         } else {
708                                 stcb->asoc.my_rwnd_control_len += sizeof(struct mbuf);
709                         }
710                         cntDel++;
711                 } else {
712                         if (sctp_sbspace(&stcb->sctp_socket->so_rcv) >=
713                             (long)chk->send_size) {
714                                 sbappend(&stcb->sctp_socket->so_rcv, chk->data);
715                                 cntDel++;
716                         } else {
717                                 /* out of space in the sb */
718                                 sctp_sorwakeup(stcb->sctp_ep,
719                                                stcb->sctp_socket);
720                                 if (hold_locks == 0)
721                                         SCTP_INP_WUNLOCK(stcb->sctp_ep);
722                                 return;
723                         }
724                 }
725                 /* pull it we did it */
726                 TAILQ_REMOVE(&asoc->reasmqueue, chk, sctp_next);
727                 if (chk->rec.data.rcv_flags & SCTP_DATA_LAST_FRAG) {
728                         asoc->fragmented_delivery_inprogress = 0;
729                         if ((chk->rec.data.rcv_flags & SCTP_DATA_UNORDERED) == 0) {
730                                 asoc->strmin[stream_no].last_sequence_delivered++;
731                         }
732                 }
733                 asoc->tsn_last_delivered = chk->rec.data.TSN_seq;
734                 asoc->size_on_reasm_queue -= chk->send_size;
735                 asoc->cnt_on_reasm_queue--;
736                 /* free up the chk */
737                 sctp_free_remote_addr(chk->whoTo);
738                 chk->data = NULL;
739                 SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
740                 sctppcbinfo.ipi_count_chunk--;
741                 if ((int)sctppcbinfo.ipi_count_chunk < 0) {
742                         panic("Chunk count is negative");
743                 }
744                 sctppcbinfo.ipi_gencnt_chunk++;
745                 if (asoc->fragmented_delivery_inprogress == 0) {
746                         /*
747                          * Now lets see if we can deliver the next one on the
748                          * stream
749                          */
750                         u_int16_t nxt_todel;
751                         struct sctp_stream_in *strm;
752
753                         strm = &asoc->strmin[stream_no];
754                         nxt_todel = strm->last_sequence_delivered + 1;
755                         chk = TAILQ_FIRST(&strm->inqueue);
756                         if (chk && (nxt_todel == chk->rec.data.stream_seq)) {
757                                 while (chk != NULL) {
758                                         /* all delivered */
759                                         if (nxt_todel ==
760                                             chk->rec.data.stream_seq) {
761                                                 at = TAILQ_NEXT(chk, sctp_next);
762                                                 TAILQ_REMOVE(&strm->inqueue,
763                                                              chk, sctp_next);
764                                                 asoc->size_on_all_streams -=
765                                                         chk->send_size;
766                                                 asoc->cnt_on_all_streams--;
767                                                 strm->last_sequence_delivered++;
768                                                 /*
769                                                  * We ignore the return of
770                                                  * deliver_data here since we
771                                                  * always can hold the chunk on
772                                                  * the d-queue. And we have a
773                                                  * finite number that can be
774                                                  * delivered from the strq.
775                                                  */
776                                                 sctp_deliver_data(stcb, asoc, chk, 1);
777                                                 chk = at;
778                                         } else {
779                                                 break;
780                                         }
781                                         nxt_todel =
782                                                 strm->last_sequence_delivered + 1;
783                                 }
784                         }
785                         if (!TAILQ_EMPTY(&asoc->delivery_queue)) {
786                                 /* Here if deliver_data fails, we must break */
787                                 if (sctp_deliver_data(stcb, asoc, NULL, 1) == 0)
788                                         break;
789                         }
790                         sctp_sorwakeup(stcb->sctp_ep, stcb->sctp_socket);
791                         if (hold_locks == 0)
792                                 SCTP_INP_WUNLOCK(stcb->sctp_ep);
793                         return;
794                 }
795                 chk = TAILQ_FIRST(&asoc->reasmqueue);
796         } while (chk);
797         if (cntDel) {
798                 sctp_sorwakeup(stcb->sctp_ep, stcb->sctp_socket);
799         }
800         if (hold_locks == 0)
801                 SCTP_INP_WUNLOCK(stcb->sctp_ep);
802 }
803
804 /*
805  * Queue the chunk either right into the socket buffer if it is the next one
806  * to go OR put it in the correct place in the delivery queue.  If we do
807  * append to the so_buf, keep doing so until we are out of order.
808  * One big question still remains, what to do when the socket buffer is FULL??
809  */
810 static void
811 sctp_queue_data_to_stream(struct sctp_tcb *stcb, struct sctp_association *asoc,
812     struct sctp_tmit_chunk *chk, int *abort_flag)
813 {
814         struct sctp_stream_in *strm;
815         struct sctp_tmit_chunk *at;
816         int queue_needed;
817         u_int16_t nxt_todel;
818         struct mbuf *oper;
819
820 /*** FIX FIX FIX ???
821  * Need to add code to deal with 16 bit seq wrap
822  * without a TSN wrap for ordered delivery (maybe).
823  * FIX FIX FIX ???
824  */
825         queue_needed = 1;
826         asoc->size_on_all_streams += chk->send_size;
827         asoc->cnt_on_all_streams++;
828         strm = &asoc->strmin[chk->rec.data.stream_number];
829         nxt_todel = strm->last_sequence_delivered + 1;
830 #ifdef SCTP_STR_LOGGING
831         sctp_log_strm_del(chk, NULL, SCTP_STR_LOG_FROM_INTO_STRD);
832 #endif
833 #ifdef SCTP_DEBUG
834         if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
835                 printf("queue to stream called for ssn:%u lastdel:%u nxt:%u\n",
836                     (u_int)chk->rec.data.stream_seq,
837                     (u_int)strm->last_sequence_delivered, (u_int)nxt_todel);
838         }
839 #endif
840         if (compare_with_wrap(strm->last_sequence_delivered,
841             chk->rec.data.stream_seq, MAX_SEQ) ||
842             (strm->last_sequence_delivered == chk->rec.data.stream_seq)) {
843                 /* The incoming sseq is behind where we last delivered? */
844 #ifdef SCTP_DEBUG
845                 if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
846                         printf("Duplicate S-SEQ:%d delivered:%d from peer, Abort  association\n",
847                             chk->rec.data.stream_seq,
848                             strm->last_sequence_delivered);
849                 }
850 #endif
851                 /*
852                  * throw it in the stream so it gets cleaned up in
853                  * association destruction
854                  */
855                 TAILQ_INSERT_HEAD(&strm->inqueue, chk, sctp_next);
856                 MGET(oper, M_DONTWAIT, MT_DATA);
857                 if (oper) {
858                         struct sctp_paramhdr *ph;
859                         u_int32_t *ippp;
860
861                         oper->m_len = sizeof(struct sctp_paramhdr) +
862                             sizeof(*ippp);
863                         ph = mtod(oper, struct sctp_paramhdr *);
864                         ph->param_type = htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
865                         ph->param_length = htons(oper->m_len);
866                         ippp = (u_int32_t *)(ph + 1);
867                         *ippp = htonl(0x00000001);
868                 }
869                 sctp_abort_an_association(stcb->sctp_ep, stcb,
870                     SCTP_PEER_FAULTY, oper);
871
872                 *abort_flag = 1;
873                 return;
874
875         }
876         if (nxt_todel == chk->rec.data.stream_seq) {
877                 /* can be delivered right away */
878 #ifdef SCTP_DEBUG
879                 if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
880                         printf("It's NEXT!\n");
881                 }
882 #endif
883 #ifdef SCTP_STR_LOGGING
884                 sctp_log_strm_del(chk, NULL, SCTP_STR_LOG_FROM_IMMED_DEL);
885 #endif
886                 queue_needed = 0;
887                 asoc->size_on_all_streams -= chk->send_size;
888                 asoc->cnt_on_all_streams--;
889                 strm->last_sequence_delivered++;
890                 sctp_deliver_data(stcb, asoc, chk, 0);
891                 chk = TAILQ_FIRST(&strm->inqueue);
892                 while (chk != NULL) {
893                         /* all delivered */
894                         nxt_todel = strm->last_sequence_delivered + 1;
895                         if (nxt_todel == chk->rec.data.stream_seq) {
896                                 at = TAILQ_NEXT(chk, sctp_next);
897                                 TAILQ_REMOVE(&strm->inqueue, chk, sctp_next);
898                                 asoc->size_on_all_streams -= chk->send_size;
899                                 asoc->cnt_on_all_streams--;
900                                 strm->last_sequence_delivered++;
901                                 /*
902                                  * We ignore the return of deliver_data here
903                                  * since we always can hold the chunk on the
904                                  * d-queue. And we have a finite number that
905                                  * can be delivered from the strq.
906                                  */
907 #ifdef SCTP_STR_LOGGING
908                                 sctp_log_strm_del(chk, NULL,
909                                     SCTP_STR_LOG_FROM_IMMED_DEL);
910 #endif
911                                 sctp_deliver_data(stcb, asoc, chk, 0);
912                                 chk = at;
913                                 continue;
914                         }
915                         break;
916                 }
917         }
918         if (queue_needed) {
919                 /*
920                  * Ok, we did not deliver this guy, find
921                  * the correct place to put it on the queue.
922                  */
923 #ifdef SCTP_DEBUG
924                 if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
925                         printf("Queue Needed!\n");
926                 }
927 #endif
928                 if (TAILQ_EMPTY(&strm->inqueue)) {
929                         /* Empty queue */
930 #ifdef SCTP_STR_LOGGING
931                         sctp_log_strm_del(chk, NULL, SCTP_STR_LOG_FROM_INSERT_HD);
932 #endif
933                         TAILQ_INSERT_HEAD(&strm->inqueue, chk, sctp_next);
934                 } else {
935                         TAILQ_FOREACH(at, &strm->inqueue, sctp_next) {
936                                 if (compare_with_wrap(at->rec.data.stream_seq,
937                                     chk->rec.data.stream_seq, MAX_SEQ)) {
938                                         /*
939                                          * one in queue is bigger than the new
940                                          * one, insert before this one
941                                          */
942 #ifdef SCTP_STR_LOGGING
943                                         sctp_log_strm_del(chk, at,
944                                             SCTP_STR_LOG_FROM_INSERT_MD);
945 #endif
946                                         TAILQ_INSERT_BEFORE(at, chk, sctp_next);
947                                         break;
948                                 } else if (at->rec.data.stream_seq ==
949                                     chk->rec.data.stream_seq) {
950                                         /*
951                                          * Gak, He sent me a duplicate str seq
952                                          * number
953                                          */
954                                         /*
955                                          * foo bar, I guess I will just free
956                                          * this new guy, should we abort too?
957                                          * FIX ME MAYBE? Or it COULD be that
958                                          * the SSN's have wrapped. Maybe I
959                                          * should compare to TSN somehow...
960                                          * sigh for now just blow away the
961                                          * chunk!
962                                          */
963
964                                         if (chk->data)
965                                                 sctp_m_freem(chk->data);
966                                         chk->data = NULL;
967                                         asoc->size_on_all_streams -= chk->send_size;
968                                         asoc->cnt_on_all_streams--;
969                                         sctp_pegs[SCTP_DUP_SSN_RCVD]++;
970                                         sctp_free_remote_addr(chk->whoTo);
971                                         SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
972                                         sctppcbinfo.ipi_count_chunk--;
973                                         if ((int)sctppcbinfo.ipi_count_chunk <
974                                             0) {
975                                                 panic("Chunk count is negative");
976                                         }
977                                         sctppcbinfo.ipi_gencnt_chunk++;
978                                         return;
979                                 } else {
980                                         if (TAILQ_NEXT(at, sctp_next) == NULL) {
981                                                 /*
982                                                  * We are at the end, insert it
983                                                  * after this one
984                                                  */
985 #ifdef SCTP_STR_LOGGING
986                                                 sctp_log_strm_del(chk, at,
987                                                     SCTP_STR_LOG_FROM_INSERT_TL);
988 #endif
989                                                 TAILQ_INSERT_AFTER(&strm->inqueue,
990                                                     at, chk, sctp_next);
991                                                 break;
992                                         }
993                                 }
994                         }
995                 }
996         } else {
997                 /* We delivered some chunks, wake them up */
998
999 #ifdef SCTP_DEBUG
1000                 if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
1001                         printf("Doing WAKEUP!\n");
1002                 }
1003 #endif
1004                 sctp_sorwakeup(stcb->sctp_ep, stcb->sctp_socket);
1005         }
1006 }
1007
1008 /*
1009  * Returns two things: You get the total size of the deliverable parts of the
1010  * first fragmented message on the reassembly queue. And you get a 1 back if
1011  * all of the message is ready or a 0 back if the message is still incomplete
1012  */
1013 static int
1014 sctp_is_all_msg_on_reasm(struct sctp_association *asoc, int *t_size)
1015 {
1016         struct sctp_tmit_chunk *chk;
1017         u_int32_t tsn;
1018
1019         *t_size = 0;
1020         chk = TAILQ_FIRST(&asoc->reasmqueue);
1021         if (chk == NULL) {
1022                 /* nothing on the queue */
1023                 return (0);
1024         }
1025         if ((chk->rec.data.rcv_flags & SCTP_DATA_FIRST_FRAG) == 0) {
1026                 /* Not a first on the queue */
1027                 return (0);
1028         }
1029         tsn = chk->rec.data.TSN_seq;
1030         while (chk) {
1031                 if (tsn != chk->rec.data.TSN_seq) {
1032                         return (0);
1033                 }
1034                 *t_size += chk->send_size;
1035                 if (chk->rec.data.rcv_flags & SCTP_DATA_LAST_FRAG) {
1036                         return (1);
1037                 }
1038                 tsn++;
1039                 chk = TAILQ_NEXT(chk, sctp_next);
1040         }
1041         return (0);
1042 }
1043
1044 /*
1045  * Dump onto the re-assembly queue, in its proper place. After dumping on
1046  * the queue, see if anthing can be delivered. If so pull it off (or as much
1047  * as we can. If we run out of space then we must dump what we can and set
1048  * the appropriate flag to say we queued what we could.
1049  */
1050 static void
1051 sctp_queue_data_for_reasm(struct sctp_tcb *stcb, struct sctp_association *asoc,
1052     struct sctp_tmit_chunk *chk, int *abort_flag)
1053 {
1054         struct mbuf *oper;
1055         u_int16_t nxt_todel;
1056         u_int32_t cum_ackp1, last_tsn, prev_tsn, post_tsn;
1057         int tsize;
1058         u_char last_flags;
1059         struct sctp_tmit_chunk *at, *prev, *next;
1060
1061         prev = next = NULL;
1062         cum_ackp1 = asoc->tsn_last_delivered + 1;
1063
1064         if (TAILQ_EMPTY(&asoc->reasmqueue)) {
1065                 /* This is the first one on the queue */
1066                 TAILQ_INSERT_HEAD(&asoc->reasmqueue, chk, sctp_next);
1067                 /*
1068                  * we do not check for delivery of anything when
1069                  * only one fragment is here
1070                  */
1071                 asoc->size_on_reasm_queue = chk->send_size;
1072                 asoc->cnt_on_reasm_queue++;
1073                 if (chk->rec.data.TSN_seq == cum_ackp1) {
1074                         if (asoc->fragmented_delivery_inprogress == 0  &&
1075                             (chk->rec.data.rcv_flags & SCTP_DATA_FIRST_FRAG) !=
1076                             SCTP_DATA_FIRST_FRAG) {
1077                                 /*
1078                                  * An empty queue, no delivery inprogress, we
1079                                  * hit the next one and it does NOT have a
1080                                  * FIRST fragment mark.
1081                                  */
1082 #ifdef SCTP_DEBUG
1083                                 if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
1084                                         printf("Gak, Evil plot, its not first, no fragmented delivery in progress\n");
1085                                 }
1086 #endif
1087                                 MGET(oper, M_DONTWAIT, MT_DATA);
1088                                 if (oper) {
1089                                         struct sctp_paramhdr *ph;
1090                                         u_int32_t *ippp;
1091
1092                                         oper->m_len =
1093                                             sizeof(struct sctp_paramhdr) +
1094                                             sizeof(*ippp);
1095                                         ph = mtod(oper, struct sctp_paramhdr *);
1096                                         ph->param_type =
1097                                             htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
1098                                         ph->param_length = htons(oper->m_len);
1099                                         ippp = (u_int32_t *)(ph + 1);
1100                                         *ippp = htonl(0x10000001);
1101                                 }
1102                                 sctp_abort_an_association(stcb->sctp_ep, stcb,
1103                                     SCTP_PEER_FAULTY, oper);
1104                                 *abort_flag = 1;
1105                         } else if (asoc->fragmented_delivery_inprogress &&
1106                             (chk->rec.data.rcv_flags & SCTP_DATA_FIRST_FRAG) == SCTP_DATA_FIRST_FRAG) {
1107                                 /*
1108                                  * We are doing a partial delivery and the NEXT
1109                                  * chunk MUST be either the LAST or MIDDLE
1110                                  * fragment NOT a FIRST
1111                                  */
1112 #ifdef SCTP_DEBUG
1113                                 if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
1114                                         printf("Gak, Evil plot, it IS a first and fragmented delivery in progress\n");
1115                                 }
1116 #endif
1117                                 MGET(oper, M_DONTWAIT, MT_DATA);
1118                                 if (oper) {
1119                                         struct sctp_paramhdr *ph;
1120                                         u_int32_t *ippp;
1121
1122                                         oper->m_len =
1123                                             sizeof(struct sctp_paramhdr) +
1124                                             sizeof(*ippp);
1125                                         ph = mtod(oper, struct sctp_paramhdr *);
1126                                         ph->param_type =
1127                                             htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
1128                                         ph->param_length = htons(oper->m_len);
1129                                         ippp = (u_int32_t *)(ph + 1);
1130                                         *ippp = htonl(0x10000002);
1131                                 }
1132                                 sctp_abort_an_association(stcb->sctp_ep, stcb,
1133                                     SCTP_PEER_FAULTY, oper);
1134                                 *abort_flag = 1;
1135                         } else if (asoc->fragmented_delivery_inprogress) {
1136                                 /* Here we are ok with a MIDDLE or LAST piece */
1137                                 if (chk->rec.data.stream_number !=
1138                                     asoc->str_of_pdapi) {
1139                                         /* Got to be the right STR No */
1140 #ifdef SCTP_DEBUG
1141                                         if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
1142                                                 printf("Gak, Evil plot, it IS not same stream number %d vs %d\n",
1143                                                     chk->rec.data.stream_number,
1144                                                     asoc->str_of_pdapi);
1145                                         }
1146 #endif
1147                                         MGET(oper, M_DONTWAIT, MT_DATA);
1148                                         if (oper) {
1149                                                 struct sctp_paramhdr *ph;
1150                                                 u_int32_t *ippp;
1151                                                 oper->m_len =
1152                                                     sizeof(struct sctp_paramhdr) +
1153                                                     sizeof(*ippp);
1154                                                 ph = mtod(oper,
1155                                                     struct sctp_paramhdr *);
1156                                                 ph->param_type =
1157                                                     htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
1158                                                 ph->param_length =
1159                                                     htons(oper->m_len);
1160                                                 ippp = (u_int32_t *)(ph + 1);
1161                                                 *ippp = htonl(0x10000003);
1162                                         }
1163                                         sctp_abort_an_association(stcb->sctp_ep,
1164                                             stcb, SCTP_PEER_FAULTY, oper);
1165                                         *abort_flag = 1;
1166                                 } else if ((asoc->fragment_flags & SCTP_DATA_UNORDERED) !=
1167                                     SCTP_DATA_UNORDERED &&
1168                                     chk->rec.data.stream_seq !=
1169                                     asoc->ssn_of_pdapi) {
1170                                         /* Got to be the right STR Seq */
1171 #ifdef SCTP_DEBUG
1172                                         if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
1173                                                 printf("Gak, Evil plot, it IS not same stream seq %d vs %d\n",
1174                                                     chk->rec.data.stream_seq,
1175                                                     asoc->ssn_of_pdapi);
1176                                         }
1177 #endif
1178                                         MGET(oper, M_DONTWAIT, MT_DATA);
1179                                         if (oper) {
1180                                                 struct sctp_paramhdr *ph;
1181                                                 u_int32_t *ippp;
1182                                                 oper->m_len =
1183                                                     sizeof(struct sctp_paramhdr) +
1184                                                     sizeof(*ippp);
1185                                                 ph = mtod(oper,
1186                                                     struct sctp_paramhdr *);
1187                                                 ph->param_type =
1188                                                     htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
1189                                                 ph->param_length =
1190                                                     htons(oper->m_len);
1191                                                 ippp = (u_int32_t *)(ph + 1);
1192                                                 *ippp = htonl(0x10000004);
1193                                         }
1194                                         sctp_abort_an_association(stcb->sctp_ep,
1195                                             stcb, SCTP_PEER_FAULTY, oper);
1196                                         *abort_flag = 1;
1197                                 }
1198                         }
1199                 }
1200                 return;
1201         }
1202         /* Find its place */
1203         at = TAILQ_FIRST(&asoc->reasmqueue);
1204
1205         /* Grab the top flags */
1206         TAILQ_FOREACH(at, &asoc->reasmqueue, sctp_next) {
1207                 if (compare_with_wrap(at->rec.data.TSN_seq,
1208                     chk->rec.data.TSN_seq, MAX_TSN)) {
1209                         /*
1210                          * one in queue is bigger than the new one, insert
1211                          * before this one
1212                          */
1213                         /* A check */
1214                         asoc->size_on_reasm_queue += chk->send_size;
1215                         asoc->cnt_on_reasm_queue++;
1216                         next = at;
1217                         TAILQ_INSERT_BEFORE(at, chk, sctp_next);
1218                         break;
1219                 } else if (at->rec.data.TSN_seq == chk->rec.data.TSN_seq) {
1220                         /* Gak, He sent me a duplicate str seq number */
1221                         /*
1222                          * foo bar, I guess I will just free this new guy,
1223                          * should we abort too? FIX ME MAYBE? Or it COULD be
1224                          * that the SSN's have wrapped. Maybe I should compare
1225                          * to TSN somehow... sigh for now just blow away the
1226                          * chunk!
1227                          */
1228                         if (chk->data)
1229                                 sctp_m_freem(chk->data);
1230                         chk->data = NULL;
1231                         sctp_free_remote_addr(chk->whoTo);
1232                         SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
1233                         sctppcbinfo.ipi_count_chunk--;
1234                         if ((int)sctppcbinfo.ipi_count_chunk < 0) {
1235                                 panic("Chunk count is negative");
1236                         }
1237                         sctppcbinfo.ipi_gencnt_chunk++;
1238                         return;
1239                 } else {
1240                         last_flags = at->rec.data.rcv_flags;
1241                         last_tsn = at->rec.data.TSN_seq;
1242                         prev = at;
1243                         if (TAILQ_NEXT(at, sctp_next) == NULL) {
1244                                 /*
1245                                  * We are at the end, insert it after this one
1246                                  */
1247                                 /* check it first */
1248                                 asoc->size_on_reasm_queue += chk->send_size;
1249                                 asoc->cnt_on_reasm_queue++;
1250                                 TAILQ_INSERT_AFTER(&asoc->reasmqueue, at, chk, sctp_next);
1251                                 break;
1252                         }
1253                 }
1254         }
1255         /* Now the audits */
1256         if (prev) {
1257                 prev_tsn = chk->rec.data.TSN_seq - 1;
1258                 if (prev_tsn == prev->rec.data.TSN_seq) {
1259                         /*
1260                          * Ok the one I am dropping onto the end
1261                          * is the NEXT. A bit of valdiation here.
1262                          */
1263                         if ((prev->rec.data.rcv_flags & SCTP_DATA_FRAG_MASK) ==
1264                             SCTP_DATA_FIRST_FRAG ||
1265                             (prev->rec.data.rcv_flags & SCTP_DATA_FRAG_MASK) ==
1266                             SCTP_DATA_MIDDLE_FRAG) {
1267                                 /*
1268                                  * Insert chk MUST be a MIDDLE or LAST fragment
1269                                  */
1270                                 if ((chk->rec.data.rcv_flags & SCTP_DATA_FRAG_MASK) ==
1271                                     SCTP_DATA_FIRST_FRAG) {
1272 #ifdef SCTP_DEBUG
1273                                         if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
1274                                                 printf("Prev check - It can be a midlle or last but not a first\n");
1275                                                 printf("Gak, Evil plot, it's a FIRST!\n");
1276                                         }
1277 #endif
1278                                         MGET(oper, M_DONTWAIT, MT_DATA);
1279                                         if (oper) {
1280                                                 struct sctp_paramhdr *ph;
1281                                                 u_int32_t *ippp;
1282
1283                                                 oper->m_len =
1284                                                     sizeof(struct sctp_paramhdr) +
1285                                                     sizeof(*ippp);
1286                                                 ph = mtod(oper,
1287                                                     struct sctp_paramhdr *);
1288                                                 ph->param_type =
1289                                                     htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
1290                                                 ph->param_length =
1291                                                     htons(oper->m_len);
1292
1293                                                 ippp = (u_int32_t *)(ph + 1);
1294                                                 *ippp = htonl(0x10000005);
1295                                         }
1296                                         sctp_abort_an_association(stcb->sctp_ep,
1297                                             stcb, SCTP_PEER_FAULTY, oper);
1298                                         *abort_flag = 1;
1299                                         return;
1300                                 }
1301                                 if (chk->rec.data.stream_number !=
1302                                     prev->rec.data.stream_number) {
1303                                         /*
1304                                          * Huh, need the correct STR here, they
1305                                          * must be the same.
1306                                          */
1307 #ifdef SCTP_DEBUG
1308                                         if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
1309                                                 printf("Prev check - Gak, Evil plot, ssn:%d not the same as at:%d\n",
1310                                                     chk->rec.data.stream_number,
1311                                                     prev->rec.data.stream_number);
1312                                         }
1313 #endif
1314                                         MGET(oper, M_DONTWAIT, MT_DATA);
1315                                         if (oper) {
1316                                                 struct sctp_paramhdr *ph;
1317                                                 u_int32_t *ippp;
1318
1319                                                 oper->m_len =
1320                                                     sizeof(struct sctp_paramhdr) +
1321                                                     sizeof(*ippp);
1322                                                 ph = mtod(oper,
1323                                                     struct sctp_paramhdr *);
1324                                                 ph->param_type =
1325                                                     htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
1326                                                 ph->param_length =
1327                                                     htons(oper->m_len);
1328                                                 ippp = (u_int32_t *)(ph + 1);
1329                                                 *ippp = htonl(0x10000006);
1330                                         }
1331
1332                                         sctp_abort_an_association(stcb->sctp_ep,
1333                                             stcb, SCTP_PEER_FAULTY, oper);
1334
1335                                         *abort_flag = 1;
1336                                         return;
1337                                 }
1338                                 if ((prev->rec.data.rcv_flags & SCTP_DATA_UNORDERED) == 0 &&
1339                                     chk->rec.data.stream_seq !=
1340                                     prev->rec.data.stream_seq) {
1341                                         /*
1342                                          * Huh, need the correct STR here, they
1343                                          * must be the same.
1344                                          */
1345 #ifdef SCTP_DEBUG
1346                                         if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
1347                                                 printf("Prev check - Gak, Evil plot, sseq:%d not the same as at:%d\n",
1348                                                     chk->rec.data.stream_seq,
1349                                                     prev->rec.data.stream_seq);
1350                                         }
1351 #endif
1352                                         MGET(oper, M_DONTWAIT, MT_DATA);
1353                                         if (oper) {
1354                                                 struct sctp_paramhdr *ph;
1355                                                 u_int32_t *ippp;
1356
1357                                                 oper->m_len =
1358                                                     sizeof(struct sctp_paramhdr) +
1359                                                     sizeof(*ippp);
1360                                                 ph = mtod(oper,
1361                                                     struct sctp_paramhdr *);
1362                                                 ph->param_type =
1363                                                     htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
1364                                                 ph->param_length =
1365                                                     htons(oper->m_len);
1366                                                 ippp = (u_int32_t *)(ph + 1);
1367                                                 *ippp = htonl(0x10000007);
1368                                         }
1369
1370                                         sctp_abort_an_association(stcb->sctp_ep,
1371                                             stcb, SCTP_PEER_FAULTY, oper);
1372
1373                                         *abort_flag = 1;
1374                                         return;
1375                                 }
1376                         } else if ((prev->rec.data.rcv_flags & SCTP_DATA_FRAG_MASK) ==
1377                             SCTP_DATA_LAST_FRAG) {
1378                                 /* Insert chk MUST be a FIRST */
1379                                 if ((chk->rec.data.rcv_flags & SCTP_DATA_FRAG_MASK) !=
1380                                     SCTP_DATA_FIRST_FRAG) {
1381 #ifdef SCTP_DEBUG
1382                                         if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
1383                                                 printf("Prev check - Gak, evil plot, its not FIRST and it must be!\n");
1384                                         }
1385 #endif
1386                                         MGET(oper, M_DONTWAIT, MT_DATA);
1387                                         if (oper) {
1388                                                 struct sctp_paramhdr *ph;
1389                                                 u_int32_t *ippp;
1390
1391                                                 oper->m_len =
1392                                                     sizeof(struct sctp_paramhdr) +
1393                                                     sizeof(*ippp);
1394                                                 ph = mtod(oper,
1395                                                     struct sctp_paramhdr *);
1396                                                 ph->param_type =
1397                                                     htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
1398                                                 ph->param_length =
1399                                                     htons(oper->m_len);
1400                                                 ippp = (u_int32_t *)(ph + 1);
1401                                                 *ippp = htonl(0x10000008);
1402                                         }
1403
1404                                         sctp_abort_an_association(stcb->sctp_ep,
1405                                             stcb, SCTP_PEER_FAULTY, oper);
1406
1407                                         *abort_flag = 1;
1408                                         return;
1409                                 }
1410                         }
1411                 }
1412         }
1413
1414         if (next) {
1415                 post_tsn = chk->rec.data.TSN_seq + 1;
1416                 if (post_tsn == next->rec.data.TSN_seq) {
1417                         /*
1418                          * Ok the one I am inserting ahead of
1419                          * is my NEXT one. A bit of valdiation here.
1420                          */
1421                         if (next->rec.data.rcv_flags & SCTP_DATA_FIRST_FRAG) {
1422                                 /* Insert chk MUST be a last fragment */
1423                                 if ((chk->rec.data.rcv_flags&SCTP_DATA_FRAG_MASK)
1424                                    != SCTP_DATA_LAST_FRAG) {
1425 #ifdef SCTP_DEBUG
1426                                         if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
1427                                                 printf("Next chk - Next is FIRST, we must be LAST\n");
1428                                                 printf("Gak, Evil plot, its not a last!\n");
1429                                         }
1430 #endif
1431                                         MGET(oper, M_DONTWAIT, MT_DATA);
1432                                         if (oper) {
1433                                                 struct sctp_paramhdr *ph;
1434                                                 u_int32_t *ippp;
1435
1436                                                 oper->m_len =
1437                                                     sizeof(struct sctp_paramhdr) +
1438                                                     sizeof(*ippp);
1439                                                 ph = mtod(oper,
1440                                                     struct sctp_paramhdr *);
1441                                                 ph->param_type =
1442                                                     htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
1443                                                 ph->param_length =
1444                                                     htons(oper->m_len);
1445                                                 ippp = (u_int32_t *)(ph + 1);
1446                                                 *ippp = htonl(0x10000009);
1447                                         }
1448
1449                                         sctp_abort_an_association(stcb->sctp_ep,
1450                                             stcb, SCTP_PEER_FAULTY, oper);
1451
1452                                         *abort_flag = 1;
1453                                         return;
1454                                 }
1455                         } else if ((next->rec.data.rcv_flags & SCTP_DATA_FRAG_MASK) ==
1456                             SCTP_DATA_MIDDLE_FRAG ||
1457                             (next->rec.data.rcv_flags&SCTP_DATA_FRAG_MASK) ==
1458                             SCTP_DATA_LAST_FRAG) {
1459                                 /* Insert chk CAN be MIDDLE or FIRST NOT LAST */
1460                                 if ((chk->rec.data.rcv_flags & SCTP_DATA_FRAG_MASK) ==
1461                                     SCTP_DATA_LAST_FRAG) {
1462 #ifdef SCTP_DEBUG
1463                                         if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
1464                                                 printf("Next chk - Next is a MIDDLE/LAST\n");
1465                                                 printf("Gak, Evil plot, new prev chunk is a LAST\n");
1466                                         }
1467 #endif
1468                                         MGET(oper, M_DONTWAIT, MT_DATA);
1469                                         if (oper) {
1470                                                 struct sctp_paramhdr *ph;
1471                                                 u_int32_t *ippp;
1472
1473                                                 oper->m_len =
1474                                                     sizeof(struct sctp_paramhdr) +
1475                                                     sizeof(*ippp);
1476                                                 ph = mtod(oper,
1477                                                     struct sctp_paramhdr *);
1478                                                 ph->param_type =
1479                                                     htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
1480                                                 ph->param_length =
1481                                                     htons(oper->m_len);
1482                                                 ippp = (u_int32_t *)(ph + 1);
1483                                                 *ippp = htonl(0x1000000a);
1484                                         }
1485                                         sctp_abort_an_association(stcb->sctp_ep,
1486                                             stcb, SCTP_PEER_FAULTY, oper);
1487
1488                                         *abort_flag = 1;
1489                                         return;
1490                                 }
1491                                 if (chk->rec.data.stream_number !=
1492                                     next->rec.data.stream_number) {
1493                                         /*
1494                                          * Huh, need the correct STR here, they
1495                                          * must be the same.
1496                                          */
1497 #ifdef SCTP_DEBUG
1498                                         if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
1499                                                 printf("Next chk - Gak, Evil plot, ssn:%d not the same as at:%d\n",
1500                                                     chk->rec.data.stream_number,
1501                                                     next->rec.data.stream_number);
1502                                         }
1503 #endif
1504                                         MGET(oper, M_DONTWAIT, MT_DATA);
1505                                         if (oper) {
1506                                                 struct sctp_paramhdr *ph;
1507                                                 u_int32_t *ippp;
1508
1509                                                 oper->m_len =
1510                                                     sizeof(struct sctp_paramhdr) +
1511                                                     sizeof(*ippp);
1512                                                 ph = mtod(oper,
1513                                                     struct sctp_paramhdr *);
1514                                                 ph->param_type =
1515                                                     htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
1516                                                 ph->param_length =
1517                                                     htons(oper->m_len);
1518                                                 ippp = (u_int32_t *)(ph + 1);
1519                                                 *ippp = htonl(0x1000000b);
1520                                         }
1521
1522                                         sctp_abort_an_association(stcb->sctp_ep,
1523                                             stcb, SCTP_PEER_FAULTY, oper);
1524
1525                                         *abort_flag = 1;
1526                                         return;
1527                                 }
1528                                 if ((next->rec.data.rcv_flags & SCTP_DATA_UNORDERED) == 0 &&
1529                                     chk->rec.data.stream_seq !=
1530                                     next->rec.data.stream_seq) {
1531                                         /*
1532                                          * Huh, need the correct STR here, they
1533                                          * must be the same.
1534                                          */
1535 #ifdef SCTP_DEBUG
1536                                         if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
1537                                                 printf("Next chk - Gak, Evil plot, sseq:%d not the same as at:%d\n",
1538                                                     chk->rec.data.stream_seq,
1539                                                     next->rec.data.stream_seq);
1540                                         }
1541 #endif
1542                                         MGET(oper, M_DONTWAIT, MT_DATA);
1543                                         if (oper) {
1544                                                 struct sctp_paramhdr *ph;
1545                                                 u_int32_t *ippp;
1546
1547                                                 oper->m_len =
1548                                                     sizeof(struct sctp_paramhdr) +
1549                                                     sizeof(*ippp);
1550                                                 ph = mtod(oper,
1551                                                     struct sctp_paramhdr *);
1552                                                 ph->param_type =
1553                                                     htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
1554                                                 ph->param_length =
1555                                                     htons(oper->m_len);
1556                                                 ippp = (u_int32_t *)(ph + 1);
1557                                                 *ippp = htonl(0x1000000c);
1558                                         }
1559
1560                                         sctp_abort_an_association(stcb->sctp_ep,
1561                                             stcb, SCTP_PEER_FAULTY, oper);
1562
1563                                         *abort_flag = 1;
1564                                         return;
1565
1566                                 }
1567                         }
1568                 }
1569         }
1570         /*
1571          * now that we have all in there place we must check a number of
1572          * things to see if we can send data to the ULP.
1573          */
1574         /* we need to do some delivery, if we can */
1575         chk = TAILQ_FIRST(&asoc->reasmqueue);
1576         if (chk == NULL) {
1577                 /* Huh? */
1578                 asoc->size_on_reasm_queue = 0;
1579                 asoc->cnt_on_reasm_queue = 0;
1580                 return;
1581         }
1582         if (asoc->fragmented_delivery_inprogress == 0) {
1583                 nxt_todel =
1584                     asoc->strmin[chk->rec.data.stream_number].last_sequence_delivered + 1;
1585                 if ((chk->rec.data.rcv_flags & SCTP_DATA_FIRST_FRAG) &&
1586                     (nxt_todel == chk->rec.data.stream_seq ||
1587                      (chk->rec.data.rcv_flags & SCTP_DATA_UNORDERED))) {
1588                         /*
1589                          * Yep the first one is here and its
1590                          * ok to deliver but should we?
1591                          */
1592                         if (TAILQ_EMPTY(&asoc->delivery_queue) &&
1593                             (sctp_is_all_msg_on_reasm(asoc, &tsize) ||
1594                              (asoc->size_on_reasm_queue >=
1595                               (stcb->sctp_socket->so_rcv.sb_hiwat >> 2) &&
1596                               tsize))) {
1597                                 /*
1598                                  * Yes, we setup to
1599                                  * start reception, by backing down the TSN
1600                                  * just in case we can't deliver. If we
1601                                  */
1602                                 asoc->fragmented_delivery_inprogress = 1;
1603                                 asoc->tsn_last_delivered =
1604                                     chk->rec.data.TSN_seq - 1;
1605                                 asoc->str_of_pdapi =
1606                                     chk->rec.data.stream_number;
1607                                 asoc->ssn_of_pdapi = chk->rec.data.stream_seq;
1608                                 asoc->fragment_flags = chk->rec.data.rcv_flags;
1609                                 sctp_service_reassembly(stcb, asoc, 0);
1610                         }
1611                 }
1612         } else {
1613                 sctp_service_reassembly(stcb, asoc, 0);
1614         }
1615 }
1616
1617 /*
1618  * This is an unfortunate routine. It checks to make sure a evil guy is not
1619  * stuffing us full of bad packet fragments. A broken peer could also do this
1620  * but this is doubtful. It is to bad I must worry about evil crackers sigh
1621  * :< more cycles.
1622  */
1623 static int
1624 sctp_does_chk_belong_to_reasm(struct sctp_association *asoc,
1625     struct sctp_tmit_chunk *chk)
1626 {
1627         struct sctp_tmit_chunk *at;
1628         u_int32_t tsn_est;
1629
1630         TAILQ_FOREACH(at, &asoc->reasmqueue, sctp_next) {
1631                 if (compare_with_wrap(chk->rec.data.TSN_seq,
1632                     at->rec.data.TSN_seq, MAX_TSN)) {
1633                         /* is it one bigger? */
1634                         tsn_est = at->rec.data.TSN_seq + 1;
1635                         if (tsn_est == chk->rec.data.TSN_seq) {
1636                                 /* yep. It better be a last then*/
1637                                 if ((at->rec.data.rcv_flags & SCTP_DATA_FRAG_MASK) !=
1638                                     SCTP_DATA_LAST_FRAG) {
1639                                         /*
1640                                          * Ok this guy belongs next to a guy
1641                                          * that is NOT last, it should be a
1642                                          * middle/last, not a complete chunk.
1643                                          */
1644                                         return (1);
1645                                 } else {
1646                                         /*
1647                                          * This guy is ok since its a LAST and
1648                                          * the new chunk is a fully self-
1649                                          * contained one.
1650                                          */
1651                                         return (0);
1652                                 }
1653                         }
1654                 } else if (chk->rec.data.TSN_seq == at->rec.data.TSN_seq) {
1655                         /* Software error since I have a dup? */
1656                         return (1);
1657                 } else {
1658                         /*
1659                          * Ok, 'at' is larger than new chunk but does it
1660                          * need to be right before it.
1661                          */
1662                         tsn_est = chk->rec.data.TSN_seq + 1;
1663                         if (tsn_est == at->rec.data.TSN_seq) {
1664                                 /* Yep, It better be a first */
1665                                 if ((at->rec.data.rcv_flags & SCTP_DATA_FRAG_MASK) !=
1666                                     SCTP_DATA_FIRST_FRAG) {
1667                                         return (1);
1668                                 } else {
1669                                         return (0);
1670                                 }
1671                         }
1672                 }
1673         }
1674         return (0);
1675 }
1676
1677 extern unsigned int sctp_max_chunks_on_queue;
1678 static int
1679 sctp_process_a_data_chunk(struct sctp_tcb *stcb, struct sctp_association *asoc,
1680     struct mbuf **m, int offset, struct sctp_data_chunk *ch, int chk_length,
1681     struct sctp_nets *net, u_int32_t *high_tsn, int *abort_flag,
1682     int *break_flag, int last_chunk)
1683 {
1684         /* Process a data chunk */
1685         /*  struct sctp_tmit_chunk *chk;*/
1686         struct sctp_tmit_chunk *chk;
1687         u_int32_t tsn, gap;
1688         struct mbuf *dmbuf;
1689         int indx, the_len;
1690         u_int16_t strmno, strmseq;
1691         struct mbuf *oper;
1692
1693         chk = NULL;
1694         tsn = ntohl(ch->dp.tsn);
1695 #ifdef SCTP_MAP_LOGGING
1696         sctp_log_map(0, tsn, asoc->cumulative_tsn, SCTP_MAP_PREPARE_SLIDE);
1697 #endif
1698         if (compare_with_wrap(asoc->cumulative_tsn, tsn, MAX_TSN) ||
1699             asoc->cumulative_tsn == tsn) {
1700                 /* It is a duplicate */
1701                 sctp_pegs[SCTP_DUPTSN_RECVD]++;
1702                 if (asoc->numduptsns < SCTP_MAX_DUP_TSNS) {
1703                         /* Record a dup for the next outbound sack */
1704                         asoc->dup_tsns[asoc->numduptsns] = tsn;
1705                         asoc->numduptsns++;
1706                 }
1707                 return (0);
1708         }
1709         /* Calculate the number of TSN's between the base and this TSN */
1710         if (tsn >= asoc->mapping_array_base_tsn) {
1711                 gap  = tsn - asoc->mapping_array_base_tsn;
1712         } else {
1713                 gap = (MAX_TSN - asoc->mapping_array_base_tsn) + tsn + 1;
1714         }
1715         if (gap >= (SCTP_MAPPING_ARRAY << 3)) {
1716                 /* Can't hold the bit in the mapping at max array, toss it */
1717                 return (0);
1718         }
1719         if (gap >= (uint32_t)(asoc->mapping_array_size << 3)) {
1720                 if (sctp_expand_mapping_array(asoc)) {
1721                         /* Can't expand, drop it */
1722                         return (0);
1723                 }
1724         }
1725         if (compare_with_wrap(tsn, *high_tsn, MAX_TSN)) {
1726                 *high_tsn = tsn;
1727         }
1728         /* See if we have received this one already */
1729         if (SCTP_IS_TSN_PRESENT(asoc->mapping_array, gap)) {
1730                 sctp_pegs[SCTP_DUPTSN_RECVD]++;
1731                 if (asoc->numduptsns < SCTP_MAX_DUP_TSNS) {
1732                         /* Record a dup for the next outbound sack */
1733                         asoc->dup_tsns[asoc->numduptsns] = tsn;
1734                         asoc->numduptsns++;
1735                 }
1736                 if (!callout_pending(&asoc->dack_timer.timer)) {
1737                         /*
1738                          * By starting the timer we assure that we
1739                          * WILL sack at the end of the packet
1740                          * when sctp_sack_check gets called.
1741                          */
1742                         sctp_timer_start(SCTP_TIMER_TYPE_RECV, stcb->sctp_ep,
1743                             stcb, NULL);
1744                 }
1745                 return (0);
1746         }
1747         /*
1748          * Check to see about the GONE flag, duplicates would cause
1749          * a sack to be sent up above
1750          */
1751         if (stcb && (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE)) {
1752                 /*
1753                  * wait a minute, this guy is gone, there is no
1754                  * longer a receiver. Send peer an ABORT!
1755                  */
1756                 struct mbuf *op_err;
1757                 op_err = sctp_generate_invmanparam(SCTP_CAUSE_OUT_OF_RESC);
1758                 sctp_abort_an_association(stcb->sctp_ep, stcb, 0, op_err);
1759                 *abort_flag = 1;
1760                 return (0);
1761         }
1762         /*
1763          * Now before going further we see if there is room. If NOT then
1764          * we MAY let one through only IF this TSN is the one we are
1765          * waiting for on a partial delivery API.
1766          */
1767
1768         /* now do the tests */
1769         if (((asoc->cnt_on_all_streams +
1770          asoc->cnt_on_delivery_queue +
1771          asoc->cnt_on_reasm_queue +
1772           asoc->cnt_msg_on_sb) > sctp_max_chunks_on_queue) ||
1773            (((int)asoc->my_rwnd) <= 0)) {
1774                 /*
1775                  * When we have NO room in the rwnd we check
1776                  * to make sure the reader is doing its job...
1777                  */
1778                 if (stcb->sctp_socket->so_rcv.sb_cc) {
1779                         /* some to read, wake-up */
1780                         sctp_sorwakeup(stcb->sctp_ep, stcb->sctp_socket);
1781                 }
1782                 /* now is it in the mapping array of what we have accepted? */
1783                 if (compare_with_wrap(tsn,
1784                     asoc->highest_tsn_inside_map, MAX_TSN)) {
1785
1786                         /* Nope not in the valid range dump it */
1787 #ifdef SCTP_DEBUG
1788                         if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
1789                                 printf("My rwnd overrun1:tsn:%lx rwnd %lu sbspace:%ld delq:%d!\n",
1790                                     (u_long)tsn, (u_long)asoc->my_rwnd,
1791                                     sctp_sbspace(&stcb->sctp_socket->so_rcv),
1792                                     stcb->asoc.cnt_on_delivery_queue);
1793                         }
1794 #endif
1795                         sctp_set_rwnd(stcb, asoc);
1796                         if ((asoc->cnt_on_all_streams +
1797                             asoc->cnt_on_delivery_queue +
1798                             asoc->cnt_on_reasm_queue +
1799                             asoc->cnt_msg_on_sb) > sctp_max_chunks_on_queue) {
1800                                 sctp_pegs[SCTP_MSGC_DROP]++;
1801                         } else {
1802                                 sctp_pegs[SCTP_RWND_DROPS]++;
1803                         }
1804                         indx = *break_flag;
1805                         *break_flag = 1;
1806                         return (0);
1807                 }
1808         }
1809         strmno = ntohs(ch->dp.stream_id);
1810         if (strmno >= asoc->streamincnt) {
1811                 struct sctp_paramhdr *phdr;
1812                 struct mbuf *mb;
1813
1814                 MGETHDR(mb, M_DONTWAIT, MT_DATA);
1815                 if (mb != NULL) {
1816                         /* add some space up front so prepend will work well */
1817                         mb->m_data += sizeof(struct sctp_chunkhdr);
1818                         phdr = mtod(mb, struct sctp_paramhdr *);
1819                         /*
1820                          * Error causes are just param's and this one has
1821                          * two back to back phdr, one with the error type
1822                          * and size, the other with the streamid and a rsvd
1823                          */
1824                         mb->m_pkthdr.len = mb->m_len =
1825                             (sizeof(struct sctp_paramhdr) * 2);
1826                         phdr->param_type = htons(SCTP_CAUSE_INV_STRM);
1827                         phdr->param_length =
1828                             htons(sizeof(struct sctp_paramhdr) * 2);
1829                         phdr++;
1830                         /* We insert the stream in the type field */
1831                         phdr->param_type = ch->dp.stream_id;
1832                         /* And set the length to 0 for the rsvd field */
1833                         phdr->param_length = 0;
1834                         sctp_queue_op_err(stcb, mb);
1835                 }
1836                 sctp_pegs[SCTP_BAD_STRMNO]++;
1837                 return (0);
1838         }
1839         /*
1840          * Before we continue lets validate that we are not
1841          * being fooled by an evil attacker. We can only
1842          * have 4k chunks based on our TSN spread allowed
1843          * by the mapping array 512 * 8 bits, so there is
1844          * no way our stream sequence numbers could have wrapped.
1845          * We of course only validate the FIRST fragment so the
1846          * bit must be set.
1847          */
1848         strmseq = ntohs(ch->dp.stream_sequence);
1849         if ((ch->ch.chunk_flags & SCTP_DATA_FIRST_FRAG) &&
1850             (ch->ch.chunk_flags & SCTP_DATA_UNORDERED) == 0 &&
1851             (compare_with_wrap(asoc->strmin[strmno].last_sequence_delivered,
1852              strmseq, MAX_SEQ) ||
1853              asoc->strmin[strmno].last_sequence_delivered == strmseq)) {
1854                 /* The incoming sseq is behind where we last delivered? */
1855 #ifdef SCTP_DEBUG
1856                 if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
1857                         printf("EVIL/Broken-Dup S-SEQ:%d delivered:%d from peer, Abort!\n",
1858                             strmseq,
1859                             asoc->strmin[strmno].last_sequence_delivered);
1860                 }
1861 #endif
1862                 /*
1863                  * throw it in the stream so it gets cleaned up in
1864                  * association destruction
1865                  */
1866                 MGET(oper, M_DONTWAIT, MT_DATA);
1867                 if (oper) {
1868                         struct sctp_paramhdr *ph;
1869                         u_int32_t *ippp;
1870
1871                         oper->m_len = sizeof(struct sctp_paramhdr) +
1872                             sizeof(*ippp);
1873                         ph = mtod(oper, struct sctp_paramhdr *);
1874                         ph->param_type = htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
1875                         ph->param_length = htons(oper->m_len);
1876                         ippp = (u_int32_t *)(ph + 1);
1877                         *ippp = htonl(0x20000001);
1878                 }
1879                 sctp_abort_an_association(stcb->sctp_ep, stcb, SCTP_PEER_FAULTY,
1880                     oper);
1881                 sctp_pegs[SCTP_BAD_SSN_WRAP]++;
1882                 *abort_flag = 1;
1883                 return (0);
1884         }
1885
1886         the_len = (chk_length-sizeof(struct sctp_data_chunk));
1887         if (last_chunk == 0) {
1888                 dmbuf = sctp_m_copym(*m,
1889                     (offset + sizeof(struct sctp_data_chunk)),
1890                     the_len, M_DONTWAIT);
1891         } else {
1892                 /* We can steal the last chunk */
1893                 dmbuf = *m;
1894                 /* lop off the top part */
1895                 m_adj(dmbuf, (offset + sizeof(struct sctp_data_chunk)));
1896                 if (dmbuf->m_pkthdr.len > the_len) {
1897                         /* Trim the end round bytes off  too */
1898                         m_adj(dmbuf, -(dmbuf->m_pkthdr.len-the_len));
1899                 }
1900                 sctp_pegs[SCTP_NO_COPY_IN]++;
1901         }
1902         if (dmbuf == NULL) {
1903                 sctp_pegs[SCTP_DROP_NOMEMORY]++;
1904                 return (0);
1905         }
1906         if ((ch->ch.chunk_flags & SCTP_DATA_NOT_FRAG) == SCTP_DATA_NOT_FRAG &&
1907             asoc->fragmented_delivery_inprogress == 0 &&
1908             TAILQ_EMPTY(&asoc->delivery_queue) &&
1909             ((ch->ch.chunk_flags & SCTP_DATA_UNORDERED) ||
1910              ((asoc->strmin[strmno].last_sequence_delivered + 1) == strmseq &&
1911               TAILQ_EMPTY(&asoc->strmin[strmno].inqueue))) &&
1912             ((long)(stcb->sctp_socket->so_rcv.sb_hiwat -
1913                     stcb->sctp_socket->so_rcv.sb_cc) >= (long)the_len)) {
1914                 /* Candidate for express delivery */
1915                 /*
1916                  * Its not fragmented,
1917                  * No PD-API is up,
1918                  * Nothing in the delivery queue,
1919                  * Its un-ordered OR ordered and the next to deliver AND
1920                  * nothing else is stuck on the stream queue,
1921                  * And there is room for it in the socket buffer.
1922                  * Lets just stuff it up the buffer....
1923                  */
1924
1925                 struct mbuf *control, *mmm;
1926                 struct sockaddr_in6 sin6;
1927                 struct sockaddr_in6 lsa6;
1928                 struct sockaddr *to;
1929
1930                 /* It would be nice to avoid this copy if we could :< */
1931                 control = sctp_build_ctl_nchunk(stcb, tsn,
1932                     ch->dp.protocol_id, 0, strmno, strmseq,
1933                     ch->ch.chunk_flags);
1934                 /* XXX need to append PKTHDR to the socket buffer first */
1935
1936                 if ((dmbuf->m_flags & M_PKTHDR) == 0) {
1937                         struct mbuf *tmp;
1938                         MGETHDR(tmp, M_DONTWAIT, MT_DATA);
1939                         if (tmp == NULL) {
1940
1941                                 /* no room! */
1942                                 if (control) {
1943                                         sctp_m_freem(control);
1944                                         stcb->asoc.my_rwnd_control_len -=
1945                                             CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
1946                                 }
1947
1948                                 goto failed_express_del;
1949                         }
1950                         tmp->m_pkthdr.len = the_len;
1951                         tmp->m_len = 0;
1952                         tmp->m_next = dmbuf;
1953                         dmbuf = tmp;
1954                 }
1955                 to = (struct sockaddr *)&net->ro._l_addr;
1956                 if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_NEEDS_MAPPED_V4) &&
1957                     to->sa_family == AF_INET) {
1958                         struct sockaddr_in *sin;
1959
1960                         sin = (struct sockaddr_in *)to;
1961                         bzero(&sin6, sizeof(sin6));
1962                         sin6.sin6_family = AF_INET6;
1963                         sin6.sin6_len = sizeof(struct sockaddr_in6);
1964                         sin6.sin6_addr.s6_addr16[2] = 0xffff;
1965                         bcopy(&sin->sin_addr,
1966                             &sin6.sin6_addr.s6_addr16[3],
1967                             sizeof(sin6.sin6_addr.s6_addr16[3]));
1968                         sin6.sin6_port = sin->sin_port;
1969                         to = (struct sockaddr *)&sin6;
1970                 }
1971
1972                 /* check and strip embedded scope junk */
1973                 to = (struct sockaddr *)sctp_recover_scope((struct sockaddr_in6 *)to,
1974                     &lsa6);
1975                 if (((struct sockaddr_in *)to)->sin_port == 0) {
1976                         printf("Huh c, port is %d not net:%x %d?\n",
1977                                ((struct sockaddr_in *)to)->sin_port,
1978                                (u_int)net,
1979                                (int)(ntohs(stcb->rport)));
1980                         ((struct sockaddr_in *)to)->sin_port = stcb->rport;
1981                 }
1982
1983                 mmm = dmbuf;
1984                 /* Mark the EOR */
1985                 while (mmm->m_next != NULL) {
1986                         mmm = mmm->m_next;
1987                 }
1988                 mmm->m_flags |= M_EOR;
1989                 if (compare_with_wrap(tsn, asoc->highest_tsn_inside_map, MAX_TSN)) {
1990                         /* we have a new high score */
1991                         asoc->highest_tsn_inside_map = tsn;
1992 #ifdef SCTP_MAP_LOGGING
1993                         sctp_log_map(0, 1, asoc->highest_tsn_inside_map, SCTP_MAP_SLIDE_RESULT);
1994 #endif
1995                 }
1996                 SCTP_TCB_UNLOCK(stcb);
1997                 SCTP_INP_WLOCK(stcb->sctp_ep);
1998                 SCTP_TCB_LOCK(stcb);
1999                 if (!sbappendaddr_nocheck(&stcb->sctp_socket->so_rcv, to, dmbuf,
2000                     control, stcb->asoc.my_vtag, stcb->sctp_ep)) {
2001                         if (control) {
2002                                 sctp_m_freem(control);
2003                                 stcb->asoc.my_rwnd_control_len -=
2004                                     CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
2005                         }
2006                         sctp_m_freem(dmbuf);
2007                         goto failed_express_del;
2008                 }
2009                 if ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL) == 0) {
2010                         if (sctp_add_to_socket_q(stcb->sctp_ep, stcb)) {
2011                                 stcb->asoc.my_rwnd_control_len += sizeof(struct mbuf);
2012                         }
2013                 } else {
2014                         stcb->asoc.my_rwnd_control_len += sizeof(struct mbuf);
2015                 }
2016                 SCTP_INP_WUNLOCK(stcb->sctp_ep);
2017                 sctp_sorwakeup(stcb->sctp_ep, stcb->sctp_socket);
2018                 if ((ch->ch.chunk_flags & SCTP_DATA_UNORDERED) == 0) {
2019
2020                         /* for ordered, bump what we delivered */
2021                         asoc->strmin[strmno].last_sequence_delivered++;
2022                 }
2023                 sctp_pegs[SCTP_EXPRESS_ROUTE]++;
2024 #ifdef SCTP_STR_LOGGING
2025                 sctp_log_strm_del_alt(tsn, strmseq,
2026                     SCTP_STR_LOG_FROM_EXPRS_DEL);
2027 #endif
2028 #ifdef SCTP_DEBUG
2029                 if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
2030                         printf("Express Delivery succeeds\n");
2031                 }
2032 #endif
2033                 goto finish_express_del;
2034         }
2035
2036  failed_express_del:
2037         /* If we reach here this is a new chunk */
2038         chk = (struct sctp_tmit_chunk *)SCTP_ZONE_GET(sctppcbinfo.ipi_zone_chunk);
2039         if (chk == NULL) {
2040                 /* No memory so we drop the chunk */
2041                 sctp_pegs[SCTP_DROP_NOMEMORY]++;
2042                 if (last_chunk == 0) {
2043                         /* we copied it, free the copy */
2044                         sctp_m_freem(dmbuf);
2045                 }
2046                 return (0);
2047         }
2048         sctppcbinfo.ipi_count_chunk++;
2049         sctppcbinfo.ipi_gencnt_chunk++;
2050         chk->rec.data.TSN_seq = tsn;
2051         chk->rec.data.stream_seq = strmseq;
2052         chk->rec.data.stream_number = strmno;
2053         chk->rec.data.payloadtype = ch->dp.protocol_id;
2054         chk->rec.data.context = 0;
2055         chk->rec.data.doing_fast_retransmit = 0;
2056         chk->rec.data.rcv_flags = ch->ch.chunk_flags;
2057         chk->asoc = asoc;
2058         chk->send_size = the_len;
2059         chk->whoTo = net;
2060         net->ref_count++;
2061         chk->data = dmbuf;
2062
2063
2064         /* Mark it as received */
2065         /* Now queue it where it belongs */
2066         if ((chk->rec.data.rcv_flags & SCTP_DATA_NOT_FRAG) ==
2067             SCTP_DATA_NOT_FRAG) {
2068                 /* First a sanity check */
2069                 if (asoc->fragmented_delivery_inprogress) {
2070                         /*
2071                          * Ok, we have a fragmented delivery in progress
2072                          * if this chunk is next to deliver OR belongs in
2073                          * our view to the reassembly, the peer is evil
2074                          * or broken.
2075                          */
2076                         u_int32_t estimate_tsn;
2077                         estimate_tsn = asoc->tsn_last_delivered + 1;
2078                         if (TAILQ_EMPTY(&asoc->reasmqueue) &&
2079                             (estimate_tsn == chk->rec.data.TSN_seq)) {
2080                                 /* Evil/Broke peer */
2081                                 MGET(oper, M_DONTWAIT, MT_DATA);
2082                                 if (oper) {
2083                                         struct sctp_paramhdr *ph;
2084                                         u_int32_t *ippp;
2085
2086                                         oper->m_len =
2087                                             sizeof(struct sctp_paramhdr) +
2088                                             sizeof(*ippp);
2089                                         ph = mtod(oper, struct sctp_paramhdr *);
2090                                         ph->param_type =
2091                                             htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
2092                                         ph->param_length = htons(oper->m_len);
2093                                         ippp = (u_int32_t *)(ph + 1);
2094                                         *ippp = htonl(0x20000002);
2095                                 }
2096                                 sctp_abort_an_association(stcb->sctp_ep, stcb,
2097                                     SCTP_PEER_FAULTY, oper);
2098
2099                                 *abort_flag = 1;
2100                                 sctp_pegs[SCTP_DROP_FRAG]++;
2101                                 return (0);
2102                         } else {
2103                                 if (sctp_does_chk_belong_to_reasm(asoc, chk)) {
2104                                         MGET(oper, M_DONTWAIT, MT_DATA);
2105                                         if (oper) {
2106                                                 struct sctp_paramhdr *ph;
2107                                                 u_int32_t *ippp;
2108
2109                                                 oper->m_len =
2110                                                     sizeof(struct sctp_paramhdr) +
2111                                                     sizeof(*ippp);
2112                                                 ph = mtod(oper,
2113                                                     struct sctp_paramhdr *);
2114                                                 ph->param_type =
2115                                                     htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
2116                                                 ph->param_length =
2117                                                     htons(oper->m_len);
2118                                                 ippp = (u_int32_t *)(ph + 1);
2119                                                 *ippp = htonl(0x20000003);
2120                                         }
2121                                         sctp_abort_an_association(stcb->sctp_ep,
2122                                             stcb, SCTP_PEER_FAULTY, oper);
2123
2124                                         *abort_flag = 1;
2125                                         sctp_pegs[SCTP_DROP_FRAG]++;
2126                                         return (0);
2127                                 }
2128                         }
2129                 } else {
2130                         if (!TAILQ_EMPTY(&asoc->reasmqueue)) {
2131                                 /*
2132                                  * Reassembly queue is NOT empty
2133                                  * validate that this chk does not need to
2134                                  * be in reasembly queue. If it does then
2135                                  * our peer is broken or evil.
2136                                  */
2137                                 if (sctp_does_chk_belong_to_reasm(asoc, chk)) {
2138                                         MGET(oper, M_DONTWAIT, MT_DATA);
2139                                         if (oper) {
2140                                                 struct sctp_paramhdr *ph;
2141                                                 u_int32_t *ippp;
2142
2143                                                 oper->m_len =
2144                                                     sizeof(struct sctp_paramhdr) +
2145                                                     sizeof(*ippp);
2146                                                 ph = mtod(oper,
2147                                                     struct sctp_paramhdr *);
2148                                                 ph->param_type =
2149                                                     htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
2150                                                 ph->param_length =
2151                                                     htons(oper->m_len);
2152                                                 ippp = (u_int32_t *)(ph + 1);
2153                                                 *ippp = htonl(0x20000004);
2154                                         }
2155                                         sctp_abort_an_association(stcb->sctp_ep,
2156                                             stcb, SCTP_PEER_FAULTY, oper);
2157
2158                                         *abort_flag = 1;
2159                                         sctp_pegs[SCTP_DROP_FRAG]++;
2160                                         return (0);
2161                                 }
2162                         }
2163                 }
2164                 if (chk->rec.data.rcv_flags & SCTP_DATA_UNORDERED) {
2165                         /* queue directly into socket buffer */
2166                         sctp_deliver_data(stcb, asoc, chk, 0);
2167                         sctp_sorwakeup(stcb->sctp_ep, stcb->sctp_socket);
2168                 } else {
2169                         /* Special check for when streams are resetting.
2170                          * We could be more smart about this and check the
2171                          * actual stream to see if it is not being reset.. that
2172                          * way we would not create a HOLB when amongst streams
2173                          * being reset and those not being reset.
2174                          *
2175                          * We take complete messages that have a stream reset
2176                          * intervening (aka the TSN is after where our cum-ack needs
2177                          * to be) off and put them on a pending_reply_queue. The
2178                          * reassembly ones we do not have to worry about since
2179                          * they are all sorted and proceessed by TSN order. It
2180                          * is only the singletons I must worry about.
2181                          */
2182                         if ((asoc->pending_reply) &&
2183                            ((compare_with_wrap(tsn, ntohl(asoc->pending_reply->reset_at_tsn), MAX_TSN)) ||
2184                             (tsn == ntohl(asoc->pending_reply->reset_at_tsn)))
2185                                 ) {
2186                                 /* yep its past where we need to reset... go ahead and
2187                                  * queue it.
2188                                  */
2189                                 TAILQ_INSERT_TAIL(&asoc->pending_reply_queue , chk, sctp_next);
2190                         }  else {
2191                                 sctp_queue_data_to_stream(stcb, asoc, chk, abort_flag);
2192                         }
2193                 }
2194         } else {
2195                 /* Into the re-assembly queue */
2196                 sctp_queue_data_for_reasm(stcb, asoc, chk, abort_flag);
2197                 if (*abort_flag) {
2198                         sctp_pegs[SCTP_DROP_FRAG]++;
2199                         return (0);
2200                 }
2201         }
2202         if (compare_with_wrap(tsn, asoc->highest_tsn_inside_map, MAX_TSN)) {
2203                 /* we have a new high score */
2204                 asoc->highest_tsn_inside_map = tsn;
2205 #ifdef SCTP_MAP_LOGGING
2206                 sctp_log_map(0, 2, asoc->highest_tsn_inside_map, SCTP_MAP_SLIDE_RESULT);
2207 #endif
2208         }
2209  finish_express_del:
2210         if (last_chunk) {
2211                 *m = NULL;
2212         }
2213         sctp_pegs[SCTP_PEG_TSNS_RCVD]++;
2214         /* Set it present please */
2215 #ifdef SCTP_STR_LOGGING
2216         sctp_log_strm_del_alt(tsn, strmseq, SCTP_STR_LOG_FROM_MARK_TSN);
2217 #endif
2218 #ifdef SCTP_MAP_LOGGING
2219         sctp_log_map(asoc->mapping_array_base_tsn, asoc->cumulative_tsn,
2220                      asoc->highest_tsn_inside_map, SCTP_MAP_PREPARE_SLIDE);
2221 #endif
2222         SCTP_SET_TSN_PRESENT(asoc->mapping_array, gap);
2223         return (1);
2224 }
2225
2226 void
2227 sctp_sack_check(struct sctp_tcb *stcb, int ok_to_sack, int was_a_gap, int *abort_flag)
2228 {
2229         /*
2230          * Now we also need to check the mapping array in a couple of ways.
2231          * 1) Did we move the cum-ack point?
2232          */
2233         struct sctp_association *asoc;
2234         int i, at;
2235         int m_size, all_ones;
2236         int slide_from, slide_end, lgap, distance;
2237 #ifdef SCTP_MAP_LOGGING
2238         uint32_t old_cumack, old_base, old_highest;
2239         unsigned char aux_array[64];
2240 #endif
2241
2242         asoc = &stcb->asoc;
2243         at = 0;
2244
2245 #ifdef SCTP_MAP_LOGGING
2246         old_cumack = asoc->cumulative_tsn;
2247         old_base = asoc->mapping_array_base_tsn;
2248         old_highest = asoc->highest_tsn_inside_map;
2249         if (asoc->mapping_array_size < 64)
2250                 memcpy(aux_array, asoc->mapping_array,
2251                     asoc->mapping_array_size);
2252         else
2253                 memcpy(aux_array, asoc->mapping_array, 64);
2254 #endif
2255
2256         /*
2257          * We could probably improve this a small bit by calculating the
2258          * offset of the current cum-ack as the starting point.
2259          */
2260         all_ones = 1;
2261         m_size = stcb->asoc.mapping_array_size << 3;
2262         for (i = 0; i < m_size; i++) {
2263                 if (!SCTP_IS_TSN_PRESENT(asoc->mapping_array, i)) {
2264                         /*
2265                          * Ok we found the first place that we are
2266                          * missing a TSN.
2267                          */
2268                         at = i;
2269                         all_ones = 0;
2270                         asoc->cumulative_tsn = asoc->mapping_array_base_tsn +
2271                             (i - 1);
2272                         break;
2273                 }
2274         }
2275         if (compare_with_wrap(asoc->cumulative_tsn,
2276                               asoc->highest_tsn_inside_map,
2277                               MAX_TSN)) {
2278                 panic("huh, cumack greater than high-tsn in map");
2279         }
2280         if (all_ones ||
2281             (asoc->cumulative_tsn == asoc->highest_tsn_inside_map && at >= 8)) {
2282                 /* The complete array was completed by a single FR */
2283                 /* higest becomes the cum-ack */
2284                 int clr;
2285                 asoc->cumulative_tsn = asoc->highest_tsn_inside_map;
2286                 /* clear the array */
2287                 if (all_ones)
2288                         clr = asoc->mapping_array_size;
2289                 else {
2290                         clr = (at >> 3) + 1;
2291                         /*
2292                          * this should be the allones case
2293                          * but just in case :>
2294                          */
2295                         if (clr > asoc->mapping_array_size)
2296                                 clr = asoc->mapping_array_size;
2297                 }
2298                 memset(asoc->mapping_array, 0, clr);
2299                 /* base becomes one ahead of the cum-ack */
2300                 asoc->mapping_array_base_tsn = asoc->cumulative_tsn + 1;
2301 #ifdef SCTP_MAP_LOGGING
2302                 sctp_log_map(old_base, old_cumack, old_highest,
2303                     SCTP_MAP_PREPARE_SLIDE);
2304                 sctp_log_map(asoc->mapping_array_base_tsn, asoc->cumulative_tsn,
2305                     asoc->highest_tsn_inside_map, SCTP_MAP_SLIDE_CLEARED);
2306 #endif
2307         } else if (at >= 8) {
2308                 /* we can slide the mapping array down */
2309                 /* Calculate the new byte postion we can move down */
2310                 slide_from = at >> 3;
2311                 /* now calculate the ceiling of the move using our highest TSN value */
2312                 if (asoc->highest_tsn_inside_map >= asoc->mapping_array_base_tsn) {
2313                         lgap = asoc->highest_tsn_inside_map -
2314                             asoc->mapping_array_base_tsn;
2315                 } else {
2316                         lgap = (MAX_TSN - asoc->mapping_array_base_tsn) +
2317                             asoc->highest_tsn_inside_map + 1;
2318                 }
2319                 slide_end = lgap >> 3;
2320                 if (slide_end < slide_from) {
2321                         panic("impossible slide");
2322                 }
2323                 distance = (slide_end-slide_from) + 1;
2324 #ifdef SCTP_MAP_LOGGING
2325                 sctp_log_map(old_base, old_cumack, old_highest,
2326                     SCTP_MAP_PREPARE_SLIDE);
2327                 sctp_log_map((uint32_t)slide_from, (uint32_t)slide_end,
2328                     (uint32_t)lgap, SCTP_MAP_SLIDE_FROM);
2329 #endif
2330                 if (distance + slide_from > asoc->mapping_array_size ||
2331                     distance < 0) {
2332 #ifdef SCTP_DEBUG
2333                         if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
2334                                 printf("Ugh bad addition.. you can't hrumpp!\n");
2335                         }
2336 #endif
2337                         /*
2338                          * Here we do NOT slide forward the array so that
2339                          * hopefully when more data comes in to fill it up
2340                          * we will be able to slide it forward. Really
2341                          * I don't think this should happen :-0
2342                          */
2343
2344 #ifdef SCTP_MAP_LOGGING
2345                         sctp_log_map((uint32_t)distance, (uint32_t)slide_from,
2346                             (uint32_t)asoc->mapping_array_size,
2347                             SCTP_MAP_SLIDE_NONE);
2348 #endif
2349                 } else {
2350                         int ii;
2351                         for (ii = 0; ii < distance; ii++) {
2352                                 asoc->mapping_array[ii] =
2353                                     asoc->mapping_array[slide_from + ii];
2354                         }
2355                         for (ii = distance;ii <= slide_end; ii++) {
2356                                 asoc->mapping_array[ii] = 0;
2357                         }
2358                         asoc->mapping_array_base_tsn += (slide_from << 3);
2359 #ifdef SCTP_MAP_LOGGING
2360                         sctp_log_map(asoc->mapping_array_base_tsn,
2361                             asoc->cumulative_tsn, asoc->highest_tsn_inside_map,
2362                             SCTP_MAP_SLIDE_RESULT);
2363 #endif
2364                 }
2365         }
2366
2367         /* check the special flag for stream resets */
2368         if ((asoc->pending_reply) &&
2369            ((compare_with_wrap((asoc->cumulative_tsn+1), ntohl(asoc->pending_reply->reset_at_tsn), MAX_TSN)) ||
2370             ((asoc->cumulative_tsn+1) ==  ntohl(asoc->pending_reply->reset_at_tsn)))
2371                 ) {
2372                 /* we have finished working through the backlogged TSN's now
2373                  * time to reset streams.
2374                  * 1: call reset function.
2375                  * 2: free pending_reply space
2376                  * 3: distribute any chunks in pending_reply_queue.
2377                  */
2378                 struct sctp_tmit_chunk *chk;
2379                 sctp_handle_stream_reset_response(stcb, asoc->pending_reply);
2380                 FREE(asoc->pending_reply, M_PCB);
2381                 asoc->pending_reply = NULL;
2382                 chk = TAILQ_FIRST(&asoc->pending_reply_queue);
2383                 while (chk) {
2384                         TAILQ_REMOVE(&asoc->pending_reply_queue, chk, sctp_next);
2385                         sctp_queue_data_to_stream(stcb, asoc, chk, abort_flag);
2386                         if (*abort_flag) {
2387                                 return;
2388                         }
2389                         chk = TAILQ_FIRST(&asoc->pending_reply_queue);
2390                 }
2391         }
2392         /*
2393          * Now we need to see if we need to queue a sack or just start
2394          * the timer (if allowed).
2395          */
2396         if (ok_to_sack) {
2397                 if (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) {
2398                         /*
2399                          * Ok special case, in SHUTDOWN-SENT case.
2400                          * here we maker sure SACK timer is off and
2401                          * instead send a SHUTDOWN and a SACK
2402                          */
2403                         if (callout_pending(&stcb->asoc.dack_timer.timer)) {
2404                                 sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
2405                                     stcb->sctp_ep, stcb, NULL);
2406                         }
2407 #ifdef SCTP_DEBUG
2408                         if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
2409                                 printf("%s:%d sends a shutdown\n",
2410                                        __FILE__,
2411                                        __LINE__
2412                                        );
2413                         }
2414 #endif
2415                         sctp_send_shutdown(stcb, stcb->asoc.primary_destination);
2416                         sctp_send_sack(stcb);
2417                 } else {
2418                         int is_a_gap;
2419                         /* is there a gap now ? */
2420                         is_a_gap = compare_with_wrap(stcb->asoc.highest_tsn_inside_map,
2421                             stcb->asoc.cumulative_tsn, MAX_TSN);
2422                         if ((stcb->asoc.first_ack_sent == 0) || /* First time we send a sack */
2423                             ((was_a_gap) && (is_a_gap == 0)) || /* was a gap, but no longer is one */
2424                             (stcb->asoc.numduptsns) ||          /* we have dup's */
2425                             (is_a_gap) ||                       /* is still a gap */
2426                             (callout_pending(&stcb->asoc.dack_timer.timer)) /* timer was up . second packet */
2427                                 ) {
2428                                 /*
2429                                  * Ok we must build a SACK since the timer
2430                                  * is pending, we got our first packet OR
2431                                  * there are gaps or duplicates.
2432                                  */
2433                                 stcb->asoc.first_ack_sent = 1;
2434                                 sctp_send_sack(stcb);
2435                                 /* The sending will stop the timer */
2436                         } else {
2437                                 sctp_timer_start(SCTP_TIMER_TYPE_RECV,
2438                                     stcb->sctp_ep, stcb, NULL);
2439                         }
2440                 }
2441         }
2442 }
2443
2444 void
2445 sctp_service_queues(struct sctp_tcb *stcb, struct sctp_association *asoc, int hold_locks)
2446 {
2447         struct sctp_tmit_chunk *chk;
2448         int tsize, cntDel;
2449         u_int16_t nxt_todel;
2450
2451         cntDel = 0;
2452         if (asoc->fragmented_delivery_inprogress) {
2453                 sctp_service_reassembly(stcb, asoc, hold_locks);
2454         }
2455         /* Can we proceed further, i.e. the PD-API is complete */
2456         if (asoc->fragmented_delivery_inprogress) {
2457                 /* no */
2458                 return;
2459         }
2460
2461         /*
2462          * Yes, reassembly delivery no longer in progress see if we
2463          * have some on the sb hold queue.
2464          */
2465         do {
2466                 if (stcb->sctp_socket->so_rcv.sb_cc >= stcb->sctp_socket->so_rcv.sb_hiwat) {
2467                         if (cntDel == 0)
2468                                 sctp_sorwakeup(stcb->sctp_ep, stcb->sctp_socket);
2469                         break;
2470                 }
2471                 /* If deliver_data says no we must stop */
2472                 if (sctp_deliver_data(stcb, asoc, (struct sctp_tmit_chunk *)NULL, hold_locks) == 0)
2473                         break;
2474                 cntDel++;
2475                 chk = TAILQ_FIRST(&asoc->delivery_queue);
2476         } while (chk);
2477         if (cntDel) {
2478                 sctp_sorwakeup(stcb->sctp_ep, stcb->sctp_socket);
2479         }
2480         /*
2481          * Now is there some other chunk I can deliver
2482          * from the reassembly queue.
2483          */
2484         chk = TAILQ_FIRST(&asoc->reasmqueue);
2485         if (chk == NULL) {
2486                 asoc->size_on_reasm_queue = 0;
2487                 asoc->cnt_on_reasm_queue = 0;
2488                 return;
2489         }
2490         nxt_todel = asoc->strmin[chk->rec.data.stream_number].last_sequence_delivered + 1;
2491         if ((chk->rec.data.rcv_flags & SCTP_DATA_FIRST_FRAG) &&
2492             ((nxt_todel == chk->rec.data.stream_seq) ||
2493              (chk->rec.data.rcv_flags & SCTP_DATA_UNORDERED))) {
2494                 /*
2495                  * Yep the first one is here. We setup to
2496                  * start reception, by backing down the TSN
2497                  * just in case we can't deliver.
2498                  */
2499
2500                 /*
2501                  * Before we start though either all of the
2502                  * message should be here or 1/4 the socket buffer
2503                  * max or nothing on the delivery queue and something
2504                  * can be delivered.
2505                  */
2506                 if (TAILQ_EMPTY(&asoc->delivery_queue) &&
2507                     (sctp_is_all_msg_on_reasm(asoc, &tsize) ||
2508                      (asoc->size_on_reasm_queue >=
2509                       (stcb->sctp_socket->so_rcv.sb_hiwat >> 2) && tsize))) {
2510                         asoc->fragmented_delivery_inprogress = 1;
2511                         asoc->tsn_last_delivered = chk->rec.data.TSN_seq-1;
2512                         asoc->str_of_pdapi = chk->rec.data.stream_number;
2513                         asoc->ssn_of_pdapi = chk->rec.data.stream_seq;
2514                         asoc->fragment_flags = chk->rec.data.rcv_flags;
2515                         sctp_service_reassembly(stcb, asoc, hold_locks);
2516                 }
2517         }
2518 }
2519
2520 int
2521 sctp_process_data(struct mbuf **mm, int iphlen, int *offset, int length,
2522     struct sctphdr *sh, struct sctp_inpcb *inp, struct sctp_tcb *stcb,
2523     struct sctp_nets *net, u_int32_t *high_tsn)
2524 {
2525         struct sctp_data_chunk *ch, chunk_buf;
2526         struct sctp_association *asoc;
2527         int num_chunks = 0;     /* number of control chunks processed */
2528         int chk_length, break_flag, last_chunk;
2529         int abort_flag = 0, was_a_gap = 0;
2530         struct mbuf *m;
2531
2532         /* set the rwnd */
2533         sctp_set_rwnd(stcb, &stcb->asoc);
2534
2535         m = *mm;
2536         asoc = &stcb->asoc;
2537         if (compare_with_wrap(stcb->asoc.highest_tsn_inside_map,
2538             stcb->asoc.cumulative_tsn, MAX_TSN)) {
2539                 /* there was a gap before this data was processed */
2540                 was_a_gap = 1;
2541         }
2542         /*
2543          * setup where we got the last DATA packet from for
2544          * any SACK that may need to go out. Don't bump
2545          * the net. This is done ONLY when a chunk
2546          * is assigned.
2547          */
2548         asoc->last_data_chunk_from = net;
2549
2550         /*
2551          * Now before we proceed we must figure out if this
2552          * is a wasted cluster... i.e. it is a small packet
2553          * sent in and yet the driver underneath allocated a
2554          * full cluster for it. If so we must copy it to a
2555          * smaller mbuf and free up the cluster mbuf. This
2556          * will help with cluster starvation.
2557          */
2558         if (m->m_len < (long)MHLEN && m->m_next == NULL) {
2559                 /* we only handle mbufs that are singletons.. not chains */
2560                 MGET(m, M_DONTWAIT, MT_DATA);
2561                 if (m) {
2562                         /* ok lets see if we can copy the data up */
2563                         caddr_t *from, *to;
2564
2565                         if ((*mm)->m_flags & M_PKTHDR) {
2566                                 /* got to copy the header first */
2567 #ifdef __APPLE__
2568                                 M_COPY_PKTHDR(m, (*mm));
2569 #else
2570                                 M_MOVE_PKTHDR(m, (*mm));
2571 #endif
2572                         }
2573                         /* get the pointers and copy */
2574                         to = mtod(m, caddr_t *);
2575                         from = mtod((*mm), caddr_t *);
2576                         memcpy(to, from, (*mm)->m_len);
2577                         /* copy the length and free up the old */
2578                         m->m_len = (*mm)->m_len;
2579                         sctp_m_freem(*mm);
2580                         /* sucess, back copy */
2581                         *mm = m;
2582                 } else {
2583                         /* We are in trouble in the mbuf world .. yikes */
2584                         m = *mm;
2585                 }
2586         }
2587         /* get pointer to the first chunk header */
2588         ch = (struct sctp_data_chunk *)sctp_m_getptr(m, *offset,
2589             sizeof(chunk_buf), (u_int8_t *)&chunk_buf);
2590         if (ch == NULL) {
2591                 printf(" ... its short\n");
2592                 return (1);
2593         }
2594         /*
2595          * process all DATA chunks...
2596          */
2597
2598 #ifdef SCTP_DEBUG
2599         if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
2600                 printf("In process data off:%d length:%d iphlen:%d ch->type:%d\n",
2601                     *offset, length, iphlen, (int)ch->ch.chunk_type);
2602         }
2603 #endif
2604
2605         *high_tsn = asoc->cumulative_tsn;
2606         break_flag = 0;
2607         while (ch->ch.chunk_type == SCTP_DATA) {
2608                 /* validate chunk length */
2609                 chk_length = ntohs(ch->ch.chunk_length);
2610                 if ((size_t)chk_length < sizeof(struct sctp_data_chunk) + 1 ||
2611                     length - *offset < chk_length) {
2612                         /*
2613                          * Need to send an abort since we had a invalid
2614                          * data chunk.
2615                          */
2616                         struct mbuf *op_err;
2617                         MGET(op_err, M_DONTWAIT, MT_DATA);
2618                         if (op_err) {
2619                                 struct sctp_paramhdr *ph;
2620                                 u_int32_t *ippp;
2621
2622                                 op_err->m_len = sizeof(struct sctp_paramhdr) +
2623                                     sizeof(*ippp);
2624                                 ph = mtod(op_err, struct sctp_paramhdr *);
2625                                 ph->param_type =
2626                                     htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
2627                                 ph->param_length = htons(op_err->m_len);
2628                                 ippp = (u_int32_t *)(ph + 1);
2629                                 *ippp = htonl(0x30000001);
2630                         }
2631                         sctp_abort_association(inp, stcb, m, iphlen, sh,
2632                             op_err);
2633                         return (2);
2634                 }
2635 #ifdef SCTP_DEBUG
2636                 if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
2637                         printf("A chunk of len:%d to process (tot:%d)\n",
2638                             chk_length, length - *offset);
2639                 }
2640 #endif
2641
2642 #ifdef SCTP_AUDITING_ENABLED
2643                 sctp_audit_log(0xB1, 0);
2644 #endif
2645                 if (SCTP_SIZE32(chk_length) == *offset - length) {
2646                         last_chunk = 1;
2647                 } else {
2648                         last_chunk = 0;
2649                 }
2650                 if (sctp_process_a_data_chunk(stcb, asoc, mm, *offset, ch,
2651                     chk_length, net, high_tsn, &abort_flag, &break_flag,
2652                     last_chunk)) {
2653                         num_chunks++;
2654 #ifdef SCTP_DEBUG
2655                         if (sctp_debug_on & SCTP_DEBUG_INPUT1) {
2656                                 printf("Now incr num_chunks to %d\n",
2657                                     num_chunks);
2658                         }
2659 #endif
2660                 }
2661                 if (abort_flag)
2662                         return (2);
2663
2664                 if (break_flag) {
2665                         /*
2666                          * Set because of out of rwnd space and no drop rep
2667                          * space left.
2668                          */
2669                         break;
2670                 }
2671
2672                 *offset += SCTP_SIZE32(chk_length);
2673                 if (*offset >= length) {
2674                         /* no more data left in the mbuf chain */
2675                         break;
2676                 }
2677                 ch = (struct sctp_data_chunk *)sctp_m_getptr(m, *offset,
2678                     sizeof(chunk_buf), (u_int8_t *)&chunk_buf);
2679                 if (ch == NULL) {
2680                         *offset = length;
2681                         break;
2682                 }
2683         } /* while */
2684         if (break_flag) {
2685                 /*
2686                  * we need to report rwnd overrun drops.
2687                  */
2688                 sctp_send_packet_dropped(stcb, net, *mm, iphlen, 0);
2689         }
2690         if (num_chunks) {
2691                 /*
2692                  * Did we get data, if so update the time for
2693                  * auto-close and give peer credit for being
2694                  * alive.
2695                  */
2696                 sctp_pegs[SCTP_DATA_DG_RECV]++;
2697                 stcb->asoc.overall_error_count = 0;
2698                 SCTP_GETTIME_TIMEVAL(&stcb->asoc.time_last_rcvd);
2699         }
2700         /* now service all of the reassm queue and delivery queue */
2701         sctp_service_queues(stcb, asoc, 0);
2702         if (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) {
2703                 /*
2704                  * Assure that we ack right away by making
2705                  * sure that a d-ack timer is running. So the
2706                  * sack_check will send a sack.
2707                  */
2708                 sctp_timer_start(SCTP_TIMER_TYPE_RECV, stcb->sctp_ep, stcb,
2709                     net);
2710         }
2711         /* Start a sack timer or QUEUE a SACK for sending */
2712         sctp_sack_check(stcb, 1, was_a_gap, &abort_flag);
2713         if (abort_flag)
2714                 return (2);
2715
2716         return (0);
2717 }
2718
2719 static void
2720 sctp_handle_segments(struct sctp_tcb *stcb, struct sctp_association *asoc,
2721     struct sctp_sack_chunk *ch, u_long last_tsn, u_long *biggest_tsn_acked,
2722     u_long *biggest_newly_acked_tsn, int num_seg, int *ecn_seg_sums)
2723 {
2724         /************************************************/
2725         /* process fragments and update sendqueue        */
2726         /************************************************/
2727         struct sctp_sack *sack;
2728         struct sctp_gap_ack_block *frag;
2729         struct sctp_tmit_chunk *tp1;
2730         int i;
2731         unsigned int j;
2732 #ifdef SCTP_FR_LOGGING
2733         int num_frs=0;
2734 #endif
2735         uint16_t frag_strt, frag_end, primary_flag_set;
2736         u_long last_frag_high;
2737
2738         if (asoc->primary_destination->dest_state & SCTP_ADDR_SWITCH_PRIMARY) {
2739                 primary_flag_set = 1;
2740         } else {
2741                 primary_flag_set = 0;
2742         }
2743
2744         sack = &ch->sack;
2745         frag = (struct sctp_gap_ack_block *)((caddr_t)sack +
2746             sizeof(struct sctp_sack));
2747         tp1 = NULL;
2748         last_frag_high = 0;
2749         for (i = 0; i < num_seg; i++) {
2750                 frag_strt = ntohs(frag->start);
2751                 frag_end = ntohs(frag->end);
2752                 /* some sanity checks on the fargment offsets */
2753                 if (frag_strt > frag_end) {
2754                         /* this one is malformed, skip */
2755                         frag++;
2756                         continue;
2757                 }
2758                 if (compare_with_wrap((frag_end+last_tsn), *biggest_tsn_acked,
2759                     MAX_TSN))
2760                         *biggest_tsn_acked = frag_end+last_tsn;
2761
2762                 /* mark acked dgs and find out the highestTSN being acked */
2763                 if (tp1 == NULL) {
2764                         tp1 = TAILQ_FIRST(&asoc->sent_queue);
2765
2766                         /* save the locations of the last frags */
2767                         last_frag_high = frag_end + last_tsn;
2768                 } else {
2769                         /*
2770                          * now lets see if we need to reset the queue
2771                          * due to a out-of-order SACK fragment
2772                          */
2773                         if (compare_with_wrap(frag_strt+last_tsn,
2774                             last_frag_high, MAX_TSN)) {
2775                                 /*
2776                                  * if the new frag starts after the last TSN
2777                                  * frag covered, we are ok
2778                                  * and this one is beyond the last one
2779                                  */
2780                                 ;
2781                         } else {
2782                                 /*
2783                                  * ok, they have reset us, so we need to reset
2784                                  * the queue this will cause extra hunting but
2785                                  * hey, they chose the performance
2786                                  * hit when they failed to order there gaps..
2787                                  */
2788                                 tp1 = TAILQ_FIRST(&asoc->sent_queue);
2789                         }
2790                         last_frag_high = frag_end + last_tsn;
2791                 }
2792                 for (j = frag_strt + last_tsn; j <= frag_end + last_tsn; j++) {
2793                         while (tp1) {
2794 #ifdef SCTP_FR_LOGGING
2795                                 if (tp1->rec.data.doing_fast_retransmit)
2796                                         num_frs++;
2797 #endif
2798
2799                                 if (tp1->rec.data.TSN_seq == j) {
2800                                         if (tp1->sent != SCTP_DATAGRAM_UNSENT) {
2801                                                 /* must be held until cum-ack passes */
2802                                                 /* ECN Nonce: Add the nonce value to the sender's nonce sum */
2803                                                 if (tp1->sent < SCTP_DATAGRAM_ACKED) {
2804                                                         /*
2805                                                          * If it is less than
2806                                                          * ACKED, it is now
2807                                                          * no-longer in flight.
2808                                                          * Higher values may
2809                                                          * already be set via
2810                                                          * previous Gap Ack
2811                                                          * Blocks...
2812                                                          * i.e. ACKED or MARKED.
2813                                                          */
2814                                                         if (compare_with_wrap(tp1->rec.data.TSN_seq,
2815                                                             *biggest_newly_acked_tsn,
2816                                                             MAX_TSN)) {
2817                                                                 *biggest_newly_acked_tsn =
2818                                                                     tp1->rec.data.TSN_seq;
2819                                                         }
2820                                                         tp1->whoTo->flight_size -= tp1->book_size;
2821                                                         if (tp1->whoTo->flight_size < 0) {
2822                                                                 tp1->whoTo->flight_size = 0;
2823                                                         }
2824                                                         asoc->total_flight -=
2825                                                             tp1->book_size;
2826
2827                                                         if (asoc->total_flight < 0) {
2828                                                                 asoc->total_flight = 0;
2829                                                         }
2830
2831                                                         asoc->total_flight_count--;
2832                                                         if (asoc->total_flight_count < 0) {
2833                                                                 asoc->total_flight_count = 0;
2834                                                         }
2835
2836                                                         if (tp1->snd_count < 2) {
2837                                                                 /* True non-retransmited chunk */
2838                                                                 tp1->whoTo->net_ack2 +=
2839                                                                     tp1->send_size;
2840
2841                                                                 /* update RTO too? */
2842                                                                 if (tp1->do_rtt) {
2843                                                                         tp1->whoTo->RTO =
2844                                                                             sctp_calculate_rto(stcb,
2845                                                                             asoc,
2846                                                                             tp1->whoTo,
2847                                                                             &tp1->sent_rcv_time);
2848                                                                         tp1->whoTo->rto_pending = 0;
2849                                                                         tp1->do_rtt = 0;
2850                                                                 }
2851                                                         }
2852                                                 }
2853                                                 if (tp1->sent <= SCTP_DATAGRAM_RESEND &&
2854                                                     tp1->sent != SCTP_DATAGRAM_UNSENT &&
2855                                                     compare_with_wrap(tp1->rec.data.TSN_seq,
2856                                                     asoc->this_sack_highest_gap,
2857                                                     MAX_TSN)) {
2858                                                         asoc->this_sack_highest_gap =
2859                                                             tp1->rec.data.TSN_seq;
2860                                                         if (primary_flag_set) {
2861                                                                 tp1->whoTo->cacc_saw_newack = 1;
2862                                                         }
2863                                                 }
2864                                                 if (tp1->sent == SCTP_DATAGRAM_RESEND) {
2865 #ifdef SCTP_DEBUG
2866                                                         if (sctp_debug_on &
2867                                                             SCTP_DEBUG_INDATA3) {
2868                                                                 printf("Hmm. one that is in RESEND that is now ACKED\n");
2869                                                         }
2870 #endif
2871                                                         asoc->sent_queue_retran_cnt--;
2872 #ifdef SCTP_AUDITING_ENABLED
2873                                                         sctp_audit_log(0xB2,
2874                                                             (asoc->sent_queue_retran_cnt & 0x000000ff));
2875 #endif
2876
2877                                                         if (asoc->sent_queue_retran_cnt < 0) {
2878                                                                 printf("huh3 retran went negative?\n");
2879 #ifdef SCTP_AUDITING_ENABLED
2880                                                                 sctp_auditing(30,
2881                                                                     inp, tcb,
2882                                                                     NULL);
2883 #else
2884                                                                 asoc->sent_queue_retran_cnt = 0;
2885 #endif
2886                                                         }
2887                                                 }
2888                                                 (*ecn_seg_sums) += tp1->rec.data.ect_nonce;
2889                                                 (*ecn_seg_sums) &= SCTP_SACK_NONCE_SUM;
2890                                                 tp1->sent = SCTP_DATAGRAM_MARKED;
2891                                         }
2892                                         break;
2893                                 } /* if (tp1->TSN_seq == j) */
2894                                 if (compare_with_wrap(tp1->rec.data.TSN_seq, j,
2895                                     MAX_TSN))
2896                                         break;
2897                                 tp1 = TAILQ_NEXT(tp1, sctp_next);
2898                         }/* end while (tp1) */
2899                 }  /* end for (j = fragStart */
2900                 frag++; /* next one */
2901         }
2902 #ifdef SCTP_FR_LOGGING
2903         if (num_frs)
2904                 sctp_log_fr(*biggest_tsn_acked, *biggest_newly_acked_tsn,
2905                     last_tsn, SCTP_FR_LOG_BIGGEST_TSNS);
2906 #endif
2907 }
2908
2909 static void
2910 sctp_check_for_revoked(struct sctp_association *asoc, u_long cum_ack,
2911     u_long biggest_tsn_acked)
2912 {
2913         struct sctp_tmit_chunk *tp1;
2914         int tot_revoked=0;
2915
2916         tp1 = TAILQ_FIRST(&asoc->sent_queue);
2917         while (tp1) {
2918                 if (compare_with_wrap(tp1->rec.data.TSN_seq, cum_ack,
2919                     MAX_TSN)) {
2920                         /*
2921                          * ok this guy is either ACK or MARKED. If it is ACKED
2922                          * it has been previously acked but not this time i.e.
2923                          * revoked.  If it is MARKED it was ACK'ed again.
2924                          */
2925                         if (tp1->sent == SCTP_DATAGRAM_ACKED) {
2926                                 /* it has been revoked */
2927                                 /*
2928                                  * We do NOT add back to flight size here since
2929                                  * it is really NOT in flight. Resend (when/if
2930                                  * it occurs will add to flight size
2931                                  */
2932                                 tp1->sent = SCTP_DATAGRAM_SENT;
2933                                 tot_revoked++;
2934                         } else if (tp1->sent == SCTP_DATAGRAM_MARKED) {
2935                                 /* it has been re-acked in this SACK */
2936                                 tp1->sent = SCTP_DATAGRAM_ACKED;
2937                         }
2938                 }
2939                 if (compare_with_wrap(tp1->rec.data.TSN_seq, biggest_tsn_acked,
2940                     MAX_TSN)) {
2941                         /* above the sack */
2942                         break;
2943                 }
2944                 if (tp1->sent == SCTP_DATAGRAM_UNSENT)
2945                         break;
2946                 tp1 = TAILQ_NEXT(tp1, sctp_next);
2947         }
2948         if (tot_revoked > 0) {
2949                 /* Setup the ecn nonce re-sync point. We
2950                  * do this since once data is revoked
2951                  * we begin to retransmit things, which
2952                  * do NOT have the ECN bits set. This means
2953                  * we are now out of sync and must wait until
2954                  * we get back in sync with the peer to
2955                  * check ECN bits.
2956                  */
2957                 tp1 = TAILQ_FIRST(&asoc->send_queue);
2958                 if (tp1 == NULL) {
2959                         asoc->nonce_resync_tsn = asoc->sending_seq;
2960                 } else {
2961                         asoc->nonce_resync_tsn = tp1->rec.data.TSN_seq;
2962                 }
2963                 asoc->nonce_wait_for_ecne = 0;
2964                 asoc->nonce_sum_check = 0;
2965         }
2966
2967 }
2968
2969 extern int sctp_peer_chunk_oh;
2970
2971 static void
2972 sctp_strike_gap_ack_chunks(struct sctp_tcb *stcb, struct sctp_association *asoc,
2973     u_long biggest_tsn_acked, int strike_enabled,
2974     u_long biggest_tsn_newly_acked, int accum_moved)
2975 {
2976         struct sctp_tmit_chunk *tp1;
2977         int strike_flag=0;
2978         struct timeval now;
2979         int tot_retrans=0;
2980         u_int32_t sending_seq;
2981         int primary_switch_active = 0;
2982         int double_switch_active = 0;
2983
2984         /* select the sending_seq, this is
2985          * either the next thing ready to
2986          * be sent but not transmitted, OR,
2987          * the next seq we assign.
2988          */
2989         tp1 = TAILQ_FIRST(&stcb->asoc.send_queue);
2990         if (tp1 == NULL) {
2991                 sending_seq = asoc->sending_seq;
2992         } else {
2993                 sending_seq = tp1->rec.data.TSN_seq;
2994         }
2995
2996         if (asoc->primary_destination->dest_state & SCTP_ADDR_SWITCH_PRIMARY) {
2997                 primary_switch_active = 1;
2998         }
2999         if (asoc->primary_destination->dest_state & SCTP_ADDR_DOUBLE_SWITCH) {
3000                 double_switch_active = 1;
3001         }
3002         if (stcb->asoc.peer_supports_prsctp ) {
3003                 SCTP_GETTIME_TIMEVAL(&now);
3004         }
3005         tp1 = TAILQ_FIRST(&asoc->sent_queue);
3006         while (tp1) {
3007                 strike_flag=0;
3008                 if (compare_with_wrap(tp1->rec.data.TSN_seq, biggest_tsn_acked,
3009                     MAX_TSN) ||
3010                     tp1->sent == SCTP_DATAGRAM_UNSENT) {
3011                         /* done */
3012                         break;
3013                 }
3014                 if ((tp1->flags & (SCTP_PR_SCTP_ENABLED|SCTP_PR_SCTP_BUFFER)) ==
3015                     SCTP_PR_SCTP_ENABLED &&
3016                     tp1->sent < SCTP_DATAGRAM_ACKED) {
3017                         /* Is it expired? */
3018 #ifndef __FreeBSD__
3019                         if (timercmp(&now, &tp1->rec.data.timetodrop, >))
3020 #else
3021                         if (timevalcmp(&now, &tp1->rec.data.timetodrop, >))
3022 #endif
3023                         {
3024                                 /* Yes so drop it */
3025                                 if (tp1->data != NULL) {
3026                                         sctp_release_pr_sctp_chunk(stcb, tp1,
3027                                             (SCTP_RESPONSE_TO_USER_REQ|SCTP_NOTIFY_DATAGRAM_SENT),
3028                                             &asoc->sent_queue);
3029                                 }
3030                                 tp1 = TAILQ_NEXT(tp1, sctp_next);
3031                                 continue;
3032                         }
3033                 }
3034
3035                 if (compare_with_wrap(tp1->rec.data.TSN_seq,
3036                     asoc->this_sack_highest_gap, MAX_TSN)) {
3037                         /* we are beyond the tsn in the sack  */
3038                         break;
3039                 }
3040                 if (tp1->sent >= SCTP_DATAGRAM_RESEND) {
3041                         /* either a RESEND, ACKED, or MARKED */
3042                         /* skip */
3043                         tp1 = TAILQ_NEXT(tp1, sctp_next);
3044                         continue;
3045                 }
3046                 if (primary_switch_active && (strike_enabled == 0)) {
3047                         if (tp1->whoTo != asoc->primary_destination) {
3048                                 /*
3049                                  * We can only strike things on the primary if
3050                                  * the strike_enabled flag is clear
3051                                  */
3052                                 tp1 = TAILQ_NEXT(tp1, sctp_next);
3053                                 continue;
3054                         }
3055                 } else if (primary_switch_active) {
3056                         if (tp1->whoTo->cacc_saw_newack == 0) {
3057                                 /*
3058                                  * Only one was received but it was NOT
3059                                  * this one.
3060                                  */
3061                                 tp1 = TAILQ_NEXT(tp1, sctp_next);
3062                                 continue;
3063                         }
3064                 }
3065                 if (double_switch_active &&
3066                     (compare_with_wrap(asoc->primary_destination->next_tsn_at_change,
3067                     tp1->rec.data.TSN_seq, MAX_TSN))) {
3068                         /*
3069                          * With a double switch we do NOT mark unless we
3070                          * are beyond the switch point.
3071                          */
3072                         tp1 = TAILQ_NEXT(tp1, sctp_next);
3073                         continue;
3074                 }
3075                 /*
3076                  * Here we check to see if we were have already done a FR
3077                  * and if so we see if the biggest TSN we saw in the sack is
3078                  * smaller than the recovery point. If so we don't strike the
3079                  * tsn... otherwise we CAN strike the TSN.
3080                  */
3081                 if (accum_moved && asoc->fast_retran_loss_recovery) {
3082                         /*
3083                          * Strike the TSN if in fast-recovery and
3084                          * cum-ack moved.
3085                          */
3086                         tp1->sent++;
3087                 } else if (tp1->rec.data.doing_fast_retransmit) {
3088                         /*
3089                          * For those that have done a FR we must
3090                          * take special consideration if we strike. I.e
3091                          * the biggest_newly_acked must be higher
3092                          * than the sending_seq at the time we did
3093                          * the FR.
3094                          */
3095 #ifdef SCTP_FR_TO_ALTERNATE
3096                         /*
3097                          * If FR's go to new networks, then we
3098                          * must only do this for singly homed asoc's. However
3099                          * if the FR's go to the same network (Armando's work)
3100                          * then its ok to FR multiple times.
3101                          */
3102                         if (asoc->numnets < 2)
3103 #else
3104                         if (1)
3105 #endif
3106                         {
3107                                 if ((compare_with_wrap(biggest_tsn_newly_acked,
3108                                     tp1->rec.data.fast_retran_tsn, MAX_TSN)) ||
3109                                     (biggest_tsn_newly_acked ==
3110                                      tp1->rec.data.fast_retran_tsn)) {
3111                                         /*
3112                                          * Strike the TSN, since this ack is
3113                                          * beyond where things were when we did
3114                                          * a FR.
3115                                          */
3116 #ifdef SCTP_FR_LOGGING
3117                                         sctp_log_fr(biggest_tsn_newly_acked,
3118                                             tp1->rec.data.TSN_seq,
3119                                             tp1->rec.data.fast_retran_tsn,
3120                                             SCTP_FR_LOG_STRIKE_CHUNK);
3121 #endif
3122                                         tp1->sent++;
3123                                         strike_flag=1;
3124                                 }
3125                         }
3126                 } else if (compare_with_wrap(tp1->rec.data.TSN_seq,
3127                     biggest_tsn_newly_acked, MAX_TSN)) {
3128                         /*
3129                          * We don't strike these:
3130                          * This is the  HTNA algorithm i.e. we don't strike
3131                          * If our TSN is larger than the Highest TSN Newly
3132                          * Acked.
3133                          */
3134                         ;
3135                 } else {
3136                         /* Strike the TSN */
3137                         tp1->sent++;
3138                 }
3139                 if (tp1->sent == SCTP_DATAGRAM_RESEND) {
3140                         /* Increment the count to resend */
3141                         struct sctp_nets *alt;
3142
3143 #ifdef SCTP_FR_LOGGING
3144                         sctp_log_fr(tp1->rec.data.TSN_seq, tp1->snd_count,
3145                             0, SCTP_FR_MARKED);
3146 #endif
3147                         if (strike_flag) {
3148                                 /* This is a subsequent FR */
3149                                 sctp_pegs[SCTP_DUP_FR]++;
3150                         }
3151                         asoc->sent_queue_retran_cnt++;
3152 #ifdef SCTP_FR_TO_ALTERNATE
3153                         /* Can we find an alternate? */
3154                         alt = sctp_find_alternate_net(stcb, tp1->whoTo);
3155 #else
3156                         /*
3157                          * default behavior is to NOT retransmit FR's
3158                          * to an alternate. Armando Caro's paper details
3159                          * why.
3160                          */
3161                         alt = tp1->whoTo;
3162 #endif
3163                         tp1->rec.data.doing_fast_retransmit = 1;
3164                         tot_retrans++;
3165                         /* mark the sending seq for possible subsequent FR's */
3166                         if (TAILQ_EMPTY(&asoc->send_queue)) {
3167                                 /*
3168                                  * If the queue of send is empty then its the
3169                                  * next sequence number that will be assigned so
3170                                  * we subtract one from this to get the one we
3171                                  * last sent.
3172                                  */
3173                                 tp1->rec.data.fast_retran_tsn = sending_seq - 1;
3174                         } else {
3175                                 /*
3176                                  * If there are chunks on the send queue
3177                                  * (unsent data that has made it from the
3178                                  * stream queues but not out the door, we take
3179                                  * the first one (which will have the lowest
3180                                  * TSN) and subtract one to get the one we last
3181                                  * sent.
3182                                  */
3183                                 struct sctp_tmit_chunk *ttt;
3184                                 ttt = TAILQ_FIRST(&asoc->send_queue);
3185                                 tp1->rec.data.fast_retran_tsn =
3186                                     ttt->rec.data.TSN_seq - 1;
3187                         }
3188                         if (tp1->do_rtt) {
3189                                 /*
3190                                  * this guy had a RTO calculation pending on it,
3191                                  * cancel it
3192                                  */
3193                                 tp1->whoTo->rto_pending = 0;
3194                                 tp1->do_rtt = 0;
3195                         }
3196                         /* fix counts and things */
3197
3198                         tp1->whoTo->net_ack++;
3199                         tp1->whoTo->flight_size -= tp1->book_size;
3200                         if (tp1->whoTo->flight_size < 0) {
3201                                 tp1->whoTo->flight_size = 0;
3202                         }
3203 #ifdef SCTP_LOG_RWND
3204                         sctp_log_rwnd(SCTP_INCREASE_PEER_RWND,
3205                                       asoc->peers_rwnd , tp1->send_size, sctp_peer_chunk_oh);
3206 #endif
3207                         /* add back to the rwnd */
3208                         asoc->peers_rwnd += (tp1->send_size + sctp_peer_chunk_oh);
3209
3210                         /* remove from the total flight */
3211                         asoc->total_flight -= tp1->book_size;
3212                         if (asoc->total_flight < 0) {
3213                                 asoc->total_flight = 0;
3214                         }
3215                         asoc->total_flight_count--;
3216                         if (asoc->total_flight_count < 0) {
3217                                 asoc->total_flight_count = 0;
3218                         }
3219                         if (alt != tp1->whoTo) {
3220                                 /* yes, there is an alternate. */
3221                                 sctp_free_remote_addr(tp1->whoTo);
3222                                 tp1->whoTo = alt;
3223                                 alt->ref_count++;
3224                         }
3225                 }
3226                 tp1 = TAILQ_NEXT(tp1, sctp_next);
3227         } /* while (tp1) */
3228
3229         if (tot_retrans > 0) {
3230                 /* Setup the ecn nonce re-sync point. We
3231                  * do this since once we go to FR something
3232                  * we introduce a Karn's rule scenario and
3233                  * won't know the totals for the ECN bits.
3234                  */
3235                 asoc->nonce_resync_tsn = sending_seq;
3236                 asoc->nonce_wait_for_ecne = 0;
3237                 asoc->nonce_sum_check = 0;
3238         }
3239
3240 }
3241
3242 struct sctp_tmit_chunk *
3243 sctp_try_advance_peer_ack_point(struct sctp_tcb *stcb,
3244     struct sctp_association *asoc)
3245 {
3246         struct sctp_tmit_chunk *tp1, *tp2, *a_adv=NULL;
3247         struct timeval now;
3248         int now_filled=0;
3249
3250         if (asoc->peer_supports_prsctp == 0) {
3251                 return (NULL);
3252         }
3253         tp1 = TAILQ_FIRST(&asoc->sent_queue);
3254         while (tp1) {
3255                 if (tp1->sent != SCTP_FORWARD_TSN_SKIP &&
3256                     tp1->sent != SCTP_DATAGRAM_RESEND) {
3257                         /* no chance to advance, out of here */
3258                         break;
3259                 }
3260                 if ((tp1->flags & SCTP_PR_SCTP_ENABLED) == 0) {
3261                         /*
3262                          * We can't fwd-tsn past any that are reliable
3263                          * aka retransmitted until the asoc fails.
3264                          */
3265                         break;
3266                 }
3267                 if (!now_filled) {
3268                         SCTP_GETTIME_TIMEVAL(&now);
3269                         now_filled = 1;
3270                 }
3271                 tp2 = TAILQ_NEXT(tp1, sctp_next);
3272                 /*
3273                  * now we got a chunk which is marked for another
3274                  * retransmission to a PR-stream but has run
3275                  * out its chances already maybe OR has been
3276                  * marked to skip now. Can we skip it if its a
3277                  * resend?
3278                  */
3279                 if (tp1->sent == SCTP_DATAGRAM_RESEND &&
3280                     (tp1->flags & SCTP_PR_SCTP_BUFFER) == 0) {
3281                         /*
3282                          * Now is this one marked for resend and its time
3283                          * is now up?
3284                          */
3285 #ifndef __FreeBSD__
3286                         if (timercmp(&now, &tp1->rec.data.timetodrop, >))
3287 #else
3288                         if (timevalcmp(&now, &tp1->rec.data.timetodrop, >))
3289 #endif
3290                         {
3291                                 /* Yes so drop it */
3292                                 if (tp1->data) {
3293                                         sctp_release_pr_sctp_chunk(stcb, tp1,
3294                                             (SCTP_RESPONSE_TO_USER_REQ|SCTP_NOTIFY_DATAGRAM_SENT),
3295                                             &asoc->sent_queue);
3296                                 }
3297                         } else {
3298                                 /*
3299                                  * No, we are done when hit one for resend whos
3300                                  * time as not expired.
3301                                  */
3302                                 break;
3303                         }
3304                 }
3305                 /*
3306                  * Ok now if this chunk is marked to drop it
3307                  * we can clean up the chunk, advance our peer ack point
3308                  * and we can check the next chunk.
3309                  */
3310                 if (tp1->sent == SCTP_FORWARD_TSN_SKIP) {
3311                         /* advance PeerAckPoint goes forward */
3312                         asoc->advanced_peer_ack_point = tp1->rec.data.TSN_seq;
3313                         a_adv = tp1;
3314                         /*
3315                          * we don't want to de-queue it here. Just wait for the
3316                          * next peer SACK to come with a new cumTSN and then
3317                          * the chunk will be droped in the normal fashion.
3318                          */
3319                         if (tp1->data) {
3320                                 sctp_free_bufspace(stcb, asoc, tp1);
3321 #ifdef SCTP_DEBUG
3322                                 if (sctp_debug_on & SCTP_DEBUG_OUTPUT2) {
3323                                         printf("--total out:%lu total_mbuf_out:%lu\n",
3324                                             (u_long)asoc->total_output_queue_size,
3325                                             (u_long)asoc->total_output_mbuf_queue_size);
3326                                 }
3327 #endif
3328                                 /*
3329                                  * Maybe there should be another notification
3330                                  * type
3331                                  */
3332                                 sctp_ulp_notify(SCTP_NOTIFY_DG_FAIL, stcb,
3333                                     (SCTP_RESPONSE_TO_USER_REQ|SCTP_NOTIFY_DATAGRAM_SENT),
3334                                     tp1);
3335                                 sctp_m_freem(tp1->data);
3336                                 tp1->data = NULL;
3337                                 sctp_sowwakeup(stcb->sctp_ep,
3338                                     stcb->sctp_socket);
3339                         }
3340                 } else {
3341                         /* If it is still in RESEND we can advance no further */
3342                         break;
3343                 }
3344                 /*
3345                  * If we hit here we just dumped tp1, move to next
3346                  * tsn on sent queue.
3347                  */
3348                 tp1 = tp2;
3349         }
3350         return (a_adv);
3351 }
3352
3353 #ifdef SCTP_HIGH_SPEED
3354 struct sctp_hs_raise_drop {
3355         int32_t cwnd;
3356         int32_t increase;
3357         int32_t drop_percent;
3358 };
3359
3360 #define SCTP_HS_TABLE_SIZE 73
3361
3362 struct sctp_hs_raise_drop sctp_cwnd_adjust[SCTP_HS_TABLE_SIZE] = {
3363         {38,1,50},      /* 0   */
3364         {118,2,44},     /* 1   */
3365         {221,3,41},     /* 2   */
3366         {347,4,38},     /* 3   */
3367         {495,5,37},     /* 4   */
3368         {663,6,35},     /* 5   */
3369         {851,7,34},     /* 6   */
3370         {1058,8,33},    /* 7   */
3371         {1284,9,32},    /* 8   */
3372         {1529,10,31},   /* 9   */
3373         {1793,11,30},   /* 10  */
3374         {2076,12,29},   /* 11  */
3375         {2378,13,28},   /* 12  */
3376         {2699,14,28},   /* 13  */
3377         {3039,15,27},   /* 14  */
3378         {3399,16,27},   /* 15  */
3379         {3778,17,26},   /* 16  */
3380         {4177,18,26},   /* 17  */
3381         {4596,19,25},   /* 18  */
3382         {5036,20,25},   /* 19  */
3383         {5497,21,24},   /* 20  */
3384         {5979,22,24},   /* 21  */
3385         {6483,23,23},   /* 22  */
3386         {7009,24,23},   /* 23  */
3387         {7558,25,22},   /* 24  */
3388         {8130,26,22},   /* 25  */
3389         {8726,27,22},   /* 26  */
3390         {9346,28,21},   /* 27  */
3391         {9991,29,21},   /* 28  */
3392         {10661,30,21},  /* 29  */
3393         {11358,31,20},  /* 30  */
3394         {12082,32,20},  /* 31  */
3395         {12834,33,20},  /* 32  */
3396         {13614,34,19},  /* 33  */
3397         {14424,35,19},  /* 34  */
3398         {15265,36,19},  /* 35  */
3399         {16137,37,19},  /* 36  */
3400         {17042,38,18},  /* 37  */
3401         {17981,39,18},  /* 38  */
3402         {18955,40,18},  /* 39  */
3403         {19965,41,17},  /* 40  */
3404         {21013,42,17},  /* 41  */
3405         {22101,43,17},  /* 42  */
3406         {23230,44,17},  /* 43  */
3407         {24402,45,16},  /* 44  */
3408         {25618,46,16},  /* 45  */
3409         {26881,47,16},  /* 46  */
3410         {28193,48,16},  /* 47  */
3411         {29557,49,15},  /* 48  */
3412         {30975,50,15},  /* 49  */
3413         {32450,51,15},  /* 50  */
3414         {33986,52,15},  /* 51  */
3415         {35586,53,14},  /* 52  */
3416         {37253,54,14},  /* 53  */
3417         {38992,55,14},  /* 54  */
3418         {40808,56,14},  /* 55  */
3419         {42707,57,13},  /* 56  */
3420         {44694,58,13},  /* 57  */
3421         {46776,59,13},  /* 58  */
3422         {48961,60,13},  /* 59  */
3423         {51258,61,13},  /* 60  */
3424         {53677,62,12},  /* 61  */
3425         {56230,63,12},  /* 62  */
3426         {58932,64,12},  /* 63  */
3427         {61799,65,12},  /* 64  */
3428         {64851,66,11},  /* 65  */
3429         {68113,67,11},  /* 66  */
3430         {71617,68,11},  /* 67  */
3431         {75401,69,10},  /* 68  */
3432         {79517,70,10},  /* 69  */
3433         {84035,71,10},  /* 70  */
3434         {89053,72,10},  /* 71  */
3435         {94717,73,9}    /* 72  */
3436 };
3437
3438 static void
3439 sctp_hs_cwnd_increase(struct sctp_nets *net)
3440 {
3441         int cur_val, i, indx, incr;
3442
3443         cur_val = net->cwnd >> 10;
3444         indx = SCTP_HS_TABLE_SIZE - 1;
3445
3446         if (cur_val < sctp_cwnd_adjust[0].cwnd) {
3447                 /* normal mode */
3448                 if (net->net_ack > net->mtu) {
3449                         net->cwnd += net->mtu;
3450 #ifdef SCTP_CWND_LOGGING
3451                         sctp_log_cwnd(net, net->mtu, SCTP_CWND_LOG_FROM_SS);
3452 #endif
3453                 } else {
3454                         net->cwnd += net->net_ack;
3455 #ifdef SCTP_CWND_LOGGING
3456                         sctp_log_cwnd(net, net->net_ack, SCTP_CWND_LOG_FROM_SS);
3457 #endif
3458                 }
3459         } else {
3460                 for (i=net->last_hs_used; i<SCTP_HS_TABLE_SIZE; i++) {
3461                         if (cur_val < sctp_cwnd_adjust[i].cwnd) {
3462                                 indx = i;
3463                                 break;
3464                         }
3465                 }
3466                 net->last_hs_used = indx;
3467                 incr = ((sctp_cwnd_adjust[indx].increase) << 10);
3468                 net->cwnd += incr;
3469 #ifdef SCTP_CWND_LOGGING
3470                 sctp_log_cwnd(net, incr, SCTP_CWND_LOG_FROM_SS);
3471 #endif
3472         }
3473 }
3474
3475 static void
3476 sctp_hs_cwnd_decrease(struct sctp_nets *net)
3477 {
3478         int cur_val, i, indx;
3479 #ifdef SCTP_CWND_LOGGING
3480         int old_cwnd = net->cwnd;
3481 #endif
3482
3483         cur_val = net->cwnd >> 10;
3484         indx = net->last_hs_used;
3485         if (cur_val < sctp_cwnd_adjust[0].cwnd) {
3486                 /* normal mode */
3487                 net->ssthresh = net->cwnd / 2;
3488                 if (net->ssthresh < (net->mtu*2)) {
3489                         net->ssthresh = 2 * net->mtu;
3490                 }
3491                 net->cwnd = net->ssthresh;
3492 #ifdef SCTP_CWND_LOGGING
3493                 sctp_log_cwnd(net, (net->cwnd-old_cwnd), SCTP_CWND_LOG_FROM_FR);
3494 #endif
3495         } else {
3496                 /* drop by the proper amount */
3497                 net->ssthresh = net->cwnd - (int)((net->cwnd / 100) *
3498                     sctp_cwnd_adjust[net->last_hs_used].drop_percent);
3499                 net->cwnd = net->ssthresh;
3500                 /* now where are we */
3501                 indx = net->last_hs_used;
3502                 cur_val = net->cwnd >> 10;
3503                 /* reset where we are in the table */
3504                 if (cur_val < sctp_cwnd_adjust[0].cwnd) {
3505                         /* feel out of hs */
3506                         net->last_hs_used = 0;
3507                 } else {
3508                         for (i = indx; i >= 1; i--) {
3509                                 if (cur_val > sctp_cwnd_adjust[i - 1].cwnd) {
3510                                         break;
3511                                 }
3512                         }
3513                         net->last_hs_used = indx;
3514                 }
3515         }
3516 }
3517 #endif
3518
3519 void
3520 sctp_handle_sack(struct sctp_sack_chunk *ch, struct sctp_tcb *stcb,
3521     struct sctp_nets *net_from, int *abort_now)
3522 {
3523         struct sctp_association *asoc;
3524         struct sctp_sack *sack;
3525         struct sctp_tmit_chunk *tp1, *tp2;
3526         u_long cum_ack, last_tsn, biggest_tsn_acked, biggest_tsn_newly_acked;
3527         uint16_t num_seg;
3528         unsigned int sack_length;
3529         uint32_t send_s;
3530         int some_on_streamwheel;
3531         long j;
3532         int strike_enabled = 0, cnt_of_cacc = 0;
3533         int accum_moved = 0;
3534         int marking_allowed = 1;
3535         int will_exit_fast_recovery=0;
3536         u_int32_t a_rwnd;
3537         struct sctp_nets *net = NULL;
3538         int nonce_sum_flag, ecn_seg_sums=0;
3539         asoc = &stcb->asoc;
3540
3541         /*
3542          * Handle the incoming sack on data I have been sending.
3543          */
3544
3545         /*
3546          * we take any chance we can to service our queues since we
3547          * cannot get awoken when the socket is read from :<
3548          */
3549         asoc->overall_error_count = 0;
3550
3551         if (asoc->sent_queue_retran_cnt) {
3552 #ifdef SCTP_DEBUG
3553                 if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
3554                         printf("Handling SACK for asoc:%p retran:%d\n",
3555                                asoc, asoc->sent_queue_retran_cnt);
3556                 }
3557 #endif
3558         }
3559
3560         sctp_service_queues(stcb, asoc, 0);
3561
3562         /*
3563          * Now perform the actual SACK handling:
3564          * 1) Verify that it is not an old sack, if so discard.
3565          * 2) If there is nothing left in the send queue (cum-ack is equal
3566          *    to last acked) then you have a duplicate too, update any rwnd
3567          *    change and verify no timers are running. then return.
3568          * 3) Process any new consequtive data i.e. cum-ack moved
3569          *    process these first and note that it moved.
3570          * 4) Process any sack blocks.
3571          * 5) Drop any acked from the queue.
3572          * 6) Check for any revoked blocks and mark.
3573          * 7) Update the cwnd.
3574          * 8) Nothing left, sync up flightsizes and things, stop all timers
3575          *    and also check for shutdown_pending state. If so then go ahead
3576          *    and send off the shutdown. If in shutdown recv, send off the
3577          *    shutdown-ack and start that timer, Ret.
3578          * 9) Strike any non-acked things and do FR procedure if needed being
3579          *    sure to set the FR flag.
3580          * 10) Do pr-sctp procedures.
3581          * 11) Apply any FR penalties.
3582          * 12) Assure we will SACK if in shutdown_recv state.
3583          */
3584
3585         j = 0;
3586         sack_length = ntohs(ch->ch.chunk_length);
3587         if (sack_length < sizeof(struct sctp_sack_chunk)) {
3588 #ifdef SCTP_DEBUG
3589                 if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
3590                         printf("Bad size on sack chunk .. to small\n");
3591                 }
3592 #endif
3593                 return;
3594         }
3595         /* ECN Nonce */
3596         nonce_sum_flag = ch->ch.chunk_flags & SCTP_SACK_NONCE_SUM;
3597         sack = &ch->sack;
3598         cum_ack = last_tsn = ntohl(sack->cum_tsn_ack);
3599         num_seg = ntohs(sack->num_gap_ack_blks);
3600
3601         /* reality check */
3602         if (TAILQ_EMPTY(&asoc->send_queue)) {
3603                 send_s = asoc->sending_seq;
3604         } else {
3605                 tp1 = TAILQ_FIRST(&asoc->send_queue);
3606                 send_s = tp1->rec.data.TSN_seq;
3607         }
3608
3609         if (sctp_strict_sacks) {
3610                 if (cum_ack == send_s ||
3611                     compare_with_wrap(cum_ack, send_s, MAX_TSN)) {
3612                         struct mbuf *oper;
3613                         /*
3614                          * no way, we have not even sent this TSN out yet.
3615                          * Peer is hopelessly messed up with us.
3616                          */
3617                 hopeless_peer:
3618                         *abort_now = 1;
3619                         /* XXX */
3620                         MGET(oper, M_DONTWAIT, MT_DATA);
3621                         if (oper) {
3622                                 struct sctp_paramhdr *ph;
3623                                 u_int32_t *ippp;
3624
3625                                 oper->m_len = sizeof(struct sctp_paramhdr) +
3626                                         sizeof(*ippp);
3627                                 ph = mtod(oper, struct sctp_paramhdr *);
3628                                 ph->param_type = htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
3629                                 ph->param_length = htons(oper->m_len);
3630                                 ippp = (u_int32_t *)(ph + 1);
3631                                 *ippp = htonl(0x30000002);
3632                         }
3633                         sctp_abort_an_association(stcb->sctp_ep, stcb, SCTP_PEER_FAULTY, oper);
3634                         return;
3635                 }
3636         }
3637         /* update the Rwnd of the peer */
3638         a_rwnd = (u_int32_t)ntohl(sack->a_rwnd);
3639         if (asoc->sent_queue_retran_cnt) {
3640 #ifdef SCTP_DEBUG
3641                 if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
3642                         printf("cum_ack:%lx num_seg:%u last_acked_seq:%x\n",
3643                                cum_ack, (u_int)num_seg, asoc->last_acked_seq);
3644                 }
3645 #endif
3646         }
3647         if (compare_with_wrap(asoc->t3timeout_highest_marked, cum_ack, MAX_TSN)) {
3648                 /* we are not allowed to mark for FR */
3649                 marking_allowed = 0;
3650         }
3651         /**********************/
3652         /* 1) check the range */
3653         /**********************/
3654         if (compare_with_wrap(asoc->last_acked_seq, last_tsn, MAX_TSN)) {
3655                 /* acking something behind */
3656                 if (asoc->sent_queue_retran_cnt) {
3657 #ifdef SCTP_DEBUG
3658                         if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
3659                                 printf("The cum-ack is behind us\n");
3660                         }
3661 #endif
3662                 }
3663                 return;
3664         }
3665
3666         if (TAILQ_EMPTY(&asoc->sent_queue)) {
3667                 /* nothing left on sendqueue.. consider done */
3668 #ifdef SCTP_LOG_RWND
3669                 sctp_log_rwnd_set(SCTP_SET_PEER_RWND_VIA_SACK,
3670                                   asoc->peers_rwnd, 0, 0, a_rwnd);
3671 #endif
3672                 asoc->peers_rwnd = a_rwnd;
3673                 if (asoc->sent_queue_retran_cnt) {
3674 #ifdef SCTP_DEBUG
3675                         if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
3676                                 printf("Huh? retran set but none on queue\n");
3677                         }
3678 #endif
3679                         asoc->sent_queue_retran_cnt = 0;
3680                 }
3681                 if (asoc->peers_rwnd < stcb->sctp_ep->sctp_ep.sctp_sws_sender) {
3682                         /* SWS sender side engages */
3683                         asoc->peers_rwnd = 0;
3684                 }
3685                 /* stop any timers */
3686                 TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
3687                         sctp_timer_stop(SCTP_TIMER_TYPE_SEND, stcb->sctp_ep,
3688                                         stcb, net);
3689                         net->partial_bytes_acked = 0;
3690                         net->flight_size = 0;
3691                 }
3692                 asoc->total_flight = 0;
3693                 asoc->total_flight_count = 0;
3694                 return;
3695         }
3696         /*
3697          * We init netAckSz and netAckSz2 to 0. These are used to track 2
3698          * things. The total byte count acked is tracked in netAckSz AND
3699          * netAck2 is used to track the total bytes acked that are un-
3700          * amibguious and were never retransmitted. We track these on a
3701          * per destination address basis.
3702          */
3703         TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
3704                 net->prev_cwnd = net->cwnd;
3705                 net->net_ack = 0;
3706                 net->net_ack2 = 0;
3707         }
3708         /* process the new consecutive TSN first */
3709         tp1 = TAILQ_FIRST(&asoc->sent_queue);
3710         while (tp1) {
3711                 if (compare_with_wrap(last_tsn, tp1->rec.data.TSN_seq,
3712                                       MAX_TSN) ||
3713                     last_tsn == tp1->rec.data.TSN_seq) {
3714                         if (tp1->sent != SCTP_DATAGRAM_UNSENT) {
3715                                 /* ECN Nonce: Add the nonce to the sender's nonce sum */
3716                                 asoc->nonce_sum_expect_base += tp1->rec.data.ect_nonce;
3717                                 accum_moved = 1;
3718                                 if (tp1->sent < SCTP_DATAGRAM_ACKED) {
3719                                         /*
3720                                          * If it is less than ACKED, it is now
3721                                          * no-longer in flight. Higher values
3722                                          * may occur during marking
3723                                          */
3724                                         if ((tp1->whoTo->dest_state &
3725                                              SCTP_ADDR_UNCONFIRMED) &&
3726                                             (tp1->snd_count < 2) ) {
3727                                                 /*
3728                                                  * If there was no retran and
3729                                                  * the address is un-confirmed
3730                                                  * and we sent there and are
3731                                                  * now sacked.. its confirmed,
3732                                                  * mark it so.
3733                                                  */
3734                                                 tp1->whoTo->dest_state &=
3735                                                         ~SCTP_ADDR_UNCONFIRMED;
3736                                         }
3737                                         tp1->whoTo->flight_size -=
3738                                                 tp1->book_size;
3739                                         if (tp1->whoTo->flight_size < 0) {
3740                                                 tp1->whoTo->flight_size = 0;
3741                                         }
3742                                         asoc->total_flight -= tp1->book_size;
3743                                         if (asoc->total_flight < 0) {
3744                                                 asoc->total_flight = 0;
3745                                         }
3746                                         asoc->total_flight_count--;
3747                                         if (asoc->total_flight_count < 0) {
3748                                                 asoc->total_flight_count = 0;
3749                                         }
3750                                         tp1->whoTo->net_ack += tp1->send_size;
3751                                         if (tp1->snd_count < 2) {
3752                                                 /* True non-retransmited chunk */
3753                                                 tp1->whoTo->net_ack2 +=
3754                                                         tp1->send_size;
3755                                                 /* update RTO too? */
3756                                                 if (tp1->do_rtt) {
3757                                                         tp1->whoTo->RTO =
3758                                                                 sctp_calculate_rto(stcb,
3759                                                                                    asoc, tp1->whoTo,
3760                                                                                    &tp1->sent_rcv_time);
3761                                                         tp1->whoTo->rto_pending = 0;
3762                                                         tp1->do_rtt = 0;
3763                                                 }
3764                                         }
3765                                 }
3766                                 if (tp1->sent == SCTP_DATAGRAM_RESEND) {
3767 #ifdef SCTP_DEBUG
3768                                         if (sctp_debug_on & SCTP_DEBUG_INDATA3) {
3769                                                 printf("Hmm. one that is in RESEND that is now ACKED\n");
3770                                         }
3771 #endif
3772                                         asoc->sent_queue_retran_cnt--;
3773 #ifdef SCTP_AUDITING_ENABLED
3774                                         sctp_audit_log(0xB3,
3775                                                        (asoc->sent_queue_retran_cnt & 0x000000ff));
3776 #endif
3777                                         if (asoc->sent_queue_retran_cnt < 0) {
3778                                                 printf("huh4 retran went negative?\n");
3779 #ifdef SCTP_AUDITING_ENABLED
3780                                                 sctp_auditing(31, inp, tcb,
3781                                                               NULL);
3782 #else
3783                                                 asoc->sent_queue_retran_cnt = 0;
3784 #endif
3785                                         }
3786
3787                                 }
3788                                 tp1->sent = SCTP_DATAGRAM_ACKED;
3789                         }
3790                 } else {
3791                         break;
3792                 }
3793                 tp1 = TAILQ_NEXT(tp1, sctp_next);
3794         }
3795         /*******************************************/
3796         /* cancel ALL T3-send timer if accum moved */
3797         /*******************************************/
3798         if (accum_moved) {
3799                 TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
3800                         sctp_timer_stop(SCTP_TIMER_TYPE_SEND, stcb->sctp_ep,
3801                                         stcb, net);
3802                 }
3803         }
3804         biggest_tsn_newly_acked = biggest_tsn_acked = last_tsn;
3805         /* always set this up to cum-ack */
3806         asoc->this_sack_highest_gap = last_tsn;
3807
3808         if (((num_seg * sizeof (sizeof(struct sctp_gap_ack_block))) + sizeof(struct sctp_sack_chunk)) > sack_length) {
3809                 /* skip corrupt segments */
3810                 strike_enabled = 0;
3811                 goto skip_segments;
3812         }
3813
3814         if (num_seg > 0) {
3815                 if (asoc->primary_destination->dest_state &
3816                     SCTP_ADDR_SWITCH_PRIMARY) {
3817                         /* clear the nets CACC flags */
3818                         TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
3819                                 net->cacc_saw_newack = 0;
3820                         }
3821                 }
3822                 /*
3823                  * thisSackHighestGap will increase while handling NEW segments
3824                  */
3825
3826                 sctp_handle_segments(stcb, asoc, ch, last_tsn,
3827                     &biggest_tsn_acked, &biggest_tsn_newly_acked,
3828                     num_seg, &ecn_seg_sums);
3829
3830                 if (sctp_strict_sacks) {
3831                         /* validate the biggest_tsn_acked in the gap acks
3832                          * if strict adherence is wanted.
3833                          */
3834                         if ((biggest_tsn_acked == send_s) ||
3835                             (compare_with_wrap(biggest_tsn_acked, send_s, MAX_TSN))) {
3836                                 /*
3837                                  * peer is either confused or we are under
3838                                  * attack. We must abort.
3839                                  */
3840                                 goto hopeless_peer;
3841                         }
3842                 }
3843
3844                 if (asoc->primary_destination->dest_state &
3845                     SCTP_ADDR_SWITCH_PRIMARY) {
3846                         /* clear the nets CACC flags */
3847                         TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
3848                                 if (net->cacc_saw_newack) {
3849                                         cnt_of_cacc++;
3850                                 }
3851                         }
3852                 }
3853
3854         }
3855
3856         if (cnt_of_cacc < 2) {
3857                 strike_enabled = 1;
3858         } else {
3859                 strike_enabled = 0;
3860         }
3861  skip_segments:
3862         /********************************************/
3863         /* drop the acked chunks from the sendqueue */
3864         /********************************************/
3865         asoc->last_acked_seq = cum_ack;
3866         if (asoc->primary_destination->dest_state & SCTP_ADDR_SWITCH_PRIMARY) {
3867                 if ((cum_ack == asoc->primary_destination->next_tsn_at_change) ||
3868                     (compare_with_wrap(cum_ack,
3869                                        asoc->primary_destination->next_tsn_at_change, MAX_TSN))) {
3870                         struct sctp_nets *lnet;
3871                         /* Turn off the switch flag for ALL addresses */
3872                         TAILQ_FOREACH(lnet, &asoc->nets, sctp_next) {
3873                                 asoc->primary_destination->dest_state &=
3874                                         ~(SCTP_ADDR_SWITCH_PRIMARY|SCTP_ADDR_DOUBLE_SWITCH);
3875                         }
3876                 }
3877         }
3878         /* Drag along the t3 timeout point so we don't have a problem at wrap */
3879         if (marking_allowed) {
3880                 asoc->t3timeout_highest_marked = cum_ack;
3881         }
3882         tp1 = TAILQ_FIRST(&asoc->sent_queue);
3883         do {
3884                 if (compare_with_wrap(tp1->rec.data.TSN_seq, cum_ack,
3885                                       MAX_TSN)) {
3886                         break;
3887                 }
3888                 if (tp1->sent == SCTP_DATAGRAM_UNSENT) {
3889                         /* no more sent on list */
3890                         break;
3891                 }
3892                 tp2 = TAILQ_NEXT(tp1, sctp_next);
3893                 TAILQ_REMOVE(&asoc->sent_queue, tp1, sctp_next);
3894                 if (tp1->data) {
3895                         sctp_free_bufspace(stcb, asoc, tp1);
3896 #ifdef SCTP_DEBUG
3897                         if (sctp_debug_on & SCTP_DEBUG_OUTPUT2) {
3898                                 printf("--total out:%lu total_mbuf_out:%lu\n",
3899                                        (u_long)asoc->total_output_queue_size,
3900                                        (u_long)asoc->total_output_mbuf_queue_size);
3901                         }
3902 #endif
3903
3904                         sctp_m_freem(tp1->data);
3905                         if (tp1->flags & SCTP_PR_SCTP_BUFFER) {
3906                                 asoc->sent_queue_cnt_removeable--;
3907                         }
3908
3909                 }
3910                 tp1->data = NULL;
3911                 asoc->sent_queue_cnt--;
3912                 sctp_free_remote_addr(tp1->whoTo);
3913                 sctppcbinfo.ipi_count_chunk--;
3914                 asoc->chunks_on_out_queue--;
3915
3916                 if ((int)sctppcbinfo.ipi_count_chunk < 0) {
3917                         panic("Chunk count is going negative");
3918                 }
3919                 SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, tp1);
3920                 sctppcbinfo.ipi_gencnt_chunk++;
3921                 sctp_sowwakeup(stcb->sctp_ep, stcb->sctp_socket);
3922                 tp1 = tp2;
3923         } while (tp1 != NULL);
3924
3925
3926         if (asoc->fast_retran_loss_recovery && accum_moved) {
3927                 if (compare_with_wrap(asoc->last_acked_seq,
3928                                       asoc->fast_recovery_tsn, MAX_TSN) ||
3929                     asoc->last_acked_seq == asoc->fast_recovery_tsn) {
3930                         /* Setup so we will exit RFC2582 fast recovery */
3931                         will_exit_fast_recovery = 1;
3932                 }
3933         }
3934
3935         /* Check for revoked fragments if we hand
3936          * fragments in a previous segment. If we
3937          * had no previous fragments we cannot have
3938          * a revoke issue.
3939          */
3940         if (asoc->saw_sack_with_frags)
3941                 sctp_check_for_revoked(asoc, cum_ack, biggest_tsn_acked);
3942
3943         if (num_seg)
3944                 asoc->saw_sack_with_frags = 1;
3945         else
3946                 asoc->saw_sack_with_frags = 0;
3947
3948         /******************************/
3949         /* update cwnd                */
3950         /******************************/
3951         TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
3952                 /* if nothing was acked on this destination skip it */
3953                 if (net->net_ack == 0)
3954                         continue;
3955
3956                 if (net->net_ack2 > 0) {
3957                         /*
3958                          * Karn's rule applies to clearing error count,
3959                          * this is optional.
3960                          */
3961                         net->error_count = 0;
3962                         if ((net->dest_state&SCTP_ADDR_NOT_REACHABLE) ==
3963                             SCTP_ADDR_NOT_REACHABLE) {
3964                                 /* addr came good */
3965                                 net->dest_state &= ~SCTP_ADDR_NOT_REACHABLE;
3966                                 net->dest_state |= SCTP_ADDR_REACHABLE;
3967                                 sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_UP, stcb,
3968                                                 SCTP_RECEIVED_SACK, (void *)net);
3969                                 /* now was it the primary? if so restore */
3970                                 if (net->dest_state & SCTP_ADDR_WAS_PRIMARY) {
3971                                         sctp_set_primary_addr(stcb, (struct sockaddr *)NULL, net);
3972                                 }
3973                         }
3974                 }
3975
3976                 if (asoc->fast_retran_loss_recovery &&
3977                     will_exit_fast_recovery == 0) {
3978                         /* If we are in loss recovery we skip any cwnd update */
3979                         sctp_pegs[SCTP_CWND_SKIP]++;
3980                         goto skip_cwnd_update;
3981                 }
3982                 if (accum_moved) {
3983                         /* If the cumulative ack moved we can proceed */
3984                         if (net->cwnd <= net->ssthresh) {
3985                                 /* We are in slow start */
3986                                 if (net->flight_size + net->net_ack >=
3987                                     net->cwnd ) {
3988 #ifdef SCTP_HIGH_SPEED
3989                                         sctp_hs_cwnd_increase(net);
3990 #else
3991                                         if (net->net_ack > net->mtu) {
3992                                                 net->cwnd += net->mtu;
3993 #ifdef SCTP_CWND_LOGGING
3994                                                 sctp_log_cwnd(net, net->mtu,
3995                                                               SCTP_CWND_LOG_FROM_SS);
3996 #endif
3997
3998                                         } else {
3999                                                 net->cwnd += net->net_ack;
4000 #ifdef SCTP_CWND_LOGGING
4001                                                 sctp_log_cwnd(net, net->net_ack,
4002                                                               SCTP_CWND_LOG_FROM_SS);
4003 #endif
4004
4005                                         }
4006 #endif
4007                                         sctp_pegs[SCTP_CWND_SS]++;
4008                                 } else {
4009                                         unsigned int dif;
4010                                         sctp_pegs[SCTP_CWND_NOUSE_SS]++;
4011                                         dif = net->cwnd - (net->flight_size +
4012                                                            net->net_ack);
4013 #ifdef SCTP_CWND_LOGGING
4014 /*                                      sctp_log_cwnd(net, net->net_ack,
4015                                         SCTP_CWND_LOG_NOADV_SS);*/
4016 #endif
4017                                         if (dif > sctp_pegs[SCTP_CWND_DIFF_SA]) {
4018                                                 sctp_pegs[SCTP_CWND_DIFF_SA] =
4019                                                         dif;
4020                                                 sctp_pegs[SCTP_OQS_AT_SS] =
4021                                                         asoc->total_output_queue_size;
4022                                                 sctp_pegs[SCTP_SQQ_AT_SS] =
4023                                                         asoc->sent_queue_cnt;
4024                                                 sctp_pegs[SCTP_SQC_AT_SS] =
4025                                                         asoc->send_queue_cnt;
4026                                         }
4027                                 }
4028                         } else {
4029                                 /* We are in congestion avoidance */
4030                                 if (net->flight_size + net->net_ack >=
4031                                     net->cwnd) {
4032                                         /*
4033                                          * add to pba only if we had a cwnd's
4034                                          * worth (or so) in flight OR the
4035                                          * burst limit was applied.
4036                                          */
4037                                         net->partial_bytes_acked +=
4038                                                 net->net_ack;
4039
4040                                         /*
4041                                          * Do we need to increase
4042                                          * (if pba is > cwnd)?
4043                                          */
4044                                         if (net->partial_bytes_acked >=
4045                                             net->cwnd) {
4046                                                 if (net->cwnd <
4047                                                     net->partial_bytes_acked) {
4048                                                         net->partial_bytes_acked -=
4049                                                                 net->cwnd;
4050                                                 } else {
4051                                                         net->partial_bytes_acked =
4052                                                                 0;
4053                                                 }
4054                                                 net->cwnd += net->mtu;
4055 #ifdef SCTP_CWND_LOGGING
4056                                                 sctp_log_cwnd(net, net->mtu,
4057                                                               SCTP_CWND_LOG_FROM_CA);
4058 #endif
4059                                                 sctp_pegs[SCTP_CWND_CA]++;
4060                                         }
4061                                 } else {
4062                                         unsigned int dif;
4063                                         sctp_pegs[SCTP_CWND_NOUSE_CA]++;
4064 #ifdef SCTP_CWND_LOGGING
4065 /*                                      sctp_log_cwnd(net, net->net_ack,
4066                                         SCTP_CWND_LOG_NOADV_CA);
4067 */
4068 #endif
4069                                         dif = net->cwnd - (net->flight_size +
4070                                                            net->net_ack);
4071                                         if (dif > sctp_pegs[SCTP_CWND_DIFF_CA]) {
4072                                                 sctp_pegs[SCTP_CWND_DIFF_CA] =
4073                                                         dif;
4074                                                 sctp_pegs[SCTP_OQS_AT_CA] =
4075                                                         asoc->total_output_queue_size;
4076                                                 sctp_pegs[SCTP_SQQ_AT_CA] =
4077                                                         asoc->sent_queue_cnt;
4078                                                 sctp_pegs[SCTP_SQC_AT_CA] =
4079                                                         asoc->send_queue_cnt;
4080
4081                                         }
4082
4083                                 }
4084                         }
4085                 } else {
4086                         sctp_pegs[SCTP_CWND_NOCUM]++;
4087                 }
4088         skip_cwnd_update:
4089                 /*
4090                  * NOW, according to Karn's rule do we need to restore the
4091                  * RTO timer back? Check our net_ack2. If not set then we
4092                  * have a ambiguity.. i.e. all data ack'd was sent to more
4093                  * than one place.
4094                  */
4095
4096                 if (net->net_ack2) {
4097                         /* restore any doubled timers */
4098                         net->RTO = ((net->lastsa >> 2) + net->lastsv) >> 1;
4099                         if (net->RTO < stcb->asoc.minrto) {
4100                                 net->RTO = stcb->asoc.minrto;
4101                         }
4102                         if (net->RTO > stcb->asoc.maxrto) {
4103                                 net->RTO = stcb->asoc.maxrto;
4104                         }
4105                 }
4106                 if (net->cwnd > sctp_pegs[SCTP_MAX_CWND]) {
4107                         sctp_pegs[SCTP_MAX_CWND] = net->cwnd;
4108                 }
4109         }
4110         /**********************************/
4111         /* Now what about shutdown issues */
4112         /**********************************/
4113         some_on_streamwheel = 0;
4114         if (!TAILQ_EMPTY(&asoc->out_wheel)) {
4115                 /* Check to see if some data queued */
4116                 struct sctp_stream_out *outs;
4117                 TAILQ_FOREACH(outs, &asoc->out_wheel, next_spoke) {
4118                         if (!TAILQ_EMPTY(&outs->outqueue)) {
4119                                 some_on_streamwheel = 1;
4120                                 break;
4121                         }
4122                 }
4123         }
4124         if (TAILQ_EMPTY(&asoc->send_queue) && TAILQ_EMPTY(&asoc->sent_queue) &&
4125             some_on_streamwheel == 0) {
4126                 /* nothing left on sendqueue.. consider done */
4127                 /* stop all timers */
4128 #ifdef SCTP_LOG_RWND
4129                 sctp_log_rwnd_set(SCTP_SET_PEER_RWND_VIA_SACK,
4130                                   asoc->peers_rwnd, 0, 0,  a_rwnd);
4131 #endif
4132                 asoc->peers_rwnd = a_rwnd;
4133                 if (asoc->peers_rwnd < stcb->sctp_ep->sctp_ep.sctp_sws_sender) {
4134                         /* SWS sender side engages */
4135                         asoc->peers_rwnd = 0;
4136                 }
4137                 /* stop any timers */
4138                 TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
4139                         sctp_timer_stop(SCTP_TIMER_TYPE_SEND, stcb->sctp_ep,
4140                                         stcb, net);
4141                         net->flight_size = 0;
4142                         net->partial_bytes_acked = 0;
4143                 }
4144                 asoc->total_flight = 0;
4145                 asoc->total_flight_count = 0;
4146                 /* clean up */
4147                 if (asoc->state & SCTP_STATE_SHUTDOWN_PENDING) {
4148                         asoc->state = SCTP_STATE_SHUTDOWN_SENT;
4149 #ifdef SCTP_DEBUG
4150                         if (sctp_debug_on & SCTP_DEBUG_OUTPUT4) {
4151                                 printf("%s:%d sends a shutdown\n",
4152                                        __FILE__,
4153                                        __LINE__
4154                                        );
4155                         }
4156 #endif
4157                         sctp_send_shutdown(stcb,
4158                                            stcb->asoc.primary_destination);
4159                         sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN,
4160                                          stcb->sctp_ep, stcb, asoc->primary_destination);
4161                         sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD,
4162                                          stcb->sctp_ep, stcb, asoc->primary_destination);
4163                 } else if (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) {
4164                         asoc->state = SCTP_STATE_SHUTDOWN_ACK_SENT;
4165
4166                         sctp_send_shutdown_ack(stcb,
4167                                                stcb->asoc.primary_destination);
4168
4169                         sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNACK,
4170                                          stcb->sctp_ep, stcb, asoc->primary_destination);
4171                 }
4172                 return;
4173         }
4174         /*
4175          * Now here we are going to recycle net_ack for a different
4176          * use... HEADS UP.
4177          */
4178         TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
4179                 net->net_ack = 0;
4180         }
4181         if ((num_seg > 0) && marking_allowed) {
4182                 sctp_strike_gap_ack_chunks(stcb, asoc, biggest_tsn_acked,
4183                                            strike_enabled, biggest_tsn_newly_acked, accum_moved);
4184         }
4185
4186         /*********************************************/
4187         /* Here we perform PR-SCTP procedures        */
4188         /* (section 4.2)                             */
4189         /*********************************************/
4190         /* C1. update advancedPeerAckPoint */
4191         if (compare_with_wrap(cum_ack, asoc->advanced_peer_ack_point, MAX_TSN)) {
4192                 asoc->advanced_peer_ack_point = cum_ack;
4193         }
4194         /* C2. try to further move advancedPeerAckPoint ahead */
4195         if (asoc->peer_supports_prsctp) {
4196                 struct sctp_tmit_chunk *lchk;
4197                 lchk = sctp_try_advance_peer_ack_point(stcb, asoc);
4198                 /* C3. See if we need to send a Fwd-TSN */
4199                 if (compare_with_wrap(asoc->advanced_peer_ack_point, cum_ack,
4200                                       MAX_TSN)) {
4201                         /*
4202                          * ISSUE with ECN, see FWD-TSN processing for notes
4203                          * on issues that will occur when the ECN NONCE stuff
4204                          * is put into SCTP for cross checking.
4205                          */
4206                         send_forward_tsn(stcb, asoc);
4207
4208                         /* ECN Nonce: Disable Nonce Sum check when FWD TSN is sent and store resync tsn*/
4209                         asoc->nonce_sum_check = 0;
4210                         asoc->nonce_resync_tsn = asoc->advanced_peer_ack_point;
4211                         if (lchk) {
4212                                 /* Assure a timer is up */
4213                                 sctp_timer_start(SCTP_TIMER_TYPE_SEND,
4214                                                  stcb->sctp_ep, stcb, lchk->whoTo);
4215                         }
4216                 }
4217         }
4218         TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
4219                 if (asoc->fast_retran_loss_recovery == 0) {
4220                         /* out of a RFC2582 Fast recovery window? */
4221                         if (net->net_ack > 0) {
4222                                 /*
4223                                  * per section 7.2.3, are there
4224                                  * any destinations that had a fast
4225                                  * retransmit to them. If so what we
4226                                  * need to do is adjust ssthresh and
4227                                  * cwnd.
4228                                  */
4229                                 struct sctp_tmit_chunk *lchk;
4230 #ifdef  SCTP_HIGH_SPEED
4231                                 sctp_hs_cwnd_decrease(net);
4232 #else
4233 #ifdef SCTP_CWND_LOGGING
4234                                 int old_cwnd = net->cwnd;
4235 #endif
4236                                 net->ssthresh = net->cwnd / 2;
4237                                 if (net->ssthresh < (net->mtu*2)) {
4238                                         net->ssthresh = 2 * net->mtu;
4239                                 }
4240                                 net->cwnd = net->ssthresh;
4241 #ifdef SCTP_CWND_LOGGING
4242                                 sctp_log_cwnd(net, (net->cwnd-old_cwnd),
4243                                               SCTP_CWND_LOG_FROM_FR);
4244 #endif
4245 #endif
4246
4247                                 lchk = TAILQ_FIRST(&asoc->send_queue);
4248
4249                                 net->partial_bytes_acked = 0;
4250                                 /* Turn on fast recovery window */
4251                                 asoc->fast_retran_loss_recovery = 1;
4252                                 if (lchk == NULL) {
4253                                         /* Mark end of the window */
4254                                         asoc->fast_recovery_tsn = asoc->sending_seq - 1;
4255                                 } else {
4256                                         asoc->fast_recovery_tsn = lchk->rec.data.TSN_seq - 1;
4257                                 }
4258
4259
4260                                 /* Disable Nonce Sum Checking and store the resync tsn*/
4261                                 asoc->nonce_sum_check = 0;
4262                                 asoc->nonce_resync_tsn = asoc->fast_recovery_tsn + 1;
4263
4264                                 sctp_timer_stop(SCTP_TIMER_TYPE_SEND,
4265                                                 stcb->sctp_ep, stcb, net);
4266                                 sctp_timer_start(SCTP_TIMER_TYPE_SEND,
4267                                                  stcb->sctp_ep, stcb, net);
4268                         }
4269                 } else if (net->net_ack > 0) {
4270                         /*
4271                          * Mark a peg that we WOULD have done a cwnd reduction
4272                          * but RFC2582 prevented this action.
4273                          */
4274                         sctp_pegs[SCTP_FR_INAWINDOW]++;
4275                 }
4276         }
4277
4278
4279         /******************************************************************
4280          *  Here we do the stuff with ECN Nonce checking.
4281          *  We basically check to see if the nonce sum flag was incorrect
4282          *  or if resynchronization needs to be done. Also if we catch a
4283          *  misbehaving receiver we give him the kick.
4284          ******************************************************************/
4285
4286         if (asoc->ecn_nonce_allowed) {
4287                 if (asoc->nonce_sum_check) {
4288                         if (nonce_sum_flag != ((asoc->nonce_sum_expect_base + ecn_seg_sums) & SCTP_SACK_NONCE_SUM)) {
4289                                 if (asoc->nonce_wait_for_ecne == 0) {
4290                                         struct sctp_tmit_chunk *lchk;
4291                                         lchk = TAILQ_FIRST(&asoc->send_queue);
4292                                         asoc->nonce_wait_for_ecne = 1;
4293                                         if (lchk) {
4294                                                 asoc->nonce_wait_tsn = lchk->rec.data.TSN_seq;
4295                                         } else {
4296                                                 asoc->nonce_wait_tsn = asoc->sending_seq;
4297                                         }
4298                                 } else {
4299                                         if (compare_with_wrap(asoc->last_acked_seq, asoc->nonce_wait_tsn, MAX_TSN) ||
4300                                            (asoc->last_acked_seq == asoc->nonce_wait_tsn)) {
4301                                                 /* Misbehaving peer. We need to react to this guy */
4302                                                 printf("Mis-behaving peer detected\n");
4303                                                 asoc->ecn_allowed = 0;
4304                                                 asoc->ecn_nonce_allowed = 0;
4305                                         }
4306                                 }
4307                         }
4308                 } else {
4309                         /* See if Resynchronization Possible */
4310                         if (compare_with_wrap(asoc->last_acked_seq, asoc->nonce_resync_tsn, MAX_TSN)) {
4311                                 asoc->nonce_sum_check = 1;
4312                                 /* now we must calculate what the base
4313                                  * is. We do this based on two things, we know
4314                                  * the total's for all the segments gap-acked
4315                                  * in the SACK, its stored in ecn_seg_sums.
4316                                  * We also know the SACK's nonce sum, its
4317                                  * in nonce_sum_flag. So we can build a truth
4318                                  * table to back-calculate the new value of asoc->nonce_sum_expect_base:
4319                                  *
4320                                  *   SACK-flag-Value         Seg-Sums              Base
4321                                  *         0                    0                   0
4322                                  *         1                    0                   1
4323                                  *         0                    1                   1
4324                                  *         1                    1                   0
4325                                  */
4326                                 asoc->nonce_sum_expect_base = (ecn_seg_sums ^ nonce_sum_flag) & SCTP_SACK_NONCE_SUM;
4327                         }
4328                 }
4329         }
4330         /* Now are we exiting loss recovery ? */
4331         if (will_exit_fast_recovery) {
4332                 /* Ok, we must exit fast recovery */
4333                 asoc->fast_retran_loss_recovery = 0;
4334         }
4335         if ((asoc->sat_t3_loss_recovery) &&
4336             ((compare_with_wrap(asoc->last_acked_seq, asoc->sat_t3_recovery_tsn,
4337                                 MAX_TSN) ||
4338               (asoc->last_acked_seq == asoc->sat_t3_recovery_tsn)))) {
4339                 /* end satellite t3 loss recovery */
4340                 asoc->sat_t3_loss_recovery = 0;
4341         }
4342         /* Adjust and set the new rwnd value */
4343 #ifdef SCTP_LOG_RWND
4344         sctp_log_rwnd_set(SCTP_SET_PEER_RWND_VIA_SACK,
4345                           asoc->peers_rwnd,  asoc->total_flight, (asoc->sent_queue_cnt * sctp_peer_chunk_oh), a_rwnd);
4346 #endif
4347
4348         asoc->peers_rwnd = sctp_sbspace_sub(a_rwnd,
4349                                             (u_int32_t)(asoc->total_flight + (asoc->sent_queue_cnt * sctp_peer_chunk_oh)));
4350         if (asoc->peers_rwnd < stcb->sctp_ep->sctp_ep.sctp_sws_sender) {
4351                 /* SWS sender side engages */
4352                 asoc->peers_rwnd = 0;
4353         }
4354         /*
4355          * Now we must setup so we have a timer up for anyone with
4356          * outstanding data.
4357          */
4358         TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
4359                 struct sctp_tmit_chunk *chk;
4360                 TAILQ_FOREACH(chk, &asoc->sent_queue, sctp_next) {
4361                         if (chk->whoTo == net &&
4362                             (chk->sent < SCTP_DATAGRAM_ACKED ||
4363                              chk->sent == SCTP_FORWARD_TSN_SKIP)) {
4364                                 /*
4365                                  * Not ack'ed and still outstanding to this
4366                                  * destination or marked and must be
4367                                  * sacked after fwd-tsn sent.
4368                                  */
4369                                 sctp_timer_start(SCTP_TIMER_TYPE_SEND,
4370                                                  stcb->sctp_ep, stcb, net);
4371                                 break;
4372                         }
4373                 }
4374         }
4375 }
4376
4377 void
4378 sctp_update_acked(struct sctp_tcb *stcb, struct sctp_shutdown_chunk *cp,
4379     struct sctp_nets *netp, int *abort_flag)
4380 {
4381         /* Mutate a shutdown into a SACK */
4382         struct sctp_sack_chunk sack;
4383
4384         /* Copy cum-ack */
4385         sack.sack.cum_tsn_ack = cp->cumulative_tsn_ack;
4386         /* Arrange so a_rwnd does NOT change */
4387         sack.ch.chunk_type = SCTP_SELECTIVE_ACK;
4388         sack.ch.chunk_flags = 0;
4389         sack.ch.chunk_length = ntohs(sizeof(struct sctp_sack_chunk));
4390         sack.sack.a_rwnd =
4391             htonl(stcb->asoc.peers_rwnd + stcb->asoc.total_flight);
4392         /*
4393          * no gaps in this one. This may cause a temporal view to reneging,
4394          * but hopefully the second chunk is a true SACK in the packet and
4395          * will correct this view. One will come soon after no matter what
4396          * to fix this.
4397          */
4398         sack.sack.num_gap_ack_blks = 0;
4399         sack.sack.num_dup_tsns = 0;
4400         /* Now call the SACK processor */
4401         sctp_handle_sack(&sack, stcb, netp, abort_flag);
4402 }
4403
4404 static void
4405 sctp_kick_prsctp_reorder_queue(struct sctp_tcb *stcb,
4406     struct sctp_stream_in *strmin)
4407 {
4408         struct sctp_tmit_chunk *chk, *nchk;
4409         struct sctp_association *asoc;
4410         int tt;
4411
4412         asoc = &stcb->asoc;
4413         tt = strmin->last_sequence_delivered;
4414         /*
4415          * First deliver anything prior to and including the stream no that
4416          * came in
4417          */
4418         chk = TAILQ_FIRST(&strmin->inqueue);
4419         while (chk) {
4420                 nchk = TAILQ_NEXT(chk, sctp_next);
4421                 if (compare_with_wrap(tt, chk->rec.data.stream_seq, MAX_SEQ) ||
4422                     (tt == chk->rec.data.stream_seq)) {
4423                         /* this is deliverable now */
4424                         TAILQ_REMOVE(&strmin->inqueue, chk, sctp_next);
4425                         /* subtract pending on streams */
4426                         asoc->size_on_all_streams -= chk->send_size;
4427                         asoc->cnt_on_all_streams--;
4428                         /* deliver it to at least the delivery-q */
4429                         sctp_deliver_data(stcb, &stcb->asoc, chk, 0);
4430                 } else {
4431                         /* no more delivery now. */
4432                         break;
4433                 }
4434                 chk = nchk;
4435         }
4436         /*
4437          * now we must deliver things in queue the normal way  if any
4438          * are now ready.
4439          */
4440         tt = strmin->last_sequence_delivered + 1;
4441         chk = TAILQ_FIRST(&strmin->inqueue);
4442         while (chk) {
4443                 nchk = TAILQ_NEXT(chk, sctp_next);
4444                 if (tt == chk->rec.data.stream_seq) {
4445                         /* this is deliverable now */
4446                         TAILQ_REMOVE(&strmin->inqueue, chk, sctp_next);
4447                         /* subtract pending on streams */
4448                         asoc->size_on_all_streams -= chk->send_size;
4449                         asoc->cnt_on_all_streams--;
4450                         /* deliver it to at least the delivery-q */
4451                         strmin->last_sequence_delivered =
4452                             chk->rec.data.stream_seq;
4453                         sctp_deliver_data(stcb, &stcb->asoc, chk, 0);
4454                         tt = strmin->last_sequence_delivered + 1;
4455                 } else {
4456                         break;
4457                 }
4458                 chk = nchk;
4459         }
4460
4461 }
4462
4463 void
4464 sctp_handle_forward_tsn(struct sctp_tcb *stcb,
4465     struct sctp_forward_tsn_chunk *fwd, int *abort_flag)
4466 {
4467         /*
4468          * ISSUES that MUST be fixed for ECN! When we are the
4469          * sender of the forward TSN, when the SACK comes back
4470          * that acknowledges the FWD-TSN we must reset the
4471          * NONCE sum to match correctly. This will get quite
4472          * tricky since we may have sent more data interveneing and
4473          * must carefully account for what the SACK says on the
4474          * nonce and any gaps that are reported. This work
4475          * will NOT be done here, but I note it here since
4476          * it is really related to PR-SCTP and FWD-TSN's
4477          */
4478
4479         /* The pr-sctp fwd tsn */
4480         /*
4481          * here we will perform all the data receiver side steps for
4482          * processing FwdTSN, as required in by pr-sctp draft:
4483          *
4484          * Assume we get FwdTSN(x):
4485          *
4486          * 1) update local cumTSN to x
4487          * 2) try to further advance cumTSN to x + others we have
4488          * 3) examine and update re-ordering queue on pr-in-streams
4489          * 4) clean up re-assembly queue
4490          * 5) Send a sack to report where we are.
4491          */
4492         struct sctp_strseq *stseq;
4493         struct sctp_association *asoc;
4494         u_int32_t new_cum_tsn, gap, back_out_htsn;
4495         unsigned int i, cnt_gone, fwd_sz, cumack_set_flag, m_size;
4496         struct sctp_stream_in *strm;
4497         struct sctp_tmit_chunk *chk, *at;
4498
4499         cumack_set_flag = 0;
4500         asoc = &stcb->asoc;
4501         cnt_gone = 0;
4502         if ((fwd_sz = ntohs(fwd->ch.chunk_length)) < sizeof(struct sctp_forward_tsn_chunk)) {
4503 #ifdef SCTP_DEBUG
4504                 if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
4505                         printf("Bad size too small/big fwd-tsn\n");
4506                 }
4507 #endif
4508                 return;
4509         }
4510         m_size = (stcb->asoc.mapping_array_size << 3);
4511         /*************************************************************/
4512         /* 1. Here we update local cumTSN and shift the bitmap array */
4513         /*************************************************************/
4514         new_cum_tsn = ntohl(fwd->new_cumulative_tsn);
4515
4516         if (compare_with_wrap(asoc->cumulative_tsn, new_cum_tsn, MAX_TSN) ||
4517             asoc->cumulative_tsn == new_cum_tsn) {
4518                 /* Already got there ... */
4519                 return;
4520         }
4521
4522         back_out_htsn = asoc->highest_tsn_inside_map;
4523         if (compare_with_wrap(new_cum_tsn, asoc->highest_tsn_inside_map,
4524             MAX_TSN)) {
4525                 asoc->highest_tsn_inside_map = new_cum_tsn;
4526 #ifdef SCTP_MAP_LOGGING
4527                         sctp_log_map(0, 0, asoc->highest_tsn_inside_map, SCTP_MAP_SLIDE_RESULT);
4528 #endif
4529         }
4530         /*
4531          * now we know the new TSN is more advanced, let's find the
4532          * actual gap
4533          */
4534         if ((compare_with_wrap(new_cum_tsn, asoc->mapping_array_base_tsn,
4535                                MAX_TSN)) ||
4536              (new_cum_tsn == asoc->mapping_array_base_tsn)) {
4537                 gap = new_cum_tsn - asoc->mapping_array_base_tsn;
4538         } else {
4539                 /* try to prevent underflow here */
4540                 gap = new_cum_tsn + (MAX_TSN - asoc->mapping_array_base_tsn) + 1;
4541         }
4542
4543         if (gap > m_size  || gap < 0) {
4544                 asoc->highest_tsn_inside_map = back_out_htsn;
4545                 if ((long)gap > sctp_sbspace(&stcb->sctp_socket->so_rcv)) {
4546                         /*
4547                          * out of range (of single byte chunks in the rwnd I
4548                          * give out)
4549                          * too questionable. better to drop it silently
4550                          */
4551                         return;
4552                 }
4553                 if (asoc->highest_tsn_inside_map >
4554                     asoc->mapping_array_base_tsn) {
4555                         gap = asoc->highest_tsn_inside_map -
4556                             asoc->mapping_array_base_tsn;
4557                 } else {
4558                         gap = asoc->highest_tsn_inside_map +
4559                             (MAX_TSN - asoc->mapping_array_base_tsn) + 1;
4560                 }
4561                 cumack_set_flag = 1;
4562         }
4563         for (i = 0; i <= gap; i++) {
4564                 SCTP_SET_TSN_PRESENT(asoc->mapping_array, i);
4565         }
4566         /*
4567          * Now after marking all, slide thing forward but no
4568          * sack please.
4569          */
4570         sctp_sack_check(stcb, 0, 0, abort_flag);
4571         if (*abort_flag)
4572                 return;
4573
4574         if (cumack_set_flag) {
4575                 /*
4576                  * fwd-tsn went outside my gap array - not a
4577                  * common occurance. Do the same thing we
4578                  * do when a cookie-echo arrives.
4579                  */
4580                 asoc->highest_tsn_inside_map =  new_cum_tsn - 1;
4581                 asoc->mapping_array_base_tsn = new_cum_tsn;
4582                 asoc->cumulative_tsn = asoc->highest_tsn_inside_map;
4583 #ifdef SCTP_MAP_LOGGING
4584                 sctp_log_map(0, 3, asoc->highest_tsn_inside_map, SCTP_MAP_SLIDE_RESULT);
4585 #endif
4586                 asoc->last_echo_tsn = asoc->highest_tsn_inside_map;
4587         }
4588         /*************************************************************/
4589         /* 2. Clear up re-assembly queue                             */
4590         /*************************************************************/
4591
4592         /*
4593          * First service it if pd-api is up, just in case we can
4594          * progress it forward
4595          */
4596         if (asoc->fragmented_delivery_inprogress) {
4597                 sctp_service_reassembly(stcb, asoc, 0);
4598         }
4599         if (!TAILQ_EMPTY(&asoc->reasmqueue)) {
4600                 /* For each one on here see if we need to toss it */
4601                 /*
4602                  * For now large messages held on the reasmqueue that are
4603                  * complete will be tossed too. We could in theory do more
4604                  * work to spin through and stop after dumping one msg
4605                  * aka seeing the start of a new msg at the head, and call
4606                  * the delivery function... to see if it can be delivered...
4607                  * But for now we just dump everything on the queue.
4608                  */
4609                 chk = TAILQ_FIRST(&asoc->reasmqueue);
4610                 while (chk) {
4611                         at = TAILQ_NEXT(chk, sctp_next);
4612                         if (compare_with_wrap(asoc->cumulative_tsn,
4613                             chk->rec.data.TSN_seq, MAX_TSN) ||
4614                             asoc->cumulative_tsn == chk->rec.data.TSN_seq) {
4615                                 /* It needs to be tossed */
4616                                 TAILQ_REMOVE(&asoc->reasmqueue, chk, sctp_next);
4617                                 if (compare_with_wrap(chk->rec.data.TSN_seq,
4618                                     asoc->tsn_last_delivered, MAX_TSN)) {
4619                                         asoc->tsn_last_delivered =
4620                                             chk->rec.data.TSN_seq;
4621                                         asoc->str_of_pdapi =
4622                                             chk->rec.data.stream_number;
4623                                         asoc->ssn_of_pdapi =
4624                                             chk->rec.data.stream_seq;
4625                                         asoc->fragment_flags =
4626                                             chk->rec.data.rcv_flags;
4627                                 }
4628                                 asoc->size_on_reasm_queue -= chk->send_size;
4629                                 asoc->cnt_on_reasm_queue--;
4630                                 cnt_gone++;
4631
4632                                 /* Clear up any stream problem */
4633                                 if ((chk->rec.data.rcv_flags & SCTP_DATA_UNORDERED) !=
4634                                     SCTP_DATA_UNORDERED &&
4635                                     (compare_with_wrap(chk->rec.data.stream_seq,
4636                                     asoc->strmin[chk->rec.data.stream_number].last_sequence_delivered,
4637                                     MAX_SEQ))) {
4638                                         /*
4639                                          * We must dump forward this streams
4640                                          * sequence number if the chunk is not
4641                                          * unordered that is being skipped.
4642                                          * There is a chance that if the peer
4643                                          * does not include the last fragment
4644                                          * in its FWD-TSN we WILL have a problem
4645                                          * here since you would have a partial
4646                                          * chunk in queue that may not be
4647                                          * deliverable.
4648                                          * Also if a Partial delivery API as
4649                                          * started the user may get a partial
4650                                          * chunk. The next read returning a new
4651                                          * chunk... really ugly but I see no way
4652                                          * around it! Maybe a notify??
4653                                          */
4654                                         asoc->strmin[chk->rec.data.stream_number].last_sequence_delivered =
4655                                             chk->rec.data.stream_seq;
4656                                 }
4657                                 if (chk->data) {
4658                                         sctp_m_freem(chk->data);
4659                                         chk->data = NULL;
4660                                 }
4661                                 sctp_free_remote_addr(chk->whoTo);
4662                                 SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
4663                                 sctppcbinfo.ipi_count_chunk--;
4664                                 if ((int)sctppcbinfo.ipi_count_chunk < 0) {
4665                                         panic("Chunk count is negative");
4666                                 }
4667                                 sctppcbinfo.ipi_gencnt_chunk++;
4668                         } else {
4669                                 /*
4670                                  * Ok we have gone beyond the end of the
4671                                  * fwd-tsn's mark. Some checks...
4672                                  */
4673                                 if ((asoc->fragmented_delivery_inprogress) &&
4674                                     (chk->rec.data.rcv_flags & SCTP_DATA_FIRST_FRAG)) {
4675                                         /* Special case PD-API is up and what we fwd-tsn'
4676                                          * over includes one that had the LAST_FRAG. We
4677                                          * no longer need to do the PD-API.
4678                                          */
4679                                         asoc->fragmented_delivery_inprogress = 0;
4680                                         sctp_ulp_notify(SCTP_NOTIFY_PARTIAL_DELVIERY_INDICATION,
4681                                             stcb, SCTP_PARTIAL_DELIVERY_ABORTED, (void *)NULL);
4682
4683                                 }
4684                                 break;
4685                         }
4686                         chk = at;
4687                 }
4688         }
4689         if (asoc->fragmented_delivery_inprogress) {
4690                 /*
4691                  * Ok we removed cnt_gone chunks in the PD-API queue that
4692                  * were being delivered. So now we must turn off the
4693                  * flag.
4694                  */
4695                 sctp_ulp_notify(SCTP_NOTIFY_PARTIAL_DELVIERY_INDICATION,
4696                     stcb, SCTP_PARTIAL_DELIVERY_ABORTED, (void *)NULL);
4697                 asoc->fragmented_delivery_inprogress = 0;
4698         }
4699         /*************************************************************/
4700         /* 3. Update the PR-stream re-ordering queues                */
4701         /*************************************************************/
4702         stseq = (struct sctp_strseq *)((caddr_t)fwd + sizeof(*fwd));
4703         fwd_sz -= sizeof(*fwd);
4704         {
4705                 /* New method. */
4706                 int num_str, i;
4707                 num_str = fwd_sz/sizeof(struct sctp_strseq);
4708 #ifdef SCTP_DEBUG
4709                 if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
4710                         printf("Using NEW method, %d strseq's reported in FWD-TSN\n",
4711                             num_str);
4712                 }
4713 #endif
4714                 for (i = 0; i < num_str; i++) {
4715                         u_int16_t st;
4716                         unsigned char *xx;
4717                         /* Convert */
4718                         xx = (unsigned char *)&stseq[i];
4719                         st = ntohs(stseq[i].stream);
4720                         stseq[i].stream = st;
4721                         st = ntohs(stseq[i].sequence);
4722                         stseq[i].sequence = st;
4723                         /* now process */
4724                         if (stseq[i].stream > asoc->streamincnt) {
4725 #ifdef SCTP_DEBUG
4726                                 if (sctp_debug_on & SCTP_DEBUG_INDATA1) {
4727                                         printf("Bogus stream number %d "
4728                                             "streamincnt is %d\n",
4729                                             stseq[i].stream, asoc->streamincnt);
4730                                 }
4731 #endif
4732                                 /*
4733                                  * It is arguable if we should continue. Since
4734                                  * the peer sent bogus stream info we may be in
4735                                  * deep trouble..
4736                                  * a return may be a better choice?
4737                                  */
4738                                 continue;
4739                         }
4740                         strm = &asoc->strmin[stseq[i].stream];
4741                         if (compare_with_wrap(stseq[i].sequence,
4742                             strm->last_sequence_delivered, MAX_SEQ)) {
4743                                 /* Update the sequence number */
4744                                 strm->last_sequence_delivered =
4745                                     stseq[i].sequence;
4746                         }
4747                         /* now kick the stream the new way */
4748                         sctp_kick_prsctp_reorder_queue(stcb, strm);
4749                 }
4750         }
4751 }