xref: /freebsd-src/sys/netinet/sctp_output.c (revision 3abc9103eb34adbb48853f2361206eba207d6c4f)
1 /*-
2  * Copyright (c) 2001-2007, by Cisco Systems, Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  * a) Redistributions of source code must retain the above copyright notice,
8  *   this list of conditions and the following disclaimer.
9  *
10  * b) Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in
12  *   the documentation and/or other materials provided with the distribution.
13  *
14  * c) Neither the name of Cisco Systems, Inc. nor the names of its
15  *    contributors may be used to endorse or promote products derived
16  *    from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
20  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
28  * THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 /* $KAME: sctp_output.c,v 1.46 2005/03/06 16:04:17 itojun Exp $	 */
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 
53 
54 
55 #define SCTP_MAX_GAPS_INARRAY 4
56 struct sack_track {
57 	uint8_t right_edge;	/* mergable on the right edge */
58 	uint8_t left_edge;	/* mergable on the left edge */
59 	uint8_t num_entries;
60 	uint8_t spare;
61 	struct sctp_gap_ack_block gaps[SCTP_MAX_GAPS_INARRAY];
62 };
63 
64 struct sack_track sack_array[256] = {
65 	{0, 0, 0, 0,		/* 0x00 */
66 		{{0, 0},
67 		{0, 0},
68 		{0, 0},
69 		{0, 0}
70 		}
71 	},
72 	{1, 0, 1, 0,		/* 0x01 */
73 		{{0, 0},
74 		{0, 0},
75 		{0, 0},
76 		{0, 0}
77 		}
78 	},
79 	{0, 0, 1, 0,		/* 0x02 */
80 		{{1, 1},
81 		{0, 0},
82 		{0, 0},
83 		{0, 0}
84 		}
85 	},
86 	{1, 0, 1, 0,		/* 0x03 */
87 		{{0, 1},
88 		{0, 0},
89 		{0, 0},
90 		{0, 0}
91 		}
92 	},
93 	{0, 0, 1, 0,		/* 0x04 */
94 		{{2, 2},
95 		{0, 0},
96 		{0, 0},
97 		{0, 0}
98 		}
99 	},
100 	{1, 0, 2, 0,		/* 0x05 */
101 		{{0, 0},
102 		{2, 2},
103 		{0, 0},
104 		{0, 0}
105 		}
106 	},
107 	{0, 0, 1, 0,		/* 0x06 */
108 		{{1, 2},
109 		{0, 0},
110 		{0, 0},
111 		{0, 0}
112 		}
113 	},
114 	{1, 0, 1, 0,		/* 0x07 */
115 		{{0, 2},
116 		{0, 0},
117 		{0, 0},
118 		{0, 0}
119 		}
120 	},
121 	{0, 0, 1, 0,		/* 0x08 */
122 		{{3, 3},
123 		{0, 0},
124 		{0, 0},
125 		{0, 0}
126 		}
127 	},
128 	{1, 0, 2, 0,		/* 0x09 */
129 		{{0, 0},
130 		{3, 3},
131 		{0, 0},
132 		{0, 0}
133 		}
134 	},
135 	{0, 0, 2, 0,		/* 0x0a */
136 		{{1, 1},
137 		{3, 3},
138 		{0, 0},
139 		{0, 0}
140 		}
141 	},
142 	{1, 0, 2, 0,		/* 0x0b */
143 		{{0, 1},
144 		{3, 3},
145 		{0, 0},
146 		{0, 0}
147 		}
148 	},
149 	{0, 0, 1, 0,		/* 0x0c */
150 		{{2, 3},
151 		{0, 0},
152 		{0, 0},
153 		{0, 0}
154 		}
155 	},
156 	{1, 0, 2, 0,		/* 0x0d */
157 		{{0, 0},
158 		{2, 3},
159 		{0, 0},
160 		{0, 0}
161 		}
162 	},
163 	{0, 0, 1, 0,		/* 0x0e */
164 		{{1, 3},
165 		{0, 0},
166 		{0, 0},
167 		{0, 0}
168 		}
169 	},
170 	{1, 0, 1, 0,		/* 0x0f */
171 		{{0, 3},
172 		{0, 0},
173 		{0, 0},
174 		{0, 0}
175 		}
176 	},
177 	{0, 0, 1, 0,		/* 0x10 */
178 		{{4, 4},
179 		{0, 0},
180 		{0, 0},
181 		{0, 0}
182 		}
183 	},
184 	{1, 0, 2, 0,		/* 0x11 */
185 		{{0, 0},
186 		{4, 4},
187 		{0, 0},
188 		{0, 0}
189 		}
190 	},
191 	{0, 0, 2, 0,		/* 0x12 */
192 		{{1, 1},
193 		{4, 4},
194 		{0, 0},
195 		{0, 0}
196 		}
197 	},
198 	{1, 0, 2, 0,		/* 0x13 */
199 		{{0, 1},
200 		{4, 4},
201 		{0, 0},
202 		{0, 0}
203 		}
204 	},
205 	{0, 0, 2, 0,		/* 0x14 */
206 		{{2, 2},
207 		{4, 4},
208 		{0, 0},
209 		{0, 0}
210 		}
211 	},
212 	{1, 0, 3, 0,		/* 0x15 */
213 		{{0, 0},
214 		{2, 2},
215 		{4, 4},
216 		{0, 0}
217 		}
218 	},
219 	{0, 0, 2, 0,		/* 0x16 */
220 		{{1, 2},
221 		{4, 4},
222 		{0, 0},
223 		{0, 0}
224 		}
225 	},
226 	{1, 0, 2, 0,		/* 0x17 */
227 		{{0, 2},
228 		{4, 4},
229 		{0, 0},
230 		{0, 0}
231 		}
232 	},
233 	{0, 0, 1, 0,		/* 0x18 */
234 		{{3, 4},
235 		{0, 0},
236 		{0, 0},
237 		{0, 0}
238 		}
239 	},
240 	{1, 0, 2, 0,		/* 0x19 */
241 		{{0, 0},
242 		{3, 4},
243 		{0, 0},
244 		{0, 0}
245 		}
246 	},
247 	{0, 0, 2, 0,		/* 0x1a */
248 		{{1, 1},
249 		{3, 4},
250 		{0, 0},
251 		{0, 0}
252 		}
253 	},
254 	{1, 0, 2, 0,		/* 0x1b */
255 		{{0, 1},
256 		{3, 4},
257 		{0, 0},
258 		{0, 0}
259 		}
260 	},
261 	{0, 0, 1, 0,		/* 0x1c */
262 		{{2, 4},
263 		{0, 0},
264 		{0, 0},
265 		{0, 0}
266 		}
267 	},
268 	{1, 0, 2, 0,		/* 0x1d */
269 		{{0, 0},
270 		{2, 4},
271 		{0, 0},
272 		{0, 0}
273 		}
274 	},
275 	{0, 0, 1, 0,		/* 0x1e */
276 		{{1, 4},
277 		{0, 0},
278 		{0, 0},
279 		{0, 0}
280 		}
281 	},
282 	{1, 0, 1, 0,		/* 0x1f */
283 		{{0, 4},
284 		{0, 0},
285 		{0, 0},
286 		{0, 0}
287 		}
288 	},
289 	{0, 0, 1, 0,		/* 0x20 */
290 		{{5, 5},
291 		{0, 0},
292 		{0, 0},
293 		{0, 0}
294 		}
295 	},
296 	{1, 0, 2, 0,		/* 0x21 */
297 		{{0, 0},
298 		{5, 5},
299 		{0, 0},
300 		{0, 0}
301 		}
302 	},
303 	{0, 0, 2, 0,		/* 0x22 */
304 		{{1, 1},
305 		{5, 5},
306 		{0, 0},
307 		{0, 0}
308 		}
309 	},
310 	{1, 0, 2, 0,		/* 0x23 */
311 		{{0, 1},
312 		{5, 5},
313 		{0, 0},
314 		{0, 0}
315 		}
316 	},
317 	{0, 0, 2, 0,		/* 0x24 */
318 		{{2, 2},
319 		{5, 5},
320 		{0, 0},
321 		{0, 0}
322 		}
323 	},
324 	{1, 0, 3, 0,		/* 0x25 */
325 		{{0, 0},
326 		{2, 2},
327 		{5, 5},
328 		{0, 0}
329 		}
330 	},
331 	{0, 0, 2, 0,		/* 0x26 */
332 		{{1, 2},
333 		{5, 5},
334 		{0, 0},
335 		{0, 0}
336 		}
337 	},
338 	{1, 0, 2, 0,		/* 0x27 */
339 		{{0, 2},
340 		{5, 5},
341 		{0, 0},
342 		{0, 0}
343 		}
344 	},
345 	{0, 0, 2, 0,		/* 0x28 */
346 		{{3, 3},
347 		{5, 5},
348 		{0, 0},
349 		{0, 0}
350 		}
351 	},
352 	{1, 0, 3, 0,		/* 0x29 */
353 		{{0, 0},
354 		{3, 3},
355 		{5, 5},
356 		{0, 0}
357 		}
358 	},
359 	{0, 0, 3, 0,		/* 0x2a */
360 		{{1, 1},
361 		{3, 3},
362 		{5, 5},
363 		{0, 0}
364 		}
365 	},
366 	{1, 0, 3, 0,		/* 0x2b */
367 		{{0, 1},
368 		{3, 3},
369 		{5, 5},
370 		{0, 0}
371 		}
372 	},
373 	{0, 0, 2, 0,		/* 0x2c */
374 		{{2, 3},
375 		{5, 5},
376 		{0, 0},
377 		{0, 0}
378 		}
379 	},
380 	{1, 0, 3, 0,		/* 0x2d */
381 		{{0, 0},
382 		{2, 3},
383 		{5, 5},
384 		{0, 0}
385 		}
386 	},
387 	{0, 0, 2, 0,		/* 0x2e */
388 		{{1, 3},
389 		{5, 5},
390 		{0, 0},
391 		{0, 0}
392 		}
393 	},
394 	{1, 0, 2, 0,		/* 0x2f */
395 		{{0, 3},
396 		{5, 5},
397 		{0, 0},
398 		{0, 0}
399 		}
400 	},
401 	{0, 0, 1, 0,		/* 0x30 */
402 		{{4, 5},
403 		{0, 0},
404 		{0, 0},
405 		{0, 0}
406 		}
407 	},
408 	{1, 0, 2, 0,		/* 0x31 */
409 		{{0, 0},
410 		{4, 5},
411 		{0, 0},
412 		{0, 0}
413 		}
414 	},
415 	{0, 0, 2, 0,		/* 0x32 */
416 		{{1, 1},
417 		{4, 5},
418 		{0, 0},
419 		{0, 0}
420 		}
421 	},
422 	{1, 0, 2, 0,		/* 0x33 */
423 		{{0, 1},
424 		{4, 5},
425 		{0, 0},
426 		{0, 0}
427 		}
428 	},
429 	{0, 0, 2, 0,		/* 0x34 */
430 		{{2, 2},
431 		{4, 5},
432 		{0, 0},
433 		{0, 0}
434 		}
435 	},
436 	{1, 0, 3, 0,		/* 0x35 */
437 		{{0, 0},
438 		{2, 2},
439 		{4, 5},
440 		{0, 0}
441 		}
442 	},
443 	{0, 0, 2, 0,		/* 0x36 */
444 		{{1, 2},
445 		{4, 5},
446 		{0, 0},
447 		{0, 0}
448 		}
449 	},
450 	{1, 0, 2, 0,		/* 0x37 */
451 		{{0, 2},
452 		{4, 5},
453 		{0, 0},
454 		{0, 0}
455 		}
456 	},
457 	{0, 0, 1, 0,		/* 0x38 */
458 		{{3, 5},
459 		{0, 0},
460 		{0, 0},
461 		{0, 0}
462 		}
463 	},
464 	{1, 0, 2, 0,		/* 0x39 */
465 		{{0, 0},
466 		{3, 5},
467 		{0, 0},
468 		{0, 0}
469 		}
470 	},
471 	{0, 0, 2, 0,		/* 0x3a */
472 		{{1, 1},
473 		{3, 5},
474 		{0, 0},
475 		{0, 0}
476 		}
477 	},
478 	{1, 0, 2, 0,		/* 0x3b */
479 		{{0, 1},
480 		{3, 5},
481 		{0, 0},
482 		{0, 0}
483 		}
484 	},
485 	{0, 0, 1, 0,		/* 0x3c */
486 		{{2, 5},
487 		{0, 0},
488 		{0, 0},
489 		{0, 0}
490 		}
491 	},
492 	{1, 0, 2, 0,		/* 0x3d */
493 		{{0, 0},
494 		{2, 5},
495 		{0, 0},
496 		{0, 0}
497 		}
498 	},
499 	{0, 0, 1, 0,		/* 0x3e */
500 		{{1, 5},
501 		{0, 0},
502 		{0, 0},
503 		{0, 0}
504 		}
505 	},
506 	{1, 0, 1, 0,		/* 0x3f */
507 		{{0, 5},
508 		{0, 0},
509 		{0, 0},
510 		{0, 0}
511 		}
512 	},
513 	{0, 0, 1, 0,		/* 0x40 */
514 		{{6, 6},
515 		{0, 0},
516 		{0, 0},
517 		{0, 0}
518 		}
519 	},
520 	{1, 0, 2, 0,		/* 0x41 */
521 		{{0, 0},
522 		{6, 6},
523 		{0, 0},
524 		{0, 0}
525 		}
526 	},
527 	{0, 0, 2, 0,		/* 0x42 */
528 		{{1, 1},
529 		{6, 6},
530 		{0, 0},
531 		{0, 0}
532 		}
533 	},
534 	{1, 0, 2, 0,		/* 0x43 */
535 		{{0, 1},
536 		{6, 6},
537 		{0, 0},
538 		{0, 0}
539 		}
540 	},
541 	{0, 0, 2, 0,		/* 0x44 */
542 		{{2, 2},
543 		{6, 6},
544 		{0, 0},
545 		{0, 0}
546 		}
547 	},
548 	{1, 0, 3, 0,		/* 0x45 */
549 		{{0, 0},
550 		{2, 2},
551 		{6, 6},
552 		{0, 0}
553 		}
554 	},
555 	{0, 0, 2, 0,		/* 0x46 */
556 		{{1, 2},
557 		{6, 6},
558 		{0, 0},
559 		{0, 0}
560 		}
561 	},
562 	{1, 0, 2, 0,		/* 0x47 */
563 		{{0, 2},
564 		{6, 6},
565 		{0, 0},
566 		{0, 0}
567 		}
568 	},
569 	{0, 0, 2, 0,		/* 0x48 */
570 		{{3, 3},
571 		{6, 6},
572 		{0, 0},
573 		{0, 0}
574 		}
575 	},
576 	{1, 0, 3, 0,		/* 0x49 */
577 		{{0, 0},
578 		{3, 3},
579 		{6, 6},
580 		{0, 0}
581 		}
582 	},
583 	{0, 0, 3, 0,		/* 0x4a */
584 		{{1, 1},
585 		{3, 3},
586 		{6, 6},
587 		{0, 0}
588 		}
589 	},
590 	{1, 0, 3, 0,		/* 0x4b */
591 		{{0, 1},
592 		{3, 3},
593 		{6, 6},
594 		{0, 0}
595 		}
596 	},
597 	{0, 0, 2, 0,		/* 0x4c */
598 		{{2, 3},
599 		{6, 6},
600 		{0, 0},
601 		{0, 0}
602 		}
603 	},
604 	{1, 0, 3, 0,		/* 0x4d */
605 		{{0, 0},
606 		{2, 3},
607 		{6, 6},
608 		{0, 0}
609 		}
610 	},
611 	{0, 0, 2, 0,		/* 0x4e */
612 		{{1, 3},
613 		{6, 6},
614 		{0, 0},
615 		{0, 0}
616 		}
617 	},
618 	{1, 0, 2, 0,		/* 0x4f */
619 		{{0, 3},
620 		{6, 6},
621 		{0, 0},
622 		{0, 0}
623 		}
624 	},
625 	{0, 0, 2, 0,		/* 0x50 */
626 		{{4, 4},
627 		{6, 6},
628 		{0, 0},
629 		{0, 0}
630 		}
631 	},
632 	{1, 0, 3, 0,		/* 0x51 */
633 		{{0, 0},
634 		{4, 4},
635 		{6, 6},
636 		{0, 0}
637 		}
638 	},
639 	{0, 0, 3, 0,		/* 0x52 */
640 		{{1, 1},
641 		{4, 4},
642 		{6, 6},
643 		{0, 0}
644 		}
645 	},
646 	{1, 0, 3, 0,		/* 0x53 */
647 		{{0, 1},
648 		{4, 4},
649 		{6, 6},
650 		{0, 0}
651 		}
652 	},
653 	{0, 0, 3, 0,		/* 0x54 */
654 		{{2, 2},
655 		{4, 4},
656 		{6, 6},
657 		{0, 0}
658 		}
659 	},
660 	{1, 0, 4, 0,		/* 0x55 */
661 		{{0, 0},
662 		{2, 2},
663 		{4, 4},
664 		{6, 6}
665 		}
666 	},
667 	{0, 0, 3, 0,		/* 0x56 */
668 		{{1, 2},
669 		{4, 4},
670 		{6, 6},
671 		{0, 0}
672 		}
673 	},
674 	{1, 0, 3, 0,		/* 0x57 */
675 		{{0, 2},
676 		{4, 4},
677 		{6, 6},
678 		{0, 0}
679 		}
680 	},
681 	{0, 0, 2, 0,		/* 0x58 */
682 		{{3, 4},
683 		{6, 6},
684 		{0, 0},
685 		{0, 0}
686 		}
687 	},
688 	{1, 0, 3, 0,		/* 0x59 */
689 		{{0, 0},
690 		{3, 4},
691 		{6, 6},
692 		{0, 0}
693 		}
694 	},
695 	{0, 0, 3, 0,		/* 0x5a */
696 		{{1, 1},
697 		{3, 4},
698 		{6, 6},
699 		{0, 0}
700 		}
701 	},
702 	{1, 0, 3, 0,		/* 0x5b */
703 		{{0, 1},
704 		{3, 4},
705 		{6, 6},
706 		{0, 0}
707 		}
708 	},
709 	{0, 0, 2, 0,		/* 0x5c */
710 		{{2, 4},
711 		{6, 6},
712 		{0, 0},
713 		{0, 0}
714 		}
715 	},
716 	{1, 0, 3, 0,		/* 0x5d */
717 		{{0, 0},
718 		{2, 4},
719 		{6, 6},
720 		{0, 0}
721 		}
722 	},
723 	{0, 0, 2, 0,		/* 0x5e */
724 		{{1, 4},
725 		{6, 6},
726 		{0, 0},
727 		{0, 0}
728 		}
729 	},
730 	{1, 0, 2, 0,		/* 0x5f */
731 		{{0, 4},
732 		{6, 6},
733 		{0, 0},
734 		{0, 0}
735 		}
736 	},
737 	{0, 0, 1, 0,		/* 0x60 */
738 		{{5, 6},
739 		{0, 0},
740 		{0, 0},
741 		{0, 0}
742 		}
743 	},
744 	{1, 0, 2, 0,		/* 0x61 */
745 		{{0, 0},
746 		{5, 6},
747 		{0, 0},
748 		{0, 0}
749 		}
750 	},
751 	{0, 0, 2, 0,		/* 0x62 */
752 		{{1, 1},
753 		{5, 6},
754 		{0, 0},
755 		{0, 0}
756 		}
757 	},
758 	{1, 0, 2, 0,		/* 0x63 */
759 		{{0, 1},
760 		{5, 6},
761 		{0, 0},
762 		{0, 0}
763 		}
764 	},
765 	{0, 0, 2, 0,		/* 0x64 */
766 		{{2, 2},
767 		{5, 6},
768 		{0, 0},
769 		{0, 0}
770 		}
771 	},
772 	{1, 0, 3, 0,		/* 0x65 */
773 		{{0, 0},
774 		{2, 2},
775 		{5, 6},
776 		{0, 0}
777 		}
778 	},
779 	{0, 0, 2, 0,		/* 0x66 */
780 		{{1, 2},
781 		{5, 6},
782 		{0, 0},
783 		{0, 0}
784 		}
785 	},
786 	{1, 0, 2, 0,		/* 0x67 */
787 		{{0, 2},
788 		{5, 6},
789 		{0, 0},
790 		{0, 0}
791 		}
792 	},
793 	{0, 0, 2, 0,		/* 0x68 */
794 		{{3, 3},
795 		{5, 6},
796 		{0, 0},
797 		{0, 0}
798 		}
799 	},
800 	{1, 0, 3, 0,		/* 0x69 */
801 		{{0, 0},
802 		{3, 3},
803 		{5, 6},
804 		{0, 0}
805 		}
806 	},
807 	{0, 0, 3, 0,		/* 0x6a */
808 		{{1, 1},
809 		{3, 3},
810 		{5, 6},
811 		{0, 0}
812 		}
813 	},
814 	{1, 0, 3, 0,		/* 0x6b */
815 		{{0, 1},
816 		{3, 3},
817 		{5, 6},
818 		{0, 0}
819 		}
820 	},
821 	{0, 0, 2, 0,		/* 0x6c */
822 		{{2, 3},
823 		{5, 6},
824 		{0, 0},
825 		{0, 0}
826 		}
827 	},
828 	{1, 0, 3, 0,		/* 0x6d */
829 		{{0, 0},
830 		{2, 3},
831 		{5, 6},
832 		{0, 0}
833 		}
834 	},
835 	{0, 0, 2, 0,		/* 0x6e */
836 		{{1, 3},
837 		{5, 6},
838 		{0, 0},
839 		{0, 0}
840 		}
841 	},
842 	{1, 0, 2, 0,		/* 0x6f */
843 		{{0, 3},
844 		{5, 6},
845 		{0, 0},
846 		{0, 0}
847 		}
848 	},
849 	{0, 0, 1, 0,		/* 0x70 */
850 		{{4, 6},
851 		{0, 0},
852 		{0, 0},
853 		{0, 0}
854 		}
855 	},
856 	{1, 0, 2, 0,		/* 0x71 */
857 		{{0, 0},
858 		{4, 6},
859 		{0, 0},
860 		{0, 0}
861 		}
862 	},
863 	{0, 0, 2, 0,		/* 0x72 */
864 		{{1, 1},
865 		{4, 6},
866 		{0, 0},
867 		{0, 0}
868 		}
869 	},
870 	{1, 0, 2, 0,		/* 0x73 */
871 		{{0, 1},
872 		{4, 6},
873 		{0, 0},
874 		{0, 0}
875 		}
876 	},
877 	{0, 0, 2, 0,		/* 0x74 */
878 		{{2, 2},
879 		{4, 6},
880 		{0, 0},
881 		{0, 0}
882 		}
883 	},
884 	{1, 0, 3, 0,		/* 0x75 */
885 		{{0, 0},
886 		{2, 2},
887 		{4, 6},
888 		{0, 0}
889 		}
890 	},
891 	{0, 0, 2, 0,		/* 0x76 */
892 		{{1, 2},
893 		{4, 6},
894 		{0, 0},
895 		{0, 0}
896 		}
897 	},
898 	{1, 0, 2, 0,		/* 0x77 */
899 		{{0, 2},
900 		{4, 6},
901 		{0, 0},
902 		{0, 0}
903 		}
904 	},
905 	{0, 0, 1, 0,		/* 0x78 */
906 		{{3, 6},
907 		{0, 0},
908 		{0, 0},
909 		{0, 0}
910 		}
911 	},
912 	{1, 0, 2, 0,		/* 0x79 */
913 		{{0, 0},
914 		{3, 6},
915 		{0, 0},
916 		{0, 0}
917 		}
918 	},
919 	{0, 0, 2, 0,		/* 0x7a */
920 		{{1, 1},
921 		{3, 6},
922 		{0, 0},
923 		{0, 0}
924 		}
925 	},
926 	{1, 0, 2, 0,		/* 0x7b */
927 		{{0, 1},
928 		{3, 6},
929 		{0, 0},
930 		{0, 0}
931 		}
932 	},
933 	{0, 0, 1, 0,		/* 0x7c */
934 		{{2, 6},
935 		{0, 0},
936 		{0, 0},
937 		{0, 0}
938 		}
939 	},
940 	{1, 0, 2, 0,		/* 0x7d */
941 		{{0, 0},
942 		{2, 6},
943 		{0, 0},
944 		{0, 0}
945 		}
946 	},
947 	{0, 0, 1, 0,		/* 0x7e */
948 		{{1, 6},
949 		{0, 0},
950 		{0, 0},
951 		{0, 0}
952 		}
953 	},
954 	{1, 0, 1, 0,		/* 0x7f */
955 		{{0, 6},
956 		{0, 0},
957 		{0, 0},
958 		{0, 0}
959 		}
960 	},
961 	{0, 1, 1, 0,		/* 0x80 */
962 		{{7, 7},
963 		{0, 0},
964 		{0, 0},
965 		{0, 0}
966 		}
967 	},
968 	{1, 1, 2, 0,		/* 0x81 */
969 		{{0, 0},
970 		{7, 7},
971 		{0, 0},
972 		{0, 0}
973 		}
974 	},
975 	{0, 1, 2, 0,		/* 0x82 */
976 		{{1, 1},
977 		{7, 7},
978 		{0, 0},
979 		{0, 0}
980 		}
981 	},
982 	{1, 1, 2, 0,		/* 0x83 */
983 		{{0, 1},
984 		{7, 7},
985 		{0, 0},
986 		{0, 0}
987 		}
988 	},
989 	{0, 1, 2, 0,		/* 0x84 */
990 		{{2, 2},
991 		{7, 7},
992 		{0, 0},
993 		{0, 0}
994 		}
995 	},
996 	{1, 1, 3, 0,		/* 0x85 */
997 		{{0, 0},
998 		{2, 2},
999 		{7, 7},
1000 		{0, 0}
1001 		}
1002 	},
1003 	{0, 1, 2, 0,		/* 0x86 */
1004 		{{1, 2},
1005 		{7, 7},
1006 		{0, 0},
1007 		{0, 0}
1008 		}
1009 	},
1010 	{1, 1, 2, 0,		/* 0x87 */
1011 		{{0, 2},
1012 		{7, 7},
1013 		{0, 0},
1014 		{0, 0}
1015 		}
1016 	},
1017 	{0, 1, 2, 0,		/* 0x88 */
1018 		{{3, 3},
1019 		{7, 7},
1020 		{0, 0},
1021 		{0, 0}
1022 		}
1023 	},
1024 	{1, 1, 3, 0,		/* 0x89 */
1025 		{{0, 0},
1026 		{3, 3},
1027 		{7, 7},
1028 		{0, 0}
1029 		}
1030 	},
1031 	{0, 1, 3, 0,		/* 0x8a */
1032 		{{1, 1},
1033 		{3, 3},
1034 		{7, 7},
1035 		{0, 0}
1036 		}
1037 	},
1038 	{1, 1, 3, 0,		/* 0x8b */
1039 		{{0, 1},
1040 		{3, 3},
1041 		{7, 7},
1042 		{0, 0}
1043 		}
1044 	},
1045 	{0, 1, 2, 0,		/* 0x8c */
1046 		{{2, 3},
1047 		{7, 7},
1048 		{0, 0},
1049 		{0, 0}
1050 		}
1051 	},
1052 	{1, 1, 3, 0,		/* 0x8d */
1053 		{{0, 0},
1054 		{2, 3},
1055 		{7, 7},
1056 		{0, 0}
1057 		}
1058 	},
1059 	{0, 1, 2, 0,		/* 0x8e */
1060 		{{1, 3},
1061 		{7, 7},
1062 		{0, 0},
1063 		{0, 0}
1064 		}
1065 	},
1066 	{1, 1, 2, 0,		/* 0x8f */
1067 		{{0, 3},
1068 		{7, 7},
1069 		{0, 0},
1070 		{0, 0}
1071 		}
1072 	},
1073 	{0, 1, 2, 0,		/* 0x90 */
1074 		{{4, 4},
1075 		{7, 7},
1076 		{0, 0},
1077 		{0, 0}
1078 		}
1079 	},
1080 	{1, 1, 3, 0,		/* 0x91 */
1081 		{{0, 0},
1082 		{4, 4},
1083 		{7, 7},
1084 		{0, 0}
1085 		}
1086 	},
1087 	{0, 1, 3, 0,		/* 0x92 */
1088 		{{1, 1},
1089 		{4, 4},
1090 		{7, 7},
1091 		{0, 0}
1092 		}
1093 	},
1094 	{1, 1, 3, 0,		/* 0x93 */
1095 		{{0, 1},
1096 		{4, 4},
1097 		{7, 7},
1098 		{0, 0}
1099 		}
1100 	},
1101 	{0, 1, 3, 0,		/* 0x94 */
1102 		{{2, 2},
1103 		{4, 4},
1104 		{7, 7},
1105 		{0, 0}
1106 		}
1107 	},
1108 	{1, 1, 4, 0,		/* 0x95 */
1109 		{{0, 0},
1110 		{2, 2},
1111 		{4, 4},
1112 		{7, 7}
1113 		}
1114 	},
1115 	{0, 1, 3, 0,		/* 0x96 */
1116 		{{1, 2},
1117 		{4, 4},
1118 		{7, 7},
1119 		{0, 0}
1120 		}
1121 	},
1122 	{1, 1, 3, 0,		/* 0x97 */
1123 		{{0, 2},
1124 		{4, 4},
1125 		{7, 7},
1126 		{0, 0}
1127 		}
1128 	},
1129 	{0, 1, 2, 0,		/* 0x98 */
1130 		{{3, 4},
1131 		{7, 7},
1132 		{0, 0},
1133 		{0, 0}
1134 		}
1135 	},
1136 	{1, 1, 3, 0,		/* 0x99 */
1137 		{{0, 0},
1138 		{3, 4},
1139 		{7, 7},
1140 		{0, 0}
1141 		}
1142 	},
1143 	{0, 1, 3, 0,		/* 0x9a */
1144 		{{1, 1},
1145 		{3, 4},
1146 		{7, 7},
1147 		{0, 0}
1148 		}
1149 	},
1150 	{1, 1, 3, 0,		/* 0x9b */
1151 		{{0, 1},
1152 		{3, 4},
1153 		{7, 7},
1154 		{0, 0}
1155 		}
1156 	},
1157 	{0, 1, 2, 0,		/* 0x9c */
1158 		{{2, 4},
1159 		{7, 7},
1160 		{0, 0},
1161 		{0, 0}
1162 		}
1163 	},
1164 	{1, 1, 3, 0,		/* 0x9d */
1165 		{{0, 0},
1166 		{2, 4},
1167 		{7, 7},
1168 		{0, 0}
1169 		}
1170 	},
1171 	{0, 1, 2, 0,		/* 0x9e */
1172 		{{1, 4},
1173 		{7, 7},
1174 		{0, 0},
1175 		{0, 0}
1176 		}
1177 	},
1178 	{1, 1, 2, 0,		/* 0x9f */
1179 		{{0, 4},
1180 		{7, 7},
1181 		{0, 0},
1182 		{0, 0}
1183 		}
1184 	},
1185 	{0, 1, 2, 0,		/* 0xa0 */
1186 		{{5, 5},
1187 		{7, 7},
1188 		{0, 0},
1189 		{0, 0}
1190 		}
1191 	},
1192 	{1, 1, 3, 0,		/* 0xa1 */
1193 		{{0, 0},
1194 		{5, 5},
1195 		{7, 7},
1196 		{0, 0}
1197 		}
1198 	},
1199 	{0, 1, 3, 0,		/* 0xa2 */
1200 		{{1, 1},
1201 		{5, 5},
1202 		{7, 7},
1203 		{0, 0}
1204 		}
1205 	},
1206 	{1, 1, 3, 0,		/* 0xa3 */
1207 		{{0, 1},
1208 		{5, 5},
1209 		{7, 7},
1210 		{0, 0}
1211 		}
1212 	},
1213 	{0, 1, 3, 0,		/* 0xa4 */
1214 		{{2, 2},
1215 		{5, 5},
1216 		{7, 7},
1217 		{0, 0}
1218 		}
1219 	},
1220 	{1, 1, 4, 0,		/* 0xa5 */
1221 		{{0, 0},
1222 		{2, 2},
1223 		{5, 5},
1224 		{7, 7}
1225 		}
1226 	},
1227 	{0, 1, 3, 0,		/* 0xa6 */
1228 		{{1, 2},
1229 		{5, 5},
1230 		{7, 7},
1231 		{0, 0}
1232 		}
1233 	},
1234 	{1, 1, 3, 0,		/* 0xa7 */
1235 		{{0, 2},
1236 		{5, 5},
1237 		{7, 7},
1238 		{0, 0}
1239 		}
1240 	},
1241 	{0, 1, 3, 0,		/* 0xa8 */
1242 		{{3, 3},
1243 		{5, 5},
1244 		{7, 7},
1245 		{0, 0}
1246 		}
1247 	},
1248 	{1, 1, 4, 0,		/* 0xa9 */
1249 		{{0, 0},
1250 		{3, 3},
1251 		{5, 5},
1252 		{7, 7}
1253 		}
1254 	},
1255 	{0, 1, 4, 0,		/* 0xaa */
1256 		{{1, 1},
1257 		{3, 3},
1258 		{5, 5},
1259 		{7, 7}
1260 		}
1261 	},
1262 	{1, 1, 4, 0,		/* 0xab */
1263 		{{0, 1},
1264 		{3, 3},
1265 		{5, 5},
1266 		{7, 7}
1267 		}
1268 	},
1269 	{0, 1, 3, 0,		/* 0xac */
1270 		{{2, 3},
1271 		{5, 5},
1272 		{7, 7},
1273 		{0, 0}
1274 		}
1275 	},
1276 	{1, 1, 4, 0,		/* 0xad */
1277 		{{0, 0},
1278 		{2, 3},
1279 		{5, 5},
1280 		{7, 7}
1281 		}
1282 	},
1283 	{0, 1, 3, 0,		/* 0xae */
1284 		{{1, 3},
1285 		{5, 5},
1286 		{7, 7},
1287 		{0, 0}
1288 		}
1289 	},
1290 	{1, 1, 3, 0,		/* 0xaf */
1291 		{{0, 3},
1292 		{5, 5},
1293 		{7, 7},
1294 		{0, 0}
1295 		}
1296 	},
1297 	{0, 1, 2, 0,		/* 0xb0 */
1298 		{{4, 5},
1299 		{7, 7},
1300 		{0, 0},
1301 		{0, 0}
1302 		}
1303 	},
1304 	{1, 1, 3, 0,		/* 0xb1 */
1305 		{{0, 0},
1306 		{4, 5},
1307 		{7, 7},
1308 		{0, 0}
1309 		}
1310 	},
1311 	{0, 1, 3, 0,		/* 0xb2 */
1312 		{{1, 1},
1313 		{4, 5},
1314 		{7, 7},
1315 		{0, 0}
1316 		}
1317 	},
1318 	{1, 1, 3, 0,		/* 0xb3 */
1319 		{{0, 1},
1320 		{4, 5},
1321 		{7, 7},
1322 		{0, 0}
1323 		}
1324 	},
1325 	{0, 1, 3, 0,		/* 0xb4 */
1326 		{{2, 2},
1327 		{4, 5},
1328 		{7, 7},
1329 		{0, 0}
1330 		}
1331 	},
1332 	{1, 1, 4, 0,		/* 0xb5 */
1333 		{{0, 0},
1334 		{2, 2},
1335 		{4, 5},
1336 		{7, 7}
1337 		}
1338 	},
1339 	{0, 1, 3, 0,		/* 0xb6 */
1340 		{{1, 2},
1341 		{4, 5},
1342 		{7, 7},
1343 		{0, 0}
1344 		}
1345 	},
1346 	{1, 1, 3, 0,		/* 0xb7 */
1347 		{{0, 2},
1348 		{4, 5},
1349 		{7, 7},
1350 		{0, 0}
1351 		}
1352 	},
1353 	{0, 1, 2, 0,		/* 0xb8 */
1354 		{{3, 5},
1355 		{7, 7},
1356 		{0, 0},
1357 		{0, 0}
1358 		}
1359 	},
1360 	{1, 1, 3, 0,		/* 0xb9 */
1361 		{{0, 0},
1362 		{3, 5},
1363 		{7, 7},
1364 		{0, 0}
1365 		}
1366 	},
1367 	{0, 1, 3, 0,		/* 0xba */
1368 		{{1, 1},
1369 		{3, 5},
1370 		{7, 7},
1371 		{0, 0}
1372 		}
1373 	},
1374 	{1, 1, 3, 0,		/* 0xbb */
1375 		{{0, 1},
1376 		{3, 5},
1377 		{7, 7},
1378 		{0, 0}
1379 		}
1380 	},
1381 	{0, 1, 2, 0,		/* 0xbc */
1382 		{{2, 5},
1383 		{7, 7},
1384 		{0, 0},
1385 		{0, 0}
1386 		}
1387 	},
1388 	{1, 1, 3, 0,		/* 0xbd */
1389 		{{0, 0},
1390 		{2, 5},
1391 		{7, 7},
1392 		{0, 0}
1393 		}
1394 	},
1395 	{0, 1, 2, 0,		/* 0xbe */
1396 		{{1, 5},
1397 		{7, 7},
1398 		{0, 0},
1399 		{0, 0}
1400 		}
1401 	},
1402 	{1, 1, 2, 0,		/* 0xbf */
1403 		{{0, 5},
1404 		{7, 7},
1405 		{0, 0},
1406 		{0, 0}
1407 		}
1408 	},
1409 	{0, 1, 1, 0,		/* 0xc0 */
1410 		{{6, 7},
1411 		{0, 0},
1412 		{0, 0},
1413 		{0, 0}
1414 		}
1415 	},
1416 	{1, 1, 2, 0,		/* 0xc1 */
1417 		{{0, 0},
1418 		{6, 7},
1419 		{0, 0},
1420 		{0, 0}
1421 		}
1422 	},
1423 	{0, 1, 2, 0,		/* 0xc2 */
1424 		{{1, 1},
1425 		{6, 7},
1426 		{0, 0},
1427 		{0, 0}
1428 		}
1429 	},
1430 	{1, 1, 2, 0,		/* 0xc3 */
1431 		{{0, 1},
1432 		{6, 7},
1433 		{0, 0},
1434 		{0, 0}
1435 		}
1436 	},
1437 	{0, 1, 2, 0,		/* 0xc4 */
1438 		{{2, 2},
1439 		{6, 7},
1440 		{0, 0},
1441 		{0, 0}
1442 		}
1443 	},
1444 	{1, 1, 3, 0,		/* 0xc5 */
1445 		{{0, 0},
1446 		{2, 2},
1447 		{6, 7},
1448 		{0, 0}
1449 		}
1450 	},
1451 	{0, 1, 2, 0,		/* 0xc6 */
1452 		{{1, 2},
1453 		{6, 7},
1454 		{0, 0},
1455 		{0, 0}
1456 		}
1457 	},
1458 	{1, 1, 2, 0,		/* 0xc7 */
1459 		{{0, 2},
1460 		{6, 7},
1461 		{0, 0},
1462 		{0, 0}
1463 		}
1464 	},
1465 	{0, 1, 2, 0,		/* 0xc8 */
1466 		{{3, 3},
1467 		{6, 7},
1468 		{0, 0},
1469 		{0, 0}
1470 		}
1471 	},
1472 	{1, 1, 3, 0,		/* 0xc9 */
1473 		{{0, 0},
1474 		{3, 3},
1475 		{6, 7},
1476 		{0, 0}
1477 		}
1478 	},
1479 	{0, 1, 3, 0,		/* 0xca */
1480 		{{1, 1},
1481 		{3, 3},
1482 		{6, 7},
1483 		{0, 0}
1484 		}
1485 	},
1486 	{1, 1, 3, 0,		/* 0xcb */
1487 		{{0, 1},
1488 		{3, 3},
1489 		{6, 7},
1490 		{0, 0}
1491 		}
1492 	},
1493 	{0, 1, 2, 0,		/* 0xcc */
1494 		{{2, 3},
1495 		{6, 7},
1496 		{0, 0},
1497 		{0, 0}
1498 		}
1499 	},
1500 	{1, 1, 3, 0,		/* 0xcd */
1501 		{{0, 0},
1502 		{2, 3},
1503 		{6, 7},
1504 		{0, 0}
1505 		}
1506 	},
1507 	{0, 1, 2, 0,		/* 0xce */
1508 		{{1, 3},
1509 		{6, 7},
1510 		{0, 0},
1511 		{0, 0}
1512 		}
1513 	},
1514 	{1, 1, 2, 0,		/* 0xcf */
1515 		{{0, 3},
1516 		{6, 7},
1517 		{0, 0},
1518 		{0, 0}
1519 		}
1520 	},
1521 	{0, 1, 2, 0,		/* 0xd0 */
1522 		{{4, 4},
1523 		{6, 7},
1524 		{0, 0},
1525 		{0, 0}
1526 		}
1527 	},
1528 	{1, 1, 3, 0,		/* 0xd1 */
1529 		{{0, 0},
1530 		{4, 4},
1531 		{6, 7},
1532 		{0, 0}
1533 		}
1534 	},
1535 	{0, 1, 3, 0,		/* 0xd2 */
1536 		{{1, 1},
1537 		{4, 4},
1538 		{6, 7},
1539 		{0, 0}
1540 		}
1541 	},
1542 	{1, 1, 3, 0,		/* 0xd3 */
1543 		{{0, 1},
1544 		{4, 4},
1545 		{6, 7},
1546 		{0, 0}
1547 		}
1548 	},
1549 	{0, 1, 3, 0,		/* 0xd4 */
1550 		{{2, 2},
1551 		{4, 4},
1552 		{6, 7},
1553 		{0, 0}
1554 		}
1555 	},
1556 	{1, 1, 4, 0,		/* 0xd5 */
1557 		{{0, 0},
1558 		{2, 2},
1559 		{4, 4},
1560 		{6, 7}
1561 		}
1562 	},
1563 	{0, 1, 3, 0,		/* 0xd6 */
1564 		{{1, 2},
1565 		{4, 4},
1566 		{6, 7},
1567 		{0, 0}
1568 		}
1569 	},
1570 	{1, 1, 3, 0,		/* 0xd7 */
1571 		{{0, 2},
1572 		{4, 4},
1573 		{6, 7},
1574 		{0, 0}
1575 		}
1576 	},
1577 	{0, 1, 2, 0,		/* 0xd8 */
1578 		{{3, 4},
1579 		{6, 7},
1580 		{0, 0},
1581 		{0, 0}
1582 		}
1583 	},
1584 	{1, 1, 3, 0,		/* 0xd9 */
1585 		{{0, 0},
1586 		{3, 4},
1587 		{6, 7},
1588 		{0, 0}
1589 		}
1590 	},
1591 	{0, 1, 3, 0,		/* 0xda */
1592 		{{1, 1},
1593 		{3, 4},
1594 		{6, 7},
1595 		{0, 0}
1596 		}
1597 	},
1598 	{1, 1, 3, 0,		/* 0xdb */
1599 		{{0, 1},
1600 		{3, 4},
1601 		{6, 7},
1602 		{0, 0}
1603 		}
1604 	},
1605 	{0, 1, 2, 0,		/* 0xdc */
1606 		{{2, 4},
1607 		{6, 7},
1608 		{0, 0},
1609 		{0, 0}
1610 		}
1611 	},
1612 	{1, 1, 3, 0,		/* 0xdd */
1613 		{{0, 0},
1614 		{2, 4},
1615 		{6, 7},
1616 		{0, 0}
1617 		}
1618 	},
1619 	{0, 1, 2, 0,		/* 0xde */
1620 		{{1, 4},
1621 		{6, 7},
1622 		{0, 0},
1623 		{0, 0}
1624 		}
1625 	},
1626 	{1, 1, 2, 0,		/* 0xdf */
1627 		{{0, 4},
1628 		{6, 7},
1629 		{0, 0},
1630 		{0, 0}
1631 		}
1632 	},
1633 	{0, 1, 1, 0,		/* 0xe0 */
1634 		{{5, 7},
1635 		{0, 0},
1636 		{0, 0},
1637 		{0, 0}
1638 		}
1639 	},
1640 	{1, 1, 2, 0,		/* 0xe1 */
1641 		{{0, 0},
1642 		{5, 7},
1643 		{0, 0},
1644 		{0, 0}
1645 		}
1646 	},
1647 	{0, 1, 2, 0,		/* 0xe2 */
1648 		{{1, 1},
1649 		{5, 7},
1650 		{0, 0},
1651 		{0, 0}
1652 		}
1653 	},
1654 	{1, 1, 2, 0,		/* 0xe3 */
1655 		{{0, 1},
1656 		{5, 7},
1657 		{0, 0},
1658 		{0, 0}
1659 		}
1660 	},
1661 	{0, 1, 2, 0,		/* 0xe4 */
1662 		{{2, 2},
1663 		{5, 7},
1664 		{0, 0},
1665 		{0, 0}
1666 		}
1667 	},
1668 	{1, 1, 3, 0,		/* 0xe5 */
1669 		{{0, 0},
1670 		{2, 2},
1671 		{5, 7},
1672 		{0, 0}
1673 		}
1674 	},
1675 	{0, 1, 2, 0,		/* 0xe6 */
1676 		{{1, 2},
1677 		{5, 7},
1678 		{0, 0},
1679 		{0, 0}
1680 		}
1681 	},
1682 	{1, 1, 2, 0,		/* 0xe7 */
1683 		{{0, 2},
1684 		{5, 7},
1685 		{0, 0},
1686 		{0, 0}
1687 		}
1688 	},
1689 	{0, 1, 2, 0,		/* 0xe8 */
1690 		{{3, 3},
1691 		{5, 7},
1692 		{0, 0},
1693 		{0, 0}
1694 		}
1695 	},
1696 	{1, 1, 3, 0,		/* 0xe9 */
1697 		{{0, 0},
1698 		{3, 3},
1699 		{5, 7},
1700 		{0, 0}
1701 		}
1702 	},
1703 	{0, 1, 3, 0,		/* 0xea */
1704 		{{1, 1},
1705 		{3, 3},
1706 		{5, 7},
1707 		{0, 0}
1708 		}
1709 	},
1710 	{1, 1, 3, 0,		/* 0xeb */
1711 		{{0, 1},
1712 		{3, 3},
1713 		{5, 7},
1714 		{0, 0}
1715 		}
1716 	},
1717 	{0, 1, 2, 0,		/* 0xec */
1718 		{{2, 3},
1719 		{5, 7},
1720 		{0, 0},
1721 		{0, 0}
1722 		}
1723 	},
1724 	{1, 1, 3, 0,		/* 0xed */
1725 		{{0, 0},
1726 		{2, 3},
1727 		{5, 7},
1728 		{0, 0}
1729 		}
1730 	},
1731 	{0, 1, 2, 0,		/* 0xee */
1732 		{{1, 3},
1733 		{5, 7},
1734 		{0, 0},
1735 		{0, 0}
1736 		}
1737 	},
1738 	{1, 1, 2, 0,		/* 0xef */
1739 		{{0, 3},
1740 		{5, 7},
1741 		{0, 0},
1742 		{0, 0}
1743 		}
1744 	},
1745 	{0, 1, 1, 0,		/* 0xf0 */
1746 		{{4, 7},
1747 		{0, 0},
1748 		{0, 0},
1749 		{0, 0}
1750 		}
1751 	},
1752 	{1, 1, 2, 0,		/* 0xf1 */
1753 		{{0, 0},
1754 		{4, 7},
1755 		{0, 0},
1756 		{0, 0}
1757 		}
1758 	},
1759 	{0, 1, 2, 0,		/* 0xf2 */
1760 		{{1, 1},
1761 		{4, 7},
1762 		{0, 0},
1763 		{0, 0}
1764 		}
1765 	},
1766 	{1, 1, 2, 0,		/* 0xf3 */
1767 		{{0, 1},
1768 		{4, 7},
1769 		{0, 0},
1770 		{0, 0}
1771 		}
1772 	},
1773 	{0, 1, 2, 0,		/* 0xf4 */
1774 		{{2, 2},
1775 		{4, 7},
1776 		{0, 0},
1777 		{0, 0}
1778 		}
1779 	},
1780 	{1, 1, 3, 0,		/* 0xf5 */
1781 		{{0, 0},
1782 		{2, 2},
1783 		{4, 7},
1784 		{0, 0}
1785 		}
1786 	},
1787 	{0, 1, 2, 0,		/* 0xf6 */
1788 		{{1, 2},
1789 		{4, 7},
1790 		{0, 0},
1791 		{0, 0}
1792 		}
1793 	},
1794 	{1, 1, 2, 0,		/* 0xf7 */
1795 		{{0, 2},
1796 		{4, 7},
1797 		{0, 0},
1798 		{0, 0}
1799 		}
1800 	},
1801 	{0, 1, 1, 0,		/* 0xf8 */
1802 		{{3, 7},
1803 		{0, 0},
1804 		{0, 0},
1805 		{0, 0}
1806 		}
1807 	},
1808 	{1, 1, 2, 0,		/* 0xf9 */
1809 		{{0, 0},
1810 		{3, 7},
1811 		{0, 0},
1812 		{0, 0}
1813 		}
1814 	},
1815 	{0, 1, 2, 0,		/* 0xfa */
1816 		{{1, 1},
1817 		{3, 7},
1818 		{0, 0},
1819 		{0, 0}
1820 		}
1821 	},
1822 	{1, 1, 2, 0,		/* 0xfb */
1823 		{{0, 1},
1824 		{3, 7},
1825 		{0, 0},
1826 		{0, 0}
1827 		}
1828 	},
1829 	{0, 1, 1, 0,		/* 0xfc */
1830 		{{2, 7},
1831 		{0, 0},
1832 		{0, 0},
1833 		{0, 0}
1834 		}
1835 	},
1836 	{1, 1, 2, 0,		/* 0xfd */
1837 		{{0, 0},
1838 		{2, 7},
1839 		{0, 0},
1840 		{0, 0}
1841 		}
1842 	},
1843 	{0, 1, 1, 0,		/* 0xfe */
1844 		{{1, 7},
1845 		{0, 0},
1846 		{0, 0},
1847 		{0, 0}
1848 		}
1849 	},
1850 	{1, 1, 1, 0,		/* 0xff */
1851 		{{0, 7},
1852 		{0, 0},
1853 		{0, 0},
1854 		{0, 0}
1855 		}
1856 	}
1857 };
1858 
1859 
1860 int
1861 sctp_is_address_in_scope(struct sctp_ifa *ifa,
1862     int ipv4_addr_legal,
1863     int ipv6_addr_legal,
1864     int loopback_scope,
1865     int ipv4_local_scope,
1866     int local_scope,
1867     int site_scope,
1868     int do_update)
1869 {
1870 	if ((loopback_scope == 0) &&
1871 	    (ifa->ifn_p) && SCTP_IFN_IS_IFT_LOOP(ifa->ifn_p)) {
1872 		/*
1873 		 * skip loopback if not in scope *
1874 		 */
1875 		return (0);
1876 	}
1877 	if ((ifa->address.sa.sa_family == AF_INET) && ipv4_addr_legal) {
1878 		struct sockaddr_in *sin;
1879 
1880 		sin = (struct sockaddr_in *)&ifa->address.sin;
1881 		if (sin->sin_addr.s_addr == 0) {
1882 			/* not in scope , unspecified */
1883 			return (0);
1884 		}
1885 		if ((ipv4_local_scope == 0) &&
1886 		    (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr))) {
1887 			/* private address not in scope */
1888 			return (0);
1889 		}
1890 	} else if ((ifa->address.sa.sa_family == AF_INET6) && ipv6_addr_legal) {
1891 		struct sockaddr_in6 *sin6;
1892 
1893 		/*
1894 		 * Must update the flags,  bummer, which means any IFA locks
1895 		 * must now be applied HERE <->
1896 		 */
1897 		if (do_update) {
1898 			sctp_gather_internal_ifa_flags(ifa);
1899 		}
1900 		if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
1901 			return (0);
1902 		}
1903 		/* ok to use deprecated addresses? */
1904 		sin6 = (struct sockaddr_in6 *)&ifa->address.sin6;
1905 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
1906 			/* skip unspecifed addresses */
1907 			return (0);
1908 		}
1909 		if (		/* (local_scope == 0) && */
1910 		    (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr))) {
1911 			return (0);
1912 		}
1913 		if ((site_scope == 0) &&
1914 		    (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr))) {
1915 			return (0);
1916 		}
1917 	} else {
1918 		return (0);
1919 	}
1920 	return (1);
1921 }
1922 
1923 static struct mbuf *
1924 sctp_add_addr_to_mbuf(struct mbuf *m, struct sctp_ifa *ifa)
1925 {
1926 	struct sctp_paramhdr *parmh;
1927 	struct mbuf *mret;
1928 	int len;
1929 
1930 	if (ifa->address.sa.sa_family == AF_INET) {
1931 		len = sizeof(struct sctp_ipv4addr_param);
1932 	} else if (ifa->address.sa.sa_family == AF_INET6) {
1933 		len = sizeof(struct sctp_ipv6addr_param);
1934 	} else {
1935 		/* unknown type */
1936 		return (m);
1937 	}
1938 	if (M_TRAILINGSPACE(m) >= len) {
1939 		/* easy side we just drop it on the end */
1940 		parmh = (struct sctp_paramhdr *)(SCTP_BUF_AT(m, SCTP_BUF_LEN(m)));
1941 		mret = m;
1942 	} else {
1943 		/* Need more space */
1944 		mret = m;
1945 		while (SCTP_BUF_NEXT(mret) != NULL) {
1946 			mret = SCTP_BUF_NEXT(mret);
1947 		}
1948 		SCTP_BUF_NEXT(mret) = sctp_get_mbuf_for_msg(len, 0, M_DONTWAIT, 1, MT_DATA);
1949 		if (SCTP_BUF_NEXT(mret) == NULL) {
1950 			/* We are hosed, can't add more addresses */
1951 			return (m);
1952 		}
1953 		mret = SCTP_BUF_NEXT(mret);
1954 		parmh = mtod(mret, struct sctp_paramhdr *);
1955 	}
1956 	/* now add the parameter */
1957 	if (ifa->address.sa.sa_family == AF_INET) {
1958 		struct sctp_ipv4addr_param *ipv4p;
1959 		struct sockaddr_in *sin;
1960 
1961 		sin = (struct sockaddr_in *)&ifa->address.sin;
1962 		ipv4p = (struct sctp_ipv4addr_param *)parmh;
1963 		parmh->param_type = htons(SCTP_IPV4_ADDRESS);
1964 		parmh->param_length = htons(len);
1965 		ipv4p->addr = sin->sin_addr.s_addr;
1966 		SCTP_BUF_LEN(mret) += len;
1967 	} else if (ifa->address.sa.sa_family == AF_INET6) {
1968 		struct sctp_ipv6addr_param *ipv6p;
1969 		struct sockaddr_in6 *sin6;
1970 
1971 		sin6 = (struct sockaddr_in6 *)&ifa->address.sin6;
1972 		ipv6p = (struct sctp_ipv6addr_param *)parmh;
1973 		parmh->param_type = htons(SCTP_IPV6_ADDRESS);
1974 		parmh->param_length = htons(len);
1975 		memcpy(ipv6p->addr, &sin6->sin6_addr,
1976 		    sizeof(ipv6p->addr));
1977 		/* clear embedded scope in the address */
1978 		in6_clearscope((struct in6_addr *)ipv6p->addr);
1979 		SCTP_BUF_LEN(mret) += len;
1980 	} else {
1981 		return (m);
1982 	}
1983 	return (mret);
1984 }
1985 
1986 
1987 struct mbuf *
1988 sctp_add_addresses_to_i_ia(struct sctp_inpcb *inp, struct sctp_scoping *scope,
1989     struct mbuf *m_at, int cnt_inits_to)
1990 {
1991 	struct sctp_vrf *vrf = NULL;
1992 	int cnt, limit_out = 0, total_count;
1993 	uint32_t vrf_id;
1994 
1995 	vrf_id = inp->def_vrf_id;
1996 	SCTP_IPI_ADDR_LOCK();
1997 	vrf = sctp_find_vrf(vrf_id);
1998 	if (vrf == NULL) {
1999 		SCTP_IPI_ADDR_UNLOCK();
2000 		return (m_at);
2001 	}
2002 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
2003 		struct sctp_ifa *sctp_ifap;
2004 		struct sctp_ifn *sctp_ifnp;
2005 
2006 		cnt = cnt_inits_to;
2007 		if (vrf->total_ifa_count > SCTP_COUNT_LIMIT) {
2008 			limit_out = 1;
2009 			cnt = SCTP_ADDRESS_LIMIT;
2010 			goto skip_count;
2011 		}
2012 		LIST_FOREACH(sctp_ifnp, &vrf->ifnlist, next_ifn) {
2013 			if ((scope->loopback_scope == 0) &&
2014 			    SCTP_IFN_IS_IFT_LOOP(sctp_ifnp)) {
2015 				/*
2016 				 * Skip loopback devices if loopback_scope
2017 				 * not set
2018 				 */
2019 				continue;
2020 			}
2021 			LIST_FOREACH(sctp_ifap, &sctp_ifnp->ifalist, next_ifa) {
2022 				if (sctp_is_address_in_scope(sctp_ifap,
2023 				    scope->ipv4_addr_legal,
2024 				    scope->ipv6_addr_legal,
2025 				    scope->loopback_scope,
2026 				    scope->ipv4_local_scope,
2027 				    scope->local_scope,
2028 				    scope->site_scope, 1) == 0) {
2029 					continue;
2030 				}
2031 				cnt++;
2032 				if (cnt > SCTP_ADDRESS_LIMIT) {
2033 					break;
2034 				}
2035 			}
2036 			if (cnt > SCTP_ADDRESS_LIMIT) {
2037 				break;
2038 			}
2039 		}
2040 skip_count:
2041 		if (cnt > 1) {
2042 			total_count = 0;
2043 			LIST_FOREACH(sctp_ifnp, &vrf->ifnlist, next_ifn) {
2044 				cnt = 0;
2045 				if ((scope->loopback_scope == 0) &&
2046 				    SCTP_IFN_IS_IFT_LOOP(sctp_ifnp)) {
2047 					/*
2048 					 * Skip loopback devices if
2049 					 * loopback_scope not set
2050 					 */
2051 					continue;
2052 				}
2053 				LIST_FOREACH(sctp_ifap, &sctp_ifnp->ifalist, next_ifa) {
2054 					if (sctp_is_address_in_scope(sctp_ifap,
2055 					    scope->ipv4_addr_legal,
2056 					    scope->ipv6_addr_legal,
2057 					    scope->loopback_scope,
2058 					    scope->ipv4_local_scope,
2059 					    scope->local_scope,
2060 					    scope->site_scope, 0) == 0) {
2061 						continue;
2062 					}
2063 					m_at = sctp_add_addr_to_mbuf(m_at, sctp_ifap);
2064 					if (limit_out) {
2065 						cnt++;
2066 						total_count++;
2067 						if (cnt >= 2) {
2068 							/*
2069 							 * two from each
2070 							 * address
2071 							 */
2072 							break;
2073 						}
2074 						if (total_count > SCTP_ADDRESS_LIMIT) {
2075 							/* No more addresses */
2076 							break;
2077 						}
2078 					}
2079 				}
2080 			}
2081 		}
2082 	} else {
2083 		struct sctp_laddr *laddr;
2084 
2085 		cnt = cnt_inits_to;
2086 		/* First, how many ? */
2087 		LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
2088 			if (laddr->ifa == NULL) {
2089 				continue;
2090 			}
2091 			if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED)
2092 				/*
2093 				 * Address being deleted by the system, dont
2094 				 * list.
2095 				 */
2096 				continue;
2097 			if (laddr->action == SCTP_DEL_IP_ADDRESS) {
2098 				/*
2099 				 * Address being deleted on this ep don't
2100 				 * list.
2101 				 */
2102 				continue;
2103 			}
2104 			if (sctp_is_address_in_scope(laddr->ifa,
2105 			    scope->ipv4_addr_legal,
2106 			    scope->ipv6_addr_legal,
2107 			    scope->loopback_scope,
2108 			    scope->ipv4_local_scope,
2109 			    scope->local_scope,
2110 			    scope->site_scope, 1) == 0) {
2111 				continue;
2112 			}
2113 			cnt++;
2114 		}
2115 		if (cnt > SCTP_ADDRESS_LIMIT) {
2116 			limit_out = 1;
2117 		}
2118 		/*
2119 		 * To get through a NAT we only list addresses if we have
2120 		 * more than one. That way if you just bind a single address
2121 		 * we let the source of the init dictate our address.
2122 		 */
2123 		if (cnt > 1) {
2124 			LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
2125 				cnt = 0;
2126 				if (laddr->ifa == NULL) {
2127 					continue;
2128 				}
2129 				if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED)
2130 					continue;
2131 
2132 				if (sctp_is_address_in_scope(laddr->ifa,
2133 				    scope->ipv4_addr_legal,
2134 				    scope->ipv6_addr_legal,
2135 				    scope->loopback_scope,
2136 				    scope->ipv4_local_scope,
2137 				    scope->local_scope,
2138 				    scope->site_scope, 0) == 0) {
2139 					continue;
2140 				}
2141 				m_at = sctp_add_addr_to_mbuf(m_at, laddr->ifa);
2142 				cnt++;
2143 				if (cnt >= SCTP_ADDRESS_LIMIT) {
2144 					break;
2145 				}
2146 			}
2147 		}
2148 	}
2149 	SCTP_IPI_ADDR_UNLOCK();
2150 	return (m_at);
2151 }
2152 
2153 static struct sctp_ifa *
2154 sctp_is_ifa_addr_preferred(struct sctp_ifa *ifa,
2155     uint8_t dest_is_loop,
2156     uint8_t dest_is_priv,
2157     sa_family_t fam)
2158 {
2159 	uint8_t dest_is_global = 0;
2160 
2161 	/* dest_is_priv is true if destination is a private address */
2162 	/* dest_is_loop is true if destination is a loopback addresses */
2163 
2164 	/*
2165 	 * Here we determine if its a preferred address. A preferred address
2166 	 * means it is the same scope or higher scope then the destination.
2167 	 * L = loopback, P = private, G = global
2168 	 * ----------------------------------------- src    |  dest | result
2169 	 * ---------------------------------------- L     |    L  |    yes
2170 	 * ----------------------------------------- P     |    L  |
2171 	 * yes-v4 no-v6 ----------------------------------------- G     |
2172 	 * L  |    yes-v4 no-v6 ----------------------------------------- L
2173 	 * |    P  |    no ----------------------------------------- P     |
2174 	 * P  |    yes ----------------------------------------- G     |
2175 	 * P  |    no ----------------------------------------- L     |    G
2176 	 * |    no ----------------------------------------- P     |    G  |
2177 	 * no ----------------------------------------- G     |    G  |
2178 	 * yes -----------------------------------------
2179 	 */
2180 
2181 	if (ifa->address.sa.sa_family != fam) {
2182 		/* forget mis-matched family */
2183 		return (NULL);
2184 	}
2185 	if ((dest_is_priv == 0) && (dest_is_loop == 0)) {
2186 		dest_is_global = 1;
2187 	}
2188 	SCTPDBG(SCTP_DEBUG_OUTPUT2, "Is destination preferred:");
2189 	SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, &ifa->address.sa);
2190 	/* Ok the address may be ok */
2191 	if (fam == AF_INET6) {
2192 		/* ok to use deprecated addresses? */
2193 		if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
2194 			SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:1\n");
2195 			return (NULL);
2196 		}
2197 		if (ifa->src_is_priv) {
2198 			if (dest_is_loop) {
2199 				SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:2\n");
2200 				return (NULL);
2201 			}
2202 		}
2203 		if (ifa->src_is_glob) {
2204 			if (dest_is_loop) {
2205 				SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:3\n");
2206 				return (NULL);
2207 			}
2208 		}
2209 	}
2210 	/*
2211 	 * Now that we know what is what, implement or table this could in
2212 	 * theory be done slicker (it used to be), but this is
2213 	 * straightforward and easier to validate :-)
2214 	 */
2215 	SCTPDBG(SCTP_DEBUG_OUTPUT3, "src_loop:%d src_priv:%d src_glob:%d\n",
2216 	    ifa->src_is_loop, ifa->src_is_priv, ifa->src_is_glob);
2217 	SCTPDBG(SCTP_DEBUG_OUTPUT3, "dest_loop:%d dest_priv:%d dest_glob:%d\n",
2218 	    dest_is_loop, dest_is_priv, dest_is_global);
2219 
2220 	if ((ifa->src_is_loop) && (dest_is_priv)) {
2221 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:4\n");
2222 		return (NULL);
2223 	}
2224 	if ((ifa->src_is_glob) && (dest_is_priv)) {
2225 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:5\n");
2226 		return (NULL);
2227 	}
2228 	if ((ifa->src_is_loop) && (dest_is_global)) {
2229 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:6\n");
2230 		return (NULL);
2231 	}
2232 	if ((ifa->src_is_priv) && (dest_is_global)) {
2233 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:7\n");
2234 		return (NULL);
2235 	}
2236 	SCTPDBG(SCTP_DEBUG_OUTPUT3, "YES\n");
2237 	/* its a preferred address */
2238 	return (ifa);
2239 }
2240 
2241 static struct sctp_ifa *
2242 sctp_is_ifa_addr_acceptable(struct sctp_ifa *ifa,
2243     uint8_t dest_is_loop,
2244     uint8_t dest_is_priv,
2245     sa_family_t fam)
2246 {
2247 	uint8_t dest_is_global = 0;
2248 
2249 
2250 	/*
2251 	 * Here we determine if its a acceptable address. A acceptable
2252 	 * address means it is the same scope or higher scope but we can
2253 	 * allow for NAT which means its ok to have a global dest and a
2254 	 * private src.
2255 	 *
2256 	 * L = loopback, P = private, G = global
2257 	 * ----------------------------------------- src    |  dest | result
2258 	 * ----------------------------------------- L     |   L   |    yes
2259 	 * ----------------------------------------- P     |   L   |
2260 	 * yes-v4 no-v6 ----------------------------------------- G     |
2261 	 * L   |    yes ----------------------------------------- L     |
2262 	 * P   |    no ----------------------------------------- P     |   P
2263 	 * |    yes ----------------------------------------- G     |   P
2264 	 * |    yes - May not work -----------------------------------------
2265 	 * L     |   G   |    no ----------------------------------------- P
2266 	 * |   G   |    yes - May not work
2267 	 * ----------------------------------------- G     |   G   |    yes
2268 	 * -----------------------------------------
2269 	 */
2270 
2271 	if (ifa->address.sa.sa_family != fam) {
2272 		/* forget non matching family */
2273 		return (NULL);
2274 	}
2275 	/* Ok the address may be ok */
2276 	if ((dest_is_loop == 0) && (dest_is_priv == 0)) {
2277 		dest_is_global = 1;
2278 	}
2279 	if (fam == AF_INET6) {
2280 		/* ok to use deprecated addresses? */
2281 		if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
2282 			return (NULL);
2283 		}
2284 		if (ifa->src_is_priv) {
2285 			/* Special case, linklocal to loop */
2286 			if (dest_is_loop)
2287 				return (NULL);
2288 		}
2289 	}
2290 	/*
2291 	 * Now that we know what is what, implement our table. This could in
2292 	 * theory be done slicker (it used to be), but this is
2293 	 * straightforward and easier to validate :-)
2294 	 */
2295 	if ((ifa->src_is_loop == 1) && (dest_is_priv)) {
2296 		return (NULL);
2297 	}
2298 	if ((ifa->src_is_loop == 1) && (dest_is_global)) {
2299 		return (NULL);
2300 	}
2301 	/* its an acceptable address */
2302 	return (ifa);
2303 }
2304 
2305 int
2306 sctp_is_addr_restricted(struct sctp_tcb *stcb, struct sctp_ifa *ifa)
2307 {
2308 	struct sctp_laddr *laddr;
2309 
2310 	if (stcb == NULL) {
2311 		/* There are no restrictions, no TCB :-) */
2312 		return (0);
2313 	}
2314 	LIST_FOREACH(laddr, &stcb->asoc.sctp_restricted_addrs, sctp_nxt_addr) {
2315 		if (laddr->ifa == NULL) {
2316 			SCTPDBG(SCTP_DEBUG_OUTPUT1, "%s: NULL ifa\n",
2317 			    __FUNCTION__);
2318 			continue;
2319 		}
2320 		if (laddr->ifa == ifa) {
2321 			/* Yes it is on the list */
2322 			return (1);
2323 		}
2324 	}
2325 	return (0);
2326 }
2327 
2328 
2329 int
2330 sctp_is_addr_in_ep(struct sctp_inpcb *inp, struct sctp_ifa *ifa)
2331 {
2332 	struct sctp_laddr *laddr;
2333 
2334 	if (ifa == NULL)
2335 		return (0);
2336 	LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
2337 		if (laddr->ifa == NULL) {
2338 			SCTPDBG(SCTP_DEBUG_OUTPUT1, "%s: NULL ifa\n",
2339 			    __FUNCTION__);
2340 			continue;
2341 		}
2342 		if ((laddr->ifa == ifa) && laddr->action == 0)
2343 			/* same pointer */
2344 			return (1);
2345 	}
2346 	return (0);
2347 }
2348 
2349 
2350 
2351 static struct sctp_ifa *
2352 sctp_choose_boundspecific_inp(struct sctp_inpcb *inp,
2353     sctp_route_t * ro,
2354     uint32_t vrf_id,
2355     int non_asoc_addr_ok,
2356     uint8_t dest_is_priv,
2357     uint8_t dest_is_loop,
2358     sa_family_t fam)
2359 {
2360 	struct sctp_laddr *laddr, *starting_point;
2361 	void *ifn;
2362 	int resettotop = 0;
2363 	struct sctp_ifn *sctp_ifn;
2364 	struct sctp_ifa *sctp_ifa, *sifa;
2365 	struct sctp_vrf *vrf;
2366 	uint32_t ifn_index;
2367 
2368 	vrf = sctp_find_vrf(vrf_id);
2369 	if (vrf == NULL)
2370 		return (NULL);
2371 
2372 	ifn = SCTP_GET_IFN_VOID_FROM_ROUTE(ro);
2373 	ifn_index = SCTP_GET_IF_INDEX_FROM_ROUTE(ro);
2374 	sctp_ifn = sctp_find_ifn(ifn, ifn_index);
2375 	/*
2376 	 * first question, is the ifn we will emit on in our list, if so, we
2377 	 * want such an address. Note that we first looked for a preferred
2378 	 * address.
2379 	 */
2380 	if (sctp_ifn) {
2381 		/* is a preferred one on the interface we route out? */
2382 		LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
2383 			if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) && (non_asoc_addr_ok == 0))
2384 				continue;
2385 			sifa = sctp_is_ifa_addr_preferred(sctp_ifa, dest_is_loop, dest_is_priv, fam);
2386 			if (sifa == NULL)
2387 				continue;
2388 			if (sctp_is_addr_in_ep(inp, sifa)) {
2389 				atomic_add_int(&sifa->refcount, 1);
2390 				return (sifa);
2391 			}
2392 		}
2393 	}
2394 	/*
2395 	 * ok, now we now need to find one on the list of the addresses. We
2396 	 * can't get one on the emitting interface so let's find first a
2397 	 * preferred one. If not that an acceptable one otherwise... we
2398 	 * return NULL.
2399 	 */
2400 	starting_point = inp->next_addr_touse;
2401 once_again:
2402 	if (inp->next_addr_touse == NULL) {
2403 		inp->next_addr_touse = LIST_FIRST(&inp->sctp_addr_list);
2404 		resettotop = 1;
2405 	}
2406 	for (laddr = inp->next_addr_touse; laddr; laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
2407 		if (laddr->ifa == NULL) {
2408 			/* address has been removed */
2409 			continue;
2410 		}
2411 		sifa = sctp_is_ifa_addr_preferred(laddr->ifa, dest_is_loop, dest_is_priv, fam);
2412 		if (sifa == NULL)
2413 			continue;
2414 		atomic_add_int(&sifa->refcount, 1);
2415 		return (sifa);
2416 	}
2417 	if (resettotop == 0) {
2418 		inp->next_addr_touse = NULL;
2419 		goto once_again;
2420 	}
2421 	inp->next_addr_touse = starting_point;
2422 	resettotop = 0;
2423 once_again_too:
2424 	if (inp->next_addr_touse == NULL) {
2425 		inp->next_addr_touse = LIST_FIRST(&inp->sctp_addr_list);
2426 		resettotop = 1;
2427 	}
2428 	/* ok, what about an acceptable address in the inp */
2429 	for (laddr = inp->next_addr_touse; laddr; laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
2430 		if (laddr->ifa == NULL) {
2431 			/* address has been removed */
2432 			continue;
2433 		}
2434 		sifa = sctp_is_ifa_addr_acceptable(laddr->ifa, dest_is_loop, dest_is_priv, fam);
2435 		if (sifa == NULL)
2436 			continue;
2437 		atomic_add_int(&sifa->refcount, 1);
2438 		return (sifa);
2439 	}
2440 	if (resettotop == 0) {
2441 		inp->next_addr_touse = NULL;
2442 		goto once_again_too;
2443 	}
2444 	/*
2445 	 * no address bound can be a source for the destination we are in
2446 	 * trouble
2447 	 */
2448 	return (NULL);
2449 }
2450 
2451 
2452 
2453 static struct sctp_ifa *
2454 sctp_choose_boundspecific_stcb(struct sctp_inpcb *inp,
2455     struct sctp_tcb *stcb,
2456     struct sctp_nets *net,
2457     sctp_route_t * ro,
2458     uint32_t vrf_id,
2459     uint8_t dest_is_priv,
2460     uint8_t dest_is_loop,
2461     int non_asoc_addr_ok,
2462     sa_family_t fam)
2463 {
2464 	struct sctp_laddr *laddr, *starting_point;
2465 	void *ifn;
2466 	struct sctp_ifn *sctp_ifn;
2467 	struct sctp_ifa *sctp_ifa, *sifa;
2468 	uint8_t start_at_beginning = 0;
2469 	struct sctp_vrf *vrf;
2470 	uint32_t ifn_index;
2471 
2472 	/*
2473 	 * first question, is the ifn we will emit on in our list, if so, we
2474 	 * want that one.
2475 	 */
2476 	vrf = sctp_find_vrf(vrf_id);
2477 	if (vrf == NULL)
2478 		return (NULL);
2479 
2480 	ifn = SCTP_GET_IFN_VOID_FROM_ROUTE(ro);
2481 	ifn_index = SCTP_GET_IF_INDEX_FROM_ROUTE(ro);
2482 	sctp_ifn = sctp_find_ifn(ifn, ifn_index);
2483 
2484 	/*
2485 	 * first question, is the ifn we will emit on in our list?  If so,
2486 	 * we want that one. First we look for a preferred. Second, we go
2487 	 * for an acceptable.
2488 	 */
2489 	if (sctp_ifn) {
2490 		/* first try for a preferred address on the ep */
2491 		LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
2492 			if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) && (non_asoc_addr_ok == 0))
2493 				continue;
2494 			if (sctp_is_addr_in_ep(inp, sctp_ifa)) {
2495 				sifa = sctp_is_ifa_addr_preferred(sctp_ifa, dest_is_loop, dest_is_priv, fam);
2496 				if (sifa == NULL)
2497 					continue;
2498 				if ((non_asoc_addr_ok == 0) &&
2499 				    (sctp_is_addr_restricted(stcb, sifa))) {
2500 					/* on the no-no list */
2501 					continue;
2502 				}
2503 				atomic_add_int(&sifa->refcount, 1);
2504 				return (sifa);
2505 			}
2506 		}
2507 		/* next try for an acceptable address on the ep */
2508 		LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
2509 			if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) && (non_asoc_addr_ok == 0))
2510 				continue;
2511 			if (sctp_is_addr_in_ep(inp, sctp_ifa)) {
2512 				sifa = sctp_is_ifa_addr_acceptable(sctp_ifa, dest_is_loop, dest_is_priv, fam);
2513 				if (sifa == NULL)
2514 					continue;
2515 				if ((non_asoc_addr_ok == 0) &&
2516 				    (sctp_is_addr_restricted(stcb, sifa))) {
2517 					/* on the no-no list */
2518 					continue;
2519 				}
2520 				atomic_add_int(&sifa->refcount, 1);
2521 				return (sifa);
2522 			}
2523 		}
2524 
2525 	}
2526 	/*
2527 	 * if we can't find one like that then we must look at all addresses
2528 	 * bound to pick one at first preferable then secondly acceptable.
2529 	 */
2530 	starting_point = stcb->asoc.last_used_address;
2531 sctp_from_the_top:
2532 	if (stcb->asoc.last_used_address == NULL) {
2533 		start_at_beginning = 1;
2534 		stcb->asoc.last_used_address = LIST_FIRST(&inp->sctp_addr_list);
2535 	}
2536 	/* search beginning with the last used address */
2537 	for (laddr = stcb->asoc.last_used_address; laddr;
2538 	    laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
2539 		if (laddr->ifa == NULL) {
2540 			/* address has been removed */
2541 			continue;
2542 		}
2543 		sifa = sctp_is_ifa_addr_preferred(laddr->ifa, dest_is_loop, dest_is_priv, fam);
2544 		if (sifa == NULL)
2545 			continue;
2546 		if ((non_asoc_addr_ok == 0) &&
2547 		    (sctp_is_addr_restricted(stcb, sifa))) {
2548 			/* on the no-no list */
2549 			continue;
2550 		}
2551 		stcb->asoc.last_used_address = laddr;
2552 		atomic_add_int(&sifa->refcount, 1);
2553 		return (sifa);
2554 
2555 	}
2556 	if (start_at_beginning == 0) {
2557 		stcb->asoc.last_used_address = NULL;
2558 		goto sctp_from_the_top;
2559 	}
2560 	/* now try for any higher scope than the destination */
2561 	stcb->asoc.last_used_address = starting_point;
2562 	start_at_beginning = 0;
2563 sctp_from_the_top2:
2564 	if (stcb->asoc.last_used_address == NULL) {
2565 		start_at_beginning = 1;
2566 		stcb->asoc.last_used_address = LIST_FIRST(&inp->sctp_addr_list);
2567 	}
2568 	/* search beginning with the last used address */
2569 	for (laddr = stcb->asoc.last_used_address; laddr;
2570 	    laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
2571 		if (laddr->ifa == NULL) {
2572 			/* address has been removed */
2573 			continue;
2574 		}
2575 		sifa = sctp_is_ifa_addr_acceptable(laddr->ifa, dest_is_loop,
2576 		    dest_is_priv, fam);
2577 		if (sifa == NULL)
2578 			continue;
2579 		if ((non_asoc_addr_ok == 0) &&
2580 		    (sctp_is_addr_restricted(stcb, sifa))) {
2581 			/* on the no-no list */
2582 			continue;
2583 		}
2584 		stcb->asoc.last_used_address = laddr;
2585 		atomic_add_int(&sifa->refcount, 1);
2586 		return (sifa);
2587 	}
2588 	if (start_at_beginning == 0) {
2589 		stcb->asoc.last_used_address = NULL;
2590 		goto sctp_from_the_top2;
2591 	}
2592 	return (NULL);
2593 }
2594 
2595 static struct sctp_ifa *
2596 sctp_select_nth_preferred_addr_from_ifn_boundall(struct sctp_ifn *ifn,
2597     struct sctp_tcb *stcb,
2598     int non_asoc_addr_ok,
2599     uint8_t dest_is_loop,
2600     uint8_t dest_is_priv,
2601     int addr_wanted,
2602     sa_family_t fam)
2603 {
2604 	struct sctp_ifa *ifa, *sifa;
2605 	int num_eligible_addr = 0;
2606 
2607 	LIST_FOREACH(ifa, &ifn->ifalist, next_ifa) {
2608 		if ((ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
2609 		    (non_asoc_addr_ok == 0))
2610 			continue;
2611 		sifa = sctp_is_ifa_addr_preferred(ifa, dest_is_loop,
2612 		    dest_is_priv, fam);
2613 		if (sifa == NULL)
2614 			continue;
2615 		if (stcb) {
2616 			if ((non_asoc_addr_ok == 0) &&
2617 			    sctp_is_addr_restricted(stcb, sifa)) {
2618 				/*
2619 				 * It is restricted for some reason..
2620 				 * probably not yet added.
2621 				 */
2622 				continue;
2623 			}
2624 		}
2625 		if (num_eligible_addr >= addr_wanted) {
2626 			return (sifa);
2627 		}
2628 		num_eligible_addr++;
2629 	}
2630 	return (NULL);
2631 }
2632 
2633 
2634 static int
2635 sctp_count_num_preferred_boundall(struct sctp_ifn *ifn,
2636     struct sctp_tcb *stcb,
2637     int non_asoc_addr_ok,
2638     uint8_t dest_is_loop,
2639     uint8_t dest_is_priv,
2640     sa_family_t fam)
2641 {
2642 	struct sctp_ifa *ifa, *sifa;
2643 	int num_eligible_addr = 0;
2644 
2645 	LIST_FOREACH(ifa, &ifn->ifalist, next_ifa) {
2646 		if ((ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
2647 		    (non_asoc_addr_ok == 0)) {
2648 			continue;
2649 		}
2650 		sifa = sctp_is_ifa_addr_preferred(ifa, dest_is_loop,
2651 		    dest_is_priv, fam);
2652 		if (sifa == NULL) {
2653 			continue;
2654 		}
2655 		if (stcb) {
2656 			if ((non_asoc_addr_ok == 0) &&
2657 			    sctp_is_addr_restricted(stcb, sifa)) {
2658 				/*
2659 				 * It is restricted for some reason..
2660 				 * probably not yet added.
2661 				 */
2662 				continue;
2663 			}
2664 		}
2665 		num_eligible_addr++;
2666 	}
2667 	return (num_eligible_addr);
2668 }
2669 
2670 static struct sctp_ifa *
2671 sctp_choose_boundall(struct sctp_inpcb *inp,
2672     struct sctp_tcb *stcb,
2673     struct sctp_nets *net,
2674     sctp_route_t * ro,
2675     uint32_t vrf_id,
2676     uint8_t dest_is_priv,
2677     uint8_t dest_is_loop,
2678     int non_asoc_addr_ok,
2679     sa_family_t fam)
2680 {
2681 	int cur_addr_num = 0, num_preferred = 0;
2682 	void *ifn;
2683 	struct sctp_ifn *sctp_ifn, *looked_at = NULL, *emit_ifn;
2684 	struct sctp_ifa *sctp_ifa, *sifa;
2685 	uint32_t ifn_index;
2686 	struct sctp_vrf *vrf;
2687 
2688 	/*
2689 	 * For boundall we can use any address in the association. If
2690 	 * non_asoc_addr_ok is set we can use any address (at least in
2691 	 * theory). So we look for preferred addresses first. If we find
2692 	 * one, we use it. Otherwise we next try to get an address on the
2693 	 * interface, which we should be able to do (unless non_asoc_addr_ok
2694 	 * is false and we are routed out that way). In these cases where we
2695 	 * can't use the address of the interface we go through all the
2696 	 * ifn's looking for an address we can use and fill that in. Punting
2697 	 * means we send back address 0, which will probably cause problems
2698 	 * actually since then IP will fill in the address of the route ifn,
2699 	 * which means we probably already rejected it.. i.e. here comes an
2700 	 * abort :-<.
2701 	 */
2702 	vrf = sctp_find_vrf(vrf_id);
2703 	if (vrf == NULL)
2704 		return (NULL);
2705 
2706 	ifn = SCTP_GET_IFN_VOID_FROM_ROUTE(ro);
2707 	ifn_index = SCTP_GET_IF_INDEX_FROM_ROUTE(ro);
2708 
2709 	emit_ifn = looked_at = sctp_ifn = sctp_find_ifn(ifn, ifn_index);
2710 	if (sctp_ifn == NULL) {
2711 		/* ?? We don't have this guy ?? */
2712 		goto bound_all_plan_b;
2713 	}
2714 	if (net) {
2715 		cur_addr_num = net->indx_of_eligible_next_to_use;
2716 	}
2717 	num_preferred = sctp_count_num_preferred_boundall(sctp_ifn,
2718 	    stcb,
2719 	    non_asoc_addr_ok,
2720 	    dest_is_loop,
2721 	    dest_is_priv, fam);
2722 	SCTPDBG(SCTP_DEBUG_OUTPUT2, "Found %d preferred source addresses\n",
2723 	    num_preferred);
2724 	if (num_preferred == 0) {
2725 		/*
2726 		 * no eligible addresses, we must use some other interface
2727 		 * address if we can find one.
2728 		 */
2729 		goto bound_all_plan_b;
2730 	}
2731 	/*
2732 	 * Ok we have num_eligible_addr set with how many we can use, this
2733 	 * may vary from call to call due to addresses being deprecated
2734 	 * etc..
2735 	 */
2736 	if (cur_addr_num >= num_preferred) {
2737 		cur_addr_num = 0;
2738 	}
2739 	/*
2740 	 * select the nth address from the list (where cur_addr_num is the
2741 	 * nth) and 0 is the first one, 1 is the second one etc...
2742 	 */
2743 	SCTPDBG(SCTP_DEBUG_OUTPUT2, "cur_addr_num:%d\n", cur_addr_num);
2744 
2745 	sctp_ifa = sctp_select_nth_preferred_addr_from_ifn_boundall(sctp_ifn, stcb, non_asoc_addr_ok, dest_is_loop,
2746 	    dest_is_priv, cur_addr_num, fam);
2747 
2748 	/* if sctp_ifa is NULL something changed??, fall to plan b. */
2749 	if (sctp_ifa) {
2750 		atomic_add_int(&sctp_ifa->refcount, 1);
2751 		if (net) {
2752 			/* save off where the next one we will want */
2753 			net->indx_of_eligible_next_to_use = cur_addr_num + 1;
2754 		}
2755 		return (sctp_ifa);
2756 	}
2757 	/*
2758 	 * plan_b: Look at all interfaces and find a preferred address. If
2759 	 * no preferred fall through to plan_c.
2760 	 */
2761 bound_all_plan_b:
2762 	SCTPDBG(SCTP_DEBUG_OUTPUT2, "Trying Plan B\n");
2763 	LIST_FOREACH(sctp_ifn, &vrf->ifnlist, next_ifn) {
2764 		if (dest_is_loop == 0 && SCTP_IFN_IS_IFT_LOOP(sctp_ifn)) {
2765 			/* wrong base scope */
2766 			continue;
2767 		}
2768 		if ((sctp_ifn == looked_at) && looked_at)
2769 			/* already looked at this guy */
2770 			continue;
2771 		num_preferred = sctp_count_num_preferred_boundall(sctp_ifn, stcb, non_asoc_addr_ok,
2772 		    dest_is_loop, dest_is_priv, fam);
2773 		SCTPDBG(SCTP_DEBUG_OUTPUT2,
2774 		    "Found ifn:%p %d preferred source addresses\n",
2775 		    ifn, num_preferred);
2776 		if (num_preferred == 0) {
2777 			/* None on this interface. */
2778 			continue;
2779 		}
2780 		SCTPDBG(SCTP_DEBUG_OUTPUT2,
2781 		    "num preferred:%d on interface:%p cur_addr_num:%d\n",
2782 		    num_preferred, sctp_ifn, cur_addr_num);
2783 
2784 		/*
2785 		 * Ok we have num_eligible_addr set with how many we can
2786 		 * use, this may vary from call to call due to addresses
2787 		 * being deprecated etc..
2788 		 */
2789 		if (cur_addr_num >= num_preferred) {
2790 			cur_addr_num = 0;
2791 		}
2792 		sifa = sctp_select_nth_preferred_addr_from_ifn_boundall(sctp_ifn, stcb, non_asoc_addr_ok, dest_is_loop,
2793 		    dest_is_priv, cur_addr_num, fam);
2794 		if (sifa == NULL)
2795 			continue;
2796 		if (net) {
2797 			net->indx_of_eligible_next_to_use = cur_addr_num + 1;
2798 			SCTPDBG(SCTP_DEBUG_OUTPUT2, "we selected %d\n",
2799 			    cur_addr_num);
2800 			SCTPDBG(SCTP_DEBUG_OUTPUT2, "Source:");
2801 			SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, &sifa->address.sa);
2802 			SCTPDBG(SCTP_DEBUG_OUTPUT2, "Dest:");
2803 			SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, &net->ro._l_addr.sa);
2804 		}
2805 		atomic_add_int(&sifa->refcount, 1);
2806 		return (sifa);
2807 
2808 	}
2809 
2810 	/* plan_c: do we have an acceptable address on the emit interface */
2811 	SCTPDBG(SCTP_DEBUG_OUTPUT2, "Trying Plan C: find acceptable on interface\n");
2812 	if (emit_ifn == NULL) {
2813 		goto plan_d;
2814 	}
2815 	LIST_FOREACH(sctp_ifa, &emit_ifn->ifalist, next_ifa) {
2816 		if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
2817 		    (non_asoc_addr_ok == 0))
2818 			continue;
2819 		sifa = sctp_is_ifa_addr_acceptable(sctp_ifa, dest_is_loop,
2820 		    dest_is_priv, fam);
2821 		if (sifa == NULL)
2822 			continue;
2823 		if (stcb) {
2824 			if ((non_asoc_addr_ok == 0) &&
2825 			    sctp_is_addr_restricted(stcb, sifa)) {
2826 				/*
2827 				 * It is restricted for some reason..
2828 				 * probably not yet added.
2829 				 */
2830 				continue;
2831 			}
2832 		}
2833 		atomic_add_int(&sifa->refcount, 1);
2834 		return (sifa);
2835 	}
2836 plan_d:
2837 	/*
2838 	 * plan_d: We are in trouble. No preferred address on the emit
2839 	 * interface. And not even a perfered address on all interfaces. Go
2840 	 * out and see if we can find an acceptable address somewhere
2841 	 * amongst all interfaces.
2842 	 */
2843 	SCTPDBG(SCTP_DEBUG_OUTPUT2, "Trying Plan D\n");
2844 	LIST_FOREACH(sctp_ifn, &vrf->ifnlist, next_ifn) {
2845 		if (dest_is_loop == 0 && SCTP_IFN_IS_IFT_LOOP(sctp_ifn)) {
2846 			/* wrong base scope */
2847 			continue;
2848 		}
2849 		if ((sctp_ifn == looked_at) && looked_at)
2850 			/* already looked at this guy */
2851 			continue;
2852 
2853 		LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
2854 			if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
2855 			    (non_asoc_addr_ok == 0))
2856 				continue;
2857 			sifa = sctp_is_ifa_addr_acceptable(sctp_ifa,
2858 			    dest_is_loop,
2859 			    dest_is_priv, fam);
2860 			if (sifa == NULL)
2861 				continue;
2862 			if (stcb) {
2863 				if ((non_asoc_addr_ok == 0) &&
2864 				    sctp_is_addr_restricted(stcb, sifa)) {
2865 					/*
2866 					 * It is restricted for some
2867 					 * reason.. probably not yet added.
2868 					 */
2869 					continue;
2870 				}
2871 			}
2872 			atomic_add_int(&sifa->refcount, 1);
2873 			return (sifa);
2874 		}
2875 	}
2876 	/*
2877 	 * Ok we can find NO address to source from that is not on our
2878 	 * negative list and non_asoc_address is NOT ok, or its on our
2879 	 * negative list. We cant source to it :-(
2880 	 */
2881 	return (NULL);
2882 }
2883 
2884 
2885 
2886 /* tcb may be NULL */
2887 struct sctp_ifa *
2888 sctp_source_address_selection(struct sctp_inpcb *inp,
2889     struct sctp_tcb *stcb,
2890     sctp_route_t * ro,
2891     struct sctp_nets *net,
2892     int non_asoc_addr_ok, uint32_t vrf_id)
2893 {
2894 
2895 	struct sockaddr_in *to = (struct sockaddr_in *)&ro->ro_dst;
2896 	struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&ro->ro_dst;
2897 	struct sctp_ifa *answer;
2898 	uint8_t dest_is_priv, dest_is_loop;
2899 	sa_family_t fam;
2900 
2901 	/*
2902 	 * Rules: - Find the route if needed, cache if I can. - Look at
2903 	 * interface address in route, Is it in the bound list. If so we
2904 	 * have the best source. - If not we must rotate amongst the
2905 	 * addresses.
2906 	 *
2907 	 * Cavets and issues
2908 	 *
2909 	 * Do we need to pay attention to scope. We can have a private address
2910 	 * or a global address we are sourcing or sending to. So if we draw
2911 	 * it out zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
2912 	 * For V4 ------------------------------------------ source     *
2913 	 * dest  *  result ----------------------------------------- <a>
2914 	 * Private    *    Global  *	NAT
2915 	 * ----------------------------------------- <b>  Private    *
2916 	 * Private *  No problem -----------------------------------------
2917 	 * <c>  Global     *    Private *  Huh, How will this work?
2918 	 * ----------------------------------------- <d>  Global     *
2919 	 * Global  *  No Problem ------------------------------------------
2920 	 * zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz For V6
2921 	 * ------------------------------------------ source     *      dest  *
2922 	 * result ----------------------------------------- <a>  Linklocal  *
2923 	 * Global  *	----------------------------------------- <b>
2924 	 * Linklocal  * Linklocal  *  No problem
2925 	 * ----------------------------------------- <c>  Global     *
2926 	 * Linklocal  *  Huh, How will this work?
2927 	 * ----------------------------------------- <d>  Global     *
2928 	 * Global  *  No Problem ------------------------------------------
2929 	 * zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
2930 	 *
2931 	 * And then we add to that what happens if there are multiple addresses
2932 	 * assigned to an interface. Remember the ifa on a ifn is a linked
2933 	 * list of addresses. So one interface can have more than one IP
2934 	 * address. What happens if we have both a private and a global
2935 	 * address? Do we then use context of destination to sort out which
2936 	 * one is best? And what about NAT's sending P->G may get you a NAT
2937 	 * translation, or should you select the G thats on the interface in
2938 	 * preference.
2939 	 *
2940 	 * Decisions:
2941 	 *
2942 	 * - count the number of addresses on the interface. - if its one, no
2943 	 * problem except case <c>. For <a> we will assume a NAT out there.
2944 	 * - if there are more than one, then we need to worry about scope P
2945 	 * or G. We should prefer G -> G and P -> P if possible. Then as a
2946 	 * secondary fall back to mixed types G->P being a last ditch one. -
2947 	 * The above all works for bound all, but bound specific we need to
2948 	 * use the same concept but instead only consider the bound
2949 	 * addresses. If the bound set is NOT assigned to the interface then
2950 	 * we must use rotation amongst the bound addresses..
2951 	 */
2952 	if (ro->ro_rt == NULL) {
2953 		/*
2954 		 * Need a route to cache.
2955 		 */
2956 		SCTP_RTALLOC(ro, vrf_id);
2957 	}
2958 	if (ro->ro_rt == NULL) {
2959 		return (NULL);
2960 	}
2961 	fam = to->sin_family;
2962 	dest_is_priv = dest_is_loop = 0;
2963 	/* Setup our scopes for the destination */
2964 	if (fam == AF_INET) {
2965 		/* Scope based on outbound address */
2966 		if ((IN4_ISPRIVATE_ADDRESS(&to->sin_addr))) {
2967 			dest_is_priv = 1;
2968 		} else if (IN4_ISLOOPBACK_ADDRESS(&to->sin_addr)) {
2969 			dest_is_loop = 1;
2970 			if (net != NULL) {
2971 				/* mark it as local */
2972 				net->addr_is_local = 1;
2973 			}
2974 		}
2975 	} else if (fam == AF_INET6) {
2976 		/* Scope based on outbound address */
2977 		if (IN6_IS_ADDR_LOOPBACK(&to6->sin6_addr)) {
2978 			/*
2979 			 * If the route goes to the loopback address OR the
2980 			 * address is a loopback address, we are loopback
2981 			 * scope. But we don't use dest_is_priv (link local
2982 			 * addresses).
2983 			 */
2984 			dest_is_loop = 1;
2985 			if (net != NULL) {
2986 				/* mark it as local */
2987 				net->addr_is_local = 1;
2988 			}
2989 		} else if (IN6_IS_ADDR_LINKLOCAL(&to6->sin6_addr)) {
2990 			dest_is_priv = 1;
2991 		}
2992 	}
2993 	SCTPDBG(SCTP_DEBUG_OUTPUT2, "Select source addr for:");
2994 	SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, (struct sockaddr *)to);
2995 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
2996 		/*
2997 		 * When bound to all if the address list is set it is a
2998 		 * negative list. Addresses being added by asconf.
2999 		 */
3000 		answer = sctp_choose_boundall(inp, stcb, net, ro, vrf_id,
3001 		    dest_is_priv, dest_is_loop,
3002 		    non_asoc_addr_ok, fam);
3003 		return (answer);
3004 	}
3005 	/*
3006 	 * Three possiblities here:
3007 	 *
3008 	 * a) stcb is NULL, which means we operate only from the list of
3009 	 * addresses (ifa's) bound to the endpoint and we care not about the
3010 	 * list. b) stcb is NOT-NULL, which means we have an assoc structure
3011 	 * and auto-asconf is on. This means that the list of addresses is a
3012 	 * NOT list. We use the list from the inp, but any listed address in
3013 	 * our list is NOT yet added. However if the non_asoc_addr_ok is set
3014 	 * we CAN use an address NOT available (i.e. being added). Its a
3015 	 * negative list. c) stcb is NOT-NULL, which means we have an assoc
3016 	 * structure and auto-asconf is off. This means that the list of
3017 	 * addresses is the ONLY addresses I can use.. its positive.
3018 	 *
3019 	 * Note we collapse b & c into the same function just like in the v6
3020 	 * address selection.
3021 	 */
3022 	if (stcb) {
3023 		answer = sctp_choose_boundspecific_stcb(inp, stcb, net, ro,
3024 		    vrf_id, dest_is_priv,
3025 		    dest_is_loop,
3026 		    non_asoc_addr_ok, fam);
3027 	} else {
3028 		answer = sctp_choose_boundspecific_inp(inp, ro, vrf_id,
3029 		    non_asoc_addr_ok,
3030 		    dest_is_priv,
3031 		    dest_is_loop, fam);
3032 	}
3033 	return (answer);
3034 }
3035 
3036 static int
3037 sctp_find_cmsg(int c_type, void *data, struct mbuf *control, int cpsize)
3038 {
3039 	struct cmsghdr cmh;
3040 	int tlen, at;
3041 
3042 	tlen = SCTP_BUF_LEN(control);
3043 	at = 0;
3044 	/*
3045 	 * Independent of how many mbufs, find the c_type inside the control
3046 	 * structure and copy out the data.
3047 	 */
3048 	while (at < tlen) {
3049 		if ((tlen - at) < (int)CMSG_ALIGN(sizeof(cmh))) {
3050 			/* not enough room for one more we are done. */
3051 			return (0);
3052 		}
3053 		m_copydata(control, at, sizeof(cmh), (caddr_t)&cmh);
3054 		if (((int)cmh.cmsg_len + at) > tlen) {
3055 			/*
3056 			 * this is real messed up since there is not enough
3057 			 * data here to cover the cmsg header. We are done.
3058 			 */
3059 			return (0);
3060 		}
3061 		if ((cmh.cmsg_level == IPPROTO_SCTP) &&
3062 		    (c_type == cmh.cmsg_type)) {
3063 			/* found the one we want, copy it out */
3064 			at += CMSG_ALIGN(sizeof(struct cmsghdr));
3065 			if ((int)(cmh.cmsg_len - CMSG_ALIGN(sizeof(struct cmsghdr))) < cpsize) {
3066 				/*
3067 				 * space of cmsg_len after header not big
3068 				 * enough
3069 				 */
3070 				return (0);
3071 			}
3072 			m_copydata(control, at, cpsize, data);
3073 			return (1);
3074 		} else {
3075 			at += CMSG_ALIGN(cmh.cmsg_len);
3076 			if (cmh.cmsg_len == 0) {
3077 				break;
3078 			}
3079 		}
3080 	}
3081 	/* not found */
3082 	return (0);
3083 }
3084 
3085 static struct mbuf *
3086 sctp_add_cookie(struct sctp_inpcb *inp, struct mbuf *init, int init_offset,
3087     struct mbuf *initack, int initack_offset, struct sctp_state_cookie *stc_in, uint8_t ** signature)
3088 {
3089 	struct mbuf *copy_init, *copy_initack, *m_at, *sig, *mret;
3090 	struct sctp_state_cookie *stc;
3091 	struct sctp_paramhdr *ph;
3092 	uint8_t *foo;
3093 	int sig_offset;
3094 	uint16_t cookie_sz;
3095 
3096 	mret = NULL;
3097 	mret = sctp_get_mbuf_for_msg((sizeof(struct sctp_state_cookie) +
3098 	    sizeof(struct sctp_paramhdr)), 0,
3099 	    M_DONTWAIT, 1, MT_DATA);
3100 	if (mret == NULL) {
3101 		return (NULL);
3102 	}
3103 	copy_init = SCTP_M_COPYM(init, init_offset, M_COPYALL, M_DONTWAIT);
3104 	if (copy_init == NULL) {
3105 		sctp_m_freem(mret);
3106 		return (NULL);
3107 	}
3108 	copy_initack = SCTP_M_COPYM(initack, initack_offset, M_COPYALL,
3109 	    M_DONTWAIT);
3110 	if (copy_initack == NULL) {
3111 		sctp_m_freem(mret);
3112 		sctp_m_freem(copy_init);
3113 		return (NULL);
3114 	}
3115 	/* easy side we just drop it on the end */
3116 	ph = mtod(mret, struct sctp_paramhdr *);
3117 	SCTP_BUF_LEN(mret) = sizeof(struct sctp_state_cookie) +
3118 	    sizeof(struct sctp_paramhdr);
3119 	stc = (struct sctp_state_cookie *)((caddr_t)ph +
3120 	    sizeof(struct sctp_paramhdr));
3121 	ph->param_type = htons(SCTP_STATE_COOKIE);
3122 	ph->param_length = 0;	/* fill in at the end */
3123 	/* Fill in the stc cookie data */
3124 	memcpy(stc, stc_in, sizeof(struct sctp_state_cookie));
3125 
3126 	/* tack the INIT and then the INIT-ACK onto the chain */
3127 	cookie_sz = 0;
3128 	m_at = mret;
3129 	for (m_at = mret; m_at; m_at = SCTP_BUF_NEXT(m_at)) {
3130 		cookie_sz += SCTP_BUF_LEN(m_at);
3131 		if (SCTP_BUF_NEXT(m_at) == NULL) {
3132 			SCTP_BUF_NEXT(m_at) = copy_init;
3133 			break;
3134 		}
3135 	}
3136 
3137 	for (m_at = copy_init; m_at; m_at = SCTP_BUF_NEXT(m_at)) {
3138 		cookie_sz += SCTP_BUF_LEN(m_at);
3139 		if (SCTP_BUF_NEXT(m_at) == NULL) {
3140 			SCTP_BUF_NEXT(m_at) = copy_initack;
3141 			break;
3142 		}
3143 	}
3144 
3145 	for (m_at = copy_initack; m_at; m_at = SCTP_BUF_NEXT(m_at)) {
3146 		cookie_sz += SCTP_BUF_LEN(m_at);
3147 		if (SCTP_BUF_NEXT(m_at) == NULL) {
3148 			break;
3149 		}
3150 	}
3151 	sig = sctp_get_mbuf_for_msg(SCTP_SECRET_SIZE, 0, M_DONTWAIT, 1, MT_DATA);
3152 	if (sig == NULL) {
3153 		/* no space, so free the entire chain */
3154 		sctp_m_freem(mret);
3155 		return (NULL);
3156 	}
3157 	SCTP_BUF_LEN(sig) = 0;
3158 	SCTP_BUF_NEXT(m_at) = sig;
3159 	sig_offset = 0;
3160 	foo = (uint8_t *) (mtod(sig, caddr_t)+sig_offset);
3161 	memset(foo, 0, SCTP_SIGNATURE_SIZE);
3162 	*signature = foo;
3163 	SCTP_BUF_LEN(sig) += SCTP_SIGNATURE_SIZE;
3164 	cookie_sz += SCTP_SIGNATURE_SIZE;
3165 	ph->param_length = htons(cookie_sz);
3166 	return (mret);
3167 }
3168 
3169 
3170 static uint8_t
3171 sctp_get_ect(struct sctp_tcb *stcb,
3172     struct sctp_tmit_chunk *chk)
3173 {
3174 	uint8_t this_random;
3175 
3176 	/* Huh? */
3177 	if (sctp_ecn_enable == 0)
3178 		return (0);
3179 
3180 	if (sctp_ecn_nonce == 0)
3181 		/* no nonce, always return ECT0 */
3182 		return (SCTP_ECT0_BIT);
3183 
3184 	if (stcb->asoc.peer_supports_ecn_nonce == 0) {
3185 		/* Peer does NOT support it, so we send a ECT0 only */
3186 		return (SCTP_ECT0_BIT);
3187 	}
3188 	if (chk == NULL)
3189 		return (SCTP_ECT0_BIT);
3190 
3191 	if ((stcb->asoc.hb_random_idx > 3) ||
3192 	    ((stcb->asoc.hb_random_idx == 3) &&
3193 	    (stcb->asoc.hb_ect_randombit > 7))) {
3194 		uint32_t rndval;
3195 
3196 warp_drive_sa:
3197 		rndval = sctp_select_initial_TSN(&stcb->sctp_ep->sctp_ep);
3198 		memcpy(stcb->asoc.hb_random_values, &rndval,
3199 		    sizeof(stcb->asoc.hb_random_values));
3200 		this_random = stcb->asoc.hb_random_values[0];
3201 		stcb->asoc.hb_random_idx = 0;
3202 		stcb->asoc.hb_ect_randombit = 0;
3203 	} else {
3204 		if (stcb->asoc.hb_ect_randombit > 7) {
3205 			stcb->asoc.hb_ect_randombit = 0;
3206 			stcb->asoc.hb_random_idx++;
3207 			if (stcb->asoc.hb_random_idx > 3) {
3208 				goto warp_drive_sa;
3209 			}
3210 		}
3211 		this_random = stcb->asoc.hb_random_values[stcb->asoc.hb_random_idx];
3212 	}
3213 	if ((this_random >> stcb->asoc.hb_ect_randombit) & 0x01) {
3214 		if (chk != NULL)
3215 			/* ECN Nonce stuff */
3216 			chk->rec.data.ect_nonce = SCTP_ECT1_BIT;
3217 		stcb->asoc.hb_ect_randombit++;
3218 		return (SCTP_ECT1_BIT);
3219 	} else {
3220 		stcb->asoc.hb_ect_randombit++;
3221 		return (SCTP_ECT0_BIT);
3222 	}
3223 }
3224 
3225 static int
3226 sctp_lowlevel_chunk_output(struct sctp_inpcb *inp,
3227     struct sctp_tcb *stcb,	/* may be NULL */
3228     struct sctp_nets *net,
3229     struct sockaddr *to,
3230     struct mbuf *m,
3231     uint32_t auth_offset,
3232     struct sctp_auth_chunk *auth,
3233     int nofragment_flag,
3234     int ecn_ok,
3235     struct sctp_tmit_chunk *chk,
3236     int out_of_asoc_ok)
3237 /* nofragment_flag to tell if IP_DF should be set (IPv4 only) */
3238 {
3239 	/*
3240 	 * Given a mbuf chain (via SCTP_BUF_NEXT()) that holds a packet
3241 	 * header WITH an SCTPHDR but no IP header, endpoint inp and sa
3242 	 * structure: - fill in the HMAC digest of any AUTH chunk in the
3243 	 * packet. - calculate and fill in the SCTP checksum. - prepend an
3244 	 * IP address header. - if boundall use INADDR_ANY. - if
3245 	 * boundspecific do source address selection. - set fragmentation
3246 	 * option for ipV4. - On return from IP output, check/adjust mtu
3247 	 * size of output interface and smallest_mtu size as well.
3248 	 */
3249 	/* Will need ifdefs around this */
3250 	struct mbuf *o_pak;
3251 	struct mbuf *newm;
3252 	struct sctphdr *sctphdr;
3253 	int packet_length;
3254 	uint32_t csum;
3255 	int ret;
3256 	uint32_t vrf_id;
3257 	sctp_route_t *ro = NULL;
3258 
3259 	if ((net) && (net->dest_state & SCTP_ADDR_OUT_OF_SCOPE)) {
3260 		sctp_m_freem(m);
3261 		return (EFAULT);
3262 	}
3263 	if (stcb) {
3264 		vrf_id = stcb->asoc.vrf_id;
3265 	} else {
3266 		vrf_id = inp->def_vrf_id;
3267 	}
3268 
3269 	/* fill in the HMAC digest for any AUTH chunk in the packet */
3270 	if ((auth != NULL) && (stcb != NULL)) {
3271 		sctp_fill_hmac_digest_m(m, auth_offset, auth, stcb);
3272 	}
3273 	/* Calculate the csum and fill in the length of the packet */
3274 	sctphdr = mtod(m, struct sctphdr *);
3275 	if (sctp_no_csum_on_loopback &&
3276 	    (stcb) &&
3277 	    (stcb->asoc.loopback_scope)) {
3278 		sctphdr->checksum = 0;
3279 		/*
3280 		 * This can probably now be taken out since my audit shows
3281 		 * no more bad pktlen's coming in. But we will wait a while
3282 		 * yet.
3283 		 */
3284 		packet_length = sctp_calculate_len(m);
3285 	} else {
3286 		sctphdr->checksum = 0;
3287 		csum = sctp_calculate_sum(m, &packet_length, 0);
3288 		sctphdr->checksum = csum;
3289 	}
3290 
3291 	if (to->sa_family == AF_INET) {
3292 		struct ip *ip = NULL;
3293 		sctp_route_t iproute;
3294 		uint8_t tos_value;
3295 
3296 		newm = sctp_get_mbuf_for_msg(sizeof(struct ip), 1, M_DONTWAIT, 1, MT_DATA);
3297 		if (newm == NULL) {
3298 			sctp_m_freem(m);
3299 			SCTP_LTRACE_ERR(inp, stcb, ENOMEM, 0);
3300 			return (ENOMEM);
3301 		}
3302 		SCTP_ALIGN_TO_END(newm, sizeof(struct ip));
3303 		SCTP_BUF_LEN(newm) = sizeof(struct ip);
3304 		packet_length += sizeof(struct ip);
3305 		SCTP_BUF_NEXT(newm) = m;
3306 		m = newm;
3307 		ip = mtod(m, struct ip *);
3308 		ip->ip_v = IPVERSION;
3309 		ip->ip_hl = (sizeof(struct ip) >> 2);
3310 		if (net) {
3311 			tos_value = net->tos_flowlabel & 0x000000ff;
3312 		} else {
3313 			tos_value = inp->ip_inp.inp.inp_ip_tos;
3314 		}
3315 		if (nofragment_flag) {
3316 #if defined(WITH_CONVERT_IP_OFF) || defined(__FreeBSD__) || defined(__APPLE__)
3317 			ip->ip_off = IP_DF;
3318 #else
3319 			ip->ip_off = htons(IP_DF);
3320 #endif
3321 		} else
3322 			ip->ip_off = 0;
3323 
3324 		/* FreeBSD has a function for ip_id's */
3325 		ip->ip_id = ip_newid();
3326 
3327 		ip->ip_ttl = inp->ip_inp.inp.inp_ip_ttl;
3328 		ip->ip_len = packet_length;
3329 		if (stcb) {
3330 			if ((stcb->asoc.ecn_allowed) && ecn_ok) {
3331 				/* Enable ECN */
3332 				ip->ip_tos = ((u_char)(tos_value & 0xfc) | sctp_get_ect(stcb, chk));
3333 			} else {
3334 				/* No ECN */
3335 				ip->ip_tos = (u_char)(tos_value & 0xfc);
3336 			}
3337 		} else {
3338 			/* no association at all */
3339 			ip->ip_tos = (tos_value & 0xfc);
3340 		}
3341 		ip->ip_p = IPPROTO_SCTP;
3342 		ip->ip_sum = 0;
3343 		if (net == NULL) {
3344 			ro = &iproute;
3345 			memset(&iproute, 0, sizeof(iproute));
3346 			memcpy(&ro->ro_dst, to, to->sa_len);
3347 		} else {
3348 			ro = (sctp_route_t *) & net->ro;
3349 		}
3350 		/* Now the address selection part */
3351 		ip->ip_dst.s_addr = ((struct sockaddr_in *)to)->sin_addr.s_addr;
3352 
3353 		/* call the routine to select the src address */
3354 		if (net) {
3355 			if (net->ro._s_addr && (net->ro._s_addr->localifa_flags & SCTP_BEING_DELETED)) {
3356 				sctp_free_ifa(net->ro._s_addr);
3357 				net->ro._s_addr = NULL;
3358 				net->src_addr_selected = 0;
3359 			}
3360 			if (net->src_addr_selected == 0) {
3361 				/* Cache the source address */
3362 				net->ro._s_addr = sctp_source_address_selection(inp, stcb,
3363 				    ro, net, out_of_asoc_ok,
3364 				    vrf_id);
3365 				net->src_addr_selected = 1;
3366 			}
3367 			if (net->ro._s_addr == NULL) {
3368 				/* No route to host */
3369 				net->src_addr_selected = 0;
3370 				goto no_route;
3371 			}
3372 			ip->ip_src = net->ro._s_addr->address.sin.sin_addr;
3373 		} else {
3374 			struct sctp_ifa *_lsrc;
3375 
3376 			_lsrc = sctp_source_address_selection(inp,
3377 			    stcb, ro, net, out_of_asoc_ok, vrf_id);
3378 			if (_lsrc == NULL) {
3379 				goto no_route;
3380 			}
3381 			ip->ip_src = _lsrc->address.sin.sin_addr;
3382 			sctp_free_ifa(_lsrc);
3383 		}
3384 
3385 		/*
3386 		 * If source address selection fails and we find no route
3387 		 * then the ip_output should fail as well with a
3388 		 * NO_ROUTE_TO_HOST type error. We probably should catch
3389 		 * that somewhere and abort the association right away
3390 		 * (assuming this is an INIT being sent).
3391 		 */
3392 		if ((ro->ro_rt == NULL)) {
3393 			/*
3394 			 * src addr selection failed to find a route (or
3395 			 * valid source addr), so we can't get there from
3396 			 * here (yet)!
3397 			 */
3398 	no_route:
3399 			SCTPDBG(SCTP_DEBUG_OUTPUT1,
3400 			    "%s: dropped packet - no valid source addr\n",
3401 			    __FUNCTION__);
3402 			if (net) {
3403 				SCTPDBG(SCTP_DEBUG_OUTPUT1,
3404 				    "Destination was ");
3405 				SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT1,
3406 				    &net->ro._l_addr.sa);
3407 				if (net->dest_state & SCTP_ADDR_CONFIRMED) {
3408 					if ((net->dest_state & SCTP_ADDR_REACHABLE) && stcb) {
3409 						SCTPDBG(SCTP_DEBUG_OUTPUT1, "no route takes interface %p down\n", net);
3410 						sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_DOWN,
3411 						    stcb,
3412 						    SCTP_FAILED_THRESHOLD,
3413 						    (void *)net);
3414 						net->dest_state &= ~SCTP_ADDR_REACHABLE;
3415 						net->dest_state |= SCTP_ADDR_NOT_REACHABLE;
3416 						/*
3417 						 * JRS 5/14/07 - If a
3418 						 * destination is
3419 						 * unreachable, the PF bit
3420 						 * is turned off.  This
3421 						 * allows an unambiguous use
3422 						 * of the PF bit for
3423 						 * destinations that are
3424 						 * reachable but potentially
3425 						 * failed. If the
3426 						 * destination is set to the
3427 						 * unreachable state, also
3428 						 * set the destination to
3429 						 * the PF state.
3430 						 */
3431 						/*
3432 						 * Add debug message here if
3433 						 * destination is not in PF
3434 						 * state.
3435 						 */
3436 						/*
3437 						 * Stop any running T3
3438 						 * timers here?
3439 						 */
3440 						if (sctp_cmt_on_off && sctp_cmt_pf) {
3441 							net->dest_state &= ~SCTP_ADDR_PF;
3442 							SCTPDBG(SCTP_DEBUG_OUTPUT1, "Destination %p moved from PF to unreachable.\n",
3443 							    net);
3444 						}
3445 					}
3446 				}
3447 				if (stcb) {
3448 					if (net == stcb->asoc.primary_destination) {
3449 						/* need a new primary */
3450 						struct sctp_nets *alt;
3451 
3452 						alt = sctp_find_alternate_net(stcb, net, 0);
3453 						if (alt != net) {
3454 							if (sctp_set_primary_addr(stcb,
3455 							    (struct sockaddr *)NULL,
3456 							    alt) == 0) {
3457 								net->dest_state |= SCTP_ADDR_WAS_PRIMARY;
3458 								if (net->ro._s_addr) {
3459 									sctp_free_ifa(net->ro._s_addr);
3460 									net->ro._s_addr = NULL;
3461 								}
3462 								net->src_addr_selected = 0;
3463 							}
3464 						}
3465 					}
3466 				}
3467 			}
3468 			sctp_m_freem(m);
3469 			return (EHOSTUNREACH);
3470 		}
3471 		if (ro != &iproute) {
3472 			memcpy(&iproute, ro, sizeof(*ro));
3473 		}
3474 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "Calling ipv4 output routine from low level src addr:%x\n",
3475 		    (uint32_t) (ntohl(ip->ip_src.s_addr)));
3476 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "Destination is %x\n",
3477 		    (uint32_t) (ntohl(ip->ip_dst.s_addr)));
3478 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "RTP route is %p through\n",
3479 		    ro->ro_rt);
3480 
3481 		if (SCTP_GET_HEADER_FOR_OUTPUT(o_pak)) {
3482 			/* failed to prepend data, give up */
3483 			sctp_m_freem(m);
3484 			SCTP_LTRACE_ERR(inp, stcb, ENOMEM, 0);
3485 			return (ENOMEM);
3486 		}
3487 #ifdef  SCTP_PACKET_LOGGING
3488 		if (sctp_logging_level & SCTP_LAST_PACKET_TRACING)
3489 			sctp_packet_log(m, packet_length);
3490 #endif
3491 		SCTP_ATTACH_CHAIN(o_pak, m, packet_length);
3492 
3493 		/* send it out.  table id is taken from stcb */
3494 		SCTP_IP_OUTPUT(ret, o_pak, ro, stcb, vrf_id);
3495 
3496 		SCTP_STAT_INCR(sctps_sendpackets);
3497 		SCTP_STAT_INCR_COUNTER64(sctps_outpackets);
3498 		if (ret)
3499 			SCTP_STAT_INCR(sctps_senderrors);
3500 
3501 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "IP output returns %d\n", ret);
3502 		if (net == NULL) {
3503 			/* free tempy routes */
3504 			if (ro->ro_rt) {
3505 				RTFREE(ro->ro_rt);
3506 				ro->ro_rt = NULL;
3507 			}
3508 		} else {
3509 			/* PMTU check versus smallest asoc MTU goes here */
3510 			if (ro->ro_rt != NULL) {
3511 				uint32_t mtu;
3512 
3513 				mtu = SCTP_GATHER_MTU_FROM_ROUTE(net->ro._s_addr, &net->ro._l_addr.sa, ro->ro_rt);
3514 				if (mtu &&
3515 				    (stcb->asoc.smallest_mtu > mtu)) {
3516 #ifdef SCTP_PRINT_FOR_B_AND_M
3517 					SCTP_PRINTF("sctp_mtu_size_reset called after ip_output mtu-change:%d\n",
3518 					    mtu);
3519 #endif
3520 					sctp_mtu_size_reset(inp, &stcb->asoc, mtu);
3521 					net->mtu = mtu;
3522 				}
3523 			} else {
3524 				/* route was freed */
3525 				if (net->ro._s_addr &&
3526 				    net->src_addr_selected) {
3527 					sctp_free_ifa(net->ro._s_addr);
3528 					net->ro._s_addr = NULL;
3529 				}
3530 				net->src_addr_selected = 0;
3531 			}
3532 		}
3533 		return (ret);
3534 	}
3535 #ifdef INET6
3536 	else if (to->sa_family == AF_INET6) {
3537 		uint32_t flowlabel;
3538 		struct ip6_hdr *ip6h;
3539 		struct route_in6 ip6route;
3540 		struct ifnet *ifp;
3541 		u_char flowTop;
3542 		uint16_t flowBottom;
3543 		u_char tosBottom, tosTop;
3544 		struct sockaddr_in6 *sin6, tmp, *lsa6, lsa6_tmp;
3545 		int prev_scope = 0;
3546 		struct sockaddr_in6 lsa6_storage;
3547 		int error;
3548 		u_short prev_port = 0;
3549 
3550 		if (net != NULL) {
3551 			flowlabel = net->tos_flowlabel;
3552 		} else {
3553 			flowlabel = ((struct in6pcb *)inp)->in6p_flowinfo;
3554 		}
3555 
3556 		newm = sctp_get_mbuf_for_msg(sizeof(struct ip6_hdr), 1, M_DONTWAIT, 1, MT_DATA);
3557 		if (newm == NULL) {
3558 			sctp_m_freem(m);
3559 			SCTP_LTRACE_ERR(inp, stcb, ENOMEM, 0);
3560 			return (ENOMEM);
3561 		}
3562 		SCTP_ALIGN_TO_END(newm, sizeof(struct ip6_hdr));
3563 		SCTP_BUF_LEN(newm) = sizeof(struct ip6_hdr);
3564 		packet_length += sizeof(struct ip6_hdr);
3565 		SCTP_BUF_NEXT(newm) = m;
3566 		m = newm;
3567 
3568 		ip6h = mtod(m, struct ip6_hdr *);
3569 		/*
3570 		 * We assume here that inp_flow is in host byte order within
3571 		 * the TCB!
3572 		 */
3573 		flowBottom = flowlabel & 0x0000ffff;
3574 		flowTop = ((flowlabel & 0x000f0000) >> 16);
3575 		tosTop = (((flowlabel & 0xf0) >> 4) | IPV6_VERSION);
3576 		/* protect *sin6 from overwrite */
3577 		sin6 = (struct sockaddr_in6 *)to;
3578 		tmp = *sin6;
3579 		sin6 = &tmp;
3580 
3581 		/* KAME hack: embed scopeid */
3582 		if (sa6_embedscope(sin6, ip6_use_defzone) != 0)
3583 			return (EINVAL);
3584 		if (net == NULL) {
3585 			memset(&ip6route, 0, sizeof(ip6route));
3586 			ro = (sctp_route_t *) & ip6route;
3587 			memcpy(&ro->ro_dst, sin6, sin6->sin6_len);
3588 		} else {
3589 			ro = (sctp_route_t *) & net->ro;
3590 		}
3591 		if (stcb != NULL) {
3592 			if ((stcb->asoc.ecn_allowed) && ecn_ok) {
3593 				/* Enable ECN */
3594 				tosBottom = (((((struct in6pcb *)inp)->in6p_flowinfo & 0x0c) | sctp_get_ect(stcb, chk)) << 4);
3595 			} else {
3596 				/* No ECN */
3597 				tosBottom = ((((struct in6pcb *)inp)->in6p_flowinfo & 0x0c) << 4);
3598 			}
3599 		} else {
3600 			/* we could get no asoc if it is a O-O-T-B packet */
3601 			tosBottom = ((((struct in6pcb *)inp)->in6p_flowinfo & 0x0c) << 4);
3602 		}
3603 		ip6h->ip6_flow = htonl(((tosTop << 24) | ((tosBottom | flowTop) << 16) | flowBottom));
3604 		ip6h->ip6_nxt = IPPROTO_SCTP;
3605 		ip6h->ip6_plen = (packet_length - sizeof(struct ip6_hdr));
3606 		ip6h->ip6_dst = sin6->sin6_addr;
3607 
3608 		/*
3609 		 * Add SRC address selection here: we can only reuse to a
3610 		 * limited degree the kame src-addr-sel, since we can try
3611 		 * their selection but it may not be bound.
3612 		 */
3613 		bzero(&lsa6_tmp, sizeof(lsa6_tmp));
3614 		lsa6_tmp.sin6_family = AF_INET6;
3615 		lsa6_tmp.sin6_len = sizeof(lsa6_tmp);
3616 		lsa6 = &lsa6_tmp;
3617 		if (net) {
3618 			if (net->ro._s_addr && net->ro._s_addr->localifa_flags & SCTP_BEING_DELETED) {
3619 				sctp_free_ifa(net->ro._s_addr);
3620 				net->ro._s_addr = NULL;
3621 				net->src_addr_selected = 0;
3622 			}
3623 			if (net->src_addr_selected == 0) {
3624 				/* Cache the source address */
3625 				net->ro._s_addr = sctp_source_address_selection(inp,
3626 				    stcb,
3627 				    ro,
3628 				    net,
3629 				    out_of_asoc_ok,
3630 				    vrf_id);
3631 				net->src_addr_selected = 1;
3632 			}
3633 			if (net->ro._s_addr == NULL) {
3634 				SCTPDBG(SCTP_DEBUG_OUTPUT3, "V6:No route to host\n");
3635 				net->src_addr_selected = 0;
3636 				goto no_route;
3637 			}
3638 			lsa6->sin6_addr = net->ro._s_addr->address.sin6.sin6_addr;
3639 		} else {
3640 			struct sctp_ifa *_lsrc;
3641 
3642 			_lsrc = sctp_source_address_selection(inp, stcb, ro, net, out_of_asoc_ok, vrf_id);
3643 			if (_lsrc == NULL) {
3644 				goto no_route;
3645 			}
3646 			lsa6->sin6_addr = _lsrc->address.sin6.sin6_addr;
3647 			sctp_free_ifa(_lsrc);
3648 		}
3649 		lsa6->sin6_port = inp->sctp_lport;
3650 
3651 		if ((ro->ro_rt == NULL)) {
3652 			/*
3653 			 * src addr selection failed to find a route (or
3654 			 * valid source addr), so we can't get there from
3655 			 * here!
3656 			 */
3657 			goto no_route;
3658 		}
3659 		/*
3660 		 * XXX: sa6 may not have a valid sin6_scope_id in the
3661 		 * non-SCOPEDROUTING case.
3662 		 */
3663 		bzero(&lsa6_storage, sizeof(lsa6_storage));
3664 		lsa6_storage.sin6_family = AF_INET6;
3665 		lsa6_storage.sin6_len = sizeof(lsa6_storage);
3666 		if ((error = sa6_recoverscope(&lsa6_storage)) != 0) {
3667 			sctp_m_freem(m);
3668 			return (error);
3669 		}
3670 		/* XXX */
3671 		lsa6_storage.sin6_addr = lsa6->sin6_addr;
3672 		lsa6_storage.sin6_port = inp->sctp_lport;
3673 		lsa6 = &lsa6_storage;
3674 		ip6h->ip6_src = lsa6->sin6_addr;
3675 
3676 		/*
3677 		 * We set the hop limit now since there is a good chance
3678 		 * that our ro pointer is now filled
3679 		 */
3680 		ip6h->ip6_hlim = SCTP_GET_HLIM(inp, ro);
3681 		ifp = SCTP_GET_IFN_VOID_FROM_ROUTE(ro);
3682 
3683 #ifdef SCTP_DEBUG
3684 		/* Copy to be sure something bad is not happening */
3685 		sin6->sin6_addr = ip6h->ip6_dst;
3686 		lsa6->sin6_addr = ip6h->ip6_src;
3687 #endif
3688 
3689 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "Calling ipv6 output routine from low level\n");
3690 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "src: ");
3691 		SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT3, (struct sockaddr *)lsa6);
3692 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "dst: ");
3693 		SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT3, (struct sockaddr *)sin6);
3694 		if (net) {
3695 			sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
3696 			/* preserve the port and scope for link local send */
3697 			prev_scope = sin6->sin6_scope_id;
3698 			prev_port = sin6->sin6_port;
3699 		}
3700 		if (SCTP_GET_HEADER_FOR_OUTPUT(o_pak)) {
3701 			/* failed to prepend data, give up */
3702 			sctp_m_freem(m);
3703 			SCTP_LTRACE_ERR(inp, stcb, ENOMEM, 0);
3704 			return (ENOMEM);
3705 		}
3706 #ifdef  SCTP_PACKET_LOGGING
3707 		if (sctp_logging_level & SCTP_LAST_PACKET_TRACING)
3708 			sctp_packet_log(m, packet_length);
3709 #endif
3710 		SCTP_ATTACH_CHAIN(o_pak, m, packet_length);
3711 
3712 		/* send it out. table id is taken from stcb */
3713 		SCTP_IP6_OUTPUT(ret, o_pak, (struct route_in6 *)ro, &ifp,
3714 		    stcb, vrf_id);
3715 
3716 		if (net) {
3717 			/* for link local this must be done */
3718 			sin6->sin6_scope_id = prev_scope;
3719 			sin6->sin6_port = prev_port;
3720 		}
3721 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "return from send is %d\n", ret);
3722 		SCTP_STAT_INCR(sctps_sendpackets);
3723 		SCTP_STAT_INCR_COUNTER64(sctps_outpackets);
3724 		if (ret) {
3725 			SCTP_STAT_INCR(sctps_senderrors);
3726 		}
3727 		if (net == NULL) {
3728 			/* Now if we had a temp route free it */
3729 			if (ro->ro_rt) {
3730 				RTFREE(ro->ro_rt);
3731 			}
3732 		} else {
3733 			/* PMTU check versus smallest asoc MTU goes here */
3734 			if (ro->ro_rt == NULL) {
3735 				/* Route was freed */
3736 				if (net->ro._s_addr &&
3737 				    net->src_addr_selected) {
3738 					sctp_free_ifa(net->ro._s_addr);
3739 					net->ro._s_addr = NULL;
3740 				}
3741 				net->src_addr_selected = 0;
3742 			}
3743 			if (ro->ro_rt != NULL) {
3744 				uint32_t mtu;
3745 
3746 				mtu = SCTP_GATHER_MTU_FROM_ROUTE(net->ro._s_addr, &net->ro._l_addr.sa, ro->ro_rt);
3747 				if (mtu &&
3748 				    (stcb->asoc.smallest_mtu > mtu)) {
3749 #ifdef SCTP_PRINT_FOR_B_AND_M
3750 					SCTP_PRINTF("sctp_mtu_size_reset called after ip6_output mtu-change:%d\n",
3751 					    mtu);
3752 #endif
3753 					sctp_mtu_size_reset(inp, &stcb->asoc, mtu);
3754 					net->mtu = mtu;
3755 				}
3756 			} else if (ifp) {
3757 				if (ND_IFINFO(ifp)->linkmtu &&
3758 				    (stcb->asoc.smallest_mtu > ND_IFINFO(ifp)->linkmtu)) {
3759 #ifdef SCTP_PRINT_FOR_B_AND_M
3760 					SCTP_PRINTF("sctp_mtu_size_reset called via ifp ND_IFINFO() linkmtu:%d\n",
3761 					    ND_IFINFO(ifp)->linkmtu);
3762 #endif
3763 					sctp_mtu_size_reset(inp,
3764 					    &stcb->asoc,
3765 					    ND_IFINFO(ifp)->linkmtu);
3766 				}
3767 			}
3768 		}
3769 		return (ret);
3770 	}
3771 #endif
3772 	else {
3773 		SCTPDBG(SCTP_DEBUG_OUTPUT1, "Unknown protocol (TSNH) type %d\n",
3774 		    ((struct sockaddr *)to)->sa_family);
3775 		sctp_m_freem(m);
3776 		return (EFAULT);
3777 	}
3778 }
3779 
3780 
3781 void
3782 sctp_send_initiate(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
3783 {
3784 	struct mbuf *m, *m_at, *mp_last;
3785 	struct sctp_nets *net;
3786 	struct sctp_init_msg *initm;
3787 	struct sctp_supported_addr_param *sup_addr;
3788 	struct sctp_ecn_supported_param *ecn;
3789 	struct sctp_prsctp_supported_param *prsctp;
3790 	struct sctp_ecn_nonce_supported_param *ecn_nonce;
3791 	struct sctp_supported_chunk_types_param *pr_supported;
3792 	int cnt_inits_to = 0;
3793 	int padval, ret;
3794 	int num_ext;
3795 	int p_len;
3796 
3797 	/* INIT's always go to the primary (and usually ONLY address) */
3798 	mp_last = NULL;
3799 	net = stcb->asoc.primary_destination;
3800 	if (net == NULL) {
3801 		net = TAILQ_FIRST(&stcb->asoc.nets);
3802 		if (net == NULL) {
3803 			/* TSNH */
3804 			return;
3805 		}
3806 		/* we confirm any address we send an INIT to */
3807 		net->dest_state &= ~SCTP_ADDR_UNCONFIRMED;
3808 		(void)sctp_set_primary_addr(stcb, NULL, net);
3809 	} else {
3810 		/* we confirm any address we send an INIT to */
3811 		net->dest_state &= ~SCTP_ADDR_UNCONFIRMED;
3812 	}
3813 	SCTPDBG(SCTP_DEBUG_OUTPUT4, "Sending INIT\n");
3814 	if (((struct sockaddr *)&(net->ro._l_addr))->sa_family == AF_INET6) {
3815 		/*
3816 		 * special hook, if we are sending to link local it will not
3817 		 * show up in our private address count.
3818 		 */
3819 		struct sockaddr_in6 *sin6l;
3820 
3821 		sin6l = &net->ro._l_addr.sin6;
3822 		if (IN6_IS_ADDR_LINKLOCAL(&sin6l->sin6_addr))
3823 			cnt_inits_to = 1;
3824 	}
3825 	if (SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer)) {
3826 		/* This case should not happen */
3827 		return;
3828 	}
3829 	/* start the INIT timer */
3830 	sctp_timer_start(SCTP_TIMER_TYPE_INIT, inp, stcb, net);
3831 
3832 	m = sctp_get_mbuf_for_msg(MCLBYTES, 1, M_DONTWAIT, 1, MT_DATA);
3833 	if (m == NULL) {
3834 		/* No memory, INIT timer will re-attempt. */
3835 		return;
3836 	}
3837 	SCTP_BUF_LEN(m) = sizeof(struct sctp_init_msg);
3838 	/*
3839 	 * assume peer supports asconf in order to be able to queue local
3840 	 * address changes while an INIT is in flight and before the assoc
3841 	 * is established.
3842 	 */
3843 	stcb->asoc.peer_supports_asconf = 1;
3844 	/* Now lets put the SCTP header in place */
3845 	initm = mtod(m, struct sctp_init_msg *);
3846 	initm->sh.src_port = inp->sctp_lport;
3847 	initm->sh.dest_port = stcb->rport;
3848 	initm->sh.v_tag = 0;
3849 	initm->sh.checksum = 0;	/* calculate later */
3850 	/* now the chunk header */
3851 	initm->msg.ch.chunk_type = SCTP_INITIATION;
3852 	initm->msg.ch.chunk_flags = 0;
3853 	/* fill in later from mbuf we build */
3854 	initm->msg.ch.chunk_length = 0;
3855 	/* place in my tag */
3856 	initm->msg.init.initiate_tag = htonl(stcb->asoc.my_vtag);
3857 	/* set up some of the credits. */
3858 	initm->msg.init.a_rwnd = htonl(max(SCTP_SB_LIMIT_RCV(inp->sctp_socket),
3859 	    SCTP_MINIMAL_RWND));
3860 
3861 	initm->msg.init.num_outbound_streams = htons(stcb->asoc.pre_open_streams);
3862 	initm->msg.init.num_inbound_streams = htons(stcb->asoc.max_inbound_streams);
3863 	initm->msg.init.initial_tsn = htonl(stcb->asoc.init_seq_number);
3864 	/* now the address restriction */
3865 	sup_addr = (struct sctp_supported_addr_param *)((caddr_t)initm +
3866 	    sizeof(*initm));
3867 	sup_addr->ph.param_type = htons(SCTP_SUPPORTED_ADDRTYPE);
3868 	/* we support 2 types IPv6/IPv4 */
3869 	sup_addr->ph.param_length = htons(sizeof(*sup_addr) +
3870 	    sizeof(uint16_t));
3871 	sup_addr->addr_type[0] = htons(SCTP_IPV4_ADDRESS);
3872 	sup_addr->addr_type[1] = htons(SCTP_IPV6_ADDRESS);
3873 	SCTP_BUF_LEN(m) += sizeof(*sup_addr) + sizeof(uint16_t);
3874 
3875 	if (inp->sctp_ep.adaptation_layer_indicator) {
3876 		struct sctp_adaptation_layer_indication *ali;
3877 
3878 		ali = (struct sctp_adaptation_layer_indication *)(
3879 		    (caddr_t)sup_addr + sizeof(*sup_addr) + sizeof(uint16_t));
3880 		ali->ph.param_type = htons(SCTP_ULP_ADAPTATION);
3881 		ali->ph.param_length = htons(sizeof(*ali));
3882 		ali->indication = ntohl(inp->sctp_ep.adaptation_layer_indicator);
3883 		SCTP_BUF_LEN(m) += sizeof(*ali);
3884 		ecn = (struct sctp_ecn_supported_param *)((caddr_t)ali +
3885 		    sizeof(*ali));
3886 	} else {
3887 		ecn = (struct sctp_ecn_supported_param *)((caddr_t)sup_addr +
3888 		    sizeof(*sup_addr) + sizeof(uint16_t));
3889 	}
3890 
3891 	/* now any cookie time extensions */
3892 	if (stcb->asoc.cookie_preserve_req) {
3893 		struct sctp_cookie_perserve_param *cookie_preserve;
3894 
3895 		cookie_preserve = (struct sctp_cookie_perserve_param *)(ecn);
3896 		cookie_preserve->ph.param_type = htons(SCTP_COOKIE_PRESERVE);
3897 		cookie_preserve->ph.param_length = htons(
3898 		    sizeof(*cookie_preserve));
3899 		cookie_preserve->time = htonl(stcb->asoc.cookie_preserve_req);
3900 		SCTP_BUF_LEN(m) += sizeof(*cookie_preserve);
3901 		ecn = (struct sctp_ecn_supported_param *)(
3902 		    (caddr_t)cookie_preserve + sizeof(*cookie_preserve));
3903 		stcb->asoc.cookie_preserve_req = 0;
3904 	}
3905 	/* ECN parameter */
3906 	if (sctp_ecn_enable == 1) {
3907 		ecn->ph.param_type = htons(SCTP_ECN_CAPABLE);
3908 		ecn->ph.param_length = htons(sizeof(*ecn));
3909 		SCTP_BUF_LEN(m) += sizeof(*ecn);
3910 		prsctp = (struct sctp_prsctp_supported_param *)((caddr_t)ecn +
3911 		    sizeof(*ecn));
3912 	} else {
3913 		prsctp = (struct sctp_prsctp_supported_param *)((caddr_t)ecn);
3914 	}
3915 	/* And now tell the peer we do pr-sctp */
3916 	prsctp->ph.param_type = htons(SCTP_PRSCTP_SUPPORTED);
3917 	prsctp->ph.param_length = htons(sizeof(*prsctp));
3918 	SCTP_BUF_LEN(m) += sizeof(*prsctp);
3919 
3920 	/* And now tell the peer we do all the extensions */
3921 	pr_supported = (struct sctp_supported_chunk_types_param *)
3922 	    ((caddr_t)prsctp + sizeof(*prsctp));
3923 	pr_supported->ph.param_type = htons(SCTP_SUPPORTED_CHUNK_EXT);
3924 	num_ext = 0;
3925 	pr_supported->chunk_types[num_ext++] = SCTP_ASCONF;
3926 	pr_supported->chunk_types[num_ext++] = SCTP_ASCONF_ACK;
3927 	pr_supported->chunk_types[num_ext++] = SCTP_FORWARD_CUM_TSN;
3928 	pr_supported->chunk_types[num_ext++] = SCTP_PACKET_DROPPED;
3929 	pr_supported->chunk_types[num_ext++] = SCTP_STREAM_RESET;
3930 	if (!sctp_auth_disable)
3931 		pr_supported->chunk_types[num_ext++] = SCTP_AUTHENTICATION;
3932 	p_len = sizeof(*pr_supported) + num_ext;
3933 	pr_supported->ph.param_length = htons(p_len);
3934 	bzero((caddr_t)pr_supported + p_len, SCTP_SIZE32(p_len) - p_len);
3935 	SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
3936 
3937 	/* ECN nonce: And now tell the peer we support ECN nonce */
3938 	if (sctp_ecn_nonce) {
3939 		ecn_nonce = (struct sctp_ecn_nonce_supported_param *)
3940 		    ((caddr_t)pr_supported + SCTP_SIZE32(p_len));
3941 		ecn_nonce->ph.param_type = htons(SCTP_ECN_NONCE_SUPPORTED);
3942 		ecn_nonce->ph.param_length = htons(sizeof(*ecn_nonce));
3943 		SCTP_BUF_LEN(m) += sizeof(*ecn_nonce);
3944 	}
3945 	/* add authentication parameters */
3946 	if (!sctp_auth_disable) {
3947 		struct sctp_auth_random *randp;
3948 		struct sctp_auth_hmac_algo *hmacs;
3949 		struct sctp_auth_chunk_list *chunks;
3950 
3951 		/* attach RANDOM parameter, if available */
3952 		if (stcb->asoc.authinfo.random != NULL) {
3953 			randp = (struct sctp_auth_random *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
3954 			p_len = sizeof(*randp) + stcb->asoc.authinfo.random_len;
3955 #ifdef SCTP_AUTH_DRAFT_04
3956 			randp->ph.param_type = htons(SCTP_RANDOM);
3957 			randp->ph.param_length = htons(p_len);
3958 			bcopy(stcb->asoc.authinfo.random->key,
3959 			    randp->random_data,
3960 			    stcb->asoc.authinfo.random_len);
3961 #else
3962 			/* random key already contains the header */
3963 			bcopy(stcb->asoc.authinfo.random->key, randp, p_len);
3964 #endif
3965 			/* zero out any padding required */
3966 			bzero((caddr_t)randp + p_len, SCTP_SIZE32(p_len) - p_len);
3967 			SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
3968 		}
3969 		/* add HMAC_ALGO parameter */
3970 		hmacs = (struct sctp_auth_hmac_algo *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
3971 		p_len = sctp_serialize_hmaclist(stcb->asoc.local_hmacs,
3972 		    (uint8_t *) hmacs->hmac_ids);
3973 		if (p_len > 0) {
3974 			p_len += sizeof(*hmacs);
3975 			hmacs->ph.param_type = htons(SCTP_HMAC_LIST);
3976 			hmacs->ph.param_length = htons(p_len);
3977 			/* zero out any padding required */
3978 			bzero((caddr_t)hmacs + p_len, SCTP_SIZE32(p_len) - p_len);
3979 			SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
3980 		}
3981 		/* add CHUNKS parameter */
3982 		chunks = (struct sctp_auth_chunk_list *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
3983 		p_len = sctp_serialize_auth_chunks(stcb->asoc.local_auth_chunks,
3984 		    chunks->chunk_types);
3985 		if (p_len > 0) {
3986 			p_len += sizeof(*chunks);
3987 			chunks->ph.param_type = htons(SCTP_CHUNK_LIST);
3988 			chunks->ph.param_length = htons(p_len);
3989 			/* zero out any padding required */
3990 			bzero((caddr_t)chunks + p_len, SCTP_SIZE32(p_len) - p_len);
3991 			SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
3992 		}
3993 	}
3994 	m_at = m;
3995 	/* now the addresses */
3996 	{
3997 		struct sctp_scoping scp;
3998 
3999 		/*
4000 		 * To optimize this we could put the scoping stuff into a
4001 		 * structure and remove the individual uint8's from the
4002 		 * assoc structure. Then we could just sifa in the address
4003 		 * within the stcb.. but for now this is a quick hack to get
4004 		 * the address stuff teased apart.
4005 		 */
4006 		scp.ipv4_addr_legal = stcb->asoc.ipv4_addr_legal;
4007 		scp.ipv6_addr_legal = stcb->asoc.ipv6_addr_legal;
4008 		scp.loopback_scope = stcb->asoc.loopback_scope;
4009 		scp.ipv4_local_scope = stcb->asoc.ipv4_local_scope;
4010 		scp.local_scope = stcb->asoc.local_scope;
4011 		scp.site_scope = stcb->asoc.site_scope;
4012 
4013 		m_at = sctp_add_addresses_to_i_ia(inp, &scp, m_at, cnt_inits_to);
4014 	}
4015 
4016 	/* calulate the size and update pkt header and chunk header */
4017 	p_len = 0;
4018 	for (m_at = m; m_at; m_at = SCTP_BUF_NEXT(m_at)) {
4019 		if (SCTP_BUF_NEXT(m_at) == NULL)
4020 			mp_last = m_at;
4021 		p_len += SCTP_BUF_LEN(m_at);
4022 	}
4023 	initm->msg.ch.chunk_length = htons((p_len - sizeof(struct sctphdr)));
4024 	/*
4025 	 * We sifa 0 here to NOT set IP_DF if its IPv4, we ignore the return
4026 	 * here since the timer will drive a retranmission.
4027 	 */
4028 
4029 	/* I don't expect this to execute but we will be safe here */
4030 	padval = p_len % 4;
4031 	if ((padval) && (mp_last)) {
4032 		/*
4033 		 * The compiler worries that mp_last may not be set even
4034 		 * though I think it is impossible :-> however we add
4035 		 * mp_last here just in case.
4036 		 */
4037 		ret = sctp_add_pad_tombuf(mp_last, (4 - padval));
4038 		if (ret) {
4039 			/* Houston we have a problem, no space */
4040 			sctp_m_freem(m);
4041 			return;
4042 		}
4043 		p_len += padval;
4044 	}
4045 	ret = sctp_lowlevel_chunk_output(inp, stcb, net,
4046 	    (struct sockaddr *)&net->ro._l_addr,
4047 	    m, 0, NULL, 0, 0, NULL, 0);
4048 	SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
4049 	sctp_timer_start(SCTP_TIMER_TYPE_INIT, inp, stcb, net);
4050 	(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
4051 }
4052 
4053 struct mbuf *
4054 sctp_arethere_unrecognized_parameters(struct mbuf *in_initpkt,
4055     int param_offset, int *abort_processing, struct sctp_chunkhdr *cp)
4056 {
4057 	/*
4058 	 * Given a mbuf containing an INIT or INIT-ACK with the param_offset
4059 	 * being equal to the beginning of the params i.e. (iphlen +
4060 	 * sizeof(struct sctp_init_msg) parse through the parameters to the
4061 	 * end of the mbuf verifying that all parameters are known.
4062 	 *
4063 	 * For unknown parameters build and return a mbuf with
4064 	 * UNRECOGNIZED_PARAMETER errors. If the flags indicate to stop
4065 	 * processing this chunk stop, and set *abort_processing to 1.
4066 	 *
4067 	 * By having param_offset be pre-set to where parameters begin it is
4068 	 * hoped that this routine may be reused in the future by new
4069 	 * features.
4070 	 */
4071 	struct sctp_paramhdr *phdr, params;
4072 
4073 	struct mbuf *mat, *op_err;
4074 	char tempbuf[SCTP_PARAM_BUFFER_SIZE];
4075 	int at, limit, pad_needed;
4076 	uint16_t ptype, plen, padded_size;
4077 	int err_at;
4078 
4079 	*abort_processing = 0;
4080 	mat = in_initpkt;
4081 	err_at = 0;
4082 	limit = ntohs(cp->chunk_length) - sizeof(struct sctp_init_chunk);
4083 	at = param_offset;
4084 	op_err = NULL;
4085 	SCTPDBG(SCTP_DEBUG_OUTPUT1, "Check for unrecognized param's\n");
4086 	phdr = sctp_get_next_param(mat, at, &params, sizeof(params));
4087 	while ((phdr != NULL) && ((size_t)limit >= sizeof(struct sctp_paramhdr))) {
4088 		ptype = ntohs(phdr->param_type);
4089 		plen = ntohs(phdr->param_length);
4090 		if ((plen > limit) || (plen < sizeof(struct sctp_paramhdr))) {
4091 			/* wacked parameter */
4092 			SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error %d\n", plen);
4093 			goto invalid_size;
4094 		}
4095 		limit -= SCTP_SIZE32(plen);
4096 		/*-
4097 		 * All parameters for all chunks that we know/understand are
4098 		 * listed here. We process them other places and make
4099 		 * appropriate stop actions per the upper bits. However this
4100 		 * is the generic routine processor's can call to get back
4101 		 * an operr.. to either incorporate (init-ack) or send.
4102 		 */
4103 		padded_size = SCTP_SIZE32(plen);
4104 		switch (ptype) {
4105 			/* Param's with variable size */
4106 		case SCTP_HEARTBEAT_INFO:
4107 		case SCTP_STATE_COOKIE:
4108 		case SCTP_UNRECOG_PARAM:
4109 		case SCTP_ERROR_CAUSE_IND:
4110 			/* ok skip fwd */
4111 			at += padded_size;
4112 			break;
4113 			/* Param's with variable size within a range */
4114 		case SCTP_CHUNK_LIST:
4115 		case SCTP_SUPPORTED_CHUNK_EXT:
4116 			if (padded_size > (sizeof(struct sctp_supported_chunk_types_param) + (sizeof(uint8_t) * SCTP_MAX_SUPPORTED_EXT))) {
4117 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error chklist %d\n", plen);
4118 				goto invalid_size;
4119 			}
4120 			at += padded_size;
4121 			break;
4122 		case SCTP_SUPPORTED_ADDRTYPE:
4123 			if (padded_size > SCTP_MAX_ADDR_PARAMS_SIZE) {
4124 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error supaddrtype %d\n", plen);
4125 				goto invalid_size;
4126 			}
4127 			at += padded_size;
4128 			break;
4129 		case SCTP_RANDOM:
4130 			if (padded_size > (sizeof(struct sctp_auth_random) + SCTP_RANDOM_MAX_SIZE)) {
4131 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error random %d\n", plen);
4132 				goto invalid_size;
4133 			}
4134 			at += padded_size;
4135 			break;
4136 		case SCTP_SET_PRIM_ADDR:
4137 		case SCTP_DEL_IP_ADDRESS:
4138 		case SCTP_ADD_IP_ADDRESS:
4139 			if ((padded_size != sizeof(struct sctp_asconf_addrv4_param)) &&
4140 			    (padded_size != sizeof(struct sctp_asconf_addr_param))) {
4141 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error setprim %d\n", plen);
4142 				goto invalid_size;
4143 			}
4144 			at += padded_size;
4145 			break;
4146 			/* Param's with a fixed size */
4147 		case SCTP_IPV4_ADDRESS:
4148 			if (padded_size != sizeof(struct sctp_ipv4addr_param)) {
4149 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error ipv4 addr %d\n", plen);
4150 				goto invalid_size;
4151 			}
4152 			at += padded_size;
4153 			break;
4154 		case SCTP_IPV6_ADDRESS:
4155 			if (padded_size != sizeof(struct sctp_ipv6addr_param)) {
4156 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error ipv6 addr %d\n", plen);
4157 				goto invalid_size;
4158 			}
4159 			at += padded_size;
4160 			break;
4161 		case SCTP_COOKIE_PRESERVE:
4162 			if (padded_size != sizeof(struct sctp_cookie_perserve_param)) {
4163 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error cookie-preserve %d\n", plen);
4164 				goto invalid_size;
4165 			}
4166 			at += padded_size;
4167 			break;
4168 		case SCTP_ECN_NONCE_SUPPORTED:
4169 		case SCTP_PRSCTP_SUPPORTED:
4170 			if (padded_size != sizeof(struct sctp_paramhdr)) {
4171 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error ecnnonce/prsctp %d\n", plen);
4172 				goto invalid_size;
4173 			}
4174 			at += padded_size;
4175 			break;
4176 		case SCTP_ECN_CAPABLE:
4177 			if (padded_size != sizeof(struct sctp_ecn_supported_param)) {
4178 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error ecn %d\n", plen);
4179 				goto invalid_size;
4180 			}
4181 			at += padded_size;
4182 			break;
4183 		case SCTP_ULP_ADAPTATION:
4184 			if (padded_size != sizeof(struct sctp_adaptation_layer_indication)) {
4185 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error adapatation %d\n", plen);
4186 				goto invalid_size;
4187 			}
4188 			at += padded_size;
4189 			break;
4190 		case SCTP_SUCCESS_REPORT:
4191 			if (padded_size != sizeof(struct sctp_asconf_paramhdr)) {
4192 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error success %d\n", plen);
4193 				goto invalid_size;
4194 			}
4195 			at += padded_size;
4196 			break;
4197 		case SCTP_HOSTNAME_ADDRESS:
4198 			{
4199 				/* We can NOT handle HOST NAME addresses!! */
4200 				int l_len;
4201 
4202 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Can't handle hostname addresses.. abort processing\n");
4203 				*abort_processing = 1;
4204 				if (op_err == NULL) {
4205 					/* Ok need to try to get a mbuf */
4206 					l_len = sizeof(struct ip6_hdr) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
4207 					l_len += plen;
4208 					l_len += sizeof(struct sctp_paramhdr);
4209 					op_err = sctp_get_mbuf_for_msg(l_len, 0, M_DONTWAIT, 1, MT_DATA);
4210 					if (op_err) {
4211 						SCTP_BUF_LEN(op_err) = 0;
4212 						/*
4213 						 * pre-reserve space for ip
4214 						 * and sctp header  and
4215 						 * chunk hdr
4216 						 */
4217 						SCTP_BUF_RESV_UF(op_err, sizeof(struct ip6_hdr));
4218 						SCTP_BUF_RESV_UF(op_err, sizeof(struct sctphdr));
4219 						SCTP_BUF_RESV_UF(op_err, sizeof(struct sctp_chunkhdr));
4220 					}
4221 				}
4222 				if (op_err) {
4223 					/* If we have space */
4224 					struct sctp_paramhdr s;
4225 
4226 					if (err_at % 4) {
4227 						uint32_t cpthis = 0;
4228 
4229 						pad_needed = 4 - (err_at % 4);
4230 						m_copyback(op_err, err_at, pad_needed, (caddr_t)&cpthis);
4231 						err_at += pad_needed;
4232 					}
4233 					s.param_type = htons(SCTP_CAUSE_UNRESOLVABLE_ADDR);
4234 					s.param_length = htons(sizeof(s) + plen);
4235 					m_copyback(op_err, err_at, sizeof(s), (caddr_t)&s);
4236 					err_at += sizeof(s);
4237 					phdr = sctp_get_next_param(mat, at, (struct sctp_paramhdr *)tempbuf, min(sizeof(tempbuf), plen));
4238 					if (phdr == NULL) {
4239 						sctp_m_freem(op_err);
4240 						/*
4241 						 * we are out of memory but
4242 						 * we still need to have a
4243 						 * look at what to do (the
4244 						 * system is in trouble
4245 						 * though).
4246 						 */
4247 						return (NULL);
4248 					}
4249 					m_copyback(op_err, err_at, plen, (caddr_t)phdr);
4250 					err_at += plen;
4251 				}
4252 				return (op_err);
4253 				break;
4254 			}
4255 		default:
4256 			/*
4257 			 * we do not recognize the parameter figure out what
4258 			 * we do.
4259 			 */
4260 			SCTPDBG(SCTP_DEBUG_OUTPUT1, "Hit default param %x\n", ptype);
4261 			if ((ptype & 0x4000) == 0x4000) {
4262 				/* Report bit is set?? */
4263 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "report op err\n");
4264 				if (op_err == NULL) {
4265 					int l_len;
4266 
4267 					/* Ok need to try to get an mbuf */
4268 					l_len = sizeof(struct ip6_hdr) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
4269 					l_len += plen;
4270 					l_len += sizeof(struct sctp_paramhdr);
4271 					op_err = sctp_get_mbuf_for_msg(l_len, 0, M_DONTWAIT, 1, MT_DATA);
4272 					if (op_err) {
4273 						SCTP_BUF_LEN(op_err) = 0;
4274 						SCTP_BUF_RESV_UF(op_err, sizeof(struct ip6_hdr));
4275 						SCTP_BUF_RESV_UF(op_err, sizeof(struct sctphdr));
4276 						SCTP_BUF_RESV_UF(op_err, sizeof(struct sctp_chunkhdr));
4277 					}
4278 				}
4279 				if (op_err) {
4280 					/* If we have space */
4281 					struct sctp_paramhdr s;
4282 
4283 					if (err_at % 4) {
4284 						uint32_t cpthis = 0;
4285 
4286 						pad_needed = 4 - (err_at % 4);
4287 						m_copyback(op_err, err_at, pad_needed, (caddr_t)&cpthis);
4288 						err_at += pad_needed;
4289 					}
4290 					s.param_type = htons(SCTP_UNRECOG_PARAM);
4291 					s.param_length = htons(sizeof(s) + plen);
4292 					m_copyback(op_err, err_at, sizeof(s), (caddr_t)&s);
4293 					err_at += sizeof(s);
4294 					if (plen > sizeof(tempbuf)) {
4295 						plen = sizeof(tempbuf);
4296 					}
4297 					phdr = sctp_get_next_param(mat, at, (struct sctp_paramhdr *)tempbuf, min(sizeof(tempbuf), plen));
4298 					if (phdr == NULL) {
4299 						sctp_m_freem(op_err);
4300 						/*
4301 						 * we are out of memory but
4302 						 * we still need to have a
4303 						 * look at what to do (the
4304 						 * system is in trouble
4305 						 * though).
4306 						 */
4307 						op_err = NULL;
4308 						goto more_processing;
4309 					}
4310 					m_copyback(op_err, err_at, plen, (caddr_t)phdr);
4311 					err_at += plen;
4312 				}
4313 			}
4314 	more_processing:
4315 			if ((ptype & 0x8000) == 0x0000) {
4316 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "stop proc\n");
4317 				return (op_err);
4318 			} else {
4319 				/* skip this chunk and continue processing */
4320 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "move on\n");
4321 				at += SCTP_SIZE32(plen);
4322 			}
4323 			break;
4324 
4325 		}
4326 		phdr = sctp_get_next_param(mat, at, &params, sizeof(params));
4327 	}
4328 	return (op_err);
4329 invalid_size:
4330 	SCTPDBG(SCTP_DEBUG_OUTPUT1, "abort flag set\n");
4331 	*abort_processing = 1;
4332 	if ((op_err == NULL) && phdr) {
4333 		int l_len;
4334 
4335 		l_len = sizeof(struct ip6_hdr) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
4336 		l_len += (2 * sizeof(struct sctp_paramhdr));
4337 		op_err = sctp_get_mbuf_for_msg(l_len, 0, M_DONTWAIT, 1, MT_DATA);
4338 		if (op_err) {
4339 			SCTP_BUF_LEN(op_err) = 0;
4340 			SCTP_BUF_RESV_UF(op_err, sizeof(struct ip6_hdr));
4341 			SCTP_BUF_RESV_UF(op_err, sizeof(struct sctphdr));
4342 			SCTP_BUF_RESV_UF(op_err, sizeof(struct sctp_chunkhdr));
4343 		}
4344 	}
4345 	if ((op_err) && phdr) {
4346 		struct sctp_paramhdr s;
4347 
4348 		if (err_at % 4) {
4349 			uint32_t cpthis = 0;
4350 
4351 			pad_needed = 4 - (err_at % 4);
4352 			m_copyback(op_err, err_at, pad_needed, (caddr_t)&cpthis);
4353 			err_at += pad_needed;
4354 		}
4355 		s.param_type = htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
4356 		s.param_length = htons(sizeof(s) + sizeof(struct sctp_paramhdr));
4357 		m_copyback(op_err, err_at, sizeof(s), (caddr_t)&s);
4358 		err_at += sizeof(s);
4359 		/* Only copy back the p-hdr that caused the issue */
4360 		m_copyback(op_err, err_at, sizeof(struct sctp_paramhdr), (caddr_t)phdr);
4361 	}
4362 	return (op_err);
4363 }
4364 
4365 static int
4366 sctp_are_there_new_addresses(struct sctp_association *asoc,
4367     struct mbuf *in_initpkt, int iphlen, int offset)
4368 {
4369 	/*
4370 	 * Given a INIT packet, look through the packet to verify that there
4371 	 * are NO new addresses. As we go through the parameters add reports
4372 	 * of any un-understood parameters that require an error.  Also we
4373 	 * must return (1) to drop the packet if we see a un-understood
4374 	 * parameter that tells us to drop the chunk.
4375 	 */
4376 	struct sockaddr_in sin4, *sa4;
4377 	struct sockaddr_in6 sin6, *sa6;
4378 	struct sockaddr *sa_touse;
4379 	struct sockaddr *sa;
4380 	struct sctp_paramhdr *phdr, params;
4381 	struct ip *iph;
4382 	struct mbuf *mat;
4383 	uint16_t ptype, plen;
4384 	int err_at;
4385 	uint8_t fnd;
4386 	struct sctp_nets *net;
4387 
4388 	memset(&sin4, 0, sizeof(sin4));
4389 	memset(&sin6, 0, sizeof(sin6));
4390 	sin4.sin_family = AF_INET;
4391 	sin4.sin_len = sizeof(sin4);
4392 	sin6.sin6_family = AF_INET6;
4393 	sin6.sin6_len = sizeof(sin6);
4394 
4395 	sa_touse = NULL;
4396 	/* First what about the src address of the pkt ? */
4397 	iph = mtod(in_initpkt, struct ip *);
4398 	if (iph->ip_v == IPVERSION) {
4399 		/* source addr is IPv4 */
4400 		sin4.sin_addr = iph->ip_src;
4401 		sa_touse = (struct sockaddr *)&sin4;
4402 	} else if (iph->ip_v == (IPV6_VERSION >> 4)) {
4403 		/* source addr is IPv6 */
4404 		struct ip6_hdr *ip6h;
4405 
4406 		ip6h = mtod(in_initpkt, struct ip6_hdr *);
4407 		sin6.sin6_addr = ip6h->ip6_src;
4408 		sa_touse = (struct sockaddr *)&sin6;
4409 	} else {
4410 		return (1);
4411 	}
4412 
4413 	fnd = 0;
4414 	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
4415 		sa = (struct sockaddr *)&net->ro._l_addr;
4416 		if (sa->sa_family == sa_touse->sa_family) {
4417 			if (sa->sa_family == AF_INET) {
4418 				sa4 = (struct sockaddr_in *)sa;
4419 				if (sa4->sin_addr.s_addr ==
4420 				    sin4.sin_addr.s_addr) {
4421 					fnd = 1;
4422 					break;
4423 				}
4424 			} else if (sa->sa_family == AF_INET6) {
4425 				sa6 = (struct sockaddr_in6 *)sa;
4426 				if (SCTP6_ARE_ADDR_EQUAL(&sa6->sin6_addr,
4427 				    &sin6.sin6_addr)) {
4428 					fnd = 1;
4429 					break;
4430 				}
4431 			}
4432 		}
4433 	}
4434 	if (fnd == 0) {
4435 		/* New address added! no need to look futher. */
4436 		return (1);
4437 	}
4438 	/* Ok so far lets munge through the rest of the packet */
4439 	mat = in_initpkt;
4440 	err_at = 0;
4441 	sa_touse = NULL;
4442 	offset += sizeof(struct sctp_init_chunk);
4443 	phdr = sctp_get_next_param(mat, offset, &params, sizeof(params));
4444 	while (phdr) {
4445 		ptype = ntohs(phdr->param_type);
4446 		plen = ntohs(phdr->param_length);
4447 		if (ptype == SCTP_IPV4_ADDRESS) {
4448 			struct sctp_ipv4addr_param *p4, p4_buf;
4449 
4450 			phdr = sctp_get_next_param(mat, offset,
4451 			    (struct sctp_paramhdr *)&p4_buf, sizeof(p4_buf));
4452 			if (plen != sizeof(struct sctp_ipv4addr_param) ||
4453 			    phdr == NULL) {
4454 				return (1);
4455 			}
4456 			p4 = (struct sctp_ipv4addr_param *)phdr;
4457 			sin4.sin_addr.s_addr = p4->addr;
4458 			sa_touse = (struct sockaddr *)&sin4;
4459 		} else if (ptype == SCTP_IPV6_ADDRESS) {
4460 			struct sctp_ipv6addr_param *p6, p6_buf;
4461 
4462 			phdr = sctp_get_next_param(mat, offset,
4463 			    (struct sctp_paramhdr *)&p6_buf, sizeof(p6_buf));
4464 			if (plen != sizeof(struct sctp_ipv6addr_param) ||
4465 			    phdr == NULL) {
4466 				return (1);
4467 			}
4468 			p6 = (struct sctp_ipv6addr_param *)phdr;
4469 			memcpy((caddr_t)&sin6.sin6_addr, p6->addr,
4470 			    sizeof(p6->addr));
4471 			sa_touse = (struct sockaddr *)&sin4;
4472 		}
4473 		if (sa_touse) {
4474 			/* ok, sa_touse points to one to check */
4475 			fnd = 0;
4476 			TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
4477 				sa = (struct sockaddr *)&net->ro._l_addr;
4478 				if (sa->sa_family != sa_touse->sa_family) {
4479 					continue;
4480 				}
4481 				if (sa->sa_family == AF_INET) {
4482 					sa4 = (struct sockaddr_in *)sa;
4483 					if (sa4->sin_addr.s_addr ==
4484 					    sin4.sin_addr.s_addr) {
4485 						fnd = 1;
4486 						break;
4487 					}
4488 				} else if (sa->sa_family == AF_INET6) {
4489 					sa6 = (struct sockaddr_in6 *)sa;
4490 					if (SCTP6_ARE_ADDR_EQUAL(
4491 					    &sa6->sin6_addr, &sin6.sin6_addr)) {
4492 						fnd = 1;
4493 						break;
4494 					}
4495 				}
4496 			}
4497 			if (!fnd) {
4498 				/* New addr added! no need to look further */
4499 				return (1);
4500 			}
4501 		}
4502 		offset += SCTP_SIZE32(plen);
4503 		phdr = sctp_get_next_param(mat, offset, &params, sizeof(params));
4504 	}
4505 	return (0);
4506 }
4507 
4508 /*
4509  * Given a MBUF chain that was sent into us containing an INIT. Build a
4510  * INIT-ACK with COOKIE and send back. We assume that the in_initpkt has done
4511  * a pullup to include IPv6/4header, SCTP header and initial part of INIT
4512  * message (i.e. the struct sctp_init_msg).
4513  */
4514 void
4515 sctp_send_initiate_ack(struct sctp_inpcb *inp, struct sctp_tcb *stcb,
4516     struct mbuf *init_pkt, int iphlen, int offset, struct sctphdr *sh,
4517     struct sctp_init_chunk *init_chk, uint32_t vrf_id)
4518 {
4519 	struct sctp_association *asoc;
4520 	struct mbuf *m, *m_at, *m_tmp, *m_cookie, *op_err, *mp_last;
4521 	struct sctp_init_msg *initackm_out;
4522 	struct sctp_ecn_supported_param *ecn;
4523 	struct sctp_prsctp_supported_param *prsctp;
4524 	struct sctp_ecn_nonce_supported_param *ecn_nonce;
4525 	struct sctp_supported_chunk_types_param *pr_supported;
4526 	struct sockaddr_storage store;
4527 	struct sockaddr_in *sin;
4528 	struct sockaddr_in6 *sin6;
4529 	sctp_route_t *ro;
4530 	struct ip *iph;
4531 	struct ip6_hdr *ip6;
4532 	struct sockaddr *to;
4533 	struct sctp_state_cookie stc;
4534 	struct sctp_nets *net = NULL;
4535 	uint8_t *signature = NULL;
4536 	int cnt_inits_to = 0;
4537 	uint16_t his_limit, i_want;
4538 	int abort_flag, padval;
4539 	int num_ext;
4540 	int p_len;
4541 
4542 	if (stcb)
4543 		asoc = &stcb->asoc;
4544 	else
4545 		asoc = NULL;
4546 	mp_last = NULL;
4547 	if ((asoc != NULL) &&
4548 	    (SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_WAIT) &&
4549 	    (sctp_are_there_new_addresses(asoc, init_pkt, iphlen, offset))) {
4550 		/* new addresses, out of here in non-cookie-wait states */
4551 		/*
4552 		 * Send a ABORT, we don't add the new address error clause
4553 		 * though we even set the T bit and copy in the 0 tag.. this
4554 		 * looks no different than if no listener was present.
4555 		 */
4556 		sctp_send_abort(init_pkt, iphlen, sh, 0, NULL, vrf_id);
4557 		return;
4558 	}
4559 	abort_flag = 0;
4560 	op_err = sctp_arethere_unrecognized_parameters(init_pkt,
4561 	    (offset + sizeof(struct sctp_init_chunk)),
4562 	    &abort_flag, (struct sctp_chunkhdr *)init_chk);
4563 	if (abort_flag) {
4564 		sctp_send_abort(init_pkt, iphlen, sh,
4565 		    init_chk->init.initiate_tag, op_err, vrf_id);
4566 		return;
4567 	}
4568 	m = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_DATA);
4569 	if (m == NULL) {
4570 		/* No memory, INIT timer will re-attempt. */
4571 		if (op_err)
4572 			sctp_m_freem(op_err);
4573 		return;
4574 	}
4575 	SCTP_BUF_LEN(m) = sizeof(struct sctp_init_msg);
4576 
4577 	/* the time I built cookie */
4578 	(void)SCTP_GETTIME_TIMEVAL(&stc.time_entered);
4579 
4580 	/* populate any tie tags */
4581 	if (asoc != NULL) {
4582 		/* unlock before tag selections */
4583 		stc.tie_tag_my_vtag = asoc->my_vtag_nonce;
4584 		stc.tie_tag_peer_vtag = asoc->peer_vtag_nonce;
4585 		stc.cookie_life = asoc->cookie_life;
4586 		net = asoc->primary_destination;
4587 	} else {
4588 		stc.tie_tag_my_vtag = 0;
4589 		stc.tie_tag_peer_vtag = 0;
4590 		/* life I will award this cookie */
4591 		stc.cookie_life = inp->sctp_ep.def_cookie_life;
4592 	}
4593 
4594 	/* copy in the ports for later check */
4595 	stc.myport = sh->dest_port;
4596 	stc.peerport = sh->src_port;
4597 
4598 	/*
4599 	 * If we wanted to honor cookie life extentions, we would add to
4600 	 * stc.cookie_life. For now we should NOT honor any extension
4601 	 */
4602 	stc.site_scope = stc.local_scope = stc.loopback_scope = 0;
4603 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
4604 		struct inpcb *in_inp;
4605 
4606 		/* Its a V6 socket */
4607 		in_inp = (struct inpcb *)inp;
4608 		stc.ipv6_addr_legal = 1;
4609 		/* Now look at the binding flag to see if V4 will be legal */
4610 		if (SCTP_IPV6_V6ONLY(in_inp) == 0) {
4611 			stc.ipv4_addr_legal = 1;
4612 		} else {
4613 			/* V4 addresses are NOT legal on the association */
4614 			stc.ipv4_addr_legal = 0;
4615 		}
4616 	} else {
4617 		/* Its a V4 socket, no - V6 */
4618 		stc.ipv4_addr_legal = 1;
4619 		stc.ipv6_addr_legal = 0;
4620 	}
4621 
4622 #ifdef SCTP_DONT_DO_PRIVADDR_SCOPE
4623 	stc.ipv4_scope = 1;
4624 #else
4625 	stc.ipv4_scope = 0;
4626 #endif
4627 	/* now for scope setup */
4628 	memset((caddr_t)&store, 0, sizeof(store));
4629 	sin = (struct sockaddr_in *)&store;
4630 	sin6 = (struct sockaddr_in6 *)&store;
4631 	if (net == NULL) {
4632 		to = (struct sockaddr *)&store;
4633 		iph = mtod(init_pkt, struct ip *);
4634 		if (iph->ip_v == IPVERSION) {
4635 			struct sctp_ifa *addr;
4636 			sctp_route_t iproute;
4637 
4638 			sin->sin_family = AF_INET;
4639 			sin->sin_len = sizeof(struct sockaddr_in);
4640 			sin->sin_port = sh->src_port;
4641 			sin->sin_addr = iph->ip_src;
4642 			/* lookup address */
4643 			stc.address[0] = sin->sin_addr.s_addr;
4644 			stc.address[1] = 0;
4645 			stc.address[2] = 0;
4646 			stc.address[3] = 0;
4647 			stc.addr_type = SCTP_IPV4_ADDRESS;
4648 			/* local from address */
4649 			memset(&iproute, 0, sizeof(iproute));
4650 			ro = &iproute;
4651 			memcpy(&ro->ro_dst, sin, sizeof(*sin));
4652 			addr = sctp_source_address_selection(inp, NULL,
4653 			    ro, NULL, 0,
4654 			    vrf_id);
4655 			if (addr == NULL)
4656 				return;
4657 
4658 			if (ro->ro_rt) {
4659 				RTFREE(ro->ro_rt);
4660 				ro->ro_rt = NULL;
4661 			}
4662 			stc.laddress[0] = addr->address.sin.sin_addr.s_addr;
4663 			stc.laddress[1] = 0;
4664 			stc.laddress[2] = 0;
4665 			stc.laddress[3] = 0;
4666 			stc.laddr_type = SCTP_IPV4_ADDRESS;
4667 			/* scope_id is only for v6 */
4668 			stc.scope_id = 0;
4669 #ifndef SCTP_DONT_DO_PRIVADDR_SCOPE
4670 			if (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) {
4671 				stc.ipv4_scope = 1;
4672 			}
4673 #else
4674 			stc.ipv4_scope = 1;
4675 #endif				/* SCTP_DONT_DO_PRIVADDR_SCOPE */
4676 			/* Must use the address in this case */
4677 			if (sctp_is_address_on_local_host((struct sockaddr *)sin, vrf_id)) {
4678 				stc.loopback_scope = 1;
4679 				stc.ipv4_scope = 1;
4680 				stc.site_scope = 1;
4681 				stc.local_scope = 0;
4682 			}
4683 			sctp_free_ifa(addr);
4684 		} else if (iph->ip_v == (IPV6_VERSION >> 4)) {
4685 			struct sctp_ifa *addr;
4686 			struct route_in6 iproute6;
4687 
4688 			ip6 = mtod(init_pkt, struct ip6_hdr *);
4689 			sin6->sin6_family = AF_INET6;
4690 			sin6->sin6_len = sizeof(struct sockaddr_in6);
4691 			sin6->sin6_port = sh->src_port;
4692 			sin6->sin6_addr = ip6->ip6_src;
4693 			/* lookup address */
4694 			memcpy(&stc.address, &sin6->sin6_addr,
4695 			    sizeof(struct in6_addr));
4696 			sin6->sin6_scope_id = 0;
4697 			stc.addr_type = SCTP_IPV6_ADDRESS;
4698 			stc.scope_id = 0;
4699 			if (sctp_is_address_on_local_host((struct sockaddr *)sin6, vrf_id)) {
4700 				stc.loopback_scope = 1;
4701 				stc.local_scope = 0;
4702 				stc.site_scope = 1;
4703 				stc.ipv4_scope = 1;
4704 			} else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
4705 				/*
4706 				 * If the new destination is a LINK_LOCAL we
4707 				 * must have common both site and local
4708 				 * scope. Don't set local scope though since
4709 				 * we must depend on the source to be added
4710 				 * implicitly. We cannot assure just because
4711 				 * we share one link that all links are
4712 				 * common.
4713 				 */
4714 				stc.local_scope = 0;
4715 				stc.site_scope = 1;
4716 				stc.ipv4_scope = 1;
4717 				/*
4718 				 * we start counting for the private address
4719 				 * stuff at 1. since the link local we
4720 				 * source from won't show up in our scoped
4721 				 * count.
4722 				 */
4723 				cnt_inits_to = 1;
4724 				/* pull out the scope_id from incoming pkt */
4725 				/* FIX ME: does this have scope from rcvif? */
4726 				(void)sa6_recoverscope(sin6);
4727 
4728 				sa6_embedscope(sin6, ip6_use_defzone);
4729 				stc.scope_id = sin6->sin6_scope_id;
4730 			} else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr)) {
4731 				/*
4732 				 * If the new destination is SITE_LOCAL then
4733 				 * we must have site scope in common.
4734 				 */
4735 				stc.site_scope = 1;
4736 			}
4737 			/* local from address */
4738 			memset(&iproute6, 0, sizeof(iproute6));
4739 			ro = (sctp_route_t *) & iproute6;
4740 			memcpy(&ro->ro_dst, sin6, sizeof(*sin6));
4741 			addr = sctp_source_address_selection(inp, NULL,
4742 			    ro, NULL, 0, vrf_id);
4743 			if (addr == NULL)
4744 				return;
4745 
4746 			if (ro->ro_rt) {
4747 				RTFREE(ro->ro_rt);
4748 				ro->ro_rt = NULL;
4749 			}
4750 			memcpy(&stc.laddress, &addr->address.sin6.sin6_addr, sizeof(struct in6_addr));
4751 			stc.laddr_type = SCTP_IPV6_ADDRESS;
4752 			sctp_free_ifa(addr);
4753 		}
4754 	} else {
4755 		/* set the scope per the existing tcb */
4756 		struct sctp_nets *lnet;
4757 
4758 		stc.loopback_scope = asoc->loopback_scope;
4759 		stc.ipv4_scope = asoc->ipv4_local_scope;
4760 		stc.site_scope = asoc->site_scope;
4761 		stc.local_scope = asoc->local_scope;
4762 		TAILQ_FOREACH(lnet, &asoc->nets, sctp_next) {
4763 			if (lnet->ro._l_addr.sin6.sin6_family == AF_INET6) {
4764 				if (IN6_IS_ADDR_LINKLOCAL(&lnet->ro._l_addr.sin6.sin6_addr)) {
4765 					/*
4766 					 * if we have a LL address, start
4767 					 * counting at 1.
4768 					 */
4769 					cnt_inits_to = 1;
4770 				}
4771 			}
4772 		}
4773 
4774 		/* use the net pointer */
4775 		to = (struct sockaddr *)&net->ro._l_addr;
4776 		if (to->sa_family == AF_INET) {
4777 			sin = (struct sockaddr_in *)to;
4778 			stc.address[0] = sin->sin_addr.s_addr;
4779 			stc.address[1] = 0;
4780 			stc.address[2] = 0;
4781 			stc.address[3] = 0;
4782 			stc.addr_type = SCTP_IPV4_ADDRESS;
4783 			if (net->src_addr_selected == 0) {
4784 				/*
4785 				 * strange case here, the INIT should have
4786 				 * did the selection.
4787 				 */
4788 				net->ro._s_addr = sctp_source_address_selection(inp,
4789 				    stcb, (sctp_route_t *) & net->ro,
4790 				    net, 0, vrf_id);
4791 				if (net->ro._s_addr == NULL)
4792 					return;
4793 
4794 				net->src_addr_selected = 1;
4795 
4796 			}
4797 			stc.laddress[0] = net->ro._s_addr->address.sin.sin_addr.s_addr;
4798 			stc.laddress[1] = 0;
4799 			stc.laddress[2] = 0;
4800 			stc.laddress[3] = 0;
4801 			stc.laddr_type = SCTP_IPV4_ADDRESS;
4802 		} else if (to->sa_family == AF_INET6) {
4803 			sin6 = (struct sockaddr_in6 *)to;
4804 			memcpy(&stc.address, &sin6->sin6_addr,
4805 			    sizeof(struct in6_addr));
4806 			stc.addr_type = SCTP_IPV6_ADDRESS;
4807 			if (net->src_addr_selected == 0) {
4808 				/*
4809 				 * strange case here, the INIT should have
4810 				 * did the selection.
4811 				 */
4812 				net->ro._s_addr = sctp_source_address_selection(inp,
4813 				    stcb, (sctp_route_t *) & net->ro,
4814 				    net, 0, vrf_id);
4815 				if (net->ro._s_addr == NULL)
4816 					return;
4817 
4818 				net->src_addr_selected = 1;
4819 			}
4820 			memcpy(&stc.laddress, &net->ro._s_addr->address.sin6.sin6_addr,
4821 			    sizeof(struct in6_addr));
4822 			stc.laddr_type = SCTP_IPV6_ADDRESS;
4823 		}
4824 	}
4825 	/* Now lets put the SCTP header in place */
4826 	initackm_out = mtod(m, struct sctp_init_msg *);
4827 	initackm_out->sh.src_port = inp->sctp_lport;
4828 	initackm_out->sh.dest_port = sh->src_port;
4829 	initackm_out->sh.v_tag = init_chk->init.initiate_tag;
4830 	/* Save it off for quick ref */
4831 	stc.peers_vtag = init_chk->init.initiate_tag;
4832 	initackm_out->sh.checksum = 0;	/* calculate later */
4833 	/* who are we */
4834 	memcpy(stc.identification, SCTP_VERSION_STRING,
4835 	    min(strlen(SCTP_VERSION_STRING), sizeof(stc.identification)));
4836 	/* now the chunk header */
4837 	initackm_out->msg.ch.chunk_type = SCTP_INITIATION_ACK;
4838 	initackm_out->msg.ch.chunk_flags = 0;
4839 	/* fill in later from mbuf we build */
4840 	initackm_out->msg.ch.chunk_length = 0;
4841 	/* place in my tag */
4842 	if ((asoc != NULL) &&
4843 	    ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
4844 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_INUSE) ||
4845 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED))) {
4846 		/* re-use the v-tags and init-seq here */
4847 		initackm_out->msg.init.initiate_tag = htonl(asoc->my_vtag);
4848 		initackm_out->msg.init.initial_tsn = htonl(asoc->init_seq_number);
4849 	} else {
4850 		uint32_t vtag;
4851 
4852 		if (asoc) {
4853 			atomic_add_int(&asoc->refcnt, 1);
4854 			SCTP_TCB_UNLOCK(stcb);
4855 			vtag = sctp_select_a_tag(inp);
4856 			initackm_out->msg.init.initiate_tag = htonl(vtag);
4857 			/* get a TSN to use too */
4858 			initackm_out->msg.init.initial_tsn = htonl(sctp_select_initial_TSN(&inp->sctp_ep));
4859 			SCTP_TCB_LOCK(stcb);
4860 			atomic_add_int(&asoc->refcnt, -1);
4861 		} else {
4862 			vtag = sctp_select_a_tag(inp);
4863 			initackm_out->msg.init.initiate_tag = htonl(vtag);
4864 			/* get a TSN to use too */
4865 			initackm_out->msg.init.initial_tsn = htonl(sctp_select_initial_TSN(&inp->sctp_ep));
4866 		}
4867 	}
4868 	/* save away my tag to */
4869 	stc.my_vtag = initackm_out->msg.init.initiate_tag;
4870 
4871 	/* set up some of the credits. */
4872 	initackm_out->msg.init.a_rwnd = htonl(max(SCTP_SB_LIMIT_RCV(inp->sctp_socket), SCTP_MINIMAL_RWND));
4873 	/* set what I want */
4874 	his_limit = ntohs(init_chk->init.num_inbound_streams);
4875 	/* choose what I want */
4876 	if (asoc != NULL) {
4877 		if (asoc->streamoutcnt > inp->sctp_ep.pre_open_stream_count) {
4878 			i_want = asoc->streamoutcnt;
4879 		} else {
4880 			i_want = inp->sctp_ep.pre_open_stream_count;
4881 		}
4882 	} else {
4883 		i_want = inp->sctp_ep.pre_open_stream_count;
4884 	}
4885 	if (his_limit < i_want) {
4886 		/* I Want more :< */
4887 		initackm_out->msg.init.num_outbound_streams = init_chk->init.num_inbound_streams;
4888 	} else {
4889 		/* I can have what I want :> */
4890 		initackm_out->msg.init.num_outbound_streams = htons(i_want);
4891 	}
4892 	/* tell him his limt. */
4893 	initackm_out->msg.init.num_inbound_streams =
4894 	    htons(inp->sctp_ep.max_open_streams_intome);
4895 	/* setup the ECN pointer */
4896 
4897 	if (inp->sctp_ep.adaptation_layer_indicator) {
4898 		struct sctp_adaptation_layer_indication *ali;
4899 
4900 		ali = (struct sctp_adaptation_layer_indication *)(
4901 		    (caddr_t)initackm_out + sizeof(*initackm_out));
4902 		ali->ph.param_type = htons(SCTP_ULP_ADAPTATION);
4903 		ali->ph.param_length = htons(sizeof(*ali));
4904 		ali->indication = ntohl(inp->sctp_ep.adaptation_layer_indicator);
4905 		SCTP_BUF_LEN(m) += sizeof(*ali);
4906 		ecn = (struct sctp_ecn_supported_param *)((caddr_t)ali +
4907 		    sizeof(*ali));
4908 	} else {
4909 		ecn = (struct sctp_ecn_supported_param *)(
4910 		    (caddr_t)initackm_out + sizeof(*initackm_out));
4911 	}
4912 
4913 	/* ECN parameter */
4914 	if (sctp_ecn_enable == 1) {
4915 		ecn->ph.param_type = htons(SCTP_ECN_CAPABLE);
4916 		ecn->ph.param_length = htons(sizeof(*ecn));
4917 		SCTP_BUF_LEN(m) += sizeof(*ecn);
4918 
4919 		prsctp = (struct sctp_prsctp_supported_param *)((caddr_t)ecn +
4920 		    sizeof(*ecn));
4921 	} else {
4922 		prsctp = (struct sctp_prsctp_supported_param *)((caddr_t)ecn);
4923 	}
4924 	/* And now tell the peer we do  pr-sctp */
4925 	prsctp->ph.param_type = htons(SCTP_PRSCTP_SUPPORTED);
4926 	prsctp->ph.param_length = htons(sizeof(*prsctp));
4927 	SCTP_BUF_LEN(m) += sizeof(*prsctp);
4928 
4929 	/* And now tell the peer we do all the extensions */
4930 	pr_supported = (struct sctp_supported_chunk_types_param *)
4931 	    ((caddr_t)prsctp + sizeof(*prsctp));
4932 
4933 	pr_supported->ph.param_type = htons(SCTP_SUPPORTED_CHUNK_EXT);
4934 	num_ext = 0;
4935 	pr_supported->chunk_types[num_ext++] = SCTP_ASCONF;
4936 	pr_supported->chunk_types[num_ext++] = SCTP_ASCONF_ACK;
4937 	pr_supported->chunk_types[num_ext++] = SCTP_FORWARD_CUM_TSN;
4938 	pr_supported->chunk_types[num_ext++] = SCTP_PACKET_DROPPED;
4939 	pr_supported->chunk_types[num_ext++] = SCTP_STREAM_RESET;
4940 	if (!sctp_auth_disable)
4941 		pr_supported->chunk_types[num_ext++] = SCTP_AUTHENTICATION;
4942 	p_len = sizeof(*pr_supported) + num_ext;
4943 	pr_supported->ph.param_length = htons(p_len);
4944 	bzero((caddr_t)pr_supported + p_len, SCTP_SIZE32(p_len) - p_len);
4945 	SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
4946 
4947 	/* ECN nonce: And now tell the peer we support ECN nonce */
4948 	if (sctp_ecn_nonce) {
4949 		ecn_nonce = (struct sctp_ecn_nonce_supported_param *)
4950 		    ((caddr_t)pr_supported + SCTP_SIZE32(p_len));
4951 		ecn_nonce->ph.param_type = htons(SCTP_ECN_NONCE_SUPPORTED);
4952 		ecn_nonce->ph.param_length = htons(sizeof(*ecn_nonce));
4953 		SCTP_BUF_LEN(m) += sizeof(*ecn_nonce);
4954 	}
4955 	/* add authentication parameters */
4956 	if (!sctp_auth_disable) {
4957 		struct sctp_auth_random *randp;
4958 		struct sctp_auth_hmac_algo *hmacs;
4959 		struct sctp_auth_chunk_list *chunks;
4960 		uint16_t random_len;
4961 
4962 		/* generate and add RANDOM parameter */
4963 		random_len = SCTP_AUTH_RANDOM_SIZE_DEFAULT;
4964 		randp = (struct sctp_auth_random *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
4965 		randp->ph.param_type = htons(SCTP_RANDOM);
4966 		p_len = sizeof(*randp) + random_len;
4967 		randp->ph.param_length = htons(p_len);
4968 		SCTP_READ_RANDOM(randp->random_data, random_len);
4969 		/* zero out any padding required */
4970 		bzero((caddr_t)randp + p_len, SCTP_SIZE32(p_len) - p_len);
4971 		SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
4972 
4973 		/* add HMAC_ALGO parameter */
4974 		hmacs = (struct sctp_auth_hmac_algo *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
4975 		p_len = sctp_serialize_hmaclist(inp->sctp_ep.local_hmacs,
4976 		    (uint8_t *) hmacs->hmac_ids);
4977 		if (p_len > 0) {
4978 			p_len += sizeof(*hmacs);
4979 			hmacs->ph.param_type = htons(SCTP_HMAC_LIST);
4980 			hmacs->ph.param_length = htons(p_len);
4981 			/* zero out any padding required */
4982 			bzero((caddr_t)hmacs + p_len, SCTP_SIZE32(p_len) - p_len);
4983 			SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
4984 		}
4985 		/* add CHUNKS parameter */
4986 		chunks = (struct sctp_auth_chunk_list *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
4987 		p_len = sctp_serialize_auth_chunks(inp->sctp_ep.local_auth_chunks,
4988 		    chunks->chunk_types);
4989 		if (p_len > 0) {
4990 			p_len += sizeof(*chunks);
4991 			chunks->ph.param_type = htons(SCTP_CHUNK_LIST);
4992 			chunks->ph.param_length = htons(p_len);
4993 			/* zero out any padding required */
4994 			bzero((caddr_t)chunks + p_len, SCTP_SIZE32(p_len) - p_len);
4995 			SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
4996 		}
4997 	}
4998 	m_at = m;
4999 	/* now the addresses */
5000 	{
5001 		struct sctp_scoping scp;
5002 
5003 		/*
5004 		 * To optimize this we could put the scoping stuff into a
5005 		 * structure and remove the individual uint8's from the stc
5006 		 * structure. Then we could just sifa in the address within
5007 		 * the stc.. but for now this is a quick hack to get the
5008 		 * address stuff teased apart.
5009 		 */
5010 		scp.ipv4_addr_legal = stc.ipv4_addr_legal;
5011 		scp.ipv6_addr_legal = stc.ipv6_addr_legal;
5012 		scp.loopback_scope = stc.loopback_scope;
5013 		scp.ipv4_local_scope = stc.ipv4_scope;
5014 		scp.local_scope = stc.local_scope;
5015 		scp.site_scope = stc.site_scope;
5016 		m_at = sctp_add_addresses_to_i_ia(inp, &scp, m_at, cnt_inits_to);
5017 	}
5018 
5019 	/* tack on the operational error if present */
5020 	if (op_err) {
5021 		struct mbuf *ol;
5022 		int llen;
5023 
5024 		llen = 0;
5025 		ol = op_err;
5026 		while (ol) {
5027 			llen += SCTP_BUF_LEN(ol);
5028 			ol = SCTP_BUF_NEXT(ol);
5029 		}
5030 		if (llen % 4) {
5031 			/* must add a pad to the param */
5032 			uint32_t cpthis = 0;
5033 			int padlen;
5034 
5035 			padlen = 4 - (llen % 4);
5036 			m_copyback(op_err, llen, padlen, (caddr_t)&cpthis);
5037 		}
5038 		while (SCTP_BUF_NEXT(m_at) != NULL) {
5039 			m_at = SCTP_BUF_NEXT(m_at);
5040 		}
5041 		SCTP_BUF_NEXT(m_at) = op_err;
5042 		while (SCTP_BUF_NEXT(m_at) != NULL) {
5043 			m_at = SCTP_BUF_NEXT(m_at);
5044 		}
5045 	}
5046 	/* pre-calulate the size and update pkt header and chunk header */
5047 	p_len = 0;
5048 	for (m_tmp = m; m_tmp; m_tmp = SCTP_BUF_NEXT(m_tmp)) {
5049 		p_len += SCTP_BUF_LEN(m_tmp);
5050 		if (SCTP_BUF_NEXT(m_tmp) == NULL) {
5051 			/* m_tmp should now point to last one */
5052 			break;
5053 		}
5054 	}
5055 
5056 	/* Now we must build a cookie */
5057 	m_cookie = sctp_add_cookie(inp, init_pkt, offset, m,
5058 	    sizeof(struct sctphdr), &stc, &signature);
5059 	if (m_cookie == NULL) {
5060 		/* memory problem */
5061 		sctp_m_freem(m);
5062 		return;
5063 	}
5064 	/* Now append the cookie to the end and update the space/size */
5065 	SCTP_BUF_NEXT(m_tmp) = m_cookie;
5066 
5067 	for (m_tmp = m_cookie; m_tmp; m_tmp = SCTP_BUF_NEXT(m_tmp)) {
5068 		p_len += SCTP_BUF_LEN(m_tmp);
5069 		if (SCTP_BUF_NEXT(m_tmp) == NULL) {
5070 			/* m_tmp should now point to last one */
5071 			mp_last = m_tmp;
5072 			break;
5073 		}
5074 	}
5075 	/*
5076 	 * Place in the size, but we don't include the last pad (if any) in
5077 	 * the INIT-ACK.
5078 	 */
5079 	initackm_out->msg.ch.chunk_length = htons((p_len - sizeof(struct sctphdr)));
5080 
5081 	/*
5082 	 * Time to sign the cookie, we don't sign over the cookie signature
5083 	 * though thus we set trailer.
5084 	 */
5085 	(void)sctp_hmac_m(SCTP_HMAC,
5086 	    (uint8_t *) inp->sctp_ep.secret_key[(int)(inp->sctp_ep.current_secret_number)],
5087 	    SCTP_SECRET_SIZE, m_cookie, sizeof(struct sctp_paramhdr),
5088 	    (uint8_t *) signature, SCTP_SIGNATURE_SIZE);
5089 	/*
5090 	 * We sifa 0 here to NOT set IP_DF if its IPv4, we ignore the return
5091 	 * here since the timer will drive a retranmission.
5092 	 */
5093 	padval = p_len % 4;
5094 	if ((padval) && (mp_last)) {
5095 		/* see my previous comments on mp_last */
5096 		int ret;
5097 
5098 		ret = sctp_add_pad_tombuf(mp_last, (4 - padval));
5099 		if (ret) {
5100 			/* Houston we have a problem, no space */
5101 			sctp_m_freem(m);
5102 			return;
5103 		}
5104 		p_len += padval;
5105 	}
5106 	(void)sctp_lowlevel_chunk_output(inp, NULL, NULL, to, m, 0, NULL, 0, 0,
5107 	    NULL, 0);
5108 	SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
5109 }
5110 
5111 
5112 void
5113 sctp_insert_on_wheel(struct sctp_tcb *stcb,
5114     struct sctp_association *asoc,
5115     struct sctp_stream_out *strq, int holds_lock)
5116 {
5117 	struct sctp_stream_out *stre, *strn;
5118 
5119 	if (holds_lock == 0) {
5120 		SCTP_TCB_SEND_LOCK(stcb);
5121 	}
5122 	if ((strq->next_spoke.tqe_next) ||
5123 	    (strq->next_spoke.tqe_prev)) {
5124 		/* already on wheel */
5125 		goto outof_here;
5126 	}
5127 	stre = TAILQ_FIRST(&asoc->out_wheel);
5128 	if (stre == NULL) {
5129 		/* only one on wheel */
5130 		TAILQ_INSERT_HEAD(&asoc->out_wheel, strq, next_spoke);
5131 		goto outof_here;
5132 	}
5133 	for (; stre; stre = strn) {
5134 		strn = TAILQ_NEXT(stre, next_spoke);
5135 		if (stre->stream_no > strq->stream_no) {
5136 			TAILQ_INSERT_BEFORE(stre, strq, next_spoke);
5137 			goto outof_here;
5138 		} else if (stre->stream_no == strq->stream_no) {
5139 			/* huh, should not happen */
5140 			goto outof_here;
5141 		} else if (strn == NULL) {
5142 			/* next one is null */
5143 			TAILQ_INSERT_AFTER(&asoc->out_wheel, stre, strq,
5144 			    next_spoke);
5145 		}
5146 	}
5147 outof_here:
5148 	if (holds_lock == 0) {
5149 		SCTP_TCB_SEND_UNLOCK(stcb);
5150 	}
5151 }
5152 
5153 static void
5154 sctp_remove_from_wheel(struct sctp_tcb *stcb,
5155     struct sctp_association *asoc,
5156     struct sctp_stream_out *strq)
5157 {
5158 	/* take off and then setup so we know it is not on the wheel */
5159 	SCTP_TCB_SEND_LOCK(stcb);
5160 	if (TAILQ_FIRST(&strq->outqueue)) {
5161 		/* more was added */
5162 		SCTP_TCB_SEND_UNLOCK(stcb);
5163 		return;
5164 	}
5165 	TAILQ_REMOVE(&asoc->out_wheel, strq, next_spoke);
5166 	strq->next_spoke.tqe_next = NULL;
5167 	strq->next_spoke.tqe_prev = NULL;
5168 	SCTP_TCB_SEND_UNLOCK(stcb);
5169 }
5170 
5171 static void
5172 sctp_prune_prsctp(struct sctp_tcb *stcb,
5173     struct sctp_association *asoc,
5174     struct sctp_sndrcvinfo *srcv,
5175     int dataout)
5176 {
5177 	int freed_spc = 0;
5178 	struct sctp_tmit_chunk *chk, *nchk;
5179 
5180 	SCTP_TCB_LOCK_ASSERT(stcb);
5181 	if ((asoc->peer_supports_prsctp) &&
5182 	    (asoc->sent_queue_cnt_removeable > 0)) {
5183 		TAILQ_FOREACH(chk, &asoc->sent_queue, sctp_next) {
5184 			/*
5185 			 * Look for chunks marked with the PR_SCTP flag AND
5186 			 * the buffer space flag. If the one being sent is
5187 			 * equal or greater priority then purge the old one
5188 			 * and free some space.
5189 			 */
5190 			if (PR_SCTP_BUF_ENABLED(chk->flags)) {
5191 				/*
5192 				 * This one is PR-SCTP AND buffer space
5193 				 * limited type
5194 				 */
5195 				if (chk->rec.data.timetodrop.tv_sec >= (long)srcv->sinfo_timetolive) {
5196 					/*
5197 					 * Lower numbers equates to higher
5198 					 * priority so if the one we are
5199 					 * looking at has a larger or equal
5200 					 * priority we want to drop the data
5201 					 * and NOT retransmit it.
5202 					 */
5203 					if (chk->data) {
5204 						/*
5205 						 * We release the book_size
5206 						 * if the mbuf is here
5207 						 */
5208 						int ret_spc;
5209 						int cause;
5210 
5211 						if (chk->sent > SCTP_DATAGRAM_UNSENT)
5212 							cause = SCTP_RESPONSE_TO_USER_REQ | SCTP_NOTIFY_DATAGRAM_SENT;
5213 						else
5214 							cause = SCTP_RESPONSE_TO_USER_REQ | SCTP_NOTIFY_DATAGRAM_UNSENT;
5215 						ret_spc = sctp_release_pr_sctp_chunk(stcb, chk,
5216 						    cause,
5217 						    &asoc->sent_queue);
5218 						freed_spc += ret_spc;
5219 						if (freed_spc >= dataout) {
5220 							return;
5221 						}
5222 					}	/* if chunk was present */
5223 				}	/* if of sufficent priority */
5224 			}	/* if chunk has enabled */
5225 		}		/* tailqforeach */
5226 
5227 		chk = TAILQ_FIRST(&asoc->send_queue);
5228 		while (chk) {
5229 			nchk = TAILQ_NEXT(chk, sctp_next);
5230 			/* Here we must move to the sent queue and mark */
5231 			if (PR_SCTP_TTL_ENABLED(chk->flags)) {
5232 				if (chk->rec.data.timetodrop.tv_sec >= (long)srcv->sinfo_timetolive) {
5233 					if (chk->data) {
5234 						/*
5235 						 * We release the book_size
5236 						 * if the mbuf is here
5237 						 */
5238 						int ret_spc;
5239 
5240 						ret_spc = sctp_release_pr_sctp_chunk(stcb, chk,
5241 						    SCTP_RESPONSE_TO_USER_REQ | SCTP_NOTIFY_DATAGRAM_UNSENT,
5242 						    &asoc->send_queue);
5243 
5244 						freed_spc += ret_spc;
5245 						if (freed_spc >= dataout) {
5246 							return;
5247 						}
5248 					}	/* end if chk->data */
5249 				}	/* end if right class */
5250 			}	/* end if chk pr-sctp */
5251 			chk = nchk;
5252 		}		/* end while (chk) */
5253 	}			/* if enabled in asoc */
5254 }
5255 
5256 int
5257 sctp_get_frag_point(struct sctp_tcb *stcb,
5258     struct sctp_association *asoc)
5259 {
5260 	int siz, ovh;
5261 
5262 	/*
5263 	 * For endpoints that have both v6 and v4 addresses we must reserve
5264 	 * room for the ipv6 header, for those that are only dealing with V4
5265 	 * we use a larger frag point.
5266 	 */
5267 	if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
5268 		ovh = SCTP_MED_OVERHEAD;
5269 	} else {
5270 		ovh = SCTP_MED_V4_OVERHEAD;
5271 	}
5272 
5273 	if (stcb->asoc.sctp_frag_point > asoc->smallest_mtu)
5274 		siz = asoc->smallest_mtu - ovh;
5275 	else
5276 		siz = (stcb->asoc.sctp_frag_point - ovh);
5277 	/*
5278 	 * if (siz > (MCLBYTES-sizeof(struct sctp_data_chunk))) {
5279 	 */
5280 	/* A data chunk MUST fit in a cluster */
5281 	/* siz = (MCLBYTES - sizeof(struct sctp_data_chunk)); */
5282 	/* } */
5283 
5284 	/* adjust for an AUTH chunk if DATA requires auth */
5285 	if (sctp_auth_is_required_chunk(SCTP_DATA, stcb->asoc.peer_auth_chunks))
5286 		siz -= sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
5287 
5288 	if (siz % 4) {
5289 		/* make it an even word boundary please */
5290 		siz -= (siz % 4);
5291 	}
5292 	return (siz);
5293 }
5294 
5295 static void
5296 sctp_set_prsctp_policy(struct sctp_tcb *stcb,
5297     struct sctp_stream_queue_pending *sp)
5298 {
5299 	sp->pr_sctp_on = 0;
5300 	if (stcb->asoc.peer_supports_prsctp) {
5301 		/*
5302 		 * We assume that the user wants PR_SCTP_TTL if the user
5303 		 * provides a positive lifetime but does not specify any
5304 		 * PR_SCTP policy. This is a BAD assumption and causes
5305 		 * problems at least with the U-Vancovers MPI folks. I will
5306 		 * change this to be no policy means NO PR-SCTP.
5307 		 */
5308 		if (PR_SCTP_ENABLED(sp->sinfo_flags)) {
5309 			sp->act_flags |= PR_SCTP_POLICY(sp->sinfo_flags);
5310 			sp->pr_sctp_on = 1;
5311 		} else {
5312 			return;
5313 		}
5314 		switch (PR_SCTP_POLICY(sp->sinfo_flags)) {
5315 		case CHUNK_FLAGS_PR_SCTP_BUF:
5316 			/*
5317 			 * Time to live is a priority stored in tv_sec when
5318 			 * doing the buffer drop thing.
5319 			 */
5320 			sp->ts.tv_sec = sp->timetolive;
5321 			sp->ts.tv_usec = 0;
5322 			break;
5323 		case CHUNK_FLAGS_PR_SCTP_TTL:
5324 			{
5325 				struct timeval tv;
5326 
5327 				(void)SCTP_GETTIME_TIMEVAL(&sp->ts);
5328 				tv.tv_sec = sp->timetolive / 1000;
5329 				tv.tv_usec = (sp->timetolive * 1000) % 1000000;
5330 				timevaladd(&sp->ts, &tv);
5331 			}
5332 			break;
5333 		case CHUNK_FLAGS_PR_SCTP_RTX:
5334 			/*
5335 			 * Time to live is a the number or retransmissions
5336 			 * stored in tv_sec.
5337 			 */
5338 			sp->ts.tv_sec = sp->timetolive;
5339 			sp->ts.tv_usec = 0;
5340 			break;
5341 		default:
5342 			SCTPDBG(SCTP_DEBUG_USRREQ1,
5343 			    "Unknown PR_SCTP policy %u.\n",
5344 			    PR_SCTP_POLICY(sp->sinfo_flags));
5345 			break;
5346 		}
5347 	}
5348 }
5349 
5350 static int
5351 sctp_msg_append(struct sctp_tcb *stcb,
5352     struct sctp_nets *net,
5353     struct mbuf *m,
5354     struct sctp_sndrcvinfo *srcv, int hold_stcb_lock)
5355 {
5356 	int error = 0, holds_lock;
5357 	struct mbuf *at;
5358 	struct sctp_stream_queue_pending *sp = NULL;
5359 	struct sctp_stream_out *strm;
5360 
5361 	/*
5362 	 * Given an mbuf chain, put it into the association send queue and
5363 	 * place it on the wheel
5364 	 */
5365 	holds_lock = hold_stcb_lock;
5366 	if (srcv->sinfo_stream >= stcb->asoc.streamoutcnt) {
5367 		/* Invalid stream number */
5368 		error = EINVAL;
5369 		goto out_now;
5370 	}
5371 	if ((stcb->asoc.stream_locked) &&
5372 	    (stcb->asoc.stream_locked_on != srcv->sinfo_stream)) {
5373 		error = EAGAIN;
5374 		goto out_now;
5375 	}
5376 	strm = &stcb->asoc.strmout[srcv->sinfo_stream];
5377 	/* Now can we send this? */
5378 	if ((SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
5379 	    (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
5380 	    (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
5381 	    (stcb->asoc.state & SCTP_STATE_SHUTDOWN_PENDING)) {
5382 		/* got data while shutting down */
5383 		error = ECONNRESET;
5384 		goto out_now;
5385 	}
5386 	sctp_alloc_a_strmoq(stcb, sp);
5387 	if (sp == NULL) {
5388 		SCTP_LTRACE_ERR(stcb->sctp_ep, stcb, ENOMEM, 0);
5389 		error = ENOMEM;
5390 		goto out_now;
5391 	}
5392 	sp->sinfo_flags = srcv->sinfo_flags;
5393 	sp->timetolive = srcv->sinfo_timetolive;
5394 	sp->ppid = srcv->sinfo_ppid;
5395 	sp->context = srcv->sinfo_context;
5396 	sp->strseq = 0;
5397 	if (sp->sinfo_flags & SCTP_ADDR_OVER) {
5398 		sp->net = net;
5399 		sp->addr_over = 1;
5400 	} else {
5401 		sp->net = stcb->asoc.primary_destination;
5402 		sp->addr_over = 0;
5403 	}
5404 	atomic_add_int(&sp->net->ref_count, 1);
5405 	(void)SCTP_GETTIME_TIMEVAL(&sp->ts);
5406 	sp->stream = srcv->sinfo_stream;
5407 	sp->msg_is_complete = 1;
5408 	sp->sender_all_done = 1;
5409 	sp->some_taken = 0;
5410 	sp->data = m;
5411 	sp->tail_mbuf = NULL;
5412 	sp->length = 0;
5413 	at = m;
5414 	sctp_set_prsctp_policy(stcb, sp);
5415 	/*
5416 	 * We could in theory (for sendall) sifa the length in, but we would
5417 	 * still have to hunt through the chain since we need to setup the
5418 	 * tail_mbuf
5419 	 */
5420 	while (at) {
5421 		if (SCTP_BUF_NEXT(at) == NULL)
5422 			sp->tail_mbuf = at;
5423 		sp->length += SCTP_BUF_LEN(at);
5424 		at = SCTP_BUF_NEXT(at);
5425 	}
5426 	SCTP_TCB_SEND_LOCK(stcb);
5427 	sctp_snd_sb_alloc(stcb, sp->length);
5428 	atomic_add_int(&stcb->asoc.stream_queue_cnt, 1);
5429 	TAILQ_INSERT_TAIL(&strm->outqueue, sp, next);
5430 	if ((srcv->sinfo_flags & SCTP_UNORDERED) == 0) {
5431 		sp->strseq = strm->next_sequence_sent;
5432 		strm->next_sequence_sent++;
5433 	}
5434 	if ((strm->next_spoke.tqe_next == NULL) &&
5435 	    (strm->next_spoke.tqe_prev == NULL)) {
5436 		/* Not on wheel, insert */
5437 		sctp_insert_on_wheel(stcb, &stcb->asoc, strm, 1);
5438 	}
5439 	m = NULL;
5440 	SCTP_TCB_SEND_UNLOCK(stcb);
5441 out_now:
5442 	if (m) {
5443 		sctp_m_freem(m);
5444 	}
5445 	return (error);
5446 }
5447 
5448 
5449 static struct mbuf *
5450 sctp_copy_mbufchain(struct mbuf *clonechain,
5451     struct mbuf *outchain,
5452     struct mbuf **endofchain,
5453     int can_take_mbuf,
5454     int sizeofcpy,
5455     uint8_t copy_by_ref)
5456 {
5457 	struct mbuf *m;
5458 	struct mbuf *appendchain;
5459 	caddr_t cp;
5460 	int len;
5461 
5462 	if (endofchain == NULL) {
5463 		/* error */
5464 error_out:
5465 		if (outchain)
5466 			sctp_m_freem(outchain);
5467 		return (NULL);
5468 	}
5469 	if (can_take_mbuf) {
5470 		appendchain = clonechain;
5471 	} else {
5472 		if (!copy_by_ref &&
5473 		    (sizeofcpy <= (int)((((sctp_mbuf_threshold_count - 1) * MLEN) + MHLEN)))
5474 		    ) {
5475 			/* Its not in a cluster */
5476 			if (*endofchain == NULL) {
5477 				/* lets get a mbuf cluster */
5478 				if (outchain == NULL) {
5479 					/* This is the general case */
5480 			new_mbuf:
5481 					outchain = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_HEADER);
5482 					if (outchain == NULL) {
5483 						goto error_out;
5484 					}
5485 					SCTP_BUF_LEN(outchain) = 0;
5486 					*endofchain = outchain;
5487 					/* get the prepend space */
5488 					SCTP_BUF_RESV_UF(outchain, (SCTP_FIRST_MBUF_RESV + 4));
5489 				} else {
5490 					/*
5491 					 * We really should not get a NULL
5492 					 * in endofchain
5493 					 */
5494 					/* find end */
5495 					m = outchain;
5496 					while (m) {
5497 						if (SCTP_BUF_NEXT(m) == NULL) {
5498 							*endofchain = m;
5499 							break;
5500 						}
5501 						m = SCTP_BUF_NEXT(m);
5502 					}
5503 					/* sanity */
5504 					if (*endofchain == NULL) {
5505 						/*
5506 						 * huh, TSNH XXX maybe we
5507 						 * should panic
5508 						 */
5509 						sctp_m_freem(outchain);
5510 						goto new_mbuf;
5511 					}
5512 				}
5513 				/* get the new end of length */
5514 				len = M_TRAILINGSPACE(*endofchain);
5515 			} else {
5516 				/* how much is left at the end? */
5517 				len = M_TRAILINGSPACE(*endofchain);
5518 			}
5519 			/* Find the end of the data, for appending */
5520 			cp = (mtod((*endofchain), caddr_t)+SCTP_BUF_LEN((*endofchain)));
5521 
5522 			/* Now lets copy it out */
5523 			if (len >= sizeofcpy) {
5524 				/* It all fits, copy it in */
5525 				m_copydata(clonechain, 0, sizeofcpy, cp);
5526 				SCTP_BUF_LEN((*endofchain)) += sizeofcpy;
5527 			} else {
5528 				/* fill up the end of the chain */
5529 				if (len > 0) {
5530 					m_copydata(clonechain, 0, len, cp);
5531 					SCTP_BUF_LEN((*endofchain)) += len;
5532 					/* now we need another one */
5533 					sizeofcpy -= len;
5534 				}
5535 				m = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_HEADER);
5536 				if (m == NULL) {
5537 					/* We failed */
5538 					goto error_out;
5539 				}
5540 				SCTP_BUF_NEXT((*endofchain)) = m;
5541 				*endofchain = m;
5542 				cp = mtod((*endofchain), caddr_t);
5543 				m_copydata(clonechain, len, sizeofcpy, cp);
5544 				SCTP_BUF_LEN((*endofchain)) += sizeofcpy;
5545 			}
5546 			return (outchain);
5547 		} else {
5548 			/* copy the old fashion way */
5549 			appendchain = SCTP_M_COPYM(clonechain, 0, M_COPYALL, M_DONTWAIT);
5550 		}
5551 	}
5552 	if (appendchain == NULL) {
5553 		/* error */
5554 		if (outchain)
5555 			sctp_m_freem(outchain);
5556 		return (NULL);
5557 	}
5558 	if (outchain) {
5559 		/* tack on to the end */
5560 		if (*endofchain != NULL) {
5561 			SCTP_BUF_NEXT(((*endofchain))) = appendchain;
5562 		} else {
5563 			m = outchain;
5564 			while (m) {
5565 				if (SCTP_BUF_NEXT(m) == NULL) {
5566 					SCTP_BUF_NEXT(m) = appendchain;
5567 					break;
5568 				}
5569 				m = SCTP_BUF_NEXT(m);
5570 			}
5571 		}
5572 		/*
5573 		 * save off the end and update the end-chain postion
5574 		 */
5575 		m = appendchain;
5576 		while (m) {
5577 			if (SCTP_BUF_NEXT(m) == NULL) {
5578 				*endofchain = m;
5579 				break;
5580 			}
5581 			m = SCTP_BUF_NEXT(m);
5582 		}
5583 		return (outchain);
5584 	} else {
5585 		/* save off the end and update the end-chain postion */
5586 		m = appendchain;
5587 		while (m) {
5588 			if (SCTP_BUF_NEXT(m) == NULL) {
5589 				*endofchain = m;
5590 				break;
5591 			}
5592 			m = SCTP_BUF_NEXT(m);
5593 		}
5594 		return (appendchain);
5595 	}
5596 }
5597 
5598 int
5599 sctp_med_chunk_output(struct sctp_inpcb *inp,
5600     struct sctp_tcb *stcb,
5601     struct sctp_association *asoc,
5602     int *num_out,
5603     int *reason_code,
5604     int control_only, int *cwnd_full, int from_where,
5605     struct timeval *now, int *now_filled, int frag_point);
5606 
5607 static void
5608 sctp_sendall_iterator(struct sctp_inpcb *inp, struct sctp_tcb *stcb, void *ptr,
5609     uint32_t val)
5610 {
5611 	struct sctp_copy_all *ca;
5612 	struct mbuf *m;
5613 	int ret = 0;
5614 	int added_control = 0;
5615 	int un_sent, do_chunk_output = 1;
5616 	struct sctp_association *asoc;
5617 
5618 	ca = (struct sctp_copy_all *)ptr;
5619 	if (ca->m == NULL) {
5620 		return;
5621 	}
5622 	if (ca->inp != inp) {
5623 		/* TSNH */
5624 		return;
5625 	}
5626 	if ((ca->m) && ca->sndlen) {
5627 		m = SCTP_M_COPYM(ca->m, 0, M_COPYALL, M_DONTWAIT);
5628 		if (m == NULL) {
5629 			/* can't copy so we are done */
5630 			ca->cnt_failed++;
5631 			return;
5632 		}
5633 	} else {
5634 		m = NULL;
5635 	}
5636 	SCTP_TCB_LOCK_ASSERT(stcb);
5637 	if (ca->sndrcv.sinfo_flags & SCTP_ABORT) {
5638 		/* Abort this assoc with m as the user defined reason */
5639 		if (m) {
5640 			struct sctp_paramhdr *ph;
5641 
5642 			SCTP_BUF_PREPEND(m, sizeof(struct sctp_paramhdr), M_DONTWAIT);
5643 			if (m) {
5644 				ph = mtod(m, struct sctp_paramhdr *);
5645 				ph->param_type = htons(SCTP_CAUSE_USER_INITIATED_ABT);
5646 				ph->param_length = htons(ca->sndlen);
5647 			}
5648 			/*
5649 			 * We add one here to keep the assoc from
5650 			 * dis-appearing on us.
5651 			 */
5652 			atomic_add_int(&stcb->asoc.refcnt, 1);
5653 			sctp_abort_an_association(inp, stcb,
5654 			    SCTP_RESPONSE_TO_USER_REQ,
5655 			    m);
5656 			/*
5657 			 * sctp_abort_an_association calls sctp_free_asoc()
5658 			 * free association will NOT free it since we
5659 			 * incremented the refcnt .. we do this to prevent
5660 			 * it being freed and things getting tricky since we
5661 			 * could end up (from free_asoc) calling inpcb_free
5662 			 * which would get a recursive lock call to the
5663 			 * iterator lock.. But as a consequence of that the
5664 			 * stcb will return to us un-locked.. since
5665 			 * free_asoc returns with either no TCB or the TCB
5666 			 * unlocked, we must relock.. to unlock in the
5667 			 * iterator timer :-0
5668 			 */
5669 			SCTP_TCB_LOCK(stcb);
5670 			atomic_add_int(&stcb->asoc.refcnt, -1);
5671 			goto no_chunk_output;
5672 		}
5673 	} else {
5674 		if (m) {
5675 			ret = sctp_msg_append(stcb, stcb->asoc.primary_destination, m,
5676 			    &ca->sndrcv, 1);
5677 		}
5678 		asoc = &stcb->asoc;
5679 		if (ca->sndrcv.sinfo_flags & SCTP_EOF) {
5680 			/* shutdown this assoc */
5681 			int cnt;
5682 
5683 			cnt = sctp_is_there_unsent_data(stcb);
5684 
5685 			if (TAILQ_EMPTY(&asoc->send_queue) &&
5686 			    TAILQ_EMPTY(&asoc->sent_queue) &&
5687 			    (cnt == 0)) {
5688 				if (asoc->locked_on_sending) {
5689 					goto abort_anyway;
5690 				}
5691 				/*
5692 				 * there is nothing queued to send, so I'm
5693 				 * done...
5694 				 */
5695 				if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
5696 				    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
5697 				    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
5698 					/*
5699 					 * only send SHUTDOWN the first time
5700 					 * through
5701 					 */
5702 					sctp_send_shutdown(stcb, stcb->asoc.primary_destination);
5703 					if (SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) {
5704 						SCTP_STAT_DECR_GAUGE32(sctps_currestab);
5705 					}
5706 					asoc->state = SCTP_STATE_SHUTDOWN_SENT;
5707 					sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, stcb->sctp_ep, stcb,
5708 					    asoc->primary_destination);
5709 					sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
5710 					    asoc->primary_destination);
5711 					added_control = 1;
5712 					do_chunk_output = 0;
5713 				}
5714 			} else {
5715 				/*
5716 				 * we still got (or just got) data to send,
5717 				 * so set SHUTDOWN_PENDING
5718 				 */
5719 				/*
5720 				 * XXX sockets draft says that SCTP_EOF
5721 				 * should be sent with no data.  currently,
5722 				 * we will allow user data to be sent first
5723 				 * and move to SHUTDOWN-PENDING
5724 				 */
5725 				if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
5726 				    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
5727 				    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
5728 					if (asoc->locked_on_sending) {
5729 						/*
5730 						 * Locked to send out the
5731 						 * data
5732 						 */
5733 						struct sctp_stream_queue_pending *sp;
5734 
5735 						sp = TAILQ_LAST(&asoc->locked_on_sending->outqueue, sctp_streamhead);
5736 						if (sp) {
5737 							if ((sp->length == 0) && (sp->msg_is_complete == 0))
5738 								asoc->state |= SCTP_STATE_PARTIAL_MSG_LEFT;
5739 						}
5740 					}
5741 					asoc->state |= SCTP_STATE_SHUTDOWN_PENDING;
5742 					if (TAILQ_EMPTY(&asoc->send_queue) &&
5743 					    TAILQ_EMPTY(&asoc->sent_queue) &&
5744 					    (asoc->state & SCTP_STATE_PARTIAL_MSG_LEFT)) {
5745 				abort_anyway:
5746 						atomic_add_int(&stcb->asoc.refcnt, 1);
5747 						sctp_abort_an_association(stcb->sctp_ep, stcb,
5748 						    SCTP_RESPONSE_TO_USER_REQ,
5749 						    NULL);
5750 						atomic_add_int(&stcb->asoc.refcnt, -1);
5751 						goto no_chunk_output;
5752 					}
5753 					sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
5754 					    asoc->primary_destination);
5755 				}
5756 			}
5757 
5758 		}
5759 	}
5760 	un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
5761 	    ((stcb->asoc.chunks_on_out_queue - stcb->asoc.total_flight_count) * sizeof(struct sctp_data_chunk)));
5762 
5763 	if ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY)) &&
5764 	    (stcb->asoc.total_flight > 0) &&
5765 	    (un_sent < (int)(stcb->asoc.smallest_mtu - SCTP_MIN_OVERHEAD))
5766 	    ) {
5767 		do_chunk_output = 0;
5768 	}
5769 	if (do_chunk_output)
5770 		sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_USR_SEND);
5771 	else if (added_control) {
5772 		int num_out = 0, reason = 0, cwnd_full = 0, now_filled = 0;
5773 		struct timeval now;
5774 		int frag_point;
5775 
5776 		frag_point = sctp_get_frag_point(stcb, &stcb->asoc);
5777 		(void)sctp_med_chunk_output(inp, stcb, &stcb->asoc, &num_out,
5778 		    &reason, 1, &cwnd_full, 1, &now, &now_filled, frag_point);
5779 	}
5780 no_chunk_output:
5781 	if (ret) {
5782 		ca->cnt_failed++;
5783 	} else {
5784 		ca->cnt_sent++;
5785 	}
5786 }
5787 
5788 static void
5789 sctp_sendall_completes(void *ptr, uint32_t val)
5790 {
5791 	struct sctp_copy_all *ca;
5792 
5793 	ca = (struct sctp_copy_all *)ptr;
5794 	/*
5795 	 * Do a notify here? Kacheong suggests that the notify be done at
5796 	 * the send time.. so you would push up a notification if any send
5797 	 * failed. Don't know if this is feasable since the only failures we
5798 	 * have is "memory" related and if you cannot get an mbuf to send
5799 	 * the data you surely can't get an mbuf to send up to notify the
5800 	 * user you can't send the data :->
5801 	 */
5802 
5803 	/* now free everything */
5804 	sctp_m_freem(ca->m);
5805 	SCTP_FREE(ca, SCTP_M_COPYAL);
5806 }
5807 
5808 
5809 #define	MC_ALIGN(m, len) do {						\
5810 	SCTP_BUF_RESV_UF(m, ((MCLBYTES - (len)) & ~(sizeof(long) - 1));	\
5811 } while (0)
5812 
5813 
5814 
5815 static struct mbuf *
5816 sctp_copy_out_all(struct uio *uio, int len)
5817 {
5818 	struct mbuf *ret, *at;
5819 	int left, willcpy, cancpy, error;
5820 
5821 	ret = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_WAIT, 1, MT_DATA);
5822 	if (ret == NULL) {
5823 		/* TSNH */
5824 		return (NULL);
5825 	}
5826 	left = len;
5827 	SCTP_BUF_LEN(ret) = 0;
5828 	/* save space for the data chunk header */
5829 	cancpy = M_TRAILINGSPACE(ret);
5830 	willcpy = min(cancpy, left);
5831 	at = ret;
5832 	while (left > 0) {
5833 		/* Align data to the end */
5834 		error = uiomove(mtod(at, caddr_t), willcpy, uio);
5835 		if (error) {
5836 	err_out_now:
5837 			sctp_m_freem(at);
5838 			return (NULL);
5839 		}
5840 		SCTP_BUF_LEN(at) = willcpy;
5841 		SCTP_BUF_NEXT_PKT(at) = SCTP_BUF_NEXT(at) = 0;
5842 		left -= willcpy;
5843 		if (left > 0) {
5844 			SCTP_BUF_NEXT(at) = sctp_get_mbuf_for_msg(left, 0, M_WAIT, 1, MT_DATA);
5845 			if (SCTP_BUF_NEXT(at) == NULL) {
5846 				goto err_out_now;
5847 			}
5848 			at = SCTP_BUF_NEXT(at);
5849 			SCTP_BUF_LEN(at) = 0;
5850 			cancpy = M_TRAILINGSPACE(at);
5851 			willcpy = min(cancpy, left);
5852 		}
5853 	}
5854 	return (ret);
5855 }
5856 
5857 static int
5858 sctp_sendall(struct sctp_inpcb *inp, struct uio *uio, struct mbuf *m,
5859     struct sctp_sndrcvinfo *srcv)
5860 {
5861 	int ret;
5862 	struct sctp_copy_all *ca;
5863 
5864 	SCTP_MALLOC(ca, struct sctp_copy_all *, sizeof(struct sctp_copy_all),
5865 	    SCTP_M_COPYAL);
5866 	if (ca == NULL) {
5867 		sctp_m_freem(m);
5868 		SCTP_LTRACE_ERR(inp, NULL, ENOMEM, 0);
5869 		return (ENOMEM);
5870 	}
5871 	memset(ca, 0, sizeof(struct sctp_copy_all));
5872 
5873 	ca->inp = inp;
5874 	memcpy(&ca->sndrcv, srcv, sizeof(struct sctp_nonpad_sndrcvinfo));
5875 	/*
5876 	 * take off the sendall flag, it would be bad if we failed to do
5877 	 * this :-0
5878 	 */
5879 	ca->sndrcv.sinfo_flags &= ~SCTP_SENDALL;
5880 	/* get length and mbuf chain */
5881 	if (uio) {
5882 		ca->sndlen = uio->uio_resid;
5883 		ca->m = sctp_copy_out_all(uio, ca->sndlen);
5884 		if (ca->m == NULL) {
5885 			SCTP_FREE(ca, SCTP_M_COPYAL);
5886 			SCTP_LTRACE_ERR(inp, NULL, ENOMEM, 0);
5887 			return (ENOMEM);
5888 		}
5889 	} else {
5890 		/* Gather the length of the send */
5891 		struct mbuf *mat;
5892 
5893 		mat = m;
5894 		ca->sndlen = 0;
5895 		while (m) {
5896 			ca->sndlen += SCTP_BUF_LEN(m);
5897 			m = SCTP_BUF_NEXT(m);
5898 		}
5899 		ca->m = m;
5900 	}
5901 	ret = sctp_initiate_iterator(NULL, sctp_sendall_iterator, NULL,
5902 	    SCTP_PCB_ANY_FLAGS, SCTP_PCB_ANY_FEATURES,
5903 	    SCTP_ASOC_ANY_STATE,
5904 	    (void *)ca, 0,
5905 	    sctp_sendall_completes, inp, 1);
5906 	if (ret) {
5907 		SCTP_PRINTF("Failed to initiate iterator for sendall\n");
5908 		SCTP_FREE(ca, SCTP_M_COPYAL);
5909 		return (EFAULT);
5910 	}
5911 	return (0);
5912 }
5913 
5914 
5915 void
5916 sctp_toss_old_cookies(struct sctp_tcb *stcb, struct sctp_association *asoc)
5917 {
5918 	struct sctp_tmit_chunk *chk, *nchk;
5919 
5920 	chk = TAILQ_FIRST(&asoc->control_send_queue);
5921 	while (chk) {
5922 		nchk = TAILQ_NEXT(chk, sctp_next);
5923 		if (chk->rec.chunk_id.id == SCTP_COOKIE_ECHO) {
5924 			TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
5925 			if (chk->data) {
5926 				sctp_m_freem(chk->data);
5927 				chk->data = NULL;
5928 			}
5929 			asoc->ctrl_queue_cnt--;
5930 			sctp_free_a_chunk(stcb, chk);
5931 		}
5932 		chk = nchk;
5933 	}
5934 }
5935 
5936 void
5937 sctp_toss_old_asconf(struct sctp_tcb *stcb)
5938 {
5939 	struct sctp_association *asoc;
5940 	struct sctp_tmit_chunk *chk, *chk_tmp;
5941 
5942 	asoc = &stcb->asoc;
5943 	for (chk = TAILQ_FIRST(&asoc->control_send_queue); chk != NULL;
5944 	    chk = chk_tmp) {
5945 		/* get next chk */
5946 		chk_tmp = TAILQ_NEXT(chk, sctp_next);
5947 		/* find SCTP_ASCONF chunk in queue (only one ever in queue) */
5948 		if (chk->rec.chunk_id.id == SCTP_ASCONF) {
5949 			TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
5950 			if (chk->data) {
5951 				sctp_m_freem(chk->data);
5952 				chk->data = NULL;
5953 			}
5954 			asoc->ctrl_queue_cnt--;
5955 			sctp_free_a_chunk(stcb, chk);
5956 		}
5957 	}
5958 }
5959 
5960 
5961 static void
5962 sctp_clean_up_datalist(struct sctp_tcb *stcb,
5963 
5964     struct sctp_association *asoc,
5965     struct sctp_tmit_chunk **data_list,
5966     int bundle_at,
5967     struct sctp_nets *net)
5968 {
5969 	int i;
5970 	struct sctp_tmit_chunk *tp1;
5971 
5972 	for (i = 0; i < bundle_at; i++) {
5973 		/* off of the send queue */
5974 		if (i) {
5975 			/*
5976 			 * Any chunk NOT 0 you zap the time chunk 0 gets
5977 			 * zapped or set based on if a RTO measurment is
5978 			 * needed.
5979 			 */
5980 			data_list[i]->do_rtt = 0;
5981 		}
5982 		/* record time */
5983 		data_list[i]->sent_rcv_time = net->last_sent_time;
5984 		data_list[i]->rec.data.fast_retran_tsn = data_list[i]->rec.data.TSN_seq;
5985 		TAILQ_REMOVE(&asoc->send_queue,
5986 		    data_list[i],
5987 		    sctp_next);
5988 		/* on to the sent queue */
5989 		tp1 = TAILQ_LAST(&asoc->sent_queue, sctpchunk_listhead);
5990 		if ((tp1) && (compare_with_wrap(tp1->rec.data.TSN_seq,
5991 		    data_list[i]->rec.data.TSN_seq, MAX_TSN))) {
5992 			struct sctp_tmit_chunk *tpp;
5993 
5994 			/* need to move back */
5995 	back_up_more:
5996 			tpp = TAILQ_PREV(tp1, sctpchunk_listhead, sctp_next);
5997 			if (tpp == NULL) {
5998 				TAILQ_INSERT_BEFORE(tp1, data_list[i], sctp_next);
5999 				goto all_done;
6000 			}
6001 			tp1 = tpp;
6002 			if (compare_with_wrap(tp1->rec.data.TSN_seq,
6003 			    data_list[i]->rec.data.TSN_seq, MAX_TSN)) {
6004 				goto back_up_more;
6005 			}
6006 			TAILQ_INSERT_AFTER(&asoc->sent_queue, tp1, data_list[i], sctp_next);
6007 		} else {
6008 			TAILQ_INSERT_TAIL(&asoc->sent_queue,
6009 			    data_list[i],
6010 			    sctp_next);
6011 		}
6012 all_done:
6013 		/* This does not lower until the cum-ack passes it */
6014 		asoc->sent_queue_cnt++;
6015 		asoc->send_queue_cnt--;
6016 		if ((asoc->peers_rwnd <= 0) &&
6017 		    (asoc->total_flight == 0) &&
6018 		    (bundle_at == 1)) {
6019 			/* Mark the chunk as being a window probe */
6020 			SCTP_STAT_INCR(sctps_windowprobed);
6021 		}
6022 #ifdef SCTP_AUDITING_ENABLED
6023 		sctp_audit_log(0xC2, 3);
6024 #endif
6025 		data_list[i]->sent = SCTP_DATAGRAM_SENT;
6026 		data_list[i]->snd_count = 1;
6027 		data_list[i]->rec.data.chunk_was_revoked = 0;
6028 		if (sctp_logging_level & SCTP_FLIGHT_LOGGING_ENABLE) {
6029 			sctp_misc_ints(SCTP_FLIGHT_LOG_UP,
6030 			    data_list[i]->whoTo->flight_size,
6031 			    data_list[i]->book_size,
6032 			    (uintptr_t) data_list[i]->whoTo,
6033 			    data_list[i]->rec.data.TSN_seq);
6034 		}
6035 		sctp_flight_size_increase(data_list[i]);
6036 		sctp_total_flight_increase(stcb, data_list[i]);
6037 		if (sctp_logging_level & SCTP_LOG_RWND_ENABLE) {
6038 			sctp_log_rwnd(SCTP_DECREASE_PEER_RWND,
6039 			    asoc->peers_rwnd, data_list[i]->send_size, sctp_peer_chunk_oh);
6040 		}
6041 		asoc->peers_rwnd = sctp_sbspace_sub(asoc->peers_rwnd,
6042 		    (uint32_t) (data_list[i]->send_size + sctp_peer_chunk_oh));
6043 		if (asoc->peers_rwnd < stcb->sctp_ep->sctp_ep.sctp_sws_sender) {
6044 			/* SWS sender side engages */
6045 			asoc->peers_rwnd = 0;
6046 		}
6047 	}
6048 }
6049 
6050 static void
6051 sctp_clean_up_ctl(struct sctp_tcb *stcb, struct sctp_association *asoc)
6052 {
6053 	struct sctp_tmit_chunk *chk, *nchk;
6054 
6055 	for (chk = TAILQ_FIRST(&asoc->control_send_queue);
6056 	    chk; chk = nchk) {
6057 		nchk = TAILQ_NEXT(chk, sctp_next);
6058 		if ((chk->rec.chunk_id.id == SCTP_SELECTIVE_ACK) ||
6059 		    (chk->rec.chunk_id.id == SCTP_HEARTBEAT_REQUEST) ||
6060 		    (chk->rec.chunk_id.id == SCTP_HEARTBEAT_ACK) ||
6061 		    (chk->rec.chunk_id.id == SCTP_SHUTDOWN) ||
6062 		    (chk->rec.chunk_id.id == SCTP_SHUTDOWN_ACK) ||
6063 		    (chk->rec.chunk_id.id == SCTP_OPERATION_ERROR) ||
6064 		    (chk->rec.chunk_id.id == SCTP_PACKET_DROPPED) ||
6065 		    (chk->rec.chunk_id.id == SCTP_COOKIE_ACK) ||
6066 		    (chk->rec.chunk_id.id == SCTP_ECN_CWR) ||
6067 		    (chk->rec.chunk_id.id == SCTP_ASCONF_ACK)) {
6068 			/* Stray chunks must be cleaned up */
6069 	clean_up_anyway:
6070 			TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
6071 			if (chk->data) {
6072 				sctp_m_freem(chk->data);
6073 				chk->data = NULL;
6074 			}
6075 			asoc->ctrl_queue_cnt--;
6076 			sctp_free_a_chunk(stcb, chk);
6077 		} else if (chk->rec.chunk_id.id == SCTP_STREAM_RESET) {
6078 			/* special handling, we must look into the param */
6079 			if (chk != asoc->str_reset) {
6080 				goto clean_up_anyway;
6081 			}
6082 		}
6083 	}
6084 }
6085 
6086 
6087 static int
6088 sctp_can_we_split_this(struct sctp_tcb *stcb,
6089     struct sctp_stream_queue_pending *sp,
6090     uint32_t goal_mtu, uint32_t frag_point, int eeor_on)
6091 {
6092 	/*
6093 	 * Make a decision on if I should split a msg into multiple parts.
6094 	 * This is only asked of incomplete messages.
6095 	 */
6096 	if (eeor_on) {
6097 		/*
6098 		 * If we are doing EEOR we need to always send it if its the
6099 		 * entire thing, since it might be all the guy is putting in
6100 		 * the hopper.
6101 		 */
6102 		if (goal_mtu >= sp->length) {
6103 			/*-
6104 			 * If we have data outstanding,
6105 			 * we get another chance when the sack
6106 			 * arrives to transmit - wait for more data
6107 			 */
6108 			if (stcb->asoc.total_flight == 0) {
6109 				/*
6110 				 * If nothing is in flight, we zero the
6111 				 * packet counter.
6112 				 */
6113 				return (sp->length);
6114 			}
6115 			return (0);
6116 
6117 		} else {
6118 			/* You can fill the rest */
6119 			return (goal_mtu);
6120 		}
6121 	}
6122 	if ((sp->length <= goal_mtu) ||
6123 	    ((sp->length - goal_mtu) < sctp_min_residual)) {
6124 		/* Sub-optimial residual don't split in non-eeor mode. */
6125 		return (0);
6126 	}
6127 	/*
6128 	 * If we reach here sp->length is larger than the goal_mtu. Do we
6129 	 * wish to split it for the sake of packet putting together?
6130 	 */
6131 	if (goal_mtu >= min(sctp_min_split_point, frag_point)) {
6132 		/* Its ok to split it */
6133 		return (min(goal_mtu, frag_point));
6134 	}
6135 	/* Nope, can't split */
6136 	return (0);
6137 
6138 }
6139 
6140 static uint32_t
6141 sctp_move_to_outqueue(struct sctp_tcb *stcb, struct sctp_nets *net,
6142     struct sctp_stream_out *strq,
6143     uint32_t goal_mtu,
6144     uint32_t frag_point,
6145     int *locked,
6146     int *giveup,
6147     int eeor_mode,
6148     int *bail)
6149 {
6150 	/* Move from the stream to the send_queue keeping track of the total */
6151 	struct sctp_association *asoc;
6152 	struct sctp_stream_queue_pending *sp;
6153 	struct sctp_tmit_chunk *chk;
6154 	struct sctp_data_chunk *dchkh;
6155 	uint32_t to_move;
6156 	uint8_t rcv_flags = 0;
6157 	uint8_t some_taken;
6158 	uint8_t send_lock_up = 0;
6159 
6160 	SCTP_TCB_LOCK_ASSERT(stcb);
6161 	asoc = &stcb->asoc;
6162 one_more_time:
6163 	/* sa_ignore FREED_MEMORY */
6164 	sp = TAILQ_FIRST(&strq->outqueue);
6165 	if (sp == NULL) {
6166 		*locked = 0;
6167 		SCTP_TCB_SEND_LOCK(stcb);
6168 		sp = TAILQ_FIRST(&strq->outqueue);
6169 		if (sp) {
6170 			SCTP_TCB_SEND_UNLOCK(stcb);
6171 			goto one_more_time;
6172 		}
6173 		if (strq->last_msg_incomplete) {
6174 			SCTP_PRINTF("Huh? Stream:%d lm_in_c=%d but queue is NULL\n",
6175 			    strq->stream_no,
6176 			    strq->last_msg_incomplete);
6177 			strq->last_msg_incomplete = 0;
6178 		}
6179 		SCTP_TCB_SEND_UNLOCK(stcb);
6180 		return (0);
6181 	}
6182 	if (sp->msg_is_complete) {
6183 		if (sp->length == 0) {
6184 			if (sp->sender_all_done) {
6185 				/*
6186 				 * We are doing differed cleanup. Last time
6187 				 * through when we took all the data the
6188 				 * sender_all_done was not set.
6189 				 */
6190 				if (sp->put_last_out == 0) {
6191 					SCTP_PRINTF("Gak, put out entire msg with NO end!-1\n");
6192 					SCTP_PRINTF("sender_done:%d len:%d msg_comp:%d put_last_out:%d send_lock:%d\n",
6193 					    sp->sender_all_done,
6194 					    sp->length,
6195 					    sp->msg_is_complete,
6196 					    sp->put_last_out,
6197 					    send_lock_up);
6198 				}
6199 				if (TAILQ_NEXT(sp, next) == NULL) {
6200 					SCTP_TCB_SEND_LOCK(stcb);
6201 					send_lock_up = 1;
6202 				}
6203 				atomic_subtract_int(&asoc->stream_queue_cnt, 1);
6204 				TAILQ_REMOVE(&strq->outqueue, sp, next);
6205 				sctp_free_remote_addr(sp->net);
6206 				if (sp->data) {
6207 					sctp_m_freem(sp->data);
6208 					sp->data = NULL;
6209 				}
6210 				sctp_free_a_strmoq(stcb, sp);
6211 
6212 				/* we can't be locked to it */
6213 				*locked = 0;
6214 				stcb->asoc.locked_on_sending = NULL;
6215 				if (send_lock_up) {
6216 					SCTP_TCB_SEND_UNLOCK(stcb);
6217 					send_lock_up = 0;
6218 				}
6219 				/* back to get the next msg */
6220 				goto one_more_time;
6221 			} else {
6222 				/*
6223 				 * sender just finished this but still holds
6224 				 * a reference
6225 				 */
6226 				*locked = 1;
6227 				*giveup = 1;
6228 				return (0);
6229 			}
6230 		}
6231 	} else {
6232 		/* is there some to get */
6233 		if (sp->length == 0) {
6234 			/* no */
6235 			*locked = 1;
6236 			*giveup = 1;
6237 			return (0);
6238 		}
6239 	}
6240 	some_taken = sp->some_taken;
6241 	if (stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET) {
6242 		sp->msg_is_complete = 1;
6243 	}
6244 re_look:
6245 	if (sp->msg_is_complete) {
6246 		/* The message is complete */
6247 		to_move = min(sp->length, frag_point);
6248 		if (to_move == sp->length) {
6249 			/* All of it fits in the MTU */
6250 			if (sp->some_taken) {
6251 				rcv_flags |= SCTP_DATA_LAST_FRAG;
6252 				sp->put_last_out = 1;
6253 			} else {
6254 				rcv_flags |= SCTP_DATA_NOT_FRAG;
6255 				sp->put_last_out = 1;
6256 			}
6257 		} else {
6258 			/* Not all of it fits, we fragment */
6259 			if (sp->some_taken == 0) {
6260 				rcv_flags |= SCTP_DATA_FIRST_FRAG;
6261 			}
6262 			sp->some_taken = 1;
6263 		}
6264 	} else {
6265 		to_move = sctp_can_we_split_this(stcb, sp, goal_mtu,
6266 		    frag_point, eeor_mode);
6267 		if (to_move) {
6268 			/*-
6269 			 * We use a snapshot of length in case it
6270 			 * is expanding during the compare.
6271 			 */
6272 			uint32_t llen;
6273 
6274 			llen = sp->length;
6275 			if (to_move >= llen) {
6276 				to_move = llen;
6277 				if (send_lock_up == 0) {
6278 					/*-
6279 					 * We are taking all of an incomplete msg
6280 					 * thus we need a send lock.
6281 					 */
6282 					SCTP_TCB_SEND_LOCK(stcb);
6283 					send_lock_up = 1;
6284 					if (sp->msg_is_complete) {
6285 						/*
6286 						 * the sender finished the
6287 						 * msg
6288 						 */
6289 						goto re_look;
6290 					}
6291 				}
6292 			}
6293 			if (sp->some_taken == 0) {
6294 				rcv_flags |= SCTP_DATA_FIRST_FRAG;
6295 				sp->some_taken = 1;
6296 			}
6297 		} else {
6298 			/* Nothing to take. */
6299 			if (sp->some_taken) {
6300 				*locked = 1;
6301 			}
6302 			*giveup = 1;
6303 			return (0);
6304 		}
6305 	}
6306 
6307 	/* If we reach here, we can copy out a chunk */
6308 	sctp_alloc_a_chunk(stcb, chk);
6309 	if (chk == NULL) {
6310 		/* No chunk memory */
6311 out_gu:
6312 		if (send_lock_up) {
6313 			SCTP_TCB_SEND_UNLOCK(stcb);
6314 			send_lock_up = 0;
6315 		}
6316 		*giveup = 1;
6317 		return (0);
6318 	}
6319 	/*
6320 	 * Setup for unordered if needed by looking at the user sent info
6321 	 * flags.
6322 	 */
6323 	if (sp->sinfo_flags & SCTP_UNORDERED) {
6324 		rcv_flags |= SCTP_DATA_UNORDERED;
6325 	}
6326 	/* clear out the chunk before setting up */
6327 	memset(chk, sizeof(*chk), 0);
6328 	chk->rec.data.rcv_flags = rcv_flags;
6329 	if (SCTP_BUF_IS_EXTENDED(sp->data)) {
6330 		chk->copy_by_ref = 1;
6331 	} else {
6332 		chk->copy_by_ref = 0;
6333 	}
6334 	if (to_move >= sp->length) {
6335 		/* we can steal the whole thing */
6336 		chk->data = sp->data;
6337 		chk->last_mbuf = sp->tail_mbuf;
6338 		/* register the stealing */
6339 		sp->data = sp->tail_mbuf = NULL;
6340 	} else {
6341 		struct mbuf *m;
6342 
6343 		chk->data = SCTP_M_COPYM(sp->data, 0, to_move, M_DONTWAIT);
6344 		chk->last_mbuf = NULL;
6345 		if (chk->data == NULL) {
6346 			sp->some_taken = some_taken;
6347 			sctp_free_a_chunk(stcb, chk);
6348 			*bail = 1;
6349 			goto out_gu;
6350 		}
6351 		/* Pull off the data */
6352 		m_adj(sp->data, to_move);
6353 		/* Now lets work our way down and compact it */
6354 		m = sp->data;
6355 		while (m && (SCTP_BUF_LEN(m) == 0)) {
6356 			sp->data = SCTP_BUF_NEXT(m);
6357 			SCTP_BUF_NEXT(m) = NULL;
6358 			if (sp->tail_mbuf == m) {
6359 				/*-
6360 				 * Freeing tail? TSNH since
6361 				 * we supposedly were taking less
6362 				 * than the sp->length.
6363 				 */
6364 #ifdef INVARIANTS
6365 				panic("Huh, freing tail? - TSNH");
6366 #else
6367 				SCTP_PRINTF("Huh, freeing tail? - TSNH\n");
6368 				sp->tail_mbuf = sp->data = NULL;
6369 				sp->length = 0;
6370 #endif
6371 
6372 			}
6373 			sctp_m_free(m);
6374 			m = sp->data;
6375 		}
6376 	}
6377 	if (to_move > sp->length) {
6378 		/*- This should not happen either
6379 		 * since we always lower to_move to the size
6380 		 * of sp->length if its larger.
6381 		 */
6382 #ifdef INVARIANTS
6383 		panic("Huh, how can to_move be larger?");
6384 #else
6385 		SCTP_PRINTF("Huh, how can to_move be larger?\n");
6386 		sp->length = 0;
6387 #endif
6388 	} else {
6389 		atomic_subtract_int(&sp->length, to_move);
6390 	}
6391 	if (M_LEADINGSPACE(chk->data) < (int)sizeof(struct sctp_data_chunk)) {
6392 		/* Not enough room for a chunk header, get some */
6393 		struct mbuf *m;
6394 
6395 		m = sctp_get_mbuf_for_msg(1, 0, M_DONTWAIT, 0, MT_DATA);
6396 		if (m == NULL) {
6397 			/*
6398 			 * we're in trouble here. _PREPEND below will free
6399 			 * all the data if there is no leading space, so we
6400 			 * must put the data back and restore.
6401 			 */
6402 			if (send_lock_up == 0) {
6403 				SCTP_TCB_SEND_LOCK(stcb);
6404 				send_lock_up = 1;
6405 			}
6406 			if (chk->data == NULL) {
6407 				/* unsteal the data */
6408 				sp->data = chk->data;
6409 				sp->tail_mbuf = chk->last_mbuf;
6410 			} else {
6411 				struct mbuf *m_tmp;
6412 
6413 				/* reassemble the data */
6414 				m_tmp = sp->data;
6415 				sp->data = chk->data;
6416 				SCTP_BUF_NEXT(sp->data) = m_tmp;
6417 			}
6418 			sp->some_taken = some_taken;
6419 			atomic_add_int(&sp->length, to_move);
6420 			chk->data = NULL;
6421 			*bail = 1;
6422 			sctp_free_a_chunk(stcb, chk);
6423 			goto out_gu;
6424 		} else {
6425 			SCTP_BUF_LEN(m) = 0;
6426 			SCTP_BUF_NEXT(m) = chk->data;
6427 			chk->data = m;
6428 			M_ALIGN(chk->data, 4);
6429 		}
6430 	}
6431 	SCTP_BUF_PREPEND(chk->data, sizeof(struct sctp_data_chunk), M_DONTWAIT);
6432 	if (chk->data == NULL) {
6433 		/* HELP, TSNH since we assured it would not above? */
6434 #ifdef INVARIANTS
6435 		panic("prepend failes HELP?");
6436 #else
6437 		SCTP_PRINTF("prepend fails HELP?\n");
6438 		sctp_free_a_chunk(stcb, chk);
6439 #endif
6440 		*bail = 1;
6441 		goto out_gu;
6442 	}
6443 	sctp_snd_sb_alloc(stcb, sizeof(struct sctp_data_chunk));
6444 	chk->book_size = chk->send_size = (to_move +
6445 	    sizeof(struct sctp_data_chunk));
6446 	chk->book_size_scale = 0;
6447 	chk->sent = SCTP_DATAGRAM_UNSENT;
6448 
6449 	/*
6450 	 * get last_mbuf and counts of mb useage This is ugly but hopefully
6451 	 * its only one mbuf.
6452 	 */
6453 	if (chk->last_mbuf == NULL) {
6454 		chk->last_mbuf = chk->data;
6455 		while (SCTP_BUF_NEXT(chk->last_mbuf) != NULL) {
6456 			chk->last_mbuf = SCTP_BUF_NEXT(chk->last_mbuf);
6457 		}
6458 	}
6459 	chk->flags = 0;
6460 	chk->asoc = &stcb->asoc;
6461 	chk->pad_inplace = 0;
6462 	chk->no_fr_allowed = 0;
6463 	chk->rec.data.stream_seq = sp->strseq;
6464 	chk->rec.data.stream_number = sp->stream;
6465 	chk->rec.data.payloadtype = sp->ppid;
6466 	chk->rec.data.context = sp->context;
6467 	chk->rec.data.doing_fast_retransmit = 0;
6468 	chk->rec.data.ect_nonce = 0;	/* ECN Nonce */
6469 
6470 	chk->rec.data.timetodrop = sp->ts;
6471 	chk->flags = sp->act_flags;
6472 	chk->addr_over = sp->addr_over;
6473 
6474 	chk->whoTo = net;
6475 	atomic_add_int(&chk->whoTo->ref_count, 1);
6476 
6477 	chk->rec.data.TSN_seq = atomic_fetchadd_int(&asoc->sending_seq, 1);
6478 #ifdef SCTP_LOG_SENDING_STR
6479 	sctp_misc_ints(SCTP_STRMOUT_LOG_SEND,
6480 	    (uintptr_t) stcb, (uintptr_t) sp,
6481 	    (uint32_t) ((chk->rec.data.stream_number << 16) | chk->rec.data.stream_seq),
6482 	    chk->rec.data.TSN_seq);
6483 #endif
6484 
6485 	dchkh = mtod(chk->data, struct sctp_data_chunk *);
6486 	/*
6487 	 * Put the rest of the things in place now. Size was done earlier in
6488 	 * previous loop prior to padding.
6489 	 */
6490 
6491 #ifdef SCTP_ASOCLOG_OF_TSNS
6492 	SCTP_TCB_LOCK_ASSERT(stcb);
6493 	if (asoc->tsn_out_at >= SCTP_TSN_LOG_SIZE) {
6494 		asoc->tsn_out_at = 0;
6495 		asoc->tsn_out_wrapped = 1;
6496 	}
6497 	asoc->out_tsnlog[asoc->tsn_out_at].tsn = chk->rec.data.TSN_seq;
6498 	asoc->out_tsnlog[asoc->tsn_out_at].strm = chk->rec.data.stream_number;
6499 	asoc->out_tsnlog[asoc->tsn_out_at].seq = chk->rec.data.stream_seq;
6500 	asoc->out_tsnlog[asoc->tsn_out_at].sz = chk->send_size;
6501 	asoc->out_tsnlog[asoc->tsn_out_at].flgs = chk->rec.data.rcv_flags;
6502 	asoc->out_tsnlog[asoc->tsn_out_at].stcb = (void *)stcb;
6503 	asoc->out_tsnlog[asoc->tsn_out_at].in_pos = asoc->tsn_out_at;
6504 	asoc->out_tsnlog[asoc->tsn_out_at].in_out = 2;
6505 	asoc->tsn_out_at++;
6506 #endif
6507 
6508 	dchkh->ch.chunk_type = SCTP_DATA;
6509 	dchkh->ch.chunk_flags = chk->rec.data.rcv_flags;
6510 	dchkh->dp.tsn = htonl(chk->rec.data.TSN_seq);
6511 	dchkh->dp.stream_id = htons(strq->stream_no);
6512 	dchkh->dp.stream_sequence = htons(chk->rec.data.stream_seq);
6513 	dchkh->dp.protocol_id = chk->rec.data.payloadtype;
6514 	dchkh->ch.chunk_length = htons(chk->send_size);
6515 	/* Now advance the chk->send_size by the actual pad needed. */
6516 	if (chk->send_size < SCTP_SIZE32(chk->book_size)) {
6517 		/* need a pad */
6518 		struct mbuf *lm;
6519 		int pads;
6520 
6521 		pads = SCTP_SIZE32(chk->book_size) - chk->send_size;
6522 		if (sctp_pad_lastmbuf(chk->data, pads, chk->last_mbuf) == 0) {
6523 			chk->pad_inplace = 1;
6524 		}
6525 		if ((lm = SCTP_BUF_NEXT(chk->last_mbuf)) != NULL) {
6526 			/* pad added an mbuf */
6527 			chk->last_mbuf = lm;
6528 		}
6529 		chk->send_size += pads;
6530 	}
6531 	/* We only re-set the policy if it is on */
6532 	if (sp->pr_sctp_on) {
6533 		sctp_set_prsctp_policy(stcb, sp);
6534 		asoc->pr_sctp_cnt++;
6535 		chk->pr_sctp_on = 1;
6536 	} else {
6537 		chk->pr_sctp_on = 0;
6538 	}
6539 	if (sp->msg_is_complete && (sp->length == 0) && (sp->sender_all_done)) {
6540 		/* All done pull and kill the message */
6541 		atomic_subtract_int(&asoc->stream_queue_cnt, 1);
6542 		if (sp->put_last_out == 0) {
6543 			SCTP_PRINTF("Gak, put out entire msg with NO end!-2\n");
6544 			SCTP_PRINTF("sender_done:%d len:%d msg_comp:%d put_last_out:%d send_lock:%d\n",
6545 			    sp->sender_all_done,
6546 			    sp->length,
6547 			    sp->msg_is_complete,
6548 			    sp->put_last_out,
6549 			    send_lock_up);
6550 		}
6551 		if ((send_lock_up == 0) && (TAILQ_NEXT(sp, next) == NULL)) {
6552 			SCTP_TCB_SEND_LOCK(stcb);
6553 			send_lock_up = 1;
6554 		}
6555 		TAILQ_REMOVE(&strq->outqueue, sp, next);
6556 		sctp_free_remote_addr(sp->net);
6557 		if (sp->data) {
6558 			sctp_m_freem(sp->data);
6559 			sp->data = NULL;
6560 		}
6561 		sctp_free_a_strmoq(stcb, sp);
6562 
6563 		/* we can't be locked to it */
6564 		*locked = 0;
6565 		stcb->asoc.locked_on_sending = NULL;
6566 	} else {
6567 		/* more to go, we are locked */
6568 		*locked = 1;
6569 	}
6570 	asoc->chunks_on_out_queue++;
6571 	TAILQ_INSERT_TAIL(&asoc->send_queue, chk, sctp_next);
6572 	asoc->send_queue_cnt++;
6573 	if (send_lock_up) {
6574 		SCTP_TCB_SEND_UNLOCK(stcb);
6575 		send_lock_up = 0;
6576 	}
6577 	return (to_move);
6578 }
6579 
6580 
6581 static struct sctp_stream_out *
6582 sctp_select_a_stream(struct sctp_tcb *stcb, struct sctp_association *asoc)
6583 {
6584 	struct sctp_stream_out *strq;
6585 
6586 	/* Find the next stream to use */
6587 	if (asoc->last_out_stream == NULL) {
6588 		strq = asoc->last_out_stream = TAILQ_FIRST(&asoc->out_wheel);
6589 		if (asoc->last_out_stream == NULL) {
6590 			/* huh nothing on the wheel, TSNH */
6591 			return (NULL);
6592 		}
6593 		goto done_it;
6594 	}
6595 	strq = TAILQ_NEXT(asoc->last_out_stream, next_spoke);
6596 done_it:
6597 	if (strq == NULL) {
6598 		strq = asoc->last_out_stream = TAILQ_FIRST(&asoc->out_wheel);
6599 	}
6600 	/* Save off the last stream */
6601 	asoc->last_out_stream = strq;
6602 	return (strq);
6603 
6604 }
6605 
6606 static void
6607 sctp_fill_outqueue(struct sctp_tcb *stcb,
6608     struct sctp_nets *net, int frag_point, int eeor_mode, int *quit_now)
6609 {
6610 	struct sctp_association *asoc;
6611 	struct sctp_stream_out *strq, *strqn, *strqt;
6612 	int goal_mtu, moved_how_much, total_moved = 0, bail = 0;
6613 	int locked, giveup;
6614 	struct sctp_stream_queue_pending *sp;
6615 
6616 	SCTP_TCB_LOCK_ASSERT(stcb);
6617 	asoc = &stcb->asoc;
6618 #ifdef INET6
6619 	if (net->ro._l_addr.sin6.sin6_family == AF_INET6) {
6620 		goal_mtu = net->mtu - SCTP_MIN_OVERHEAD;
6621 	} else {
6622 		/* ?? not sure what else to do */
6623 		goal_mtu = net->mtu - SCTP_MIN_V4_OVERHEAD;
6624 	}
6625 #else
6626 	goal_mtu = net->mtu - SCTP_MIN_OVERHEAD;
6627 	mtu_fromwheel = 0;
6628 #endif
6629 	/* Need an allowance for the data chunk header too */
6630 	goal_mtu -= sizeof(struct sctp_data_chunk);
6631 
6632 	/* must make even word boundary */
6633 	goal_mtu &= 0xfffffffc;
6634 	if (asoc->locked_on_sending) {
6635 		/* We are stuck on one stream until the message completes. */
6636 		strqn = strq = asoc->locked_on_sending;
6637 		locked = 1;
6638 	} else {
6639 		strqn = strq = sctp_select_a_stream(stcb, asoc);
6640 		locked = 0;
6641 	}
6642 
6643 	while ((goal_mtu > 0) && strq) {
6644 		sp = TAILQ_FIRST(&strq->outqueue);
6645 		/*
6646 		 * If CMT is off, we must validate that the stream in
6647 		 * question has the first item pointed towards are network
6648 		 * destionation requested by the caller. Note that if we
6649 		 * turn out to be locked to a stream (assigning TSN's then
6650 		 * we must stop, since we cannot look for another stream
6651 		 * with data to send to that destination). In CMT's case, by
6652 		 * skipping this check, we will send one data packet towards
6653 		 * the requested net.
6654 		 */
6655 		if (sp == NULL) {
6656 			break;
6657 		}
6658 		if ((sp->net != net) && (sctp_cmt_on_off == 0)) {
6659 			/* none for this network */
6660 			if (locked) {
6661 				break;
6662 			} else {
6663 				strq = sctp_select_a_stream(stcb, asoc);
6664 				if (strq == NULL)
6665 					/* none left */
6666 					break;
6667 				if (strqn == strq) {
6668 					/* I have circled */
6669 					break;
6670 				}
6671 				continue;
6672 			}
6673 		}
6674 		giveup = 0;
6675 		bail = 0;
6676 		moved_how_much = sctp_move_to_outqueue(stcb, net, strq, goal_mtu, frag_point, &locked,
6677 		    &giveup, eeor_mode, &bail);
6678 		asoc->last_out_stream = strq;
6679 		if (locked) {
6680 			asoc->locked_on_sending = strq;
6681 			if ((moved_how_much == 0) || (giveup) || bail)
6682 				/* no more to move for now */
6683 				break;
6684 		} else {
6685 			asoc->locked_on_sending = NULL;
6686 			strqt = sctp_select_a_stream(stcb, asoc);
6687 			if (TAILQ_FIRST(&strq->outqueue) == NULL) {
6688 				if (strq == strqn) {
6689 					/* Must move start to next one */
6690 					strqn = TAILQ_NEXT(asoc->last_out_stream, next_spoke);
6691 					if (strqn == NULL) {
6692 						strqn = TAILQ_FIRST(&asoc->out_wheel);
6693 						if (strqn == NULL) {
6694 							break;
6695 						}
6696 					}
6697 				}
6698 				sctp_remove_from_wheel(stcb, asoc, strq);
6699 			}
6700 			if ((giveup) || bail) {
6701 				break;
6702 			}
6703 			strq = strqt;
6704 			if (strq == NULL) {
6705 				break;
6706 			}
6707 		}
6708 		total_moved += moved_how_much;
6709 		goal_mtu -= (moved_how_much + sizeof(struct sctp_data_chunk));
6710 		goal_mtu &= 0xfffffffc;
6711 	}
6712 	if (bail)
6713 		*quit_now = 1;
6714 
6715 	if (total_moved == 0) {
6716 		if ((sctp_cmt_on_off == 0) &&
6717 		    (net == stcb->asoc.primary_destination)) {
6718 			/* ran dry for primary network net */
6719 			SCTP_STAT_INCR(sctps_primary_randry);
6720 		} else if (sctp_cmt_on_off) {
6721 			/* ran dry with CMT on */
6722 			SCTP_STAT_INCR(sctps_cmt_randry);
6723 		}
6724 	}
6725 }
6726 
6727 void
6728 sctp_fix_ecn_echo(struct sctp_association *asoc)
6729 {
6730 	struct sctp_tmit_chunk *chk;
6731 
6732 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
6733 		if (chk->rec.chunk_id.id == SCTP_ECN_ECHO) {
6734 			chk->sent = SCTP_DATAGRAM_UNSENT;
6735 		}
6736 	}
6737 }
6738 
6739 static void
6740 sctp_move_to_an_alt(struct sctp_tcb *stcb,
6741     struct sctp_association *asoc,
6742     struct sctp_nets *net)
6743 {
6744 	struct sctp_tmit_chunk *chk;
6745 	struct sctp_nets *a_net;
6746 
6747 	SCTP_TCB_LOCK_ASSERT(stcb);
6748 	/*
6749 	 * JRS 5/14/07 - If CMT PF is turned on, find an alternate
6750 	 * destination using the PF algorithm for finding alternate
6751 	 * destinations.
6752 	 */
6753 	if (sctp_cmt_on_off && sctp_cmt_pf) {
6754 		a_net = sctp_find_alternate_net(stcb, net, 2);
6755 	} else {
6756 		a_net = sctp_find_alternate_net(stcb, net, 0);
6757 	}
6758 	if ((a_net != net) &&
6759 	    ((a_net->dest_state & SCTP_ADDR_REACHABLE) == SCTP_ADDR_REACHABLE)) {
6760 		/*
6761 		 * We only proceed if a valid alternate is found that is not
6762 		 * this one and is reachable. Here we must move all chunks
6763 		 * queued in the send queue off of the destination address
6764 		 * to our alternate.
6765 		 */
6766 		TAILQ_FOREACH(chk, &asoc->send_queue, sctp_next) {
6767 			if (chk->whoTo == net) {
6768 				/* Move the chunk to our alternate */
6769 				sctp_free_remote_addr(chk->whoTo);
6770 				chk->whoTo = a_net;
6771 				atomic_add_int(&a_net->ref_count, 1);
6772 			}
6773 		}
6774 	}
6775 }
6776 
6777 int
6778 sctp_med_chunk_output(struct sctp_inpcb *inp,
6779     struct sctp_tcb *stcb,
6780     struct sctp_association *asoc,
6781     int *num_out,
6782     int *reason_code,
6783     int control_only, int *cwnd_full, int from_where,
6784     struct timeval *now, int *now_filled, int frag_point)
6785 {
6786 	/*
6787 	 * Ok this is the generic chunk service queue. we must do the
6788 	 * following: - Service the stream queue that is next, moving any
6789 	 * message (note I must get a complete message i.e. FIRST/MIDDLE and
6790 	 * LAST to the out queue in one pass) and assigning TSN's - Check to
6791 	 * see if the cwnd/rwnd allows any output, if so we go ahead and
6792 	 * fomulate and send the low level chunks. Making sure to combine
6793 	 * any control in the control chunk queue also.
6794 	 */
6795 	struct sctp_nets *net;
6796 	struct mbuf *outchain, *endoutchain;
6797 	struct sctp_tmit_chunk *chk, *nchk;
6798 	struct sctphdr *shdr;
6799 
6800 	/* temp arrays for unlinking */
6801 	struct sctp_tmit_chunk *data_list[SCTP_MAX_DATA_BUNDLING];
6802 	int no_fragmentflg, error;
6803 	int one_chunk, hbflag, skip_data_for_this_net;
6804 	int asconf, cookie, no_out_cnt;
6805 	int bundle_at, ctl_cnt, no_data_chunks, cwnd_full_ind, eeor_mode;
6806 	unsigned int mtu, r_mtu, omtu, mx_mtu, to_out;
6807 	struct sctp_nets *start_at, *old_startat = NULL, *send_start_at;
6808 	int tsns_sent = 0;
6809 	uint32_t auth_offset = 0;
6810 	struct sctp_auth_chunk *auth = NULL;
6811 
6812 	/*
6813 	 * JRS 5/14/07 - Add flag for whether a heartbeat is sent to the
6814 	 * destination.
6815 	 */
6816 	int pf_hbflag = 0;
6817 	int quit_now = 0;
6818 
6819 	*num_out = 0;
6820 	cwnd_full_ind = 0;
6821 
6822 	if ((asoc->state & SCTP_STATE_SHUTDOWN_PENDING) ||
6823 	    (asoc->state & SCTP_STATE_SHUTDOWN_RECEIVED) ||
6824 	    (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_EXPLICIT_EOR))) {
6825 		eeor_mode = 1;
6826 	} else {
6827 		eeor_mode = 0;
6828 	}
6829 	ctl_cnt = no_out_cnt = asconf = cookie = 0;
6830 	/*
6831 	 * First lets prime the pump. For each destination, if there is room
6832 	 * in the flight size, attempt to pull an MTU's worth out of the
6833 	 * stream queues into the general send_queue
6834 	 */
6835 #ifdef SCTP_AUDITING_ENABLED
6836 	sctp_audit_log(0xC2, 2);
6837 #endif
6838 	SCTP_TCB_LOCK_ASSERT(stcb);
6839 	hbflag = 0;
6840 	if ((control_only) || (asoc->stream_reset_outstanding))
6841 		no_data_chunks = 1;
6842 	else
6843 		no_data_chunks = 0;
6844 
6845 	/* Nothing to possible to send? */
6846 	if (TAILQ_EMPTY(&asoc->control_send_queue) &&
6847 	    TAILQ_EMPTY(&asoc->send_queue) &&
6848 	    TAILQ_EMPTY(&asoc->out_wheel)) {
6849 		*reason_code = 9;
6850 		return (0);
6851 	}
6852 	if (asoc->peers_rwnd == 0) {
6853 		/* No room in peers rwnd */
6854 		*cwnd_full = 1;
6855 		*reason_code = 1;
6856 		if (asoc->total_flight > 0) {
6857 			/* we are allowed one chunk in flight */
6858 			no_data_chunks = 1;
6859 		}
6860 	}
6861 	if ((no_data_chunks == 0) && (!TAILQ_EMPTY(&asoc->out_wheel))) {
6862 		if (sctp_cmt_on_off) {
6863 			/*
6864 			 * for CMT we start at the next one past the one we
6865 			 * last added data to.
6866 			 */
6867 			if (TAILQ_FIRST(&asoc->send_queue) != NULL) {
6868 				goto skip_the_fill_from_streams;
6869 			}
6870 			if (asoc->last_net_data_came_from) {
6871 				net = TAILQ_NEXT(asoc->last_net_data_came_from, sctp_next);
6872 				if (net == NULL) {
6873 					net = TAILQ_FIRST(&asoc->nets);
6874 				}
6875 			} else {
6876 				/* back to start */
6877 				net = TAILQ_FIRST(&asoc->nets);
6878 			}
6879 
6880 		} else {
6881 			net = asoc->primary_destination;
6882 			if (net == NULL) {
6883 				/* TSNH */
6884 				net = TAILQ_FIRST(&asoc->nets);
6885 			}
6886 		}
6887 		start_at = net;
6888 one_more_time:
6889 		for (; net != NULL; net = TAILQ_NEXT(net, sctp_next)) {
6890 			net->window_probe = 0;
6891 			if (old_startat && (old_startat == net)) {
6892 				break;
6893 			}
6894 			if ((sctp_cmt_on_off == 0) && (net->ref_count < 2)) {
6895 				/* nothing can be in queue for this guy */
6896 				continue;
6897 			}
6898 			if (net->flight_size >= net->cwnd) {
6899 				/* skip this network, no room */
6900 				cwnd_full_ind++;
6901 				continue;
6902 			}
6903 			/*
6904 			 * @@@ JRI : this for loop we are in takes in each
6905 			 * net, if its's got space in cwnd and has data sent
6906 			 * to it (when CMT is off) then it calls
6907 			 * sctp_fill_outqueue for the net. This gets data on
6908 			 * the send queue for that network.
6909 			 *
6910 			 * In sctp_fill_outqueue TSN's are assigned and data is
6911 			 * copied out of the stream buffers. Note mostly
6912 			 * copy by reference (we hope).
6913 			 */
6914 			if (sctp_logging_level & SCTP_CWND_LOGGING_ENABLE) {
6915 				sctp_log_cwnd(stcb, net, 0, SCTP_CWND_LOG_FILL_OUTQ_CALLED);
6916 			}
6917 			sctp_fill_outqueue(stcb, net, frag_point, eeor_mode, &quit_now);
6918 			if (quit_now) {
6919 				/* memory alloc failure */
6920 				no_data_chunks = 1;
6921 				goto skip_the_fill_from_streams;
6922 			}
6923 		}
6924 		if (start_at != TAILQ_FIRST(&asoc->nets)) {
6925 			/* got to pick up the beginning stuff. */
6926 			old_startat = start_at;
6927 			start_at = net = TAILQ_FIRST(&asoc->nets);
6928 			if (old_startat)
6929 				goto one_more_time;
6930 		}
6931 	}
6932 skip_the_fill_from_streams:
6933 	*cwnd_full = cwnd_full_ind;
6934 	/* now service each destination and send out what we can for it */
6935 	/* Nothing to send? */
6936 	if ((TAILQ_FIRST(&asoc->control_send_queue) == NULL) &&
6937 	    (TAILQ_FIRST(&asoc->send_queue) == NULL)) {
6938 		*reason_code = 8;
6939 		return (0);
6940 	}
6941 	if (no_data_chunks) {
6942 		chk = TAILQ_FIRST(&asoc->control_send_queue);
6943 	} else {
6944 		chk = TAILQ_FIRST(&asoc->send_queue);
6945 	}
6946 	if (chk) {
6947 		send_start_at = chk->whoTo;
6948 	} else {
6949 		send_start_at = TAILQ_FIRST(&asoc->nets);
6950 	}
6951 	old_startat = NULL;
6952 again_one_more_time:
6953 	for (net = send_start_at; net != NULL; net = TAILQ_NEXT(net, sctp_next)) {
6954 		/* how much can we send? */
6955 		/* SCTPDBG("Examine for sending net:%x\n", (uint32_t)net); */
6956 		if (old_startat && (old_startat == net)) {
6957 			/* through list ocmpletely. */
6958 			break;
6959 		}
6960 		tsns_sent = 0;
6961 		if (net->ref_count < 2) {
6962 			/*
6963 			 * Ref-count of 1 so we cannot have data or control
6964 			 * queued to this address. Skip it.
6965 			 */
6966 			continue;
6967 		}
6968 		ctl_cnt = bundle_at = 0;
6969 		endoutchain = outchain = NULL;
6970 		no_fragmentflg = 1;
6971 		one_chunk = 0;
6972 		if (net->dest_state & SCTP_ADDR_UNCONFIRMED) {
6973 			skip_data_for_this_net = 1;
6974 		} else {
6975 			skip_data_for_this_net = 0;
6976 		}
6977 		if ((net->ro.ro_rt) && (net->ro.ro_rt->rt_ifp)) {
6978 			/*
6979 			 * if we have a route and an ifp check to see if we
6980 			 * have room to send to this guy
6981 			 */
6982 			struct ifnet *ifp;
6983 
6984 			ifp = net->ro.ro_rt->rt_ifp;
6985 			if ((ifp->if_snd.ifq_len + 2) >= ifp->if_snd.ifq_maxlen) {
6986 				SCTP_STAT_INCR(sctps_ifnomemqueued);
6987 				if (sctp_logging_level & SCTP_LOG_MAXBURST_ENABLE) {
6988 					sctp_log_maxburst(stcb, net, ifp->if_snd.ifq_len, ifp->if_snd.ifq_maxlen, SCTP_MAX_IFP_APPLIED);
6989 				}
6990 				continue;
6991 			}
6992 		}
6993 		if (((struct sockaddr *)&net->ro._l_addr)->sa_family == AF_INET) {
6994 			mtu = net->mtu - (sizeof(struct ip) + sizeof(struct sctphdr));
6995 		} else {
6996 			mtu = net->mtu - (sizeof(struct ip6_hdr) + sizeof(struct sctphdr));
6997 		}
6998 		mx_mtu = mtu;
6999 		to_out = 0;
7000 		if (mtu > asoc->peers_rwnd) {
7001 			if (asoc->total_flight > 0) {
7002 				/* We have a packet in flight somewhere */
7003 				r_mtu = asoc->peers_rwnd;
7004 			} else {
7005 				/* We are always allowed to send one MTU out */
7006 				one_chunk = 1;
7007 				r_mtu = mtu;
7008 			}
7009 		} else {
7010 			r_mtu = mtu;
7011 		}
7012 		/************************/
7013 		/* Control transmission */
7014 		/************************/
7015 		/* Now first lets go through the control queue */
7016 		for (chk = TAILQ_FIRST(&asoc->control_send_queue);
7017 		    chk; chk = nchk) {
7018 			nchk = TAILQ_NEXT(chk, sctp_next);
7019 			if (chk->whoTo != net) {
7020 				/*
7021 				 * No, not sent to the network we are
7022 				 * looking at
7023 				 */
7024 				continue;
7025 			}
7026 			if (chk->data == NULL) {
7027 				continue;
7028 			}
7029 			if (chk->sent != SCTP_DATAGRAM_UNSENT) {
7030 				/*
7031 				 * It must be unsent. Cookies and ASCONF's
7032 				 * hang around but there timers will force
7033 				 * when marked for resend.
7034 				 */
7035 				continue;
7036 			}
7037 			/*
7038 			 * if no AUTH is yet included and this chunk
7039 			 * requires it, make sure to account for it.  We
7040 			 * don't apply the size until the AUTH chunk is
7041 			 * actually added below in case there is no room for
7042 			 * this chunk. NOTE: we overload the use of "omtu"
7043 			 * here
7044 			 */
7045 			if ((auth == NULL) &&
7046 			    sctp_auth_is_required_chunk(chk->rec.chunk_id.id,
7047 			    stcb->asoc.peer_auth_chunks)) {
7048 				omtu = sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
7049 			} else
7050 				omtu = 0;
7051 			/* Here we do NOT factor the r_mtu */
7052 			if ((chk->send_size < (int)(mtu - omtu)) ||
7053 			    (chk->flags & CHUNK_FLAGS_FRAGMENT_OK)) {
7054 				/*
7055 				 * We probably should glom the mbuf chain
7056 				 * from the chk->data for control but the
7057 				 * problem is it becomes yet one more level
7058 				 * of tracking to do if for some reason
7059 				 * output fails. Then I have got to
7060 				 * reconstruct the merged control chain.. el
7061 				 * yucko.. for now we take the easy way and
7062 				 * do the copy
7063 				 */
7064 				/*
7065 				 * Add an AUTH chunk, if chunk requires it
7066 				 * save the offset into the chain for AUTH
7067 				 */
7068 				if ((auth == NULL) &&
7069 				    (sctp_auth_is_required_chunk(chk->rec.chunk_id.id,
7070 				    stcb->asoc.peer_auth_chunks))) {
7071 					outchain = sctp_add_auth_chunk(outchain,
7072 					    &endoutchain,
7073 					    &auth,
7074 					    &auth_offset,
7075 					    stcb,
7076 					    chk->rec.chunk_id.id);
7077 					SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
7078 				}
7079 				outchain = sctp_copy_mbufchain(chk->data, outchain, &endoutchain,
7080 				    (int)chk->rec.chunk_id.can_take_data,
7081 				    chk->send_size, chk->copy_by_ref);
7082 				if (outchain == NULL) {
7083 					*reason_code = 8;
7084 					SCTP_LTRACE_ERR(inp, stcb, ENOMEM, 0);
7085 					return (ENOMEM);
7086 				}
7087 				SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
7088 				/* update our MTU size */
7089 				if (mtu > (chk->send_size + omtu))
7090 					mtu -= (chk->send_size + omtu);
7091 				else
7092 					mtu = 0;
7093 				to_out += (chk->send_size + omtu);
7094 				/* Do clear IP_DF ? */
7095 				if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
7096 					no_fragmentflg = 0;
7097 				}
7098 				if (chk->rec.chunk_id.can_take_data)
7099 					chk->data = NULL;
7100 				/* Mark things to be removed, if needed */
7101 				if ((chk->rec.chunk_id.id == SCTP_SELECTIVE_ACK) ||
7102 				    (chk->rec.chunk_id.id == SCTP_HEARTBEAT_REQUEST) ||
7103 				    (chk->rec.chunk_id.id == SCTP_HEARTBEAT_ACK) ||
7104 				    (chk->rec.chunk_id.id == SCTP_SHUTDOWN) ||
7105 				    (chk->rec.chunk_id.id == SCTP_SHUTDOWN_ACK) ||
7106 				    (chk->rec.chunk_id.id == SCTP_OPERATION_ERROR) ||
7107 				    (chk->rec.chunk_id.id == SCTP_COOKIE_ACK) ||
7108 				    (chk->rec.chunk_id.id == SCTP_ECN_CWR) ||
7109 				    (chk->rec.chunk_id.id == SCTP_PACKET_DROPPED) ||
7110 				    (chk->rec.chunk_id.id == SCTP_ASCONF_ACK)) {
7111 
7112 					if (chk->rec.chunk_id.id == SCTP_HEARTBEAT_REQUEST) {
7113 						hbflag = 1;
7114 						/*
7115 						 * JRS 5/14/07 - Set the
7116 						 * flag to say a heartbeat
7117 						 * is being sent.
7118 						 */
7119 						pf_hbflag = 1;
7120 					}
7121 					/* remove these chunks at the end */
7122 					if (chk->rec.chunk_id.id == SCTP_SELECTIVE_ACK) {
7123 						/* turn off the timer */
7124 						if (SCTP_OS_TIMER_PENDING(&stcb->asoc.dack_timer.timer)) {
7125 							sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
7126 							    inp, stcb, net, SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_1);
7127 						}
7128 					}
7129 					ctl_cnt++;
7130 				} else {
7131 					/*
7132 					 * Other chunks, since they have
7133 					 * timers running (i.e. COOKIE or
7134 					 * ASCONF) we just "trust" that it
7135 					 * gets sent or retransmitted.
7136 					 */
7137 					ctl_cnt++;
7138 					if (chk->rec.chunk_id.id == SCTP_COOKIE_ECHO) {
7139 						cookie = 1;
7140 						no_out_cnt = 1;
7141 					} else if (chk->rec.chunk_id.id == SCTP_ASCONF) {
7142 						/*
7143 						 * set hb flag since we can
7144 						 * use these for RTO
7145 						 */
7146 						hbflag = 1;
7147 						asconf = 1;
7148 					}
7149 					chk->sent = SCTP_DATAGRAM_SENT;
7150 					chk->snd_count++;
7151 				}
7152 				if (mtu == 0) {
7153 					/*
7154 					 * Ok we are out of room but we can
7155 					 * output without effecting the
7156 					 * flight size since this little guy
7157 					 * is a control only packet.
7158 					 */
7159 					if (asconf) {
7160 						sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp, stcb, net);
7161 						asconf = 0;
7162 					}
7163 					if (cookie) {
7164 						sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, inp, stcb, net);
7165 						cookie = 0;
7166 					}
7167 					SCTP_BUF_PREPEND(outchain, sizeof(struct sctphdr), M_DONTWAIT);
7168 					if (outchain == NULL) {
7169 						/* no memory */
7170 						error = ENOBUFS;
7171 						goto error_out_again;
7172 					}
7173 					shdr = mtod(outchain, struct sctphdr *);
7174 					shdr->src_port = inp->sctp_lport;
7175 					shdr->dest_port = stcb->rport;
7176 					shdr->v_tag = htonl(stcb->asoc.peer_vtag);
7177 					shdr->checksum = 0;
7178 					auth_offset += sizeof(struct sctphdr);
7179 					if ((error = sctp_lowlevel_chunk_output(inp, stcb, net,
7180 					    (struct sockaddr *)&net->ro._l_addr,
7181 					    outchain, auth_offset, auth,
7182 					    no_fragmentflg, 0, NULL, asconf))) {
7183 						if (error == ENOBUFS) {
7184 							asoc->ifp_had_enobuf = 1;
7185 							SCTP_STAT_INCR(sctps_lowlevelerr);
7186 						}
7187 						if (from_where == 0) {
7188 							SCTP_STAT_INCR(sctps_lowlevelerrusr);
7189 						}
7190 				error_out_again:
7191 						/* error, could not output */
7192 						if (hbflag) {
7193 							if (*now_filled == 0) {
7194 								(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
7195 								*now_filled = 1;
7196 								*now = net->last_sent_time;
7197 							} else {
7198 								net->last_sent_time = *now;
7199 							}
7200 							hbflag = 0;
7201 						}
7202 						if (error == EHOSTUNREACH) {
7203 							/*
7204 							 * Destination went
7205 							 * unreachable
7206 							 * during this send
7207 							 */
7208 							sctp_move_to_an_alt(stcb, asoc, net);
7209 						}
7210 						*reason_code = 7;
7211 						continue;
7212 					} else
7213 						asoc->ifp_had_enobuf = 0;
7214 					/* Only HB or ASCONF advances time */
7215 					if (hbflag) {
7216 						if (*now_filled == 0) {
7217 							(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
7218 							*now_filled = 1;
7219 							*now = net->last_sent_time;
7220 						} else {
7221 							net->last_sent_time = *now;
7222 						}
7223 						hbflag = 0;
7224 					}
7225 					/*
7226 					 * increase the number we sent, if a
7227 					 * cookie is sent we don't tell them
7228 					 * any was sent out.
7229 					 */
7230 					outchain = endoutchain = NULL;
7231 					auth = NULL;
7232 					auth_offset = 0;
7233 					if (!no_out_cnt)
7234 						*num_out += ctl_cnt;
7235 					/* recalc a clean slate and setup */
7236 					if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
7237 						mtu = (net->mtu - SCTP_MIN_OVERHEAD);
7238 					} else {
7239 						mtu = (net->mtu - SCTP_MIN_V4_OVERHEAD);
7240 					}
7241 					to_out = 0;
7242 					no_fragmentflg = 1;
7243 				}
7244 			}
7245 		}
7246 		/*********************/
7247 		/* Data transmission */
7248 		/*********************/
7249 		/*
7250 		 * if AUTH for DATA is required and no AUTH has been added
7251 		 * yet, account for this in the mtu now... if no data can be
7252 		 * bundled, this adjustment won't matter anyways since the
7253 		 * packet will be going out...
7254 		 */
7255 		if ((auth == NULL) &&
7256 		    sctp_auth_is_required_chunk(SCTP_DATA,
7257 		    stcb->asoc.peer_auth_chunks)) {
7258 			mtu -= sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
7259 		}
7260 		/* now lets add any data within the MTU constraints */
7261 		if (((struct sockaddr *)&net->ro._l_addr)->sa_family == AF_INET) {
7262 			if (net->mtu > (sizeof(struct ip) + sizeof(struct sctphdr)))
7263 				omtu = net->mtu - (sizeof(struct ip) + sizeof(struct sctphdr));
7264 			else
7265 				omtu = 0;
7266 		} else {
7267 			if (net->mtu > (sizeof(struct ip6_hdr) + sizeof(struct sctphdr)))
7268 				omtu = net->mtu - (sizeof(struct ip6_hdr) + sizeof(struct sctphdr));
7269 			else
7270 				omtu = 0;
7271 		}
7272 		if ((((asoc->state & SCTP_STATE_OPEN) == SCTP_STATE_OPEN) && (skip_data_for_this_net == 0)) ||
7273 		    (cookie)) {
7274 			for (chk = TAILQ_FIRST(&asoc->send_queue); chk; chk = nchk) {
7275 				if (no_data_chunks) {
7276 					/* let only control go out */
7277 					*reason_code = 1;
7278 					break;
7279 				}
7280 				if (net->flight_size >= net->cwnd) {
7281 					/* skip this net, no room for data */
7282 					*reason_code = 2;
7283 					break;
7284 				}
7285 				nchk = TAILQ_NEXT(chk, sctp_next);
7286 				if (chk->whoTo != net) {
7287 					/* No, not sent to this net */
7288 					continue;
7289 				}
7290 				if ((chk->send_size > omtu) && ((chk->flags & CHUNK_FLAGS_FRAGMENT_OK) == 0)) {
7291 					/*-
7292 					 * strange, we have a chunk that is
7293 					 * to big for its destination and
7294 					 * yet no fragment ok flag.
7295 					 * Something went wrong when the
7296 					 * PMTU changed...we did not mark
7297 					 * this chunk for some reason?? I
7298 					 * will fix it here by letting IP
7299 					 * fragment it for now and printing
7300 					 * a warning. This really should not
7301 					 * happen ...
7302 					 */
7303 					SCTP_PRINTF("Warning chunk of %d bytes > mtu:%d and yet PMTU disc missed\n",
7304 					    chk->send_size, mtu);
7305 					chk->flags |= CHUNK_FLAGS_FRAGMENT_OK;
7306 				}
7307 				if (((chk->send_size <= mtu) && (chk->send_size <= r_mtu)) ||
7308 				    ((chk->flags & CHUNK_FLAGS_FRAGMENT_OK) && (chk->send_size <= asoc->peers_rwnd))) {
7309 					/* ok we will add this one */
7310 
7311 					/*
7312 					 * Add an AUTH chunk, if chunk
7313 					 * requires it, save the offset into
7314 					 * the chain for AUTH
7315 					 */
7316 					if ((auth == NULL) &&
7317 					    (sctp_auth_is_required_chunk(SCTP_DATA,
7318 					    stcb->asoc.peer_auth_chunks))) {
7319 
7320 						outchain = sctp_add_auth_chunk(outchain,
7321 						    &endoutchain,
7322 						    &auth,
7323 						    &auth_offset,
7324 						    stcb,
7325 						    SCTP_DATA);
7326 						SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
7327 					}
7328 					outchain = sctp_copy_mbufchain(chk->data, outchain, &endoutchain, 0,
7329 					    chk->send_size, chk->copy_by_ref);
7330 					if (outchain == NULL) {
7331 						SCTPDBG(SCTP_DEBUG_OUTPUT3, "No memory?\n");
7332 						if (!SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer)) {
7333 							sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
7334 						}
7335 						*reason_code = 3;
7336 						SCTP_LTRACE_ERR(inp, stcb, ENOMEM, 0);
7337 						return (ENOMEM);
7338 					}
7339 					/* upate our MTU size */
7340 					/* Do clear IP_DF ? */
7341 					if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
7342 						no_fragmentflg = 0;
7343 					}
7344 					/* unsigned subtraction of mtu */
7345 					if (mtu > chk->send_size)
7346 						mtu -= chk->send_size;
7347 					else
7348 						mtu = 0;
7349 					/* unsigned subtraction of r_mtu */
7350 					if (r_mtu > chk->send_size)
7351 						r_mtu -= chk->send_size;
7352 					else
7353 						r_mtu = 0;
7354 
7355 					to_out += chk->send_size;
7356 					if ((to_out > mx_mtu) && no_fragmentflg) {
7357 #ifdef INVARIANTS
7358 						panic("Exceeding mtu of %d out size is %d", mx_mtu, to_out);
7359 #else
7360 						SCTP_PRINTF("Exceeding mtu of %d out size is %d\n",
7361 						    mx_mtu, to_out);
7362 #endif
7363 					}
7364 					chk->window_probe = 0;
7365 					data_list[bundle_at++] = chk;
7366 					if (bundle_at >= SCTP_MAX_DATA_BUNDLING) {
7367 						mtu = 0;
7368 						break;
7369 					}
7370 					if (chk->sent == SCTP_DATAGRAM_UNSENT) {
7371 						if ((chk->rec.data.rcv_flags & SCTP_DATA_UNORDERED) == 0) {
7372 							SCTP_STAT_INCR_COUNTER64(sctps_outorderchunks);
7373 						} else {
7374 							SCTP_STAT_INCR_COUNTER64(sctps_outunorderchunks);
7375 						}
7376 						if (((chk->rec.data.rcv_flags & SCTP_DATA_LAST_FRAG) == SCTP_DATA_LAST_FRAG) &&
7377 						    ((chk->rec.data.rcv_flags & SCTP_DATA_FIRST_FRAG) == 0))
7378 							/*
7379 							 * Count number of
7380 							 * user msg's that
7381 							 * were fragmented
7382 							 * we do this by
7383 							 * counting when we
7384 							 * see a LAST
7385 							 * fragment only.
7386 							 */
7387 							SCTP_STAT_INCR_COUNTER64(sctps_fragusrmsgs);
7388 					}
7389 					if ((mtu == 0) || (r_mtu == 0) || (one_chunk)) {
7390 						if (one_chunk) {
7391 							data_list[0]->window_probe = 1;
7392 							net->window_probe = 1;
7393 						}
7394 						break;
7395 					}
7396 				} else {
7397 					/*
7398 					 * Must be sent in order of the
7399 					 * TSN's (on a network)
7400 					 */
7401 					break;
7402 				}
7403 			}	/* for (chunk gather loop for this net) */
7404 		}		/* if asoc.state OPEN */
7405 		/* Is there something to send for this destination? */
7406 		if (outchain) {
7407 			/* We may need to start a control timer or two */
7408 			if (asconf) {
7409 				sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp, stcb, net);
7410 				asconf = 0;
7411 			}
7412 			if (cookie) {
7413 				sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, inp, stcb, net);
7414 				cookie = 0;
7415 			}
7416 			/* must start a send timer if data is being sent */
7417 			if (bundle_at && (!SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer))) {
7418 				/*
7419 				 * no timer running on this destination
7420 				 * restart it.
7421 				 */
7422 				sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
7423 			} else if (sctp_cmt_on_off && sctp_cmt_pf && pf_hbflag && ((net->dest_state & SCTP_ADDR_PF) == SCTP_ADDR_PF)
7424 			    && (!SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer))) {
7425 				/*
7426 				 * JRS 5/14/07 - If a HB has been sent to a
7427 				 * PF destination and no T3 timer is
7428 				 * currently running, start the T3 timer to
7429 				 * track the HBs that were sent.
7430 				 */
7431 				sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
7432 			}
7433 			/* Now send it, if there is anything to send :> */
7434 			SCTP_BUF_PREPEND(outchain, sizeof(struct sctphdr), M_DONTWAIT);
7435 			if (outchain == NULL) {
7436 				/* out of mbufs */
7437 				error = ENOBUFS;
7438 				goto errored_send;
7439 			}
7440 			shdr = mtod(outchain, struct sctphdr *);
7441 			shdr->src_port = inp->sctp_lport;
7442 			shdr->dest_port = stcb->rport;
7443 			shdr->v_tag = htonl(stcb->asoc.peer_vtag);
7444 			shdr->checksum = 0;
7445 			auth_offset += sizeof(struct sctphdr);
7446 			if ((error = sctp_lowlevel_chunk_output(inp,
7447 			    stcb,
7448 			    net,
7449 			    (struct sockaddr *)&net->ro._l_addr,
7450 			    outchain,
7451 			    auth_offset,
7452 			    auth,
7453 			    no_fragmentflg,
7454 			    bundle_at,
7455 			    data_list[0],
7456 			    asconf))) {
7457 				/* error, we could not output */
7458 				if (error == ENOBUFS) {
7459 					SCTP_STAT_INCR(sctps_lowlevelerr);
7460 					asoc->ifp_had_enobuf = 1;
7461 				}
7462 				if (from_where == 0) {
7463 					SCTP_STAT_INCR(sctps_lowlevelerrusr);
7464 				}
7465 		errored_send:
7466 				SCTPDBG(SCTP_DEBUG_OUTPUT3, "Gak send error %d\n", error);
7467 				if (hbflag) {
7468 					if (*now_filled == 0) {
7469 						(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
7470 						*now_filled = 1;
7471 						*now = net->last_sent_time;
7472 					} else {
7473 						net->last_sent_time = *now;
7474 					}
7475 					hbflag = 0;
7476 				}
7477 				if (error == EHOSTUNREACH) {
7478 					/*
7479 					 * Destination went unreachable
7480 					 * during this send
7481 					 */
7482 					sctp_move_to_an_alt(stcb, asoc, net);
7483 				}
7484 				*reason_code = 6;
7485 				/*-
7486 				 * I add this line to be paranoid. As far as
7487 				 * I can tell the continue, takes us back to
7488 				 * the top of the for, but just to make sure
7489 				 * I will reset these again here.
7490 				 */
7491 				ctl_cnt = bundle_at = 0;
7492 				continue;	/* This takes us back to the
7493 						 * for() for the nets. */
7494 			} else {
7495 				asoc->ifp_had_enobuf = 0;
7496 			}
7497 			outchain = endoutchain = NULL;
7498 			auth = NULL;
7499 			auth_offset = 0;
7500 			if (bundle_at || hbflag) {
7501 				/* For data/asconf and hb set time */
7502 				if (*now_filled == 0) {
7503 					(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
7504 					*now_filled = 1;
7505 					*now = net->last_sent_time;
7506 				} else {
7507 					net->last_sent_time = *now;
7508 				}
7509 			}
7510 			if (!no_out_cnt) {
7511 				*num_out += (ctl_cnt + bundle_at);
7512 			}
7513 			if (bundle_at) {
7514 				/* setup for a RTO measurement */
7515 				tsns_sent = data_list[0]->rec.data.TSN_seq;
7516 				/* fill time if not already filled */
7517 				if (*now_filled == 0) {
7518 					(void)SCTP_GETTIME_TIMEVAL(&asoc->time_last_sent);
7519 					*now_filled = 1;
7520 					*now = asoc->time_last_sent;
7521 				} else {
7522 					asoc->time_last_sent = *now;
7523 				}
7524 				data_list[0]->do_rtt = 1;
7525 				SCTP_STAT_INCR_BY(sctps_senddata, bundle_at);
7526 				sctp_clean_up_datalist(stcb, asoc, data_list, bundle_at, net);
7527 				if (sctp_early_fr) {
7528 					if (net->flight_size < net->cwnd) {
7529 						/* start or restart it */
7530 						if (SCTP_OS_TIMER_PENDING(&net->fr_timer.timer)) {
7531 							sctp_timer_stop(SCTP_TIMER_TYPE_EARLYFR, inp, stcb, net,
7532 							    SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_2);
7533 						}
7534 						SCTP_STAT_INCR(sctps_earlyfrstrout);
7535 						sctp_timer_start(SCTP_TIMER_TYPE_EARLYFR, inp, stcb, net);
7536 					} else {
7537 						/* stop it if its running */
7538 						if (SCTP_OS_TIMER_PENDING(&net->fr_timer.timer)) {
7539 							SCTP_STAT_INCR(sctps_earlyfrstpout);
7540 							sctp_timer_stop(SCTP_TIMER_TYPE_EARLYFR, inp, stcb, net,
7541 							    SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_3);
7542 						}
7543 					}
7544 				}
7545 			}
7546 			if (one_chunk) {
7547 				break;
7548 			}
7549 		}
7550 		if (sctp_logging_level & SCTP_CWND_LOGGING_ENABLE) {
7551 			sctp_log_cwnd(stcb, net, tsns_sent, SCTP_CWND_LOG_FROM_SEND);
7552 		}
7553 	}
7554 	if (old_startat == NULL) {
7555 		old_startat = send_start_at;
7556 		send_start_at = TAILQ_FIRST(&asoc->nets);
7557 		if (old_startat)
7558 			goto again_one_more_time;
7559 	}
7560 	/*
7561 	 * At the end there should be no NON timed chunks hanging on this
7562 	 * queue.
7563 	 */
7564 	if (sctp_logging_level & SCTP_CWND_LOGGING_ENABLE) {
7565 		sctp_log_cwnd(stcb, net, *num_out, SCTP_CWND_LOG_FROM_SEND);
7566 	}
7567 	if ((*num_out == 0) && (*reason_code == 0)) {
7568 		*reason_code = 4;
7569 	} else {
7570 		*reason_code = 5;
7571 	}
7572 	sctp_clean_up_ctl(stcb, asoc);
7573 	return (0);
7574 }
7575 
7576 void
7577 sctp_queue_op_err(struct sctp_tcb *stcb, struct mbuf *op_err)
7578 {
7579 	/*-
7580 	 * Prepend a OPERATIONAL_ERROR chunk header and put on the end of
7581 	 * the control chunk queue.
7582 	 */
7583 	struct sctp_chunkhdr *hdr;
7584 	struct sctp_tmit_chunk *chk;
7585 	struct mbuf *mat;
7586 
7587 	SCTP_TCB_LOCK_ASSERT(stcb);
7588 	sctp_alloc_a_chunk(stcb, chk);
7589 	if (chk == NULL) {
7590 		/* no memory */
7591 		sctp_m_freem(op_err);
7592 		return;
7593 	}
7594 	chk->copy_by_ref = 0;
7595 	SCTP_BUF_PREPEND(op_err, sizeof(struct sctp_chunkhdr), M_DONTWAIT);
7596 	if (op_err == NULL) {
7597 		sctp_free_a_chunk(stcb, chk);
7598 		return;
7599 	}
7600 	chk->send_size = 0;
7601 	mat = op_err;
7602 	while (mat != NULL) {
7603 		chk->send_size += SCTP_BUF_LEN(mat);
7604 		mat = SCTP_BUF_NEXT(mat);
7605 	}
7606 	chk->rec.chunk_id.id = SCTP_OPERATION_ERROR;
7607 	chk->rec.chunk_id.can_take_data = 1;
7608 	chk->sent = SCTP_DATAGRAM_UNSENT;
7609 	chk->snd_count = 0;
7610 	chk->flags = 0;
7611 	chk->asoc = &stcb->asoc;
7612 	chk->data = op_err;
7613 	chk->whoTo = chk->asoc->primary_destination;
7614 	atomic_add_int(&chk->whoTo->ref_count, 1);
7615 	hdr = mtod(op_err, struct sctp_chunkhdr *);
7616 	hdr->chunk_type = SCTP_OPERATION_ERROR;
7617 	hdr->chunk_flags = 0;
7618 	hdr->chunk_length = htons(chk->send_size);
7619 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue,
7620 	    chk,
7621 	    sctp_next);
7622 	chk->asoc->ctrl_queue_cnt++;
7623 }
7624 
7625 int
7626 sctp_send_cookie_echo(struct mbuf *m,
7627     int offset,
7628     struct sctp_tcb *stcb,
7629     struct sctp_nets *net)
7630 {
7631 	/*-
7632 	 * pull out the cookie and put it at the front of the control chunk
7633 	 * queue.
7634 	 */
7635 	int at;
7636 	struct mbuf *cookie;
7637 	struct sctp_paramhdr parm, *phdr;
7638 	struct sctp_chunkhdr *hdr;
7639 	struct sctp_tmit_chunk *chk;
7640 	uint16_t ptype, plen;
7641 
7642 	/* First find the cookie in the param area */
7643 	cookie = NULL;
7644 	at = offset + sizeof(struct sctp_init_chunk);
7645 
7646 	SCTP_TCB_LOCK_ASSERT(stcb);
7647 	do {
7648 		phdr = sctp_get_next_param(m, at, &parm, sizeof(parm));
7649 		if (phdr == NULL) {
7650 			return (-3);
7651 		}
7652 		ptype = ntohs(phdr->param_type);
7653 		plen = ntohs(phdr->param_length);
7654 		if (ptype == SCTP_STATE_COOKIE) {
7655 			int pad;
7656 
7657 			/* found the cookie */
7658 			if ((pad = (plen % 4))) {
7659 				plen += 4 - pad;
7660 			}
7661 			cookie = SCTP_M_COPYM(m, at, plen, M_DONTWAIT);
7662 			if (cookie == NULL) {
7663 				/* No memory */
7664 				return (-2);
7665 			}
7666 			break;
7667 		}
7668 		at += SCTP_SIZE32(plen);
7669 	} while (phdr);
7670 	if (cookie == NULL) {
7671 		/* Did not find the cookie */
7672 		return (-3);
7673 	}
7674 	/* ok, we got the cookie lets change it into a cookie echo chunk */
7675 
7676 	/* first the change from param to cookie */
7677 	hdr = mtod(cookie, struct sctp_chunkhdr *);
7678 	hdr->chunk_type = SCTP_COOKIE_ECHO;
7679 	hdr->chunk_flags = 0;
7680 	/* get the chunk stuff now and place it in the FRONT of the queue */
7681 	sctp_alloc_a_chunk(stcb, chk);
7682 	if (chk == NULL) {
7683 		/* no memory */
7684 		sctp_m_freem(cookie);
7685 		return (-5);
7686 	}
7687 	chk->copy_by_ref = 0;
7688 	chk->send_size = plen;
7689 	chk->rec.chunk_id.id = SCTP_COOKIE_ECHO;
7690 	chk->rec.chunk_id.can_take_data = 0;
7691 	chk->sent = SCTP_DATAGRAM_UNSENT;
7692 	chk->snd_count = 0;
7693 	chk->flags = 0;
7694 	chk->asoc = &stcb->asoc;
7695 	chk->data = cookie;
7696 	chk->whoTo = chk->asoc->primary_destination;
7697 	atomic_add_int(&chk->whoTo->ref_count, 1);
7698 	TAILQ_INSERT_HEAD(&chk->asoc->control_send_queue, chk, sctp_next);
7699 	chk->asoc->ctrl_queue_cnt++;
7700 	return (0);
7701 }
7702 
7703 void
7704 sctp_send_heartbeat_ack(struct sctp_tcb *stcb,
7705     struct mbuf *m,
7706     int offset,
7707     int chk_length,
7708     struct sctp_nets *net)
7709 {
7710 	/*
7711 	 * take a HB request and make it into a HB ack and send it.
7712 	 */
7713 	struct mbuf *outchain;
7714 	struct sctp_chunkhdr *chdr;
7715 	struct sctp_tmit_chunk *chk;
7716 
7717 
7718 	if (net == NULL)
7719 		/* must have a net pointer */
7720 		return;
7721 
7722 	outchain = SCTP_M_COPYM(m, offset, chk_length, M_DONTWAIT);
7723 	if (outchain == NULL) {
7724 		/* gak out of memory */
7725 		return;
7726 	}
7727 	chdr = mtod(outchain, struct sctp_chunkhdr *);
7728 	chdr->chunk_type = SCTP_HEARTBEAT_ACK;
7729 	chdr->chunk_flags = 0;
7730 	if (chk_length % 4) {
7731 		/* need pad */
7732 		uint32_t cpthis = 0;
7733 		int padlen;
7734 
7735 		padlen = 4 - (chk_length % 4);
7736 		m_copyback(outchain, chk_length, padlen, (caddr_t)&cpthis);
7737 	}
7738 	sctp_alloc_a_chunk(stcb, chk);
7739 	if (chk == NULL) {
7740 		/* no memory */
7741 		sctp_m_freem(outchain);
7742 		return;
7743 	}
7744 	chk->copy_by_ref = 0;
7745 	chk->send_size = chk_length;
7746 	chk->rec.chunk_id.id = SCTP_HEARTBEAT_ACK;
7747 	chk->rec.chunk_id.can_take_data = 1;
7748 	chk->sent = SCTP_DATAGRAM_UNSENT;
7749 	chk->snd_count = 0;
7750 	chk->flags = 0;
7751 	chk->asoc = &stcb->asoc;
7752 	chk->data = outchain;
7753 	chk->whoTo = net;
7754 	atomic_add_int(&chk->whoTo->ref_count, 1);
7755 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
7756 	chk->asoc->ctrl_queue_cnt++;
7757 }
7758 
7759 void
7760 sctp_send_cookie_ack(struct sctp_tcb *stcb)
7761 {
7762 	/* formulate and queue a cookie-ack back to sender */
7763 	struct mbuf *cookie_ack;
7764 	struct sctp_chunkhdr *hdr;
7765 	struct sctp_tmit_chunk *chk;
7766 
7767 	cookie_ack = NULL;
7768 	SCTP_TCB_LOCK_ASSERT(stcb);
7769 
7770 	cookie_ack = sctp_get_mbuf_for_msg(sizeof(struct sctp_chunkhdr), 0, M_DONTWAIT, 1, MT_HEADER);
7771 	if (cookie_ack == NULL) {
7772 		/* no mbuf's */
7773 		return;
7774 	}
7775 	SCTP_BUF_RESV_UF(cookie_ack, SCTP_MIN_OVERHEAD);
7776 	sctp_alloc_a_chunk(stcb, chk);
7777 	if (chk == NULL) {
7778 		/* no memory */
7779 		sctp_m_freem(cookie_ack);
7780 		return;
7781 	}
7782 	chk->copy_by_ref = 0;
7783 	chk->send_size = sizeof(struct sctp_chunkhdr);
7784 	chk->rec.chunk_id.id = SCTP_COOKIE_ACK;
7785 	chk->rec.chunk_id.can_take_data = 1;
7786 	chk->sent = SCTP_DATAGRAM_UNSENT;
7787 	chk->snd_count = 0;
7788 	chk->flags = 0;
7789 	chk->asoc = &stcb->asoc;
7790 	chk->data = cookie_ack;
7791 	if (chk->asoc->last_control_chunk_from != NULL) {
7792 		chk->whoTo = chk->asoc->last_control_chunk_from;
7793 	} else {
7794 		chk->whoTo = chk->asoc->primary_destination;
7795 	}
7796 	atomic_add_int(&chk->whoTo->ref_count, 1);
7797 	hdr = mtod(cookie_ack, struct sctp_chunkhdr *);
7798 	hdr->chunk_type = SCTP_COOKIE_ACK;
7799 	hdr->chunk_flags = 0;
7800 	hdr->chunk_length = htons(chk->send_size);
7801 	SCTP_BUF_LEN(cookie_ack) = chk->send_size;
7802 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
7803 	chk->asoc->ctrl_queue_cnt++;
7804 	return;
7805 }
7806 
7807 
7808 void
7809 sctp_send_shutdown_ack(struct sctp_tcb *stcb, struct sctp_nets *net)
7810 {
7811 	/* formulate and queue a SHUTDOWN-ACK back to the sender */
7812 	struct mbuf *m_shutdown_ack;
7813 	struct sctp_shutdown_ack_chunk *ack_cp;
7814 	struct sctp_tmit_chunk *chk;
7815 
7816 	m_shutdown_ack = sctp_get_mbuf_for_msg(sizeof(struct sctp_shutdown_ack_chunk), 0, M_DONTWAIT, 1, MT_HEADER);
7817 	if (m_shutdown_ack == NULL) {
7818 		/* no mbuf's */
7819 		return;
7820 	}
7821 	SCTP_BUF_RESV_UF(m_shutdown_ack, SCTP_MIN_OVERHEAD);
7822 	sctp_alloc_a_chunk(stcb, chk);
7823 	if (chk == NULL) {
7824 		/* no memory */
7825 		sctp_m_freem(m_shutdown_ack);
7826 		return;
7827 	}
7828 	chk->copy_by_ref = 0;
7829 
7830 	chk->send_size = sizeof(struct sctp_chunkhdr);
7831 	chk->rec.chunk_id.id = SCTP_SHUTDOWN_ACK;
7832 	chk->rec.chunk_id.can_take_data = 1;
7833 	chk->sent = SCTP_DATAGRAM_UNSENT;
7834 	chk->snd_count = 0;
7835 	chk->flags = 0;
7836 	chk->asoc = &stcb->asoc;
7837 	chk->data = m_shutdown_ack;
7838 	chk->whoTo = net;
7839 	atomic_add_int(&net->ref_count, 1);
7840 
7841 	ack_cp = mtod(m_shutdown_ack, struct sctp_shutdown_ack_chunk *);
7842 	ack_cp->ch.chunk_type = SCTP_SHUTDOWN_ACK;
7843 	ack_cp->ch.chunk_flags = 0;
7844 	ack_cp->ch.chunk_length = htons(chk->send_size);
7845 	SCTP_BUF_LEN(m_shutdown_ack) = chk->send_size;
7846 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
7847 	chk->asoc->ctrl_queue_cnt++;
7848 	return;
7849 }
7850 
7851 void
7852 sctp_send_shutdown(struct sctp_tcb *stcb, struct sctp_nets *net)
7853 {
7854 	/* formulate and queue a SHUTDOWN to the sender */
7855 	struct mbuf *m_shutdown;
7856 	struct sctp_shutdown_chunk *shutdown_cp;
7857 	struct sctp_tmit_chunk *chk;
7858 
7859 	m_shutdown = sctp_get_mbuf_for_msg(sizeof(struct sctp_shutdown_chunk), 0, M_DONTWAIT, 1, MT_HEADER);
7860 	if (m_shutdown == NULL) {
7861 		/* no mbuf's */
7862 		return;
7863 	}
7864 	SCTP_BUF_RESV_UF(m_shutdown, SCTP_MIN_OVERHEAD);
7865 	sctp_alloc_a_chunk(stcb, chk);
7866 	if (chk == NULL) {
7867 		/* no memory */
7868 		sctp_m_freem(m_shutdown);
7869 		return;
7870 	}
7871 	chk->copy_by_ref = 0;
7872 	chk->send_size = sizeof(struct sctp_shutdown_chunk);
7873 	chk->rec.chunk_id.id = SCTP_SHUTDOWN;
7874 	chk->rec.chunk_id.can_take_data = 1;
7875 	chk->sent = SCTP_DATAGRAM_UNSENT;
7876 	chk->snd_count = 0;
7877 	chk->flags = 0;
7878 	chk->asoc = &stcb->asoc;
7879 	chk->data = m_shutdown;
7880 	chk->whoTo = net;
7881 	atomic_add_int(&net->ref_count, 1);
7882 
7883 	shutdown_cp = mtod(m_shutdown, struct sctp_shutdown_chunk *);
7884 	shutdown_cp->ch.chunk_type = SCTP_SHUTDOWN;
7885 	shutdown_cp->ch.chunk_flags = 0;
7886 	shutdown_cp->ch.chunk_length = htons(chk->send_size);
7887 	shutdown_cp->cumulative_tsn_ack = htonl(stcb->asoc.cumulative_tsn);
7888 	SCTP_BUF_LEN(m_shutdown) = chk->send_size;
7889 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
7890 	chk->asoc->ctrl_queue_cnt++;
7891 	return;
7892 }
7893 
7894 void
7895 sctp_send_asconf(struct sctp_tcb *stcb, struct sctp_nets *net)
7896 {
7897 	/*
7898 	 * formulate and queue an ASCONF to the peer ASCONF parameters
7899 	 * should be queued on the assoc queue
7900 	 */
7901 	struct sctp_tmit_chunk *chk;
7902 	struct mbuf *m_asconf;
7903 	struct sctp_asconf_chunk *acp;
7904 	int len;
7905 
7906 
7907 	SCTP_TCB_LOCK_ASSERT(stcb);
7908 	/* compose an ASCONF chunk, maximum length is PMTU */
7909 	m_asconf = sctp_compose_asconf(stcb, &len);
7910 	if (m_asconf == NULL) {
7911 		return;
7912 	}
7913 	acp = mtod(m_asconf, struct sctp_asconf_chunk *);
7914 	sctp_alloc_a_chunk(stcb, chk);
7915 	if (chk == NULL) {
7916 		/* no memory */
7917 		sctp_m_freem(m_asconf);
7918 		return;
7919 	}
7920 	chk->copy_by_ref = 0;
7921 	chk->data = m_asconf;
7922 	chk->send_size = len;
7923 	chk->rec.chunk_id.id = SCTP_ASCONF;
7924 	chk->rec.chunk_id.can_take_data = 0;
7925 	chk->sent = SCTP_DATAGRAM_UNSENT;
7926 	chk->snd_count = 0;
7927 	chk->flags = 0;
7928 	chk->asoc = &stcb->asoc;
7929 	chk->whoTo = chk->asoc->primary_destination;
7930 	atomic_add_int(&chk->whoTo->ref_count, 1);
7931 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
7932 	chk->asoc->ctrl_queue_cnt++;
7933 	return;
7934 }
7935 
7936 void
7937 sctp_send_asconf_ack(struct sctp_tcb *stcb, uint32_t retrans)
7938 {
7939 	/*
7940 	 * formulate and queue a asconf-ack back to sender the asconf-ack
7941 	 * must be stored in the tcb
7942 	 */
7943 	struct sctp_tmit_chunk *chk;
7944 	struct mbuf *m_ack, *m;
7945 
7946 	SCTP_TCB_LOCK_ASSERT(stcb);
7947 	/* is there a asconf-ack mbuf chain to send? */
7948 	if (stcb->asoc.last_asconf_ack_sent == NULL) {
7949 		return;
7950 	}
7951 	/* copy the asconf_ack */
7952 	m_ack = SCTP_M_COPYM(stcb->asoc.last_asconf_ack_sent, 0, M_COPYALL, M_DONTWAIT);
7953 	if (m_ack == NULL) {
7954 		/* couldn't copy it */
7955 
7956 		return;
7957 	}
7958 	sctp_alloc_a_chunk(stcb, chk);
7959 	if (chk == NULL) {
7960 		/* no memory */
7961 		if (m_ack)
7962 			sctp_m_freem(m_ack);
7963 		return;
7964 	}
7965 	chk->copy_by_ref = 0;
7966 	/* figure out where it goes to */
7967 	if (retrans) {
7968 		/* we're doing a retransmission */
7969 		if (stcb->asoc.used_alt_asconfack > 2) {
7970 			/* tried alternate nets already, go back */
7971 			chk->whoTo = NULL;
7972 		} else {
7973 			/* need to try and alternate net */
7974 			chk->whoTo = sctp_find_alternate_net(stcb, stcb->asoc.last_control_chunk_from, 0);
7975 			stcb->asoc.used_alt_asconfack++;
7976 		}
7977 		if (chk->whoTo == NULL) {
7978 			/* no alternate */
7979 			if (stcb->asoc.last_control_chunk_from == NULL)
7980 				chk->whoTo = stcb->asoc.primary_destination;
7981 			else
7982 				chk->whoTo = stcb->asoc.last_control_chunk_from;
7983 			stcb->asoc.used_alt_asconfack = 0;
7984 		}
7985 	} else {
7986 		/* normal case */
7987 		if (stcb->asoc.last_control_chunk_from == NULL)
7988 			chk->whoTo = stcb->asoc.primary_destination;
7989 		else
7990 			chk->whoTo = stcb->asoc.last_control_chunk_from;
7991 		stcb->asoc.used_alt_asconfack = 0;
7992 	}
7993 	chk->data = m_ack;
7994 	chk->send_size = 0;
7995 	/* Get size */
7996 	m = m_ack;
7997 	while (m) {
7998 		chk->send_size += SCTP_BUF_LEN(m);
7999 		m = SCTP_BUF_NEXT(m);
8000 	}
8001 	chk->rec.chunk_id.id = SCTP_ASCONF_ACK;
8002 	chk->rec.chunk_id.can_take_data = 1;
8003 	chk->sent = SCTP_DATAGRAM_UNSENT;
8004 	chk->snd_count = 0;
8005 	chk->flags = 0;
8006 	chk->asoc = &stcb->asoc;
8007 	atomic_add_int(&chk->whoTo->ref_count, 1);
8008 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
8009 	chk->asoc->ctrl_queue_cnt++;
8010 	return;
8011 }
8012 
8013 
8014 static int
8015 sctp_chunk_retransmission(struct sctp_inpcb *inp,
8016     struct sctp_tcb *stcb,
8017     struct sctp_association *asoc,
8018     int *cnt_out, struct timeval *now, int *now_filled, int *fr_done)
8019 {
8020 	/*-
8021 	 * send out one MTU of retransmission. If fast_retransmit is
8022 	 * happening we ignore the cwnd. Otherwise we obey the cwnd and
8023 	 * rwnd. For a Cookie or Asconf in the control chunk queue we
8024 	 * retransmit them by themselves.
8025 	 *
8026 	 * For data chunks we will pick out the lowest TSN's in the sent_queue
8027 	 * marked for resend and bundle them all together (up to a MTU of
8028 	 * destination). The address to send to should have been
8029 	 * selected/changed where the retransmission was marked (i.e. in FR
8030 	 * or t3-timeout routines).
8031 	 */
8032 	struct sctp_tmit_chunk *data_list[SCTP_MAX_DATA_BUNDLING];
8033 	struct sctp_tmit_chunk *chk, *fwd;
8034 	struct mbuf *m, *endofchain;
8035 	struct sctphdr *shdr;
8036 	int asconf;
8037 	struct sctp_nets *net;
8038 	uint32_t tsns_sent = 0;
8039 	int no_fragmentflg, bundle_at, cnt_thru;
8040 	unsigned int mtu;
8041 	int error, i, one_chunk, fwd_tsn, ctl_cnt, tmr_started;
8042 	struct sctp_auth_chunk *auth = NULL;
8043 	uint32_t auth_offset = 0;
8044 	uint32_t dmtu = 0;
8045 
8046 	SCTP_TCB_LOCK_ASSERT(stcb);
8047 	tmr_started = ctl_cnt = bundle_at = error = 0;
8048 	no_fragmentflg = 1;
8049 	asconf = 0;
8050 	fwd_tsn = 0;
8051 	*cnt_out = 0;
8052 	fwd = NULL;
8053 	endofchain = m = NULL;
8054 #ifdef SCTP_AUDITING_ENABLED
8055 	sctp_audit_log(0xC3, 1);
8056 #endif
8057 	if ((TAILQ_EMPTY(&asoc->sent_queue)) &&
8058 	    (TAILQ_EMPTY(&asoc->control_send_queue))) {
8059 		SCTPDBG(SCTP_DEBUG_OUTPUT1, "SCTP hits empty queue with cnt set to %d?\n",
8060 		    asoc->sent_queue_retran_cnt);
8061 		asoc->sent_queue_cnt = 0;
8062 		asoc->sent_queue_cnt_removeable = 0;
8063 		/* send back 0/0 so we enter normal transmission */
8064 		*cnt_out = 0;
8065 		return (0);
8066 	}
8067 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
8068 		if ((chk->rec.chunk_id.id == SCTP_COOKIE_ECHO) ||
8069 		    (chk->rec.chunk_id.id == SCTP_ASCONF) ||
8070 		    (chk->rec.chunk_id.id == SCTP_STREAM_RESET) ||
8071 		    (chk->rec.chunk_id.id == SCTP_FORWARD_CUM_TSN)) {
8072 			if (chk->rec.chunk_id.id == SCTP_STREAM_RESET) {
8073 				if (chk != asoc->str_reset) {
8074 					/*
8075 					 * not eligible for retran if its
8076 					 * not ours
8077 					 */
8078 					continue;
8079 				}
8080 			}
8081 			ctl_cnt++;
8082 			if (chk->rec.chunk_id.id == SCTP_ASCONF) {
8083 				no_fragmentflg = 1;
8084 				asconf = 1;
8085 			}
8086 			if (chk->rec.chunk_id.id == SCTP_FORWARD_CUM_TSN) {
8087 				fwd_tsn = 1;
8088 				fwd = chk;
8089 			}
8090 			/*
8091 			 * Add an AUTH chunk, if chunk requires it save the
8092 			 * offset into the chain for AUTH
8093 			 */
8094 			if ((auth == NULL) &&
8095 			    (sctp_auth_is_required_chunk(chk->rec.chunk_id.id,
8096 			    stcb->asoc.peer_auth_chunks))) {
8097 				m = sctp_add_auth_chunk(m, &endofchain,
8098 				    &auth, &auth_offset,
8099 				    stcb,
8100 				    chk->rec.chunk_id.id);
8101 			}
8102 			m = sctp_copy_mbufchain(chk->data, m, &endofchain, 0, chk->send_size, chk->copy_by_ref);
8103 			break;
8104 		}
8105 	}
8106 	one_chunk = 0;
8107 	cnt_thru = 0;
8108 	/* do we have control chunks to retransmit? */
8109 	if (m != NULL) {
8110 		/* Start a timer no matter if we suceed or fail */
8111 		if (chk->rec.chunk_id.id == SCTP_COOKIE_ECHO) {
8112 			sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, inp, stcb, chk->whoTo);
8113 		} else if (chk->rec.chunk_id.id == SCTP_ASCONF)
8114 			sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp, stcb, chk->whoTo);
8115 
8116 		SCTP_BUF_PREPEND(m, sizeof(struct sctphdr), M_DONTWAIT);
8117 		if (m == NULL) {
8118 			return (ENOBUFS);
8119 		}
8120 		shdr = mtod(m, struct sctphdr *);
8121 		shdr->src_port = inp->sctp_lport;
8122 		shdr->dest_port = stcb->rport;
8123 		shdr->v_tag = htonl(stcb->asoc.peer_vtag);
8124 		shdr->checksum = 0;
8125 		auth_offset += sizeof(struct sctphdr);
8126 		chk->snd_count++;	/* update our count */
8127 
8128 		if ((error = sctp_lowlevel_chunk_output(inp, stcb, chk->whoTo,
8129 		    (struct sockaddr *)&chk->whoTo->ro._l_addr, m, auth_offset,
8130 		    auth, no_fragmentflg, 0, NULL, asconf))) {
8131 			SCTP_STAT_INCR(sctps_lowlevelerr);
8132 			return (error);
8133 		}
8134 		m = endofchain = NULL;
8135 		auth = NULL;
8136 		auth_offset = 0;
8137 		/*
8138 		 * We don't want to mark the net->sent time here since this
8139 		 * we use this for HB and retrans cannot measure RTT
8140 		 */
8141 		/* (void)SCTP_GETTIME_TIMEVAL(&chk->whoTo->last_sent_time); */
8142 		*cnt_out += 1;
8143 		chk->sent = SCTP_DATAGRAM_SENT;
8144 		sctp_ucount_decr(asoc->sent_queue_retran_cnt);
8145 		if (fwd_tsn == 0) {
8146 			return (0);
8147 		} else {
8148 			/* Clean up the fwd-tsn list */
8149 			sctp_clean_up_ctl(stcb, asoc);
8150 			return (0);
8151 		}
8152 	}
8153 	/*
8154 	 * Ok, it is just data retransmission we need to do or that and a
8155 	 * fwd-tsn with it all.
8156 	 */
8157 	if (TAILQ_EMPTY(&asoc->sent_queue)) {
8158 		return (SCTP_RETRAN_DONE);
8159 	}
8160 	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED) ||
8161 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT)) {
8162 		/* not yet open, resend the cookie and that is it */
8163 		return (1);
8164 	}
8165 #ifdef SCTP_AUDITING_ENABLED
8166 	sctp_auditing(20, inp, stcb, NULL);
8167 #endif
8168 	TAILQ_FOREACH(chk, &asoc->sent_queue, sctp_next) {
8169 		if (chk->sent != SCTP_DATAGRAM_RESEND) {
8170 			/* No, not sent to this net or not ready for rtx */
8171 			continue;
8172 		}
8173 		if ((sctp_max_retran_chunk) && (chk->snd_count >= sctp_max_retran_chunk)) {
8174 			/* Gak, we have exceeded max unlucky retran, abort! */
8175 			SCTP_PRINTF("Gak, chk->snd_count:%d >= max:%d - send abort\n",
8176 			    chk->snd_count,
8177 			    sctp_max_retran_chunk);
8178 			sctp_send_abort_tcb(stcb, NULL);
8179 			sctp_timer_start(SCTP_TIMER_TYPE_ASOCKILL, inp, stcb, NULL);
8180 			return (SCTP_RETRAN_EXIT);
8181 		}
8182 		/* pick up the net */
8183 		net = chk->whoTo;
8184 		if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
8185 			mtu = (net->mtu - SCTP_MIN_OVERHEAD);
8186 		} else {
8187 			mtu = net->mtu - SCTP_MIN_V4_OVERHEAD;
8188 		}
8189 
8190 		if ((asoc->peers_rwnd < mtu) && (asoc->total_flight > 0)) {
8191 			/* No room in peers rwnd */
8192 			uint32_t tsn;
8193 
8194 			tsn = asoc->last_acked_seq + 1;
8195 			if (tsn == chk->rec.data.TSN_seq) {
8196 				/*
8197 				 * we make a special exception for this
8198 				 * case. The peer has no rwnd but is missing
8199 				 * the lowest chunk.. which is probably what
8200 				 * is holding up the rwnd.
8201 				 */
8202 				goto one_chunk_around;
8203 			}
8204 			return (1);
8205 		}
8206 one_chunk_around:
8207 		if (asoc->peers_rwnd < mtu) {
8208 			one_chunk = 1;
8209 			if ((asoc->peers_rwnd == 0) &&
8210 			    (asoc->total_flight == 0)) {
8211 				chk->window_probe = 1;
8212 				chk->whoTo->window_probe = 1;
8213 			}
8214 		}
8215 #ifdef SCTP_AUDITING_ENABLED
8216 		sctp_audit_log(0xC3, 2);
8217 #endif
8218 		bundle_at = 0;
8219 		m = NULL;
8220 		net->fast_retran_ip = 0;
8221 		if (chk->rec.data.doing_fast_retransmit == 0) {
8222 			/*
8223 			 * if no FR in progress skip destination that have
8224 			 * flight_size > cwnd.
8225 			 */
8226 			if (net->flight_size >= net->cwnd) {
8227 				continue;
8228 			}
8229 		} else {
8230 			/*
8231 			 * Mark the destination net to have FR recovery
8232 			 * limits put on it.
8233 			 */
8234 			*fr_done = 1;
8235 			net->fast_retran_ip = 1;
8236 		}
8237 
8238 		/*
8239 		 * if no AUTH is yet included and this chunk requires it,
8240 		 * make sure to account for it.  We don't apply the size
8241 		 * until the AUTH chunk is actually added below in case
8242 		 * there is no room for this chunk.
8243 		 */
8244 		if ((auth == NULL) &&
8245 		    sctp_auth_is_required_chunk(SCTP_DATA,
8246 		    stcb->asoc.peer_auth_chunks)) {
8247 			dmtu = sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
8248 		} else
8249 			dmtu = 0;
8250 
8251 		if ((chk->send_size <= (mtu - dmtu)) ||
8252 		    (chk->flags & CHUNK_FLAGS_FRAGMENT_OK)) {
8253 			/* ok we will add this one */
8254 			if ((auth == NULL) &&
8255 			    (sctp_auth_is_required_chunk(SCTP_DATA,
8256 			    stcb->asoc.peer_auth_chunks))) {
8257 				m = sctp_add_auth_chunk(m, &endofchain,
8258 				    &auth, &auth_offset,
8259 				    stcb, SCTP_DATA);
8260 			}
8261 			m = sctp_copy_mbufchain(chk->data, m, &endofchain, 0, chk->send_size, chk->copy_by_ref);
8262 			if (m == NULL) {
8263 				SCTP_LTRACE_ERR(inp, stcb, ENOMEM, 0);
8264 				return (ENOMEM);
8265 			}
8266 			/* Do clear IP_DF ? */
8267 			if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
8268 				no_fragmentflg = 0;
8269 			}
8270 			/* upate our MTU size */
8271 			if (mtu > (chk->send_size + dmtu))
8272 				mtu -= (chk->send_size + dmtu);
8273 			else
8274 				mtu = 0;
8275 			data_list[bundle_at++] = chk;
8276 			if (one_chunk && (asoc->total_flight <= 0)) {
8277 				SCTP_STAT_INCR(sctps_windowprobed);
8278 			}
8279 		}
8280 		if (one_chunk == 0) {
8281 			/*
8282 			 * now are there anymore forward from chk to pick
8283 			 * up?
8284 			 */
8285 			fwd = TAILQ_NEXT(chk, sctp_next);
8286 			while (fwd) {
8287 				if (fwd->sent != SCTP_DATAGRAM_RESEND) {
8288 					/* Nope, not for retran */
8289 					fwd = TAILQ_NEXT(fwd, sctp_next);
8290 					continue;
8291 				}
8292 				if (fwd->whoTo != net) {
8293 					/* Nope, not the net in question */
8294 					fwd = TAILQ_NEXT(fwd, sctp_next);
8295 					continue;
8296 				}
8297 				if ((auth == NULL) &&
8298 				    sctp_auth_is_required_chunk(SCTP_DATA,
8299 				    stcb->asoc.peer_auth_chunks)) {
8300 					dmtu = sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
8301 				} else
8302 					dmtu = 0;
8303 				if (fwd->send_size <= (mtu - dmtu)) {
8304 					if ((auth == NULL) &&
8305 					    (sctp_auth_is_required_chunk(SCTP_DATA,
8306 					    stcb->asoc.peer_auth_chunks))) {
8307 						m = sctp_add_auth_chunk(m,
8308 						    &endofchain,
8309 						    &auth, &auth_offset,
8310 						    stcb,
8311 						    SCTP_DATA);
8312 					}
8313 					m = sctp_copy_mbufchain(fwd->data, m, &endofchain, 0, fwd->send_size, fwd->copy_by_ref);
8314 					if (m == NULL) {
8315 						SCTP_LTRACE_ERR(inp, stcb, ENOMEM, 0);
8316 						return (ENOMEM);
8317 					}
8318 					/* Do clear IP_DF ? */
8319 					if (fwd->flags & CHUNK_FLAGS_FRAGMENT_OK) {
8320 						no_fragmentflg = 0;
8321 					}
8322 					/* upate our MTU size */
8323 					if (mtu > (fwd->send_size + dmtu))
8324 						mtu -= (fwd->send_size + dmtu);
8325 					else
8326 						mtu = 0;
8327 					data_list[bundle_at++] = fwd;
8328 					if (bundle_at >= SCTP_MAX_DATA_BUNDLING) {
8329 						break;
8330 					}
8331 					fwd = TAILQ_NEXT(fwd, sctp_next);
8332 				} else {
8333 					/* can't fit so we are done */
8334 					break;
8335 				}
8336 			}
8337 		}
8338 		/* Is there something to send for this destination? */
8339 		if (m) {
8340 			/*
8341 			 * No matter if we fail/or suceed we should start a
8342 			 * timer. A failure is like a lost IP packet :-)
8343 			 */
8344 			if (!SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer)) {
8345 				/*
8346 				 * no timer running on this destination
8347 				 * restart it.
8348 				 */
8349 				sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
8350 				tmr_started = 1;
8351 			}
8352 			SCTP_BUF_PREPEND(m, sizeof(struct sctphdr), M_DONTWAIT);
8353 			if (m == NULL) {
8354 				return (ENOBUFS);
8355 			}
8356 			shdr = mtod(m, struct sctphdr *);
8357 			shdr->src_port = inp->sctp_lport;
8358 			shdr->dest_port = stcb->rport;
8359 			shdr->v_tag = htonl(stcb->asoc.peer_vtag);
8360 			shdr->checksum = 0;
8361 			auth_offset += sizeof(struct sctphdr);
8362 			/* Now lets send it, if there is anything to send :> */
8363 			if ((error = sctp_lowlevel_chunk_output(inp, stcb, net,
8364 			    (struct sockaddr *)&net->ro._l_addr, m, auth_offset,
8365 			    auth, no_fragmentflg, 0, NULL, asconf))) {
8366 				/* error, we could not output */
8367 				SCTP_STAT_INCR(sctps_lowlevelerr);
8368 				return (error);
8369 			}
8370 			m = endofchain = NULL;
8371 			auth = NULL;
8372 			auth_offset = 0;
8373 			/* For HB's */
8374 			/*
8375 			 * We don't want to mark the net->sent time here
8376 			 * since this we use this for HB and retrans cannot
8377 			 * measure RTT
8378 			 */
8379 			/* (void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time); */
8380 
8381 			/* For auto-close */
8382 			cnt_thru++;
8383 			if (*now_filled == 0) {
8384 				(void)SCTP_GETTIME_TIMEVAL(&asoc->time_last_sent);
8385 				*now = asoc->time_last_sent;
8386 				*now_filled = 1;
8387 			} else {
8388 				asoc->time_last_sent = *now;
8389 			}
8390 			*cnt_out += bundle_at;
8391 #ifdef SCTP_AUDITING_ENABLED
8392 			sctp_audit_log(0xC4, bundle_at);
8393 #endif
8394 			if (bundle_at) {
8395 				tsns_sent = data_list[0]->rec.data.TSN_seq;
8396 			}
8397 			for (i = 0; i < bundle_at; i++) {
8398 				SCTP_STAT_INCR(sctps_sendretransdata);
8399 				data_list[i]->sent = SCTP_DATAGRAM_SENT;
8400 				/*
8401 				 * When we have a revoked data, and we
8402 				 * retransmit it, then we clear the revoked
8403 				 * flag since this flag dictates if we
8404 				 * subtracted from the fs
8405 				 */
8406 				if (data_list[i]->rec.data.chunk_was_revoked) {
8407 					/* Deflate the cwnd */
8408 					data_list[i]->whoTo->cwnd -= data_list[i]->book_size;
8409 					data_list[i]->rec.data.chunk_was_revoked = 0;
8410 				}
8411 				data_list[i]->snd_count++;
8412 				sctp_ucount_decr(asoc->sent_queue_retran_cnt);
8413 				/* record the time */
8414 				data_list[i]->sent_rcv_time = asoc->time_last_sent;
8415 				if (data_list[i]->book_size_scale) {
8416 					/*
8417 					 * need to double the book size on
8418 					 * this one
8419 					 */
8420 					data_list[i]->book_size_scale = 0;
8421 					/*
8422 					 * Since we double the booksize, we
8423 					 * must also double the output queue
8424 					 * size, since this get shrunk when
8425 					 * we free by this amount.
8426 					 */
8427 					atomic_add_int(&((asoc)->total_output_queue_size), data_list[i]->book_size);
8428 					data_list[i]->book_size *= 2;
8429 
8430 
8431 				} else {
8432 					if (sctp_logging_level & SCTP_LOG_RWND_ENABLE) {
8433 						sctp_log_rwnd(SCTP_DECREASE_PEER_RWND,
8434 						    asoc->peers_rwnd, data_list[i]->send_size, sctp_peer_chunk_oh);
8435 					}
8436 					asoc->peers_rwnd = sctp_sbspace_sub(asoc->peers_rwnd,
8437 					    (uint32_t) (data_list[i]->send_size +
8438 					    sctp_peer_chunk_oh));
8439 				}
8440 				if (sctp_logging_level & SCTP_FLIGHT_LOGGING_ENABLE) {
8441 					sctp_misc_ints(SCTP_FLIGHT_LOG_UP_RSND,
8442 					    data_list[i]->whoTo->flight_size,
8443 					    data_list[i]->book_size,
8444 					    (uintptr_t) data_list[i]->whoTo,
8445 					    data_list[i]->rec.data.TSN_seq);
8446 				}
8447 				sctp_flight_size_increase(data_list[i]);
8448 				sctp_total_flight_increase(stcb, data_list[i]);
8449 				if (asoc->peers_rwnd < stcb->sctp_ep->sctp_ep.sctp_sws_sender) {
8450 					/* SWS sender side engages */
8451 					asoc->peers_rwnd = 0;
8452 				}
8453 				if ((i == 0) &&
8454 				    (data_list[i]->rec.data.doing_fast_retransmit)) {
8455 					SCTP_STAT_INCR(sctps_sendfastretrans);
8456 					if ((data_list[i] == TAILQ_FIRST(&asoc->sent_queue)) &&
8457 					    (tmr_started == 0)) {
8458 						/*-
8459 						 * ok we just fast-retrans'd
8460 						 * the lowest TSN, i.e the
8461 						 * first on the list. In
8462 						 * this case we want to give
8463 						 * some more time to get a
8464 						 * SACK back without a
8465 						 * t3-expiring.
8466 						 */
8467 						sctp_timer_stop(SCTP_TIMER_TYPE_SEND, inp, stcb, net,
8468 						    SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_4);
8469 						sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
8470 					}
8471 				}
8472 			}
8473 			if (sctp_logging_level & SCTP_CWND_LOGGING_ENABLE) {
8474 				sctp_log_cwnd(stcb, net, tsns_sent, SCTP_CWND_LOG_FROM_RESEND);
8475 			}
8476 #ifdef SCTP_AUDITING_ENABLED
8477 			sctp_auditing(21, inp, stcb, NULL);
8478 #endif
8479 		} else {
8480 			/* None will fit */
8481 			return (1);
8482 		}
8483 		if (asoc->sent_queue_retran_cnt <= 0) {
8484 			/* all done we have no more to retran */
8485 			asoc->sent_queue_retran_cnt = 0;
8486 			break;
8487 		}
8488 		if (one_chunk) {
8489 			/* No more room in rwnd */
8490 			return (1);
8491 		}
8492 		/* stop the for loop here. we sent out a packet */
8493 		break;
8494 	}
8495 	return (0);
8496 }
8497 
8498 
8499 static int
8500 sctp_timer_validation(struct sctp_inpcb *inp,
8501     struct sctp_tcb *stcb,
8502     struct sctp_association *asoc,
8503     int ret)
8504 {
8505 	struct sctp_nets *net;
8506 
8507 	/* Validate that a timer is running somewhere */
8508 	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
8509 		if (SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer)) {
8510 			/* Here is a timer */
8511 			return (ret);
8512 		}
8513 	}
8514 	SCTP_TCB_LOCK_ASSERT(stcb);
8515 	/* Gak, we did not have a timer somewhere */
8516 	SCTPDBG(SCTP_DEBUG_OUTPUT3, "Deadlock avoided starting timer on a dest at retran\n");
8517 	sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, asoc->primary_destination);
8518 	return (ret);
8519 }
8520 
8521 void
8522 sctp_chunk_output(struct sctp_inpcb *inp,
8523     struct sctp_tcb *stcb,
8524     int from_where)
8525 {
8526 	/*-
8527 	 * Ok this is the generic chunk service queue. we must do the
8528 	 * following:
8529 	 * - See if there are retransmits pending, if so we must
8530 	 *   do these first.
8531 	 * - Service the stream queue that is next, moving any
8532 	 *   message (note I must get a complete message i.e.
8533 	 *   FIRST/MIDDLE and LAST to the out queue in one pass) and assigning
8534 	 *   TSN's
8535 	 * - Check to see if the cwnd/rwnd allows any output, if so we
8536 	 *   go ahead and fomulate and send the low level chunks. Making sure
8537 	 *   to combine any control in the control chunk queue also.
8538 	 */
8539 	struct sctp_association *asoc;
8540 	struct sctp_nets *net;
8541 	int error = 0, num_out = 0, tot_out = 0, ret = 0, reason_code = 0,
8542 	    burst_cnt = 0, burst_limit = 0;
8543 	struct timeval now;
8544 	int now_filled = 0;
8545 	int cwnd_full = 0;
8546 	int nagle_on = 0;
8547 	int frag_point = sctp_get_frag_point(stcb, &stcb->asoc);
8548 	int un_sent = 0;
8549 	int fr_done, tot_frs = 0;
8550 
8551 	asoc = &stcb->asoc;
8552 	if (from_where == SCTP_OUTPUT_FROM_USR_SEND) {
8553 		if (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_NODELAY)) {
8554 			nagle_on = 0;
8555 		} else {
8556 			nagle_on = 1;
8557 		}
8558 	}
8559 	SCTP_TCB_LOCK_ASSERT(stcb);
8560 
8561 	un_sent = (stcb->asoc.total_output_queue_size - stcb->asoc.total_flight);
8562 
8563 	if ((un_sent <= 0) &&
8564 	    (TAILQ_EMPTY(&asoc->control_send_queue)) &&
8565 	    (asoc->sent_queue_retran_cnt == 0)) {
8566 		/* Nothing to do unless there is something to be sent left */
8567 		return;
8568 	}
8569 	/*
8570 	 * Do we have something to send, data or control AND a sack timer
8571 	 * running, if so piggy-back the sack.
8572 	 */
8573 	if (SCTP_OS_TIMER_PENDING(&stcb->asoc.dack_timer.timer)) {
8574 		sctp_send_sack(stcb);
8575 		(void)SCTP_OS_TIMER_STOP(&stcb->asoc.dack_timer.timer);
8576 	}
8577 	while (asoc->sent_queue_retran_cnt) {
8578 		/*-
8579 		 * Ok, it is retransmission time only, we send out only ONE
8580 		 * packet with a single call off to the retran code.
8581 		 */
8582 		if (from_where == SCTP_OUTPUT_FROM_COOKIE_ACK) {
8583 			/*-
8584 			 * Special hook for handling cookiess discarded
8585 			 * by peer that carried data. Send cookie-ack only
8586 			 * and then the next call with get the retran's.
8587 			 */
8588 			(void)sctp_med_chunk_output(inp, stcb, asoc, &num_out, &reason_code, 1,
8589 			    &cwnd_full, from_where,
8590 			    &now, &now_filled, frag_point);
8591 			return;
8592 		} else if (from_where != SCTP_OUTPUT_FROM_HB_TMR) {
8593 			/* if its not from a HB then do it */
8594 			fr_done = 0;
8595 			ret = sctp_chunk_retransmission(inp, stcb, asoc, &num_out, &now, &now_filled, &fr_done);
8596 			if (fr_done) {
8597 				tot_frs++;
8598 			}
8599 		} else {
8600 			/*
8601 			 * its from any other place, we don't allow retran
8602 			 * output (only control)
8603 			 */
8604 			ret = 1;
8605 		}
8606 		if (ret > 0) {
8607 			/* Can't send anymore */
8608 			/*-
8609 			 * now lets push out control by calling med-level
8610 			 * output once. this assures that we WILL send HB's
8611 			 * if queued too.
8612 			 */
8613 			(void)sctp_med_chunk_output(inp, stcb, asoc, &num_out, &reason_code, 1,
8614 			    &cwnd_full, from_where,
8615 			    &now, &now_filled, frag_point);
8616 #ifdef SCTP_AUDITING_ENABLED
8617 			sctp_auditing(8, inp, stcb, NULL);
8618 #endif
8619 			(void)sctp_timer_validation(inp, stcb, asoc, ret);
8620 			return;
8621 		}
8622 		if (ret < 0) {
8623 			/*-
8624 			 * The count was off.. retran is not happening so do
8625 			 * the normal retransmission.
8626 			 */
8627 #ifdef SCTP_AUDITING_ENABLED
8628 			sctp_auditing(9, inp, stcb, NULL);
8629 #endif
8630 			if (ret == SCTP_RETRAN_EXIT) {
8631 				return;
8632 			}
8633 			break;
8634 		}
8635 		if (from_where == SCTP_OUTPUT_FROM_T3) {
8636 			/* Only one transmission allowed out of a timeout */
8637 #ifdef SCTP_AUDITING_ENABLED
8638 			sctp_auditing(10, inp, stcb, NULL);
8639 #endif
8640 			/* Push out any control */
8641 			(void)sctp_med_chunk_output(inp, stcb, asoc, &num_out, &reason_code, 1, &cwnd_full, from_where,
8642 			    &now, &now_filled, frag_point);
8643 			return;
8644 		}
8645 		if (tot_frs > asoc->max_burst) {
8646 			/* Hit FR burst limit */
8647 			return;
8648 		}
8649 		if ((num_out == 0) && (ret == 0)) {
8650 
8651 			/* No more retrans to send */
8652 			break;
8653 		}
8654 	}
8655 #ifdef SCTP_AUDITING_ENABLED
8656 	sctp_auditing(12, inp, stcb, NULL);
8657 #endif
8658 	/* Check for bad destinations, if they exist move chunks around. */
8659 	burst_limit = asoc->max_burst;
8660 	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
8661 		if ((net->dest_state & SCTP_ADDR_NOT_REACHABLE) ==
8662 		    SCTP_ADDR_NOT_REACHABLE) {
8663 			/*-
8664 			 * if possible move things off of this address we
8665 			 * still may send below due to the dormant state but
8666 			 * we try to find an alternate address to send to
8667 			 * and if we have one we move all queued data on the
8668 			 * out wheel to this alternate address.
8669 			 */
8670 			if (net->ref_count > 1)
8671 				sctp_move_to_an_alt(stcb, asoc, net);
8672 		} else if (sctp_cmt_on_off && sctp_cmt_pf && ((net->dest_state & SCTP_ADDR_PF) ==
8673 		    SCTP_ADDR_PF)) {
8674 			/*
8675 			 * JRS 5/14/07 - If CMT PF is on and the current
8676 			 * destination is in PF state, move all queued data
8677 			 * to an alternate desination.
8678 			 */
8679 			if (net->ref_count > 1)
8680 				sctp_move_to_an_alt(stcb, asoc, net);
8681 		} else {
8682 			/*-
8683 			 * if ((asoc->sat_network) || (net->addr_is_local))
8684 			 * { burst_limit = asoc->max_burst *
8685 			 * SCTP_SAT_NETWORK_BURST_INCR; }
8686 			 */
8687 			if (sctp_use_cwnd_based_maxburst) {
8688 				if ((net->flight_size + (burst_limit * net->mtu)) < net->cwnd) {
8689 					/*
8690 					 * JRS - Use the congestion control
8691 					 * given in the congestion control
8692 					 * module
8693 					 */
8694 					asoc->cc_functions.sctp_cwnd_update_after_output(stcb, net, burst_limit);
8695 					if (sctp_logging_level & SCTP_LOG_MAXBURST_ENABLE) {
8696 						sctp_log_maxburst(stcb, net, 0, burst_limit, SCTP_MAX_BURST_APPLIED);
8697 					}
8698 					SCTP_STAT_INCR(sctps_maxburstqueued);
8699 				}
8700 				net->fast_retran_ip = 0;
8701 			} else {
8702 				if (net->flight_size == 0) {
8703 					/* Should be decaying the cwnd here */
8704 					;
8705 				}
8706 			}
8707 		}
8708 
8709 	}
8710 	burst_cnt = 0;
8711 	cwnd_full = 0;
8712 	do {
8713 		error = sctp_med_chunk_output(inp, stcb, asoc, &num_out,
8714 		    &reason_code, 0, &cwnd_full, from_where,
8715 		    &now, &now_filled, frag_point);
8716 		if (error) {
8717 			SCTPDBG(SCTP_DEBUG_OUTPUT1, "Error %d was returned from med-c-op\n", error);
8718 			if (sctp_logging_level & SCTP_LOG_MAXBURST_ENABLE) {
8719 				sctp_log_maxburst(stcb, asoc->primary_destination, error, burst_cnt, SCTP_MAX_BURST_ERROR_STOP);
8720 			}
8721 			if (sctp_logging_level & SCTP_CWND_LOGGING_ENABLE) {
8722 				sctp_log_cwnd(stcb, NULL, error, SCTP_SEND_NOW_COMPLETES);
8723 				sctp_log_cwnd(stcb, NULL, 0xdeadbeef, SCTP_SEND_NOW_COMPLETES);
8724 			}
8725 			break;
8726 		}
8727 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "m-c-o put out %d\n", num_out);
8728 
8729 		tot_out += num_out;
8730 		burst_cnt++;
8731 		if (sctp_logging_level & SCTP_CWND_LOGGING_ENABLE) {
8732 			sctp_log_cwnd(stcb, NULL, num_out, SCTP_SEND_NOW_COMPLETES);
8733 			if (num_out == 0) {
8734 				sctp_log_cwnd(stcb, NULL, reason_code, SCTP_SEND_NOW_COMPLETES);
8735 			}
8736 		}
8737 		if (nagle_on) {
8738 			/*-
8739 			 * When nagle is on, we look at how much is un_sent, then
8740 			 * if its smaller than an MTU and we have data in
8741 			 * flight we stop.
8742 			 */
8743 			un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
8744 			    ((stcb->asoc.chunks_on_out_queue - stcb->asoc.total_flight_count)
8745 			    * sizeof(struct sctp_data_chunk)));
8746 			if ((un_sent < (int)(stcb->asoc.smallest_mtu - SCTP_MIN_OVERHEAD)) &&
8747 			    (stcb->asoc.total_flight > 0)) {
8748 				break;
8749 			}
8750 		}
8751 		if (TAILQ_EMPTY(&asoc->control_send_queue) &&
8752 		    TAILQ_EMPTY(&asoc->send_queue) &&
8753 		    TAILQ_EMPTY(&asoc->out_wheel)) {
8754 			/* Nothing left to send */
8755 			break;
8756 		}
8757 		if ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) <= 0) {
8758 			/* Nothing left to send */
8759 			break;
8760 		}
8761 	} while (num_out && (sctp_use_cwnd_based_maxburst ||
8762 	    (burst_cnt < burst_limit)));
8763 
8764 	if (sctp_use_cwnd_based_maxburst == 0) {
8765 		if (burst_cnt >= burst_limit) {
8766 			SCTP_STAT_INCR(sctps_maxburstqueued);
8767 			asoc->burst_limit_applied = 1;
8768 			if (sctp_logging_level & SCTP_LOG_MAXBURST_ENABLE) {
8769 				sctp_log_maxburst(stcb, asoc->primary_destination, 0, burst_cnt, SCTP_MAX_BURST_APPLIED);
8770 			}
8771 		} else {
8772 			asoc->burst_limit_applied = 0;
8773 		}
8774 	}
8775 	if (sctp_logging_level & SCTP_CWND_LOGGING_ENABLE) {
8776 		sctp_log_cwnd(stcb, NULL, tot_out, SCTP_SEND_NOW_COMPLETES);
8777 	}
8778 	SCTPDBG(SCTP_DEBUG_OUTPUT1, "Ok, we have put out %d chunks\n",
8779 	    tot_out);
8780 
8781 	/*-
8782 	 * Now we need to clean up the control chunk chain if a ECNE is on
8783 	 * it. It must be marked as UNSENT again so next call will continue
8784 	 * to send it until such time that we get a CWR, to remove it.
8785 	 */
8786 	if (stcb->asoc.ecn_echo_cnt_onq)
8787 		sctp_fix_ecn_echo(asoc);
8788 	return;
8789 }
8790 
8791 
8792 int
8793 sctp_output(inp, m, addr, control, p, flags)
8794 	struct sctp_inpcb *inp;
8795 	struct mbuf *m;
8796 	struct sockaddr *addr;
8797 	struct mbuf *control;
8798 	struct thread *p;
8799 	int flags;
8800 {
8801 	if (inp == NULL) {
8802 		return (EINVAL);
8803 	}
8804 	if (inp->sctp_socket == NULL) {
8805 		return (EINVAL);
8806 	}
8807 	return (sctp_sosend(inp->sctp_socket,
8808 	    addr,
8809 	    (struct uio *)NULL,
8810 	    m,
8811 	    control,
8812 	    flags, p
8813 	    ));
8814 }
8815 
8816 void
8817 send_forward_tsn(struct sctp_tcb *stcb,
8818     struct sctp_association *asoc)
8819 {
8820 	struct sctp_tmit_chunk *chk;
8821 	struct sctp_forward_tsn_chunk *fwdtsn;
8822 
8823 	SCTP_TCB_LOCK_ASSERT(stcb);
8824 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
8825 		if (chk->rec.chunk_id.id == SCTP_FORWARD_CUM_TSN) {
8826 			/* mark it to unsent */
8827 			chk->sent = SCTP_DATAGRAM_UNSENT;
8828 			chk->snd_count = 0;
8829 			/* Do we correct its output location? */
8830 			if (chk->whoTo != asoc->primary_destination) {
8831 				sctp_free_remote_addr(chk->whoTo);
8832 				chk->whoTo = asoc->primary_destination;
8833 				atomic_add_int(&chk->whoTo->ref_count, 1);
8834 			}
8835 			goto sctp_fill_in_rest;
8836 		}
8837 	}
8838 	/* Ok if we reach here we must build one */
8839 	sctp_alloc_a_chunk(stcb, chk);
8840 	if (chk == NULL) {
8841 		return;
8842 	}
8843 	chk->copy_by_ref = 0;
8844 	chk->rec.chunk_id.id = SCTP_FORWARD_CUM_TSN;
8845 	chk->rec.chunk_id.can_take_data = 0;
8846 	chk->asoc = asoc;
8847 	chk->whoTo = NULL;
8848 
8849 	chk->data = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_DATA);
8850 	if (chk->data == NULL) {
8851 		sctp_free_a_chunk(stcb, chk);
8852 		return;
8853 	}
8854 	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
8855 	chk->sent = SCTP_DATAGRAM_UNSENT;
8856 	chk->snd_count = 0;
8857 	chk->whoTo = asoc->primary_destination;
8858 	atomic_add_int(&chk->whoTo->ref_count, 1);
8859 	TAILQ_INSERT_TAIL(&asoc->control_send_queue, chk, sctp_next);
8860 	asoc->ctrl_queue_cnt++;
8861 sctp_fill_in_rest:
8862 	/*-
8863 	 * Here we go through and fill out the part that deals with
8864 	 * stream/seq of the ones we skip.
8865 	 */
8866 	SCTP_BUF_LEN(chk->data) = 0;
8867 	{
8868 		struct sctp_tmit_chunk *at, *tp1, *last;
8869 		struct sctp_strseq *strseq;
8870 		unsigned int cnt_of_space, i, ovh;
8871 		unsigned int space_needed;
8872 		unsigned int cnt_of_skipped = 0;
8873 
8874 		TAILQ_FOREACH(at, &asoc->sent_queue, sctp_next) {
8875 			if (at->sent != SCTP_FORWARD_TSN_SKIP) {
8876 				/* no more to look at */
8877 				break;
8878 			}
8879 			if (at->rec.data.rcv_flags & SCTP_DATA_UNORDERED) {
8880 				/* We don't report these */
8881 				continue;
8882 			}
8883 			cnt_of_skipped++;
8884 		}
8885 		space_needed = (sizeof(struct sctp_forward_tsn_chunk) +
8886 		    (cnt_of_skipped * sizeof(struct sctp_strseq)));
8887 
8888 		cnt_of_space = M_TRAILINGSPACE(chk->data);
8889 
8890 		if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
8891 			ovh = SCTP_MIN_OVERHEAD;
8892 		} else {
8893 			ovh = SCTP_MIN_V4_OVERHEAD;
8894 		}
8895 		if (cnt_of_space > (asoc->smallest_mtu - ovh)) {
8896 			/* trim to a mtu size */
8897 			cnt_of_space = asoc->smallest_mtu - ovh;
8898 		}
8899 		if (cnt_of_space < space_needed) {
8900 			/*-
8901 			 * ok we must trim down the chunk by lowering the
8902 			 * advance peer ack point.
8903 			 */
8904 			cnt_of_skipped = (cnt_of_space -
8905 			    ((sizeof(struct sctp_forward_tsn_chunk)) /
8906 			    sizeof(struct sctp_strseq)));
8907 			/*-
8908 			 * Go through and find the TSN that will be the one
8909 			 * we report.
8910 			 */
8911 			at = TAILQ_FIRST(&asoc->sent_queue);
8912 			for (i = 0; i < cnt_of_skipped; i++) {
8913 				tp1 = TAILQ_NEXT(at, sctp_next);
8914 				at = tp1;
8915 			}
8916 			last = at;
8917 			/*-
8918 			 * last now points to last one I can report, update
8919 			 * peer ack point
8920 			 */
8921 			asoc->advanced_peer_ack_point = last->rec.data.TSN_seq;
8922 			space_needed -= (cnt_of_skipped * sizeof(struct sctp_strseq));
8923 		}
8924 		chk->send_size = space_needed;
8925 		/* Setup the chunk */
8926 		fwdtsn = mtod(chk->data, struct sctp_forward_tsn_chunk *);
8927 		fwdtsn->ch.chunk_length = htons(chk->send_size);
8928 		fwdtsn->ch.chunk_flags = 0;
8929 		fwdtsn->ch.chunk_type = SCTP_FORWARD_CUM_TSN;
8930 		fwdtsn->new_cumulative_tsn = htonl(asoc->advanced_peer_ack_point);
8931 		chk->send_size = (sizeof(struct sctp_forward_tsn_chunk) +
8932 		    (cnt_of_skipped * sizeof(struct sctp_strseq)));
8933 		SCTP_BUF_LEN(chk->data) = chk->send_size;
8934 		fwdtsn++;
8935 		/*-
8936 		 * Move pointer to after the fwdtsn and transfer to the
8937 		 * strseq pointer.
8938 		 */
8939 		strseq = (struct sctp_strseq *)fwdtsn;
8940 		/*-
8941 		 * Now populate the strseq list. This is done blindly
8942 		 * without pulling out duplicate stream info. This is
8943 		 * inefficent but won't harm the process since the peer will
8944 		 * look at these in sequence and will thus release anything.
8945 		 * It could mean we exceed the PMTU and chop off some that
8946 		 * we could have included.. but this is unlikely (aka 1432/4
8947 		 * would mean 300+ stream seq's would have to be reported in
8948 		 * one FWD-TSN. With a bit of work we can later FIX this to
8949 		 * optimize and pull out duplcates.. but it does add more
8950 		 * overhead. So for now... not!
8951 		 */
8952 		at = TAILQ_FIRST(&asoc->sent_queue);
8953 		for (i = 0; i < cnt_of_skipped; i++) {
8954 			tp1 = TAILQ_NEXT(at, sctp_next);
8955 			if (at->rec.data.rcv_flags & SCTP_DATA_UNORDERED) {
8956 				/* We don't report these */
8957 				i--;
8958 				at = tp1;
8959 				continue;
8960 			}
8961 			strseq->stream = ntohs(at->rec.data.stream_number);
8962 			strseq->sequence = ntohs(at->rec.data.stream_seq);
8963 			strseq++;
8964 			at = tp1;
8965 		}
8966 	}
8967 	return;
8968 
8969 }
8970 
8971 void
8972 sctp_send_sack(struct sctp_tcb *stcb)
8973 {
8974 	/*-
8975 	 * Queue up a SACK in the control queue. We must first check to see
8976 	 * if a SACK is somehow on the control queue. If so, we will take
8977 	 * and and remove the old one.
8978 	 */
8979 	struct sctp_association *asoc;
8980 	struct sctp_tmit_chunk *chk, *a_chk;
8981 	struct sctp_sack_chunk *sack;
8982 	struct sctp_gap_ack_block *gap_descriptor;
8983 	struct sack_track *selector;
8984 	int mergeable = 0;
8985 	int offset;
8986 	caddr_t limit;
8987 	uint32_t *dup;
8988 	int limit_reached = 0;
8989 	unsigned int i, jstart, siz, j;
8990 	unsigned int num_gap_blocks = 0, space;
8991 	int num_dups = 0;
8992 	int space_req;
8993 
8994 
8995 	a_chk = NULL;
8996 	asoc = &stcb->asoc;
8997 	SCTP_TCB_LOCK_ASSERT(stcb);
8998 	if (asoc->last_data_chunk_from == NULL) {
8999 		/* Hmm we never received anything */
9000 		return;
9001 	}
9002 	sctp_set_rwnd(stcb, asoc);
9003 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
9004 		if (chk->rec.chunk_id.id == SCTP_SELECTIVE_ACK) {
9005 			/* Hmm, found a sack already on queue, remove it */
9006 			TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
9007 			asoc->ctrl_queue_cnt++;
9008 			a_chk = chk;
9009 			if (a_chk->data) {
9010 				sctp_m_freem(a_chk->data);
9011 				a_chk->data = NULL;
9012 			}
9013 			sctp_free_remote_addr(a_chk->whoTo);
9014 			a_chk->whoTo = NULL;
9015 			break;
9016 		}
9017 	}
9018 	if (a_chk == NULL) {
9019 		sctp_alloc_a_chunk(stcb, a_chk);
9020 		if (a_chk == NULL) {
9021 			/* No memory so we drop the idea, and set a timer */
9022 			if (stcb->asoc.delayed_ack) {
9023 				sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
9024 				    stcb->sctp_ep, stcb, NULL, SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_5);
9025 				sctp_timer_start(SCTP_TIMER_TYPE_RECV,
9026 				    stcb->sctp_ep, stcb, NULL);
9027 			} else {
9028 				stcb->asoc.send_sack = 1;
9029 			}
9030 			return;
9031 		}
9032 		a_chk->copy_by_ref = 0;
9033 		/* a_chk->rec.chunk_id.id = SCTP_SELECTIVE_ACK; */
9034 		a_chk->rec.chunk_id.id = SCTP_SELECTIVE_ACK;
9035 		a_chk->rec.chunk_id.can_take_data = 1;
9036 	}
9037 	/* Clear our pkt counts */
9038 	asoc->data_pkts_seen = 0;
9039 
9040 	a_chk->asoc = asoc;
9041 	a_chk->snd_count = 0;
9042 	a_chk->send_size = 0;	/* fill in later */
9043 	a_chk->sent = SCTP_DATAGRAM_UNSENT;
9044 	a_chk->whoTo = NULL;
9045 
9046 	if ((asoc->numduptsns) ||
9047 	    (asoc->last_data_chunk_from->dest_state & SCTP_ADDR_NOT_REACHABLE)
9048 	    ) {
9049 		/*-
9050 		 * Ok, we have some duplicates or the destination for the
9051 		 * sack is unreachable, lets see if we can select an
9052 		 * alternate than asoc->last_data_chunk_from
9053 		 */
9054 		if ((!(asoc->last_data_chunk_from->dest_state &
9055 		    SCTP_ADDR_NOT_REACHABLE)) &&
9056 		    (asoc->used_alt_onsack > asoc->numnets)) {
9057 			/* We used an alt last time, don't this time */
9058 			a_chk->whoTo = NULL;
9059 		} else {
9060 			asoc->used_alt_onsack++;
9061 			a_chk->whoTo = sctp_find_alternate_net(stcb, asoc->last_data_chunk_from, 0);
9062 		}
9063 		if (a_chk->whoTo == NULL) {
9064 			/* Nope, no alternate */
9065 			a_chk->whoTo = asoc->last_data_chunk_from;
9066 			asoc->used_alt_onsack = 0;
9067 		}
9068 	} else {
9069 		/*
9070 		 * No duplicates so we use the last place we received data
9071 		 * from.
9072 		 */
9073 		asoc->used_alt_onsack = 0;
9074 		a_chk->whoTo = asoc->last_data_chunk_from;
9075 	}
9076 	if (a_chk->whoTo) {
9077 		atomic_add_int(&a_chk->whoTo->ref_count, 1);
9078 	}
9079 	if (asoc->highest_tsn_inside_map == asoc->cumulative_tsn) {
9080 		/* no gaps */
9081 		space_req = sizeof(struct sctp_sack_chunk);
9082 	} else {
9083 		/* gaps get a cluster */
9084 		space_req = MCLBYTES;
9085 	}
9086 	/* Ok now lets formulate a MBUF with our sack */
9087 	a_chk->data = sctp_get_mbuf_for_msg(space_req, 0, M_DONTWAIT, 1, MT_DATA);
9088 	if ((a_chk->data == NULL) ||
9089 	    (a_chk->whoTo == NULL)) {
9090 		/* rats, no mbuf memory */
9091 		if (a_chk->data) {
9092 			/* was a problem with the destination */
9093 			sctp_m_freem(a_chk->data);
9094 			a_chk->data = NULL;
9095 		}
9096 		sctp_free_a_chunk(stcb, a_chk);
9097 		if (stcb->asoc.delayed_ack) {
9098 			sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
9099 			    stcb->sctp_ep, stcb, NULL, SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_6);
9100 			sctp_timer_start(SCTP_TIMER_TYPE_RECV,
9101 			    stcb->sctp_ep, stcb, NULL);
9102 		} else {
9103 			stcb->asoc.send_sack = 1;
9104 		}
9105 		return;
9106 	}
9107 	/* ok, lets go through and fill it in */
9108 	SCTP_BUF_RESV_UF(a_chk->data, SCTP_MIN_OVERHEAD);
9109 	space = M_TRAILINGSPACE(a_chk->data);
9110 	if (space > (a_chk->whoTo->mtu - SCTP_MIN_OVERHEAD)) {
9111 		space = (a_chk->whoTo->mtu - SCTP_MIN_OVERHEAD);
9112 	}
9113 	limit = mtod(a_chk->data, caddr_t);
9114 	limit += space;
9115 
9116 	sack = mtod(a_chk->data, struct sctp_sack_chunk *);
9117 	sack->ch.chunk_type = SCTP_SELECTIVE_ACK;
9118 	/* 0x01 is used by nonce for ecn */
9119 	if ((sctp_ecn_enable) &&
9120 	    (sctp_ecn_nonce) &&
9121 	    (asoc->peer_supports_ecn_nonce))
9122 		sack->ch.chunk_flags = (asoc->receiver_nonce_sum & SCTP_SACK_NONCE_SUM);
9123 	else
9124 		sack->ch.chunk_flags = 0;
9125 
9126 	if (sctp_cmt_on_off && sctp_cmt_use_dac) {
9127 		/*-
9128 		 * CMT DAC algorithm: If 2 (i.e., 0x10) packets have been
9129 		 * received, then set high bit to 1, else 0. Reset
9130 		 * pkts_rcvd.
9131 		 */
9132 		sack->ch.chunk_flags |= (asoc->cmt_dac_pkts_rcvd << 6);
9133 		asoc->cmt_dac_pkts_rcvd = 0;
9134 	}
9135 	sack->sack.cum_tsn_ack = htonl(asoc->cumulative_tsn);
9136 	sack->sack.a_rwnd = htonl(asoc->my_rwnd);
9137 	asoc->my_last_reported_rwnd = asoc->my_rwnd;
9138 
9139 	/* reset the readers interpretation */
9140 	stcb->freed_by_sorcv_sincelast = 0;
9141 
9142 	gap_descriptor = (struct sctp_gap_ack_block *)((caddr_t)sack + sizeof(struct sctp_sack_chunk));
9143 
9144 	siz = (((asoc->highest_tsn_inside_map - asoc->mapping_array_base_tsn) + 1) + 7) / 8;
9145 	if (compare_with_wrap(asoc->mapping_array_base_tsn, asoc->cumulative_tsn, MAX_TSN)) {
9146 		offset = 1;
9147 		/*-
9148 		 * cum-ack behind the mapping array, so we start and use all
9149 		 * entries.
9150 		 */
9151 		jstart = 0;
9152 	} else {
9153 		offset = asoc->mapping_array_base_tsn - asoc->cumulative_tsn;
9154 		/*-
9155 		 * we skip the first one when the cum-ack is at or above the
9156 		 * mapping array base. Note this only works if
9157 		 */
9158 		jstart = 1;
9159 	}
9160 	if (compare_with_wrap(asoc->highest_tsn_inside_map, asoc->cumulative_tsn, MAX_TSN)) {
9161 		/* we have a gap .. maybe */
9162 		for (i = 0; i < siz; i++) {
9163 			selector = &sack_array[asoc->mapping_array[i]];
9164 			if (mergeable && selector->right_edge) {
9165 				/*
9166 				 * Backup, left and right edges were ok to
9167 				 * merge.
9168 				 */
9169 				num_gap_blocks--;
9170 				gap_descriptor--;
9171 			}
9172 			if (selector->num_entries == 0)
9173 				mergeable = 0;
9174 			else {
9175 				for (j = jstart; j < selector->num_entries; j++) {
9176 					if (mergeable && selector->right_edge) {
9177 						/*
9178 						 * do a merge by NOT setting
9179 						 * the left side
9180 						 */
9181 						mergeable = 0;
9182 					} else {
9183 						/*
9184 						 * no merge, set the left
9185 						 * side
9186 						 */
9187 						mergeable = 0;
9188 						gap_descriptor->start = htons((selector->gaps[j].start + offset));
9189 					}
9190 					gap_descriptor->end = htons((selector->gaps[j].end + offset));
9191 					num_gap_blocks++;
9192 					gap_descriptor++;
9193 					if (((caddr_t)gap_descriptor + sizeof(struct sctp_gap_ack_block)) > limit) {
9194 						/* no more room */
9195 						limit_reached = 1;
9196 						break;
9197 					}
9198 				}
9199 				if (selector->left_edge) {
9200 					mergeable = 1;
9201 				}
9202 			}
9203 			if (limit_reached) {
9204 				/* Reached the limit stop */
9205 				break;
9206 			}
9207 			jstart = 0;
9208 			offset += 8;
9209 		}
9210 		if (num_gap_blocks == 0) {
9211 			/* reneged all chunks */
9212 			asoc->highest_tsn_inside_map = asoc->cumulative_tsn;
9213 		}
9214 	}
9215 	/* now we must add any dups we are going to report. */
9216 	if ((limit_reached == 0) && (asoc->numduptsns)) {
9217 		dup = (uint32_t *) gap_descriptor;
9218 		for (i = 0; i < asoc->numduptsns; i++) {
9219 			*dup = htonl(asoc->dup_tsns[i]);
9220 			dup++;
9221 			num_dups++;
9222 			if (((caddr_t)dup + sizeof(uint32_t)) > limit) {
9223 				/* no more room */
9224 				break;
9225 			}
9226 		}
9227 		asoc->numduptsns = 0;
9228 	}
9229 	/*
9230 	 * now that the chunk is prepared queue it to the control chunk
9231 	 * queue.
9232 	 */
9233 	a_chk->send_size = (sizeof(struct sctp_sack_chunk) +
9234 	    (num_gap_blocks * sizeof(struct sctp_gap_ack_block)) +
9235 	    (num_dups * sizeof(int32_t)));
9236 	SCTP_BUF_LEN(a_chk->data) = a_chk->send_size;
9237 	sack->sack.num_gap_ack_blks = htons(num_gap_blocks);
9238 	sack->sack.num_dup_tsns = htons(num_dups);
9239 	sack->ch.chunk_length = htons(a_chk->send_size);
9240 	TAILQ_INSERT_TAIL(&asoc->control_send_queue, a_chk, sctp_next);
9241 	asoc->ctrl_queue_cnt++;
9242 	asoc->send_sack = 0;
9243 	SCTP_STAT_INCR(sctps_sendsacks);
9244 	return;
9245 }
9246 
9247 
9248 void
9249 sctp_send_abort_tcb(struct sctp_tcb *stcb, struct mbuf *operr)
9250 {
9251 	struct mbuf *m_abort;
9252 	struct mbuf *m_out = NULL, *m_end = NULL;
9253 	struct sctp_abort_chunk *abort = NULL;
9254 	int sz;
9255 	uint32_t auth_offset = 0;
9256 	struct sctp_auth_chunk *auth = NULL;
9257 	struct sctphdr *shdr;
9258 
9259 	/*-
9260 	 * Add an AUTH chunk, if chunk requires it and save the offset into
9261 	 * the chain for AUTH
9262 	 */
9263 	if (sctp_auth_is_required_chunk(SCTP_ABORT_ASSOCIATION,
9264 	    stcb->asoc.peer_auth_chunks)) {
9265 		m_out = sctp_add_auth_chunk(m_out, &m_end, &auth, &auth_offset,
9266 		    stcb, SCTP_ABORT_ASSOCIATION);
9267 	}
9268 	SCTP_TCB_LOCK_ASSERT(stcb);
9269 	m_abort = sctp_get_mbuf_for_msg(sizeof(struct sctp_abort_chunk), 0, M_DONTWAIT, 1, MT_HEADER);
9270 	if (m_abort == NULL) {
9271 		/* no mbuf's */
9272 		if (m_out)
9273 			sctp_m_freem(m_out);
9274 		return;
9275 	}
9276 	/* link in any error */
9277 	SCTP_BUF_NEXT(m_abort) = operr;
9278 	sz = 0;
9279 	if (operr) {
9280 		struct mbuf *n;
9281 
9282 		n = operr;
9283 		while (n) {
9284 			sz += SCTP_BUF_LEN(n);
9285 			n = SCTP_BUF_NEXT(n);
9286 		}
9287 	}
9288 	SCTP_BUF_LEN(m_abort) = sizeof(*abort);
9289 	if (m_out == NULL) {
9290 		/* NO Auth chunk prepended, so reserve space in front */
9291 		SCTP_BUF_RESV_UF(m_abort, SCTP_MIN_OVERHEAD);
9292 		m_out = m_abort;
9293 	} else {
9294 		/* Put AUTH chunk at the front of the chain */
9295 		SCTP_BUF_NEXT(m_end) = m_abort;
9296 	}
9297 
9298 	/* fill in the ABORT chunk */
9299 	abort = mtod(m_abort, struct sctp_abort_chunk *);
9300 	abort->ch.chunk_type = SCTP_ABORT_ASSOCIATION;
9301 	abort->ch.chunk_flags = 0;
9302 	abort->ch.chunk_length = htons(sizeof(*abort) + sz);
9303 
9304 	/* prepend and fill in the SCTP header */
9305 	SCTP_BUF_PREPEND(m_out, sizeof(struct sctphdr), M_DONTWAIT);
9306 	if (m_out == NULL) {
9307 		/* TSNH: no memory */
9308 		return;
9309 	}
9310 	shdr = mtod(m_out, struct sctphdr *);
9311 	shdr->src_port = stcb->sctp_ep->sctp_lport;
9312 	shdr->dest_port = stcb->rport;
9313 	shdr->v_tag = htonl(stcb->asoc.peer_vtag);
9314 	shdr->checksum = 0;
9315 	auth_offset += sizeof(struct sctphdr);
9316 
9317 	(void)sctp_lowlevel_chunk_output(stcb->sctp_ep, stcb,
9318 	    stcb->asoc.primary_destination,
9319 	    (struct sockaddr *)&stcb->asoc.primary_destination->ro._l_addr,
9320 	    m_out, auth_offset, auth, 1, 0, NULL, 0);
9321 	SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
9322 }
9323 
9324 void
9325 sctp_send_shutdown_complete(struct sctp_tcb *stcb,
9326     struct sctp_nets *net)
9327 {
9328 	/* formulate and SEND a SHUTDOWN-COMPLETE */
9329 	struct mbuf *m_shutdown_comp;
9330 	struct sctp_shutdown_complete_msg *comp_cp;
9331 
9332 	m_shutdown_comp = sctp_get_mbuf_for_msg(sizeof(struct sctp_shutdown_complete_msg), 0, M_DONTWAIT, 1, MT_HEADER);
9333 	if (m_shutdown_comp == NULL) {
9334 		/* no mbuf's */
9335 		return;
9336 	}
9337 	comp_cp = mtod(m_shutdown_comp, struct sctp_shutdown_complete_msg *);
9338 	comp_cp->shut_cmp.ch.chunk_type = SCTP_SHUTDOWN_COMPLETE;
9339 	comp_cp->shut_cmp.ch.chunk_flags = 0;
9340 	comp_cp->shut_cmp.ch.chunk_length = htons(sizeof(struct sctp_shutdown_complete_chunk));
9341 	comp_cp->sh.src_port = stcb->sctp_ep->sctp_lport;
9342 	comp_cp->sh.dest_port = stcb->rport;
9343 	comp_cp->sh.v_tag = htonl(stcb->asoc.peer_vtag);
9344 	comp_cp->sh.checksum = 0;
9345 
9346 	SCTP_BUF_LEN(m_shutdown_comp) = sizeof(struct sctp_shutdown_complete_msg);
9347 	(void)sctp_lowlevel_chunk_output(stcb->sctp_ep, stcb, net,
9348 	    (struct sockaddr *)&net->ro._l_addr,
9349 	    m_shutdown_comp, 0, NULL, 1, 0, NULL, 0);
9350 	SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
9351 	return;
9352 }
9353 
9354 void
9355 sctp_send_shutdown_complete2(struct mbuf *m, int iphlen, struct sctphdr *sh,
9356     uint32_t vrf_id)
9357 {
9358 	/* formulate and SEND a SHUTDOWN-COMPLETE */
9359 	struct mbuf *o_pak;
9360 	struct mbuf *mout;
9361 	struct ip *iph, *iph_out;
9362 	struct ip6_hdr *ip6, *ip6_out;
9363 	int offset_out, len, mlen;
9364 	struct sctp_shutdown_complete_msg *comp_cp;
9365 
9366 	/* Get room for the largest message */
9367 	len = (sizeof(struct ip6_hdr) + sizeof(struct sctp_shutdown_complete_msg));
9368 	mout = sctp_get_mbuf_for_msg(len, 1, M_DONTWAIT, 1, MT_DATA);
9369 	if (mout == NULL) {
9370 		return;
9371 	}
9372 	SCTP_BUF_LEN(mout) = len;
9373 	iph = mtod(m, struct ip *);
9374 	iph_out = NULL;
9375 	ip6_out = NULL;
9376 	offset_out = 0;
9377 	if (iph->ip_v == IPVERSION) {
9378 		SCTP_BUF_LEN(mout) = sizeof(struct ip) +
9379 		    sizeof(struct sctp_shutdown_complete_msg);
9380 		SCTP_BUF_NEXT(mout) = NULL;
9381 		iph_out = mtod(mout, struct ip *);
9382 
9383 		/* Fill in the IP header for the ABORT */
9384 		iph_out->ip_v = IPVERSION;
9385 		iph_out->ip_hl = (sizeof(struct ip) / 4);
9386 		iph_out->ip_tos = (u_char)0;
9387 		iph_out->ip_id = 0;
9388 		iph_out->ip_off = 0;
9389 		iph_out->ip_ttl = MAXTTL;
9390 		iph_out->ip_p = IPPROTO_SCTP;
9391 		iph_out->ip_src.s_addr = iph->ip_dst.s_addr;
9392 		iph_out->ip_dst.s_addr = iph->ip_src.s_addr;
9393 
9394 		/* let IP layer calculate this */
9395 		iph_out->ip_sum = 0;
9396 		offset_out += sizeof(*iph_out);
9397 		comp_cp = (struct sctp_shutdown_complete_msg *)(
9398 		    (caddr_t)iph_out + offset_out);
9399 	} else if (iph->ip_v == (IPV6_VERSION >> 4)) {
9400 		ip6 = (struct ip6_hdr *)iph;
9401 		SCTP_BUF_LEN(mout) = sizeof(struct ip6_hdr) +
9402 		    sizeof(struct sctp_shutdown_complete_msg);
9403 		SCTP_BUF_NEXT(mout) = NULL;
9404 		ip6_out = mtod(mout, struct ip6_hdr *);
9405 
9406 		/* Fill in the IPv6 header for the ABORT */
9407 		ip6_out->ip6_flow = ip6->ip6_flow;
9408 		ip6_out->ip6_hlim = ip6_defhlim;
9409 		ip6_out->ip6_nxt = IPPROTO_SCTP;
9410 		ip6_out->ip6_src = ip6->ip6_dst;
9411 		ip6_out->ip6_dst = ip6->ip6_src;
9412 		/*
9413 		 * ?? The old code had both the iph len + payload, I think
9414 		 * this is wrong and would never have worked
9415 		 */
9416 		ip6_out->ip6_plen = sizeof(struct sctp_shutdown_complete_msg);
9417 		offset_out += sizeof(*ip6_out);
9418 		comp_cp = (struct sctp_shutdown_complete_msg *)(
9419 		    (caddr_t)ip6_out + offset_out);
9420 	} else {
9421 		/* Currently not supported. */
9422 		return;
9423 	}
9424 	if (SCTP_GET_HEADER_FOR_OUTPUT(o_pak)) {
9425 		/* no mbuf's */
9426 		sctp_m_freem(mout);
9427 		return;
9428 	}
9429 	/* Now copy in and fill in the ABORT tags etc. */
9430 	comp_cp->sh.src_port = sh->dest_port;
9431 	comp_cp->sh.dest_port = sh->src_port;
9432 	comp_cp->sh.checksum = 0;
9433 	comp_cp->sh.v_tag = sh->v_tag;
9434 	comp_cp->shut_cmp.ch.chunk_flags = SCTP_HAD_NO_TCB;
9435 	comp_cp->shut_cmp.ch.chunk_type = SCTP_SHUTDOWN_COMPLETE;
9436 	comp_cp->shut_cmp.ch.chunk_length = htons(sizeof(struct sctp_shutdown_complete_chunk));
9437 
9438 	/* add checksum */
9439 	if ((sctp_no_csum_on_loopback) && SCTP_IS_IT_LOOPBACK(mout)) {
9440 		comp_cp->sh.checksum = 0;
9441 	} else {
9442 		comp_cp->sh.checksum = sctp_calculate_sum(mout, NULL, offset_out);
9443 	}
9444 	if (iph_out != NULL) {
9445 		sctp_route_t ro;
9446 		int ret;
9447 		struct sctp_tcb *stcb = NULL;
9448 
9449 		mlen = SCTP_BUF_LEN(mout);
9450 		bzero(&ro, sizeof ro);
9451 		/* set IPv4 length */
9452 		iph_out->ip_len = mlen;
9453 #ifdef  SCTP_PACKET_LOGGING
9454 		if (sctp_logging_level & SCTP_LAST_PACKET_TRACING)
9455 			sctp_packet_log(mout, mlen);
9456 #endif
9457 		SCTP_ATTACH_CHAIN(o_pak, mout, mlen);
9458 
9459 		/* out it goes */
9460 		SCTP_IP_OUTPUT(ret, o_pak, &ro, stcb, vrf_id);
9461 
9462 		/* Free the route if we got one back */
9463 		if (ro.ro_rt)
9464 			RTFREE(ro.ro_rt);
9465 	} else if (ip6_out != NULL) {
9466 		struct route_in6 ro;
9467 		int ret;
9468 		struct sctp_tcb *stcb = NULL;
9469 		struct ifnet *ifp = NULL;
9470 
9471 		bzero(&ro, sizeof(ro));
9472 		mlen = SCTP_BUF_LEN(mout);
9473 #ifdef  SCTP_PACKET_LOGGING
9474 		if (sctp_logging_level & SCTP_LAST_PACKET_TRACING)
9475 			sctp_packet_log(mout, mlen);
9476 #endif
9477 		SCTP_ATTACH_CHAIN(o_pak, mout, mlen);
9478 		SCTP_IP6_OUTPUT(ret, o_pak, &ro, &ifp, stcb, vrf_id);
9479 
9480 		/* Free the route if we got one back */
9481 		if (ro.ro_rt)
9482 			RTFREE(ro.ro_rt);
9483 	}
9484 	SCTP_STAT_INCR(sctps_sendpackets);
9485 	SCTP_STAT_INCR_COUNTER64(sctps_outpackets);
9486 	SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
9487 	return;
9488 
9489 }
9490 
9491 static struct sctp_nets *
9492 sctp_select_hb_destination(struct sctp_tcb *stcb, struct timeval *now)
9493 {
9494 	struct sctp_nets *net, *hnet;
9495 	int ms_goneby, highest_ms, state_overide = 0;
9496 
9497 	(void)SCTP_GETTIME_TIMEVAL(now);
9498 	highest_ms = 0;
9499 	hnet = NULL;
9500 	SCTP_TCB_LOCK_ASSERT(stcb);
9501 	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
9502 		if (
9503 		    ((net->dest_state & SCTP_ADDR_NOHB) && ((net->dest_state & SCTP_ADDR_UNCONFIRMED) == 0)) ||
9504 		    (net->dest_state & SCTP_ADDR_OUT_OF_SCOPE)
9505 		    ) {
9506 			/*
9507 			 * Skip this guy from consideration if HB is off AND
9508 			 * its confirmed
9509 			 */
9510 			continue;
9511 		}
9512 		if (sctp_destination_is_reachable(stcb, (struct sockaddr *)&net->ro._l_addr) == 0) {
9513 			/* skip this dest net from consideration */
9514 			continue;
9515 		}
9516 		if (net->last_sent_time.tv_sec) {
9517 			/* Sent to so we subtract */
9518 			ms_goneby = (now->tv_sec - net->last_sent_time.tv_sec) * 1000;
9519 		} else
9520 			/* Never been sent to */
9521 			ms_goneby = 0x7fffffff;
9522 		/*-
9523 		 * When the address state is unconfirmed but still
9524 		 * considered reachable, we HB at a higher rate. Once it
9525 		 * goes confirmed OR reaches the "unreachable" state, thenw
9526 		 * we cut it back to HB at a more normal pace.
9527 		 */
9528 		if ((net->dest_state & (SCTP_ADDR_UNCONFIRMED | SCTP_ADDR_NOT_REACHABLE)) == SCTP_ADDR_UNCONFIRMED) {
9529 			state_overide = 1;
9530 		} else {
9531 			state_overide = 0;
9532 		}
9533 
9534 		if ((((unsigned int)ms_goneby >= net->RTO) || (state_overide)) &&
9535 		    (ms_goneby > highest_ms)) {
9536 			highest_ms = ms_goneby;
9537 			hnet = net;
9538 		}
9539 	}
9540 	if (hnet &&
9541 	    ((hnet->dest_state & (SCTP_ADDR_UNCONFIRMED | SCTP_ADDR_NOT_REACHABLE)) == SCTP_ADDR_UNCONFIRMED)) {
9542 		state_overide = 1;
9543 	} else {
9544 		state_overide = 0;
9545 	}
9546 
9547 	if (hnet && highest_ms && (((unsigned int)highest_ms >= hnet->RTO) || state_overide)) {
9548 		/*-
9549 		 * Found the one with longest delay bounds OR it is
9550 		 * unconfirmed and still not marked unreachable.
9551 		 */
9552 		SCTPDBG(SCTP_DEBUG_OUTPUT4, "net:%p is the hb winner -", hnet);
9553 #ifdef SCTP_DEBUG
9554 		if (hnet) {
9555 			SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT4,
9556 			    (struct sockaddr *)&hnet->ro._l_addr);
9557 		} else {
9558 			SCTPDBG(SCTP_DEBUG_OUTPUT4, " none\n");
9559 		}
9560 #endif
9561 		/* update the timer now */
9562 		hnet->last_sent_time = *now;
9563 		return (hnet);
9564 	}
9565 	/* Nothing to HB */
9566 	return (NULL);
9567 }
9568 
9569 int
9570 sctp_send_hb(struct sctp_tcb *stcb, int user_req, struct sctp_nets *u_net)
9571 {
9572 	struct sctp_tmit_chunk *chk;
9573 	struct sctp_nets *net;
9574 	struct sctp_heartbeat_chunk *hb;
9575 	struct timeval now;
9576 	struct sockaddr_in *sin;
9577 	struct sockaddr_in6 *sin6;
9578 
9579 	SCTP_TCB_LOCK_ASSERT(stcb);
9580 	if (user_req == 0) {
9581 		net = sctp_select_hb_destination(stcb, &now);
9582 		if (net == NULL) {
9583 			/*-
9584 			 * All our busy none to send to, just start the
9585 			 * timer again.
9586 			 */
9587 			if (stcb->asoc.state == 0) {
9588 				return (0);
9589 			}
9590 			sctp_timer_start(SCTP_TIMER_TYPE_HEARTBEAT,
9591 			    stcb->sctp_ep,
9592 			    stcb,
9593 			    net);
9594 			return (0);
9595 		}
9596 	} else {
9597 		net = u_net;
9598 		if (net == NULL) {
9599 			return (0);
9600 		}
9601 		(void)SCTP_GETTIME_TIMEVAL(&now);
9602 	}
9603 	sin = (struct sockaddr_in *)&net->ro._l_addr;
9604 	if (sin->sin_family != AF_INET) {
9605 		if (sin->sin_family != AF_INET6) {
9606 			/* huh */
9607 			return (0);
9608 		}
9609 	}
9610 	sctp_alloc_a_chunk(stcb, chk);
9611 	if (chk == NULL) {
9612 		SCTPDBG(SCTP_DEBUG_OUTPUT4, "Gak, can't get a chunk for hb\n");
9613 		return (0);
9614 	}
9615 	chk->copy_by_ref = 0;
9616 	chk->rec.chunk_id.id = SCTP_HEARTBEAT_REQUEST;
9617 	chk->rec.chunk_id.can_take_data = 1;
9618 	chk->asoc = &stcb->asoc;
9619 	chk->send_size = sizeof(struct sctp_heartbeat_chunk);
9620 
9621 	chk->data = sctp_get_mbuf_for_msg(chk->send_size, 0, M_DONTWAIT, 1, MT_HEADER);
9622 	if (chk->data == NULL) {
9623 		sctp_free_a_chunk(stcb, chk);
9624 		return (0);
9625 	}
9626 	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
9627 	SCTP_BUF_LEN(chk->data) = chk->send_size;
9628 	chk->sent = SCTP_DATAGRAM_UNSENT;
9629 	chk->snd_count = 0;
9630 	chk->whoTo = net;
9631 	atomic_add_int(&chk->whoTo->ref_count, 1);
9632 	/* Now we have a mbuf that we can fill in with the details */
9633 	hb = mtod(chk->data, struct sctp_heartbeat_chunk *);
9634 	memset(hb, 0, sizeof(struct sctp_heartbeat_chunk));
9635 	/* fill out chunk header */
9636 	hb->ch.chunk_type = SCTP_HEARTBEAT_REQUEST;
9637 	hb->ch.chunk_flags = 0;
9638 	hb->ch.chunk_length = htons(chk->send_size);
9639 	/* Fill out hb parameter */
9640 	hb->heartbeat.hb_info.ph.param_type = htons(SCTP_HEARTBEAT_INFO);
9641 	hb->heartbeat.hb_info.ph.param_length = htons(sizeof(struct sctp_heartbeat_info_param));
9642 	hb->heartbeat.hb_info.time_value_1 = now.tv_sec;
9643 	hb->heartbeat.hb_info.time_value_2 = now.tv_usec;
9644 	/* Did our user request this one, put it in */
9645 	hb->heartbeat.hb_info.user_req = user_req;
9646 	hb->heartbeat.hb_info.addr_family = sin->sin_family;
9647 	hb->heartbeat.hb_info.addr_len = sin->sin_len;
9648 	if (net->dest_state & SCTP_ADDR_UNCONFIRMED) {
9649 		/*
9650 		 * we only take from the entropy pool if the address is not
9651 		 * confirmed.
9652 		 */
9653 		net->heartbeat_random1 = hb->heartbeat.hb_info.random_value1 = sctp_select_initial_TSN(&stcb->sctp_ep->sctp_ep);
9654 		net->heartbeat_random2 = hb->heartbeat.hb_info.random_value2 = sctp_select_initial_TSN(&stcb->sctp_ep->sctp_ep);
9655 	} else {
9656 		net->heartbeat_random1 = hb->heartbeat.hb_info.random_value1 = 0;
9657 		net->heartbeat_random2 = hb->heartbeat.hb_info.random_value2 = 0;
9658 	}
9659 	if (sin->sin_family == AF_INET) {
9660 		memcpy(hb->heartbeat.hb_info.address, &sin->sin_addr, sizeof(sin->sin_addr));
9661 	} else if (sin->sin_family == AF_INET6) {
9662 		/* We leave the scope the way it is in our lookup table. */
9663 		sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
9664 		memcpy(hb->heartbeat.hb_info.address, &sin6->sin6_addr, sizeof(sin6->sin6_addr));
9665 	} else {
9666 		/* huh compiler bug */
9667 		return (0);
9668 	}
9669 
9670 	/*
9671 	 * JRS 5/14/07 - In CMT PF, the T3 timer is used to track
9672 	 * PF-heartbeats.  Because of this, threshold management is done by
9673 	 * the t3 timer handler, and does not need to be done upon the send
9674 	 * of a PF-heartbeat. If CMT PF is on and the destination to which a
9675 	 * heartbeat is being sent is in PF state, do NOT do threshold
9676 	 * management.
9677 	 */
9678 	if ((sctp_cmt_pf == 0) || ((net->dest_state & SCTP_ADDR_PF) != SCTP_ADDR_PF)) {
9679 		/* ok we have a destination that needs a beat */
9680 		/* lets do the theshold management Qiaobing style */
9681 		if (sctp_threshold_management(stcb->sctp_ep, stcb, net,
9682 		    stcb->asoc.max_send_times)) {
9683 			/*-
9684 			 * we have lost the association, in a way this is
9685 			 * quite bad since we really are one less time since
9686 			 * we really did not send yet. This is the down side
9687 			 * to the Q's style as defined in the RFC and not my
9688 			 * alternate style defined in the RFC.
9689 			 */
9690 			if (chk->data != NULL) {
9691 				sctp_m_freem(chk->data);
9692 				chk->data = NULL;
9693 			}
9694 			/*
9695 			 * Here we do NOT use the macro since the
9696 			 * association is now gone.
9697 			 */
9698 			if (chk->whoTo) {
9699 				sctp_free_remote_addr(chk->whoTo);
9700 				chk->whoTo = NULL;
9701 			}
9702 			SCTP_ZONE_FREE(sctppcbinfo.ipi_zone_chunk, chk);
9703 			SCTP_DECR_CHK_COUNT();
9704 			return (-1);
9705 		}
9706 	}
9707 	net->hb_responded = 0;
9708 	TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
9709 	stcb->asoc.ctrl_queue_cnt++;
9710 	SCTP_STAT_INCR(sctps_sendheartbeat);
9711 	/*-
9712 	 * Call directly med level routine to put out the chunk. It will
9713 	 * always tumble out control chunks aka HB but it may even tumble
9714 	 * out data too.
9715 	 */
9716 	return (1);
9717 }
9718 
9719 void
9720 sctp_send_ecn_echo(struct sctp_tcb *stcb, struct sctp_nets *net,
9721     uint32_t high_tsn)
9722 {
9723 	struct sctp_association *asoc;
9724 	struct sctp_ecne_chunk *ecne;
9725 	struct sctp_tmit_chunk *chk;
9726 
9727 	asoc = &stcb->asoc;
9728 	SCTP_TCB_LOCK_ASSERT(stcb);
9729 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
9730 		if (chk->rec.chunk_id.id == SCTP_ECN_ECHO) {
9731 			/* found a previous ECN_ECHO update it if needed */
9732 			ecne = mtod(chk->data, struct sctp_ecne_chunk *);
9733 			ecne->tsn = htonl(high_tsn);
9734 			return;
9735 		}
9736 	}
9737 	/* nope could not find one to update so we must build one */
9738 	sctp_alloc_a_chunk(stcb, chk);
9739 	if (chk == NULL) {
9740 		return;
9741 	}
9742 	chk->copy_by_ref = 0;
9743 	SCTP_STAT_INCR(sctps_sendecne);
9744 	chk->rec.chunk_id.id = SCTP_ECN_ECHO;
9745 	chk->rec.chunk_id.can_take_data = 0;
9746 	chk->asoc = &stcb->asoc;
9747 	chk->send_size = sizeof(struct sctp_ecne_chunk);
9748 	chk->data = sctp_get_mbuf_for_msg(chk->send_size, 0, M_DONTWAIT, 1, MT_HEADER);
9749 	if (chk->data == NULL) {
9750 		sctp_free_a_chunk(stcb, chk);
9751 		return;
9752 	}
9753 	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
9754 	SCTP_BUF_LEN(chk->data) = chk->send_size;
9755 	chk->sent = SCTP_DATAGRAM_UNSENT;
9756 	chk->snd_count = 0;
9757 	chk->whoTo = net;
9758 	atomic_add_int(&chk->whoTo->ref_count, 1);
9759 	stcb->asoc.ecn_echo_cnt_onq++;
9760 	ecne = mtod(chk->data, struct sctp_ecne_chunk *);
9761 	ecne->ch.chunk_type = SCTP_ECN_ECHO;
9762 	ecne->ch.chunk_flags = 0;
9763 	ecne->ch.chunk_length = htons(sizeof(struct sctp_ecne_chunk));
9764 	ecne->tsn = htonl(high_tsn);
9765 	TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
9766 	asoc->ctrl_queue_cnt++;
9767 }
9768 
9769 void
9770 sctp_send_packet_dropped(struct sctp_tcb *stcb, struct sctp_nets *net,
9771     struct mbuf *m, int iphlen, int bad_crc)
9772 {
9773 	struct sctp_association *asoc;
9774 	struct sctp_pktdrop_chunk *drp;
9775 	struct sctp_tmit_chunk *chk;
9776 	uint8_t *datap;
9777 	int len;
9778 	int was_trunc = 0;
9779 	struct ip *iph;
9780 	int fullsz = 0, extra = 0;
9781 	long spc;
9782 
9783 	asoc = &stcb->asoc;
9784 	SCTP_TCB_LOCK_ASSERT(stcb);
9785 	if (asoc->peer_supports_pktdrop == 0) {
9786 		/*-
9787 		 * peer must declare support before I send one.
9788 		 */
9789 		return;
9790 	}
9791 	if (stcb->sctp_socket == NULL) {
9792 		return;
9793 	}
9794 	sctp_alloc_a_chunk(stcb, chk);
9795 	if (chk == NULL) {
9796 		return;
9797 	}
9798 	chk->copy_by_ref = 0;
9799 	iph = mtod(m, struct ip *);
9800 	if (iph == NULL) {
9801 		sctp_free_a_chunk(stcb, chk);
9802 		return;
9803 	}
9804 	if (iph->ip_v == IPVERSION) {
9805 		/* IPv4 */
9806 		len = chk->send_size = iph->ip_len;
9807 	} else {
9808 		struct ip6_hdr *ip6h;
9809 
9810 		/* IPv6 */
9811 		ip6h = mtod(m, struct ip6_hdr *);
9812 		len = chk->send_size = htons(ip6h->ip6_plen);
9813 	}
9814 	if ((len + SCTP_MAX_OVERHEAD + sizeof(struct sctp_pktdrop_chunk)) >
9815 	    min(stcb->asoc.smallest_mtu, MCLBYTES)) {
9816 		/*
9817 		 * only send 1 mtu worth, trim off the excess on the end.
9818 		 */
9819 		fullsz = len - extra;
9820 		len = min(stcb->asoc.smallest_mtu, MCLBYTES) - SCTP_MAX_OVERHEAD;
9821 		was_trunc = 1;
9822 	}
9823 	chk->asoc = &stcb->asoc;
9824 	chk->data = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_DATA);
9825 	if (chk->data == NULL) {
9826 jump_out:
9827 		sctp_free_a_chunk(stcb, chk);
9828 		return;
9829 	}
9830 	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
9831 	drp = mtod(chk->data, struct sctp_pktdrop_chunk *);
9832 	if (drp == NULL) {
9833 		sctp_m_freem(chk->data);
9834 		chk->data = NULL;
9835 		goto jump_out;
9836 	}
9837 	chk->book_size = SCTP_SIZE32((chk->send_size + sizeof(struct sctp_pktdrop_chunk) +
9838 	    sizeof(struct sctphdr) + SCTP_MED_OVERHEAD));
9839 	chk->book_size_scale = 0;
9840 	if (was_trunc) {
9841 		drp->ch.chunk_flags = SCTP_PACKET_TRUNCATED;
9842 		drp->trunc_len = htons(fullsz);
9843 		/*
9844 		 * Len is already adjusted to size minus overhead above take
9845 		 * out the pkt_drop chunk itself from it.
9846 		 */
9847 		chk->send_size = len - sizeof(struct sctp_pktdrop_chunk);
9848 		len = chk->send_size;
9849 	} else {
9850 		/* no truncation needed */
9851 		drp->ch.chunk_flags = 0;
9852 		drp->trunc_len = htons(0);
9853 	}
9854 	if (bad_crc) {
9855 		drp->ch.chunk_flags |= SCTP_BADCRC;
9856 	}
9857 	chk->send_size += sizeof(struct sctp_pktdrop_chunk);
9858 	SCTP_BUF_LEN(chk->data) = chk->send_size;
9859 	chk->sent = SCTP_DATAGRAM_UNSENT;
9860 	chk->snd_count = 0;
9861 	if (net) {
9862 		/* we should hit here */
9863 		chk->whoTo = net;
9864 	} else {
9865 		chk->whoTo = asoc->primary_destination;
9866 	}
9867 	atomic_add_int(&chk->whoTo->ref_count, 1);
9868 	chk->rec.chunk_id.id = SCTP_PACKET_DROPPED;
9869 	chk->rec.chunk_id.can_take_data = 1;
9870 	drp->ch.chunk_type = SCTP_PACKET_DROPPED;
9871 	drp->ch.chunk_length = htons(chk->send_size);
9872 	spc = SCTP_SB_LIMIT_RCV(stcb->sctp_socket);
9873 	if (spc < 0) {
9874 		spc = 0;
9875 	}
9876 	drp->bottle_bw = htonl(spc);
9877 	if (asoc->my_rwnd) {
9878 		drp->current_onq = htonl(asoc->size_on_reasm_queue +
9879 		    asoc->size_on_all_streams +
9880 		    asoc->my_rwnd_control_len +
9881 		    stcb->sctp_socket->so_rcv.sb_cc);
9882 	} else {
9883 		/*-
9884 		 * If my rwnd is 0, possibly from mbuf depletion as well as
9885 		 * space used, tell the peer there is NO space aka onq == bw
9886 		 */
9887 		drp->current_onq = htonl(spc);
9888 	}
9889 	drp->reserved = 0;
9890 	datap = drp->data;
9891 	m_copydata(m, iphlen, len, (caddr_t)datap);
9892 	TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
9893 	asoc->ctrl_queue_cnt++;
9894 }
9895 
9896 void
9897 sctp_send_cwr(struct sctp_tcb *stcb, struct sctp_nets *net, uint32_t high_tsn)
9898 {
9899 	struct sctp_association *asoc;
9900 	struct sctp_cwr_chunk *cwr;
9901 	struct sctp_tmit_chunk *chk;
9902 
9903 	asoc = &stcb->asoc;
9904 	SCTP_TCB_LOCK_ASSERT(stcb);
9905 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
9906 		if (chk->rec.chunk_id.id == SCTP_ECN_CWR) {
9907 			/* found a previous ECN_CWR update it if needed */
9908 			cwr = mtod(chk->data, struct sctp_cwr_chunk *);
9909 			if (compare_with_wrap(high_tsn, ntohl(cwr->tsn),
9910 			    MAX_TSN)) {
9911 				cwr->tsn = htonl(high_tsn);
9912 			}
9913 			return;
9914 		}
9915 	}
9916 	/* nope could not find one to update so we must build one */
9917 	sctp_alloc_a_chunk(stcb, chk);
9918 	if (chk == NULL) {
9919 		return;
9920 	}
9921 	chk->copy_by_ref = 0;
9922 	chk->rec.chunk_id.id = SCTP_ECN_CWR;
9923 	chk->rec.chunk_id.can_take_data = 1;
9924 	chk->asoc = &stcb->asoc;
9925 	chk->send_size = sizeof(struct sctp_cwr_chunk);
9926 	chk->data = sctp_get_mbuf_for_msg(chk->send_size, 0, M_DONTWAIT, 1, MT_HEADER);
9927 	if (chk->data == NULL) {
9928 		sctp_free_a_chunk(stcb, chk);
9929 		return;
9930 	}
9931 	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
9932 	SCTP_BUF_LEN(chk->data) = chk->send_size;
9933 	chk->sent = SCTP_DATAGRAM_UNSENT;
9934 	chk->snd_count = 0;
9935 	chk->whoTo = net;
9936 	atomic_add_int(&chk->whoTo->ref_count, 1);
9937 	cwr = mtod(chk->data, struct sctp_cwr_chunk *);
9938 	cwr->ch.chunk_type = SCTP_ECN_CWR;
9939 	cwr->ch.chunk_flags = 0;
9940 	cwr->ch.chunk_length = htons(sizeof(struct sctp_cwr_chunk));
9941 	cwr->tsn = htonl(high_tsn);
9942 	TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
9943 	asoc->ctrl_queue_cnt++;
9944 }
9945 
9946 void
9947 sctp_add_stream_reset_out(struct sctp_tmit_chunk *chk,
9948     int number_entries, uint16_t * list,
9949     uint32_t seq, uint32_t resp_seq, uint32_t last_sent)
9950 {
9951 	int len, old_len, i;
9952 	struct sctp_stream_reset_out_request *req_out;
9953 	struct sctp_chunkhdr *ch;
9954 
9955 	ch = mtod(chk->data, struct sctp_chunkhdr *);
9956 
9957 
9958 	old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
9959 
9960 	/* get to new offset for the param. */
9961 	req_out = (struct sctp_stream_reset_out_request *)((caddr_t)ch + len);
9962 	/* now how long will this param be? */
9963 	len = (sizeof(struct sctp_stream_reset_out_request) + (sizeof(uint16_t) * number_entries));
9964 	req_out->ph.param_type = htons(SCTP_STR_RESET_OUT_REQUEST);
9965 	req_out->ph.param_length = htons(len);
9966 	req_out->request_seq = htonl(seq);
9967 	req_out->response_seq = htonl(resp_seq);
9968 	req_out->send_reset_at_tsn = htonl(last_sent);
9969 	if (number_entries) {
9970 		for (i = 0; i < number_entries; i++) {
9971 			req_out->list_of_streams[i] = htons(list[i]);
9972 		}
9973 	}
9974 	if (SCTP_SIZE32(len) > len) {
9975 		/*-
9976 		 * Need to worry about the pad we may end up adding to the
9977 		 * end. This is easy since the struct is either aligned to 4
9978 		 * bytes or 2 bytes off.
9979 		 */
9980 		req_out->list_of_streams[number_entries] = 0;
9981 	}
9982 	/* now fix the chunk length */
9983 	ch->chunk_length = htons(len + old_len);
9984 	chk->book_size = len + old_len;
9985 	chk->book_size_scale = 0;
9986 	chk->send_size = SCTP_SIZE32(chk->book_size);
9987 	SCTP_BUF_LEN(chk->data) = chk->send_size;
9988 	return;
9989 }
9990 
9991 
9992 void
9993 sctp_add_stream_reset_in(struct sctp_tmit_chunk *chk,
9994     int number_entries, uint16_t * list,
9995     uint32_t seq)
9996 {
9997 	int len, old_len, i;
9998 	struct sctp_stream_reset_in_request *req_in;
9999 	struct sctp_chunkhdr *ch;
10000 
10001 	ch = mtod(chk->data, struct sctp_chunkhdr *);
10002 
10003 
10004 	old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
10005 
10006 	/* get to new offset for the param. */
10007 	req_in = (struct sctp_stream_reset_in_request *)((caddr_t)ch + len);
10008 	/* now how long will this param be? */
10009 	len = (sizeof(struct sctp_stream_reset_in_request) + (sizeof(uint16_t) * number_entries));
10010 	req_in->ph.param_type = htons(SCTP_STR_RESET_IN_REQUEST);
10011 	req_in->ph.param_length = htons(len);
10012 	req_in->request_seq = htonl(seq);
10013 	if (number_entries) {
10014 		for (i = 0; i < number_entries; i++) {
10015 			req_in->list_of_streams[i] = htons(list[i]);
10016 		}
10017 	}
10018 	if (SCTP_SIZE32(len) > len) {
10019 		/*-
10020 		 * Need to worry about the pad we may end up adding to the
10021 		 * end. This is easy since the struct is either aligned to 4
10022 		 * bytes or 2 bytes off.
10023 		 */
10024 		req_in->list_of_streams[number_entries] = 0;
10025 	}
10026 	/* now fix the chunk length */
10027 	ch->chunk_length = htons(len + old_len);
10028 	chk->book_size = len + old_len;
10029 	chk->book_size_scale = 0;
10030 	chk->send_size = SCTP_SIZE32(chk->book_size);
10031 	SCTP_BUF_LEN(chk->data) = chk->send_size;
10032 	return;
10033 }
10034 
10035 
10036 void
10037 sctp_add_stream_reset_tsn(struct sctp_tmit_chunk *chk,
10038     uint32_t seq)
10039 {
10040 	int len, old_len;
10041 	struct sctp_stream_reset_tsn_request *req_tsn;
10042 	struct sctp_chunkhdr *ch;
10043 
10044 	ch = mtod(chk->data, struct sctp_chunkhdr *);
10045 
10046 
10047 	old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
10048 
10049 	/* get to new offset for the param. */
10050 	req_tsn = (struct sctp_stream_reset_tsn_request *)((caddr_t)ch + len);
10051 	/* now how long will this param be? */
10052 	len = sizeof(struct sctp_stream_reset_tsn_request);
10053 	req_tsn->ph.param_type = htons(SCTP_STR_RESET_TSN_REQUEST);
10054 	req_tsn->ph.param_length = htons(len);
10055 	req_tsn->request_seq = htonl(seq);
10056 
10057 	/* now fix the chunk length */
10058 	ch->chunk_length = htons(len + old_len);
10059 	chk->send_size = len + old_len;
10060 	chk->book_size = SCTP_SIZE32(chk->send_size);
10061 	chk->book_size_scale = 0;
10062 	SCTP_BUF_LEN(chk->data) = SCTP_SIZE32(chk->send_size);
10063 	return;
10064 }
10065 
10066 void
10067 sctp_add_stream_reset_result(struct sctp_tmit_chunk *chk,
10068     uint32_t resp_seq, uint32_t result)
10069 {
10070 	int len, old_len;
10071 	struct sctp_stream_reset_response *resp;
10072 	struct sctp_chunkhdr *ch;
10073 
10074 	ch = mtod(chk->data, struct sctp_chunkhdr *);
10075 
10076 
10077 	old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
10078 
10079 	/* get to new offset for the param. */
10080 	resp = (struct sctp_stream_reset_response *)((caddr_t)ch + len);
10081 	/* now how long will this param be? */
10082 	len = sizeof(struct sctp_stream_reset_response);
10083 	resp->ph.param_type = htons(SCTP_STR_RESET_RESPONSE);
10084 	resp->ph.param_length = htons(len);
10085 	resp->response_seq = htonl(resp_seq);
10086 	resp->result = ntohl(result);
10087 
10088 	/* now fix the chunk length */
10089 	ch->chunk_length = htons(len + old_len);
10090 	chk->book_size = len + old_len;
10091 	chk->book_size_scale = 0;
10092 	chk->send_size = SCTP_SIZE32(chk->book_size);
10093 	SCTP_BUF_LEN(chk->data) = chk->send_size;
10094 	return;
10095 
10096 }
10097 
10098 
10099 void
10100 sctp_add_stream_reset_result_tsn(struct sctp_tmit_chunk *chk,
10101     uint32_t resp_seq, uint32_t result,
10102     uint32_t send_una, uint32_t recv_next)
10103 {
10104 	int len, old_len;
10105 	struct sctp_stream_reset_response_tsn *resp;
10106 	struct sctp_chunkhdr *ch;
10107 
10108 	ch = mtod(chk->data, struct sctp_chunkhdr *);
10109 
10110 
10111 	old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
10112 
10113 	/* get to new offset for the param. */
10114 	resp = (struct sctp_stream_reset_response_tsn *)((caddr_t)ch + len);
10115 	/* now how long will this param be? */
10116 	len = sizeof(struct sctp_stream_reset_response_tsn);
10117 	resp->ph.param_type = htons(SCTP_STR_RESET_RESPONSE);
10118 	resp->ph.param_length = htons(len);
10119 	resp->response_seq = htonl(resp_seq);
10120 	resp->result = htonl(result);
10121 	resp->senders_next_tsn = htonl(send_una);
10122 	resp->receivers_next_tsn = htonl(recv_next);
10123 
10124 	/* now fix the chunk length */
10125 	ch->chunk_length = htons(len + old_len);
10126 	chk->book_size = len + old_len;
10127 	chk->send_size = SCTP_SIZE32(chk->book_size);
10128 	chk->book_size_scale = 0;
10129 	SCTP_BUF_LEN(chk->data) = chk->send_size;
10130 	return;
10131 }
10132 
10133 
10134 int
10135 sctp_send_str_reset_req(struct sctp_tcb *stcb,
10136     int number_entries, uint16_t * list,
10137     uint8_t send_out_req, uint32_t resp_seq,
10138     uint8_t send_in_req,
10139     uint8_t send_tsn_req)
10140 {
10141 
10142 	struct sctp_association *asoc;
10143 	struct sctp_tmit_chunk *chk;
10144 	struct sctp_chunkhdr *ch;
10145 	uint32_t seq;
10146 
10147 	asoc = &stcb->asoc;
10148 	if (asoc->stream_reset_outstanding) {
10149 		/*-
10150 		 * Already one pending, must get ACK back to clear the flag.
10151 		 */
10152 		return (EBUSY);
10153 	}
10154 	if ((send_out_req == 0) && (send_in_req == 0) && (send_tsn_req == 0)) {
10155 		/* nothing to do */
10156 		return (EINVAL);
10157 	}
10158 	if (send_tsn_req && (send_out_req || send_in_req)) {
10159 		/* error, can't do that */
10160 		return (EINVAL);
10161 	}
10162 	sctp_alloc_a_chunk(stcb, chk);
10163 	if (chk == NULL) {
10164 		SCTP_LTRACE_ERR(stcb->sctp_ep, stcb, ENOMEM, 0);
10165 		return (ENOMEM);
10166 	}
10167 	chk->copy_by_ref = 0;
10168 	chk->rec.chunk_id.id = SCTP_STREAM_RESET;
10169 	chk->rec.chunk_id.can_take_data = 0;
10170 	chk->asoc = &stcb->asoc;
10171 	chk->book_size = sizeof(struct sctp_chunkhdr);
10172 	chk->send_size = SCTP_SIZE32(chk->book_size);
10173 	chk->book_size_scale = 0;
10174 
10175 	chk->data = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_DATA);
10176 	if (chk->data == NULL) {
10177 		sctp_free_a_chunk(stcb, chk);
10178 		SCTP_LTRACE_ERR(stcb->sctp_ep, stcb, ENOMEM, 0);
10179 		return (ENOMEM);
10180 	}
10181 	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
10182 
10183 	/* setup chunk parameters */
10184 	chk->sent = SCTP_DATAGRAM_UNSENT;
10185 	chk->snd_count = 0;
10186 	chk->whoTo = asoc->primary_destination;
10187 	atomic_add_int(&chk->whoTo->ref_count, 1);
10188 
10189 	ch = mtod(chk->data, struct sctp_chunkhdr *);
10190 	ch->chunk_type = SCTP_STREAM_RESET;
10191 	ch->chunk_flags = 0;
10192 	ch->chunk_length = htons(chk->book_size);
10193 	SCTP_BUF_LEN(chk->data) = chk->send_size;
10194 
10195 	seq = stcb->asoc.str_reset_seq_out;
10196 	if (send_out_req) {
10197 		sctp_add_stream_reset_out(chk, number_entries, list,
10198 		    seq, resp_seq, (stcb->asoc.sending_seq - 1));
10199 		asoc->stream_reset_out_is_outstanding = 1;
10200 		seq++;
10201 		asoc->stream_reset_outstanding++;
10202 	}
10203 	if (send_in_req) {
10204 		sctp_add_stream_reset_in(chk, number_entries, list, seq);
10205 		asoc->stream_reset_outstanding++;
10206 	}
10207 	if (send_tsn_req) {
10208 		sctp_add_stream_reset_tsn(chk, seq);
10209 		asoc->stream_reset_outstanding++;
10210 	}
10211 	asoc->str_reset = chk;
10212 
10213 	/* insert the chunk for sending */
10214 	TAILQ_INSERT_TAIL(&asoc->control_send_queue,
10215 	    chk,
10216 	    sctp_next);
10217 	asoc->ctrl_queue_cnt++;
10218 	sctp_timer_start(SCTP_TIMER_TYPE_STRRESET, stcb->sctp_ep, stcb, chk->whoTo);
10219 	return (0);
10220 }
10221 
10222 void
10223 sctp_send_abort(struct mbuf *m, int iphlen, struct sctphdr *sh, uint32_t vtag,
10224     struct mbuf *err_cause, uint32_t vrf_id)
10225 {
10226 	/*-
10227 	 * Formulate the abort message, and send it back down.
10228 	 */
10229 	struct mbuf *o_pak;
10230 	struct mbuf *mout;
10231 	struct sctp_abort_msg *abm;
10232 	struct ip *iph, *iph_out;
10233 	struct ip6_hdr *ip6, *ip6_out;
10234 	int iphlen_out, len;
10235 
10236 	/* don't respond to ABORT with ABORT */
10237 	if (sctp_is_there_an_abort_here(m, iphlen, &vtag)) {
10238 		if (err_cause)
10239 			sctp_m_freem(err_cause);
10240 		return;
10241 	}
10242 	len = (sizeof(struct ip6_hdr) + sizeof(struct sctp_abort_msg));
10243 
10244 	mout = sctp_get_mbuf_for_msg(len, 1, M_DONTWAIT, 1, MT_DATA);
10245 	if (mout == NULL) {
10246 		if (err_cause)
10247 			sctp_m_freem(err_cause);
10248 		return;
10249 	}
10250 	iph = mtod(m, struct ip *);
10251 	iph_out = NULL;
10252 	ip6_out = NULL;
10253 	if (iph->ip_v == IPVERSION) {
10254 		iph_out = mtod(mout, struct ip *);
10255 		SCTP_BUF_LEN(mout) = sizeof(*iph_out) + sizeof(*abm);
10256 		SCTP_BUF_NEXT(mout) = err_cause;
10257 
10258 		/* Fill in the IP header for the ABORT */
10259 		iph_out->ip_v = IPVERSION;
10260 		iph_out->ip_hl = (sizeof(struct ip) / 4);
10261 		iph_out->ip_tos = (u_char)0;
10262 		iph_out->ip_id = 0;
10263 		iph_out->ip_off = 0;
10264 		iph_out->ip_ttl = MAXTTL;
10265 		iph_out->ip_p = IPPROTO_SCTP;
10266 		iph_out->ip_src.s_addr = iph->ip_dst.s_addr;
10267 		iph_out->ip_dst.s_addr = iph->ip_src.s_addr;
10268 		/* let IP layer calculate this */
10269 		iph_out->ip_sum = 0;
10270 
10271 		iphlen_out = sizeof(*iph_out);
10272 		abm = (struct sctp_abort_msg *)((caddr_t)iph_out + iphlen_out);
10273 	} else if (iph->ip_v == (IPV6_VERSION >> 4)) {
10274 		ip6 = (struct ip6_hdr *)iph;
10275 		ip6_out = mtod(mout, struct ip6_hdr *);
10276 		SCTP_BUF_LEN(mout) = sizeof(*ip6_out) + sizeof(*abm);
10277 		SCTP_BUF_NEXT(mout) = err_cause;
10278 
10279 		/* Fill in the IP6 header for the ABORT */
10280 		ip6_out->ip6_flow = ip6->ip6_flow;
10281 		ip6_out->ip6_hlim = ip6_defhlim;
10282 		ip6_out->ip6_nxt = IPPROTO_SCTP;
10283 		ip6_out->ip6_src = ip6->ip6_dst;
10284 		ip6_out->ip6_dst = ip6->ip6_src;
10285 
10286 		iphlen_out = sizeof(*ip6_out);
10287 		abm = (struct sctp_abort_msg *)((caddr_t)ip6_out + iphlen_out);
10288 	} else {
10289 		/* Currently not supported */
10290 		return;
10291 	}
10292 
10293 	abm->sh.src_port = sh->dest_port;
10294 	abm->sh.dest_port = sh->src_port;
10295 	abm->sh.checksum = 0;
10296 	if (vtag == 0) {
10297 		abm->sh.v_tag = sh->v_tag;
10298 		abm->msg.ch.chunk_flags = SCTP_HAD_NO_TCB;
10299 	} else {
10300 		abm->sh.v_tag = htonl(vtag);
10301 		abm->msg.ch.chunk_flags = 0;
10302 	}
10303 	abm->msg.ch.chunk_type = SCTP_ABORT_ASSOCIATION;
10304 
10305 	if (err_cause) {
10306 		struct mbuf *m_tmp = err_cause;
10307 		int err_len = 0;
10308 
10309 		/* get length of the err_cause chain */
10310 		while (m_tmp != NULL) {
10311 			err_len += SCTP_BUF_LEN(m_tmp);
10312 			m_tmp = SCTP_BUF_NEXT(m_tmp);
10313 		}
10314 		len = SCTP_BUF_LEN(mout) + err_len;
10315 		if (err_len % 4) {
10316 			/* need pad at end of chunk */
10317 			uint32_t cpthis = 0;
10318 			int padlen;
10319 
10320 			padlen = 4 - (len % 4);
10321 			m_copyback(mout, len, padlen, (caddr_t)&cpthis);
10322 			len += padlen;
10323 		}
10324 		abm->msg.ch.chunk_length = htons(sizeof(abm->msg.ch) + err_len);
10325 	} else {
10326 		len = SCTP_BUF_LEN(mout);
10327 		abm->msg.ch.chunk_length = htons(sizeof(abm->msg.ch));
10328 	}
10329 
10330 	/* add checksum */
10331 	if ((sctp_no_csum_on_loopback) && SCTP_IS_IT_LOOPBACK(m)) {
10332 		abm->sh.checksum = 0;
10333 	} else {
10334 		abm->sh.checksum = sctp_calculate_sum(mout, NULL, iphlen_out);
10335 	}
10336 	if (SCTP_GET_HEADER_FOR_OUTPUT(o_pak)) {
10337 		/* no mbuf's */
10338 		sctp_m_freem(mout);
10339 		return;
10340 	}
10341 	if (iph_out != NULL) {
10342 		sctp_route_t ro;
10343 		struct sctp_tcb *stcb = NULL;
10344 		int ret;
10345 
10346 		/* zap the stack pointer to the route */
10347 		bzero(&ro, sizeof ro);
10348 		SCTPDBG(SCTP_DEBUG_OUTPUT2, "sctp_send_abort calling ip_output:\n");
10349 		SCTPDBG_PKT(SCTP_DEBUG_OUTPUT2, iph_out, &abm->sh);
10350 		/* set IPv4 length */
10351 		iph_out->ip_len = len;
10352 		/* out it goes */
10353 #ifdef  SCTP_PACKET_LOGGING
10354 		if (sctp_logging_level & SCTP_LAST_PACKET_TRACING)
10355 			sctp_packet_log(mout, len);
10356 #endif
10357 		SCTP_ATTACH_CHAIN(o_pak, mout, len);
10358 		SCTP_IP_OUTPUT(ret, o_pak, &ro, stcb, vrf_id);
10359 
10360 		/* Free the route if we got one back */
10361 		if (ro.ro_rt)
10362 			RTFREE(ro.ro_rt);
10363 	} else if (ip6_out != NULL) {
10364 		struct route_in6 ro;
10365 		int ret;
10366 		struct sctp_tcb *stcb = NULL;
10367 		struct ifnet *ifp = NULL;
10368 
10369 		/* zap the stack pointer to the route */
10370 		bzero(&ro, sizeof(ro));
10371 		SCTPDBG(SCTP_DEBUG_OUTPUT2, "sctp_send_abort calling ip6_output:\n");
10372 		SCTPDBG_PKT(SCTP_DEBUG_OUTPUT2, (struct ip *)ip6_out, &abm->sh);
10373 		ip6_out->ip6_plen = len - sizeof(*ip6_out);
10374 #ifdef  SCTP_PACKET_LOGGING
10375 		if (sctp_logging_level & SCTP_LAST_PACKET_TRACING)
10376 			sctp_packet_log(mout, len);
10377 #endif
10378 		SCTP_ATTACH_CHAIN(o_pak, mout, len);
10379 		SCTP_IP6_OUTPUT(ret, o_pak, &ro, &ifp, stcb, vrf_id);
10380 
10381 		/* Free the route if we got one back */
10382 		if (ro.ro_rt)
10383 			RTFREE(ro.ro_rt);
10384 	}
10385 	SCTP_STAT_INCR(sctps_sendpackets);
10386 	SCTP_STAT_INCR_COUNTER64(sctps_outpackets);
10387 }
10388 
10389 void
10390 sctp_send_operr_to(struct mbuf *m, int iphlen, struct mbuf *scm, uint32_t vtag,
10391     uint32_t vrf_id)
10392 {
10393 	struct mbuf *o_pak;
10394 	struct sctphdr *ihdr;
10395 	int retcode;
10396 	struct sctphdr *ohdr;
10397 	struct sctp_chunkhdr *ophdr;
10398 	struct ip *iph;
10399 	struct mbuf *mout;
10400 
10401 #ifdef SCTP_DEBUG
10402 	struct sockaddr_in6 lsa6, fsa6;
10403 
10404 #endif
10405 	uint32_t val;
10406 	struct mbuf *at;
10407 	int len;
10408 
10409 	iph = mtod(m, struct ip *);
10410 	ihdr = (struct sctphdr *)((caddr_t)iph + iphlen);
10411 
10412 	SCTP_BUF_PREPEND(scm, (sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr)), M_DONTWAIT);
10413 	if (scm == NULL) {
10414 		/* can't send because we can't add a mbuf */
10415 		return;
10416 	}
10417 	ohdr = mtod(scm, struct sctphdr *);
10418 	ohdr->src_port = ihdr->dest_port;
10419 	ohdr->dest_port = ihdr->src_port;
10420 	ohdr->v_tag = vtag;
10421 	ohdr->checksum = 0;
10422 	ophdr = (struct sctp_chunkhdr *)(ohdr + 1);
10423 	ophdr->chunk_type = SCTP_OPERATION_ERROR;
10424 	ophdr->chunk_flags = 0;
10425 	len = 0;
10426 	at = scm;
10427 	while (at) {
10428 		len += SCTP_BUF_LEN(at);
10429 		at = SCTP_BUF_NEXT(at);
10430 	}
10431 	ophdr->chunk_length = htons(len - sizeof(struct sctphdr));
10432 	if (len % 4) {
10433 		/* need padding */
10434 		uint32_t cpthis = 0;
10435 		int padlen;
10436 
10437 		padlen = 4 - (len % 4);
10438 		m_copyback(scm, len, padlen, (caddr_t)&cpthis);
10439 		len += padlen;
10440 	}
10441 	if ((sctp_no_csum_on_loopback) && SCTP_IS_IT_LOOPBACK(m)) {
10442 		val = 0;
10443 	} else {
10444 		val = sctp_calculate_sum(scm, NULL, 0);
10445 	}
10446 	mout = sctp_get_mbuf_for_msg(sizeof(struct ip6_hdr), 1, M_DONTWAIT, 1, MT_DATA);
10447 	if (mout == NULL) {
10448 		sctp_m_freem(scm);
10449 		return;
10450 	}
10451 	SCTP_BUF_NEXT(mout) = scm;
10452 	if (SCTP_GET_HEADER_FOR_OUTPUT(o_pak)) {
10453 		sctp_m_freem(mout);
10454 		return;
10455 	}
10456 	ohdr->checksum = val;
10457 	if (iph->ip_v == IPVERSION) {
10458 		/* V4 */
10459 		struct ip *out;
10460 		sctp_route_t ro;
10461 		struct sctp_tcb *stcb = NULL;
10462 
10463 		SCTP_BUF_LEN(mout) = sizeof(struct ip);
10464 		len += sizeof(struct ip);
10465 
10466 		bzero(&ro, sizeof ro);
10467 		out = mtod(mout, struct ip *);
10468 		out->ip_v = iph->ip_v;
10469 		out->ip_hl = (sizeof(struct ip) / 4);
10470 		out->ip_tos = iph->ip_tos;
10471 		out->ip_id = iph->ip_id;
10472 		out->ip_off = 0;
10473 		out->ip_ttl = MAXTTL;
10474 		out->ip_p = IPPROTO_SCTP;
10475 		out->ip_sum = 0;
10476 		out->ip_src = iph->ip_dst;
10477 		out->ip_dst = iph->ip_src;
10478 		out->ip_len = len;
10479 #ifdef  SCTP_PACKET_LOGGING
10480 		if (sctp_logging_level & SCTP_LAST_PACKET_TRACING)
10481 			sctp_packet_log(mout, len);
10482 #endif
10483 		SCTP_ATTACH_CHAIN(o_pak, mout, len);
10484 
10485 		SCTP_IP_OUTPUT(retcode, o_pak, &ro, stcb, vrf_id);
10486 
10487 		SCTP_STAT_INCR(sctps_sendpackets);
10488 		SCTP_STAT_INCR_COUNTER64(sctps_outpackets);
10489 		/* Free the route if we got one back */
10490 		if (ro.ro_rt)
10491 			RTFREE(ro.ro_rt);
10492 	} else {
10493 		/* V6 */
10494 		struct route_in6 ro;
10495 		int ret;
10496 		struct sctp_tcb *stcb = NULL;
10497 		struct ifnet *ifp = NULL;
10498 		struct ip6_hdr *out6, *in6;
10499 
10500 		SCTP_BUF_LEN(mout) = sizeof(struct ip6_hdr);
10501 		len += sizeof(struct ip6_hdr);
10502 		bzero(&ro, sizeof ro);
10503 		in6 = mtod(m, struct ip6_hdr *);
10504 		out6 = mtod(mout, struct ip6_hdr *);
10505 		out6->ip6_flow = in6->ip6_flow;
10506 		out6->ip6_hlim = ip6_defhlim;
10507 		out6->ip6_nxt = IPPROTO_SCTP;
10508 		out6->ip6_src = in6->ip6_dst;
10509 		out6->ip6_dst = in6->ip6_src;
10510 		out6->ip6_plen = len - sizeof(struct ip6_hdr);
10511 
10512 #ifdef SCTP_DEBUG
10513 		bzero(&lsa6, sizeof(lsa6));
10514 		lsa6.sin6_len = sizeof(lsa6);
10515 		lsa6.sin6_family = AF_INET6;
10516 		lsa6.sin6_addr = out6->ip6_src;
10517 		bzero(&fsa6, sizeof(fsa6));
10518 		fsa6.sin6_len = sizeof(fsa6);
10519 		fsa6.sin6_family = AF_INET6;
10520 		fsa6.sin6_addr = out6->ip6_dst;
10521 #endif
10522 		SCTPDBG(SCTP_DEBUG_OUTPUT2, "sctp_operr_to calling ipv6 output:\n");
10523 		SCTPDBG(SCTP_DEBUG_OUTPUT2, "src: ");
10524 		SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, (struct sockaddr *)&lsa6);
10525 		SCTPDBG(SCTP_DEBUG_OUTPUT2, "dst ");
10526 		SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, (struct sockaddr *)&fsa6);
10527 
10528 #ifdef  SCTP_PACKET_LOGGING
10529 		if (sctp_logging_level & SCTP_LAST_PACKET_TRACING)
10530 			sctp_packet_log(mout, len);
10531 #endif
10532 		SCTP_ATTACH_CHAIN(o_pak, mout, len);
10533 		SCTP_IP6_OUTPUT(ret, o_pak, &ro, &ifp, stcb, vrf_id);
10534 
10535 		SCTP_STAT_INCR(sctps_sendpackets);
10536 		SCTP_STAT_INCR_COUNTER64(sctps_outpackets);
10537 		/* Free the route if we got one back */
10538 		if (ro.ro_rt)
10539 			RTFREE(ro.ro_rt);
10540 	}
10541 }
10542 
10543 static struct mbuf *
10544 sctp_copy_resume(struct sctp_stream_queue_pending *sp,
10545     struct uio *uio,
10546     struct sctp_sndrcvinfo *srcv,
10547     int max_send_len,
10548     int user_marks_eor,
10549     int *error,
10550     uint32_t * sndout,
10551     struct mbuf **new_tail)
10552 {
10553 	struct mbuf *m;
10554 
10555 	m = m_uiotombuf(uio, M_WAITOK, max_send_len, 0,
10556 	    (M_PKTHDR | (user_marks_eor ? M_EOR : 0)));
10557 	if (m == NULL)
10558 		*error = ENOMEM;
10559 	else {
10560 		*sndout = m_length(m, NULL);
10561 		*new_tail = m_last(m);
10562 	}
10563 	return (m);
10564 }
10565 
10566 static int
10567 sctp_copy_one(struct sctp_stream_queue_pending *sp,
10568     struct uio *uio,
10569     int resv_upfront)
10570 {
10571 	int left;
10572 
10573 	left = sp->length;
10574 	sp->data = m_uiotombuf(uio, M_WAITOK, sp->length,
10575 	    resv_upfront, 0);
10576 	if (sp->data == NULL)
10577 		return (ENOMEM);
10578 
10579 	sp->tail_mbuf = m_last(sp->data);
10580 	return (0);
10581 }
10582 
10583 
10584 
10585 static struct sctp_stream_queue_pending *
10586 sctp_copy_it_in(struct sctp_tcb *stcb,
10587     struct sctp_association *asoc,
10588     struct sctp_sndrcvinfo *srcv,
10589     struct uio *uio,
10590     struct sctp_nets *net,
10591     int max_send_len,
10592     int user_marks_eor,
10593     int *error,
10594     int non_blocking)
10595 {
10596 	/*-
10597 	 * This routine must be very careful in its work. Protocol
10598 	 * processing is up and running so care must be taken to spl...()
10599 	 * when you need to do something that may effect the stcb/asoc. The
10600 	 * sb is locked however. When data is copied the protocol processing
10601 	 * should be enabled since this is a slower operation...
10602 	 */
10603 	struct sctp_stream_queue_pending *sp = NULL;
10604 	int resv_in_first;
10605 
10606 	*error = 0;
10607 	/* Unless E_EOR mode is on, we must make a send FIT in one call. */
10608 	if (((user_marks_eor == 0) && non_blocking) &&
10609 	    (uio->uio_resid > (int)SCTP_SB_LIMIT_SND(stcb->sctp_socket))) {
10610 		/* It will NEVER fit */
10611 		*error = EMSGSIZE;
10612 		goto out_now;
10613 	}
10614 	/* Now can we send this? */
10615 	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
10616 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
10617 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
10618 	    (asoc->state & SCTP_STATE_SHUTDOWN_PENDING)) {
10619 		/* got data while shutting down */
10620 		*error = ECONNRESET;
10621 		goto out_now;
10622 	}
10623 	sctp_alloc_a_strmoq(stcb, sp);
10624 	if (sp == NULL) {
10625 		*error = ENOMEM;
10626 		goto out_now;
10627 	}
10628 	sp->act_flags = 0;
10629 	sp->sender_all_done = 0;
10630 	sp->sinfo_flags = srcv->sinfo_flags;
10631 	sp->timetolive = srcv->sinfo_timetolive;
10632 	sp->ppid = srcv->sinfo_ppid;
10633 	sp->context = srcv->sinfo_context;
10634 	sp->strseq = 0;
10635 	(void)SCTP_GETTIME_TIMEVAL(&sp->ts);
10636 
10637 	sp->stream = srcv->sinfo_stream;
10638 	sp->length = min(uio->uio_resid, max_send_len);
10639 	if ((sp->length == (uint32_t) uio->uio_resid) &&
10640 	    ((user_marks_eor == 0) ||
10641 	    (srcv->sinfo_flags & SCTP_EOF) ||
10642 	    (user_marks_eor && (srcv->sinfo_flags & SCTP_EOR)))) {
10643 		sp->msg_is_complete = 1;
10644 	} else {
10645 		sp->msg_is_complete = 0;
10646 	}
10647 	sp->sender_all_done = 0;
10648 	sp->some_taken = 0;
10649 	sp->put_last_out = 0;
10650 	resv_in_first = sizeof(struct sctp_data_chunk);
10651 	sp->data = sp->tail_mbuf = NULL;
10652 	*error = sctp_copy_one(sp, uio, resv_in_first);
10653 	if (*error) {
10654 		sctp_free_a_strmoq(stcb, sp);
10655 		sp = NULL;
10656 	} else {
10657 		if (sp->sinfo_flags & SCTP_ADDR_OVER) {
10658 			sp->net = net;
10659 			sp->addr_over = 1;
10660 		} else {
10661 			sp->net = asoc->primary_destination;
10662 			sp->addr_over = 0;
10663 		}
10664 		atomic_add_int(&sp->net->ref_count, 1);
10665 		sctp_set_prsctp_policy(stcb, sp);
10666 	}
10667 out_now:
10668 	return (sp);
10669 }
10670 
10671 
10672 int
10673 sctp_sosend(struct socket *so,
10674     struct sockaddr *addr,
10675     struct uio *uio,
10676     struct mbuf *top,
10677     struct mbuf *control,
10678     int flags
10679     ,
10680     struct thread *p
10681 )
10682 {
10683 	struct sctp_inpcb *inp;
10684 	int error, use_rcvinfo = 0;
10685 	struct sctp_sndrcvinfo srcv;
10686 
10687 	inp = (struct sctp_inpcb *)so->so_pcb;
10688 	if (control) {
10689 		/* process cmsg snd/rcv info (maybe a assoc-id) */
10690 		if (sctp_find_cmsg(SCTP_SNDRCV, (void *)&srcv, control,
10691 		    sizeof(srcv))) {
10692 			/* got one */
10693 			use_rcvinfo = 1;
10694 		}
10695 	}
10696 	error = sctp_lower_sosend(so, addr, uio, top,
10697 	    control,
10698 	    flags,
10699 	    use_rcvinfo, &srcv
10700 	    ,p
10701 	    );
10702 	return (error);
10703 }
10704 
10705 
10706 int
10707 sctp_lower_sosend(struct socket *so,
10708     struct sockaddr *addr,
10709     struct uio *uio,
10710     struct mbuf *i_pak,
10711     struct mbuf *control,
10712     int flags,
10713     int use_rcvinfo,
10714     struct sctp_sndrcvinfo *srcv
10715     ,
10716     struct thread *p
10717 )
10718 {
10719 	unsigned int sndlen = 0, max_len;
10720 	int error, len;
10721 	struct mbuf *top = NULL;
10722 
10723 #if defined(__NetBSD__) || defined(__OpenBSD_)
10724 	int s;
10725 
10726 #endif
10727 	int queue_only = 0, queue_only_for_init = 0;
10728 	int free_cnt_applied = 0;
10729 	int un_sent = 0;
10730 	int now_filled = 0;
10731 	struct sctp_block_entry be;
10732 	struct sctp_inpcb *inp;
10733 	struct sctp_tcb *stcb = NULL;
10734 	struct timeval now;
10735 	struct sctp_nets *net;
10736 	struct sctp_association *asoc;
10737 	struct sctp_inpcb *t_inp;
10738 	int create_lock_applied = 0;
10739 	int nagle_applies = 0;
10740 	int some_on_control = 0;
10741 	int got_all_of_the_send = 0;
10742 	int hold_tcblock = 0;
10743 	int non_blocking = 0;
10744 	int temp_flags = 0;
10745 
10746 	error = 0;
10747 	net = NULL;
10748 	stcb = NULL;
10749 	asoc = NULL;
10750 	t_inp = inp = (struct sctp_inpcb *)so->so_pcb;
10751 	if (inp == NULL) {
10752 		error = EFAULT;
10753 		goto out_unlocked;
10754 	}
10755 	if ((uio == NULL) && (i_pak == NULL)) {
10756 		return (EINVAL);
10757 	}
10758 	atomic_add_int(&inp->total_sends, 1);
10759 	if (uio)
10760 		sndlen = uio->uio_resid;
10761 	else {
10762 		sndlen = SCTP_HEADER_LEN(i_pak);
10763 		top = SCTP_HEADER_TO_CHAIN(i_pak);
10764 	}
10765 	/*
10766 	 * Pre-screen address, if one is given the sin-len must be set
10767 	 * correctly!
10768 	 */
10769 	if (addr) {
10770 		if ((addr->sa_family == AF_INET) &&
10771 		    (addr->sa_len != sizeof(struct sockaddr_in))) {
10772 			error = EINVAL;
10773 			goto out_unlocked;
10774 		} else if ((addr->sa_family == AF_INET6) &&
10775 		    (addr->sa_len != sizeof(struct sockaddr_in6))) {
10776 			error = EINVAL;
10777 			goto out_unlocked;
10778 		}
10779 	}
10780 	hold_tcblock = 0;
10781 
10782 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) &&
10783 	    (inp->sctp_socket->so_qlimit)) {
10784 		/* The listener can NOT send */
10785 		error = EFAULT;
10786 		goto out_unlocked;
10787 	}
10788 	if ((use_rcvinfo) && srcv) {
10789 		if (INVALID_SINFO_FLAG(srcv->sinfo_flags) ||
10790 		    PR_SCTP_INVALID_POLICY(srcv->sinfo_flags)) {
10791 			error = EINVAL;
10792 			goto out_unlocked;
10793 		}
10794 		if (srcv->sinfo_flags)
10795 			SCTP_STAT_INCR(sctps_sends_with_flags);
10796 
10797 		if (srcv->sinfo_flags & SCTP_SENDALL) {
10798 			/* its a sendall */
10799 			error = sctp_sendall(inp, uio, top, srcv);
10800 			top = NULL;
10801 			goto out_unlocked;
10802 		}
10803 	}
10804 	/* now we must find the assoc */
10805 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) ||
10806 	    (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
10807 		SCTP_INP_RLOCK(inp);
10808 		stcb = LIST_FIRST(&inp->sctp_asoc_list);
10809 		if (stcb == NULL) {
10810 			SCTP_INP_RUNLOCK(inp);
10811 			error = ENOTCONN;
10812 			goto out_unlocked;
10813 		}
10814 		hold_tcblock = 0;
10815 		SCTP_INP_RUNLOCK(inp);
10816 		if (addr) {
10817 			/* Must locate the net structure if addr given */
10818 			net = sctp_findnet(stcb, addr);
10819 			if (net) {
10820 				/* validate port was 0 or correct */
10821 				struct sockaddr_in *sin;
10822 
10823 				sin = (struct sockaddr_in *)addr;
10824 				if ((sin->sin_port != 0) &&
10825 				    (sin->sin_port != stcb->rport)) {
10826 					net = NULL;
10827 				}
10828 			}
10829 			temp_flags |= SCTP_ADDR_OVER;
10830 		} else
10831 			net = stcb->asoc.primary_destination;
10832 		if (addr && (net == NULL)) {
10833 			/* Could not find address, was it legal */
10834 			if (addr->sa_family == AF_INET) {
10835 				struct sockaddr_in *sin;
10836 
10837 				sin = (struct sockaddr_in *)addr;
10838 				if (sin->sin_addr.s_addr == 0) {
10839 					if ((sin->sin_port == 0) ||
10840 					    (sin->sin_port == stcb->rport)) {
10841 						net = stcb->asoc.primary_destination;
10842 					}
10843 				}
10844 			} else {
10845 				struct sockaddr_in6 *sin6;
10846 
10847 				sin6 = (struct sockaddr_in6 *)addr;
10848 				if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
10849 					if ((sin6->sin6_port == 0) ||
10850 					    (sin6->sin6_port == stcb->rport)) {
10851 						net = stcb->asoc.primary_destination;
10852 					}
10853 				}
10854 			}
10855 		}
10856 		if (net == NULL) {
10857 			error = EINVAL;
10858 			goto out_unlocked;
10859 		}
10860 	} else if (use_rcvinfo && srcv && srcv->sinfo_assoc_id) {
10861 		stcb = sctp_findassociation_ep_asocid(inp, srcv->sinfo_assoc_id, 0);
10862 		if (stcb) {
10863 			if (addr)
10864 				/*
10865 				 * Must locate the net structure if addr
10866 				 * given
10867 				 */
10868 				net = sctp_findnet(stcb, addr);
10869 			else
10870 				net = stcb->asoc.primary_destination;
10871 			if ((srcv->sinfo_flags & SCTP_ADDR_OVER) &&
10872 			    ((net == NULL) || (addr == NULL))) {
10873 				struct sockaddr_in *sin;
10874 
10875 				if (addr == NULL) {
10876 					error = EINVAL;
10877 					goto out_unlocked;
10878 				}
10879 				sin = (struct sockaddr_in *)addr;
10880 				/* Validate port is 0 or correct */
10881 				if ((sin->sin_port != 0) &&
10882 				    (sin->sin_port != stcb->rport)) {
10883 					net = NULL;
10884 				}
10885 			}
10886 		}
10887 		hold_tcblock = 0;
10888 	} else if (addr) {
10889 		/*-
10890 		 * Since we did not use findep we must
10891 		 * increment it, and if we don't find a tcb
10892 		 * decrement it.
10893 		 */
10894 		SCTP_INP_WLOCK(inp);
10895 		SCTP_INP_INCR_REF(inp);
10896 		SCTP_INP_WUNLOCK(inp);
10897 		stcb = sctp_findassociation_ep_addr(&t_inp, addr, &net, NULL, NULL);
10898 		if (stcb == NULL) {
10899 			SCTP_INP_WLOCK(inp);
10900 			SCTP_INP_DECR_REF(inp);
10901 			SCTP_INP_WUNLOCK(inp);
10902 		} else {
10903 			hold_tcblock = 1;
10904 		}
10905 	}
10906 	if ((stcb == NULL) && (addr)) {
10907 		/* Possible implicit send? */
10908 		SCTP_ASOC_CREATE_LOCK(inp);
10909 		create_lock_applied = 1;
10910 		if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
10911 		    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
10912 			/* Should I really unlock ? */
10913 			error = EFAULT;
10914 			goto out_unlocked;
10915 
10916 		}
10917 		if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) &&
10918 		    (addr->sa_family == AF_INET6)) {
10919 			error = EINVAL;
10920 			goto out_unlocked;
10921 		}
10922 		SCTP_INP_WLOCK(inp);
10923 		SCTP_INP_INCR_REF(inp);
10924 		SCTP_INP_WUNLOCK(inp);
10925 		/* With the lock applied look again */
10926 		stcb = sctp_findassociation_ep_addr(&t_inp, addr, &net, NULL, NULL);
10927 		if (stcb == NULL) {
10928 			SCTP_INP_WLOCK(inp);
10929 			SCTP_INP_DECR_REF(inp);
10930 			SCTP_INP_WUNLOCK(inp);
10931 		} else {
10932 			hold_tcblock = 1;
10933 		}
10934 		if (t_inp != inp) {
10935 			error = ENOTCONN;
10936 			goto out_unlocked;
10937 		}
10938 	}
10939 	if (stcb == NULL) {
10940 		if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
10941 		    (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
10942 			error = ENOTCONN;
10943 			goto out_unlocked;
10944 		} else if (addr == NULL) {
10945 			error = ENOENT;
10946 			goto out_unlocked;
10947 		} else {
10948 			/*
10949 			 * UDP style, we must go ahead and start the INIT
10950 			 * process
10951 			 */
10952 			uint32_t vrf_id;
10953 
10954 			if ((use_rcvinfo) && (srcv) &&
10955 			    ((srcv->sinfo_flags & SCTP_ABORT) ||
10956 			    ((srcv->sinfo_flags & SCTP_EOF) &&
10957 			    (uio) &&
10958 			    (uio->uio_resid == 0)))) {
10959 				/*-
10960 				 * User asks to abort a non-existant assoc,
10961 				 * or EOF a non-existant assoc with no data
10962 				 */
10963 				error = ENOENT;
10964 				goto out_unlocked;
10965 			}
10966 			/* get an asoc/stcb struct */
10967 			vrf_id = inp->def_vrf_id;
10968 			stcb = sctp_aloc_assoc(inp, addr, 1, &error, 0, vrf_id);
10969 			if (stcb == NULL) {
10970 				/* Error is setup for us in the call */
10971 				goto out_unlocked;
10972 			}
10973 			if (create_lock_applied) {
10974 				SCTP_ASOC_CREATE_UNLOCK(inp);
10975 				create_lock_applied = 0;
10976 			} else {
10977 				SCTP_PRINTF("Huh-3? create lock should have been on??\n");
10978 			}
10979 			/*
10980 			 * Turn on queue only flag to prevent data from
10981 			 * being sent
10982 			 */
10983 			queue_only = 1;
10984 			asoc = &stcb->asoc;
10985 			asoc->state = SCTP_STATE_COOKIE_WAIT;
10986 			(void)SCTP_GETTIME_TIMEVAL(&asoc->time_entered);
10987 
10988 			/* initialize authentication params for the assoc */
10989 			sctp_initialize_auth_params(inp, stcb);
10990 
10991 			if (control) {
10992 				/*
10993 				 * see if a init structure exists in cmsg
10994 				 * headers
10995 				 */
10996 				struct sctp_initmsg initm;
10997 				int i;
10998 
10999 				if (sctp_find_cmsg(SCTP_INIT, (void *)&initm, control,
11000 				    sizeof(initm))) {
11001 					/*
11002 					 * we have an INIT override of the
11003 					 * default
11004 					 */
11005 					if (initm.sinit_max_attempts)
11006 						asoc->max_init_times = initm.sinit_max_attempts;
11007 					if (initm.sinit_num_ostreams)
11008 						asoc->pre_open_streams = initm.sinit_num_ostreams;
11009 					if (initm.sinit_max_instreams)
11010 						asoc->max_inbound_streams = initm.sinit_max_instreams;
11011 					if (initm.sinit_max_init_timeo)
11012 						asoc->initial_init_rto_max = initm.sinit_max_init_timeo;
11013 					if (asoc->streamoutcnt < asoc->pre_open_streams) {
11014 						/* Default is NOT correct */
11015 						SCTPDBG(SCTP_DEBUG_OUTPUT1, "Ok, defout:%d pre_open:%d\n",
11016 						    asoc->streamoutcnt, asoc->pre_open_streams);
11017 						/*
11018 						 * What happens if this
11019 						 * fails? we panic ...
11020 						 */
11021 						{
11022 							struct sctp_stream_out *tmp_str;
11023 							int had_lock = 0;
11024 
11025 							if (hold_tcblock) {
11026 								had_lock = 1;
11027 								SCTP_TCB_UNLOCK(stcb);
11028 							}
11029 							SCTP_MALLOC(tmp_str,
11030 							    struct sctp_stream_out *,
11031 							    (asoc->pre_open_streams *
11032 							    sizeof(struct sctp_stream_out)),
11033 							    SCTP_M_STRMO);
11034 							if (had_lock) {
11035 								SCTP_TCB_LOCK(stcb);
11036 							}
11037 							if (tmp_str != NULL) {
11038 								SCTP_FREE(asoc->strmout, SCTP_M_STRMO);
11039 								asoc->strmout = tmp_str;
11040 								asoc->streamoutcnt = asoc->pre_open_streams;
11041 							} else {
11042 								asoc->pre_open_streams = asoc->streamoutcnt;
11043 							}
11044 						}
11045 						for (i = 0; i < asoc->streamoutcnt; i++) {
11046 							/*-
11047 							 * inbound side must be set
11048 							 * to 0xffff, also NOTE when
11049 							 * we get the INIT-ACK back
11050 							 * (for INIT sender) we MUST
11051 							 * reduce the count
11052 							 * (streamoutcnt) but first
11053 							 * check if we sent to any
11054 							 * of the upper streams that
11055 							 * were dropped (if some
11056 							 * were). Those that were
11057 							 * dropped must be notified
11058 							 * to the upper layer as
11059 							 * failed to send.
11060 							 */
11061 							asoc->strmout[i].next_sequence_sent = 0x0;
11062 							TAILQ_INIT(&asoc->strmout[i].outqueue);
11063 							asoc->strmout[i].stream_no = i;
11064 							asoc->strmout[i].last_msg_incomplete = 0;
11065 							asoc->strmout[i].next_spoke.tqe_next = 0;
11066 							asoc->strmout[i].next_spoke.tqe_prev = 0;
11067 						}
11068 					}
11069 				}
11070 			}
11071 			hold_tcblock = 1;
11072 			/* out with the INIT */
11073 			queue_only_for_init = 1;
11074 			/*-
11075 			 * we may want to dig in after this call and adjust the MTU
11076 			 * value. It defaulted to 1500 (constant) but the ro
11077 			 * structure may now have an update and thus we may need to
11078 			 * change it BEFORE we append the message.
11079 			 */
11080 			net = stcb->asoc.primary_destination;
11081 			asoc = &stcb->asoc;
11082 		}
11083 	}
11084 	if ((SCTP_SO_IS_NBIO(so)
11085 	    || (flags & MSG_NBIO)
11086 	    )) {
11087 		non_blocking = 1;
11088 	}
11089 	asoc = &stcb->asoc;
11090 
11091 	if (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_NO_FRAGMENT)) {
11092 		if (sndlen > asoc->smallest_mtu) {
11093 			error = EMSGSIZE;
11094 			goto out_unlocked;
11095 		}
11096 	}
11097 	/* would we block? */
11098 	if (non_blocking) {
11099 		if ((SCTP_SB_LIMIT_SND(so) <
11100 		    (sndlen + stcb->asoc.total_output_queue_size)) ||
11101 		    (stcb->asoc.chunks_on_out_queue >
11102 		    sctp_max_chunks_on_queue)) {
11103 			error = EWOULDBLOCK;
11104 			atomic_add_int(&stcb->sctp_ep->total_nospaces, 1);
11105 			goto out_unlocked;
11106 		}
11107 	}
11108 	/* Keep the stcb from being freed under our feet */
11109 	if (free_cnt_applied)
11110 		panic("refcnt already incremented");
11111 	atomic_add_int(&stcb->asoc.refcnt, 1);
11112 	free_cnt_applied = 1;
11113 
11114 	if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
11115 		error = ECONNRESET;
11116 		goto out_unlocked;
11117 	}
11118 	if (create_lock_applied) {
11119 		SCTP_ASOC_CREATE_UNLOCK(inp);
11120 		create_lock_applied = 0;
11121 	}
11122 	if (asoc->stream_reset_outstanding) {
11123 		/*
11124 		 * Can't queue any data while stream reset is underway.
11125 		 */
11126 		error = EAGAIN;
11127 		goto out_unlocked;
11128 	}
11129 	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
11130 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)) {
11131 		queue_only = 1;
11132 	}
11133 	if ((use_rcvinfo == 0) || (srcv == NULL)) {
11134 		/* Grab the default stuff from the asoc */
11135 		srcv = (struct sctp_sndrcvinfo *)&stcb->asoc.def_send;
11136 	}
11137 	/* we are now done with all control */
11138 	if (control) {
11139 		sctp_m_freem(control);
11140 		control = NULL;
11141 	}
11142 	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
11143 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
11144 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
11145 	    (asoc->state & SCTP_STATE_SHUTDOWN_PENDING)) {
11146 		if ((use_rcvinfo) &&
11147 		    (srcv->sinfo_flags & SCTP_ABORT)) {
11148 			;
11149 		} else {
11150 			error = ECONNRESET;
11151 			goto out_unlocked;
11152 		}
11153 	}
11154 	/* Ok, we will attempt a msgsnd :> */
11155 	if (p) {
11156 		p->td_ru.ru_msgsnd++;
11157 	}
11158 	if (stcb) {
11159 		if (((srcv->sinfo_flags | temp_flags) & SCTP_ADDR_OVER) == 0) {
11160 			net = stcb->asoc.primary_destination;
11161 		}
11162 	}
11163 	if (net == NULL) {
11164 		error = EINVAL;
11165 		goto out_unlocked;
11166 	}
11167 	if ((net->flight_size > net->cwnd) && (sctp_cmt_on_off == 0)) {
11168 		/*-
11169 		 * CMT: Added check for CMT above. net above is the primary
11170 		 * dest. If CMT is ON, sender should always attempt to send
11171 		 * with the output routine sctp_fill_outqueue() that loops
11172 		 * through all destination addresses. Therefore, if CMT is
11173 		 * ON, queue_only is NOT set to 1 here, so that
11174 		 * sctp_chunk_output() can be called below.
11175 		 */
11176 		queue_only = 1;
11177 
11178 	} else if (asoc->ifp_had_enobuf) {
11179 		SCTP_STAT_INCR(sctps_ifnomemqueued);
11180 		if (net->flight_size > (net->mtu * 2))
11181 			queue_only = 1;
11182 		asoc->ifp_had_enobuf = 0;
11183 	} else {
11184 		un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
11185 		    ((stcb->asoc.chunks_on_out_queue - stcb->asoc.total_flight_count) * sizeof(struct sctp_data_chunk)));
11186 	}
11187 	/* Are we aborting? */
11188 	if (srcv->sinfo_flags & SCTP_ABORT) {
11189 		struct mbuf *mm;
11190 		int tot_demand, tot_out = 0, max_out;
11191 
11192 		SCTP_STAT_INCR(sctps_sends_with_abort);
11193 		if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
11194 		    (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)) {
11195 			/* It has to be up before we abort */
11196 			/* how big is the user initiated abort? */
11197 			error = EINVAL;
11198 			goto out;
11199 		}
11200 		if (hold_tcblock) {
11201 			SCTP_TCB_UNLOCK(stcb);
11202 			hold_tcblock = 0;
11203 		}
11204 		if (top) {
11205 			struct mbuf *cntm;
11206 
11207 			mm = sctp_get_mbuf_for_msg(1, 0, M_WAIT, 1, MT_DATA);
11208 
11209 			cntm = top;
11210 			while (cntm) {
11211 				tot_out += SCTP_BUF_LEN(cntm);
11212 				cntm = SCTP_BUF_NEXT(cntm);
11213 			}
11214 			tot_demand = (tot_out + sizeof(struct sctp_paramhdr));
11215 		} else {
11216 			/* Must fit in a MTU */
11217 			if (uio)
11218 				tot_out = uio->uio_resid;
11219 			tot_demand = (tot_out + sizeof(struct sctp_paramhdr));
11220 			mm = sctp_get_mbuf_for_msg(tot_demand, 0, M_WAIT, 1, MT_DATA);
11221 		}
11222 		if (mm == NULL) {
11223 			error = ENOMEM;
11224 			goto out;
11225 		}
11226 		max_out = asoc->smallest_mtu - sizeof(struct sctp_paramhdr);
11227 		max_out -= sizeof(struct sctp_abort_msg);
11228 		if (tot_out > max_out) {
11229 			tot_out = max_out;
11230 		}
11231 		if (mm) {
11232 			struct sctp_paramhdr *ph;
11233 
11234 			/* now move forward the data pointer */
11235 			ph = mtod(mm, struct sctp_paramhdr *);
11236 			ph->param_type = htons(SCTP_CAUSE_USER_INITIATED_ABT);
11237 			ph->param_length = htons((sizeof(struct sctp_paramhdr) + tot_out));
11238 			ph++;
11239 			SCTP_BUF_LEN(mm) = tot_out + sizeof(struct sctp_paramhdr);
11240 			if (top == NULL) {
11241 				error = uiomove((caddr_t)ph, (int)tot_out, uio);
11242 				if (error) {
11243 					/*-
11244 					 * Here if we can't get his data we
11245 					 * still abort we just don't get to
11246 					 * send the users note :-0
11247 					 */
11248 					sctp_m_freem(mm);
11249 					mm = NULL;
11250 				}
11251 			} else {
11252 				SCTP_BUF_NEXT(mm) = top;
11253 			}
11254 		}
11255 		if (hold_tcblock == 0) {
11256 			SCTP_TCB_LOCK(stcb);
11257 			hold_tcblock = 1;
11258 		}
11259 		atomic_add_int(&stcb->asoc.refcnt, -1);
11260 		free_cnt_applied = 0;
11261 		/* release this lock, otherwise we hang on ourselves */
11262 		sctp_abort_an_association(stcb->sctp_ep, stcb,
11263 		    SCTP_RESPONSE_TO_USER_REQ,
11264 		    mm);
11265 		/* now relock the stcb so everything is sane */
11266 		hold_tcblock = 0;
11267 		stcb = NULL;
11268 		goto out_unlocked;
11269 	}
11270 	/* Calculate the maximum we can send */
11271 	if (SCTP_SB_LIMIT_SND(so) > stcb->asoc.total_output_queue_size) {
11272 		max_len = SCTP_SB_LIMIT_SND(so) - stcb->asoc.total_output_queue_size;
11273 	} else {
11274 		max_len = 0;
11275 	}
11276 	if (hold_tcblock) {
11277 		SCTP_TCB_UNLOCK(stcb);
11278 		hold_tcblock = 0;
11279 	}
11280 	/* Is the stream no. valid? */
11281 	if (srcv->sinfo_stream >= asoc->streamoutcnt) {
11282 		/* Invalid stream number */
11283 		error = EINVAL;
11284 		goto out_unlocked;
11285 	}
11286 	if (asoc->strmout == NULL) {
11287 		/* huh? software error */
11288 		error = EFAULT;
11289 		goto out_unlocked;
11290 	}
11291 	len = 0;
11292 	if (max_len < sctp_add_more_threshold) {
11293 		/* No room right no ! */
11294 		SOCKBUF_LOCK(&so->so_snd);
11295 		while (SCTP_SB_LIMIT_SND(so) < (stcb->asoc.total_output_queue_size + sctp_add_more_threshold)) {
11296 			if (sctp_logging_level & SCTP_BLK_LOGGING_ENABLE) {
11297 				sctp_log_block(SCTP_BLOCK_LOG_INTO_BLKA,
11298 				    so, asoc, uio->uio_resid);
11299 			}
11300 			be.error = 0;
11301 			stcb->block_entry = &be;
11302 			error = sbwait(&so->so_snd);
11303 			stcb->block_entry = NULL;
11304 			if (error || so->so_error || be.error) {
11305 				if (error == 0) {
11306 					if (so->so_error)
11307 						error = so->so_error;
11308 					if (be.error) {
11309 						error = be.error;
11310 					}
11311 				}
11312 				SOCKBUF_UNLOCK(&so->so_snd);
11313 				goto out_unlocked;
11314 			}
11315 			if (sctp_logging_level & SCTP_BLK_LOGGING_ENABLE) {
11316 				sctp_log_block(SCTP_BLOCK_LOG_OUTOF_BLK,
11317 				    so, asoc, stcb->asoc.total_output_queue_size);
11318 			}
11319 			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
11320 				goto out_unlocked;
11321 			}
11322 		}
11323 		if (SCTP_SB_LIMIT_SND(so) > stcb->asoc.total_output_queue_size) {
11324 			max_len = SCTP_SB_LIMIT_SND(so) - stcb->asoc.total_output_queue_size;
11325 		} else {
11326 			max_len = 0;
11327 		}
11328 		SOCKBUF_UNLOCK(&so->so_snd);
11329 	}
11330 	if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
11331 		goto out_unlocked;
11332 	}
11333 	atomic_add_int(&stcb->total_sends, 1);
11334 	if (top == NULL) {
11335 		struct sctp_stream_queue_pending *sp;
11336 
11337 #ifdef INVARIANTS
11338 		struct sctp_stream_queue_pending *msp;
11339 
11340 #endif
11341 		struct sctp_stream_out *strm;
11342 		uint32_t sndout, initial_out;
11343 		int user_marks_eor;
11344 
11345 		if (uio->uio_resid == 0) {
11346 			if (srcv->sinfo_flags & SCTP_EOF) {
11347 				got_all_of_the_send = 1;
11348 				goto dataless_eof;
11349 			} else {
11350 				error = EINVAL;
11351 				goto out;
11352 			}
11353 		}
11354 		initial_out = uio->uio_resid;
11355 
11356 		SCTP_TCB_SEND_LOCK(stcb);
11357 		if ((asoc->stream_locked) &&
11358 		    (asoc->stream_locked_on != srcv->sinfo_stream)) {
11359 			SCTP_TCB_SEND_UNLOCK(stcb);
11360 			error = EAGAIN;
11361 			goto out;
11362 		}
11363 		SCTP_TCB_SEND_UNLOCK(stcb);
11364 
11365 		strm = &stcb->asoc.strmout[srcv->sinfo_stream];
11366 		user_marks_eor = sctp_is_feature_on(inp, SCTP_PCB_FLAGS_EXPLICIT_EOR);
11367 		if (strm->last_msg_incomplete == 0) {
11368 	do_a_copy_in:
11369 			sp = sctp_copy_it_in(stcb, asoc, srcv, uio, net, max_len, user_marks_eor, &error, non_blocking);
11370 			if ((sp == NULL) || (error)) {
11371 				goto out;
11372 			}
11373 			SCTP_TCB_SEND_LOCK(stcb);
11374 #ifdef INVARIANTS
11375 			msp = TAILQ_LAST(&strm->outqueue, sctp_streamhead);
11376 			if (msp && (msp->msg_is_complete == 0))
11377 				panic("Huh, new mesg and old not done?");
11378 #endif
11379 			if (sp->msg_is_complete) {
11380 				strm->last_msg_incomplete = 0;
11381 				asoc->stream_locked = 0;
11382 			} else {
11383 				/*
11384 				 * Just got locked to this guy in case of an
11385 				 * interupt.
11386 				 */
11387 				strm->last_msg_incomplete = 1;
11388 				asoc->stream_locked = 1;
11389 				asoc->stream_locked_on = srcv->sinfo_stream;
11390 				sp->sender_all_done = 0;
11391 			}
11392 			sctp_snd_sb_alloc(stcb, sp->length);
11393 			atomic_add_int(&asoc->stream_queue_cnt, 1);
11394 			if ((srcv->sinfo_flags & SCTP_UNORDERED) == 0) {
11395 				sp->strseq = strm->next_sequence_sent;
11396 #ifdef SCTP_LOG_SENDING_STR
11397 				sctp_misc_ints(SCTP_STRMOUT_LOG_ASSIGN,
11398 				    (uintptr_t) stcb, (uintptr_t) sp,
11399 				    (uint32_t) ((srcv->sinfo_stream << 16) | sp->strseq), 0);
11400 #endif
11401 				strm->next_sequence_sent++;
11402 			} else {
11403 				SCTP_STAT_INCR(sctps_sends_with_unord);
11404 			}
11405 			TAILQ_INSERT_TAIL(&strm->outqueue, sp, next);
11406 			if ((strm->next_spoke.tqe_next == NULL) &&
11407 			    (strm->next_spoke.tqe_prev == NULL)) {
11408 				/* Not on wheel, insert */
11409 				sctp_insert_on_wheel(stcb, asoc, strm, 1);
11410 			}
11411 			SCTP_TCB_SEND_UNLOCK(stcb);
11412 		} else {
11413 			SCTP_TCB_SEND_LOCK(stcb);
11414 			sp = TAILQ_LAST(&strm->outqueue, sctp_streamhead);
11415 			SCTP_TCB_SEND_UNLOCK(stcb);
11416 			if (sp == NULL) {
11417 				/* ???? Huh ??? last msg is gone */
11418 #ifdef INVARIANTS
11419 				panic("Warning: Last msg marked incomplete, yet nothing left?");
11420 #else
11421 				SCTP_PRINTF("Warning: Last msg marked incomplete, yet nothing left?\n");
11422 				strm->last_msg_incomplete = 0;
11423 #endif
11424 				goto do_a_copy_in;
11425 
11426 			}
11427 		}
11428 		while (uio->uio_resid > 0) {
11429 			/* How much room do we have? */
11430 			struct mbuf *new_tail, *mm;
11431 
11432 			if (SCTP_SB_LIMIT_SND(so) > stcb->asoc.total_output_queue_size)
11433 				max_len = SCTP_SB_LIMIT_SND(so) - stcb->asoc.total_output_queue_size;
11434 			else
11435 				max_len = 0;
11436 
11437 			if ((max_len > sctp_add_more_threshold) ||
11438 			    (uio->uio_resid &&
11439 			    (uio->uio_resid < (int)max_len))) {
11440 				sndout = 0;
11441 				new_tail = NULL;
11442 				if (hold_tcblock) {
11443 					SCTP_TCB_UNLOCK(stcb);
11444 					hold_tcblock = 0;
11445 				}
11446 				mm = sctp_copy_resume(sp, uio, srcv, max_len, user_marks_eor, &error, &sndout, &new_tail);
11447 				if ((mm == NULL) || error) {
11448 					if (mm) {
11449 						sctp_m_freem(mm);
11450 					}
11451 					goto out;
11452 				}
11453 				/* Update the mbuf and count */
11454 				SCTP_TCB_SEND_LOCK(stcb);
11455 				if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
11456 					/*
11457 					 * we need to get out. Peer probably
11458 					 * aborted.
11459 					 */
11460 					sctp_m_freem(mm);
11461 					if (stcb->asoc.state & SCTP_PCB_FLAGS_WAS_ABORTED)
11462 						error = ECONNRESET;
11463 					SCTP_TCB_SEND_UNLOCK(stcb);
11464 					goto out;
11465 				}
11466 				if (sp->tail_mbuf) {
11467 					/* tack it to the end */
11468 					SCTP_BUF_NEXT(sp->tail_mbuf) = mm;
11469 					sp->tail_mbuf = new_tail;
11470 				} else {
11471 					/* A stolen mbuf */
11472 					sp->data = mm;
11473 					sp->tail_mbuf = new_tail;
11474 				}
11475 				sctp_snd_sb_alloc(stcb, sndout);
11476 				atomic_add_int(&sp->length, sndout);
11477 				len += sndout;
11478 
11479 				/* Did we reach EOR? */
11480 				if ((uio->uio_resid == 0) &&
11481 				    ((user_marks_eor == 0) ||
11482 				    (srcv->sinfo_flags & SCTP_EOF) ||
11483 				    (user_marks_eor && (srcv->sinfo_flags & SCTP_EOR)))
11484 				    ) {
11485 					sp->msg_is_complete = 1;
11486 				} else {
11487 					sp->msg_is_complete = 0;
11488 				}
11489 				SCTP_TCB_SEND_UNLOCK(stcb);
11490 			}
11491 			if (uio->uio_resid == 0) {
11492 				/* got it all? */
11493 				continue;
11494 			}
11495 			/* PR-SCTP? */
11496 			if ((asoc->peer_supports_prsctp) && (asoc->sent_queue_cnt_removeable > 0)) {
11497 				/*
11498 				 * This is ugly but we must assure locking
11499 				 * order
11500 				 */
11501 				if (hold_tcblock == 0) {
11502 					SCTP_TCB_LOCK(stcb);
11503 					hold_tcblock = 1;
11504 				}
11505 				sctp_prune_prsctp(stcb, asoc, srcv, sndlen);
11506 				if (SCTP_SB_LIMIT_SND(so) > stcb->asoc.total_output_queue_size)
11507 					max_len = SCTP_SB_LIMIT_SND(so) - stcb->asoc.total_output_queue_size;
11508 				else
11509 					max_len = 0;
11510 				if (max_len > 0) {
11511 					continue;
11512 				}
11513 				SCTP_TCB_UNLOCK(stcb);
11514 				hold_tcblock = 0;
11515 			}
11516 			/* wait for space now */
11517 			if (non_blocking) {
11518 				/* Non-blocking io in place out */
11519 				goto skip_out_eof;
11520 			}
11521 			if ((net->flight_size > net->cwnd) &&
11522 			    (sctp_cmt_on_off == 0)) {
11523 				queue_only = 1;
11524 
11525 			} else if (asoc->ifp_had_enobuf) {
11526 				SCTP_STAT_INCR(sctps_ifnomemqueued);
11527 				if (net->flight_size > (net->mtu * 2)) {
11528 					queue_only = 1;
11529 				} else {
11530 					queue_only = 0;
11531 				}
11532 				asoc->ifp_had_enobuf = 0;
11533 				un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
11534 				    ((stcb->asoc.chunks_on_out_queue - stcb->asoc.total_flight_count) *
11535 				    sizeof(struct sctp_data_chunk)));
11536 			} else {
11537 				un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
11538 				    ((stcb->asoc.chunks_on_out_queue - stcb->asoc.total_flight_count) *
11539 				    sizeof(struct sctp_data_chunk)));
11540 				if (net->flight_size > (net->mtu * stcb->asoc.max_burst)) {
11541 					queue_only = 1;
11542 					SCTP_STAT_INCR(sctps_send_burst_avoid);
11543 				} else if (net->flight_size > net->cwnd) {
11544 					queue_only = 1;
11545 					SCTP_STAT_INCR(sctps_send_cwnd_avoid);
11546 				} else {
11547 					queue_only = 0;
11548 				}
11549 			}
11550 			if ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY)) &&
11551 			    (stcb->asoc.total_flight > 0) &&
11552 			    (un_sent < (int)(stcb->asoc.smallest_mtu - SCTP_MIN_OVERHEAD))
11553 			    ) {
11554 
11555 				/*-
11556 				 * Ok, Nagle is set on and we have data outstanding.
11557 				 * Don't send anything and let SACKs drive out the
11558 				 * data unless wen have a "full" segment to send.
11559 				 */
11560 				if (sctp_logging_level & SCTP_NAGLE_LOGGING_ENABLE) {
11561 					sctp_log_nagle_event(stcb, SCTP_NAGLE_APPLIED);
11562 				}
11563 				SCTP_STAT_INCR(sctps_naglequeued);
11564 				nagle_applies = 1;
11565 			} else {
11566 				if (sctp_logging_level & SCTP_NAGLE_LOGGING_ENABLE) {
11567 					if (sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY))
11568 						sctp_log_nagle_event(stcb, SCTP_NAGLE_SKIPPED);
11569 				}
11570 				SCTP_STAT_INCR(sctps_naglesent);
11571 				nagle_applies = 0;
11572 			}
11573 			/* What about the INIT, send it maybe */
11574 			if (sctp_logging_level & SCTP_BLK_LOGGING_ENABLE) {
11575 
11576 				sctp_misc_ints(SCTP_CWNDLOG_PRESEND, queue_only_for_init, queue_only,
11577 				    nagle_applies, un_sent);
11578 				sctp_misc_ints(SCTP_CWNDLOG_PRESEND, stcb->asoc.total_output_queue_size,
11579 				    stcb->asoc.total_flight,
11580 				    stcb->asoc.chunks_on_out_queue, stcb->asoc.total_flight_count);
11581 			}
11582 			if (queue_only_for_init) {
11583 				if (hold_tcblock == 0) {
11584 					SCTP_TCB_LOCK(stcb);
11585 					hold_tcblock = 1;
11586 				}
11587 				if (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_OPEN) {
11588 					/* a collision took us forward? */
11589 					queue_only_for_init = 0;
11590 					queue_only = 0;
11591 				} else {
11592 					sctp_send_initiate(inp, stcb);
11593 					stcb->asoc.state = SCTP_STATE_COOKIE_WAIT;
11594 					queue_only_for_init = 0;
11595 					queue_only = 1;
11596 				}
11597 			}
11598 			if ((queue_only == 0) && (nagle_applies == 0)
11599 			    ) {
11600 				/*-
11601 				 * need to start chunk output
11602 				 * before blocking.. note that if
11603 				 * a lock is already applied, then
11604 				 * the input via the net is happening
11605 				 * and I don't need to start output :-D
11606 				 */
11607 				if (hold_tcblock == 0) {
11608 					if (SCTP_TCB_TRYLOCK(stcb)) {
11609 						hold_tcblock = 1;
11610 						sctp_chunk_output(inp,
11611 						    stcb,
11612 						    SCTP_OUTPUT_FROM_USR_SEND);
11613 
11614 					}
11615 				} else {
11616 					sctp_chunk_output(inp,
11617 					    stcb,
11618 					    SCTP_OUTPUT_FROM_USR_SEND);
11619 				}
11620 				if (hold_tcblock == 1) {
11621 					SCTP_TCB_UNLOCK(stcb);
11622 					hold_tcblock = 0;
11623 				}
11624 			}
11625 			SOCKBUF_LOCK(&so->so_snd);
11626 			/*-
11627 			 * This is a bit strange, but I think it will
11628 			 * work. The total_output_queue_size is locked and
11629 			 * protected by the TCB_LOCK, which we just released.
11630 			 * There is a race that can occur between releasing it
11631 			 * above, and me getting the socket lock, where sacks
11632 			 * come in but we have not put the SB_WAIT on the
11633 			 * so_snd buffer to get the wakeup. After the LOCK
11634 			 * is applied the sack_processing will also need to
11635 			 * LOCK the so->so_snd to do the actual sowwakeup(). So
11636 			 * once we have the socket buffer lock if we recheck the
11637 			 * size we KNOW we will get to sleep safely with the
11638 			 * wakeup flag in place.
11639 			 */
11640 			if (SCTP_SB_LIMIT_SND(so) < (stcb->asoc.total_output_queue_size + sctp_add_more_threshold)) {
11641 				if (sctp_logging_level & SCTP_BLK_LOGGING_ENABLE) {
11642 					sctp_log_block(SCTP_BLOCK_LOG_INTO_BLK,
11643 					    so, asoc, uio->uio_resid);
11644 				}
11645 				be.error = 0;
11646 				stcb->block_entry = &be;
11647 				error = sbwait(&so->so_snd);
11648 				stcb->block_entry = NULL;
11649 
11650 				if (error || so->so_error || be.error) {
11651 					if (error == 0) {
11652 						if (so->so_error)
11653 							error = so->so_error;
11654 						if (be.error) {
11655 							error = be.error;
11656 						}
11657 					}
11658 					SOCKBUF_UNLOCK(&so->so_snd);
11659 					goto out_unlocked;
11660 				}
11661 				if (sctp_logging_level & SCTP_BLK_LOGGING_ENABLE) {
11662 					sctp_log_block(SCTP_BLOCK_LOG_OUTOF_BLK,
11663 					    so, asoc, stcb->asoc.total_output_queue_size);
11664 				}
11665 			}
11666 			SOCKBUF_UNLOCK(&so->so_snd);
11667 			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
11668 				goto out_unlocked;
11669 			}
11670 		}
11671 		SCTP_TCB_SEND_LOCK(stcb);
11672 		if (sp) {
11673 			if (sp->msg_is_complete == 0) {
11674 				strm->last_msg_incomplete = 1;
11675 				asoc->stream_locked = 1;
11676 				asoc->stream_locked_on = srcv->sinfo_stream;
11677 			} else {
11678 				sp->sender_all_done = 1;
11679 				strm->last_msg_incomplete = 0;
11680 				asoc->stream_locked = 0;
11681 			}
11682 		} else {
11683 			SCTP_PRINTF("Huh no sp TSNH?\n");
11684 			strm->last_msg_incomplete = 0;
11685 			asoc->stream_locked = 0;
11686 		}
11687 		SCTP_TCB_SEND_UNLOCK(stcb);
11688 		if (uio->uio_resid == 0) {
11689 			got_all_of_the_send = 1;
11690 		}
11691 	} else if (top) {
11692 		/* We send in a 0, since we do NOT have any locks */
11693 		error = sctp_msg_append(stcb, net, top, srcv, 0);
11694 		top = NULL;
11695 	}
11696 	if (error) {
11697 		goto out;
11698 	}
11699 dataless_eof:
11700 	/* EOF thing ? */
11701 	if ((srcv->sinfo_flags & SCTP_EOF) &&
11702 	    (got_all_of_the_send == 1) &&
11703 	    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_UDPTYPE)
11704 	    ) {
11705 		int cnt;
11706 
11707 		SCTP_STAT_INCR(sctps_sends_with_eof);
11708 		error = 0;
11709 		if (hold_tcblock == 0) {
11710 			SCTP_TCB_LOCK(stcb);
11711 			hold_tcblock = 1;
11712 		}
11713 		cnt = sctp_is_there_unsent_data(stcb);
11714 		if (TAILQ_EMPTY(&asoc->send_queue) &&
11715 		    TAILQ_EMPTY(&asoc->sent_queue) &&
11716 		    (cnt == 0)) {
11717 			if (asoc->locked_on_sending) {
11718 				goto abort_anyway;
11719 			}
11720 			/* there is nothing queued to send, so I'm done... */
11721 			if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
11722 			    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
11723 			    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
11724 				/* only send SHUTDOWN the first time through */
11725 				sctp_send_shutdown(stcb, stcb->asoc.primary_destination);
11726 				if (SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) {
11727 					SCTP_STAT_DECR_GAUGE32(sctps_currestab);
11728 				}
11729 				asoc->state = SCTP_STATE_SHUTDOWN_SENT;
11730 				sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, stcb->sctp_ep, stcb,
11731 				    asoc->primary_destination);
11732 				sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
11733 				    asoc->primary_destination);
11734 			}
11735 		} else {
11736 			/*-
11737 			 * we still got (or just got) data to send, so set
11738 			 * SHUTDOWN_PENDING
11739 			 */
11740 			/*-
11741 			 * XXX sockets draft says that SCTP_EOF should be
11742 			 * sent with no data.  currently, we will allow user
11743 			 * data to be sent first and move to
11744 			 * SHUTDOWN-PENDING
11745 			 */
11746 			if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
11747 			    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
11748 			    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
11749 				if (hold_tcblock == 0) {
11750 					SCTP_TCB_LOCK(stcb);
11751 					hold_tcblock = 1;
11752 				}
11753 				if (asoc->locked_on_sending) {
11754 					/* Locked to send out the data */
11755 					struct sctp_stream_queue_pending *sp;
11756 
11757 					sp = TAILQ_LAST(&asoc->locked_on_sending->outqueue, sctp_streamhead);
11758 					if (sp) {
11759 						if ((sp->length == 0) && (sp->msg_is_complete == 0))
11760 							asoc->state |= SCTP_STATE_PARTIAL_MSG_LEFT;
11761 					}
11762 				}
11763 				asoc->state |= SCTP_STATE_SHUTDOWN_PENDING;
11764 				if (TAILQ_EMPTY(&asoc->send_queue) &&
11765 				    TAILQ_EMPTY(&asoc->sent_queue) &&
11766 				    (asoc->state & SCTP_STATE_PARTIAL_MSG_LEFT)) {
11767 			abort_anyway:
11768 					if (free_cnt_applied) {
11769 						atomic_add_int(&stcb->asoc.refcnt, -1);
11770 						free_cnt_applied = 0;
11771 					}
11772 					sctp_abort_an_association(stcb->sctp_ep, stcb,
11773 					    SCTP_RESPONSE_TO_USER_REQ,
11774 					    NULL);
11775 					/*
11776 					 * now relock the stcb so everything
11777 					 * is sane
11778 					 */
11779 					hold_tcblock = 0;
11780 					stcb = NULL;
11781 					goto out;
11782 				}
11783 				sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
11784 				    asoc->primary_destination);
11785 			}
11786 		}
11787 	}
11788 skip_out_eof:
11789 	if (!TAILQ_EMPTY(&stcb->asoc.control_send_queue)) {
11790 		some_on_control = 1;
11791 	}
11792 	if ((net->flight_size > net->cwnd) &&
11793 	    (sctp_cmt_on_off == 0)) {
11794 		queue_only = 1;
11795 	} else if (asoc->ifp_had_enobuf) {
11796 		SCTP_STAT_INCR(sctps_ifnomemqueued);
11797 		if (net->flight_size > (net->mtu * 2)) {
11798 			queue_only = 1;
11799 		} else {
11800 			queue_only = 0;
11801 		}
11802 		asoc->ifp_had_enobuf = 0;
11803 		un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
11804 		    ((stcb->asoc.chunks_on_out_queue - stcb->asoc.total_flight_count) *
11805 		    sizeof(struct sctp_data_chunk)));
11806 	} else {
11807 		un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
11808 		    ((stcb->asoc.chunks_on_out_queue - stcb->asoc.total_flight_count) *
11809 		    sizeof(struct sctp_data_chunk)));
11810 		if (net->flight_size > (net->mtu * stcb->asoc.max_burst)) {
11811 			queue_only = 1;
11812 			SCTP_STAT_INCR(sctps_send_burst_avoid);
11813 		} else if (net->flight_size > net->cwnd) {
11814 			queue_only = 1;
11815 			SCTP_STAT_INCR(sctps_send_cwnd_avoid);
11816 		} else {
11817 			queue_only = 0;
11818 		}
11819 	}
11820 	if ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY)) &&
11821 	    (stcb->asoc.total_flight > 0) &&
11822 	    (un_sent < (int)(stcb->asoc.smallest_mtu - SCTP_MIN_OVERHEAD))
11823 	    ) {
11824 
11825 		/*-
11826 		 * Ok, Nagle is set on and we have data outstanding.
11827 		 * Don't send anything and let SACKs drive out the
11828 		 * data unless wen have a "full" segment to send.
11829 		 */
11830 		if (sctp_logging_level & SCTP_NAGLE_LOGGING_ENABLE) {
11831 			sctp_log_nagle_event(stcb, SCTP_NAGLE_APPLIED);
11832 		}
11833 		SCTP_STAT_INCR(sctps_naglequeued);
11834 		nagle_applies = 1;
11835 	} else {
11836 		if (sctp_logging_level & SCTP_NAGLE_LOGGING_ENABLE) {
11837 			if (sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY))
11838 				sctp_log_nagle_event(stcb, SCTP_NAGLE_SKIPPED);
11839 		}
11840 		SCTP_STAT_INCR(sctps_naglesent);
11841 		nagle_applies = 0;
11842 	}
11843 	if (queue_only_for_init) {
11844 		if (hold_tcblock == 0) {
11845 			SCTP_TCB_LOCK(stcb);
11846 			hold_tcblock = 1;
11847 		}
11848 		if (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_OPEN) {
11849 			/* a collision took us forward? */
11850 			queue_only_for_init = 0;
11851 			queue_only = 0;
11852 		} else {
11853 			sctp_send_initiate(inp, stcb);
11854 			if (stcb->asoc.state & SCTP_STATE_SHUTDOWN_PENDING)
11855 				stcb->asoc.state = SCTP_STATE_COOKIE_WAIT |
11856 				    SCTP_STATE_SHUTDOWN_PENDING;
11857 			else
11858 				stcb->asoc.state = SCTP_STATE_COOKIE_WAIT;
11859 			queue_only_for_init = 0;
11860 			queue_only = 1;
11861 		}
11862 	}
11863 	if ((queue_only == 0) && (nagle_applies == 0) && (stcb->asoc.peers_rwnd && un_sent)) {
11864 		/* we can attempt to send too. */
11865 		if (hold_tcblock == 0) {
11866 			/*
11867 			 * If there is activity recv'ing sacks no need to
11868 			 * send
11869 			 */
11870 			if (SCTP_TCB_TRYLOCK(stcb)) {
11871 				sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_USR_SEND);
11872 				hold_tcblock = 1;
11873 			}
11874 		} else {
11875 			sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_USR_SEND);
11876 		}
11877 	} else if ((queue_only == 0) &&
11878 		    (stcb->asoc.peers_rwnd == 0) &&
11879 	    (stcb->asoc.total_flight == 0)) {
11880 		/* We get to have a probe outstanding */
11881 		if (hold_tcblock == 0) {
11882 			hold_tcblock = 1;
11883 			SCTP_TCB_LOCK(stcb);
11884 		}
11885 		sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_USR_SEND);
11886 	} else if (some_on_control) {
11887 		int num_out, reason, cwnd_full, frag_point;
11888 
11889 		/* Here we do control only */
11890 		if (hold_tcblock == 0) {
11891 			hold_tcblock = 1;
11892 			SCTP_TCB_LOCK(stcb);
11893 		}
11894 		frag_point = sctp_get_frag_point(stcb, &stcb->asoc);
11895 		(void)sctp_med_chunk_output(inp, stcb, &stcb->asoc, &num_out,
11896 		    &reason, 1, &cwnd_full, 1, &now, &now_filled, frag_point);
11897 	}
11898 	SCTPDBG(SCTP_DEBUG_OUTPUT1, "USR Send complete qo:%d prw:%d unsent:%d tf:%d cooq:%d toqs:%d \n",
11899 	    queue_only, stcb->asoc.peers_rwnd, un_sent,
11900 	    stcb->asoc.total_flight, stcb->asoc.chunks_on_out_queue,
11901 	    stcb->asoc.total_output_queue_size);
11902 
11903 out:
11904 out_unlocked:
11905 
11906 
11907 	if (create_lock_applied) {
11908 		SCTP_ASOC_CREATE_UNLOCK(inp);
11909 		create_lock_applied = 0;
11910 	}
11911 	if ((stcb) && hold_tcblock) {
11912 		SCTP_TCB_UNLOCK(stcb);
11913 	}
11914 	if (stcb && free_cnt_applied) {
11915 		atomic_add_int(&stcb->asoc.refcnt, -1);
11916 	}
11917 #ifdef INVARIANTS
11918 	if (stcb) {
11919 		if (mtx_owned(&stcb->tcb_mtx)) {
11920 			panic("Leaving with tcb mtx owned?");
11921 		}
11922 		if (mtx_owned(&stcb->tcb_send_mtx)) {
11923 			panic("Leaving with tcb send mtx owned?");
11924 		}
11925 	}
11926 #endif
11927 	if (top) {
11928 		sctp_m_freem(top);
11929 	}
11930 	if (control) {
11931 		sctp_m_freem(control);
11932 	}
11933 	return (error);
11934 }
11935 
11936 
11937 /*
11938  * generate an AUTHentication chunk, if required
11939  */
11940 struct mbuf *
11941 sctp_add_auth_chunk(struct mbuf *m, struct mbuf **m_end,
11942     struct sctp_auth_chunk **auth_ret, uint32_t * offset,
11943     struct sctp_tcb *stcb, uint8_t chunk)
11944 {
11945 	struct mbuf *m_auth;
11946 	struct sctp_auth_chunk *auth;
11947 	int chunk_len;
11948 
11949 	if ((m_end == NULL) || (auth_ret == NULL) || (offset == NULL) ||
11950 	    (stcb == NULL))
11951 		return (m);
11952 
11953 	/* sysctl disabled auth? */
11954 	if (sctp_auth_disable)
11955 		return (m);
11956 
11957 	/* peer doesn't do auth... */
11958 	if (!stcb->asoc.peer_supports_auth) {
11959 		return (m);
11960 	}
11961 	/* does the requested chunk require auth? */
11962 	if (!sctp_auth_is_required_chunk(chunk, stcb->asoc.peer_auth_chunks)) {
11963 		return (m);
11964 	}
11965 	m_auth = sctp_get_mbuf_for_msg(sizeof(*auth), 0, M_DONTWAIT, 1, MT_HEADER);
11966 	if (m_auth == NULL) {
11967 		/* no mbuf's */
11968 		return (m);
11969 	}
11970 	/* reserve some space if this will be the first mbuf */
11971 	if (m == NULL)
11972 		SCTP_BUF_RESV_UF(m_auth, SCTP_MIN_OVERHEAD);
11973 	/* fill in the AUTH chunk details */
11974 	auth = mtod(m_auth, struct sctp_auth_chunk *);
11975 	bzero(auth, sizeof(*auth));
11976 	auth->ch.chunk_type = SCTP_AUTHENTICATION;
11977 	auth->ch.chunk_flags = 0;
11978 	chunk_len = sizeof(*auth) +
11979 	    sctp_get_hmac_digest_len(stcb->asoc.peer_hmac_id);
11980 	auth->ch.chunk_length = htons(chunk_len);
11981 	auth->hmac_id = htons(stcb->asoc.peer_hmac_id);
11982 	/* key id and hmac digest will be computed and filled in upon send */
11983 
11984 	/* save the offset where the auth was inserted into the chain */
11985 	if (m != NULL) {
11986 		struct mbuf *cn;
11987 
11988 		*offset = 0;
11989 		cn = m;
11990 		while (cn) {
11991 			*offset += SCTP_BUF_LEN(cn);
11992 			cn = SCTP_BUF_NEXT(cn);
11993 		}
11994 	} else
11995 		*offset = 0;
11996 
11997 	/* update length and return pointer to the auth chunk */
11998 	SCTP_BUF_LEN(m_auth) = chunk_len;
11999 	m = sctp_copy_mbufchain(m_auth, m, m_end, 1, chunk_len, 0);
12000 	if (auth_ret != NULL)
12001 		*auth_ret = auth;
12002 
12003 	return (m);
12004 }
12005