]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/netinet/sctp_output.c
MFC r244026:
[FreeBSD/stable/9.git] / sys / netinet / sctp_output.c
1 /*-
2  * Copyright (c) 2001-2008, by Cisco Systems, Inc. All rights reserved.
3  * Copyright (c) 2008-2012, by Randall Stewart. All rights reserved.
4  * Copyright (c) 2008-2012, by Michael Tuexen. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * a) Redistributions of source code must retain the above copyright notice,
10  *    this list of conditions and the following disclaimer.
11  *
12  * b) Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in
14  *    the documentation and/or other materials provided with the distribution.
15  *
16  * c) Neither the name of Cisco Systems, Inc. nor the names of its
17  *    contributors may be used to endorse or promote products derived
18  *    from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
22  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
30  * THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35
36 #include <netinet/sctp_os.h>
37 #include <sys/proc.h>
38 #include <netinet/sctp_var.h>
39 #include <netinet/sctp_sysctl.h>
40 #include <netinet/sctp_header.h>
41 #include <netinet/sctp_pcb.h>
42 #include <netinet/sctputil.h>
43 #include <netinet/sctp_output.h>
44 #include <netinet/sctp_uio.h>
45 #include <netinet/sctputil.h>
46 #include <netinet/sctp_auth.h>
47 #include <netinet/sctp_timer.h>
48 #include <netinet/sctp_asconf.h>
49 #include <netinet/sctp_indata.h>
50 #include <netinet/sctp_bsd_addr.h>
51 #include <netinet/sctp_input.h>
52 #include <netinet/sctp_crc32.h>
53 #include <netinet/udp.h>
54 #include <netinet/udp_var.h>
55 #include <machine/in_cksum.h>
56
57
58
59 #define SCTP_MAX_GAPS_INARRAY 4
60 struct sack_track {
61         uint8_t right_edge;     /* mergable on the right edge */
62         uint8_t left_edge;      /* mergable on the left edge */
63         uint8_t num_entries;
64         uint8_t spare;
65         struct sctp_gap_ack_block gaps[SCTP_MAX_GAPS_INARRAY];
66 };
67
68 struct sack_track sack_array[256] = {
69         {0, 0, 0, 0,            /* 0x00 */
70                 {{0, 0},
71                 {0, 0},
72                 {0, 0},
73                 {0, 0}
74                 }
75         },
76         {1, 0, 1, 0,            /* 0x01 */
77                 {{0, 0},
78                 {0, 0},
79                 {0, 0},
80                 {0, 0}
81                 }
82         },
83         {0, 0, 1, 0,            /* 0x02 */
84                 {{1, 1},
85                 {0, 0},
86                 {0, 0},
87                 {0, 0}
88                 }
89         },
90         {1, 0, 1, 0,            /* 0x03 */
91                 {{0, 1},
92                 {0, 0},
93                 {0, 0},
94                 {0, 0}
95                 }
96         },
97         {0, 0, 1, 0,            /* 0x04 */
98                 {{2, 2},
99                 {0, 0},
100                 {0, 0},
101                 {0, 0}
102                 }
103         },
104         {1, 0, 2, 0,            /* 0x05 */
105                 {{0, 0},
106                 {2, 2},
107                 {0, 0},
108                 {0, 0}
109                 }
110         },
111         {0, 0, 1, 0,            /* 0x06 */
112                 {{1, 2},
113                 {0, 0},
114                 {0, 0},
115                 {0, 0}
116                 }
117         },
118         {1, 0, 1, 0,            /* 0x07 */
119                 {{0, 2},
120                 {0, 0},
121                 {0, 0},
122                 {0, 0}
123                 }
124         },
125         {0, 0, 1, 0,            /* 0x08 */
126                 {{3, 3},
127                 {0, 0},
128                 {0, 0},
129                 {0, 0}
130                 }
131         },
132         {1, 0, 2, 0,            /* 0x09 */
133                 {{0, 0},
134                 {3, 3},
135                 {0, 0},
136                 {0, 0}
137                 }
138         },
139         {0, 0, 2, 0,            /* 0x0a */
140                 {{1, 1},
141                 {3, 3},
142                 {0, 0},
143                 {0, 0}
144                 }
145         },
146         {1, 0, 2, 0,            /* 0x0b */
147                 {{0, 1},
148                 {3, 3},
149                 {0, 0},
150                 {0, 0}
151                 }
152         },
153         {0, 0, 1, 0,            /* 0x0c */
154                 {{2, 3},
155                 {0, 0},
156                 {0, 0},
157                 {0, 0}
158                 }
159         },
160         {1, 0, 2, 0,            /* 0x0d */
161                 {{0, 0},
162                 {2, 3},
163                 {0, 0},
164                 {0, 0}
165                 }
166         },
167         {0, 0, 1, 0,            /* 0x0e */
168                 {{1, 3},
169                 {0, 0},
170                 {0, 0},
171                 {0, 0}
172                 }
173         },
174         {1, 0, 1, 0,            /* 0x0f */
175                 {{0, 3},
176                 {0, 0},
177                 {0, 0},
178                 {0, 0}
179                 }
180         },
181         {0, 0, 1, 0,            /* 0x10 */
182                 {{4, 4},
183                 {0, 0},
184                 {0, 0},
185                 {0, 0}
186                 }
187         },
188         {1, 0, 2, 0,            /* 0x11 */
189                 {{0, 0},
190                 {4, 4},
191                 {0, 0},
192                 {0, 0}
193                 }
194         },
195         {0, 0, 2, 0,            /* 0x12 */
196                 {{1, 1},
197                 {4, 4},
198                 {0, 0},
199                 {0, 0}
200                 }
201         },
202         {1, 0, 2, 0,            /* 0x13 */
203                 {{0, 1},
204                 {4, 4},
205                 {0, 0},
206                 {0, 0}
207                 }
208         },
209         {0, 0, 2, 0,            /* 0x14 */
210                 {{2, 2},
211                 {4, 4},
212                 {0, 0},
213                 {0, 0}
214                 }
215         },
216         {1, 0, 3, 0,            /* 0x15 */
217                 {{0, 0},
218                 {2, 2},
219                 {4, 4},
220                 {0, 0}
221                 }
222         },
223         {0, 0, 2, 0,            /* 0x16 */
224                 {{1, 2},
225                 {4, 4},
226                 {0, 0},
227                 {0, 0}
228                 }
229         },
230         {1, 0, 2, 0,            /* 0x17 */
231                 {{0, 2},
232                 {4, 4},
233                 {0, 0},
234                 {0, 0}
235                 }
236         },
237         {0, 0, 1, 0,            /* 0x18 */
238                 {{3, 4},
239                 {0, 0},
240                 {0, 0},
241                 {0, 0}
242                 }
243         },
244         {1, 0, 2, 0,            /* 0x19 */
245                 {{0, 0},
246                 {3, 4},
247                 {0, 0},
248                 {0, 0}
249                 }
250         },
251         {0, 0, 2, 0,            /* 0x1a */
252                 {{1, 1},
253                 {3, 4},
254                 {0, 0},
255                 {0, 0}
256                 }
257         },
258         {1, 0, 2, 0,            /* 0x1b */
259                 {{0, 1},
260                 {3, 4},
261                 {0, 0},
262                 {0, 0}
263                 }
264         },
265         {0, 0, 1, 0,            /* 0x1c */
266                 {{2, 4},
267                 {0, 0},
268                 {0, 0},
269                 {0, 0}
270                 }
271         },
272         {1, 0, 2, 0,            /* 0x1d */
273                 {{0, 0},
274                 {2, 4},
275                 {0, 0},
276                 {0, 0}
277                 }
278         },
279         {0, 0, 1, 0,            /* 0x1e */
280                 {{1, 4},
281                 {0, 0},
282                 {0, 0},
283                 {0, 0}
284                 }
285         },
286         {1, 0, 1, 0,            /* 0x1f */
287                 {{0, 4},
288                 {0, 0},
289                 {0, 0},
290                 {0, 0}
291                 }
292         },
293         {0, 0, 1, 0,            /* 0x20 */
294                 {{5, 5},
295                 {0, 0},
296                 {0, 0},
297                 {0, 0}
298                 }
299         },
300         {1, 0, 2, 0,            /* 0x21 */
301                 {{0, 0},
302                 {5, 5},
303                 {0, 0},
304                 {0, 0}
305                 }
306         },
307         {0, 0, 2, 0,            /* 0x22 */
308                 {{1, 1},
309                 {5, 5},
310                 {0, 0},
311                 {0, 0}
312                 }
313         },
314         {1, 0, 2, 0,            /* 0x23 */
315                 {{0, 1},
316                 {5, 5},
317                 {0, 0},
318                 {0, 0}
319                 }
320         },
321         {0, 0, 2, 0,            /* 0x24 */
322                 {{2, 2},
323                 {5, 5},
324                 {0, 0},
325                 {0, 0}
326                 }
327         },
328         {1, 0, 3, 0,            /* 0x25 */
329                 {{0, 0},
330                 {2, 2},
331                 {5, 5},
332                 {0, 0}
333                 }
334         },
335         {0, 0, 2, 0,            /* 0x26 */
336                 {{1, 2},
337                 {5, 5},
338                 {0, 0},
339                 {0, 0}
340                 }
341         },
342         {1, 0, 2, 0,            /* 0x27 */
343                 {{0, 2},
344                 {5, 5},
345                 {0, 0},
346                 {0, 0}
347                 }
348         },
349         {0, 0, 2, 0,            /* 0x28 */
350                 {{3, 3},
351                 {5, 5},
352                 {0, 0},
353                 {0, 0}
354                 }
355         },
356         {1, 0, 3, 0,            /* 0x29 */
357                 {{0, 0},
358                 {3, 3},
359                 {5, 5},
360                 {0, 0}
361                 }
362         },
363         {0, 0, 3, 0,            /* 0x2a */
364                 {{1, 1},
365                 {3, 3},
366                 {5, 5},
367                 {0, 0}
368                 }
369         },
370         {1, 0, 3, 0,            /* 0x2b */
371                 {{0, 1},
372                 {3, 3},
373                 {5, 5},
374                 {0, 0}
375                 }
376         },
377         {0, 0, 2, 0,            /* 0x2c */
378                 {{2, 3},
379                 {5, 5},
380                 {0, 0},
381                 {0, 0}
382                 }
383         },
384         {1, 0, 3, 0,            /* 0x2d */
385                 {{0, 0},
386                 {2, 3},
387                 {5, 5},
388                 {0, 0}
389                 }
390         },
391         {0, 0, 2, 0,            /* 0x2e */
392                 {{1, 3},
393                 {5, 5},
394                 {0, 0},
395                 {0, 0}
396                 }
397         },
398         {1, 0, 2, 0,            /* 0x2f */
399                 {{0, 3},
400                 {5, 5},
401                 {0, 0},
402                 {0, 0}
403                 }
404         },
405         {0, 0, 1, 0,            /* 0x30 */
406                 {{4, 5},
407                 {0, 0},
408                 {0, 0},
409                 {0, 0}
410                 }
411         },
412         {1, 0, 2, 0,            /* 0x31 */
413                 {{0, 0},
414                 {4, 5},
415                 {0, 0},
416                 {0, 0}
417                 }
418         },
419         {0, 0, 2, 0,            /* 0x32 */
420                 {{1, 1},
421                 {4, 5},
422                 {0, 0},
423                 {0, 0}
424                 }
425         },
426         {1, 0, 2, 0,            /* 0x33 */
427                 {{0, 1},
428                 {4, 5},
429                 {0, 0},
430                 {0, 0}
431                 }
432         },
433         {0, 0, 2, 0,            /* 0x34 */
434                 {{2, 2},
435                 {4, 5},
436                 {0, 0},
437                 {0, 0}
438                 }
439         },
440         {1, 0, 3, 0,            /* 0x35 */
441                 {{0, 0},
442                 {2, 2},
443                 {4, 5},
444                 {0, 0}
445                 }
446         },
447         {0, 0, 2, 0,            /* 0x36 */
448                 {{1, 2},
449                 {4, 5},
450                 {0, 0},
451                 {0, 0}
452                 }
453         },
454         {1, 0, 2, 0,            /* 0x37 */
455                 {{0, 2},
456                 {4, 5},
457                 {0, 0},
458                 {0, 0}
459                 }
460         },
461         {0, 0, 1, 0,            /* 0x38 */
462                 {{3, 5},
463                 {0, 0},
464                 {0, 0},
465                 {0, 0}
466                 }
467         },
468         {1, 0, 2, 0,            /* 0x39 */
469                 {{0, 0},
470                 {3, 5},
471                 {0, 0},
472                 {0, 0}
473                 }
474         },
475         {0, 0, 2, 0,            /* 0x3a */
476                 {{1, 1},
477                 {3, 5},
478                 {0, 0},
479                 {0, 0}
480                 }
481         },
482         {1, 0, 2, 0,            /* 0x3b */
483                 {{0, 1},
484                 {3, 5},
485                 {0, 0},
486                 {0, 0}
487                 }
488         },
489         {0, 0, 1, 0,            /* 0x3c */
490                 {{2, 5},
491                 {0, 0},
492                 {0, 0},
493                 {0, 0}
494                 }
495         },
496         {1, 0, 2, 0,            /* 0x3d */
497                 {{0, 0},
498                 {2, 5},
499                 {0, 0},
500                 {0, 0}
501                 }
502         },
503         {0, 0, 1, 0,            /* 0x3e */
504                 {{1, 5},
505                 {0, 0},
506                 {0, 0},
507                 {0, 0}
508                 }
509         },
510         {1, 0, 1, 0,            /* 0x3f */
511                 {{0, 5},
512                 {0, 0},
513                 {0, 0},
514                 {0, 0}
515                 }
516         },
517         {0, 0, 1, 0,            /* 0x40 */
518                 {{6, 6},
519                 {0, 0},
520                 {0, 0},
521                 {0, 0}
522                 }
523         },
524         {1, 0, 2, 0,            /* 0x41 */
525                 {{0, 0},
526                 {6, 6},
527                 {0, 0},
528                 {0, 0}
529                 }
530         },
531         {0, 0, 2, 0,            /* 0x42 */
532                 {{1, 1},
533                 {6, 6},
534                 {0, 0},
535                 {0, 0}
536                 }
537         },
538         {1, 0, 2, 0,            /* 0x43 */
539                 {{0, 1},
540                 {6, 6},
541                 {0, 0},
542                 {0, 0}
543                 }
544         },
545         {0, 0, 2, 0,            /* 0x44 */
546                 {{2, 2},
547                 {6, 6},
548                 {0, 0},
549                 {0, 0}
550                 }
551         },
552         {1, 0, 3, 0,            /* 0x45 */
553                 {{0, 0},
554                 {2, 2},
555                 {6, 6},
556                 {0, 0}
557                 }
558         },
559         {0, 0, 2, 0,            /* 0x46 */
560                 {{1, 2},
561                 {6, 6},
562                 {0, 0},
563                 {0, 0}
564                 }
565         },
566         {1, 0, 2, 0,            /* 0x47 */
567                 {{0, 2},
568                 {6, 6},
569                 {0, 0},
570                 {0, 0}
571                 }
572         },
573         {0, 0, 2, 0,            /* 0x48 */
574                 {{3, 3},
575                 {6, 6},
576                 {0, 0},
577                 {0, 0}
578                 }
579         },
580         {1, 0, 3, 0,            /* 0x49 */
581                 {{0, 0},
582                 {3, 3},
583                 {6, 6},
584                 {0, 0}
585                 }
586         },
587         {0, 0, 3, 0,            /* 0x4a */
588                 {{1, 1},
589                 {3, 3},
590                 {6, 6},
591                 {0, 0}
592                 }
593         },
594         {1, 0, 3, 0,            /* 0x4b */
595                 {{0, 1},
596                 {3, 3},
597                 {6, 6},
598                 {0, 0}
599                 }
600         },
601         {0, 0, 2, 0,            /* 0x4c */
602                 {{2, 3},
603                 {6, 6},
604                 {0, 0},
605                 {0, 0}
606                 }
607         },
608         {1, 0, 3, 0,            /* 0x4d */
609                 {{0, 0},
610                 {2, 3},
611                 {6, 6},
612                 {0, 0}
613                 }
614         },
615         {0, 0, 2, 0,            /* 0x4e */
616                 {{1, 3},
617                 {6, 6},
618                 {0, 0},
619                 {0, 0}
620                 }
621         },
622         {1, 0, 2, 0,            /* 0x4f */
623                 {{0, 3},
624                 {6, 6},
625                 {0, 0},
626                 {0, 0}
627                 }
628         },
629         {0, 0, 2, 0,            /* 0x50 */
630                 {{4, 4},
631                 {6, 6},
632                 {0, 0},
633                 {0, 0}
634                 }
635         },
636         {1, 0, 3, 0,            /* 0x51 */
637                 {{0, 0},
638                 {4, 4},
639                 {6, 6},
640                 {0, 0}
641                 }
642         },
643         {0, 0, 3, 0,            /* 0x52 */
644                 {{1, 1},
645                 {4, 4},
646                 {6, 6},
647                 {0, 0}
648                 }
649         },
650         {1, 0, 3, 0,            /* 0x53 */
651                 {{0, 1},
652                 {4, 4},
653                 {6, 6},
654                 {0, 0}
655                 }
656         },
657         {0, 0, 3, 0,            /* 0x54 */
658                 {{2, 2},
659                 {4, 4},
660                 {6, 6},
661                 {0, 0}
662                 }
663         },
664         {1, 0, 4, 0,            /* 0x55 */
665                 {{0, 0},
666                 {2, 2},
667                 {4, 4},
668                 {6, 6}
669                 }
670         },
671         {0, 0, 3, 0,            /* 0x56 */
672                 {{1, 2},
673                 {4, 4},
674                 {6, 6},
675                 {0, 0}
676                 }
677         },
678         {1, 0, 3, 0,            /* 0x57 */
679                 {{0, 2},
680                 {4, 4},
681                 {6, 6},
682                 {0, 0}
683                 }
684         },
685         {0, 0, 2, 0,            /* 0x58 */
686                 {{3, 4},
687                 {6, 6},
688                 {0, 0},
689                 {0, 0}
690                 }
691         },
692         {1, 0, 3, 0,            /* 0x59 */
693                 {{0, 0},
694                 {3, 4},
695                 {6, 6},
696                 {0, 0}
697                 }
698         },
699         {0, 0, 3, 0,            /* 0x5a */
700                 {{1, 1},
701                 {3, 4},
702                 {6, 6},
703                 {0, 0}
704                 }
705         },
706         {1, 0, 3, 0,            /* 0x5b */
707                 {{0, 1},
708                 {3, 4},
709                 {6, 6},
710                 {0, 0}
711                 }
712         },
713         {0, 0, 2, 0,            /* 0x5c */
714                 {{2, 4},
715                 {6, 6},
716                 {0, 0},
717                 {0, 0}
718                 }
719         },
720         {1, 0, 3, 0,            /* 0x5d */
721                 {{0, 0},
722                 {2, 4},
723                 {6, 6},
724                 {0, 0}
725                 }
726         },
727         {0, 0, 2, 0,            /* 0x5e */
728                 {{1, 4},
729                 {6, 6},
730                 {0, 0},
731                 {0, 0}
732                 }
733         },
734         {1, 0, 2, 0,            /* 0x5f */
735                 {{0, 4},
736                 {6, 6},
737                 {0, 0},
738                 {0, 0}
739                 }
740         },
741         {0, 0, 1, 0,            /* 0x60 */
742                 {{5, 6},
743                 {0, 0},
744                 {0, 0},
745                 {0, 0}
746                 }
747         },
748         {1, 0, 2, 0,            /* 0x61 */
749                 {{0, 0},
750                 {5, 6},
751                 {0, 0},
752                 {0, 0}
753                 }
754         },
755         {0, 0, 2, 0,            /* 0x62 */
756                 {{1, 1},
757                 {5, 6},
758                 {0, 0},
759                 {0, 0}
760                 }
761         },
762         {1, 0, 2, 0,            /* 0x63 */
763                 {{0, 1},
764                 {5, 6},
765                 {0, 0},
766                 {0, 0}
767                 }
768         },
769         {0, 0, 2, 0,            /* 0x64 */
770                 {{2, 2},
771                 {5, 6},
772                 {0, 0},
773                 {0, 0}
774                 }
775         },
776         {1, 0, 3, 0,            /* 0x65 */
777                 {{0, 0},
778                 {2, 2},
779                 {5, 6},
780                 {0, 0}
781                 }
782         },
783         {0, 0, 2, 0,            /* 0x66 */
784                 {{1, 2},
785                 {5, 6},
786                 {0, 0},
787                 {0, 0}
788                 }
789         },
790         {1, 0, 2, 0,            /* 0x67 */
791                 {{0, 2},
792                 {5, 6},
793                 {0, 0},
794                 {0, 0}
795                 }
796         },
797         {0, 0, 2, 0,            /* 0x68 */
798                 {{3, 3},
799                 {5, 6},
800                 {0, 0},
801                 {0, 0}
802                 }
803         },
804         {1, 0, 3, 0,            /* 0x69 */
805                 {{0, 0},
806                 {3, 3},
807                 {5, 6},
808                 {0, 0}
809                 }
810         },
811         {0, 0, 3, 0,            /* 0x6a */
812                 {{1, 1},
813                 {3, 3},
814                 {5, 6},
815                 {0, 0}
816                 }
817         },
818         {1, 0, 3, 0,            /* 0x6b */
819                 {{0, 1},
820                 {3, 3},
821                 {5, 6},
822                 {0, 0}
823                 }
824         },
825         {0, 0, 2, 0,            /* 0x6c */
826                 {{2, 3},
827                 {5, 6},
828                 {0, 0},
829                 {0, 0}
830                 }
831         },
832         {1, 0, 3, 0,            /* 0x6d */
833                 {{0, 0},
834                 {2, 3},
835                 {5, 6},
836                 {0, 0}
837                 }
838         },
839         {0, 0, 2, 0,            /* 0x6e */
840                 {{1, 3},
841                 {5, 6},
842                 {0, 0},
843                 {0, 0}
844                 }
845         },
846         {1, 0, 2, 0,            /* 0x6f */
847                 {{0, 3},
848                 {5, 6},
849                 {0, 0},
850                 {0, 0}
851                 }
852         },
853         {0, 0, 1, 0,            /* 0x70 */
854                 {{4, 6},
855                 {0, 0},
856                 {0, 0},
857                 {0, 0}
858                 }
859         },
860         {1, 0, 2, 0,            /* 0x71 */
861                 {{0, 0},
862                 {4, 6},
863                 {0, 0},
864                 {0, 0}
865                 }
866         },
867         {0, 0, 2, 0,            /* 0x72 */
868                 {{1, 1},
869                 {4, 6},
870                 {0, 0},
871                 {0, 0}
872                 }
873         },
874         {1, 0, 2, 0,            /* 0x73 */
875                 {{0, 1},
876                 {4, 6},
877                 {0, 0},
878                 {0, 0}
879                 }
880         },
881         {0, 0, 2, 0,            /* 0x74 */
882                 {{2, 2},
883                 {4, 6},
884                 {0, 0},
885                 {0, 0}
886                 }
887         },
888         {1, 0, 3, 0,            /* 0x75 */
889                 {{0, 0},
890                 {2, 2},
891                 {4, 6},
892                 {0, 0}
893                 }
894         },
895         {0, 0, 2, 0,            /* 0x76 */
896                 {{1, 2},
897                 {4, 6},
898                 {0, 0},
899                 {0, 0}
900                 }
901         },
902         {1, 0, 2, 0,            /* 0x77 */
903                 {{0, 2},
904                 {4, 6},
905                 {0, 0},
906                 {0, 0}
907                 }
908         },
909         {0, 0, 1, 0,            /* 0x78 */
910                 {{3, 6},
911                 {0, 0},
912                 {0, 0},
913                 {0, 0}
914                 }
915         },
916         {1, 0, 2, 0,            /* 0x79 */
917                 {{0, 0},
918                 {3, 6},
919                 {0, 0},
920                 {0, 0}
921                 }
922         },
923         {0, 0, 2, 0,            /* 0x7a */
924                 {{1, 1},
925                 {3, 6},
926                 {0, 0},
927                 {0, 0}
928                 }
929         },
930         {1, 0, 2, 0,            /* 0x7b */
931                 {{0, 1},
932                 {3, 6},
933                 {0, 0},
934                 {0, 0}
935                 }
936         },
937         {0, 0, 1, 0,            /* 0x7c */
938                 {{2, 6},
939                 {0, 0},
940                 {0, 0},
941                 {0, 0}
942                 }
943         },
944         {1, 0, 2, 0,            /* 0x7d */
945                 {{0, 0},
946                 {2, 6},
947                 {0, 0},
948                 {0, 0}
949                 }
950         },
951         {0, 0, 1, 0,            /* 0x7e */
952                 {{1, 6},
953                 {0, 0},
954                 {0, 0},
955                 {0, 0}
956                 }
957         },
958         {1, 0, 1, 0,            /* 0x7f */
959                 {{0, 6},
960                 {0, 0},
961                 {0, 0},
962                 {0, 0}
963                 }
964         },
965         {0, 1, 1, 0,            /* 0x80 */
966                 {{7, 7},
967                 {0, 0},
968                 {0, 0},
969                 {0, 0}
970                 }
971         },
972         {1, 1, 2, 0,            /* 0x81 */
973                 {{0, 0},
974                 {7, 7},
975                 {0, 0},
976                 {0, 0}
977                 }
978         },
979         {0, 1, 2, 0,            /* 0x82 */
980                 {{1, 1},
981                 {7, 7},
982                 {0, 0},
983                 {0, 0}
984                 }
985         },
986         {1, 1, 2, 0,            /* 0x83 */
987                 {{0, 1},
988                 {7, 7},
989                 {0, 0},
990                 {0, 0}
991                 }
992         },
993         {0, 1, 2, 0,            /* 0x84 */
994                 {{2, 2},
995                 {7, 7},
996                 {0, 0},
997                 {0, 0}
998                 }
999         },
1000         {1, 1, 3, 0,            /* 0x85 */
1001                 {{0, 0},
1002                 {2, 2},
1003                 {7, 7},
1004                 {0, 0}
1005                 }
1006         },
1007         {0, 1, 2, 0,            /* 0x86 */
1008                 {{1, 2},
1009                 {7, 7},
1010                 {0, 0},
1011                 {0, 0}
1012                 }
1013         },
1014         {1, 1, 2, 0,            /* 0x87 */
1015                 {{0, 2},
1016                 {7, 7},
1017                 {0, 0},
1018                 {0, 0}
1019                 }
1020         },
1021         {0, 1, 2, 0,            /* 0x88 */
1022                 {{3, 3},
1023                 {7, 7},
1024                 {0, 0},
1025                 {0, 0}
1026                 }
1027         },
1028         {1, 1, 3, 0,            /* 0x89 */
1029                 {{0, 0},
1030                 {3, 3},
1031                 {7, 7},
1032                 {0, 0}
1033                 }
1034         },
1035         {0, 1, 3, 0,            /* 0x8a */
1036                 {{1, 1},
1037                 {3, 3},
1038                 {7, 7},
1039                 {0, 0}
1040                 }
1041         },
1042         {1, 1, 3, 0,            /* 0x8b */
1043                 {{0, 1},
1044                 {3, 3},
1045                 {7, 7},
1046                 {0, 0}
1047                 }
1048         },
1049         {0, 1, 2, 0,            /* 0x8c */
1050                 {{2, 3},
1051                 {7, 7},
1052                 {0, 0},
1053                 {0, 0}
1054                 }
1055         },
1056         {1, 1, 3, 0,            /* 0x8d */
1057                 {{0, 0},
1058                 {2, 3},
1059                 {7, 7},
1060                 {0, 0}
1061                 }
1062         },
1063         {0, 1, 2, 0,            /* 0x8e */
1064                 {{1, 3},
1065                 {7, 7},
1066                 {0, 0},
1067                 {0, 0}
1068                 }
1069         },
1070         {1, 1, 2, 0,            /* 0x8f */
1071                 {{0, 3},
1072                 {7, 7},
1073                 {0, 0},
1074                 {0, 0}
1075                 }
1076         },
1077         {0, 1, 2, 0,            /* 0x90 */
1078                 {{4, 4},
1079                 {7, 7},
1080                 {0, 0},
1081                 {0, 0}
1082                 }
1083         },
1084         {1, 1, 3, 0,            /* 0x91 */
1085                 {{0, 0},
1086                 {4, 4},
1087                 {7, 7},
1088                 {0, 0}
1089                 }
1090         },
1091         {0, 1, 3, 0,            /* 0x92 */
1092                 {{1, 1},
1093                 {4, 4},
1094                 {7, 7},
1095                 {0, 0}
1096                 }
1097         },
1098         {1, 1, 3, 0,            /* 0x93 */
1099                 {{0, 1},
1100                 {4, 4},
1101                 {7, 7},
1102                 {0, 0}
1103                 }
1104         },
1105         {0, 1, 3, 0,            /* 0x94 */
1106                 {{2, 2},
1107                 {4, 4},
1108                 {7, 7},
1109                 {0, 0}
1110                 }
1111         },
1112         {1, 1, 4, 0,            /* 0x95 */
1113                 {{0, 0},
1114                 {2, 2},
1115                 {4, 4},
1116                 {7, 7}
1117                 }
1118         },
1119         {0, 1, 3, 0,            /* 0x96 */
1120                 {{1, 2},
1121                 {4, 4},
1122                 {7, 7},
1123                 {0, 0}
1124                 }
1125         },
1126         {1, 1, 3, 0,            /* 0x97 */
1127                 {{0, 2},
1128                 {4, 4},
1129                 {7, 7},
1130                 {0, 0}
1131                 }
1132         },
1133         {0, 1, 2, 0,            /* 0x98 */
1134                 {{3, 4},
1135                 {7, 7},
1136                 {0, 0},
1137                 {0, 0}
1138                 }
1139         },
1140         {1, 1, 3, 0,            /* 0x99 */
1141                 {{0, 0},
1142                 {3, 4},
1143                 {7, 7},
1144                 {0, 0}
1145                 }
1146         },
1147         {0, 1, 3, 0,            /* 0x9a */
1148                 {{1, 1},
1149                 {3, 4},
1150                 {7, 7},
1151                 {0, 0}
1152                 }
1153         },
1154         {1, 1, 3, 0,            /* 0x9b */
1155                 {{0, 1},
1156                 {3, 4},
1157                 {7, 7},
1158                 {0, 0}
1159                 }
1160         },
1161         {0, 1, 2, 0,            /* 0x9c */
1162                 {{2, 4},
1163                 {7, 7},
1164                 {0, 0},
1165                 {0, 0}
1166                 }
1167         },
1168         {1, 1, 3, 0,            /* 0x9d */
1169                 {{0, 0},
1170                 {2, 4},
1171                 {7, 7},
1172                 {0, 0}
1173                 }
1174         },
1175         {0, 1, 2, 0,            /* 0x9e */
1176                 {{1, 4},
1177                 {7, 7},
1178                 {0, 0},
1179                 {0, 0}
1180                 }
1181         },
1182         {1, 1, 2, 0,            /* 0x9f */
1183                 {{0, 4},
1184                 {7, 7},
1185                 {0, 0},
1186                 {0, 0}
1187                 }
1188         },
1189         {0, 1, 2, 0,            /* 0xa0 */
1190                 {{5, 5},
1191                 {7, 7},
1192                 {0, 0},
1193                 {0, 0}
1194                 }
1195         },
1196         {1, 1, 3, 0,            /* 0xa1 */
1197                 {{0, 0},
1198                 {5, 5},
1199                 {7, 7},
1200                 {0, 0}
1201                 }
1202         },
1203         {0, 1, 3, 0,            /* 0xa2 */
1204                 {{1, 1},
1205                 {5, 5},
1206                 {7, 7},
1207                 {0, 0}
1208                 }
1209         },
1210         {1, 1, 3, 0,            /* 0xa3 */
1211                 {{0, 1},
1212                 {5, 5},
1213                 {7, 7},
1214                 {0, 0}
1215                 }
1216         },
1217         {0, 1, 3, 0,            /* 0xa4 */
1218                 {{2, 2},
1219                 {5, 5},
1220                 {7, 7},
1221                 {0, 0}
1222                 }
1223         },
1224         {1, 1, 4, 0,            /* 0xa5 */
1225                 {{0, 0},
1226                 {2, 2},
1227                 {5, 5},
1228                 {7, 7}
1229                 }
1230         },
1231         {0, 1, 3, 0,            /* 0xa6 */
1232                 {{1, 2},
1233                 {5, 5},
1234                 {7, 7},
1235                 {0, 0}
1236                 }
1237         },
1238         {1, 1, 3, 0,            /* 0xa7 */
1239                 {{0, 2},
1240                 {5, 5},
1241                 {7, 7},
1242                 {0, 0}
1243                 }
1244         },
1245         {0, 1, 3, 0,            /* 0xa8 */
1246                 {{3, 3},
1247                 {5, 5},
1248                 {7, 7},
1249                 {0, 0}
1250                 }
1251         },
1252         {1, 1, 4, 0,            /* 0xa9 */
1253                 {{0, 0},
1254                 {3, 3},
1255                 {5, 5},
1256                 {7, 7}
1257                 }
1258         },
1259         {0, 1, 4, 0,            /* 0xaa */
1260                 {{1, 1},
1261                 {3, 3},
1262                 {5, 5},
1263                 {7, 7}
1264                 }
1265         },
1266         {1, 1, 4, 0,            /* 0xab */
1267                 {{0, 1},
1268                 {3, 3},
1269                 {5, 5},
1270                 {7, 7}
1271                 }
1272         },
1273         {0, 1, 3, 0,            /* 0xac */
1274                 {{2, 3},
1275                 {5, 5},
1276                 {7, 7},
1277                 {0, 0}
1278                 }
1279         },
1280         {1, 1, 4, 0,            /* 0xad */
1281                 {{0, 0},
1282                 {2, 3},
1283                 {5, 5},
1284                 {7, 7}
1285                 }
1286         },
1287         {0, 1, 3, 0,            /* 0xae */
1288                 {{1, 3},
1289                 {5, 5},
1290                 {7, 7},
1291                 {0, 0}
1292                 }
1293         },
1294         {1, 1, 3, 0,            /* 0xaf */
1295                 {{0, 3},
1296                 {5, 5},
1297                 {7, 7},
1298                 {0, 0}
1299                 }
1300         },
1301         {0, 1, 2, 0,            /* 0xb0 */
1302                 {{4, 5},
1303                 {7, 7},
1304                 {0, 0},
1305                 {0, 0}
1306                 }
1307         },
1308         {1, 1, 3, 0,            /* 0xb1 */
1309                 {{0, 0},
1310                 {4, 5},
1311                 {7, 7},
1312                 {0, 0}
1313                 }
1314         },
1315         {0, 1, 3, 0,            /* 0xb2 */
1316                 {{1, 1},
1317                 {4, 5},
1318                 {7, 7},
1319                 {0, 0}
1320                 }
1321         },
1322         {1, 1, 3, 0,            /* 0xb3 */
1323                 {{0, 1},
1324                 {4, 5},
1325                 {7, 7},
1326                 {0, 0}
1327                 }
1328         },
1329         {0, 1, 3, 0,            /* 0xb4 */
1330                 {{2, 2},
1331                 {4, 5},
1332                 {7, 7},
1333                 {0, 0}
1334                 }
1335         },
1336         {1, 1, 4, 0,            /* 0xb5 */
1337                 {{0, 0},
1338                 {2, 2},
1339                 {4, 5},
1340                 {7, 7}
1341                 }
1342         },
1343         {0, 1, 3, 0,            /* 0xb6 */
1344                 {{1, 2},
1345                 {4, 5},
1346                 {7, 7},
1347                 {0, 0}
1348                 }
1349         },
1350         {1, 1, 3, 0,            /* 0xb7 */
1351                 {{0, 2},
1352                 {4, 5},
1353                 {7, 7},
1354                 {0, 0}
1355                 }
1356         },
1357         {0, 1, 2, 0,            /* 0xb8 */
1358                 {{3, 5},
1359                 {7, 7},
1360                 {0, 0},
1361                 {0, 0}
1362                 }
1363         },
1364         {1, 1, 3, 0,            /* 0xb9 */
1365                 {{0, 0},
1366                 {3, 5},
1367                 {7, 7},
1368                 {0, 0}
1369                 }
1370         },
1371         {0, 1, 3, 0,            /* 0xba */
1372                 {{1, 1},
1373                 {3, 5},
1374                 {7, 7},
1375                 {0, 0}
1376                 }
1377         },
1378         {1, 1, 3, 0,            /* 0xbb */
1379                 {{0, 1},
1380                 {3, 5},
1381                 {7, 7},
1382                 {0, 0}
1383                 }
1384         },
1385         {0, 1, 2, 0,            /* 0xbc */
1386                 {{2, 5},
1387                 {7, 7},
1388                 {0, 0},
1389                 {0, 0}
1390                 }
1391         },
1392         {1, 1, 3, 0,            /* 0xbd */
1393                 {{0, 0},
1394                 {2, 5},
1395                 {7, 7},
1396                 {0, 0}
1397                 }
1398         },
1399         {0, 1, 2, 0,            /* 0xbe */
1400                 {{1, 5},
1401                 {7, 7},
1402                 {0, 0},
1403                 {0, 0}
1404                 }
1405         },
1406         {1, 1, 2, 0,            /* 0xbf */
1407                 {{0, 5},
1408                 {7, 7},
1409                 {0, 0},
1410                 {0, 0}
1411                 }
1412         },
1413         {0, 1, 1, 0,            /* 0xc0 */
1414                 {{6, 7},
1415                 {0, 0},
1416                 {0, 0},
1417                 {0, 0}
1418                 }
1419         },
1420         {1, 1, 2, 0,            /* 0xc1 */
1421                 {{0, 0},
1422                 {6, 7},
1423                 {0, 0},
1424                 {0, 0}
1425                 }
1426         },
1427         {0, 1, 2, 0,            /* 0xc2 */
1428                 {{1, 1},
1429                 {6, 7},
1430                 {0, 0},
1431                 {0, 0}
1432                 }
1433         },
1434         {1, 1, 2, 0,            /* 0xc3 */
1435                 {{0, 1},
1436                 {6, 7},
1437                 {0, 0},
1438                 {0, 0}
1439                 }
1440         },
1441         {0, 1, 2, 0,            /* 0xc4 */
1442                 {{2, 2},
1443                 {6, 7},
1444                 {0, 0},
1445                 {0, 0}
1446                 }
1447         },
1448         {1, 1, 3, 0,            /* 0xc5 */
1449                 {{0, 0},
1450                 {2, 2},
1451                 {6, 7},
1452                 {0, 0}
1453                 }
1454         },
1455         {0, 1, 2, 0,            /* 0xc6 */
1456                 {{1, 2},
1457                 {6, 7},
1458                 {0, 0},
1459                 {0, 0}
1460                 }
1461         },
1462         {1, 1, 2, 0,            /* 0xc7 */
1463                 {{0, 2},
1464                 {6, 7},
1465                 {0, 0},
1466                 {0, 0}
1467                 }
1468         },
1469         {0, 1, 2, 0,            /* 0xc8 */
1470                 {{3, 3},
1471                 {6, 7},
1472                 {0, 0},
1473                 {0, 0}
1474                 }
1475         },
1476         {1, 1, 3, 0,            /* 0xc9 */
1477                 {{0, 0},
1478                 {3, 3},
1479                 {6, 7},
1480                 {0, 0}
1481                 }
1482         },
1483         {0, 1, 3, 0,            /* 0xca */
1484                 {{1, 1},
1485                 {3, 3},
1486                 {6, 7},
1487                 {0, 0}
1488                 }
1489         },
1490         {1, 1, 3, 0,            /* 0xcb */
1491                 {{0, 1},
1492                 {3, 3},
1493                 {6, 7},
1494                 {0, 0}
1495                 }
1496         },
1497         {0, 1, 2, 0,            /* 0xcc */
1498                 {{2, 3},
1499                 {6, 7},
1500                 {0, 0},
1501                 {0, 0}
1502                 }
1503         },
1504         {1, 1, 3, 0,            /* 0xcd */
1505                 {{0, 0},
1506                 {2, 3},
1507                 {6, 7},
1508                 {0, 0}
1509                 }
1510         },
1511         {0, 1, 2, 0,            /* 0xce */
1512                 {{1, 3},
1513                 {6, 7},
1514                 {0, 0},
1515                 {0, 0}
1516                 }
1517         },
1518         {1, 1, 2, 0,            /* 0xcf */
1519                 {{0, 3},
1520                 {6, 7},
1521                 {0, 0},
1522                 {0, 0}
1523                 }
1524         },
1525         {0, 1, 2, 0,            /* 0xd0 */
1526                 {{4, 4},
1527                 {6, 7},
1528                 {0, 0},
1529                 {0, 0}
1530                 }
1531         },
1532         {1, 1, 3, 0,            /* 0xd1 */
1533                 {{0, 0},
1534                 {4, 4},
1535                 {6, 7},
1536                 {0, 0}
1537                 }
1538         },
1539         {0, 1, 3, 0,            /* 0xd2 */
1540                 {{1, 1},
1541                 {4, 4},
1542                 {6, 7},
1543                 {0, 0}
1544                 }
1545         },
1546         {1, 1, 3, 0,            /* 0xd3 */
1547                 {{0, 1},
1548                 {4, 4},
1549                 {6, 7},
1550                 {0, 0}
1551                 }
1552         },
1553         {0, 1, 3, 0,            /* 0xd4 */
1554                 {{2, 2},
1555                 {4, 4},
1556                 {6, 7},
1557                 {0, 0}
1558                 }
1559         },
1560         {1, 1, 4, 0,            /* 0xd5 */
1561                 {{0, 0},
1562                 {2, 2},
1563                 {4, 4},
1564                 {6, 7}
1565                 }
1566         },
1567         {0, 1, 3, 0,            /* 0xd6 */
1568                 {{1, 2},
1569                 {4, 4},
1570                 {6, 7},
1571                 {0, 0}
1572                 }
1573         },
1574         {1, 1, 3, 0,            /* 0xd7 */
1575                 {{0, 2},
1576                 {4, 4},
1577                 {6, 7},
1578                 {0, 0}
1579                 }
1580         },
1581         {0, 1, 2, 0,            /* 0xd8 */
1582                 {{3, 4},
1583                 {6, 7},
1584                 {0, 0},
1585                 {0, 0}
1586                 }
1587         },
1588         {1, 1, 3, 0,            /* 0xd9 */
1589                 {{0, 0},
1590                 {3, 4},
1591                 {6, 7},
1592                 {0, 0}
1593                 }
1594         },
1595         {0, 1, 3, 0,            /* 0xda */
1596                 {{1, 1},
1597                 {3, 4},
1598                 {6, 7},
1599                 {0, 0}
1600                 }
1601         },
1602         {1, 1, 3, 0,            /* 0xdb */
1603                 {{0, 1},
1604                 {3, 4},
1605                 {6, 7},
1606                 {0, 0}
1607                 }
1608         },
1609         {0, 1, 2, 0,            /* 0xdc */
1610                 {{2, 4},
1611                 {6, 7},
1612                 {0, 0},
1613                 {0, 0}
1614                 }
1615         },
1616         {1, 1, 3, 0,            /* 0xdd */
1617                 {{0, 0},
1618                 {2, 4},
1619                 {6, 7},
1620                 {0, 0}
1621                 }
1622         },
1623         {0, 1, 2, 0,            /* 0xde */
1624                 {{1, 4},
1625                 {6, 7},
1626                 {0, 0},
1627                 {0, 0}
1628                 }
1629         },
1630         {1, 1, 2, 0,            /* 0xdf */
1631                 {{0, 4},
1632                 {6, 7},
1633                 {0, 0},
1634                 {0, 0}
1635                 }
1636         },
1637         {0, 1, 1, 0,            /* 0xe0 */
1638                 {{5, 7},
1639                 {0, 0},
1640                 {0, 0},
1641                 {0, 0}
1642                 }
1643         },
1644         {1, 1, 2, 0,            /* 0xe1 */
1645                 {{0, 0},
1646                 {5, 7},
1647                 {0, 0},
1648                 {0, 0}
1649                 }
1650         },
1651         {0, 1, 2, 0,            /* 0xe2 */
1652                 {{1, 1},
1653                 {5, 7},
1654                 {0, 0},
1655                 {0, 0}
1656                 }
1657         },
1658         {1, 1, 2, 0,            /* 0xe3 */
1659                 {{0, 1},
1660                 {5, 7},
1661                 {0, 0},
1662                 {0, 0}
1663                 }
1664         },
1665         {0, 1, 2, 0,            /* 0xe4 */
1666                 {{2, 2},
1667                 {5, 7},
1668                 {0, 0},
1669                 {0, 0}
1670                 }
1671         },
1672         {1, 1, 3, 0,            /* 0xe5 */
1673                 {{0, 0},
1674                 {2, 2},
1675                 {5, 7},
1676                 {0, 0}
1677                 }
1678         },
1679         {0, 1, 2, 0,            /* 0xe6 */
1680                 {{1, 2},
1681                 {5, 7},
1682                 {0, 0},
1683                 {0, 0}
1684                 }
1685         },
1686         {1, 1, 2, 0,            /* 0xe7 */
1687                 {{0, 2},
1688                 {5, 7},
1689                 {0, 0},
1690                 {0, 0}
1691                 }
1692         },
1693         {0, 1, 2, 0,            /* 0xe8 */
1694                 {{3, 3},
1695                 {5, 7},
1696                 {0, 0},
1697                 {0, 0}
1698                 }
1699         },
1700         {1, 1, 3, 0,            /* 0xe9 */
1701                 {{0, 0},
1702                 {3, 3},
1703                 {5, 7},
1704                 {0, 0}
1705                 }
1706         },
1707         {0, 1, 3, 0,            /* 0xea */
1708                 {{1, 1},
1709                 {3, 3},
1710                 {5, 7},
1711                 {0, 0}
1712                 }
1713         },
1714         {1, 1, 3, 0,            /* 0xeb */
1715                 {{0, 1},
1716                 {3, 3},
1717                 {5, 7},
1718                 {0, 0}
1719                 }
1720         },
1721         {0, 1, 2, 0,            /* 0xec */
1722                 {{2, 3},
1723                 {5, 7},
1724                 {0, 0},
1725                 {0, 0}
1726                 }
1727         },
1728         {1, 1, 3, 0,            /* 0xed */
1729                 {{0, 0},
1730                 {2, 3},
1731                 {5, 7},
1732                 {0, 0}
1733                 }
1734         },
1735         {0, 1, 2, 0,            /* 0xee */
1736                 {{1, 3},
1737                 {5, 7},
1738                 {0, 0},
1739                 {0, 0}
1740                 }
1741         },
1742         {1, 1, 2, 0,            /* 0xef */
1743                 {{0, 3},
1744                 {5, 7},
1745                 {0, 0},
1746                 {0, 0}
1747                 }
1748         },
1749         {0, 1, 1, 0,            /* 0xf0 */
1750                 {{4, 7},
1751                 {0, 0},
1752                 {0, 0},
1753                 {0, 0}
1754                 }
1755         },
1756         {1, 1, 2, 0,            /* 0xf1 */
1757                 {{0, 0},
1758                 {4, 7},
1759                 {0, 0},
1760                 {0, 0}
1761                 }
1762         },
1763         {0, 1, 2, 0,            /* 0xf2 */
1764                 {{1, 1},
1765                 {4, 7},
1766                 {0, 0},
1767                 {0, 0}
1768                 }
1769         },
1770         {1, 1, 2, 0,            /* 0xf3 */
1771                 {{0, 1},
1772                 {4, 7},
1773                 {0, 0},
1774                 {0, 0}
1775                 }
1776         },
1777         {0, 1, 2, 0,            /* 0xf4 */
1778                 {{2, 2},
1779                 {4, 7},
1780                 {0, 0},
1781                 {0, 0}
1782                 }
1783         },
1784         {1, 1, 3, 0,            /* 0xf5 */
1785                 {{0, 0},
1786                 {2, 2},
1787                 {4, 7},
1788                 {0, 0}
1789                 }
1790         },
1791         {0, 1, 2, 0,            /* 0xf6 */
1792                 {{1, 2},
1793                 {4, 7},
1794                 {0, 0},
1795                 {0, 0}
1796                 }
1797         },
1798         {1, 1, 2, 0,            /* 0xf7 */
1799                 {{0, 2},
1800                 {4, 7},
1801                 {0, 0},
1802                 {0, 0}
1803                 }
1804         },
1805         {0, 1, 1, 0,            /* 0xf8 */
1806                 {{3, 7},
1807                 {0, 0},
1808                 {0, 0},
1809                 {0, 0}
1810                 }
1811         },
1812         {1, 1, 2, 0,            /* 0xf9 */
1813                 {{0, 0},
1814                 {3, 7},
1815                 {0, 0},
1816                 {0, 0}
1817                 }
1818         },
1819         {0, 1, 2, 0,            /* 0xfa */
1820                 {{1, 1},
1821                 {3, 7},
1822                 {0, 0},
1823                 {0, 0}
1824                 }
1825         },
1826         {1, 1, 2, 0,            /* 0xfb */
1827                 {{0, 1},
1828                 {3, 7},
1829                 {0, 0},
1830                 {0, 0}
1831                 }
1832         },
1833         {0, 1, 1, 0,            /* 0xfc */
1834                 {{2, 7},
1835                 {0, 0},
1836                 {0, 0},
1837                 {0, 0}
1838                 }
1839         },
1840         {1, 1, 2, 0,            /* 0xfd */
1841                 {{0, 0},
1842                 {2, 7},
1843                 {0, 0},
1844                 {0, 0}
1845                 }
1846         },
1847         {0, 1, 1, 0,            /* 0xfe */
1848                 {{1, 7},
1849                 {0, 0},
1850                 {0, 0},
1851                 {0, 0}
1852                 }
1853         },
1854         {1, 1, 1, 0,            /* 0xff */
1855                 {{0, 7},
1856                 {0, 0},
1857                 {0, 0},
1858                 {0, 0}
1859                 }
1860         }
1861 };
1862
1863
1864 int
1865 sctp_is_address_in_scope(struct sctp_ifa *ifa,
1866     int ipv4_addr_legal,
1867     int ipv6_addr_legal,
1868     int loopback_scope,
1869     int ipv4_local_scope,
1870     int local_scope SCTP_UNUSED,/* XXX */
1871     int site_scope,
1872     int do_update)
1873 {
1874         if ((loopback_scope == 0) &&
1875             (ifa->ifn_p) && SCTP_IFN_IS_IFT_LOOP(ifa->ifn_p)) {
1876                 /*
1877                  * skip loopback if not in scope *
1878                  */
1879                 return (0);
1880         }
1881         switch (ifa->address.sa.sa_family) {
1882 #ifdef INET
1883         case AF_INET:
1884                 if (ipv4_addr_legal) {
1885                         struct sockaddr_in *sin;
1886
1887                         sin = (struct sockaddr_in *)&ifa->address.sin;
1888                         if (sin->sin_addr.s_addr == 0) {
1889                                 /* not in scope , unspecified */
1890                                 return (0);
1891                         }
1892                         if ((ipv4_local_scope == 0) &&
1893                             (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr))) {
1894                                 /* private address not in scope */
1895                                 return (0);
1896                         }
1897                 } else {
1898                         return (0);
1899                 }
1900                 break;
1901 #endif
1902 #ifdef INET6
1903         case AF_INET6:
1904                 if (ipv6_addr_legal) {
1905                         struct sockaddr_in6 *sin6;
1906
1907                         /*
1908                          * Must update the flags,  bummer, which means any
1909                          * IFA locks must now be applied HERE <->
1910                          */
1911                         if (do_update) {
1912                                 sctp_gather_internal_ifa_flags(ifa);
1913                         }
1914                         if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
1915                                 return (0);
1916                         }
1917                         /* ok to use deprecated addresses? */
1918                         sin6 = (struct sockaddr_in6 *)&ifa->address.sin6;
1919                         if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
1920                                 /* skip unspecifed addresses */
1921                                 return (0);
1922                         }
1923                         if (    /* (local_scope == 0) && */
1924                             (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr))) {
1925                                 return (0);
1926                         }
1927                         if ((site_scope == 0) &&
1928                             (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr))) {
1929                                 return (0);
1930                         }
1931                 } else {
1932                         return (0);
1933                 }
1934                 break;
1935 #endif
1936         default:
1937                 return (0);
1938         }
1939         return (1);
1940 }
1941
1942 static struct mbuf *
1943 sctp_add_addr_to_mbuf(struct mbuf *m, struct sctp_ifa *ifa, uint16_t * len)
1944 {
1945         struct sctp_paramhdr *parmh;
1946         struct mbuf *mret;
1947         uint16_t plen;
1948
1949         switch (ifa->address.sa.sa_family) {
1950 #ifdef INET
1951         case AF_INET:
1952                 plen = (uint16_t) sizeof(struct sctp_ipv4addr_param);
1953                 break;
1954 #endif
1955 #ifdef INET6
1956         case AF_INET6:
1957                 plen = (uint16_t) sizeof(struct sctp_ipv6addr_param);
1958                 break;
1959 #endif
1960         default:
1961                 return (m);
1962         }
1963         if (M_TRAILINGSPACE(m) >= plen) {
1964                 /* easy side we just drop it on the end */
1965                 parmh = (struct sctp_paramhdr *)(SCTP_BUF_AT(m, SCTP_BUF_LEN(m)));
1966                 mret = m;
1967         } else {
1968                 /* Need more space */
1969                 mret = m;
1970                 while (SCTP_BUF_NEXT(mret) != NULL) {
1971                         mret = SCTP_BUF_NEXT(mret);
1972                 }
1973                 SCTP_BUF_NEXT(mret) = sctp_get_mbuf_for_msg(plen, 0, M_DONTWAIT, 1, MT_DATA);
1974                 if (SCTP_BUF_NEXT(mret) == NULL) {
1975                         /* We are hosed, can't add more addresses */
1976                         return (m);
1977                 }
1978                 mret = SCTP_BUF_NEXT(mret);
1979                 parmh = mtod(mret, struct sctp_paramhdr *);
1980         }
1981         /* now add the parameter */
1982         switch (ifa->address.sa.sa_family) {
1983 #ifdef INET
1984         case AF_INET:
1985                 {
1986                         struct sctp_ipv4addr_param *ipv4p;
1987                         struct sockaddr_in *sin;
1988
1989                         sin = (struct sockaddr_in *)&ifa->address.sin;
1990                         ipv4p = (struct sctp_ipv4addr_param *)parmh;
1991                         parmh->param_type = htons(SCTP_IPV4_ADDRESS);
1992                         parmh->param_length = htons(plen);
1993                         ipv4p->addr = sin->sin_addr.s_addr;
1994                         SCTP_BUF_LEN(mret) += plen;
1995                         break;
1996                 }
1997 #endif
1998 #ifdef INET6
1999         case AF_INET6:
2000                 {
2001                         struct sctp_ipv6addr_param *ipv6p;
2002                         struct sockaddr_in6 *sin6;
2003
2004                         sin6 = (struct sockaddr_in6 *)&ifa->address.sin6;
2005                         ipv6p = (struct sctp_ipv6addr_param *)parmh;
2006                         parmh->param_type = htons(SCTP_IPV6_ADDRESS);
2007                         parmh->param_length = htons(plen);
2008                         memcpy(ipv6p->addr, &sin6->sin6_addr,
2009                             sizeof(ipv6p->addr));
2010                         /* clear embedded scope in the address */
2011                         in6_clearscope((struct in6_addr *)ipv6p->addr);
2012                         SCTP_BUF_LEN(mret) += plen;
2013                         break;
2014                 }
2015 #endif
2016         default:
2017                 return (m);
2018         }
2019         if (len != NULL) {
2020                 *len += plen;
2021         }
2022         return (mret);
2023 }
2024
2025
2026 struct mbuf *
2027 sctp_add_addresses_to_i_ia(struct sctp_inpcb *inp, struct sctp_tcb *stcb,
2028     struct sctp_scoping *scope,
2029     struct mbuf *m_at, int cnt_inits_to,
2030     uint16_t * padding_len, uint16_t * chunk_len)
2031 {
2032         struct sctp_vrf *vrf = NULL;
2033         int cnt, limit_out = 0, total_count;
2034         uint32_t vrf_id;
2035
2036         vrf_id = inp->def_vrf_id;
2037         SCTP_IPI_ADDR_RLOCK();
2038         vrf = sctp_find_vrf(vrf_id);
2039         if (vrf == NULL) {
2040                 SCTP_IPI_ADDR_RUNLOCK();
2041                 return (m_at);
2042         }
2043         if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
2044                 struct sctp_ifa *sctp_ifap;
2045                 struct sctp_ifn *sctp_ifnp;
2046
2047                 cnt = cnt_inits_to;
2048                 if (vrf->total_ifa_count > SCTP_COUNT_LIMIT) {
2049                         limit_out = 1;
2050                         cnt = SCTP_ADDRESS_LIMIT;
2051                         goto skip_count;
2052                 }
2053                 LIST_FOREACH(sctp_ifnp, &vrf->ifnlist, next_ifn) {
2054                         if ((scope->loopback_scope == 0) &&
2055                             SCTP_IFN_IS_IFT_LOOP(sctp_ifnp)) {
2056                                 /*
2057                                  * Skip loopback devices if loopback_scope
2058                                  * not set
2059                                  */
2060                                 continue;
2061                         }
2062                         LIST_FOREACH(sctp_ifap, &sctp_ifnp->ifalist, next_ifa) {
2063                                 if (sctp_is_addr_restricted(stcb, sctp_ifap)) {
2064                                         continue;
2065                                 }
2066                                 if (sctp_is_address_in_scope(sctp_ifap,
2067                                     scope->ipv4_addr_legal,
2068                                     scope->ipv6_addr_legal,
2069                                     scope->loopback_scope,
2070                                     scope->ipv4_local_scope,
2071                                     scope->local_scope,
2072                                     scope->site_scope, 1) == 0) {
2073                                         continue;
2074                                 }
2075                                 cnt++;
2076                                 if (cnt > SCTP_ADDRESS_LIMIT) {
2077                                         break;
2078                                 }
2079                         }
2080                         if (cnt > SCTP_ADDRESS_LIMIT) {
2081                                 break;
2082                         }
2083                 }
2084 skip_count:
2085                 if (cnt > 1) {
2086                         total_count = 0;
2087                         LIST_FOREACH(sctp_ifnp, &vrf->ifnlist, next_ifn) {
2088                                 cnt = 0;
2089                                 if ((scope->loopback_scope == 0) &&
2090                                     SCTP_IFN_IS_IFT_LOOP(sctp_ifnp)) {
2091                                         /*
2092                                          * Skip loopback devices if
2093                                          * loopback_scope not set
2094                                          */
2095                                         continue;
2096                                 }
2097                                 LIST_FOREACH(sctp_ifap, &sctp_ifnp->ifalist, next_ifa) {
2098                                         if (sctp_is_addr_restricted(stcb, sctp_ifap)) {
2099                                                 continue;
2100                                         }
2101                                         if (sctp_is_address_in_scope(sctp_ifap,
2102                                             scope->ipv4_addr_legal,
2103                                             scope->ipv6_addr_legal,
2104                                             scope->loopback_scope,
2105                                             scope->ipv4_local_scope,
2106                                             scope->local_scope,
2107                                             scope->site_scope, 0) == 0) {
2108                                                 continue;
2109                                         }
2110                                         if ((chunk_len != NULL) &&
2111                                             (padding_len != NULL) &&
2112                                             (*padding_len > 0)) {
2113                                                 memset(mtod(m_at, caddr_t)+*chunk_len, 0, *padding_len);
2114                                                 SCTP_BUF_LEN(m_at) += *padding_len;
2115                                                 *chunk_len += *padding_len;
2116                                                 *padding_len = 0;
2117                                         }
2118                                         m_at = sctp_add_addr_to_mbuf(m_at, sctp_ifap, chunk_len);
2119                                         if (limit_out) {
2120                                                 cnt++;
2121                                                 total_count++;
2122                                                 if (cnt >= 2) {
2123                                                         /*
2124                                                          * two from each
2125                                                          * address
2126                                                          */
2127                                                         break;
2128                                                 }
2129                                                 if (total_count > SCTP_ADDRESS_LIMIT) {
2130                                                         /* No more addresses */
2131                                                         break;
2132                                                 }
2133                                         }
2134                                 }
2135                         }
2136                 }
2137         } else {
2138                 struct sctp_laddr *laddr;
2139
2140                 cnt = cnt_inits_to;
2141                 /* First, how many ? */
2142                 LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
2143                         if (laddr->ifa == NULL) {
2144                                 continue;
2145                         }
2146                         if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED)
2147                                 /*
2148                                  * Address being deleted by the system, dont
2149                                  * list.
2150                                  */
2151                                 continue;
2152                         if (laddr->action == SCTP_DEL_IP_ADDRESS) {
2153                                 /*
2154                                  * Address being deleted on this ep don't
2155                                  * list.
2156                                  */
2157                                 continue;
2158                         }
2159                         if (sctp_is_address_in_scope(laddr->ifa,
2160                             scope->ipv4_addr_legal,
2161                             scope->ipv6_addr_legal,
2162                             scope->loopback_scope,
2163                             scope->ipv4_local_scope,
2164                             scope->local_scope,
2165                             scope->site_scope, 1) == 0) {
2166                                 continue;
2167                         }
2168                         cnt++;
2169                 }
2170                 /*
2171                  * To get through a NAT we only list addresses if we have
2172                  * more than one. That way if you just bind a single address
2173                  * we let the source of the init dictate our address.
2174                  */
2175                 if (cnt > 1) {
2176                         cnt = cnt_inits_to;
2177                         LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
2178                                 if (laddr->ifa == NULL) {
2179                                         continue;
2180                                 }
2181                                 if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED) {
2182                                         continue;
2183                                 }
2184                                 if (sctp_is_address_in_scope(laddr->ifa,
2185                                     scope->ipv4_addr_legal,
2186                                     scope->ipv6_addr_legal,
2187                                     scope->loopback_scope,
2188                                     scope->ipv4_local_scope,
2189                                     scope->local_scope,
2190                                     scope->site_scope, 0) == 0) {
2191                                         continue;
2192                                 }
2193                                 if ((chunk_len != NULL) &&
2194                                     (padding_len != NULL) &&
2195                                     (*padding_len > 0)) {
2196                                         memset(mtod(m_at, caddr_t)+*chunk_len, 0, *padding_len);
2197                                         SCTP_BUF_LEN(m_at) += *padding_len;
2198                                         *chunk_len += *padding_len;
2199                                         *padding_len = 0;
2200                                 }
2201                                 m_at = sctp_add_addr_to_mbuf(m_at, laddr->ifa, chunk_len);
2202                                 cnt++;
2203                                 if (cnt >= SCTP_ADDRESS_LIMIT) {
2204                                         break;
2205                                 }
2206                         }
2207                 }
2208         }
2209         SCTP_IPI_ADDR_RUNLOCK();
2210         return (m_at);
2211 }
2212
2213 static struct sctp_ifa *
2214 sctp_is_ifa_addr_preferred(struct sctp_ifa *ifa,
2215     uint8_t dest_is_loop,
2216     uint8_t dest_is_priv,
2217     sa_family_t fam)
2218 {
2219         uint8_t dest_is_global = 0;
2220
2221         /* dest_is_priv is true if destination is a private address */
2222         /* dest_is_loop is true if destination is a loopback addresses */
2223
2224         /**
2225          * Here we determine if its a preferred address. A preferred address
2226          * means it is the same scope or higher scope then the destination.
2227          * L = loopback, P = private, G = global
2228          * -----------------------------------------
2229          *    src    |  dest | result
2230          *  ----------------------------------------
2231          *     L     |    L  |    yes
2232          *  -----------------------------------------
2233          *     P     |    L  |    yes-v4 no-v6
2234          *  -----------------------------------------
2235          *     G     |    L  |    yes-v4 no-v6
2236          *  -----------------------------------------
2237          *     L     |    P  |    no
2238          *  -----------------------------------------
2239          *     P     |    P  |    yes
2240          *  -----------------------------------------
2241          *     G     |    P  |    no
2242          *   -----------------------------------------
2243          *     L     |    G  |    no
2244          *   -----------------------------------------
2245          *     P     |    G  |    no
2246          *    -----------------------------------------
2247          *     G     |    G  |    yes
2248          *    -----------------------------------------
2249          */
2250
2251         if (ifa->address.sa.sa_family != fam) {
2252                 /* forget mis-matched family */
2253                 return (NULL);
2254         }
2255         if ((dest_is_priv == 0) && (dest_is_loop == 0)) {
2256                 dest_is_global = 1;
2257         }
2258         SCTPDBG(SCTP_DEBUG_OUTPUT2, "Is destination preferred:");
2259         SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, &ifa->address.sa);
2260         /* Ok the address may be ok */
2261 #ifdef INET6
2262         if (fam == AF_INET6) {
2263                 /* ok to use deprecated addresses? no lets not! */
2264                 if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
2265                         SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:1\n");
2266                         return (NULL);
2267                 }
2268                 if (ifa->src_is_priv && !ifa->src_is_loop) {
2269                         if (dest_is_loop) {
2270                                 SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:2\n");
2271                                 return (NULL);
2272                         }
2273                 }
2274                 if (ifa->src_is_glob) {
2275                         if (dest_is_loop) {
2276                                 SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:3\n");
2277                                 return (NULL);
2278                         }
2279                 }
2280         }
2281 #endif
2282         /*
2283          * Now that we know what is what, implement or table this could in
2284          * theory be done slicker (it used to be), but this is
2285          * straightforward and easier to validate :-)
2286          */
2287         SCTPDBG(SCTP_DEBUG_OUTPUT3, "src_loop:%d src_priv:%d src_glob:%d\n",
2288             ifa->src_is_loop, ifa->src_is_priv, ifa->src_is_glob);
2289         SCTPDBG(SCTP_DEBUG_OUTPUT3, "dest_loop:%d dest_priv:%d dest_glob:%d\n",
2290             dest_is_loop, dest_is_priv, dest_is_global);
2291
2292         if ((ifa->src_is_loop) && (dest_is_priv)) {
2293                 SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:4\n");
2294                 return (NULL);
2295         }
2296         if ((ifa->src_is_glob) && (dest_is_priv)) {
2297                 SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:5\n");
2298                 return (NULL);
2299         }
2300         if ((ifa->src_is_loop) && (dest_is_global)) {
2301                 SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:6\n");
2302                 return (NULL);
2303         }
2304         if ((ifa->src_is_priv) && (dest_is_global)) {
2305                 SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:7\n");
2306                 return (NULL);
2307         }
2308         SCTPDBG(SCTP_DEBUG_OUTPUT3, "YES\n");
2309         /* its a preferred address */
2310         return (ifa);
2311 }
2312
2313 static struct sctp_ifa *
2314 sctp_is_ifa_addr_acceptable(struct sctp_ifa *ifa,
2315     uint8_t dest_is_loop,
2316     uint8_t dest_is_priv,
2317     sa_family_t fam)
2318 {
2319         uint8_t dest_is_global = 0;
2320
2321         /**
2322          * Here we determine if its a acceptable address. A acceptable
2323          * address means it is the same scope or higher scope but we can
2324          * allow for NAT which means its ok to have a global dest and a
2325          * private src.
2326          *
2327          * L = loopback, P = private, G = global
2328          * -----------------------------------------
2329          *  src    |  dest | result
2330          * -----------------------------------------
2331          *   L     |   L   |    yes
2332          *  -----------------------------------------
2333          *   P     |   L   |    yes-v4 no-v6
2334          *  -----------------------------------------
2335          *   G     |   L   |    yes
2336          * -----------------------------------------
2337          *   L     |   P   |    no
2338          * -----------------------------------------
2339          *   P     |   P   |    yes
2340          * -----------------------------------------
2341          *   G     |   P   |    yes - May not work
2342          * -----------------------------------------
2343          *   L     |   G   |    no
2344          * -----------------------------------------
2345          *   P     |   G   |    yes - May not work
2346          * -----------------------------------------
2347          *   G     |   G   |    yes
2348          * -----------------------------------------
2349          */
2350
2351         if (ifa->address.sa.sa_family != fam) {
2352                 /* forget non matching family */
2353                 SCTPDBG(SCTP_DEBUG_OUTPUT3, "ifa_fam:%d fam:%d\n",
2354                     ifa->address.sa.sa_family, fam);
2355                 return (NULL);
2356         }
2357         /* Ok the address may be ok */
2358         SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT3, &ifa->address.sa);
2359         SCTPDBG(SCTP_DEBUG_OUTPUT3, "dst_is_loop:%d dest_is_priv:%d\n",
2360             dest_is_loop, dest_is_priv);
2361         if ((dest_is_loop == 0) && (dest_is_priv == 0)) {
2362                 dest_is_global = 1;
2363         }
2364 #ifdef INET6
2365         if (fam == AF_INET6) {
2366                 /* ok to use deprecated addresses? */
2367                 if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
2368                         return (NULL);
2369                 }
2370                 if (ifa->src_is_priv) {
2371                         /* Special case, linklocal to loop */
2372                         if (dest_is_loop)
2373                                 return (NULL);
2374                 }
2375         }
2376 #endif
2377         /*
2378          * Now that we know what is what, implement our table. This could in
2379          * theory be done slicker (it used to be), but this is
2380          * straightforward and easier to validate :-)
2381          */
2382         SCTPDBG(SCTP_DEBUG_OUTPUT3, "ifa->src_is_loop:%d dest_is_priv:%d\n",
2383             ifa->src_is_loop,
2384             dest_is_priv);
2385         if ((ifa->src_is_loop == 1) && (dest_is_priv)) {
2386                 return (NULL);
2387         }
2388         SCTPDBG(SCTP_DEBUG_OUTPUT3, "ifa->src_is_loop:%d dest_is_glob:%d\n",
2389             ifa->src_is_loop,
2390             dest_is_global);
2391         if ((ifa->src_is_loop == 1) && (dest_is_global)) {
2392                 return (NULL);
2393         }
2394         SCTPDBG(SCTP_DEBUG_OUTPUT3, "address is acceptable\n");
2395         /* its an acceptable address */
2396         return (ifa);
2397 }
2398
2399 int
2400 sctp_is_addr_restricted(struct sctp_tcb *stcb, struct sctp_ifa *ifa)
2401 {
2402         struct sctp_laddr *laddr;
2403
2404         if (stcb == NULL) {
2405                 /* There are no restrictions, no TCB :-) */
2406                 return (0);
2407         }
2408         LIST_FOREACH(laddr, &stcb->asoc.sctp_restricted_addrs, sctp_nxt_addr) {
2409                 if (laddr->ifa == NULL) {
2410                         SCTPDBG(SCTP_DEBUG_OUTPUT1, "%s: NULL ifa\n",
2411                             __FUNCTION__);
2412                         continue;
2413                 }
2414                 if (laddr->ifa == ifa) {
2415                         /* Yes it is on the list */
2416                         return (1);
2417                 }
2418         }
2419         return (0);
2420 }
2421
2422
2423 int
2424 sctp_is_addr_in_ep(struct sctp_inpcb *inp, struct sctp_ifa *ifa)
2425 {
2426         struct sctp_laddr *laddr;
2427
2428         if (ifa == NULL)
2429                 return (0);
2430         LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
2431                 if (laddr->ifa == NULL) {
2432                         SCTPDBG(SCTP_DEBUG_OUTPUT1, "%s: NULL ifa\n",
2433                             __FUNCTION__);
2434                         continue;
2435                 }
2436                 if ((laddr->ifa == ifa) && laddr->action == 0)
2437                         /* same pointer */
2438                         return (1);
2439         }
2440         return (0);
2441 }
2442
2443
2444
2445 static struct sctp_ifa *
2446 sctp_choose_boundspecific_inp(struct sctp_inpcb *inp,
2447     sctp_route_t * ro,
2448     uint32_t vrf_id,
2449     int non_asoc_addr_ok,
2450     uint8_t dest_is_priv,
2451     uint8_t dest_is_loop,
2452     sa_family_t fam)
2453 {
2454         struct sctp_laddr *laddr, *starting_point;
2455         void *ifn;
2456         int resettotop = 0;
2457         struct sctp_ifn *sctp_ifn;
2458         struct sctp_ifa *sctp_ifa, *sifa;
2459         struct sctp_vrf *vrf;
2460         uint32_t ifn_index;
2461
2462         vrf = sctp_find_vrf(vrf_id);
2463         if (vrf == NULL)
2464                 return (NULL);
2465
2466         ifn = SCTP_GET_IFN_VOID_FROM_ROUTE(ro);
2467         ifn_index = SCTP_GET_IF_INDEX_FROM_ROUTE(ro);
2468         sctp_ifn = sctp_find_ifn(ifn, ifn_index);
2469         /*
2470          * first question, is the ifn we will emit on in our list, if so, we
2471          * want such an address. Note that we first looked for a preferred
2472          * address.
2473          */
2474         if (sctp_ifn) {
2475                 /* is a preferred one on the interface we route out? */
2476                 LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
2477                         if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
2478                             (non_asoc_addr_ok == 0))
2479                                 continue;
2480                         sifa = sctp_is_ifa_addr_preferred(sctp_ifa,
2481                             dest_is_loop,
2482                             dest_is_priv, fam);
2483                         if (sifa == NULL)
2484                                 continue;
2485                         if (sctp_is_addr_in_ep(inp, sifa)) {
2486                                 atomic_add_int(&sifa->refcount, 1);
2487                                 return (sifa);
2488                         }
2489                 }
2490         }
2491         /*
2492          * ok, now we now need to find one on the list of the addresses. We
2493          * can't get one on the emitting interface so let's find first a
2494          * preferred one. If not that an acceptable one otherwise... we
2495          * return NULL.
2496          */
2497         starting_point = inp->next_addr_touse;
2498 once_again:
2499         if (inp->next_addr_touse == NULL) {
2500                 inp->next_addr_touse = LIST_FIRST(&inp->sctp_addr_list);
2501                 resettotop = 1;
2502         }
2503         for (laddr = inp->next_addr_touse; laddr;
2504             laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
2505                 if (laddr->ifa == NULL) {
2506                         /* address has been removed */
2507                         continue;
2508                 }
2509                 if (laddr->action == SCTP_DEL_IP_ADDRESS) {
2510                         /* address is being deleted */
2511                         continue;
2512                 }
2513                 sifa = sctp_is_ifa_addr_preferred(laddr->ifa, dest_is_loop,
2514                     dest_is_priv, fam);
2515                 if (sifa == NULL)
2516                         continue;
2517                 atomic_add_int(&sifa->refcount, 1);
2518                 return (sifa);
2519         }
2520         if (resettotop == 0) {
2521                 inp->next_addr_touse = NULL;
2522                 goto once_again;
2523         }
2524         inp->next_addr_touse = starting_point;
2525         resettotop = 0;
2526 once_again_too:
2527         if (inp->next_addr_touse == NULL) {
2528                 inp->next_addr_touse = LIST_FIRST(&inp->sctp_addr_list);
2529                 resettotop = 1;
2530         }
2531         /* ok, what about an acceptable address in the inp */
2532         for (laddr = inp->next_addr_touse; laddr;
2533             laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
2534                 if (laddr->ifa == NULL) {
2535                         /* address has been removed */
2536                         continue;
2537                 }
2538                 if (laddr->action == SCTP_DEL_IP_ADDRESS) {
2539                         /* address is being deleted */
2540                         continue;
2541                 }
2542                 sifa = sctp_is_ifa_addr_acceptable(laddr->ifa, dest_is_loop,
2543                     dest_is_priv, fam);
2544                 if (sifa == NULL)
2545                         continue;
2546                 atomic_add_int(&sifa->refcount, 1);
2547                 return (sifa);
2548         }
2549         if (resettotop == 0) {
2550                 inp->next_addr_touse = NULL;
2551                 goto once_again_too;
2552         }
2553         /*
2554          * no address bound can be a source for the destination we are in
2555          * trouble
2556          */
2557         return (NULL);
2558 }
2559
2560
2561
2562 static struct sctp_ifa *
2563 sctp_choose_boundspecific_stcb(struct sctp_inpcb *inp,
2564     struct sctp_tcb *stcb,
2565     sctp_route_t * ro,
2566     uint32_t vrf_id,
2567     uint8_t dest_is_priv,
2568     uint8_t dest_is_loop,
2569     int non_asoc_addr_ok,
2570     sa_family_t fam)
2571 {
2572         struct sctp_laddr *laddr, *starting_point;
2573         void *ifn;
2574         struct sctp_ifn *sctp_ifn;
2575         struct sctp_ifa *sctp_ifa, *sifa;
2576         uint8_t start_at_beginning = 0;
2577         struct sctp_vrf *vrf;
2578         uint32_t ifn_index;
2579
2580         /*
2581          * first question, is the ifn we will emit on in our list, if so, we
2582          * want that one.
2583          */
2584         vrf = sctp_find_vrf(vrf_id);
2585         if (vrf == NULL)
2586                 return (NULL);
2587
2588         ifn = SCTP_GET_IFN_VOID_FROM_ROUTE(ro);
2589         ifn_index = SCTP_GET_IF_INDEX_FROM_ROUTE(ro);
2590         sctp_ifn = sctp_find_ifn(ifn, ifn_index);
2591
2592         /*
2593          * first question, is the ifn we will emit on in our list?  If so,
2594          * we want that one. First we look for a preferred. Second, we go
2595          * for an acceptable.
2596          */
2597         if (sctp_ifn) {
2598                 /* first try for a preferred address on the ep */
2599                 LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
2600                         if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) && (non_asoc_addr_ok == 0))
2601                                 continue;
2602                         if (sctp_is_addr_in_ep(inp, sctp_ifa)) {
2603                                 sifa = sctp_is_ifa_addr_preferred(sctp_ifa, dest_is_loop, dest_is_priv, fam);
2604                                 if (sifa == NULL)
2605                                         continue;
2606                                 if (((non_asoc_addr_ok == 0) &&
2607                                     (sctp_is_addr_restricted(stcb, sifa))) ||
2608                                     (non_asoc_addr_ok &&
2609                                     (sctp_is_addr_restricted(stcb, sifa)) &&
2610                                     (!sctp_is_addr_pending(stcb, sifa)))) {
2611                                         /* on the no-no list */
2612                                         continue;
2613                                 }
2614                                 atomic_add_int(&sifa->refcount, 1);
2615                                 return (sifa);
2616                         }
2617                 }
2618                 /* next try for an acceptable address on the ep */
2619                 LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
2620                         if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) && (non_asoc_addr_ok == 0))
2621                                 continue;
2622                         if (sctp_is_addr_in_ep(inp, sctp_ifa)) {
2623                                 sifa = sctp_is_ifa_addr_acceptable(sctp_ifa, dest_is_loop, dest_is_priv, fam);
2624                                 if (sifa == NULL)
2625                                         continue;
2626                                 if (((non_asoc_addr_ok == 0) &&
2627                                     (sctp_is_addr_restricted(stcb, sifa))) ||
2628                                     (non_asoc_addr_ok &&
2629                                     (sctp_is_addr_restricted(stcb, sifa)) &&
2630                                     (!sctp_is_addr_pending(stcb, sifa)))) {
2631                                         /* on the no-no list */
2632                                         continue;
2633                                 }
2634                                 atomic_add_int(&sifa->refcount, 1);
2635                                 return (sifa);
2636                         }
2637                 }
2638
2639         }
2640         /*
2641          * if we can't find one like that then we must look at all addresses
2642          * bound to pick one at first preferable then secondly acceptable.
2643          */
2644         starting_point = stcb->asoc.last_used_address;
2645 sctp_from_the_top:
2646         if (stcb->asoc.last_used_address == NULL) {
2647                 start_at_beginning = 1;
2648                 stcb->asoc.last_used_address = LIST_FIRST(&inp->sctp_addr_list);
2649         }
2650         /* search beginning with the last used address */
2651         for (laddr = stcb->asoc.last_used_address; laddr;
2652             laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
2653                 if (laddr->ifa == NULL) {
2654                         /* address has been removed */
2655                         continue;
2656                 }
2657                 if (laddr->action == SCTP_DEL_IP_ADDRESS) {
2658                         /* address is being deleted */
2659                         continue;
2660                 }
2661                 sifa = sctp_is_ifa_addr_preferred(laddr->ifa, dest_is_loop, dest_is_priv, fam);
2662                 if (sifa == NULL)
2663                         continue;
2664                 if (((non_asoc_addr_ok == 0) &&
2665                     (sctp_is_addr_restricted(stcb, sifa))) ||
2666                     (non_asoc_addr_ok &&
2667                     (sctp_is_addr_restricted(stcb, sifa)) &&
2668                     (!sctp_is_addr_pending(stcb, sifa)))) {
2669                         /* on the no-no list */
2670                         continue;
2671                 }
2672                 stcb->asoc.last_used_address = laddr;
2673                 atomic_add_int(&sifa->refcount, 1);
2674                 return (sifa);
2675         }
2676         if (start_at_beginning == 0) {
2677                 stcb->asoc.last_used_address = NULL;
2678                 goto sctp_from_the_top;
2679         }
2680         /* now try for any higher scope than the destination */
2681         stcb->asoc.last_used_address = starting_point;
2682         start_at_beginning = 0;
2683 sctp_from_the_top2:
2684         if (stcb->asoc.last_used_address == NULL) {
2685                 start_at_beginning = 1;
2686                 stcb->asoc.last_used_address = LIST_FIRST(&inp->sctp_addr_list);
2687         }
2688         /* search beginning with the last used address */
2689         for (laddr = stcb->asoc.last_used_address; laddr;
2690             laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
2691                 if (laddr->ifa == NULL) {
2692                         /* address has been removed */
2693                         continue;
2694                 }
2695                 if (laddr->action == SCTP_DEL_IP_ADDRESS) {
2696                         /* address is being deleted */
2697                         continue;
2698                 }
2699                 sifa = sctp_is_ifa_addr_acceptable(laddr->ifa, dest_is_loop,
2700                     dest_is_priv, fam);
2701                 if (sifa == NULL)
2702                         continue;
2703                 if (((non_asoc_addr_ok == 0) &&
2704                     (sctp_is_addr_restricted(stcb, sifa))) ||
2705                     (non_asoc_addr_ok &&
2706                     (sctp_is_addr_restricted(stcb, sifa)) &&
2707                     (!sctp_is_addr_pending(stcb, sifa)))) {
2708                         /* on the no-no list */
2709                         continue;
2710                 }
2711                 stcb->asoc.last_used_address = laddr;
2712                 atomic_add_int(&sifa->refcount, 1);
2713                 return (sifa);
2714         }
2715         if (start_at_beginning == 0) {
2716                 stcb->asoc.last_used_address = NULL;
2717                 goto sctp_from_the_top2;
2718         }
2719         return (NULL);
2720 }
2721
2722 static struct sctp_ifa *
2723 sctp_select_nth_preferred_addr_from_ifn_boundall(struct sctp_ifn *ifn,
2724     struct sctp_tcb *stcb,
2725     int non_asoc_addr_ok,
2726     uint8_t dest_is_loop,
2727     uint8_t dest_is_priv,
2728     int addr_wanted,
2729     sa_family_t fam,
2730     sctp_route_t * ro
2731 )
2732 {
2733         struct sctp_ifa *ifa, *sifa;
2734         int num_eligible_addr = 0;
2735
2736 #ifdef INET6
2737         struct sockaddr_in6 sin6, lsa6;
2738
2739         if (fam == AF_INET6) {
2740                 memcpy(&sin6, &ro->ro_dst, sizeof(struct sockaddr_in6));
2741                 (void)sa6_recoverscope(&sin6);
2742         }
2743 #endif                          /* INET6 */
2744         LIST_FOREACH(ifa, &ifn->ifalist, next_ifa) {
2745                 if ((ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
2746                     (non_asoc_addr_ok == 0))
2747                         continue;
2748                 sifa = sctp_is_ifa_addr_preferred(ifa, dest_is_loop,
2749                     dest_is_priv, fam);
2750                 if (sifa == NULL)
2751                         continue;
2752 #ifdef INET6
2753                 if (fam == AF_INET6 &&
2754                     dest_is_loop &&
2755                     sifa->src_is_loop && sifa->src_is_priv) {
2756                         /*
2757                          * don't allow fe80::1 to be a src on loop ::1, we
2758                          * don't list it to the peer so we will get an
2759                          * abort.
2760                          */
2761                         continue;
2762                 }
2763                 if (fam == AF_INET6 &&
2764                     IN6_IS_ADDR_LINKLOCAL(&sifa->address.sin6.sin6_addr) &&
2765                     IN6_IS_ADDR_LINKLOCAL(&sin6.sin6_addr)) {
2766                         /*
2767                          * link-local <-> link-local must belong to the same
2768                          * scope.
2769                          */
2770                         memcpy(&lsa6, &sifa->address.sin6, sizeof(struct sockaddr_in6));
2771                         (void)sa6_recoverscope(&lsa6);
2772                         if (sin6.sin6_scope_id != lsa6.sin6_scope_id) {
2773                                 continue;
2774                         }
2775                 }
2776 #endif                          /* INET6 */
2777
2778                 /*
2779                  * Check if the IPv6 address matches to next-hop. In the
2780                  * mobile case, old IPv6 address may be not deleted from the
2781                  * interface. Then, the interface has previous and new
2782                  * addresses.  We should use one corresponding to the
2783                  * next-hop.  (by micchie)
2784                  */
2785 #ifdef INET6
2786                 if (stcb && fam == AF_INET6 &&
2787                     sctp_is_mobility_feature_on(stcb->sctp_ep, SCTP_MOBILITY_BASE)) {
2788                         if (sctp_v6src_match_nexthop(&sifa->address.sin6, ro)
2789                             == 0) {
2790                                 continue;
2791                         }
2792                 }
2793 #endif
2794 #ifdef INET
2795                 /* Avoid topologically incorrect IPv4 address */
2796                 if (stcb && fam == AF_INET &&
2797                     sctp_is_mobility_feature_on(stcb->sctp_ep, SCTP_MOBILITY_BASE)) {
2798                         if (sctp_v4src_match_nexthop(sifa, ro) == 0) {
2799                                 continue;
2800                         }
2801                 }
2802 #endif
2803                 if (stcb) {
2804                         if (sctp_is_address_in_scope(ifa,
2805                             stcb->asoc.ipv4_addr_legal,
2806                             stcb->asoc.ipv6_addr_legal,
2807                             stcb->asoc.loopback_scope,
2808                             stcb->asoc.ipv4_local_scope,
2809                             stcb->asoc.local_scope,
2810                             stcb->asoc.site_scope, 0) == 0) {
2811                                 continue;
2812                         }
2813                         if (((non_asoc_addr_ok == 0) &&
2814                             (sctp_is_addr_restricted(stcb, sifa))) ||
2815                             (non_asoc_addr_ok &&
2816                             (sctp_is_addr_restricted(stcb, sifa)) &&
2817                             (!sctp_is_addr_pending(stcb, sifa)))) {
2818                                 /*
2819                                  * It is restricted for some reason..
2820                                  * probably not yet added.
2821                                  */
2822                                 continue;
2823                         }
2824                 }
2825                 if (num_eligible_addr >= addr_wanted) {
2826                         return (sifa);
2827                 }
2828                 num_eligible_addr++;
2829         }
2830         return (NULL);
2831 }
2832
2833
2834 static int
2835 sctp_count_num_preferred_boundall(struct sctp_ifn *ifn,
2836     struct sctp_tcb *stcb,
2837     int non_asoc_addr_ok,
2838     uint8_t dest_is_loop,
2839     uint8_t dest_is_priv,
2840     sa_family_t fam)
2841 {
2842         struct sctp_ifa *ifa, *sifa;
2843         int num_eligible_addr = 0;
2844
2845         LIST_FOREACH(ifa, &ifn->ifalist, next_ifa) {
2846                 if ((ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
2847                     (non_asoc_addr_ok == 0)) {
2848                         continue;
2849                 }
2850                 sifa = sctp_is_ifa_addr_preferred(ifa, dest_is_loop,
2851                     dest_is_priv, fam);
2852                 if (sifa == NULL) {
2853                         continue;
2854                 }
2855                 if (stcb) {
2856                         if (sctp_is_address_in_scope(ifa,
2857                             stcb->asoc.ipv4_addr_legal,
2858                             stcb->asoc.ipv6_addr_legal,
2859                             stcb->asoc.loopback_scope,
2860                             stcb->asoc.ipv4_local_scope,
2861                             stcb->asoc.local_scope,
2862                             stcb->asoc.site_scope, 0) == 0) {
2863                                 continue;
2864                         }
2865                         if (((non_asoc_addr_ok == 0) &&
2866                             (sctp_is_addr_restricted(stcb, sifa))) ||
2867                             (non_asoc_addr_ok &&
2868                             (sctp_is_addr_restricted(stcb, sifa)) &&
2869                             (!sctp_is_addr_pending(stcb, sifa)))) {
2870                                 /*
2871                                  * It is restricted for some reason..
2872                                  * probably not yet added.
2873                                  */
2874                                 continue;
2875                         }
2876                 }
2877                 num_eligible_addr++;
2878         }
2879         return (num_eligible_addr);
2880 }
2881
2882 static struct sctp_ifa *
2883 sctp_choose_boundall(struct sctp_tcb *stcb,
2884     struct sctp_nets *net,
2885     sctp_route_t * ro,
2886     uint32_t vrf_id,
2887     uint8_t dest_is_priv,
2888     uint8_t dest_is_loop,
2889     int non_asoc_addr_ok,
2890     sa_family_t fam)
2891 {
2892         int cur_addr_num = 0, num_preferred = 0;
2893         void *ifn;
2894         struct sctp_ifn *sctp_ifn, *looked_at = NULL, *emit_ifn;
2895         struct sctp_ifa *sctp_ifa, *sifa;
2896         uint32_t ifn_index;
2897         struct sctp_vrf *vrf;
2898
2899 #ifdef INET
2900         int retried = 0;
2901
2902 #endif
2903
2904         /*-
2905          * For boundall we can use any address in the association.
2906          * If non_asoc_addr_ok is set we can use any address (at least in
2907          * theory). So we look for preferred addresses first. If we find one,
2908          * we use it. Otherwise we next try to get an address on the
2909          * interface, which we should be able to do (unless non_asoc_addr_ok
2910          * is false and we are routed out that way). In these cases where we
2911          * can't use the address of the interface we go through all the
2912          * ifn's looking for an address we can use and fill that in. Punting
2913          * means we send back address 0, which will probably cause problems
2914          * actually since then IP will fill in the address of the route ifn,
2915          * which means we probably already rejected it.. i.e. here comes an
2916          * abort :-<.
2917          */
2918         vrf = sctp_find_vrf(vrf_id);
2919         if (vrf == NULL)
2920                 return (NULL);
2921
2922         ifn = SCTP_GET_IFN_VOID_FROM_ROUTE(ro);
2923         ifn_index = SCTP_GET_IF_INDEX_FROM_ROUTE(ro);
2924         SCTPDBG(SCTP_DEBUG_OUTPUT2, "ifn from route:%p ifn_index:%d\n", ifn, ifn_index);
2925         emit_ifn = looked_at = sctp_ifn = sctp_find_ifn(ifn, ifn_index);
2926         if (sctp_ifn == NULL) {
2927                 /* ?? We don't have this guy ?? */
2928                 SCTPDBG(SCTP_DEBUG_OUTPUT2, "No ifn emit interface?\n");
2929                 goto bound_all_plan_b;
2930         }
2931         SCTPDBG(SCTP_DEBUG_OUTPUT2, "ifn_index:%d name:%s is emit interface\n",
2932             ifn_index, sctp_ifn->ifn_name);
2933
2934         if (net) {
2935                 cur_addr_num = net->indx_of_eligible_next_to_use;
2936         }
2937         num_preferred = sctp_count_num_preferred_boundall(sctp_ifn,
2938             stcb,
2939             non_asoc_addr_ok,
2940             dest_is_loop,
2941             dest_is_priv, fam);
2942         SCTPDBG(SCTP_DEBUG_OUTPUT2, "Found %d preferred source addresses for intf:%s\n",
2943             num_preferred, sctp_ifn->ifn_name);
2944         if (num_preferred == 0) {
2945                 /*
2946                  * no eligible addresses, we must use some other interface
2947                  * address if we can find one.
2948                  */
2949                 goto bound_all_plan_b;
2950         }
2951         /*
2952          * Ok we have num_eligible_addr set with how many we can use, this
2953          * may vary from call to call due to addresses being deprecated
2954          * etc..
2955          */
2956         if (cur_addr_num >= num_preferred) {
2957                 cur_addr_num = 0;
2958         }
2959         /*
2960          * select the nth address from the list (where cur_addr_num is the
2961          * nth) and 0 is the first one, 1 is the second one etc...
2962          */
2963         SCTPDBG(SCTP_DEBUG_OUTPUT2, "cur_addr_num:%d\n", cur_addr_num);
2964
2965         sctp_ifa = sctp_select_nth_preferred_addr_from_ifn_boundall(sctp_ifn, stcb, non_asoc_addr_ok, dest_is_loop,
2966             dest_is_priv, cur_addr_num, fam, ro);
2967
2968         /* if sctp_ifa is NULL something changed??, fall to plan b. */
2969         if (sctp_ifa) {
2970                 atomic_add_int(&sctp_ifa->refcount, 1);
2971                 if (net) {
2972                         /* save off where the next one we will want */
2973                         net->indx_of_eligible_next_to_use = cur_addr_num + 1;
2974                 }
2975                 return (sctp_ifa);
2976         }
2977         /*
2978          * plan_b: Look at all interfaces and find a preferred address. If
2979          * no preferred fall through to plan_c.
2980          */
2981 bound_all_plan_b:
2982         SCTPDBG(SCTP_DEBUG_OUTPUT2, "Trying Plan B\n");
2983         LIST_FOREACH(sctp_ifn, &vrf->ifnlist, next_ifn) {
2984                 SCTPDBG(SCTP_DEBUG_OUTPUT2, "Examine interface %s\n",
2985                     sctp_ifn->ifn_name);
2986                 if (dest_is_loop == 0 && SCTP_IFN_IS_IFT_LOOP(sctp_ifn)) {
2987                         /* wrong base scope */
2988                         SCTPDBG(SCTP_DEBUG_OUTPUT2, "skip\n");
2989                         continue;
2990                 }
2991                 if ((sctp_ifn == looked_at) && looked_at) {
2992                         /* already looked at this guy */
2993                         SCTPDBG(SCTP_DEBUG_OUTPUT2, "already seen\n");
2994                         continue;
2995                 }
2996                 num_preferred = sctp_count_num_preferred_boundall(sctp_ifn, stcb, non_asoc_addr_ok,
2997                     dest_is_loop, dest_is_priv, fam);
2998                 SCTPDBG(SCTP_DEBUG_OUTPUT2,
2999                     "Found ifn:%p %d preferred source addresses\n",
3000                     ifn, num_preferred);
3001                 if (num_preferred == 0) {
3002                         /* None on this interface. */
3003                         SCTPDBG(SCTP_DEBUG_OUTPUT2, "No prefered -- skipping to next\n");
3004                         continue;
3005                 }
3006                 SCTPDBG(SCTP_DEBUG_OUTPUT2,
3007                     "num preferred:%d on interface:%p cur_addr_num:%d\n",
3008                     num_preferred, (void *)sctp_ifn, cur_addr_num);
3009
3010                 /*
3011                  * Ok we have num_eligible_addr set with how many we can
3012                  * use, this may vary from call to call due to addresses
3013                  * being deprecated etc..
3014                  */
3015                 if (cur_addr_num >= num_preferred) {
3016                         cur_addr_num = 0;
3017                 }
3018                 sifa = sctp_select_nth_preferred_addr_from_ifn_boundall(sctp_ifn, stcb, non_asoc_addr_ok, dest_is_loop,
3019                     dest_is_priv, cur_addr_num, fam, ro);
3020                 if (sifa == NULL)
3021                         continue;
3022                 if (net) {
3023                         net->indx_of_eligible_next_to_use = cur_addr_num + 1;
3024                         SCTPDBG(SCTP_DEBUG_OUTPUT2, "we selected %d\n",
3025                             cur_addr_num);
3026                         SCTPDBG(SCTP_DEBUG_OUTPUT2, "Source:");
3027                         SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, &sifa->address.sa);
3028                         SCTPDBG(SCTP_DEBUG_OUTPUT2, "Dest:");
3029                         SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, &net->ro._l_addr.sa);
3030                 }
3031                 atomic_add_int(&sifa->refcount, 1);
3032                 return (sifa);
3033         }
3034 #ifdef INET
3035 again_with_private_addresses_allowed:
3036 #endif
3037         /* plan_c: do we have an acceptable address on the emit interface */
3038         sifa = NULL;
3039         SCTPDBG(SCTP_DEBUG_OUTPUT2, "Trying Plan C: find acceptable on interface\n");
3040         if (emit_ifn == NULL) {
3041                 SCTPDBG(SCTP_DEBUG_OUTPUT2, "Jump to Plan D - no emit_ifn\n");
3042                 goto plan_d;
3043         }
3044         LIST_FOREACH(sctp_ifa, &emit_ifn->ifalist, next_ifa) {
3045                 SCTPDBG(SCTP_DEBUG_OUTPUT2, "ifa:%p\n", (void *)sctp_ifa);
3046                 if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
3047                     (non_asoc_addr_ok == 0)) {
3048                         SCTPDBG(SCTP_DEBUG_OUTPUT2, "Defer\n");
3049                         continue;
3050                 }
3051                 sifa = sctp_is_ifa_addr_acceptable(sctp_ifa, dest_is_loop,
3052                     dest_is_priv, fam);
3053                 if (sifa == NULL) {
3054                         SCTPDBG(SCTP_DEBUG_OUTPUT2, "IFA not acceptable\n");
3055                         continue;
3056                 }
3057                 if (stcb) {
3058                         if (sctp_is_address_in_scope(sifa,
3059                             stcb->asoc.ipv4_addr_legal,
3060                             stcb->asoc.ipv6_addr_legal,
3061                             stcb->asoc.loopback_scope,
3062                             stcb->asoc.ipv4_local_scope,
3063                             stcb->asoc.local_scope,
3064                             stcb->asoc.site_scope, 0) == 0) {
3065                                 SCTPDBG(SCTP_DEBUG_OUTPUT2, "NOT in scope\n");
3066                                 sifa = NULL;
3067                                 continue;
3068                         }
3069                         if (((non_asoc_addr_ok == 0) &&
3070                             (sctp_is_addr_restricted(stcb, sifa))) ||
3071                             (non_asoc_addr_ok &&
3072                             (sctp_is_addr_restricted(stcb, sifa)) &&
3073                             (!sctp_is_addr_pending(stcb, sifa)))) {
3074                                 /*
3075                                  * It is restricted for some reason..
3076                                  * probably not yet added.
3077                                  */
3078                                 SCTPDBG(SCTP_DEBUG_OUTPUT2, "Its resticted\n");
3079                                 sifa = NULL;
3080                                 continue;
3081                         }
3082                 } else {
3083                         SCTP_PRINTF("Stcb is null - no print\n");
3084                 }
3085                 atomic_add_int(&sifa->refcount, 1);
3086                 goto out;
3087         }
3088 plan_d:
3089         /*
3090          * plan_d: We are in trouble. No preferred address on the emit
3091          * interface. And not even a preferred address on all interfaces. Go
3092          * out and see if we can find an acceptable address somewhere
3093          * amongst all interfaces.
3094          */
3095         SCTPDBG(SCTP_DEBUG_OUTPUT2, "Trying Plan D looked_at is %p\n", (void *)looked_at);
3096         LIST_FOREACH(sctp_ifn, &vrf->ifnlist, next_ifn) {
3097                 if (dest_is_loop == 0 && SCTP_IFN_IS_IFT_LOOP(sctp_ifn)) {
3098                         /* wrong base scope */
3099                         continue;
3100                 }
3101                 LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
3102                         if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
3103                             (non_asoc_addr_ok == 0))
3104                                 continue;
3105                         sifa = sctp_is_ifa_addr_acceptable(sctp_ifa,
3106                             dest_is_loop,
3107                             dest_is_priv, fam);
3108                         if (sifa == NULL)
3109                                 continue;
3110                         if (stcb) {
3111                                 if (sctp_is_address_in_scope(sifa,
3112                                     stcb->asoc.ipv4_addr_legal,
3113                                     stcb->asoc.ipv6_addr_legal,
3114                                     stcb->asoc.loopback_scope,
3115                                     stcb->asoc.ipv4_local_scope,
3116                                     stcb->asoc.local_scope,
3117                                     stcb->asoc.site_scope, 0) == 0) {
3118                                         sifa = NULL;
3119                                         continue;
3120                                 }
3121                                 if (((non_asoc_addr_ok == 0) &&
3122                                     (sctp_is_addr_restricted(stcb, sifa))) ||
3123                                     (non_asoc_addr_ok &&
3124                                     (sctp_is_addr_restricted(stcb, sifa)) &&
3125                                     (!sctp_is_addr_pending(stcb, sifa)))) {
3126                                         /*
3127                                          * It is restricted for some
3128                                          * reason.. probably not yet added.
3129                                          */
3130                                         sifa = NULL;
3131                                         continue;
3132                                 }
3133                         }
3134                         goto out;
3135                 }
3136         }
3137 #ifdef INET
3138         if ((retried == 0) && (stcb->asoc.ipv4_local_scope == 0)) {
3139                 stcb->asoc.ipv4_local_scope = 1;
3140                 retried = 1;
3141                 goto again_with_private_addresses_allowed;
3142         } else if (retried == 1) {
3143                 stcb->asoc.ipv4_local_scope = 0;
3144         }
3145 #endif
3146 out:
3147 #ifdef INET
3148         if (sifa) {
3149                 if (retried == 1) {
3150                         LIST_FOREACH(sctp_ifn, &vrf->ifnlist, next_ifn) {
3151                                 if (dest_is_loop == 0 && SCTP_IFN_IS_IFT_LOOP(sctp_ifn)) {
3152                                         /* wrong base scope */
3153                                         continue;
3154                                 }
3155                                 LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
3156                                         struct sctp_ifa *tmp_sifa;
3157
3158                                         if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
3159                                             (non_asoc_addr_ok == 0))
3160                                                 continue;
3161                                         tmp_sifa = sctp_is_ifa_addr_acceptable(sctp_ifa,
3162                                             dest_is_loop,
3163                                             dest_is_priv, fam);
3164                                         if (tmp_sifa == NULL) {
3165                                                 continue;
3166                                         }
3167                                         if (tmp_sifa == sifa) {
3168                                                 continue;
3169                                         }
3170                                         if (stcb) {
3171                                                 if (sctp_is_address_in_scope(tmp_sifa,
3172                                                     stcb->asoc.ipv4_addr_legal,
3173                                                     stcb->asoc.ipv6_addr_legal,
3174                                                     stcb->asoc.loopback_scope,
3175                                                     stcb->asoc.ipv4_local_scope,
3176                                                     stcb->asoc.local_scope,
3177                                                     stcb->asoc.site_scope, 0) == 0) {
3178                                                         continue;
3179                                                 }
3180                                                 if (((non_asoc_addr_ok == 0) &&
3181                                                     (sctp_is_addr_restricted(stcb, tmp_sifa))) ||
3182                                                     (non_asoc_addr_ok &&
3183                                                     (sctp_is_addr_restricted(stcb, tmp_sifa)) &&
3184                                                     (!sctp_is_addr_pending(stcb, tmp_sifa)))) {
3185                                                         /*
3186                                                          * It is restricted
3187                                                          * for some reason..
3188                                                          * probably not yet
3189                                                          * added.
3190                                                          */
3191                                                         continue;
3192                                                 }
3193                                         }
3194                                         if ((tmp_sifa->address.sin.sin_family == AF_INET) &&
3195                                             (IN4_ISPRIVATE_ADDRESS(&(tmp_sifa->address.sin.sin_addr)))) {
3196                                                 sctp_add_local_addr_restricted(stcb, tmp_sifa);
3197                                         }
3198                                 }
3199                         }
3200                 }
3201                 atomic_add_int(&sifa->refcount, 1);
3202         }
3203 #endif
3204         return (sifa);
3205 }
3206
3207
3208
3209 /* tcb may be NULL */
3210 struct sctp_ifa *
3211 sctp_source_address_selection(struct sctp_inpcb *inp,
3212     struct sctp_tcb *stcb,
3213     sctp_route_t * ro,
3214     struct sctp_nets *net,
3215     int non_asoc_addr_ok, uint32_t vrf_id)
3216 {
3217         struct sctp_ifa *answer;
3218         uint8_t dest_is_priv, dest_is_loop;
3219         sa_family_t fam;
3220
3221 #ifdef INET
3222         struct sockaddr_in *to = (struct sockaddr_in *)&ro->ro_dst;
3223
3224 #endif
3225 #ifdef INET6
3226         struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&ro->ro_dst;
3227
3228 #endif
3229
3230         /**
3231          * Rules: - Find the route if needed, cache if I can. - Look at
3232          * interface address in route, Is it in the bound list. If so we
3233          * have the best source. - If not we must rotate amongst the
3234          * addresses.
3235          *
3236          * Cavets and issues
3237          *
3238          * Do we need to pay attention to scope. We can have a private address
3239          * or a global address we are sourcing or sending to. So if we draw
3240          * it out
3241          * zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
3242          * For V4
3243          * ------------------------------------------
3244          *      source     *      dest  *  result
3245          * -----------------------------------------
3246          * <a>  Private    *    Global  *  NAT
3247          * -----------------------------------------
3248          * <b>  Private    *    Private *  No problem
3249          * -----------------------------------------
3250          * <c>  Global     *    Private *  Huh, How will this work?
3251          * -----------------------------------------
3252          * <d>  Global     *    Global  *  No Problem
3253          *------------------------------------------
3254          * zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
3255          * For V6
3256          *------------------------------------------
3257          *      source     *      dest  *  result
3258          * -----------------------------------------
3259          * <a>  Linklocal  *    Global  *
3260          * -----------------------------------------
3261          * <b>  Linklocal  * Linklocal  *  No problem
3262          * -----------------------------------------
3263          * <c>  Global     * Linklocal  *  Huh, How will this work?
3264          * -----------------------------------------
3265          * <d>  Global     *    Global  *  No Problem
3266          *------------------------------------------
3267          * zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
3268          *
3269          * And then we add to that what happens if there are multiple addresses
3270          * assigned to an interface. Remember the ifa on a ifn is a linked
3271          * list of addresses. So one interface can have more than one IP
3272          * address. What happens if we have both a private and a global
3273          * address? Do we then use context of destination to sort out which
3274          * one is best? And what about NAT's sending P->G may get you a NAT
3275          * translation, or should you select the G thats on the interface in
3276          * preference.
3277          *
3278          * Decisions:
3279          *
3280          * - count the number of addresses on the interface.
3281          * - if it is one, no problem except case <c>.
3282          *   For <a> we will assume a NAT out there.
3283          * - if there are more than one, then we need to worry about scope P
3284          *   or G. We should prefer G -> G and P -> P if possible.
3285          *   Then as a secondary fall back to mixed types G->P being a last
3286          *   ditch one.
3287          * - The above all works for bound all, but bound specific we need to
3288          *   use the same concept but instead only consider the bound
3289          *   addresses. If the bound set is NOT assigned to the interface then
3290          *   we must use rotation amongst the bound addresses..
3291          */
3292         if (ro->ro_rt == NULL) {
3293                 /*
3294                  * Need a route to cache.
3295                  */
3296                 SCTP_RTALLOC(ro, vrf_id);
3297         }
3298         if (ro->ro_rt == NULL) {
3299                 return (NULL);
3300         }
3301         fam = ro->ro_dst.sa_family;
3302         dest_is_priv = dest_is_loop = 0;
3303         /* Setup our scopes for the destination */
3304         switch (fam) {
3305 #ifdef INET
3306         case AF_INET:
3307                 /* Scope based on outbound address */
3308                 if (IN4_ISLOOPBACK_ADDRESS(&to->sin_addr)) {
3309                         dest_is_loop = 1;
3310                         if (net != NULL) {
3311                                 /* mark it as local */
3312                                 net->addr_is_local = 1;
3313                         }
3314                 } else if ((IN4_ISPRIVATE_ADDRESS(&to->sin_addr))) {
3315                         dest_is_priv = 1;
3316                 }
3317                 break;
3318 #endif
3319 #ifdef INET6
3320         case AF_INET6:
3321                 /* Scope based on outbound address */
3322                 if (IN6_IS_ADDR_LOOPBACK(&to6->sin6_addr) ||
3323                     SCTP_ROUTE_IS_REAL_LOOP(ro)) {
3324                         /*
3325                          * If the address is a loopback address, which
3326                          * consists of "::1" OR "fe80::1%lo0", we are
3327                          * loopback scope. But we don't use dest_is_priv
3328                          * (link local addresses).
3329                          */
3330                         dest_is_loop = 1;
3331                         if (net != NULL) {
3332                                 /* mark it as local */
3333                                 net->addr_is_local = 1;
3334                         }
3335                 } else if (IN6_IS_ADDR_LINKLOCAL(&to6->sin6_addr)) {
3336                         dest_is_priv = 1;
3337                 }
3338                 break;
3339 #endif
3340         }
3341         SCTPDBG(SCTP_DEBUG_OUTPUT2, "Select source addr for:");
3342         SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, (struct sockaddr *)&ro->ro_dst);
3343         SCTP_IPI_ADDR_RLOCK();
3344         if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
3345                 /*
3346                  * Bound all case
3347                  */
3348                 answer = sctp_choose_boundall(stcb, net, ro, vrf_id,
3349                     dest_is_priv, dest_is_loop,
3350                     non_asoc_addr_ok, fam);
3351                 SCTP_IPI_ADDR_RUNLOCK();
3352                 return (answer);
3353         }
3354         /*
3355          * Subset bound case
3356          */
3357         if (stcb) {
3358                 answer = sctp_choose_boundspecific_stcb(inp, stcb, ro,
3359                     vrf_id, dest_is_priv,
3360                     dest_is_loop,
3361                     non_asoc_addr_ok, fam);
3362         } else {
3363                 answer = sctp_choose_boundspecific_inp(inp, ro, vrf_id,
3364                     non_asoc_addr_ok,
3365                     dest_is_priv,
3366                     dest_is_loop, fam);
3367         }
3368         SCTP_IPI_ADDR_RUNLOCK();
3369         return (answer);
3370 }
3371
3372 static int
3373 sctp_find_cmsg(int c_type, void *data, struct mbuf *control, size_t cpsize)
3374 {
3375         struct cmsghdr cmh;
3376         int tlen, at, found;
3377         struct sctp_sndinfo sndinfo;
3378         struct sctp_prinfo prinfo;
3379         struct sctp_authinfo authinfo;
3380
3381         tlen = SCTP_BUF_LEN(control);
3382         at = 0;
3383         found = 0;
3384         /*
3385          * Independent of how many mbufs, find the c_type inside the control
3386          * structure and copy out the data.
3387          */
3388         while (at < tlen) {
3389                 if ((tlen - at) < (int)CMSG_ALIGN(sizeof(cmh))) {
3390                         /* There is not enough room for one more. */
3391                         return (found);
3392                 }
3393                 m_copydata(control, at, sizeof(cmh), (caddr_t)&cmh);
3394                 if (cmh.cmsg_len < CMSG_ALIGN(sizeof(cmh))) {
3395                         /* We dont't have a complete CMSG header. */
3396                         return (found);
3397                 }
3398                 if (((int)cmh.cmsg_len + at) > tlen) {
3399                         /* We don't have the complete CMSG. */
3400                         return (found);
3401                 }
3402                 if ((cmh.cmsg_level == IPPROTO_SCTP) &&
3403                     ((c_type == cmh.cmsg_type) ||
3404                     ((c_type == SCTP_SNDRCV) &&
3405                     ((cmh.cmsg_type == SCTP_SNDINFO) ||
3406                     (cmh.cmsg_type == SCTP_PRINFO) ||
3407                     (cmh.cmsg_type == SCTP_AUTHINFO))))) {
3408                         if (c_type == cmh.cmsg_type) {
3409                                 if ((size_t)(cmh.cmsg_len - CMSG_ALIGN(sizeof(cmh))) < cpsize) {
3410                                         return (found);
3411                                 }
3412                                 /* It is exactly what we want. Copy it out. */
3413                                 m_copydata(control, at + CMSG_ALIGN(sizeof(cmh)), cpsize, (caddr_t)data);
3414                                 return (1);
3415                         } else {
3416                                 struct sctp_sndrcvinfo *sndrcvinfo;
3417
3418                                 sndrcvinfo = (struct sctp_sndrcvinfo *)data;
3419                                 if (found == 0) {
3420                                         if (cpsize < sizeof(struct sctp_sndrcvinfo)) {
3421                                                 return (found);
3422                                         }
3423                                         memset(sndrcvinfo, 0, sizeof(struct sctp_sndrcvinfo));
3424                                 }
3425                                 switch (cmh.cmsg_type) {
3426                                 case SCTP_SNDINFO:
3427                                         if ((size_t)(cmh.cmsg_len - CMSG_ALIGN(sizeof(cmh))) < sizeof(struct sctp_sndinfo)) {
3428                                                 return (found);
3429                                         }
3430                                         m_copydata(control, at + CMSG_ALIGN(sizeof(cmh)), sizeof(struct sctp_sndinfo), (caddr_t)&sndinfo);
3431                                         sndrcvinfo->sinfo_stream = sndinfo.snd_sid;
3432                                         sndrcvinfo->sinfo_flags = sndinfo.snd_flags;
3433                                         sndrcvinfo->sinfo_ppid = sndinfo.snd_ppid;
3434                                         sndrcvinfo->sinfo_context = sndinfo.snd_context;
3435                                         sndrcvinfo->sinfo_assoc_id = sndinfo.snd_assoc_id;
3436                                         break;
3437                                 case SCTP_PRINFO:
3438                                         if ((size_t)(cmh.cmsg_len - CMSG_ALIGN(sizeof(cmh))) < sizeof(struct sctp_prinfo)) {
3439                                                 return (found);
3440                                         }
3441                                         m_copydata(control, at + CMSG_ALIGN(sizeof(cmh)), sizeof(struct sctp_prinfo), (caddr_t)&prinfo);
3442                                         sndrcvinfo->sinfo_timetolive = prinfo.pr_value;
3443                                         sndrcvinfo->sinfo_flags |= prinfo.pr_policy;
3444                                         break;
3445                                 case SCTP_AUTHINFO:
3446                                         if ((size_t)(cmh.cmsg_len - CMSG_ALIGN(sizeof(cmh))) < sizeof(struct sctp_authinfo)) {
3447                                                 return (found);
3448                                         }
3449                                         m_copydata(control, at + CMSG_ALIGN(sizeof(cmh)), sizeof(struct sctp_authinfo), (caddr_t)&authinfo);
3450                                         sndrcvinfo->sinfo_keynumber_valid = 1;
3451                                         sndrcvinfo->sinfo_keynumber = authinfo.auth_keynumber;
3452                                         break;
3453                                 default:
3454                                         return (found);
3455                                 }
3456                                 found = 1;
3457                         }
3458                 }
3459                 at += CMSG_ALIGN(cmh.cmsg_len);
3460         }
3461         return (found);
3462 }
3463
3464 static int
3465 sctp_process_cmsgs_for_init(struct sctp_tcb *stcb, struct mbuf *control, int *error)
3466 {
3467         struct cmsghdr cmh;
3468         int tlen, at;
3469         struct sctp_initmsg initmsg;
3470
3471 #ifdef INET
3472         struct sockaddr_in sin;
3473
3474 #endif
3475 #ifdef INET6
3476         struct sockaddr_in6 sin6;
3477
3478 #endif
3479
3480         tlen = SCTP_BUF_LEN(control);
3481         at = 0;
3482         while (at < tlen) {
3483                 if ((tlen - at) < (int)CMSG_ALIGN(sizeof(cmh))) {
3484                         /* There is not enough room for one more. */
3485                         *error = EINVAL;
3486                         return (1);
3487                 }
3488                 m_copydata(control, at, sizeof(cmh), (caddr_t)&cmh);
3489                 if (cmh.cmsg_len < CMSG_ALIGN(sizeof(cmh))) {
3490                         /* We dont't have a complete CMSG header. */
3491                         *error = EINVAL;
3492                         return (1);
3493                 }
3494                 if (((int)cmh.cmsg_len + at) > tlen) {
3495                         /* We don't have the complete CMSG. */
3496                         *error = EINVAL;
3497                         return (1);
3498                 }
3499                 if (cmh.cmsg_level == IPPROTO_SCTP) {
3500                         switch (cmh.cmsg_type) {
3501                         case SCTP_INIT:
3502                                 if ((size_t)(cmh.cmsg_len - CMSG_ALIGN(sizeof(cmh))) < sizeof(struct sctp_initmsg)) {
3503                                         *error = EINVAL;
3504                                         return (1);
3505                                 }
3506                                 m_copydata(control, at + CMSG_ALIGN(sizeof(cmh)), sizeof(struct sctp_initmsg), (caddr_t)&initmsg);
3507                                 if (initmsg.sinit_max_attempts)
3508                                         stcb->asoc.max_init_times = initmsg.sinit_max_attempts;
3509                                 if (initmsg.sinit_num_ostreams)
3510                                         stcb->asoc.pre_open_streams = initmsg.sinit_num_ostreams;
3511                                 if (initmsg.sinit_max_instreams)
3512                                         stcb->asoc.max_inbound_streams = initmsg.sinit_max_instreams;
3513                                 if (initmsg.sinit_max_init_timeo)
3514                                         stcb->asoc.initial_init_rto_max = initmsg.sinit_max_init_timeo;
3515                                 if (stcb->asoc.streamoutcnt < stcb->asoc.pre_open_streams) {
3516                                         struct sctp_stream_out *tmp_str;
3517                                         unsigned int i;
3518
3519                                         /* Default is NOT correct */
3520                                         SCTPDBG(SCTP_DEBUG_OUTPUT1, "Ok, default:%d pre_open:%d\n",
3521                                             stcb->asoc.streamoutcnt, stcb->asoc.pre_open_streams);
3522                                         SCTP_TCB_UNLOCK(stcb);
3523                                         SCTP_MALLOC(tmp_str,
3524                                             struct sctp_stream_out *,
3525                                             (stcb->asoc.pre_open_streams * sizeof(struct sctp_stream_out)),
3526                                             SCTP_M_STRMO);
3527                                         SCTP_TCB_LOCK(stcb);
3528                                         if (tmp_str != NULL) {
3529                                                 SCTP_FREE(stcb->asoc.strmout, SCTP_M_STRMO);
3530                                                 stcb->asoc.strmout = tmp_str;
3531                                                 stcb->asoc.strm_realoutsize = stcb->asoc.streamoutcnt = stcb->asoc.pre_open_streams;
3532                                         } else {
3533                                                 stcb->asoc.pre_open_streams = stcb->asoc.streamoutcnt;
3534                                         }
3535                                         for (i = 0; i < stcb->asoc.streamoutcnt; i++) {
3536                                                 TAILQ_INIT(&stcb->asoc.strmout[i].outqueue);
3537                                                 stcb->asoc.strmout[i].chunks_on_queues = 0;
3538                                                 stcb->asoc.strmout[i].next_sequence_send = 0;
3539                                                 stcb->asoc.strmout[i].stream_no = i;
3540                                                 stcb->asoc.strmout[i].last_msg_incomplete = 0;
3541                                                 stcb->asoc.ss_functions.sctp_ss_init_stream(&stcb->asoc.strmout[i], NULL);
3542                                         }
3543                                 }
3544                                 break;
3545 #ifdef INET
3546                         case SCTP_DSTADDRV4:
3547                                 if ((size_t)(cmh.cmsg_len - CMSG_ALIGN(sizeof(cmh))) < sizeof(struct in_addr)) {
3548                                         *error = EINVAL;
3549                                         return (1);
3550                                 }
3551                                 memset(&sin, 0, sizeof(struct sockaddr_in));
3552                                 sin.sin_family = AF_INET;
3553                                 sin.sin_len = sizeof(struct sockaddr_in);
3554                                 sin.sin_port = stcb->rport;
3555                                 m_copydata(control, at + CMSG_ALIGN(sizeof(cmh)), sizeof(struct in_addr), (caddr_t)&sin.sin_addr);
3556                                 if ((sin.sin_addr.s_addr == INADDR_ANY) ||
3557                                     (sin.sin_addr.s_addr == INADDR_BROADCAST) ||
3558                                     IN_MULTICAST(ntohl(sin.sin_addr.s_addr))) {
3559                                         *error = EINVAL;
3560                                         return (1);
3561                                 }
3562                                 if (sctp_add_remote_addr(stcb, (struct sockaddr *)&sin, NULL,
3563                                     SCTP_DONOT_SETSCOPE, SCTP_ADDR_IS_CONFIRMED)) {
3564                                         *error = ENOBUFS;
3565                                         return (1);
3566                                 }
3567                                 break;
3568 #endif
3569 #ifdef INET6
3570                         case SCTP_DSTADDRV6:
3571                                 if ((size_t)(cmh.cmsg_len - CMSG_ALIGN(sizeof(cmh))) < sizeof(struct in6_addr)) {
3572                                         *error = EINVAL;
3573                                         return (1);
3574                                 }
3575                                 memset(&sin6, 0, sizeof(struct sockaddr_in6));
3576                                 sin6.sin6_family = AF_INET6;
3577                                 sin6.sin6_len = sizeof(struct sockaddr_in6);
3578                                 sin6.sin6_port = stcb->rport;
3579                                 m_copydata(control, at + CMSG_ALIGN(sizeof(cmh)), sizeof(struct in6_addr), (caddr_t)&sin6.sin6_addr);
3580                                 if (IN6_IS_ADDR_UNSPECIFIED(&sin6.sin6_addr) ||
3581                                     IN6_IS_ADDR_MULTICAST(&sin6.sin6_addr)) {
3582                                         *error = EINVAL;
3583                                         return (1);
3584                                 }
3585 #ifdef INET
3586                                 if (IN6_IS_ADDR_V4MAPPED(&sin6.sin6_addr)) {
3587                                         in6_sin6_2_sin(&sin, &sin6);
3588                                         if ((sin.sin_addr.s_addr == INADDR_ANY) ||
3589                                             (sin.sin_addr.s_addr == INADDR_BROADCAST) ||
3590                                             IN_MULTICAST(ntohl(sin.sin_addr.s_addr))) {
3591                                                 *error = EINVAL;
3592                                                 return (1);
3593                                         }
3594                                         if (sctp_add_remote_addr(stcb, (struct sockaddr *)&sin, NULL,
3595                                             SCTP_DONOT_SETSCOPE, SCTP_ADDR_IS_CONFIRMED)) {
3596                                                 *error = ENOBUFS;
3597                                                 return (1);
3598                                         }
3599                                 } else
3600 #endif
3601                                         if (sctp_add_remote_addr(stcb, (struct sockaddr *)&sin6, NULL,
3602                                     SCTP_DONOT_SETSCOPE, SCTP_ADDR_IS_CONFIRMED)) {
3603                                         *error = ENOBUFS;
3604                                         return (1);
3605                                 }
3606                                 break;
3607 #endif
3608                         default:
3609                                 break;
3610                         }
3611                 }
3612                 at += CMSG_ALIGN(cmh.cmsg_len);
3613         }
3614         return (0);
3615 }
3616
3617 static struct sctp_tcb *
3618 sctp_findassociation_cmsgs(struct sctp_inpcb **inp_p,
3619     in_port_t port,
3620     struct mbuf *control,
3621     struct sctp_nets **net_p,
3622     int *error)
3623 {
3624         struct cmsghdr cmh;
3625         int tlen, at;
3626         struct sctp_tcb *stcb;
3627         struct sockaddr *addr;
3628
3629 #ifdef INET
3630         struct sockaddr_in sin;
3631
3632 #endif
3633 #ifdef INET6
3634         struct sockaddr_in6 sin6;
3635
3636 #endif
3637
3638         tlen = SCTP_BUF_LEN(control);
3639         at = 0;
3640         while (at < tlen) {
3641                 if ((tlen - at) < (int)CMSG_ALIGN(sizeof(cmh))) {
3642                         /* There is not enough room for one more. */
3643                         *error = EINVAL;
3644                         return (NULL);
3645                 }
3646                 m_copydata(control, at, sizeof(cmh), (caddr_t)&cmh);
3647                 if (cmh.cmsg_len < CMSG_ALIGN(sizeof(cmh))) {
3648                         /* We dont't have a complete CMSG header. */
3649                         *error = EINVAL;
3650                         return (NULL);
3651                 }
3652                 if (((int)cmh.cmsg_len + at) > tlen) {
3653                         /* We don't have the complete CMSG. */
3654                         *error = EINVAL;
3655                         return (NULL);
3656                 }
3657                 if (cmh.cmsg_level == IPPROTO_SCTP) {
3658                         switch (cmh.cmsg_type) {
3659 #ifdef INET
3660                         case SCTP_DSTADDRV4:
3661                                 if ((size_t)(cmh.cmsg_len - CMSG_ALIGN(sizeof(cmh))) < sizeof(struct in_addr)) {
3662                                         *error = EINVAL;
3663                                         return (NULL);
3664                                 }
3665                                 memset(&sin, 0, sizeof(struct sockaddr_in));
3666                                 sin.sin_family = AF_INET;
3667                                 sin.sin_len = sizeof(struct sockaddr_in);
3668                                 sin.sin_port = port;
3669                                 m_copydata(control, at + CMSG_ALIGN(sizeof(cmh)), sizeof(struct in_addr), (caddr_t)&sin.sin_addr);
3670                                 addr = (struct sockaddr *)&sin;
3671                                 break;
3672 #endif
3673 #ifdef INET6
3674                         case SCTP_DSTADDRV6:
3675                                 if ((size_t)(cmh.cmsg_len - CMSG_ALIGN(sizeof(cmh))) < sizeof(struct in6_addr)) {
3676                                         *error = EINVAL;
3677                                         return (NULL);
3678                                 }
3679                                 memset(&sin6, 0, sizeof(struct sockaddr_in6));
3680                                 sin6.sin6_family = AF_INET6;
3681                                 sin6.sin6_len = sizeof(struct sockaddr_in6);
3682                                 sin6.sin6_port = port;
3683                                 m_copydata(control, at + CMSG_ALIGN(sizeof(cmh)), sizeof(struct in6_addr), (caddr_t)&sin6.sin6_addr);
3684 #ifdef INET
3685                                 if (IN6_IS_ADDR_V4MAPPED(&sin6.sin6_addr)) {
3686                                         in6_sin6_2_sin(&sin, &sin6);
3687                                         addr = (struct sockaddr *)&sin;
3688                                 } else
3689 #endif
3690                                         addr = (struct sockaddr *)&sin6;
3691                                 break;
3692 #endif
3693                         default:
3694                                 addr = NULL;
3695                                 break;
3696                         }
3697                         if (addr) {
3698                                 stcb = sctp_findassociation_ep_addr(inp_p, addr, net_p, NULL, NULL);
3699                                 if (stcb != NULL) {
3700                                         return (stcb);
3701                                 }
3702                         }
3703                 }
3704                 at += CMSG_ALIGN(cmh.cmsg_len);
3705         }
3706         return (NULL);
3707 }
3708
3709 static struct mbuf *
3710 sctp_add_cookie(struct mbuf *init, int init_offset,
3711     struct mbuf *initack, int initack_offset, struct sctp_state_cookie *stc_in, uint8_t ** signature)
3712 {
3713         struct mbuf *copy_init, *copy_initack, *m_at, *sig, *mret;
3714         struct sctp_state_cookie *stc;
3715         struct sctp_paramhdr *ph;
3716         uint8_t *foo;
3717         int sig_offset;
3718         uint16_t cookie_sz;
3719
3720         mret = NULL;
3721         mret = sctp_get_mbuf_for_msg((sizeof(struct sctp_state_cookie) +
3722             sizeof(struct sctp_paramhdr)), 0,
3723             M_DONTWAIT, 1, MT_DATA);
3724         if (mret == NULL) {
3725                 return (NULL);
3726         }
3727         copy_init = SCTP_M_COPYM(init, init_offset, M_COPYALL, M_DONTWAIT);
3728         if (copy_init == NULL) {
3729                 sctp_m_freem(mret);
3730                 return (NULL);
3731         }
3732 #ifdef SCTP_MBUF_LOGGING
3733         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
3734                 struct mbuf *mat;
3735
3736                 for (mat = copy_init; mat; mat = SCTP_BUF_NEXT(mat)) {
3737                         if (SCTP_BUF_IS_EXTENDED(mat)) {
3738                                 sctp_log_mb(mat, SCTP_MBUF_ICOPY);
3739                         }
3740                 }
3741         }
3742 #endif
3743         copy_initack = SCTP_M_COPYM(initack, initack_offset, M_COPYALL,
3744             M_DONTWAIT);
3745         if (copy_initack == NULL) {
3746                 sctp_m_freem(mret);
3747                 sctp_m_freem(copy_init);
3748                 return (NULL);
3749         }
3750 #ifdef SCTP_MBUF_LOGGING
3751         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
3752                 struct mbuf *mat;
3753
3754                 for (mat = copy_initack; mat; mat = SCTP_BUF_NEXT(mat)) {
3755                         if (SCTP_BUF_IS_EXTENDED(mat)) {
3756                                 sctp_log_mb(mat, SCTP_MBUF_ICOPY);
3757                         }
3758                 }
3759         }
3760 #endif
3761         /* easy side we just drop it on the end */
3762         ph = mtod(mret, struct sctp_paramhdr *);
3763         SCTP_BUF_LEN(mret) = sizeof(struct sctp_state_cookie) +
3764             sizeof(struct sctp_paramhdr);
3765         stc = (struct sctp_state_cookie *)((caddr_t)ph +
3766             sizeof(struct sctp_paramhdr));
3767         ph->param_type = htons(SCTP_STATE_COOKIE);
3768         ph->param_length = 0;   /* fill in at the end */
3769         /* Fill in the stc cookie data */
3770         memcpy(stc, stc_in, sizeof(struct sctp_state_cookie));
3771
3772         /* tack the INIT and then the INIT-ACK onto the chain */
3773         cookie_sz = 0;
3774         for (m_at = mret; m_at; m_at = SCTP_BUF_NEXT(m_at)) {
3775                 cookie_sz += SCTP_BUF_LEN(m_at);
3776                 if (SCTP_BUF_NEXT(m_at) == NULL) {
3777                         SCTP_BUF_NEXT(m_at) = copy_init;
3778                         break;
3779                 }
3780         }
3781         for (m_at = copy_init; m_at; m_at = SCTP_BUF_NEXT(m_at)) {
3782                 cookie_sz += SCTP_BUF_LEN(m_at);
3783                 if (SCTP_BUF_NEXT(m_at) == NULL) {
3784                         SCTP_BUF_NEXT(m_at) = copy_initack;
3785                         break;
3786                 }
3787         }
3788         for (m_at = copy_initack; m_at; m_at = SCTP_BUF_NEXT(m_at)) {
3789                 cookie_sz += SCTP_BUF_LEN(m_at);
3790                 if (SCTP_BUF_NEXT(m_at) == NULL) {
3791                         break;
3792                 }
3793         }
3794         sig = sctp_get_mbuf_for_msg(SCTP_SECRET_SIZE, 0, M_DONTWAIT, 1, MT_DATA);
3795         if (sig == NULL) {
3796                 /* no space, so free the entire chain */
3797                 sctp_m_freem(mret);
3798                 return (NULL);
3799         }
3800         SCTP_BUF_LEN(sig) = 0;
3801         SCTP_BUF_NEXT(m_at) = sig;
3802         sig_offset = 0;
3803         foo = (uint8_t *) (mtod(sig, caddr_t)+sig_offset);
3804         memset(foo, 0, SCTP_SIGNATURE_SIZE);
3805         *signature = foo;
3806         SCTP_BUF_LEN(sig) += SCTP_SIGNATURE_SIZE;
3807         cookie_sz += SCTP_SIGNATURE_SIZE;
3808         ph->param_length = htons(cookie_sz);
3809         return (mret);
3810 }
3811
3812
3813 static uint8_t
3814 sctp_get_ect(struct sctp_tcb *stcb)
3815 {
3816         if ((stcb != NULL) && (stcb->asoc.ecn_allowed == 1)) {
3817                 return (SCTP_ECT0_BIT);
3818         } else {
3819                 return (0);
3820         }
3821 }
3822
3823 #if defined(INET) || defined(INET6)
3824 static void
3825 sctp_handle_no_route(struct sctp_tcb *stcb,
3826     struct sctp_nets *net,
3827     int so_locked)
3828 {
3829         SCTPDBG(SCTP_DEBUG_OUTPUT1, "dropped packet - no valid source addr\n");
3830
3831         if (net) {
3832                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "Destination was ");
3833                 SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT1, &net->ro._l_addr.sa);
3834                 if (net->dest_state & SCTP_ADDR_CONFIRMED) {
3835                         if ((net->dest_state & SCTP_ADDR_REACHABLE) && stcb) {
3836                                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "no route takes interface %p down\n", (void *)net);
3837                                 sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_DOWN,
3838                                     stcb, 0,
3839                                     (void *)net,
3840                                     so_locked);
3841                                 net->dest_state &= ~SCTP_ADDR_REACHABLE;
3842                                 net->dest_state &= ~SCTP_ADDR_PF;
3843                         }
3844                 }
3845                 if (stcb) {
3846                         if (net == stcb->asoc.primary_destination) {
3847                                 /* need a new primary */
3848                                 struct sctp_nets *alt;
3849
3850                                 alt = sctp_find_alternate_net(stcb, net, 0);
3851                                 if (alt != net) {
3852                                         if (stcb->asoc.alternate) {
3853                                                 sctp_free_remote_addr(stcb->asoc.alternate);
3854                                         }
3855                                         stcb->asoc.alternate = alt;
3856                                         atomic_add_int(&stcb->asoc.alternate->ref_count, 1);
3857                                         if (net->ro._s_addr) {
3858                                                 sctp_free_ifa(net->ro._s_addr);
3859                                                 net->ro._s_addr = NULL;
3860                                         }
3861                                         net->src_addr_selected = 0;
3862                                 }
3863                         }
3864                 }
3865         }
3866 }
3867
3868 #endif
3869
3870 static int
3871 sctp_lowlevel_chunk_output(struct sctp_inpcb *inp,
3872     struct sctp_tcb *stcb,      /* may be NULL */
3873     struct sctp_nets *net,
3874     struct sockaddr *to,
3875     struct mbuf *m,
3876     uint32_t auth_offset,
3877     struct sctp_auth_chunk *auth,
3878     uint16_t auth_keyid,
3879     int nofragment_flag,
3880     int ecn_ok,
3881     int out_of_asoc_ok,
3882     uint16_t src_port,
3883     uint16_t dest_port,
3884     uint32_t v_tag,
3885     uint16_t port,
3886     union sctp_sockstore *over_addr,
3887     uint8_t use_mflowid, uint32_t mflowid,
3888 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
3889     int so_locked SCTP_UNUSED
3890 #else
3891     int so_locked
3892 #endif
3893 )
3894 /* nofragment_flag to tell if IP_DF should be set (IPv4 only) */
3895 {
3896         /**
3897          * Given a mbuf chain (via SCTP_BUF_NEXT()) that holds a packet header
3898          * WITH an SCTPHDR but no IP header, endpoint inp and sa structure:
3899          * - fill in the HMAC digest of any AUTH chunk in the packet.
3900          * - calculate and fill in the SCTP checksum.
3901          * - prepend an IP address header.
3902          * - if boundall use INADDR_ANY.
3903          * - if boundspecific do source address selection.
3904          * - set fragmentation option for ipV4.
3905          * - On return from IP output, check/adjust mtu size of output
3906          *   interface and smallest_mtu size as well.
3907          */
3908         /* Will need ifdefs around this */
3909         struct mbuf *newm;
3910         struct sctphdr *sctphdr;
3911         int packet_length;
3912         int ret;
3913         uint32_t vrf_id;
3914
3915 #if defined(INET) || defined(INET6)
3916         struct mbuf *o_pak;
3917         sctp_route_t *ro = NULL;
3918         struct udphdr *udp = NULL;
3919
3920 #endif
3921         uint8_t tos_value;
3922
3923 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
3924         struct socket *so = NULL;
3925
3926 #endif
3927
3928         if ((net) && (net->dest_state & SCTP_ADDR_OUT_OF_SCOPE)) {
3929                 SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EFAULT);
3930                 sctp_m_freem(m);
3931                 return (EFAULT);
3932         }
3933         if (stcb) {
3934                 vrf_id = stcb->asoc.vrf_id;
3935         } else {
3936                 vrf_id = inp->def_vrf_id;
3937         }
3938
3939         /* fill in the HMAC digest for any AUTH chunk in the packet */
3940         if ((auth != NULL) && (stcb != NULL)) {
3941                 sctp_fill_hmac_digest_m(m, auth_offset, auth, stcb, auth_keyid);
3942         }
3943         if (net) {
3944                 tos_value = net->dscp;
3945         } else if (stcb) {
3946                 tos_value = stcb->asoc.default_dscp;
3947         } else {
3948                 tos_value = inp->sctp_ep.default_dscp;
3949         }
3950
3951         switch (to->sa_family) {
3952 #ifdef INET
3953         case AF_INET:
3954                 {
3955                         struct ip *ip = NULL;
3956                         sctp_route_t iproute;
3957                         int len;
3958
3959                         len = sizeof(struct ip) + sizeof(struct sctphdr);
3960                         if (port) {
3961                                 len += sizeof(struct udphdr);
3962                         }
3963                         newm = sctp_get_mbuf_for_msg(len, 1, M_DONTWAIT, 1, MT_DATA);
3964                         if (newm == NULL) {
3965                                 sctp_m_freem(m);
3966                                 SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
3967                                 return (ENOMEM);
3968                         }
3969                         SCTP_ALIGN_TO_END(newm, len);
3970                         SCTP_BUF_LEN(newm) = len;
3971                         SCTP_BUF_NEXT(newm) = m;
3972                         m = newm;
3973                         if (net != NULL) {
3974 #ifdef INVARIANTS
3975                                 if (net->flowidset == 0) {
3976                                         panic("Flow ID not set");
3977                                 }
3978 #endif
3979                                 m->m_pkthdr.flowid = net->flowid;
3980                                 m->m_flags |= M_FLOWID;
3981                         } else {
3982                                 if (use_mflowid != 0) {
3983                                         m->m_pkthdr.flowid = mflowid;
3984                                         m->m_flags |= M_FLOWID;
3985                                 }
3986                         }
3987                         packet_length = sctp_calculate_len(m);
3988                         ip = mtod(m, struct ip *);
3989                         ip->ip_v = IPVERSION;
3990                         ip->ip_hl = (sizeof(struct ip) >> 2);
3991                         if (tos_value == 0) {
3992                                 /*
3993                                  * This means especially, that it is not set
3994                                  * at the SCTP layer. So use the value from
3995                                  * the IP layer.
3996                                  */
3997                                 tos_value = inp->ip_inp.inp.inp_ip_tos;
3998                         }
3999                         tos_value &= 0xfc;
4000                         if (ecn_ok) {
4001                                 tos_value |= sctp_get_ect(stcb);
4002                         }
4003                         if ((nofragment_flag) && (port == 0)) {
4004                                 ip->ip_off = IP_DF;
4005                         } else {
4006                                 ip->ip_off = 0;
4007                         }
4008                         /* FreeBSD has a function for ip_id's */
4009                         ip->ip_id = ip_newid();
4010
4011                         ip->ip_ttl = inp->ip_inp.inp.inp_ip_ttl;
4012                         ip->ip_len = packet_length;
4013                         ip->ip_tos = tos_value;
4014                         if (port) {
4015                                 ip->ip_p = IPPROTO_UDP;
4016                         } else {
4017                                 ip->ip_p = IPPROTO_SCTP;
4018                         }
4019                         ip->ip_sum = 0;
4020                         if (net == NULL) {
4021                                 ro = &iproute;
4022                                 memset(&iproute, 0, sizeof(iproute));
4023                                 memcpy(&ro->ro_dst, to, to->sa_len);
4024                         } else {
4025                                 ro = (sctp_route_t *) & net->ro;
4026                         }
4027                         /* Now the address selection part */
4028                         ip->ip_dst.s_addr = ((struct sockaddr_in *)to)->sin_addr.s_addr;
4029
4030                         /* call the routine to select the src address */
4031                         if (net && out_of_asoc_ok == 0) {
4032                                 if (net->ro._s_addr && (net->ro._s_addr->localifa_flags & (SCTP_BEING_DELETED | SCTP_ADDR_IFA_UNUSEABLE))) {
4033                                         sctp_free_ifa(net->ro._s_addr);
4034                                         net->ro._s_addr = NULL;
4035                                         net->src_addr_selected = 0;
4036                                         if (ro->ro_rt) {
4037                                                 RTFREE(ro->ro_rt);
4038                                                 ro->ro_rt = NULL;
4039                                         }
4040                                 }
4041                                 if (net->src_addr_selected == 0) {
4042                                         /* Cache the source address */
4043                                         net->ro._s_addr = sctp_source_address_selection(inp, stcb,
4044                                             ro, net, 0,
4045                                             vrf_id);
4046                                         net->src_addr_selected = 1;
4047                                 }
4048                                 if (net->ro._s_addr == NULL) {
4049                                         /* No route to host */
4050                                         net->src_addr_selected = 0;
4051                                         sctp_handle_no_route(stcb, net, so_locked);
4052                                         SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EHOSTUNREACH);
4053                                         sctp_m_freem(m);
4054                                         return (EHOSTUNREACH);
4055                                 }
4056                                 ip->ip_src = net->ro._s_addr->address.sin.sin_addr;
4057                         } else {
4058                                 if (over_addr == NULL) {
4059                                         struct sctp_ifa *_lsrc;
4060
4061                                         _lsrc = sctp_source_address_selection(inp, stcb, ro,
4062                                             net,
4063                                             out_of_asoc_ok,
4064                                             vrf_id);
4065                                         if (_lsrc == NULL) {
4066                                                 sctp_handle_no_route(stcb, net, so_locked);
4067                                                 SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EHOSTUNREACH);
4068                                                 sctp_m_freem(m);
4069                                                 return (EHOSTUNREACH);
4070                                         }
4071                                         ip->ip_src = _lsrc->address.sin.sin_addr;
4072                                         sctp_free_ifa(_lsrc);
4073                                 } else {
4074                                         ip->ip_src = over_addr->sin.sin_addr;
4075                                         SCTP_RTALLOC(ro, vrf_id);
4076                                 }
4077                         }
4078                         if (port) {
4079                                 if (htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port)) == 0) {
4080                                         sctp_handle_no_route(stcb, net, so_locked);
4081                                         SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EHOSTUNREACH);
4082                                         sctp_m_freem(m);
4083                                         return (EHOSTUNREACH);
4084                                 }
4085                                 udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
4086                                 udp->uh_sport = htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port));
4087                                 udp->uh_dport = port;
4088                                 udp->uh_ulen = htons(packet_length - sizeof(struct ip));
4089                                 if (V_udp_cksum) {
4090                                         udp->uh_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr, udp->uh_ulen + htons(IPPROTO_UDP));
4091                                 } else {
4092                                         udp->uh_sum = 0;
4093                                 }
4094                                 sctphdr = (struct sctphdr *)((caddr_t)udp + sizeof(struct udphdr));
4095                         } else {
4096                                 sctphdr = (struct sctphdr *)((caddr_t)ip + sizeof(struct ip));
4097                         }
4098
4099                         sctphdr->src_port = src_port;
4100                         sctphdr->dest_port = dest_port;
4101                         sctphdr->v_tag = v_tag;
4102                         sctphdr->checksum = 0;
4103
4104                         /*
4105                          * If source address selection fails and we find no
4106                          * route then the ip_output should fail as well with
4107                          * a NO_ROUTE_TO_HOST type error. We probably should
4108                          * catch that somewhere and abort the association
4109                          * right away (assuming this is an INIT being sent).
4110                          */
4111                         if (ro->ro_rt == NULL) {
4112                                 /*
4113                                  * src addr selection failed to find a route
4114                                  * (or valid source addr), so we can't get
4115                                  * there from here (yet)!
4116                                  */
4117                                 sctp_handle_no_route(stcb, net, so_locked);
4118                                 SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EHOSTUNREACH);
4119                                 sctp_m_freem(m);
4120                                 return (EHOSTUNREACH);
4121                         }
4122                         if (ro != &iproute) {
4123                                 memcpy(&iproute, ro, sizeof(*ro));
4124                         }
4125                         SCTPDBG(SCTP_DEBUG_OUTPUT3, "Calling ipv4 output routine from low level src addr:%x\n",
4126                             (uint32_t) (ntohl(ip->ip_src.s_addr)));
4127                         SCTPDBG(SCTP_DEBUG_OUTPUT3, "Destination is %x\n",
4128                             (uint32_t) (ntohl(ip->ip_dst.s_addr)));
4129                         SCTPDBG(SCTP_DEBUG_OUTPUT3, "RTP route is %p through\n",
4130                             (void *)ro->ro_rt);
4131
4132                         if (SCTP_GET_HEADER_FOR_OUTPUT(o_pak)) {
4133                                 /* failed to prepend data, give up */
4134                                 SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
4135                                 sctp_m_freem(m);
4136                                 return (ENOMEM);
4137                         }
4138                         SCTP_ATTACH_CHAIN(o_pak, m, packet_length);
4139                         if (port) {
4140 #if defined(SCTP_WITH_NO_CSUM)
4141                                 SCTP_STAT_INCR(sctps_sendnocrc);
4142 #else
4143                                 sctphdr->checksum = sctp_calculate_cksum(m, sizeof(struct ip) + sizeof(struct udphdr));
4144                                 SCTP_STAT_INCR(sctps_sendswcrc);
4145 #endif
4146                                 if (V_udp_cksum) {
4147                                         SCTP_ENABLE_UDP_CSUM(o_pak);
4148                                 }
4149                         } else {
4150 #if defined(SCTP_WITH_NO_CSUM)
4151                                 SCTP_STAT_INCR(sctps_sendnocrc);
4152 #else
4153                                 m->m_pkthdr.csum_flags = CSUM_SCTP;
4154                                 m->m_pkthdr.csum_data = 0;
4155                                 SCTP_STAT_INCR(sctps_sendhwcrc);
4156 #endif
4157                         }
4158 #ifdef SCTP_PACKET_LOGGING
4159                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LAST_PACKET_TRACING)
4160                                 sctp_packet_log(o_pak);
4161 #endif
4162                         /* send it out.  table id is taken from stcb */
4163 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4164                         if ((SCTP_BASE_SYSCTL(sctp_output_unlocked)) && (so_locked)) {
4165                                 so = SCTP_INP_SO(inp);
4166                                 SCTP_SOCKET_UNLOCK(so, 0);
4167                         }
4168 #endif
4169                         SCTP_IP_OUTPUT(ret, o_pak, ro, stcb, vrf_id);
4170 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4171                         if ((SCTP_BASE_SYSCTL(sctp_output_unlocked)) && (so_locked)) {
4172                                 atomic_add_int(&stcb->asoc.refcnt, 1);
4173                                 SCTP_TCB_UNLOCK(stcb);
4174                                 SCTP_SOCKET_LOCK(so, 0);
4175                                 SCTP_TCB_LOCK(stcb);
4176                                 atomic_subtract_int(&stcb->asoc.refcnt, 1);
4177                         }
4178 #endif
4179                         SCTP_STAT_INCR(sctps_sendpackets);
4180                         SCTP_STAT_INCR_COUNTER64(sctps_outpackets);
4181                         if (ret)
4182                                 SCTP_STAT_INCR(sctps_senderrors);
4183
4184                         SCTPDBG(SCTP_DEBUG_OUTPUT3, "IP output returns %d\n", ret);
4185                         if (net == NULL) {
4186                                 /* free tempy routes */
4187                                 RO_RTFREE(ro);
4188                         } else {
4189                                 /*
4190                                  * PMTU check versus smallest asoc MTU goes
4191                                  * here
4192                                  */
4193                                 if ((ro->ro_rt != NULL) &&
4194                                     (net->ro._s_addr)) {
4195                                         uint32_t mtu;
4196
4197                                         mtu = SCTP_GATHER_MTU_FROM_ROUTE(net->ro._s_addr, &net->ro._l_addr.sa, ro->ro_rt);
4198                                         if (net->port) {
4199                                                 mtu -= sizeof(struct udphdr);
4200                                         }
4201                                         if (mtu && (stcb->asoc.smallest_mtu > mtu)) {
4202                                                 sctp_mtu_size_reset(inp, &stcb->asoc, mtu);
4203                                                 net->mtu = mtu;
4204                                         }
4205                                 } else if (ro->ro_rt == NULL) {
4206                                         /* route was freed */
4207                                         if (net->ro._s_addr &&
4208                                             net->src_addr_selected) {
4209                                                 sctp_free_ifa(net->ro._s_addr);
4210                                                 net->ro._s_addr = NULL;
4211                                         }
4212                                         net->src_addr_selected = 0;
4213                                 }
4214                         }
4215                         return (ret);
4216                 }
4217 #endif
4218 #ifdef INET6
4219         case AF_INET6:
4220                 {
4221                         uint32_t flowlabel, flowinfo;
4222                         struct ip6_hdr *ip6h;
4223                         struct route_in6 ip6route;
4224                         struct ifnet *ifp;
4225                         struct sockaddr_in6 *sin6, tmp, *lsa6, lsa6_tmp;
4226                         int prev_scope = 0;
4227                         struct sockaddr_in6 lsa6_storage;
4228                         int error;
4229                         u_short prev_port = 0;
4230                         int len;
4231
4232                         if (net) {
4233                                 flowlabel = net->flowlabel;
4234                         } else if (stcb) {
4235                                 flowlabel = stcb->asoc.default_flowlabel;
4236                         } else {
4237                                 flowlabel = inp->sctp_ep.default_flowlabel;
4238                         }
4239                         if (flowlabel == 0) {
4240                                 /*
4241                                  * This means especially, that it is not set
4242                                  * at the SCTP layer. So use the value from
4243                                  * the IP layer.
4244                                  */
4245                                 flowlabel = ntohl(((struct in6pcb *)inp)->in6p_flowinfo);
4246                         }
4247                         flowlabel &= 0x000fffff;
4248                         len = sizeof(struct ip6_hdr) + sizeof(struct sctphdr);
4249                         if (port) {
4250                                 len += sizeof(struct udphdr);
4251                         }
4252                         newm = sctp_get_mbuf_for_msg(len, 1, M_DONTWAIT, 1, MT_DATA);
4253                         if (newm == NULL) {
4254                                 sctp_m_freem(m);
4255                                 SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
4256                                 return (ENOMEM);
4257                         }
4258                         SCTP_ALIGN_TO_END(newm, len);
4259                         SCTP_BUF_LEN(newm) = len;
4260                         SCTP_BUF_NEXT(newm) = m;
4261                         m = newm;
4262                         if (net != NULL) {
4263 #ifdef INVARIANTS
4264                                 if (net->flowidset == 0) {
4265                                         panic("Flow ID not set");
4266                                 }
4267 #endif
4268                                 m->m_pkthdr.flowid = net->flowid;
4269                                 m->m_flags |= M_FLOWID;
4270                         } else {
4271                                 if (use_mflowid != 0) {
4272                                         m->m_pkthdr.flowid = mflowid;
4273                                         m->m_flags |= M_FLOWID;
4274                                 }
4275                         }
4276                         packet_length = sctp_calculate_len(m);
4277
4278                         ip6h = mtod(m, struct ip6_hdr *);
4279                         /* protect *sin6 from overwrite */
4280                         sin6 = (struct sockaddr_in6 *)to;
4281                         tmp = *sin6;
4282                         sin6 = &tmp;
4283
4284                         /* KAME hack: embed scopeid */
4285                         if (sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
4286                                 SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
4287                                 return (EINVAL);
4288                         }
4289                         if (net == NULL) {
4290                                 memset(&ip6route, 0, sizeof(ip6route));
4291                                 ro = (sctp_route_t *) & ip6route;
4292                                 memcpy(&ro->ro_dst, sin6, sin6->sin6_len);
4293                         } else {
4294                                 ro = (sctp_route_t *) & net->ro;
4295                         }
4296                         /*
4297                          * We assume here that inp_flow is in host byte
4298                          * order within the TCB!
4299                          */
4300                         if (tos_value == 0) {
4301                                 /*
4302                                  * This means especially, that it is not set
4303                                  * at the SCTP layer. So use the value from
4304                                  * the IP layer.
4305                                  */
4306                                 tos_value = (ntohl(((struct in6pcb *)inp)->in6p_flowinfo) >> 20) & 0xff;
4307                         }
4308                         tos_value &= 0xfc;
4309                         if (ecn_ok) {
4310                                 tos_value |= sctp_get_ect(stcb);
4311                         }
4312                         flowinfo = 0x06;
4313                         flowinfo <<= 8;
4314                         flowinfo |= tos_value;
4315                         flowinfo <<= 20;
4316                         flowinfo |= flowlabel;
4317                         ip6h->ip6_flow = htonl(flowinfo);
4318                         if (port) {
4319                                 ip6h->ip6_nxt = IPPROTO_UDP;
4320                         } else {
4321                                 ip6h->ip6_nxt = IPPROTO_SCTP;
4322                         }
4323                         ip6h->ip6_plen = (packet_length - sizeof(struct ip6_hdr));
4324                         ip6h->ip6_dst = sin6->sin6_addr;
4325
4326                         /*
4327                          * Add SRC address selection here: we can only reuse
4328                          * to a limited degree the kame src-addr-sel, since
4329                          * we can try their selection but it may not be
4330                          * bound.
4331                          */
4332                         bzero(&lsa6_tmp, sizeof(lsa6_tmp));
4333                         lsa6_tmp.sin6_family = AF_INET6;
4334                         lsa6_tmp.sin6_len = sizeof(lsa6_tmp);
4335                         lsa6 = &lsa6_tmp;
4336                         if (net && out_of_asoc_ok == 0) {
4337                                 if (net->ro._s_addr && (net->ro._s_addr->localifa_flags & (SCTP_BEING_DELETED | SCTP_ADDR_IFA_UNUSEABLE))) {
4338                                         sctp_free_ifa(net->ro._s_addr);
4339                                         net->ro._s_addr = NULL;
4340                                         net->src_addr_selected = 0;
4341                                         if (ro->ro_rt) {
4342                                                 RTFREE(ro->ro_rt);
4343                                                 ro->ro_rt = NULL;
4344                                         }
4345                                 }
4346                                 if (net->src_addr_selected == 0) {
4347                                         sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
4348                                         /* KAME hack: embed scopeid */
4349                                         if (sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
4350                                                 SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
4351                                                 return (EINVAL);
4352                                         }
4353                                         /* Cache the source address */
4354                                         net->ro._s_addr = sctp_source_address_selection(inp,
4355                                             stcb,
4356                                             ro,
4357                                             net,
4358                                             0,
4359                                             vrf_id);
4360                                         (void)sa6_recoverscope(sin6);
4361                                         net->src_addr_selected = 1;
4362                                 }
4363                                 if (net->ro._s_addr == NULL) {
4364                                         SCTPDBG(SCTP_DEBUG_OUTPUT3, "V6:No route to host\n");
4365                                         net->src_addr_selected = 0;
4366                                         sctp_handle_no_route(stcb, net, so_locked);
4367                                         SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EHOSTUNREACH);
4368                                         sctp_m_freem(m);
4369                                         return (EHOSTUNREACH);
4370                                 }
4371                                 lsa6->sin6_addr = net->ro._s_addr->address.sin6.sin6_addr;
4372                         } else {
4373                                 sin6 = (struct sockaddr_in6 *)&ro->ro_dst;
4374                                 /* KAME hack: embed scopeid */
4375                                 if (sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
4376                                         SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
4377                                         return (EINVAL);
4378                                 }
4379                                 if (over_addr == NULL) {
4380                                         struct sctp_ifa *_lsrc;
4381
4382                                         _lsrc = sctp_source_address_selection(inp, stcb, ro,
4383                                             net,
4384                                             out_of_asoc_ok,
4385                                             vrf_id);
4386                                         if (_lsrc == NULL) {
4387                                                 sctp_handle_no_route(stcb, net, so_locked);
4388                                                 SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EHOSTUNREACH);
4389                                                 sctp_m_freem(m);
4390                                                 return (EHOSTUNREACH);
4391                                         }
4392                                         lsa6->sin6_addr = _lsrc->address.sin6.sin6_addr;
4393                                         sctp_free_ifa(_lsrc);
4394                                 } else {
4395                                         lsa6->sin6_addr = over_addr->sin6.sin6_addr;
4396                                         SCTP_RTALLOC(ro, vrf_id);
4397                                 }
4398                                 (void)sa6_recoverscope(sin6);
4399                         }
4400                         lsa6->sin6_port = inp->sctp_lport;
4401
4402                         if (ro->ro_rt == NULL) {
4403                                 /*
4404                                  * src addr selection failed to find a route
4405                                  * (or valid source addr), so we can't get
4406                                  * there from here!
4407                                  */
4408                                 sctp_handle_no_route(stcb, net, so_locked);
4409                                 SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EHOSTUNREACH);
4410                                 sctp_m_freem(m);
4411                                 return (EHOSTUNREACH);
4412                         }
4413                         /*
4414                          * XXX: sa6 may not have a valid sin6_scope_id in
4415                          * the non-SCOPEDROUTING case.
4416                          */
4417                         bzero(&lsa6_storage, sizeof(lsa6_storage));
4418                         lsa6_storage.sin6_family = AF_INET6;
4419                         lsa6_storage.sin6_len = sizeof(lsa6_storage);
4420                         lsa6_storage.sin6_addr = lsa6->sin6_addr;
4421                         if ((error = sa6_recoverscope(&lsa6_storage)) != 0) {
4422                                 SCTPDBG(SCTP_DEBUG_OUTPUT3, "recover scope fails error %d\n", error);
4423                                 sctp_m_freem(m);
4424                                 return (error);
4425                         }
4426                         /* XXX */
4427                         lsa6_storage.sin6_addr = lsa6->sin6_addr;
4428                         lsa6_storage.sin6_port = inp->sctp_lport;
4429                         lsa6 = &lsa6_storage;
4430                         ip6h->ip6_src = lsa6->sin6_addr;
4431
4432                         if (port) {
4433                                 if (htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port)) == 0) {
4434                                         sctp_handle_no_route(stcb, net, so_locked);
4435                                         SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EHOSTUNREACH);
4436                                         sctp_m_freem(m);
4437                                         return (EHOSTUNREACH);
4438                                 }
4439                                 udp = (struct udphdr *)((caddr_t)ip6h + sizeof(struct ip6_hdr));
4440                                 udp->uh_sport = htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port));
4441                                 udp->uh_dport = port;
4442                                 udp->uh_ulen = htons(packet_length - sizeof(struct ip6_hdr));
4443                                 udp->uh_sum = 0;
4444                                 sctphdr = (struct sctphdr *)((caddr_t)udp + sizeof(struct udphdr));
4445                         } else {
4446                                 sctphdr = (struct sctphdr *)((caddr_t)ip6h + sizeof(struct ip6_hdr));
4447                         }
4448
4449                         sctphdr->src_port = src_port;
4450                         sctphdr->dest_port = dest_port;
4451                         sctphdr->v_tag = v_tag;
4452                         sctphdr->checksum = 0;
4453
4454                         /*
4455                          * We set the hop limit now since there is a good
4456                          * chance that our ro pointer is now filled
4457                          */
4458                         ip6h->ip6_hlim = SCTP_GET_HLIM(inp, ro);
4459                         ifp = SCTP_GET_IFN_VOID_FROM_ROUTE(ro);
4460
4461 #ifdef SCTP_DEBUG
4462                         /* Copy to be sure something bad is not happening */
4463                         sin6->sin6_addr = ip6h->ip6_dst;
4464                         lsa6->sin6_addr = ip6h->ip6_src;
4465 #endif
4466
4467                         SCTPDBG(SCTP_DEBUG_OUTPUT3, "Calling ipv6 output routine from low level\n");
4468                         SCTPDBG(SCTP_DEBUG_OUTPUT3, "src: ");
4469                         SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT3, (struct sockaddr *)lsa6);
4470                         SCTPDBG(SCTP_DEBUG_OUTPUT3, "dst: ");
4471                         SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT3, (struct sockaddr *)sin6);
4472                         if (net) {
4473                                 sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
4474                                 /*
4475                                  * preserve the port and scope for link
4476                                  * local send
4477                                  */
4478                                 prev_scope = sin6->sin6_scope_id;
4479                                 prev_port = sin6->sin6_port;
4480                         }
4481                         if (SCTP_GET_HEADER_FOR_OUTPUT(o_pak)) {
4482                                 /* failed to prepend data, give up */
4483                                 sctp_m_freem(m);
4484                                 SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
4485                                 return (ENOMEM);
4486                         }
4487                         SCTP_ATTACH_CHAIN(o_pak, m, packet_length);
4488                         if (port) {
4489 #if defined(SCTP_WITH_NO_CSUM)
4490                                 SCTP_STAT_INCR(sctps_sendnocrc);
4491 #else
4492                                 sctphdr->checksum = sctp_calculate_cksum(m, sizeof(struct ip6_hdr) + sizeof(struct udphdr));
4493                                 SCTP_STAT_INCR(sctps_sendswcrc);
4494 #endif
4495                                 if ((udp->uh_sum = in6_cksum(o_pak, IPPROTO_UDP, sizeof(struct ip6_hdr), packet_length - sizeof(struct ip6_hdr))) == 0) {
4496                                         udp->uh_sum = 0xffff;
4497                                 }
4498                         } else {
4499 #if defined(SCTP_WITH_NO_CSUM)
4500                                 SCTP_STAT_INCR(sctps_sendnocrc);
4501 #else
4502                                 m->m_pkthdr.csum_flags = CSUM_SCTP_IPV6;
4503                                 m->m_pkthdr.csum_data = 0;
4504                                 SCTP_STAT_INCR(sctps_sendhwcrc);
4505 #endif
4506                         }
4507                         /* send it out. table id is taken from stcb */
4508 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4509                         if ((SCTP_BASE_SYSCTL(sctp_output_unlocked)) && (so_locked)) {
4510                                 so = SCTP_INP_SO(inp);
4511                                 SCTP_SOCKET_UNLOCK(so, 0);
4512                         }
4513 #endif
4514 #ifdef SCTP_PACKET_LOGGING
4515                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LAST_PACKET_TRACING)
4516                                 sctp_packet_log(o_pak);
4517 #endif
4518                         SCTP_IP6_OUTPUT(ret, o_pak, (struct route_in6 *)ro, &ifp, stcb, vrf_id);
4519 #if defined(__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4520                         if ((SCTP_BASE_SYSCTL(sctp_output_unlocked)) && (so_locked)) {
4521                                 atomic_add_int(&stcb->asoc.refcnt, 1);
4522                                 SCTP_TCB_UNLOCK(stcb);
4523                                 SCTP_SOCKET_LOCK(so, 0);
4524                                 SCTP_TCB_LOCK(stcb);
4525                                 atomic_subtract_int(&stcb->asoc.refcnt, 1);
4526                         }
4527 #endif
4528                         if (net) {
4529                                 /* for link local this must be done */
4530                                 sin6->sin6_scope_id = prev_scope;
4531                                 sin6->sin6_port = prev_port;
4532                         }
4533                         SCTPDBG(SCTP_DEBUG_OUTPUT3, "return from send is %d\n", ret);
4534                         SCTP_STAT_INCR(sctps_sendpackets);
4535                         SCTP_STAT_INCR_COUNTER64(sctps_outpackets);
4536                         if (ret) {
4537                                 SCTP_STAT_INCR(sctps_senderrors);
4538                         }
4539                         if (net == NULL) {
4540                                 /* Now if we had a temp route free it */
4541                                 RO_RTFREE(ro);
4542                         } else {
4543                                 /*
4544                                  * PMTU check versus smallest asoc MTU goes
4545                                  * here
4546                                  */
4547                                 if (ro->ro_rt == NULL) {
4548                                         /* Route was freed */
4549                                         if (net->ro._s_addr &&
4550                                             net->src_addr_selected) {
4551                                                 sctp_free_ifa(net->ro._s_addr);
4552                                                 net->ro._s_addr = NULL;
4553                                         }
4554                                         net->src_addr_selected = 0;
4555                                 }
4556                                 if ((ro->ro_rt != NULL) &&
4557                                     (net->ro._s_addr)) {
4558                                         uint32_t mtu;
4559
4560                                         mtu = SCTP_GATHER_MTU_FROM_ROUTE(net->ro._s_addr, &net->ro._l_addr.sa, ro->ro_rt);
4561                                         if (mtu &&
4562                                             (stcb->asoc.smallest_mtu > mtu)) {
4563                                                 sctp_mtu_size_reset(inp, &stcb->asoc, mtu);
4564                                                 net->mtu = mtu;
4565                                                 if (net->port) {
4566                                                         net->mtu -= sizeof(struct udphdr);
4567                                                 }
4568                                         }
4569                                 } else if (ifp) {
4570                                         if (ND_IFINFO(ifp)->linkmtu &&
4571                                             (stcb->asoc.smallest_mtu > ND_IFINFO(ifp)->linkmtu)) {
4572                                                 sctp_mtu_size_reset(inp,
4573                                                     &stcb->asoc,
4574                                                     ND_IFINFO(ifp)->linkmtu);
4575                                         }
4576                                 }
4577                         }
4578                         return (ret);
4579                 }
4580 #endif
4581         default:
4582                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "Unknown protocol (TSNH) type %d\n",
4583                     ((struct sockaddr *)to)->sa_family);
4584                 sctp_m_freem(m);
4585                 SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EFAULT);
4586                 return (EFAULT);
4587         }
4588 }
4589
4590
4591 void
4592 sctp_send_initiate(struct sctp_inpcb *inp, struct sctp_tcb *stcb, int so_locked
4593 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
4594     SCTP_UNUSED
4595 #endif
4596 )
4597 {
4598         struct sctp_scoping scp;
4599         struct mbuf *m;
4600         struct sctp_nets *net;
4601         struct sctp_init_chunk *init;
4602         struct sctp_supported_addr_param *sup_addr;
4603         struct sctp_adaptation_layer_indication *ali;
4604         struct sctp_supported_chunk_types_param *pr_supported;
4605         struct sctp_paramhdr *ph;
4606         int cnt_inits_to = 0;
4607         int ret;
4608         uint16_t num_ext, chunk_len, padding_len, parameter_len;
4609
4610         /* INIT's always go to the primary (and usually ONLY address) */
4611         net = stcb->asoc.primary_destination;
4612         if (net == NULL) {
4613                 net = TAILQ_FIRST(&stcb->asoc.nets);
4614                 if (net == NULL) {
4615                         /* TSNH */
4616                         return;
4617                 }
4618                 /* we confirm any address we send an INIT to */
4619                 net->dest_state &= ~SCTP_ADDR_UNCONFIRMED;
4620                 (void)sctp_set_primary_addr(stcb, NULL, net);
4621         } else {
4622                 /* we confirm any address we send an INIT to */
4623                 net->dest_state &= ~SCTP_ADDR_UNCONFIRMED;
4624         }
4625         SCTPDBG(SCTP_DEBUG_OUTPUT4, "Sending INIT\n");
4626 #ifdef INET6
4627         if (net->ro._l_addr.sa.sa_family == AF_INET6) {
4628                 /*
4629                  * special hook, if we are sending to link local it will not
4630                  * show up in our private address count.
4631                  */
4632                 if (IN6_IS_ADDR_LINKLOCAL(&net->ro._l_addr.sin6.sin6_addr))
4633                         cnt_inits_to = 1;
4634         }
4635 #endif
4636         if (SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer)) {
4637                 /* This case should not happen */
4638                 SCTPDBG(SCTP_DEBUG_OUTPUT4, "Sending INIT - failed timer?\n");
4639                 return;
4640         }
4641         /* start the INIT timer */
4642         sctp_timer_start(SCTP_TIMER_TYPE_INIT, inp, stcb, net);
4643
4644         m = sctp_get_mbuf_for_msg(MCLBYTES, 1, M_DONTWAIT, 1, MT_DATA);
4645         if (m == NULL) {
4646                 /* No memory, INIT timer will re-attempt. */
4647                 SCTPDBG(SCTP_DEBUG_OUTPUT4, "Sending INIT - mbuf?\n");
4648                 return;
4649         }
4650         chunk_len = (uint16_t) sizeof(struct sctp_init_chunk);
4651         padding_len = 0;
4652         /*
4653          * assume peer supports asconf in order to be able to queue local
4654          * address changes while an INIT is in flight and before the assoc
4655          * is established.
4656          */
4657         stcb->asoc.peer_supports_asconf = 1;
4658         /* Now lets put the chunk header in place */
4659         init = mtod(m, struct sctp_init_chunk *);
4660         /* now the chunk header */
4661         init->ch.chunk_type = SCTP_INITIATION;
4662         init->ch.chunk_flags = 0;
4663         /* fill in later from mbuf we build */
4664         init->ch.chunk_length = 0;
4665         /* place in my tag */
4666         init->init.initiate_tag = htonl(stcb->asoc.my_vtag);
4667         /* set up some of the credits. */
4668         init->init.a_rwnd = htonl(max(inp->sctp_socket ? SCTP_SB_LIMIT_RCV(inp->sctp_socket) : 0,
4669             SCTP_MINIMAL_RWND));
4670         init->init.num_outbound_streams = htons(stcb->asoc.pre_open_streams);
4671         init->init.num_inbound_streams = htons(stcb->asoc.max_inbound_streams);
4672         init->init.initial_tsn = htonl(stcb->asoc.init_seq_number);
4673
4674 #if defined(INET) || defined(INET6)
4675         /* now the address restriction */
4676         /* XXX Should we take the address family of the socket into account? */
4677         sup_addr = (struct sctp_supported_addr_param *)(mtod(m, caddr_t)+chunk_len);
4678         sup_addr->ph.param_type = htons(SCTP_SUPPORTED_ADDRTYPE);
4679 #ifdef INET6
4680 #ifdef INET
4681         /* we support 2 types: IPv4/IPv6 */
4682         parameter_len = (uint16_t) (sizeof(struct sctp_paramhdr) + 2 * sizeof(uint16_t));
4683         sup_addr->ph.param_length = htons(parameter_len);
4684         sup_addr->addr_type[0] = htons(SCTP_IPV4_ADDRESS);
4685         sup_addr->addr_type[1] = htons(SCTP_IPV6_ADDRESS);
4686         padding_len = 0;
4687 #else
4688         /* we support 1 type: IPv6 */
4689         parameter_len = (uint16_t) (sizeof(struct sctp_paramhdr) + sizeof(uint16_t));
4690         sup_addr->ph.param_length = htons(parameter_len);
4691         sup_addr->addr_type[0] = htons(SCTP_IPV6_ADDRESS);
4692         sup_addr->addr_type[1] = htons(0);      /* this is the padding */
4693         padding_len = (uint16_t) sizeof(uint16_t);
4694 #endif
4695 #else
4696         /* we support 1 type: IPv4 */
4697         parameter_len = (uint16_t) (sizeof(struct sctp_paramhdr) + sizeof(uint16_t));
4698         sup_addr->ph.param_length = htons(parameter_len);
4699         sup_addr->addr_type[0] = htons(SCTP_IPV4_ADDRESS);
4700         sup_addr->addr_type[1] = htons(0);      /* this is the padding */
4701         padding_len = (uint16_t) sizeof(uint16_t);
4702 #endif
4703         chunk_len += parameter_len;
4704 #endif
4705         /* Adaptation layer indication parameter */
4706         /* XXX: Should we include this always? */
4707         if (padding_len > 0) {
4708                 memset(mtod(m, caddr_t)+chunk_len, 0, padding_len);
4709                 chunk_len += padding_len;
4710                 padding_len = 0;
4711         }
4712         parameter_len = (uint16_t) sizeof(struct sctp_adaptation_layer_indication);
4713         ali = (struct sctp_adaptation_layer_indication *)(mtod(m, caddr_t)+chunk_len);
4714         ali->ph.param_type = htons(SCTP_ULP_ADAPTATION);
4715         ali->ph.param_length = htons(parameter_len);
4716         ali->indication = ntohl(inp->sctp_ep.adaptation_layer_indicator);
4717         chunk_len += parameter_len;
4718
4719         if (SCTP_BASE_SYSCTL(sctp_inits_include_nat_friendly)) {
4720                 /* Add NAT friendly parameter. */
4721                 if (padding_len > 0) {
4722                         memset(mtod(m, caddr_t)+chunk_len, 0, padding_len);
4723                         chunk_len += padding_len;
4724                         padding_len = 0;
4725                 }
4726                 parameter_len = (uint16_t) sizeof(struct sctp_paramhdr);
4727                 ph = (struct sctp_paramhdr *)(mtod(m, caddr_t)+chunk_len);
4728                 ph->param_type = htons(SCTP_HAS_NAT_SUPPORT);
4729                 ph->param_length = htons(parameter_len);
4730                 chunk_len += parameter_len;
4731         }
4732         /* now any cookie time extensions */
4733         if (stcb->asoc.cookie_preserve_req) {
4734                 struct sctp_cookie_perserve_param *cookie_preserve;
4735
4736                 if (padding_len > 0) {
4737                         memset(mtod(m, caddr_t)+chunk_len, 0, padding_len);
4738                         chunk_len += padding_len;
4739                         padding_len = 0;
4740                 }
4741                 parameter_len = (uint16_t) sizeof(struct sctp_cookie_perserve_param);
4742                 cookie_preserve = (struct sctp_cookie_perserve_param *)(mtod(m, caddr_t)+chunk_len);
4743                 cookie_preserve->ph.param_type = htons(SCTP_COOKIE_PRESERVE);
4744                 cookie_preserve->ph.param_length = htons(parameter_len);
4745                 cookie_preserve->time = htonl(stcb->asoc.cookie_preserve_req);
4746                 stcb->asoc.cookie_preserve_req = 0;
4747                 chunk_len += parameter_len;
4748         }
4749         /* ECN parameter */
4750         if (stcb->asoc.ecn_allowed == 1) {
4751                 if (padding_len > 0) {
4752                         memset(mtod(m, caddr_t)+chunk_len, 0, padding_len);
4753                         chunk_len += padding_len;
4754                         padding_len = 0;
4755                 }
4756                 parameter_len = (uint16_t) sizeof(struct sctp_paramhdr);
4757                 ph = (struct sctp_paramhdr *)(mtod(m, caddr_t)+chunk_len);
4758                 ph->param_type = htons(SCTP_ECN_CAPABLE);
4759                 ph->param_length = htons(parameter_len);
4760                 chunk_len += parameter_len;
4761         }
4762         /* And now tell the peer we do support PR-SCTP. */
4763         if (padding_len > 0) {
4764                 memset(mtod(m, caddr_t)+chunk_len, 0, padding_len);
4765                 chunk_len += padding_len;
4766                 padding_len = 0;
4767         }
4768         parameter_len = (uint16_t) sizeof(struct sctp_paramhdr);
4769         ph = (struct sctp_paramhdr *)(mtod(m, caddr_t)+chunk_len);
4770         ph->param_type = htons(SCTP_PRSCTP_SUPPORTED);
4771         ph->param_length = htons(parameter_len);
4772         chunk_len += parameter_len;
4773
4774         /* And now tell the peer we do all the extensions */
4775         pr_supported = (struct sctp_supported_chunk_types_param *)(mtod(m, caddr_t)+chunk_len);
4776         pr_supported->ph.param_type = htons(SCTP_SUPPORTED_CHUNK_EXT);
4777         num_ext = 0;
4778         pr_supported->chunk_types[num_ext++] = SCTP_ASCONF;
4779         pr_supported->chunk_types[num_ext++] = SCTP_ASCONF_ACK;
4780         pr_supported->chunk_types[num_ext++] = SCTP_FORWARD_CUM_TSN;
4781         pr_supported->chunk_types[num_ext++] = SCTP_PACKET_DROPPED;
4782         pr_supported->chunk_types[num_ext++] = SCTP_STREAM_RESET;
4783         if (!SCTP_BASE_SYSCTL(sctp_auth_disable)) {
4784                 pr_supported->chunk_types[num_ext++] = SCTP_AUTHENTICATION;
4785         }
4786         if (stcb->asoc.sctp_nr_sack_on_off == 1) {
4787                 pr_supported->chunk_types[num_ext++] = SCTP_NR_SELECTIVE_ACK;
4788         }
4789         parameter_len = (uint16_t) sizeof(struct sctp_supported_chunk_types_param) + num_ext;
4790         pr_supported->ph.param_length = htons(parameter_len);
4791         padding_len = SCTP_SIZE32(parameter_len) - parameter_len;
4792         chunk_len += parameter_len;
4793
4794         /* add authentication parameters */
4795         if (!SCTP_BASE_SYSCTL(sctp_auth_disable)) {
4796                 /* attach RANDOM parameter, if available */
4797                 if (stcb->asoc.authinfo.random != NULL) {
4798                         struct sctp_auth_random *randp;
4799
4800                         if (padding_len > 0) {
4801                                 memset(mtod(m, caddr_t)+chunk_len, 0, padding_len);
4802                                 chunk_len += padding_len;
4803                                 padding_len = 0;
4804                         }
4805                         randp = (struct sctp_auth_random *)(mtod(m, caddr_t)+chunk_len);
4806                         parameter_len = (uint16_t) sizeof(struct sctp_auth_random) + stcb->asoc.authinfo.random_len;
4807                         /* random key already contains the header */
4808                         memcpy(randp, stcb->asoc.authinfo.random->key, parameter_len);
4809                         padding_len = SCTP_SIZE32(parameter_len) - parameter_len;
4810                         chunk_len += parameter_len;
4811                 }
4812                 /* add HMAC_ALGO parameter */
4813                 if ((stcb->asoc.local_hmacs != NULL) &&
4814                     (stcb->asoc.local_hmacs->num_algo > 0)) {
4815                         struct sctp_auth_hmac_algo *hmacs;
4816
4817                         if (padding_len > 0) {
4818                                 memset(mtod(m, caddr_t)+chunk_len, 0, padding_len);
4819                                 chunk_len += padding_len;
4820                                 padding_len = 0;
4821                         }
4822                         hmacs = (struct sctp_auth_hmac_algo *)(mtod(m, caddr_t)+chunk_len);
4823                         parameter_len = (uint16_t) (sizeof(struct sctp_auth_hmac_algo) +
4824                             stcb->asoc.local_hmacs->num_algo * sizeof(uint16_t));
4825                         hmacs->ph.param_type = htons(SCTP_HMAC_LIST);
4826                         hmacs->ph.param_length = htons(parameter_len);
4827                         sctp_serialize_hmaclist(stcb->asoc.local_hmacs, (uint8_t *) hmacs->hmac_ids);
4828                         padding_len = SCTP_SIZE32(parameter_len) - parameter_len;
4829                         chunk_len += parameter_len;
4830                 }
4831                 /* add CHUNKS parameter */
4832                 if (sctp_auth_get_chklist_size(stcb->asoc.local_auth_chunks) > 0) {
4833                         struct sctp_auth_chunk_list *chunks;
4834
4835                         if (padding_len > 0) {
4836                                 memset(mtod(m, caddr_t)+chunk_len, 0, padding_len);
4837                                 chunk_len += padding_len;
4838                                 padding_len = 0;
4839                         }
4840                         chunks = (struct sctp_auth_chunk_list *)(mtod(m, caddr_t)+chunk_len);
4841                         parameter_len = (uint16_t) (sizeof(struct sctp_auth_chunk_list) +
4842                             sctp_auth_get_chklist_size(stcb->asoc.local_auth_chunks));
4843                         chunks->ph.param_type = htons(SCTP_CHUNK_LIST);
4844                         chunks->ph.param_length = htons(parameter_len);
4845                         sctp_serialize_auth_chunks(stcb->asoc.local_auth_chunks, chunks->chunk_types);
4846                         padding_len = SCTP_SIZE32(parameter_len) - parameter_len;
4847                         chunk_len += parameter_len;
4848                 }
4849         }
4850         SCTP_BUF_LEN(m) = chunk_len;
4851
4852         /* now the addresses */
4853         /*
4854          * To optimize this we could put the scoping stuff into a structure
4855          * and remove the individual uint8's from the assoc structure. Then
4856          * we could just sifa in the address within the stcb. But for now
4857          * this is a quick hack to get the address stuff teased apart.
4858          */
4859         scp.ipv4_addr_legal = stcb->asoc.ipv4_addr_legal;
4860         scp.ipv6_addr_legal = stcb->asoc.ipv6_addr_legal;
4861         scp.loopback_scope = stcb->asoc.loopback_scope;
4862         scp.ipv4_local_scope = stcb->asoc.ipv4_local_scope;
4863         scp.local_scope = stcb->asoc.local_scope;
4864         scp.site_scope = stcb->asoc.site_scope;
4865         sctp_add_addresses_to_i_ia(inp, stcb, &scp, m, cnt_inits_to, &padding_len, &chunk_len);
4866
4867         init->ch.chunk_length = htons(chunk_len);
4868         if (padding_len > 0) {
4869                 struct mbuf *m_at, *mp_last;
4870
4871                 mp_last = NULL;
4872                 for (m_at = m; m_at; m_at = SCTP_BUF_NEXT(m_at)) {
4873                         if (SCTP_BUF_NEXT(m_at) == NULL)
4874                                 mp_last = m_at;
4875                 }
4876                 if ((mp_last == NULL) || sctp_add_pad_tombuf(mp_last, padding_len)) {
4877                         sctp_m_freem(m);
4878                         return;
4879                 }
4880         }
4881         SCTPDBG(SCTP_DEBUG_OUTPUT4, "Sending INIT - calls lowlevel_output\n");
4882         ret = sctp_lowlevel_chunk_output(inp, stcb, net,
4883             (struct sockaddr *)&net->ro._l_addr,
4884             m, 0, NULL, 0, 0, 0, 0,
4885             inp->sctp_lport, stcb->rport, htonl(0),
4886             net->port, NULL,
4887             0, 0,
4888             so_locked);
4889         SCTPDBG(SCTP_DEBUG_OUTPUT4, "lowlevel_output - %d\n", ret);
4890         SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
4891         (void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
4892 }
4893
4894 struct mbuf *
4895 sctp_arethere_unrecognized_parameters(struct mbuf *in_initpkt,
4896     int param_offset, int *abort_processing, struct sctp_chunkhdr *cp, int *nat_friendly)
4897 {
4898         /*
4899          * Given a mbuf containing an INIT or INIT-ACK with the param_offset
4900          * being equal to the beginning of the params i.e. (iphlen +
4901          * sizeof(struct sctp_init_msg) parse through the parameters to the
4902          * end of the mbuf verifying that all parameters are known.
4903          * 
4904          * For unknown parameters build and return a mbuf with
4905          * UNRECOGNIZED_PARAMETER errors. If the flags indicate to stop
4906          * processing this chunk stop, and set *abort_processing to 1.
4907          * 
4908          * By having param_offset be pre-set to where parameters begin it is
4909          * hoped that this routine may be reused in the future by new
4910          * features.
4911          */
4912         struct sctp_paramhdr *phdr, params;
4913
4914         struct mbuf *mat, *op_err;
4915         char tempbuf[SCTP_PARAM_BUFFER_SIZE];
4916         int at, limit, pad_needed;
4917         uint16_t ptype, plen, padded_size;
4918         int err_at;
4919
4920         *abort_processing = 0;
4921         mat = in_initpkt;
4922         err_at = 0;
4923         limit = ntohs(cp->chunk_length) - sizeof(struct sctp_init_chunk);
4924         at = param_offset;
4925         op_err = NULL;
4926         SCTPDBG(SCTP_DEBUG_OUTPUT1, "Check for unrecognized param's\n");
4927         phdr = sctp_get_next_param(mat, at, &params, sizeof(params));
4928         while ((phdr != NULL) && ((size_t)limit >= sizeof(struct sctp_paramhdr))) {
4929                 ptype = ntohs(phdr->param_type);
4930                 plen = ntohs(phdr->param_length);
4931                 if ((plen > limit) || (plen < sizeof(struct sctp_paramhdr))) {
4932                         /* wacked parameter */
4933                         SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error %d\n", plen);
4934                         goto invalid_size;
4935                 }
4936                 limit -= SCTP_SIZE32(plen);
4937                 /*-
4938                  * All parameters for all chunks that we know/understand are
4939                  * listed here. We process them other places and make
4940                  * appropriate stop actions per the upper bits. However this
4941                  * is the generic routine processor's can call to get back
4942                  * an operr.. to either incorporate (init-ack) or send.
4943                  */
4944                 padded_size = SCTP_SIZE32(plen);
4945                 switch (ptype) {
4946                         /* Param's with variable size */
4947                 case SCTP_HEARTBEAT_INFO:
4948                 case SCTP_STATE_COOKIE:
4949                 case SCTP_UNRECOG_PARAM:
4950                 case SCTP_ERROR_CAUSE_IND:
4951                         /* ok skip fwd */
4952                         at += padded_size;
4953                         break;
4954                         /* Param's with variable size within a range */
4955                 case SCTP_CHUNK_LIST:
4956                 case SCTP_SUPPORTED_CHUNK_EXT:
4957                         if (padded_size > (sizeof(struct sctp_supported_chunk_types_param) + (sizeof(uint8_t) * SCTP_MAX_SUPPORTED_EXT))) {
4958                                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error chklist %d\n", plen);
4959                                 goto invalid_size;
4960                         }
4961                         at += padded_size;
4962                         break;
4963                 case SCTP_SUPPORTED_ADDRTYPE:
4964                         if (padded_size > SCTP_MAX_ADDR_PARAMS_SIZE) {
4965                                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error supaddrtype %d\n", plen);
4966                                 goto invalid_size;
4967                         }
4968                         at += padded_size;
4969                         break;
4970                 case SCTP_RANDOM:
4971                         if (padded_size > (sizeof(struct sctp_auth_random) + SCTP_RANDOM_MAX_SIZE)) {
4972                                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error random %d\n", plen);
4973                                 goto invalid_size;
4974                         }
4975                         at += padded_size;
4976                         break;
4977                 case SCTP_SET_PRIM_ADDR:
4978                 case SCTP_DEL_IP_ADDRESS:
4979                 case SCTP_ADD_IP_ADDRESS:
4980                         if ((padded_size != sizeof(struct sctp_asconf_addrv4_param)) &&
4981                             (padded_size != sizeof(struct sctp_asconf_addr_param))) {
4982                                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error setprim %d\n", plen);
4983                                 goto invalid_size;
4984                         }
4985                         at += padded_size;
4986                         break;
4987                         /* Param's with a fixed size */
4988                 case SCTP_IPV4_ADDRESS:
4989                         if (padded_size != sizeof(struct sctp_ipv4addr_param)) {
4990                                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error ipv4 addr %d\n", plen);
4991                                 goto invalid_size;
4992                         }
4993                         at += padded_size;
4994                         break;
4995                 case SCTP_IPV6_ADDRESS:
4996                         if (padded_size != sizeof(struct sctp_ipv6addr_param)) {
4997                                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error ipv6 addr %d\n", plen);
4998                                 goto invalid_size;
4999                         }
5000                         at += padded_size;
5001                         break;
5002                 case SCTP_COOKIE_PRESERVE:
5003                         if (padded_size != sizeof(struct sctp_cookie_perserve_param)) {
5004                                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error cookie-preserve %d\n", plen);
5005                                 goto invalid_size;
5006                         }
5007                         at += padded_size;
5008                         break;
5009                 case SCTP_HAS_NAT_SUPPORT:
5010                         *nat_friendly = 1;
5011                         /* fall through */
5012                 case SCTP_PRSCTP_SUPPORTED:
5013
5014                         if (padded_size != sizeof(struct sctp_paramhdr)) {
5015                                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error prsctp/nat support %d\n", plen);
5016                                 goto invalid_size;
5017                         }
5018                         at += padded_size;
5019                         break;
5020                 case SCTP_ECN_CAPABLE:
5021                         if (padded_size != sizeof(struct sctp_ecn_supported_param)) {
5022                                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error ecn %d\n", plen);
5023                                 goto invalid_size;
5024                         }
5025                         at += padded_size;
5026                         break;
5027                 case SCTP_ULP_ADAPTATION:
5028                         if (padded_size != sizeof(struct sctp_adaptation_layer_indication)) {
5029                                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error adapatation %d\n", plen);
5030                                 goto invalid_size;
5031                         }
5032                         at += padded_size;
5033                         break;
5034                 case SCTP_SUCCESS_REPORT:
5035                         if (padded_size != sizeof(struct sctp_asconf_paramhdr)) {
5036                                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error success %d\n", plen);
5037                                 goto invalid_size;
5038                         }
5039                         at += padded_size;
5040                         break;
5041                 case SCTP_HOSTNAME_ADDRESS:
5042                         {
5043                                 /* We can NOT handle HOST NAME addresses!! */
5044                                 int l_len;
5045
5046                                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "Can't handle hostname addresses.. abort processing\n");
5047                                 *abort_processing = 1;
5048                                 if (op_err == NULL) {
5049                                         /* Ok need to try to get a mbuf */
5050 #ifdef INET6
5051                                         l_len = sizeof(struct ip6_hdr) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
5052 #else
5053                                         l_len = sizeof(struct ip) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
5054 #endif
5055                                         l_len += plen;
5056                                         l_len += sizeof(struct sctp_paramhdr);
5057                                         op_err = sctp_get_mbuf_for_msg(l_len, 0, M_DONTWAIT, 1, MT_DATA);
5058                                         if (op_err) {
5059                                                 SCTP_BUF_LEN(op_err) = 0;
5060                                                 /*
5061                                                  * pre-reserve space for ip
5062                                                  * and sctp header  and
5063                                                  * chunk hdr
5064                                                  */
5065 #ifdef INET6
5066                                                 SCTP_BUF_RESV_UF(op_err, sizeof(struct ip6_hdr));
5067 #else
5068                                                 SCTP_BUF_RESV_UF(op_err, sizeof(struct ip));
5069 #endif
5070                                                 SCTP_BUF_RESV_UF(op_err, sizeof(struct sctphdr));
5071                                                 SCTP_BUF_RESV_UF(op_err, sizeof(struct sctp_chunkhdr));
5072                                         }
5073                                 }
5074                                 if (op_err) {
5075                                         /* If we have space */
5076                                         struct sctp_paramhdr s;
5077
5078                                         if (err_at % 4) {
5079                                                 uint32_t cpthis = 0;
5080
5081                                                 pad_needed = 4 - (err_at % 4);
5082                                                 m_copyback(op_err, err_at, pad_needed, (caddr_t)&cpthis);
5083                                                 err_at += pad_needed;
5084                                         }
5085                                         s.param_type = htons(SCTP_CAUSE_UNRESOLVABLE_ADDR);
5086                                         s.param_length = htons(sizeof(s) + plen);
5087                                         m_copyback(op_err, err_at, sizeof(s), (caddr_t)&s);
5088                                         err_at += sizeof(s);
5089                                         phdr = sctp_get_next_param(mat, at, (struct sctp_paramhdr *)tempbuf, min(sizeof(tempbuf), plen));
5090                                         if (phdr == NULL) {
5091                                                 sctp_m_freem(op_err);
5092                                                 /*
5093                                                  * we are out of memory but
5094                                                  * we still need to have a
5095                                                  * look at what to do (the
5096                                                  * system is in trouble
5097                                                  * though).
5098                                                  */
5099                                                 return (NULL);
5100                                         }
5101                                         m_copyback(op_err, err_at, plen, (caddr_t)phdr);
5102                                 }
5103                                 return (op_err);
5104                                 break;
5105                         }
5106                 default:
5107                         /*
5108                          * we do not recognize the parameter figure out what
5109                          * we do.
5110                          */
5111                         SCTPDBG(SCTP_DEBUG_OUTPUT1, "Hit default param %x\n", ptype);
5112                         if ((ptype & 0x4000) == 0x4000) {
5113                                 /* Report bit is set?? */
5114                                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "report op err\n");
5115                                 if (op_err == NULL) {
5116                                         int l_len;
5117
5118                                         /* Ok need to try to get an mbuf */
5119 #ifdef INET6
5120                                         l_len = sizeof(struct ip6_hdr) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
5121 #else
5122                                         l_len = sizeof(struct ip) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
5123 #endif
5124                                         l_len += plen;
5125                                         l_len += sizeof(struct sctp_paramhdr);
5126                                         op_err = sctp_get_mbuf_for_msg(l_len, 0, M_DONTWAIT, 1, MT_DATA);
5127                                         if (op_err) {
5128                                                 SCTP_BUF_LEN(op_err) = 0;
5129 #ifdef INET6
5130                                                 SCTP_BUF_RESV_UF(op_err, sizeof(struct ip6_hdr));
5131 #else
5132                                                 SCTP_BUF_RESV_UF(op_err, sizeof(struct ip));
5133 #endif
5134                                                 SCTP_BUF_RESV_UF(op_err, sizeof(struct sctphdr));
5135                                                 SCTP_BUF_RESV_UF(op_err, sizeof(struct sctp_chunkhdr));
5136                                         }
5137                                 }
5138                                 if (op_err) {
5139                                         /* If we have space */
5140                                         struct sctp_paramhdr s;
5141
5142                                         if (err_at % 4) {
5143                                                 uint32_t cpthis = 0;
5144
5145                                                 pad_needed = 4 - (err_at % 4);
5146                                                 m_copyback(op_err, err_at, pad_needed, (caddr_t)&cpthis);
5147                                                 err_at += pad_needed;
5148                                         }
5149                                         s.param_type = htons(SCTP_UNRECOG_PARAM);
5150                                         s.param_length = htons(sizeof(s) + plen);
5151                                         m_copyback(op_err, err_at, sizeof(s), (caddr_t)&s);
5152                                         err_at += sizeof(s);
5153                                         if (plen > sizeof(tempbuf)) {
5154                                                 plen = sizeof(tempbuf);
5155                                         }
5156                                         phdr = sctp_get_next_param(mat, at, (struct sctp_paramhdr *)tempbuf, min(sizeof(tempbuf), plen));
5157                                         if (phdr == NULL) {
5158                                                 sctp_m_freem(op_err);
5159                                                 /*
5160                                                  * we are out of memory but
5161                                                  * we still need to have a
5162                                                  * look at what to do (the
5163                                                  * system is in trouble
5164                                                  * though).
5165                                                  */
5166                                                 op_err = NULL;
5167                                                 goto more_processing;
5168                                         }
5169                                         m_copyback(op_err, err_at, plen, (caddr_t)phdr);
5170                                         err_at += plen;
5171                                 }
5172                         }
5173         more_processing:
5174                         if ((ptype & 0x8000) == 0x0000) {
5175                                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "stop proc\n");
5176                                 return (op_err);
5177                         } else {
5178                                 /* skip this chunk and continue processing */
5179                                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "move on\n");
5180                                 at += SCTP_SIZE32(plen);
5181                         }
5182                         break;
5183
5184                 }
5185                 phdr = sctp_get_next_param(mat, at, &params, sizeof(params));
5186         }
5187         return (op_err);
5188 invalid_size:
5189         SCTPDBG(SCTP_DEBUG_OUTPUT1, "abort flag set\n");
5190         *abort_processing = 1;
5191         if ((op_err == NULL) && phdr) {
5192                 int l_len;
5193
5194 #ifdef INET6
5195                 l_len = sizeof(struct ip6_hdr) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
5196 #else
5197                 l_len = sizeof(struct ip) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
5198 #endif
5199                 l_len += (2 * sizeof(struct sctp_paramhdr));
5200                 op_err = sctp_get_mbuf_for_msg(l_len, 0, M_DONTWAIT, 1, MT_DATA);
5201                 if (op_err) {
5202                         SCTP_BUF_LEN(op_err) = 0;
5203 #ifdef INET6
5204                         SCTP_BUF_RESV_UF(op_err, sizeof(struct ip6_hdr));
5205 #else
5206                         SCTP_BUF_RESV_UF(op_err, sizeof(struct ip));
5207 #endif
5208                         SCTP_BUF_RESV_UF(op_err, sizeof(struct sctphdr));
5209                         SCTP_BUF_RESV_UF(op_err, sizeof(struct sctp_chunkhdr));
5210                 }
5211         }
5212         if ((op_err) && phdr) {
5213                 struct sctp_paramhdr s;
5214
5215                 if (err_at % 4) {
5216                         uint32_t cpthis = 0;
5217
5218                         pad_needed = 4 - (err_at % 4);
5219                         m_copyback(op_err, err_at, pad_needed, (caddr_t)&cpthis);
5220                         err_at += pad_needed;
5221                 }
5222                 s.param_type = htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
5223                 s.param_length = htons(sizeof(s) + sizeof(struct sctp_paramhdr));
5224                 m_copyback(op_err, err_at, sizeof(s), (caddr_t)&s);
5225                 err_at += sizeof(s);
5226                 /* Only copy back the p-hdr that caused the issue */
5227                 m_copyback(op_err, err_at, sizeof(struct sctp_paramhdr), (caddr_t)phdr);
5228         }
5229         return (op_err);
5230 }
5231
5232 static int
5233 sctp_are_there_new_addresses(struct sctp_association *asoc,
5234     struct mbuf *in_initpkt, int offset, struct sockaddr *src)
5235 {
5236         /*
5237          * Given a INIT packet, look through the packet to verify that there
5238          * are NO new addresses. As we go through the parameters add reports
5239          * of any un-understood parameters that require an error.  Also we
5240          * must return (1) to drop the packet if we see a un-understood
5241          * parameter that tells us to drop the chunk.
5242          */
5243         struct sockaddr *sa_touse;
5244         struct sockaddr *sa;
5245         struct sctp_paramhdr *phdr, params;
5246         uint16_t ptype, plen;
5247         uint8_t fnd;
5248         struct sctp_nets *net;
5249
5250 #ifdef INET
5251         struct sockaddr_in sin4, *sa4;
5252
5253 #endif
5254 #ifdef INET6
5255         struct sockaddr_in6 sin6, *sa6;
5256
5257 #endif
5258
5259 #ifdef INET
5260         memset(&sin4, 0, sizeof(sin4));
5261         sin4.sin_family = AF_INET;
5262         sin4.sin_len = sizeof(sin4);
5263 #endif
5264 #ifdef INET6
5265         memset(&sin6, 0, sizeof(sin6));
5266         sin6.sin6_family = AF_INET6;
5267         sin6.sin6_len = sizeof(sin6);
5268 #endif
5269         /* First what about the src address of the pkt ? */
5270         fnd = 0;
5271         TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
5272                 sa = (struct sockaddr *)&net->ro._l_addr;
5273                 if (sa->sa_family == src->sa_family) {
5274 #ifdef INET
5275                         if (sa->sa_family == AF_INET) {
5276                                 struct sockaddr_in *src4;
5277
5278                                 sa4 = (struct sockaddr_in *)sa;
5279                                 src4 = (struct sockaddr_in *)src;
5280                                 if (sa4->sin_addr.s_addr == src4->sin_addr.s_addr) {
5281                                         fnd = 1;
5282                                         break;
5283                                 }
5284                         }
5285 #endif
5286 #ifdef INET6
5287                         if (sa->sa_family == AF_INET6) {
5288                                 struct sockaddr_in6 *src6;
5289
5290                                 sa6 = (struct sockaddr_in6 *)sa;
5291                                 src6 = (struct sockaddr_in6 *)src;
5292                                 if (SCTP6_ARE_ADDR_EQUAL(sa6, src6)) {
5293                                         fnd = 1;
5294                                         break;
5295                                 }
5296                         }
5297 #endif
5298                 }
5299         }
5300         if (fnd == 0) {
5301                 /* New address added! no need to look futher. */
5302                 return (1);
5303         }
5304         /* Ok so far lets munge through the rest of the packet */
5305         offset += sizeof(struct sctp_init_chunk);
5306         phdr = sctp_get_next_param(in_initpkt, offset, &params, sizeof(params));
5307         while (phdr) {
5308                 sa_touse = NULL;
5309                 ptype = ntohs(phdr->param_type);
5310                 plen = ntohs(phdr->param_length);
5311                 switch (ptype) {
5312 #ifdef INET
5313                 case SCTP_IPV4_ADDRESS:
5314                         {
5315                                 struct sctp_ipv4addr_param *p4, p4_buf;
5316
5317                                 phdr = sctp_get_next_param(in_initpkt, offset,
5318                                     (struct sctp_paramhdr *)&p4_buf, sizeof(p4_buf));
5319                                 if (plen != sizeof(struct sctp_ipv4addr_param) ||
5320                                     phdr == NULL) {
5321                                         return (1);
5322                                 }
5323                                 p4 = (struct sctp_ipv4addr_param *)phdr;
5324                                 sin4.sin_addr.s_addr = p4->addr;
5325                                 sa_touse = (struct sockaddr *)&sin4;
5326                                 break;
5327                         }
5328 #endif
5329 #ifdef INET6
5330                 case SCTP_IPV6_ADDRESS:
5331                         {
5332                                 struct sctp_ipv6addr_param *p6, p6_buf;
5333
5334                                 phdr = sctp_get_next_param(in_initpkt, offset,
5335                                     (struct sctp_paramhdr *)&p6_buf, sizeof(p6_buf));
5336                                 if (plen != sizeof(struct sctp_ipv6addr_param) ||
5337                                     phdr == NULL) {
5338                                         return (1);
5339                                 }
5340                                 p6 = (struct sctp_ipv6addr_param *)phdr;
5341                                 memcpy((caddr_t)&sin6.sin6_addr, p6->addr,
5342                                     sizeof(p6->addr));
5343                                 sa_touse = (struct sockaddr *)&sin6;
5344                                 break;
5345                         }
5346 #endif
5347                 default:
5348                         sa_touse = NULL;
5349                         break;
5350                 }
5351                 if (sa_touse) {
5352                         /* ok, sa_touse points to one to check */
5353                         fnd = 0;
5354                         TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
5355                                 sa = (struct sockaddr *)&net->ro._l_addr;
5356                                 if (sa->sa_family != sa_touse->sa_family) {
5357                                         continue;
5358                                 }
5359 #ifdef INET
5360                                 if (sa->sa_family == AF_INET) {
5361                                         sa4 = (struct sockaddr_in *)sa;
5362                                         if (sa4->sin_addr.s_addr ==
5363                                             sin4.sin_addr.s_addr) {
5364                                                 fnd = 1;
5365                                                 break;
5366                                         }
5367                                 }
5368 #endif
5369 #ifdef INET6
5370                                 if (sa->sa_family == AF_INET6) {
5371                                         sa6 = (struct sockaddr_in6 *)sa;
5372                                         if (SCTP6_ARE_ADDR_EQUAL(
5373                                             sa6, &sin6)) {
5374                                                 fnd = 1;
5375                                                 break;
5376                                         }
5377                                 }
5378 #endif
5379                         }
5380                         if (!fnd) {
5381                                 /* New addr added! no need to look further */
5382                                 return (1);
5383                         }
5384                 }
5385                 offset += SCTP_SIZE32(plen);
5386                 phdr = sctp_get_next_param(in_initpkt, offset, &params, sizeof(params));
5387         }
5388         return (0);
5389 }
5390
5391 /*
5392  * Given a MBUF chain that was sent into us containing an INIT. Build a
5393  * INIT-ACK with COOKIE and send back. We assume that the in_initpkt has done
5394  * a pullup to include IPv6/4header, SCTP header and initial part of INIT
5395  * message (i.e. the struct sctp_init_msg).
5396  */
5397 void
5398 sctp_send_initiate_ack(struct sctp_inpcb *inp, struct sctp_tcb *stcb,
5399     struct mbuf *init_pkt, int iphlen, int offset,
5400     struct sockaddr *src, struct sockaddr *dst,
5401     struct sctphdr *sh, struct sctp_init_chunk *init_chk,
5402     uint8_t use_mflowid, uint32_t mflowid,
5403     uint32_t vrf_id, uint16_t port, int hold_inp_lock)
5404 {
5405         struct sctp_association *asoc;
5406         struct mbuf *m, *m_at, *m_tmp, *m_cookie, *op_err, *mp_last;
5407         struct sctp_init_ack_chunk *initack;
5408         struct sctp_adaptation_layer_indication *ali;
5409         struct sctp_ecn_supported_param *ecn;
5410         struct sctp_prsctp_supported_param *prsctp;
5411         struct sctp_supported_chunk_types_param *pr_supported;
5412         union sctp_sockstore *over_addr;
5413
5414 #ifdef INET
5415         struct sockaddr_in *dst4 = (struct sockaddr_in *)dst;
5416         struct sockaddr_in *src4 = (struct sockaddr_in *)src;
5417         struct sockaddr_in *sin;
5418
5419 #endif
5420 #ifdef INET6
5421         struct sockaddr_in6 *dst6 = (struct sockaddr_in6 *)dst;
5422         struct sockaddr_in6 *src6 = (struct sockaddr_in6 *)src;
5423         struct sockaddr_in6 *sin6;
5424
5425 #endif
5426         struct sockaddr *to;
5427         struct sctp_state_cookie stc;
5428         struct sctp_nets *net = NULL;
5429         uint8_t *signature = NULL;
5430         int cnt_inits_to = 0;
5431         uint16_t his_limit, i_want;
5432         int abort_flag, padval;
5433         int num_ext;
5434         int p_len;
5435         int nat_friendly = 0;
5436         struct socket *so;
5437
5438         if (stcb) {
5439                 asoc = &stcb->asoc;
5440         } else {
5441                 asoc = NULL;
5442         }
5443         mp_last = NULL;
5444         if ((asoc != NULL) &&
5445             (SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_WAIT) &&
5446             (sctp_are_there_new_addresses(asoc, init_pkt, offset, src))) {
5447                 /* new addresses, out of here in non-cookie-wait states */
5448                 /*
5449                  * Send a ABORT, we don't add the new address error clause
5450                  * though we even set the T bit and copy in the 0 tag.. this
5451                  * looks no different than if no listener was present.
5452                  */
5453                 sctp_send_abort(init_pkt, iphlen, src, dst, sh, 0, NULL,
5454                     use_mflowid, mflowid,
5455                     vrf_id, port);
5456                 return;
5457         }
5458         abort_flag = 0;
5459         op_err = sctp_arethere_unrecognized_parameters(init_pkt,
5460             (offset + sizeof(struct sctp_init_chunk)),
5461             &abort_flag, (struct sctp_chunkhdr *)init_chk, &nat_friendly);
5462         if (abort_flag) {
5463 do_a_abort:
5464                 sctp_send_abort(init_pkt, iphlen, src, dst, sh,
5465                     init_chk->init.initiate_tag, op_err,
5466                     use_mflowid, mflowid,
5467                     vrf_id, port);
5468                 return;
5469         }
5470         m = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_DATA);
5471         if (m == NULL) {
5472                 /* No memory, INIT timer will re-attempt. */
5473                 if (op_err)
5474                         sctp_m_freem(op_err);
5475                 return;
5476         }
5477         SCTP_BUF_LEN(m) = sizeof(struct sctp_init_chunk);
5478
5479         /* the time I built cookie */
5480         (void)SCTP_GETTIME_TIMEVAL(&stc.time_entered);
5481
5482         /* populate any tie tags */
5483         if (asoc != NULL) {
5484                 /* unlock before tag selections */
5485                 stc.tie_tag_my_vtag = asoc->my_vtag_nonce;
5486                 stc.tie_tag_peer_vtag = asoc->peer_vtag_nonce;
5487                 stc.cookie_life = asoc->cookie_life;
5488                 net = asoc->primary_destination;
5489         } else {
5490                 stc.tie_tag_my_vtag = 0;
5491                 stc.tie_tag_peer_vtag = 0;
5492                 /* life I will award this cookie */
5493                 stc.cookie_life = inp->sctp_ep.def_cookie_life;
5494         }
5495
5496         /* copy in the ports for later check */
5497         stc.myport = sh->dest_port;
5498         stc.peerport = sh->src_port;
5499
5500         /*
5501          * If we wanted to honor cookie life extentions, we would add to
5502          * stc.cookie_life. For now we should NOT honor any extension
5503          */
5504         stc.site_scope = stc.local_scope = stc.loopback_scope = 0;
5505         if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
5506                 struct inpcb *in_inp;
5507
5508                 /* Its a V6 socket */
5509                 in_inp = (struct inpcb *)inp;
5510                 stc.ipv6_addr_legal = 1;
5511                 /* Now look at the binding flag to see if V4 will be legal */
5512                 if (SCTP_IPV6_V6ONLY(in_inp) == 0) {
5513                         stc.ipv4_addr_legal = 1;
5514                 } else {
5515                         /* V4 addresses are NOT legal on the association */
5516                         stc.ipv4_addr_legal = 0;
5517                 }
5518         } else {
5519                 /* Its a V4 socket, no - V6 */
5520                 stc.ipv4_addr_legal = 1;
5521                 stc.ipv6_addr_legal = 0;
5522         }
5523
5524 #ifdef SCTP_DONT_DO_PRIVADDR_SCOPE
5525         stc.ipv4_scope = 1;
5526 #else
5527         stc.ipv4_scope = 0;
5528 #endif
5529         if (net == NULL) {
5530                 to = src;
5531                 switch (dst->sa_family) {
5532 #ifdef INET
5533                 case AF_INET:
5534                         {
5535                                 /* lookup address */
5536                                 stc.address[0] = src4->sin_addr.s_addr;
5537                                 stc.address[1] = 0;
5538                                 stc.address[2] = 0;
5539                                 stc.address[3] = 0;
5540                                 stc.addr_type = SCTP_IPV4_ADDRESS;
5541                                 /* local from address */
5542                                 stc.laddress[0] = dst4->sin_addr.s_addr;
5543                                 stc.laddress[1] = 0;
5544                                 stc.laddress[2] = 0;
5545                                 stc.laddress[3] = 0;
5546                                 stc.laddr_type = SCTP_IPV4_ADDRESS;
5547                                 /* scope_id is only for v6 */
5548                                 stc.scope_id = 0;
5549 #ifndef SCTP_DONT_DO_PRIVADDR_SCOPE
5550                                 if (IN4_ISPRIVATE_ADDRESS(&src4->sin_addr)) {
5551                                         stc.ipv4_scope = 1;
5552                                 }
5553 #else
5554                                 stc.ipv4_scope = 1;
5555 #endif                          /* SCTP_DONT_DO_PRIVADDR_SCOPE */
5556                                 /* Must use the address in this case */
5557                                 if (sctp_is_address_on_local_host(src, vrf_id)) {
5558                                         stc.loopback_scope = 1;
5559                                         stc.ipv4_scope = 1;
5560                                         stc.site_scope = 1;
5561                                         stc.local_scope = 0;
5562                                 }
5563                                 break;
5564                         }
5565 #endif
5566 #ifdef INET6
5567                 case AF_INET6:
5568                         {
5569                                 stc.addr_type = SCTP_IPV6_ADDRESS;
5570                                 memcpy(&stc.address, &src6->sin6_addr, sizeof(struct in6_addr));
5571                                 stc.scope_id = in6_getscope(&src6->sin6_addr);
5572                                 if (sctp_is_address_on_local_host(src, vrf_id)) {
5573                                         stc.loopback_scope = 1;
5574                                         stc.local_scope = 0;
5575                                         stc.site_scope = 1;
5576                                         stc.ipv4_scope = 1;
5577                                 } else if (IN6_IS_ADDR_LINKLOCAL(&src6->sin6_addr)) {
5578                                         /*
5579                                          * If the new destination is a
5580                                          * LINK_LOCAL we must have common
5581                                          * both site and local scope. Don't
5582                                          * set local scope though since we
5583                                          * must depend on the source to be
5584                                          * added implicitly. We cannot
5585                                          * assure just because we share one
5586                                          * link that all links are common.
5587                                          */
5588                                         stc.local_scope = 0;
5589                                         stc.site_scope = 1;
5590                                         stc.ipv4_scope = 1;
5591                                         /*
5592                                          * we start counting for the private
5593                                          * address stuff at 1. since the
5594                                          * link local we source from won't
5595                                          * show up in our scoped count.
5596                                          */
5597                                         cnt_inits_to = 1;
5598                                         /*
5599                                          * pull out the scope_id from
5600                                          * incoming pkt
5601                                          */
5602                                 } else if (IN6_IS_ADDR_SITELOCAL(&src6->sin6_addr)) {
5603                                         /*
5604                                          * If the new destination is
5605                                          * SITE_LOCAL then we must have site
5606                                          * scope in common.
5607                                          */
5608                                         stc.site_scope = 1;
5609                                 }
5610                                 memcpy(&stc.laddress, &dst6->sin6_addr, sizeof(struct in6_addr));
5611                                 stc.laddr_type = SCTP_IPV6_ADDRESS;
5612                                 break;
5613                         }
5614 #endif
5615                 default:
5616                         /* TSNH */
5617                         goto do_a_abort;
5618                         break;
5619                 }
5620         } else {
5621                 /* set the scope per the existing tcb */
5622
5623 #ifdef INET6
5624                 struct sctp_nets *lnet;
5625
5626 #endif
5627
5628                 stc.loopback_scope = asoc->loopback_scope;
5629                 stc.ipv4_scope = asoc->ipv4_local_scope;
5630                 stc.site_scope = asoc->site_scope;
5631                 stc.local_scope = asoc->local_scope;
5632 #ifdef INET6
5633                 /* Why do we not consider IPv4 LL addresses? */
5634                 TAILQ_FOREACH(lnet, &asoc->nets, sctp_next) {
5635                         if (lnet->ro._l_addr.sin6.sin6_family == AF_INET6) {
5636                                 if (IN6_IS_ADDR_LINKLOCAL(&lnet->ro._l_addr.sin6.sin6_addr)) {
5637                                         /*
5638                                          * if we have a LL address, start
5639                                          * counting at 1.
5640                                          */
5641                                         cnt_inits_to = 1;
5642                                 }
5643                         }
5644                 }
5645 #endif
5646                 /* use the net pointer */
5647                 to = (struct sockaddr *)&net->ro._l_addr;
5648                 switch (to->sa_family) {
5649 #ifdef INET
5650                 case AF_INET:
5651                         sin = (struct sockaddr_in *)to;
5652                         stc.address[0] = sin->sin_addr.s_addr;
5653                         stc.address[1] = 0;
5654                         stc.address[2] = 0;
5655                         stc.address[3] = 0;
5656                         stc.addr_type = SCTP_IPV4_ADDRESS;
5657                         if (net->src_addr_selected == 0) {
5658                                 /*
5659                                  * strange case here, the INIT should have
5660                                  * did the selection.
5661                                  */
5662                                 net->ro._s_addr = sctp_source_address_selection(inp,
5663                                     stcb, (sctp_route_t *) & net->ro,
5664                                     net, 0, vrf_id);
5665                                 if (net->ro._s_addr == NULL)
5666                                         return;
5667
5668                                 net->src_addr_selected = 1;
5669
5670                         }
5671                         stc.laddress[0] = net->ro._s_addr->address.sin.sin_addr.s_addr;
5672                         stc.laddress[1] = 0;
5673                         stc.laddress[2] = 0;
5674                         stc.laddress[3] = 0;
5675                         stc.laddr_type = SCTP_IPV4_ADDRESS;
5676                         /* scope_id is only for v6 */
5677                         stc.scope_id = 0;
5678                         break;
5679 #endif
5680 #ifdef INET6
5681                 case AF_INET6:
5682                         sin6 = (struct sockaddr_in6 *)to;
5683                         memcpy(&stc.address, &sin6->sin6_addr,
5684                             sizeof(struct in6_addr));
5685                         stc.addr_type = SCTP_IPV6_ADDRESS;
5686                         stc.scope_id = sin6->sin6_scope_id;
5687                         if (net->src_addr_selected == 0) {
5688                                 /*
5689                                  * strange case here, the INIT should have
5690                                  * done the selection.
5691                                  */
5692                                 net->ro._s_addr = sctp_source_address_selection(inp,
5693                                     stcb, (sctp_route_t *) & net->ro,
5694                                     net, 0, vrf_id);
5695                                 if (net->ro._s_addr == NULL)
5696                                         return;
5697
5698                                 net->src_addr_selected = 1;
5699                         }
5700                         memcpy(&stc.laddress, &net->ro._s_addr->address.sin6.sin6_addr,
5701                             sizeof(struct in6_addr));
5702                         stc.laddr_type = SCTP_IPV6_ADDRESS;
5703                         break;
5704 #endif
5705                 }
5706         }
5707         /* Now lets put the SCTP header in place */
5708         initack = mtod(m, struct sctp_init_ack_chunk *);
5709         /* Save it off for quick ref */
5710         stc.peers_vtag = init_chk->init.initiate_tag;
5711         /* who are we */
5712         memcpy(stc.identification, SCTP_VERSION_STRING,
5713             min(strlen(SCTP_VERSION_STRING), sizeof(stc.identification)));
5714         memset(stc.reserved, 0, SCTP_RESERVE_SPACE);
5715         /* now the chunk header */
5716         initack->ch.chunk_type = SCTP_INITIATION_ACK;
5717         initack->ch.chunk_flags = 0;
5718         /* fill in later from mbuf we build */
5719         initack->ch.chunk_length = 0;
5720         /* place in my tag */
5721         if ((asoc != NULL) &&
5722             ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
5723             (SCTP_GET_STATE(asoc) == SCTP_STATE_INUSE) ||
5724             (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED))) {
5725                 /* re-use the v-tags and init-seq here */
5726                 initack->init.initiate_tag = htonl(asoc->my_vtag);
5727                 initack->init.initial_tsn = htonl(asoc->init_seq_number);
5728         } else {
5729                 uint32_t vtag, itsn;
5730
5731                 if (hold_inp_lock) {
5732                         SCTP_INP_INCR_REF(inp);
5733                         SCTP_INP_RUNLOCK(inp);
5734                 }
5735                 if (asoc) {
5736                         atomic_add_int(&asoc->refcnt, 1);
5737                         SCTP_TCB_UNLOCK(stcb);
5738         new_tag:
5739                         vtag = sctp_select_a_tag(inp, inp->sctp_lport, sh->src_port, 1);
5740                         if ((asoc->peer_supports_nat) && (vtag == asoc->my_vtag)) {
5741                                 /*
5742                                  * Got a duplicate vtag on some guy behind a
5743                                  * nat make sure we don't use it.
5744                                  */
5745                                 goto new_tag;
5746                         }
5747                         initack->init.initiate_tag = htonl(vtag);
5748                         /* get a TSN to use too */
5749                         itsn = sctp_select_initial_TSN(&inp->sctp_ep);
5750                         initack->init.initial_tsn = htonl(itsn);
5751                         SCTP_TCB_LOCK(stcb);
5752                         atomic_add_int(&asoc->refcnt, -1);
5753                 } else {
5754                         vtag = sctp_select_a_tag(inp, inp->sctp_lport, sh->src_port, 1);
5755                         initack->init.initiate_tag = htonl(vtag);
5756                         /* get a TSN to use too */
5757                         initack->init.initial_tsn = htonl(sctp_select_initial_TSN(&inp->sctp_ep));
5758                 }
5759                 if (hold_inp_lock) {
5760                         SCTP_INP_RLOCK(inp);
5761                         SCTP_INP_DECR_REF(inp);
5762                 }
5763         }
5764         /* save away my tag to */
5765         stc.my_vtag = initack->init.initiate_tag;
5766
5767         /* set up some of the credits. */
5768         so = inp->sctp_socket;
5769         if (so == NULL) {
5770                 /* memory problem */
5771                 sctp_m_freem(m);
5772                 return;
5773         } else {
5774                 initack->init.a_rwnd = htonl(max(SCTP_SB_LIMIT_RCV(so), SCTP_MINIMAL_RWND));
5775         }
5776         /* set what I want */
5777         his_limit = ntohs(init_chk->init.num_inbound_streams);
5778         /* choose what I want */
5779         if (asoc != NULL) {
5780                 if (asoc->streamoutcnt > inp->sctp_ep.pre_open_stream_count) {
5781                         i_want = asoc->streamoutcnt;
5782                 } else {
5783                         i_want = inp->sctp_ep.pre_open_stream_count;
5784                 }
5785         } else {
5786                 i_want = inp->sctp_ep.pre_open_stream_count;
5787         }
5788         if (his_limit < i_want) {
5789                 /* I Want more :< */
5790                 initack->init.num_outbound_streams = init_chk->init.num_inbound_streams;
5791         } else {
5792                 /* I can have what I want :> */
5793                 initack->init.num_outbound_streams = htons(i_want);
5794         }
5795         /* tell him his limit. */
5796         initack->init.num_inbound_streams =
5797             htons(inp->sctp_ep.max_open_streams_intome);
5798
5799         /* adaptation layer indication parameter */
5800         ali = (struct sctp_adaptation_layer_indication *)((caddr_t)initack + sizeof(*initack));
5801         ali->ph.param_type = htons(SCTP_ULP_ADAPTATION);
5802         ali->ph.param_length = htons(sizeof(*ali));
5803         ali->indication = ntohl(inp->sctp_ep.adaptation_layer_indicator);
5804         SCTP_BUF_LEN(m) += sizeof(*ali);
5805         ecn = (struct sctp_ecn_supported_param *)((caddr_t)ali + sizeof(*ali));
5806
5807         /* ECN parameter */
5808         if (((asoc != NULL) && (asoc->ecn_allowed == 1)) ||
5809             (inp->sctp_ecn_enable == 1)) {
5810                 ecn->ph.param_type = htons(SCTP_ECN_CAPABLE);
5811                 ecn->ph.param_length = htons(sizeof(*ecn));
5812                 SCTP_BUF_LEN(m) += sizeof(*ecn);
5813
5814                 prsctp = (struct sctp_prsctp_supported_param *)((caddr_t)ecn +
5815                     sizeof(*ecn));
5816         } else {
5817                 prsctp = (struct sctp_prsctp_supported_param *)((caddr_t)ecn);
5818         }
5819         /* And now tell the peer we do  pr-sctp */
5820         prsctp->ph.param_type = htons(SCTP_PRSCTP_SUPPORTED);
5821         prsctp->ph.param_length = htons(sizeof(*prsctp));
5822         SCTP_BUF_LEN(m) += sizeof(*prsctp);
5823         if (nat_friendly) {
5824                 /* Add NAT friendly parameter */
5825                 struct sctp_paramhdr *ph;
5826
5827                 ph = (struct sctp_paramhdr *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
5828                 ph->param_type = htons(SCTP_HAS_NAT_SUPPORT);
5829                 ph->param_length = htons(sizeof(struct sctp_paramhdr));
5830                 SCTP_BUF_LEN(m) += sizeof(struct sctp_paramhdr);
5831         }
5832         /* And now tell the peer we do all the extensions */
5833         pr_supported = (struct sctp_supported_chunk_types_param *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
5834         pr_supported->ph.param_type = htons(SCTP_SUPPORTED_CHUNK_EXT);
5835         num_ext = 0;
5836         pr_supported->chunk_types[num_ext++] = SCTP_ASCONF;
5837         pr_supported->chunk_types[num_ext++] = SCTP_ASCONF_ACK;
5838         pr_supported->chunk_types[num_ext++] = SCTP_FORWARD_CUM_TSN;
5839         pr_supported->chunk_types[num_ext++] = SCTP_PACKET_DROPPED;
5840         pr_supported->chunk_types[num_ext++] = SCTP_STREAM_RESET;
5841         if (!SCTP_BASE_SYSCTL(sctp_auth_disable))
5842                 pr_supported->chunk_types[num_ext++] = SCTP_AUTHENTICATION;
5843         if (SCTP_BASE_SYSCTL(sctp_nr_sack_on_off))
5844                 pr_supported->chunk_types[num_ext++] = SCTP_NR_SELECTIVE_ACK;
5845         p_len = sizeof(*pr_supported) + num_ext;
5846         pr_supported->ph.param_length = htons(p_len);
5847         bzero((caddr_t)pr_supported + p_len, SCTP_SIZE32(p_len) - p_len);
5848         SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
5849
5850         /* add authentication parameters */
5851         if (!SCTP_BASE_SYSCTL(sctp_auth_disable)) {
5852                 struct sctp_auth_random *randp;
5853                 struct sctp_auth_hmac_algo *hmacs;
5854                 struct sctp_auth_chunk_list *chunks;
5855                 uint16_t random_len;
5856
5857                 /* generate and add RANDOM parameter */
5858                 random_len = SCTP_AUTH_RANDOM_SIZE_DEFAULT;
5859                 randp = (struct sctp_auth_random *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
5860                 randp->ph.param_type = htons(SCTP_RANDOM);
5861                 p_len = sizeof(*randp) + random_len;
5862                 randp->ph.param_length = htons(p_len);
5863                 SCTP_READ_RANDOM(randp->random_data, random_len);
5864                 /* zero out any padding required */
5865                 bzero((caddr_t)randp + p_len, SCTP_SIZE32(p_len) - p_len);
5866                 SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
5867
5868                 /* add HMAC_ALGO parameter */
5869                 hmacs = (struct sctp_auth_hmac_algo *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
5870                 p_len = sctp_serialize_hmaclist(inp->sctp_ep.local_hmacs,
5871                     (uint8_t *) hmacs->hmac_ids);
5872                 if (p_len > 0) {
5873                         p_len += sizeof(*hmacs);
5874                         hmacs->ph.param_type = htons(SCTP_HMAC_LIST);
5875                         hmacs->ph.param_length = htons(p_len);
5876                         /* zero out any padding required */
5877                         bzero((caddr_t)hmacs + p_len, SCTP_SIZE32(p_len) - p_len);
5878                         SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
5879                 }
5880                 /* add CHUNKS parameter */
5881                 chunks = (struct sctp_auth_chunk_list *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
5882                 p_len = sctp_serialize_auth_chunks(inp->sctp_ep.local_auth_chunks,
5883                     chunks->chunk_types);
5884                 if (p_len > 0) {
5885                         p_len += sizeof(*chunks);
5886                         chunks->ph.param_type = htons(SCTP_CHUNK_LIST);
5887                         chunks->ph.param_length = htons(p_len);
5888                         /* zero out any padding required */
5889                         bzero((caddr_t)chunks + p_len, SCTP_SIZE32(p_len) - p_len);
5890                         SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
5891                 }
5892         }
5893         m_at = m;
5894         /* now the addresses */
5895         {
5896                 struct sctp_scoping scp;
5897
5898                 /*
5899                  * To optimize this we could put the scoping stuff into a
5900                  * structure and remove the individual uint8's from the stc
5901                  * structure. Then we could just sifa in the address within
5902                  * the stc.. but for now this is a quick hack to get the
5903                  * address stuff teased apart.
5904                  */
5905                 scp.ipv4_addr_legal = stc.ipv4_addr_legal;
5906                 scp.ipv6_addr_legal = stc.ipv6_addr_legal;
5907                 scp.loopback_scope = stc.loopback_scope;
5908                 scp.ipv4_local_scope = stc.ipv4_scope;
5909                 scp.local_scope = stc.local_scope;
5910                 scp.site_scope = stc.site_scope;
5911                 m_at = sctp_add_addresses_to_i_ia(inp, stcb, &scp, m_at, cnt_inits_to, NULL, NULL);
5912         }
5913
5914         /* tack on the operational error if present */
5915         if (op_err) {
5916                 struct mbuf *ol;
5917                 int llen;
5918
5919                 llen = 0;
5920                 ol = op_err;
5921
5922                 while (ol) {
5923                         llen += SCTP_BUF_LEN(ol);
5924                         ol = SCTP_BUF_NEXT(ol);
5925                 }
5926                 if (llen % 4) {
5927                         /* must add a pad to the param */
5928                         uint32_t cpthis = 0;
5929                         int padlen;
5930
5931                         padlen = 4 - (llen % 4);
5932                         m_copyback(op_err, llen, padlen, (caddr_t)&cpthis);
5933                 }
5934                 while (SCTP_BUF_NEXT(m_at) != NULL) {
5935                         m_at = SCTP_BUF_NEXT(m_at);
5936                 }
5937                 SCTP_BUF_NEXT(m_at) = op_err;
5938                 while (SCTP_BUF_NEXT(m_at) != NULL) {
5939                         m_at = SCTP_BUF_NEXT(m_at);
5940                 }
5941         }
5942         /* pre-calulate the size and update pkt header and chunk header */
5943         p_len = 0;
5944         for (m_tmp = m; m_tmp; m_tmp = SCTP_BUF_NEXT(m_tmp)) {
5945                 p_len += SCTP_BUF_LEN(m_tmp);
5946                 if (SCTP_BUF_NEXT(m_tmp) == NULL) {
5947                         /* m_tmp should now point to last one */
5948                         break;
5949                 }
5950         }
5951
5952         /* Now we must build a cookie */
5953         m_cookie = sctp_add_cookie(init_pkt, offset, m, 0, &stc, &signature);
5954         if (m_cookie == NULL) {
5955                 /* memory problem */
5956                 sctp_m_freem(m);
5957                 return;
5958         }
5959         /* Now append the cookie to the end and update the space/size */
5960         SCTP_BUF_NEXT(m_tmp) = m_cookie;
5961
5962         for (m_tmp = m_cookie; m_tmp; m_tmp = SCTP_BUF_NEXT(m_tmp)) {
5963                 p_len += SCTP_BUF_LEN(m_tmp);
5964                 if (SCTP_BUF_NEXT(m_tmp) == NULL) {
5965                         /* m_tmp should now point to last one */
5966                         mp_last = m_tmp;
5967                         break;
5968                 }
5969         }
5970         /*
5971          * Place in the size, but we don't include the last pad (if any) in
5972          * the INIT-ACK.
5973          */
5974         initack->ch.chunk_length = htons(p_len);
5975
5976         /*
5977          * Time to sign the cookie, we don't sign over the cookie signature
5978          * though thus we set trailer.
5979          */
5980         (void)sctp_hmac_m(SCTP_HMAC,
5981             (uint8_t *) inp->sctp_ep.secret_key[(int)(inp->sctp_ep.current_secret_number)],
5982             SCTP_SECRET_SIZE, m_cookie, sizeof(struct sctp_paramhdr),
5983             (uint8_t *) signature, SCTP_SIGNATURE_SIZE);
5984         /*
5985          * We sifa 0 here to NOT set IP_DF if its IPv4, we ignore the return
5986          * here since the timer will drive a retranmission.
5987          */
5988         padval = p_len % 4;
5989         if ((padval) && (mp_last)) {
5990                 /* see my previous comments on mp_last */
5991                 if (sctp_add_pad_tombuf(mp_last, (4 - padval))) {
5992                         /* Houston we have a problem, no space */
5993                         sctp_m_freem(m);
5994                         return;
5995                 }
5996         }
5997         if (stc.loopback_scope) {
5998                 over_addr = (union sctp_sockstore *)dst;
5999         } else {
6000                 over_addr = NULL;
6001         }
6002
6003         (void)sctp_lowlevel_chunk_output(inp, NULL, NULL, to, m, 0, NULL, 0, 0,
6004             0, 0,
6005             inp->sctp_lport, sh->src_port, init_chk->init.initiate_tag,
6006             port, over_addr,
6007             use_mflowid, mflowid,
6008             SCTP_SO_NOT_LOCKED);
6009         SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
6010 }
6011
6012
6013 static void
6014 sctp_prune_prsctp(struct sctp_tcb *stcb,
6015     struct sctp_association *asoc,
6016     struct sctp_sndrcvinfo *srcv,
6017     int dataout)
6018 {
6019         int freed_spc = 0;
6020         struct sctp_tmit_chunk *chk, *nchk;
6021
6022         SCTP_TCB_LOCK_ASSERT(stcb);
6023         if ((asoc->peer_supports_prsctp) &&
6024             (asoc->sent_queue_cnt_removeable > 0)) {
6025                 TAILQ_FOREACH(chk, &asoc->sent_queue, sctp_next) {
6026                         /*
6027                          * Look for chunks marked with the PR_SCTP flag AND
6028                          * the buffer space flag. If the one being sent is
6029                          * equal or greater priority then purge the old one
6030                          * and free some space.
6031                          */
6032                         if (PR_SCTP_BUF_ENABLED(chk->flags)) {
6033                                 /*
6034                                  * This one is PR-SCTP AND buffer space
6035                                  * limited type
6036                                  */
6037                                 if (chk->rec.data.timetodrop.tv_sec >= (long)srcv->sinfo_timetolive) {
6038                                         /*
6039                                          * Lower numbers equates to higher
6040                                          * priority so if the one we are
6041                                          * looking at has a larger or equal
6042                                          * priority we want to drop the data
6043                                          * and NOT retransmit it.
6044                                          */
6045                                         if (chk->data) {
6046                                                 /*
6047                                                  * We release the book_size
6048                                                  * if the mbuf is here
6049                                                  */
6050                                                 int ret_spc;
6051                                                 uint8_t sent;
6052
6053                                                 if (chk->sent > SCTP_DATAGRAM_UNSENT)
6054                                                         sent = 1;
6055                                                 else
6056                                                         sent = 0;
6057                                                 ret_spc = sctp_release_pr_sctp_chunk(stcb, chk,
6058                                                     sent,
6059                                                     SCTP_SO_LOCKED);
6060                                                 freed_spc += ret_spc;
6061                                                 if (freed_spc >= dataout) {
6062                                                         return;
6063                                                 }
6064                                         }       /* if chunk was present */
6065                                 }       /* if of sufficent priority */
6066                         }       /* if chunk has enabled */
6067                 }               /* tailqforeach */
6068
6069                 TAILQ_FOREACH_SAFE(chk, &asoc->send_queue, sctp_next, nchk) {
6070                         /* Here we must move to the sent queue and mark */
6071                         if (PR_SCTP_BUF_ENABLED(chk->flags)) {
6072                                 if (chk->rec.data.timetodrop.tv_sec >= (long)srcv->sinfo_timetolive) {
6073                                         if (chk->data) {
6074                                                 /*
6075                                                  * We release the book_size
6076                                                  * if the mbuf is here
6077                                                  */
6078                                                 int ret_spc;
6079
6080                                                 ret_spc = sctp_release_pr_sctp_chunk(stcb, chk,
6081                                                     0, SCTP_SO_LOCKED);
6082
6083                                                 freed_spc += ret_spc;
6084                                                 if (freed_spc >= dataout) {
6085                                                         return;
6086                                                 }
6087                                         }       /* end if chk->data */
6088                                 }       /* end if right class */
6089                         }       /* end if chk pr-sctp */
6090                 }               /* tailqforeachsafe (chk) */
6091         }                       /* if enabled in asoc */
6092 }
6093
6094 int
6095 sctp_get_frag_point(struct sctp_tcb *stcb,
6096     struct sctp_association *asoc)
6097 {
6098         int siz, ovh;
6099
6100         /*
6101          * For endpoints that have both v6 and v4 addresses we must reserve
6102          * room for the ipv6 header, for those that are only dealing with V4
6103          * we use a larger frag point.
6104          */
6105         if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
6106                 ovh = SCTP_MED_OVERHEAD;
6107         } else {
6108                 ovh = SCTP_MED_V4_OVERHEAD;
6109         }
6110
6111         if (stcb->asoc.sctp_frag_point > asoc->smallest_mtu)
6112                 siz = asoc->smallest_mtu - ovh;
6113         else
6114                 siz = (stcb->asoc.sctp_frag_point - ovh);
6115         /*
6116          * if (siz > (MCLBYTES-sizeof(struct sctp_data_chunk))) {
6117          */
6118         /* A data chunk MUST fit in a cluster */
6119         /* siz = (MCLBYTES - sizeof(struct sctp_data_chunk)); */
6120         /* } */
6121
6122         /* adjust for an AUTH chunk if DATA requires auth */
6123         if (sctp_auth_is_required_chunk(SCTP_DATA, stcb->asoc.peer_auth_chunks))
6124                 siz -= sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
6125
6126         if (siz % 4) {
6127                 /* make it an even word boundary please */
6128                 siz -= (siz % 4);
6129         }
6130         return (siz);
6131 }
6132
6133 static void
6134 sctp_set_prsctp_policy(struct sctp_stream_queue_pending *sp)
6135 {
6136         sp->pr_sctp_on = 0;
6137         /*
6138          * We assume that the user wants PR_SCTP_TTL if the user provides a
6139          * positive lifetime but does not specify any PR_SCTP policy. This
6140          * is a BAD assumption and causes problems at least with the
6141          * U-Vancovers MPI folks. I will change this to be no policy means
6142          * NO PR-SCTP.
6143          */
6144         if (PR_SCTP_ENABLED(sp->sinfo_flags)) {
6145                 sp->act_flags |= PR_SCTP_POLICY(sp->sinfo_flags);
6146                 sp->pr_sctp_on = 1;
6147         } else {
6148                 return;
6149         }
6150         switch (PR_SCTP_POLICY(sp->sinfo_flags)) {
6151         case CHUNK_FLAGS_PR_SCTP_BUF:
6152                 /*
6153                  * Time to live is a priority stored in tv_sec when doing
6154                  * the buffer drop thing.
6155                  */
6156                 sp->ts.tv_sec = sp->timetolive;
6157                 sp->ts.tv_usec = 0;
6158                 break;
6159         case CHUNK_FLAGS_PR_SCTP_TTL:
6160                 {
6161                         struct timeval tv;
6162
6163                         (void)SCTP_GETTIME_TIMEVAL(&sp->ts);
6164                         tv.tv_sec = sp->timetolive / 1000;
6165                         tv.tv_usec = (sp->timetolive * 1000) % 1000000;
6166                         /*
6167                          * TODO sctp_constants.h needs alternative time
6168                          * macros when _KERNEL is undefined.
6169                          */
6170                         timevaladd(&sp->ts, &tv);
6171                 }
6172                 break;
6173         case CHUNK_FLAGS_PR_SCTP_RTX:
6174                 /*
6175                  * Time to live is a the number or retransmissions stored in
6176                  * tv_sec.
6177                  */
6178                 sp->ts.tv_sec = sp->timetolive;
6179                 sp->ts.tv_usec = 0;
6180                 break;
6181         default:
6182                 SCTPDBG(SCTP_DEBUG_USRREQ1,
6183                     "Unknown PR_SCTP policy %u.\n",
6184                     PR_SCTP_POLICY(sp->sinfo_flags));
6185                 break;
6186         }
6187 }
6188
6189 static int
6190 sctp_msg_append(struct sctp_tcb *stcb,
6191     struct sctp_nets *net,
6192     struct mbuf *m,
6193     struct sctp_sndrcvinfo *srcv, int hold_stcb_lock)
6194 {
6195         int error = 0;
6196         struct mbuf *at;
6197         struct sctp_stream_queue_pending *sp = NULL;
6198         struct sctp_stream_out *strm;
6199
6200         /*
6201          * Given an mbuf chain, put it into the association send queue and
6202          * place it on the wheel
6203          */
6204         if (srcv->sinfo_stream >= stcb->asoc.streamoutcnt) {
6205                 /* Invalid stream number */
6206                 SCTP_LTRACE_ERR_RET_PKT(m, NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
6207                 error = EINVAL;
6208                 goto out_now;
6209         }
6210         if ((stcb->asoc.stream_locked) &&
6211             (stcb->asoc.stream_locked_on != srcv->sinfo_stream)) {
6212                 SCTP_LTRACE_ERR_RET_PKT(m, NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
6213                 error = EINVAL;
6214                 goto out_now;
6215         }
6216         strm = &stcb->asoc.strmout[srcv->sinfo_stream];
6217         /* Now can we send this? */
6218         if ((SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
6219             (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
6220             (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
6221             (stcb->asoc.state & SCTP_STATE_SHUTDOWN_PENDING)) {
6222                 /* got data while shutting down */
6223                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ECONNRESET);
6224                 error = ECONNRESET;
6225                 goto out_now;
6226         }
6227         sctp_alloc_a_strmoq(stcb, sp);
6228         if (sp == NULL) {
6229                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
6230                 error = ENOMEM;
6231                 goto out_now;
6232         }
6233         sp->sinfo_flags = srcv->sinfo_flags;
6234         sp->timetolive = srcv->sinfo_timetolive;
6235         sp->ppid = srcv->sinfo_ppid;
6236         sp->context = srcv->sinfo_context;
6237         if (sp->sinfo_flags & SCTP_ADDR_OVER) {
6238                 sp->net = net;
6239                 atomic_add_int(&sp->net->ref_count, 1);
6240         } else {
6241                 sp->net = NULL;
6242         }
6243         (void)SCTP_GETTIME_TIMEVAL(&sp->ts);
6244         sp->stream = srcv->sinfo_stream;
6245         sp->msg_is_complete = 1;
6246         sp->sender_all_done = 1;
6247         sp->some_taken = 0;
6248         sp->data = m;
6249         sp->tail_mbuf = NULL;
6250         sctp_set_prsctp_policy(sp);
6251         /*
6252          * We could in theory (for sendall) sifa the length in, but we would
6253          * still have to hunt through the chain since we need to setup the
6254          * tail_mbuf
6255          */
6256         sp->length = 0;
6257         for (at = m; at; at = SCTP_BUF_NEXT(at)) {
6258                 if (SCTP_BUF_NEXT(at) == NULL)
6259                         sp->tail_mbuf = at;
6260                 sp->length += SCTP_BUF_LEN(at);
6261         }
6262         if (srcv->sinfo_keynumber_valid) {
6263                 sp->auth_keyid = srcv->sinfo_keynumber;
6264         } else {
6265                 sp->auth_keyid = stcb->asoc.authinfo.active_keyid;
6266         }
6267         if (sctp_auth_is_required_chunk(SCTP_DATA, stcb->asoc.peer_auth_chunks)) {
6268                 sctp_auth_key_acquire(stcb, sp->auth_keyid);
6269                 sp->holds_key_ref = 1;
6270         }
6271         if (hold_stcb_lock == 0) {
6272                 SCTP_TCB_SEND_LOCK(stcb);
6273         }
6274         sctp_snd_sb_alloc(stcb, sp->length);
6275         atomic_add_int(&stcb->asoc.stream_queue_cnt, 1);
6276         TAILQ_INSERT_TAIL(&strm->outqueue, sp, next);
6277         stcb->asoc.ss_functions.sctp_ss_add_to_stream(stcb, &stcb->asoc, strm, sp, 1);
6278         m = NULL;
6279         if (hold_stcb_lock == 0) {
6280                 SCTP_TCB_SEND_UNLOCK(stcb);
6281         }
6282 out_now:
6283         if (m) {
6284                 sctp_m_freem(m);
6285         }
6286         return (error);
6287 }
6288
6289
6290 static struct mbuf *
6291 sctp_copy_mbufchain(struct mbuf *clonechain,
6292     struct mbuf *outchain,
6293     struct mbuf **endofchain,
6294     int can_take_mbuf,
6295     int sizeofcpy,
6296     uint8_t copy_by_ref)
6297 {
6298         struct mbuf *m;
6299         struct mbuf *appendchain;
6300         caddr_t cp;
6301         int len;
6302
6303         if (endofchain == NULL) {
6304                 /* error */
6305 error_out:
6306                 if (outchain)
6307                         sctp_m_freem(outchain);
6308                 return (NULL);
6309         }
6310         if (can_take_mbuf) {
6311                 appendchain = clonechain;
6312         } else {
6313                 if (!copy_by_ref &&
6314                     (sizeofcpy <= (int)((((SCTP_BASE_SYSCTL(sctp_mbuf_threshold_count) - 1) * MLEN) + MHLEN)))
6315                     ) {
6316                         /* Its not in a cluster */
6317                         if (*endofchain == NULL) {
6318                                 /* lets get a mbuf cluster */
6319                                 if (outchain == NULL) {
6320                                         /* This is the general case */
6321                         new_mbuf:
6322                                         outchain = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_HEADER);
6323                                         if (outchain == NULL) {
6324                                                 goto error_out;
6325                                         }
6326                                         SCTP_BUF_LEN(outchain) = 0;
6327                                         *endofchain = outchain;
6328                                         /* get the prepend space */
6329                                         SCTP_BUF_RESV_UF(outchain, (SCTP_FIRST_MBUF_RESV + 4));
6330                                 } else {
6331                                         /*
6332                                          * We really should not get a NULL
6333                                          * in endofchain
6334                                          */
6335                                         /* find end */
6336                                         m = outchain;
6337                                         while (m) {
6338                                                 if (SCTP_BUF_NEXT(m) == NULL) {
6339                                                         *endofchain = m;
6340                                                         break;
6341                                                 }
6342                                                 m = SCTP_BUF_NEXT(m);
6343                                         }
6344                                         /* sanity */
6345                                         if (*endofchain == NULL) {
6346                                                 /*
6347                                                  * huh, TSNH XXX maybe we
6348                                                  * should panic
6349                                                  */
6350                                                 sctp_m_freem(outchain);
6351                                                 goto new_mbuf;
6352                                         }
6353                                 }
6354                                 /* get the new end of length */
6355                                 len = M_TRAILINGSPACE(*endofchain);
6356                         } else {
6357                                 /* how much is left at the end? */
6358                                 len = M_TRAILINGSPACE(*endofchain);
6359                         }
6360                         /* Find the end of the data, for appending */
6361                         cp = (mtod((*endofchain), caddr_t)+SCTP_BUF_LEN((*endofchain)));
6362
6363                         /* Now lets copy it out */
6364                         if (len >= sizeofcpy) {
6365                                 /* It all fits, copy it in */
6366                                 m_copydata(clonechain, 0, sizeofcpy, cp);
6367                                 SCTP_BUF_LEN((*endofchain)) += sizeofcpy;
6368                         } else {
6369                                 /* fill up the end of the chain */
6370                                 if (len > 0) {
6371                                         m_copydata(clonechain, 0, len, cp);
6372                                         SCTP_BUF_LEN((*endofchain)) += len;
6373                                         /* now we need another one */
6374                                         sizeofcpy -= len;
6375                                 }
6376                                 m = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_HEADER);
6377                                 if (m == NULL) {
6378                                         /* We failed */
6379                                         goto error_out;
6380                                 }
6381                                 SCTP_BUF_NEXT((*endofchain)) = m;
6382                                 *endofchain = m;
6383                                 cp = mtod((*endofchain), caddr_t);
6384                                 m_copydata(clonechain, len, sizeofcpy, cp);
6385                                 SCTP_BUF_LEN((*endofchain)) += sizeofcpy;
6386                         }
6387                         return (outchain);
6388                 } else {
6389                         /* copy the old fashion way */
6390                         appendchain = SCTP_M_COPYM(clonechain, 0, M_COPYALL, M_DONTWAIT);
6391 #ifdef SCTP_MBUF_LOGGING
6392                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
6393                                 struct mbuf *mat;
6394
6395                                 for (mat = appendchain; mat; mat = SCTP_BUF_NEXT(mat)) {
6396                                         if (SCTP_BUF_IS_EXTENDED(mat)) {
6397                                                 sctp_log_mb(mat, SCTP_MBUF_ICOPY);
6398                                         }
6399                                 }
6400                         }
6401 #endif
6402                 }
6403         }
6404         if (appendchain == NULL) {
6405                 /* error */
6406                 if (outchain)
6407                         sctp_m_freem(outchain);
6408                 return (NULL);
6409         }
6410         if (outchain) {
6411                 /* tack on to the end */
6412                 if (*endofchain != NULL) {
6413                         SCTP_BUF_NEXT(((*endofchain))) = appendchain;
6414                 } else {
6415                         m = outchain;
6416                         while (m) {
6417                                 if (SCTP_BUF_NEXT(m) == NULL) {
6418                                         SCTP_BUF_NEXT(m) = appendchain;
6419                                         break;
6420                                 }
6421                                 m = SCTP_BUF_NEXT(m);
6422                         }
6423                 }
6424                 /*
6425                  * save off the end and update the end-chain postion
6426                  */
6427                 m = appendchain;
6428                 while (m) {
6429                         if (SCTP_BUF_NEXT(m) == NULL) {
6430                                 *endofchain = m;
6431                                 break;
6432                         }
6433                         m = SCTP_BUF_NEXT(m);
6434                 }
6435                 return (outchain);
6436         } else {
6437                 /* save off the end and update the end-chain postion */
6438                 m = appendchain;
6439                 while (m) {
6440                         if (SCTP_BUF_NEXT(m) == NULL) {
6441                                 *endofchain = m;
6442                                 break;
6443                         }
6444                         m = SCTP_BUF_NEXT(m);
6445                 }
6446                 return (appendchain);
6447         }
6448 }
6449
6450 static int
6451 sctp_med_chunk_output(struct sctp_inpcb *inp,
6452     struct sctp_tcb *stcb,
6453     struct sctp_association *asoc,
6454     int *num_out,
6455     int *reason_code,
6456     int control_only, int from_where,
6457     struct timeval *now, int *now_filled, int frag_point, int so_locked
6458 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
6459     SCTP_UNUSED
6460 #endif
6461 );
6462
6463 static void
6464 sctp_sendall_iterator(struct sctp_inpcb *inp, struct sctp_tcb *stcb, void *ptr,
6465     uint32_t val SCTP_UNUSED)
6466 {
6467         struct sctp_copy_all *ca;
6468         struct mbuf *m;
6469         int ret = 0;
6470         int added_control = 0;
6471         int un_sent, do_chunk_output = 1;
6472         struct sctp_association *asoc;
6473         struct sctp_nets *net;
6474
6475         ca = (struct sctp_copy_all *)ptr;
6476         if (ca->m == NULL) {
6477                 return;
6478         }
6479         if (ca->inp != inp) {
6480                 /* TSNH */
6481                 return;
6482         }
6483         if ((ca->m) && ca->sndlen) {
6484                 m = SCTP_M_COPYM(ca->m, 0, M_COPYALL, M_DONTWAIT);
6485                 if (m == NULL) {
6486                         /* can't copy so we are done */
6487                         ca->cnt_failed++;
6488                         return;
6489                 }
6490 #ifdef SCTP_MBUF_LOGGING
6491                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
6492                         struct mbuf *mat;
6493
6494                         for (mat = m; mat; mat = SCTP_BUF_NEXT(mat)) {
6495                                 if (SCTP_BUF_IS_EXTENDED(mat)) {
6496                                         sctp_log_mb(mat, SCTP_MBUF_ICOPY);
6497                                 }
6498                         }
6499                 }
6500 #endif
6501         } else {
6502                 m = NULL;
6503         }
6504         SCTP_TCB_LOCK_ASSERT(stcb);
6505         if (stcb->asoc.alternate) {
6506                 net = stcb->asoc.alternate;
6507         } else {
6508                 net = stcb->asoc.primary_destination;
6509         }
6510         if (ca->sndrcv.sinfo_flags & SCTP_ABORT) {
6511                 /* Abort this assoc with m as the user defined reason */
6512                 if (m) {
6513                         struct sctp_paramhdr *ph;
6514
6515                         SCTP_BUF_PREPEND(m, sizeof(struct sctp_paramhdr), M_DONTWAIT);
6516                         if (m) {
6517                                 ph = mtod(m, struct sctp_paramhdr *);
6518                                 ph->param_type = htons(SCTP_CAUSE_USER_INITIATED_ABT);
6519                                 ph->param_length = htons(ca->sndlen);
6520                         }
6521                         /*
6522                          * We add one here to keep the assoc from
6523                          * dis-appearing on us.
6524                          */
6525                         atomic_add_int(&stcb->asoc.refcnt, 1);
6526                         sctp_abort_an_association(inp, stcb, m, SCTP_SO_NOT_LOCKED);
6527                         /*
6528                          * sctp_abort_an_association calls sctp_free_asoc()
6529                          * free association will NOT free it since we
6530                          * incremented the refcnt .. we do this to prevent
6531                          * it being freed and things getting tricky since we
6532                          * could end up (from free_asoc) calling inpcb_free
6533                          * which would get a recursive lock call to the
6534                          * iterator lock.. But as a consequence of that the
6535                          * stcb will return to us un-locked.. since
6536                          * free_asoc returns with either no TCB or the TCB
6537                          * unlocked, we must relock.. to unlock in the
6538                          * iterator timer :-0
6539                          */
6540                         SCTP_TCB_LOCK(stcb);
6541                         atomic_add_int(&stcb->asoc.refcnt, -1);
6542                         goto no_chunk_output;
6543                 }
6544         } else {
6545                 if (m) {
6546                         ret = sctp_msg_append(stcb, net, m,
6547                             &ca->sndrcv, 1);
6548                 }
6549                 asoc = &stcb->asoc;
6550                 if (ca->sndrcv.sinfo_flags & SCTP_EOF) {
6551                         /* shutdown this assoc */
6552                         int cnt;
6553
6554                         cnt = sctp_is_there_unsent_data(stcb, SCTP_SO_NOT_LOCKED);
6555
6556                         if (TAILQ_EMPTY(&asoc->send_queue) &&
6557                             TAILQ_EMPTY(&asoc->sent_queue) &&
6558                             (cnt == 0)) {
6559                                 if (asoc->locked_on_sending) {
6560                                         goto abort_anyway;
6561                                 }
6562                                 /*
6563                                  * there is nothing queued to send, so I'm
6564                                  * done...
6565                                  */
6566                                 if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
6567                                     (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
6568                                     (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
6569                                         /*
6570                                          * only send SHUTDOWN the first time
6571                                          * through
6572                                          */
6573                                         sctp_send_shutdown(stcb, net);
6574                                         if (SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) {
6575                                                 SCTP_STAT_DECR_GAUGE32(sctps_currestab);
6576                                         }
6577                                         SCTP_SET_STATE(asoc, SCTP_STATE_SHUTDOWN_SENT);
6578                                         SCTP_CLEAR_SUBSTATE(asoc, SCTP_STATE_SHUTDOWN_PENDING);
6579                                         sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, stcb->sctp_ep, stcb,
6580                                             net);
6581                                         sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
6582                                             asoc->primary_destination);
6583                                         added_control = 1;
6584                                         do_chunk_output = 0;
6585                                 }
6586                         } else {
6587                                 /*
6588                                  * we still got (or just got) data to send,
6589                                  * so set SHUTDOWN_PENDING
6590                                  */
6591                                 /*
6592                                  * XXX sockets draft says that SCTP_EOF
6593                                  * should be sent with no data.  currently,
6594                                  * we will allow user data to be sent first
6595                                  * and move to SHUTDOWN-PENDING
6596                                  */
6597                                 if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
6598                                     (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
6599                                     (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
6600                                         if (asoc->locked_on_sending) {
6601                                                 /*
6602                                                  * Locked to send out the
6603                                                  * data
6604                                                  */
6605                                                 struct sctp_stream_queue_pending *sp;
6606
6607                                                 sp = TAILQ_LAST(&asoc->locked_on_sending->outqueue, sctp_streamhead);
6608                                                 if (sp) {
6609                                                         if ((sp->length == 0) && (sp->msg_is_complete == 0))
6610                                                                 asoc->state |= SCTP_STATE_PARTIAL_MSG_LEFT;
6611                                                 }
6612                                         }
6613                                         asoc->state |= SCTP_STATE_SHUTDOWN_PENDING;
6614                                         if (TAILQ_EMPTY(&asoc->send_queue) &&
6615                                             TAILQ_EMPTY(&asoc->sent_queue) &&
6616                                             (asoc->state & SCTP_STATE_PARTIAL_MSG_LEFT)) {
6617                                 abort_anyway:
6618                                                 atomic_add_int(&stcb->asoc.refcnt, 1);
6619                                                 sctp_abort_an_association(stcb->sctp_ep, stcb,
6620                                                     NULL, SCTP_SO_NOT_LOCKED);
6621                                                 atomic_add_int(&stcb->asoc.refcnt, -1);
6622                                                 goto no_chunk_output;
6623                                         }
6624                                         sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
6625                                             asoc->primary_destination);
6626                                 }
6627                         }
6628
6629                 }
6630         }
6631         un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
6632             (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
6633
6634         if ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY)) &&
6635             (stcb->asoc.total_flight > 0) &&
6636             (un_sent < (int)(stcb->asoc.smallest_mtu - SCTP_MIN_OVERHEAD))
6637             ) {
6638                 do_chunk_output = 0;
6639         }
6640         if (do_chunk_output)
6641                 sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_USR_SEND, SCTP_SO_NOT_LOCKED);
6642         else if (added_control) {
6643                 int num_out = 0, reason = 0, now_filled = 0;
6644                 struct timeval now;
6645                 int frag_point;
6646
6647                 frag_point = sctp_get_frag_point(stcb, &stcb->asoc);
6648                 (void)sctp_med_chunk_output(inp, stcb, &stcb->asoc, &num_out,
6649                     &reason, 1, 1, &now, &now_filled, frag_point, SCTP_SO_NOT_LOCKED);
6650         }
6651 no_chunk_output:
6652         if (ret) {
6653                 ca->cnt_failed++;
6654         } else {
6655                 ca->cnt_sent++;
6656         }
6657 }
6658
6659 static void
6660 sctp_sendall_completes(void *ptr, uint32_t val SCTP_UNUSED)
6661 {
6662         struct sctp_copy_all *ca;
6663
6664         ca = (struct sctp_copy_all *)ptr;
6665         /*
6666          * Do a notify here? Kacheong suggests that the notify be done at
6667          * the send time.. so you would push up a notification if any send
6668          * failed. Don't know if this is feasable since the only failures we
6669          * have is "memory" related and if you cannot get an mbuf to send
6670          * the data you surely can't get an mbuf to send up to notify the
6671          * user you can't send the data :->
6672          */
6673
6674         /* now free everything */
6675         sctp_m_freem(ca->m);
6676         SCTP_FREE(ca, SCTP_M_COPYAL);
6677 }
6678
6679
6680 #define MC_ALIGN(m, len) do {                                           \
6681         SCTP_BUF_RESV_UF(m, ((MCLBYTES - (len)) & ~(sizeof(long) - 1)); \
6682 } while (0)
6683
6684
6685
6686 static struct mbuf *
6687 sctp_copy_out_all(struct uio *uio, int len)
6688 {
6689         struct mbuf *ret, *at;
6690         int left, willcpy, cancpy, error;
6691
6692         ret = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_WAIT, 1, MT_DATA);
6693         if (ret == NULL) {
6694                 /* TSNH */
6695                 return (NULL);
6696         }
6697         left = len;
6698         SCTP_BUF_LEN(ret) = 0;
6699         /* save space for the data chunk header */
6700         cancpy = M_TRAILINGSPACE(ret);
6701         willcpy = min(cancpy, left);
6702         at = ret;
6703         while (left > 0) {
6704                 /* Align data to the end */
6705                 error = uiomove(mtod(at, caddr_t), willcpy, uio);
6706                 if (error) {
6707         err_out_now:
6708                         sctp_m_freem(at);
6709                         return (NULL);
6710                 }
6711                 SCTP_BUF_LEN(at) = willcpy;
6712                 SCTP_BUF_NEXT_PKT(at) = SCTP_BUF_NEXT(at) = 0;
6713                 left -= willcpy;
6714                 if (left > 0) {
6715                         SCTP_BUF_NEXT(at) = sctp_get_mbuf_for_msg(left, 0, M_WAIT, 1, MT_DATA);
6716                         if (SCTP_BUF_NEXT(at) == NULL) {
6717                                 goto err_out_now;
6718                         }
6719                         at = SCTP_BUF_NEXT(at);
6720                         SCTP_BUF_LEN(at) = 0;
6721                         cancpy = M_TRAILINGSPACE(at);
6722                         willcpy = min(cancpy, left);
6723                 }
6724         }
6725         return (ret);
6726 }
6727
6728 static int
6729 sctp_sendall(struct sctp_inpcb *inp, struct uio *uio, struct mbuf *m,
6730     struct sctp_sndrcvinfo *srcv)
6731 {
6732         int ret;
6733         struct sctp_copy_all *ca;
6734
6735         SCTP_MALLOC(ca, struct sctp_copy_all *, sizeof(struct sctp_copy_all),
6736             SCTP_M_COPYAL);
6737         if (ca == NULL) {
6738                 sctp_m_freem(m);
6739                 SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
6740                 return (ENOMEM);
6741         }
6742         memset(ca, 0, sizeof(struct sctp_copy_all));
6743
6744         ca->inp = inp;
6745         if (srcv) {
6746                 memcpy(&ca->sndrcv, srcv, sizeof(struct sctp_nonpad_sndrcvinfo));
6747         }
6748         /*
6749          * take off the sendall flag, it would be bad if we failed to do
6750          * this :-0
6751          */
6752         ca->sndrcv.sinfo_flags &= ~SCTP_SENDALL;
6753         /* get length and mbuf chain */
6754         if (uio) {
6755                 ca->sndlen = uio->uio_resid;
6756                 ca->m = sctp_copy_out_all(uio, ca->sndlen);
6757                 if (ca->m == NULL) {
6758                         SCTP_FREE(ca, SCTP_M_COPYAL);
6759                         SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
6760                         return (ENOMEM);
6761                 }
6762         } else {
6763                 /* Gather the length of the send */
6764                 struct mbuf *mat;
6765
6766                 mat = m;
6767                 ca->sndlen = 0;
6768                 while (m) {
6769                         ca->sndlen += SCTP_BUF_LEN(m);
6770                         m = SCTP_BUF_NEXT(m);
6771                 }
6772                 ca->m = mat;
6773         }
6774         ret = sctp_initiate_iterator(NULL, sctp_sendall_iterator, NULL,
6775             SCTP_PCB_ANY_FLAGS, SCTP_PCB_ANY_FEATURES,
6776             SCTP_ASOC_ANY_STATE,
6777             (void *)ca, 0,
6778             sctp_sendall_completes, inp, 1);
6779         if (ret) {
6780                 SCTP_PRINTF("Failed to initiate iterator for sendall\n");
6781                 SCTP_FREE(ca, SCTP_M_COPYAL);
6782                 SCTP_LTRACE_ERR_RET_PKT(m, inp, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, EFAULT);
6783                 return (EFAULT);
6784         }
6785         return (0);
6786 }
6787
6788
6789 void
6790 sctp_toss_old_cookies(struct sctp_tcb *stcb, struct sctp_association *asoc)
6791 {
6792         struct sctp_tmit_chunk *chk, *nchk;
6793
6794         TAILQ_FOREACH_SAFE(chk, &asoc->control_send_queue, sctp_next, nchk) {
6795                 if (chk->rec.chunk_id.id == SCTP_COOKIE_ECHO) {
6796                         TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
6797                         if (chk->data) {
6798                                 sctp_m_freem(chk->data);
6799                                 chk->data = NULL;
6800                         }
6801                         asoc->ctrl_queue_cnt--;
6802                         sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
6803                 }
6804         }
6805 }
6806
6807 void
6808 sctp_toss_old_asconf(struct sctp_tcb *stcb)
6809 {
6810         struct sctp_association *asoc;
6811         struct sctp_tmit_chunk *chk, *nchk;
6812         struct sctp_asconf_chunk *acp;
6813
6814         asoc = &stcb->asoc;
6815         TAILQ_FOREACH_SAFE(chk, &asoc->asconf_send_queue, sctp_next, nchk) {
6816                 /* find SCTP_ASCONF chunk in queue */
6817                 if (chk->rec.chunk_id.id == SCTP_ASCONF) {
6818                         if (chk->data) {
6819                                 acp = mtod(chk->data, struct sctp_asconf_chunk *);
6820                                 if (SCTP_TSN_GT(ntohl(acp->serial_number), asoc->asconf_seq_out_acked)) {
6821                                         /* Not Acked yet */
6822                                         break;
6823                                 }
6824                         }
6825                         TAILQ_REMOVE(&asoc->asconf_send_queue, chk, sctp_next);
6826                         if (chk->data) {
6827                                 sctp_m_freem(chk->data);
6828                                 chk->data = NULL;
6829                         }
6830                         asoc->ctrl_queue_cnt--;
6831                         sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
6832                 }
6833         }
6834 }
6835
6836
6837 static void
6838 sctp_clean_up_datalist(struct sctp_tcb *stcb,
6839     struct sctp_association *asoc,
6840     struct sctp_tmit_chunk **data_list,
6841     int bundle_at,
6842     struct sctp_nets *net)
6843 {
6844         int i;
6845         struct sctp_tmit_chunk *tp1;
6846
6847         for (i = 0; i < bundle_at; i++) {
6848                 /* off of the send queue */
6849                 TAILQ_REMOVE(&asoc->send_queue, data_list[i], sctp_next);
6850                 asoc->send_queue_cnt--;
6851                 if (i > 0) {
6852                         /*
6853                          * Any chunk NOT 0 you zap the time chunk 0 gets
6854                          * zapped or set based on if a RTO measurment is
6855                          * needed.
6856                          */
6857                         data_list[i]->do_rtt = 0;
6858                 }
6859                 /* record time */
6860                 data_list[i]->sent_rcv_time = net->last_sent_time;
6861                 data_list[i]->rec.data.cwnd_at_send = net->cwnd;
6862                 data_list[i]->rec.data.fast_retran_tsn = data_list[i]->rec.data.TSN_seq;
6863                 if (data_list[i]->whoTo == NULL) {
6864                         data_list[i]->whoTo = net;
6865                         atomic_add_int(&net->ref_count, 1);
6866                 }
6867                 /* on to the sent queue */
6868                 tp1 = TAILQ_LAST(&asoc->sent_queue, sctpchunk_listhead);
6869                 if ((tp1) && SCTP_TSN_GT(tp1->rec.data.TSN_seq, data_list[i]->rec.data.TSN_seq)) {
6870                         struct sctp_tmit_chunk *tpp;
6871
6872                         /* need to move back */
6873         back_up_more:
6874                         tpp = TAILQ_PREV(tp1, sctpchunk_listhead, sctp_next);
6875                         if (tpp == NULL) {
6876                                 TAILQ_INSERT_BEFORE(tp1, data_list[i], sctp_next);
6877                                 goto all_done;
6878                         }
6879                         tp1 = tpp;
6880                         if (SCTP_TSN_GT(tp1->rec.data.TSN_seq, data_list[i]->rec.data.TSN_seq)) {
6881                                 goto back_up_more;
6882                         }
6883                         TAILQ_INSERT_AFTER(&asoc->sent_queue, tp1, data_list[i], sctp_next);
6884                 } else {
6885                         TAILQ_INSERT_TAIL(&asoc->sent_queue,
6886                             data_list[i],
6887                             sctp_next);
6888                 }
6889 all_done:
6890                 /* This does not lower until the cum-ack passes it */
6891                 asoc->sent_queue_cnt++;
6892                 if ((asoc->peers_rwnd <= 0) &&
6893                     (asoc->total_flight == 0) &&
6894                     (bundle_at == 1)) {
6895                         /* Mark the chunk as being a window probe */
6896                         SCTP_STAT_INCR(sctps_windowprobed);
6897                 }
6898 #ifdef SCTP_AUDITING_ENABLED
6899                 sctp_audit_log(0xC2, 3);
6900 #endif
6901                 data_list[i]->sent = SCTP_DATAGRAM_SENT;
6902                 data_list[i]->snd_count = 1;
6903                 data_list[i]->rec.data.chunk_was_revoked = 0;
6904                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_FLIGHT_LOGGING_ENABLE) {
6905                         sctp_misc_ints(SCTP_FLIGHT_LOG_UP,
6906                             data_list[i]->whoTo->flight_size,
6907                             data_list[i]->book_size,
6908                             (uintptr_t) data_list[i]->whoTo,
6909                             data_list[i]->rec.data.TSN_seq);
6910                 }
6911                 sctp_flight_size_increase(data_list[i]);
6912                 sctp_total_flight_increase(stcb, data_list[i]);
6913                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_RWND_ENABLE) {
6914                         sctp_log_rwnd(SCTP_DECREASE_PEER_RWND,
6915                             asoc->peers_rwnd, data_list[i]->send_size, SCTP_BASE_SYSCTL(sctp_peer_chunk_oh));
6916                 }
6917                 asoc->peers_rwnd = sctp_sbspace_sub(asoc->peers_rwnd,
6918                     (uint32_t) (data_list[i]->send_size + SCTP_BASE_SYSCTL(sctp_peer_chunk_oh)));
6919                 if (asoc->peers_rwnd < stcb->sctp_ep->sctp_ep.sctp_sws_sender) {
6920                         /* SWS sender side engages */
6921                         asoc->peers_rwnd = 0;
6922                 }
6923         }
6924         if (asoc->cc_functions.sctp_cwnd_update_packet_transmitted) {
6925                 (*asoc->cc_functions.sctp_cwnd_update_packet_transmitted) (stcb, net);
6926         }
6927 }
6928
6929 static void
6930 sctp_clean_up_ctl(struct sctp_tcb *stcb, struct sctp_association *asoc, int so_locked
6931 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
6932     SCTP_UNUSED
6933 #endif
6934 )
6935 {
6936         struct sctp_tmit_chunk *chk, *nchk;
6937
6938         TAILQ_FOREACH_SAFE(chk, &asoc->control_send_queue, sctp_next, nchk) {
6939                 if ((chk->rec.chunk_id.id == SCTP_SELECTIVE_ACK) ||
6940                     (chk->rec.chunk_id.id == SCTP_NR_SELECTIVE_ACK) ||  /* EY */
6941                     (chk->rec.chunk_id.id == SCTP_HEARTBEAT_REQUEST) ||
6942                     (chk->rec.chunk_id.id == SCTP_HEARTBEAT_ACK) ||
6943                     (chk->rec.chunk_id.id == SCTP_FORWARD_CUM_TSN) ||
6944                     (chk->rec.chunk_id.id == SCTP_SHUTDOWN) ||
6945                     (chk->rec.chunk_id.id == SCTP_SHUTDOWN_ACK) ||
6946                     (chk->rec.chunk_id.id == SCTP_OPERATION_ERROR) ||
6947                     (chk->rec.chunk_id.id == SCTP_PACKET_DROPPED) ||
6948                     (chk->rec.chunk_id.id == SCTP_COOKIE_ACK) ||
6949                     (chk->rec.chunk_id.id == SCTP_ECN_CWR) ||
6950                     (chk->rec.chunk_id.id == SCTP_ASCONF_ACK)) {
6951                         /* Stray chunks must be cleaned up */
6952         clean_up_anyway:
6953                         TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
6954                         if (chk->data) {
6955                                 sctp_m_freem(chk->data);
6956                                 chk->data = NULL;
6957                         }
6958                         asoc->ctrl_queue_cnt--;
6959                         if (chk->rec.chunk_id.id == SCTP_FORWARD_CUM_TSN)
6960                                 asoc->fwd_tsn_cnt--;
6961                         sctp_free_a_chunk(stcb, chk, so_locked);
6962                 } else if (chk->rec.chunk_id.id == SCTP_STREAM_RESET) {
6963                         /* special handling, we must look into the param */
6964                         if (chk != asoc->str_reset) {
6965                                 goto clean_up_anyway;
6966                         }
6967                 }
6968         }
6969 }
6970
6971
6972 static int
6973 sctp_can_we_split_this(struct sctp_tcb *stcb,
6974     uint32_t length,
6975     uint32_t goal_mtu, uint32_t frag_point, int eeor_on)
6976 {
6977         /*
6978          * Make a decision on if I should split a msg into multiple parts.
6979          * This is only asked of incomplete messages.
6980          */
6981         if (eeor_on) {
6982                 /*
6983                  * If we are doing EEOR we need to always send it if its the
6984                  * entire thing, since it might be all the guy is putting in
6985                  * the hopper.
6986                  */
6987                 if (goal_mtu >= length) {
6988                         /*-
6989                          * If we have data outstanding,
6990                          * we get another chance when the sack
6991                          * arrives to transmit - wait for more data
6992                          */
6993                         if (stcb->asoc.total_flight == 0) {
6994                                 /*
6995                                  * If nothing is in flight, we zero the
6996                                  * packet counter.
6997                                  */
6998                                 return (length);
6999                         }
7000                         return (0);
7001
7002                 } else {
7003                         /* You can fill the rest */
7004                         return (goal_mtu);
7005                 }
7006         }
7007         /*-
7008          * For those strange folk that make the send buffer
7009          * smaller than our fragmentation point, we can't
7010          * get a full msg in so we have to allow splitting.
7011          */
7012         if (SCTP_SB_LIMIT_SND(stcb->sctp_socket) < frag_point) {
7013                 return (length);
7014         }
7015         if ((length <= goal_mtu) ||
7016             ((length - goal_mtu) < SCTP_BASE_SYSCTL(sctp_min_residual))) {
7017                 /* Sub-optimial residual don't split in non-eeor mode. */
7018                 return (0);
7019         }
7020         /*
7021          * If we reach here length is larger than the goal_mtu. Do we wish
7022          * to split it for the sake of packet putting together?
7023          */
7024         if (goal_mtu >= min(SCTP_BASE_SYSCTL(sctp_min_split_point), frag_point)) {
7025                 /* Its ok to split it */
7026                 return (min(goal_mtu, frag_point));
7027         }
7028         /* Nope, can't split */
7029         return (0);
7030
7031 }
7032
7033 static uint32_t
7034 sctp_move_to_outqueue(struct sctp_tcb *stcb,
7035     struct sctp_stream_out *strq,
7036     uint32_t goal_mtu,
7037     uint32_t frag_point,
7038     int *locked,
7039     int *giveup,
7040     int eeor_mode,
7041     int *bail,
7042     int so_locked
7043 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
7044     SCTP_UNUSED
7045 #endif
7046 )
7047 {
7048         /* Move from the stream to the send_queue keeping track of the total */
7049         struct sctp_association *asoc;
7050         struct sctp_stream_queue_pending *sp;
7051         struct sctp_tmit_chunk *chk;
7052         struct sctp_data_chunk *dchkh;
7053         uint32_t to_move, length;
7054         uint8_t rcv_flags = 0;
7055         uint8_t some_taken;
7056         uint8_t send_lock_up = 0;
7057
7058         SCTP_TCB_LOCK_ASSERT(stcb);
7059         asoc = &stcb->asoc;
7060 one_more_time:
7061         /* sa_ignore FREED_MEMORY */
7062         sp = TAILQ_FIRST(&strq->outqueue);
7063         if (sp == NULL) {
7064                 *locked = 0;
7065                 if (send_lock_up == 0) {
7066                         SCTP_TCB_SEND_LOCK(stcb);
7067                         send_lock_up = 1;
7068                 }
7069                 sp = TAILQ_FIRST(&strq->outqueue);
7070                 if (sp) {
7071                         goto one_more_time;
7072                 }
7073                 if (strq->last_msg_incomplete) {
7074                         SCTP_PRINTF("Huh? Stream:%d lm_in_c=%d but queue is NULL\n",
7075                             strq->stream_no,
7076                             strq->last_msg_incomplete);
7077                         strq->last_msg_incomplete = 0;
7078                 }
7079                 to_move = 0;
7080                 if (send_lock_up) {
7081                         SCTP_TCB_SEND_UNLOCK(stcb);
7082                         send_lock_up = 0;
7083                 }
7084                 goto out_of;
7085         }
7086         if ((sp->msg_is_complete) && (sp->length == 0)) {
7087                 if (sp->sender_all_done) {
7088                         /*
7089                          * We are doing differed cleanup. Last time through
7090                          * when we took all the data the sender_all_done was
7091                          * not set.
7092                          */
7093                         if ((sp->put_last_out == 0) && (sp->discard_rest == 0)) {
7094                                 SCTP_PRINTF("Gak, put out entire msg with NO end!-1\n");
7095                                 SCTP_PRINTF("sender_done:%d len:%d msg_comp:%d put_last_out:%d send_lock:%d\n",
7096                                     sp->sender_all_done,
7097                                     sp->length,
7098                                     sp->msg_is_complete,
7099                                     sp->put_last_out,
7100                                     send_lock_up);
7101                         }
7102                         if ((TAILQ_NEXT(sp, next) == NULL) && (send_lock_up == 0)) {
7103                                 SCTP_TCB_SEND_LOCK(stcb);
7104                                 send_lock_up = 1;
7105                         }
7106                         atomic_subtract_int(&asoc->stream_queue_cnt, 1);
7107                         TAILQ_REMOVE(&strq->outqueue, sp, next);
7108                         stcb->asoc.ss_functions.sctp_ss_remove_from_stream(stcb, asoc, strq, sp, send_lock_up);
7109                         if (sp->net) {
7110                                 sctp_free_remote_addr(sp->net);
7111                                 sp->net = NULL;
7112                         }
7113                         if (sp->data) {
7114                                 sctp_m_freem(sp->data);
7115                                 sp->data = NULL;
7116                         }
7117                         sctp_free_a_strmoq(stcb, sp, so_locked);
7118                         /* we can't be locked to it */
7119                         *locked = 0;
7120                         stcb->asoc.locked_on_sending = NULL;
7121                         if (send_lock_up) {
7122                                 SCTP_TCB_SEND_UNLOCK(stcb);
7123                                 send_lock_up = 0;
7124                         }
7125                         /* back to get the next msg */
7126                         goto one_more_time;
7127                 } else {
7128                         /*
7129                          * sender just finished this but still holds a
7130                          * reference
7131                          */
7132                         *locked = 1;
7133                         *giveup = 1;
7134                         to_move = 0;
7135                         goto out_of;
7136                 }
7137         } else {
7138                 /* is there some to get */
7139                 if (sp->length == 0) {
7140                         /* no */
7141                         *locked = 1;
7142                         *giveup = 1;
7143                         to_move = 0;
7144                         goto out_of;
7145                 } else if (sp->discard_rest) {
7146                         if (send_lock_up == 0) {
7147                                 SCTP_TCB_SEND_LOCK(stcb);
7148                                 send_lock_up = 1;
7149                         }
7150                         /* Whack down the size */
7151                         atomic_subtract_int(&stcb->asoc.total_output_queue_size, sp->length);
7152                         if ((stcb->sctp_socket != NULL) && \
7153                             ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
7154                             (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL))) {
7155                                 atomic_subtract_int(&stcb->sctp_socket->so_snd.sb_cc, sp->length);
7156                         }
7157                         if (sp->data) {
7158                                 sctp_m_freem(sp->data);
7159                                 sp->data = NULL;
7160                                 sp->tail_mbuf = NULL;
7161                         }
7162                         sp->length = 0;
7163                         sp->some_taken = 1;
7164                         *locked = 1;
7165                         *giveup = 1;
7166                         to_move = 0;
7167                         goto out_of;
7168                 }
7169         }
7170         some_taken = sp->some_taken;
7171         if (stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET) {
7172                 sp->msg_is_complete = 1;
7173         }
7174 re_look:
7175         length = sp->length;
7176         if (sp->msg_is_complete) {
7177                 /* The message is complete */
7178                 to_move = min(length, frag_point);
7179                 if (to_move == length) {
7180                         /* All of it fits in the MTU */
7181                         if (sp->some_taken) {
7182                                 rcv_flags |= SCTP_DATA_LAST_FRAG;
7183                                 sp->put_last_out = 1;
7184                         } else {
7185                                 rcv_flags |= SCTP_DATA_NOT_FRAG;
7186                                 sp->put_last_out = 1;
7187                         }
7188                 } else {
7189                         /* Not all of it fits, we fragment */
7190                         if (sp->some_taken == 0) {
7191                                 rcv_flags |= SCTP_DATA_FIRST_FRAG;
7192                         }
7193                         sp->some_taken = 1;
7194                 }
7195         } else {
7196                 to_move = sctp_can_we_split_this(stcb, length, goal_mtu, frag_point, eeor_mode);
7197                 if (to_move) {
7198                         /*-
7199                          * We use a snapshot of length in case it
7200                          * is expanding during the compare.
7201                          */
7202                         uint32_t llen;
7203
7204                         llen = length;
7205                         if (to_move >= llen) {
7206                                 to_move = llen;
7207                                 if (send_lock_up == 0) {
7208                                         /*-
7209                                          * We are taking all of an incomplete msg
7210                                          * thus we need a send lock.
7211                                          */
7212                                         SCTP_TCB_SEND_LOCK(stcb);
7213                                         send_lock_up = 1;
7214                                         if (sp->msg_is_complete) {
7215                                                 /*
7216                                                  * the sender finished the
7217                                                  * msg
7218                                                  */
7219                                                 goto re_look;
7220                                         }
7221                                 }
7222                         }
7223                         if (sp->some_taken == 0) {
7224                                 rcv_flags |= SCTP_DATA_FIRST_FRAG;
7225                                 sp->some_taken = 1;
7226                         }
7227                 } else {
7228                         /* Nothing to take. */
7229                         if (sp->some_taken) {
7230                                 *locked = 1;
7231                         }
7232                         *giveup = 1;
7233                         to_move = 0;
7234                         goto out_of;
7235                 }
7236         }
7237
7238         /* If we reach here, we can copy out a chunk */
7239         sctp_alloc_a_chunk(stcb, chk);
7240         if (chk == NULL) {
7241                 /* No chunk memory */
7242                 *giveup = 1;
7243                 to_move = 0;
7244                 goto out_of;
7245         }
7246         /*
7247          * Setup for unordered if needed by looking at the user sent info
7248          * flags.
7249          */
7250         if (sp->sinfo_flags & SCTP_UNORDERED) {
7251                 rcv_flags |= SCTP_DATA_UNORDERED;
7252         }
7253         if ((SCTP_BASE_SYSCTL(sctp_enable_sack_immediately) && ((sp->sinfo_flags & SCTP_EOF) == SCTP_EOF)) ||
7254             ((sp->sinfo_flags & SCTP_SACK_IMMEDIATELY) == SCTP_SACK_IMMEDIATELY)) {
7255                 rcv_flags |= SCTP_DATA_SACK_IMMEDIATELY;
7256         }
7257         /* clear out the chunk before setting up */
7258         memset(chk, 0, sizeof(*chk));
7259         chk->rec.data.rcv_flags = rcv_flags;
7260
7261         if (to_move >= length) {
7262                 /* we think we can steal the whole thing */
7263                 if ((sp->sender_all_done == 0) && (send_lock_up == 0)) {
7264                         SCTP_TCB_SEND_LOCK(stcb);
7265                         send_lock_up = 1;
7266                 }
7267                 if (to_move < sp->length) {
7268                         /* bail, it changed */
7269                         goto dont_do_it;
7270                 }
7271                 chk->data = sp->data;
7272                 chk->last_mbuf = sp->tail_mbuf;
7273                 /* register the stealing */
7274                 sp->data = sp->tail_mbuf = NULL;
7275         } else {
7276                 struct mbuf *m;
7277
7278 dont_do_it:
7279                 chk->data = SCTP_M_COPYM(sp->data, 0, to_move, M_DONTWAIT);
7280                 chk->last_mbuf = NULL;
7281                 if (chk->data == NULL) {
7282                         sp->some_taken = some_taken;
7283                         sctp_free_a_chunk(stcb, chk, so_locked);
7284                         *bail = 1;
7285                         to_move = 0;
7286                         goto out_of;
7287                 }
7288 #ifdef SCTP_MBUF_LOGGING
7289                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
7290                         struct mbuf *mat;
7291
7292                         for (mat = chk->data; mat; mat = SCTP_BUF_NEXT(mat)) {
7293                                 if (SCTP_BUF_IS_EXTENDED(mat)) {
7294                                         sctp_log_mb(mat, SCTP_MBUF_ICOPY);
7295                                 }
7296                         }
7297                 }
7298 #endif
7299                 /* Pull off the data */
7300                 m_adj(sp->data, to_move);
7301                 /* Now lets work our way down and compact it */
7302                 m = sp->data;
7303                 while (m && (SCTP_BUF_LEN(m) == 0)) {
7304                         sp->data = SCTP_BUF_NEXT(m);
7305                         SCTP_BUF_NEXT(m) = NULL;
7306                         if (sp->tail_mbuf == m) {
7307                                 /*-
7308                                  * Freeing tail? TSNH since
7309                                  * we supposedly were taking less
7310                                  * than the sp->length.
7311                                  */
7312 #ifdef INVARIANTS
7313                                 panic("Huh, freing tail? - TSNH");
7314 #else
7315                                 SCTP_PRINTF("Huh, freeing tail? - TSNH\n");
7316                                 sp->tail_mbuf = sp->data = NULL;
7317                                 sp->length = 0;
7318 #endif
7319
7320                         }
7321                         sctp_m_free(m);
7322                         m = sp->data;
7323                 }
7324         }
7325         if (SCTP_BUF_IS_EXTENDED(chk->data)) {
7326                 chk->copy_by_ref = 1;
7327         } else {
7328                 chk->copy_by_ref = 0;
7329         }
7330         /*
7331          * get last_mbuf and counts of mb useage This is ugly but hopefully
7332          * its only one mbuf.
7333          */
7334         if (chk->last_mbuf == NULL) {
7335                 chk->last_mbuf = chk->data;
7336                 while (SCTP_BUF_NEXT(chk->last_mbuf) != NULL) {
7337                         chk->last_mbuf = SCTP_BUF_NEXT(chk->last_mbuf);
7338                 }
7339         }
7340         if (to_move > length) {
7341                 /*- This should not happen either
7342                  * since we always lower to_move to the size
7343                  * of sp->length if its larger.
7344                  */
7345 #ifdef INVARIANTS
7346                 panic("Huh, how can to_move be larger?");
7347 #else
7348                 SCTP_PRINTF("Huh, how can to_move be larger?\n");
7349                 sp->length = 0;
7350 #endif
7351         } else {
7352                 atomic_subtract_int(&sp->length, to_move);
7353         }
7354         if (M_LEADINGSPACE(chk->data) < (int)sizeof(struct sctp_data_chunk)) {
7355                 /* Not enough room for a chunk header, get some */
7356                 struct mbuf *m;
7357
7358                 m = sctp_get_mbuf_for_msg(1, 0, M_DONTWAIT, 0, MT_DATA);
7359                 if (m == NULL) {
7360                         /*
7361                          * we're in trouble here. _PREPEND below will free
7362                          * all the data if there is no leading space, so we
7363                          * must put the data back and restore.
7364                          */
7365                         if (send_lock_up == 0) {
7366                                 SCTP_TCB_SEND_LOCK(stcb);
7367                                 send_lock_up = 1;
7368                         }
7369                         if (chk->data == NULL) {
7370                                 /* unsteal the data */
7371                                 sp->data = chk->data;
7372                                 sp->tail_mbuf = chk->last_mbuf;
7373                         } else {
7374                                 struct mbuf *m_tmp;
7375
7376                                 /* reassemble the data */
7377                                 m_tmp = sp->data;
7378                                 sp->data = chk->data;
7379                                 SCTP_BUF_NEXT(chk->last_mbuf) = m_tmp;
7380                         }
7381                         sp->some_taken = some_taken;
7382                         atomic_add_int(&sp->length, to_move);
7383                         chk->data = NULL;
7384                         *bail = 1;
7385                         sctp_free_a_chunk(stcb, chk, so_locked);
7386                         to_move = 0;
7387                         goto out_of;
7388                 } else {
7389                         SCTP_BUF_LEN(m) = 0;
7390                         SCTP_BUF_NEXT(m) = chk->data;
7391                         chk->data = m;
7392                         M_ALIGN(chk->data, 4);
7393                 }
7394         }
7395         SCTP_BUF_PREPEND(chk->data, sizeof(struct sctp_data_chunk), M_DONTWAIT);
7396         if (chk->data == NULL) {
7397                 /* HELP, TSNH since we assured it would not above? */
7398 #ifdef INVARIANTS
7399                 panic("prepend failes HELP?");
7400 #else
7401                 SCTP_PRINTF("prepend fails HELP?\n");
7402                 sctp_free_a_chunk(stcb, chk, so_locked);
7403 #endif
7404                 *bail = 1;
7405                 to_move = 0;
7406                 goto out_of;
7407         }
7408         sctp_snd_sb_alloc(stcb, sizeof(struct sctp_data_chunk));
7409         chk->book_size = chk->send_size = (to_move + sizeof(struct sctp_data_chunk));
7410         chk->book_size_scale = 0;
7411         chk->sent = SCTP_DATAGRAM_UNSENT;
7412
7413         chk->flags = 0;
7414         chk->asoc = &stcb->asoc;
7415         chk->pad_inplace = 0;
7416         chk->no_fr_allowed = 0;
7417         chk->rec.data.stream_seq = strq->next_sequence_send;
7418         if (rcv_flags & SCTP_DATA_LAST_FRAG) {
7419                 strq->next_sequence_send++;
7420         }
7421         chk->rec.data.stream_number = sp->stream;
7422         chk->rec.data.payloadtype = sp->ppid;
7423         chk->rec.data.context = sp->context;
7424         chk->rec.data.doing_fast_retransmit = 0;
7425
7426         chk->rec.data.timetodrop = sp->ts;
7427         chk->flags = sp->act_flags;
7428
7429         if (sp->net) {
7430                 chk->whoTo = sp->net;
7431                 atomic_add_int(&chk->whoTo->ref_count, 1);
7432         } else
7433                 chk->whoTo = NULL;
7434
7435         if (sp->holds_key_ref) {
7436                 chk->auth_keyid = sp->auth_keyid;
7437                 sctp_auth_key_acquire(stcb, chk->auth_keyid);
7438                 chk->holds_key_ref = 1;
7439         }
7440         chk->rec.data.TSN_seq = atomic_fetchadd_int(&asoc->sending_seq, 1);
7441         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_AT_SEND_2_OUTQ) {
7442                 sctp_misc_ints(SCTP_STRMOUT_LOG_SEND,
7443                     (uintptr_t) stcb, sp->length,
7444                     (uint32_t) ((chk->rec.data.stream_number << 16) | chk->rec.data.stream_seq),
7445                     chk->rec.data.TSN_seq);
7446         }
7447         dchkh = mtod(chk->data, struct sctp_data_chunk *);
7448         /*
7449          * Put the rest of the things in place now. Size was done earlier in
7450          * previous loop prior to padding.
7451          */
7452
7453 #ifdef SCTP_ASOCLOG_OF_TSNS
7454         SCTP_TCB_LOCK_ASSERT(stcb);
7455         if (asoc->tsn_out_at >= SCTP_TSN_LOG_SIZE) {
7456                 asoc->tsn_out_at = 0;
7457                 asoc->tsn_out_wrapped = 1;
7458         }
7459         asoc->out_tsnlog[asoc->tsn_out_at].tsn = chk->rec.data.TSN_seq;
7460         asoc->out_tsnlog[asoc->tsn_out_at].strm = chk->rec.data.stream_number;
7461         asoc->out_tsnlog[asoc->tsn_out_at].seq = chk->rec.data.stream_seq;
7462         asoc->out_tsnlog[asoc->tsn_out_at].sz = chk->send_size;
7463         asoc->out_tsnlog[asoc->tsn_out_at].flgs = chk->rec.data.rcv_flags;
7464         asoc->out_tsnlog[asoc->tsn_out_at].stcb = (void *)stcb;
7465         asoc->out_tsnlog[asoc->tsn_out_at].in_pos = asoc->tsn_out_at;
7466         asoc->out_tsnlog[asoc->tsn_out_at].in_out = 2;
7467         asoc->tsn_out_at++;
7468 #endif
7469
7470         dchkh->ch.chunk_type = SCTP_DATA;
7471         dchkh->ch.chunk_flags = chk->rec.data.rcv_flags;
7472         dchkh->dp.tsn = htonl(chk->rec.data.TSN_seq);
7473         dchkh->dp.stream_id = htons(strq->stream_no);
7474         dchkh->dp.stream_sequence = htons(chk->rec.data.stream_seq);
7475         dchkh->dp.protocol_id = chk->rec.data.payloadtype;
7476         dchkh->ch.chunk_length = htons(chk->send_size);
7477         /* Now advance the chk->send_size by the actual pad needed. */
7478         if (chk->send_size < SCTP_SIZE32(chk->book_size)) {
7479                 /* need a pad */
7480                 struct mbuf *lm;
7481                 int pads;
7482
7483                 pads = SCTP_SIZE32(chk->book_size) - chk->send_size;
7484                 if (sctp_pad_lastmbuf(chk->data, pads, chk->last_mbuf) == 0) {
7485                         chk->pad_inplace = 1;
7486                 }
7487                 if ((lm = SCTP_BUF_NEXT(chk->last_mbuf)) != NULL) {
7488                         /* pad added an mbuf */
7489                         chk->last_mbuf = lm;
7490                 }
7491                 chk->send_size += pads;
7492         }
7493         /* We only re-set the policy if it is on */
7494         if (sp->pr_sctp_on) {
7495                 sctp_set_prsctp_policy(sp);
7496                 asoc->pr_sctp_cnt++;
7497                 chk->pr_sctp_on = 1;
7498         } else {
7499                 chk->pr_sctp_on = 0;
7500         }
7501         if (sp->msg_is_complete && (sp->length == 0) && (sp->sender_all_done)) {
7502                 /* All done pull and kill the message */
7503                 atomic_subtract_int(&asoc->stream_queue_cnt, 1);
7504                 if (sp->put_last_out == 0) {
7505                         SCTP_PRINTF("Gak, put out entire msg with NO end!-2\n");
7506                         SCTP_PRINTF("sender_done:%d len:%d msg_comp:%d put_last_out:%d send_lock:%d\n",
7507                             sp->sender_all_done,
7508                             sp->length,
7509                             sp->msg_is_complete,
7510                             sp->put_last_out,
7511                             send_lock_up);
7512                 }
7513                 if ((send_lock_up == 0) && (TAILQ_NEXT(sp, next) == NULL)) {
7514                         SCTP_TCB_SEND_LOCK(stcb);
7515                         send_lock_up = 1;
7516                 }
7517                 TAILQ_REMOVE(&strq->outqueue, sp, next);
7518                 stcb->asoc.ss_functions.sctp_ss_remove_from_stream(stcb, asoc, strq, sp, send_lock_up);
7519                 if (sp->net) {
7520                         sctp_free_remote_addr(sp->net);
7521                         sp->net = NULL;
7522                 }
7523                 if (sp->data) {
7524                         sctp_m_freem(sp->data);
7525                         sp->data = NULL;
7526                 }
7527                 sctp_free_a_strmoq(stcb, sp, so_locked);
7528
7529                 /* we can't be locked to it */
7530                 *locked = 0;
7531                 stcb->asoc.locked_on_sending = NULL;
7532         } else {
7533                 /* more to go, we are locked */
7534                 *locked = 1;
7535         }
7536         asoc->chunks_on_out_queue++;
7537         strq->chunks_on_queues++;
7538         TAILQ_INSERT_TAIL(&asoc->send_queue, chk, sctp_next);
7539         asoc->send_queue_cnt++;
7540 out_of:
7541         if (send_lock_up) {
7542                 SCTP_TCB_SEND_UNLOCK(stcb);
7543         }
7544         return (to_move);
7545 }
7546
7547
7548 static void
7549 sctp_fill_outqueue(struct sctp_tcb *stcb,
7550     struct sctp_nets *net, int frag_point, int eeor_mode, int *quit_now, int so_locked
7551 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
7552     SCTP_UNUSED
7553 #endif
7554 )
7555 {
7556         struct sctp_association *asoc;
7557         struct sctp_stream_out *strq;
7558         int goal_mtu, moved_how_much, total_moved = 0, bail = 0;
7559         int locked, giveup;
7560
7561         SCTP_TCB_LOCK_ASSERT(stcb);
7562         asoc = &stcb->asoc;
7563         switch (net->ro._l_addr.sa.sa_family) {
7564 #ifdef INET
7565         case AF_INET:
7566                 goal_mtu = net->mtu - SCTP_MIN_V4_OVERHEAD;
7567                 break;
7568 #endif
7569 #ifdef INET6
7570         case AF_INET6:
7571                 goal_mtu = net->mtu - SCTP_MIN_OVERHEAD;
7572                 break;
7573 #endif
7574         default:
7575                 /* TSNH */
7576                 goal_mtu = net->mtu;
7577                 break;
7578         }
7579         /* Need an allowance for the data chunk header too */
7580         goal_mtu -= sizeof(struct sctp_data_chunk);
7581
7582         /* must make even word boundary */
7583         goal_mtu &= 0xfffffffc;
7584         if (asoc->locked_on_sending) {
7585                 /* We are stuck on one stream until the message completes. */
7586                 strq = asoc->locked_on_sending;
7587                 locked = 1;
7588         } else {
7589                 strq = stcb->asoc.ss_functions.sctp_ss_select_stream(stcb, net, asoc);
7590                 locked = 0;
7591         }
7592         while ((goal_mtu > 0) && strq) {
7593                 giveup = 0;
7594                 bail = 0;
7595                 moved_how_much = sctp_move_to_outqueue(stcb, strq, goal_mtu, frag_point, &locked,
7596                     &giveup, eeor_mode, &bail, so_locked);
7597                 if (moved_how_much)
7598                         stcb->asoc.ss_functions.sctp_ss_scheduled(stcb, net, asoc, strq, moved_how_much);
7599
7600                 if (locked) {
7601                         asoc->locked_on_sending = strq;
7602                         if ((moved_how_much == 0) || (giveup) || bail)
7603                                 /* no more to move for now */
7604                                 break;
7605                 } else {
7606                         asoc->locked_on_sending = NULL;
7607                         if ((giveup) || bail) {
7608                                 break;
7609                         }
7610                         strq = stcb->asoc.ss_functions.sctp_ss_select_stream(stcb, net, asoc);
7611                         if (strq == NULL) {
7612                                 break;
7613                         }
7614                 }
7615                 total_moved += moved_how_much;
7616                 goal_mtu -= (moved_how_much + sizeof(struct sctp_data_chunk));
7617                 goal_mtu &= 0xfffffffc;
7618         }
7619         if (bail)
7620                 *quit_now = 1;
7621
7622         stcb->asoc.ss_functions.sctp_ss_packet_done(stcb, net, asoc);
7623
7624         if (total_moved == 0) {
7625                 if ((stcb->asoc.sctp_cmt_on_off == 0) &&
7626                     (net == stcb->asoc.primary_destination)) {
7627                         /* ran dry for primary network net */
7628                         SCTP_STAT_INCR(sctps_primary_randry);
7629                 } else if (stcb->asoc.sctp_cmt_on_off > 0) {
7630                         /* ran dry with CMT on */
7631                         SCTP_STAT_INCR(sctps_cmt_randry);
7632                 }
7633         }
7634 }
7635
7636 void
7637 sctp_fix_ecn_echo(struct sctp_association *asoc)
7638 {
7639         struct sctp_tmit_chunk *chk;
7640
7641         TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
7642                 if (chk->rec.chunk_id.id == SCTP_ECN_ECHO) {
7643                         chk->sent = SCTP_DATAGRAM_UNSENT;
7644                 }
7645         }
7646 }
7647
7648 void
7649 sctp_move_chunks_from_net(struct sctp_tcb *stcb, struct sctp_nets *net)
7650 {
7651         struct sctp_association *asoc;
7652         struct sctp_tmit_chunk *chk;
7653         struct sctp_stream_queue_pending *sp;
7654         unsigned int i;
7655
7656         if (net == NULL) {
7657                 return;
7658         }
7659         asoc = &stcb->asoc;
7660         for (i = 0; i < stcb->asoc.streamoutcnt; i++) {
7661                 TAILQ_FOREACH(sp, &stcb->asoc.strmout[i].outqueue, next) {
7662                         if (sp->net == net) {
7663                                 sctp_free_remote_addr(sp->net);
7664                                 sp->net = NULL;
7665                         }
7666                 }
7667         }
7668         TAILQ_FOREACH(chk, &asoc->send_queue, sctp_next) {
7669                 if (chk->whoTo == net) {
7670                         sctp_free_remote_addr(chk->whoTo);
7671                         chk->whoTo = NULL;
7672                 }
7673         }
7674 }
7675
7676 int
7677 sctp_med_chunk_output(struct sctp_inpcb *inp,
7678     struct sctp_tcb *stcb,
7679     struct sctp_association *asoc,
7680     int *num_out,
7681     int *reason_code,
7682     int control_only, int from_where,
7683     struct timeval *now, int *now_filled, int frag_point, int so_locked
7684 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
7685     SCTP_UNUSED
7686 #endif
7687 )
7688 {
7689         /*
7690          * Ok this is the generic chunk service queue. we must do the
7691          * following: - Service the stream queue that is next, moving any
7692          * message (note I must get a complete message i.e. FIRST/MIDDLE and
7693          * LAST to the out queue in one pass) and assigning TSN's - Check to
7694          * see if the cwnd/rwnd allows any output, if so we go ahead and
7695          * fomulate and send the low level chunks. Making sure to combine
7696          * any control in the control chunk queue also.
7697          */
7698         struct sctp_nets *net, *start_at, *sack_goes_to = NULL, *old_start_at = NULL;
7699         struct mbuf *outchain, *endoutchain;
7700         struct sctp_tmit_chunk *chk, *nchk;
7701
7702         /* temp arrays for unlinking */
7703         struct sctp_tmit_chunk *data_list[SCTP_MAX_DATA_BUNDLING];
7704         int no_fragmentflg, error;
7705         unsigned int max_rwnd_per_dest, max_send_per_dest;
7706         int one_chunk, hbflag, skip_data_for_this_net;
7707         int asconf, cookie, no_out_cnt;
7708         int bundle_at, ctl_cnt, no_data_chunks, eeor_mode;
7709         unsigned int mtu, r_mtu, omtu, mx_mtu, to_out;
7710         int tsns_sent = 0;
7711         uint32_t auth_offset = 0;
7712         struct sctp_auth_chunk *auth = NULL;
7713         uint16_t auth_keyid;
7714         int override_ok = 1;
7715         int skip_fill_up = 0;
7716         int data_auth_reqd = 0;
7717
7718         /*
7719          * JRS 5/14/07 - Add flag for whether a heartbeat is sent to the
7720          * destination.
7721          */
7722         int quit_now = 0;
7723
7724         *num_out = 0;
7725         auth_keyid = stcb->asoc.authinfo.active_keyid;
7726
7727         if ((asoc->state & SCTP_STATE_SHUTDOWN_PENDING) ||
7728             (asoc->state & SCTP_STATE_SHUTDOWN_RECEIVED) ||
7729             (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_EXPLICIT_EOR))) {
7730                 eeor_mode = 1;
7731         } else {
7732                 eeor_mode = 0;
7733         }
7734         ctl_cnt = no_out_cnt = asconf = cookie = 0;
7735         /*
7736          * First lets prime the pump. For each destination, if there is room
7737          * in the flight size, attempt to pull an MTU's worth out of the
7738          * stream queues into the general send_queue
7739          */
7740 #ifdef SCTP_AUDITING_ENABLED
7741         sctp_audit_log(0xC2, 2);
7742 #endif
7743         SCTP_TCB_LOCK_ASSERT(stcb);
7744         hbflag = 0;
7745         if ((control_only) || (asoc->stream_reset_outstanding))
7746                 no_data_chunks = 1;
7747         else
7748                 no_data_chunks = 0;
7749
7750         /* Nothing to possible to send? */
7751         if ((TAILQ_EMPTY(&asoc->control_send_queue) ||
7752             (asoc->ctrl_queue_cnt == stcb->asoc.ecn_echo_cnt_onq)) &&
7753             TAILQ_EMPTY(&asoc->asconf_send_queue) &&
7754             TAILQ_EMPTY(&asoc->send_queue) &&
7755             stcb->asoc.ss_functions.sctp_ss_is_empty(stcb, asoc)) {
7756 nothing_to_send:
7757                 *reason_code = 9;
7758                 return (0);
7759         }
7760         if (asoc->peers_rwnd == 0) {
7761                 /* No room in peers rwnd */
7762                 *reason_code = 1;
7763                 if (asoc->total_flight > 0) {
7764                         /* we are allowed one chunk in flight */
7765                         no_data_chunks = 1;
7766                 }
7767         }
7768         if (stcb->asoc.ecn_echo_cnt_onq) {
7769                 /* Record where a sack goes, if any */
7770                 if (no_data_chunks &&
7771                     (asoc->ctrl_queue_cnt == stcb->asoc.ecn_echo_cnt_onq)) {
7772                         /* Nothing but ECNe to send - we don't do that */
7773                         goto nothing_to_send;
7774                 }
7775                 TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
7776                         if ((chk->rec.chunk_id.id == SCTP_SELECTIVE_ACK) ||
7777                             (chk->rec.chunk_id.id == SCTP_NR_SELECTIVE_ACK)) {
7778                                 sack_goes_to = chk->whoTo;
7779                                 break;
7780                         }
7781                 }
7782         }
7783         max_rwnd_per_dest = ((asoc->peers_rwnd + asoc->total_flight) / asoc->numnets);
7784         if (stcb->sctp_socket)
7785                 max_send_per_dest = SCTP_SB_LIMIT_SND(stcb->sctp_socket) / asoc->numnets;
7786         else
7787                 max_send_per_dest = 0;
7788         if (no_data_chunks == 0) {
7789                 /* How many non-directed chunks are there? */
7790                 TAILQ_FOREACH(chk, &asoc->send_queue, sctp_next) {
7791                         if (chk->whoTo == NULL) {
7792                                 /*
7793                                  * We already have non-directed chunks on
7794                                  * the queue, no need to do a fill-up.
7795                                  */
7796                                 skip_fill_up = 1;
7797                                 break;
7798                         }
7799                 }
7800
7801         }
7802         if ((no_data_chunks == 0) &&
7803             (skip_fill_up == 0) &&
7804             (!stcb->asoc.ss_functions.sctp_ss_is_empty(stcb, asoc))) {
7805                 TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
7806                         /*
7807                          * This for loop we are in takes in each net, if
7808                          * its's got space in cwnd and has data sent to it
7809                          * (when CMT is off) then it calls
7810                          * sctp_fill_outqueue for the net. This gets data on
7811                          * the send queue for that network.
7812                          * 
7813                          * In sctp_fill_outqueue TSN's are assigned and data is
7814                          * copied out of the stream buffers. Note mostly
7815                          * copy by reference (we hope).
7816                          */
7817                         net->window_probe = 0;
7818                         if ((net != stcb->asoc.alternate) &&
7819                             ((net->dest_state & SCTP_ADDR_PF) ||
7820                             (!(net->dest_state & SCTP_ADDR_REACHABLE)) ||
7821                             (net->dest_state & SCTP_ADDR_UNCONFIRMED))) {
7822                                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
7823                                         sctp_log_cwnd(stcb, net, 1,
7824                                             SCTP_CWND_LOG_FILL_OUTQ_CALLED);
7825                                 }
7826                                 continue;
7827                         }
7828                         if ((stcb->asoc.cc_functions.sctp_cwnd_new_transmission_begins) &&
7829                             (net->flight_size == 0)) {
7830                                 (*stcb->asoc.cc_functions.sctp_cwnd_new_transmission_begins) (stcb, net);
7831                         }
7832                         if (net->flight_size >= net->cwnd) {
7833                                 /* skip this network, no room - can't fill */
7834                                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
7835                                         sctp_log_cwnd(stcb, net, 3,
7836                                             SCTP_CWND_LOG_FILL_OUTQ_CALLED);
7837                                 }
7838                                 continue;
7839                         }
7840                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
7841                                 sctp_log_cwnd(stcb, net, 4, SCTP_CWND_LOG_FILL_OUTQ_CALLED);
7842                         }
7843                         sctp_fill_outqueue(stcb, net, frag_point, eeor_mode, &quit_now, so_locked);
7844                         if (quit_now) {
7845                                 /* memory alloc failure */
7846                                 no_data_chunks = 1;
7847                                 break;
7848                         }
7849                 }
7850         }
7851         /* now service each destination and send out what we can for it */
7852         /* Nothing to send? */
7853         if (TAILQ_EMPTY(&asoc->control_send_queue) &&
7854             TAILQ_EMPTY(&asoc->asconf_send_queue) &&
7855             TAILQ_EMPTY(&asoc->send_queue)) {
7856                 *reason_code = 8;
7857                 return (0);
7858         }
7859         if (asoc->sctp_cmt_on_off > 0) {
7860                 /* get the last start point */
7861                 start_at = asoc->last_net_cmt_send_started;
7862                 if (start_at == NULL) {
7863                         /* null so to beginning */
7864                         start_at = TAILQ_FIRST(&asoc->nets);
7865                 } else {
7866                         start_at = TAILQ_NEXT(asoc->last_net_cmt_send_started, sctp_next);
7867                         if (start_at == NULL) {
7868                                 start_at = TAILQ_FIRST(&asoc->nets);
7869                         }
7870                 }
7871                 asoc->last_net_cmt_send_started = start_at;
7872         } else {
7873                 start_at = TAILQ_FIRST(&asoc->nets);
7874         }
7875         TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
7876                 if (chk->whoTo == NULL) {
7877                         if (asoc->alternate) {
7878                                 chk->whoTo = asoc->alternate;
7879                         } else {
7880                                 chk->whoTo = asoc->primary_destination;
7881                         }
7882                         atomic_add_int(&chk->whoTo->ref_count, 1);
7883                 }
7884         }
7885         old_start_at = NULL;
7886 again_one_more_time:
7887         for (net = start_at; net != NULL; net = TAILQ_NEXT(net, sctp_next)) {
7888                 /* how much can we send? */
7889                 /* SCTPDBG("Examine for sending net:%x\n", (uint32_t)net); */
7890                 if (old_start_at && (old_start_at == net)) {
7891                         /* through list ocmpletely. */
7892                         break;
7893                 }
7894                 tsns_sent = 0xa;
7895                 if (TAILQ_EMPTY(&asoc->control_send_queue) &&
7896                     TAILQ_EMPTY(&asoc->asconf_send_queue) &&
7897                     (net->flight_size >= net->cwnd)) {
7898                         /*
7899                          * Nothing on control or asconf and flight is full,
7900                          * we can skip even in the CMT case.
7901                          */
7902                         continue;
7903                 }
7904                 bundle_at = 0;
7905                 endoutchain = outchain = NULL;
7906                 no_fragmentflg = 1;
7907                 one_chunk = 0;
7908                 if (net->dest_state & SCTP_ADDR_UNCONFIRMED) {
7909                         skip_data_for_this_net = 1;
7910                 } else {
7911                         skip_data_for_this_net = 0;
7912                 }
7913                 if ((net->ro.ro_rt) && (net->ro.ro_rt->rt_ifp)) {
7914                         /*
7915                          * if we have a route and an ifp check to see if we
7916                          * have room to send to this guy
7917                          */
7918                         struct ifnet *ifp;
7919
7920                         ifp = net->ro.ro_rt->rt_ifp;
7921                         if ((ifp->if_snd.ifq_len + 2) >= ifp->if_snd.ifq_maxlen) {
7922                                 SCTP_STAT_INCR(sctps_ifnomemqueued);
7923                                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_MAXBURST_ENABLE) {
7924                                         sctp_log_maxburst(stcb, net, ifp->if_snd.ifq_len, ifp->if_snd.ifq_maxlen, SCTP_MAX_IFP_APPLIED);
7925                                 }
7926                                 continue;
7927                         }
7928                 }
7929                 switch (((struct sockaddr *)&net->ro._l_addr)->sa_family) {
7930 #ifdef INET
7931                 case AF_INET:
7932                         mtu = net->mtu - (sizeof(struct ip) + sizeof(struct sctphdr));
7933                         break;
7934 #endif
7935 #ifdef INET6
7936                 case AF_INET6:
7937                         mtu = net->mtu - (sizeof(struct ip6_hdr) + sizeof(struct sctphdr));
7938                         break;
7939 #endif
7940                 default:
7941                         /* TSNH */
7942                         mtu = net->mtu;
7943                         break;
7944                 }
7945                 mx_mtu = mtu;
7946                 to_out = 0;
7947                 if (mtu > asoc->peers_rwnd) {
7948                         if (asoc->total_flight > 0) {
7949                                 /* We have a packet in flight somewhere */
7950                                 r_mtu = asoc->peers_rwnd;
7951                         } else {
7952                                 /* We are always allowed to send one MTU out */
7953                                 one_chunk = 1;
7954                                 r_mtu = mtu;
7955                         }
7956                 } else {
7957                         r_mtu = mtu;
7958                 }
7959                 /************************/
7960                 /* ASCONF transmission */
7961                 /************************/
7962                 /* Now first lets go through the asconf queue */
7963                 TAILQ_FOREACH_SAFE(chk, &asoc->asconf_send_queue, sctp_next, nchk) {
7964                         if (chk->rec.chunk_id.id != SCTP_ASCONF) {
7965                                 continue;
7966                         }
7967                         if (chk->whoTo == NULL) {
7968                                 if (asoc->alternate == NULL) {
7969                                         if (asoc->primary_destination != net) {
7970                                                 break;
7971                                         }
7972                                 } else {
7973                                         if (asoc->alternate != net) {
7974                                                 break;
7975                                         }
7976                                 }
7977                         } else {
7978                                 if (chk->whoTo != net) {
7979                                         break;
7980                                 }
7981                         }
7982                         if (chk->data == NULL) {
7983                                 break;
7984                         }
7985                         if (chk->sent != SCTP_DATAGRAM_UNSENT &&
7986                             chk->sent != SCTP_DATAGRAM_RESEND) {
7987                                 break;
7988                         }
7989                         /*
7990                          * if no AUTH is yet included and this chunk
7991                          * requires it, make sure to account for it.  We
7992                          * don't apply the size until the AUTH chunk is
7993                          * actually added below in case there is no room for
7994                          * this chunk. NOTE: we overload the use of "omtu"
7995                          * here
7996                          */
7997                         if ((auth == NULL) &&
7998                             sctp_auth_is_required_chunk(chk->rec.chunk_id.id,
7999                             stcb->asoc.peer_auth_chunks)) {
8000                                 omtu = sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
8001                         } else
8002                                 omtu = 0;
8003                         /* Here we do NOT factor the r_mtu */
8004                         if ((chk->send_size < (int)(mtu - omtu)) ||
8005                             (chk->flags & CHUNK_FLAGS_FRAGMENT_OK)) {
8006                                 /*
8007                                  * We probably should glom the mbuf chain
8008                                  * from the chk->data for control but the
8009                                  * problem is it becomes yet one more level
8010                                  * of tracking to do if for some reason
8011                                  * output fails. Then I have got to
8012                                  * reconstruct the merged control chain.. el
8013                                  * yucko.. for now we take the easy way and
8014                                  * do the copy
8015                                  */
8016                                 /*
8017                                  * Add an AUTH chunk, if chunk requires it
8018                                  * save the offset into the chain for AUTH
8019                                  */
8020                                 if ((auth == NULL) &&
8021                                     (sctp_auth_is_required_chunk(chk->rec.chunk_id.id,
8022                                     stcb->asoc.peer_auth_chunks))) {
8023                                         outchain = sctp_add_auth_chunk(outchain,
8024                                             &endoutchain,
8025                                             &auth,
8026                                             &auth_offset,
8027                                             stcb,
8028                                             chk->rec.chunk_id.id);
8029                                         SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
8030                                 }
8031                                 outchain = sctp_copy_mbufchain(chk->data, outchain, &endoutchain,
8032                                     (int)chk->rec.chunk_id.can_take_data,
8033                                     chk->send_size, chk->copy_by_ref);
8034                                 if (outchain == NULL) {
8035                                         *reason_code = 8;
8036                                         SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
8037                                         return (ENOMEM);
8038                                 }
8039                                 SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
8040                                 /* update our MTU size */
8041                                 if (mtu > (chk->send_size + omtu))
8042                                         mtu -= (chk->send_size + omtu);
8043                                 else
8044                                         mtu = 0;
8045                                 to_out += (chk->send_size + omtu);
8046                                 /* Do clear IP_DF ? */
8047                                 if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
8048                                         no_fragmentflg = 0;
8049                                 }
8050                                 if (chk->rec.chunk_id.can_take_data)
8051                                         chk->data = NULL;
8052                                 /*
8053                                  * set hb flag since we can use these for
8054                                  * RTO
8055                                  */
8056                                 hbflag = 1;
8057                                 asconf = 1;
8058                                 /*
8059                                  * should sysctl this: don't bundle data
8060                                  * with ASCONF since it requires AUTH
8061                                  */
8062                                 no_data_chunks = 1;
8063                                 chk->sent = SCTP_DATAGRAM_SENT;
8064                                 if (chk->whoTo == NULL) {
8065                                         chk->whoTo = net;
8066                                         atomic_add_int(&net->ref_count, 1);
8067                                 }
8068                                 chk->snd_count++;
8069                                 if (mtu == 0) {
8070                                         /*
8071                                          * Ok we are out of room but we can
8072                                          * output without effecting the
8073                                          * flight size since this little guy
8074                                          * is a control only packet.
8075                                          */
8076                                         sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp, stcb, net);
8077                                         /*
8078                                          * do NOT clear the asconf flag as
8079                                          * it is used to do appropriate
8080                                          * source address selection.
8081                                          */
8082                                         if ((error = sctp_lowlevel_chunk_output(inp, stcb, net,
8083                                             (struct sockaddr *)&net->ro._l_addr,
8084                                             outchain, auth_offset, auth,
8085                                             stcb->asoc.authinfo.active_keyid,
8086                                             no_fragmentflg, 0, asconf,
8087                                             inp->sctp_lport, stcb->rport,
8088                                             htonl(stcb->asoc.peer_vtag),
8089                                             net->port, NULL,
8090                                             0, 0,
8091                                             so_locked))) {
8092                                                 if (error == ENOBUFS) {
8093                                                         asoc->ifp_had_enobuf = 1;
8094                                                         SCTP_STAT_INCR(sctps_lowlevelerr);
8095                                                 }
8096                                                 if (from_where == 0) {
8097                                                         SCTP_STAT_INCR(sctps_lowlevelerrusr);
8098                                                 }
8099                                                 if (*now_filled == 0) {
8100                                                         (void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
8101                                                         *now_filled = 1;
8102                                                         *now = net->last_sent_time;
8103                                                 } else {
8104                                                         net->last_sent_time = *now;
8105                                                 }
8106                                                 hbflag = 0;
8107                                                 /* error, could not output */
8108                                                 if (error == EHOSTUNREACH) {
8109                                                         /*
8110                                                          * Destination went
8111                                                          * unreachable
8112                                                          * during this send
8113                                                          */
8114                                                         sctp_move_chunks_from_net(stcb, net);
8115                                                 }
8116                                                 *reason_code = 7;
8117                                                 continue;
8118                                         } else
8119                                                 asoc->ifp_had_enobuf = 0;
8120                                         if (*now_filled == 0) {
8121                                                 (void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
8122                                                 *now_filled = 1;
8123                                                 *now = net->last_sent_time;
8124                                         } else {
8125                                                 net->last_sent_time = *now;
8126                                         }
8127                                         hbflag = 0;
8128                                         /*
8129                                          * increase the number we sent, if a
8130                                          * cookie is sent we don't tell them
8131                                          * any was sent out.
8132                                          */
8133                                         outchain = endoutchain = NULL;
8134                                         auth = NULL;
8135                                         auth_offset = 0;
8136                                         if (!no_out_cnt)
8137                                                 *num_out += ctl_cnt;
8138                                         /* recalc a clean slate and setup */
8139                                         switch (net->ro._l_addr.sa.sa_family) {
8140 #ifdef INET
8141                                         case AF_INET:
8142                                                 mtu = net->mtu - SCTP_MIN_V4_OVERHEAD;
8143                                                 break;
8144 #endif
8145 #ifdef INET6
8146                                         case AF_INET6:
8147                                                 mtu = net->mtu - SCTP_MIN_OVERHEAD;
8148                                                 break;
8149 #endif
8150                                         default:
8151                                                 /* TSNH */
8152                                                 mtu = net->mtu;
8153                                                 break;
8154                                         }
8155                                         to_out = 0;
8156                                         no_fragmentflg = 1;
8157                                 }
8158                         }
8159                 }
8160                 /************************/
8161                 /* Control transmission */
8162                 /************************/
8163                 /* Now first lets go through the control queue */
8164                 TAILQ_FOREACH_SAFE(chk, &asoc->control_send_queue, sctp_next, nchk) {
8165                         if ((sack_goes_to) &&
8166                             (chk->rec.chunk_id.id == SCTP_ECN_ECHO) &&
8167                             (chk->whoTo != sack_goes_to)) {
8168                                 /*
8169                                  * if we have a sack in queue, and we are
8170                                  * looking at an ecn echo that is NOT queued
8171                                  * to where the sack is going..
8172                                  */
8173                                 if (chk->whoTo == net) {
8174                                         /*
8175                                          * Don't transmit it to where its
8176                                          * going (current net)
8177                                          */
8178                                         continue;
8179                                 } else if (sack_goes_to == net) {
8180                                         /*
8181                                          * But do transmit it to this
8182                                          * address
8183                                          */
8184                                         goto skip_net_check;
8185                                 }
8186                         }
8187                         if (chk->whoTo == NULL) {
8188                                 if (asoc->alternate == NULL) {
8189                                         if (asoc->primary_destination != net) {
8190                                                 continue;
8191                                         }
8192                                 } else {
8193                                         if (asoc->alternate != net) {
8194                                                 continue;
8195                                         }
8196                                 }
8197                         } else {
8198                                 if (chk->whoTo != net) {
8199                                         continue;
8200                                 }
8201                         }
8202         skip_net_check:
8203                         if (chk->data == NULL) {
8204                                 continue;
8205                         }
8206                         if (chk->sent != SCTP_DATAGRAM_UNSENT) {
8207                                 /*
8208                                  * It must be unsent. Cookies and ASCONF's
8209                                  * hang around but there timers will force
8210                                  * when marked for resend.
8211                                  */
8212                                 continue;
8213                         }
8214                         /*
8215                          * if no AUTH is yet included and this chunk
8216                          * requires it, make sure to account for it.  We
8217                          * don't apply the size until the AUTH chunk is
8218                          * actually added below in case there is no room for
8219                          * this chunk. NOTE: we overload the use of "omtu"
8220                          * here
8221                          */
8222                         if ((auth == NULL) &&
8223                             sctp_auth_is_required_chunk(chk->rec.chunk_id.id,
8224                             stcb->asoc.peer_auth_chunks)) {
8225                                 omtu = sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
8226                         } else
8227                                 omtu = 0;
8228                         /* Here we do NOT factor the r_mtu */
8229                         if ((chk->send_size <= (int)(mtu - omtu)) ||
8230                             (chk->flags & CHUNK_FLAGS_FRAGMENT_OK)) {
8231                                 /*
8232                                  * We probably should glom the mbuf chain
8233                                  * from the chk->data for control but the
8234                                  * problem is it becomes yet one more level
8235                                  * of tracking to do if for some reason
8236                                  * output fails. Then I have got to
8237                                  * reconstruct the merged control chain.. el
8238                                  * yucko.. for now we take the easy way and
8239                                  * do the copy
8240                                  */
8241                                 /*
8242                                  * Add an AUTH chunk, if chunk requires it
8243                                  * save the offset into the chain for AUTH
8244                                  */
8245                                 if ((auth == NULL) &&
8246                                     (sctp_auth_is_required_chunk(chk->rec.chunk_id.id,
8247                                     stcb->asoc.peer_auth_chunks))) {
8248                                         outchain = sctp_add_auth_chunk(outchain,
8249                                             &endoutchain,
8250                                             &auth,
8251                                             &auth_offset,
8252                                             stcb,
8253                                             chk->rec.chunk_id.id);
8254                                         SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
8255                                 }
8256                                 outchain = sctp_copy_mbufchain(chk->data, outchain, &endoutchain,
8257                                     (int)chk->rec.chunk_id.can_take_data,
8258                                     chk->send_size, chk->copy_by_ref);
8259                                 if (outchain == NULL) {
8260                                         *reason_code = 8;
8261                                         SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
8262                                         return (ENOMEM);
8263                                 }
8264                                 SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
8265                                 /* update our MTU size */
8266                                 if (mtu > (chk->send_size + omtu))
8267                                         mtu -= (chk->send_size + omtu);
8268                                 else
8269                                         mtu = 0;
8270                                 to_out += (chk->send_size + omtu);
8271                                 /* Do clear IP_DF ? */
8272                                 if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
8273                                         no_fragmentflg = 0;
8274                                 }
8275                                 if (chk->rec.chunk_id.can_take_data)
8276                                         chk->data = NULL;
8277                                 /* Mark things to be removed, if needed */
8278                                 if ((chk->rec.chunk_id.id == SCTP_SELECTIVE_ACK) ||
8279                                     (chk->rec.chunk_id.id == SCTP_NR_SELECTIVE_ACK) ||  /* EY */
8280                                     (chk->rec.chunk_id.id == SCTP_HEARTBEAT_REQUEST) ||
8281                                     (chk->rec.chunk_id.id == SCTP_HEARTBEAT_ACK) ||
8282                                     (chk->rec.chunk_id.id == SCTP_SHUTDOWN) ||
8283                                     (chk->rec.chunk_id.id == SCTP_SHUTDOWN_ACK) ||
8284                                     (chk->rec.chunk_id.id == SCTP_OPERATION_ERROR) ||
8285                                     (chk->rec.chunk_id.id == SCTP_COOKIE_ACK) ||
8286                                     (chk->rec.chunk_id.id == SCTP_ECN_CWR) ||
8287                                     (chk->rec.chunk_id.id == SCTP_PACKET_DROPPED) ||
8288                                     (chk->rec.chunk_id.id == SCTP_ASCONF_ACK)) {
8289                                         if (chk->rec.chunk_id.id == SCTP_HEARTBEAT_REQUEST) {
8290                                                 hbflag = 1;
8291                                         }
8292                                         /* remove these chunks at the end */
8293                                         if ((chk->rec.chunk_id.id == SCTP_SELECTIVE_ACK) ||
8294                                             (chk->rec.chunk_id.id == SCTP_NR_SELECTIVE_ACK)) {
8295                                                 /* turn off the timer */
8296                                                 if (SCTP_OS_TIMER_PENDING(&stcb->asoc.dack_timer.timer)) {
8297                                                         sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
8298                                                             inp, stcb, net, SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_1);
8299                                                 }
8300                                         }
8301                                         ctl_cnt++;
8302                                 } else {
8303                                         /*
8304                                          * Other chunks, since they have
8305                                          * timers running (i.e. COOKIE) we
8306                                          * just "trust" that it gets sent or
8307                                          * retransmitted.
8308                                          */
8309                                         ctl_cnt++;
8310                                         if (chk->rec.chunk_id.id == SCTP_COOKIE_ECHO) {
8311                                                 cookie = 1;
8312                                                 no_out_cnt = 1;
8313                                         } else if (chk->rec.chunk_id.id == SCTP_ECN_ECHO) {
8314                                                 /*
8315                                                  * Increment ecne send count
8316                                                  * here this means we may be
8317                                                  * over-zealous in our
8318                                                  * counting if the send
8319                                                  * fails, but its the best
8320                                                  * place to do it (we used
8321                                                  * to do it in the queue of
8322                                                  * the chunk, but that did
8323                                                  * not tell how many times
8324                                                  * it was sent.
8325                                                  */
8326                                                 SCTP_STAT_INCR(sctps_sendecne);
8327                                         }
8328                                         chk->sent = SCTP_DATAGRAM_SENT;
8329                                         if (chk->whoTo == NULL) {
8330                                                 chk->whoTo = net;
8331                                                 atomic_add_int(&net->ref_count, 1);
8332                                         }
8333                                         chk->snd_count++;
8334                                 }
8335                                 if (mtu == 0) {
8336                                         /*
8337                                          * Ok we are out of room but we can
8338                                          * output without effecting the
8339                                          * flight size since this little guy
8340                                          * is a control only packet.
8341                                          */
8342                                         if (asconf) {
8343                                                 sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp, stcb, net);
8344                                                 /*
8345                                                  * do NOT clear the asconf
8346                                                  * flag as it is used to do
8347                                                  * appropriate source
8348                                                  * address selection.
8349                                                  */
8350                                         }
8351                                         if (cookie) {
8352                                                 sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, inp, stcb, net);
8353                                                 cookie = 0;
8354                                         }
8355                                         if ((error = sctp_lowlevel_chunk_output(inp, stcb, net,
8356                                             (struct sockaddr *)&net->ro._l_addr,
8357                                             outchain,
8358                                             auth_offset, auth,
8359                                             stcb->asoc.authinfo.active_keyid,
8360                                             no_fragmentflg, 0, asconf,
8361                                             inp->sctp_lport, stcb->rport,
8362                                             htonl(stcb->asoc.peer_vtag),
8363                                             net->port, NULL,
8364                                             0, 0,
8365                                             so_locked))) {
8366                                                 if (error == ENOBUFS) {
8367                                                         asoc->ifp_had_enobuf = 1;
8368                                                         SCTP_STAT_INCR(sctps_lowlevelerr);
8369                                                 }
8370                                                 if (from_where == 0) {
8371                                                         SCTP_STAT_INCR(sctps_lowlevelerrusr);
8372                                                 }
8373                                                 /* error, could not output */
8374                                                 if (hbflag) {
8375                                                         if (*now_filled == 0) {
8376                                                                 (void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
8377                                                                 *now_filled = 1;
8378                                                                 *now = net->last_sent_time;
8379                                                         } else {
8380                                                                 net->last_sent_time = *now;
8381                                                         }
8382                                                         hbflag = 0;
8383                                                 }
8384                                                 if (error == EHOSTUNREACH) {
8385                                                         /*
8386                                                          * Destination went
8387                                                          * unreachable
8388                                                          * during this send
8389                                                          */
8390                                                         sctp_move_chunks_from_net(stcb, net);
8391                                                 }
8392                                                 *reason_code = 7;
8393                                                 continue;
8394                                         } else
8395                                                 asoc->ifp_had_enobuf = 0;
8396                                         /* Only HB or ASCONF advances time */
8397                                         if (hbflag) {
8398                                                 if (*now_filled == 0) {
8399                                                         (void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
8400                                                         *now_filled = 1;
8401                                                         *now = net->last_sent_time;
8402                                                 } else {
8403                                                         net->last_sent_time = *now;
8404                                                 }
8405                                                 hbflag = 0;
8406                                         }
8407                                         /*
8408                                          * increase the number we sent, if a
8409                                          * cookie is sent we don't tell them
8410                                          * any was sent out.
8411                                          */
8412                                         outchain = endoutchain = NULL;
8413                                         auth = NULL;
8414                                         auth_offset = 0;
8415                                         if (!no_out_cnt)
8416                                                 *num_out += ctl_cnt;
8417                                         /* recalc a clean slate and setup */
8418                                         switch (net->ro._l_addr.sa.sa_family) {
8419 #ifdef INET
8420                                         case AF_INET:
8421                                                 mtu = net->mtu - SCTP_MIN_V4_OVERHEAD;
8422                                                 break;
8423 #endif
8424 #ifdef INET6
8425                                         case AF_INET6:
8426                                                 mtu = net->mtu - SCTP_MIN_OVERHEAD;
8427                                                 break;
8428 #endif
8429                                         default:
8430                                                 /* TSNH */
8431                                                 mtu = net->mtu;
8432                                                 break;
8433                                         }
8434                                         to_out = 0;
8435                                         no_fragmentflg = 1;
8436                                 }
8437                         }
8438                 }
8439                 /* JRI: if dest is in PF state, do not send data to it */
8440                 if ((asoc->sctp_cmt_on_off > 0) &&
8441                     (net != stcb->asoc.alternate) &&
8442                     (net->dest_state & SCTP_ADDR_PF)) {
8443                         goto no_data_fill;
8444                 }
8445                 if (net->flight_size >= net->cwnd) {
8446                         goto no_data_fill;
8447                 }
8448                 if ((asoc->sctp_cmt_on_off > 0) &&
8449                     (SCTP_BASE_SYSCTL(sctp_buffer_splitting) & SCTP_RECV_BUFFER_SPLITTING) &&
8450                     (net->flight_size > max_rwnd_per_dest)) {
8451                         goto no_data_fill;
8452                 }
8453                 /*
8454                  * We need a specific accounting for the usage of the send
8455                  * buffer. We also need to check the number of messages per
8456                  * net. For now, this is better than nothing and it disabled
8457                  * by default...
8458                  */
8459                 if ((asoc->sctp_cmt_on_off > 0) &&
8460                     (SCTP_BASE_SYSCTL(sctp_buffer_splitting) & SCTP_SEND_BUFFER_SPLITTING) &&
8461                     (max_send_per_dest > 0) &&
8462                     (net->flight_size > max_send_per_dest)) {
8463                         goto no_data_fill;
8464                 }
8465                 /*********************/
8466                 /* Data transmission */
8467                 /*********************/
8468                 /*
8469                  * if AUTH for DATA is required and no AUTH has been added
8470                  * yet, account for this in the mtu now... if no data can be
8471                  * bundled, this adjustment won't matter anyways since the
8472                  * packet will be going out...
8473                  */
8474                 data_auth_reqd = sctp_auth_is_required_chunk(SCTP_DATA,
8475                     stcb->asoc.peer_auth_chunks);
8476                 if (data_auth_reqd && (auth == NULL)) {
8477                         mtu -= sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
8478                 }
8479                 /* now lets add any data within the MTU constraints */
8480                 switch (((struct sockaddr *)&net->ro._l_addr)->sa_family) {
8481 #ifdef INET
8482                 case AF_INET:
8483                         if (net->mtu > (sizeof(struct ip) + sizeof(struct sctphdr)))
8484                                 omtu = net->mtu - (sizeof(struct ip) + sizeof(struct sctphdr));
8485                         else
8486                                 omtu = 0;
8487                         break;
8488 #endif
8489 #ifdef INET6
8490                 case AF_INET6:
8491                         if (net->mtu > (sizeof(struct ip6_hdr) + sizeof(struct sctphdr)))
8492                                 omtu = net->mtu - (sizeof(struct ip6_hdr) + sizeof(struct sctphdr));
8493                         else
8494                                 omtu = 0;
8495                         break;
8496 #endif
8497                 default:
8498                         /* TSNH */
8499                         omtu = 0;
8500                         break;
8501                 }
8502                 if ((((asoc->state & SCTP_STATE_OPEN) == SCTP_STATE_OPEN) &&
8503                     (skip_data_for_this_net == 0)) ||
8504                     (cookie)) {
8505                         TAILQ_FOREACH_SAFE(chk, &asoc->send_queue, sctp_next, nchk) {
8506                                 if (no_data_chunks) {
8507                                         /* let only control go out */
8508                                         *reason_code = 1;
8509                                         break;
8510                                 }
8511                                 if (net->flight_size >= net->cwnd) {
8512                                         /* skip this net, no room for data */
8513                                         *reason_code = 2;
8514                                         break;
8515                                 }
8516                                 if ((chk->whoTo != NULL) &&
8517                                     (chk->whoTo != net)) {
8518                                         /* Don't send the chunk on this net */
8519                                         continue;
8520                                 }
8521                                 if (asoc->sctp_cmt_on_off == 0) {
8522                                         if ((asoc->alternate) &&
8523                                             (asoc->alternate != net) &&
8524                                             (chk->whoTo == NULL)) {
8525                                                 continue;
8526                                         } else if ((net != asoc->primary_destination) &&
8527                                                     (asoc->alternate == NULL) &&
8528                                             (chk->whoTo == NULL)) {
8529                                                 continue;
8530                                         }
8531                                 }
8532                                 if ((chk->send_size > omtu) && ((chk->flags & CHUNK_FLAGS_FRAGMENT_OK) == 0)) {
8533                                         /*-
8534                                          * strange, we have a chunk that is
8535                                          * to big for its destination and
8536                                          * yet no fragment ok flag.
8537                                          * Something went wrong when the
8538                                          * PMTU changed...we did not mark
8539                                          * this chunk for some reason?? I
8540                                          * will fix it here by letting IP
8541                                          * fragment it for now and printing
8542                                          * a warning. This really should not
8543                                          * happen ...
8544                                          */
8545                                         SCTP_PRINTF("Warning chunk of %d bytes > mtu:%d and yet PMTU disc missed\n",
8546                                             chk->send_size, mtu);
8547                                         chk->flags |= CHUNK_FLAGS_FRAGMENT_OK;
8548                                 }
8549                                 if (SCTP_BASE_SYSCTL(sctp_enable_sack_immediately) &&
8550                                     ((asoc->state & SCTP_STATE_SHUTDOWN_PENDING) == SCTP_STATE_SHUTDOWN_PENDING)) {
8551                                         struct sctp_data_chunk *dchkh;
8552
8553                                         dchkh = mtod(chk->data, struct sctp_data_chunk *);
8554                                         dchkh->ch.chunk_flags |= SCTP_DATA_SACK_IMMEDIATELY;
8555                                 }
8556                                 if (((chk->send_size <= mtu) && (chk->send_size <= r_mtu)) ||
8557                                     ((chk->flags & CHUNK_FLAGS_FRAGMENT_OK) && (chk->send_size <= asoc->peers_rwnd))) {
8558                                         /* ok we will add this one */
8559
8560                                         /*
8561                                          * Add an AUTH chunk, if chunk
8562                                          * requires it, save the offset into
8563                                          * the chain for AUTH
8564                                          */
8565                                         if (data_auth_reqd) {
8566                                                 if (auth == NULL) {
8567                                                         outchain = sctp_add_auth_chunk(outchain,
8568                                                             &endoutchain,
8569                                                             &auth,
8570                                                             &auth_offset,
8571                                                             stcb,
8572                                                             SCTP_DATA);
8573                                                         auth_keyid = chk->auth_keyid;
8574                                                         override_ok = 0;
8575                                                         SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
8576                                                 } else if (override_ok) {
8577                                                         /*
8578                                                          * use this data's
8579                                                          * keyid
8580                                                          */
8581                                                         auth_keyid = chk->auth_keyid;
8582                                                         override_ok = 0;
8583                                                 } else if (auth_keyid != chk->auth_keyid) {
8584                                                         /*
8585                                                          * different keyid,
8586                                                          * so done bundling
8587                                                          */
8588                                                         break;
8589                                                 }
8590                                         }
8591                                         outchain = sctp_copy_mbufchain(chk->data, outchain, &endoutchain, 0,
8592                                             chk->send_size, chk->copy_by_ref);
8593                                         if (outchain == NULL) {
8594                                                 SCTPDBG(SCTP_DEBUG_OUTPUT3, "No memory?\n");
8595                                                 if (!SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer)) {
8596                                                         sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
8597                                                 }
8598                                                 *reason_code = 3;
8599                                                 SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
8600                                                 return (ENOMEM);
8601                                         }
8602                                         /* upate our MTU size */
8603                                         /* Do clear IP_DF ? */
8604                                         if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
8605                                                 no_fragmentflg = 0;
8606                                         }
8607                                         /* unsigned subtraction of mtu */
8608                                         if (mtu > chk->send_size)
8609                                                 mtu -= chk->send_size;
8610                                         else
8611                                                 mtu = 0;
8612                                         /* unsigned subtraction of r_mtu */
8613                                         if (r_mtu > chk->send_size)
8614                                                 r_mtu -= chk->send_size;
8615                                         else
8616                                                 r_mtu = 0;
8617
8618                                         to_out += chk->send_size;
8619                                         if ((to_out > mx_mtu) && no_fragmentflg) {
8620 #ifdef INVARIANTS
8621                                                 panic("Exceeding mtu of %d out size is %d", mx_mtu, to_out);
8622 #else
8623                                                 SCTP_PRINTF("Exceeding mtu of %d out size is %d\n",
8624                                                     mx_mtu, to_out);
8625 #endif
8626                                         }
8627                                         chk->window_probe = 0;
8628                                         data_list[bundle_at++] = chk;
8629                                         if (bundle_at >= SCTP_MAX_DATA_BUNDLING) {
8630                                                 break;
8631                                         }
8632                                         if (chk->sent == SCTP_DATAGRAM_UNSENT) {
8633                                                 if ((chk->rec.data.rcv_flags & SCTP_DATA_UNORDERED) == 0) {
8634                                                         SCTP_STAT_INCR_COUNTER64(sctps_outorderchunks);
8635                                                 } else {
8636                                                         SCTP_STAT_INCR_COUNTER64(sctps_outunorderchunks);
8637                                                 }
8638                                                 if (((chk->rec.data.rcv_flags & SCTP_DATA_LAST_FRAG) == SCTP_DATA_LAST_FRAG) &&
8639                                                     ((chk->rec.data.rcv_flags & SCTP_DATA_FIRST_FRAG) == 0))
8640                                                         /*
8641                                                          * Count number of
8642                                                          * user msg's that
8643                                                          * were fragmented
8644                                                          * we do this by
8645                                                          * counting when we
8646                                                          * see a LAST
8647                                                          * fragment only.
8648                                                          */
8649                                                         SCTP_STAT_INCR_COUNTER64(sctps_fragusrmsgs);
8650                                         }
8651                                         if ((mtu == 0) || (r_mtu == 0) || (one_chunk)) {
8652                                                 if ((one_chunk) && (stcb->asoc.total_flight == 0)) {
8653                                                         data_list[0]->window_probe = 1;
8654                                                         net->window_probe = 1;
8655                                                 }
8656                                                 break;
8657                                         }
8658                                 } else {
8659                                         /*
8660                                          * Must be sent in order of the
8661                                          * TSN's (on a network)
8662                                          */
8663                                         break;
8664                                 }
8665                         }       /* for (chunk gather loop for this net) */
8666                 }               /* if asoc.state OPEN */
8667 no_data_fill:
8668                 /* Is there something to send for this destination? */
8669                 if (outchain) {
8670                         /* We may need to start a control timer or two */
8671                         if (asconf) {
8672                                 sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp,
8673                                     stcb, net);
8674                                 /*
8675                                  * do NOT clear the asconf flag as it is
8676                                  * used to do appropriate source address
8677                                  * selection.
8678                                  */
8679                         }
8680                         if (cookie) {
8681                                 sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, inp, stcb, net);
8682                                 cookie = 0;
8683                         }
8684                         /* must start a send timer if data is being sent */
8685                         if (bundle_at && (!SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer))) {
8686                                 /*
8687                                  * no timer running on this destination
8688                                  * restart it.
8689                                  */
8690                                 sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
8691                         }
8692                         /* Now send it, if there is anything to send :> */
8693                         if ((error = sctp_lowlevel_chunk_output(inp,
8694                             stcb,
8695                             net,
8696                             (struct sockaddr *)&net->ro._l_addr,
8697                             outchain,
8698                             auth_offset,
8699                             auth,
8700                             auth_keyid,
8701                             no_fragmentflg,
8702                             bundle_at,
8703                             asconf,
8704                             inp->sctp_lport, stcb->rport,
8705                             htonl(stcb->asoc.peer_vtag),
8706                             net->port, NULL,
8707                             0, 0,
8708                             so_locked))) {
8709                                 /* error, we could not output */
8710                                 if (error == ENOBUFS) {
8711                                         SCTP_STAT_INCR(sctps_lowlevelerr);
8712                                         asoc->ifp_had_enobuf = 1;
8713                                 }
8714                                 if (from_where == 0) {
8715                                         SCTP_STAT_INCR(sctps_lowlevelerrusr);
8716                                 }
8717                                 SCTPDBG(SCTP_DEBUG_OUTPUT3, "Gak send error %d\n", error);
8718                                 if (hbflag) {
8719                                         if (*now_filled == 0) {
8720                                                 (void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
8721                                                 *now_filled = 1;
8722                                                 *now = net->last_sent_time;
8723                                         } else {
8724                                                 net->last_sent_time = *now;
8725                                         }
8726                                         hbflag = 0;
8727                                 }
8728                                 if (error == EHOSTUNREACH) {
8729                                         /*
8730                                          * Destination went unreachable
8731                                          * during this send
8732                                          */
8733                                         sctp_move_chunks_from_net(stcb, net);
8734                                 }
8735                                 *reason_code = 6;
8736                                 /*-
8737                                  * I add this line to be paranoid. As far as
8738                                  * I can tell the continue, takes us back to
8739                                  * the top of the for, but just to make sure
8740                                  * I will reset these again here.
8741                                  */
8742                                 ctl_cnt = bundle_at = 0;
8743                                 continue;       /* This takes us back to the
8744                                                  * for() for the nets. */
8745                         } else {
8746                                 asoc->ifp_had_enobuf = 0;
8747                         }
8748                         endoutchain = NULL;
8749                         auth = NULL;
8750                         auth_offset = 0;
8751                         if (bundle_at || hbflag) {
8752                                 /* For data/asconf and hb set time */
8753                                 if (*now_filled == 0) {
8754                                         (void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
8755                                         *now_filled = 1;
8756                                         *now = net->last_sent_time;
8757                                 } else {
8758                                         net->last_sent_time = *now;
8759                                 }
8760                         }
8761                         if (!no_out_cnt) {
8762                                 *num_out += (ctl_cnt + bundle_at);
8763                         }
8764                         if (bundle_at) {
8765                                 /* setup for a RTO measurement */
8766                                 tsns_sent = data_list[0]->rec.data.TSN_seq;
8767                                 /* fill time if not already filled */
8768                                 if (*now_filled == 0) {
8769                                         (void)SCTP_GETTIME_TIMEVAL(&asoc->time_last_sent);
8770                                         *now_filled = 1;
8771                                         *now = asoc->time_last_sent;
8772                                 } else {
8773                                         asoc->time_last_sent = *now;
8774                                 }
8775                                 if (net->rto_needed) {
8776                                         data_list[0]->do_rtt = 1;
8777                                         net->rto_needed = 0;
8778                                 }
8779                                 SCTP_STAT_INCR_BY(sctps_senddata, bundle_at);
8780                                 sctp_clean_up_datalist(stcb, asoc, data_list, bundle_at, net);
8781                         }
8782                         if (one_chunk) {
8783                                 break;
8784                         }
8785                 }
8786                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
8787                         sctp_log_cwnd(stcb, net, tsns_sent, SCTP_CWND_LOG_FROM_SEND);
8788                 }
8789         }
8790         if (old_start_at == NULL) {
8791                 old_start_at = start_at;
8792                 start_at = TAILQ_FIRST(&asoc->nets);
8793                 if (old_start_at)
8794                         goto again_one_more_time;
8795         }
8796         /*
8797          * At the end there should be no NON timed chunks hanging on this
8798          * queue.
8799          */
8800         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
8801                 sctp_log_cwnd(stcb, net, *num_out, SCTP_CWND_LOG_FROM_SEND);
8802         }
8803         if ((*num_out == 0) && (*reason_code == 0)) {
8804                 *reason_code = 4;
8805         } else {
8806                 *reason_code = 5;
8807         }
8808         sctp_clean_up_ctl(stcb, asoc, so_locked);
8809         return (0);
8810 }
8811
8812 void
8813 sctp_queue_op_err(struct sctp_tcb *stcb, struct mbuf *op_err)
8814 {
8815         /*-
8816          * Prepend a OPERATIONAL_ERROR chunk header and put on the end of
8817          * the control chunk queue.
8818          */
8819         struct sctp_chunkhdr *hdr;
8820         struct sctp_tmit_chunk *chk;
8821         struct mbuf *mat;
8822
8823         SCTP_TCB_LOCK_ASSERT(stcb);
8824         sctp_alloc_a_chunk(stcb, chk);
8825         if (chk == NULL) {
8826                 /* no memory */
8827                 sctp_m_freem(op_err);
8828                 return;
8829         }
8830         chk->copy_by_ref = 0;
8831         SCTP_BUF_PREPEND(op_err, sizeof(struct sctp_chunkhdr), M_DONTWAIT);
8832         if (op_err == NULL) {
8833                 sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
8834                 return;
8835         }
8836         chk->send_size = 0;
8837         mat = op_err;
8838         while (mat != NULL) {
8839                 chk->send_size += SCTP_BUF_LEN(mat);
8840                 mat = SCTP_BUF_NEXT(mat);
8841         }
8842         chk->rec.chunk_id.id = SCTP_OPERATION_ERROR;
8843         chk->rec.chunk_id.can_take_data = 1;
8844         chk->sent = SCTP_DATAGRAM_UNSENT;
8845         chk->snd_count = 0;
8846         chk->flags = 0;
8847         chk->asoc = &stcb->asoc;
8848         chk->data = op_err;
8849         chk->whoTo = NULL;
8850         hdr = mtod(op_err, struct sctp_chunkhdr *);
8851         hdr->chunk_type = SCTP_OPERATION_ERROR;
8852         hdr->chunk_flags = 0;
8853         hdr->chunk_length = htons(chk->send_size);
8854         TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue,
8855             chk,
8856             sctp_next);
8857         chk->asoc->ctrl_queue_cnt++;
8858 }
8859
8860 int
8861 sctp_send_cookie_echo(struct mbuf *m,
8862     int offset,
8863     struct sctp_tcb *stcb,
8864     struct sctp_nets *net)
8865 {
8866         /*-
8867          * pull out the cookie and put it at the front of the control chunk
8868          * queue.
8869          */
8870         int at;
8871         struct mbuf *cookie;
8872         struct sctp_paramhdr parm, *phdr;
8873         struct sctp_chunkhdr *hdr;
8874         struct sctp_tmit_chunk *chk;
8875         uint16_t ptype, plen;
8876
8877         /* First find the cookie in the param area */
8878         cookie = NULL;
8879         at = offset + sizeof(struct sctp_init_chunk);
8880
8881         SCTP_TCB_LOCK_ASSERT(stcb);
8882         do {
8883                 phdr = sctp_get_next_param(m, at, &parm, sizeof(parm));
8884                 if (phdr == NULL) {
8885                         return (-3);
8886                 }
8887                 ptype = ntohs(phdr->param_type);
8888                 plen = ntohs(phdr->param_length);
8889                 if (ptype == SCTP_STATE_COOKIE) {
8890                         int pad;
8891
8892                         /* found the cookie */
8893                         if ((pad = (plen % 4))) {
8894                                 plen += 4 - pad;
8895                         }
8896                         cookie = SCTP_M_COPYM(m, at, plen, M_DONTWAIT);
8897                         if (cookie == NULL) {
8898                                 /* No memory */
8899                                 return (-2);
8900                         }
8901 #ifdef SCTP_MBUF_LOGGING
8902                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
8903                                 struct mbuf *mat;
8904
8905                                 for (mat = cookie; mat; mat = SCTP_BUF_NEXT(mat)) {
8906                                         if (SCTP_BUF_IS_EXTENDED(mat)) {
8907                                                 sctp_log_mb(mat, SCTP_MBUF_ICOPY);
8908                                         }
8909                                 }
8910                         }
8911 #endif
8912                         break;
8913                 }
8914                 at += SCTP_SIZE32(plen);
8915         } while (phdr);
8916         if (cookie == NULL) {
8917                 /* Did not find the cookie */
8918                 return (-3);
8919         }
8920         /* ok, we got the cookie lets change it into a cookie echo chunk */
8921
8922         /* first the change from param to cookie */
8923         hdr = mtod(cookie, struct sctp_chunkhdr *);
8924         hdr->chunk_type = SCTP_COOKIE_ECHO;
8925         hdr->chunk_flags = 0;
8926         /* get the chunk stuff now and place it in the FRONT of the queue */
8927         sctp_alloc_a_chunk(stcb, chk);
8928         if (chk == NULL) {
8929                 /* no memory */
8930                 sctp_m_freem(cookie);
8931                 return (-5);
8932         }
8933         chk->copy_by_ref = 0;
8934         chk->send_size = plen;
8935         chk->rec.chunk_id.id = SCTP_COOKIE_ECHO;
8936         chk->rec.chunk_id.can_take_data = 0;
8937         chk->sent = SCTP_DATAGRAM_UNSENT;
8938         chk->snd_count = 0;
8939         chk->flags = CHUNK_FLAGS_FRAGMENT_OK;
8940         chk->asoc = &stcb->asoc;
8941         chk->data = cookie;
8942         chk->whoTo = net;
8943         atomic_add_int(&chk->whoTo->ref_count, 1);
8944         TAILQ_INSERT_HEAD(&chk->asoc->control_send_queue, chk, sctp_next);
8945         chk->asoc->ctrl_queue_cnt++;
8946         return (0);
8947 }
8948
8949 void
8950 sctp_send_heartbeat_ack(struct sctp_tcb *stcb,
8951     struct mbuf *m,
8952     int offset,
8953     int chk_length,
8954     struct sctp_nets *net)
8955 {
8956         /*
8957          * take a HB request and make it into a HB ack and send it.
8958          */
8959         struct mbuf *outchain;
8960         struct sctp_chunkhdr *chdr;
8961         struct sctp_tmit_chunk *chk;
8962
8963
8964         if (net == NULL)
8965                 /* must have a net pointer */
8966                 return;
8967
8968         outchain = SCTP_M_COPYM(m, offset, chk_length, M_DONTWAIT);
8969         if (outchain == NULL) {
8970                 /* gak out of memory */
8971                 return;
8972         }
8973 #ifdef SCTP_MBUF_LOGGING
8974         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
8975                 struct mbuf *mat;
8976
8977                 for (mat = outchain; mat; mat = SCTP_BUF_NEXT(mat)) {
8978                         if (SCTP_BUF_IS_EXTENDED(mat)) {
8979                                 sctp_log_mb(mat, SCTP_MBUF_ICOPY);
8980                         }
8981                 }
8982         }
8983 #endif
8984         chdr = mtod(outchain, struct sctp_chunkhdr *);
8985         chdr->chunk_type = SCTP_HEARTBEAT_ACK;
8986         chdr->chunk_flags = 0;
8987         if (chk_length % 4) {
8988                 /* need pad */
8989                 uint32_t cpthis = 0;
8990                 int padlen;
8991
8992                 padlen = 4 - (chk_length % 4);
8993                 m_copyback(outchain, chk_length, padlen, (caddr_t)&cpthis);
8994         }
8995         sctp_alloc_a_chunk(stcb, chk);
8996         if (chk == NULL) {
8997                 /* no memory */
8998                 sctp_m_freem(outchain);
8999                 return;
9000         }
9001         chk->copy_by_ref = 0;
9002         chk->send_size = chk_length;
9003         chk->rec.chunk_id.id = SCTP_HEARTBEAT_ACK;
9004         chk->rec.chunk_id.can_take_data = 1;
9005         chk->sent = SCTP_DATAGRAM_UNSENT;
9006         chk->snd_count = 0;
9007         chk->flags = 0;
9008         chk->asoc = &stcb->asoc;
9009         chk->data = outchain;
9010         chk->whoTo = net;
9011         atomic_add_int(&chk->whoTo->ref_count, 1);
9012         TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
9013         chk->asoc->ctrl_queue_cnt++;
9014 }
9015
9016 void
9017 sctp_send_cookie_ack(struct sctp_tcb *stcb)
9018 {
9019         /* formulate and queue a cookie-ack back to sender */
9020         struct mbuf *cookie_ack;
9021         struct sctp_chunkhdr *hdr;
9022         struct sctp_tmit_chunk *chk;
9023
9024         cookie_ack = NULL;
9025         SCTP_TCB_LOCK_ASSERT(stcb);
9026
9027         cookie_ack = sctp_get_mbuf_for_msg(sizeof(struct sctp_chunkhdr), 0, M_DONTWAIT, 1, MT_HEADER);
9028         if (cookie_ack == NULL) {
9029                 /* no mbuf's */
9030                 return;
9031         }
9032         SCTP_BUF_RESV_UF(cookie_ack, SCTP_MIN_OVERHEAD);
9033         sctp_alloc_a_chunk(stcb, chk);
9034         if (chk == NULL) {
9035                 /* no memory */
9036                 sctp_m_freem(cookie_ack);
9037                 return;
9038         }
9039         chk->copy_by_ref = 0;
9040         chk->send_size = sizeof(struct sctp_chunkhdr);
9041         chk->rec.chunk_id.id = SCTP_COOKIE_ACK;
9042         chk->rec.chunk_id.can_take_data = 1;
9043         chk->sent = SCTP_DATAGRAM_UNSENT;
9044         chk->snd_count = 0;
9045         chk->flags = 0;
9046         chk->asoc = &stcb->asoc;
9047         chk->data = cookie_ack;
9048         if (chk->asoc->last_control_chunk_from != NULL) {
9049                 chk->whoTo = chk->asoc->last_control_chunk_from;
9050                 atomic_add_int(&chk->whoTo->ref_count, 1);
9051         } else {
9052                 chk->whoTo = NULL;
9053         }
9054         hdr = mtod(cookie_ack, struct sctp_chunkhdr *);
9055         hdr->chunk_type = SCTP_COOKIE_ACK;
9056         hdr->chunk_flags = 0;
9057         hdr->chunk_length = htons(chk->send_size);
9058         SCTP_BUF_LEN(cookie_ack) = chk->send_size;
9059         TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
9060         chk->asoc->ctrl_queue_cnt++;
9061         return;
9062 }
9063
9064
9065 void
9066 sctp_send_shutdown_ack(struct sctp_tcb *stcb, struct sctp_nets *net)
9067 {
9068         /* formulate and queue a SHUTDOWN-ACK back to the sender */
9069         struct mbuf *m_shutdown_ack;
9070         struct sctp_shutdown_ack_chunk *ack_cp;
9071         struct sctp_tmit_chunk *chk;
9072
9073         m_shutdown_ack = sctp_get_mbuf_for_msg(sizeof(struct sctp_shutdown_ack_chunk), 0, M_DONTWAIT, 1, MT_HEADER);
9074         if (m_shutdown_ack == NULL) {
9075                 /* no mbuf's */
9076                 return;
9077         }
9078         SCTP_BUF_RESV_UF(m_shutdown_ack, SCTP_MIN_OVERHEAD);
9079         sctp_alloc_a_chunk(stcb, chk);
9080         if (chk == NULL) {
9081                 /* no memory */
9082                 sctp_m_freem(m_shutdown_ack);
9083                 return;
9084         }
9085         chk->copy_by_ref = 0;
9086         chk->send_size = sizeof(struct sctp_chunkhdr);
9087         chk->rec.chunk_id.id = SCTP_SHUTDOWN_ACK;
9088         chk->rec.chunk_id.can_take_data = 1;
9089         chk->sent = SCTP_DATAGRAM_UNSENT;
9090         chk->snd_count = 0;
9091         chk->flags = 0;
9092         chk->asoc = &stcb->asoc;
9093         chk->data = m_shutdown_ack;
9094         chk->whoTo = net;
9095         if (chk->whoTo) {
9096                 atomic_add_int(&chk->whoTo->ref_count, 1);
9097         }
9098         ack_cp = mtod(m_shutdown_ack, struct sctp_shutdown_ack_chunk *);
9099         ack_cp->ch.chunk_type = SCTP_SHUTDOWN_ACK;
9100         ack_cp->ch.chunk_flags = 0;
9101         ack_cp->ch.chunk_length = htons(chk->send_size);
9102         SCTP_BUF_LEN(m_shutdown_ack) = chk->send_size;
9103         TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
9104         chk->asoc->ctrl_queue_cnt++;
9105         return;
9106 }
9107
9108 void
9109 sctp_send_shutdown(struct sctp_tcb *stcb, struct sctp_nets *net)
9110 {
9111         /* formulate and queue a SHUTDOWN to the sender */
9112         struct mbuf *m_shutdown;
9113         struct sctp_shutdown_chunk *shutdown_cp;
9114         struct sctp_tmit_chunk *chk;
9115
9116         m_shutdown = sctp_get_mbuf_for_msg(sizeof(struct sctp_shutdown_chunk), 0, M_DONTWAIT, 1, MT_HEADER);
9117         if (m_shutdown == NULL) {
9118                 /* no mbuf's */
9119                 return;
9120         }
9121         SCTP_BUF_RESV_UF(m_shutdown, SCTP_MIN_OVERHEAD);
9122         sctp_alloc_a_chunk(stcb, chk);
9123         if (chk == NULL) {
9124                 /* no memory */
9125                 sctp_m_freem(m_shutdown);
9126                 return;
9127         }
9128         chk->copy_by_ref = 0;
9129         chk->send_size = sizeof(struct sctp_shutdown_chunk);
9130         chk->rec.chunk_id.id = SCTP_SHUTDOWN;
9131         chk->rec.chunk_id.can_take_data = 1;
9132         chk->sent = SCTP_DATAGRAM_UNSENT;
9133         chk->snd_count = 0;
9134         chk->flags = 0;
9135         chk->asoc = &stcb->asoc;
9136         chk->data = m_shutdown;
9137         chk->whoTo = net;
9138         if (chk->whoTo) {
9139                 atomic_add_int(&chk->whoTo->ref_count, 1);
9140         }
9141         shutdown_cp = mtod(m_shutdown, struct sctp_shutdown_chunk *);
9142         shutdown_cp->ch.chunk_type = SCTP_SHUTDOWN;
9143         shutdown_cp->ch.chunk_flags = 0;
9144         shutdown_cp->ch.chunk_length = htons(chk->send_size);
9145         shutdown_cp->cumulative_tsn_ack = htonl(stcb->asoc.cumulative_tsn);
9146         SCTP_BUF_LEN(m_shutdown) = chk->send_size;
9147         TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
9148         chk->asoc->ctrl_queue_cnt++;
9149         return;
9150 }
9151
9152 void
9153 sctp_send_asconf(struct sctp_tcb *stcb, struct sctp_nets *net, int addr_locked)
9154 {
9155         /*
9156          * formulate and queue an ASCONF to the peer. ASCONF parameters
9157          * should be queued on the assoc queue.
9158          */
9159         struct sctp_tmit_chunk *chk;
9160         struct mbuf *m_asconf;
9161         int len;
9162
9163         SCTP_TCB_LOCK_ASSERT(stcb);
9164
9165         if ((!TAILQ_EMPTY(&stcb->asoc.asconf_send_queue)) &&
9166             (!sctp_is_feature_on(stcb->sctp_ep, SCTP_PCB_FLAGS_MULTIPLE_ASCONFS))) {
9167                 /* can't send a new one if there is one in flight already */
9168                 return;
9169         }
9170         /* compose an ASCONF chunk, maximum length is PMTU */
9171         m_asconf = sctp_compose_asconf(stcb, &len, addr_locked);
9172         if (m_asconf == NULL) {
9173                 return;
9174         }
9175         sctp_alloc_a_chunk(stcb, chk);
9176         if (chk == NULL) {
9177                 /* no memory */
9178                 sctp_m_freem(m_asconf);
9179                 return;
9180         }
9181         chk->copy_by_ref = 0;
9182         chk->data = m_asconf;
9183         chk->send_size = len;
9184         chk->rec.chunk_id.id = SCTP_ASCONF;
9185         chk->rec.chunk_id.can_take_data = 0;
9186         chk->sent = SCTP_DATAGRAM_UNSENT;
9187         chk->snd_count = 0;
9188         chk->flags = CHUNK_FLAGS_FRAGMENT_OK;
9189         chk->asoc = &stcb->asoc;
9190         chk->whoTo = net;
9191         if (chk->whoTo) {
9192                 atomic_add_int(&chk->whoTo->ref_count, 1);
9193         }
9194         TAILQ_INSERT_TAIL(&chk->asoc->asconf_send_queue, chk, sctp_next);
9195         chk->asoc->ctrl_queue_cnt++;
9196         return;
9197 }
9198
9199 void
9200 sctp_send_asconf_ack(struct sctp_tcb *stcb)
9201 {
9202         /*
9203          * formulate and queue a asconf-ack back to sender. the asconf-ack
9204          * must be stored in the tcb.
9205          */
9206         struct sctp_tmit_chunk *chk;
9207         struct sctp_asconf_ack *ack, *latest_ack;
9208         struct mbuf *m_ack;
9209         struct sctp_nets *net = NULL;
9210
9211         SCTP_TCB_LOCK_ASSERT(stcb);
9212         /* Get the latest ASCONF-ACK */
9213         latest_ack = TAILQ_LAST(&stcb->asoc.asconf_ack_sent, sctp_asconf_ackhead);
9214         if (latest_ack == NULL) {
9215                 return;
9216         }
9217         if (latest_ack->last_sent_to != NULL &&
9218             latest_ack->last_sent_to == stcb->asoc.last_control_chunk_from) {
9219                 /* we're doing a retransmission */
9220                 net = sctp_find_alternate_net(stcb, stcb->asoc.last_control_chunk_from, 0);
9221                 if (net == NULL) {
9222                         /* no alternate */
9223                         if (stcb->asoc.last_control_chunk_from == NULL) {
9224                                 if (stcb->asoc.alternate) {
9225                                         net = stcb->asoc.alternate;
9226                                 } else {
9227                                         net = stcb->asoc.primary_destination;
9228                                 }
9229                         } else {
9230                                 net = stcb->asoc.last_control_chunk_from;
9231                         }
9232                 }
9233         } else {
9234                 /* normal case */
9235                 if (stcb->asoc.last_control_chunk_from == NULL) {
9236                         if (stcb->asoc.alternate) {
9237                                 net = stcb->asoc.alternate;
9238                         } else {
9239                                 net = stcb->asoc.primary_destination;
9240                         }
9241                 } else {
9242                         net = stcb->asoc.last_control_chunk_from;
9243                 }
9244         }
9245         latest_ack->last_sent_to = net;
9246
9247         TAILQ_FOREACH(ack, &stcb->asoc.asconf_ack_sent, next) {
9248                 if (ack->data == NULL) {
9249                         continue;
9250                 }
9251                 /* copy the asconf_ack */
9252                 m_ack = SCTP_M_COPYM(ack->data, 0, M_COPYALL, M_DONTWAIT);
9253                 if (m_ack == NULL) {
9254                         /* couldn't copy it */
9255                         return;
9256                 }
9257 #ifdef SCTP_MBUF_LOGGING
9258                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
9259                         struct mbuf *mat;
9260
9261                         for (mat = m_ack; mat; mat = SCTP_BUF_NEXT(mat)) {
9262                                 if (SCTP_BUF_IS_EXTENDED(mat)) {
9263                                         sctp_log_mb(mat, SCTP_MBUF_ICOPY);
9264                                 }
9265                         }
9266                 }
9267 #endif
9268
9269                 sctp_alloc_a_chunk(stcb, chk);
9270                 if (chk == NULL) {
9271                         /* no memory */
9272                         if (m_ack)
9273                                 sctp_m_freem(m_ack);
9274                         return;
9275                 }
9276                 chk->copy_by_ref = 0;
9277
9278                 chk->whoTo = net;
9279                 if (chk->whoTo) {
9280                         atomic_add_int(&chk->whoTo->ref_count, 1);
9281                 }
9282                 chk->data = m_ack;
9283                 chk->send_size = 0;
9284                 /* Get size */
9285                 chk->send_size = ack->len;
9286                 chk->rec.chunk_id.id = SCTP_ASCONF_ACK;
9287                 chk->rec.chunk_id.can_take_data = 1;
9288                 chk->sent = SCTP_DATAGRAM_UNSENT;
9289                 chk->snd_count = 0;
9290                 chk->flags |= CHUNK_FLAGS_FRAGMENT_OK;  /* XXX */
9291                 chk->asoc = &stcb->asoc;
9292
9293                 TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
9294                 chk->asoc->ctrl_queue_cnt++;
9295         }
9296         return;
9297 }
9298
9299
9300 static int
9301 sctp_chunk_retransmission(struct sctp_inpcb *inp,
9302     struct sctp_tcb *stcb,
9303     struct sctp_association *asoc,
9304     int *cnt_out, struct timeval *now, int *now_filled, int *fr_done, int so_locked
9305 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
9306     SCTP_UNUSED
9307 #endif
9308 )
9309 {
9310         /*-
9311          * send out one MTU of retransmission. If fast_retransmit is
9312          * happening we ignore the cwnd. Otherwise we obey the cwnd and
9313          * rwnd. For a Cookie or Asconf in the control chunk queue we
9314          * retransmit them by themselves.
9315          *
9316          * For data chunks we will pick out the lowest TSN's in the sent_queue
9317          * marked for resend and bundle them all together (up to a MTU of
9318          * destination). The address to send to should have been
9319          * selected/changed where the retransmission was marked (i.e. in FR
9320          * or t3-timeout routines).
9321          */
9322         struct sctp_tmit_chunk *data_list[SCTP_MAX_DATA_BUNDLING];
9323         struct sctp_tmit_chunk *chk, *fwd;
9324         struct mbuf *m, *endofchain;
9325         struct sctp_nets *net = NULL;
9326         uint32_t tsns_sent = 0;
9327         int no_fragmentflg, bundle_at, cnt_thru;
9328         unsigned int mtu;
9329         int error, i, one_chunk, fwd_tsn, ctl_cnt, tmr_started;
9330         struct sctp_auth_chunk *auth = NULL;
9331         uint32_t auth_offset = 0;
9332         uint16_t auth_keyid;
9333         int override_ok = 1;
9334         int data_auth_reqd = 0;
9335         uint32_t dmtu = 0;
9336
9337         SCTP_TCB_LOCK_ASSERT(stcb);
9338         tmr_started = ctl_cnt = bundle_at = error = 0;
9339         no_fragmentflg = 1;
9340         fwd_tsn = 0;
9341         *cnt_out = 0;
9342         fwd = NULL;
9343         endofchain = m = NULL;
9344         auth_keyid = stcb->asoc.authinfo.active_keyid;
9345 #ifdef SCTP_AUDITING_ENABLED
9346         sctp_audit_log(0xC3, 1);
9347 #endif
9348         if ((TAILQ_EMPTY(&asoc->sent_queue)) &&
9349             (TAILQ_EMPTY(&asoc->control_send_queue))) {
9350                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "SCTP hits empty queue with cnt set to %d?\n",
9351                     asoc->sent_queue_retran_cnt);
9352                 asoc->sent_queue_cnt = 0;
9353                 asoc->sent_queue_cnt_removeable = 0;
9354                 /* send back 0/0 so we enter normal transmission */
9355                 *cnt_out = 0;
9356                 return (0);
9357         }
9358         TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
9359                 if ((chk->rec.chunk_id.id == SCTP_COOKIE_ECHO) ||
9360                     (chk->rec.chunk_id.id == SCTP_STREAM_RESET) ||
9361                     (chk->rec.chunk_id.id == SCTP_FORWARD_CUM_TSN)) {
9362                         if (chk->sent != SCTP_DATAGRAM_RESEND) {
9363                                 continue;
9364                         }
9365                         if (chk->rec.chunk_id.id == SCTP_STREAM_RESET) {
9366                                 if (chk != asoc->str_reset) {
9367                                         /*
9368                                          * not eligible for retran if its
9369                                          * not ours
9370                                          */
9371                                         continue;
9372                                 }
9373                         }
9374                         ctl_cnt++;
9375                         if (chk->rec.chunk_id.id == SCTP_FORWARD_CUM_TSN) {
9376                                 fwd_tsn = 1;
9377                         }
9378                         /*
9379                          * Add an AUTH chunk, if chunk requires it save the
9380                          * offset into the chain for AUTH
9381                          */
9382                         if ((auth == NULL) &&
9383                             (sctp_auth_is_required_chunk(chk->rec.chunk_id.id,
9384                             stcb->asoc.peer_auth_chunks))) {
9385                                 m = sctp_add_auth_chunk(m, &endofchain,
9386                                     &auth, &auth_offset,
9387                                     stcb,
9388                                     chk->rec.chunk_id.id);
9389                                 SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
9390                         }
9391                         m = sctp_copy_mbufchain(chk->data, m, &endofchain, 0, chk->send_size, chk->copy_by_ref);
9392                         break;
9393                 }
9394         }
9395         one_chunk = 0;
9396         cnt_thru = 0;
9397         /* do we have control chunks to retransmit? */
9398         if (m != NULL) {
9399                 /* Start a timer no matter if we suceed or fail */
9400                 if (chk->rec.chunk_id.id == SCTP_COOKIE_ECHO) {
9401                         sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, inp, stcb, chk->whoTo);
9402                 } else if (chk->rec.chunk_id.id == SCTP_ASCONF)
9403                         sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp, stcb, chk->whoTo);
9404                 chk->snd_count++;       /* update our count */
9405                 if ((error = sctp_lowlevel_chunk_output(inp, stcb, chk->whoTo,
9406                     (struct sockaddr *)&chk->whoTo->ro._l_addr, m,
9407                     auth_offset, auth, stcb->asoc.authinfo.active_keyid,
9408                     no_fragmentflg, 0, 0,
9409                     inp->sctp_lport, stcb->rport, htonl(stcb->asoc.peer_vtag),
9410                     chk->whoTo->port, NULL,
9411                     0, 0,
9412                     so_locked))) {
9413                         SCTP_STAT_INCR(sctps_lowlevelerr);
9414                         return (error);
9415                 }
9416                 endofchain = NULL;
9417                 auth = NULL;
9418                 auth_offset = 0;
9419                 /*
9420                  * We don't want to mark the net->sent time here since this
9421                  * we use this for HB and retrans cannot measure RTT
9422                  */
9423                 /* (void)SCTP_GETTIME_TIMEVAL(&chk->whoTo->last_sent_time); */
9424                 *cnt_out += 1;
9425                 chk->sent = SCTP_DATAGRAM_SENT;
9426                 sctp_ucount_decr(stcb->asoc.sent_queue_retran_cnt);
9427                 if (fwd_tsn == 0) {
9428                         return (0);
9429                 } else {
9430                         /* Clean up the fwd-tsn list */
9431                         sctp_clean_up_ctl(stcb, asoc, so_locked);
9432                         return (0);
9433                 }
9434         }
9435         /*
9436          * Ok, it is just data retransmission we need to do or that and a
9437          * fwd-tsn with it all.
9438          */
9439         if (TAILQ_EMPTY(&asoc->sent_queue)) {
9440                 return (SCTP_RETRAN_DONE);
9441         }
9442         if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED) ||
9443             (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT)) {
9444                 /* not yet open, resend the cookie and that is it */
9445                 return (1);
9446         }
9447 #ifdef SCTP_AUDITING_ENABLED
9448         sctp_auditing(20, inp, stcb, NULL);
9449 #endif
9450         data_auth_reqd = sctp_auth_is_required_chunk(SCTP_DATA, stcb->asoc.peer_auth_chunks);
9451         TAILQ_FOREACH(chk, &asoc->sent_queue, sctp_next) {
9452                 if (chk->sent != SCTP_DATAGRAM_RESEND) {
9453                         /* No, not sent to this net or not ready for rtx */
9454                         continue;
9455                 }
9456                 if (chk->data == NULL) {
9457                         SCTP_PRINTF("TSN:%x chk->snd_count:%d chk->sent:%d can't retran - no data\n",
9458                             chk->rec.data.TSN_seq, chk->snd_count, chk->sent);
9459                         continue;
9460                 }
9461                 if ((SCTP_BASE_SYSCTL(sctp_max_retran_chunk)) &&
9462                     (chk->snd_count >= SCTP_BASE_SYSCTL(sctp_max_retran_chunk))) {
9463                         /* Gak, we have exceeded max unlucky retran, abort! */
9464                         SCTP_PRINTF("Gak, chk->snd_count:%d >= max:%d - send abort\n",
9465                             chk->snd_count,
9466                             SCTP_BASE_SYSCTL(sctp_max_retran_chunk));
9467                         atomic_add_int(&stcb->asoc.refcnt, 1);
9468                         sctp_abort_an_association(stcb->sctp_ep, stcb, NULL, so_locked);
9469                         SCTP_TCB_LOCK(stcb);
9470                         atomic_subtract_int(&stcb->asoc.refcnt, 1);
9471                         return (SCTP_RETRAN_EXIT);
9472                 }
9473                 /* pick up the net */
9474                 net = chk->whoTo;
9475                 switch (net->ro._l_addr.sa.sa_family) {
9476 #ifdef INET
9477                 case AF_INET:
9478                         mtu = net->mtu - SCTP_MIN_V4_OVERHEAD;
9479                         break;
9480 #endif
9481 #ifdef INET6
9482                 case AF_INET6:
9483                         mtu = net->mtu - SCTP_MIN_OVERHEAD;
9484                         break;
9485 #endif
9486                 default:
9487                         /* TSNH */
9488                         mtu = net->mtu;
9489                         break;
9490                 }
9491
9492                 if ((asoc->peers_rwnd < mtu) && (asoc->total_flight > 0)) {
9493                         /* No room in peers rwnd */
9494                         uint32_t tsn;
9495
9496                         tsn = asoc->last_acked_seq + 1;
9497                         if (tsn == chk->rec.data.TSN_seq) {
9498                                 /*
9499                                  * we make a special exception for this
9500                                  * case. The peer has no rwnd but is missing
9501                                  * the lowest chunk.. which is probably what
9502                                  * is holding up the rwnd.
9503                                  */
9504                                 goto one_chunk_around;
9505                         }
9506                         return (1);
9507                 }
9508 one_chunk_around:
9509                 if (asoc->peers_rwnd < mtu) {
9510                         one_chunk = 1;
9511                         if ((asoc->peers_rwnd == 0) &&
9512                             (asoc->total_flight == 0)) {
9513                                 chk->window_probe = 1;
9514                                 chk->whoTo->window_probe = 1;
9515                         }
9516                 }
9517 #ifdef SCTP_AUDITING_ENABLED
9518                 sctp_audit_log(0xC3, 2);
9519 #endif
9520                 bundle_at = 0;
9521                 m = NULL;
9522                 net->fast_retran_ip = 0;
9523                 if (chk->rec.data.doing_fast_retransmit == 0) {
9524                         /*
9525                          * if no FR in progress skip destination that have
9526                          * flight_size > cwnd.
9527                          */
9528                         if (net->flight_size >= net->cwnd) {
9529                                 continue;
9530                         }
9531                 } else {
9532                         /*
9533                          * Mark the destination net to have FR recovery
9534                          * limits put on it.
9535                          */
9536                         *fr_done = 1;
9537                         net->fast_retran_ip = 1;
9538                 }
9539
9540                 /*
9541                  * if no AUTH is yet included and this chunk requires it,
9542                  * make sure to account for it.  We don't apply the size
9543                  * until the AUTH chunk is actually added below in case
9544                  * there is no room for this chunk.
9545                  */
9546                 if (data_auth_reqd && (auth == NULL)) {
9547                         dmtu = sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
9548                 } else
9549                         dmtu = 0;
9550
9551                 if ((chk->send_size <= (mtu - dmtu)) ||
9552                     (chk->flags & CHUNK_FLAGS_FRAGMENT_OK)) {
9553                         /* ok we will add this one */
9554                         if (data_auth_reqd) {
9555                                 if (auth == NULL) {
9556                                         m = sctp_add_auth_chunk(m,
9557                                             &endofchain,
9558                                             &auth,
9559                                             &auth_offset,
9560                                             stcb,
9561                                             SCTP_DATA);
9562                                         auth_keyid = chk->auth_keyid;
9563                                         override_ok = 0;
9564                                         SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
9565                                 } else if (override_ok) {
9566                                         auth_keyid = chk->auth_keyid;
9567                                         override_ok = 0;
9568                                 } else if (chk->auth_keyid != auth_keyid) {
9569                                         /* different keyid, so done bundling */
9570                                         break;
9571                                 }
9572                         }
9573                         m = sctp_copy_mbufchain(chk->data, m, &endofchain, 0, chk->send_size, chk->copy_by_ref);
9574                         if (m == NULL) {
9575                                 SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
9576                                 return (ENOMEM);
9577                         }
9578                         /* Do clear IP_DF ? */
9579                         if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
9580                                 no_fragmentflg = 0;
9581                         }
9582                         /* upate our MTU size */
9583                         if (mtu > (chk->send_size + dmtu))
9584                                 mtu -= (chk->send_size + dmtu);
9585                         else
9586                                 mtu = 0;
9587                         data_list[bundle_at++] = chk;
9588                         if (one_chunk && (asoc->total_flight <= 0)) {
9589                                 SCTP_STAT_INCR(sctps_windowprobed);
9590                         }
9591                 }
9592                 if (one_chunk == 0) {
9593                         /*
9594                          * now are there anymore forward from chk to pick
9595                          * up?
9596                          */
9597                         for (fwd = TAILQ_NEXT(chk, sctp_next); fwd != NULL; fwd = TAILQ_NEXT(fwd, sctp_next)) {
9598                                 if (fwd->sent != SCTP_DATAGRAM_RESEND) {
9599                                         /* Nope, not for retran */
9600                                         continue;
9601                                 }
9602                                 if (fwd->whoTo != net) {
9603                                         /* Nope, not the net in question */
9604                                         continue;
9605                                 }
9606                                 if (data_auth_reqd && (auth == NULL)) {
9607                                         dmtu = sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
9608                                 } else
9609                                         dmtu = 0;
9610                                 if (fwd->send_size <= (mtu - dmtu)) {
9611                                         if (data_auth_reqd) {
9612                                                 if (auth == NULL) {
9613                                                         m = sctp_add_auth_chunk(m,
9614                                                             &endofchain,
9615                                                             &auth,
9616                                                             &auth_offset,
9617                                                             stcb,
9618                                                             SCTP_DATA);
9619                                                         auth_keyid = fwd->auth_keyid;
9620                                                         override_ok = 0;
9621                                                         SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
9622                                                 } else if (override_ok) {
9623                                                         auth_keyid = fwd->auth_keyid;
9624                                                         override_ok = 0;
9625                                                 } else if (fwd->auth_keyid != auth_keyid) {
9626                                                         /*
9627                                                          * different keyid,
9628                                                          * so done bundling
9629                                                          */
9630                                                         break;
9631                                                 }
9632                                         }
9633                                         m = sctp_copy_mbufchain(fwd->data, m, &endofchain, 0, fwd->send_size, fwd->copy_by_ref);
9634                                         if (m == NULL) {
9635                                                 SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
9636                                                 return (ENOMEM);
9637                                         }
9638                                         /* Do clear IP_DF ? */
9639                                         if (fwd->flags & CHUNK_FLAGS_FRAGMENT_OK) {
9640                                                 no_fragmentflg = 0;
9641                                         }
9642                                         /* upate our MTU size */
9643                                         if (mtu > (fwd->send_size + dmtu))
9644                                                 mtu -= (fwd->send_size + dmtu);
9645                                         else
9646                                                 mtu = 0;
9647                                         data_list[bundle_at++] = fwd;
9648                                         if (bundle_at >= SCTP_MAX_DATA_BUNDLING) {
9649                                                 break;
9650                                         }
9651                                 } else {
9652                                         /* can't fit so we are done */
9653                                         break;
9654                                 }
9655                         }
9656                 }
9657                 /* Is there something to send for this destination? */
9658                 if (m) {
9659                         /*
9660                          * No matter if we fail/or suceed we should start a
9661                          * timer. A failure is like a lost IP packet :-)
9662                          */
9663                         if (!SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer)) {
9664                                 /*
9665                                  * no timer running on this destination
9666                                  * restart it.
9667                                  */
9668                                 sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
9669                                 tmr_started = 1;
9670                         }
9671                         /* Now lets send it, if there is anything to send :> */
9672                         if ((error = sctp_lowlevel_chunk_output(inp, stcb, net,
9673                             (struct sockaddr *)&net->ro._l_addr, m,
9674                             auth_offset, auth, auth_keyid,
9675                             no_fragmentflg, 0, 0,
9676                             inp->sctp_lport, stcb->rport, htonl(stcb->asoc.peer_vtag),
9677                             net->port, NULL,
9678                             0, 0,
9679                             so_locked))) {
9680                                 /* error, we could not output */
9681                                 SCTP_STAT_INCR(sctps_lowlevelerr);
9682                                 return (error);
9683                         }
9684                         endofchain = NULL;
9685                         auth = NULL;
9686                         auth_offset = 0;
9687                         /* For HB's */
9688                         /*
9689                          * We don't want to mark the net->sent time here
9690                          * since this we use this for HB and retrans cannot
9691                          * measure RTT
9692                          */
9693                         /* (void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time); */
9694
9695                         /* For auto-close */
9696                         cnt_thru++;
9697                         if (*now_filled == 0) {
9698                                 (void)SCTP_GETTIME_TIMEVAL(&asoc->time_last_sent);
9699                                 *now = asoc->time_last_sent;
9700                                 *now_filled = 1;
9701                         } else {
9702                                 asoc->time_last_sent = *now;
9703                         }
9704                         *cnt_out += bundle_at;
9705 #ifdef SCTP_AUDITING_ENABLED
9706                         sctp_audit_log(0xC4, bundle_at);
9707 #endif
9708                         if (bundle_at) {
9709                                 tsns_sent = data_list[0]->rec.data.TSN_seq;
9710                         }
9711                         for (i = 0; i < bundle_at; i++) {
9712                                 SCTP_STAT_INCR(sctps_sendretransdata);
9713                                 data_list[i]->sent = SCTP_DATAGRAM_SENT;
9714                                 /*
9715                                  * When we have a revoked data, and we
9716                                  * retransmit it, then we clear the revoked
9717                                  * flag since this flag dictates if we
9718                                  * subtracted from the fs
9719                                  */
9720                                 if (data_list[i]->rec.data.chunk_was_revoked) {
9721                                         /* Deflate the cwnd */
9722                                         data_list[i]->whoTo->cwnd -= data_list[i]->book_size;
9723                                         data_list[i]->rec.data.chunk_was_revoked = 0;
9724                                 }
9725                                 data_list[i]->snd_count++;
9726                                 sctp_ucount_decr(asoc->sent_queue_retran_cnt);
9727                                 /* record the time */
9728                                 data_list[i]->sent_rcv_time = asoc->time_last_sent;
9729                                 if (data_list[i]->book_size_scale) {
9730                                         /*
9731                                          * need to double the book size on
9732                                          * this one
9733                                          */
9734                                         data_list[i]->book_size_scale = 0;
9735                                         /*
9736                                          * Since we double the booksize, we
9737                                          * must also double the output queue
9738                                          * size, since this get shrunk when
9739                                          * we free by this amount.
9740                                          */
9741                                         atomic_add_int(&((asoc)->total_output_queue_size), data_list[i]->book_size);
9742                                         data_list[i]->book_size *= 2;
9743
9744
9745                                 } else {
9746                                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_RWND_ENABLE) {
9747                                                 sctp_log_rwnd(SCTP_DECREASE_PEER_RWND,
9748                                                     asoc->peers_rwnd, data_list[i]->send_size, SCTP_BASE_SYSCTL(sctp_peer_chunk_oh));
9749                                         }
9750                                         asoc->peers_rwnd = sctp_sbspace_sub(asoc->peers_rwnd,
9751                                             (uint32_t) (data_list[i]->send_size +
9752                                             SCTP_BASE_SYSCTL(sctp_peer_chunk_oh)));
9753                                 }
9754                                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_FLIGHT_LOGGING_ENABLE) {
9755                                         sctp_misc_ints(SCTP_FLIGHT_LOG_UP_RSND,
9756                                             data_list[i]->whoTo->flight_size,
9757                                             data_list[i]->book_size,
9758                                             (uintptr_t) data_list[i]->whoTo,
9759                                             data_list[i]->rec.data.TSN_seq);
9760                                 }
9761                                 sctp_flight_size_increase(data_list[i]);
9762                                 sctp_total_flight_increase(stcb, data_list[i]);
9763                                 if (asoc->peers_rwnd < stcb->sctp_ep->sctp_ep.sctp_sws_sender) {
9764                                         /* SWS sender side engages */
9765                                         asoc->peers_rwnd = 0;
9766                                 }
9767                                 if ((i == 0) &&
9768                                     (data_list[i]->rec.data.doing_fast_retransmit)) {
9769                                         SCTP_STAT_INCR(sctps_sendfastretrans);
9770                                         if ((data_list[i] == TAILQ_FIRST(&asoc->sent_queue)) &&
9771                                             (tmr_started == 0)) {
9772                                                 /*-
9773                                                  * ok we just fast-retrans'd
9774                                                  * the lowest TSN, i.e the
9775                                                  * first on the list. In
9776                                                  * this case we want to give
9777                                                  * some more time to get a
9778                                                  * SACK back without a
9779                                                  * t3-expiring.
9780                                                  */
9781                                                 sctp_timer_stop(SCTP_TIMER_TYPE_SEND, inp, stcb, net,
9782                                                     SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_4);
9783                                                 sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
9784                                         }
9785                                 }
9786                         }
9787                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
9788                                 sctp_log_cwnd(stcb, net, tsns_sent, SCTP_CWND_LOG_FROM_RESEND);
9789                         }
9790 #ifdef SCTP_AUDITING_ENABLED
9791                         sctp_auditing(21, inp, stcb, NULL);
9792 #endif
9793                 } else {
9794                         /* None will fit */
9795                         return (1);
9796                 }
9797                 if (asoc->sent_queue_retran_cnt <= 0) {
9798                         /* all done we have no more to retran */
9799                         asoc->sent_queue_retran_cnt = 0;
9800                         break;
9801                 }
9802                 if (one_chunk) {
9803                         /* No more room in rwnd */
9804                         return (1);
9805                 }
9806                 /* stop the for loop here. we sent out a packet */
9807                 break;
9808         }
9809         return (0);
9810 }
9811
9812 static void
9813 sctp_timer_validation(struct sctp_inpcb *inp,
9814     struct sctp_tcb *stcb,
9815     struct sctp_association *asoc)
9816 {
9817         struct sctp_nets *net;
9818
9819         /* Validate that a timer is running somewhere */
9820         TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
9821                 if (SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer)) {
9822                         /* Here is a timer */
9823                         return;
9824                 }
9825         }
9826         SCTP_TCB_LOCK_ASSERT(stcb);
9827         /* Gak, we did not have a timer somewhere */
9828         SCTPDBG(SCTP_DEBUG_OUTPUT3, "Deadlock avoided starting timer on a dest at retran\n");
9829         if (asoc->alternate) {
9830                 sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, asoc->alternate);
9831         } else {
9832                 sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, asoc->primary_destination);
9833         }
9834         return;
9835 }
9836
9837 void
9838 sctp_chunk_output(struct sctp_inpcb *inp,
9839     struct sctp_tcb *stcb,
9840     int from_where,
9841     int so_locked
9842 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
9843     SCTP_UNUSED
9844 #endif
9845 )
9846 {
9847         /*-
9848          * Ok this is the generic chunk service queue. we must do the
9849          * following:
9850          * - See if there are retransmits pending, if so we must
9851          *   do these first.
9852          * - Service the stream queue that is next, moving any
9853          *   message (note I must get a complete message i.e.
9854          *   FIRST/MIDDLE and LAST to the out queue in one pass) and assigning
9855          *   TSN's
9856          * - Check to see if the cwnd/rwnd allows any output, if so we
9857          *   go ahead and fomulate and send the low level chunks. Making sure
9858          *   to combine any control in the control chunk queue also.
9859          */
9860         struct sctp_association *asoc;
9861         struct sctp_nets *net;
9862         int error = 0, num_out = 0, tot_out = 0, ret = 0, reason_code = 0;
9863         unsigned int burst_cnt = 0;
9864         struct timeval now;
9865         int now_filled = 0;
9866         int nagle_on;
9867         int frag_point = sctp_get_frag_point(stcb, &stcb->asoc);
9868         int un_sent = 0;
9869         int fr_done;
9870         unsigned int tot_frs = 0;
9871
9872         asoc = &stcb->asoc;
9873         /* The Nagle algorithm is only applied when handling a send call. */
9874         if (from_where == SCTP_OUTPUT_FROM_USR_SEND) {
9875                 if (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_NODELAY)) {
9876                         nagle_on = 0;
9877                 } else {
9878                         nagle_on = 1;
9879                 }
9880         } else {
9881                 nagle_on = 0;
9882         }
9883         SCTP_TCB_LOCK_ASSERT(stcb);
9884
9885         un_sent = (stcb->asoc.total_output_queue_size - stcb->asoc.total_flight);
9886
9887         if ((un_sent <= 0) &&
9888             (TAILQ_EMPTY(&asoc->control_send_queue)) &&
9889             (TAILQ_EMPTY(&asoc->asconf_send_queue)) &&
9890             (asoc->sent_queue_retran_cnt == 0)) {
9891                 /* Nothing to do unless there is something to be sent left */
9892                 return;
9893         }
9894         /*
9895          * Do we have something to send, data or control AND a sack timer
9896          * running, if so piggy-back the sack.
9897          */
9898         if (SCTP_OS_TIMER_PENDING(&stcb->asoc.dack_timer.timer)) {
9899                 sctp_send_sack(stcb, so_locked);
9900                 (void)SCTP_OS_TIMER_STOP(&stcb->asoc.dack_timer.timer);
9901         }
9902         while (asoc->sent_queue_retran_cnt) {
9903                 /*-
9904                  * Ok, it is retransmission time only, we send out only ONE
9905                  * packet with a single call off to the retran code.
9906                  */
9907                 if (from_where == SCTP_OUTPUT_FROM_COOKIE_ACK) {
9908                         /*-
9909                          * Special hook for handling cookiess discarded
9910                          * by peer that carried data. Send cookie-ack only
9911                          * and then the next call with get the retran's.
9912                          */
9913                         (void)sctp_med_chunk_output(inp, stcb, asoc, &num_out, &reason_code, 1,
9914                             from_where,
9915                             &now, &now_filled, frag_point, so_locked);
9916                         return;
9917                 } else if (from_where != SCTP_OUTPUT_FROM_HB_TMR) {
9918                         /* if its not from a HB then do it */
9919                         fr_done = 0;
9920                         ret = sctp_chunk_retransmission(inp, stcb, asoc, &num_out, &now, &now_filled, &fr_done, so_locked);
9921                         if (fr_done) {
9922                                 tot_frs++;
9923                         }
9924                 } else {
9925                         /*
9926                          * its from any other place, we don't allow retran
9927                          * output (only control)
9928                          */
9929                         ret = 1;
9930                 }
9931                 if (ret > 0) {
9932                         /* Can't send anymore */
9933                         /*-
9934                          * now lets push out control by calling med-level
9935                          * output once. this assures that we WILL send HB's
9936                          * if queued too.
9937                          */
9938                         (void)sctp_med_chunk_output(inp, stcb, asoc, &num_out, &reason_code, 1,
9939                             from_where,
9940                             &now, &now_filled, frag_point, so_locked);
9941 #ifdef SCTP_AUDITING_ENABLED
9942                         sctp_auditing(8, inp, stcb, NULL);
9943 #endif
9944                         sctp_timer_validation(inp, stcb, asoc);
9945                         return;
9946                 }
9947                 if (ret < 0) {
9948                         /*-
9949                          * The count was off.. retran is not happening so do
9950                          * the normal retransmission.
9951                          */
9952 #ifdef SCTP_AUDITING_ENABLED
9953                         sctp_auditing(9, inp, stcb, NULL);
9954 #endif
9955                         if (ret == SCTP_RETRAN_EXIT) {
9956                                 return;
9957                         }
9958                         break;
9959                 }
9960                 if (from_where == SCTP_OUTPUT_FROM_T3) {
9961                         /* Only one transmission allowed out of a timeout */
9962 #ifdef SCTP_AUDITING_ENABLED
9963                         sctp_auditing(10, inp, stcb, NULL);
9964 #endif
9965                         /* Push out any control */
9966                         (void)sctp_med_chunk_output(inp, stcb, asoc, &num_out, &reason_code, 1, from_where,
9967                             &now, &now_filled, frag_point, so_locked);
9968                         return;
9969                 }
9970                 if ((asoc->fr_max_burst > 0) && (tot_frs >= asoc->fr_max_burst)) {
9971                         /* Hit FR burst limit */
9972                         return;
9973                 }
9974                 if ((num_out == 0) && (ret == 0)) {
9975                         /* No more retrans to send */
9976                         break;
9977                 }
9978         }
9979 #ifdef SCTP_AUDITING_ENABLED
9980         sctp_auditing(12, inp, stcb, NULL);
9981 #endif
9982         /* Check for bad destinations, if they exist move chunks around. */
9983         TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
9984                 if (!(net->dest_state & SCTP_ADDR_REACHABLE)) {
9985                         /*-
9986                          * if possible move things off of this address we
9987                          * still may send below due to the dormant state but
9988                          * we try to find an alternate address to send to
9989                          * and if we have one we move all queued data on the
9990                          * out wheel to this alternate address.
9991                          */
9992                         if (net->ref_count > 1)
9993                                 sctp_move_chunks_from_net(stcb, net);
9994                 } else {
9995                         /*-
9996                          * if ((asoc->sat_network) || (net->addr_is_local))
9997                          * { burst_limit = asoc->max_burst *
9998                          * SCTP_SAT_NETWORK_BURST_INCR; }
9999                          */
10000                         if (asoc->max_burst > 0) {
10001                                 if (SCTP_BASE_SYSCTL(sctp_use_cwnd_based_maxburst)) {
10002                                         if ((net->flight_size + (asoc->max_burst * net->mtu)) < net->cwnd) {
10003                                                 /*
10004                                                  * JRS - Use the congestion
10005                                                  * control given in the
10006                                                  * congestion control module
10007                                                  */
10008                                                 asoc->cc_functions.sctp_cwnd_update_after_output(stcb, net, asoc->max_burst);
10009                                                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_MAXBURST_ENABLE) {
10010                                                         sctp_log_maxburst(stcb, net, 0, asoc->max_burst, SCTP_MAX_BURST_APPLIED);
10011                                                 }
10012                                                 SCTP_STAT_INCR(sctps_maxburstqueued);
10013                                         }
10014                                         net->fast_retran_ip = 0;
10015                                 } else {
10016                                         if (net->flight_size == 0) {
10017                                                 /*
10018                                                  * Should be decaying the
10019                                                  * cwnd here
10020                                                  */
10021                                                 ;
10022                                         }
10023                                 }
10024                         }
10025                 }
10026
10027         }
10028         burst_cnt = 0;
10029         do {
10030                 error = sctp_med_chunk_output(inp, stcb, asoc, &num_out,
10031                     &reason_code, 0, from_where,
10032                     &now, &now_filled, frag_point, so_locked);
10033                 if (error) {
10034                         SCTPDBG(SCTP_DEBUG_OUTPUT1, "Error %d was returned from med-c-op\n", error);
10035                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_MAXBURST_ENABLE) {
10036                                 sctp_log_maxburst(stcb, asoc->primary_destination, error, burst_cnt, SCTP_MAX_BURST_ERROR_STOP);
10037                         }
10038                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
10039                                 sctp_log_cwnd(stcb, NULL, error, SCTP_SEND_NOW_COMPLETES);
10040                                 sctp_log_cwnd(stcb, NULL, 0xdeadbeef, SCTP_SEND_NOW_COMPLETES);
10041                         }
10042                         break;
10043                 }
10044                 SCTPDBG(SCTP_DEBUG_OUTPUT3, "m-c-o put out %d\n", num_out);
10045
10046                 tot_out += num_out;
10047                 burst_cnt++;
10048                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
10049                         sctp_log_cwnd(stcb, NULL, num_out, SCTP_SEND_NOW_COMPLETES);
10050                         if (num_out == 0) {
10051                                 sctp_log_cwnd(stcb, NULL, reason_code, SCTP_SEND_NOW_COMPLETES);
10052                         }
10053                 }
10054                 if (nagle_on) {
10055                         /*
10056                          * When the Nagle algorithm is used, look at how
10057                          * much is unsent, then if its smaller than an MTU
10058                          * and we have data in flight we stop, except if we
10059                          * are handling a fragmented user message.
10060                          */
10061                         un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
10062                             (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
10063                         if ((un_sent < (int)(stcb->asoc.smallest_mtu - SCTP_MIN_OVERHEAD)) &&
10064                             (stcb->asoc.total_flight > 0) &&
10065                             ((stcb->asoc.locked_on_sending == NULL) ||
10066                             sctp_is_feature_on(inp, SCTP_PCB_FLAGS_EXPLICIT_EOR))) {
10067                                 break;
10068                         }
10069                 }
10070                 if (TAILQ_EMPTY(&asoc->control_send_queue) &&
10071                     TAILQ_EMPTY(&asoc->send_queue) &&
10072                     stcb->asoc.ss_functions.sctp_ss_is_empty(stcb, asoc)) {
10073                         /* Nothing left to send */
10074                         break;
10075                 }
10076                 if ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) <= 0) {
10077                         /* Nothing left to send */
10078                         break;
10079                 }
10080         } while (num_out &&
10081             ((asoc->max_burst == 0) ||
10082             SCTP_BASE_SYSCTL(sctp_use_cwnd_based_maxburst) ||
10083             (burst_cnt < asoc->max_burst)));
10084
10085         if (SCTP_BASE_SYSCTL(sctp_use_cwnd_based_maxburst) == 0) {
10086                 if ((asoc->max_burst > 0) && (burst_cnt >= asoc->max_burst)) {
10087                         SCTP_STAT_INCR(sctps_maxburstqueued);
10088                         asoc->burst_limit_applied = 1;
10089                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_MAXBURST_ENABLE) {
10090                                 sctp_log_maxburst(stcb, asoc->primary_destination, 0, burst_cnt, SCTP_MAX_BURST_APPLIED);
10091                         }
10092                 } else {
10093                         asoc->burst_limit_applied = 0;
10094                 }
10095         }
10096         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
10097                 sctp_log_cwnd(stcb, NULL, tot_out, SCTP_SEND_NOW_COMPLETES);
10098         }
10099         SCTPDBG(SCTP_DEBUG_OUTPUT1, "Ok, we have put out %d chunks\n",
10100             tot_out);
10101
10102         /*-
10103          * Now we need to clean up the control chunk chain if a ECNE is on
10104          * it. It must be marked as UNSENT again so next call will continue
10105          * to send it until such time that we get a CWR, to remove it.
10106          */
10107         if (stcb->asoc.ecn_echo_cnt_onq)
10108                 sctp_fix_ecn_echo(asoc);
10109         return;
10110 }
10111
10112
10113 int
10114 sctp_output(
10115     struct sctp_inpcb *inp,
10116     struct mbuf *m,
10117     struct sockaddr *addr,
10118     struct mbuf *control,
10119     struct thread *p,
10120     int flags)
10121 {
10122         if (inp == NULL) {
10123                 SCTP_LTRACE_ERR_RET_PKT(m, inp, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, EINVAL);
10124                 return (EINVAL);
10125         }
10126         if (inp->sctp_socket == NULL) {
10127                 SCTP_LTRACE_ERR_RET_PKT(m, inp, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, EINVAL);
10128                 return (EINVAL);
10129         }
10130         return (sctp_sosend(inp->sctp_socket,
10131             addr,
10132             (struct uio *)NULL,
10133             m,
10134             control,
10135             flags, p
10136             ));
10137 }
10138
10139 void
10140 send_forward_tsn(struct sctp_tcb *stcb,
10141     struct sctp_association *asoc)
10142 {
10143         struct sctp_tmit_chunk *chk;
10144         struct sctp_forward_tsn_chunk *fwdtsn;
10145         uint32_t advance_peer_ack_point;
10146
10147         SCTP_TCB_LOCK_ASSERT(stcb);
10148         TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
10149                 if (chk->rec.chunk_id.id == SCTP_FORWARD_CUM_TSN) {
10150                         /* mark it to unsent */
10151                         chk->sent = SCTP_DATAGRAM_UNSENT;
10152                         chk->snd_count = 0;
10153                         /* Do we correct its output location? */
10154                         if (chk->whoTo) {
10155                                 sctp_free_remote_addr(chk->whoTo);
10156                                 chk->whoTo = NULL;
10157                         }
10158                         goto sctp_fill_in_rest;
10159                 }
10160         }
10161         /* Ok if we reach here we must build one */
10162         sctp_alloc_a_chunk(stcb, chk);
10163         if (chk == NULL) {
10164                 return;
10165         }
10166         asoc->fwd_tsn_cnt++;
10167         chk->copy_by_ref = 0;
10168         chk->rec.chunk_id.id = SCTP_FORWARD_CUM_TSN;
10169         chk->rec.chunk_id.can_take_data = 0;
10170         chk->asoc = asoc;
10171         chk->whoTo = NULL;
10172         chk->data = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_DATA);
10173         if (chk->data == NULL) {
10174                 sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
10175                 return;
10176         }
10177         SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
10178         chk->sent = SCTP_DATAGRAM_UNSENT;
10179         chk->snd_count = 0;
10180         TAILQ_INSERT_TAIL(&asoc->control_send_queue, chk, sctp_next);
10181         asoc->ctrl_queue_cnt++;
10182 sctp_fill_in_rest:
10183         /*-
10184          * Here we go through and fill out the part that deals with
10185          * stream/seq of the ones we skip.
10186          */
10187         SCTP_BUF_LEN(chk->data) = 0;
10188         {
10189                 struct sctp_tmit_chunk *at, *tp1, *last;
10190                 struct sctp_strseq *strseq;
10191                 unsigned int cnt_of_space, i, ovh;
10192                 unsigned int space_needed;
10193                 unsigned int cnt_of_skipped = 0;
10194
10195                 TAILQ_FOREACH(at, &asoc->sent_queue, sctp_next) {
10196                         if ((at->sent != SCTP_FORWARD_TSN_SKIP) &&
10197                             (at->sent != SCTP_DATAGRAM_NR_ACKED)) {
10198                                 /* no more to look at */
10199                                 break;
10200                         }
10201                         if (at->rec.data.rcv_flags & SCTP_DATA_UNORDERED) {
10202                                 /* We don't report these */
10203                                 continue;
10204                         }
10205                         cnt_of_skipped++;
10206                 }
10207                 space_needed = (sizeof(struct sctp_forward_tsn_chunk) +
10208                     (cnt_of_skipped * sizeof(struct sctp_strseq)));
10209
10210                 cnt_of_space = M_TRAILINGSPACE(chk->data);
10211
10212                 if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
10213                         ovh = SCTP_MIN_OVERHEAD;
10214                 } else {
10215                         ovh = SCTP_MIN_V4_OVERHEAD;
10216                 }
10217                 if (cnt_of_space > (asoc->smallest_mtu - ovh)) {
10218                         /* trim to a mtu size */
10219                         cnt_of_space = asoc->smallest_mtu - ovh;
10220                 }
10221                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_TRY_ADVANCE) {
10222                         sctp_misc_ints(SCTP_FWD_TSN_CHECK,
10223                             0xff, 0, cnt_of_skipped,
10224                             asoc->advanced_peer_ack_point);
10225
10226                 }
10227                 advance_peer_ack_point = asoc->advanced_peer_ack_point;
10228                 if (cnt_of_space < space_needed) {
10229                         /*-
10230                          * ok we must trim down the chunk by lowering the
10231                          * advance peer ack point.
10232                          */
10233                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_TRY_ADVANCE) {
10234                                 sctp_misc_ints(SCTP_FWD_TSN_CHECK,
10235                                     0xff, 0xff, cnt_of_space,
10236                                     space_needed);
10237                         }
10238                         cnt_of_skipped = cnt_of_space - sizeof(struct sctp_forward_tsn_chunk);
10239                         cnt_of_skipped /= sizeof(struct sctp_strseq);
10240                         /*-
10241                          * Go through and find the TSN that will be the one
10242                          * we report.
10243                          */
10244                         at = TAILQ_FIRST(&asoc->sent_queue);
10245                         if (at != NULL) {
10246                                 for (i = 0; i < cnt_of_skipped; i++) {
10247                                         tp1 = TAILQ_NEXT(at, sctp_next);
10248                                         if (tp1 == NULL) {
10249                                                 break;
10250                                         }
10251                                         at = tp1;
10252                                 }
10253                         }
10254                         if (at && SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_TRY_ADVANCE) {
10255                                 sctp_misc_ints(SCTP_FWD_TSN_CHECK,
10256                                     0xff, cnt_of_skipped, at->rec.data.TSN_seq,
10257                                     asoc->advanced_peer_ack_point);
10258                         }
10259                         last = at;
10260                         /*-
10261                          * last now points to last one I can report, update
10262                          * peer ack point
10263                          */
10264                         if (last)
10265                                 advance_peer_ack_point = last->rec.data.TSN_seq;
10266                         space_needed = sizeof(struct sctp_forward_tsn_chunk) +
10267                             cnt_of_skipped * sizeof(struct sctp_strseq);
10268                 }
10269                 chk->send_size = space_needed;
10270                 /* Setup the chunk */
10271                 fwdtsn = mtod(chk->data, struct sctp_forward_tsn_chunk *);
10272                 fwdtsn->ch.chunk_length = htons(chk->send_size);
10273                 fwdtsn->ch.chunk_flags = 0;
10274                 fwdtsn->ch.chunk_type = SCTP_FORWARD_CUM_TSN;
10275                 fwdtsn->new_cumulative_tsn = htonl(advance_peer_ack_point);
10276                 SCTP_BUF_LEN(chk->data) = chk->send_size;
10277                 fwdtsn++;
10278                 /*-
10279                  * Move pointer to after the fwdtsn and transfer to the
10280                  * strseq pointer.
10281                  */
10282                 strseq = (struct sctp_strseq *)fwdtsn;
10283                 /*-
10284                  * Now populate the strseq list. This is done blindly
10285                  * without pulling out duplicate stream info. This is
10286                  * inefficent but won't harm the process since the peer will
10287                  * look at these in sequence and will thus release anything.
10288                  * It could mean we exceed the PMTU and chop off some that
10289                  * we could have included.. but this is unlikely (aka 1432/4
10290                  * would mean 300+ stream seq's would have to be reported in
10291                  * one FWD-TSN. With a bit of work we can later FIX this to
10292                  * optimize and pull out duplcates.. but it does add more
10293                  * overhead. So for now... not!
10294                  */
10295                 at = TAILQ_FIRST(&asoc->sent_queue);
10296                 for (i = 0; i < cnt_of_skipped; i++) {
10297                         tp1 = TAILQ_NEXT(at, sctp_next);
10298                         if (tp1 == NULL)
10299                                 break;
10300                         if (at->rec.data.rcv_flags & SCTP_DATA_UNORDERED) {
10301                                 /* We don't report these */
10302                                 i--;
10303                                 at = tp1;
10304                                 continue;
10305                         }
10306                         if (at->rec.data.TSN_seq == advance_peer_ack_point) {
10307                                 at->rec.data.fwd_tsn_cnt = 0;
10308                         }
10309                         strseq->stream = ntohs(at->rec.data.stream_number);
10310                         strseq->sequence = ntohs(at->rec.data.stream_seq);
10311                         strseq++;
10312                         at = tp1;
10313                 }
10314         }
10315         return;
10316 }
10317
10318 void
10319 sctp_send_sack(struct sctp_tcb *stcb, int so_locked
10320 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
10321     SCTP_UNUSED
10322 #endif
10323 )
10324 {
10325         /*-
10326          * Queue up a SACK or NR-SACK in the control queue.
10327          * We must first check to see if a SACK or NR-SACK is
10328          * somehow on the control queue.
10329          * If so, we will take and and remove the old one.
10330          */
10331         struct sctp_association *asoc;
10332         struct sctp_tmit_chunk *chk, *a_chk;
10333         struct sctp_sack_chunk *sack;
10334         struct sctp_nr_sack_chunk *nr_sack;
10335         struct sctp_gap_ack_block *gap_descriptor;
10336         struct sack_track *selector;
10337         int mergeable = 0;
10338         int offset;
10339         caddr_t limit;
10340         uint32_t *dup;
10341         int limit_reached = 0;
10342         unsigned int i, siz, j;
10343         unsigned int num_gap_blocks = 0, num_nr_gap_blocks = 0, space;
10344         int num_dups = 0;
10345         int space_req;
10346         uint32_t highest_tsn;
10347         uint8_t flags;
10348         uint8_t type;
10349         uint8_t tsn_map;
10350
10351         if ((stcb->asoc.sctp_nr_sack_on_off == 1) &&
10352             (stcb->asoc.peer_supports_nr_sack == 1)) {
10353                 type = SCTP_NR_SELECTIVE_ACK;
10354         } else {
10355                 type = SCTP_SELECTIVE_ACK;
10356         }
10357         a_chk = NULL;
10358         asoc = &stcb->asoc;
10359         SCTP_TCB_LOCK_ASSERT(stcb);
10360         if (asoc->last_data_chunk_from == NULL) {
10361                 /* Hmm we never received anything */
10362                 return;
10363         }
10364         sctp_slide_mapping_arrays(stcb);
10365         sctp_set_rwnd(stcb, asoc);
10366         TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
10367                 if (chk->rec.chunk_id.id == type) {
10368                         /* Hmm, found a sack already on queue, remove it */
10369                         TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
10370                         asoc->ctrl_queue_cnt--;
10371                         a_chk = chk;
10372                         if (a_chk->data) {
10373                                 sctp_m_freem(a_chk->data);
10374                                 a_chk->data = NULL;
10375                         }
10376                         if (a_chk->whoTo) {
10377                                 sctp_free_remote_addr(a_chk->whoTo);
10378                                 a_chk->whoTo = NULL;
10379                         }
10380                         break;
10381                 }
10382         }
10383         if (a_chk == NULL) {
10384                 sctp_alloc_a_chunk(stcb, a_chk);
10385                 if (a_chk == NULL) {
10386                         /* No memory so we drop the idea, and set a timer */
10387                         if (stcb->asoc.delayed_ack) {
10388                                 sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
10389                                     stcb->sctp_ep, stcb, NULL, SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_5);
10390                                 sctp_timer_start(SCTP_TIMER_TYPE_RECV,
10391                                     stcb->sctp_ep, stcb, NULL);
10392                         } else {
10393                                 stcb->asoc.send_sack = 1;
10394                         }
10395                         return;
10396                 }
10397                 a_chk->copy_by_ref = 0;
10398                 a_chk->rec.chunk_id.id = type;
10399                 a_chk->rec.chunk_id.can_take_data = 1;
10400         }
10401         /* Clear our pkt counts */
10402         asoc->data_pkts_seen = 0;
10403
10404         a_chk->asoc = asoc;
10405         a_chk->snd_count = 0;
10406         a_chk->send_size = 0;   /* fill in later */
10407         a_chk->sent = SCTP_DATAGRAM_UNSENT;
10408         a_chk->whoTo = NULL;
10409
10410         if ((asoc->numduptsns) ||
10411             (!(asoc->last_data_chunk_from->dest_state & SCTP_ADDR_REACHABLE))) {
10412                 /*-
10413                  * Ok, we have some duplicates or the destination for the
10414                  * sack is unreachable, lets see if we can select an
10415                  * alternate than asoc->last_data_chunk_from
10416                  */
10417                 if ((asoc->last_data_chunk_from->dest_state & SCTP_ADDR_REACHABLE) &&
10418                     (asoc->used_alt_onsack > asoc->numnets)) {
10419                         /* We used an alt last time, don't this time */
10420                         a_chk->whoTo = NULL;
10421                 } else {
10422                         asoc->used_alt_onsack++;
10423                         a_chk->whoTo = sctp_find_alternate_net(stcb, asoc->last_data_chunk_from, 0);
10424                 }
10425                 if (a_chk->whoTo == NULL) {
10426                         /* Nope, no alternate */
10427                         a_chk->whoTo = asoc->last_data_chunk_from;
10428                         asoc->used_alt_onsack = 0;
10429                 }
10430         } else {
10431                 /*
10432                  * No duplicates so we use the last place we received data
10433                  * from.
10434                  */
10435                 asoc->used_alt_onsack = 0;
10436                 a_chk->whoTo = asoc->last_data_chunk_from;
10437         }
10438         if (a_chk->whoTo) {
10439                 atomic_add_int(&a_chk->whoTo->ref_count, 1);
10440         }
10441         if (SCTP_TSN_GT(asoc->highest_tsn_inside_map, asoc->highest_tsn_inside_nr_map)) {
10442                 highest_tsn = asoc->highest_tsn_inside_map;
10443         } else {
10444                 highest_tsn = asoc->highest_tsn_inside_nr_map;
10445         }
10446         if (highest_tsn == asoc->cumulative_tsn) {
10447                 /* no gaps */
10448                 if (type == SCTP_SELECTIVE_ACK) {
10449                         space_req = sizeof(struct sctp_sack_chunk);
10450                 } else {
10451                         space_req = sizeof(struct sctp_nr_sack_chunk);
10452                 }
10453         } else {
10454                 /* gaps get a cluster */
10455                 space_req = MCLBYTES;
10456         }
10457         /* Ok now lets formulate a MBUF with our sack */
10458         a_chk->data = sctp_get_mbuf_for_msg(space_req, 0, M_DONTWAIT, 1, MT_DATA);
10459         if ((a_chk->data == NULL) ||
10460             (a_chk->whoTo == NULL)) {
10461                 /* rats, no mbuf memory */
10462                 if (a_chk->data) {
10463                         /* was a problem with the destination */
10464                         sctp_m_freem(a_chk->data);
10465                         a_chk->data = NULL;
10466                 }
10467                 sctp_free_a_chunk(stcb, a_chk, so_locked);
10468                 /* sa_ignore NO_NULL_CHK */
10469                 if (stcb->asoc.delayed_ack) {
10470                         sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
10471                             stcb->sctp_ep, stcb, NULL, SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_6);
10472                         sctp_timer_start(SCTP_TIMER_TYPE_RECV,
10473                             stcb->sctp_ep, stcb, NULL);
10474                 } else {
10475                         stcb->asoc.send_sack = 1;
10476                 }
10477                 return;
10478         }
10479         /* ok, lets go through and fill it in */
10480         SCTP_BUF_RESV_UF(a_chk->data, SCTP_MIN_OVERHEAD);
10481         space = M_TRAILINGSPACE(a_chk->data);
10482         if (space > (a_chk->whoTo->mtu - SCTP_MIN_OVERHEAD)) {
10483                 space = (a_chk->whoTo->mtu - SCTP_MIN_OVERHEAD);
10484         }
10485         limit = mtod(a_chk->data, caddr_t);
10486         limit += space;
10487
10488         flags = 0;
10489
10490         if ((asoc->sctp_cmt_on_off > 0) &&
10491             SCTP_BASE_SYSCTL(sctp_cmt_use_dac)) {
10492                 /*-
10493                  * CMT DAC algorithm: If 2 (i.e., 0x10) packets have been
10494                  * received, then set high bit to 1, else 0. Reset
10495                  * pkts_rcvd.
10496                  */
10497                 flags |= (asoc->cmt_dac_pkts_rcvd << 6);
10498                 asoc->cmt_dac_pkts_rcvd = 0;
10499         }
10500 #ifdef SCTP_ASOCLOG_OF_TSNS
10501         stcb->asoc.cumack_logsnt[stcb->asoc.cumack_log_atsnt] = asoc->cumulative_tsn;
10502         stcb->asoc.cumack_log_atsnt++;
10503         if (stcb->asoc.cumack_log_atsnt >= SCTP_TSN_LOG_SIZE) {
10504                 stcb->asoc.cumack_log_atsnt = 0;
10505         }
10506 #endif
10507         /* reset the readers interpretation */
10508         stcb->freed_by_sorcv_sincelast = 0;
10509
10510         if (type == SCTP_SELECTIVE_ACK) {
10511                 sack = mtod(a_chk->data, struct sctp_sack_chunk *);
10512                 nr_sack = NULL;
10513                 gap_descriptor = (struct sctp_gap_ack_block *)((caddr_t)sack + sizeof(struct sctp_sack_chunk));
10514                 if (highest_tsn > asoc->mapping_array_base_tsn) {
10515                         siz = (((highest_tsn - asoc->mapping_array_base_tsn) + 1) + 7) / 8;
10516                 } else {
10517                         siz = (((MAX_TSN - highest_tsn) + 1) + highest_tsn + 7) / 8;
10518                 }
10519         } else {
10520                 sack = NULL;
10521                 nr_sack = mtod(a_chk->data, struct sctp_nr_sack_chunk *);
10522                 gap_descriptor = (struct sctp_gap_ack_block *)((caddr_t)nr_sack + sizeof(struct sctp_nr_sack_chunk));
10523                 if (asoc->highest_tsn_inside_map > asoc->mapping_array_base_tsn) {
10524                         siz = (((asoc->highest_tsn_inside_map - asoc->mapping_array_base_tsn) + 1) + 7) / 8;
10525                 } else {
10526                         siz = (((MAX_TSN - asoc->mapping_array_base_tsn) + 1) + asoc->highest_tsn_inside_map + 7) / 8;
10527                 }
10528         }
10529
10530         if (SCTP_TSN_GT(asoc->mapping_array_base_tsn, asoc->cumulative_tsn)) {
10531                 offset = 1;
10532         } else {
10533                 offset = asoc->mapping_array_base_tsn - asoc->cumulative_tsn;
10534         }
10535         if (((type == SCTP_SELECTIVE_ACK) &&
10536             SCTP_TSN_GT(highest_tsn, asoc->cumulative_tsn)) ||
10537             ((type == SCTP_NR_SELECTIVE_ACK) &&
10538             SCTP_TSN_GT(asoc->highest_tsn_inside_map, asoc->cumulative_tsn))) {
10539                 /* we have a gap .. maybe */
10540                 for (i = 0; i < siz; i++) {
10541                         tsn_map = asoc->mapping_array[i];
10542                         if (type == SCTP_SELECTIVE_ACK) {
10543                                 tsn_map |= asoc->nr_mapping_array[i];
10544                         }
10545                         if (i == 0) {
10546                                 /*
10547                                  * Clear all bits corresponding to TSNs
10548                                  * smaller or equal to the cumulative TSN.
10549                                  */
10550                                 tsn_map &= (~0 << (1 - offset));
10551                         }
10552                         selector = &sack_array[tsn_map];
10553                         if (mergeable && selector->right_edge) {
10554                                 /*
10555                                  * Backup, left and right edges were ok to
10556                                  * merge.
10557                                  */
10558                                 num_gap_blocks--;
10559                                 gap_descriptor--;
10560                         }
10561                         if (selector->num_entries == 0)
10562                                 mergeable = 0;
10563                         else {
10564                                 for (j = 0; j < selector->num_entries; j++) {
10565                                         if (mergeable && selector->right_edge) {
10566                                                 /*
10567                                                  * do a merge by NOT setting
10568                                                  * the left side
10569                                                  */
10570                                                 mergeable = 0;
10571                                         } else {
10572                                                 /*
10573                                                  * no merge, set the left
10574                                                  * side
10575                                                  */
10576                                                 mergeable = 0;
10577                                                 gap_descriptor->start = htons((selector->gaps[j].start + offset));
10578                                         }
10579                                         gap_descriptor->end = htons((selector->gaps[j].end + offset));
10580                                         num_gap_blocks++;
10581                                         gap_descriptor++;
10582                                         if (((caddr_t)gap_descriptor + sizeof(struct sctp_gap_ack_block)) > limit) {
10583                                                 /* no more room */
10584                                                 limit_reached = 1;
10585                                                 break;
10586                                         }
10587                                 }
10588                                 if (selector->left_edge) {
10589                                         mergeable = 1;
10590                                 }
10591                         }
10592                         if (limit_reached) {
10593                                 /* Reached the limit stop */
10594                                 break;
10595                         }
10596                         offset += 8;
10597                 }
10598         }
10599         if ((type == SCTP_NR_SELECTIVE_ACK) &&
10600             (limit_reached == 0)) {
10601
10602                 mergeable = 0;
10603
10604                 if (asoc->highest_tsn_inside_nr_map > asoc->mapping_array_base_tsn) {
10605                         siz = (((asoc->highest_tsn_inside_nr_map - asoc->mapping_array_base_tsn) + 1) + 7) / 8;
10606                 } else {
10607                         siz = (((MAX_TSN - asoc->mapping_array_base_tsn) + 1) + asoc->highest_tsn_inside_nr_map + 7) / 8;
10608                 }
10609
10610                 if (SCTP_TSN_GT(asoc->mapping_array_base_tsn, asoc->cumulative_tsn)) {
10611                         offset = 1;
10612                 } else {
10613                         offset = asoc->mapping_array_base_tsn - asoc->cumulative_tsn;
10614                 }
10615                 if (SCTP_TSN_GT(asoc->highest_tsn_inside_nr_map, asoc->cumulative_tsn)) {
10616                         /* we have a gap .. maybe */
10617                         for (i = 0; i < siz; i++) {
10618                                 tsn_map = asoc->nr_mapping_array[i];
10619                                 if (i == 0) {
10620                                         /*
10621                                          * Clear all bits corresponding to
10622                                          * TSNs smaller or equal to the
10623                                          * cumulative TSN.
10624                                          */
10625                                         tsn_map &= (~0 << (1 - offset));
10626                                 }
10627                                 selector = &sack_array[tsn_map];
10628                                 if (mergeable && selector->right_edge) {
10629                                         /*
10630                                          * Backup, left and right edges were
10631                                          * ok to merge.
10632                                          */
10633                                         num_nr_gap_blocks--;
10634                                         gap_descriptor--;
10635                                 }
10636                                 if (selector->num_entries == 0)
10637                                         mergeable = 0;
10638                                 else {
10639                                         for (j = 0; j < selector->num_entries; j++) {
10640                                                 if (mergeable && selector->right_edge) {
10641                                                         /*
10642                                                          * do a merge by NOT
10643                                                          * setting the left
10644                                                          * side
10645                                                          */
10646                                                         mergeable = 0;
10647                                                 } else {
10648                                                         /*
10649                                                          * no merge, set the
10650                                                          * left side
10651                                                          */
10652                                                         mergeable = 0;
10653                                                         gap_descriptor->start = htons((selector->gaps[j].start + offset));
10654                                                 }
10655                                                 gap_descriptor->end = htons((selector->gaps[j].end + offset));
10656                                                 num_nr_gap_blocks++;
10657                                                 gap_descriptor++;
10658                                                 if (((caddr_t)gap_descriptor + sizeof(struct sctp_gap_ack_block)) > limit) {
10659                                                         /* no more room */
10660                                                         limit_reached = 1;
10661                                                         break;
10662                                                 }
10663                                         }
10664                                         if (selector->left_edge) {
10665                                                 mergeable = 1;
10666                                         }
10667                                 }
10668                                 if (limit_reached) {
10669                                         /* Reached the limit stop */
10670                                         break;
10671                                 }
10672                                 offset += 8;
10673                         }
10674                 }
10675         }
10676         /* now we must add any dups we are going to report. */
10677         if ((limit_reached == 0) && (asoc->numduptsns)) {
10678                 dup = (uint32_t *) gap_descriptor;
10679                 for (i = 0; i < asoc->numduptsns; i++) {
10680                         *dup = htonl(asoc->dup_tsns[i]);
10681                         dup++;
10682                         num_dups++;
10683                         if (((caddr_t)dup + sizeof(uint32_t)) > limit) {
10684                                 /* no more room */
10685                                 break;
10686                         }
10687                 }
10688                 asoc->numduptsns = 0;
10689         }
10690         /*
10691          * now that the chunk is prepared queue it to the control chunk
10692          * queue.
10693          */
10694         if (type == SCTP_SELECTIVE_ACK) {
10695                 a_chk->send_size = sizeof(struct sctp_sack_chunk) +
10696                     (num_gap_blocks + num_nr_gap_blocks) * sizeof(struct sctp_gap_ack_block) +
10697                     num_dups * sizeof(int32_t);
10698                 SCTP_BUF_LEN(a_chk->data) = a_chk->send_size;
10699                 sack->sack.cum_tsn_ack = htonl(asoc->cumulative_tsn);
10700                 sack->sack.a_rwnd = htonl(asoc->my_rwnd);
10701                 sack->sack.num_gap_ack_blks = htons(num_gap_blocks);
10702                 sack->sack.num_dup_tsns = htons(num_dups);
10703                 sack->ch.chunk_type = type;
10704                 sack->ch.chunk_flags = flags;
10705                 sack->ch.chunk_length = htons(a_chk->send_size);
10706         } else {
10707                 a_chk->send_size = sizeof(struct sctp_nr_sack_chunk) +
10708                     (num_gap_blocks + num_nr_gap_blocks) * sizeof(struct sctp_gap_ack_block) +
10709                     num_dups * sizeof(int32_t);
10710                 SCTP_BUF_LEN(a_chk->data) = a_chk->send_size;
10711                 nr_sack->nr_sack.cum_tsn_ack = htonl(asoc->cumulative_tsn);
10712                 nr_sack->nr_sack.a_rwnd = htonl(asoc->my_rwnd);
10713                 nr_sack->nr_sack.num_gap_ack_blks = htons(num_gap_blocks);
10714                 nr_sack->nr_sack.num_nr_gap_ack_blks = htons(num_nr_gap_blocks);
10715                 nr_sack->nr_sack.num_dup_tsns = htons(num_dups);
10716                 nr_sack->nr_sack.reserved = 0;
10717                 nr_sack->ch.chunk_type = type;
10718                 nr_sack->ch.chunk_flags = flags;
10719                 nr_sack->ch.chunk_length = htons(a_chk->send_size);
10720         }
10721         TAILQ_INSERT_TAIL(&asoc->control_send_queue, a_chk, sctp_next);
10722         asoc->my_last_reported_rwnd = asoc->my_rwnd;
10723         asoc->ctrl_queue_cnt++;
10724         asoc->send_sack = 0;
10725         SCTP_STAT_INCR(sctps_sendsacks);
10726         return;
10727 }
10728
10729 void
10730 sctp_send_abort_tcb(struct sctp_tcb *stcb, struct mbuf *operr, int so_locked
10731 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
10732     SCTP_UNUSED
10733 #endif
10734 )
10735 {
10736         struct mbuf *m_abort, *m, *m_last;
10737         struct mbuf *m_out, *m_end = NULL;
10738         struct sctp_abort_chunk *abort;
10739         struct sctp_auth_chunk *auth = NULL;
10740         struct sctp_nets *net;
10741         uint32_t auth_offset = 0;
10742         uint16_t cause_len, chunk_len, padding_len;
10743
10744         SCTP_TCB_LOCK_ASSERT(stcb);
10745         /*-
10746          * Add an AUTH chunk, if chunk requires it and save the offset into
10747          * the chain for AUTH
10748          */
10749         if (sctp_auth_is_required_chunk(SCTP_ABORT_ASSOCIATION,
10750             stcb->asoc.peer_auth_chunks)) {
10751                 m_out = sctp_add_auth_chunk(NULL, &m_end, &auth, &auth_offset,
10752                     stcb, SCTP_ABORT_ASSOCIATION);
10753                 SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
10754         } else {
10755                 m_out = NULL;
10756         }
10757         m_abort = sctp_get_mbuf_for_msg(sizeof(struct sctp_abort_chunk), 0, M_DONTWAIT, 1, MT_HEADER);
10758         if (m_abort == NULL) {
10759                 if (m_out) {
10760                         sctp_m_freem(m_out);
10761                 }
10762                 if (operr) {
10763                         sctp_m_freem(operr);
10764                 }
10765                 return;
10766         }
10767         /* link in any error */
10768         SCTP_BUF_NEXT(m_abort) = operr;
10769         cause_len = 0;
10770         m_last = NULL;
10771         for (m = operr; m; m = SCTP_BUF_NEXT(m)) {
10772                 cause_len += (uint16_t) SCTP_BUF_LEN(m);
10773                 if (SCTP_BUF_NEXT(m) == NULL) {
10774                         m_last = m;
10775                 }
10776         }
10777         SCTP_BUF_LEN(m_abort) = sizeof(struct sctp_abort_chunk);
10778         chunk_len = (uint16_t) sizeof(struct sctp_abort_chunk) + cause_len;
10779         padding_len = SCTP_SIZE32(chunk_len) - chunk_len;
10780         if (m_out == NULL) {
10781                 /* NO Auth chunk prepended, so reserve space in front */
10782                 SCTP_BUF_RESV_UF(m_abort, SCTP_MIN_OVERHEAD);
10783                 m_out = m_abort;
10784         } else {
10785                 /* Put AUTH chunk at the front of the chain */
10786                 SCTP_BUF_NEXT(m_end) = m_abort;
10787         }
10788         if (stcb->asoc.alternate) {
10789                 net = stcb->asoc.alternate;
10790         } else {
10791                 net = stcb->asoc.primary_destination;
10792         }
10793         /* Fill in the ABORT chunk header. */
10794         abort = mtod(m_abort, struct sctp_abort_chunk *);
10795         abort->ch.chunk_type = SCTP_ABORT_ASSOCIATION;
10796         abort->ch.chunk_flags = 0;
10797         abort->ch.chunk_length = htons(chunk_len);
10798         /* Add padding, if necessary. */
10799         if (padding_len > 0) {
10800                 if ((m_last == NULL) || sctp_add_pad_tombuf(m_last, padding_len)) {
10801                         sctp_m_freem(m_out);
10802                         return;
10803                 }
10804         }
10805         (void)sctp_lowlevel_chunk_output(stcb->sctp_ep, stcb, net,
10806             (struct sockaddr *)&net->ro._l_addr,
10807             m_out, auth_offset, auth, stcb->asoc.authinfo.active_keyid, 1, 0, 0,
10808             stcb->sctp_ep->sctp_lport, stcb->rport, htonl(stcb->asoc.peer_vtag),
10809             stcb->asoc.primary_destination->port, NULL,
10810             0, 0,
10811             so_locked);
10812         SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
10813 }
10814
10815 void
10816 sctp_send_shutdown_complete(struct sctp_tcb *stcb,
10817     struct sctp_nets *net,
10818     int reflect_vtag)
10819 {
10820         /* formulate and SEND a SHUTDOWN-COMPLETE */
10821         struct mbuf *m_shutdown_comp;
10822         struct sctp_shutdown_complete_chunk *shutdown_complete;
10823         uint32_t vtag;
10824         uint8_t flags;
10825
10826         m_shutdown_comp = sctp_get_mbuf_for_msg(sizeof(struct sctp_chunkhdr), 0, M_DONTWAIT, 1, MT_HEADER);
10827         if (m_shutdown_comp == NULL) {
10828                 /* no mbuf's */
10829                 return;
10830         }
10831         if (reflect_vtag) {
10832                 flags = SCTP_HAD_NO_TCB;
10833                 vtag = stcb->asoc.my_vtag;
10834         } else {
10835                 flags = 0;
10836                 vtag = stcb->asoc.peer_vtag;
10837         }
10838         shutdown_complete = mtod(m_shutdown_comp, struct sctp_shutdown_complete_chunk *);
10839         shutdown_complete->ch.chunk_type = SCTP_SHUTDOWN_COMPLETE;
10840         shutdown_complete->ch.chunk_flags = flags;
10841         shutdown_complete->ch.chunk_length = htons(sizeof(struct sctp_shutdown_complete_chunk));
10842         SCTP_BUF_LEN(m_shutdown_comp) = sizeof(struct sctp_shutdown_complete_chunk);
10843         (void)sctp_lowlevel_chunk_output(stcb->sctp_ep, stcb, net,
10844             (struct sockaddr *)&net->ro._l_addr,
10845             m_shutdown_comp, 0, NULL, 0, 1, 0, 0,
10846             stcb->sctp_ep->sctp_lport, stcb->rport,
10847             htonl(vtag),
10848             net->port, NULL,
10849             0, 0,
10850             SCTP_SO_NOT_LOCKED);
10851         SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
10852         return;
10853 }
10854
10855 static void
10856 sctp_send_resp_msg(struct sockaddr *src, struct sockaddr *dst,
10857     struct sctphdr *sh, uint32_t vtag,
10858     uint8_t type, struct mbuf *cause,
10859     uint8_t use_mflowid, uint32_t mflowid,
10860     uint32_t vrf_id, uint16_t port)
10861 {
10862         struct mbuf *o_pak;
10863         struct mbuf *mout;
10864         struct sctphdr *shout;
10865         struct sctp_chunkhdr *ch;
10866         struct udphdr *udp;
10867         int len, cause_len, padding_len, ret;
10868
10869 #ifdef INET
10870         struct sockaddr_in *src_sin, *dst_sin;
10871         struct ip *ip;
10872
10873 #endif
10874 #ifdef INET6
10875         struct sockaddr_in6 *src_sin6, *dst_sin6;
10876         struct ip6_hdr *ip6;
10877
10878 #endif
10879
10880         /* Compute the length of the cause and add final padding. */
10881         cause_len = 0;
10882         if (cause != NULL) {
10883                 struct mbuf *m_at, *m_last = NULL;
10884
10885                 for (m_at = cause; m_at; m_at = SCTP_BUF_NEXT(m_at)) {
10886                         if (SCTP_BUF_NEXT(m_at) == NULL)
10887                                 m_last = m_at;
10888                         cause_len += SCTP_BUF_LEN(m_at);
10889                 }
10890                 padding_len = cause_len % 4;
10891                 if (padding_len != 0) {
10892                         padding_len = 4 - padding_len;
10893                 }
10894                 if (padding_len != 0) {
10895                         if (sctp_add_pad_tombuf(m_last, padding_len)) {
10896                                 sctp_m_freem(cause);
10897                                 return;
10898                         }
10899                 }
10900         } else {
10901                 padding_len = 0;
10902         }
10903         /* Get an mbuf for the header. */
10904         len = sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
10905         switch (dst->sa_family) {
10906 #ifdef INET
10907         case AF_INET:
10908                 len += sizeof(struct ip);
10909                 break;
10910 #endif
10911 #ifdef INET6
10912         case AF_INET6:
10913                 len += sizeof(struct ip6_hdr);
10914                 break;
10915 #endif
10916         default:
10917                 break;
10918         }
10919         if (port) {
10920                 len += sizeof(struct udphdr);
10921         }
10922         mout = sctp_get_mbuf_for_msg(len + max_linkhdr, 1, M_DONTWAIT, 1, MT_DATA);
10923         if (mout == NULL) {
10924                 if (cause) {
10925                         sctp_m_freem(cause);
10926                 }
10927                 return;
10928         }
10929         SCTP_BUF_RESV_UF(mout, max_linkhdr);
10930         SCTP_BUF_LEN(mout) = len;
10931         SCTP_BUF_NEXT(mout) = cause;
10932         if (use_mflowid != 0) {
10933                 mout->m_pkthdr.flowid = mflowid;
10934                 mout->m_flags |= M_FLOWID;
10935         }
10936 #ifdef INET
10937         ip = NULL;
10938 #endif
10939 #ifdef INET6
10940         ip6 = NULL;
10941 #endif
10942         switch (dst->sa_family) {
10943 #ifdef INET
10944         case AF_INET:
10945                 src_sin = (struct sockaddr_in *)src;
10946                 dst_sin = (struct sockaddr_in *)dst;
10947                 ip = mtod(mout, struct ip *);
10948                 ip->ip_v = IPVERSION;
10949                 ip->ip_hl = (sizeof(struct ip) >> 2);
10950                 ip->ip_tos = 0;
10951                 ip->ip_id = ip_newid();
10952                 ip->ip_off = 0;
10953                 ip->ip_ttl = MODULE_GLOBAL(ip_defttl);
10954                 if (port) {
10955                         ip->ip_p = IPPROTO_UDP;
10956                 } else {
10957                         ip->ip_p = IPPROTO_SCTP;
10958                 }
10959                 ip->ip_src.s_addr = dst_sin->sin_addr.s_addr;
10960                 ip->ip_dst.s_addr = src_sin->sin_addr.s_addr;
10961                 ip->ip_sum = 0;
10962                 len = sizeof(struct ip);
10963                 shout = (struct sctphdr *)((caddr_t)ip + len);
10964                 break;
10965 #endif
10966 #ifdef INET6
10967         case AF_INET6:
10968                 src_sin6 = (struct sockaddr_in6 *)src;
10969                 dst_sin6 = (struct sockaddr_in6 *)dst;
10970                 ip6 = mtod(mout, struct ip6_hdr *);
10971                 ip6->ip6_flow = htonl(0x60000000);
10972                 if (V_ip6_auto_flowlabel) {
10973                         ip6->ip6_flow |= (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
10974                 }
10975                 ip6->ip6_hlim = MODULE_GLOBAL(ip6_defhlim);
10976                 if (port) {
10977                         ip6->ip6_nxt = IPPROTO_UDP;
10978                 } else {
10979                         ip6->ip6_nxt = IPPROTO_SCTP;
10980                 }
10981                 ip6->ip6_src = dst_sin6->sin6_addr;
10982                 ip6->ip6_dst = src_sin6->sin6_addr;
10983                 len = sizeof(struct ip6_hdr);
10984                 shout = (struct sctphdr *)((caddr_t)ip6 + len);
10985                 break;
10986 #endif
10987         default:
10988                 len = 0;
10989                 shout = mtod(mout, struct sctphdr *);
10990                 break;
10991         }
10992         if (port) {
10993                 if (htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port)) == 0) {
10994                         sctp_m_freem(mout);
10995                         return;
10996                 }
10997                 udp = (struct udphdr *)shout;
10998                 udp->uh_sport = htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port));
10999                 udp->uh_dport = port;
11000                 udp->uh_sum = 0;
11001                 udp->uh_ulen = htons(sizeof(struct udphdr) +
11002                     sizeof(struct sctphdr) +
11003                     sizeof(struct sctp_chunkhdr) +
11004                     cause_len + padding_len);
11005                 len += sizeof(struct udphdr);
11006                 shout = (struct sctphdr *)((caddr_t)shout + sizeof(struct udphdr));
11007         } else {
11008                 udp = NULL;
11009         }
11010         shout->src_port = sh->dest_port;
11011         shout->dest_port = sh->src_port;
11012         shout->checksum = 0;
11013         if (vtag) {
11014                 shout->v_tag = htonl(vtag);
11015         } else {
11016                 shout->v_tag = sh->v_tag;
11017         }
11018         len += sizeof(struct sctphdr);
11019         ch = (struct sctp_chunkhdr *)((caddr_t)shout + sizeof(struct sctphdr));
11020         ch->chunk_type = type;
11021         if (vtag) {
11022                 ch->chunk_flags = 0;
11023         } else {
11024                 ch->chunk_flags = SCTP_HAD_NO_TCB;
11025         }
11026         ch->chunk_length = htons(sizeof(struct sctp_chunkhdr) + cause_len);
11027         len += sizeof(struct sctp_chunkhdr);
11028         len += cause_len + padding_len;
11029
11030         if (SCTP_GET_HEADER_FOR_OUTPUT(o_pak)) {
11031                 sctp_m_freem(mout);
11032                 return;
11033         }
11034         SCTP_ATTACH_CHAIN(o_pak, mout, len);
11035         switch (dst->sa_family) {
11036 #ifdef INET
11037         case AF_INET:
11038                 if (port) {
11039                         if (V_udp_cksum) {
11040                                 udp->uh_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr, udp->uh_ulen + htons(IPPROTO_UDP));
11041                         } else {
11042                                 udp->uh_sum = 0;
11043                         }
11044                 }
11045                 ip->ip_len = len;
11046                 if (port) {
11047 #if defined(SCTP_WITH_NO_CSUM)
11048                         SCTP_STAT_INCR(sctps_sendnocrc);
11049 #else
11050                         shout->checksum = sctp_calculate_cksum(mout, sizeof(struct ip) + sizeof(struct udphdr));
11051                         SCTP_STAT_INCR(sctps_sendswcrc);
11052 #endif
11053                         if (V_udp_cksum) {
11054                                 SCTP_ENABLE_UDP_CSUM(o_pak);
11055                         }
11056                 } else {
11057 #if defined(SCTP_WITH_NO_CSUM)
11058                         SCTP_STAT_INCR(sctps_sendnocrc);
11059 #else
11060                         mout->m_pkthdr.csum_flags = CSUM_SCTP;
11061                         mout->m_pkthdr.csum_data = 0;
11062                         SCTP_STAT_INCR(sctps_sendhwcrc);
11063 #endif
11064                 }
11065 #ifdef SCTP_PACKET_LOGGING
11066                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LAST_PACKET_TRACING) {
11067                         sctp_packet_log(o_pak);
11068                 }
11069 #endif
11070                 SCTP_IP_OUTPUT(ret, o_pak, NULL, NULL, vrf_id);
11071                 break;
11072 #endif
11073 #ifdef INET6
11074         case AF_INET6:
11075                 ip6->ip6_plen = len - sizeof(struct ip6_hdr);
11076                 if (port) {
11077 #if defined(SCTP_WITH_NO_CSUM)
11078                         SCTP_STAT_INCR(sctps_sendnocrc);
11079 #else
11080                         shout->checksum = sctp_calculate_cksum(mout, sizeof(struct ip6_hdr) + sizeof(struct udphdr));
11081                         SCTP_STAT_INCR(sctps_sendswcrc);
11082 #endif
11083                         if ((udp->uh_sum = in6_cksum(o_pak, IPPROTO_UDP, sizeof(struct ip6_hdr), len - sizeof(struct ip6_hdr))) == 0) {
11084                                 udp->uh_sum = 0xffff;
11085                         }
11086                 } else {
11087 #if defined(SCTP_WITH_NO_CSUM)
11088                         SCTP_STAT_INCR(sctps_sendnocrc);
11089 #else
11090                         mout->m_pkthdr.csum_flags = CSUM_SCTP_IPV6;
11091                         mout->m_pkthdr.csum_data = 0;
11092                         SCTP_STAT_INCR(sctps_sendhwcrc);
11093 #endif
11094                 }
11095 #ifdef SCTP_PACKET_LOGGING
11096                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LAST_PACKET_TRACING) {
11097                         sctp_packet_log(o_pak);
11098                 }
11099 #endif
11100                 SCTP_IP6_OUTPUT(ret, o_pak, NULL, NULL, NULL, vrf_id);
11101                 break;
11102 #endif
11103         default:
11104                 SCTPDBG(SCTP_DEBUG_OUTPUT1, "Unknown protocol (TSNH) type %d\n",
11105                     dst->sa_family);
11106                 sctp_m_freem(mout);
11107                 SCTP_LTRACE_ERR_RET_PKT(mout, NULL, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, EFAULT);
11108                 return;
11109         }
11110         SCTP_STAT_INCR(sctps_sendpackets);
11111         SCTP_STAT_INCR_COUNTER64(sctps_outpackets);
11112         SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
11113         return;
11114 }
11115
11116 void
11117 sctp_send_shutdown_complete2(struct sockaddr *src, struct sockaddr *dst,
11118     struct sctphdr *sh,
11119     uint8_t use_mflowid, uint32_t mflowid,
11120     uint32_t vrf_id, uint16_t port)
11121 {
11122         sctp_send_resp_msg(src, dst, sh, 0, SCTP_SHUTDOWN_COMPLETE, NULL,
11123             use_mflowid, mflowid,
11124             vrf_id, port);
11125 }
11126
11127 void
11128 sctp_send_hb(struct sctp_tcb *stcb, struct sctp_nets *net, int so_locked
11129 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
11130     SCTP_UNUSED
11131 #endif
11132 )
11133 {
11134         struct sctp_tmit_chunk *chk;
11135         struct sctp_heartbeat_chunk *hb;
11136         struct timeval now;
11137
11138         SCTP_TCB_LOCK_ASSERT(stcb);
11139         if (net == NULL) {
11140                 return;
11141         }
11142         (void)SCTP_GETTIME_TIMEVAL(&now);
11143         switch (net->ro._l_addr.sa.sa_family) {
11144 #ifdef INET
11145         case AF_INET:
11146                 break;
11147 #endif
11148 #ifdef INET6
11149         case AF_INET6:
11150                 break;
11151 #endif
11152         default:
11153                 return;
11154         }
11155         sctp_alloc_a_chunk(stcb, chk);
11156         if (chk == NULL) {
11157                 SCTPDBG(SCTP_DEBUG_OUTPUT4, "Gak, can't get a chunk for hb\n");
11158                 return;
11159         }
11160         chk->copy_by_ref = 0;
11161         chk->rec.chunk_id.id = SCTP_HEARTBEAT_REQUEST;
11162         chk->rec.chunk_id.can_take_data = 1;
11163         chk->asoc = &stcb->asoc;
11164         chk->send_size = sizeof(struct sctp_heartbeat_chunk);
11165
11166         chk->data = sctp_get_mbuf_for_msg(chk->send_size, 0, M_DONTWAIT, 1, MT_HEADER);
11167         if (chk->data == NULL) {
11168                 sctp_free_a_chunk(stcb, chk, so_locked);
11169                 return;
11170         }
11171         SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
11172         SCTP_BUF_LEN(chk->data) = chk->send_size;
11173         chk->sent = SCTP_DATAGRAM_UNSENT;
11174         chk->snd_count = 0;
11175         chk->whoTo = net;
11176         atomic_add_int(&chk->whoTo->ref_count, 1);
11177         /* Now we have a mbuf that we can fill in with the details */
11178         hb = mtod(chk->data, struct sctp_heartbeat_chunk *);
11179         memset(hb, 0, sizeof(struct sctp_heartbeat_chunk));
11180         /* fill out chunk header */
11181         hb->ch.chunk_type = SCTP_HEARTBEAT_REQUEST;
11182         hb->ch.chunk_flags = 0;
11183         hb->ch.chunk_length = htons(chk->send_size);
11184         /* Fill out hb parameter */
11185         hb->heartbeat.hb_info.ph.param_type = htons(SCTP_HEARTBEAT_INFO);
11186         hb->heartbeat.hb_info.ph.param_length = htons(sizeof(struct sctp_heartbeat_info_param));
11187         hb->heartbeat.hb_info.time_value_1 = now.tv_sec;
11188         hb->heartbeat.hb_info.time_value_2 = now.tv_usec;
11189         /* Did our user request this one, put it in */
11190         hb->heartbeat.hb_info.addr_family = net->ro._l_addr.sa.sa_family;
11191         hb->heartbeat.hb_info.addr_len = net->ro._l_addr.sa.sa_len;
11192         if (net->dest_state & SCTP_ADDR_UNCONFIRMED) {
11193                 /*
11194                  * we only take from the entropy pool if the address is not
11195                  * confirmed.
11196                  */
11197                 net->heartbeat_random1 = hb->heartbeat.hb_info.random_value1 = sctp_select_initial_TSN(&stcb->sctp_ep->sctp_ep);
11198                 net->heartbeat_random2 = hb->heartbeat.hb_info.random_value2 = sctp_select_initial_TSN(&stcb->sctp_ep->sctp_ep);
11199         } else {
11200                 net->heartbeat_random1 = hb->heartbeat.hb_info.random_value1 = 0;
11201                 net->heartbeat_random2 = hb->heartbeat.hb_info.random_value2 = 0;
11202         }
11203         switch (net->ro._l_addr.sa.sa_family) {
11204 #ifdef INET
11205         case AF_INET:
11206                 memcpy(hb->heartbeat.hb_info.address,
11207                     &net->ro._l_addr.sin.sin_addr,
11208                     sizeof(net->ro._l_addr.sin.sin_addr));
11209                 break;
11210 #endif
11211 #ifdef INET6
11212         case AF_INET6:
11213                 memcpy(hb->heartbeat.hb_info.address,
11214                     &net->ro._l_addr.sin6.sin6_addr,
11215                     sizeof(net->ro._l_addr.sin6.sin6_addr));
11216                 break;
11217 #endif
11218         default:
11219                 return;
11220                 break;
11221         }
11222         net->hb_responded = 0;
11223         TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
11224         stcb->asoc.ctrl_queue_cnt++;
11225         SCTP_STAT_INCR(sctps_sendheartbeat);
11226         return;
11227 }
11228
11229 void
11230 sctp_send_ecn_echo(struct sctp_tcb *stcb, struct sctp_nets *net,
11231     uint32_t high_tsn)
11232 {
11233         struct sctp_association *asoc;
11234         struct sctp_ecne_chunk *ecne;
11235         struct sctp_tmit_chunk *chk;
11236
11237         if (net == NULL) {
11238                 return;
11239         }
11240         asoc = &stcb->asoc;
11241         SCTP_TCB_LOCK_ASSERT(stcb);
11242         TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
11243                 if ((chk->rec.chunk_id.id == SCTP_ECN_ECHO) && (net == chk->whoTo)) {
11244                         /* found a previous ECN_ECHO update it if needed */
11245                         uint32_t cnt, ctsn;
11246
11247                         ecne = mtod(chk->data, struct sctp_ecne_chunk *);
11248                         ctsn = ntohl(ecne->tsn);
11249                         if (SCTP_TSN_GT(high_tsn, ctsn)) {
11250                                 ecne->tsn = htonl(high_tsn);
11251                                 SCTP_STAT_INCR(sctps_queue_upd_ecne);
11252                         }
11253                         cnt = ntohl(ecne->num_pkts_since_cwr);
11254                         cnt++;
11255                         ecne->num_pkts_since_cwr = htonl(cnt);
11256                         return;
11257                 }
11258         }
11259         /* nope could not find one to update so we must build one */
11260         sctp_alloc_a_chunk(stcb, chk);
11261         if (chk == NULL) {
11262                 return;
11263         }
11264         chk->copy_by_ref = 0;
11265         SCTP_STAT_INCR(sctps_queue_upd_ecne);
11266         chk->rec.chunk_id.id = SCTP_ECN_ECHO;
11267         chk->rec.chunk_id.can_take_data = 0;
11268         chk->asoc = &stcb->asoc;
11269         chk->send_size = sizeof(struct sctp_ecne_chunk);
11270         chk->data = sctp_get_mbuf_for_msg(chk->send_size, 0, M_DONTWAIT, 1, MT_HEADER);
11271         if (chk->data == NULL) {
11272                 sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
11273                 return;
11274         }
11275         SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
11276         SCTP_BUF_LEN(chk->data) = chk->send_size;
11277         chk->sent = SCTP_DATAGRAM_UNSENT;
11278         chk->snd_count = 0;
11279         chk->whoTo = net;
11280         atomic_add_int(&chk->whoTo->ref_count, 1);
11281
11282         stcb->asoc.ecn_echo_cnt_onq++;
11283         ecne = mtod(chk->data, struct sctp_ecne_chunk *);
11284         ecne->ch.chunk_type = SCTP_ECN_ECHO;
11285         ecne->ch.chunk_flags = 0;
11286         ecne->ch.chunk_length = htons(sizeof(struct sctp_ecne_chunk));
11287         ecne->tsn = htonl(high_tsn);
11288         ecne->num_pkts_since_cwr = htonl(1);
11289         TAILQ_INSERT_HEAD(&stcb->asoc.control_send_queue, chk, sctp_next);
11290         asoc->ctrl_queue_cnt++;
11291 }
11292
11293 void
11294 sctp_send_packet_dropped(struct sctp_tcb *stcb, struct sctp_nets *net,
11295     struct mbuf *m, int len, int iphlen, int bad_crc)
11296 {
11297         struct sctp_association *asoc;
11298         struct sctp_pktdrop_chunk *drp;
11299         struct sctp_tmit_chunk *chk;
11300         uint8_t *datap;
11301         int was_trunc = 0;
11302         int fullsz = 0;
11303         long spc;
11304         int offset;
11305         struct sctp_chunkhdr *ch, chunk_buf;
11306         unsigned int chk_length;
11307
11308         if (!stcb) {
11309                 return;
11310         }
11311         asoc = &stcb->asoc;
11312         SCTP_TCB_LOCK_ASSERT(stcb);
11313         if (asoc->peer_supports_pktdrop == 0) {
11314                 /*-
11315                  * peer must declare support before I send one.
11316                  */
11317                 return;
11318         }
11319         if (stcb->sctp_socket == NULL) {
11320                 return;
11321         }
11322         sctp_alloc_a_chunk(stcb, chk);
11323         if (chk == NULL) {
11324                 return;
11325         }
11326         chk->copy_by_ref = 0;
11327         len -= iphlen;
11328         chk->send_size = len;
11329         /* Validate that we do not have an ABORT in here. */
11330         offset = iphlen + sizeof(struct sctphdr);
11331         ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, offset,
11332             sizeof(*ch), (uint8_t *) & chunk_buf);
11333         while (ch != NULL) {
11334                 chk_length = ntohs(ch->chunk_length);
11335                 if (chk_length < sizeof(*ch)) {
11336                         /* break to abort land */
11337                         break;
11338                 }
11339                 switch (ch->chunk_type) {
11340                 case SCTP_PACKET_DROPPED:
11341                 case SCTP_ABORT_ASSOCIATION:
11342                 case SCTP_INITIATION_ACK:
11343                         /**
11344                          * We don't respond with an PKT-DROP to an ABORT
11345                          * or PKT-DROP. We also do not respond to an
11346                          * INIT-ACK, because we can't know if the initiation
11347                          * tag is correct or not.
11348                          */
11349                         sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
11350                         return;
11351                 default:
11352                         break;
11353                 }
11354                 offset += SCTP_SIZE32(chk_length);
11355                 ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, offset,
11356                     sizeof(*ch), (uint8_t *) & chunk_buf);
11357         }
11358
11359         if ((len + SCTP_MAX_OVERHEAD + sizeof(struct sctp_pktdrop_chunk)) >
11360             min(stcb->asoc.smallest_mtu, MCLBYTES)) {
11361                 /*
11362                  * only send 1 mtu worth, trim off the excess on the end.
11363                  */
11364                 fullsz = len;
11365                 len = min(stcb->asoc.smallest_mtu, MCLBYTES) - SCTP_MAX_OVERHEAD;
11366                 was_trunc = 1;
11367         }
11368         chk->asoc = &stcb->asoc;
11369         chk->data = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_DATA);
11370         if (chk->data == NULL) {
11371 jump_out:
11372                 sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
11373                 return;
11374         }
11375         SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
11376         drp = mtod(chk->data, struct sctp_pktdrop_chunk *);
11377         if (drp == NULL) {
11378                 sctp_m_freem(chk->data);
11379                 chk->data = NULL;
11380                 goto jump_out;
11381         }
11382         chk->book_size = SCTP_SIZE32((chk->send_size + sizeof(struct sctp_pktdrop_chunk) +
11383             sizeof(struct sctphdr) + SCTP_MED_OVERHEAD));
11384         chk->book_size_scale = 0;
11385         if (was_trunc) {
11386                 drp->ch.chunk_flags = SCTP_PACKET_TRUNCATED;
11387                 drp->trunc_len = htons(fullsz);
11388                 /*
11389                  * Len is already adjusted to size minus overhead above take
11390                  * out the pkt_drop chunk itself from it.
11391                  */
11392                 chk->send_size = len - sizeof(struct sctp_pktdrop_chunk);
11393                 len = chk->send_size;
11394         } else {
11395                 /* no truncation needed */
11396                 drp->ch.chunk_flags = 0;
11397                 drp->trunc_len = htons(0);
11398         }
11399         if (bad_crc) {
11400                 drp->ch.chunk_flags |= SCTP_BADCRC;
11401         }
11402         chk->send_size += sizeof(struct sctp_pktdrop_chunk);
11403         SCTP_BUF_LEN(chk->data) = chk->send_size;
11404         chk->sent = SCTP_DATAGRAM_UNSENT;
11405         chk->snd_count = 0;
11406         if (net) {
11407                 /* we should hit here */
11408                 chk->whoTo = net;
11409                 atomic_add_int(&chk->whoTo->ref_count, 1);
11410         } else {
11411                 chk->whoTo = NULL;
11412         }
11413         chk->rec.chunk_id.id = SCTP_PACKET_DROPPED;
11414         chk->rec.chunk_id.can_take_data = 1;
11415         drp->ch.chunk_type = SCTP_PACKET_DROPPED;
11416         drp->ch.chunk_length = htons(chk->send_size);
11417         spc = SCTP_SB_LIMIT_RCV(stcb->sctp_socket);
11418         if (spc < 0) {
11419                 spc = 0;
11420         }
11421         drp->bottle_bw = htonl(spc);
11422         if (asoc->my_rwnd) {
11423                 drp->current_onq = htonl(asoc->size_on_reasm_queue +
11424                     asoc->size_on_all_streams +
11425                     asoc->my_rwnd_control_len +
11426                     stcb->sctp_socket->so_rcv.sb_cc);
11427         } else {
11428                 /*-
11429                  * If my rwnd is 0, possibly from mbuf depletion as well as
11430                  * space used, tell the peer there is NO space aka onq == bw
11431                  */
11432                 drp->current_onq = htonl(spc);
11433         }
11434         drp->reserved = 0;
11435         datap = drp->data;
11436         m_copydata(m, iphlen, len, (caddr_t)datap);
11437         TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
11438         asoc->ctrl_queue_cnt++;
11439 }
11440
11441 void
11442 sctp_send_cwr(struct sctp_tcb *stcb, struct sctp_nets *net, uint32_t high_tsn, uint8_t override)
11443 {
11444         struct sctp_association *asoc;
11445         struct sctp_cwr_chunk *cwr;
11446         struct sctp_tmit_chunk *chk;
11447
11448         SCTP_TCB_LOCK_ASSERT(stcb);
11449         if (net == NULL) {
11450                 return;
11451         }
11452         asoc = &stcb->asoc;
11453         TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
11454                 if ((chk->rec.chunk_id.id == SCTP_ECN_CWR) && (net == chk->whoTo)) {
11455                         /*
11456                          * found a previous CWR queued to same destination
11457                          * update it if needed
11458                          */
11459                         uint32_t ctsn;
11460
11461                         cwr = mtod(chk->data, struct sctp_cwr_chunk *);
11462                         ctsn = ntohl(cwr->tsn);
11463                         if (SCTP_TSN_GT(high_tsn, ctsn)) {
11464                                 cwr->tsn = htonl(high_tsn);
11465                         }
11466                         if (override & SCTP_CWR_REDUCE_OVERRIDE) {
11467                                 /* Make sure override is carried */
11468                                 cwr->ch.chunk_flags |= SCTP_CWR_REDUCE_OVERRIDE;
11469                         }
11470                         return;
11471                 }
11472         }
11473         sctp_alloc_a_chunk(stcb, chk);
11474         if (chk == NULL) {
11475                 return;
11476         }
11477         chk->copy_by_ref = 0;
11478         chk->rec.chunk_id.id = SCTP_ECN_CWR;
11479         chk->rec.chunk_id.can_take_data = 1;
11480         chk->asoc = &stcb->asoc;
11481         chk->send_size = sizeof(struct sctp_cwr_chunk);
11482         chk->data = sctp_get_mbuf_for_msg(chk->send_size, 0, M_DONTWAIT, 1, MT_HEADER);
11483         if (chk->data == NULL) {
11484                 sctp_free_a_chunk(stcb, chk, SCTP_SO_NOT_LOCKED);
11485                 return;
11486         }
11487         SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
11488         SCTP_BUF_LEN(chk->data) = chk->send_size;
11489         chk->sent = SCTP_DATAGRAM_UNSENT;
11490         chk->snd_count = 0;
11491         chk->whoTo = net;
11492         atomic_add_int(&chk->whoTo->ref_count, 1);
11493         cwr = mtod(chk->data, struct sctp_cwr_chunk *);
11494         cwr->ch.chunk_type = SCTP_ECN_CWR;
11495         cwr->ch.chunk_flags = override;
11496         cwr->ch.chunk_length = htons(sizeof(struct sctp_cwr_chunk));
11497         cwr->tsn = htonl(high_tsn);
11498         TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
11499         asoc->ctrl_queue_cnt++;
11500 }
11501
11502 void
11503 sctp_add_stream_reset_out(struct sctp_tmit_chunk *chk,
11504     int number_entries, uint16_t * list,
11505     uint32_t seq, uint32_t resp_seq, uint32_t last_sent)
11506 {
11507         uint16_t len, old_len, i;
11508         struct sctp_stream_reset_out_request *req_out;
11509         struct sctp_chunkhdr *ch;
11510
11511         ch = mtod(chk->data, struct sctp_chunkhdr *);
11512         old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11513
11514         /* get to new offset for the param. */
11515         req_out = (struct sctp_stream_reset_out_request *)((caddr_t)ch + len);
11516         /* now how long will this param be? */
11517         len = (sizeof(struct sctp_stream_reset_out_request) + (sizeof(uint16_t) * number_entries));
11518         req_out->ph.param_type = htons(SCTP_STR_RESET_OUT_REQUEST);
11519         req_out->ph.param_length = htons(len);
11520         req_out->request_seq = htonl(seq);
11521         req_out->response_seq = htonl(resp_seq);
11522         req_out->send_reset_at_tsn = htonl(last_sent);
11523         if (number_entries) {
11524                 for (i = 0; i < number_entries; i++) {
11525                         req_out->list_of_streams[i] = htons(list[i]);
11526                 }
11527         }
11528         if (SCTP_SIZE32(len) > len) {
11529                 /*-
11530                  * Need to worry about the pad we may end up adding to the
11531                  * end. This is easy since the struct is either aligned to 4
11532                  * bytes or 2 bytes off.
11533                  */
11534                 req_out->list_of_streams[number_entries] = 0;
11535         }
11536         /* now fix the chunk length */
11537         ch->chunk_length = htons(len + old_len);
11538         chk->book_size = len + old_len;
11539         chk->book_size_scale = 0;
11540         chk->send_size = SCTP_SIZE32(chk->book_size);
11541         SCTP_BUF_LEN(chk->data) = chk->send_size;
11542         return;
11543 }
11544
11545 static void
11546 sctp_add_stream_reset_in(struct sctp_tmit_chunk *chk,
11547     int number_entries, uint16_t * list,
11548     uint32_t seq)
11549 {
11550         uint16_t len, old_len, i;
11551         struct sctp_stream_reset_in_request *req_in;
11552         struct sctp_chunkhdr *ch;
11553
11554         ch = mtod(chk->data, struct sctp_chunkhdr *);
11555         old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11556
11557         /* get to new offset for the param. */
11558         req_in = (struct sctp_stream_reset_in_request *)((caddr_t)ch + len);
11559         /* now how long will this param be? */
11560         len = (sizeof(struct sctp_stream_reset_in_request) + (sizeof(uint16_t) * number_entries));
11561         req_in->ph.param_type = htons(SCTP_STR_RESET_IN_REQUEST);
11562         req_in->ph.param_length = htons(len);
11563         req_in->request_seq = htonl(seq);
11564         if (number_entries) {
11565                 for (i = 0; i < number_entries; i++) {
11566                         req_in->list_of_streams[i] = htons(list[i]);
11567                 }
11568         }
11569         if (SCTP_SIZE32(len) > len) {
11570                 /*-
11571                  * Need to worry about the pad we may end up adding to the
11572                  * end. This is easy since the struct is either aligned to 4
11573                  * bytes or 2 bytes off.
11574                  */
11575                 req_in->list_of_streams[number_entries] = 0;
11576         }
11577         /* now fix the chunk length */
11578         ch->chunk_length = htons(len + old_len);
11579         chk->book_size = len + old_len;
11580         chk->book_size_scale = 0;
11581         chk->send_size = SCTP_SIZE32(chk->book_size);
11582         SCTP_BUF_LEN(chk->data) = chk->send_size;
11583         return;
11584 }
11585
11586 static void
11587 sctp_add_stream_reset_tsn(struct sctp_tmit_chunk *chk,
11588     uint32_t seq)
11589 {
11590         uint16_t len, old_len;
11591         struct sctp_stream_reset_tsn_request *req_tsn;
11592         struct sctp_chunkhdr *ch;
11593
11594         ch = mtod(chk->data, struct sctp_chunkhdr *);
11595         old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11596
11597         /* get to new offset for the param. */
11598         req_tsn = (struct sctp_stream_reset_tsn_request *)((caddr_t)ch + len);
11599         /* now how long will this param be? */
11600         len = sizeof(struct sctp_stream_reset_tsn_request);
11601         req_tsn->ph.param_type = htons(SCTP_STR_RESET_TSN_REQUEST);
11602         req_tsn->ph.param_length = htons(len);
11603         req_tsn->request_seq = htonl(seq);
11604
11605         /* now fix the chunk length */
11606         ch->chunk_length = htons(len + old_len);
11607         chk->send_size = len + old_len;
11608         chk->book_size = SCTP_SIZE32(chk->send_size);
11609         chk->book_size_scale = 0;
11610         SCTP_BUF_LEN(chk->data) = SCTP_SIZE32(chk->send_size);
11611         return;
11612 }
11613
11614 void
11615 sctp_add_stream_reset_result(struct sctp_tmit_chunk *chk,
11616     uint32_t resp_seq, uint32_t result)
11617 {
11618         uint16_t len, old_len;
11619         struct sctp_stream_reset_response *resp;
11620         struct sctp_chunkhdr *ch;
11621
11622         ch = mtod(chk->data, struct sctp_chunkhdr *);
11623         old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11624
11625         /* get to new offset for the param. */
11626         resp = (struct sctp_stream_reset_response *)((caddr_t)ch + len);
11627         /* now how long will this param be? */
11628         len = sizeof(struct sctp_stream_reset_response);
11629         resp->ph.param_type = htons(SCTP_STR_RESET_RESPONSE);
11630         resp->ph.param_length = htons(len);
11631         resp->response_seq = htonl(resp_seq);
11632         resp->result = ntohl(result);
11633
11634         /* now fix the chunk length */
11635         ch->chunk_length = htons(len + old_len);
11636         chk->book_size = len + old_len;
11637         chk->book_size_scale = 0;
11638         chk->send_size = SCTP_SIZE32(chk->book_size);
11639         SCTP_BUF_LEN(chk->data) = chk->send_size;
11640         return;
11641 }
11642
11643 void
11644 sctp_add_stream_reset_result_tsn(struct sctp_tmit_chunk *chk,
11645     uint32_t resp_seq, uint32_t result,
11646     uint32_t send_una, uint32_t recv_next)
11647 {
11648         uint16_t len, old_len;
11649         struct sctp_stream_reset_response_tsn *resp;
11650         struct sctp_chunkhdr *ch;
11651
11652         ch = mtod(chk->data, struct sctp_chunkhdr *);
11653         old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11654
11655         /* get to new offset for the param. */
11656         resp = (struct sctp_stream_reset_response_tsn *)((caddr_t)ch + len);
11657         /* now how long will this param be? */
11658         len = sizeof(struct sctp_stream_reset_response_tsn);
11659         resp->ph.param_type = htons(SCTP_STR_RESET_RESPONSE);
11660         resp->ph.param_length = htons(len);
11661         resp->response_seq = htonl(resp_seq);
11662         resp->result = htonl(result);
11663         resp->senders_next_tsn = htonl(send_una);
11664         resp->receivers_next_tsn = htonl(recv_next);
11665
11666         /* now fix the chunk length */
11667         ch->chunk_length = htons(len + old_len);
11668         chk->book_size = len + old_len;
11669         chk->send_size = SCTP_SIZE32(chk->book_size);
11670         chk->book_size_scale = 0;
11671         SCTP_BUF_LEN(chk->data) = chk->send_size;
11672         return;
11673 }
11674
11675 static void
11676 sctp_add_an_out_stream(struct sctp_tmit_chunk *chk,
11677     uint32_t seq,
11678     uint16_t adding)
11679 {
11680         uint16_t len, old_len;
11681         struct sctp_chunkhdr *ch;
11682         struct sctp_stream_reset_add_strm *addstr;
11683
11684         ch = mtod(chk->data, struct sctp_chunkhdr *);
11685         old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11686
11687         /* get to new offset for the param. */
11688         addstr = (struct sctp_stream_reset_add_strm *)((caddr_t)ch + len);
11689         /* now how long will this param be? */
11690         len = sizeof(struct sctp_stream_reset_add_strm);
11691
11692         /* Fill it out. */
11693         addstr->ph.param_type = htons(SCTP_STR_RESET_ADD_OUT_STREAMS);
11694         addstr->ph.param_length = htons(len);
11695         addstr->request_seq = htonl(seq);
11696         addstr->number_of_streams = htons(adding);
11697         addstr->reserved = 0;
11698
11699         /* now fix the chunk length */
11700         ch->chunk_length = htons(len + old_len);
11701         chk->send_size = len + old_len;
11702         chk->book_size = SCTP_SIZE32(chk->send_size);
11703         chk->book_size_scale = 0;
11704         SCTP_BUF_LEN(chk->data) = SCTP_SIZE32(chk->send_size);
11705         return;
11706 }
11707
11708 static void
11709 sctp_add_an_in_stream(struct sctp_tmit_chunk *chk,
11710     uint32_t seq,
11711     uint16_t adding)
11712 {
11713         uint16_t len, old_len;
11714         struct sctp_chunkhdr *ch;
11715         struct sctp_stream_reset_add_strm *addstr;
11716
11717         ch = mtod(chk->data, struct sctp_chunkhdr *);
11718         old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11719
11720         /* get to new offset for the param. */
11721         addstr = (struct sctp_stream_reset_add_strm *)((caddr_t)ch + len);
11722         /* now how long will this param be? */
11723         len = sizeof(struct sctp_stream_reset_add_strm);
11724         /* Fill it out. */
11725         addstr->ph.param_type = htons(SCTP_STR_RESET_ADD_IN_STREAMS);
11726         addstr->ph.param_length = htons(len);
11727         addstr->request_seq = htonl(seq);
11728         addstr->number_of_streams = htons(adding);
11729         addstr->reserved = 0;
11730
11731         /* now fix the chunk length */
11732         ch->chunk_length = htons(len + old_len);
11733         chk->send_size = len + old_len;
11734         chk->book_size = SCTP_SIZE32(chk->send_size);
11735         chk->book_size_scale = 0;
11736         SCTP_BUF_LEN(chk->data) = SCTP_SIZE32(chk->send_size);
11737         return;
11738 }
11739
11740 int
11741 sctp_send_str_reset_req(struct sctp_tcb *stcb,
11742     int number_entries, uint16_t * list,
11743     uint8_t send_out_req,
11744     uint8_t send_in_req,
11745     uint8_t send_tsn_req,
11746     uint8_t add_stream,
11747     uint16_t adding_o,
11748     uint16_t adding_i, uint8_t peer_asked)
11749 {
11750
11751         struct sctp_association *asoc;
11752         struct sctp_tmit_chunk *chk;
11753         struct sctp_chunkhdr *ch;
11754         uint32_t seq;
11755
11756         asoc = &stcb->asoc;
11757         if (asoc->stream_reset_outstanding) {
11758                 /*-
11759                  * Already one pending, must get ACK back to clear the flag.
11760                  */
11761                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EBUSY);
11762                 return (EBUSY);
11763         }
11764         if ((send_out_req == 0) && (send_in_req == 0) && (send_tsn_req == 0) &&
11765             (add_stream == 0)) {
11766                 /* nothing to do */
11767                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EINVAL);
11768                 return (EINVAL);
11769         }
11770         if (send_tsn_req && (send_out_req || send_in_req)) {
11771                 /* error, can't do that */
11772                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EINVAL);
11773                 return (EINVAL);
11774         }
11775         sctp_alloc_a_chunk(stcb, chk);
11776         if (chk == NULL) {
11777                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
11778                 return (ENOMEM);
11779         }
11780         chk->copy_by_ref = 0;
11781         chk->rec.chunk_id.id = SCTP_STREAM_RESET;
11782         chk->rec.chunk_id.can_take_data = 0;
11783         chk->asoc = &stcb->asoc;
11784         chk->book_size = sizeof(struct sctp_chunkhdr);
11785         chk->send_size = SCTP_SIZE32(chk->book_size);
11786         chk->book_size_scale = 0;
11787
11788         chk->data = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_DATA);
11789         if (chk->data == NULL) {
11790                 sctp_free_a_chunk(stcb, chk, SCTP_SO_LOCKED);
11791                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
11792                 return (ENOMEM);
11793         }
11794         SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
11795
11796         /* setup chunk parameters */
11797         chk->sent = SCTP_DATAGRAM_UNSENT;
11798         chk->snd_count = 0;
11799         if (stcb->asoc.alternate) {
11800                 chk->whoTo = stcb->asoc.alternate;
11801         } else {
11802                 chk->whoTo = stcb->asoc.primary_destination;
11803         }
11804         atomic_add_int(&chk->whoTo->ref_count, 1);
11805         ch = mtod(chk->data, struct sctp_chunkhdr *);
11806         ch->chunk_type = SCTP_STREAM_RESET;
11807         ch->chunk_flags = 0;
11808         ch->chunk_length = htons(chk->book_size);
11809         SCTP_BUF_LEN(chk->data) = chk->send_size;
11810
11811         seq = stcb->asoc.str_reset_seq_out;
11812         if (send_out_req) {
11813                 sctp_add_stream_reset_out(chk, number_entries, list,
11814                     seq, (stcb->asoc.str_reset_seq_in - 1), (stcb->asoc.sending_seq - 1));
11815                 asoc->stream_reset_out_is_outstanding = 1;
11816                 seq++;
11817                 asoc->stream_reset_outstanding++;
11818         }
11819         if ((add_stream & 1) &&
11820             ((stcb->asoc.strm_realoutsize - stcb->asoc.streamoutcnt) < adding_o)) {
11821                 /* Need to allocate more */
11822                 struct sctp_stream_out *oldstream;
11823                 struct sctp_stream_queue_pending *sp, *nsp;
11824                 int i;
11825
11826                 oldstream = stcb->asoc.strmout;
11827                 /* get some more */
11828                 SCTP_MALLOC(stcb->asoc.strmout, struct sctp_stream_out *,
11829                     ((stcb->asoc.streamoutcnt + adding_o) * sizeof(struct sctp_stream_out)),
11830                     SCTP_M_STRMO);
11831                 if (stcb->asoc.strmout == NULL) {
11832                         uint8_t x;
11833
11834                         stcb->asoc.strmout = oldstream;
11835                         /* Turn off the bit */
11836                         x = add_stream & 0xfe;
11837                         add_stream = x;
11838                         goto skip_stuff;
11839                 }
11840                 /*
11841                  * Ok now we proceed with copying the old out stuff and
11842                  * initializing the new stuff.
11843                  */
11844                 SCTP_TCB_SEND_LOCK(stcb);
11845                 stcb->asoc.ss_functions.sctp_ss_clear(stcb, &stcb->asoc, 0, 1);
11846                 for (i = 0; i < stcb->asoc.streamoutcnt; i++) {
11847                         TAILQ_INIT(&stcb->asoc.strmout[i].outqueue);
11848                         stcb->asoc.strmout[i].chunks_on_queues = oldstream[i].chunks_on_queues;
11849                         stcb->asoc.strmout[i].next_sequence_send = oldstream[i].next_sequence_send;
11850                         stcb->asoc.strmout[i].last_msg_incomplete = oldstream[i].last_msg_incomplete;
11851                         stcb->asoc.strmout[i].stream_no = i;
11852                         stcb->asoc.ss_functions.sctp_ss_init_stream(&stcb->asoc.strmout[i], &oldstream[i]);
11853                         /* now anything on those queues? */
11854                         TAILQ_FOREACH_SAFE(sp, &oldstream[i].outqueue, next, nsp) {
11855                                 TAILQ_REMOVE(&oldstream[i].outqueue, sp, next);
11856                                 TAILQ_INSERT_TAIL(&stcb->asoc.strmout[i].outqueue, sp, next);
11857                         }
11858                         /* Now move assoc pointers too */
11859                         if (stcb->asoc.last_out_stream == &oldstream[i]) {
11860                                 stcb->asoc.last_out_stream = &stcb->asoc.strmout[i];
11861                         }
11862                         if (stcb->asoc.locked_on_sending == &oldstream[i]) {
11863                                 stcb->asoc.locked_on_sending = &stcb->asoc.strmout[i];
11864                         }
11865                 }
11866                 /* now the new streams */
11867                 stcb->asoc.ss_functions.sctp_ss_init(stcb, &stcb->asoc, 1);
11868                 for (i = stcb->asoc.streamoutcnt; i < (stcb->asoc.streamoutcnt + adding_o); i++) {
11869                         TAILQ_INIT(&stcb->asoc.strmout[i].outqueue);
11870                         stcb->asoc.strmout[i].chunks_on_queues = 0;
11871                         stcb->asoc.strmout[i].next_sequence_send = 0x0;
11872                         stcb->asoc.strmout[i].stream_no = i;
11873                         stcb->asoc.strmout[i].last_msg_incomplete = 0;
11874                         stcb->asoc.ss_functions.sctp_ss_init_stream(&stcb->asoc.strmout[i], NULL);
11875                 }
11876                 stcb->asoc.strm_realoutsize = stcb->asoc.streamoutcnt + adding_o;
11877                 SCTP_FREE(oldstream, SCTP_M_STRMO);
11878                 SCTP_TCB_SEND_UNLOCK(stcb);
11879         }
11880 skip_stuff:
11881         if ((add_stream & 1) && (adding_o > 0)) {
11882                 asoc->strm_pending_add_size = adding_o;
11883                 asoc->peer_req_out = peer_asked;
11884                 sctp_add_an_out_stream(chk, seq, adding_o);
11885                 seq++;
11886                 asoc->stream_reset_outstanding++;
11887         }
11888         if ((add_stream & 2) && (adding_i > 0)) {
11889                 sctp_add_an_in_stream(chk, seq, adding_i);
11890                 seq++;
11891                 asoc->stream_reset_outstanding++;
11892         }
11893         if (send_in_req) {
11894                 sctp_add_stream_reset_in(chk, number_entries, list, seq);
11895                 seq++;
11896                 asoc->stream_reset_outstanding++;
11897         }
11898         if (send_tsn_req) {
11899                 sctp_add_stream_reset_tsn(chk, seq);
11900                 asoc->stream_reset_outstanding++;
11901         }
11902         asoc->str_reset = chk;
11903         /* insert the chunk for sending */
11904         TAILQ_INSERT_TAIL(&asoc->control_send_queue,
11905             chk,
11906             sctp_next);
11907         asoc->ctrl_queue_cnt++;
11908         sctp_timer_start(SCTP_TIMER_TYPE_STRRESET, stcb->sctp_ep, stcb, chk->whoTo);
11909         return (0);
11910 }
11911
11912 void
11913 sctp_send_abort(struct mbuf *m, int iphlen, struct sockaddr *src, struct sockaddr *dst,
11914     struct sctphdr *sh, uint32_t vtag, struct mbuf *cause,
11915     uint8_t use_mflowid, uint32_t mflowid,
11916     uint32_t vrf_id, uint16_t port)
11917 {
11918         /* Don't respond to an ABORT with an ABORT. */
11919         if (sctp_is_there_an_abort_here(m, iphlen, &vtag)) {
11920                 if (cause)
11921                         sctp_m_freem(cause);
11922                 return;
11923         }
11924         sctp_send_resp_msg(src, dst, sh, vtag, SCTP_ABORT_ASSOCIATION, cause,
11925             use_mflowid, mflowid,
11926             vrf_id, port);
11927         return;
11928 }
11929
11930 void
11931 sctp_send_operr_to(struct sockaddr *src, struct sockaddr *dst,
11932     struct sctphdr *sh, uint32_t vtag, struct mbuf *cause,
11933     uint8_t use_mflowid, uint32_t mflowid,
11934     uint32_t vrf_id, uint16_t port)
11935 {
11936         sctp_send_resp_msg(src, dst, sh, vtag, SCTP_OPERATION_ERROR, cause,
11937             use_mflowid, mflowid,
11938             vrf_id, port);
11939         return;
11940 }
11941
11942 static struct mbuf *
11943 sctp_copy_resume(struct uio *uio,
11944     int max_send_len,
11945     int user_marks_eor,
11946     int *error,
11947     uint32_t * sndout,
11948     struct mbuf **new_tail)
11949 {
11950         struct mbuf *m;
11951
11952         m = m_uiotombuf(uio, M_WAITOK, max_send_len, 0,
11953             (M_PKTHDR | (user_marks_eor ? M_EOR : 0)));
11954         if (m == NULL) {
11955                 SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
11956                 *error = ENOMEM;
11957         } else {
11958                 *sndout = m_length(m, NULL);
11959                 *new_tail = m_last(m);
11960         }
11961         return (m);
11962 }
11963
11964 static int
11965 sctp_copy_one(struct sctp_stream_queue_pending *sp,
11966     struct uio *uio,
11967     int resv_upfront)
11968 {
11969         int left;
11970
11971         left = sp->length;
11972         sp->data = m_uiotombuf(uio, M_WAITOK, sp->length,
11973             resv_upfront, 0);
11974         if (sp->data == NULL) {
11975                 SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
11976                 return (ENOMEM);
11977         }
11978         sp->tail_mbuf = m_last(sp->data);
11979         return (0);
11980 }
11981
11982
11983
11984 static struct sctp_stream_queue_pending *
11985 sctp_copy_it_in(struct sctp_tcb *stcb,
11986     struct sctp_association *asoc,
11987     struct sctp_sndrcvinfo *srcv,
11988     struct uio *uio,
11989     struct sctp_nets *net,
11990     int max_send_len,
11991     int user_marks_eor,
11992     int *error)
11993 {
11994         /*-
11995          * This routine must be very careful in its work. Protocol
11996          * processing is up and running so care must be taken to spl...()
11997          * when you need to do something that may effect the stcb/asoc. The
11998          * sb is locked however. When data is copied the protocol processing
11999          * should be enabled since this is a slower operation...
12000          */
12001         struct sctp_stream_queue_pending *sp = NULL;
12002         int resv_in_first;
12003
12004         *error = 0;
12005         /* Now can we send this? */
12006         if ((SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
12007             (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
12008             (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
12009             (asoc->state & SCTP_STATE_SHUTDOWN_PENDING)) {
12010                 /* got data while shutting down */
12011                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ECONNRESET);
12012                 *error = ECONNRESET;
12013                 goto out_now;
12014         }
12015         sctp_alloc_a_strmoq(stcb, sp);
12016         if (sp == NULL) {
12017                 SCTP_LTRACE_ERR_RET(NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
12018                 *error = ENOMEM;
12019                 goto out_now;
12020         }
12021         sp->act_flags = 0;
12022         sp->sender_all_done = 0;
12023         sp->sinfo_flags = srcv->sinfo_flags;
12024         sp->timetolive = srcv->sinfo_timetolive;
12025         sp->ppid = srcv->sinfo_ppid;
12026         sp->context = srcv->sinfo_context;
12027         (void)SCTP_GETTIME_TIMEVAL(&sp->ts);
12028
12029         sp->stream = srcv->sinfo_stream;
12030         sp->length = min(uio->uio_resid, max_send_len);
12031         if ((sp->length == (uint32_t) uio->uio_resid) &&
12032             ((user_marks_eor == 0) ||
12033             (srcv->sinfo_flags & SCTP_EOF) ||
12034             (user_marks_eor && (srcv->sinfo_flags & SCTP_EOR)))) {
12035                 sp->msg_is_complete = 1;
12036         } else {
12037                 sp->msg_is_complete = 0;
12038         }
12039         sp->sender_all_done = 0;
12040         sp->some_taken = 0;
12041         sp->put_last_out = 0;
12042         resv_in_first = sizeof(struct sctp_data_chunk);
12043         sp->data = sp->tail_mbuf = NULL;
12044         if (sp->length == 0) {
12045                 *error = 0;
12046                 goto skip_copy;
12047         }
12048         if (srcv->sinfo_keynumber_valid) {
12049                 sp->auth_keyid = srcv->sinfo_keynumber;
12050         } else {
12051                 sp->auth_keyid = stcb->asoc.authinfo.active_keyid;
12052         }
12053         if (sctp_auth_is_required_chunk(SCTP_DATA, stcb->asoc.peer_auth_chunks)) {
12054                 sctp_auth_key_acquire(stcb, sp->auth_keyid);
12055                 sp->holds_key_ref = 1;
12056         }
12057         *error = sctp_copy_one(sp, uio, resv_in_first);
12058 skip_copy:
12059         if (*error) {
12060                 sctp_free_a_strmoq(stcb, sp, SCTP_SO_LOCKED);
12061                 sp = NULL;
12062         } else {
12063                 if (sp->sinfo_flags & SCTP_ADDR_OVER) {
12064                         sp->net = net;
12065                         atomic_add_int(&sp->net->ref_count, 1);
12066                 } else {
12067                         sp->net = NULL;
12068                 }
12069                 sctp_set_prsctp_policy(sp);
12070         }
12071 out_now:
12072         return (sp);
12073 }
12074
12075
12076 int
12077 sctp_sosend(struct socket *so,
12078     struct sockaddr *addr,
12079     struct uio *uio,
12080     struct mbuf *top,
12081     struct mbuf *control,
12082     int flags,
12083     struct thread *p
12084 )
12085 {
12086         int error, use_sndinfo = 0;
12087         struct sctp_sndrcvinfo sndrcvninfo;
12088         struct sockaddr *addr_to_use;
12089
12090 #if defined(INET) && defined(INET6)
12091         struct sockaddr_in sin;
12092
12093 #endif
12094
12095         if (control) {
12096                 /* process cmsg snd/rcv info (maybe a assoc-id) */
12097                 if (sctp_find_cmsg(SCTP_SNDRCV, (void *)&sndrcvninfo, control,
12098                     sizeof(sndrcvninfo))) {
12099                         /* got one */
12100                         use_sndinfo = 1;
12101                 }
12102         }
12103         addr_to_use = addr;
12104 #if defined(INET) && defined(INET6)
12105         if ((addr) && (addr->sa_family == AF_INET6)) {
12106                 struct sockaddr_in6 *sin6;
12107
12108                 sin6 = (struct sockaddr_in6 *)addr;
12109                 if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
12110                         in6_sin6_2_sin(&sin, sin6);
12111                         addr_to_use = (struct sockaddr *)&sin;
12112                 }
12113         }
12114 #endif
12115         error = sctp_lower_sosend(so, addr_to_use, uio, top,
12116             control,
12117             flags,
12118             use_sndinfo ? &sndrcvninfo : NULL
12119             ,p
12120             );
12121         return (error);
12122 }
12123
12124
12125 int
12126 sctp_lower_sosend(struct socket *so,
12127     struct sockaddr *addr,
12128     struct uio *uio,
12129     struct mbuf *i_pak,
12130     struct mbuf *control,
12131     int flags,
12132     struct sctp_sndrcvinfo *srcv
12133     ,
12134     struct thread *p
12135 )
12136 {
12137         unsigned int sndlen = 0, max_len;
12138         int error, len;
12139         struct mbuf *top = NULL;
12140         int queue_only = 0, queue_only_for_init = 0;
12141         int free_cnt_applied = 0;
12142         int un_sent;
12143         int now_filled = 0;
12144         unsigned int inqueue_bytes = 0;
12145         struct sctp_block_entry be;
12146         struct sctp_inpcb *inp;
12147         struct sctp_tcb *stcb = NULL;
12148         struct timeval now;
12149         struct sctp_nets *net;
12150         struct sctp_association *asoc;
12151         struct sctp_inpcb *t_inp;
12152         int user_marks_eor;
12153         int create_lock_applied = 0;
12154         int nagle_applies = 0;
12155         int some_on_control = 0;
12156         int got_all_of_the_send = 0;
12157         int hold_tcblock = 0;
12158         int non_blocking = 0;
12159         uint32_t local_add_more, local_soresv = 0;
12160         uint16_t port;
12161         uint16_t sinfo_flags;
12162         sctp_assoc_t sinfo_assoc_id;
12163
12164         error = 0;
12165         net = NULL;
12166         stcb = NULL;
12167         asoc = NULL;
12168
12169         t_inp = inp = (struct sctp_inpcb *)so->so_pcb;
12170         if (inp == NULL) {
12171                 SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12172                 error = EINVAL;
12173                 if (i_pak) {
12174                         SCTP_RELEASE_PKT(i_pak);
12175                 }
12176                 return (error);
12177         }
12178         if ((uio == NULL) && (i_pak == NULL)) {
12179                 SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12180                 return (EINVAL);
12181         }
12182         user_marks_eor = sctp_is_feature_on(inp, SCTP_PCB_FLAGS_EXPLICIT_EOR);
12183         atomic_add_int(&inp->total_sends, 1);
12184         if (uio) {
12185                 if (uio->uio_resid < 0) {
12186                         SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12187                         return (EINVAL);
12188                 }
12189                 sndlen = uio->uio_resid;
12190         } else {
12191                 top = SCTP_HEADER_TO_CHAIN(i_pak);
12192                 sndlen = SCTP_HEADER_LEN(i_pak);
12193         }
12194         SCTPDBG(SCTP_DEBUG_OUTPUT1, "Send called addr:%p send length %d\n",
12195             (void *)addr,
12196             sndlen);
12197         if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) &&
12198             (inp->sctp_socket->so_qlimit)) {
12199                 /* The listener can NOT send */
12200                 SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, ENOTCONN);
12201                 error = ENOTCONN;
12202                 goto out_unlocked;
12203         }
12204         /**
12205          * Pre-screen address, if one is given the sin-len
12206          * must be set correctly!
12207          */
12208         if (addr) {
12209                 union sctp_sockstore *raddr = (union sctp_sockstore *)addr;
12210
12211                 switch (raddr->sa.sa_family) {
12212 #ifdef INET
12213                 case AF_INET:
12214                         if (raddr->sin.sin_len != sizeof(struct sockaddr_in)) {
12215                                 SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12216                                 error = EINVAL;
12217                                 goto out_unlocked;
12218                         }
12219                         port = raddr->sin.sin_port;
12220                         break;
12221 #endif
12222 #ifdef INET6
12223                 case AF_INET6:
12224                         if (raddr->sin6.sin6_len != sizeof(struct sockaddr_in6)) {
12225                                 SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12226                                 error = EINVAL;
12227                                 goto out_unlocked;
12228                         }
12229                         port = raddr->sin6.sin6_port;
12230                         break;
12231 #endif
12232                 default:
12233                         SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EAFNOSUPPORT);
12234                         error = EAFNOSUPPORT;
12235                         goto out_unlocked;
12236                 }
12237         } else
12238                 port = 0;
12239
12240         if (srcv) {
12241                 sinfo_flags = srcv->sinfo_flags;
12242                 sinfo_assoc_id = srcv->sinfo_assoc_id;
12243                 if (INVALID_SINFO_FLAG(sinfo_flags) ||
12244                     PR_SCTP_INVALID_POLICY(sinfo_flags)) {
12245                         SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12246                         error = EINVAL;
12247                         goto out_unlocked;
12248                 }
12249                 if (srcv->sinfo_flags)
12250                         SCTP_STAT_INCR(sctps_sends_with_flags);
12251         } else {
12252                 sinfo_flags = inp->def_send.sinfo_flags;
12253                 sinfo_assoc_id = inp->def_send.sinfo_assoc_id;
12254         }
12255         if (sinfo_flags & SCTP_SENDALL) {
12256                 /* its a sendall */
12257                 error = sctp_sendall(inp, uio, top, srcv);
12258                 top = NULL;
12259                 goto out_unlocked;
12260         }
12261         if ((sinfo_flags & SCTP_ADDR_OVER) && (addr == NULL)) {
12262                 SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12263                 error = EINVAL;
12264                 goto out_unlocked;
12265         }
12266         /* now we must find the assoc */
12267         if ((inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) ||
12268             (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
12269                 SCTP_INP_RLOCK(inp);
12270                 stcb = LIST_FIRST(&inp->sctp_asoc_list);
12271                 if (stcb) {
12272                         SCTP_TCB_LOCK(stcb);
12273                         hold_tcblock = 1;
12274                 }
12275                 SCTP_INP_RUNLOCK(inp);
12276         } else if (sinfo_assoc_id) {
12277                 stcb = sctp_findassociation_ep_asocid(inp, sinfo_assoc_id, 0);
12278         } else if (addr) {
12279                 /*-
12280                  * Since we did not use findep we must
12281                  * increment it, and if we don't find a tcb
12282                  * decrement it.
12283                  */
12284                 SCTP_INP_WLOCK(inp);
12285                 SCTP_INP_INCR_REF(inp);
12286                 SCTP_INP_WUNLOCK(inp);
12287                 stcb = sctp_findassociation_ep_addr(&t_inp, addr, &net, NULL, NULL);
12288                 if (stcb == NULL) {
12289                         SCTP_INP_WLOCK(inp);
12290                         SCTP_INP_DECR_REF(inp);
12291                         SCTP_INP_WUNLOCK(inp);
12292                 } else {
12293                         hold_tcblock = 1;
12294                 }
12295         }
12296         if ((stcb == NULL) && (addr)) {
12297                 /* Possible implicit send? */
12298                 SCTP_ASOC_CREATE_LOCK(inp);
12299                 create_lock_applied = 1;
12300                 if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
12301                     (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
12302                         /* Should I really unlock ? */
12303                         SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12304                         error = EINVAL;
12305                         goto out_unlocked;
12306
12307                 }
12308                 if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) &&
12309                     (addr->sa_family == AF_INET6)) {
12310                         SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12311                         error = EINVAL;
12312                         goto out_unlocked;
12313                 }
12314                 SCTP_INP_WLOCK(inp);
12315                 SCTP_INP_INCR_REF(inp);
12316                 SCTP_INP_WUNLOCK(inp);
12317                 /* With the lock applied look again */
12318                 stcb = sctp_findassociation_ep_addr(&t_inp, addr, &net, NULL, NULL);
12319                 if ((stcb == NULL) && (control != NULL) && (port > 0)) {
12320                         stcb = sctp_findassociation_cmsgs(&t_inp, port, control, &net, &error);
12321                 }
12322                 if (stcb == NULL) {
12323                         SCTP_INP_WLOCK(inp);
12324                         SCTP_INP_DECR_REF(inp);
12325                         SCTP_INP_WUNLOCK(inp);
12326                 } else {
12327                         hold_tcblock = 1;
12328                 }
12329                 if (error) {
12330                         goto out_unlocked;
12331                 }
12332                 if (t_inp != inp) {
12333                         SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, ENOTCONN);
12334                         error = ENOTCONN;
12335                         goto out_unlocked;
12336                 }
12337         }
12338         if (stcb == NULL) {
12339                 if (addr == NULL) {
12340                         SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, ENOENT);
12341                         error = ENOENT;
12342                         goto out_unlocked;
12343                 } else {
12344                         /* We must go ahead and start the INIT process */
12345                         uint32_t vrf_id;
12346
12347                         if ((sinfo_flags & SCTP_ABORT) ||
12348                             ((sinfo_flags & SCTP_EOF) && (sndlen == 0))) {
12349                                 /*-
12350                                  * User asks to abort a non-existant assoc,
12351                                  * or EOF a non-existant assoc with no data
12352                                  */
12353                                 SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, ENOENT);
12354                                 error = ENOENT;
12355                                 goto out_unlocked;
12356                         }
12357                         /* get an asoc/stcb struct */
12358                         vrf_id = inp->def_vrf_id;
12359 #ifdef INVARIANTS
12360                         if (create_lock_applied == 0) {
12361                                 panic("Error, should hold create lock and I don't?");
12362                         }
12363 #endif
12364                         stcb = sctp_aloc_assoc(inp, addr, &error, 0, vrf_id,
12365                             p
12366                             );
12367                         if (stcb == NULL) {
12368                                 /* Error is setup for us in the call */
12369                                 goto out_unlocked;
12370                         }
12371                         if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) {
12372                                 stcb->sctp_ep->sctp_flags |= SCTP_PCB_FLAGS_CONNECTED;
12373                                 /*
12374                                  * Set the connected flag so we can queue
12375                                  * data
12376                                  */
12377                                 soisconnecting(so);
12378                         }
12379                         hold_tcblock = 1;
12380                         if (create_lock_applied) {
12381                                 SCTP_ASOC_CREATE_UNLOCK(inp);
12382                                 create_lock_applied = 0;
12383                         } else {
12384                                 SCTP_PRINTF("Huh-3? create lock should have been on??\n");
12385                         }
12386                         /*
12387                          * Turn on queue only flag to prevent data from
12388                          * being sent
12389                          */
12390                         queue_only = 1;
12391                         asoc = &stcb->asoc;
12392                         SCTP_SET_STATE(asoc, SCTP_STATE_COOKIE_WAIT);
12393                         (void)SCTP_GETTIME_TIMEVAL(&asoc->time_entered);
12394
12395                         /* initialize authentication params for the assoc */
12396                         sctp_initialize_auth_params(inp, stcb);
12397
12398                         if (control) {
12399                                 if (sctp_process_cmsgs_for_init(stcb, control, &error)) {
12400                                         sctp_free_assoc(inp, stcb, SCTP_PCBFREE_FORCE, SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_7);
12401                                         hold_tcblock = 0;
12402                                         stcb = NULL;
12403                                         goto out_unlocked;
12404                                 }
12405                         }
12406                         /* out with the INIT */
12407                         queue_only_for_init = 1;
12408                         /*-
12409                          * we may want to dig in after this call and adjust the MTU
12410                          * value. It defaulted to 1500 (constant) but the ro
12411                          * structure may now have an update and thus we may need to
12412                          * change it BEFORE we append the message.
12413                          */
12414                 }
12415         } else
12416                 asoc = &stcb->asoc;
12417         if (srcv == NULL)
12418                 srcv = (struct sctp_sndrcvinfo *)&asoc->def_send;
12419         if (srcv->sinfo_flags & SCTP_ADDR_OVER) {
12420                 if (addr)
12421                         net = sctp_findnet(stcb, addr);
12422                 else
12423                         net = NULL;
12424                 if ((net == NULL) ||
12425                     ((port != 0) && (port != stcb->rport))) {
12426                         SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12427                         error = EINVAL;
12428                         goto out_unlocked;
12429                 }
12430         } else {
12431                 if (stcb->asoc.alternate) {
12432                         net = stcb->asoc.alternate;
12433                 } else {
12434                         net = stcb->asoc.primary_destination;
12435                 }
12436         }
12437         atomic_add_int(&stcb->total_sends, 1);
12438         /* Keep the stcb from being freed under our feet */
12439         atomic_add_int(&asoc->refcnt, 1);
12440         free_cnt_applied = 1;
12441
12442         if (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_NO_FRAGMENT)) {
12443                 if (sndlen > asoc->smallest_mtu) {
12444                         SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EMSGSIZE);
12445                         error = EMSGSIZE;
12446                         goto out_unlocked;
12447                 }
12448         }
12449         if (SCTP_SO_IS_NBIO(so)
12450             || (flags & MSG_NBIO)
12451             ) {
12452                 non_blocking = 1;
12453         }
12454         /* would we block? */
12455         if (non_blocking) {
12456                 if (hold_tcblock == 0) {
12457                         SCTP_TCB_LOCK(stcb);
12458                         hold_tcblock = 1;
12459                 }
12460                 inqueue_bytes = stcb->asoc.total_output_queue_size - (stcb->asoc.chunks_on_out_queue * sizeof(struct sctp_data_chunk));
12461                 if ((SCTP_SB_LIMIT_SND(so) < (sndlen + inqueue_bytes + stcb->asoc.sb_send_resv)) ||
12462                     (stcb->asoc.chunks_on_out_queue >= SCTP_BASE_SYSCTL(sctp_max_chunks_on_queue))) {
12463                         SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EWOULDBLOCK);
12464                         if (sndlen > SCTP_SB_LIMIT_SND(so))
12465                                 error = EMSGSIZE;
12466                         else
12467                                 error = EWOULDBLOCK;
12468                         goto out_unlocked;
12469                 }
12470                 stcb->asoc.sb_send_resv += sndlen;
12471                 SCTP_TCB_UNLOCK(stcb);
12472                 hold_tcblock = 0;
12473         } else {
12474                 atomic_add_int(&stcb->asoc.sb_send_resv, sndlen);
12475         }
12476         local_soresv = sndlen;
12477         if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
12478                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ECONNRESET);
12479                 error = ECONNRESET;
12480                 goto out_unlocked;
12481         }
12482         if (create_lock_applied) {
12483                 SCTP_ASOC_CREATE_UNLOCK(inp);
12484                 create_lock_applied = 0;
12485         }
12486         if (asoc->stream_reset_outstanding) {
12487                 /*
12488                  * Can't queue any data while stream reset is underway.
12489                  */
12490                 SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EAGAIN);
12491                 error = EAGAIN;
12492                 goto out_unlocked;
12493         }
12494         if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
12495             (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)) {
12496                 queue_only = 1;
12497         }
12498         /* we are now done with all control */
12499         if (control) {
12500                 sctp_m_freem(control);
12501                 control = NULL;
12502         }
12503         if ((SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
12504             (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
12505             (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
12506             (asoc->state & SCTP_STATE_SHUTDOWN_PENDING)) {
12507                 if (srcv->sinfo_flags & SCTP_ABORT) {
12508                         ;
12509                 } else {
12510                         SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ECONNRESET);
12511                         error = ECONNRESET;
12512                         goto out_unlocked;
12513                 }
12514         }
12515         /* Ok, we will attempt a msgsnd :> */
12516         if (p) {
12517                 p->td_ru.ru_msgsnd++;
12518         }
12519         /* Are we aborting? */
12520         if (srcv->sinfo_flags & SCTP_ABORT) {
12521                 struct mbuf *mm;
12522                 int tot_demand, tot_out = 0, max_out;
12523
12524                 SCTP_STAT_INCR(sctps_sends_with_abort);
12525                 if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
12526                     (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)) {
12527                         /* It has to be up before we abort */
12528                         /* how big is the user initiated abort? */
12529                         SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12530                         error = EINVAL;
12531                         goto out;
12532                 }
12533                 if (hold_tcblock) {
12534                         SCTP_TCB_UNLOCK(stcb);
12535                         hold_tcblock = 0;
12536                 }
12537                 if (top) {
12538                         struct mbuf *cntm = NULL;
12539
12540                         mm = sctp_get_mbuf_for_msg(sizeof(struct sctp_paramhdr), 0, M_WAIT, 1, MT_DATA);
12541                         if (sndlen != 0) {
12542                                 for (cntm = top; cntm; cntm = SCTP_BUF_NEXT(cntm)) {
12543                                         tot_out += SCTP_BUF_LEN(cntm);
12544                                 }
12545                         }
12546                 } else {
12547                         /* Must fit in a MTU */
12548                         tot_out = sndlen;
12549                         tot_demand = (tot_out + sizeof(struct sctp_paramhdr));
12550                         if (tot_demand > SCTP_DEFAULT_ADD_MORE) {
12551                                 /* To big */
12552                                 SCTP_LTRACE_ERR_RET(NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, EMSGSIZE);
12553                                 error = EMSGSIZE;
12554                                 goto out;
12555                         }
12556                         mm = sctp_get_mbuf_for_msg(tot_demand, 0, M_WAIT, 1, MT_DATA);
12557                 }
12558                 if (mm == NULL) {
12559                         SCTP_LTRACE_ERR_RET(NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
12560                         error = ENOMEM;
12561                         goto out;
12562                 }
12563                 max_out = asoc->smallest_mtu - sizeof(struct sctp_paramhdr);
12564                 max_out -= sizeof(struct sctp_abort_msg);
12565                 if (tot_out > max_out) {
12566                         tot_out = max_out;
12567                 }
12568                 if (mm) {
12569                         struct sctp_paramhdr *ph;
12570
12571                         /* now move forward the data pointer */
12572                         ph = mtod(mm, struct sctp_paramhdr *);
12573                         ph->param_type = htons(SCTP_CAUSE_USER_INITIATED_ABT);
12574                         ph->param_length = htons((sizeof(struct sctp_paramhdr) + tot_out));
12575                         ph++;
12576                         SCTP_BUF_LEN(mm) = tot_out + sizeof(struct sctp_paramhdr);
12577                         if (top == NULL) {
12578                                 error = uiomove((caddr_t)ph, (int)tot_out, uio);
12579                                 if (error) {
12580                                         /*-
12581                                          * Here if we can't get his data we
12582                                          * still abort we just don't get to
12583                                          * send the users note :-0
12584                                          */
12585                                         sctp_m_freem(mm);
12586                                         mm = NULL;
12587                                 }
12588                         } else {
12589                                 if (sndlen != 0) {
12590                                         SCTP_BUF_NEXT(mm) = top;
12591                                 }
12592                         }
12593                 }
12594                 if (hold_tcblock == 0) {
12595                         SCTP_TCB_LOCK(stcb);
12596                 }
12597                 atomic_add_int(&stcb->asoc.refcnt, -1);
12598                 free_cnt_applied = 0;
12599                 /* release this lock, otherwise we hang on ourselves */
12600                 sctp_abort_an_association(stcb->sctp_ep, stcb, mm, SCTP_SO_LOCKED);
12601                 /* now relock the stcb so everything is sane */
12602                 hold_tcblock = 0;
12603                 stcb = NULL;
12604                 /*
12605                  * In this case top is already chained to mm avoid double
12606                  * free, since we free it below if top != NULL and driver
12607                  * would free it after sending the packet out
12608                  */
12609                 if (sndlen != 0) {
12610                         top = NULL;
12611                 }
12612                 goto out_unlocked;
12613         }
12614         /* Calculate the maximum we can send */
12615         inqueue_bytes = stcb->asoc.total_output_queue_size - (stcb->asoc.chunks_on_out_queue * sizeof(struct sctp_data_chunk));
12616         if (SCTP_SB_LIMIT_SND(so) > inqueue_bytes) {
12617                 if (non_blocking) {
12618                         /* we already checked for non-blocking above. */
12619                         max_len = sndlen;
12620                 } else {
12621                         max_len = SCTP_SB_LIMIT_SND(so) - inqueue_bytes;
12622                 }
12623         } else {
12624                 max_len = 0;
12625         }
12626         if (hold_tcblock) {
12627                 SCTP_TCB_UNLOCK(stcb);
12628                 hold_tcblock = 0;
12629         }
12630         /* Is the stream no. valid? */
12631         if (srcv->sinfo_stream >= asoc->streamoutcnt) {
12632                 /* Invalid stream number */
12633                 SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12634                 error = EINVAL;
12635                 goto out_unlocked;
12636         }
12637         if (asoc->strmout == NULL) {
12638                 /* huh? software error */
12639                 SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EFAULT);
12640                 error = EFAULT;
12641                 goto out_unlocked;
12642         }
12643         /* Unless E_EOR mode is on, we must make a send FIT in one call. */
12644         if ((user_marks_eor == 0) &&
12645             (sndlen > SCTP_SB_LIMIT_SND(stcb->sctp_socket))) {
12646                 /* It will NEVER fit */
12647                 SCTP_LTRACE_ERR_RET(NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, EMSGSIZE);
12648                 error = EMSGSIZE;
12649                 goto out_unlocked;
12650         }
12651         if ((uio == NULL) && user_marks_eor) {
12652                 /*-
12653                  * We do not support eeor mode for
12654                  * sending with mbuf chains (like sendfile).
12655                  */
12656                 SCTP_LTRACE_ERR_RET(NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12657                 error = EINVAL;
12658                 goto out_unlocked;
12659         }
12660         if (user_marks_eor) {
12661                 local_add_more = min(SCTP_SB_LIMIT_SND(so), SCTP_BASE_SYSCTL(sctp_add_more_threshold));
12662         } else {
12663                 /*-
12664                  * For non-eeor the whole message must fit in
12665                  * the socket send buffer.
12666                  */
12667                 local_add_more = sndlen;
12668         }
12669         len = 0;
12670         if (non_blocking) {
12671                 goto skip_preblock;
12672         }
12673         if (((max_len <= local_add_more) &&
12674             (SCTP_SB_LIMIT_SND(so) >= local_add_more)) ||
12675             (max_len == 0) ||
12676             ((stcb->asoc.chunks_on_out_queue + stcb->asoc.stream_queue_cnt) >= SCTP_BASE_SYSCTL(sctp_max_chunks_on_queue))) {
12677                 /* No room right now ! */
12678                 SOCKBUF_LOCK(&so->so_snd);
12679                 inqueue_bytes = stcb->asoc.total_output_queue_size - (stcb->asoc.chunks_on_out_queue * sizeof(struct sctp_data_chunk));
12680                 while ((SCTP_SB_LIMIT_SND(so) < (inqueue_bytes + local_add_more)) ||
12681                     ((stcb->asoc.stream_queue_cnt + stcb->asoc.chunks_on_out_queue) >= SCTP_BASE_SYSCTL(sctp_max_chunks_on_queue))) {
12682                         SCTPDBG(SCTP_DEBUG_OUTPUT1, "pre_block limit:%u <(inq:%d + %d) || (%d+%d > %d)\n",
12683                             (unsigned int)SCTP_SB_LIMIT_SND(so),
12684                             inqueue_bytes,
12685                             local_add_more,
12686                             stcb->asoc.stream_queue_cnt,
12687                             stcb->asoc.chunks_on_out_queue,
12688                             SCTP_BASE_SYSCTL(sctp_max_chunks_on_queue));
12689                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
12690                                 sctp_log_block(SCTP_BLOCK_LOG_INTO_BLKA, asoc, sndlen);
12691                         }
12692                         be.error = 0;
12693                         stcb->block_entry = &be;
12694                         error = sbwait(&so->so_snd);
12695                         stcb->block_entry = NULL;
12696                         if (error || so->so_error || be.error) {
12697                                 if (error == 0) {
12698                                         if (so->so_error)
12699                                                 error = so->so_error;
12700                                         if (be.error) {
12701                                                 error = be.error;
12702                                         }
12703                                 }
12704                                 SOCKBUF_UNLOCK(&so->so_snd);
12705                                 goto out_unlocked;
12706                         }
12707                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
12708                                 sctp_log_block(SCTP_BLOCK_LOG_OUTOF_BLK,
12709                                     asoc, stcb->asoc.total_output_queue_size);
12710                         }
12711                         if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
12712                                 goto out_unlocked;
12713                         }
12714                         inqueue_bytes = stcb->asoc.total_output_queue_size - (stcb->asoc.chunks_on_out_queue * sizeof(struct sctp_data_chunk));
12715                 }
12716                 if (SCTP_SB_LIMIT_SND(so) > inqueue_bytes) {
12717                         max_len = SCTP_SB_LIMIT_SND(so) - inqueue_bytes;
12718                 } else {
12719                         max_len = 0;
12720                 }
12721                 SOCKBUF_UNLOCK(&so->so_snd);
12722         }
12723 skip_preblock:
12724         if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
12725                 goto out_unlocked;
12726         }
12727         /*
12728          * sndlen covers for mbuf case uio_resid covers for the non-mbuf
12729          * case NOTE: uio will be null when top/mbuf is passed
12730          */
12731         if (sndlen == 0) {
12732                 if (srcv->sinfo_flags & SCTP_EOF) {
12733                         got_all_of_the_send = 1;
12734                         goto dataless_eof;
12735                 } else {
12736                         SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12737                         error = EINVAL;
12738                         goto out;
12739                 }
12740         }
12741         if (top == NULL) {
12742                 struct sctp_stream_queue_pending *sp;
12743                 struct sctp_stream_out *strm;
12744                 uint32_t sndout;
12745
12746                 SCTP_TCB_SEND_LOCK(stcb);
12747                 if ((asoc->stream_locked) &&
12748                     (asoc->stream_locked_on != srcv->sinfo_stream)) {
12749                         SCTP_TCB_SEND_UNLOCK(stcb);
12750                         SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12751                         error = EINVAL;
12752                         goto out;
12753                 }
12754                 SCTP_TCB_SEND_UNLOCK(stcb);
12755
12756                 strm = &stcb->asoc.strmout[srcv->sinfo_stream];
12757                 if (strm->last_msg_incomplete == 0) {
12758         do_a_copy_in:
12759                         sp = sctp_copy_it_in(stcb, asoc, srcv, uio, net, max_len, user_marks_eor, &error);
12760                         if ((sp == NULL) || (error)) {
12761                                 goto out;
12762                         }
12763                         SCTP_TCB_SEND_LOCK(stcb);
12764                         if (sp->msg_is_complete) {
12765                                 strm->last_msg_incomplete = 0;
12766                                 asoc->stream_locked = 0;
12767                         } else {
12768                                 /*
12769                                  * Just got locked to this guy in case of an
12770                                  * interrupt.
12771                                  */
12772                                 strm->last_msg_incomplete = 1;
12773                                 asoc->stream_locked = 1;
12774                                 asoc->stream_locked_on = srcv->sinfo_stream;
12775                                 sp->sender_all_done = 0;
12776                         }
12777                         sctp_snd_sb_alloc(stcb, sp->length);
12778                         atomic_add_int(&asoc->stream_queue_cnt, 1);
12779                         if (srcv->sinfo_flags & SCTP_UNORDERED) {
12780                                 SCTP_STAT_INCR(sctps_sends_with_unord);
12781                         }
12782                         TAILQ_INSERT_TAIL(&strm->outqueue, sp, next);
12783                         stcb->asoc.ss_functions.sctp_ss_add_to_stream(stcb, asoc, strm, sp, 1);
12784                         SCTP_TCB_SEND_UNLOCK(stcb);
12785                 } else {
12786                         SCTP_TCB_SEND_LOCK(stcb);
12787                         sp = TAILQ_LAST(&strm->outqueue, sctp_streamhead);
12788                         SCTP_TCB_SEND_UNLOCK(stcb);
12789                         if (sp == NULL) {
12790                                 /* ???? Huh ??? last msg is gone */
12791 #ifdef INVARIANTS
12792                                 panic("Warning: Last msg marked incomplete, yet nothing left?");
12793 #else
12794                                 SCTP_PRINTF("Warning: Last msg marked incomplete, yet nothing left?\n");
12795                                 strm->last_msg_incomplete = 0;
12796 #endif
12797                                 goto do_a_copy_in;
12798
12799                         }
12800                 }
12801                 while (uio->uio_resid > 0) {
12802                         /* How much room do we have? */
12803                         struct mbuf *new_tail, *mm;
12804
12805                         if (SCTP_SB_LIMIT_SND(so) > stcb->asoc.total_output_queue_size)
12806                                 max_len = SCTP_SB_LIMIT_SND(so) - stcb->asoc.total_output_queue_size;
12807                         else
12808                                 max_len = 0;
12809
12810                         if ((max_len > SCTP_BASE_SYSCTL(sctp_add_more_threshold)) ||
12811                             (max_len && (SCTP_SB_LIMIT_SND(so) < SCTP_BASE_SYSCTL(sctp_add_more_threshold))) ||
12812                             (uio->uio_resid && (uio->uio_resid <= (int)max_len))) {
12813                                 sndout = 0;
12814                                 new_tail = NULL;
12815                                 if (hold_tcblock) {
12816                                         SCTP_TCB_UNLOCK(stcb);
12817                                         hold_tcblock = 0;
12818                                 }
12819                                 mm = sctp_copy_resume(uio, max_len, user_marks_eor, &error, &sndout, &new_tail);
12820                                 if ((mm == NULL) || error) {
12821                                         if (mm) {
12822                                                 sctp_m_freem(mm);
12823                                         }
12824                                         goto out;
12825                                 }
12826                                 /* Update the mbuf and count */
12827                                 SCTP_TCB_SEND_LOCK(stcb);
12828                                 if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
12829                                         /*
12830                                          * we need to get out. Peer probably
12831                                          * aborted.
12832                                          */
12833                                         sctp_m_freem(mm);
12834                                         if (stcb->asoc.state & SCTP_PCB_FLAGS_WAS_ABORTED) {
12835                                                 SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ECONNRESET);
12836                                                 error = ECONNRESET;
12837                                         }
12838                                         SCTP_TCB_SEND_UNLOCK(stcb);
12839                                         goto out;
12840                                 }
12841                                 if (sp->tail_mbuf) {
12842                                         /* tack it to the end */
12843                                         SCTP_BUF_NEXT(sp->tail_mbuf) = mm;
12844                                         sp->tail_mbuf = new_tail;
12845                                 } else {
12846                                         /* A stolen mbuf */
12847                                         sp->data = mm;
12848                                         sp->tail_mbuf = new_tail;
12849                                 }
12850                                 sctp_snd_sb_alloc(stcb, sndout);
12851                                 atomic_add_int(&sp->length, sndout);
12852                                 len += sndout;
12853
12854                                 /* Did we reach EOR? */
12855                                 if ((uio->uio_resid == 0) &&
12856                                     ((user_marks_eor == 0) ||
12857                                     (srcv->sinfo_flags & SCTP_EOF) ||
12858                                     (user_marks_eor && (srcv->sinfo_flags & SCTP_EOR)))) {
12859                                         sp->msg_is_complete = 1;
12860                                 } else {
12861                                         sp->msg_is_complete = 0;
12862                                 }
12863                                 SCTP_TCB_SEND_UNLOCK(stcb);
12864                         }
12865                         if (uio->uio_resid == 0) {
12866                                 /* got it all? */
12867                                 continue;
12868                         }
12869                         /* PR-SCTP? */
12870                         if ((asoc->peer_supports_prsctp) && (asoc->sent_queue_cnt_removeable > 0)) {
12871                                 /*
12872                                  * This is ugly but we must assure locking
12873                                  * order
12874                                  */
12875                                 if (hold_tcblock == 0) {
12876                                         SCTP_TCB_LOCK(stcb);
12877                                         hold_tcblock = 1;
12878                                 }
12879                                 sctp_prune_prsctp(stcb, asoc, srcv, sndlen);
12880                                 inqueue_bytes = stcb->asoc.total_output_queue_size - (stcb->asoc.chunks_on_out_queue * sizeof(struct sctp_data_chunk));
12881                                 if (SCTP_SB_LIMIT_SND(so) > stcb->asoc.total_output_queue_size)
12882                                         max_len = SCTP_SB_LIMIT_SND(so) - inqueue_bytes;
12883                                 else
12884                                         max_len = 0;
12885                                 if (max_len > 0) {
12886                                         continue;
12887                                 }
12888                                 SCTP_TCB_UNLOCK(stcb);
12889                                 hold_tcblock = 0;
12890                         }
12891                         /* wait for space now */
12892                         if (non_blocking) {
12893                                 /* Non-blocking io in place out */
12894                                 goto skip_out_eof;
12895                         }
12896                         /* What about the INIT, send it maybe */
12897                         if (queue_only_for_init) {
12898                                 if (hold_tcblock == 0) {
12899                                         SCTP_TCB_LOCK(stcb);
12900                                         hold_tcblock = 1;
12901                                 }
12902                                 if (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_OPEN) {
12903                                         /* a collision took us forward? */
12904                                         queue_only = 0;
12905                                 } else {
12906                                         sctp_send_initiate(inp, stcb, SCTP_SO_LOCKED);
12907                                         SCTP_SET_STATE(asoc, SCTP_STATE_COOKIE_WAIT);
12908                                         queue_only = 1;
12909                                 }
12910                         }
12911                         if ((net->flight_size > net->cwnd) &&
12912                             (asoc->sctp_cmt_on_off == 0)) {
12913                                 SCTP_STAT_INCR(sctps_send_cwnd_avoid);
12914                                 queue_only = 1;
12915                         } else if (asoc->ifp_had_enobuf) {
12916                                 SCTP_STAT_INCR(sctps_ifnomemqueued);
12917                                 if (net->flight_size > (2 * net->mtu)) {
12918                                         queue_only = 1;
12919                                 }
12920                                 asoc->ifp_had_enobuf = 0;
12921                         }
12922                         un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
12923                             (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
12924                         if ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY)) &&
12925                             (stcb->asoc.total_flight > 0) &&
12926                             (stcb->asoc.stream_queue_cnt < SCTP_MAX_DATA_BUNDLING) &&
12927                             (un_sent < (int)(stcb->asoc.smallest_mtu - SCTP_MIN_OVERHEAD))) {
12928
12929                                 /*-
12930                                  * Ok, Nagle is set on and we have data outstanding.
12931                                  * Don't send anything and let SACKs drive out the
12932                                  * data unless wen have a "full" segment to send.
12933                                  */
12934                                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_NAGLE_LOGGING_ENABLE) {
12935                                         sctp_log_nagle_event(stcb, SCTP_NAGLE_APPLIED);
12936                                 }
12937                                 SCTP_STAT_INCR(sctps_naglequeued);
12938                                 nagle_applies = 1;
12939                         } else {
12940                                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_NAGLE_LOGGING_ENABLE) {
12941                                         if (sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY))
12942                                                 sctp_log_nagle_event(stcb, SCTP_NAGLE_SKIPPED);
12943                                 }
12944                                 SCTP_STAT_INCR(sctps_naglesent);
12945                                 nagle_applies = 0;
12946                         }
12947                         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
12948
12949                                 sctp_misc_ints(SCTP_CWNDLOG_PRESEND, queue_only_for_init, queue_only,
12950                                     nagle_applies, un_sent);
12951                                 sctp_misc_ints(SCTP_CWNDLOG_PRESEND, stcb->asoc.total_output_queue_size,
12952                                     stcb->asoc.total_flight,
12953                                     stcb->asoc.chunks_on_out_queue, stcb->asoc.total_flight_count);
12954                         }
12955                         if (queue_only_for_init)
12956                                 queue_only_for_init = 0;
12957                         if ((queue_only == 0) && (nagle_applies == 0)) {
12958                                 /*-
12959                                  * need to start chunk output
12960                                  * before blocking.. note that if
12961                                  * a lock is already applied, then
12962                                  * the input via the net is happening
12963                                  * and I don't need to start output :-D
12964                                  */
12965                                 if (hold_tcblock == 0) {
12966                                         if (SCTP_TCB_TRYLOCK(stcb)) {
12967                                                 hold_tcblock = 1;
12968                                                 sctp_chunk_output(inp,
12969                                                     stcb,
12970                                                     SCTP_OUTPUT_FROM_USR_SEND, SCTP_SO_LOCKED);
12971                                         }
12972                                 } else {
12973                                         sctp_chunk_output(inp,
12974                                             stcb,
12975                                             SCTP_OUTPUT_FROM_USR_SEND, SCTP_SO_LOCKED);
12976                                 }
12977                                 if (hold_tcblock == 1) {
12978                                         SCTP_TCB_UNLOCK(stcb);
12979                                         hold_tcblock = 0;
12980                                 }
12981                         }
12982                         SOCKBUF_LOCK(&so->so_snd);
12983                         /*-
12984                          * This is a bit strange, but I think it will
12985                          * work. The total_output_queue_size is locked and
12986                          * protected by the TCB_LOCK, which we just released.
12987                          * There is a race that can occur between releasing it
12988                          * above, and me getting the socket lock, where sacks
12989                          * come in but we have not put the SB_WAIT on the
12990                          * so_snd buffer to get the wakeup. After the LOCK
12991                          * is applied the sack_processing will also need to
12992                          * LOCK the so->so_snd to do the actual sowwakeup(). So
12993                          * once we have the socket buffer lock if we recheck the
12994                          * size we KNOW we will get to sleep safely with the
12995                          * wakeup flag in place.
12996                          */
12997                         if (SCTP_SB_LIMIT_SND(so) <= (stcb->asoc.total_output_queue_size +
12998                             min(SCTP_BASE_SYSCTL(sctp_add_more_threshold), SCTP_SB_LIMIT_SND(so)))) {
12999                                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
13000                                         sctp_log_block(SCTP_BLOCK_LOG_INTO_BLK,
13001                                             asoc, uio->uio_resid);
13002                                 }
13003                                 be.error = 0;
13004                                 stcb->block_entry = &be;
13005                                 error = sbwait(&so->so_snd);
13006                                 stcb->block_entry = NULL;
13007
13008                                 if (error || so->so_error || be.error) {
13009                                         if (error == 0) {
13010                                                 if (so->so_error)
13011                                                         error = so->so_error;
13012                                                 if (be.error) {
13013                                                         error = be.error;
13014                                                 }
13015                                         }
13016                                         SOCKBUF_UNLOCK(&so->so_snd);
13017                                         goto out_unlocked;
13018                                 }
13019                                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
13020                                         sctp_log_block(SCTP_BLOCK_LOG_OUTOF_BLK,
13021                                             asoc, stcb->asoc.total_output_queue_size);
13022                                 }
13023                         }
13024                         SOCKBUF_UNLOCK(&so->so_snd);
13025                         if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
13026                                 goto out_unlocked;
13027                         }
13028                 }
13029                 SCTP_TCB_SEND_LOCK(stcb);
13030                 if (sp) {
13031                         if (sp->msg_is_complete == 0) {
13032                                 strm->last_msg_incomplete = 1;
13033                                 asoc->stream_locked = 1;
13034                                 asoc->stream_locked_on = srcv->sinfo_stream;
13035                         } else {
13036                                 sp->sender_all_done = 1;
13037                                 strm->last_msg_incomplete = 0;
13038                                 asoc->stream_locked = 0;
13039                         }
13040                 } else {
13041                         SCTP_PRINTF("Huh no sp TSNH?\n");
13042                         strm->last_msg_incomplete = 0;
13043                         asoc->stream_locked = 0;
13044                 }
13045                 SCTP_TCB_SEND_UNLOCK(stcb);
13046                 if (uio->uio_resid == 0) {
13047                         got_all_of_the_send = 1;
13048                 }
13049         } else {
13050                 /* We send in a 0, since we do NOT have any locks */
13051                 error = sctp_msg_append(stcb, net, top, srcv, 0);
13052                 top = NULL;
13053                 if (srcv->sinfo_flags & SCTP_EOF) {
13054                         /*
13055                          * This should only happen for Panda for the mbuf
13056                          * send case, which does NOT yet support EEOR mode.
13057                          * Thus, we can just set this flag to do the proper
13058                          * EOF handling.
13059                          */
13060                         got_all_of_the_send = 1;
13061                 }
13062         }
13063         if (error) {
13064                 goto out;
13065         }
13066 dataless_eof:
13067         /* EOF thing ? */
13068         if ((srcv->sinfo_flags & SCTP_EOF) &&
13069             (got_all_of_the_send == 1)) {
13070                 int cnt;
13071
13072                 SCTP_STAT_INCR(sctps_sends_with_eof);
13073                 error = 0;
13074                 if (hold_tcblock == 0) {
13075                         SCTP_TCB_LOCK(stcb);
13076                         hold_tcblock = 1;
13077                 }
13078                 cnt = sctp_is_there_unsent_data(stcb, SCTP_SO_LOCKED);
13079                 if (TAILQ_EMPTY(&asoc->send_queue) &&
13080                     TAILQ_EMPTY(&asoc->sent_queue) &&
13081                     (cnt == 0)) {
13082                         if (asoc->locked_on_sending) {
13083                                 goto abort_anyway;
13084                         }
13085                         /* there is nothing queued to send, so I'm done... */
13086                         if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
13087                             (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
13088                             (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
13089                                 struct sctp_nets *netp;
13090
13091                                 if (stcb->asoc.alternate) {
13092                                         netp = stcb->asoc.alternate;
13093                                 } else {
13094                                         netp = stcb->asoc.primary_destination;
13095                                 }
13096                                 /* only send SHUTDOWN the first time through */
13097                                 sctp_send_shutdown(stcb, netp);
13098                                 if (SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) {
13099                                         SCTP_STAT_DECR_GAUGE32(sctps_currestab);
13100                                 }
13101                                 SCTP_SET_STATE(asoc, SCTP_STATE_SHUTDOWN_SENT);
13102                                 SCTP_CLEAR_SUBSTATE(asoc, SCTP_STATE_SHUTDOWN_PENDING);
13103                                 sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, stcb->sctp_ep, stcb,
13104                                     netp);
13105                                 sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
13106                                     asoc->primary_destination);
13107                         }
13108                 } else {
13109                         /*-
13110                          * we still got (or just got) data to send, so set
13111                          * SHUTDOWN_PENDING
13112                          */
13113                         /*-
13114                          * XXX sockets draft says that SCTP_EOF should be
13115                          * sent with no data.  currently, we will allow user
13116                          * data to be sent first and move to
13117                          * SHUTDOWN-PENDING
13118                          */
13119                         if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
13120                             (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
13121                             (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
13122                                 if (hold_tcblock == 0) {
13123                                         SCTP_TCB_LOCK(stcb);
13124                                         hold_tcblock = 1;
13125                                 }
13126                                 if (asoc->locked_on_sending) {
13127                                         /* Locked to send out the data */
13128                                         struct sctp_stream_queue_pending *sp;
13129
13130                                         sp = TAILQ_LAST(&asoc->locked_on_sending->outqueue, sctp_streamhead);
13131                                         if (sp) {
13132                                                 if ((sp->length == 0) && (sp->msg_is_complete == 0))
13133                                                         asoc->state |= SCTP_STATE_PARTIAL_MSG_LEFT;
13134                                         }
13135                                 }
13136                                 asoc->state |= SCTP_STATE_SHUTDOWN_PENDING;
13137                                 if (TAILQ_EMPTY(&asoc->send_queue) &&
13138                                     TAILQ_EMPTY(&asoc->sent_queue) &&
13139                                     (asoc->state & SCTP_STATE_PARTIAL_MSG_LEFT)) {
13140                         abort_anyway:
13141                                         if (free_cnt_applied) {
13142                                                 atomic_add_int(&stcb->asoc.refcnt, -1);
13143                                                 free_cnt_applied = 0;
13144                                         }
13145                                         sctp_abort_an_association(stcb->sctp_ep, stcb,
13146                                             NULL, SCTP_SO_LOCKED);
13147                                         /*
13148                                          * now relock the stcb so everything
13149                                          * is sane
13150                                          */
13151                                         hold_tcblock = 0;
13152                                         stcb = NULL;
13153                                         goto out;
13154                                 }
13155                                 sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
13156                                     asoc->primary_destination);
13157                                 sctp_feature_off(inp, SCTP_PCB_FLAGS_NODELAY);
13158                         }
13159                 }
13160         }
13161 skip_out_eof:
13162         if (!TAILQ_EMPTY(&stcb->asoc.control_send_queue)) {
13163                 some_on_control = 1;
13164         }
13165         if (queue_only_for_init) {
13166                 if (hold_tcblock == 0) {
13167                         SCTP_TCB_LOCK(stcb);
13168                         hold_tcblock = 1;
13169                 }
13170                 if (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_OPEN) {
13171                         /* a collision took us forward? */
13172                         queue_only = 0;
13173                 } else {
13174                         sctp_send_initiate(inp, stcb, SCTP_SO_LOCKED);
13175                         SCTP_SET_STATE(&stcb->asoc, SCTP_STATE_COOKIE_WAIT);
13176                         queue_only = 1;
13177                 }
13178         }
13179         if ((net->flight_size > net->cwnd) &&
13180             (stcb->asoc.sctp_cmt_on_off == 0)) {
13181                 SCTP_STAT_INCR(sctps_send_cwnd_avoid);
13182                 queue_only = 1;
13183         } else if (asoc->ifp_had_enobuf) {
13184                 SCTP_STAT_INCR(sctps_ifnomemqueued);
13185                 if (net->flight_size > (2 * net->mtu)) {
13186                         queue_only = 1;
13187                 }
13188                 asoc->ifp_had_enobuf = 0;
13189         }
13190         un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
13191             (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
13192         if ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY)) &&
13193             (stcb->asoc.total_flight > 0) &&
13194             (stcb->asoc.stream_queue_cnt < SCTP_MAX_DATA_BUNDLING) &&
13195             (un_sent < (int)(stcb->asoc.smallest_mtu - SCTP_MIN_OVERHEAD))) {
13196                 /*-
13197                  * Ok, Nagle is set on and we have data outstanding.
13198                  * Don't send anything and let SACKs drive out the
13199                  * data unless wen have a "full" segment to send.
13200                  */
13201                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_NAGLE_LOGGING_ENABLE) {
13202                         sctp_log_nagle_event(stcb, SCTP_NAGLE_APPLIED);
13203                 }
13204                 SCTP_STAT_INCR(sctps_naglequeued);
13205                 nagle_applies = 1;
13206         } else {
13207                 if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_NAGLE_LOGGING_ENABLE) {
13208                         if (sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY))
13209                                 sctp_log_nagle_event(stcb, SCTP_NAGLE_SKIPPED);
13210                 }
13211                 SCTP_STAT_INCR(sctps_naglesent);
13212                 nagle_applies = 0;
13213         }
13214         if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
13215                 sctp_misc_ints(SCTP_CWNDLOG_PRESEND, queue_only_for_init, queue_only,
13216                     nagle_applies, un_sent);
13217                 sctp_misc_ints(SCTP_CWNDLOG_PRESEND, stcb->asoc.total_output_queue_size,
13218                     stcb->asoc.total_flight,
13219                     stcb->asoc.chunks_on_out_queue, stcb->asoc.total_flight_count);
13220         }
13221         if ((queue_only == 0) && (nagle_applies == 0) && (stcb->asoc.peers_rwnd && un_sent)) {
13222                 /* we can attempt to send too. */
13223                 if (hold_tcblock == 0) {
13224                         /*
13225                          * If there is activity recv'ing sacks no need to
13226                          * send
13227                          */
13228                         if (SCTP_TCB_TRYLOCK(stcb)) {
13229                                 sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_USR_SEND, SCTP_SO_LOCKED);
13230                                 hold_tcblock = 1;
13231                         }
13232                 } else {
13233                         sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_USR_SEND, SCTP_SO_LOCKED);
13234                 }
13235         } else if ((queue_only == 0) &&
13236                     (stcb->asoc.peers_rwnd == 0) &&
13237             (stcb->asoc.total_flight == 0)) {
13238                 /* We get to have a probe outstanding */
13239                 if (hold_tcblock == 0) {
13240                         hold_tcblock = 1;
13241                         SCTP_TCB_LOCK(stcb);
13242                 }
13243                 sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_USR_SEND, SCTP_SO_LOCKED);
13244         } else if (some_on_control) {
13245                 int num_out, reason, frag_point;
13246
13247                 /* Here we do control only */
13248                 if (hold_tcblock == 0) {
13249                         hold_tcblock = 1;
13250                         SCTP_TCB_LOCK(stcb);
13251                 }
13252                 frag_point = sctp_get_frag_point(stcb, &stcb->asoc);
13253                 (void)sctp_med_chunk_output(inp, stcb, &stcb->asoc, &num_out,
13254                     &reason, 1, 1, &now, &now_filled, frag_point, SCTP_SO_LOCKED);
13255         }
13256         SCTPDBG(SCTP_DEBUG_OUTPUT1, "USR Send complete qo:%d prw:%d unsent:%d tf:%d cooq:%d toqs:%d err:%d\n",
13257             queue_only, stcb->asoc.peers_rwnd, un_sent,
13258             stcb->asoc.total_flight, stcb->asoc.chunks_on_out_queue,
13259             stcb->asoc.total_output_queue_size, error);
13260
13261 out:
13262 out_unlocked:
13263
13264         if (local_soresv && stcb) {
13265                 atomic_subtract_int(&stcb->asoc.sb_send_resv, sndlen);
13266         }
13267         if (create_lock_applied) {
13268                 SCTP_ASOC_CREATE_UNLOCK(inp);
13269         }
13270         if ((stcb) && hold_tcblock) {
13271                 SCTP_TCB_UNLOCK(stcb);
13272         }
13273         if (stcb && free_cnt_applied) {
13274                 atomic_add_int(&stcb->asoc.refcnt, -1);
13275         }
13276 #ifdef INVARIANTS
13277         if (stcb) {
13278                 if (mtx_owned(&stcb->tcb_mtx)) {
13279                         panic("Leaving with tcb mtx owned?");
13280                 }
13281                 if (mtx_owned(&stcb->tcb_send_mtx)) {
13282                         panic("Leaving with tcb send mtx owned?");
13283                 }
13284         }
13285 #endif
13286 #ifdef INVARIANTS
13287         if (inp) {
13288                 sctp_validate_no_locks(inp);
13289         } else {
13290                 SCTP_PRINTF("Warning - inp is NULL so cant validate locks\n");
13291         }
13292 #endif
13293         if (top) {
13294                 sctp_m_freem(top);
13295         }
13296         if (control) {
13297                 sctp_m_freem(control);
13298         }
13299         return (error);
13300 }
13301
13302
13303 /*
13304  * generate an AUTHentication chunk, if required
13305  */
13306 struct mbuf *
13307 sctp_add_auth_chunk(struct mbuf *m, struct mbuf **m_end,
13308     struct sctp_auth_chunk **auth_ret, uint32_t * offset,
13309     struct sctp_tcb *stcb, uint8_t chunk)
13310 {
13311         struct mbuf *m_auth;
13312         struct sctp_auth_chunk *auth;
13313         int chunk_len;
13314         struct mbuf *cn;
13315
13316         if ((m_end == NULL) || (auth_ret == NULL) || (offset == NULL) ||
13317             (stcb == NULL))
13318                 return (m);
13319
13320         /* sysctl disabled auth? */
13321         if (SCTP_BASE_SYSCTL(sctp_auth_disable))
13322                 return (m);
13323
13324         /* peer doesn't do auth... */
13325         if (!stcb->asoc.peer_supports_auth) {
13326                 return (m);
13327         }
13328         /* does the requested chunk require auth? */
13329         if (!sctp_auth_is_required_chunk(chunk, stcb->asoc.peer_auth_chunks)) {
13330                 return (m);
13331         }
13332         m_auth = sctp_get_mbuf_for_msg(sizeof(*auth), 0, M_DONTWAIT, 1, MT_HEADER);
13333         if (m_auth == NULL) {
13334                 /* no mbuf's */
13335                 return (m);
13336         }
13337         /* reserve some space if this will be the first mbuf */
13338         if (m == NULL)
13339                 SCTP_BUF_RESV_UF(m_auth, SCTP_MIN_OVERHEAD);
13340         /* fill in the AUTH chunk details */
13341         auth = mtod(m_auth, struct sctp_auth_chunk *);
13342         bzero(auth, sizeof(*auth));
13343         auth->ch.chunk_type = SCTP_AUTHENTICATION;
13344         auth->ch.chunk_flags = 0;
13345         chunk_len = sizeof(*auth) +
13346             sctp_get_hmac_digest_len(stcb->asoc.peer_hmac_id);
13347         auth->ch.chunk_length = htons(chunk_len);
13348         auth->hmac_id = htons(stcb->asoc.peer_hmac_id);
13349         /* key id and hmac digest will be computed and filled in upon send */
13350
13351         /* save the offset where the auth was inserted into the chain */
13352         *offset = 0;
13353         for (cn = m; cn; cn = SCTP_BUF_NEXT(cn)) {
13354                 *offset += SCTP_BUF_LEN(cn);
13355         }
13356
13357         /* update length and return pointer to the auth chunk */
13358         SCTP_BUF_LEN(m_auth) = chunk_len;
13359         m = sctp_copy_mbufchain(m_auth, m, m_end, 1, chunk_len, 0);
13360         if (auth_ret != NULL)
13361                 *auth_ret = auth;
13362
13363         return (m);
13364 }
13365
13366 #ifdef INET6
13367 int
13368 sctp_v6src_match_nexthop(struct sockaddr_in6 *src6, sctp_route_t * ro)
13369 {
13370         struct nd_prefix *pfx = NULL;
13371         struct nd_pfxrouter *pfxrtr = NULL;
13372         struct sockaddr_in6 gw6;
13373
13374         if (ro == NULL || ro->ro_rt == NULL || src6->sin6_family != AF_INET6)
13375                 return (0);
13376
13377         /* get prefix entry of address */
13378         LIST_FOREACH(pfx, &MODULE_GLOBAL(nd_prefix), ndpr_entry) {
13379                 if (pfx->ndpr_stateflags & NDPRF_DETACHED)
13380                         continue;
13381                 if (IN6_ARE_MASKED_ADDR_EQUAL(&pfx->ndpr_prefix.sin6_addr,
13382                     &src6->sin6_addr, &pfx->ndpr_mask))
13383                         break;
13384         }
13385         /* no prefix entry in the prefix list */
13386         if (pfx == NULL) {
13387                 SCTPDBG(SCTP_DEBUG_OUTPUT2, "No prefix entry for ");
13388                 SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, (struct sockaddr *)src6);
13389                 return (0);
13390         }
13391         SCTPDBG(SCTP_DEBUG_OUTPUT2, "v6src_match_nexthop(), Prefix entry is ");
13392         SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, (struct sockaddr *)src6);
13393
13394         /* search installed gateway from prefix entry */
13395         LIST_FOREACH(pfxrtr, &pfx->ndpr_advrtrs, pfr_entry) {
13396                 memset(&gw6, 0, sizeof(struct sockaddr_in6));
13397                 gw6.sin6_family = AF_INET6;
13398                 gw6.sin6_len = sizeof(struct sockaddr_in6);
13399                 memcpy(&gw6.sin6_addr, &pfxrtr->router->rtaddr,
13400                     sizeof(struct in6_addr));
13401                 SCTPDBG(SCTP_DEBUG_OUTPUT2, "prefix router is ");
13402                 SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, (struct sockaddr *)&gw6);
13403                 SCTPDBG(SCTP_DEBUG_OUTPUT2, "installed router is ");
13404                 SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, ro->ro_rt->rt_gateway);
13405                 if (sctp_cmpaddr((struct sockaddr *)&gw6,
13406                     ro->ro_rt->rt_gateway)) {
13407                         SCTPDBG(SCTP_DEBUG_OUTPUT2, "pfxrouter is installed\n");
13408                         return (1);
13409                 }
13410         }
13411         SCTPDBG(SCTP_DEBUG_OUTPUT2, "pfxrouter is not installed\n");
13412         return (0);
13413 }
13414
13415 #endif
13416
13417 int
13418 sctp_v4src_match_nexthop(struct sctp_ifa *sifa, sctp_route_t * ro)
13419 {
13420 #ifdef INET
13421         struct sockaddr_in *sin, *mask;
13422         struct ifaddr *ifa;
13423         struct in_addr srcnetaddr, gwnetaddr;
13424
13425         if (ro == NULL || ro->ro_rt == NULL ||
13426             sifa->address.sa.sa_family != AF_INET) {
13427                 return (0);
13428         }
13429         ifa = (struct ifaddr *)sifa->ifa;
13430         mask = (struct sockaddr_in *)(ifa->ifa_netmask);
13431         sin = (struct sockaddr_in *)&sifa->address.sin;
13432         srcnetaddr.s_addr = (sin->sin_addr.s_addr & mask->sin_addr.s_addr);
13433         SCTPDBG(SCTP_DEBUG_OUTPUT1, "match_nexthop4: src address is ");
13434         SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, &sifa->address.sa);
13435         SCTPDBG(SCTP_DEBUG_OUTPUT1, "network address is %x\n", srcnetaddr.s_addr);
13436
13437         sin = (struct sockaddr_in *)ro->ro_rt->rt_gateway;
13438         gwnetaddr.s_addr = (sin->sin_addr.s_addr & mask->sin_addr.s_addr);
13439         SCTPDBG(SCTP_DEBUG_OUTPUT1, "match_nexthop4: nexthop is ");
13440         SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, ro->ro_rt->rt_gateway);
13441         SCTPDBG(SCTP_DEBUG_OUTPUT1, "network address is %x\n", gwnetaddr.s_addr);
13442         if (srcnetaddr.s_addr == gwnetaddr.s_addr) {
13443                 return (1);
13444         }
13445 #endif
13446         return (0);
13447 }