xref: /freebsd/sys/netinet/sctp_output.c (revision 4ed925457ab06e83238a5db33e89ccc94b99a713)
1 /*-
2  * Copyright (c) 2001-2008, 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 #include <netinet/sctp_crc32.h>
53 #include <netinet/udp.h>
54 #include <machine/in_cksum.h>
55 
56 
57 
58 #define SCTP_MAX_GAPS_INARRAY 4
59 struct sack_track {
60 	uint8_t right_edge;	/* mergable on the right edge */
61 	uint8_t left_edge;	/* mergable on the left edge */
62 	uint8_t num_entries;
63 	uint8_t spare;
64 	struct sctp_gap_ack_block gaps[SCTP_MAX_GAPS_INARRAY];
65 };
66 
67 struct sack_track sack_array[256] = {
68 	{0, 0, 0, 0,		/* 0x00 */
69 		{{0, 0},
70 		{0, 0},
71 		{0, 0},
72 		{0, 0}
73 		}
74 	},
75 	{1, 0, 1, 0,		/* 0x01 */
76 		{{0, 0},
77 		{0, 0},
78 		{0, 0},
79 		{0, 0}
80 		}
81 	},
82 	{0, 0, 1, 0,		/* 0x02 */
83 		{{1, 1},
84 		{0, 0},
85 		{0, 0},
86 		{0, 0}
87 		}
88 	},
89 	{1, 0, 1, 0,		/* 0x03 */
90 		{{0, 1},
91 		{0, 0},
92 		{0, 0},
93 		{0, 0}
94 		}
95 	},
96 	{0, 0, 1, 0,		/* 0x04 */
97 		{{2, 2},
98 		{0, 0},
99 		{0, 0},
100 		{0, 0}
101 		}
102 	},
103 	{1, 0, 2, 0,		/* 0x05 */
104 		{{0, 0},
105 		{2, 2},
106 		{0, 0},
107 		{0, 0}
108 		}
109 	},
110 	{0, 0, 1, 0,		/* 0x06 */
111 		{{1, 2},
112 		{0, 0},
113 		{0, 0},
114 		{0, 0}
115 		}
116 	},
117 	{1, 0, 1, 0,		/* 0x07 */
118 		{{0, 2},
119 		{0, 0},
120 		{0, 0},
121 		{0, 0}
122 		}
123 	},
124 	{0, 0, 1, 0,		/* 0x08 */
125 		{{3, 3},
126 		{0, 0},
127 		{0, 0},
128 		{0, 0}
129 		}
130 	},
131 	{1, 0, 2, 0,		/* 0x09 */
132 		{{0, 0},
133 		{3, 3},
134 		{0, 0},
135 		{0, 0}
136 		}
137 	},
138 	{0, 0, 2, 0,		/* 0x0a */
139 		{{1, 1},
140 		{3, 3},
141 		{0, 0},
142 		{0, 0}
143 		}
144 	},
145 	{1, 0, 2, 0,		/* 0x0b */
146 		{{0, 1},
147 		{3, 3},
148 		{0, 0},
149 		{0, 0}
150 		}
151 	},
152 	{0, 0, 1, 0,		/* 0x0c */
153 		{{2, 3},
154 		{0, 0},
155 		{0, 0},
156 		{0, 0}
157 		}
158 	},
159 	{1, 0, 2, 0,		/* 0x0d */
160 		{{0, 0},
161 		{2, 3},
162 		{0, 0},
163 		{0, 0}
164 		}
165 	},
166 	{0, 0, 1, 0,		/* 0x0e */
167 		{{1, 3},
168 		{0, 0},
169 		{0, 0},
170 		{0, 0}
171 		}
172 	},
173 	{1, 0, 1, 0,		/* 0x0f */
174 		{{0, 3},
175 		{0, 0},
176 		{0, 0},
177 		{0, 0}
178 		}
179 	},
180 	{0, 0, 1, 0,		/* 0x10 */
181 		{{4, 4},
182 		{0, 0},
183 		{0, 0},
184 		{0, 0}
185 		}
186 	},
187 	{1, 0, 2, 0,		/* 0x11 */
188 		{{0, 0},
189 		{4, 4},
190 		{0, 0},
191 		{0, 0}
192 		}
193 	},
194 	{0, 0, 2, 0,		/* 0x12 */
195 		{{1, 1},
196 		{4, 4},
197 		{0, 0},
198 		{0, 0}
199 		}
200 	},
201 	{1, 0, 2, 0,		/* 0x13 */
202 		{{0, 1},
203 		{4, 4},
204 		{0, 0},
205 		{0, 0}
206 		}
207 	},
208 	{0, 0, 2, 0,		/* 0x14 */
209 		{{2, 2},
210 		{4, 4},
211 		{0, 0},
212 		{0, 0}
213 		}
214 	},
215 	{1, 0, 3, 0,		/* 0x15 */
216 		{{0, 0},
217 		{2, 2},
218 		{4, 4},
219 		{0, 0}
220 		}
221 	},
222 	{0, 0, 2, 0,		/* 0x16 */
223 		{{1, 2},
224 		{4, 4},
225 		{0, 0},
226 		{0, 0}
227 		}
228 	},
229 	{1, 0, 2, 0,		/* 0x17 */
230 		{{0, 2},
231 		{4, 4},
232 		{0, 0},
233 		{0, 0}
234 		}
235 	},
236 	{0, 0, 1, 0,		/* 0x18 */
237 		{{3, 4},
238 		{0, 0},
239 		{0, 0},
240 		{0, 0}
241 		}
242 	},
243 	{1, 0, 2, 0,		/* 0x19 */
244 		{{0, 0},
245 		{3, 4},
246 		{0, 0},
247 		{0, 0}
248 		}
249 	},
250 	{0, 0, 2, 0,		/* 0x1a */
251 		{{1, 1},
252 		{3, 4},
253 		{0, 0},
254 		{0, 0}
255 		}
256 	},
257 	{1, 0, 2, 0,		/* 0x1b */
258 		{{0, 1},
259 		{3, 4},
260 		{0, 0},
261 		{0, 0}
262 		}
263 	},
264 	{0, 0, 1, 0,		/* 0x1c */
265 		{{2, 4},
266 		{0, 0},
267 		{0, 0},
268 		{0, 0}
269 		}
270 	},
271 	{1, 0, 2, 0,		/* 0x1d */
272 		{{0, 0},
273 		{2, 4},
274 		{0, 0},
275 		{0, 0}
276 		}
277 	},
278 	{0, 0, 1, 0,		/* 0x1e */
279 		{{1, 4},
280 		{0, 0},
281 		{0, 0},
282 		{0, 0}
283 		}
284 	},
285 	{1, 0, 1, 0,		/* 0x1f */
286 		{{0, 4},
287 		{0, 0},
288 		{0, 0},
289 		{0, 0}
290 		}
291 	},
292 	{0, 0, 1, 0,		/* 0x20 */
293 		{{5, 5},
294 		{0, 0},
295 		{0, 0},
296 		{0, 0}
297 		}
298 	},
299 	{1, 0, 2, 0,		/* 0x21 */
300 		{{0, 0},
301 		{5, 5},
302 		{0, 0},
303 		{0, 0}
304 		}
305 	},
306 	{0, 0, 2, 0,		/* 0x22 */
307 		{{1, 1},
308 		{5, 5},
309 		{0, 0},
310 		{0, 0}
311 		}
312 	},
313 	{1, 0, 2, 0,		/* 0x23 */
314 		{{0, 1},
315 		{5, 5},
316 		{0, 0},
317 		{0, 0}
318 		}
319 	},
320 	{0, 0, 2, 0,		/* 0x24 */
321 		{{2, 2},
322 		{5, 5},
323 		{0, 0},
324 		{0, 0}
325 		}
326 	},
327 	{1, 0, 3, 0,		/* 0x25 */
328 		{{0, 0},
329 		{2, 2},
330 		{5, 5},
331 		{0, 0}
332 		}
333 	},
334 	{0, 0, 2, 0,		/* 0x26 */
335 		{{1, 2},
336 		{5, 5},
337 		{0, 0},
338 		{0, 0}
339 		}
340 	},
341 	{1, 0, 2, 0,		/* 0x27 */
342 		{{0, 2},
343 		{5, 5},
344 		{0, 0},
345 		{0, 0}
346 		}
347 	},
348 	{0, 0, 2, 0,		/* 0x28 */
349 		{{3, 3},
350 		{5, 5},
351 		{0, 0},
352 		{0, 0}
353 		}
354 	},
355 	{1, 0, 3, 0,		/* 0x29 */
356 		{{0, 0},
357 		{3, 3},
358 		{5, 5},
359 		{0, 0}
360 		}
361 	},
362 	{0, 0, 3, 0,		/* 0x2a */
363 		{{1, 1},
364 		{3, 3},
365 		{5, 5},
366 		{0, 0}
367 		}
368 	},
369 	{1, 0, 3, 0,		/* 0x2b */
370 		{{0, 1},
371 		{3, 3},
372 		{5, 5},
373 		{0, 0}
374 		}
375 	},
376 	{0, 0, 2, 0,		/* 0x2c */
377 		{{2, 3},
378 		{5, 5},
379 		{0, 0},
380 		{0, 0}
381 		}
382 	},
383 	{1, 0, 3, 0,		/* 0x2d */
384 		{{0, 0},
385 		{2, 3},
386 		{5, 5},
387 		{0, 0}
388 		}
389 	},
390 	{0, 0, 2, 0,		/* 0x2e */
391 		{{1, 3},
392 		{5, 5},
393 		{0, 0},
394 		{0, 0}
395 		}
396 	},
397 	{1, 0, 2, 0,		/* 0x2f */
398 		{{0, 3},
399 		{5, 5},
400 		{0, 0},
401 		{0, 0}
402 		}
403 	},
404 	{0, 0, 1, 0,		/* 0x30 */
405 		{{4, 5},
406 		{0, 0},
407 		{0, 0},
408 		{0, 0}
409 		}
410 	},
411 	{1, 0, 2, 0,		/* 0x31 */
412 		{{0, 0},
413 		{4, 5},
414 		{0, 0},
415 		{0, 0}
416 		}
417 	},
418 	{0, 0, 2, 0,		/* 0x32 */
419 		{{1, 1},
420 		{4, 5},
421 		{0, 0},
422 		{0, 0}
423 		}
424 	},
425 	{1, 0, 2, 0,		/* 0x33 */
426 		{{0, 1},
427 		{4, 5},
428 		{0, 0},
429 		{0, 0}
430 		}
431 	},
432 	{0, 0, 2, 0,		/* 0x34 */
433 		{{2, 2},
434 		{4, 5},
435 		{0, 0},
436 		{0, 0}
437 		}
438 	},
439 	{1, 0, 3, 0,		/* 0x35 */
440 		{{0, 0},
441 		{2, 2},
442 		{4, 5},
443 		{0, 0}
444 		}
445 	},
446 	{0, 0, 2, 0,		/* 0x36 */
447 		{{1, 2},
448 		{4, 5},
449 		{0, 0},
450 		{0, 0}
451 		}
452 	},
453 	{1, 0, 2, 0,		/* 0x37 */
454 		{{0, 2},
455 		{4, 5},
456 		{0, 0},
457 		{0, 0}
458 		}
459 	},
460 	{0, 0, 1, 0,		/* 0x38 */
461 		{{3, 5},
462 		{0, 0},
463 		{0, 0},
464 		{0, 0}
465 		}
466 	},
467 	{1, 0, 2, 0,		/* 0x39 */
468 		{{0, 0},
469 		{3, 5},
470 		{0, 0},
471 		{0, 0}
472 		}
473 	},
474 	{0, 0, 2, 0,		/* 0x3a */
475 		{{1, 1},
476 		{3, 5},
477 		{0, 0},
478 		{0, 0}
479 		}
480 	},
481 	{1, 0, 2, 0,		/* 0x3b */
482 		{{0, 1},
483 		{3, 5},
484 		{0, 0},
485 		{0, 0}
486 		}
487 	},
488 	{0, 0, 1, 0,		/* 0x3c */
489 		{{2, 5},
490 		{0, 0},
491 		{0, 0},
492 		{0, 0}
493 		}
494 	},
495 	{1, 0, 2, 0,		/* 0x3d */
496 		{{0, 0},
497 		{2, 5},
498 		{0, 0},
499 		{0, 0}
500 		}
501 	},
502 	{0, 0, 1, 0,		/* 0x3e */
503 		{{1, 5},
504 		{0, 0},
505 		{0, 0},
506 		{0, 0}
507 		}
508 	},
509 	{1, 0, 1, 0,		/* 0x3f */
510 		{{0, 5},
511 		{0, 0},
512 		{0, 0},
513 		{0, 0}
514 		}
515 	},
516 	{0, 0, 1, 0,		/* 0x40 */
517 		{{6, 6},
518 		{0, 0},
519 		{0, 0},
520 		{0, 0}
521 		}
522 	},
523 	{1, 0, 2, 0,		/* 0x41 */
524 		{{0, 0},
525 		{6, 6},
526 		{0, 0},
527 		{0, 0}
528 		}
529 	},
530 	{0, 0, 2, 0,		/* 0x42 */
531 		{{1, 1},
532 		{6, 6},
533 		{0, 0},
534 		{0, 0}
535 		}
536 	},
537 	{1, 0, 2, 0,		/* 0x43 */
538 		{{0, 1},
539 		{6, 6},
540 		{0, 0},
541 		{0, 0}
542 		}
543 	},
544 	{0, 0, 2, 0,		/* 0x44 */
545 		{{2, 2},
546 		{6, 6},
547 		{0, 0},
548 		{0, 0}
549 		}
550 	},
551 	{1, 0, 3, 0,		/* 0x45 */
552 		{{0, 0},
553 		{2, 2},
554 		{6, 6},
555 		{0, 0}
556 		}
557 	},
558 	{0, 0, 2, 0,		/* 0x46 */
559 		{{1, 2},
560 		{6, 6},
561 		{0, 0},
562 		{0, 0}
563 		}
564 	},
565 	{1, 0, 2, 0,		/* 0x47 */
566 		{{0, 2},
567 		{6, 6},
568 		{0, 0},
569 		{0, 0}
570 		}
571 	},
572 	{0, 0, 2, 0,		/* 0x48 */
573 		{{3, 3},
574 		{6, 6},
575 		{0, 0},
576 		{0, 0}
577 		}
578 	},
579 	{1, 0, 3, 0,		/* 0x49 */
580 		{{0, 0},
581 		{3, 3},
582 		{6, 6},
583 		{0, 0}
584 		}
585 	},
586 	{0, 0, 3, 0,		/* 0x4a */
587 		{{1, 1},
588 		{3, 3},
589 		{6, 6},
590 		{0, 0}
591 		}
592 	},
593 	{1, 0, 3, 0,		/* 0x4b */
594 		{{0, 1},
595 		{3, 3},
596 		{6, 6},
597 		{0, 0}
598 		}
599 	},
600 	{0, 0, 2, 0,		/* 0x4c */
601 		{{2, 3},
602 		{6, 6},
603 		{0, 0},
604 		{0, 0}
605 		}
606 	},
607 	{1, 0, 3, 0,		/* 0x4d */
608 		{{0, 0},
609 		{2, 3},
610 		{6, 6},
611 		{0, 0}
612 		}
613 	},
614 	{0, 0, 2, 0,		/* 0x4e */
615 		{{1, 3},
616 		{6, 6},
617 		{0, 0},
618 		{0, 0}
619 		}
620 	},
621 	{1, 0, 2, 0,		/* 0x4f */
622 		{{0, 3},
623 		{6, 6},
624 		{0, 0},
625 		{0, 0}
626 		}
627 	},
628 	{0, 0, 2, 0,		/* 0x50 */
629 		{{4, 4},
630 		{6, 6},
631 		{0, 0},
632 		{0, 0}
633 		}
634 	},
635 	{1, 0, 3, 0,		/* 0x51 */
636 		{{0, 0},
637 		{4, 4},
638 		{6, 6},
639 		{0, 0}
640 		}
641 	},
642 	{0, 0, 3, 0,		/* 0x52 */
643 		{{1, 1},
644 		{4, 4},
645 		{6, 6},
646 		{0, 0}
647 		}
648 	},
649 	{1, 0, 3, 0,		/* 0x53 */
650 		{{0, 1},
651 		{4, 4},
652 		{6, 6},
653 		{0, 0}
654 		}
655 	},
656 	{0, 0, 3, 0,		/* 0x54 */
657 		{{2, 2},
658 		{4, 4},
659 		{6, 6},
660 		{0, 0}
661 		}
662 	},
663 	{1, 0, 4, 0,		/* 0x55 */
664 		{{0, 0},
665 		{2, 2},
666 		{4, 4},
667 		{6, 6}
668 		}
669 	},
670 	{0, 0, 3, 0,		/* 0x56 */
671 		{{1, 2},
672 		{4, 4},
673 		{6, 6},
674 		{0, 0}
675 		}
676 	},
677 	{1, 0, 3, 0,		/* 0x57 */
678 		{{0, 2},
679 		{4, 4},
680 		{6, 6},
681 		{0, 0}
682 		}
683 	},
684 	{0, 0, 2, 0,		/* 0x58 */
685 		{{3, 4},
686 		{6, 6},
687 		{0, 0},
688 		{0, 0}
689 		}
690 	},
691 	{1, 0, 3, 0,		/* 0x59 */
692 		{{0, 0},
693 		{3, 4},
694 		{6, 6},
695 		{0, 0}
696 		}
697 	},
698 	{0, 0, 3, 0,		/* 0x5a */
699 		{{1, 1},
700 		{3, 4},
701 		{6, 6},
702 		{0, 0}
703 		}
704 	},
705 	{1, 0, 3, 0,		/* 0x5b */
706 		{{0, 1},
707 		{3, 4},
708 		{6, 6},
709 		{0, 0}
710 		}
711 	},
712 	{0, 0, 2, 0,		/* 0x5c */
713 		{{2, 4},
714 		{6, 6},
715 		{0, 0},
716 		{0, 0}
717 		}
718 	},
719 	{1, 0, 3, 0,		/* 0x5d */
720 		{{0, 0},
721 		{2, 4},
722 		{6, 6},
723 		{0, 0}
724 		}
725 	},
726 	{0, 0, 2, 0,		/* 0x5e */
727 		{{1, 4},
728 		{6, 6},
729 		{0, 0},
730 		{0, 0}
731 		}
732 	},
733 	{1, 0, 2, 0,		/* 0x5f */
734 		{{0, 4},
735 		{6, 6},
736 		{0, 0},
737 		{0, 0}
738 		}
739 	},
740 	{0, 0, 1, 0,		/* 0x60 */
741 		{{5, 6},
742 		{0, 0},
743 		{0, 0},
744 		{0, 0}
745 		}
746 	},
747 	{1, 0, 2, 0,		/* 0x61 */
748 		{{0, 0},
749 		{5, 6},
750 		{0, 0},
751 		{0, 0}
752 		}
753 	},
754 	{0, 0, 2, 0,		/* 0x62 */
755 		{{1, 1},
756 		{5, 6},
757 		{0, 0},
758 		{0, 0}
759 		}
760 	},
761 	{1, 0, 2, 0,		/* 0x63 */
762 		{{0, 1},
763 		{5, 6},
764 		{0, 0},
765 		{0, 0}
766 		}
767 	},
768 	{0, 0, 2, 0,		/* 0x64 */
769 		{{2, 2},
770 		{5, 6},
771 		{0, 0},
772 		{0, 0}
773 		}
774 	},
775 	{1, 0, 3, 0,		/* 0x65 */
776 		{{0, 0},
777 		{2, 2},
778 		{5, 6},
779 		{0, 0}
780 		}
781 	},
782 	{0, 0, 2, 0,		/* 0x66 */
783 		{{1, 2},
784 		{5, 6},
785 		{0, 0},
786 		{0, 0}
787 		}
788 	},
789 	{1, 0, 2, 0,		/* 0x67 */
790 		{{0, 2},
791 		{5, 6},
792 		{0, 0},
793 		{0, 0}
794 		}
795 	},
796 	{0, 0, 2, 0,		/* 0x68 */
797 		{{3, 3},
798 		{5, 6},
799 		{0, 0},
800 		{0, 0}
801 		}
802 	},
803 	{1, 0, 3, 0,		/* 0x69 */
804 		{{0, 0},
805 		{3, 3},
806 		{5, 6},
807 		{0, 0}
808 		}
809 	},
810 	{0, 0, 3, 0,		/* 0x6a */
811 		{{1, 1},
812 		{3, 3},
813 		{5, 6},
814 		{0, 0}
815 		}
816 	},
817 	{1, 0, 3, 0,		/* 0x6b */
818 		{{0, 1},
819 		{3, 3},
820 		{5, 6},
821 		{0, 0}
822 		}
823 	},
824 	{0, 0, 2, 0,		/* 0x6c */
825 		{{2, 3},
826 		{5, 6},
827 		{0, 0},
828 		{0, 0}
829 		}
830 	},
831 	{1, 0, 3, 0,		/* 0x6d */
832 		{{0, 0},
833 		{2, 3},
834 		{5, 6},
835 		{0, 0}
836 		}
837 	},
838 	{0, 0, 2, 0,		/* 0x6e */
839 		{{1, 3},
840 		{5, 6},
841 		{0, 0},
842 		{0, 0}
843 		}
844 	},
845 	{1, 0, 2, 0,		/* 0x6f */
846 		{{0, 3},
847 		{5, 6},
848 		{0, 0},
849 		{0, 0}
850 		}
851 	},
852 	{0, 0, 1, 0,		/* 0x70 */
853 		{{4, 6},
854 		{0, 0},
855 		{0, 0},
856 		{0, 0}
857 		}
858 	},
859 	{1, 0, 2, 0,		/* 0x71 */
860 		{{0, 0},
861 		{4, 6},
862 		{0, 0},
863 		{0, 0}
864 		}
865 	},
866 	{0, 0, 2, 0,		/* 0x72 */
867 		{{1, 1},
868 		{4, 6},
869 		{0, 0},
870 		{0, 0}
871 		}
872 	},
873 	{1, 0, 2, 0,		/* 0x73 */
874 		{{0, 1},
875 		{4, 6},
876 		{0, 0},
877 		{0, 0}
878 		}
879 	},
880 	{0, 0, 2, 0,		/* 0x74 */
881 		{{2, 2},
882 		{4, 6},
883 		{0, 0},
884 		{0, 0}
885 		}
886 	},
887 	{1, 0, 3, 0,		/* 0x75 */
888 		{{0, 0},
889 		{2, 2},
890 		{4, 6},
891 		{0, 0}
892 		}
893 	},
894 	{0, 0, 2, 0,		/* 0x76 */
895 		{{1, 2},
896 		{4, 6},
897 		{0, 0},
898 		{0, 0}
899 		}
900 	},
901 	{1, 0, 2, 0,		/* 0x77 */
902 		{{0, 2},
903 		{4, 6},
904 		{0, 0},
905 		{0, 0}
906 		}
907 	},
908 	{0, 0, 1, 0,		/* 0x78 */
909 		{{3, 6},
910 		{0, 0},
911 		{0, 0},
912 		{0, 0}
913 		}
914 	},
915 	{1, 0, 2, 0,		/* 0x79 */
916 		{{0, 0},
917 		{3, 6},
918 		{0, 0},
919 		{0, 0}
920 		}
921 	},
922 	{0, 0, 2, 0,		/* 0x7a */
923 		{{1, 1},
924 		{3, 6},
925 		{0, 0},
926 		{0, 0}
927 		}
928 	},
929 	{1, 0, 2, 0,		/* 0x7b */
930 		{{0, 1},
931 		{3, 6},
932 		{0, 0},
933 		{0, 0}
934 		}
935 	},
936 	{0, 0, 1, 0,		/* 0x7c */
937 		{{2, 6},
938 		{0, 0},
939 		{0, 0},
940 		{0, 0}
941 		}
942 	},
943 	{1, 0, 2, 0,		/* 0x7d */
944 		{{0, 0},
945 		{2, 6},
946 		{0, 0},
947 		{0, 0}
948 		}
949 	},
950 	{0, 0, 1, 0,		/* 0x7e */
951 		{{1, 6},
952 		{0, 0},
953 		{0, 0},
954 		{0, 0}
955 		}
956 	},
957 	{1, 0, 1, 0,		/* 0x7f */
958 		{{0, 6},
959 		{0, 0},
960 		{0, 0},
961 		{0, 0}
962 		}
963 	},
964 	{0, 1, 1, 0,		/* 0x80 */
965 		{{7, 7},
966 		{0, 0},
967 		{0, 0},
968 		{0, 0}
969 		}
970 	},
971 	{1, 1, 2, 0,		/* 0x81 */
972 		{{0, 0},
973 		{7, 7},
974 		{0, 0},
975 		{0, 0}
976 		}
977 	},
978 	{0, 1, 2, 0,		/* 0x82 */
979 		{{1, 1},
980 		{7, 7},
981 		{0, 0},
982 		{0, 0}
983 		}
984 	},
985 	{1, 1, 2, 0,		/* 0x83 */
986 		{{0, 1},
987 		{7, 7},
988 		{0, 0},
989 		{0, 0}
990 		}
991 	},
992 	{0, 1, 2, 0,		/* 0x84 */
993 		{{2, 2},
994 		{7, 7},
995 		{0, 0},
996 		{0, 0}
997 		}
998 	},
999 	{1, 1, 3, 0,		/* 0x85 */
1000 		{{0, 0},
1001 		{2, 2},
1002 		{7, 7},
1003 		{0, 0}
1004 		}
1005 	},
1006 	{0, 1, 2, 0,		/* 0x86 */
1007 		{{1, 2},
1008 		{7, 7},
1009 		{0, 0},
1010 		{0, 0}
1011 		}
1012 	},
1013 	{1, 1, 2, 0,		/* 0x87 */
1014 		{{0, 2},
1015 		{7, 7},
1016 		{0, 0},
1017 		{0, 0}
1018 		}
1019 	},
1020 	{0, 1, 2, 0,		/* 0x88 */
1021 		{{3, 3},
1022 		{7, 7},
1023 		{0, 0},
1024 		{0, 0}
1025 		}
1026 	},
1027 	{1, 1, 3, 0,		/* 0x89 */
1028 		{{0, 0},
1029 		{3, 3},
1030 		{7, 7},
1031 		{0, 0}
1032 		}
1033 	},
1034 	{0, 1, 3, 0,		/* 0x8a */
1035 		{{1, 1},
1036 		{3, 3},
1037 		{7, 7},
1038 		{0, 0}
1039 		}
1040 	},
1041 	{1, 1, 3, 0,		/* 0x8b */
1042 		{{0, 1},
1043 		{3, 3},
1044 		{7, 7},
1045 		{0, 0}
1046 		}
1047 	},
1048 	{0, 1, 2, 0,		/* 0x8c */
1049 		{{2, 3},
1050 		{7, 7},
1051 		{0, 0},
1052 		{0, 0}
1053 		}
1054 	},
1055 	{1, 1, 3, 0,		/* 0x8d */
1056 		{{0, 0},
1057 		{2, 3},
1058 		{7, 7},
1059 		{0, 0}
1060 		}
1061 	},
1062 	{0, 1, 2, 0,		/* 0x8e */
1063 		{{1, 3},
1064 		{7, 7},
1065 		{0, 0},
1066 		{0, 0}
1067 		}
1068 	},
1069 	{1, 1, 2, 0,		/* 0x8f */
1070 		{{0, 3},
1071 		{7, 7},
1072 		{0, 0},
1073 		{0, 0}
1074 		}
1075 	},
1076 	{0, 1, 2, 0,		/* 0x90 */
1077 		{{4, 4},
1078 		{7, 7},
1079 		{0, 0},
1080 		{0, 0}
1081 		}
1082 	},
1083 	{1, 1, 3, 0,		/* 0x91 */
1084 		{{0, 0},
1085 		{4, 4},
1086 		{7, 7},
1087 		{0, 0}
1088 		}
1089 	},
1090 	{0, 1, 3, 0,		/* 0x92 */
1091 		{{1, 1},
1092 		{4, 4},
1093 		{7, 7},
1094 		{0, 0}
1095 		}
1096 	},
1097 	{1, 1, 3, 0,		/* 0x93 */
1098 		{{0, 1},
1099 		{4, 4},
1100 		{7, 7},
1101 		{0, 0}
1102 		}
1103 	},
1104 	{0, 1, 3, 0,		/* 0x94 */
1105 		{{2, 2},
1106 		{4, 4},
1107 		{7, 7},
1108 		{0, 0}
1109 		}
1110 	},
1111 	{1, 1, 4, 0,		/* 0x95 */
1112 		{{0, 0},
1113 		{2, 2},
1114 		{4, 4},
1115 		{7, 7}
1116 		}
1117 	},
1118 	{0, 1, 3, 0,		/* 0x96 */
1119 		{{1, 2},
1120 		{4, 4},
1121 		{7, 7},
1122 		{0, 0}
1123 		}
1124 	},
1125 	{1, 1, 3, 0,		/* 0x97 */
1126 		{{0, 2},
1127 		{4, 4},
1128 		{7, 7},
1129 		{0, 0}
1130 		}
1131 	},
1132 	{0, 1, 2, 0,		/* 0x98 */
1133 		{{3, 4},
1134 		{7, 7},
1135 		{0, 0},
1136 		{0, 0}
1137 		}
1138 	},
1139 	{1, 1, 3, 0,		/* 0x99 */
1140 		{{0, 0},
1141 		{3, 4},
1142 		{7, 7},
1143 		{0, 0}
1144 		}
1145 	},
1146 	{0, 1, 3, 0,		/* 0x9a */
1147 		{{1, 1},
1148 		{3, 4},
1149 		{7, 7},
1150 		{0, 0}
1151 		}
1152 	},
1153 	{1, 1, 3, 0,		/* 0x9b */
1154 		{{0, 1},
1155 		{3, 4},
1156 		{7, 7},
1157 		{0, 0}
1158 		}
1159 	},
1160 	{0, 1, 2, 0,		/* 0x9c */
1161 		{{2, 4},
1162 		{7, 7},
1163 		{0, 0},
1164 		{0, 0}
1165 		}
1166 	},
1167 	{1, 1, 3, 0,		/* 0x9d */
1168 		{{0, 0},
1169 		{2, 4},
1170 		{7, 7},
1171 		{0, 0}
1172 		}
1173 	},
1174 	{0, 1, 2, 0,		/* 0x9e */
1175 		{{1, 4},
1176 		{7, 7},
1177 		{0, 0},
1178 		{0, 0}
1179 		}
1180 	},
1181 	{1, 1, 2, 0,		/* 0x9f */
1182 		{{0, 4},
1183 		{7, 7},
1184 		{0, 0},
1185 		{0, 0}
1186 		}
1187 	},
1188 	{0, 1, 2, 0,		/* 0xa0 */
1189 		{{5, 5},
1190 		{7, 7},
1191 		{0, 0},
1192 		{0, 0}
1193 		}
1194 	},
1195 	{1, 1, 3, 0,		/* 0xa1 */
1196 		{{0, 0},
1197 		{5, 5},
1198 		{7, 7},
1199 		{0, 0}
1200 		}
1201 	},
1202 	{0, 1, 3, 0,		/* 0xa2 */
1203 		{{1, 1},
1204 		{5, 5},
1205 		{7, 7},
1206 		{0, 0}
1207 		}
1208 	},
1209 	{1, 1, 3, 0,		/* 0xa3 */
1210 		{{0, 1},
1211 		{5, 5},
1212 		{7, 7},
1213 		{0, 0}
1214 		}
1215 	},
1216 	{0, 1, 3, 0,		/* 0xa4 */
1217 		{{2, 2},
1218 		{5, 5},
1219 		{7, 7},
1220 		{0, 0}
1221 		}
1222 	},
1223 	{1, 1, 4, 0,		/* 0xa5 */
1224 		{{0, 0},
1225 		{2, 2},
1226 		{5, 5},
1227 		{7, 7}
1228 		}
1229 	},
1230 	{0, 1, 3, 0,		/* 0xa6 */
1231 		{{1, 2},
1232 		{5, 5},
1233 		{7, 7},
1234 		{0, 0}
1235 		}
1236 	},
1237 	{1, 1, 3, 0,		/* 0xa7 */
1238 		{{0, 2},
1239 		{5, 5},
1240 		{7, 7},
1241 		{0, 0}
1242 		}
1243 	},
1244 	{0, 1, 3, 0,		/* 0xa8 */
1245 		{{3, 3},
1246 		{5, 5},
1247 		{7, 7},
1248 		{0, 0}
1249 		}
1250 	},
1251 	{1, 1, 4, 0,		/* 0xa9 */
1252 		{{0, 0},
1253 		{3, 3},
1254 		{5, 5},
1255 		{7, 7}
1256 		}
1257 	},
1258 	{0, 1, 4, 0,		/* 0xaa */
1259 		{{1, 1},
1260 		{3, 3},
1261 		{5, 5},
1262 		{7, 7}
1263 		}
1264 	},
1265 	{1, 1, 4, 0,		/* 0xab */
1266 		{{0, 1},
1267 		{3, 3},
1268 		{5, 5},
1269 		{7, 7}
1270 		}
1271 	},
1272 	{0, 1, 3, 0,		/* 0xac */
1273 		{{2, 3},
1274 		{5, 5},
1275 		{7, 7},
1276 		{0, 0}
1277 		}
1278 	},
1279 	{1, 1, 4, 0,		/* 0xad */
1280 		{{0, 0},
1281 		{2, 3},
1282 		{5, 5},
1283 		{7, 7}
1284 		}
1285 	},
1286 	{0, 1, 3, 0,		/* 0xae */
1287 		{{1, 3},
1288 		{5, 5},
1289 		{7, 7},
1290 		{0, 0}
1291 		}
1292 	},
1293 	{1, 1, 3, 0,		/* 0xaf */
1294 		{{0, 3},
1295 		{5, 5},
1296 		{7, 7},
1297 		{0, 0}
1298 		}
1299 	},
1300 	{0, 1, 2, 0,		/* 0xb0 */
1301 		{{4, 5},
1302 		{7, 7},
1303 		{0, 0},
1304 		{0, 0}
1305 		}
1306 	},
1307 	{1, 1, 3, 0,		/* 0xb1 */
1308 		{{0, 0},
1309 		{4, 5},
1310 		{7, 7},
1311 		{0, 0}
1312 		}
1313 	},
1314 	{0, 1, 3, 0,		/* 0xb2 */
1315 		{{1, 1},
1316 		{4, 5},
1317 		{7, 7},
1318 		{0, 0}
1319 		}
1320 	},
1321 	{1, 1, 3, 0,		/* 0xb3 */
1322 		{{0, 1},
1323 		{4, 5},
1324 		{7, 7},
1325 		{0, 0}
1326 		}
1327 	},
1328 	{0, 1, 3, 0,		/* 0xb4 */
1329 		{{2, 2},
1330 		{4, 5},
1331 		{7, 7},
1332 		{0, 0}
1333 		}
1334 	},
1335 	{1, 1, 4, 0,		/* 0xb5 */
1336 		{{0, 0},
1337 		{2, 2},
1338 		{4, 5},
1339 		{7, 7}
1340 		}
1341 	},
1342 	{0, 1, 3, 0,		/* 0xb6 */
1343 		{{1, 2},
1344 		{4, 5},
1345 		{7, 7},
1346 		{0, 0}
1347 		}
1348 	},
1349 	{1, 1, 3, 0,		/* 0xb7 */
1350 		{{0, 2},
1351 		{4, 5},
1352 		{7, 7},
1353 		{0, 0}
1354 		}
1355 	},
1356 	{0, 1, 2, 0,		/* 0xb8 */
1357 		{{3, 5},
1358 		{7, 7},
1359 		{0, 0},
1360 		{0, 0}
1361 		}
1362 	},
1363 	{1, 1, 3, 0,		/* 0xb9 */
1364 		{{0, 0},
1365 		{3, 5},
1366 		{7, 7},
1367 		{0, 0}
1368 		}
1369 	},
1370 	{0, 1, 3, 0,		/* 0xba */
1371 		{{1, 1},
1372 		{3, 5},
1373 		{7, 7},
1374 		{0, 0}
1375 		}
1376 	},
1377 	{1, 1, 3, 0,		/* 0xbb */
1378 		{{0, 1},
1379 		{3, 5},
1380 		{7, 7},
1381 		{0, 0}
1382 		}
1383 	},
1384 	{0, 1, 2, 0,		/* 0xbc */
1385 		{{2, 5},
1386 		{7, 7},
1387 		{0, 0},
1388 		{0, 0}
1389 		}
1390 	},
1391 	{1, 1, 3, 0,		/* 0xbd */
1392 		{{0, 0},
1393 		{2, 5},
1394 		{7, 7},
1395 		{0, 0}
1396 		}
1397 	},
1398 	{0, 1, 2, 0,		/* 0xbe */
1399 		{{1, 5},
1400 		{7, 7},
1401 		{0, 0},
1402 		{0, 0}
1403 		}
1404 	},
1405 	{1, 1, 2, 0,		/* 0xbf */
1406 		{{0, 5},
1407 		{7, 7},
1408 		{0, 0},
1409 		{0, 0}
1410 		}
1411 	},
1412 	{0, 1, 1, 0,		/* 0xc0 */
1413 		{{6, 7},
1414 		{0, 0},
1415 		{0, 0},
1416 		{0, 0}
1417 		}
1418 	},
1419 	{1, 1, 2, 0,		/* 0xc1 */
1420 		{{0, 0},
1421 		{6, 7},
1422 		{0, 0},
1423 		{0, 0}
1424 		}
1425 	},
1426 	{0, 1, 2, 0,		/* 0xc2 */
1427 		{{1, 1},
1428 		{6, 7},
1429 		{0, 0},
1430 		{0, 0}
1431 		}
1432 	},
1433 	{1, 1, 2, 0,		/* 0xc3 */
1434 		{{0, 1},
1435 		{6, 7},
1436 		{0, 0},
1437 		{0, 0}
1438 		}
1439 	},
1440 	{0, 1, 2, 0,		/* 0xc4 */
1441 		{{2, 2},
1442 		{6, 7},
1443 		{0, 0},
1444 		{0, 0}
1445 		}
1446 	},
1447 	{1, 1, 3, 0,		/* 0xc5 */
1448 		{{0, 0},
1449 		{2, 2},
1450 		{6, 7},
1451 		{0, 0}
1452 		}
1453 	},
1454 	{0, 1, 2, 0,		/* 0xc6 */
1455 		{{1, 2},
1456 		{6, 7},
1457 		{0, 0},
1458 		{0, 0}
1459 		}
1460 	},
1461 	{1, 1, 2, 0,		/* 0xc7 */
1462 		{{0, 2},
1463 		{6, 7},
1464 		{0, 0},
1465 		{0, 0}
1466 		}
1467 	},
1468 	{0, 1, 2, 0,		/* 0xc8 */
1469 		{{3, 3},
1470 		{6, 7},
1471 		{0, 0},
1472 		{0, 0}
1473 		}
1474 	},
1475 	{1, 1, 3, 0,		/* 0xc9 */
1476 		{{0, 0},
1477 		{3, 3},
1478 		{6, 7},
1479 		{0, 0}
1480 		}
1481 	},
1482 	{0, 1, 3, 0,		/* 0xca */
1483 		{{1, 1},
1484 		{3, 3},
1485 		{6, 7},
1486 		{0, 0}
1487 		}
1488 	},
1489 	{1, 1, 3, 0,		/* 0xcb */
1490 		{{0, 1},
1491 		{3, 3},
1492 		{6, 7},
1493 		{0, 0}
1494 		}
1495 	},
1496 	{0, 1, 2, 0,		/* 0xcc */
1497 		{{2, 3},
1498 		{6, 7},
1499 		{0, 0},
1500 		{0, 0}
1501 		}
1502 	},
1503 	{1, 1, 3, 0,		/* 0xcd */
1504 		{{0, 0},
1505 		{2, 3},
1506 		{6, 7},
1507 		{0, 0}
1508 		}
1509 	},
1510 	{0, 1, 2, 0,		/* 0xce */
1511 		{{1, 3},
1512 		{6, 7},
1513 		{0, 0},
1514 		{0, 0}
1515 		}
1516 	},
1517 	{1, 1, 2, 0,		/* 0xcf */
1518 		{{0, 3},
1519 		{6, 7},
1520 		{0, 0},
1521 		{0, 0}
1522 		}
1523 	},
1524 	{0, 1, 2, 0,		/* 0xd0 */
1525 		{{4, 4},
1526 		{6, 7},
1527 		{0, 0},
1528 		{0, 0}
1529 		}
1530 	},
1531 	{1, 1, 3, 0,		/* 0xd1 */
1532 		{{0, 0},
1533 		{4, 4},
1534 		{6, 7},
1535 		{0, 0}
1536 		}
1537 	},
1538 	{0, 1, 3, 0,		/* 0xd2 */
1539 		{{1, 1},
1540 		{4, 4},
1541 		{6, 7},
1542 		{0, 0}
1543 		}
1544 	},
1545 	{1, 1, 3, 0,		/* 0xd3 */
1546 		{{0, 1},
1547 		{4, 4},
1548 		{6, 7},
1549 		{0, 0}
1550 		}
1551 	},
1552 	{0, 1, 3, 0,		/* 0xd4 */
1553 		{{2, 2},
1554 		{4, 4},
1555 		{6, 7},
1556 		{0, 0}
1557 		}
1558 	},
1559 	{1, 1, 4, 0,		/* 0xd5 */
1560 		{{0, 0},
1561 		{2, 2},
1562 		{4, 4},
1563 		{6, 7}
1564 		}
1565 	},
1566 	{0, 1, 3, 0,		/* 0xd6 */
1567 		{{1, 2},
1568 		{4, 4},
1569 		{6, 7},
1570 		{0, 0}
1571 		}
1572 	},
1573 	{1, 1, 3, 0,		/* 0xd7 */
1574 		{{0, 2},
1575 		{4, 4},
1576 		{6, 7},
1577 		{0, 0}
1578 		}
1579 	},
1580 	{0, 1, 2, 0,		/* 0xd8 */
1581 		{{3, 4},
1582 		{6, 7},
1583 		{0, 0},
1584 		{0, 0}
1585 		}
1586 	},
1587 	{1, 1, 3, 0,		/* 0xd9 */
1588 		{{0, 0},
1589 		{3, 4},
1590 		{6, 7},
1591 		{0, 0}
1592 		}
1593 	},
1594 	{0, 1, 3, 0,		/* 0xda */
1595 		{{1, 1},
1596 		{3, 4},
1597 		{6, 7},
1598 		{0, 0}
1599 		}
1600 	},
1601 	{1, 1, 3, 0,		/* 0xdb */
1602 		{{0, 1},
1603 		{3, 4},
1604 		{6, 7},
1605 		{0, 0}
1606 		}
1607 	},
1608 	{0, 1, 2, 0,		/* 0xdc */
1609 		{{2, 4},
1610 		{6, 7},
1611 		{0, 0},
1612 		{0, 0}
1613 		}
1614 	},
1615 	{1, 1, 3, 0,		/* 0xdd */
1616 		{{0, 0},
1617 		{2, 4},
1618 		{6, 7},
1619 		{0, 0}
1620 		}
1621 	},
1622 	{0, 1, 2, 0,		/* 0xde */
1623 		{{1, 4},
1624 		{6, 7},
1625 		{0, 0},
1626 		{0, 0}
1627 		}
1628 	},
1629 	{1, 1, 2, 0,		/* 0xdf */
1630 		{{0, 4},
1631 		{6, 7},
1632 		{0, 0},
1633 		{0, 0}
1634 		}
1635 	},
1636 	{0, 1, 1, 0,		/* 0xe0 */
1637 		{{5, 7},
1638 		{0, 0},
1639 		{0, 0},
1640 		{0, 0}
1641 		}
1642 	},
1643 	{1, 1, 2, 0,		/* 0xe1 */
1644 		{{0, 0},
1645 		{5, 7},
1646 		{0, 0},
1647 		{0, 0}
1648 		}
1649 	},
1650 	{0, 1, 2, 0,		/* 0xe2 */
1651 		{{1, 1},
1652 		{5, 7},
1653 		{0, 0},
1654 		{0, 0}
1655 		}
1656 	},
1657 	{1, 1, 2, 0,		/* 0xe3 */
1658 		{{0, 1},
1659 		{5, 7},
1660 		{0, 0},
1661 		{0, 0}
1662 		}
1663 	},
1664 	{0, 1, 2, 0,		/* 0xe4 */
1665 		{{2, 2},
1666 		{5, 7},
1667 		{0, 0},
1668 		{0, 0}
1669 		}
1670 	},
1671 	{1, 1, 3, 0,		/* 0xe5 */
1672 		{{0, 0},
1673 		{2, 2},
1674 		{5, 7},
1675 		{0, 0}
1676 		}
1677 	},
1678 	{0, 1, 2, 0,		/* 0xe6 */
1679 		{{1, 2},
1680 		{5, 7},
1681 		{0, 0},
1682 		{0, 0}
1683 		}
1684 	},
1685 	{1, 1, 2, 0,		/* 0xe7 */
1686 		{{0, 2},
1687 		{5, 7},
1688 		{0, 0},
1689 		{0, 0}
1690 		}
1691 	},
1692 	{0, 1, 2, 0,		/* 0xe8 */
1693 		{{3, 3},
1694 		{5, 7},
1695 		{0, 0},
1696 		{0, 0}
1697 		}
1698 	},
1699 	{1, 1, 3, 0,		/* 0xe9 */
1700 		{{0, 0},
1701 		{3, 3},
1702 		{5, 7},
1703 		{0, 0}
1704 		}
1705 	},
1706 	{0, 1, 3, 0,		/* 0xea */
1707 		{{1, 1},
1708 		{3, 3},
1709 		{5, 7},
1710 		{0, 0}
1711 		}
1712 	},
1713 	{1, 1, 3, 0,		/* 0xeb */
1714 		{{0, 1},
1715 		{3, 3},
1716 		{5, 7},
1717 		{0, 0}
1718 		}
1719 	},
1720 	{0, 1, 2, 0,		/* 0xec */
1721 		{{2, 3},
1722 		{5, 7},
1723 		{0, 0},
1724 		{0, 0}
1725 		}
1726 	},
1727 	{1, 1, 3, 0,		/* 0xed */
1728 		{{0, 0},
1729 		{2, 3},
1730 		{5, 7},
1731 		{0, 0}
1732 		}
1733 	},
1734 	{0, 1, 2, 0,		/* 0xee */
1735 		{{1, 3},
1736 		{5, 7},
1737 		{0, 0},
1738 		{0, 0}
1739 		}
1740 	},
1741 	{1, 1, 2, 0,		/* 0xef */
1742 		{{0, 3},
1743 		{5, 7},
1744 		{0, 0},
1745 		{0, 0}
1746 		}
1747 	},
1748 	{0, 1, 1, 0,		/* 0xf0 */
1749 		{{4, 7},
1750 		{0, 0},
1751 		{0, 0},
1752 		{0, 0}
1753 		}
1754 	},
1755 	{1, 1, 2, 0,		/* 0xf1 */
1756 		{{0, 0},
1757 		{4, 7},
1758 		{0, 0},
1759 		{0, 0}
1760 		}
1761 	},
1762 	{0, 1, 2, 0,		/* 0xf2 */
1763 		{{1, 1},
1764 		{4, 7},
1765 		{0, 0},
1766 		{0, 0}
1767 		}
1768 	},
1769 	{1, 1, 2, 0,		/* 0xf3 */
1770 		{{0, 1},
1771 		{4, 7},
1772 		{0, 0},
1773 		{0, 0}
1774 		}
1775 	},
1776 	{0, 1, 2, 0,		/* 0xf4 */
1777 		{{2, 2},
1778 		{4, 7},
1779 		{0, 0},
1780 		{0, 0}
1781 		}
1782 	},
1783 	{1, 1, 3, 0,		/* 0xf5 */
1784 		{{0, 0},
1785 		{2, 2},
1786 		{4, 7},
1787 		{0, 0}
1788 		}
1789 	},
1790 	{0, 1, 2, 0,		/* 0xf6 */
1791 		{{1, 2},
1792 		{4, 7},
1793 		{0, 0},
1794 		{0, 0}
1795 		}
1796 	},
1797 	{1, 1, 2, 0,		/* 0xf7 */
1798 		{{0, 2},
1799 		{4, 7},
1800 		{0, 0},
1801 		{0, 0}
1802 		}
1803 	},
1804 	{0, 1, 1, 0,		/* 0xf8 */
1805 		{{3, 7},
1806 		{0, 0},
1807 		{0, 0},
1808 		{0, 0}
1809 		}
1810 	},
1811 	{1, 1, 2, 0,		/* 0xf9 */
1812 		{{0, 0},
1813 		{3, 7},
1814 		{0, 0},
1815 		{0, 0}
1816 		}
1817 	},
1818 	{0, 1, 2, 0,		/* 0xfa */
1819 		{{1, 1},
1820 		{3, 7},
1821 		{0, 0},
1822 		{0, 0}
1823 		}
1824 	},
1825 	{1, 1, 2, 0,		/* 0xfb */
1826 		{{0, 1},
1827 		{3, 7},
1828 		{0, 0},
1829 		{0, 0}
1830 		}
1831 	},
1832 	{0, 1, 1, 0,		/* 0xfc */
1833 		{{2, 7},
1834 		{0, 0},
1835 		{0, 0},
1836 		{0, 0}
1837 		}
1838 	},
1839 	{1, 1, 2, 0,		/* 0xfd */
1840 		{{0, 0},
1841 		{2, 7},
1842 		{0, 0},
1843 		{0, 0}
1844 		}
1845 	},
1846 	{0, 1, 1, 0,		/* 0xfe */
1847 		{{1, 7},
1848 		{0, 0},
1849 		{0, 0},
1850 		{0, 0}
1851 		}
1852 	},
1853 	{1, 1, 1, 0,		/* 0xff */
1854 		{{0, 7},
1855 		{0, 0},
1856 		{0, 0},
1857 		{0, 0}
1858 		}
1859 	}
1860 };
1861 
1862 
1863 int
1864 sctp_is_address_in_scope(struct sctp_ifa *ifa,
1865     int ipv4_addr_legal,
1866     int ipv6_addr_legal,
1867     int loopback_scope,
1868     int ipv4_local_scope,
1869     int local_scope,
1870     int site_scope,
1871     int do_update)
1872 {
1873 	if ((loopback_scope == 0) &&
1874 	    (ifa->ifn_p) && SCTP_IFN_IS_IFT_LOOP(ifa->ifn_p)) {
1875 		/*
1876 		 * skip loopback if not in scope *
1877 		 */
1878 		return (0);
1879 	}
1880 	switch (ifa->address.sa.sa_family) {
1881 	case AF_INET:
1882 		if (ipv4_addr_legal) {
1883 			struct sockaddr_in *sin;
1884 
1885 			sin = (struct sockaddr_in *)&ifa->address.sin;
1886 			if (sin->sin_addr.s_addr == 0) {
1887 				/* not in scope , unspecified */
1888 				return (0);
1889 			}
1890 			if ((ipv4_local_scope == 0) &&
1891 			    (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr))) {
1892 				/* private address not in scope */
1893 				return (0);
1894 			}
1895 		} else {
1896 			return (0);
1897 		}
1898 		break;
1899 #ifdef INET6
1900 	case AF_INET6:
1901 		if (ipv6_addr_legal) {
1902 			struct sockaddr_in6 *sin6;
1903 
1904 			/*
1905 			 * Must update the flags,  bummer, which means any
1906 			 * IFA locks must now be applied HERE <->
1907 			 */
1908 			if (do_update) {
1909 				sctp_gather_internal_ifa_flags(ifa);
1910 			}
1911 			if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
1912 				return (0);
1913 			}
1914 			/* ok to use deprecated addresses? */
1915 			sin6 = (struct sockaddr_in6 *)&ifa->address.sin6;
1916 			if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
1917 				/* skip unspecifed addresses */
1918 				return (0);
1919 			}
1920 			if (	/* (local_scope == 0) && */
1921 			    (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr))) {
1922 				return (0);
1923 			}
1924 			if ((site_scope == 0) &&
1925 			    (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr))) {
1926 				return (0);
1927 			}
1928 		} else {
1929 			return (0);
1930 		}
1931 		break;
1932 #endif
1933 	default:
1934 		return (0);
1935 	}
1936 	return (1);
1937 }
1938 
1939 static struct mbuf *
1940 sctp_add_addr_to_mbuf(struct mbuf *m, struct sctp_ifa *ifa)
1941 {
1942 	struct sctp_paramhdr *parmh;
1943 	struct mbuf *mret;
1944 	int len;
1945 
1946 	if (ifa->address.sa.sa_family == AF_INET) {
1947 		len = sizeof(struct sctp_ipv4addr_param);
1948 	} else if (ifa->address.sa.sa_family == AF_INET6) {
1949 		len = sizeof(struct sctp_ipv6addr_param);
1950 	} else {
1951 		/* unknown type */
1952 		return (m);
1953 	}
1954 	if (M_TRAILINGSPACE(m) >= len) {
1955 		/* easy side we just drop it on the end */
1956 		parmh = (struct sctp_paramhdr *)(SCTP_BUF_AT(m, SCTP_BUF_LEN(m)));
1957 		mret = m;
1958 	} else {
1959 		/* Need more space */
1960 		mret = m;
1961 		while (SCTP_BUF_NEXT(mret) != NULL) {
1962 			mret = SCTP_BUF_NEXT(mret);
1963 		}
1964 		SCTP_BUF_NEXT(mret) = sctp_get_mbuf_for_msg(len, 0, M_DONTWAIT, 1, MT_DATA);
1965 		if (SCTP_BUF_NEXT(mret) == NULL) {
1966 			/* We are hosed, can't add more addresses */
1967 			return (m);
1968 		}
1969 		mret = SCTP_BUF_NEXT(mret);
1970 		parmh = mtod(mret, struct sctp_paramhdr *);
1971 	}
1972 	/* now add the parameter */
1973 	switch (ifa->address.sa.sa_family) {
1974 	case AF_INET:
1975 		{
1976 			struct sctp_ipv4addr_param *ipv4p;
1977 			struct sockaddr_in *sin;
1978 
1979 			sin = (struct sockaddr_in *)&ifa->address.sin;
1980 			ipv4p = (struct sctp_ipv4addr_param *)parmh;
1981 			parmh->param_type = htons(SCTP_IPV4_ADDRESS);
1982 			parmh->param_length = htons(len);
1983 			ipv4p->addr = sin->sin_addr.s_addr;
1984 			SCTP_BUF_LEN(mret) += len;
1985 			break;
1986 		}
1987 #ifdef INET6
1988 	case AF_INET6:
1989 		{
1990 			struct sctp_ipv6addr_param *ipv6p;
1991 			struct sockaddr_in6 *sin6;
1992 
1993 			sin6 = (struct sockaddr_in6 *)&ifa->address.sin6;
1994 			ipv6p = (struct sctp_ipv6addr_param *)parmh;
1995 			parmh->param_type = htons(SCTP_IPV6_ADDRESS);
1996 			parmh->param_length = htons(len);
1997 			memcpy(ipv6p->addr, &sin6->sin6_addr,
1998 			    sizeof(ipv6p->addr));
1999 			/* clear embedded scope in the address */
2000 			in6_clearscope((struct in6_addr *)ipv6p->addr);
2001 			SCTP_BUF_LEN(mret) += len;
2002 			break;
2003 		}
2004 #endif
2005 	default:
2006 		return (m);
2007 	}
2008 	return (mret);
2009 }
2010 
2011 
2012 struct mbuf *
2013 sctp_add_addresses_to_i_ia(struct sctp_inpcb *inp, struct sctp_scoping *scope,
2014     struct mbuf *m_at, int cnt_inits_to)
2015 {
2016 	struct sctp_vrf *vrf = NULL;
2017 	int cnt, limit_out = 0, total_count;
2018 	uint32_t vrf_id;
2019 
2020 	vrf_id = inp->def_vrf_id;
2021 	SCTP_IPI_ADDR_RLOCK();
2022 	vrf = sctp_find_vrf(vrf_id);
2023 	if (vrf == NULL) {
2024 		SCTP_IPI_ADDR_RUNLOCK();
2025 		return (m_at);
2026 	}
2027 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
2028 		struct sctp_ifa *sctp_ifap;
2029 		struct sctp_ifn *sctp_ifnp;
2030 
2031 		cnt = cnt_inits_to;
2032 		if (vrf->total_ifa_count > SCTP_COUNT_LIMIT) {
2033 			limit_out = 1;
2034 			cnt = SCTP_ADDRESS_LIMIT;
2035 			goto skip_count;
2036 		}
2037 		LIST_FOREACH(sctp_ifnp, &vrf->ifnlist, next_ifn) {
2038 			if ((scope->loopback_scope == 0) &&
2039 			    SCTP_IFN_IS_IFT_LOOP(sctp_ifnp)) {
2040 				/*
2041 				 * Skip loopback devices if loopback_scope
2042 				 * not set
2043 				 */
2044 				continue;
2045 			}
2046 			LIST_FOREACH(sctp_ifap, &sctp_ifnp->ifalist, next_ifa) {
2047 				if (sctp_is_address_in_scope(sctp_ifap,
2048 				    scope->ipv4_addr_legal,
2049 				    scope->ipv6_addr_legal,
2050 				    scope->loopback_scope,
2051 				    scope->ipv4_local_scope,
2052 				    scope->local_scope,
2053 				    scope->site_scope, 1) == 0) {
2054 					continue;
2055 				}
2056 				cnt++;
2057 				if (cnt > SCTP_ADDRESS_LIMIT) {
2058 					break;
2059 				}
2060 			}
2061 			if (cnt > SCTP_ADDRESS_LIMIT) {
2062 				break;
2063 			}
2064 		}
2065 skip_count:
2066 		if (cnt > 1) {
2067 			total_count = 0;
2068 			LIST_FOREACH(sctp_ifnp, &vrf->ifnlist, next_ifn) {
2069 				cnt = 0;
2070 				if ((scope->loopback_scope == 0) &&
2071 				    SCTP_IFN_IS_IFT_LOOP(sctp_ifnp)) {
2072 					/*
2073 					 * Skip loopback devices if
2074 					 * loopback_scope not set
2075 					 */
2076 					continue;
2077 				}
2078 				LIST_FOREACH(sctp_ifap, &sctp_ifnp->ifalist, next_ifa) {
2079 					if (sctp_is_address_in_scope(sctp_ifap,
2080 					    scope->ipv4_addr_legal,
2081 					    scope->ipv6_addr_legal,
2082 					    scope->loopback_scope,
2083 					    scope->ipv4_local_scope,
2084 					    scope->local_scope,
2085 					    scope->site_scope, 0) == 0) {
2086 						continue;
2087 					}
2088 					m_at = sctp_add_addr_to_mbuf(m_at, sctp_ifap);
2089 					if (limit_out) {
2090 						cnt++;
2091 						total_count++;
2092 						if (cnt >= 2) {
2093 							/*
2094 							 * two from each
2095 							 * address
2096 							 */
2097 							break;
2098 						}
2099 						if (total_count > SCTP_ADDRESS_LIMIT) {
2100 							/* No more addresses */
2101 							break;
2102 						}
2103 					}
2104 				}
2105 			}
2106 		}
2107 	} else {
2108 		struct sctp_laddr *laddr;
2109 
2110 		cnt = cnt_inits_to;
2111 		/* First, how many ? */
2112 		LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
2113 			if (laddr->ifa == NULL) {
2114 				continue;
2115 			}
2116 			if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED)
2117 				/*
2118 				 * Address being deleted by the system, dont
2119 				 * list.
2120 				 */
2121 				continue;
2122 			if (laddr->action == SCTP_DEL_IP_ADDRESS) {
2123 				/*
2124 				 * Address being deleted on this ep don't
2125 				 * list.
2126 				 */
2127 				continue;
2128 			}
2129 			if (sctp_is_address_in_scope(laddr->ifa,
2130 			    scope->ipv4_addr_legal,
2131 			    scope->ipv6_addr_legal,
2132 			    scope->loopback_scope,
2133 			    scope->ipv4_local_scope,
2134 			    scope->local_scope,
2135 			    scope->site_scope, 1) == 0) {
2136 				continue;
2137 			}
2138 			cnt++;
2139 		}
2140 		if (cnt > SCTP_ADDRESS_LIMIT) {
2141 			limit_out = 1;
2142 		}
2143 		/*
2144 		 * To get through a NAT we only list addresses if we have
2145 		 * more than one. That way if you just bind a single address
2146 		 * we let the source of the init dictate our address.
2147 		 */
2148 		if (cnt > 1) {
2149 			LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
2150 				cnt = 0;
2151 				if (laddr->ifa == NULL) {
2152 					continue;
2153 				}
2154 				if (laddr->ifa->localifa_flags & SCTP_BEING_DELETED)
2155 					continue;
2156 
2157 				if (sctp_is_address_in_scope(laddr->ifa,
2158 				    scope->ipv4_addr_legal,
2159 				    scope->ipv6_addr_legal,
2160 				    scope->loopback_scope,
2161 				    scope->ipv4_local_scope,
2162 				    scope->local_scope,
2163 				    scope->site_scope, 0) == 0) {
2164 					continue;
2165 				}
2166 				m_at = sctp_add_addr_to_mbuf(m_at, laddr->ifa);
2167 				cnt++;
2168 				if (cnt >= SCTP_ADDRESS_LIMIT) {
2169 					break;
2170 				}
2171 			}
2172 		}
2173 	}
2174 	SCTP_IPI_ADDR_RUNLOCK();
2175 	return (m_at);
2176 }
2177 
2178 static struct sctp_ifa *
2179 sctp_is_ifa_addr_preferred(struct sctp_ifa *ifa,
2180     uint8_t dest_is_loop,
2181     uint8_t dest_is_priv,
2182     sa_family_t fam)
2183 {
2184 	uint8_t dest_is_global = 0;
2185 
2186 	/* dest_is_priv is true if destination is a private address */
2187 	/* dest_is_loop is true if destination is a loopback addresses */
2188 
2189 	/*
2190 	 * Here we determine if its a preferred address. A preferred address
2191 	 * means it is the same scope or higher scope then the destination.
2192 	 * L = loopback, P = private, G = global
2193 	 * ----------------------------------------- src    |  dest | result
2194 	 * ---------------------------------------- L     |    L  |    yes
2195 	 * ----------------------------------------- P     |    L  |
2196 	 * yes-v4 no-v6 ----------------------------------------- G     |
2197 	 * L  |    yes-v4 no-v6 ----------------------------------------- L
2198 	 * |    P  |    no ----------------------------------------- P     |
2199 	 * P  |    yes ----------------------------------------- G     |
2200 	 * P  |    no ----------------------------------------- L     |    G
2201 	 * |    no ----------------------------------------- P     |    G  |
2202 	 * no ----------------------------------------- G     |    G  |
2203 	 * yes -----------------------------------------
2204 	 */
2205 
2206 	if (ifa->address.sa.sa_family != fam) {
2207 		/* forget mis-matched family */
2208 		return (NULL);
2209 	}
2210 	if ((dest_is_priv == 0) && (dest_is_loop == 0)) {
2211 		dest_is_global = 1;
2212 	}
2213 	SCTPDBG(SCTP_DEBUG_OUTPUT2, "Is destination preferred:");
2214 	SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, &ifa->address.sa);
2215 	/* Ok the address may be ok */
2216 	if (fam == AF_INET6) {
2217 		/* ok to use deprecated addresses? no lets not! */
2218 		if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
2219 			SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:1\n");
2220 			return (NULL);
2221 		}
2222 		if (ifa->src_is_priv && !ifa->src_is_loop) {
2223 			if (dest_is_loop) {
2224 				SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:2\n");
2225 				return (NULL);
2226 			}
2227 		}
2228 		if (ifa->src_is_glob) {
2229 			if (dest_is_loop) {
2230 				SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:3\n");
2231 				return (NULL);
2232 			}
2233 		}
2234 	}
2235 	/*
2236 	 * Now that we know what is what, implement or table this could in
2237 	 * theory be done slicker (it used to be), but this is
2238 	 * straightforward and easier to validate :-)
2239 	 */
2240 	SCTPDBG(SCTP_DEBUG_OUTPUT3, "src_loop:%d src_priv:%d src_glob:%d\n",
2241 	    ifa->src_is_loop, ifa->src_is_priv, ifa->src_is_glob);
2242 	SCTPDBG(SCTP_DEBUG_OUTPUT3, "dest_loop:%d dest_priv:%d dest_glob:%d\n",
2243 	    dest_is_loop, dest_is_priv, dest_is_global);
2244 
2245 	if ((ifa->src_is_loop) && (dest_is_priv)) {
2246 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:4\n");
2247 		return (NULL);
2248 	}
2249 	if ((ifa->src_is_glob) && (dest_is_priv)) {
2250 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:5\n");
2251 		return (NULL);
2252 	}
2253 	if ((ifa->src_is_loop) && (dest_is_global)) {
2254 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:6\n");
2255 		return (NULL);
2256 	}
2257 	if ((ifa->src_is_priv) && (dest_is_global)) {
2258 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "NO:7\n");
2259 		return (NULL);
2260 	}
2261 	SCTPDBG(SCTP_DEBUG_OUTPUT3, "YES\n");
2262 	/* its a preferred address */
2263 	return (ifa);
2264 }
2265 
2266 static struct sctp_ifa *
2267 sctp_is_ifa_addr_acceptable(struct sctp_ifa *ifa,
2268     uint8_t dest_is_loop,
2269     uint8_t dest_is_priv,
2270     sa_family_t fam)
2271 {
2272 	uint8_t dest_is_global = 0;
2273 
2274 
2275 	/*
2276 	 * Here we determine if its a acceptable address. A acceptable
2277 	 * address means it is the same scope or higher scope but we can
2278 	 * allow for NAT which means its ok to have a global dest and a
2279 	 * private src.
2280 	 *
2281 	 * L = loopback, P = private, G = global
2282 	 * ----------------------------------------- src    |  dest | result
2283 	 * ----------------------------------------- L     |   L   |    yes
2284 	 * ----------------------------------------- P     |   L   |
2285 	 * yes-v4 no-v6 ----------------------------------------- G     |
2286 	 * L   |    yes ----------------------------------------- L     |
2287 	 * P   |    no ----------------------------------------- P     |   P
2288 	 * |    yes ----------------------------------------- G     |   P
2289 	 * |    yes - May not work -----------------------------------------
2290 	 * L     |   G   |    no ----------------------------------------- P
2291 	 * |   G   |    yes - May not work
2292 	 * ----------------------------------------- G     |   G   |    yes
2293 	 * -----------------------------------------
2294 	 */
2295 
2296 	if (ifa->address.sa.sa_family != fam) {
2297 		/* forget non matching family */
2298 		return (NULL);
2299 	}
2300 	/* Ok the address may be ok */
2301 	if ((dest_is_loop == 0) && (dest_is_priv == 0)) {
2302 		dest_is_global = 1;
2303 	}
2304 	if (fam == AF_INET6) {
2305 		/* ok to use deprecated addresses? */
2306 		if (ifa->localifa_flags & SCTP_ADDR_IFA_UNUSEABLE) {
2307 			return (NULL);
2308 		}
2309 		if (ifa->src_is_priv) {
2310 			/* Special case, linklocal to loop */
2311 			if (dest_is_loop)
2312 				return (NULL);
2313 		}
2314 	}
2315 	/*
2316 	 * Now that we know what is what, implement our table. This could in
2317 	 * theory be done slicker (it used to be), but this is
2318 	 * straightforward and easier to validate :-)
2319 	 */
2320 	if ((ifa->src_is_loop == 1) && (dest_is_priv)) {
2321 		return (NULL);
2322 	}
2323 	if ((ifa->src_is_loop == 1) && (dest_is_global)) {
2324 		return (NULL);
2325 	}
2326 	/* its an acceptable address */
2327 	return (ifa);
2328 }
2329 
2330 int
2331 sctp_is_addr_restricted(struct sctp_tcb *stcb, struct sctp_ifa *ifa)
2332 {
2333 	struct sctp_laddr *laddr;
2334 
2335 	if (stcb == NULL) {
2336 		/* There are no restrictions, no TCB :-) */
2337 		return (0);
2338 	}
2339 	LIST_FOREACH(laddr, &stcb->asoc.sctp_restricted_addrs, sctp_nxt_addr) {
2340 		if (laddr->ifa == NULL) {
2341 			SCTPDBG(SCTP_DEBUG_OUTPUT1, "%s: NULL ifa\n",
2342 			    __FUNCTION__);
2343 			continue;
2344 		}
2345 		if (laddr->ifa == ifa) {
2346 			/* Yes it is on the list */
2347 			return (1);
2348 		}
2349 	}
2350 	return (0);
2351 }
2352 
2353 
2354 int
2355 sctp_is_addr_in_ep(struct sctp_inpcb *inp, struct sctp_ifa *ifa)
2356 {
2357 	struct sctp_laddr *laddr;
2358 
2359 	if (ifa == NULL)
2360 		return (0);
2361 	LIST_FOREACH(laddr, &inp->sctp_addr_list, sctp_nxt_addr) {
2362 		if (laddr->ifa == NULL) {
2363 			SCTPDBG(SCTP_DEBUG_OUTPUT1, "%s: NULL ifa\n",
2364 			    __FUNCTION__);
2365 			continue;
2366 		}
2367 		if ((laddr->ifa == ifa) && laddr->action == 0)
2368 			/* same pointer */
2369 			return (1);
2370 	}
2371 	return (0);
2372 }
2373 
2374 
2375 
2376 static struct sctp_ifa *
2377 sctp_choose_boundspecific_inp(struct sctp_inpcb *inp,
2378     sctp_route_t * ro,
2379     uint32_t vrf_id,
2380     int non_asoc_addr_ok,
2381     uint8_t dest_is_priv,
2382     uint8_t dest_is_loop,
2383     sa_family_t fam)
2384 {
2385 	struct sctp_laddr *laddr, *starting_point;
2386 	void *ifn;
2387 	int resettotop = 0;
2388 	struct sctp_ifn *sctp_ifn;
2389 	struct sctp_ifa *sctp_ifa, *sifa;
2390 	struct sctp_vrf *vrf;
2391 	uint32_t ifn_index;
2392 
2393 	vrf = sctp_find_vrf(vrf_id);
2394 	if (vrf == NULL)
2395 		return (NULL);
2396 
2397 	ifn = SCTP_GET_IFN_VOID_FROM_ROUTE(ro);
2398 	ifn_index = SCTP_GET_IF_INDEX_FROM_ROUTE(ro);
2399 	sctp_ifn = sctp_find_ifn(ifn, ifn_index);
2400 	/*
2401 	 * first question, is the ifn we will emit on in our list, if so, we
2402 	 * want such an address. Note that we first looked for a preferred
2403 	 * address.
2404 	 */
2405 	if (sctp_ifn) {
2406 		/* is a preferred one on the interface we route out? */
2407 		LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
2408 			if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
2409 			    (non_asoc_addr_ok == 0))
2410 				continue;
2411 			sifa = sctp_is_ifa_addr_preferred(sctp_ifa,
2412 			    dest_is_loop,
2413 			    dest_is_priv, fam);
2414 			if (sifa == NULL)
2415 				continue;
2416 			if (sctp_is_addr_in_ep(inp, sifa)) {
2417 				atomic_add_int(&sifa->refcount, 1);
2418 				return (sifa);
2419 			}
2420 		}
2421 	}
2422 	/*
2423 	 * ok, now we now need to find one on the list of the addresses. We
2424 	 * can't get one on the emitting interface so let's find first a
2425 	 * preferred one. If not that an acceptable one otherwise... we
2426 	 * return NULL.
2427 	 */
2428 	starting_point = inp->next_addr_touse;
2429 once_again:
2430 	if (inp->next_addr_touse == NULL) {
2431 		inp->next_addr_touse = LIST_FIRST(&inp->sctp_addr_list);
2432 		resettotop = 1;
2433 	}
2434 	for (laddr = inp->next_addr_touse; laddr;
2435 	    laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
2436 		if (laddr->ifa == NULL) {
2437 			/* address has been removed */
2438 			continue;
2439 		}
2440 		if (laddr->action == SCTP_DEL_IP_ADDRESS) {
2441 			/* address is being deleted */
2442 			continue;
2443 		}
2444 		sifa = sctp_is_ifa_addr_preferred(laddr->ifa, dest_is_loop,
2445 		    dest_is_priv, fam);
2446 		if (sifa == NULL)
2447 			continue;
2448 		atomic_add_int(&sifa->refcount, 1);
2449 		return (sifa);
2450 	}
2451 	if (resettotop == 0) {
2452 		inp->next_addr_touse = NULL;
2453 		goto once_again;
2454 	}
2455 	inp->next_addr_touse = starting_point;
2456 	resettotop = 0;
2457 once_again_too:
2458 	if (inp->next_addr_touse == NULL) {
2459 		inp->next_addr_touse = LIST_FIRST(&inp->sctp_addr_list);
2460 		resettotop = 1;
2461 	}
2462 	/* ok, what about an acceptable address in the inp */
2463 	for (laddr = inp->next_addr_touse; laddr;
2464 	    laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
2465 		if (laddr->ifa == NULL) {
2466 			/* address has been removed */
2467 			continue;
2468 		}
2469 		if (laddr->action == SCTP_DEL_IP_ADDRESS) {
2470 			/* address is being deleted */
2471 			continue;
2472 		}
2473 		sifa = sctp_is_ifa_addr_acceptable(laddr->ifa, dest_is_loop,
2474 		    dest_is_priv, fam);
2475 		if (sifa == NULL)
2476 			continue;
2477 		atomic_add_int(&sifa->refcount, 1);
2478 		return (sifa);
2479 	}
2480 	if (resettotop == 0) {
2481 		inp->next_addr_touse = NULL;
2482 		goto once_again_too;
2483 	}
2484 	/*
2485 	 * no address bound can be a source for the destination we are in
2486 	 * trouble
2487 	 */
2488 	return (NULL);
2489 }
2490 
2491 
2492 
2493 static struct sctp_ifa *
2494 sctp_choose_boundspecific_stcb(struct sctp_inpcb *inp,
2495     struct sctp_tcb *stcb,
2496     struct sctp_nets *net,
2497     sctp_route_t * ro,
2498     uint32_t vrf_id,
2499     uint8_t dest_is_priv,
2500     uint8_t dest_is_loop,
2501     int non_asoc_addr_ok,
2502     sa_family_t fam)
2503 {
2504 	struct sctp_laddr *laddr, *starting_point;
2505 	void *ifn;
2506 	struct sctp_ifn *sctp_ifn;
2507 	struct sctp_ifa *sctp_ifa, *sifa;
2508 	uint8_t start_at_beginning = 0;
2509 	struct sctp_vrf *vrf;
2510 	uint32_t ifn_index;
2511 
2512 	/*
2513 	 * first question, is the ifn we will emit on in our list, if so, we
2514 	 * want that one.
2515 	 */
2516 	vrf = sctp_find_vrf(vrf_id);
2517 	if (vrf == NULL)
2518 		return (NULL);
2519 
2520 	ifn = SCTP_GET_IFN_VOID_FROM_ROUTE(ro);
2521 	ifn_index = SCTP_GET_IF_INDEX_FROM_ROUTE(ro);
2522 	sctp_ifn = sctp_find_ifn(ifn, ifn_index);
2523 
2524 	/*
2525 	 * first question, is the ifn we will emit on in our list?  If so,
2526 	 * we want that one. First we look for a preferred. Second, we go
2527 	 * for an acceptable.
2528 	 */
2529 	if (sctp_ifn) {
2530 		/* first try for a preferred address on the ep */
2531 		LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
2532 			if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) && (non_asoc_addr_ok == 0))
2533 				continue;
2534 			if (sctp_is_addr_in_ep(inp, sctp_ifa)) {
2535 				sifa = sctp_is_ifa_addr_preferred(sctp_ifa, dest_is_loop, dest_is_priv, fam);
2536 				if (sifa == NULL)
2537 					continue;
2538 				if (((non_asoc_addr_ok == 0) &&
2539 				    (sctp_is_addr_restricted(stcb, sifa))) ||
2540 				    (non_asoc_addr_ok &&
2541 				    (sctp_is_addr_restricted(stcb, sifa)) &&
2542 				    (!sctp_is_addr_pending(stcb, sifa)))) {
2543 					/* on the no-no list */
2544 					continue;
2545 				}
2546 				atomic_add_int(&sifa->refcount, 1);
2547 				return (sifa);
2548 			}
2549 		}
2550 		/* next try for an acceptable address on the ep */
2551 		LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
2552 			if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) && (non_asoc_addr_ok == 0))
2553 				continue;
2554 			if (sctp_is_addr_in_ep(inp, sctp_ifa)) {
2555 				sifa = sctp_is_ifa_addr_acceptable(sctp_ifa, dest_is_loop, dest_is_priv, fam);
2556 				if (sifa == NULL)
2557 					continue;
2558 				if (((non_asoc_addr_ok == 0) &&
2559 				    (sctp_is_addr_restricted(stcb, sifa))) ||
2560 				    (non_asoc_addr_ok &&
2561 				    (sctp_is_addr_restricted(stcb, sifa)) &&
2562 				    (!sctp_is_addr_pending(stcb, sifa)))) {
2563 					/* on the no-no list */
2564 					continue;
2565 				}
2566 				atomic_add_int(&sifa->refcount, 1);
2567 				return (sifa);
2568 			}
2569 		}
2570 
2571 	}
2572 	/*
2573 	 * if we can't find one like that then we must look at all addresses
2574 	 * bound to pick one at first preferable then secondly acceptable.
2575 	 */
2576 	starting_point = stcb->asoc.last_used_address;
2577 sctp_from_the_top:
2578 	if (stcb->asoc.last_used_address == NULL) {
2579 		start_at_beginning = 1;
2580 		stcb->asoc.last_used_address = LIST_FIRST(&inp->sctp_addr_list);
2581 	}
2582 	/* search beginning with the last used address */
2583 	for (laddr = stcb->asoc.last_used_address; laddr;
2584 	    laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
2585 		if (laddr->ifa == NULL) {
2586 			/* address has been removed */
2587 			continue;
2588 		}
2589 		if (laddr->action == SCTP_DEL_IP_ADDRESS) {
2590 			/* address is being deleted */
2591 			continue;
2592 		}
2593 		sifa = sctp_is_ifa_addr_preferred(laddr->ifa, dest_is_loop, dest_is_priv, fam);
2594 		if (sifa == NULL)
2595 			continue;
2596 		if (((non_asoc_addr_ok == 0) &&
2597 		    (sctp_is_addr_restricted(stcb, sifa))) ||
2598 		    (non_asoc_addr_ok &&
2599 		    (sctp_is_addr_restricted(stcb, sifa)) &&
2600 		    (!sctp_is_addr_pending(stcb, sifa)))) {
2601 			/* on the no-no list */
2602 			continue;
2603 		}
2604 		stcb->asoc.last_used_address = laddr;
2605 		atomic_add_int(&sifa->refcount, 1);
2606 		return (sifa);
2607 	}
2608 	if (start_at_beginning == 0) {
2609 		stcb->asoc.last_used_address = NULL;
2610 		goto sctp_from_the_top;
2611 	}
2612 	/* now try for any higher scope than the destination */
2613 	stcb->asoc.last_used_address = starting_point;
2614 	start_at_beginning = 0;
2615 sctp_from_the_top2:
2616 	if (stcb->asoc.last_used_address == NULL) {
2617 		start_at_beginning = 1;
2618 		stcb->asoc.last_used_address = LIST_FIRST(&inp->sctp_addr_list);
2619 	}
2620 	/* search beginning with the last used address */
2621 	for (laddr = stcb->asoc.last_used_address; laddr;
2622 	    laddr = LIST_NEXT(laddr, sctp_nxt_addr)) {
2623 		if (laddr->ifa == NULL) {
2624 			/* address has been removed */
2625 			continue;
2626 		}
2627 		if (laddr->action == SCTP_DEL_IP_ADDRESS) {
2628 			/* address is being deleted */
2629 			continue;
2630 		}
2631 		sifa = sctp_is_ifa_addr_acceptable(laddr->ifa, dest_is_loop,
2632 		    dest_is_priv, fam);
2633 		if (sifa == NULL)
2634 			continue;
2635 		if (((non_asoc_addr_ok == 0) &&
2636 		    (sctp_is_addr_restricted(stcb, sifa))) ||
2637 		    (non_asoc_addr_ok &&
2638 		    (sctp_is_addr_restricted(stcb, sifa)) &&
2639 		    (!sctp_is_addr_pending(stcb, sifa)))) {
2640 			/* on the no-no list */
2641 			continue;
2642 		}
2643 		stcb->asoc.last_used_address = laddr;
2644 		atomic_add_int(&sifa->refcount, 1);
2645 		return (sifa);
2646 	}
2647 	if (start_at_beginning == 0) {
2648 		stcb->asoc.last_used_address = NULL;
2649 		goto sctp_from_the_top2;
2650 	}
2651 	return (NULL);
2652 }
2653 
2654 static struct sctp_ifa *
2655 sctp_select_nth_preferred_addr_from_ifn_boundall(struct sctp_ifn *ifn,
2656     struct sctp_tcb *stcb,
2657     int non_asoc_addr_ok,
2658     uint8_t dest_is_loop,
2659     uint8_t dest_is_priv,
2660     int addr_wanted,
2661     sa_family_t fam,
2662     sctp_route_t * ro
2663 )
2664 {
2665 	struct sctp_ifa *ifa, *sifa;
2666 	int num_eligible_addr = 0;
2667 
2668 #ifdef INET6
2669 	struct sockaddr_in6 sin6, lsa6;
2670 
2671 	if (fam == AF_INET6) {
2672 		memcpy(&sin6, &ro->ro_dst, sizeof(struct sockaddr_in6));
2673 		(void)sa6_recoverscope(&sin6);
2674 	}
2675 #endif				/* INET6 */
2676 	LIST_FOREACH(ifa, &ifn->ifalist, next_ifa) {
2677 		if ((ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
2678 		    (non_asoc_addr_ok == 0))
2679 			continue;
2680 		sifa = sctp_is_ifa_addr_preferred(ifa, dest_is_loop,
2681 		    dest_is_priv, fam);
2682 		if (sifa == NULL)
2683 			continue;
2684 #ifdef INET6
2685 		if (fam == AF_INET6 &&
2686 		    dest_is_loop &&
2687 		    sifa->src_is_loop && sifa->src_is_priv) {
2688 			/*
2689 			 * don't allow fe80::1 to be a src on loop ::1, we
2690 			 * don't list it to the peer so we will get an
2691 			 * abort.
2692 			 */
2693 			continue;
2694 		}
2695 		if (fam == AF_INET6 &&
2696 		    IN6_IS_ADDR_LINKLOCAL(&sifa->address.sin6.sin6_addr) &&
2697 		    IN6_IS_ADDR_LINKLOCAL(&sin6.sin6_addr)) {
2698 			/*
2699 			 * link-local <-> link-local must belong to the same
2700 			 * scope.
2701 			 */
2702 			memcpy(&lsa6, &sifa->address.sin6, sizeof(struct sockaddr_in6));
2703 			(void)sa6_recoverscope(&lsa6);
2704 			if (sin6.sin6_scope_id != lsa6.sin6_scope_id) {
2705 				continue;
2706 			}
2707 		}
2708 #endif				/* INET6 */
2709 
2710 		/*
2711 		 * Check if the IPv6 address matches to next-hop. In the
2712 		 * mobile case, old IPv6 address may be not deleted from the
2713 		 * interface. Then, the interface has previous and new
2714 		 * addresses.  We should use one corresponding to the
2715 		 * next-hop.  (by micchie)
2716 		 */
2717 #ifdef INET6
2718 		if (stcb && fam == AF_INET6 &&
2719 		    sctp_is_mobility_feature_on(stcb->sctp_ep, SCTP_MOBILITY_BASE)) {
2720 			if (sctp_v6src_match_nexthop(&sifa->address.sin6, ro)
2721 			    == 0) {
2722 				continue;
2723 			}
2724 		}
2725 #endif
2726 		/* Avoid topologically incorrect IPv4 address */
2727 		if (stcb && fam == AF_INET &&
2728 		    sctp_is_mobility_feature_on(stcb->sctp_ep, SCTP_MOBILITY_BASE)) {
2729 			if (sctp_v4src_match_nexthop(sifa, ro) == 0) {
2730 				continue;
2731 			}
2732 		}
2733 		if (stcb) {
2734 			if (((non_asoc_addr_ok == 0) &&
2735 			    (sctp_is_addr_restricted(stcb, sifa))) ||
2736 			    (non_asoc_addr_ok &&
2737 			    (sctp_is_addr_restricted(stcb, sifa)) &&
2738 			    (!sctp_is_addr_pending(stcb, sifa)))) {
2739 				/*
2740 				 * It is restricted for some reason..
2741 				 * probably not yet added.
2742 				 */
2743 				continue;
2744 			}
2745 		}
2746 		if (num_eligible_addr >= addr_wanted) {
2747 			return (sifa);
2748 		}
2749 		num_eligible_addr++;
2750 	}
2751 	return (NULL);
2752 }
2753 
2754 
2755 static int
2756 sctp_count_num_preferred_boundall(struct sctp_ifn *ifn,
2757     struct sctp_tcb *stcb,
2758     int non_asoc_addr_ok,
2759     uint8_t dest_is_loop,
2760     uint8_t dest_is_priv,
2761     sa_family_t fam)
2762 {
2763 	struct sctp_ifa *ifa, *sifa;
2764 	int num_eligible_addr = 0;
2765 
2766 	LIST_FOREACH(ifa, &ifn->ifalist, next_ifa) {
2767 		if ((ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
2768 		    (non_asoc_addr_ok == 0)) {
2769 			continue;
2770 		}
2771 		sifa = sctp_is_ifa_addr_preferred(ifa, dest_is_loop,
2772 		    dest_is_priv, fam);
2773 		if (sifa == NULL) {
2774 			continue;
2775 		}
2776 		if (stcb) {
2777 			if (((non_asoc_addr_ok == 0) &&
2778 			    (sctp_is_addr_restricted(stcb, sifa))) ||
2779 			    (non_asoc_addr_ok &&
2780 			    (sctp_is_addr_restricted(stcb, sifa)) &&
2781 			    (!sctp_is_addr_pending(stcb, sifa)))) {
2782 				/*
2783 				 * It is restricted for some reason..
2784 				 * probably not yet added.
2785 				 */
2786 				continue;
2787 			}
2788 		}
2789 		num_eligible_addr++;
2790 	}
2791 	return (num_eligible_addr);
2792 }
2793 
2794 static struct sctp_ifa *
2795 sctp_choose_boundall(struct sctp_inpcb *inp,
2796     struct sctp_tcb *stcb,
2797     struct sctp_nets *net,
2798     sctp_route_t * ro,
2799     uint32_t vrf_id,
2800     uint8_t dest_is_priv,
2801     uint8_t dest_is_loop,
2802     int non_asoc_addr_ok,
2803     sa_family_t fam)
2804 {
2805 	int cur_addr_num = 0, num_preferred = 0;
2806 	void *ifn;
2807 	struct sctp_ifn *sctp_ifn, *looked_at = NULL, *emit_ifn;
2808 	struct sctp_ifa *sctp_ifa, *sifa;
2809 	uint32_t ifn_index;
2810 	struct sctp_vrf *vrf;
2811 
2812 	/*-
2813 	 * For boundall we can use any address in the association.
2814 	 * If non_asoc_addr_ok is set we can use any address (at least in
2815 	 * theory). So we look for preferred addresses first. If we find one,
2816 	 * we use it. Otherwise we next try to get an address on the
2817 	 * interface, which we should be able to do (unless non_asoc_addr_ok
2818 	 * is false and we are routed out that way). In these cases where we
2819 	 * can't use the address of the interface we go through all the
2820 	 * ifn's looking for an address we can use and fill that in. Punting
2821 	 * means we send back address 0, which will probably cause problems
2822 	 * actually since then IP will fill in the address of the route ifn,
2823 	 * which means we probably already rejected it.. i.e. here comes an
2824 	 * abort :-<.
2825 	 */
2826 	vrf = sctp_find_vrf(vrf_id);
2827 	if (vrf == NULL)
2828 		return (NULL);
2829 
2830 	ifn = SCTP_GET_IFN_VOID_FROM_ROUTE(ro);
2831 	ifn_index = SCTP_GET_IF_INDEX_FROM_ROUTE(ro);
2832 	emit_ifn = looked_at = sctp_ifn = sctp_find_ifn(ifn, ifn_index);
2833 	if (sctp_ifn == NULL) {
2834 		/* ?? We don't have this guy ?? */
2835 		SCTPDBG(SCTP_DEBUG_OUTPUT2, "No ifn emit interface?\n");
2836 		goto bound_all_plan_b;
2837 	}
2838 	SCTPDBG(SCTP_DEBUG_OUTPUT2, "ifn_index:%d name:%s is emit interface\n",
2839 	    ifn_index, sctp_ifn->ifn_name);
2840 
2841 	if (net) {
2842 		cur_addr_num = net->indx_of_eligible_next_to_use;
2843 	}
2844 	num_preferred = sctp_count_num_preferred_boundall(sctp_ifn,
2845 	    stcb,
2846 	    non_asoc_addr_ok,
2847 	    dest_is_loop,
2848 	    dest_is_priv, fam);
2849 	SCTPDBG(SCTP_DEBUG_OUTPUT2, "Found %d preferred source addresses for intf:%s\n",
2850 	    num_preferred, sctp_ifn->ifn_name);
2851 	if (num_preferred == 0) {
2852 		/*
2853 		 * no eligible addresses, we must use some other interface
2854 		 * address if we can find one.
2855 		 */
2856 		goto bound_all_plan_b;
2857 	}
2858 	/*
2859 	 * Ok we have num_eligible_addr set with how many we can use, this
2860 	 * may vary from call to call due to addresses being deprecated
2861 	 * etc..
2862 	 */
2863 	if (cur_addr_num >= num_preferred) {
2864 		cur_addr_num = 0;
2865 	}
2866 	/*
2867 	 * select the nth address from the list (where cur_addr_num is the
2868 	 * nth) and 0 is the first one, 1 is the second one etc...
2869 	 */
2870 	SCTPDBG(SCTP_DEBUG_OUTPUT2, "cur_addr_num:%d\n", cur_addr_num);
2871 
2872 	sctp_ifa = sctp_select_nth_preferred_addr_from_ifn_boundall(sctp_ifn, stcb, non_asoc_addr_ok, dest_is_loop,
2873 	    dest_is_priv, cur_addr_num, fam, ro);
2874 
2875 	/* if sctp_ifa is NULL something changed??, fall to plan b. */
2876 	if (sctp_ifa) {
2877 		atomic_add_int(&sctp_ifa->refcount, 1);
2878 		if (net) {
2879 			/* save off where the next one we will want */
2880 			net->indx_of_eligible_next_to_use = cur_addr_num + 1;
2881 		}
2882 		return (sctp_ifa);
2883 	}
2884 	/*
2885 	 * plan_b: Look at all interfaces and find a preferred address. If
2886 	 * no preferred fall through to plan_c.
2887 	 */
2888 bound_all_plan_b:
2889 	SCTPDBG(SCTP_DEBUG_OUTPUT2, "Trying Plan B\n");
2890 	LIST_FOREACH(sctp_ifn, &vrf->ifnlist, next_ifn) {
2891 		SCTPDBG(SCTP_DEBUG_OUTPUT2, "Examine interface %s\n",
2892 		    sctp_ifn->ifn_name);
2893 		if (dest_is_loop == 0 && SCTP_IFN_IS_IFT_LOOP(sctp_ifn)) {
2894 			/* wrong base scope */
2895 			SCTPDBG(SCTP_DEBUG_OUTPUT2, "skip\n");
2896 			continue;
2897 		}
2898 		if ((sctp_ifn == looked_at) && looked_at) {
2899 			/* already looked at this guy */
2900 			SCTPDBG(SCTP_DEBUG_OUTPUT2, "already seen\n");
2901 			continue;
2902 		}
2903 		num_preferred = sctp_count_num_preferred_boundall(sctp_ifn, stcb, non_asoc_addr_ok,
2904 		    dest_is_loop, dest_is_priv, fam);
2905 		SCTPDBG(SCTP_DEBUG_OUTPUT2,
2906 		    "Found ifn:%p %d preferred source addresses\n",
2907 		    ifn, num_preferred);
2908 		if (num_preferred == 0) {
2909 			/* None on this interface. */
2910 			SCTPDBG(SCTP_DEBUG_OUTPUT2, "No prefered -- skipping to next\n");
2911 			continue;
2912 		}
2913 		SCTPDBG(SCTP_DEBUG_OUTPUT2,
2914 		    "num preferred:%d on interface:%p cur_addr_num:%d\n",
2915 		    num_preferred, sctp_ifn, cur_addr_num);
2916 
2917 		/*
2918 		 * Ok we have num_eligible_addr set with how many we can
2919 		 * use, this may vary from call to call due to addresses
2920 		 * being deprecated etc..
2921 		 */
2922 		if (cur_addr_num >= num_preferred) {
2923 			cur_addr_num = 0;
2924 		}
2925 		sifa = sctp_select_nth_preferred_addr_from_ifn_boundall(sctp_ifn, stcb, non_asoc_addr_ok, dest_is_loop,
2926 		    dest_is_priv, cur_addr_num, fam, ro);
2927 		if (sifa == NULL)
2928 			continue;
2929 		if (net) {
2930 			net->indx_of_eligible_next_to_use = cur_addr_num + 1;
2931 			SCTPDBG(SCTP_DEBUG_OUTPUT2, "we selected %d\n",
2932 			    cur_addr_num);
2933 			SCTPDBG(SCTP_DEBUG_OUTPUT2, "Source:");
2934 			SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, &sifa->address.sa);
2935 			SCTPDBG(SCTP_DEBUG_OUTPUT2, "Dest:");
2936 			SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, &net->ro._l_addr.sa);
2937 		}
2938 		atomic_add_int(&sifa->refcount, 1);
2939 		return (sifa);
2940 
2941 	}
2942 
2943 	/* plan_c: do we have an acceptable address on the emit interface */
2944 	SCTPDBG(SCTP_DEBUG_OUTPUT2, "Trying Plan C: find acceptable on interface\n");
2945 	if (emit_ifn == NULL) {
2946 		goto plan_d;
2947 	}
2948 	LIST_FOREACH(sctp_ifa, &emit_ifn->ifalist, next_ifa) {
2949 		if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
2950 		    (non_asoc_addr_ok == 0))
2951 			continue;
2952 		sifa = sctp_is_ifa_addr_acceptable(sctp_ifa, dest_is_loop,
2953 		    dest_is_priv, fam);
2954 		if (sifa == NULL)
2955 			continue;
2956 		if (stcb) {
2957 			if (((non_asoc_addr_ok == 0) &&
2958 			    (sctp_is_addr_restricted(stcb, sifa))) ||
2959 			    (non_asoc_addr_ok &&
2960 			    (sctp_is_addr_restricted(stcb, sifa)) &&
2961 			    (!sctp_is_addr_pending(stcb, sifa)))) {
2962 				/*
2963 				 * It is restricted for some reason..
2964 				 * probably not yet added.
2965 				 */
2966 				continue;
2967 			}
2968 		}
2969 		atomic_add_int(&sifa->refcount, 1);
2970 		return (sifa);
2971 	}
2972 plan_d:
2973 	/*
2974 	 * plan_d: We are in trouble. No preferred address on the emit
2975 	 * interface. And not even a preferred address on all interfaces. Go
2976 	 * out and see if we can find an acceptable address somewhere
2977 	 * amongst all interfaces.
2978 	 */
2979 	SCTPDBG(SCTP_DEBUG_OUTPUT2, "Trying Plan D\n");
2980 	LIST_FOREACH(sctp_ifn, &vrf->ifnlist, next_ifn) {
2981 		if (dest_is_loop == 0 && SCTP_IFN_IS_IFT_LOOP(sctp_ifn)) {
2982 			/* wrong base scope */
2983 			continue;
2984 		}
2985 		if ((sctp_ifn == looked_at) && looked_at)
2986 			/* already looked at this guy */
2987 			continue;
2988 
2989 		LIST_FOREACH(sctp_ifa, &sctp_ifn->ifalist, next_ifa) {
2990 			if ((sctp_ifa->localifa_flags & SCTP_ADDR_DEFER_USE) &&
2991 			    (non_asoc_addr_ok == 0))
2992 				continue;
2993 			sifa = sctp_is_ifa_addr_acceptable(sctp_ifa,
2994 			    dest_is_loop,
2995 			    dest_is_priv, fam);
2996 			if (sifa == NULL)
2997 				continue;
2998 			if (stcb) {
2999 				if (((non_asoc_addr_ok == 0) &&
3000 				    (sctp_is_addr_restricted(stcb, sifa))) ||
3001 				    (non_asoc_addr_ok &&
3002 				    (sctp_is_addr_restricted(stcb, sifa)) &&
3003 				    (!sctp_is_addr_pending(stcb, sifa)))) {
3004 					/*
3005 					 * It is restricted for some
3006 					 * reason.. probably not yet added.
3007 					 */
3008 					continue;
3009 				}
3010 			}
3011 			atomic_add_int(&sifa->refcount, 1);
3012 			return (sifa);
3013 		}
3014 	}
3015 	/*
3016 	 * Ok we can find NO address to source from that is not on our
3017 	 * restricted list and non_asoc_address is NOT ok, or it is on our
3018 	 * restricted list. We can't source to it :-(
3019 	 */
3020 	return (NULL);
3021 }
3022 
3023 
3024 
3025 /* tcb may be NULL */
3026 struct sctp_ifa *
3027 sctp_source_address_selection(struct sctp_inpcb *inp,
3028     struct sctp_tcb *stcb,
3029     sctp_route_t * ro,
3030     struct sctp_nets *net,
3031     int non_asoc_addr_ok, uint32_t vrf_id)
3032 {
3033 	struct sockaddr_in *to = (struct sockaddr_in *)&ro->ro_dst;
3034 
3035 #ifdef INET6
3036 	struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&ro->ro_dst;
3037 
3038 #endif
3039 	struct sctp_ifa *answer;
3040 	uint8_t dest_is_priv, dest_is_loop;
3041 	sa_family_t fam;
3042 
3043 	/*-
3044 	 * Rules: - Find the route if needed, cache if I can. - Look at
3045 	 * interface address in route, Is it in the bound list. If so we
3046 	 * have the best source. - If not we must rotate amongst the
3047 	 * addresses.
3048 	 *
3049 	 * Cavets and issues
3050 	 *
3051 	 * Do we need to pay attention to scope. We can have a private address
3052 	 * or a global address we are sourcing or sending to. So if we draw
3053 	 * it out
3054 	 * zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
3055 	 * For V4
3056          *------------------------------------------
3057 	 *      source     *      dest  *  result
3058 	 * -----------------------------------------
3059 	 * <a>  Private    *    Global  *  NAT
3060 	 * -----------------------------------------
3061 	 * <b>  Private    *    Private *  No problem
3062 	 * -----------------------------------------
3063          * <c>  Global     *    Private *  Huh, How will this work?
3064 	 * -----------------------------------------
3065          * <d>  Global     *    Global  *  No Problem
3066          *------------------------------------------
3067 	 * zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
3068 	 * For V6
3069          *------------------------------------------
3070 	 *      source     *      dest  *  result
3071 	 * -----------------------------------------
3072 	 * <a>  Linklocal  *    Global  *
3073 	 * -----------------------------------------
3074 	 * <b>  Linklocal  * Linklocal  *  No problem
3075 	 * -----------------------------------------
3076          * <c>  Global     * Linklocal  *  Huh, How will this work?
3077 	 * -----------------------------------------
3078          * <d>  Global     *    Global  *  No Problem
3079          *------------------------------------------
3080 	 * zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
3081          *
3082 	 * And then we add to that what happens if there are multiple addresses
3083 	 * assigned to an interface. Remember the ifa on a ifn is a linked
3084 	 * list of addresses. So one interface can have more than one IP
3085 	 * address. What happens if we have both a private and a global
3086 	 * address? Do we then use context of destination to sort out which
3087 	 * one is best? And what about NAT's sending P->G may get you a NAT
3088 	 * translation, or should you select the G thats on the interface in
3089 	 * preference.
3090 	 *
3091 	 * Decisions:
3092 	 *
3093 	 * - count the number of addresses on the interface.
3094          * - if it is one, no problem except case <c>.
3095          *   For <a> we will assume a NAT out there.
3096 	 * - if there are more than one, then we need to worry about scope P
3097 	 *   or G. We should prefer G -> G and P -> P if possible.
3098 	 *   Then as a secondary fall back to mixed types G->P being a last
3099 	 *   ditch one.
3100          * - The above all works for bound all, but bound specific we need to
3101 	 *   use the same concept but instead only consider the bound
3102 	 *   addresses. If the bound set is NOT assigned to the interface then
3103 	 *   we must use rotation amongst the bound addresses..
3104 	 */
3105 	if (ro->ro_rt == NULL) {
3106 		/*
3107 		 * Need a route to cache.
3108 		 */
3109 		SCTP_RTALLOC(ro, vrf_id);
3110 	}
3111 	if (ro->ro_rt == NULL) {
3112 		return (NULL);
3113 	}
3114 	fam = to->sin_family;
3115 	dest_is_priv = dest_is_loop = 0;
3116 	/* Setup our scopes for the destination */
3117 	switch (fam) {
3118 	case AF_INET:
3119 		/* Scope based on outbound address */
3120 		if (IN4_ISLOOPBACK_ADDRESS(&to->sin_addr)) {
3121 			dest_is_loop = 1;
3122 			if (net != NULL) {
3123 				/* mark it as local */
3124 				net->addr_is_local = 1;
3125 			}
3126 		} else if ((IN4_ISPRIVATE_ADDRESS(&to->sin_addr))) {
3127 			dest_is_priv = 1;
3128 		}
3129 		break;
3130 #ifdef INET6
3131 	case AF_INET6:
3132 		/* Scope based on outbound address */
3133 		if (IN6_IS_ADDR_LOOPBACK(&to6->sin6_addr) ||
3134 		    SCTP_ROUTE_IS_REAL_LOOP(ro)) {
3135 			/*
3136 			 * If the address is a loopback address, which
3137 			 * consists of "::1" OR "fe80::1%lo0", we are
3138 			 * loopback scope. But we don't use dest_is_priv
3139 			 * (link local addresses).
3140 			 */
3141 			dest_is_loop = 1;
3142 			if (net != NULL) {
3143 				/* mark it as local */
3144 				net->addr_is_local = 1;
3145 			}
3146 		} else if (IN6_IS_ADDR_LINKLOCAL(&to6->sin6_addr)) {
3147 			dest_is_priv = 1;
3148 		}
3149 		break;
3150 #endif
3151 	}
3152 	SCTPDBG(SCTP_DEBUG_OUTPUT2, "Select source addr for:");
3153 	SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, (struct sockaddr *)to);
3154 	SCTP_IPI_ADDR_RLOCK();
3155 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUNDALL) {
3156 		/*
3157 		 * Bound all case
3158 		 */
3159 		answer = sctp_choose_boundall(inp, stcb, net, ro, vrf_id,
3160 		    dest_is_priv, dest_is_loop,
3161 		    non_asoc_addr_ok, fam);
3162 		SCTP_IPI_ADDR_RUNLOCK();
3163 		return (answer);
3164 	}
3165 	/*
3166 	 * Subset bound case
3167 	 */
3168 	if (stcb) {
3169 		answer = sctp_choose_boundspecific_stcb(inp, stcb, net, ro,
3170 		    vrf_id, dest_is_priv,
3171 		    dest_is_loop,
3172 		    non_asoc_addr_ok, fam);
3173 	} else {
3174 		answer = sctp_choose_boundspecific_inp(inp, ro, vrf_id,
3175 		    non_asoc_addr_ok,
3176 		    dest_is_priv,
3177 		    dest_is_loop, fam);
3178 	}
3179 	SCTP_IPI_ADDR_RUNLOCK();
3180 	return (answer);
3181 }
3182 
3183 static int
3184 sctp_find_cmsg(int c_type, void *data, struct mbuf *control, int cpsize)
3185 {
3186 	struct cmsghdr cmh;
3187 	int tlen, at;
3188 
3189 	tlen = SCTP_BUF_LEN(control);
3190 	at = 0;
3191 	/*
3192 	 * Independent of how many mbufs, find the c_type inside the control
3193 	 * structure and copy out the data.
3194 	 */
3195 	while (at < tlen) {
3196 		if ((tlen - at) < (int)CMSG_ALIGN(sizeof(cmh))) {
3197 			/* not enough room for one more we are done. */
3198 			return (0);
3199 		}
3200 		m_copydata(control, at, sizeof(cmh), (caddr_t)&cmh);
3201 		if (((int)cmh.cmsg_len + at) > tlen) {
3202 			/*
3203 			 * this is real messed up since there is not enough
3204 			 * data here to cover the cmsg header. We are done.
3205 			 */
3206 			return (0);
3207 		}
3208 		if ((cmh.cmsg_level == IPPROTO_SCTP) &&
3209 		    (c_type == cmh.cmsg_type)) {
3210 			/* found the one we want, copy it out */
3211 			at += CMSG_ALIGN(sizeof(struct cmsghdr));
3212 			if ((int)(cmh.cmsg_len - CMSG_ALIGN(sizeof(struct cmsghdr))) < cpsize) {
3213 				/*
3214 				 * space of cmsg_len after header not big
3215 				 * enough
3216 				 */
3217 				return (0);
3218 			}
3219 			m_copydata(control, at, cpsize, data);
3220 			return (1);
3221 		} else {
3222 			at += CMSG_ALIGN(cmh.cmsg_len);
3223 			if (cmh.cmsg_len == 0) {
3224 				break;
3225 			}
3226 		}
3227 	}
3228 	/* not found */
3229 	return (0);
3230 }
3231 
3232 static struct mbuf *
3233 sctp_add_cookie(struct sctp_inpcb *inp, struct mbuf *init, int init_offset,
3234     struct mbuf *initack, int initack_offset, struct sctp_state_cookie *stc_in, uint8_t ** signature)
3235 {
3236 	struct mbuf *copy_init, *copy_initack, *m_at, *sig, *mret;
3237 	struct sctp_state_cookie *stc;
3238 	struct sctp_paramhdr *ph;
3239 	uint8_t *foo;
3240 	int sig_offset;
3241 	uint16_t cookie_sz;
3242 
3243 	mret = NULL;
3244 	mret = sctp_get_mbuf_for_msg((sizeof(struct sctp_state_cookie) +
3245 	    sizeof(struct sctp_paramhdr)), 0,
3246 	    M_DONTWAIT, 1, MT_DATA);
3247 	if (mret == NULL) {
3248 		return (NULL);
3249 	}
3250 	copy_init = SCTP_M_COPYM(init, init_offset, M_COPYALL, M_DONTWAIT);
3251 	if (copy_init == NULL) {
3252 		sctp_m_freem(mret);
3253 		return (NULL);
3254 	}
3255 #ifdef SCTP_MBUF_LOGGING
3256 	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
3257 		struct mbuf *mat;
3258 
3259 		mat = copy_init;
3260 		while (mat) {
3261 			if (SCTP_BUF_IS_EXTENDED(mat)) {
3262 				sctp_log_mb(mat, SCTP_MBUF_ICOPY);
3263 			}
3264 			mat = SCTP_BUF_NEXT(mat);
3265 		}
3266 	}
3267 #endif
3268 	copy_initack = SCTP_M_COPYM(initack, initack_offset, M_COPYALL,
3269 	    M_DONTWAIT);
3270 	if (copy_initack == NULL) {
3271 		sctp_m_freem(mret);
3272 		sctp_m_freem(copy_init);
3273 		return (NULL);
3274 	}
3275 #ifdef SCTP_MBUF_LOGGING
3276 	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
3277 		struct mbuf *mat;
3278 
3279 		mat = copy_initack;
3280 		while (mat) {
3281 			if (SCTP_BUF_IS_EXTENDED(mat)) {
3282 				sctp_log_mb(mat, SCTP_MBUF_ICOPY);
3283 			}
3284 			mat = SCTP_BUF_NEXT(mat);
3285 		}
3286 	}
3287 #endif
3288 	/* easy side we just drop it on the end */
3289 	ph = mtod(mret, struct sctp_paramhdr *);
3290 	SCTP_BUF_LEN(mret) = sizeof(struct sctp_state_cookie) +
3291 	    sizeof(struct sctp_paramhdr);
3292 	stc = (struct sctp_state_cookie *)((caddr_t)ph +
3293 	    sizeof(struct sctp_paramhdr));
3294 	ph->param_type = htons(SCTP_STATE_COOKIE);
3295 	ph->param_length = 0;	/* fill in at the end */
3296 	/* Fill in the stc cookie data */
3297 	memcpy(stc, stc_in, sizeof(struct sctp_state_cookie));
3298 
3299 	/* tack the INIT and then the INIT-ACK onto the chain */
3300 	cookie_sz = 0;
3301 	m_at = mret;
3302 	for (m_at = mret; m_at; m_at = SCTP_BUF_NEXT(m_at)) {
3303 		cookie_sz += SCTP_BUF_LEN(m_at);
3304 		if (SCTP_BUF_NEXT(m_at) == NULL) {
3305 			SCTP_BUF_NEXT(m_at) = copy_init;
3306 			break;
3307 		}
3308 	}
3309 
3310 	for (m_at = copy_init; m_at; m_at = SCTP_BUF_NEXT(m_at)) {
3311 		cookie_sz += SCTP_BUF_LEN(m_at);
3312 		if (SCTP_BUF_NEXT(m_at) == NULL) {
3313 			SCTP_BUF_NEXT(m_at) = copy_initack;
3314 			break;
3315 		}
3316 	}
3317 
3318 	for (m_at = copy_initack; m_at; m_at = SCTP_BUF_NEXT(m_at)) {
3319 		cookie_sz += SCTP_BUF_LEN(m_at);
3320 		if (SCTP_BUF_NEXT(m_at) == NULL) {
3321 			break;
3322 		}
3323 	}
3324 	sig = sctp_get_mbuf_for_msg(SCTP_SECRET_SIZE, 0, M_DONTWAIT, 1, MT_DATA);
3325 	if (sig == NULL) {
3326 		/* no space, so free the entire chain */
3327 		sctp_m_freem(mret);
3328 		return (NULL);
3329 	}
3330 	SCTP_BUF_LEN(sig) = 0;
3331 	SCTP_BUF_NEXT(m_at) = sig;
3332 	sig_offset = 0;
3333 	foo = (uint8_t *) (mtod(sig, caddr_t)+sig_offset);
3334 	memset(foo, 0, SCTP_SIGNATURE_SIZE);
3335 	*signature = foo;
3336 	SCTP_BUF_LEN(sig) += SCTP_SIGNATURE_SIZE;
3337 	cookie_sz += SCTP_SIGNATURE_SIZE;
3338 	ph->param_length = htons(cookie_sz);
3339 	return (mret);
3340 }
3341 
3342 
3343 static uint8_t
3344 sctp_get_ect(struct sctp_tcb *stcb,
3345     struct sctp_tmit_chunk *chk)
3346 {
3347 	uint8_t this_random;
3348 
3349 	/* Huh? */
3350 	if (SCTP_BASE_SYSCTL(sctp_ecn_enable) == 0)
3351 		return (0);
3352 
3353 	if (SCTP_BASE_SYSCTL(sctp_ecn_nonce) == 0)
3354 		/* no nonce, always return ECT0 */
3355 		return (SCTP_ECT0_BIT);
3356 
3357 	if (stcb->asoc.peer_supports_ecn_nonce == 0) {
3358 		/* Peer does NOT support it, so we send a ECT0 only */
3359 		return (SCTP_ECT0_BIT);
3360 	}
3361 	if (chk == NULL)
3362 		return (SCTP_ECT0_BIT);
3363 
3364 	if ((stcb->asoc.hb_random_idx > 3) ||
3365 	    ((stcb->asoc.hb_random_idx == 3) &&
3366 	    (stcb->asoc.hb_ect_randombit > 7))) {
3367 		uint32_t rndval;
3368 
3369 warp_drive_sa:
3370 		rndval = sctp_select_initial_TSN(&stcb->sctp_ep->sctp_ep);
3371 		memcpy(stcb->asoc.hb_random_values, &rndval,
3372 		    sizeof(stcb->asoc.hb_random_values));
3373 		this_random = stcb->asoc.hb_random_values[0];
3374 		stcb->asoc.hb_random_idx = 0;
3375 		stcb->asoc.hb_ect_randombit = 0;
3376 	} else {
3377 		if (stcb->asoc.hb_ect_randombit > 7) {
3378 			stcb->asoc.hb_ect_randombit = 0;
3379 			stcb->asoc.hb_random_idx++;
3380 			if (stcb->asoc.hb_random_idx > 3) {
3381 				goto warp_drive_sa;
3382 			}
3383 		}
3384 		this_random = stcb->asoc.hb_random_values[stcb->asoc.hb_random_idx];
3385 	}
3386 	if ((this_random >> stcb->asoc.hb_ect_randombit) & 0x01) {
3387 		if (chk != NULL)
3388 			/* ECN Nonce stuff */
3389 			chk->rec.data.ect_nonce = SCTP_ECT1_BIT;
3390 		stcb->asoc.hb_ect_randombit++;
3391 		return (SCTP_ECT1_BIT);
3392 	} else {
3393 		stcb->asoc.hb_ect_randombit++;
3394 		return (SCTP_ECT0_BIT);
3395 	}
3396 }
3397 
3398 static int
3399 sctp_lowlevel_chunk_output(struct sctp_inpcb *inp,
3400     struct sctp_tcb *stcb,	/* may be NULL */
3401     struct sctp_nets *net,
3402     struct sockaddr *to,
3403     struct mbuf *m,
3404     uint32_t auth_offset,
3405     struct sctp_auth_chunk *auth,
3406     uint16_t auth_keyid,
3407     int nofragment_flag,
3408     int ecn_ok,
3409     struct sctp_tmit_chunk *chk,
3410     int out_of_asoc_ok,
3411     uint16_t src_port,
3412     uint16_t dest_port,
3413     uint32_t v_tag,
3414     uint16_t port,
3415     int so_locked,
3416 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
3417     SCTP_UNUSED
3418 #endif
3419     union sctp_sockstore *over_addr
3420 )
3421 /* nofragment_flag to tell if IP_DF should be set (IPv4 only) */
3422 {
3423 	/*
3424 	 * Given a mbuf chain (via SCTP_BUF_NEXT()) that holds a packet
3425 	 * header WITH an SCTPHDR but no IP header, endpoint inp and sa
3426 	 * structure: - fill in the HMAC digest of any AUTH chunk in the
3427 	 * packet. - calculate and fill in the SCTP checksum. - prepend an
3428 	 * IP address header. - if boundall use INADDR_ANY. - if
3429 	 * boundspecific do source address selection. - set fragmentation
3430 	 * option for ipV4. - On return from IP output, check/adjust mtu
3431 	 * size of output interface and smallest_mtu size as well.
3432 	 */
3433 	/* Will need ifdefs around this */
3434 	struct mbuf *o_pak;
3435 	struct mbuf *newm;
3436 	struct sctphdr *sctphdr;
3437 	int packet_length;
3438 	int ret;
3439 	uint32_t vrf_id;
3440 	sctp_route_t *ro = NULL;
3441 	struct udphdr *udp = NULL;
3442 
3443 #if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
3444 	struct socket *so = NULL;
3445 
3446 #endif
3447 
3448 	if ((net) && (net->dest_state & SCTP_ADDR_OUT_OF_SCOPE)) {
3449 		SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EFAULT);
3450 		sctp_m_freem(m);
3451 		return (EFAULT);
3452 	}
3453 	if (stcb) {
3454 		vrf_id = stcb->asoc.vrf_id;
3455 	} else {
3456 		vrf_id = inp->def_vrf_id;
3457 	}
3458 
3459 	/* fill in the HMAC digest for any AUTH chunk in the packet */
3460 	if ((auth != NULL) && (stcb != NULL)) {
3461 		sctp_fill_hmac_digest_m(m, auth_offset, auth, stcb, auth_keyid);
3462 	}
3463 	if (to->sa_family == AF_INET) {
3464 		struct ip *ip = NULL;
3465 		sctp_route_t iproute;
3466 		uint8_t tos_value;
3467 		int len;
3468 
3469 		len = sizeof(struct ip) + sizeof(struct sctphdr);
3470 		if (port) {
3471 			len += sizeof(struct udphdr);
3472 		}
3473 		newm = sctp_get_mbuf_for_msg(len, 1, M_DONTWAIT, 1, MT_DATA);
3474 		if (newm == NULL) {
3475 			sctp_m_freem(m);
3476 			SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
3477 			return (ENOMEM);
3478 		}
3479 		SCTP_ALIGN_TO_END(newm, len);
3480 		SCTP_BUF_LEN(newm) = len;
3481 		SCTP_BUF_NEXT(newm) = m;
3482 		m = newm;
3483 		packet_length = sctp_calculate_len(m);
3484 		ip = mtod(m, struct ip *);
3485 		ip->ip_v = IPVERSION;
3486 		ip->ip_hl = (sizeof(struct ip) >> 2);
3487 		if (net) {
3488 			tos_value = net->tos_flowlabel & 0x000000ff;
3489 		} else {
3490 			tos_value = inp->ip_inp.inp.inp_ip_tos;
3491 		}
3492 		if ((nofragment_flag) && (port == 0)) {
3493 			ip->ip_off = IP_DF;
3494 		} else
3495 			ip->ip_off = 0;
3496 
3497 		/* FreeBSD has a function for ip_id's */
3498 		ip->ip_id = ip_newid();
3499 
3500 		ip->ip_ttl = inp->ip_inp.inp.inp_ip_ttl;
3501 		ip->ip_len = packet_length;
3502 		if (stcb) {
3503 			if ((stcb->asoc.ecn_allowed) && ecn_ok) {
3504 				/* Enable ECN */
3505 				ip->ip_tos = ((u_char)(tos_value & 0xfc) | sctp_get_ect(stcb, chk));
3506 			} else {
3507 				/* No ECN */
3508 				ip->ip_tos = (u_char)(tos_value & 0xfc);
3509 			}
3510 		} else {
3511 			/* no association at all */
3512 			ip->ip_tos = (tos_value & 0xfc);
3513 		}
3514 		if (port) {
3515 			ip->ip_p = IPPROTO_UDP;
3516 		} else {
3517 			ip->ip_p = IPPROTO_SCTP;
3518 		}
3519 		ip->ip_sum = 0;
3520 		if (net == NULL) {
3521 			ro = &iproute;
3522 			memset(&iproute, 0, sizeof(iproute));
3523 			memcpy(&ro->ro_dst, to, to->sa_len);
3524 		} else {
3525 			ro = (sctp_route_t *) & net->ro;
3526 		}
3527 		/* Now the address selection part */
3528 		ip->ip_dst.s_addr = ((struct sockaddr_in *)to)->sin_addr.s_addr;
3529 
3530 		/* call the routine to select the src address */
3531 		if (net && out_of_asoc_ok == 0) {
3532 			if (net->ro._s_addr && (net->ro._s_addr->localifa_flags & (SCTP_BEING_DELETED | SCTP_ADDR_IFA_UNUSEABLE))) {
3533 				sctp_free_ifa(net->ro._s_addr);
3534 				net->ro._s_addr = NULL;
3535 				net->src_addr_selected = 0;
3536 				if (ro->ro_rt) {
3537 					RTFREE(ro->ro_rt);
3538 					ro->ro_rt = NULL;
3539 				}
3540 			}
3541 			if (net->src_addr_selected == 0) {
3542 				/* Cache the source address */
3543 				net->ro._s_addr = sctp_source_address_selection(inp, stcb,
3544 				    ro, net, 0,
3545 				    vrf_id);
3546 				net->src_addr_selected = 1;
3547 			}
3548 			if (net->ro._s_addr == NULL) {
3549 				/* No route to host */
3550 				net->src_addr_selected = 0;
3551 				goto no_route;
3552 			}
3553 			ip->ip_src = net->ro._s_addr->address.sin.sin_addr;
3554 		} else {
3555 			if (over_addr == NULL) {
3556 				struct sctp_ifa *_lsrc;
3557 
3558 				_lsrc = sctp_source_address_selection(inp, stcb, ro,
3559 				    net,
3560 				    out_of_asoc_ok,
3561 				    vrf_id);
3562 				if (_lsrc == NULL) {
3563 					goto no_route;
3564 				}
3565 				ip->ip_src = _lsrc->address.sin.sin_addr;
3566 				sctp_free_ifa(_lsrc);
3567 			} else {
3568 				ip->ip_src = over_addr->sin.sin_addr;
3569 				SCTP_RTALLOC(ro, vrf_id);
3570 			}
3571 		}
3572 		if (port) {
3573 			udp = (struct udphdr *)((caddr_t)ip + sizeof(struct ip));
3574 			udp->uh_sport = htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port));
3575 			udp->uh_dport = port;
3576 			udp->uh_ulen = htons(packet_length - sizeof(struct ip));
3577 			udp->uh_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr, udp->uh_ulen + htons(IPPROTO_UDP));
3578 			sctphdr = (struct sctphdr *)((caddr_t)udp + sizeof(struct udphdr));
3579 		} else {
3580 			sctphdr = (struct sctphdr *)((caddr_t)ip + sizeof(struct ip));
3581 		}
3582 
3583 		sctphdr->src_port = src_port;
3584 		sctphdr->dest_port = dest_port;
3585 		sctphdr->v_tag = v_tag;
3586 		sctphdr->checksum = 0;
3587 
3588 		/*
3589 		 * If source address selection fails and we find no route
3590 		 * then the ip_output should fail as well with a
3591 		 * NO_ROUTE_TO_HOST type error. We probably should catch
3592 		 * that somewhere and abort the association right away
3593 		 * (assuming this is an INIT being sent).
3594 		 */
3595 		if ((ro->ro_rt == NULL)) {
3596 			/*
3597 			 * src addr selection failed to find a route (or
3598 			 * valid source addr), so we can't get there from
3599 			 * here (yet)!
3600 			 */
3601 	no_route:
3602 			SCTPDBG(SCTP_DEBUG_OUTPUT1,
3603 			    "%s: dropped packet - no valid source addr\n",
3604 			    __FUNCTION__);
3605 			if (net) {
3606 				SCTPDBG(SCTP_DEBUG_OUTPUT1,
3607 				    "Destination was ");
3608 				SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT1,
3609 				    &net->ro._l_addr.sa);
3610 				if (net->dest_state & SCTP_ADDR_CONFIRMED) {
3611 					if ((net->dest_state & SCTP_ADDR_REACHABLE) && stcb) {
3612 						SCTPDBG(SCTP_DEBUG_OUTPUT1, "no route takes interface %p down\n", net);
3613 						sctp_ulp_notify(SCTP_NOTIFY_INTERFACE_DOWN,
3614 						    stcb,
3615 						    SCTP_FAILED_THRESHOLD,
3616 						    (void *)net,
3617 						    so_locked);
3618 						net->dest_state &= ~SCTP_ADDR_REACHABLE;
3619 						net->dest_state |= SCTP_ADDR_NOT_REACHABLE;
3620 						/*
3621 						 * JRS 5/14/07 - If a
3622 						 * destination is
3623 						 * unreachable, the PF bit
3624 						 * is turned off.  This
3625 						 * allows an unambiguous use
3626 						 * of the PF bit for
3627 						 * destinations that are
3628 						 * reachable but potentially
3629 						 * failed. If the
3630 						 * destination is set to the
3631 						 * unreachable state, also
3632 						 * set the destination to
3633 						 * the PF state.
3634 						 */
3635 						/*
3636 						 * Add debug message here if
3637 						 * destination is not in PF
3638 						 * state.
3639 						 */
3640 						/*
3641 						 * Stop any running T3
3642 						 * timers here?
3643 						 */
3644 						if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && SCTP_BASE_SYSCTL(sctp_cmt_pf)) {
3645 							net->dest_state &= ~SCTP_ADDR_PF;
3646 							SCTPDBG(SCTP_DEBUG_OUTPUT1, "Destination %p moved from PF to unreachable.\n",
3647 							    net);
3648 						}
3649 					}
3650 				}
3651 				if (stcb) {
3652 					if (net == stcb->asoc.primary_destination) {
3653 						/* need a new primary */
3654 						struct sctp_nets *alt;
3655 
3656 						alt = sctp_find_alternate_net(stcb, net, 0);
3657 						if (alt != net) {
3658 							if (sctp_set_primary_addr(stcb,
3659 							    (struct sockaddr *)NULL,
3660 							    alt) == 0) {
3661 								net->dest_state |= SCTP_ADDR_WAS_PRIMARY;
3662 								if (net->ro._s_addr) {
3663 									sctp_free_ifa(net->ro._s_addr);
3664 									net->ro._s_addr = NULL;
3665 								}
3666 								net->src_addr_selected = 0;
3667 							}
3668 						}
3669 					}
3670 				}
3671 			}
3672 			SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EHOSTUNREACH);
3673 			sctp_m_freem(m);
3674 			return (EHOSTUNREACH);
3675 		}
3676 		if (ro != &iproute) {
3677 			memcpy(&iproute, ro, sizeof(*ro));
3678 		}
3679 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "Calling ipv4 output routine from low level src addr:%x\n",
3680 		    (uint32_t) (ntohl(ip->ip_src.s_addr)));
3681 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "Destination is %x\n",
3682 		    (uint32_t) (ntohl(ip->ip_dst.s_addr)));
3683 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "RTP route is %p through\n",
3684 		    ro->ro_rt);
3685 
3686 		if (SCTP_GET_HEADER_FOR_OUTPUT(o_pak)) {
3687 			/* failed to prepend data, give up */
3688 			SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
3689 			sctp_m_freem(m);
3690 			return (ENOMEM);
3691 		}
3692 #ifdef  SCTP_PACKET_LOGGING
3693 		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LAST_PACKET_TRACING)
3694 			sctp_packet_log(m, packet_length);
3695 #endif
3696 		SCTP_ATTACH_CHAIN(o_pak, m, packet_length);
3697 		if (port) {
3698 			if (!(SCTP_BASE_SYSCTL(sctp_no_csum_on_loopback) &&
3699 			    (stcb) &&
3700 			    (stcb->asoc.loopback_scope))) {
3701 				sctphdr->checksum = sctp_calculate_cksum(m, sizeof(struct ip) + sizeof(struct udphdr));
3702 				SCTP_STAT_INCR(sctps_sendswcrc);
3703 			} else {
3704 				SCTP_STAT_INCR(sctps_sendnocrc);
3705 			}
3706 			SCTP_ENABLE_UDP_CSUM(o_pak);
3707 		} else {
3708 			if (!(SCTP_BASE_SYSCTL(sctp_no_csum_on_loopback) &&
3709 			    (stcb) &&
3710 			    (stcb->asoc.loopback_scope))) {
3711 				m->m_pkthdr.csum_flags = CSUM_SCTP;
3712 				m->m_pkthdr.csum_data = 0;	/* FIXME MT */
3713 				SCTP_STAT_INCR(sctps_sendhwcrc);
3714 			} else {
3715 				SCTP_STAT_INCR(sctps_sendnocrc);
3716 			}
3717 		}
3718 		/* send it out.  table id is taken from stcb */
3719 #if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
3720 		if ((SCTP_BASE_SYSCTL(sctp_output_unlocked)) && (so_locked)) {
3721 			so = SCTP_INP_SO(inp);
3722 			SCTP_SOCKET_UNLOCK(so, 0);
3723 		}
3724 #endif
3725 		SCTP_IP_OUTPUT(ret, o_pak, ro, stcb, vrf_id);
3726 #if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
3727 		if ((SCTP_BASE_SYSCTL(sctp_output_unlocked)) && (so_locked)) {
3728 			atomic_add_int(&stcb->asoc.refcnt, 1);
3729 			SCTP_TCB_UNLOCK(stcb);
3730 			SCTP_SOCKET_LOCK(so, 0);
3731 			SCTP_TCB_LOCK(stcb);
3732 			atomic_subtract_int(&stcb->asoc.refcnt, 1);
3733 		}
3734 #endif
3735 		SCTP_STAT_INCR(sctps_sendpackets);
3736 		SCTP_STAT_INCR_COUNTER64(sctps_outpackets);
3737 		if (ret)
3738 			SCTP_STAT_INCR(sctps_senderrors);
3739 
3740 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "IP output returns %d\n", ret);
3741 		if (net == NULL) {
3742 			/* free tempy routes */
3743 			if (ro->ro_rt) {
3744 				RTFREE(ro->ro_rt);
3745 				ro->ro_rt = NULL;
3746 			}
3747 		} else {
3748 			/* PMTU check versus smallest asoc MTU goes here */
3749 			if ((ro->ro_rt != NULL) &&
3750 			    (net->ro._s_addr)) {
3751 				uint32_t mtu;
3752 
3753 				mtu = SCTP_GATHER_MTU_FROM_ROUTE(net->ro._s_addr, &net->ro._l_addr.sa, ro->ro_rt);
3754 				if (net->port) {
3755 					mtu -= sizeof(struct udphdr);
3756 				}
3757 				if (mtu && (stcb->asoc.smallest_mtu > mtu)) {
3758 #ifdef SCTP_PRINT_FOR_B_AND_M
3759 					SCTP_PRINTF("sctp_mtu_size_reset called after ip_output mtu-change:%d\n", mtu);
3760 #endif
3761 					sctp_mtu_size_reset(inp, &stcb->asoc, mtu);
3762 					net->mtu = mtu;
3763 				}
3764 			} else if (ro->ro_rt == NULL) {
3765 				/* route was freed */
3766 				if (net->ro._s_addr &&
3767 				    net->src_addr_selected) {
3768 					sctp_free_ifa(net->ro._s_addr);
3769 					net->ro._s_addr = NULL;
3770 				}
3771 				net->src_addr_selected = 0;
3772 			}
3773 		}
3774 		return (ret);
3775 	}
3776 #ifdef INET6
3777 	else if (to->sa_family == AF_INET6) {
3778 		uint32_t flowlabel;
3779 		struct ip6_hdr *ip6h;
3780 		struct route_in6 ip6route;
3781 		struct ifnet *ifp;
3782 		u_char flowTop;
3783 		uint16_t flowBottom;
3784 		u_char tosBottom, tosTop;
3785 		struct sockaddr_in6 *sin6, tmp, *lsa6, lsa6_tmp;
3786 		int prev_scope = 0;
3787 		struct sockaddr_in6 lsa6_storage;
3788 		int error;
3789 		u_short prev_port = 0;
3790 		int len;
3791 
3792 		if (net != NULL) {
3793 			flowlabel = net->tos_flowlabel;
3794 		} else {
3795 			flowlabel = ((struct in6pcb *)inp)->in6p_flowinfo;
3796 		}
3797 
3798 		len = sizeof(struct ip6_hdr) + sizeof(struct sctphdr);
3799 		if (port) {
3800 			len += sizeof(struct udphdr);
3801 		}
3802 		newm = sctp_get_mbuf_for_msg(len, 1, M_DONTWAIT, 1, MT_DATA);
3803 		if (newm == NULL) {
3804 			sctp_m_freem(m);
3805 			SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
3806 			return (ENOMEM);
3807 		}
3808 		SCTP_ALIGN_TO_END(newm, len);
3809 		SCTP_BUF_LEN(newm) = len;
3810 		SCTP_BUF_NEXT(newm) = m;
3811 		m = newm;
3812 		packet_length = sctp_calculate_len(m);
3813 
3814 		ip6h = mtod(m, struct ip6_hdr *);
3815 		/*
3816 		 * We assume here that inp_flow is in host byte order within
3817 		 * the TCB!
3818 		 */
3819 		flowBottom = flowlabel & 0x0000ffff;
3820 		flowTop = ((flowlabel & 0x000f0000) >> 16);
3821 		tosTop = (((flowlabel & 0xf0) >> 4) | IPV6_VERSION);
3822 		/* protect *sin6 from overwrite */
3823 		sin6 = (struct sockaddr_in6 *)to;
3824 		tmp = *sin6;
3825 		sin6 = &tmp;
3826 
3827 		/* KAME hack: embed scopeid */
3828 		if (sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
3829 			SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
3830 			return (EINVAL);
3831 		}
3832 		if (net == NULL) {
3833 			memset(&ip6route, 0, sizeof(ip6route));
3834 			ro = (sctp_route_t *) & ip6route;
3835 			memcpy(&ro->ro_dst, sin6, sin6->sin6_len);
3836 		} else {
3837 			ro = (sctp_route_t *) & net->ro;
3838 		}
3839 		if (stcb != NULL) {
3840 			if ((stcb->asoc.ecn_allowed) && ecn_ok) {
3841 				/* Enable ECN */
3842 				tosBottom = (((((struct in6pcb *)inp)->in6p_flowinfo & 0x0c) | sctp_get_ect(stcb, chk)) << 4);
3843 			} else {
3844 				/* No ECN */
3845 				tosBottom = ((((struct in6pcb *)inp)->in6p_flowinfo & 0x0c) << 4);
3846 			}
3847 		} else {
3848 			/* we could get no asoc if it is a O-O-T-B packet */
3849 			tosBottom = ((((struct in6pcb *)inp)->in6p_flowinfo & 0x0c) << 4);
3850 		}
3851 		ip6h->ip6_flow = htonl(((tosTop << 24) | ((tosBottom | flowTop) << 16) | flowBottom));
3852 		if (port) {
3853 			ip6h->ip6_nxt = IPPROTO_UDP;
3854 		} else {
3855 			ip6h->ip6_nxt = IPPROTO_SCTP;
3856 		}
3857 		ip6h->ip6_plen = (packet_length - sizeof(struct ip6_hdr));
3858 		ip6h->ip6_dst = sin6->sin6_addr;
3859 
3860 		/*
3861 		 * Add SRC address selection here: we can only reuse to a
3862 		 * limited degree the kame src-addr-sel, since we can try
3863 		 * their selection but it may not be bound.
3864 		 */
3865 		bzero(&lsa6_tmp, sizeof(lsa6_tmp));
3866 		lsa6_tmp.sin6_family = AF_INET6;
3867 		lsa6_tmp.sin6_len = sizeof(lsa6_tmp);
3868 		lsa6 = &lsa6_tmp;
3869 		if (net && out_of_asoc_ok == 0) {
3870 			if (net->ro._s_addr && (net->ro._s_addr->localifa_flags & (SCTP_BEING_DELETED | SCTP_ADDR_IFA_UNUSEABLE))) {
3871 				sctp_free_ifa(net->ro._s_addr);
3872 				net->ro._s_addr = NULL;
3873 				net->src_addr_selected = 0;
3874 				if (ro->ro_rt) {
3875 					RTFREE(ro->ro_rt);
3876 					ro->ro_rt = NULL;
3877 				}
3878 			}
3879 			if (net->src_addr_selected == 0) {
3880 				sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
3881 				/* KAME hack: embed scopeid */
3882 				if (sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
3883 					SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
3884 					return (EINVAL);
3885 				}
3886 				/* Cache the source address */
3887 				net->ro._s_addr = sctp_source_address_selection(inp,
3888 				    stcb,
3889 				    ro,
3890 				    net,
3891 				    0,
3892 				    vrf_id);
3893 				(void)sa6_recoverscope(sin6);
3894 				net->src_addr_selected = 1;
3895 			}
3896 			if (net->ro._s_addr == NULL) {
3897 				SCTPDBG(SCTP_DEBUG_OUTPUT3, "V6:No route to host\n");
3898 				net->src_addr_selected = 0;
3899 				goto no_route;
3900 			}
3901 			lsa6->sin6_addr = net->ro._s_addr->address.sin6.sin6_addr;
3902 		} else {
3903 			sin6 = (struct sockaddr_in6 *)&ro->ro_dst;
3904 			/* KAME hack: embed scopeid */
3905 			if (sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone)) != 0) {
3906 				SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
3907 				return (EINVAL);
3908 			}
3909 			if (over_addr == NULL) {
3910 				struct sctp_ifa *_lsrc;
3911 
3912 				_lsrc = sctp_source_address_selection(inp, stcb, ro,
3913 				    net,
3914 				    out_of_asoc_ok,
3915 				    vrf_id);
3916 				if (_lsrc == NULL) {
3917 					goto no_route;
3918 				}
3919 				lsa6->sin6_addr = _lsrc->address.sin6.sin6_addr;
3920 				sctp_free_ifa(_lsrc);
3921 			} else {
3922 				lsa6->sin6_addr = over_addr->sin6.sin6_addr;
3923 				SCTP_RTALLOC(ro, vrf_id);
3924 			}
3925 			(void)sa6_recoverscope(sin6);
3926 		}
3927 		lsa6->sin6_port = inp->sctp_lport;
3928 
3929 		if (ro->ro_rt == NULL) {
3930 			/*
3931 			 * src addr selection failed to find a route (or
3932 			 * valid source addr), so we can't get there from
3933 			 * here!
3934 			 */
3935 			goto no_route;
3936 		}
3937 		/*
3938 		 * XXX: sa6 may not have a valid sin6_scope_id in the
3939 		 * non-SCOPEDROUTING case.
3940 		 */
3941 		bzero(&lsa6_storage, sizeof(lsa6_storage));
3942 		lsa6_storage.sin6_family = AF_INET6;
3943 		lsa6_storage.sin6_len = sizeof(lsa6_storage);
3944 		lsa6_storage.sin6_addr = lsa6->sin6_addr;
3945 		if ((error = sa6_recoverscope(&lsa6_storage)) != 0) {
3946 			SCTPDBG(SCTP_DEBUG_OUTPUT3, "recover scope fails error %d\n", error);
3947 			sctp_m_freem(m);
3948 			return (error);
3949 		}
3950 		/* XXX */
3951 		lsa6_storage.sin6_addr = lsa6->sin6_addr;
3952 		lsa6_storage.sin6_port = inp->sctp_lport;
3953 		lsa6 = &lsa6_storage;
3954 		ip6h->ip6_src = lsa6->sin6_addr;
3955 
3956 		if (port) {
3957 			udp = (struct udphdr *)((caddr_t)ip6h + sizeof(struct ip6_hdr));
3958 			udp->uh_sport = htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port));
3959 			udp->uh_dport = port;
3960 			udp->uh_ulen = htons(packet_length - sizeof(struct ip6_hdr));
3961 			udp->uh_sum = 0;
3962 			sctphdr = (struct sctphdr *)((caddr_t)udp + sizeof(struct udphdr));
3963 		} else {
3964 			sctphdr = (struct sctphdr *)((caddr_t)ip6h + sizeof(struct ip6_hdr));
3965 		}
3966 
3967 		sctphdr->src_port = src_port;
3968 		sctphdr->dest_port = dest_port;
3969 		sctphdr->v_tag = v_tag;
3970 		sctphdr->checksum = 0;
3971 
3972 		/*
3973 		 * We set the hop limit now since there is a good chance
3974 		 * that our ro pointer is now filled
3975 		 */
3976 		ip6h->ip6_hlim = SCTP_GET_HLIM(inp, ro);
3977 		ifp = SCTP_GET_IFN_VOID_FROM_ROUTE(ro);
3978 
3979 #ifdef SCTP_DEBUG
3980 		/* Copy to be sure something bad is not happening */
3981 		sin6->sin6_addr = ip6h->ip6_dst;
3982 		lsa6->sin6_addr = ip6h->ip6_src;
3983 #endif
3984 
3985 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "Calling ipv6 output routine from low level\n");
3986 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "src: ");
3987 		SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT3, (struct sockaddr *)lsa6);
3988 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "dst: ");
3989 		SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT3, (struct sockaddr *)sin6);
3990 		if (net) {
3991 			sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
3992 			/* preserve the port and scope for link local send */
3993 			prev_scope = sin6->sin6_scope_id;
3994 			prev_port = sin6->sin6_port;
3995 		}
3996 		if (SCTP_GET_HEADER_FOR_OUTPUT(o_pak)) {
3997 			/* failed to prepend data, give up */
3998 			sctp_m_freem(m);
3999 			SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
4000 			return (ENOMEM);
4001 		}
4002 #ifdef  SCTP_PACKET_LOGGING
4003 		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LAST_PACKET_TRACING)
4004 			sctp_packet_log(m, packet_length);
4005 #endif
4006 		SCTP_ATTACH_CHAIN(o_pak, m, packet_length);
4007 		if (port) {
4008 			if (!(SCTP_BASE_SYSCTL(sctp_no_csum_on_loopback) &&
4009 			    (stcb) &&
4010 			    (stcb->asoc.loopback_scope))) {
4011 				sctphdr->checksum = sctp_calculate_cksum(m, sizeof(struct ip6_hdr) + sizeof(struct udphdr));
4012 				SCTP_STAT_INCR(sctps_sendswcrc);
4013 			} else {
4014 				SCTP_STAT_INCR(sctps_sendnocrc);
4015 			}
4016 			if ((udp->uh_sum = in6_cksum(o_pak, IPPROTO_UDP, sizeof(struct ip6_hdr), packet_length - sizeof(struct ip6_hdr))) == 0) {
4017 				udp->uh_sum = 0xffff;
4018 			}
4019 		} else {
4020 			if (!(SCTP_BASE_SYSCTL(sctp_no_csum_on_loopback) &&
4021 			    (stcb) &&
4022 			    (stcb->asoc.loopback_scope))) {
4023 				m->m_pkthdr.csum_flags = CSUM_SCTP;
4024 				m->m_pkthdr.csum_data = 0;	/* FIXME MT */
4025 				SCTP_STAT_INCR(sctps_sendhwcrc);
4026 			} else {
4027 				SCTP_STAT_INCR(sctps_sendnocrc);
4028 			}
4029 		}
4030 		/* send it out. table id is taken from stcb */
4031 #if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4032 		if ((SCTP_BASE_SYSCTL(sctp_output_unlocked)) && (so_locked)) {
4033 			so = SCTP_INP_SO(inp);
4034 			SCTP_SOCKET_UNLOCK(so, 0);
4035 		}
4036 #endif
4037 		SCTP_IP6_OUTPUT(ret, o_pak, (struct route_in6 *)ro, &ifp, stcb, vrf_id);
4038 #if defined (__APPLE__) || defined(SCTP_SO_LOCK_TESTING)
4039 		if ((SCTP_BASE_SYSCTL(sctp_output_unlocked)) && (so_locked)) {
4040 			atomic_add_int(&stcb->asoc.refcnt, 1);
4041 			SCTP_TCB_UNLOCK(stcb);
4042 			SCTP_SOCKET_LOCK(so, 0);
4043 			SCTP_TCB_LOCK(stcb);
4044 			atomic_subtract_int(&stcb->asoc.refcnt, 1);
4045 		}
4046 #endif
4047 		if (net) {
4048 			/* for link local this must be done */
4049 			sin6->sin6_scope_id = prev_scope;
4050 			sin6->sin6_port = prev_port;
4051 		}
4052 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "return from send is %d\n", ret);
4053 		SCTP_STAT_INCR(sctps_sendpackets);
4054 		SCTP_STAT_INCR_COUNTER64(sctps_outpackets);
4055 		if (ret) {
4056 			SCTP_STAT_INCR(sctps_senderrors);
4057 		}
4058 		if (net == NULL) {
4059 			/* Now if we had a temp route free it */
4060 			if (ro->ro_rt) {
4061 				RTFREE(ro->ro_rt);
4062 			}
4063 		} else {
4064 			/* PMTU check versus smallest asoc MTU goes here */
4065 			if (ro->ro_rt == NULL) {
4066 				/* Route was freed */
4067 				if (net->ro._s_addr &&
4068 				    net->src_addr_selected) {
4069 					sctp_free_ifa(net->ro._s_addr);
4070 					net->ro._s_addr = NULL;
4071 				}
4072 				net->src_addr_selected = 0;
4073 			}
4074 			if ((ro->ro_rt != NULL) &&
4075 			    (net->ro._s_addr)) {
4076 				uint32_t mtu;
4077 
4078 				mtu = SCTP_GATHER_MTU_FROM_ROUTE(net->ro._s_addr, &net->ro._l_addr.sa, ro->ro_rt);
4079 				if (mtu &&
4080 				    (stcb->asoc.smallest_mtu > mtu)) {
4081 #ifdef SCTP_PRINT_FOR_B_AND_M
4082 					SCTP_PRINTF("sctp_mtu_size_reset called after ip6_output mtu-change:%d\n",
4083 					    mtu);
4084 #endif
4085 					sctp_mtu_size_reset(inp, &stcb->asoc, mtu);
4086 					net->mtu = mtu;
4087 					if (net->port) {
4088 						net->mtu -= sizeof(struct udphdr);
4089 					}
4090 				}
4091 			} else if (ifp) {
4092 				if (ND_IFINFO(ifp)->linkmtu &&
4093 				    (stcb->asoc.smallest_mtu > ND_IFINFO(ifp)->linkmtu)) {
4094 #ifdef SCTP_PRINT_FOR_B_AND_M
4095 					SCTP_PRINTF("sctp_mtu_size_reset called via ifp ND_IFINFO() linkmtu:%d\n",
4096 					    ND_IFINFO(ifp)->linkmtu);
4097 #endif
4098 					sctp_mtu_size_reset(inp,
4099 					    &stcb->asoc,
4100 					    ND_IFINFO(ifp)->linkmtu);
4101 				}
4102 			}
4103 		}
4104 		return (ret);
4105 	}
4106 #endif
4107 	else {
4108 		SCTPDBG(SCTP_DEBUG_OUTPUT1, "Unknown protocol (TSNH) type %d\n",
4109 		    ((struct sockaddr *)to)->sa_family);
4110 		sctp_m_freem(m);
4111 		SCTP_LTRACE_ERR_RET_PKT(m, inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EFAULT);
4112 		return (EFAULT);
4113 	}
4114 }
4115 
4116 
4117 void
4118 sctp_send_initiate(struct sctp_inpcb *inp, struct sctp_tcb *stcb, int so_locked
4119 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
4120     SCTP_UNUSED
4121 #endif
4122 )
4123 {
4124 	struct mbuf *m, *m_at, *mp_last;
4125 	struct sctp_nets *net;
4126 	struct sctp_init_chunk *init;
4127 	struct sctp_supported_addr_param *sup_addr;
4128 	struct sctp_adaptation_layer_indication *ali;
4129 	struct sctp_ecn_supported_param *ecn;
4130 	struct sctp_prsctp_supported_param *prsctp;
4131 	struct sctp_ecn_nonce_supported_param *ecn_nonce;
4132 	struct sctp_supported_chunk_types_param *pr_supported;
4133 	int cnt_inits_to = 0;
4134 	int padval, ret;
4135 	int num_ext;
4136 	int p_len;
4137 
4138 	/* INIT's always go to the primary (and usually ONLY address) */
4139 	mp_last = NULL;
4140 	net = stcb->asoc.primary_destination;
4141 	if (net == NULL) {
4142 		net = TAILQ_FIRST(&stcb->asoc.nets);
4143 		if (net == NULL) {
4144 			/* TSNH */
4145 			return;
4146 		}
4147 		/* we confirm any address we send an INIT to */
4148 		net->dest_state &= ~SCTP_ADDR_UNCONFIRMED;
4149 		(void)sctp_set_primary_addr(stcb, NULL, net);
4150 	} else {
4151 		/* we confirm any address we send an INIT to */
4152 		net->dest_state &= ~SCTP_ADDR_UNCONFIRMED;
4153 	}
4154 	SCTPDBG(SCTP_DEBUG_OUTPUT4, "Sending INIT\n");
4155 #ifdef INET6
4156 	if (((struct sockaddr *)&(net->ro._l_addr))->sa_family == AF_INET6) {
4157 		/*
4158 		 * special hook, if we are sending to link local it will not
4159 		 * show up in our private address count.
4160 		 */
4161 		struct sockaddr_in6 *sin6l;
4162 
4163 		sin6l = &net->ro._l_addr.sin6;
4164 		if (IN6_IS_ADDR_LINKLOCAL(&sin6l->sin6_addr))
4165 			cnt_inits_to = 1;
4166 	}
4167 #endif
4168 	if (SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer)) {
4169 		/* This case should not happen */
4170 		SCTPDBG(SCTP_DEBUG_OUTPUT4, "Sending INIT - failed timer?\n");
4171 		return;
4172 	}
4173 	/* start the INIT timer */
4174 	sctp_timer_start(SCTP_TIMER_TYPE_INIT, inp, stcb, net);
4175 
4176 	m = sctp_get_mbuf_for_msg(MCLBYTES, 1, M_DONTWAIT, 1, MT_DATA);
4177 	if (m == NULL) {
4178 		/* No memory, INIT timer will re-attempt. */
4179 		SCTPDBG(SCTP_DEBUG_OUTPUT4, "Sending INIT - mbuf?\n");
4180 		return;
4181 	}
4182 	SCTP_BUF_LEN(m) = sizeof(struct sctp_init_chunk);
4183 	/*
4184 	 * assume peer supports asconf in order to be able to queue local
4185 	 * address changes while an INIT is in flight and before the assoc
4186 	 * is established.
4187 	 */
4188 	stcb->asoc.peer_supports_asconf = 1;
4189 	/* Now lets put the SCTP header in place */
4190 	init = mtod(m, struct sctp_init_chunk *);
4191 	/* now the chunk header */
4192 	init->ch.chunk_type = SCTP_INITIATION;
4193 	init->ch.chunk_flags = 0;
4194 	/* fill in later from mbuf we build */
4195 	init->ch.chunk_length = 0;
4196 	/* place in my tag */
4197 	init->init.initiate_tag = htonl(stcb->asoc.my_vtag);
4198 	/* set up some of the credits. */
4199 	init->init.a_rwnd = htonl(max(inp->sctp_socket ? SCTP_SB_LIMIT_RCV(inp->sctp_socket) : 0,
4200 	    SCTP_MINIMAL_RWND));
4201 
4202 	init->init.num_outbound_streams = htons(stcb->asoc.pre_open_streams);
4203 	init->init.num_inbound_streams = htons(stcb->asoc.max_inbound_streams);
4204 	init->init.initial_tsn = htonl(stcb->asoc.init_seq_number);
4205 	/* now the address restriction */
4206 	sup_addr = (struct sctp_supported_addr_param *)((caddr_t)init +
4207 	    sizeof(*init));
4208 	sup_addr->ph.param_type = htons(SCTP_SUPPORTED_ADDRTYPE);
4209 #ifdef INET6
4210 	/* we support 2 types: IPv6/IPv4 */
4211 	sup_addr->ph.param_length = htons(sizeof(*sup_addr) + sizeof(uint16_t));
4212 	sup_addr->addr_type[0] = htons(SCTP_IPV4_ADDRESS);
4213 	sup_addr->addr_type[1] = htons(SCTP_IPV6_ADDRESS);
4214 #else
4215 	/* we support 1 type: IPv4 */
4216 	sup_addr->ph.param_length = htons(sizeof(*sup_addr) + sizeof(uint8_t));
4217 	sup_addr->addr_type[0] = htons(SCTP_IPV4_ADDRESS);
4218 	sup_addr->addr_type[1] = htons(0);	/* this is the padding */
4219 #endif
4220 	SCTP_BUF_LEN(m) += sizeof(*sup_addr) + sizeof(uint16_t);
4221 	/* adaptation layer indication parameter */
4222 	ali = (struct sctp_adaptation_layer_indication *)((caddr_t)sup_addr + sizeof(*sup_addr) + sizeof(uint16_t));
4223 	ali->ph.param_type = htons(SCTP_ULP_ADAPTATION);
4224 	ali->ph.param_length = htons(sizeof(*ali));
4225 	ali->indication = ntohl(inp->sctp_ep.adaptation_layer_indicator);
4226 	SCTP_BUF_LEN(m) += sizeof(*ali);
4227 	ecn = (struct sctp_ecn_supported_param *)((caddr_t)ali + sizeof(*ali));
4228 
4229 	if (SCTP_BASE_SYSCTL(sctp_inits_include_nat_friendly)) {
4230 		/* Add NAT friendly parameter */
4231 		struct sctp_paramhdr *ph;
4232 
4233 		ph = (struct sctp_paramhdr *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
4234 		ph->param_type = htons(SCTP_HAS_NAT_SUPPORT);
4235 		ph->param_length = htons(sizeof(struct sctp_paramhdr));
4236 		SCTP_BUF_LEN(m) += sizeof(struct sctp_paramhdr);
4237 		ecn = (struct sctp_ecn_supported_param *)((caddr_t)ph + sizeof(*ph));
4238 	}
4239 	/* now any cookie time extensions */
4240 	if (stcb->asoc.cookie_preserve_req) {
4241 		struct sctp_cookie_perserve_param *cookie_preserve;
4242 
4243 		cookie_preserve = (struct sctp_cookie_perserve_param *)(ecn);
4244 		cookie_preserve->ph.param_type = htons(SCTP_COOKIE_PRESERVE);
4245 		cookie_preserve->ph.param_length = htons(
4246 		    sizeof(*cookie_preserve));
4247 		cookie_preserve->time = htonl(stcb->asoc.cookie_preserve_req);
4248 		SCTP_BUF_LEN(m) += sizeof(*cookie_preserve);
4249 		ecn = (struct sctp_ecn_supported_param *)(
4250 		    (caddr_t)cookie_preserve + sizeof(*cookie_preserve));
4251 		stcb->asoc.cookie_preserve_req = 0;
4252 	}
4253 	/* ECN parameter */
4254 	if (SCTP_BASE_SYSCTL(sctp_ecn_enable) == 1) {
4255 		ecn->ph.param_type = htons(SCTP_ECN_CAPABLE);
4256 		ecn->ph.param_length = htons(sizeof(*ecn));
4257 		SCTP_BUF_LEN(m) += sizeof(*ecn);
4258 		prsctp = (struct sctp_prsctp_supported_param *)((caddr_t)ecn +
4259 		    sizeof(*ecn));
4260 	} else {
4261 		prsctp = (struct sctp_prsctp_supported_param *)((caddr_t)ecn);
4262 	}
4263 	/* And now tell the peer we do pr-sctp */
4264 	prsctp->ph.param_type = htons(SCTP_PRSCTP_SUPPORTED);
4265 	prsctp->ph.param_length = htons(sizeof(*prsctp));
4266 	SCTP_BUF_LEN(m) += sizeof(*prsctp);
4267 
4268 	/* And now tell the peer we do all the extensions */
4269 	pr_supported = (struct sctp_supported_chunk_types_param *)
4270 	    ((caddr_t)prsctp + sizeof(*prsctp));
4271 	pr_supported->ph.param_type = htons(SCTP_SUPPORTED_CHUNK_EXT);
4272 	num_ext = 0;
4273 	pr_supported->chunk_types[num_ext++] = SCTP_ASCONF;
4274 	pr_supported->chunk_types[num_ext++] = SCTP_ASCONF_ACK;
4275 	pr_supported->chunk_types[num_ext++] = SCTP_FORWARD_CUM_TSN;
4276 	pr_supported->chunk_types[num_ext++] = SCTP_PACKET_DROPPED;
4277 	pr_supported->chunk_types[num_ext++] = SCTP_STREAM_RESET;
4278 	if (!SCTP_BASE_SYSCTL(sctp_auth_disable)) {
4279 		pr_supported->chunk_types[num_ext++] = SCTP_AUTHENTICATION;
4280 	}
4281 	/*
4282 	 * EY  if the initiator supports nr_sacks, need to report that to
4283 	 * responder in INIT chunk
4284 	 */
4285 	if (SCTP_BASE_SYSCTL(sctp_nr_sack_on_off)) {
4286 		pr_supported->chunk_types[num_ext++] = SCTP_NR_SELECTIVE_ACK;
4287 	}
4288 	p_len = sizeof(*pr_supported) + num_ext;
4289 	pr_supported->ph.param_length = htons(p_len);
4290 	bzero((caddr_t)pr_supported + p_len, SCTP_SIZE32(p_len) - p_len);
4291 	SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
4292 
4293 
4294 	/* ECN nonce: And now tell the peer we support ECN nonce */
4295 	if (SCTP_BASE_SYSCTL(sctp_ecn_nonce)) {
4296 		ecn_nonce = (struct sctp_ecn_nonce_supported_param *)
4297 		    ((caddr_t)pr_supported + SCTP_SIZE32(p_len));
4298 		ecn_nonce->ph.param_type = htons(SCTP_ECN_NONCE_SUPPORTED);
4299 		ecn_nonce->ph.param_length = htons(sizeof(*ecn_nonce));
4300 		SCTP_BUF_LEN(m) += sizeof(*ecn_nonce);
4301 	}
4302 	/* add authentication parameters */
4303 	if (!SCTP_BASE_SYSCTL(sctp_auth_disable)) {
4304 		struct sctp_auth_random *randp;
4305 		struct sctp_auth_hmac_algo *hmacs;
4306 		struct sctp_auth_chunk_list *chunks;
4307 
4308 		/* attach RANDOM parameter, if available */
4309 		if (stcb->asoc.authinfo.random != NULL) {
4310 			randp = (struct sctp_auth_random *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
4311 			p_len = sizeof(*randp) + stcb->asoc.authinfo.random_len;
4312 			/* random key already contains the header */
4313 			bcopy(stcb->asoc.authinfo.random->key, randp, p_len);
4314 			/* zero out any padding required */
4315 			bzero((caddr_t)randp + p_len, SCTP_SIZE32(p_len) - p_len);
4316 			SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
4317 		}
4318 		/* add HMAC_ALGO parameter */
4319 		hmacs = (struct sctp_auth_hmac_algo *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
4320 		p_len = sctp_serialize_hmaclist(stcb->asoc.local_hmacs,
4321 		    (uint8_t *) hmacs->hmac_ids);
4322 		if (p_len > 0) {
4323 			p_len += sizeof(*hmacs);
4324 			hmacs->ph.param_type = htons(SCTP_HMAC_LIST);
4325 			hmacs->ph.param_length = htons(p_len);
4326 			/* zero out any padding required */
4327 			bzero((caddr_t)hmacs + p_len, SCTP_SIZE32(p_len) - p_len);
4328 			SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
4329 		}
4330 		/* add CHUNKS parameter */
4331 		chunks = (struct sctp_auth_chunk_list *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
4332 		p_len = sctp_serialize_auth_chunks(stcb->asoc.local_auth_chunks,
4333 		    chunks->chunk_types);
4334 		if (p_len > 0) {
4335 			p_len += sizeof(*chunks);
4336 			chunks->ph.param_type = htons(SCTP_CHUNK_LIST);
4337 			chunks->ph.param_length = htons(p_len);
4338 			/* zero out any padding required */
4339 			bzero((caddr_t)chunks + p_len, SCTP_SIZE32(p_len) - p_len);
4340 			SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
4341 		}
4342 	}
4343 	m_at = m;
4344 	/* now the addresses */
4345 	{
4346 		struct sctp_scoping scp;
4347 
4348 		/*
4349 		 * To optimize this we could put the scoping stuff into a
4350 		 * structure and remove the individual uint8's from the
4351 		 * assoc structure. Then we could just sifa in the address
4352 		 * within the stcb.. but for now this is a quick hack to get
4353 		 * the address stuff teased apart.
4354 		 */
4355 		scp.ipv4_addr_legal = stcb->asoc.ipv4_addr_legal;
4356 		scp.ipv6_addr_legal = stcb->asoc.ipv6_addr_legal;
4357 		scp.loopback_scope = stcb->asoc.loopback_scope;
4358 		scp.ipv4_local_scope = stcb->asoc.ipv4_local_scope;
4359 		scp.local_scope = stcb->asoc.local_scope;
4360 		scp.site_scope = stcb->asoc.site_scope;
4361 
4362 		m_at = sctp_add_addresses_to_i_ia(inp, &scp, m_at, cnt_inits_to);
4363 	}
4364 
4365 	/* calulate the size and update pkt header and chunk header */
4366 	p_len = 0;
4367 	for (m_at = m; m_at; m_at = SCTP_BUF_NEXT(m_at)) {
4368 		if (SCTP_BUF_NEXT(m_at) == NULL)
4369 			mp_last = m_at;
4370 		p_len += SCTP_BUF_LEN(m_at);
4371 	}
4372 	init->ch.chunk_length = htons(p_len);
4373 	/*
4374 	 * We sifa 0 here to NOT set IP_DF if its IPv4, we ignore the return
4375 	 * here since the timer will drive a retranmission.
4376 	 */
4377 
4378 	/* I don't expect this to execute but we will be safe here */
4379 	padval = p_len % 4;
4380 	if ((padval) && (mp_last)) {
4381 		/*
4382 		 * The compiler worries that mp_last may not be set even
4383 		 * though I think it is impossible :-> however we add
4384 		 * mp_last here just in case.
4385 		 */
4386 		ret = sctp_add_pad_tombuf(mp_last, (4 - padval));
4387 		if (ret) {
4388 			/* Houston we have a problem, no space */
4389 			sctp_m_freem(m);
4390 			return;
4391 		}
4392 		p_len += padval;
4393 	}
4394 	SCTPDBG(SCTP_DEBUG_OUTPUT4, "Sending INIT - calls lowlevel_output\n");
4395 	ret = sctp_lowlevel_chunk_output(inp, stcb, net,
4396 	    (struct sockaddr *)&net->ro._l_addr,
4397 	    m, 0, NULL, 0, 0, 0, NULL, 0,
4398 	    inp->sctp_lport, stcb->rport, htonl(0),
4399 	    net->port, so_locked, NULL);
4400 	SCTPDBG(SCTP_DEBUG_OUTPUT4, "lowlevel_output - %d\n", ret);
4401 	SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
4402 	(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
4403 }
4404 
4405 struct mbuf *
4406 sctp_arethere_unrecognized_parameters(struct mbuf *in_initpkt,
4407     int param_offset, int *abort_processing, struct sctp_chunkhdr *cp, int *nat_friendly)
4408 {
4409 	/*
4410 	 * Given a mbuf containing an INIT or INIT-ACK with the param_offset
4411 	 * being equal to the beginning of the params i.e. (iphlen +
4412 	 * sizeof(struct sctp_init_msg) parse through the parameters to the
4413 	 * end of the mbuf verifying that all parameters are known.
4414 	 *
4415 	 * For unknown parameters build and return a mbuf with
4416 	 * UNRECOGNIZED_PARAMETER errors. If the flags indicate to stop
4417 	 * processing this chunk stop, and set *abort_processing to 1.
4418 	 *
4419 	 * By having param_offset be pre-set to where parameters begin it is
4420 	 * hoped that this routine may be reused in the future by new
4421 	 * features.
4422 	 */
4423 	struct sctp_paramhdr *phdr, params;
4424 
4425 	struct mbuf *mat, *op_err;
4426 	char tempbuf[SCTP_PARAM_BUFFER_SIZE];
4427 	int at, limit, pad_needed;
4428 	uint16_t ptype, plen, padded_size;
4429 	int err_at;
4430 
4431 	*abort_processing = 0;
4432 	mat = in_initpkt;
4433 	err_at = 0;
4434 	limit = ntohs(cp->chunk_length) - sizeof(struct sctp_init_chunk);
4435 	at = param_offset;
4436 	op_err = NULL;
4437 	SCTPDBG(SCTP_DEBUG_OUTPUT1, "Check for unrecognized param's\n");
4438 	phdr = sctp_get_next_param(mat, at, &params, sizeof(params));
4439 	while ((phdr != NULL) && ((size_t)limit >= sizeof(struct sctp_paramhdr))) {
4440 		ptype = ntohs(phdr->param_type);
4441 		plen = ntohs(phdr->param_length);
4442 		if ((plen > limit) || (plen < sizeof(struct sctp_paramhdr))) {
4443 			/* wacked parameter */
4444 			SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error %d\n", plen);
4445 			goto invalid_size;
4446 		}
4447 		limit -= SCTP_SIZE32(plen);
4448 		/*-
4449 		 * All parameters for all chunks that we know/understand are
4450 		 * listed here. We process them other places and make
4451 		 * appropriate stop actions per the upper bits. However this
4452 		 * is the generic routine processor's can call to get back
4453 		 * an operr.. to either incorporate (init-ack) or send.
4454 		 */
4455 		padded_size = SCTP_SIZE32(plen);
4456 		switch (ptype) {
4457 			/* Param's with variable size */
4458 		case SCTP_HEARTBEAT_INFO:
4459 		case SCTP_STATE_COOKIE:
4460 		case SCTP_UNRECOG_PARAM:
4461 		case SCTP_ERROR_CAUSE_IND:
4462 			/* ok skip fwd */
4463 			at += padded_size;
4464 			break;
4465 			/* Param's with variable size within a range */
4466 		case SCTP_CHUNK_LIST:
4467 		case SCTP_SUPPORTED_CHUNK_EXT:
4468 			if (padded_size > (sizeof(struct sctp_supported_chunk_types_param) + (sizeof(uint8_t) * SCTP_MAX_SUPPORTED_EXT))) {
4469 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error chklist %d\n", plen);
4470 				goto invalid_size;
4471 			}
4472 			at += padded_size;
4473 			break;
4474 		case SCTP_SUPPORTED_ADDRTYPE:
4475 			if (padded_size > SCTP_MAX_ADDR_PARAMS_SIZE) {
4476 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error supaddrtype %d\n", plen);
4477 				goto invalid_size;
4478 			}
4479 			at += padded_size;
4480 			break;
4481 		case SCTP_RANDOM:
4482 			if (padded_size > (sizeof(struct sctp_auth_random) + SCTP_RANDOM_MAX_SIZE)) {
4483 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error random %d\n", plen);
4484 				goto invalid_size;
4485 			}
4486 			at += padded_size;
4487 			break;
4488 		case SCTP_SET_PRIM_ADDR:
4489 		case SCTP_DEL_IP_ADDRESS:
4490 		case SCTP_ADD_IP_ADDRESS:
4491 			if ((padded_size != sizeof(struct sctp_asconf_addrv4_param)) &&
4492 			    (padded_size != sizeof(struct sctp_asconf_addr_param))) {
4493 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error setprim %d\n", plen);
4494 				goto invalid_size;
4495 			}
4496 			at += padded_size;
4497 			break;
4498 			/* Param's with a fixed size */
4499 		case SCTP_IPV4_ADDRESS:
4500 			if (padded_size != sizeof(struct sctp_ipv4addr_param)) {
4501 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error ipv4 addr %d\n", plen);
4502 				goto invalid_size;
4503 			}
4504 			at += padded_size;
4505 			break;
4506 		case SCTP_IPV6_ADDRESS:
4507 			if (padded_size != sizeof(struct sctp_ipv6addr_param)) {
4508 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error ipv6 addr %d\n", plen);
4509 				goto invalid_size;
4510 			}
4511 			at += padded_size;
4512 			break;
4513 		case SCTP_COOKIE_PRESERVE:
4514 			if (padded_size != sizeof(struct sctp_cookie_perserve_param)) {
4515 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error cookie-preserve %d\n", plen);
4516 				goto invalid_size;
4517 			}
4518 			at += padded_size;
4519 			break;
4520 		case SCTP_HAS_NAT_SUPPORT:
4521 			*nat_friendly = 1;
4522 			/* fall through */
4523 		case SCTP_ECN_NONCE_SUPPORTED:
4524 		case SCTP_PRSCTP_SUPPORTED:
4525 
4526 			if (padded_size != sizeof(struct sctp_paramhdr)) {
4527 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error ecnnonce/prsctp/nat support %d\n", plen);
4528 				goto invalid_size;
4529 			}
4530 			at += padded_size;
4531 			break;
4532 		case SCTP_ECN_CAPABLE:
4533 			if (padded_size != sizeof(struct sctp_ecn_supported_param)) {
4534 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error ecn %d\n", plen);
4535 				goto invalid_size;
4536 			}
4537 			at += padded_size;
4538 			break;
4539 		case SCTP_ULP_ADAPTATION:
4540 			if (padded_size != sizeof(struct sctp_adaptation_layer_indication)) {
4541 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error adapatation %d\n", plen);
4542 				goto invalid_size;
4543 			}
4544 			at += padded_size;
4545 			break;
4546 		case SCTP_SUCCESS_REPORT:
4547 			if (padded_size != sizeof(struct sctp_asconf_paramhdr)) {
4548 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Invalid size - error success %d\n", plen);
4549 				goto invalid_size;
4550 			}
4551 			at += padded_size;
4552 			break;
4553 		case SCTP_HOSTNAME_ADDRESS:
4554 			{
4555 				/* We can NOT handle HOST NAME addresses!! */
4556 				int l_len;
4557 
4558 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "Can't handle hostname addresses.. abort processing\n");
4559 				*abort_processing = 1;
4560 				if (op_err == NULL) {
4561 					/* Ok need to try to get a mbuf */
4562 #ifdef INET6
4563 					l_len = sizeof(struct ip6_hdr) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
4564 #else
4565 					l_len = sizeof(struct ip) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
4566 #endif
4567 					l_len += plen;
4568 					l_len += sizeof(struct sctp_paramhdr);
4569 					op_err = sctp_get_mbuf_for_msg(l_len, 0, M_DONTWAIT, 1, MT_DATA);
4570 					if (op_err) {
4571 						SCTP_BUF_LEN(op_err) = 0;
4572 						/*
4573 						 * pre-reserve space for ip
4574 						 * and sctp header  and
4575 						 * chunk hdr
4576 						 */
4577 #ifdef INET6
4578 						SCTP_BUF_RESV_UF(op_err, sizeof(struct ip6_hdr));
4579 #else
4580 						SCTP_BUF_RESV_UF(op_err, sizeof(struct ip));
4581 #endif
4582 						SCTP_BUF_RESV_UF(op_err, sizeof(struct sctphdr));
4583 						SCTP_BUF_RESV_UF(op_err, sizeof(struct sctp_chunkhdr));
4584 					}
4585 				}
4586 				if (op_err) {
4587 					/* If we have space */
4588 					struct sctp_paramhdr s;
4589 
4590 					if (err_at % 4) {
4591 						uint32_t cpthis = 0;
4592 
4593 						pad_needed = 4 - (err_at % 4);
4594 						m_copyback(op_err, err_at, pad_needed, (caddr_t)&cpthis);
4595 						err_at += pad_needed;
4596 					}
4597 					s.param_type = htons(SCTP_CAUSE_UNRESOLVABLE_ADDR);
4598 					s.param_length = htons(sizeof(s) + plen);
4599 					m_copyback(op_err, err_at, sizeof(s), (caddr_t)&s);
4600 					err_at += sizeof(s);
4601 					phdr = sctp_get_next_param(mat, at, (struct sctp_paramhdr *)tempbuf, min(sizeof(tempbuf), plen));
4602 					if (phdr == NULL) {
4603 						sctp_m_freem(op_err);
4604 						/*
4605 						 * we are out of memory but
4606 						 * we still need to have a
4607 						 * look at what to do (the
4608 						 * system is in trouble
4609 						 * though).
4610 						 */
4611 						return (NULL);
4612 					}
4613 					m_copyback(op_err, err_at, plen, (caddr_t)phdr);
4614 					err_at += plen;
4615 				}
4616 				return (op_err);
4617 				break;
4618 			}
4619 		default:
4620 			/*
4621 			 * we do not recognize the parameter figure out what
4622 			 * we do.
4623 			 */
4624 			SCTPDBG(SCTP_DEBUG_OUTPUT1, "Hit default param %x\n", ptype);
4625 			if ((ptype & 0x4000) == 0x4000) {
4626 				/* Report bit is set?? */
4627 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "report op err\n");
4628 				if (op_err == NULL) {
4629 					int l_len;
4630 
4631 					/* Ok need to try to get an mbuf */
4632 #ifdef INET6
4633 					l_len = sizeof(struct ip6_hdr) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
4634 #else
4635 					l_len = sizeof(struct ip) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
4636 #endif
4637 					l_len += plen;
4638 					l_len += sizeof(struct sctp_paramhdr);
4639 					op_err = sctp_get_mbuf_for_msg(l_len, 0, M_DONTWAIT, 1, MT_DATA);
4640 					if (op_err) {
4641 						SCTP_BUF_LEN(op_err) = 0;
4642 #ifdef INET6
4643 						SCTP_BUF_RESV_UF(op_err, sizeof(struct ip6_hdr));
4644 #else
4645 						SCTP_BUF_RESV_UF(op_err, sizeof(struct ip));
4646 #endif
4647 						SCTP_BUF_RESV_UF(op_err, sizeof(struct sctphdr));
4648 						SCTP_BUF_RESV_UF(op_err, sizeof(struct sctp_chunkhdr));
4649 					}
4650 				}
4651 				if (op_err) {
4652 					/* If we have space */
4653 					struct sctp_paramhdr s;
4654 
4655 					if (err_at % 4) {
4656 						uint32_t cpthis = 0;
4657 
4658 						pad_needed = 4 - (err_at % 4);
4659 						m_copyback(op_err, err_at, pad_needed, (caddr_t)&cpthis);
4660 						err_at += pad_needed;
4661 					}
4662 					s.param_type = htons(SCTP_UNRECOG_PARAM);
4663 					s.param_length = htons(sizeof(s) + plen);
4664 					m_copyback(op_err, err_at, sizeof(s), (caddr_t)&s);
4665 					err_at += sizeof(s);
4666 					if (plen > sizeof(tempbuf)) {
4667 						plen = sizeof(tempbuf);
4668 					}
4669 					phdr = sctp_get_next_param(mat, at, (struct sctp_paramhdr *)tempbuf, min(sizeof(tempbuf), plen));
4670 					if (phdr == NULL) {
4671 						sctp_m_freem(op_err);
4672 						/*
4673 						 * we are out of memory but
4674 						 * we still need to have a
4675 						 * look at what to do (the
4676 						 * system is in trouble
4677 						 * though).
4678 						 */
4679 						op_err = NULL;
4680 						goto more_processing;
4681 					}
4682 					m_copyback(op_err, err_at, plen, (caddr_t)phdr);
4683 					err_at += plen;
4684 				}
4685 			}
4686 	more_processing:
4687 			if ((ptype & 0x8000) == 0x0000) {
4688 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "stop proc\n");
4689 				return (op_err);
4690 			} else {
4691 				/* skip this chunk and continue processing */
4692 				SCTPDBG(SCTP_DEBUG_OUTPUT1, "move on\n");
4693 				at += SCTP_SIZE32(plen);
4694 			}
4695 			break;
4696 
4697 		}
4698 		phdr = sctp_get_next_param(mat, at, &params, sizeof(params));
4699 	}
4700 	return (op_err);
4701 invalid_size:
4702 	SCTPDBG(SCTP_DEBUG_OUTPUT1, "abort flag set\n");
4703 	*abort_processing = 1;
4704 	if ((op_err == NULL) && phdr) {
4705 		int l_len;
4706 
4707 #ifdef INET6
4708 		l_len = sizeof(struct ip6_hdr) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
4709 #else
4710 		l_len = sizeof(struct ip) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
4711 #endif
4712 		l_len += (2 * sizeof(struct sctp_paramhdr));
4713 		op_err = sctp_get_mbuf_for_msg(l_len, 0, M_DONTWAIT, 1, MT_DATA);
4714 		if (op_err) {
4715 			SCTP_BUF_LEN(op_err) = 0;
4716 #ifdef INET6
4717 			SCTP_BUF_RESV_UF(op_err, sizeof(struct ip6_hdr));
4718 #else
4719 			SCTP_BUF_RESV_UF(op_err, sizeof(struct ip));
4720 #endif
4721 			SCTP_BUF_RESV_UF(op_err, sizeof(struct sctphdr));
4722 			SCTP_BUF_RESV_UF(op_err, sizeof(struct sctp_chunkhdr));
4723 		}
4724 	}
4725 	if ((op_err) && phdr) {
4726 		struct sctp_paramhdr s;
4727 
4728 		if (err_at % 4) {
4729 			uint32_t cpthis = 0;
4730 
4731 			pad_needed = 4 - (err_at % 4);
4732 			m_copyback(op_err, err_at, pad_needed, (caddr_t)&cpthis);
4733 			err_at += pad_needed;
4734 		}
4735 		s.param_type = htons(SCTP_CAUSE_PROTOCOL_VIOLATION);
4736 		s.param_length = htons(sizeof(s) + sizeof(struct sctp_paramhdr));
4737 		m_copyback(op_err, err_at, sizeof(s), (caddr_t)&s);
4738 		err_at += sizeof(s);
4739 		/* Only copy back the p-hdr that caused the issue */
4740 		m_copyback(op_err, err_at, sizeof(struct sctp_paramhdr), (caddr_t)phdr);
4741 	}
4742 	return (op_err);
4743 }
4744 
4745 static int
4746 sctp_are_there_new_addresses(struct sctp_association *asoc,
4747     struct mbuf *in_initpkt, int iphlen, int offset)
4748 {
4749 	/*
4750 	 * Given a INIT packet, look through the packet to verify that there
4751 	 * are NO new addresses. As we go through the parameters add reports
4752 	 * of any un-understood parameters that require an error.  Also we
4753 	 * must return (1) to drop the packet if we see a un-understood
4754 	 * parameter that tells us to drop the chunk.
4755 	 */
4756 	struct sockaddr_in sin4, *sa4;
4757 
4758 #ifdef INET6
4759 	struct sockaddr_in6 sin6, *sa6;
4760 
4761 #endif
4762 	struct sockaddr *sa_touse;
4763 	struct sockaddr *sa;
4764 	struct sctp_paramhdr *phdr, params;
4765 	struct ip *iph;
4766 
4767 #ifdef INET6
4768 	struct ip6_hdr *ip6h;
4769 
4770 #endif
4771 	struct mbuf *mat;
4772 	uint16_t ptype, plen;
4773 	int err_at;
4774 	uint8_t fnd;
4775 	struct sctp_nets *net;
4776 
4777 	memset(&sin4, 0, sizeof(sin4));
4778 #ifdef INET6
4779 	memset(&sin6, 0, sizeof(sin6));
4780 #endif
4781 	sin4.sin_family = AF_INET;
4782 	sin4.sin_len = sizeof(sin4);
4783 #ifdef INET6
4784 	sin6.sin6_family = AF_INET6;
4785 	sin6.sin6_len = sizeof(sin6);
4786 #endif
4787 	sa_touse = NULL;
4788 	/* First what about the src address of the pkt ? */
4789 	iph = mtod(in_initpkt, struct ip *);
4790 	switch (iph->ip_v) {
4791 	case IPVERSION:
4792 		/* source addr is IPv4 */
4793 		sin4.sin_addr = iph->ip_src;
4794 		sa_touse = (struct sockaddr *)&sin4;
4795 		break;
4796 #ifdef INET6
4797 	case IPV6_VERSION >> 4:
4798 		/* source addr is IPv6 */
4799 		ip6h = mtod(in_initpkt, struct ip6_hdr *);
4800 		sin6.sin6_addr = ip6h->ip6_src;
4801 		sa_touse = (struct sockaddr *)&sin6;
4802 		break;
4803 #endif
4804 	default:
4805 		return (1);
4806 	}
4807 
4808 	fnd = 0;
4809 	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
4810 		sa = (struct sockaddr *)&net->ro._l_addr;
4811 		if (sa->sa_family == sa_touse->sa_family) {
4812 			if (sa->sa_family == AF_INET) {
4813 				sa4 = (struct sockaddr_in *)sa;
4814 				if (sa4->sin_addr.s_addr ==
4815 				    sin4.sin_addr.s_addr) {
4816 					fnd = 1;
4817 					break;
4818 				}
4819 			}
4820 #ifdef INET6
4821 			if (sa->sa_family == AF_INET6) {
4822 				sa6 = (struct sockaddr_in6 *)sa;
4823 				if (SCTP6_ARE_ADDR_EQUAL(sa6,
4824 				    &sin6)) {
4825 					fnd = 1;
4826 					break;
4827 				}
4828 			}
4829 #endif
4830 		}
4831 	}
4832 	if (fnd == 0) {
4833 		/* New address added! no need to look futher. */
4834 		return (1);
4835 	}
4836 	/* Ok so far lets munge through the rest of the packet */
4837 	mat = in_initpkt;
4838 	err_at = 0;
4839 	sa_touse = NULL;
4840 	offset += sizeof(struct sctp_init_chunk);
4841 	phdr = sctp_get_next_param(mat, offset, &params, sizeof(params));
4842 	while (phdr) {
4843 		ptype = ntohs(phdr->param_type);
4844 		plen = ntohs(phdr->param_length);
4845 		if (ptype == SCTP_IPV4_ADDRESS) {
4846 			struct sctp_ipv4addr_param *p4, p4_buf;
4847 
4848 			phdr = sctp_get_next_param(mat, offset,
4849 			    (struct sctp_paramhdr *)&p4_buf, sizeof(p4_buf));
4850 			if (plen != sizeof(struct sctp_ipv4addr_param) ||
4851 			    phdr == NULL) {
4852 				return (1);
4853 			}
4854 			p4 = (struct sctp_ipv4addr_param *)phdr;
4855 			sin4.sin_addr.s_addr = p4->addr;
4856 			sa_touse = (struct sockaddr *)&sin4;
4857 		} else if (ptype == SCTP_IPV6_ADDRESS) {
4858 			struct sctp_ipv6addr_param *p6, p6_buf;
4859 
4860 			phdr = sctp_get_next_param(mat, offset,
4861 			    (struct sctp_paramhdr *)&p6_buf, sizeof(p6_buf));
4862 			if (plen != sizeof(struct sctp_ipv6addr_param) ||
4863 			    phdr == NULL) {
4864 				return (1);
4865 			}
4866 			p6 = (struct sctp_ipv6addr_param *)phdr;
4867 #ifdef INET6
4868 			memcpy((caddr_t)&sin6.sin6_addr, p6->addr,
4869 			    sizeof(p6->addr));
4870 #endif
4871 			sa_touse = (struct sockaddr *)&sin4;
4872 		}
4873 		if (sa_touse) {
4874 			/* ok, sa_touse points to one to check */
4875 			fnd = 0;
4876 			TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
4877 				sa = (struct sockaddr *)&net->ro._l_addr;
4878 				if (sa->sa_family != sa_touse->sa_family) {
4879 					continue;
4880 				}
4881 				if (sa->sa_family == AF_INET) {
4882 					sa4 = (struct sockaddr_in *)sa;
4883 					if (sa4->sin_addr.s_addr ==
4884 					    sin4.sin_addr.s_addr) {
4885 						fnd = 1;
4886 						break;
4887 					}
4888 				}
4889 #ifdef INET6
4890 				if (sa->sa_family == AF_INET6) {
4891 					sa6 = (struct sockaddr_in6 *)sa;
4892 					if (SCTP6_ARE_ADDR_EQUAL(
4893 					    sa6, &sin6)) {
4894 						fnd = 1;
4895 						break;
4896 					}
4897 				}
4898 #endif
4899 			}
4900 			if (!fnd) {
4901 				/* New addr added! no need to look further */
4902 				return (1);
4903 			}
4904 		}
4905 		offset += SCTP_SIZE32(plen);
4906 		phdr = sctp_get_next_param(mat, offset, &params, sizeof(params));
4907 	}
4908 	return (0);
4909 }
4910 
4911 /*
4912  * Given a MBUF chain that was sent into us containing an INIT. Build a
4913  * INIT-ACK with COOKIE and send back. We assume that the in_initpkt has done
4914  * a pullup to include IPv6/4header, SCTP header and initial part of INIT
4915  * message (i.e. the struct sctp_init_msg).
4916  */
4917 void
4918 sctp_send_initiate_ack(struct sctp_inpcb *inp, struct sctp_tcb *stcb,
4919     struct mbuf *init_pkt, int iphlen, int offset, struct sctphdr *sh,
4920     struct sctp_init_chunk *init_chk, uint32_t vrf_id, uint16_t port, int hold_inp_lock)
4921 {
4922 	struct sctp_association *asoc;
4923 	struct mbuf *m, *m_at, *m_tmp, *m_cookie, *op_err, *mp_last;
4924 	struct sctp_init_ack_chunk *initack;
4925 	struct sctp_adaptation_layer_indication *ali;
4926 	struct sctp_ecn_supported_param *ecn;
4927 	struct sctp_prsctp_supported_param *prsctp;
4928 	struct sctp_ecn_nonce_supported_param *ecn_nonce;
4929 	struct sctp_supported_chunk_types_param *pr_supported;
4930 	union sctp_sockstore store, store1, *over_addr;
4931 	struct sockaddr_in *sin, *to_sin;
4932 
4933 #ifdef INET6
4934 	struct sockaddr_in6 *sin6, *to_sin6;
4935 
4936 #endif
4937 	struct ip *iph;
4938 
4939 #ifdef INET6
4940 	struct ip6_hdr *ip6;
4941 
4942 #endif
4943 	struct sockaddr *to;
4944 	struct sctp_state_cookie stc;
4945 	struct sctp_nets *net = NULL;
4946 	uint8_t *signature = NULL;
4947 	int cnt_inits_to = 0;
4948 	uint16_t his_limit, i_want;
4949 	int abort_flag, padval;
4950 	int num_ext;
4951 	int p_len;
4952 	int nat_friendly = 0;
4953 	struct socket *so;
4954 
4955 	if (stcb)
4956 		asoc = &stcb->asoc;
4957 	else
4958 		asoc = NULL;
4959 	mp_last = NULL;
4960 	if ((asoc != NULL) &&
4961 	    (SCTP_GET_STATE(asoc) != SCTP_STATE_COOKIE_WAIT) &&
4962 	    (sctp_are_there_new_addresses(asoc, init_pkt, iphlen, offset))) {
4963 		/* new addresses, out of here in non-cookie-wait states */
4964 		/*
4965 		 * Send a ABORT, we don't add the new address error clause
4966 		 * though we even set the T bit and copy in the 0 tag.. this
4967 		 * looks no different than if no listener was present.
4968 		 */
4969 		sctp_send_abort(init_pkt, iphlen, sh, 0, NULL, vrf_id, port);
4970 		return;
4971 	}
4972 	abort_flag = 0;
4973 	op_err = sctp_arethere_unrecognized_parameters(init_pkt,
4974 	    (offset + sizeof(struct sctp_init_chunk)),
4975 	    &abort_flag, (struct sctp_chunkhdr *)init_chk, &nat_friendly);
4976 	if (abort_flag) {
4977 do_a_abort:
4978 		sctp_send_abort(init_pkt, iphlen, sh,
4979 		    init_chk->init.initiate_tag, op_err, vrf_id, port);
4980 		return;
4981 	}
4982 	m = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_DATA);
4983 	if (m == NULL) {
4984 		/* No memory, INIT timer will re-attempt. */
4985 		if (op_err)
4986 			sctp_m_freem(op_err);
4987 		return;
4988 	}
4989 	SCTP_BUF_LEN(m) = sizeof(struct sctp_init_chunk);
4990 
4991 	/* the time I built cookie */
4992 	(void)SCTP_GETTIME_TIMEVAL(&stc.time_entered);
4993 
4994 	/* populate any tie tags */
4995 	if (asoc != NULL) {
4996 		/* unlock before tag selections */
4997 		stc.tie_tag_my_vtag = asoc->my_vtag_nonce;
4998 		stc.tie_tag_peer_vtag = asoc->peer_vtag_nonce;
4999 		stc.cookie_life = asoc->cookie_life;
5000 		net = asoc->primary_destination;
5001 	} else {
5002 		stc.tie_tag_my_vtag = 0;
5003 		stc.tie_tag_peer_vtag = 0;
5004 		/* life I will award this cookie */
5005 		stc.cookie_life = inp->sctp_ep.def_cookie_life;
5006 	}
5007 
5008 	/* copy in the ports for later check */
5009 	stc.myport = sh->dest_port;
5010 	stc.peerport = sh->src_port;
5011 
5012 	/*
5013 	 * If we wanted to honor cookie life extentions, we would add to
5014 	 * stc.cookie_life. For now we should NOT honor any extension
5015 	 */
5016 	stc.site_scope = stc.local_scope = stc.loopback_scope = 0;
5017 	if (inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
5018 		struct inpcb *in_inp;
5019 
5020 		/* Its a V6 socket */
5021 		in_inp = (struct inpcb *)inp;
5022 		stc.ipv6_addr_legal = 1;
5023 		/* Now look at the binding flag to see if V4 will be legal */
5024 		if (SCTP_IPV6_V6ONLY(in_inp) == 0) {
5025 			stc.ipv4_addr_legal = 1;
5026 		} else {
5027 			/* V4 addresses are NOT legal on the association */
5028 			stc.ipv4_addr_legal = 0;
5029 		}
5030 	} else {
5031 		/* Its a V4 socket, no - V6 */
5032 		stc.ipv4_addr_legal = 1;
5033 		stc.ipv6_addr_legal = 0;
5034 	}
5035 
5036 #ifdef SCTP_DONT_DO_PRIVADDR_SCOPE
5037 	stc.ipv4_scope = 1;
5038 #else
5039 	stc.ipv4_scope = 0;
5040 #endif
5041 	/* now for scope setup */
5042 	memset((caddr_t)&store, 0, sizeof(store));
5043 	memset((caddr_t)&store1, 0, sizeof(store1));
5044 	sin = &store.sin;
5045 	to_sin = &store1.sin;
5046 #ifdef INET6
5047 	sin6 = &store.sin6;
5048 	to_sin6 = &store1.sin6;
5049 #endif
5050 	iph = mtod(init_pkt, struct ip *);
5051 	/* establish the to_addr's */
5052 	switch (iph->ip_v) {
5053 	case IPVERSION:
5054 		to_sin->sin_port = sh->dest_port;
5055 		to_sin->sin_family = AF_INET;
5056 		to_sin->sin_len = sizeof(struct sockaddr_in);
5057 		to_sin->sin_addr = iph->ip_dst;
5058 		break;
5059 #ifdef INET6
5060 	case IPV6_VERSION >> 4:
5061 		ip6 = mtod(init_pkt, struct ip6_hdr *);
5062 		to_sin6->sin6_addr = ip6->ip6_dst;
5063 		to_sin6->sin6_scope_id = 0;
5064 		to_sin6->sin6_port = sh->dest_port;
5065 		to_sin6->sin6_family = AF_INET6;
5066 		to_sin6->sin6_len = sizeof(struct sockaddr_in6);
5067 		break;
5068 #endif
5069 	default:
5070 		goto do_a_abort;
5071 		break;
5072 	};
5073 
5074 	if (net == NULL) {
5075 		to = (struct sockaddr *)&store;
5076 		switch (iph->ip_v) {
5077 		case IPVERSION:
5078 			{
5079 				sin->sin_family = AF_INET;
5080 				sin->sin_len = sizeof(struct sockaddr_in);
5081 				sin->sin_port = sh->src_port;
5082 				sin->sin_addr = iph->ip_src;
5083 				/* lookup address */
5084 				stc.address[0] = sin->sin_addr.s_addr;
5085 				stc.address[1] = 0;
5086 				stc.address[2] = 0;
5087 				stc.address[3] = 0;
5088 				stc.addr_type = SCTP_IPV4_ADDRESS;
5089 				/* local from address */
5090 				stc.laddress[0] = to_sin->sin_addr.s_addr;
5091 				stc.laddress[1] = 0;
5092 				stc.laddress[2] = 0;
5093 				stc.laddress[3] = 0;
5094 				stc.laddr_type = SCTP_IPV4_ADDRESS;
5095 				/* scope_id is only for v6 */
5096 				stc.scope_id = 0;
5097 #ifndef SCTP_DONT_DO_PRIVADDR_SCOPE
5098 				if (IN4_ISPRIVATE_ADDRESS(&sin->sin_addr)) {
5099 					stc.ipv4_scope = 1;
5100 				}
5101 #else
5102 				stc.ipv4_scope = 1;
5103 #endif				/* SCTP_DONT_DO_PRIVADDR_SCOPE */
5104 				/* Must use the address in this case */
5105 				if (sctp_is_address_on_local_host((struct sockaddr *)sin, vrf_id)) {
5106 					stc.loopback_scope = 1;
5107 					stc.ipv4_scope = 1;
5108 					stc.site_scope = 1;
5109 					stc.local_scope = 0;
5110 				}
5111 				break;
5112 			}
5113 #ifdef INET6
5114 		case IPV6_VERSION >> 4:
5115 			{
5116 				ip6 = mtod(init_pkt, struct ip6_hdr *);
5117 				sin6->sin6_family = AF_INET6;
5118 				sin6->sin6_len = sizeof(struct sockaddr_in6);
5119 				sin6->sin6_port = sh->src_port;
5120 				sin6->sin6_addr = ip6->ip6_src;
5121 				/* lookup address */
5122 				memcpy(&stc.address, &sin6->sin6_addr,
5123 				    sizeof(struct in6_addr));
5124 				sin6->sin6_scope_id = 0;
5125 				stc.addr_type = SCTP_IPV6_ADDRESS;
5126 				stc.scope_id = 0;
5127 				if (sctp_is_address_on_local_host((struct sockaddr *)sin6, vrf_id)) {
5128 					/*
5129 					 * FIX ME: does this have scope from
5130 					 * rcvif?
5131 					 */
5132 					(void)sa6_recoverscope(sin6);
5133 					stc.scope_id = sin6->sin6_scope_id;
5134 					sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone));
5135 					stc.loopback_scope = 1;
5136 					stc.local_scope = 0;
5137 					stc.site_scope = 1;
5138 					stc.ipv4_scope = 1;
5139 				} else if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) {
5140 					/*
5141 					 * If the new destination is a
5142 					 * LINK_LOCAL we must have common
5143 					 * both site and local scope. Don't
5144 					 * set local scope though since we
5145 					 * must depend on the source to be
5146 					 * added implicitly. We cannot
5147 					 * assure just because we share one
5148 					 * link that all links are common.
5149 					 */
5150 					stc.local_scope = 0;
5151 					stc.site_scope = 1;
5152 					stc.ipv4_scope = 1;
5153 					/*
5154 					 * we start counting for the private
5155 					 * address stuff at 1. since the
5156 					 * link local we source from won't
5157 					 * show up in our scoped count.
5158 					 */
5159 					cnt_inits_to = 1;
5160 					/*
5161 					 * pull out the scope_id from
5162 					 * incoming pkt
5163 					 */
5164 					/*
5165 					 * FIX ME: does this have scope from
5166 					 * rcvif?
5167 					 */
5168 					(void)sa6_recoverscope(sin6);
5169 					stc.scope_id = sin6->sin6_scope_id;
5170 					sa6_embedscope(sin6, MODULE_GLOBAL(ip6_use_defzone));
5171 				} else if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr)) {
5172 					/*
5173 					 * If the new destination is
5174 					 * SITE_LOCAL then we must have site
5175 					 * scope in common.
5176 					 */
5177 					stc.site_scope = 1;
5178 				}
5179 				memcpy(&stc.laddress, &to_sin6->sin6_addr, sizeof(struct in6_addr));
5180 				stc.laddr_type = SCTP_IPV6_ADDRESS;
5181 				break;
5182 			}
5183 #endif
5184 		default:
5185 			/* TSNH */
5186 			goto do_a_abort;
5187 			break;
5188 		}
5189 	} else {
5190 		/* set the scope per the existing tcb */
5191 
5192 #ifdef INET6
5193 		struct sctp_nets *lnet;
5194 
5195 #endif
5196 
5197 		stc.loopback_scope = asoc->loopback_scope;
5198 		stc.ipv4_scope = asoc->ipv4_local_scope;
5199 		stc.site_scope = asoc->site_scope;
5200 		stc.local_scope = asoc->local_scope;
5201 #ifdef INET6
5202 		/* Why do we not consider IPv4 LL addresses? */
5203 		TAILQ_FOREACH(lnet, &asoc->nets, sctp_next) {
5204 			if (lnet->ro._l_addr.sin6.sin6_family == AF_INET6) {
5205 				if (IN6_IS_ADDR_LINKLOCAL(&lnet->ro._l_addr.sin6.sin6_addr)) {
5206 					/*
5207 					 * if we have a LL address, start
5208 					 * counting at 1.
5209 					 */
5210 					cnt_inits_to = 1;
5211 				}
5212 			}
5213 		}
5214 #endif
5215 		/* use the net pointer */
5216 		to = (struct sockaddr *)&net->ro._l_addr;
5217 		switch (to->sa_family) {
5218 		case AF_INET:
5219 			sin = (struct sockaddr_in *)to;
5220 			stc.address[0] = sin->sin_addr.s_addr;
5221 			stc.address[1] = 0;
5222 			stc.address[2] = 0;
5223 			stc.address[3] = 0;
5224 			stc.addr_type = SCTP_IPV4_ADDRESS;
5225 			if (net->src_addr_selected == 0) {
5226 				/*
5227 				 * strange case here, the INIT should have
5228 				 * did the selection.
5229 				 */
5230 				net->ro._s_addr = sctp_source_address_selection(inp,
5231 				    stcb, (sctp_route_t *) & net->ro,
5232 				    net, 0, vrf_id);
5233 				if (net->ro._s_addr == NULL)
5234 					return;
5235 
5236 				net->src_addr_selected = 1;
5237 
5238 			}
5239 			stc.laddress[0] = net->ro._s_addr->address.sin.sin_addr.s_addr;
5240 			stc.laddress[1] = 0;
5241 			stc.laddress[2] = 0;
5242 			stc.laddress[3] = 0;
5243 			stc.laddr_type = SCTP_IPV4_ADDRESS;
5244 			break;
5245 #ifdef INET6
5246 		case AF_INET6:
5247 			sin6 = (struct sockaddr_in6 *)to;
5248 			memcpy(&stc.address, &sin6->sin6_addr,
5249 			    sizeof(struct in6_addr));
5250 			stc.addr_type = SCTP_IPV6_ADDRESS;
5251 			if (net->src_addr_selected == 0) {
5252 				/*
5253 				 * strange case here, the INIT should have
5254 				 * did the selection.
5255 				 */
5256 				net->ro._s_addr = sctp_source_address_selection(inp,
5257 				    stcb, (sctp_route_t *) & net->ro,
5258 				    net, 0, vrf_id);
5259 				if (net->ro._s_addr == NULL)
5260 					return;
5261 
5262 				net->src_addr_selected = 1;
5263 			}
5264 			memcpy(&stc.laddress, &net->ro._s_addr->address.sin6.sin6_addr,
5265 			    sizeof(struct in6_addr));
5266 			stc.laddr_type = SCTP_IPV6_ADDRESS;
5267 			break;
5268 #endif
5269 		}
5270 	}
5271 	/* Now lets put the SCTP header in place */
5272 	initack = mtod(m, struct sctp_init_ack_chunk *);
5273 	/* Save it off for quick ref */
5274 	stc.peers_vtag = init_chk->init.initiate_tag;
5275 	/* who are we */
5276 	memcpy(stc.identification, SCTP_VERSION_STRING,
5277 	    min(strlen(SCTP_VERSION_STRING), sizeof(stc.identification)));
5278 	/* now the chunk header */
5279 	initack->ch.chunk_type = SCTP_INITIATION_ACK;
5280 	initack->ch.chunk_flags = 0;
5281 	/* fill in later from mbuf we build */
5282 	initack->ch.chunk_length = 0;
5283 	/* place in my tag */
5284 	if ((asoc != NULL) &&
5285 	    ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
5286 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_INUSE) ||
5287 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED))) {
5288 		/* re-use the v-tags and init-seq here */
5289 		initack->init.initiate_tag = htonl(asoc->my_vtag);
5290 		initack->init.initial_tsn = htonl(asoc->init_seq_number);
5291 	} else {
5292 		uint32_t vtag, itsn;
5293 
5294 		if (hold_inp_lock) {
5295 			SCTP_INP_INCR_REF(inp);
5296 			SCTP_INP_RUNLOCK(inp);
5297 		}
5298 		if (asoc) {
5299 			atomic_add_int(&asoc->refcnt, 1);
5300 			SCTP_TCB_UNLOCK(stcb);
5301 	new_tag:
5302 			vtag = sctp_select_a_tag(inp, inp->sctp_lport, sh->src_port, 1);
5303 			if ((asoc->peer_supports_nat) && (vtag == asoc->my_vtag)) {
5304 				/*
5305 				 * Got a duplicate vtag on some guy behind a
5306 				 * nat make sure we don't use it.
5307 				 */
5308 				goto new_tag;
5309 			}
5310 			initack->init.initiate_tag = htonl(vtag);
5311 			/* get a TSN to use too */
5312 			itsn = sctp_select_initial_TSN(&inp->sctp_ep);
5313 			initack->init.initial_tsn = htonl(itsn);
5314 			SCTP_TCB_LOCK(stcb);
5315 			atomic_add_int(&asoc->refcnt, -1);
5316 		} else {
5317 			vtag = sctp_select_a_tag(inp, inp->sctp_lport, sh->src_port, 1);
5318 			initack->init.initiate_tag = htonl(vtag);
5319 			/* get a TSN to use too */
5320 			initack->init.initial_tsn = htonl(sctp_select_initial_TSN(&inp->sctp_ep));
5321 		}
5322 		if (hold_inp_lock) {
5323 			SCTP_INP_RLOCK(inp);
5324 			SCTP_INP_DECR_REF(inp);
5325 		}
5326 	}
5327 	/* save away my tag to */
5328 	stc.my_vtag = initack->init.initiate_tag;
5329 
5330 	/* set up some of the credits. */
5331 	so = inp->sctp_socket;
5332 	if (so == NULL) {
5333 		/* memory problem */
5334 		sctp_m_freem(m);
5335 		return;
5336 	} else {
5337 		initack->init.a_rwnd = htonl(max(SCTP_SB_LIMIT_RCV(so), SCTP_MINIMAL_RWND));
5338 	}
5339 	/* set what I want */
5340 	his_limit = ntohs(init_chk->init.num_inbound_streams);
5341 	/* choose what I want */
5342 	if (asoc != NULL) {
5343 		if (asoc->streamoutcnt > inp->sctp_ep.pre_open_stream_count) {
5344 			i_want = asoc->streamoutcnt;
5345 		} else {
5346 			i_want = inp->sctp_ep.pre_open_stream_count;
5347 		}
5348 	} else {
5349 		i_want = inp->sctp_ep.pre_open_stream_count;
5350 	}
5351 	if (his_limit < i_want) {
5352 		/* I Want more :< */
5353 		initack->init.num_outbound_streams = init_chk->init.num_inbound_streams;
5354 	} else {
5355 		/* I can have what I want :> */
5356 		initack->init.num_outbound_streams = htons(i_want);
5357 	}
5358 	/* tell him his limt. */
5359 	initack->init.num_inbound_streams =
5360 	    htons(inp->sctp_ep.max_open_streams_intome);
5361 
5362 	/* adaptation layer indication parameter */
5363 	ali = (struct sctp_adaptation_layer_indication *)((caddr_t)initack + sizeof(*initack));
5364 	ali->ph.param_type = htons(SCTP_ULP_ADAPTATION);
5365 	ali->ph.param_length = htons(sizeof(*ali));
5366 	ali->indication = ntohl(inp->sctp_ep.adaptation_layer_indicator);
5367 	SCTP_BUF_LEN(m) += sizeof(*ali);
5368 	ecn = (struct sctp_ecn_supported_param *)((caddr_t)ali + sizeof(*ali));
5369 
5370 	/* ECN parameter */
5371 	if (SCTP_BASE_SYSCTL(sctp_ecn_enable) == 1) {
5372 		ecn->ph.param_type = htons(SCTP_ECN_CAPABLE);
5373 		ecn->ph.param_length = htons(sizeof(*ecn));
5374 		SCTP_BUF_LEN(m) += sizeof(*ecn);
5375 
5376 		prsctp = (struct sctp_prsctp_supported_param *)((caddr_t)ecn +
5377 		    sizeof(*ecn));
5378 	} else {
5379 		prsctp = (struct sctp_prsctp_supported_param *)((caddr_t)ecn);
5380 	}
5381 	/* And now tell the peer we do  pr-sctp */
5382 	prsctp->ph.param_type = htons(SCTP_PRSCTP_SUPPORTED);
5383 	prsctp->ph.param_length = htons(sizeof(*prsctp));
5384 	SCTP_BUF_LEN(m) += sizeof(*prsctp);
5385 	if (nat_friendly) {
5386 		/* Add NAT friendly parameter */
5387 		struct sctp_paramhdr *ph;
5388 
5389 		ph = (struct sctp_paramhdr *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
5390 		ph->param_type = htons(SCTP_HAS_NAT_SUPPORT);
5391 		ph->param_length = htons(sizeof(struct sctp_paramhdr));
5392 		SCTP_BUF_LEN(m) += sizeof(struct sctp_paramhdr);
5393 	}
5394 	/* And now tell the peer we do all the extensions */
5395 	pr_supported = (struct sctp_supported_chunk_types_param *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
5396 	pr_supported->ph.param_type = htons(SCTP_SUPPORTED_CHUNK_EXT);
5397 	num_ext = 0;
5398 	pr_supported->chunk_types[num_ext++] = SCTP_ASCONF;
5399 	pr_supported->chunk_types[num_ext++] = SCTP_ASCONF_ACK;
5400 	pr_supported->chunk_types[num_ext++] = SCTP_FORWARD_CUM_TSN;
5401 	pr_supported->chunk_types[num_ext++] = SCTP_PACKET_DROPPED;
5402 	pr_supported->chunk_types[num_ext++] = SCTP_STREAM_RESET;
5403 	if (!SCTP_BASE_SYSCTL(sctp_auth_disable))
5404 		pr_supported->chunk_types[num_ext++] = SCTP_AUTHENTICATION;
5405 	/*
5406 	 * EY  if the sysctl variable is set, tell the assoc. initiator that
5407 	 * we do nr_sack
5408 	 */
5409 	if (SCTP_BASE_SYSCTL(sctp_nr_sack_on_off))
5410 		pr_supported->chunk_types[num_ext++] = SCTP_NR_SELECTIVE_ACK;
5411 	p_len = sizeof(*pr_supported) + num_ext;
5412 	pr_supported->ph.param_length = htons(p_len);
5413 	bzero((caddr_t)pr_supported + p_len, SCTP_SIZE32(p_len) - p_len);
5414 	SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
5415 
5416 	/* ECN nonce: And now tell the peer we support ECN nonce */
5417 	if (SCTP_BASE_SYSCTL(sctp_ecn_nonce)) {
5418 		ecn_nonce = (struct sctp_ecn_nonce_supported_param *)
5419 		    ((caddr_t)pr_supported + SCTP_SIZE32(p_len));
5420 		ecn_nonce->ph.param_type = htons(SCTP_ECN_NONCE_SUPPORTED);
5421 		ecn_nonce->ph.param_length = htons(sizeof(*ecn_nonce));
5422 		SCTP_BUF_LEN(m) += sizeof(*ecn_nonce);
5423 	}
5424 	/* add authentication parameters */
5425 	if (!SCTP_BASE_SYSCTL(sctp_auth_disable)) {
5426 		struct sctp_auth_random *randp;
5427 		struct sctp_auth_hmac_algo *hmacs;
5428 		struct sctp_auth_chunk_list *chunks;
5429 		uint16_t random_len;
5430 
5431 		/* generate and add RANDOM parameter */
5432 		random_len = SCTP_AUTH_RANDOM_SIZE_DEFAULT;
5433 		randp = (struct sctp_auth_random *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
5434 		randp->ph.param_type = htons(SCTP_RANDOM);
5435 		p_len = sizeof(*randp) + random_len;
5436 		randp->ph.param_length = htons(p_len);
5437 		SCTP_READ_RANDOM(randp->random_data, random_len);
5438 		/* zero out any padding required */
5439 		bzero((caddr_t)randp + p_len, SCTP_SIZE32(p_len) - p_len);
5440 		SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
5441 
5442 		/* add HMAC_ALGO parameter */
5443 		hmacs = (struct sctp_auth_hmac_algo *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
5444 		p_len = sctp_serialize_hmaclist(inp->sctp_ep.local_hmacs,
5445 		    (uint8_t *) hmacs->hmac_ids);
5446 		if (p_len > 0) {
5447 			p_len += sizeof(*hmacs);
5448 			hmacs->ph.param_type = htons(SCTP_HMAC_LIST);
5449 			hmacs->ph.param_length = htons(p_len);
5450 			/* zero out any padding required */
5451 			bzero((caddr_t)hmacs + p_len, SCTP_SIZE32(p_len) - p_len);
5452 			SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
5453 		}
5454 		/* add CHUNKS parameter */
5455 		chunks = (struct sctp_auth_chunk_list *)(mtod(m, caddr_t)+SCTP_BUF_LEN(m));
5456 		p_len = sctp_serialize_auth_chunks(inp->sctp_ep.local_auth_chunks,
5457 		    chunks->chunk_types);
5458 		if (p_len > 0) {
5459 			p_len += sizeof(*chunks);
5460 			chunks->ph.param_type = htons(SCTP_CHUNK_LIST);
5461 			chunks->ph.param_length = htons(p_len);
5462 			/* zero out any padding required */
5463 			bzero((caddr_t)chunks + p_len, SCTP_SIZE32(p_len) - p_len);
5464 			SCTP_BUF_LEN(m) += SCTP_SIZE32(p_len);
5465 		}
5466 	}
5467 	m_at = m;
5468 	/* now the addresses */
5469 	{
5470 		struct sctp_scoping scp;
5471 
5472 		/*
5473 		 * To optimize this we could put the scoping stuff into a
5474 		 * structure and remove the individual uint8's from the stc
5475 		 * structure. Then we could just sifa in the address within
5476 		 * the stc.. but for now this is a quick hack to get the
5477 		 * address stuff teased apart.
5478 		 */
5479 		scp.ipv4_addr_legal = stc.ipv4_addr_legal;
5480 		scp.ipv6_addr_legal = stc.ipv6_addr_legal;
5481 		scp.loopback_scope = stc.loopback_scope;
5482 		scp.ipv4_local_scope = stc.ipv4_scope;
5483 		scp.local_scope = stc.local_scope;
5484 		scp.site_scope = stc.site_scope;
5485 		m_at = sctp_add_addresses_to_i_ia(inp, &scp, m_at, cnt_inits_to);
5486 	}
5487 
5488 	/* tack on the operational error if present */
5489 	if (op_err) {
5490 		struct mbuf *ol;
5491 		int llen;
5492 
5493 		llen = 0;
5494 		ol = op_err;
5495 		while (ol) {
5496 			llen += SCTP_BUF_LEN(ol);
5497 			ol = SCTP_BUF_NEXT(ol);
5498 		}
5499 		if (llen % 4) {
5500 			/* must add a pad to the param */
5501 			uint32_t cpthis = 0;
5502 			int padlen;
5503 
5504 			padlen = 4 - (llen % 4);
5505 			m_copyback(op_err, llen, padlen, (caddr_t)&cpthis);
5506 		}
5507 		while (SCTP_BUF_NEXT(m_at) != NULL) {
5508 			m_at = SCTP_BUF_NEXT(m_at);
5509 		}
5510 		SCTP_BUF_NEXT(m_at) = op_err;
5511 		while (SCTP_BUF_NEXT(m_at) != NULL) {
5512 			m_at = SCTP_BUF_NEXT(m_at);
5513 		}
5514 	}
5515 	/* pre-calulate the size and update pkt header and chunk header */
5516 	p_len = 0;
5517 	for (m_tmp = m; m_tmp; m_tmp = SCTP_BUF_NEXT(m_tmp)) {
5518 		p_len += SCTP_BUF_LEN(m_tmp);
5519 		if (SCTP_BUF_NEXT(m_tmp) == NULL) {
5520 			/* m_tmp should now point to last one */
5521 			break;
5522 		}
5523 	}
5524 
5525 	/* Now we must build a cookie */
5526 	m_cookie = sctp_add_cookie(inp, init_pkt, offset, m, 0, &stc, &signature);
5527 	if (m_cookie == NULL) {
5528 		/* memory problem */
5529 		sctp_m_freem(m);
5530 		return;
5531 	}
5532 	/* Now append the cookie to the end and update the space/size */
5533 	SCTP_BUF_NEXT(m_tmp) = m_cookie;
5534 
5535 	for (m_tmp = m_cookie; m_tmp; m_tmp = SCTP_BUF_NEXT(m_tmp)) {
5536 		p_len += SCTP_BUF_LEN(m_tmp);
5537 		if (SCTP_BUF_NEXT(m_tmp) == NULL) {
5538 			/* m_tmp should now point to last one */
5539 			mp_last = m_tmp;
5540 			break;
5541 		}
5542 	}
5543 	/*
5544 	 * Place in the size, but we don't include the last pad (if any) in
5545 	 * the INIT-ACK.
5546 	 */
5547 	initack->ch.chunk_length = htons(p_len);
5548 
5549 	/*
5550 	 * Time to sign the cookie, we don't sign over the cookie signature
5551 	 * though thus we set trailer.
5552 	 */
5553 	(void)sctp_hmac_m(SCTP_HMAC,
5554 	    (uint8_t *) inp->sctp_ep.secret_key[(int)(inp->sctp_ep.current_secret_number)],
5555 	    SCTP_SECRET_SIZE, m_cookie, sizeof(struct sctp_paramhdr),
5556 	    (uint8_t *) signature, SCTP_SIGNATURE_SIZE);
5557 	/*
5558 	 * We sifa 0 here to NOT set IP_DF if its IPv4, we ignore the return
5559 	 * here since the timer will drive a retranmission.
5560 	 */
5561 	padval = p_len % 4;
5562 	if ((padval) && (mp_last)) {
5563 		/* see my previous comments on mp_last */
5564 		int ret;
5565 
5566 		ret = sctp_add_pad_tombuf(mp_last, (4 - padval));
5567 		if (ret) {
5568 			/* Houston we have a problem, no space */
5569 			sctp_m_freem(m);
5570 			return;
5571 		}
5572 		p_len += padval;
5573 	}
5574 	if (stc.loopback_scope) {
5575 		over_addr = &store1;
5576 	} else {
5577 		over_addr = NULL;
5578 	}
5579 
5580 	(void)sctp_lowlevel_chunk_output(inp, NULL, NULL, to, m, 0, NULL, 0, 0,
5581 	    0, NULL, 0,
5582 	    inp->sctp_lport, sh->src_port, init_chk->init.initiate_tag,
5583 	    port, SCTP_SO_NOT_LOCKED, over_addr);
5584 	SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
5585 }
5586 
5587 
5588 void
5589 sctp_insert_on_wheel(struct sctp_tcb *stcb,
5590     struct sctp_association *asoc,
5591     struct sctp_stream_out *strq, int holds_lock)
5592 {
5593 	if (holds_lock == 0) {
5594 		SCTP_TCB_SEND_LOCK(stcb);
5595 	}
5596 	if ((strq->next_spoke.tqe_next == NULL) &&
5597 	    (strq->next_spoke.tqe_prev == NULL)) {
5598 		TAILQ_INSERT_TAIL(&asoc->out_wheel, strq, next_spoke);
5599 	}
5600 	if (holds_lock == 0) {
5601 		SCTP_TCB_SEND_UNLOCK(stcb);
5602 	}
5603 }
5604 
5605 void
5606 sctp_remove_from_wheel(struct sctp_tcb *stcb,
5607     struct sctp_association *asoc,
5608     struct sctp_stream_out *strq,
5609     int holds_lock)
5610 {
5611 	/* take off and then setup so we know it is not on the wheel */
5612 	if (holds_lock == 0) {
5613 		SCTP_TCB_SEND_LOCK(stcb);
5614 	}
5615 	if (TAILQ_EMPTY(&strq->outqueue)) {
5616 		if (asoc->last_out_stream == strq) {
5617 			asoc->last_out_stream = TAILQ_PREV(asoc->last_out_stream, sctpwheel_listhead, next_spoke);
5618 			if (asoc->last_out_stream == NULL) {
5619 				asoc->last_out_stream = TAILQ_LAST(&asoc->out_wheel, sctpwheel_listhead);
5620 			}
5621 			if (asoc->last_out_stream == strq) {
5622 				asoc->last_out_stream = NULL;
5623 			}
5624 		}
5625 		TAILQ_REMOVE(&asoc->out_wheel, strq, next_spoke);
5626 		strq->next_spoke.tqe_next = NULL;
5627 		strq->next_spoke.tqe_prev = NULL;
5628 	}
5629 	if (holds_lock == 0) {
5630 		SCTP_TCB_SEND_UNLOCK(stcb);
5631 	}
5632 }
5633 
5634 static void
5635 sctp_prune_prsctp(struct sctp_tcb *stcb,
5636     struct sctp_association *asoc,
5637     struct sctp_sndrcvinfo *srcv,
5638     int dataout)
5639 {
5640 	int freed_spc = 0;
5641 	struct sctp_tmit_chunk *chk, *nchk;
5642 
5643 	SCTP_TCB_LOCK_ASSERT(stcb);
5644 	if ((asoc->peer_supports_prsctp) &&
5645 	    (asoc->sent_queue_cnt_removeable > 0)) {
5646 		TAILQ_FOREACH(chk, &asoc->sent_queue, sctp_next) {
5647 			/*
5648 			 * Look for chunks marked with the PR_SCTP flag AND
5649 			 * the buffer space flag. If the one being sent is
5650 			 * equal or greater priority then purge the old one
5651 			 * and free some space.
5652 			 */
5653 			if (PR_SCTP_BUF_ENABLED(chk->flags)) {
5654 				/*
5655 				 * This one is PR-SCTP AND buffer space
5656 				 * limited type
5657 				 */
5658 				if (chk->rec.data.timetodrop.tv_sec >= (long)srcv->sinfo_timetolive) {
5659 					/*
5660 					 * Lower numbers equates to higher
5661 					 * priority so if the one we are
5662 					 * looking at has a larger or equal
5663 					 * priority we want to drop the data
5664 					 * and NOT retransmit it.
5665 					 */
5666 					if (chk->data) {
5667 						/*
5668 						 * We release the book_size
5669 						 * if the mbuf is here
5670 						 */
5671 						int ret_spc;
5672 						int cause;
5673 
5674 						if (chk->sent > SCTP_DATAGRAM_UNSENT)
5675 							cause = SCTP_RESPONSE_TO_USER_REQ | SCTP_NOTIFY_DATAGRAM_SENT;
5676 						else
5677 							cause = SCTP_RESPONSE_TO_USER_REQ | SCTP_NOTIFY_DATAGRAM_UNSENT;
5678 						ret_spc = sctp_release_pr_sctp_chunk(stcb, chk,
5679 						    cause,
5680 						    SCTP_SO_LOCKED);
5681 						freed_spc += ret_spc;
5682 						if (freed_spc >= dataout) {
5683 							return;
5684 						}
5685 					}	/* if chunk was present */
5686 				}	/* if of sufficent priority */
5687 			}	/* if chunk has enabled */
5688 		}		/* tailqforeach */
5689 
5690 		chk = TAILQ_FIRST(&asoc->send_queue);
5691 		while (chk) {
5692 			nchk = TAILQ_NEXT(chk, sctp_next);
5693 			/* Here we must move to the sent queue and mark */
5694 			if (PR_SCTP_TTL_ENABLED(chk->flags)) {
5695 				if (chk->rec.data.timetodrop.tv_sec >= (long)srcv->sinfo_timetolive) {
5696 					if (chk->data) {
5697 						/*
5698 						 * We release the book_size
5699 						 * if the mbuf is here
5700 						 */
5701 						int ret_spc;
5702 
5703 						ret_spc = sctp_release_pr_sctp_chunk(stcb, chk,
5704 						    SCTP_RESPONSE_TO_USER_REQ | SCTP_NOTIFY_DATAGRAM_UNSENT,
5705 						    SCTP_SO_LOCKED);
5706 
5707 						freed_spc += ret_spc;
5708 						if (freed_spc >= dataout) {
5709 							return;
5710 						}
5711 					}	/* end if chk->data */
5712 				}	/* end if right class */
5713 			}	/* end if chk pr-sctp */
5714 			chk = nchk;
5715 		}		/* end while (chk) */
5716 	}			/* if enabled in asoc */
5717 }
5718 
5719 int
5720 sctp_get_frag_point(struct sctp_tcb *stcb,
5721     struct sctp_association *asoc)
5722 {
5723 	int siz, ovh;
5724 
5725 	/*
5726 	 * For endpoints that have both v6 and v4 addresses we must reserve
5727 	 * room for the ipv6 header, for those that are only dealing with V4
5728 	 * we use a larger frag point.
5729 	 */
5730 	if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
5731 		ovh = SCTP_MED_OVERHEAD;
5732 	} else {
5733 		ovh = SCTP_MED_V4_OVERHEAD;
5734 	}
5735 
5736 	if (stcb->asoc.sctp_frag_point > asoc->smallest_mtu)
5737 		siz = asoc->smallest_mtu - ovh;
5738 	else
5739 		siz = (stcb->asoc.sctp_frag_point - ovh);
5740 	/*
5741 	 * if (siz > (MCLBYTES-sizeof(struct sctp_data_chunk))) {
5742 	 */
5743 	/* A data chunk MUST fit in a cluster */
5744 	/* siz = (MCLBYTES - sizeof(struct sctp_data_chunk)); */
5745 	/* } */
5746 
5747 	/* adjust for an AUTH chunk if DATA requires auth */
5748 	if (sctp_auth_is_required_chunk(SCTP_DATA, stcb->asoc.peer_auth_chunks))
5749 		siz -= sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
5750 
5751 	if (siz % 4) {
5752 		/* make it an even word boundary please */
5753 		siz -= (siz % 4);
5754 	}
5755 	return (siz);
5756 }
5757 
5758 static void
5759 sctp_set_prsctp_policy(struct sctp_stream_queue_pending *sp)
5760 {
5761 	sp->pr_sctp_on = 0;
5762 	/*
5763 	 * We assume that the user wants PR_SCTP_TTL if the user provides a
5764 	 * positive lifetime but does not specify any PR_SCTP policy. This
5765 	 * is a BAD assumption and causes problems at least with the
5766 	 * U-Vancovers MPI folks. I will change this to be no policy means
5767 	 * NO PR-SCTP.
5768 	 */
5769 	if (PR_SCTP_ENABLED(sp->sinfo_flags)) {
5770 		sp->act_flags |= PR_SCTP_POLICY(sp->sinfo_flags);
5771 		sp->pr_sctp_on = 1;
5772 	} else {
5773 		return;
5774 	}
5775 	switch (PR_SCTP_POLICY(sp->sinfo_flags)) {
5776 	case CHUNK_FLAGS_PR_SCTP_BUF:
5777 		/*
5778 		 * Time to live is a priority stored in tv_sec when doing
5779 		 * the buffer drop thing.
5780 		 */
5781 		sp->ts.tv_sec = sp->timetolive;
5782 		sp->ts.tv_usec = 0;
5783 		break;
5784 	case CHUNK_FLAGS_PR_SCTP_TTL:
5785 		{
5786 			struct timeval tv;
5787 
5788 			(void)SCTP_GETTIME_TIMEVAL(&sp->ts);
5789 			tv.tv_sec = sp->timetolive / 1000;
5790 			tv.tv_usec = (sp->timetolive * 1000) % 1000000;
5791 			/*
5792 			 * TODO sctp_constants.h needs alternative time
5793 			 * macros when _KERNEL is undefined.
5794 			 */
5795 			timevaladd(&sp->ts, &tv);
5796 		}
5797 		break;
5798 	case CHUNK_FLAGS_PR_SCTP_RTX:
5799 		/*
5800 		 * Time to live is a the number or retransmissions stored in
5801 		 * tv_sec.
5802 		 */
5803 		sp->ts.tv_sec = sp->timetolive;
5804 		sp->ts.tv_usec = 0;
5805 		break;
5806 	default:
5807 		SCTPDBG(SCTP_DEBUG_USRREQ1,
5808 		    "Unknown PR_SCTP policy %u.\n",
5809 		    PR_SCTP_POLICY(sp->sinfo_flags));
5810 		break;
5811 	}
5812 }
5813 
5814 static int
5815 sctp_msg_append(struct sctp_tcb *stcb,
5816     struct sctp_nets *net,
5817     struct mbuf *m,
5818     struct sctp_sndrcvinfo *srcv, int hold_stcb_lock)
5819 {
5820 	int error = 0, holds_lock;
5821 	struct mbuf *at;
5822 	struct sctp_stream_queue_pending *sp = NULL;
5823 	struct sctp_stream_out *strm;
5824 
5825 	/*
5826 	 * Given an mbuf chain, put it into the association send queue and
5827 	 * place it on the wheel
5828 	 */
5829 	holds_lock = hold_stcb_lock;
5830 	if (srcv->sinfo_stream >= stcb->asoc.streamoutcnt) {
5831 		/* Invalid stream number */
5832 		SCTP_LTRACE_ERR_RET_PKT(m, NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
5833 		error = EINVAL;
5834 		goto out_now;
5835 	}
5836 	if ((stcb->asoc.stream_locked) &&
5837 	    (stcb->asoc.stream_locked_on != srcv->sinfo_stream)) {
5838 		SCTP_LTRACE_ERR_RET_PKT(m, NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
5839 		error = EINVAL;
5840 		goto out_now;
5841 	}
5842 	strm = &stcb->asoc.strmout[srcv->sinfo_stream];
5843 	/* Now can we send this? */
5844 	if ((SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
5845 	    (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
5846 	    (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
5847 	    (stcb->asoc.state & SCTP_STATE_SHUTDOWN_PENDING)) {
5848 		/* got data while shutting down */
5849 		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ECONNRESET);
5850 		error = ECONNRESET;
5851 		goto out_now;
5852 	}
5853 	sctp_alloc_a_strmoq(stcb, sp);
5854 	if (sp == NULL) {
5855 		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
5856 		error = ENOMEM;
5857 		goto out_now;
5858 	}
5859 	sp->sinfo_flags = srcv->sinfo_flags;
5860 	sp->timetolive = srcv->sinfo_timetolive;
5861 	sp->ppid = srcv->sinfo_ppid;
5862 	sp->context = srcv->sinfo_context;
5863 	sp->strseq = 0;
5864 	if (sp->sinfo_flags & SCTP_ADDR_OVER) {
5865 		sp->net = net;
5866 	} else {
5867 		sp->net = stcb->asoc.primary_destination;
5868 	}
5869 	atomic_add_int(&sp->net->ref_count, 1);
5870 	(void)SCTP_GETTIME_TIMEVAL(&sp->ts);
5871 	sp->stream = srcv->sinfo_stream;
5872 	sp->msg_is_complete = 1;
5873 	sp->sender_all_done = 1;
5874 	sp->some_taken = 0;
5875 	sp->data = m;
5876 	sp->tail_mbuf = NULL;
5877 	sp->length = 0;
5878 	at = m;
5879 	sctp_set_prsctp_policy(sp);
5880 	/*
5881 	 * We could in theory (for sendall) sifa the length in, but we would
5882 	 * still have to hunt through the chain since we need to setup the
5883 	 * tail_mbuf
5884 	 */
5885 	while (at) {
5886 		if (SCTP_BUF_NEXT(at) == NULL)
5887 			sp->tail_mbuf = at;
5888 		sp->length += SCTP_BUF_LEN(at);
5889 		at = SCTP_BUF_NEXT(at);
5890 	}
5891 	SCTP_TCB_SEND_LOCK(stcb);
5892 	sctp_snd_sb_alloc(stcb, sp->length);
5893 	atomic_add_int(&stcb->asoc.stream_queue_cnt, 1);
5894 	TAILQ_INSERT_TAIL(&strm->outqueue, sp, next);
5895 	if ((srcv->sinfo_flags & SCTP_UNORDERED) == 0) {
5896 		sp->strseq = strm->next_sequence_sent;
5897 		strm->next_sequence_sent++;
5898 	}
5899 	if ((strm->next_spoke.tqe_next == NULL) &&
5900 	    (strm->next_spoke.tqe_prev == NULL)) {
5901 		/* Not on wheel, insert */
5902 		sctp_insert_on_wheel(stcb, &stcb->asoc, strm, 1);
5903 	}
5904 	m = NULL;
5905 	SCTP_TCB_SEND_UNLOCK(stcb);
5906 out_now:
5907 	if (m) {
5908 		sctp_m_freem(m);
5909 	}
5910 	return (error);
5911 }
5912 
5913 
5914 static struct mbuf *
5915 sctp_copy_mbufchain(struct mbuf *clonechain,
5916     struct mbuf *outchain,
5917     struct mbuf **endofchain,
5918     int can_take_mbuf,
5919     int sizeofcpy,
5920     uint8_t copy_by_ref)
5921 {
5922 	struct mbuf *m;
5923 	struct mbuf *appendchain;
5924 	caddr_t cp;
5925 	int len;
5926 
5927 	if (endofchain == NULL) {
5928 		/* error */
5929 error_out:
5930 		if (outchain)
5931 			sctp_m_freem(outchain);
5932 		return (NULL);
5933 	}
5934 	if (can_take_mbuf) {
5935 		appendchain = clonechain;
5936 	} else {
5937 		if (!copy_by_ref &&
5938 		    (sizeofcpy <= (int)((((SCTP_BASE_SYSCTL(sctp_mbuf_threshold_count) - 1) * MLEN) + MHLEN)))
5939 		    ) {
5940 			/* Its not in a cluster */
5941 			if (*endofchain == NULL) {
5942 				/* lets get a mbuf cluster */
5943 				if (outchain == NULL) {
5944 					/* This is the general case */
5945 			new_mbuf:
5946 					outchain = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_HEADER);
5947 					if (outchain == NULL) {
5948 						goto error_out;
5949 					}
5950 					SCTP_BUF_LEN(outchain) = 0;
5951 					*endofchain = outchain;
5952 					/* get the prepend space */
5953 					SCTP_BUF_RESV_UF(outchain, (SCTP_FIRST_MBUF_RESV + 4));
5954 				} else {
5955 					/*
5956 					 * We really should not get a NULL
5957 					 * in endofchain
5958 					 */
5959 					/* find end */
5960 					m = outchain;
5961 					while (m) {
5962 						if (SCTP_BUF_NEXT(m) == NULL) {
5963 							*endofchain = m;
5964 							break;
5965 						}
5966 						m = SCTP_BUF_NEXT(m);
5967 					}
5968 					/* sanity */
5969 					if (*endofchain == NULL) {
5970 						/*
5971 						 * huh, TSNH XXX maybe we
5972 						 * should panic
5973 						 */
5974 						sctp_m_freem(outchain);
5975 						goto new_mbuf;
5976 					}
5977 				}
5978 				/* get the new end of length */
5979 				len = M_TRAILINGSPACE(*endofchain);
5980 			} else {
5981 				/* how much is left at the end? */
5982 				len = M_TRAILINGSPACE(*endofchain);
5983 			}
5984 			/* Find the end of the data, for appending */
5985 			cp = (mtod((*endofchain), caddr_t)+SCTP_BUF_LEN((*endofchain)));
5986 
5987 			/* Now lets copy it out */
5988 			if (len >= sizeofcpy) {
5989 				/* It all fits, copy it in */
5990 				m_copydata(clonechain, 0, sizeofcpy, cp);
5991 				SCTP_BUF_LEN((*endofchain)) += sizeofcpy;
5992 			} else {
5993 				/* fill up the end of the chain */
5994 				if (len > 0) {
5995 					m_copydata(clonechain, 0, len, cp);
5996 					SCTP_BUF_LEN((*endofchain)) += len;
5997 					/* now we need another one */
5998 					sizeofcpy -= len;
5999 				}
6000 				m = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_HEADER);
6001 				if (m == NULL) {
6002 					/* We failed */
6003 					goto error_out;
6004 				}
6005 				SCTP_BUF_NEXT((*endofchain)) = m;
6006 				*endofchain = m;
6007 				cp = mtod((*endofchain), caddr_t);
6008 				m_copydata(clonechain, len, sizeofcpy, cp);
6009 				SCTP_BUF_LEN((*endofchain)) += sizeofcpy;
6010 			}
6011 			return (outchain);
6012 		} else {
6013 			/* copy the old fashion way */
6014 			appendchain = SCTP_M_COPYM(clonechain, 0, M_COPYALL, M_DONTWAIT);
6015 #ifdef SCTP_MBUF_LOGGING
6016 			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
6017 				struct mbuf *mat;
6018 
6019 				mat = appendchain;
6020 				while (mat) {
6021 					if (SCTP_BUF_IS_EXTENDED(mat)) {
6022 						sctp_log_mb(mat, SCTP_MBUF_ICOPY);
6023 					}
6024 					mat = SCTP_BUF_NEXT(mat);
6025 				}
6026 			}
6027 #endif
6028 		}
6029 	}
6030 	if (appendchain == NULL) {
6031 		/* error */
6032 		if (outchain)
6033 			sctp_m_freem(outchain);
6034 		return (NULL);
6035 	}
6036 	if (outchain) {
6037 		/* tack on to the end */
6038 		if (*endofchain != NULL) {
6039 			SCTP_BUF_NEXT(((*endofchain))) = appendchain;
6040 		} else {
6041 			m = outchain;
6042 			while (m) {
6043 				if (SCTP_BUF_NEXT(m) == NULL) {
6044 					SCTP_BUF_NEXT(m) = appendchain;
6045 					break;
6046 				}
6047 				m = SCTP_BUF_NEXT(m);
6048 			}
6049 		}
6050 		/*
6051 		 * save off the end and update the end-chain postion
6052 		 */
6053 		m = appendchain;
6054 		while (m) {
6055 			if (SCTP_BUF_NEXT(m) == NULL) {
6056 				*endofchain = m;
6057 				break;
6058 			}
6059 			m = SCTP_BUF_NEXT(m);
6060 		}
6061 		return (outchain);
6062 	} else {
6063 		/* save off the end and update the end-chain postion */
6064 		m = appendchain;
6065 		while (m) {
6066 			if (SCTP_BUF_NEXT(m) == NULL) {
6067 				*endofchain = m;
6068 				break;
6069 			}
6070 			m = SCTP_BUF_NEXT(m);
6071 		}
6072 		return (appendchain);
6073 	}
6074 }
6075 
6076 int
6077 sctp_med_chunk_output(struct sctp_inpcb *inp,
6078     struct sctp_tcb *stcb,
6079     struct sctp_association *asoc,
6080     int *num_out,
6081     int *reason_code,
6082     int control_only, int from_where,
6083     struct timeval *now, int *now_filled, int frag_point, int so_locked
6084 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
6085     SCTP_UNUSED
6086 #endif
6087 );
6088 
6089 static void
6090 sctp_sendall_iterator(struct sctp_inpcb *inp, struct sctp_tcb *stcb, void *ptr,
6091     uint32_t val)
6092 {
6093 	struct sctp_copy_all *ca;
6094 	struct mbuf *m;
6095 	int ret = 0;
6096 	int added_control = 0;
6097 	int un_sent, do_chunk_output = 1;
6098 	struct sctp_association *asoc;
6099 
6100 	ca = (struct sctp_copy_all *)ptr;
6101 	if (ca->m == NULL) {
6102 		return;
6103 	}
6104 	if (ca->inp != inp) {
6105 		/* TSNH */
6106 		return;
6107 	}
6108 	if ((ca->m) && ca->sndlen) {
6109 		m = SCTP_M_COPYM(ca->m, 0, M_COPYALL, M_DONTWAIT);
6110 		if (m == NULL) {
6111 			/* can't copy so we are done */
6112 			ca->cnt_failed++;
6113 			return;
6114 		}
6115 #ifdef SCTP_MBUF_LOGGING
6116 		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
6117 			struct mbuf *mat;
6118 
6119 			mat = m;
6120 			while (mat) {
6121 				if (SCTP_BUF_IS_EXTENDED(mat)) {
6122 					sctp_log_mb(mat, SCTP_MBUF_ICOPY);
6123 				}
6124 				mat = SCTP_BUF_NEXT(mat);
6125 			}
6126 		}
6127 #endif
6128 	} else {
6129 		m = NULL;
6130 	}
6131 	SCTP_TCB_LOCK_ASSERT(stcb);
6132 	if (ca->sndrcv.sinfo_flags & SCTP_ABORT) {
6133 		/* Abort this assoc with m as the user defined reason */
6134 		if (m) {
6135 			struct sctp_paramhdr *ph;
6136 
6137 			SCTP_BUF_PREPEND(m, sizeof(struct sctp_paramhdr), M_DONTWAIT);
6138 			if (m) {
6139 				ph = mtod(m, struct sctp_paramhdr *);
6140 				ph->param_type = htons(SCTP_CAUSE_USER_INITIATED_ABT);
6141 				ph->param_length = htons(ca->sndlen);
6142 			}
6143 			/*
6144 			 * We add one here to keep the assoc from
6145 			 * dis-appearing on us.
6146 			 */
6147 			atomic_add_int(&stcb->asoc.refcnt, 1);
6148 			sctp_abort_an_association(inp, stcb,
6149 			    SCTP_RESPONSE_TO_USER_REQ,
6150 			    m, SCTP_SO_NOT_LOCKED);
6151 			/*
6152 			 * sctp_abort_an_association calls sctp_free_asoc()
6153 			 * free association will NOT free it since we
6154 			 * incremented the refcnt .. we do this to prevent
6155 			 * it being freed and things getting tricky since we
6156 			 * could end up (from free_asoc) calling inpcb_free
6157 			 * which would get a recursive lock call to the
6158 			 * iterator lock.. But as a consequence of that the
6159 			 * stcb will return to us un-locked.. since
6160 			 * free_asoc returns with either no TCB or the TCB
6161 			 * unlocked, we must relock.. to unlock in the
6162 			 * iterator timer :-0
6163 			 */
6164 			SCTP_TCB_LOCK(stcb);
6165 			atomic_add_int(&stcb->asoc.refcnt, -1);
6166 			goto no_chunk_output;
6167 		}
6168 	} else {
6169 		if (m) {
6170 			ret = sctp_msg_append(stcb, stcb->asoc.primary_destination, m,
6171 			    &ca->sndrcv, 1);
6172 		}
6173 		asoc = &stcb->asoc;
6174 		if (ca->sndrcv.sinfo_flags & SCTP_EOF) {
6175 			/* shutdown this assoc */
6176 			int cnt;
6177 
6178 			cnt = sctp_is_there_unsent_data(stcb);
6179 
6180 			if (TAILQ_EMPTY(&asoc->send_queue) &&
6181 			    TAILQ_EMPTY(&asoc->sent_queue) &&
6182 			    (cnt == 0)) {
6183 				if (asoc->locked_on_sending) {
6184 					goto abort_anyway;
6185 				}
6186 				/*
6187 				 * there is nothing queued to send, so I'm
6188 				 * done...
6189 				 */
6190 				if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
6191 				    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
6192 				    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
6193 					/*
6194 					 * only send SHUTDOWN the first time
6195 					 * through
6196 					 */
6197 					sctp_send_shutdown(stcb, stcb->asoc.primary_destination);
6198 					if (SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) {
6199 						SCTP_STAT_DECR_GAUGE32(sctps_currestab);
6200 					}
6201 					SCTP_SET_STATE(asoc, SCTP_STATE_SHUTDOWN_SENT);
6202 					SCTP_CLEAR_SUBSTATE(asoc, SCTP_STATE_SHUTDOWN_PENDING);
6203 					sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, stcb->sctp_ep, stcb,
6204 					    asoc->primary_destination);
6205 					sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
6206 					    asoc->primary_destination);
6207 					added_control = 1;
6208 					do_chunk_output = 0;
6209 				}
6210 			} else {
6211 				/*
6212 				 * we still got (or just got) data to send,
6213 				 * so set SHUTDOWN_PENDING
6214 				 */
6215 				/*
6216 				 * XXX sockets draft says that SCTP_EOF
6217 				 * should be sent with no data.  currently,
6218 				 * we will allow user data to be sent first
6219 				 * and move to SHUTDOWN-PENDING
6220 				 */
6221 				if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
6222 				    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
6223 				    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
6224 					if (asoc->locked_on_sending) {
6225 						/*
6226 						 * Locked to send out the
6227 						 * data
6228 						 */
6229 						struct sctp_stream_queue_pending *sp;
6230 
6231 						sp = TAILQ_LAST(&asoc->locked_on_sending->outqueue, sctp_streamhead);
6232 						if (sp) {
6233 							if ((sp->length == 0) && (sp->msg_is_complete == 0))
6234 								asoc->state |= SCTP_STATE_PARTIAL_MSG_LEFT;
6235 						}
6236 					}
6237 					asoc->state |= SCTP_STATE_SHUTDOWN_PENDING;
6238 					if (TAILQ_EMPTY(&asoc->send_queue) &&
6239 					    TAILQ_EMPTY(&asoc->sent_queue) &&
6240 					    (asoc->state & SCTP_STATE_PARTIAL_MSG_LEFT)) {
6241 				abort_anyway:
6242 						atomic_add_int(&stcb->asoc.refcnt, 1);
6243 						sctp_abort_an_association(stcb->sctp_ep, stcb,
6244 						    SCTP_RESPONSE_TO_USER_REQ,
6245 						    NULL, SCTP_SO_NOT_LOCKED);
6246 						atomic_add_int(&stcb->asoc.refcnt, -1);
6247 						goto no_chunk_output;
6248 					}
6249 					sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
6250 					    asoc->primary_destination);
6251 				}
6252 			}
6253 
6254 		}
6255 	}
6256 	un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
6257 	    (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
6258 
6259 	if ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY)) &&
6260 	    (stcb->asoc.total_flight > 0) &&
6261 	    (un_sent < (int)(stcb->asoc.smallest_mtu - SCTP_MIN_OVERHEAD))
6262 	    ) {
6263 		do_chunk_output = 0;
6264 	}
6265 	if (do_chunk_output)
6266 		sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_USR_SEND, SCTP_SO_NOT_LOCKED);
6267 	else if (added_control) {
6268 		int num_out = 0, reason = 0, now_filled = 0;
6269 		struct timeval now;
6270 		int frag_point;
6271 
6272 		frag_point = sctp_get_frag_point(stcb, &stcb->asoc);
6273 		(void)sctp_med_chunk_output(inp, stcb, &stcb->asoc, &num_out,
6274 		    &reason, 1, 1, &now, &now_filled, frag_point, SCTP_SO_NOT_LOCKED);
6275 	}
6276 no_chunk_output:
6277 	if (ret) {
6278 		ca->cnt_failed++;
6279 	} else {
6280 		ca->cnt_sent++;
6281 	}
6282 }
6283 
6284 static void
6285 sctp_sendall_completes(void *ptr, uint32_t val)
6286 {
6287 	struct sctp_copy_all *ca;
6288 
6289 	ca = (struct sctp_copy_all *)ptr;
6290 	/*
6291 	 * Do a notify here? Kacheong suggests that the notify be done at
6292 	 * the send time.. so you would push up a notification if any send
6293 	 * failed. Don't know if this is feasable since the only failures we
6294 	 * have is "memory" related and if you cannot get an mbuf to send
6295 	 * the data you surely can't get an mbuf to send up to notify the
6296 	 * user you can't send the data :->
6297 	 */
6298 
6299 	/* now free everything */
6300 	sctp_m_freem(ca->m);
6301 	SCTP_FREE(ca, SCTP_M_COPYAL);
6302 }
6303 
6304 
6305 #define	MC_ALIGN(m, len) do {						\
6306 	SCTP_BUF_RESV_UF(m, ((MCLBYTES - (len)) & ~(sizeof(long) - 1));	\
6307 } while (0)
6308 
6309 
6310 
6311 static struct mbuf *
6312 sctp_copy_out_all(struct uio *uio, int len)
6313 {
6314 	struct mbuf *ret, *at;
6315 	int left, willcpy, cancpy, error;
6316 
6317 	ret = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_WAIT, 1, MT_DATA);
6318 	if (ret == NULL) {
6319 		/* TSNH */
6320 		return (NULL);
6321 	}
6322 	left = len;
6323 	SCTP_BUF_LEN(ret) = 0;
6324 	/* save space for the data chunk header */
6325 	cancpy = M_TRAILINGSPACE(ret);
6326 	willcpy = min(cancpy, left);
6327 	at = ret;
6328 	while (left > 0) {
6329 		/* Align data to the end */
6330 		error = uiomove(mtod(at, caddr_t), willcpy, uio);
6331 		if (error) {
6332 	err_out_now:
6333 			sctp_m_freem(at);
6334 			return (NULL);
6335 		}
6336 		SCTP_BUF_LEN(at) = willcpy;
6337 		SCTP_BUF_NEXT_PKT(at) = SCTP_BUF_NEXT(at) = 0;
6338 		left -= willcpy;
6339 		if (left > 0) {
6340 			SCTP_BUF_NEXT(at) = sctp_get_mbuf_for_msg(left, 0, M_WAIT, 1, MT_DATA);
6341 			if (SCTP_BUF_NEXT(at) == NULL) {
6342 				goto err_out_now;
6343 			}
6344 			at = SCTP_BUF_NEXT(at);
6345 			SCTP_BUF_LEN(at) = 0;
6346 			cancpy = M_TRAILINGSPACE(at);
6347 			willcpy = min(cancpy, left);
6348 		}
6349 	}
6350 	return (ret);
6351 }
6352 
6353 static int
6354 sctp_sendall(struct sctp_inpcb *inp, struct uio *uio, struct mbuf *m,
6355     struct sctp_sndrcvinfo *srcv)
6356 {
6357 	int ret;
6358 	struct sctp_copy_all *ca;
6359 
6360 	SCTP_MALLOC(ca, struct sctp_copy_all *, sizeof(struct sctp_copy_all),
6361 	    SCTP_M_COPYAL);
6362 	if (ca == NULL) {
6363 		sctp_m_freem(m);
6364 		SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
6365 		return (ENOMEM);
6366 	}
6367 	memset(ca, 0, sizeof(struct sctp_copy_all));
6368 
6369 	ca->inp = inp;
6370 	memcpy(&ca->sndrcv, srcv, sizeof(struct sctp_nonpad_sndrcvinfo));
6371 	/*
6372 	 * take off the sendall flag, it would be bad if we failed to do
6373 	 * this :-0
6374 	 */
6375 	ca->sndrcv.sinfo_flags &= ~SCTP_SENDALL;
6376 	/* get length and mbuf chain */
6377 	if (uio) {
6378 		ca->sndlen = uio->uio_resid;
6379 		ca->m = sctp_copy_out_all(uio, ca->sndlen);
6380 		if (ca->m == NULL) {
6381 			SCTP_FREE(ca, SCTP_M_COPYAL);
6382 			SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
6383 			return (ENOMEM);
6384 		}
6385 	} else {
6386 		/* Gather the length of the send */
6387 		struct mbuf *mat;
6388 
6389 		mat = m;
6390 		ca->sndlen = 0;
6391 		while (m) {
6392 			ca->sndlen += SCTP_BUF_LEN(m);
6393 			m = SCTP_BUF_NEXT(m);
6394 		}
6395 		ca->m = mat;
6396 	}
6397 	ret = sctp_initiate_iterator(NULL, sctp_sendall_iterator, NULL,
6398 	    SCTP_PCB_ANY_FLAGS, SCTP_PCB_ANY_FEATURES,
6399 	    SCTP_ASOC_ANY_STATE,
6400 	    (void *)ca, 0,
6401 	    sctp_sendall_completes, inp, 1);
6402 	if (ret) {
6403 		SCTP_PRINTF("Failed to initiate iterator for sendall\n");
6404 		SCTP_FREE(ca, SCTP_M_COPYAL);
6405 		SCTP_LTRACE_ERR_RET_PKT(m, inp, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, EFAULT);
6406 		return (EFAULT);
6407 	}
6408 	return (0);
6409 }
6410 
6411 
6412 void
6413 sctp_toss_old_cookies(struct sctp_tcb *stcb, struct sctp_association *asoc)
6414 {
6415 	struct sctp_tmit_chunk *chk, *nchk;
6416 
6417 	chk = TAILQ_FIRST(&asoc->control_send_queue);
6418 	while (chk) {
6419 		nchk = TAILQ_NEXT(chk, sctp_next);
6420 		if (chk->rec.chunk_id.id == SCTP_COOKIE_ECHO) {
6421 			TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
6422 			if (chk->data) {
6423 				sctp_m_freem(chk->data);
6424 				chk->data = NULL;
6425 			}
6426 			asoc->ctrl_queue_cnt--;
6427 			sctp_free_a_chunk(stcb, chk);
6428 		}
6429 		chk = nchk;
6430 	}
6431 }
6432 
6433 void
6434 sctp_toss_old_asconf(struct sctp_tcb *stcb)
6435 {
6436 	struct sctp_association *asoc;
6437 	struct sctp_tmit_chunk *chk, *chk_tmp;
6438 	struct sctp_asconf_chunk *acp;
6439 
6440 	asoc = &stcb->asoc;
6441 	for (chk = TAILQ_FIRST(&asoc->asconf_send_queue); chk != NULL;
6442 	    chk = chk_tmp) {
6443 		/* get next chk */
6444 		chk_tmp = TAILQ_NEXT(chk, sctp_next);
6445 		/* find SCTP_ASCONF chunk in queue */
6446 		if (chk->rec.chunk_id.id == SCTP_ASCONF) {
6447 			if (chk->data) {
6448 				acp = mtod(chk->data, struct sctp_asconf_chunk *);
6449 				if (compare_with_wrap(ntohl(acp->serial_number), stcb->asoc.asconf_seq_out_acked, MAX_SEQ)) {
6450 					/* Not Acked yet */
6451 					break;
6452 				}
6453 			}
6454 			TAILQ_REMOVE(&asoc->asconf_send_queue, chk, sctp_next);
6455 			if (chk->data) {
6456 				sctp_m_freem(chk->data);
6457 				chk->data = NULL;
6458 			}
6459 			asoc->ctrl_queue_cnt--;
6460 			sctp_free_a_chunk(stcb, chk);
6461 		}
6462 	}
6463 }
6464 
6465 
6466 static void
6467 sctp_clean_up_datalist(struct sctp_tcb *stcb,
6468 
6469     struct sctp_association *asoc,
6470     struct sctp_tmit_chunk **data_list,
6471     int bundle_at,
6472     struct sctp_nets *net)
6473 {
6474 	int i;
6475 	struct sctp_tmit_chunk *tp1;
6476 
6477 	for (i = 0; i < bundle_at; i++) {
6478 		/* off of the send queue */
6479 		if (i) {
6480 			/*
6481 			 * Any chunk NOT 0 you zap the time chunk 0 gets
6482 			 * zapped or set based on if a RTO measurment is
6483 			 * needed.
6484 			 */
6485 			data_list[i]->do_rtt = 0;
6486 		}
6487 		/* record time */
6488 		data_list[i]->sent_rcv_time = net->last_sent_time;
6489 		data_list[i]->rec.data.fast_retran_tsn = data_list[i]->rec.data.TSN_seq;
6490 		TAILQ_REMOVE(&asoc->send_queue,
6491 		    data_list[i],
6492 		    sctp_next);
6493 		/* on to the sent queue */
6494 		tp1 = TAILQ_LAST(&asoc->sent_queue, sctpchunk_listhead);
6495 		if ((tp1) && (compare_with_wrap(tp1->rec.data.TSN_seq,
6496 		    data_list[i]->rec.data.TSN_seq, MAX_TSN))) {
6497 			struct sctp_tmit_chunk *tpp;
6498 
6499 			/* need to move back */
6500 	back_up_more:
6501 			tpp = TAILQ_PREV(tp1, sctpchunk_listhead, sctp_next);
6502 			if (tpp == NULL) {
6503 				TAILQ_INSERT_BEFORE(tp1, data_list[i], sctp_next);
6504 				goto all_done;
6505 			}
6506 			tp1 = tpp;
6507 			if (compare_with_wrap(tp1->rec.data.TSN_seq,
6508 			    data_list[i]->rec.data.TSN_seq, MAX_TSN)) {
6509 				goto back_up_more;
6510 			}
6511 			TAILQ_INSERT_AFTER(&asoc->sent_queue, tp1, data_list[i], sctp_next);
6512 		} else {
6513 			TAILQ_INSERT_TAIL(&asoc->sent_queue,
6514 			    data_list[i],
6515 			    sctp_next);
6516 		}
6517 all_done:
6518 		/* This does not lower until the cum-ack passes it */
6519 		asoc->sent_queue_cnt++;
6520 		asoc->send_queue_cnt--;
6521 		if ((asoc->peers_rwnd <= 0) &&
6522 		    (asoc->total_flight == 0) &&
6523 		    (bundle_at == 1)) {
6524 			/* Mark the chunk as being a window probe */
6525 			SCTP_STAT_INCR(sctps_windowprobed);
6526 		}
6527 #ifdef SCTP_AUDITING_ENABLED
6528 		sctp_audit_log(0xC2, 3);
6529 #endif
6530 		data_list[i]->sent = SCTP_DATAGRAM_SENT;
6531 		data_list[i]->snd_count = 1;
6532 		data_list[i]->rec.data.chunk_was_revoked = 0;
6533 		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_FLIGHT_LOGGING_ENABLE) {
6534 			sctp_misc_ints(SCTP_FLIGHT_LOG_UP,
6535 			    data_list[i]->whoTo->flight_size,
6536 			    data_list[i]->book_size,
6537 			    (uintptr_t) data_list[i]->whoTo,
6538 			    data_list[i]->rec.data.TSN_seq);
6539 		}
6540 		sctp_flight_size_increase(data_list[i]);
6541 		sctp_total_flight_increase(stcb, data_list[i]);
6542 		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_RWND_ENABLE) {
6543 			sctp_log_rwnd(SCTP_DECREASE_PEER_RWND,
6544 			    asoc->peers_rwnd, data_list[i]->send_size, SCTP_BASE_SYSCTL(sctp_peer_chunk_oh));
6545 		}
6546 		asoc->peers_rwnd = sctp_sbspace_sub(asoc->peers_rwnd,
6547 		    (uint32_t) (data_list[i]->send_size + SCTP_BASE_SYSCTL(sctp_peer_chunk_oh)));
6548 		if (asoc->peers_rwnd < stcb->sctp_ep->sctp_ep.sctp_sws_sender) {
6549 			/* SWS sender side engages */
6550 			asoc->peers_rwnd = 0;
6551 		}
6552 	}
6553 }
6554 
6555 static void
6556 sctp_clean_up_ctl(struct sctp_tcb *stcb, struct sctp_association *asoc)
6557 {
6558 	struct sctp_tmit_chunk *chk, *nchk;
6559 
6560 	for (chk = TAILQ_FIRST(&asoc->control_send_queue);
6561 	    chk; chk = nchk) {
6562 		nchk = TAILQ_NEXT(chk, sctp_next);
6563 		if ((chk->rec.chunk_id.id == SCTP_SELECTIVE_ACK) ||
6564 		    (chk->rec.chunk_id.id == SCTP_NR_SELECTIVE_ACK) ||	/* EY */
6565 		    (chk->rec.chunk_id.id == SCTP_HEARTBEAT_REQUEST) ||
6566 		    (chk->rec.chunk_id.id == SCTP_HEARTBEAT_ACK) ||
6567 		    (chk->rec.chunk_id.id == SCTP_FORWARD_CUM_TSN) ||
6568 		    (chk->rec.chunk_id.id == SCTP_SHUTDOWN) ||
6569 		    (chk->rec.chunk_id.id == SCTP_SHUTDOWN_ACK) ||
6570 		    (chk->rec.chunk_id.id == SCTP_OPERATION_ERROR) ||
6571 		    (chk->rec.chunk_id.id == SCTP_PACKET_DROPPED) ||
6572 		    (chk->rec.chunk_id.id == SCTP_COOKIE_ACK) ||
6573 		    (chk->rec.chunk_id.id == SCTP_ECN_CWR) ||
6574 		    (chk->rec.chunk_id.id == SCTP_ASCONF_ACK)) {
6575 			/* Stray chunks must be cleaned up */
6576 	clean_up_anyway:
6577 			TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
6578 			if (chk->data) {
6579 				sctp_m_freem(chk->data);
6580 				chk->data = NULL;
6581 			}
6582 			asoc->ctrl_queue_cnt--;
6583 			sctp_free_a_chunk(stcb, chk);
6584 		} else if (chk->rec.chunk_id.id == SCTP_STREAM_RESET) {
6585 			/* special handling, we must look into the param */
6586 			if (chk != asoc->str_reset) {
6587 				goto clean_up_anyway;
6588 			}
6589 		}
6590 	}
6591 }
6592 
6593 
6594 static int
6595 sctp_can_we_split_this(struct sctp_tcb *stcb,
6596     uint32_t length,
6597     uint32_t goal_mtu, uint32_t frag_point, int eeor_on)
6598 {
6599 	/*
6600 	 * Make a decision on if I should split a msg into multiple parts.
6601 	 * This is only asked of incomplete messages.
6602 	 */
6603 	if (eeor_on) {
6604 		/*
6605 		 * If we are doing EEOR we need to always send it if its the
6606 		 * entire thing, since it might be all the guy is putting in
6607 		 * the hopper.
6608 		 */
6609 		if (goal_mtu >= length) {
6610 			/*-
6611 			 * If we have data outstanding,
6612 			 * we get another chance when the sack
6613 			 * arrives to transmit - wait for more data
6614 			 */
6615 			if (stcb->asoc.total_flight == 0) {
6616 				/*
6617 				 * If nothing is in flight, we zero the
6618 				 * packet counter.
6619 				 */
6620 				return (length);
6621 			}
6622 			return (0);
6623 
6624 		} else {
6625 			/* You can fill the rest */
6626 			return (goal_mtu);
6627 		}
6628 	}
6629 	/*-
6630 	 * For those strange folk that make the send buffer
6631 	 * smaller than our fragmentation point, we can't
6632 	 * get a full msg in so we have to allow splitting.
6633 	 */
6634 	if (SCTP_SB_LIMIT_SND(stcb->sctp_socket) < frag_point) {
6635 		return (length);
6636 	}
6637 	if ((length <= goal_mtu) ||
6638 	    ((length - goal_mtu) < SCTP_BASE_SYSCTL(sctp_min_residual))) {
6639 		/* Sub-optimial residual don't split in non-eeor mode. */
6640 		return (0);
6641 	}
6642 	/*
6643 	 * If we reach here length is larger than the goal_mtu. Do we wish
6644 	 * to split it for the sake of packet putting together?
6645 	 */
6646 	if (goal_mtu >= min(SCTP_BASE_SYSCTL(sctp_min_split_point), frag_point)) {
6647 		/* Its ok to split it */
6648 		return (min(goal_mtu, frag_point));
6649 	}
6650 	/* Nope, can't split */
6651 	return (0);
6652 
6653 }
6654 
6655 static uint32_t
6656 sctp_move_to_outqueue(struct sctp_tcb *stcb, struct sctp_nets *net,
6657     struct sctp_stream_out *strq,
6658     uint32_t goal_mtu,
6659     uint32_t frag_point,
6660     int *locked,
6661     int *giveup,
6662     int eeor_mode,
6663     int *bail)
6664 {
6665 	/* Move from the stream to the send_queue keeping track of the total */
6666 	struct sctp_association *asoc;
6667 	struct sctp_stream_queue_pending *sp;
6668 	struct sctp_tmit_chunk *chk;
6669 	struct sctp_data_chunk *dchkh;
6670 	uint32_t to_move, length;
6671 	uint8_t rcv_flags = 0;
6672 	uint8_t some_taken;
6673 	uint8_t send_lock_up = 0;
6674 
6675 	SCTP_TCB_LOCK_ASSERT(stcb);
6676 	asoc = &stcb->asoc;
6677 one_more_time:
6678 	/* sa_ignore FREED_MEMORY */
6679 	sp = TAILQ_FIRST(&strq->outqueue);
6680 	if (sp == NULL) {
6681 		*locked = 0;
6682 		if (send_lock_up == 0) {
6683 			SCTP_TCB_SEND_LOCK(stcb);
6684 			send_lock_up = 1;
6685 		}
6686 		sp = TAILQ_FIRST(&strq->outqueue);
6687 		if (sp) {
6688 			goto one_more_time;
6689 		}
6690 		if (strq->last_msg_incomplete) {
6691 			SCTP_PRINTF("Huh? Stream:%d lm_in_c=%d but queue is NULL\n",
6692 			    strq->stream_no,
6693 			    strq->last_msg_incomplete);
6694 			strq->last_msg_incomplete = 0;
6695 		}
6696 		to_move = 0;
6697 		if (send_lock_up) {
6698 			SCTP_TCB_SEND_UNLOCK(stcb);
6699 			send_lock_up = 0;
6700 		}
6701 		goto out_of;
6702 	}
6703 	if ((sp->msg_is_complete) && (sp->length == 0)) {
6704 		if (sp->sender_all_done) {
6705 			/*
6706 			 * We are doing differed cleanup. Last time through
6707 			 * when we took all the data the sender_all_done was
6708 			 * not set.
6709 			 */
6710 			if ((sp->put_last_out == 0) && (sp->discard_rest == 0)) {
6711 				SCTP_PRINTF("Gak, put out entire msg with NO end!-1\n");
6712 				SCTP_PRINTF("sender_done:%d len:%d msg_comp:%d put_last_out:%d send_lock:%d\n",
6713 				    sp->sender_all_done,
6714 				    sp->length,
6715 				    sp->msg_is_complete,
6716 				    sp->put_last_out,
6717 				    send_lock_up);
6718 			}
6719 			if ((TAILQ_NEXT(sp, next) == NULL) && (send_lock_up == 0)) {
6720 				SCTP_TCB_SEND_LOCK(stcb);
6721 				send_lock_up = 1;
6722 			}
6723 			atomic_subtract_int(&asoc->stream_queue_cnt, 1);
6724 			TAILQ_REMOVE(&strq->outqueue, sp, next);
6725 			sctp_free_remote_addr(sp->net);
6726 			if (sp->data) {
6727 				sctp_m_freem(sp->data);
6728 				sp->data = NULL;
6729 			}
6730 			sctp_free_a_strmoq(stcb, sp);
6731 			/* we can't be locked to it */
6732 			*locked = 0;
6733 			stcb->asoc.locked_on_sending = NULL;
6734 			if (send_lock_up) {
6735 				SCTP_TCB_SEND_UNLOCK(stcb);
6736 				send_lock_up = 0;
6737 			}
6738 			/* back to get the next msg */
6739 			goto one_more_time;
6740 		} else {
6741 			/*
6742 			 * sender just finished this but still holds a
6743 			 * reference
6744 			 */
6745 			*locked = 1;
6746 			*giveup = 1;
6747 			to_move = 0;
6748 			goto out_of;
6749 		}
6750 	} else {
6751 		/* is there some to get */
6752 		if (sp->length == 0) {
6753 			/* no */
6754 			*locked = 1;
6755 			*giveup = 1;
6756 			to_move = 0;
6757 			goto out_of;
6758 		} else if (sp->discard_rest) {
6759 			if (send_lock_up == 0) {
6760 				SCTP_TCB_SEND_LOCK(stcb);
6761 				send_lock_up = 1;
6762 			}
6763 			/* Whack down the size */
6764 			atomic_subtract_int(&stcb->asoc.total_output_queue_size, sp->length);
6765 			if ((stcb->sctp_socket != NULL) && \
6766 			    ((stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
6767 			    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL))) {
6768 				atomic_subtract_int(&stcb->sctp_socket->so_snd.sb_cc, sp->length);
6769 			}
6770 			if (sp->data) {
6771 				sctp_m_freem(sp->data);
6772 				sp->data = NULL;
6773 				sp->tail_mbuf = NULL;
6774 			}
6775 			sp->length = 0;
6776 			sp->some_taken = 1;
6777 			*locked = 1;
6778 			*giveup = 1;
6779 			to_move = 0;
6780 			goto out_of;
6781 		}
6782 	}
6783 	some_taken = sp->some_taken;
6784 	if (stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET) {
6785 		sp->msg_is_complete = 1;
6786 	}
6787 re_look:
6788 	length = sp->length;
6789 	if (sp->msg_is_complete) {
6790 		/* The message is complete */
6791 		to_move = min(length, frag_point);
6792 		if (to_move == length) {
6793 			/* All of it fits in the MTU */
6794 			if (sp->some_taken) {
6795 				rcv_flags |= SCTP_DATA_LAST_FRAG;
6796 				sp->put_last_out = 1;
6797 			} else {
6798 				rcv_flags |= SCTP_DATA_NOT_FRAG;
6799 				sp->put_last_out = 1;
6800 			}
6801 		} else {
6802 			/* Not all of it fits, we fragment */
6803 			if (sp->some_taken == 0) {
6804 				rcv_flags |= SCTP_DATA_FIRST_FRAG;
6805 			}
6806 			sp->some_taken = 1;
6807 		}
6808 	} else {
6809 		to_move = sctp_can_we_split_this(stcb, length, goal_mtu, frag_point, eeor_mode);
6810 		if (to_move) {
6811 			/*-
6812 			 * We use a snapshot of length in case it
6813 			 * is expanding during the compare.
6814 			 */
6815 			uint32_t llen;
6816 
6817 			llen = length;
6818 			if (to_move >= llen) {
6819 				to_move = llen;
6820 				if (send_lock_up == 0) {
6821 					/*-
6822 					 * We are taking all of an incomplete msg
6823 					 * thus we need a send lock.
6824 					 */
6825 					SCTP_TCB_SEND_LOCK(stcb);
6826 					send_lock_up = 1;
6827 					if (sp->msg_is_complete) {
6828 						/*
6829 						 * the sender finished the
6830 						 * msg
6831 						 */
6832 						goto re_look;
6833 					}
6834 				}
6835 			}
6836 			if (sp->some_taken == 0) {
6837 				rcv_flags |= SCTP_DATA_FIRST_FRAG;
6838 				sp->some_taken = 1;
6839 			}
6840 		} else {
6841 			/* Nothing to take. */
6842 			if (sp->some_taken) {
6843 				*locked = 1;
6844 			}
6845 			*giveup = 1;
6846 			to_move = 0;
6847 			goto out_of;
6848 		}
6849 	}
6850 
6851 	/* If we reach here, we can copy out a chunk */
6852 	sctp_alloc_a_chunk(stcb, chk);
6853 	if (chk == NULL) {
6854 		/* No chunk memory */
6855 		*giveup = 1;
6856 		to_move = 0;
6857 		goto out_of;
6858 	}
6859 	/*
6860 	 * Setup for unordered if needed by looking at the user sent info
6861 	 * flags.
6862 	 */
6863 	if (sp->sinfo_flags & SCTP_UNORDERED) {
6864 		rcv_flags |= SCTP_DATA_UNORDERED;
6865 	}
6866 	if ((SCTP_BASE_SYSCTL(sctp_enable_sack_immediately) && ((sp->sinfo_flags & SCTP_EOF) == SCTP_EOF)) ||
6867 	    ((sp->sinfo_flags & SCTP_SACK_IMMEDIATELY) == SCTP_SACK_IMMEDIATELY)) {
6868 		rcv_flags |= SCTP_DATA_SACK_IMMEDIATELY;
6869 	}
6870 	/* clear out the chunk before setting up */
6871 	memset(chk, 0, sizeof(*chk));
6872 	chk->rec.data.rcv_flags = rcv_flags;
6873 
6874 	if (to_move >= length) {
6875 		/* we think we can steal the whole thing */
6876 		if ((sp->sender_all_done == 0) && (send_lock_up == 0)) {
6877 			SCTP_TCB_SEND_LOCK(stcb);
6878 			send_lock_up = 1;
6879 		}
6880 		if (to_move < sp->length) {
6881 			/* bail, it changed */
6882 			goto dont_do_it;
6883 		}
6884 		chk->data = sp->data;
6885 		chk->last_mbuf = sp->tail_mbuf;
6886 		/* register the stealing */
6887 		sp->data = sp->tail_mbuf = NULL;
6888 	} else {
6889 		struct mbuf *m;
6890 
6891 dont_do_it:
6892 		chk->data = SCTP_M_COPYM(sp->data, 0, to_move, M_DONTWAIT);
6893 		chk->last_mbuf = NULL;
6894 		if (chk->data == NULL) {
6895 			sp->some_taken = some_taken;
6896 			sctp_free_a_chunk(stcb, chk);
6897 			*bail = 1;
6898 			to_move = 0;
6899 			goto out_of;
6900 		}
6901 #ifdef SCTP_MBUF_LOGGING
6902 		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
6903 			struct mbuf *mat;
6904 
6905 			mat = chk->data;
6906 			while (mat) {
6907 				if (SCTP_BUF_IS_EXTENDED(mat)) {
6908 					sctp_log_mb(mat, SCTP_MBUF_ICOPY);
6909 				}
6910 				mat = SCTP_BUF_NEXT(mat);
6911 			}
6912 		}
6913 #endif
6914 		/* Pull off the data */
6915 		m_adj(sp->data, to_move);
6916 		/* Now lets work our way down and compact it */
6917 		m = sp->data;
6918 		while (m && (SCTP_BUF_LEN(m) == 0)) {
6919 			sp->data = SCTP_BUF_NEXT(m);
6920 			SCTP_BUF_NEXT(m) = NULL;
6921 			if (sp->tail_mbuf == m) {
6922 				/*-
6923 				 * Freeing tail? TSNH since
6924 				 * we supposedly were taking less
6925 				 * than the sp->length.
6926 				 */
6927 #ifdef INVARIANTS
6928 				panic("Huh, freing tail? - TSNH");
6929 #else
6930 				SCTP_PRINTF("Huh, freeing tail? - TSNH\n");
6931 				sp->tail_mbuf = sp->data = NULL;
6932 				sp->length = 0;
6933 #endif
6934 
6935 			}
6936 			sctp_m_free(m);
6937 			m = sp->data;
6938 		}
6939 	}
6940 	if (SCTP_BUF_IS_EXTENDED(chk->data)) {
6941 		chk->copy_by_ref = 1;
6942 	} else {
6943 		chk->copy_by_ref = 0;
6944 	}
6945 	/*
6946 	 * get last_mbuf and counts of mb useage This is ugly but hopefully
6947 	 * its only one mbuf.
6948 	 */
6949 	if (chk->last_mbuf == NULL) {
6950 		chk->last_mbuf = chk->data;
6951 		while (SCTP_BUF_NEXT(chk->last_mbuf) != NULL) {
6952 			chk->last_mbuf = SCTP_BUF_NEXT(chk->last_mbuf);
6953 		}
6954 	}
6955 	if (to_move > length) {
6956 		/*- This should not happen either
6957 		 * since we always lower to_move to the size
6958 		 * of sp->length if its larger.
6959 		 */
6960 #ifdef INVARIANTS
6961 		panic("Huh, how can to_move be larger?");
6962 #else
6963 		SCTP_PRINTF("Huh, how can to_move be larger?\n");
6964 		sp->length = 0;
6965 #endif
6966 	} else {
6967 		atomic_subtract_int(&sp->length, to_move);
6968 	}
6969 	if (M_LEADINGSPACE(chk->data) < (int)sizeof(struct sctp_data_chunk)) {
6970 		/* Not enough room for a chunk header, get some */
6971 		struct mbuf *m;
6972 
6973 		m = sctp_get_mbuf_for_msg(1, 0, M_DONTWAIT, 0, MT_DATA);
6974 		if (m == NULL) {
6975 			/*
6976 			 * we're in trouble here. _PREPEND below will free
6977 			 * all the data if there is no leading space, so we
6978 			 * must put the data back and restore.
6979 			 */
6980 			if (send_lock_up == 0) {
6981 				SCTP_TCB_SEND_LOCK(stcb);
6982 				send_lock_up = 1;
6983 			}
6984 			if (chk->data == NULL) {
6985 				/* unsteal the data */
6986 				sp->data = chk->data;
6987 				sp->tail_mbuf = chk->last_mbuf;
6988 			} else {
6989 				struct mbuf *m_tmp;
6990 
6991 				/* reassemble the data */
6992 				m_tmp = sp->data;
6993 				sp->data = chk->data;
6994 				SCTP_BUF_NEXT(chk->last_mbuf) = m_tmp;
6995 			}
6996 			sp->some_taken = some_taken;
6997 			atomic_add_int(&sp->length, to_move);
6998 			chk->data = NULL;
6999 			*bail = 1;
7000 			sctp_free_a_chunk(stcb, chk);
7001 			to_move = 0;
7002 			goto out_of;
7003 		} else {
7004 			SCTP_BUF_LEN(m) = 0;
7005 			SCTP_BUF_NEXT(m) = chk->data;
7006 			chk->data = m;
7007 			M_ALIGN(chk->data, 4);
7008 		}
7009 	}
7010 	SCTP_BUF_PREPEND(chk->data, sizeof(struct sctp_data_chunk), M_DONTWAIT);
7011 	if (chk->data == NULL) {
7012 		/* HELP, TSNH since we assured it would not above? */
7013 #ifdef INVARIANTS
7014 		panic("prepend failes HELP?");
7015 #else
7016 		SCTP_PRINTF("prepend fails HELP?\n");
7017 		sctp_free_a_chunk(stcb, chk);
7018 #endif
7019 		*bail = 1;
7020 		to_move = 0;
7021 		goto out_of;
7022 	}
7023 	sctp_snd_sb_alloc(stcb, sizeof(struct sctp_data_chunk));
7024 	chk->book_size = chk->send_size = (to_move + sizeof(struct sctp_data_chunk));
7025 	chk->book_size_scale = 0;
7026 	chk->sent = SCTP_DATAGRAM_UNSENT;
7027 
7028 	chk->flags = 0;
7029 	chk->asoc = &stcb->asoc;
7030 	chk->pad_inplace = 0;
7031 	chk->no_fr_allowed = 0;
7032 	chk->rec.data.stream_seq = sp->strseq;
7033 	chk->rec.data.stream_number = sp->stream;
7034 	chk->rec.data.payloadtype = sp->ppid;
7035 	chk->rec.data.context = sp->context;
7036 	chk->rec.data.doing_fast_retransmit = 0;
7037 	chk->rec.data.ect_nonce = 0;	/* ECN Nonce */
7038 
7039 	chk->rec.data.timetodrop = sp->ts;
7040 	chk->flags = sp->act_flags;
7041 
7042 	chk->whoTo = net;
7043 	atomic_add_int(&chk->whoTo->ref_count, 1);
7044 
7045 	if (sp->holds_key_ref) {
7046 		chk->auth_keyid = sp->auth_keyid;
7047 		sctp_auth_key_acquire(stcb, chk->auth_keyid);
7048 		chk->holds_key_ref = 1;
7049 	}
7050 	chk->rec.data.TSN_seq = atomic_fetchadd_int(&asoc->sending_seq, 1);
7051 	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_AT_SEND_2_OUTQ) {
7052 		sctp_misc_ints(SCTP_STRMOUT_LOG_SEND,
7053 		    (uintptr_t) stcb, sp->length,
7054 		    (uint32_t) ((chk->rec.data.stream_number << 16) | chk->rec.data.stream_seq),
7055 		    chk->rec.data.TSN_seq);
7056 	}
7057 	dchkh = mtod(chk->data, struct sctp_data_chunk *);
7058 	/*
7059 	 * Put the rest of the things in place now. Size was done earlier in
7060 	 * previous loop prior to padding.
7061 	 */
7062 
7063 #ifdef SCTP_ASOCLOG_OF_TSNS
7064 	SCTP_TCB_LOCK_ASSERT(stcb);
7065 	if (asoc->tsn_out_at >= SCTP_TSN_LOG_SIZE) {
7066 		asoc->tsn_out_at = 0;
7067 		asoc->tsn_out_wrapped = 1;
7068 	}
7069 	asoc->out_tsnlog[asoc->tsn_out_at].tsn = chk->rec.data.TSN_seq;
7070 	asoc->out_tsnlog[asoc->tsn_out_at].strm = chk->rec.data.stream_number;
7071 	asoc->out_tsnlog[asoc->tsn_out_at].seq = chk->rec.data.stream_seq;
7072 	asoc->out_tsnlog[asoc->tsn_out_at].sz = chk->send_size;
7073 	asoc->out_tsnlog[asoc->tsn_out_at].flgs = chk->rec.data.rcv_flags;
7074 	asoc->out_tsnlog[asoc->tsn_out_at].stcb = (void *)stcb;
7075 	asoc->out_tsnlog[asoc->tsn_out_at].in_pos = asoc->tsn_out_at;
7076 	asoc->out_tsnlog[asoc->tsn_out_at].in_out = 2;
7077 	asoc->tsn_out_at++;
7078 #endif
7079 
7080 	dchkh->ch.chunk_type = SCTP_DATA;
7081 	dchkh->ch.chunk_flags = chk->rec.data.rcv_flags;
7082 	dchkh->dp.tsn = htonl(chk->rec.data.TSN_seq);
7083 	dchkh->dp.stream_id = htons(strq->stream_no);
7084 	dchkh->dp.stream_sequence = htons(chk->rec.data.stream_seq);
7085 	dchkh->dp.protocol_id = chk->rec.data.payloadtype;
7086 	dchkh->ch.chunk_length = htons(chk->send_size);
7087 	/* Now advance the chk->send_size by the actual pad needed. */
7088 	if (chk->send_size < SCTP_SIZE32(chk->book_size)) {
7089 		/* need a pad */
7090 		struct mbuf *lm;
7091 		int pads;
7092 
7093 		pads = SCTP_SIZE32(chk->book_size) - chk->send_size;
7094 		if (sctp_pad_lastmbuf(chk->data, pads, chk->last_mbuf) == 0) {
7095 			chk->pad_inplace = 1;
7096 		}
7097 		if ((lm = SCTP_BUF_NEXT(chk->last_mbuf)) != NULL) {
7098 			/* pad added an mbuf */
7099 			chk->last_mbuf = lm;
7100 		}
7101 		chk->send_size += pads;
7102 	}
7103 	/* We only re-set the policy if it is on */
7104 	if (sp->pr_sctp_on) {
7105 		sctp_set_prsctp_policy(sp);
7106 		asoc->pr_sctp_cnt++;
7107 		chk->pr_sctp_on = 1;
7108 	} else {
7109 		chk->pr_sctp_on = 0;
7110 	}
7111 	if (sp->msg_is_complete && (sp->length == 0) && (sp->sender_all_done)) {
7112 		/* All done pull and kill the message */
7113 		atomic_subtract_int(&asoc->stream_queue_cnt, 1);
7114 		if (sp->put_last_out == 0) {
7115 			SCTP_PRINTF("Gak, put out entire msg with NO end!-2\n");
7116 			SCTP_PRINTF("sender_done:%d len:%d msg_comp:%d put_last_out:%d send_lock:%d\n",
7117 			    sp->sender_all_done,
7118 			    sp->length,
7119 			    sp->msg_is_complete,
7120 			    sp->put_last_out,
7121 			    send_lock_up);
7122 		}
7123 		if ((send_lock_up == 0) && (TAILQ_NEXT(sp, next) == NULL)) {
7124 			SCTP_TCB_SEND_LOCK(stcb);
7125 			send_lock_up = 1;
7126 		}
7127 		TAILQ_REMOVE(&strq->outqueue, sp, next);
7128 		sctp_free_remote_addr(sp->net);
7129 		if (sp->data) {
7130 			sctp_m_freem(sp->data);
7131 			sp->data = NULL;
7132 		}
7133 		sctp_free_a_strmoq(stcb, sp);
7134 
7135 		/* we can't be locked to it */
7136 		*locked = 0;
7137 		stcb->asoc.locked_on_sending = NULL;
7138 	} else {
7139 		/* more to go, we are locked */
7140 		*locked = 1;
7141 	}
7142 	asoc->chunks_on_out_queue++;
7143 	TAILQ_INSERT_TAIL(&asoc->send_queue, chk, sctp_next);
7144 	asoc->send_queue_cnt++;
7145 out_of:
7146 	if (send_lock_up) {
7147 		SCTP_TCB_SEND_UNLOCK(stcb);
7148 		send_lock_up = 0;
7149 	}
7150 	return (to_move);
7151 }
7152 
7153 
7154 static struct sctp_stream_out *
7155 sctp_select_a_stream(struct sctp_tcb *stcb, struct sctp_association *asoc)
7156 {
7157 	struct sctp_stream_out *strq;
7158 
7159 	/* Find the next stream to use */
7160 	if (asoc->last_out_stream == NULL) {
7161 		strq = TAILQ_FIRST(&asoc->out_wheel);
7162 	} else {
7163 		strq = TAILQ_NEXT(asoc->last_out_stream, next_spoke);
7164 		if (strq == NULL) {
7165 			strq = TAILQ_FIRST(&asoc->out_wheel);
7166 		}
7167 	}
7168 	return (strq);
7169 }
7170 
7171 
7172 static void
7173 sctp_fill_outqueue(struct sctp_tcb *stcb,
7174     struct sctp_nets *net, int frag_point, int eeor_mode, int *quit_now)
7175 {
7176 	struct sctp_association *asoc;
7177 	struct sctp_stream_out *strq, *strqn;
7178 	int goal_mtu, moved_how_much, total_moved = 0, bail = 0;
7179 	int locked, giveup;
7180 	struct sctp_stream_queue_pending *sp;
7181 
7182 	SCTP_TCB_LOCK_ASSERT(stcb);
7183 	asoc = &stcb->asoc;
7184 #ifdef INET6
7185 	if (net->ro._l_addr.sin6.sin6_family == AF_INET6) {
7186 		goal_mtu = net->mtu - SCTP_MIN_OVERHEAD;
7187 	} else {
7188 		/* ?? not sure what else to do */
7189 		goal_mtu = net->mtu - SCTP_MIN_V4_OVERHEAD;
7190 	}
7191 #else
7192 	goal_mtu = net->mtu - SCTP_MIN_OVERHEAD;
7193 #endif
7194 	/* Need an allowance for the data chunk header too */
7195 	goal_mtu -= sizeof(struct sctp_data_chunk);
7196 
7197 	/* must make even word boundary */
7198 	goal_mtu &= 0xfffffffc;
7199 	if (asoc->locked_on_sending) {
7200 		/* We are stuck on one stream until the message completes. */
7201 		strqn = strq = asoc->locked_on_sending;
7202 		locked = 1;
7203 	} else {
7204 		strqn = strq = sctp_select_a_stream(stcb, asoc);
7205 		locked = 0;
7206 	}
7207 
7208 	while ((goal_mtu > 0) && strq) {
7209 		sp = TAILQ_FIRST(&strq->outqueue);
7210 		/*
7211 		 * If CMT is off, we must validate that the stream in
7212 		 * question has the first item pointed towards are network
7213 		 * destionation requested by the caller. Note that if we
7214 		 * turn out to be locked to a stream (assigning TSN's then
7215 		 * we must stop, since we cannot look for another stream
7216 		 * with data to send to that destination). In CMT's case, by
7217 		 * skipping this check, we will send one data packet towards
7218 		 * the requested net.
7219 		 */
7220 		if (sp == NULL) {
7221 			break;
7222 		}
7223 		if ((sp->net != net) && (SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 0)) {
7224 			/* none for this network */
7225 			if (locked) {
7226 				break;
7227 			} else {
7228 				strq = sctp_select_a_stream(stcb, asoc);
7229 				if (strq == NULL)
7230 					/* none left */
7231 					break;
7232 				if (strqn == strq) {
7233 					/* I have circled */
7234 					break;
7235 				}
7236 				continue;
7237 			}
7238 		}
7239 		giveup = 0;
7240 		bail = 0;
7241 		moved_how_much = sctp_move_to_outqueue(stcb, net, strq, goal_mtu, frag_point, &locked,
7242 		    &giveup, eeor_mode, &bail);
7243 		if (moved_how_much)
7244 			asoc->last_out_stream = strq;
7245 
7246 		if (locked) {
7247 			asoc->locked_on_sending = strq;
7248 			if ((moved_how_much == 0) || (giveup) || bail)
7249 				/* no more to move for now */
7250 				break;
7251 		} else {
7252 			asoc->locked_on_sending = NULL;
7253 			if (TAILQ_EMPTY(&strq->outqueue)) {
7254 				if (strq == strqn) {
7255 					/* Must move start to next one */
7256 					strqn = TAILQ_NEXT(strq, next_spoke);
7257 					if (strqn == NULL) {
7258 						strqn = TAILQ_FIRST(&asoc->out_wheel);
7259 						if (strqn == NULL) {
7260 							break;
7261 						}
7262 					}
7263 				}
7264 				sctp_remove_from_wheel(stcb, asoc, strq, 0);
7265 			}
7266 			if ((giveup) || bail) {
7267 				break;
7268 			}
7269 			strq = sctp_select_a_stream(stcb, asoc);
7270 			if (strq == NULL) {
7271 				break;
7272 			}
7273 		}
7274 		total_moved += moved_how_much;
7275 		goal_mtu -= (moved_how_much + sizeof(struct sctp_data_chunk));
7276 		goal_mtu &= 0xfffffffc;
7277 	}
7278 	if (bail)
7279 		*quit_now = 1;
7280 
7281 	if (total_moved == 0) {
7282 		if ((SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 0) &&
7283 		    (net == stcb->asoc.primary_destination)) {
7284 			/* ran dry for primary network net */
7285 			SCTP_STAT_INCR(sctps_primary_randry);
7286 		} else if (SCTP_BASE_SYSCTL(sctp_cmt_on_off)) {
7287 			/* ran dry with CMT on */
7288 			SCTP_STAT_INCR(sctps_cmt_randry);
7289 		}
7290 	}
7291 }
7292 
7293 void
7294 sctp_fix_ecn_echo(struct sctp_association *asoc)
7295 {
7296 	struct sctp_tmit_chunk *chk;
7297 
7298 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
7299 		if (chk->rec.chunk_id.id == SCTP_ECN_ECHO) {
7300 			chk->sent = SCTP_DATAGRAM_UNSENT;
7301 		}
7302 	}
7303 }
7304 
7305 static void
7306 sctp_move_to_an_alt(struct sctp_tcb *stcb,
7307     struct sctp_association *asoc,
7308     struct sctp_nets *net)
7309 {
7310 	struct sctp_tmit_chunk *chk;
7311 	struct sctp_nets *a_net;
7312 
7313 	SCTP_TCB_LOCK_ASSERT(stcb);
7314 	/*
7315 	 * JRS 5/14/07 - If CMT PF is turned on, find an alternate
7316 	 * destination using the PF algorithm for finding alternate
7317 	 * destinations.
7318 	 */
7319 	if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && SCTP_BASE_SYSCTL(sctp_cmt_pf)) {
7320 		a_net = sctp_find_alternate_net(stcb, net, 2);
7321 	} else {
7322 		a_net = sctp_find_alternate_net(stcb, net, 0);
7323 	}
7324 	if ((a_net != net) &&
7325 	    ((a_net->dest_state & SCTP_ADDR_REACHABLE) == SCTP_ADDR_REACHABLE)) {
7326 		/*
7327 		 * We only proceed if a valid alternate is found that is not
7328 		 * this one and is reachable. Here we must move all chunks
7329 		 * queued in the send queue off of the destination address
7330 		 * to our alternate.
7331 		 */
7332 		TAILQ_FOREACH(chk, &asoc->send_queue, sctp_next) {
7333 			if (chk->whoTo == net) {
7334 				/* Move the chunk to our alternate */
7335 				sctp_free_remote_addr(chk->whoTo);
7336 				chk->whoTo = a_net;
7337 				atomic_add_int(&a_net->ref_count, 1);
7338 			}
7339 		}
7340 	}
7341 }
7342 
7343 int
7344 sctp_med_chunk_output(struct sctp_inpcb *inp,
7345     struct sctp_tcb *stcb,
7346     struct sctp_association *asoc,
7347     int *num_out,
7348     int *reason_code,
7349     int control_only, int from_where,
7350     struct timeval *now, int *now_filled, int frag_point, int so_locked
7351 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
7352     SCTP_UNUSED
7353 #endif
7354 )
7355 {
7356 	/*
7357 	 * Ok this is the generic chunk service queue. we must do the
7358 	 * following: - Service the stream queue that is next, moving any
7359 	 * message (note I must get a complete message i.e. FIRST/MIDDLE and
7360 	 * LAST to the out queue in one pass) and assigning TSN's - Check to
7361 	 * see if the cwnd/rwnd allows any output, if so we go ahead and
7362 	 * fomulate and send the low level chunks. Making sure to combine
7363 	 * any control in the control chunk queue also.
7364 	 */
7365 	struct sctp_nets *net, *start_at, *old_start_at = NULL;
7366 	struct mbuf *outchain, *endoutchain;
7367 	struct sctp_tmit_chunk *chk, *nchk;
7368 
7369 	/* temp arrays for unlinking */
7370 	struct sctp_tmit_chunk *data_list[SCTP_MAX_DATA_BUNDLING];
7371 	int no_fragmentflg, error;
7372 	unsigned int max_rwnd_per_dest;
7373 	int one_chunk, hbflag, skip_data_for_this_net;
7374 	int asconf, cookie, no_out_cnt;
7375 	int bundle_at, ctl_cnt, no_data_chunks, eeor_mode;
7376 	unsigned int mtu, r_mtu, omtu, mx_mtu, to_out;
7377 	int tsns_sent = 0;
7378 	uint32_t auth_offset = 0;
7379 	struct sctp_auth_chunk *auth = NULL;
7380 	uint16_t auth_keyid;
7381 	int override_ok = 1;
7382 	int data_auth_reqd = 0;
7383 
7384 	/*
7385 	 * JRS 5/14/07 - Add flag for whether a heartbeat is sent to the
7386 	 * destination.
7387 	 */
7388 	int pf_hbflag = 0;
7389 	int quit_now = 0;
7390 
7391 	*num_out = 0;
7392 	auth_keyid = stcb->asoc.authinfo.active_keyid;
7393 
7394 	if ((asoc->state & SCTP_STATE_SHUTDOWN_PENDING) ||
7395 	    (asoc->state & SCTP_STATE_SHUTDOWN_RECEIVED) ||
7396 	    (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_EXPLICIT_EOR))) {
7397 		eeor_mode = 1;
7398 	} else {
7399 		eeor_mode = 0;
7400 	}
7401 	ctl_cnt = no_out_cnt = asconf = cookie = 0;
7402 	/*
7403 	 * First lets prime the pump. For each destination, if there is room
7404 	 * in the flight size, attempt to pull an MTU's worth out of the
7405 	 * stream queues into the general send_queue
7406 	 */
7407 #ifdef SCTP_AUDITING_ENABLED
7408 	sctp_audit_log(0xC2, 2);
7409 #endif
7410 	SCTP_TCB_LOCK_ASSERT(stcb);
7411 	hbflag = 0;
7412 	if ((control_only) || (asoc->stream_reset_outstanding))
7413 		no_data_chunks = 1;
7414 	else
7415 		no_data_chunks = 0;
7416 
7417 	/* Nothing to possible to send? */
7418 	if (TAILQ_EMPTY(&asoc->control_send_queue) &&
7419 	    TAILQ_EMPTY(&asoc->asconf_send_queue) &&
7420 	    TAILQ_EMPTY(&asoc->send_queue) &&
7421 	    TAILQ_EMPTY(&asoc->out_wheel)) {
7422 		*reason_code = 9;
7423 		return (0);
7424 	}
7425 	if (asoc->peers_rwnd == 0) {
7426 		/* No room in peers rwnd */
7427 		*reason_code = 1;
7428 		if (asoc->total_flight > 0) {
7429 			/* we are allowed one chunk in flight */
7430 			no_data_chunks = 1;
7431 		}
7432 	}
7433 	max_rwnd_per_dest = ((asoc->peers_rwnd + asoc->total_flight) / asoc->numnets);
7434 	if ((no_data_chunks == 0) && (!TAILQ_EMPTY(&asoc->out_wheel))) {
7435 		TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
7436 			/*
7437 			 * This for loop we are in takes in each net, if
7438 			 * its's got space in cwnd and has data sent to it
7439 			 * (when CMT is off) then it calls
7440 			 * sctp_fill_outqueue for the net. This gets data on
7441 			 * the send queue for that network.
7442 			 *
7443 			 * In sctp_fill_outqueue TSN's are assigned and data is
7444 			 * copied out of the stream buffers. Note mostly
7445 			 * copy by reference (we hope).
7446 			 */
7447 			net->window_probe = 0;
7448 			if ((net->dest_state & SCTP_ADDR_NOT_REACHABLE) || (net->dest_state & SCTP_ADDR_UNCONFIRMED)) {
7449 				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
7450 					sctp_log_cwnd(stcb, net, 1,
7451 					    SCTP_CWND_LOG_FILL_OUTQ_CALLED);
7452 				}
7453 				continue;
7454 			}
7455 			if ((SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 0) && (net->ref_count < 2)) {
7456 				/* nothing can be in queue for this guy */
7457 				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
7458 					sctp_log_cwnd(stcb, net, 2,
7459 					    SCTP_CWND_LOG_FILL_OUTQ_CALLED);
7460 				}
7461 				continue;
7462 			}
7463 			if (net->flight_size >= net->cwnd) {
7464 				/* skip this network, no room - can't fill */
7465 				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
7466 					sctp_log_cwnd(stcb, net, 3,
7467 					    SCTP_CWND_LOG_FILL_OUTQ_CALLED);
7468 				}
7469 				continue;
7470 			}
7471 			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
7472 				sctp_log_cwnd(stcb, net, 4, SCTP_CWND_LOG_FILL_OUTQ_CALLED);
7473 			}
7474 			sctp_fill_outqueue(stcb, net, frag_point, eeor_mode, &quit_now);
7475 			if (quit_now) {
7476 				/* memory alloc failure */
7477 				no_data_chunks = 1;
7478 				break;
7479 			}
7480 		}
7481 	}
7482 	/* now service each destination and send out what we can for it */
7483 	/* Nothing to send? */
7484 	if ((TAILQ_FIRST(&asoc->control_send_queue) == NULL) &&
7485 	    (TAILQ_FIRST(&asoc->asconf_send_queue) == NULL) &&
7486 	    (TAILQ_FIRST(&asoc->send_queue) == NULL)) {
7487 		*reason_code = 8;
7488 		return (0);
7489 	}
7490 	if (SCTP_BASE_SYSCTL(sctp_cmt_on_off)) {
7491 		/* get the last start point */
7492 		start_at = asoc->last_net_cmt_send_started;
7493 		if (start_at == NULL) {
7494 			/* null so to beginning */
7495 			start_at = TAILQ_FIRST(&asoc->nets);
7496 		} else {
7497 			start_at = TAILQ_NEXT(asoc->last_net_cmt_send_started, sctp_next);
7498 			if (start_at == NULL) {
7499 				start_at = TAILQ_FIRST(&asoc->nets);
7500 			}
7501 		}
7502 		asoc->last_net_cmt_send_started = start_at;
7503 	} else {
7504 		start_at = TAILQ_FIRST(&asoc->nets);
7505 	}
7506 	old_start_at = NULL;
7507 again_one_more_time:
7508 	for (net = start_at; net != NULL; net = TAILQ_NEXT(net, sctp_next)) {
7509 		/* how much can we send? */
7510 		/* SCTPDBG("Examine for sending net:%x\n", (uint32_t)net); */
7511 		if (old_start_at && (old_start_at == net)) {
7512 			/* through list ocmpletely. */
7513 			break;
7514 		}
7515 		tsns_sent = 0xa;
7516 		if ((SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 0) && (net->ref_count < 2)) {
7517 			/*
7518 			 * Ref-count of 1 so we cannot have data or control
7519 			 * queued to this address. Skip it (non-CMT).
7520 			 */
7521 			continue;
7522 		}
7523 		if ((TAILQ_FIRST(&asoc->control_send_queue) == NULL) &&
7524 		    (TAILQ_FIRST(&asoc->asconf_send_queue) == NULL) &&
7525 		    (net->flight_size >= net->cwnd)) {
7526 			/*
7527 			 * Nothing on control or asconf and flight is full,
7528 			 * we can skip even in the CMT case.
7529 			 */
7530 			continue;
7531 		}
7532 		ctl_cnt = bundle_at = 0;
7533 		endoutchain = outchain = NULL;
7534 		no_fragmentflg = 1;
7535 		one_chunk = 0;
7536 		if (net->dest_state & SCTP_ADDR_UNCONFIRMED) {
7537 			skip_data_for_this_net = 1;
7538 		} else {
7539 			skip_data_for_this_net = 0;
7540 		}
7541 		if ((net->ro.ro_rt) && (net->ro.ro_rt->rt_ifp)) {
7542 			/*
7543 			 * if we have a route and an ifp check to see if we
7544 			 * have room to send to this guy
7545 			 */
7546 			struct ifnet *ifp;
7547 
7548 			ifp = net->ro.ro_rt->rt_ifp;
7549 			if ((ifp->if_snd.ifq_len + 2) >= ifp->if_snd.ifq_maxlen) {
7550 				SCTP_STAT_INCR(sctps_ifnomemqueued);
7551 				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_MAXBURST_ENABLE) {
7552 					sctp_log_maxburst(stcb, net, ifp->if_snd.ifq_len, ifp->if_snd.ifq_maxlen, SCTP_MAX_IFP_APPLIED);
7553 				}
7554 				continue;
7555 			}
7556 		}
7557 		switch (((struct sockaddr *)&net->ro._l_addr)->sa_family) {
7558 		case AF_INET:
7559 			mtu = net->mtu - (sizeof(struct ip) + sizeof(struct sctphdr));
7560 			break;
7561 #ifdef INET6
7562 		case AF_INET6:
7563 			mtu = net->mtu - (sizeof(struct ip6_hdr) + sizeof(struct sctphdr));
7564 			break;
7565 #endif
7566 		default:
7567 			/* TSNH */
7568 			mtu = net->mtu;
7569 			break;
7570 		}
7571 		mx_mtu = mtu;
7572 		to_out = 0;
7573 		if (mtu > asoc->peers_rwnd) {
7574 			if (asoc->total_flight > 0) {
7575 				/* We have a packet in flight somewhere */
7576 				r_mtu = asoc->peers_rwnd;
7577 			} else {
7578 				/* We are always allowed to send one MTU out */
7579 				one_chunk = 1;
7580 				r_mtu = mtu;
7581 			}
7582 		} else {
7583 			r_mtu = mtu;
7584 		}
7585 		/************************/
7586 		/* ASCONF transmission */
7587 		/************************/
7588 		/* Now first lets go through the asconf queue */
7589 		for (chk = TAILQ_FIRST(&asoc->asconf_send_queue);
7590 		    chk; chk = nchk) {
7591 			nchk = TAILQ_NEXT(chk, sctp_next);
7592 			if (chk->rec.chunk_id.id != SCTP_ASCONF) {
7593 				continue;
7594 			}
7595 			if (chk->whoTo != net) {
7596 				/*
7597 				 * No, not sent to the network we are
7598 				 * looking at
7599 				 */
7600 				break;
7601 			}
7602 			if (chk->data == NULL) {
7603 				break;
7604 			}
7605 			if (chk->sent != SCTP_DATAGRAM_UNSENT &&
7606 			    chk->sent != SCTP_DATAGRAM_RESEND) {
7607 				break;
7608 			}
7609 			/*
7610 			 * if no AUTH is yet included and this chunk
7611 			 * requires it, make sure to account for it.  We
7612 			 * don't apply the size until the AUTH chunk is
7613 			 * actually added below in case there is no room for
7614 			 * this chunk. NOTE: we overload the use of "omtu"
7615 			 * here
7616 			 */
7617 			if ((auth == NULL) &&
7618 			    sctp_auth_is_required_chunk(chk->rec.chunk_id.id,
7619 			    stcb->asoc.peer_auth_chunks)) {
7620 				omtu = sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
7621 			} else
7622 				omtu = 0;
7623 			/* Here we do NOT factor the r_mtu */
7624 			if ((chk->send_size < (int)(mtu - omtu)) ||
7625 			    (chk->flags & CHUNK_FLAGS_FRAGMENT_OK)) {
7626 				/*
7627 				 * We probably should glom the mbuf chain
7628 				 * from the chk->data for control but the
7629 				 * problem is it becomes yet one more level
7630 				 * of tracking to do if for some reason
7631 				 * output fails. Then I have got to
7632 				 * reconstruct the merged control chain.. el
7633 				 * yucko.. for now we take the easy way and
7634 				 * do the copy
7635 				 */
7636 				/*
7637 				 * Add an AUTH chunk, if chunk requires it
7638 				 * save the offset into the chain for AUTH
7639 				 */
7640 				if ((auth == NULL) &&
7641 				    (sctp_auth_is_required_chunk(chk->rec.chunk_id.id,
7642 				    stcb->asoc.peer_auth_chunks))) {
7643 					outchain = sctp_add_auth_chunk(outchain,
7644 					    &endoutchain,
7645 					    &auth,
7646 					    &auth_offset,
7647 					    stcb,
7648 					    chk->rec.chunk_id.id);
7649 					SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
7650 				}
7651 				outchain = sctp_copy_mbufchain(chk->data, outchain, &endoutchain,
7652 				    (int)chk->rec.chunk_id.can_take_data,
7653 				    chk->send_size, chk->copy_by_ref);
7654 				if (outchain == NULL) {
7655 					*reason_code = 8;
7656 					SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
7657 					return (ENOMEM);
7658 				}
7659 				SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
7660 				/* update our MTU size */
7661 				if (mtu > (chk->send_size + omtu))
7662 					mtu -= (chk->send_size + omtu);
7663 				else
7664 					mtu = 0;
7665 				to_out += (chk->send_size + omtu);
7666 				/* Do clear IP_DF ? */
7667 				if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
7668 					no_fragmentflg = 0;
7669 				}
7670 				if (chk->rec.chunk_id.can_take_data)
7671 					chk->data = NULL;
7672 				/*
7673 				 * set hb flag since we can use these for
7674 				 * RTO
7675 				 */
7676 				hbflag = 1;
7677 				asconf = 1;
7678 				/*
7679 				 * should sysctl this: don't bundle data
7680 				 * with ASCONF since it requires AUTH
7681 				 */
7682 				no_data_chunks = 1;
7683 				chk->sent = SCTP_DATAGRAM_SENT;
7684 				chk->snd_count++;
7685 				if (mtu == 0) {
7686 					/*
7687 					 * Ok we are out of room but we can
7688 					 * output without effecting the
7689 					 * flight size since this little guy
7690 					 * is a control only packet.
7691 					 */
7692 					sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp, stcb, net);
7693 					/*
7694 					 * do NOT clear the asconf flag as
7695 					 * it is used to do appropriate
7696 					 * source address selection.
7697 					 */
7698 					if ((error = sctp_lowlevel_chunk_output(inp, stcb, net,
7699 					    (struct sockaddr *)&net->ro._l_addr,
7700 					    outchain, auth_offset, auth,
7701 					    stcb->asoc.authinfo.active_keyid,
7702 					    no_fragmentflg, 0, NULL, asconf,
7703 					    inp->sctp_lport, stcb->rport,
7704 					    htonl(stcb->asoc.peer_vtag),
7705 					    net->port, so_locked, NULL))) {
7706 						if (error == ENOBUFS) {
7707 							asoc->ifp_had_enobuf = 1;
7708 							SCTP_STAT_INCR(sctps_lowlevelerr);
7709 						}
7710 						if (from_where == 0) {
7711 							SCTP_STAT_INCR(sctps_lowlevelerrusr);
7712 						}
7713 						if (*now_filled == 0) {
7714 							(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
7715 							*now_filled = 1;
7716 							*now = net->last_sent_time;
7717 						} else {
7718 							net->last_sent_time = *now;
7719 						}
7720 						hbflag = 0;
7721 						/* error, could not output */
7722 						if (error == EHOSTUNREACH) {
7723 							/*
7724 							 * Destination went
7725 							 * unreachable
7726 							 * during this send
7727 							 */
7728 							sctp_move_to_an_alt(stcb, asoc, net);
7729 						}
7730 						*reason_code = 7;
7731 						continue;
7732 					} else
7733 						asoc->ifp_had_enobuf = 0;
7734 					if (*now_filled == 0) {
7735 						(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
7736 						*now_filled = 1;
7737 						*now = net->last_sent_time;
7738 					} else {
7739 						net->last_sent_time = *now;
7740 					}
7741 					hbflag = 0;
7742 					/*
7743 					 * increase the number we sent, if a
7744 					 * cookie is sent we don't tell them
7745 					 * any was sent out.
7746 					 */
7747 					outchain = endoutchain = NULL;
7748 					auth = NULL;
7749 					auth_offset = 0;
7750 					if (!no_out_cnt)
7751 						*num_out += ctl_cnt;
7752 					/* recalc a clean slate and setup */
7753 					if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
7754 						mtu = (net->mtu - SCTP_MIN_OVERHEAD);
7755 					} else {
7756 						mtu = (net->mtu - SCTP_MIN_V4_OVERHEAD);
7757 					}
7758 					to_out = 0;
7759 					no_fragmentflg = 1;
7760 				}
7761 			}
7762 		}
7763 		/************************/
7764 		/* Control transmission */
7765 		/************************/
7766 		/* Now first lets go through the control queue */
7767 		for (chk = TAILQ_FIRST(&asoc->control_send_queue);
7768 		    chk; chk = nchk) {
7769 			nchk = TAILQ_NEXT(chk, sctp_next);
7770 			if (chk->whoTo != net) {
7771 				/*
7772 				 * No, not sent to the network we are
7773 				 * looking at
7774 				 */
7775 				continue;
7776 			}
7777 			if (chk->data == NULL) {
7778 				continue;
7779 			}
7780 			if (chk->sent != SCTP_DATAGRAM_UNSENT) {
7781 				/*
7782 				 * It must be unsent. Cookies and ASCONF's
7783 				 * hang around but there timers will force
7784 				 * when marked for resend.
7785 				 */
7786 				continue;
7787 			}
7788 			/*
7789 			 * if no AUTH is yet included and this chunk
7790 			 * requires it, make sure to account for it.  We
7791 			 * don't apply the size until the AUTH chunk is
7792 			 * actually added below in case there is no room for
7793 			 * this chunk. NOTE: we overload the use of "omtu"
7794 			 * here
7795 			 */
7796 			if ((auth == NULL) &&
7797 			    sctp_auth_is_required_chunk(chk->rec.chunk_id.id,
7798 			    stcb->asoc.peer_auth_chunks)) {
7799 				omtu = sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
7800 			} else
7801 				omtu = 0;
7802 			/* Here we do NOT factor the r_mtu */
7803 			if ((chk->send_size < (int)(mtu - omtu)) ||
7804 			    (chk->flags & CHUNK_FLAGS_FRAGMENT_OK)) {
7805 				/*
7806 				 * We probably should glom the mbuf chain
7807 				 * from the chk->data for control but the
7808 				 * problem is it becomes yet one more level
7809 				 * of tracking to do if for some reason
7810 				 * output fails. Then I have got to
7811 				 * reconstruct the merged control chain.. el
7812 				 * yucko.. for now we take the easy way and
7813 				 * do the copy
7814 				 */
7815 				/*
7816 				 * Add an AUTH chunk, if chunk requires it
7817 				 * save the offset into the chain for AUTH
7818 				 */
7819 				if ((auth == NULL) &&
7820 				    (sctp_auth_is_required_chunk(chk->rec.chunk_id.id,
7821 				    stcb->asoc.peer_auth_chunks))) {
7822 					outchain = sctp_add_auth_chunk(outchain,
7823 					    &endoutchain,
7824 					    &auth,
7825 					    &auth_offset,
7826 					    stcb,
7827 					    chk->rec.chunk_id.id);
7828 					SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
7829 				}
7830 				outchain = sctp_copy_mbufchain(chk->data, outchain, &endoutchain,
7831 				    (int)chk->rec.chunk_id.can_take_data,
7832 				    chk->send_size, chk->copy_by_ref);
7833 				if (outchain == NULL) {
7834 					*reason_code = 8;
7835 					SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
7836 					return (ENOMEM);
7837 				}
7838 				SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
7839 				/* update our MTU size */
7840 				if (mtu > (chk->send_size + omtu))
7841 					mtu -= (chk->send_size + omtu);
7842 				else
7843 					mtu = 0;
7844 				to_out += (chk->send_size + omtu);
7845 				/* Do clear IP_DF ? */
7846 				if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
7847 					no_fragmentflg = 0;
7848 				}
7849 				if (chk->rec.chunk_id.can_take_data)
7850 					chk->data = NULL;
7851 				/* Mark things to be removed, if needed */
7852 				if ((chk->rec.chunk_id.id == SCTP_SELECTIVE_ACK) ||
7853 				    (chk->rec.chunk_id.id == SCTP_NR_SELECTIVE_ACK) ||	/* EY */
7854 				    (chk->rec.chunk_id.id == SCTP_HEARTBEAT_REQUEST) ||
7855 				    (chk->rec.chunk_id.id == SCTP_HEARTBEAT_ACK) ||
7856 				    (chk->rec.chunk_id.id == SCTP_SHUTDOWN) ||
7857 				    (chk->rec.chunk_id.id == SCTP_SHUTDOWN_ACK) ||
7858 				    (chk->rec.chunk_id.id == SCTP_OPERATION_ERROR) ||
7859 				    (chk->rec.chunk_id.id == SCTP_COOKIE_ACK) ||
7860 				    (chk->rec.chunk_id.id == SCTP_ECN_CWR) ||
7861 				    (chk->rec.chunk_id.id == SCTP_PACKET_DROPPED) ||
7862 				    (chk->rec.chunk_id.id == SCTP_ASCONF_ACK)) {
7863 
7864 					if (chk->rec.chunk_id.id == SCTP_HEARTBEAT_REQUEST) {
7865 						hbflag = 1;
7866 						/*
7867 						 * JRS 5/14/07 - Set the
7868 						 * flag to say a heartbeat
7869 						 * is being sent.
7870 						 */
7871 						pf_hbflag = 1;
7872 					}
7873 					/* remove these chunks at the end */
7874 					if (chk->rec.chunk_id.id == SCTP_SELECTIVE_ACK) {
7875 						/* turn off the timer */
7876 						if (SCTP_OS_TIMER_PENDING(&stcb->asoc.dack_timer.timer)) {
7877 							sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
7878 							    inp, stcb, net, SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_1);
7879 						}
7880 					}
7881 					/*
7882 					 * EY -Nr-sack version of the above
7883 					 * if statement
7884 					 */
7885 					if ((SCTP_BASE_SYSCTL(sctp_nr_sack_on_off) && asoc->peer_supports_nr_sack) &&
7886 					    (chk->rec.chunk_id.id == SCTP_NR_SELECTIVE_ACK)) {	/* EY !?! */
7887 						/* turn off the timer */
7888 						if (SCTP_OS_TIMER_PENDING(&stcb->asoc.dack_timer.timer)) {
7889 							sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
7890 							    inp, stcb, net, SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_1);
7891 						}
7892 					}
7893 					ctl_cnt++;
7894 				} else {
7895 					/*
7896 					 * Other chunks, since they have
7897 					 * timers running (i.e. COOKIE) we
7898 					 * just "trust" that it gets sent or
7899 					 * retransmitted.
7900 					 */
7901 					ctl_cnt++;
7902 					if (chk->rec.chunk_id.id == SCTP_COOKIE_ECHO) {
7903 						cookie = 1;
7904 						no_out_cnt = 1;
7905 					}
7906 					chk->sent = SCTP_DATAGRAM_SENT;
7907 					chk->snd_count++;
7908 				}
7909 				if (mtu == 0) {
7910 					/*
7911 					 * Ok we are out of room but we can
7912 					 * output without effecting the
7913 					 * flight size since this little guy
7914 					 * is a control only packet.
7915 					 */
7916 					if (asconf) {
7917 						sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp, stcb, net);
7918 						/*
7919 						 * do NOT clear the asconf
7920 						 * flag as it is used to do
7921 						 * appropriate source
7922 						 * address selection.
7923 						 */
7924 					}
7925 					if (cookie) {
7926 						sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, inp, stcb, net);
7927 						cookie = 0;
7928 					}
7929 					if ((error = sctp_lowlevel_chunk_output(inp, stcb, net,
7930 					    (struct sockaddr *)&net->ro._l_addr,
7931 					    outchain,
7932 					    auth_offset, auth,
7933 					    stcb->asoc.authinfo.active_keyid,
7934 					    no_fragmentflg, 0, NULL, asconf,
7935 					    inp->sctp_lport, stcb->rport,
7936 					    htonl(stcb->asoc.peer_vtag),
7937 					    net->port, so_locked, NULL))) {
7938 						if (error == ENOBUFS) {
7939 							asoc->ifp_had_enobuf = 1;
7940 							SCTP_STAT_INCR(sctps_lowlevelerr);
7941 						}
7942 						if (from_where == 0) {
7943 							SCTP_STAT_INCR(sctps_lowlevelerrusr);
7944 						}
7945 						/* error, could not output */
7946 						if (hbflag) {
7947 							if (*now_filled == 0) {
7948 								(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
7949 								*now_filled = 1;
7950 								*now = net->last_sent_time;
7951 							} else {
7952 								net->last_sent_time = *now;
7953 							}
7954 							hbflag = 0;
7955 						}
7956 						if (error == EHOSTUNREACH) {
7957 							/*
7958 							 * Destination went
7959 							 * unreachable
7960 							 * during this send
7961 							 */
7962 							sctp_move_to_an_alt(stcb, asoc, net);
7963 						}
7964 						*reason_code = 7;
7965 						continue;
7966 					} else
7967 						asoc->ifp_had_enobuf = 0;
7968 					/* Only HB or ASCONF advances time */
7969 					if (hbflag) {
7970 						if (*now_filled == 0) {
7971 							(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
7972 							*now_filled = 1;
7973 							*now = net->last_sent_time;
7974 						} else {
7975 							net->last_sent_time = *now;
7976 						}
7977 						hbflag = 0;
7978 					}
7979 					/*
7980 					 * increase the number we sent, if a
7981 					 * cookie is sent we don't tell them
7982 					 * any was sent out.
7983 					 */
7984 					outchain = endoutchain = NULL;
7985 					auth = NULL;
7986 					auth_offset = 0;
7987 					if (!no_out_cnt)
7988 						*num_out += ctl_cnt;
7989 					/* recalc a clean slate and setup */
7990 					if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
7991 						mtu = (net->mtu - SCTP_MIN_OVERHEAD);
7992 					} else {
7993 						mtu = (net->mtu - SCTP_MIN_V4_OVERHEAD);
7994 					}
7995 					to_out = 0;
7996 					no_fragmentflg = 1;
7997 				}
7998 			}
7999 		}
8000 		/* JRI: if dest is in PF state, do not send data to it */
8001 		if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) &&
8002 		    SCTP_BASE_SYSCTL(sctp_cmt_pf) &&
8003 		    (net->dest_state & SCTP_ADDR_PF)) {
8004 			goto no_data_fill;
8005 		}
8006 		if (net->flight_size >= net->cwnd) {
8007 			goto no_data_fill;
8008 		}
8009 		if ((SCTP_BASE_SYSCTL(sctp_cmt_on_off)) &&
8010 		    (net->flight_size > max_rwnd_per_dest)) {
8011 			goto no_data_fill;
8012 		}
8013 		/*********************/
8014 		/* Data transmission */
8015 		/*********************/
8016 		/*
8017 		 * if AUTH for DATA is required and no AUTH has been added
8018 		 * yet, account for this in the mtu now... if no data can be
8019 		 * bundled, this adjustment won't matter anyways since the
8020 		 * packet will be going out...
8021 		 */
8022 		data_auth_reqd = sctp_auth_is_required_chunk(SCTP_DATA,
8023 		    stcb->asoc.peer_auth_chunks);
8024 		if (data_auth_reqd && (auth == NULL)) {
8025 			mtu -= sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
8026 		}
8027 		/* now lets add any data within the MTU constraints */
8028 		switch (((struct sockaddr *)&net->ro._l_addr)->sa_family) {
8029 		case AF_INET:
8030 			if (net->mtu > (sizeof(struct ip) + sizeof(struct sctphdr)))
8031 				omtu = net->mtu - (sizeof(struct ip) + sizeof(struct sctphdr));
8032 			else
8033 				omtu = 0;
8034 			break;
8035 #ifdef INET6
8036 		case AF_INET6:
8037 			if (net->mtu > (sizeof(struct ip6_hdr) + sizeof(struct sctphdr)))
8038 				omtu = net->mtu - (sizeof(struct ip6_hdr) + sizeof(struct sctphdr));
8039 			else
8040 				omtu = 0;
8041 			break;
8042 #endif
8043 		default:
8044 			/* TSNH */
8045 			omtu = 0;
8046 			break;
8047 		}
8048 		if ((((asoc->state & SCTP_STATE_OPEN) == SCTP_STATE_OPEN) &&
8049 		    (skip_data_for_this_net == 0)) ||
8050 		    (cookie)) {
8051 			for (chk = TAILQ_FIRST(&asoc->send_queue); chk; chk = nchk) {
8052 				if (no_data_chunks) {
8053 					/* let only control go out */
8054 					*reason_code = 1;
8055 					break;
8056 				}
8057 				if (net->flight_size >= net->cwnd) {
8058 					/* skip this net, no room for data */
8059 					*reason_code = 2;
8060 					break;
8061 				}
8062 				nchk = TAILQ_NEXT(chk, sctp_next);
8063 				if (SCTP_BASE_SYSCTL(sctp_cmt_on_off)) {
8064 					if (chk->whoTo != net) {
8065 						/*
8066 						 * For CMT, steal the data
8067 						 * to this network if its
8068 						 * not set here.
8069 						 */
8070 						sctp_free_remote_addr(chk->whoTo);
8071 						chk->whoTo = net;
8072 						atomic_add_int(&chk->whoTo->ref_count, 1);
8073 					}
8074 				} else if (chk->whoTo != net) {
8075 					/* No, not sent to this net */
8076 					continue;
8077 				}
8078 				if ((chk->send_size > omtu) && ((chk->flags & CHUNK_FLAGS_FRAGMENT_OK) == 0)) {
8079 					/*-
8080 					 * strange, we have a chunk that is
8081 					 * to big for its destination and
8082 					 * yet no fragment ok flag.
8083 					 * Something went wrong when the
8084 					 * PMTU changed...we did not mark
8085 					 * this chunk for some reason?? I
8086 					 * will fix it here by letting IP
8087 					 * fragment it for now and printing
8088 					 * a warning. This really should not
8089 					 * happen ...
8090 					 */
8091 					SCTP_PRINTF("Warning chunk of %d bytes > mtu:%d and yet PMTU disc missed\n",
8092 					    chk->send_size, mtu);
8093 					chk->flags |= CHUNK_FLAGS_FRAGMENT_OK;
8094 				}
8095 				if (SCTP_BASE_SYSCTL(sctp_enable_sack_immediately) &&
8096 				    ((asoc->state & SCTP_STATE_SHUTDOWN_PENDING) == SCTP_STATE_SHUTDOWN_PENDING)) {
8097 					struct sctp_data_chunk *dchkh;
8098 
8099 					dchkh = mtod(chk->data, struct sctp_data_chunk *);
8100 					dchkh->ch.chunk_flags |= SCTP_DATA_SACK_IMMEDIATELY;
8101 				}
8102 				if (((chk->send_size <= mtu) && (chk->send_size <= r_mtu)) ||
8103 				    ((chk->flags & CHUNK_FLAGS_FRAGMENT_OK) && (chk->send_size <= asoc->peers_rwnd))) {
8104 					/* ok we will add this one */
8105 
8106 					/*
8107 					 * Add an AUTH chunk, if chunk
8108 					 * requires it, save the offset into
8109 					 * the chain for AUTH
8110 					 */
8111 					if (data_auth_reqd) {
8112 						if (auth == NULL) {
8113 							outchain = sctp_add_auth_chunk(outchain,
8114 							    &endoutchain,
8115 							    &auth,
8116 							    &auth_offset,
8117 							    stcb,
8118 							    SCTP_DATA);
8119 							auth_keyid = chk->auth_keyid;
8120 							override_ok = 0;
8121 							SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
8122 						} else if (override_ok) {
8123 							/*
8124 							 * use this data's
8125 							 * keyid
8126 							 */
8127 							auth_keyid = chk->auth_keyid;
8128 							override_ok = 0;
8129 						} else if (auth_keyid != chk->auth_keyid) {
8130 							/*
8131 							 * different keyid,
8132 							 * so done bundling
8133 							 */
8134 							break;
8135 						}
8136 					}
8137 					outchain = sctp_copy_mbufchain(chk->data, outchain, &endoutchain, 0,
8138 					    chk->send_size, chk->copy_by_ref);
8139 					if (outchain == NULL) {
8140 						SCTPDBG(SCTP_DEBUG_OUTPUT3, "No memory?\n");
8141 						if (!SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer)) {
8142 							sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
8143 						}
8144 						*reason_code = 3;
8145 						SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
8146 						return (ENOMEM);
8147 					}
8148 					/* upate our MTU size */
8149 					/* Do clear IP_DF ? */
8150 					if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
8151 						no_fragmentflg = 0;
8152 					}
8153 					/* unsigned subtraction of mtu */
8154 					if (mtu > chk->send_size)
8155 						mtu -= chk->send_size;
8156 					else
8157 						mtu = 0;
8158 					/* unsigned subtraction of r_mtu */
8159 					if (r_mtu > chk->send_size)
8160 						r_mtu -= chk->send_size;
8161 					else
8162 						r_mtu = 0;
8163 
8164 					to_out += chk->send_size;
8165 					if ((to_out > mx_mtu) && no_fragmentflg) {
8166 #ifdef INVARIANTS
8167 						panic("Exceeding mtu of %d out size is %d", mx_mtu, to_out);
8168 #else
8169 						SCTP_PRINTF("Exceeding mtu of %d out size is %d\n",
8170 						    mx_mtu, to_out);
8171 #endif
8172 					}
8173 					chk->window_probe = 0;
8174 					data_list[bundle_at++] = chk;
8175 					if (bundle_at >= SCTP_MAX_DATA_BUNDLING) {
8176 						mtu = 0;
8177 						break;
8178 					}
8179 					if (chk->sent == SCTP_DATAGRAM_UNSENT) {
8180 						if ((chk->rec.data.rcv_flags & SCTP_DATA_UNORDERED) == 0) {
8181 							SCTP_STAT_INCR_COUNTER64(sctps_outorderchunks);
8182 						} else {
8183 							SCTP_STAT_INCR_COUNTER64(sctps_outunorderchunks);
8184 						}
8185 						if (((chk->rec.data.rcv_flags & SCTP_DATA_LAST_FRAG) == SCTP_DATA_LAST_FRAG) &&
8186 						    ((chk->rec.data.rcv_flags & SCTP_DATA_FIRST_FRAG) == 0))
8187 							/*
8188 							 * Count number of
8189 							 * user msg's that
8190 							 * were fragmented
8191 							 * we do this by
8192 							 * counting when we
8193 							 * see a LAST
8194 							 * fragment only.
8195 							 */
8196 							SCTP_STAT_INCR_COUNTER64(sctps_fragusrmsgs);
8197 					}
8198 					if ((mtu == 0) || (r_mtu == 0) || (one_chunk)) {
8199 						if ((one_chunk) && (stcb->asoc.total_flight == 0)) {
8200 							data_list[0]->window_probe = 1;
8201 							net->window_probe = 1;
8202 						}
8203 						break;
8204 					}
8205 				} else {
8206 					/*
8207 					 * Must be sent in order of the
8208 					 * TSN's (on a network)
8209 					 */
8210 					break;
8211 				}
8212 			}	/* for (chunk gather loop for this net) */
8213 		}		/* if asoc.state OPEN */
8214 no_data_fill:
8215 		/* Is there something to send for this destination? */
8216 		if (outchain) {
8217 			/* We may need to start a control timer or two */
8218 			if (asconf) {
8219 				sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp,
8220 				    stcb, net);
8221 				/*
8222 				 * do NOT clear the asconf flag as it is
8223 				 * used to do appropriate source address
8224 				 * selection.
8225 				 */
8226 			}
8227 			if (cookie) {
8228 				sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, inp, stcb, net);
8229 				cookie = 0;
8230 			}
8231 			/* must start a send timer if data is being sent */
8232 			if (bundle_at && (!SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer))) {
8233 				/*
8234 				 * no timer running on this destination
8235 				 * restart it.
8236 				 */
8237 				sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
8238 			} else if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) &&
8239 				    SCTP_BASE_SYSCTL(sctp_cmt_pf) &&
8240 				    pf_hbflag &&
8241 				    ((net->dest_state & SCTP_ADDR_PF) == SCTP_ADDR_PF) &&
8242 			    (!SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer))) {
8243 				/*
8244 				 * JRS 5/14/07 - If a HB has been sent to a
8245 				 * PF destination and no T3 timer is
8246 				 * currently running, start the T3 timer to
8247 				 * track the HBs that were sent.
8248 				 */
8249 				sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
8250 			}
8251 			/* Now send it, if there is anything to send :> */
8252 			if ((error = sctp_lowlevel_chunk_output(inp,
8253 			    stcb,
8254 			    net,
8255 			    (struct sockaddr *)&net->ro._l_addr,
8256 			    outchain,
8257 			    auth_offset,
8258 			    auth,
8259 			    auth_keyid,
8260 			    no_fragmentflg,
8261 			    bundle_at,
8262 			    data_list[0],
8263 			    asconf,
8264 			    inp->sctp_lport, stcb->rport,
8265 			    htonl(stcb->asoc.peer_vtag),
8266 			    net->port, so_locked, NULL))) {
8267 				/* error, we could not output */
8268 				if (error == ENOBUFS) {
8269 					SCTP_STAT_INCR(sctps_lowlevelerr);
8270 					asoc->ifp_had_enobuf = 1;
8271 				}
8272 				if (from_where == 0) {
8273 					SCTP_STAT_INCR(sctps_lowlevelerrusr);
8274 				}
8275 				SCTPDBG(SCTP_DEBUG_OUTPUT3, "Gak send error %d\n", error);
8276 				if (hbflag) {
8277 					if (*now_filled == 0) {
8278 						(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
8279 						*now_filled = 1;
8280 						*now = net->last_sent_time;
8281 					} else {
8282 						net->last_sent_time = *now;
8283 					}
8284 					hbflag = 0;
8285 				}
8286 				if (error == EHOSTUNREACH) {
8287 					/*
8288 					 * Destination went unreachable
8289 					 * during this send
8290 					 */
8291 					sctp_move_to_an_alt(stcb, asoc, net);
8292 				}
8293 				*reason_code = 6;
8294 				/*-
8295 				 * I add this line to be paranoid. As far as
8296 				 * I can tell the continue, takes us back to
8297 				 * the top of the for, but just to make sure
8298 				 * I will reset these again here.
8299 				 */
8300 				ctl_cnt = bundle_at = 0;
8301 				continue;	/* This takes us back to the
8302 						 * for() for the nets. */
8303 			} else {
8304 				asoc->ifp_had_enobuf = 0;
8305 			}
8306 			outchain = endoutchain = NULL;
8307 			auth = NULL;
8308 			auth_offset = 0;
8309 			if (bundle_at || hbflag) {
8310 				/* For data/asconf and hb set time */
8311 				if (*now_filled == 0) {
8312 					(void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time);
8313 					*now_filled = 1;
8314 					*now = net->last_sent_time;
8315 				} else {
8316 					net->last_sent_time = *now;
8317 				}
8318 			}
8319 			if (!no_out_cnt) {
8320 				*num_out += (ctl_cnt + bundle_at);
8321 			}
8322 			if (bundle_at) {
8323 				/* setup for a RTO measurement */
8324 				tsns_sent = data_list[0]->rec.data.TSN_seq;
8325 				/* fill time if not already filled */
8326 				if (*now_filled == 0) {
8327 					(void)SCTP_GETTIME_TIMEVAL(&asoc->time_last_sent);
8328 					*now_filled = 1;
8329 					*now = asoc->time_last_sent;
8330 				} else {
8331 					asoc->time_last_sent = *now;
8332 				}
8333 				data_list[0]->do_rtt = 1;
8334 				SCTP_STAT_INCR_BY(sctps_senddata, bundle_at);
8335 				sctp_clean_up_datalist(stcb, asoc, data_list, bundle_at, net);
8336 				if (SCTP_BASE_SYSCTL(sctp_early_fr)) {
8337 					if (net->flight_size < net->cwnd) {
8338 						/* start or restart it */
8339 						if (SCTP_OS_TIMER_PENDING(&net->fr_timer.timer)) {
8340 							sctp_timer_stop(SCTP_TIMER_TYPE_EARLYFR, inp, stcb, net,
8341 							    SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_2);
8342 						}
8343 						SCTP_STAT_INCR(sctps_earlyfrstrout);
8344 						sctp_timer_start(SCTP_TIMER_TYPE_EARLYFR, inp, stcb, net);
8345 					} else {
8346 						/* stop it if its running */
8347 						if (SCTP_OS_TIMER_PENDING(&net->fr_timer.timer)) {
8348 							SCTP_STAT_INCR(sctps_earlyfrstpout);
8349 							sctp_timer_stop(SCTP_TIMER_TYPE_EARLYFR, inp, stcb, net,
8350 							    SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_3);
8351 						}
8352 					}
8353 				}
8354 			}
8355 			if (one_chunk) {
8356 				break;
8357 			}
8358 		}
8359 		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
8360 			sctp_log_cwnd(stcb, net, tsns_sent, SCTP_CWND_LOG_FROM_SEND);
8361 		}
8362 	}
8363 	if (old_start_at == NULL) {
8364 		old_start_at = start_at;
8365 		start_at = TAILQ_FIRST(&asoc->nets);
8366 		if (old_start_at)
8367 			goto again_one_more_time;
8368 	}
8369 	/*
8370 	 * At the end there should be no NON timed chunks hanging on this
8371 	 * queue.
8372 	 */
8373 	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
8374 		sctp_log_cwnd(stcb, net, *num_out, SCTP_CWND_LOG_FROM_SEND);
8375 	}
8376 	if ((*num_out == 0) && (*reason_code == 0)) {
8377 		*reason_code = 4;
8378 	} else {
8379 		*reason_code = 5;
8380 	}
8381 	sctp_clean_up_ctl(stcb, asoc);
8382 	return (0);
8383 }
8384 
8385 void
8386 sctp_queue_op_err(struct sctp_tcb *stcb, struct mbuf *op_err)
8387 {
8388 	/*-
8389 	 * Prepend a OPERATIONAL_ERROR chunk header and put on the end of
8390 	 * the control chunk queue.
8391 	 */
8392 	struct sctp_chunkhdr *hdr;
8393 	struct sctp_tmit_chunk *chk;
8394 	struct mbuf *mat;
8395 
8396 	SCTP_TCB_LOCK_ASSERT(stcb);
8397 	sctp_alloc_a_chunk(stcb, chk);
8398 	if (chk == NULL) {
8399 		/* no memory */
8400 		sctp_m_freem(op_err);
8401 		return;
8402 	}
8403 	chk->copy_by_ref = 0;
8404 	SCTP_BUF_PREPEND(op_err, sizeof(struct sctp_chunkhdr), M_DONTWAIT);
8405 	if (op_err == NULL) {
8406 		sctp_free_a_chunk(stcb, chk);
8407 		return;
8408 	}
8409 	chk->send_size = 0;
8410 	mat = op_err;
8411 	while (mat != NULL) {
8412 		chk->send_size += SCTP_BUF_LEN(mat);
8413 		mat = SCTP_BUF_NEXT(mat);
8414 	}
8415 	chk->rec.chunk_id.id = SCTP_OPERATION_ERROR;
8416 	chk->rec.chunk_id.can_take_data = 1;
8417 	chk->sent = SCTP_DATAGRAM_UNSENT;
8418 	chk->snd_count = 0;
8419 	chk->flags = 0;
8420 	chk->asoc = &stcb->asoc;
8421 	chk->data = op_err;
8422 	chk->whoTo = chk->asoc->primary_destination;
8423 	atomic_add_int(&chk->whoTo->ref_count, 1);
8424 	hdr = mtod(op_err, struct sctp_chunkhdr *);
8425 	hdr->chunk_type = SCTP_OPERATION_ERROR;
8426 	hdr->chunk_flags = 0;
8427 	hdr->chunk_length = htons(chk->send_size);
8428 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue,
8429 	    chk,
8430 	    sctp_next);
8431 	chk->asoc->ctrl_queue_cnt++;
8432 }
8433 
8434 int
8435 sctp_send_cookie_echo(struct mbuf *m,
8436     int offset,
8437     struct sctp_tcb *stcb,
8438     struct sctp_nets *net)
8439 {
8440 	/*-
8441 	 * pull out the cookie and put it at the front of the control chunk
8442 	 * queue.
8443 	 */
8444 	int at;
8445 	struct mbuf *cookie;
8446 	struct sctp_paramhdr parm, *phdr;
8447 	struct sctp_chunkhdr *hdr;
8448 	struct sctp_tmit_chunk *chk;
8449 	uint16_t ptype, plen;
8450 
8451 	/* First find the cookie in the param area */
8452 	cookie = NULL;
8453 	at = offset + sizeof(struct sctp_init_chunk);
8454 
8455 	SCTP_TCB_LOCK_ASSERT(stcb);
8456 	do {
8457 		phdr = sctp_get_next_param(m, at, &parm, sizeof(parm));
8458 		if (phdr == NULL) {
8459 			return (-3);
8460 		}
8461 		ptype = ntohs(phdr->param_type);
8462 		plen = ntohs(phdr->param_length);
8463 		if (ptype == SCTP_STATE_COOKIE) {
8464 			int pad;
8465 
8466 			/* found the cookie */
8467 			if ((pad = (plen % 4))) {
8468 				plen += 4 - pad;
8469 			}
8470 			cookie = SCTP_M_COPYM(m, at, plen, M_DONTWAIT);
8471 			if (cookie == NULL) {
8472 				/* No memory */
8473 				return (-2);
8474 			}
8475 #ifdef SCTP_MBUF_LOGGING
8476 			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
8477 				struct mbuf *mat;
8478 
8479 				mat = cookie;
8480 				while (mat) {
8481 					if (SCTP_BUF_IS_EXTENDED(mat)) {
8482 						sctp_log_mb(mat, SCTP_MBUF_ICOPY);
8483 					}
8484 					mat = SCTP_BUF_NEXT(mat);
8485 				}
8486 			}
8487 #endif
8488 			break;
8489 		}
8490 		at += SCTP_SIZE32(plen);
8491 	} while (phdr);
8492 	if (cookie == NULL) {
8493 		/* Did not find the cookie */
8494 		return (-3);
8495 	}
8496 	/* ok, we got the cookie lets change it into a cookie echo chunk */
8497 
8498 	/* first the change from param to cookie */
8499 	hdr = mtod(cookie, struct sctp_chunkhdr *);
8500 	hdr->chunk_type = SCTP_COOKIE_ECHO;
8501 	hdr->chunk_flags = 0;
8502 	/* get the chunk stuff now and place it in the FRONT of the queue */
8503 	sctp_alloc_a_chunk(stcb, chk);
8504 	if (chk == NULL) {
8505 		/* no memory */
8506 		sctp_m_freem(cookie);
8507 		return (-5);
8508 	}
8509 	chk->copy_by_ref = 0;
8510 	chk->send_size = plen;
8511 	chk->rec.chunk_id.id = SCTP_COOKIE_ECHO;
8512 	chk->rec.chunk_id.can_take_data = 0;
8513 	chk->sent = SCTP_DATAGRAM_UNSENT;
8514 	chk->snd_count = 0;
8515 	chk->flags = CHUNK_FLAGS_FRAGMENT_OK;
8516 	chk->asoc = &stcb->asoc;
8517 	chk->data = cookie;
8518 	chk->whoTo = chk->asoc->primary_destination;
8519 	atomic_add_int(&chk->whoTo->ref_count, 1);
8520 	TAILQ_INSERT_HEAD(&chk->asoc->control_send_queue, chk, sctp_next);
8521 	chk->asoc->ctrl_queue_cnt++;
8522 	return (0);
8523 }
8524 
8525 void
8526 sctp_send_heartbeat_ack(struct sctp_tcb *stcb,
8527     struct mbuf *m,
8528     int offset,
8529     int chk_length,
8530     struct sctp_nets *net)
8531 {
8532 	/*
8533 	 * take a HB request and make it into a HB ack and send it.
8534 	 */
8535 	struct mbuf *outchain;
8536 	struct sctp_chunkhdr *chdr;
8537 	struct sctp_tmit_chunk *chk;
8538 
8539 
8540 	if (net == NULL)
8541 		/* must have a net pointer */
8542 		return;
8543 
8544 	outchain = SCTP_M_COPYM(m, offset, chk_length, M_DONTWAIT);
8545 	if (outchain == NULL) {
8546 		/* gak out of memory */
8547 		return;
8548 	}
8549 #ifdef SCTP_MBUF_LOGGING
8550 	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
8551 		struct mbuf *mat;
8552 
8553 		mat = outchain;
8554 		while (mat) {
8555 			if (SCTP_BUF_IS_EXTENDED(mat)) {
8556 				sctp_log_mb(mat, SCTP_MBUF_ICOPY);
8557 			}
8558 			mat = SCTP_BUF_NEXT(mat);
8559 		}
8560 	}
8561 #endif
8562 	chdr = mtod(outchain, struct sctp_chunkhdr *);
8563 	chdr->chunk_type = SCTP_HEARTBEAT_ACK;
8564 	chdr->chunk_flags = 0;
8565 	if (chk_length % 4) {
8566 		/* need pad */
8567 		uint32_t cpthis = 0;
8568 		int padlen;
8569 
8570 		padlen = 4 - (chk_length % 4);
8571 		m_copyback(outchain, chk_length, padlen, (caddr_t)&cpthis);
8572 	}
8573 	sctp_alloc_a_chunk(stcb, chk);
8574 	if (chk == NULL) {
8575 		/* no memory */
8576 		sctp_m_freem(outchain);
8577 		return;
8578 	}
8579 	chk->copy_by_ref = 0;
8580 	chk->send_size = chk_length;
8581 	chk->rec.chunk_id.id = SCTP_HEARTBEAT_ACK;
8582 	chk->rec.chunk_id.can_take_data = 1;
8583 	chk->sent = SCTP_DATAGRAM_UNSENT;
8584 	chk->snd_count = 0;
8585 	chk->flags = 0;
8586 	chk->asoc = &stcb->asoc;
8587 	chk->data = outchain;
8588 	chk->whoTo = net;
8589 	atomic_add_int(&chk->whoTo->ref_count, 1);
8590 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
8591 	chk->asoc->ctrl_queue_cnt++;
8592 }
8593 
8594 void
8595 sctp_send_cookie_ack(struct sctp_tcb *stcb)
8596 {
8597 	/* formulate and queue a cookie-ack back to sender */
8598 	struct mbuf *cookie_ack;
8599 	struct sctp_chunkhdr *hdr;
8600 	struct sctp_tmit_chunk *chk;
8601 
8602 	cookie_ack = NULL;
8603 	SCTP_TCB_LOCK_ASSERT(stcb);
8604 
8605 	cookie_ack = sctp_get_mbuf_for_msg(sizeof(struct sctp_chunkhdr), 0, M_DONTWAIT, 1, MT_HEADER);
8606 	if (cookie_ack == NULL) {
8607 		/* no mbuf's */
8608 		return;
8609 	}
8610 	SCTP_BUF_RESV_UF(cookie_ack, SCTP_MIN_OVERHEAD);
8611 	sctp_alloc_a_chunk(stcb, chk);
8612 	if (chk == NULL) {
8613 		/* no memory */
8614 		sctp_m_freem(cookie_ack);
8615 		return;
8616 	}
8617 	chk->copy_by_ref = 0;
8618 	chk->send_size = sizeof(struct sctp_chunkhdr);
8619 	chk->rec.chunk_id.id = SCTP_COOKIE_ACK;
8620 	chk->rec.chunk_id.can_take_data = 1;
8621 	chk->sent = SCTP_DATAGRAM_UNSENT;
8622 	chk->snd_count = 0;
8623 	chk->flags = 0;
8624 	chk->asoc = &stcb->asoc;
8625 	chk->data = cookie_ack;
8626 	if (chk->asoc->last_control_chunk_from != NULL) {
8627 		chk->whoTo = chk->asoc->last_control_chunk_from;
8628 	} else {
8629 		chk->whoTo = chk->asoc->primary_destination;
8630 	}
8631 	atomic_add_int(&chk->whoTo->ref_count, 1);
8632 	hdr = mtod(cookie_ack, struct sctp_chunkhdr *);
8633 	hdr->chunk_type = SCTP_COOKIE_ACK;
8634 	hdr->chunk_flags = 0;
8635 	hdr->chunk_length = htons(chk->send_size);
8636 	SCTP_BUF_LEN(cookie_ack) = chk->send_size;
8637 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
8638 	chk->asoc->ctrl_queue_cnt++;
8639 	return;
8640 }
8641 
8642 
8643 void
8644 sctp_send_shutdown_ack(struct sctp_tcb *stcb, struct sctp_nets *net)
8645 {
8646 	/* formulate and queue a SHUTDOWN-ACK back to the sender */
8647 	struct mbuf *m_shutdown_ack;
8648 	struct sctp_shutdown_ack_chunk *ack_cp;
8649 	struct sctp_tmit_chunk *chk;
8650 
8651 	m_shutdown_ack = sctp_get_mbuf_for_msg(sizeof(struct sctp_shutdown_ack_chunk), 0, M_DONTWAIT, 1, MT_HEADER);
8652 	if (m_shutdown_ack == NULL) {
8653 		/* no mbuf's */
8654 		return;
8655 	}
8656 	SCTP_BUF_RESV_UF(m_shutdown_ack, SCTP_MIN_OVERHEAD);
8657 	sctp_alloc_a_chunk(stcb, chk);
8658 	if (chk == NULL) {
8659 		/* no memory */
8660 		sctp_m_freem(m_shutdown_ack);
8661 		return;
8662 	}
8663 	chk->copy_by_ref = 0;
8664 	chk->send_size = sizeof(struct sctp_chunkhdr);
8665 	chk->rec.chunk_id.id = SCTP_SHUTDOWN_ACK;
8666 	chk->rec.chunk_id.can_take_data = 1;
8667 	chk->sent = SCTP_DATAGRAM_UNSENT;
8668 	chk->snd_count = 0;
8669 	chk->flags = 0;
8670 	chk->asoc = &stcb->asoc;
8671 	chk->data = m_shutdown_ack;
8672 	chk->whoTo = net;
8673 	atomic_add_int(&net->ref_count, 1);
8674 
8675 	ack_cp = mtod(m_shutdown_ack, struct sctp_shutdown_ack_chunk *);
8676 	ack_cp->ch.chunk_type = SCTP_SHUTDOWN_ACK;
8677 	ack_cp->ch.chunk_flags = 0;
8678 	ack_cp->ch.chunk_length = htons(chk->send_size);
8679 	SCTP_BUF_LEN(m_shutdown_ack) = chk->send_size;
8680 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
8681 	chk->asoc->ctrl_queue_cnt++;
8682 	return;
8683 }
8684 
8685 void
8686 sctp_send_shutdown(struct sctp_tcb *stcb, struct sctp_nets *net)
8687 {
8688 	/* formulate and queue a SHUTDOWN to the sender */
8689 	struct mbuf *m_shutdown;
8690 	struct sctp_shutdown_chunk *shutdown_cp;
8691 	struct sctp_tmit_chunk *chk;
8692 
8693 	m_shutdown = sctp_get_mbuf_for_msg(sizeof(struct sctp_shutdown_chunk), 0, M_DONTWAIT, 1, MT_HEADER);
8694 	if (m_shutdown == NULL) {
8695 		/* no mbuf's */
8696 		return;
8697 	}
8698 	SCTP_BUF_RESV_UF(m_shutdown, SCTP_MIN_OVERHEAD);
8699 	sctp_alloc_a_chunk(stcb, chk);
8700 	if (chk == NULL) {
8701 		/* no memory */
8702 		sctp_m_freem(m_shutdown);
8703 		return;
8704 	}
8705 	chk->copy_by_ref = 0;
8706 	chk->send_size = sizeof(struct sctp_shutdown_chunk);
8707 	chk->rec.chunk_id.id = SCTP_SHUTDOWN;
8708 	chk->rec.chunk_id.can_take_data = 1;
8709 	chk->sent = SCTP_DATAGRAM_UNSENT;
8710 	chk->snd_count = 0;
8711 	chk->flags = 0;
8712 	chk->asoc = &stcb->asoc;
8713 	chk->data = m_shutdown;
8714 	chk->whoTo = net;
8715 	atomic_add_int(&net->ref_count, 1);
8716 
8717 	shutdown_cp = mtod(m_shutdown, struct sctp_shutdown_chunk *);
8718 	shutdown_cp->ch.chunk_type = SCTP_SHUTDOWN;
8719 	shutdown_cp->ch.chunk_flags = 0;
8720 	shutdown_cp->ch.chunk_length = htons(chk->send_size);
8721 	shutdown_cp->cumulative_tsn_ack = htonl(stcb->asoc.cumulative_tsn);
8722 	SCTP_BUF_LEN(m_shutdown) = chk->send_size;
8723 	TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
8724 	chk->asoc->ctrl_queue_cnt++;
8725 	return;
8726 }
8727 
8728 void
8729 sctp_send_asconf(struct sctp_tcb *stcb, struct sctp_nets *net, int addr_locked)
8730 {
8731 	/*
8732 	 * formulate and queue an ASCONF to the peer. ASCONF parameters
8733 	 * should be queued on the assoc queue.
8734 	 */
8735 	struct sctp_tmit_chunk *chk;
8736 	struct mbuf *m_asconf;
8737 	int len;
8738 
8739 	SCTP_TCB_LOCK_ASSERT(stcb);
8740 
8741 	if ((!TAILQ_EMPTY(&stcb->asoc.asconf_send_queue)) &&
8742 	    (!sctp_is_feature_on(stcb->sctp_ep, SCTP_PCB_FLAGS_MULTIPLE_ASCONFS))) {
8743 		/* can't send a new one if there is one in flight already */
8744 		return;
8745 	}
8746 	/* compose an ASCONF chunk, maximum length is PMTU */
8747 	m_asconf = sctp_compose_asconf(stcb, &len, addr_locked);
8748 	if (m_asconf == NULL) {
8749 		return;
8750 	}
8751 	sctp_alloc_a_chunk(stcb, chk);
8752 	if (chk == NULL) {
8753 		/* no memory */
8754 		sctp_m_freem(m_asconf);
8755 		return;
8756 	}
8757 	chk->copy_by_ref = 0;
8758 	chk->data = m_asconf;
8759 	chk->send_size = len;
8760 	chk->rec.chunk_id.id = SCTP_ASCONF;
8761 	chk->rec.chunk_id.can_take_data = 0;
8762 	chk->sent = SCTP_DATAGRAM_UNSENT;
8763 	chk->snd_count = 0;
8764 	chk->flags = CHUNK_FLAGS_FRAGMENT_OK;
8765 	chk->asoc = &stcb->asoc;
8766 	chk->whoTo = net;
8767 	atomic_add_int(&chk->whoTo->ref_count, 1);
8768 	TAILQ_INSERT_TAIL(&chk->asoc->asconf_send_queue, chk, sctp_next);
8769 	chk->asoc->ctrl_queue_cnt++;
8770 	return;
8771 }
8772 
8773 void
8774 sctp_send_asconf_ack(struct sctp_tcb *stcb)
8775 {
8776 	/*
8777 	 * formulate and queue a asconf-ack back to sender. the asconf-ack
8778 	 * must be stored in the tcb.
8779 	 */
8780 	struct sctp_tmit_chunk *chk;
8781 	struct sctp_asconf_ack *ack, *latest_ack;
8782 	struct mbuf *m_ack, *m;
8783 	struct sctp_nets *net = NULL;
8784 
8785 	SCTP_TCB_LOCK_ASSERT(stcb);
8786 	/* Get the latest ASCONF-ACK */
8787 	latest_ack = TAILQ_LAST(&stcb->asoc.asconf_ack_sent, sctp_asconf_ackhead);
8788 	if (latest_ack == NULL) {
8789 		return;
8790 	}
8791 	if (latest_ack->last_sent_to != NULL &&
8792 	    latest_ack->last_sent_to == stcb->asoc.last_control_chunk_from) {
8793 		/* we're doing a retransmission */
8794 		net = sctp_find_alternate_net(stcb, stcb->asoc.last_control_chunk_from, 0);
8795 		if (net == NULL) {
8796 			/* no alternate */
8797 			if (stcb->asoc.last_control_chunk_from == NULL)
8798 				net = stcb->asoc.primary_destination;
8799 			else
8800 				net = stcb->asoc.last_control_chunk_from;
8801 		}
8802 	} else {
8803 		/* normal case */
8804 		if (stcb->asoc.last_control_chunk_from == NULL)
8805 			net = stcb->asoc.primary_destination;
8806 		else
8807 			net = stcb->asoc.last_control_chunk_from;
8808 	}
8809 	latest_ack->last_sent_to = net;
8810 
8811 	TAILQ_FOREACH(ack, &stcb->asoc.asconf_ack_sent, next) {
8812 		if (ack->data == NULL) {
8813 			continue;
8814 		}
8815 		/* copy the asconf_ack */
8816 		m_ack = SCTP_M_COPYM(ack->data, 0, M_COPYALL, M_DONTWAIT);
8817 		if (m_ack == NULL) {
8818 			/* couldn't copy it */
8819 			return;
8820 		}
8821 #ifdef SCTP_MBUF_LOGGING
8822 		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_MBUF_LOGGING_ENABLE) {
8823 			struct mbuf *mat;
8824 
8825 			mat = m_ack;
8826 			while (mat) {
8827 				if (SCTP_BUF_IS_EXTENDED(mat)) {
8828 					sctp_log_mb(mat, SCTP_MBUF_ICOPY);
8829 				}
8830 				mat = SCTP_BUF_NEXT(mat);
8831 			}
8832 		}
8833 #endif
8834 
8835 		sctp_alloc_a_chunk(stcb, chk);
8836 		if (chk == NULL) {
8837 			/* no memory */
8838 			if (m_ack)
8839 				sctp_m_freem(m_ack);
8840 			return;
8841 		}
8842 		chk->copy_by_ref = 0;
8843 
8844 		chk->whoTo = net;
8845 		chk->data = m_ack;
8846 		chk->send_size = 0;
8847 		/* Get size */
8848 		m = m_ack;
8849 		chk->send_size = ack->len;
8850 		chk->rec.chunk_id.id = SCTP_ASCONF_ACK;
8851 		chk->rec.chunk_id.can_take_data = 1;
8852 		chk->sent = SCTP_DATAGRAM_UNSENT;
8853 		chk->snd_count = 0;
8854 		chk->flags |= CHUNK_FLAGS_FRAGMENT_OK;	/* XXX */
8855 		chk->asoc = &stcb->asoc;
8856 		atomic_add_int(&chk->whoTo->ref_count, 1);
8857 
8858 		TAILQ_INSERT_TAIL(&chk->asoc->control_send_queue, chk, sctp_next);
8859 		chk->asoc->ctrl_queue_cnt++;
8860 	}
8861 	return;
8862 }
8863 
8864 
8865 static int
8866 sctp_chunk_retransmission(struct sctp_inpcb *inp,
8867     struct sctp_tcb *stcb,
8868     struct sctp_association *asoc,
8869     int *cnt_out, struct timeval *now, int *now_filled, int *fr_done, int so_locked
8870 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
8871     SCTP_UNUSED
8872 #endif
8873 )
8874 {
8875 	/*-
8876 	 * send out one MTU of retransmission. If fast_retransmit is
8877 	 * happening we ignore the cwnd. Otherwise we obey the cwnd and
8878 	 * rwnd. For a Cookie or Asconf in the control chunk queue we
8879 	 * retransmit them by themselves.
8880 	 *
8881 	 * For data chunks we will pick out the lowest TSN's in the sent_queue
8882 	 * marked for resend and bundle them all together (up to a MTU of
8883 	 * destination). The address to send to should have been
8884 	 * selected/changed where the retransmission was marked (i.e. in FR
8885 	 * or t3-timeout routines).
8886 	 */
8887 	struct sctp_tmit_chunk *data_list[SCTP_MAX_DATA_BUNDLING];
8888 	struct sctp_tmit_chunk *chk, *fwd;
8889 	struct mbuf *m, *endofchain;
8890 	struct sctp_nets *net = NULL;
8891 	uint32_t tsns_sent = 0;
8892 	int no_fragmentflg, bundle_at, cnt_thru;
8893 	unsigned int mtu;
8894 	int error, i, one_chunk, fwd_tsn, ctl_cnt, tmr_started;
8895 	struct sctp_auth_chunk *auth = NULL;
8896 	uint32_t auth_offset = 0;
8897 	uint16_t auth_keyid;
8898 	int override_ok = 1;
8899 	int data_auth_reqd = 0;
8900 	uint32_t dmtu = 0;
8901 
8902 	SCTP_TCB_LOCK_ASSERT(stcb);
8903 	tmr_started = ctl_cnt = bundle_at = error = 0;
8904 	no_fragmentflg = 1;
8905 	fwd_tsn = 0;
8906 	*cnt_out = 0;
8907 	fwd = NULL;
8908 	endofchain = m = NULL;
8909 	auth_keyid = stcb->asoc.authinfo.active_keyid;
8910 #ifdef SCTP_AUDITING_ENABLED
8911 	sctp_audit_log(0xC3, 1);
8912 #endif
8913 	if ((TAILQ_EMPTY(&asoc->sent_queue)) &&
8914 	    (TAILQ_EMPTY(&asoc->control_send_queue))) {
8915 		SCTPDBG(SCTP_DEBUG_OUTPUT1, "SCTP hits empty queue with cnt set to %d?\n",
8916 		    asoc->sent_queue_retran_cnt);
8917 		asoc->sent_queue_cnt = 0;
8918 		asoc->sent_queue_cnt_removeable = 0;
8919 		/* send back 0/0 so we enter normal transmission */
8920 		*cnt_out = 0;
8921 		return (0);
8922 	}
8923 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
8924 		if ((chk->rec.chunk_id.id == SCTP_COOKIE_ECHO) ||
8925 		    (chk->rec.chunk_id.id == SCTP_STREAM_RESET) ||
8926 		    (chk->rec.chunk_id.id == SCTP_FORWARD_CUM_TSN)) {
8927 			if (chk->rec.chunk_id.id == SCTP_STREAM_RESET) {
8928 				if (chk != asoc->str_reset) {
8929 					/*
8930 					 * not eligible for retran if its
8931 					 * not ours
8932 					 */
8933 					continue;
8934 				}
8935 			}
8936 			ctl_cnt++;
8937 			if (chk->rec.chunk_id.id == SCTP_FORWARD_CUM_TSN) {
8938 				fwd_tsn = 1;
8939 				fwd = chk;
8940 			}
8941 			/*
8942 			 * Add an AUTH chunk, if chunk requires it save the
8943 			 * offset into the chain for AUTH
8944 			 */
8945 			if ((auth == NULL) &&
8946 			    (sctp_auth_is_required_chunk(chk->rec.chunk_id.id,
8947 			    stcb->asoc.peer_auth_chunks))) {
8948 				m = sctp_add_auth_chunk(m, &endofchain,
8949 				    &auth, &auth_offset,
8950 				    stcb,
8951 				    chk->rec.chunk_id.id);
8952 				SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
8953 			}
8954 			m = sctp_copy_mbufchain(chk->data, m, &endofchain, 0, chk->send_size, chk->copy_by_ref);
8955 			break;
8956 		}
8957 	}
8958 	one_chunk = 0;
8959 	cnt_thru = 0;
8960 	/* do we have control chunks to retransmit? */
8961 	if (m != NULL) {
8962 		/* Start a timer no matter if we suceed or fail */
8963 		if (chk->rec.chunk_id.id == SCTP_COOKIE_ECHO) {
8964 			sctp_timer_start(SCTP_TIMER_TYPE_COOKIE, inp, stcb, chk->whoTo);
8965 		} else if (chk->rec.chunk_id.id == SCTP_ASCONF)
8966 			sctp_timer_start(SCTP_TIMER_TYPE_ASCONF, inp, stcb, chk->whoTo);
8967 		chk->snd_count++;	/* update our count */
8968 		if ((error = sctp_lowlevel_chunk_output(inp, stcb, chk->whoTo,
8969 		    (struct sockaddr *)&chk->whoTo->ro._l_addr, m,
8970 		    auth_offset, auth, stcb->asoc.authinfo.active_keyid,
8971 		    no_fragmentflg, 0, NULL, 0,
8972 		    inp->sctp_lport, stcb->rport, htonl(stcb->asoc.peer_vtag),
8973 		    chk->whoTo->port, so_locked, NULL))) {
8974 			SCTP_STAT_INCR(sctps_lowlevelerr);
8975 			return (error);
8976 		}
8977 		m = endofchain = NULL;
8978 		auth = NULL;
8979 		auth_offset = 0;
8980 		/*
8981 		 * We don't want to mark the net->sent time here since this
8982 		 * we use this for HB and retrans cannot measure RTT
8983 		 */
8984 		/* (void)SCTP_GETTIME_TIMEVAL(&chk->whoTo->last_sent_time); */
8985 		*cnt_out += 1;
8986 		chk->sent = SCTP_DATAGRAM_SENT;
8987 		sctp_ucount_decr(asoc->sent_queue_retran_cnt);
8988 		if (fwd_tsn == 0) {
8989 			return (0);
8990 		} else {
8991 			/* Clean up the fwd-tsn list */
8992 			sctp_clean_up_ctl(stcb, asoc);
8993 			return (0);
8994 		}
8995 	}
8996 	/*
8997 	 * Ok, it is just data retransmission we need to do or that and a
8998 	 * fwd-tsn with it all.
8999 	 */
9000 	if (TAILQ_EMPTY(&asoc->sent_queue)) {
9001 		return (SCTP_RETRAN_DONE);
9002 	}
9003 	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED) ||
9004 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT)) {
9005 		/* not yet open, resend the cookie and that is it */
9006 		return (1);
9007 	}
9008 #ifdef SCTP_AUDITING_ENABLED
9009 	sctp_auditing(20, inp, stcb, NULL);
9010 #endif
9011 	data_auth_reqd = sctp_auth_is_required_chunk(SCTP_DATA, stcb->asoc.peer_auth_chunks);
9012 	TAILQ_FOREACH(chk, &asoc->sent_queue, sctp_next) {
9013 		if (chk->sent != SCTP_DATAGRAM_RESEND) {
9014 			/* No, not sent to this net or not ready for rtx */
9015 			continue;
9016 		}
9017 		if ((SCTP_BASE_SYSCTL(sctp_max_retran_chunk)) &&
9018 		    (chk->snd_count >= SCTP_BASE_SYSCTL(sctp_max_retran_chunk))) {
9019 			/* Gak, we have exceeded max unlucky retran, abort! */
9020 			SCTP_PRINTF("Gak, chk->snd_count:%d >= max:%d - send abort\n",
9021 			    chk->snd_count,
9022 			    SCTP_BASE_SYSCTL(sctp_max_retran_chunk));
9023 			atomic_add_int(&stcb->asoc.refcnt, 1);
9024 			sctp_abort_an_association(stcb->sctp_ep, stcb, 0, NULL, so_locked);
9025 			SCTP_TCB_LOCK(stcb);
9026 			atomic_subtract_int(&stcb->asoc.refcnt, 1);
9027 			return (SCTP_RETRAN_EXIT);
9028 		}
9029 		/* pick up the net */
9030 		net = chk->whoTo;
9031 		if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
9032 			mtu = (net->mtu - SCTP_MIN_OVERHEAD);
9033 		} else {
9034 			mtu = net->mtu - SCTP_MIN_V4_OVERHEAD;
9035 		}
9036 
9037 		if ((asoc->peers_rwnd < mtu) && (asoc->total_flight > 0)) {
9038 			/* No room in peers rwnd */
9039 			uint32_t tsn;
9040 
9041 			tsn = asoc->last_acked_seq + 1;
9042 			if (tsn == chk->rec.data.TSN_seq) {
9043 				/*
9044 				 * we make a special exception for this
9045 				 * case. The peer has no rwnd but is missing
9046 				 * the lowest chunk.. which is probably what
9047 				 * is holding up the rwnd.
9048 				 */
9049 				goto one_chunk_around;
9050 			}
9051 			return (1);
9052 		}
9053 one_chunk_around:
9054 		if (asoc->peers_rwnd < mtu) {
9055 			one_chunk = 1;
9056 			if ((asoc->peers_rwnd == 0) &&
9057 			    (asoc->total_flight == 0)) {
9058 				chk->window_probe = 1;
9059 				chk->whoTo->window_probe = 1;
9060 			}
9061 		}
9062 #ifdef SCTP_AUDITING_ENABLED
9063 		sctp_audit_log(0xC3, 2);
9064 #endif
9065 		bundle_at = 0;
9066 		m = NULL;
9067 		net->fast_retran_ip = 0;
9068 		if (chk->rec.data.doing_fast_retransmit == 0) {
9069 			/*
9070 			 * if no FR in progress skip destination that have
9071 			 * flight_size > cwnd.
9072 			 */
9073 			if (net->flight_size >= net->cwnd) {
9074 				continue;
9075 			}
9076 		} else {
9077 			/*
9078 			 * Mark the destination net to have FR recovery
9079 			 * limits put on it.
9080 			 */
9081 			*fr_done = 1;
9082 			net->fast_retran_ip = 1;
9083 		}
9084 
9085 		/*
9086 		 * if no AUTH is yet included and this chunk requires it,
9087 		 * make sure to account for it.  We don't apply the size
9088 		 * until the AUTH chunk is actually added below in case
9089 		 * there is no room for this chunk.
9090 		 */
9091 		if (data_auth_reqd && (auth == NULL)) {
9092 			dmtu = sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
9093 		} else
9094 			dmtu = 0;
9095 
9096 		if ((chk->send_size <= (mtu - dmtu)) ||
9097 		    (chk->flags & CHUNK_FLAGS_FRAGMENT_OK)) {
9098 			/* ok we will add this one */
9099 			if (data_auth_reqd) {
9100 				if (auth == NULL) {
9101 					m = sctp_add_auth_chunk(m,
9102 					    &endofchain,
9103 					    &auth,
9104 					    &auth_offset,
9105 					    stcb,
9106 					    SCTP_DATA);
9107 					auth_keyid = chk->auth_keyid;
9108 					override_ok = 0;
9109 					SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
9110 				} else if (override_ok) {
9111 					auth_keyid = chk->auth_keyid;
9112 					override_ok = 0;
9113 				} else if (chk->auth_keyid != auth_keyid) {
9114 					/* different keyid, so done bundling */
9115 					break;
9116 				}
9117 			}
9118 			m = sctp_copy_mbufchain(chk->data, m, &endofchain, 0, chk->send_size, chk->copy_by_ref);
9119 			if (m == NULL) {
9120 				SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
9121 				return (ENOMEM);
9122 			}
9123 			/* Do clear IP_DF ? */
9124 			if (chk->flags & CHUNK_FLAGS_FRAGMENT_OK) {
9125 				no_fragmentflg = 0;
9126 			}
9127 			/* upate our MTU size */
9128 			if (mtu > (chk->send_size + dmtu))
9129 				mtu -= (chk->send_size + dmtu);
9130 			else
9131 				mtu = 0;
9132 			data_list[bundle_at++] = chk;
9133 			if (one_chunk && (asoc->total_flight <= 0)) {
9134 				SCTP_STAT_INCR(sctps_windowprobed);
9135 			}
9136 		}
9137 		if (one_chunk == 0) {
9138 			/*
9139 			 * now are there anymore forward from chk to pick
9140 			 * up?
9141 			 */
9142 			fwd = TAILQ_NEXT(chk, sctp_next);
9143 			while (fwd) {
9144 				if (fwd->sent != SCTP_DATAGRAM_RESEND) {
9145 					/* Nope, not for retran */
9146 					fwd = TAILQ_NEXT(fwd, sctp_next);
9147 					continue;
9148 				}
9149 				if (fwd->whoTo != net) {
9150 					/* Nope, not the net in question */
9151 					fwd = TAILQ_NEXT(fwd, sctp_next);
9152 					continue;
9153 				}
9154 				if (data_auth_reqd && (auth == NULL)) {
9155 					dmtu = sctp_get_auth_chunk_len(stcb->asoc.peer_hmac_id);
9156 				} else
9157 					dmtu = 0;
9158 				if (fwd->send_size <= (mtu - dmtu)) {
9159 					if (data_auth_reqd) {
9160 						if (auth == NULL) {
9161 							m = sctp_add_auth_chunk(m,
9162 							    &endofchain,
9163 							    &auth,
9164 							    &auth_offset,
9165 							    stcb,
9166 							    SCTP_DATA);
9167 							auth_keyid = fwd->auth_keyid;
9168 							override_ok = 0;
9169 							SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
9170 						} else if (override_ok) {
9171 							auth_keyid = fwd->auth_keyid;
9172 							override_ok = 0;
9173 						} else if (fwd->auth_keyid != auth_keyid) {
9174 							/*
9175 							 * different keyid,
9176 							 * so done bundling
9177 							 */
9178 							break;
9179 						}
9180 					}
9181 					m = sctp_copy_mbufchain(fwd->data, m, &endofchain, 0, fwd->send_size, fwd->copy_by_ref);
9182 					if (m == NULL) {
9183 						SCTP_LTRACE_ERR_RET(inp, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
9184 						return (ENOMEM);
9185 					}
9186 					/* Do clear IP_DF ? */
9187 					if (fwd->flags & CHUNK_FLAGS_FRAGMENT_OK) {
9188 						no_fragmentflg = 0;
9189 					}
9190 					/* upate our MTU size */
9191 					if (mtu > (fwd->send_size + dmtu))
9192 						mtu -= (fwd->send_size + dmtu);
9193 					else
9194 						mtu = 0;
9195 					data_list[bundle_at++] = fwd;
9196 					if (bundle_at >= SCTP_MAX_DATA_BUNDLING) {
9197 						break;
9198 					}
9199 					fwd = TAILQ_NEXT(fwd, sctp_next);
9200 				} else {
9201 					/* can't fit so we are done */
9202 					break;
9203 				}
9204 			}
9205 		}
9206 		/* Is there something to send for this destination? */
9207 		if (m) {
9208 			/*
9209 			 * No matter if we fail/or suceed we should start a
9210 			 * timer. A failure is like a lost IP packet :-)
9211 			 */
9212 			if (!SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer)) {
9213 				/*
9214 				 * no timer running on this destination
9215 				 * restart it.
9216 				 */
9217 				sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
9218 				tmr_started = 1;
9219 			}
9220 			/* Now lets send it, if there is anything to send :> */
9221 			if ((error = sctp_lowlevel_chunk_output(inp, stcb, net,
9222 			    (struct sockaddr *)&net->ro._l_addr, m,
9223 			    auth_offset, auth, auth_keyid,
9224 			    no_fragmentflg, 0, NULL, 0,
9225 			    inp->sctp_lport, stcb->rport, htonl(stcb->asoc.peer_vtag),
9226 			    net->port, so_locked, NULL))) {
9227 				/* error, we could not output */
9228 				SCTP_STAT_INCR(sctps_lowlevelerr);
9229 				return (error);
9230 			}
9231 			m = endofchain = NULL;
9232 			auth = NULL;
9233 			auth_offset = 0;
9234 			/* For HB's */
9235 			/*
9236 			 * We don't want to mark the net->sent time here
9237 			 * since this we use this for HB and retrans cannot
9238 			 * measure RTT
9239 			 */
9240 			/* (void)SCTP_GETTIME_TIMEVAL(&net->last_sent_time); */
9241 
9242 			/* For auto-close */
9243 			cnt_thru++;
9244 			if (*now_filled == 0) {
9245 				(void)SCTP_GETTIME_TIMEVAL(&asoc->time_last_sent);
9246 				*now = asoc->time_last_sent;
9247 				*now_filled = 1;
9248 			} else {
9249 				asoc->time_last_sent = *now;
9250 			}
9251 			*cnt_out += bundle_at;
9252 #ifdef SCTP_AUDITING_ENABLED
9253 			sctp_audit_log(0xC4, bundle_at);
9254 #endif
9255 			if (bundle_at) {
9256 				tsns_sent = data_list[0]->rec.data.TSN_seq;
9257 			}
9258 			for (i = 0; i < bundle_at; i++) {
9259 				SCTP_STAT_INCR(sctps_sendretransdata);
9260 				data_list[i]->sent = SCTP_DATAGRAM_SENT;
9261 				/*
9262 				 * When we have a revoked data, and we
9263 				 * retransmit it, then we clear the revoked
9264 				 * flag since this flag dictates if we
9265 				 * subtracted from the fs
9266 				 */
9267 				if (data_list[i]->rec.data.chunk_was_revoked) {
9268 					/* Deflate the cwnd */
9269 					data_list[i]->whoTo->cwnd -= data_list[i]->book_size;
9270 					data_list[i]->rec.data.chunk_was_revoked = 0;
9271 				}
9272 				data_list[i]->snd_count++;
9273 				sctp_ucount_decr(asoc->sent_queue_retran_cnt);
9274 				/* record the time */
9275 				data_list[i]->sent_rcv_time = asoc->time_last_sent;
9276 				if (data_list[i]->book_size_scale) {
9277 					/*
9278 					 * need to double the book size on
9279 					 * this one
9280 					 */
9281 					data_list[i]->book_size_scale = 0;
9282 					/*
9283 					 * Since we double the booksize, we
9284 					 * must also double the output queue
9285 					 * size, since this get shrunk when
9286 					 * we free by this amount.
9287 					 */
9288 					atomic_add_int(&((asoc)->total_output_queue_size), data_list[i]->book_size);
9289 					data_list[i]->book_size *= 2;
9290 
9291 
9292 				} else {
9293 					if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_RWND_ENABLE) {
9294 						sctp_log_rwnd(SCTP_DECREASE_PEER_RWND,
9295 						    asoc->peers_rwnd, data_list[i]->send_size, SCTP_BASE_SYSCTL(sctp_peer_chunk_oh));
9296 					}
9297 					asoc->peers_rwnd = sctp_sbspace_sub(asoc->peers_rwnd,
9298 					    (uint32_t) (data_list[i]->send_size +
9299 					    SCTP_BASE_SYSCTL(sctp_peer_chunk_oh)));
9300 				}
9301 				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_FLIGHT_LOGGING_ENABLE) {
9302 					sctp_misc_ints(SCTP_FLIGHT_LOG_UP_RSND,
9303 					    data_list[i]->whoTo->flight_size,
9304 					    data_list[i]->book_size,
9305 					    (uintptr_t) data_list[i]->whoTo,
9306 					    data_list[i]->rec.data.TSN_seq);
9307 				}
9308 				sctp_flight_size_increase(data_list[i]);
9309 				sctp_total_flight_increase(stcb, data_list[i]);
9310 				if (asoc->peers_rwnd < stcb->sctp_ep->sctp_ep.sctp_sws_sender) {
9311 					/* SWS sender side engages */
9312 					asoc->peers_rwnd = 0;
9313 				}
9314 				if ((i == 0) &&
9315 				    (data_list[i]->rec.data.doing_fast_retransmit)) {
9316 					SCTP_STAT_INCR(sctps_sendfastretrans);
9317 					if ((data_list[i] == TAILQ_FIRST(&asoc->sent_queue)) &&
9318 					    (tmr_started == 0)) {
9319 						/*-
9320 						 * ok we just fast-retrans'd
9321 						 * the lowest TSN, i.e the
9322 						 * first on the list. In
9323 						 * this case we want to give
9324 						 * some more time to get a
9325 						 * SACK back without a
9326 						 * t3-expiring.
9327 						 */
9328 						sctp_timer_stop(SCTP_TIMER_TYPE_SEND, inp, stcb, net,
9329 						    SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_4);
9330 						sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, net);
9331 					}
9332 				}
9333 			}
9334 			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
9335 				sctp_log_cwnd(stcb, net, tsns_sent, SCTP_CWND_LOG_FROM_RESEND);
9336 			}
9337 #ifdef SCTP_AUDITING_ENABLED
9338 			sctp_auditing(21, inp, stcb, NULL);
9339 #endif
9340 		} else {
9341 			/* None will fit */
9342 			return (1);
9343 		}
9344 		if (asoc->sent_queue_retran_cnt <= 0) {
9345 			/* all done we have no more to retran */
9346 			asoc->sent_queue_retran_cnt = 0;
9347 			break;
9348 		}
9349 		if (one_chunk) {
9350 			/* No more room in rwnd */
9351 			return (1);
9352 		}
9353 		/* stop the for loop here. we sent out a packet */
9354 		break;
9355 	}
9356 	return (0);
9357 }
9358 
9359 
9360 static int
9361 sctp_timer_validation(struct sctp_inpcb *inp,
9362     struct sctp_tcb *stcb,
9363     struct sctp_association *asoc,
9364     int ret)
9365 {
9366 	struct sctp_nets *net;
9367 
9368 	/* Validate that a timer is running somewhere */
9369 	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
9370 		if (SCTP_OS_TIMER_PENDING(&net->rxt_timer.timer)) {
9371 			/* Here is a timer */
9372 			return (ret);
9373 		}
9374 	}
9375 	SCTP_TCB_LOCK_ASSERT(stcb);
9376 	/* Gak, we did not have a timer somewhere */
9377 	SCTPDBG(SCTP_DEBUG_OUTPUT3, "Deadlock avoided starting timer on a dest at retran\n");
9378 	sctp_timer_start(SCTP_TIMER_TYPE_SEND, inp, stcb, asoc->primary_destination);
9379 	return (ret);
9380 }
9381 
9382 void
9383 sctp_chunk_output(struct sctp_inpcb *inp,
9384     struct sctp_tcb *stcb,
9385     int from_where,
9386     int so_locked
9387 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
9388     SCTP_UNUSED
9389 #endif
9390 )
9391 {
9392 	/*-
9393 	 * Ok this is the generic chunk service queue. we must do the
9394 	 * following:
9395 	 * - See if there are retransmits pending, if so we must
9396 	 *   do these first.
9397 	 * - Service the stream queue that is next, moving any
9398 	 *   message (note I must get a complete message i.e.
9399 	 *   FIRST/MIDDLE and LAST to the out queue in one pass) and assigning
9400 	 *   TSN's
9401 	 * - Check to see if the cwnd/rwnd allows any output, if so we
9402 	 *   go ahead and fomulate and send the low level chunks. Making sure
9403 	 *   to combine any control in the control chunk queue also.
9404 	 */
9405 	struct sctp_association *asoc;
9406 	struct sctp_nets *net;
9407 	int error = 0, num_out = 0, tot_out = 0, ret = 0, reason_code = 0,
9408 	    burst_cnt = 0, burst_limit = 0;
9409 	struct timeval now;
9410 	int now_filled = 0;
9411 	int nagle_on = 0;
9412 	int frag_point = sctp_get_frag_point(stcb, &stcb->asoc);
9413 	int un_sent = 0;
9414 	int fr_done, tot_frs = 0;
9415 
9416 	asoc = &stcb->asoc;
9417 	if (from_where == SCTP_OUTPUT_FROM_USR_SEND) {
9418 		if (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_NODELAY)) {
9419 			nagle_on = 0;
9420 		} else {
9421 			nagle_on = 1;
9422 		}
9423 	}
9424 	SCTP_TCB_LOCK_ASSERT(stcb);
9425 
9426 	un_sent = (stcb->asoc.total_output_queue_size - stcb->asoc.total_flight);
9427 
9428 	if ((un_sent <= 0) &&
9429 	    (TAILQ_EMPTY(&asoc->control_send_queue)) &&
9430 	    (TAILQ_EMPTY(&asoc->asconf_send_queue)) &&
9431 	    (asoc->sent_queue_retran_cnt == 0)) {
9432 		/* Nothing to do unless there is something to be sent left */
9433 		return;
9434 	}
9435 	/*
9436 	 * Do we have something to send, data or control AND a sack timer
9437 	 * running, if so piggy-back the sack.
9438 	 */
9439 	if (SCTP_OS_TIMER_PENDING(&stcb->asoc.dack_timer.timer)) {
9440 		/*
9441 		 * EY if nr_sacks used then send an nr-sack , a sack
9442 		 * otherwise
9443 		 */
9444 		if (SCTP_BASE_SYSCTL(sctp_nr_sack_on_off) && asoc->peer_supports_nr_sack)
9445 			sctp_send_nr_sack(stcb);
9446 		else
9447 			sctp_send_sack(stcb);
9448 		(void)SCTP_OS_TIMER_STOP(&stcb->asoc.dack_timer.timer);
9449 	}
9450 	while (asoc->sent_queue_retran_cnt) {
9451 		/*-
9452 		 * Ok, it is retransmission time only, we send out only ONE
9453 		 * packet with a single call off to the retran code.
9454 		 */
9455 		if (from_where == SCTP_OUTPUT_FROM_COOKIE_ACK) {
9456 			/*-
9457 			 * Special hook for handling cookiess discarded
9458 			 * by peer that carried data. Send cookie-ack only
9459 			 * and then the next call with get the retran's.
9460 			 */
9461 			(void)sctp_med_chunk_output(inp, stcb, asoc, &num_out, &reason_code, 1,
9462 			    from_where,
9463 			    &now, &now_filled, frag_point, so_locked);
9464 			return;
9465 		} else if (from_where != SCTP_OUTPUT_FROM_HB_TMR) {
9466 			/* if its not from a HB then do it */
9467 			fr_done = 0;
9468 			ret = sctp_chunk_retransmission(inp, stcb, asoc, &num_out, &now, &now_filled, &fr_done, so_locked);
9469 			if (fr_done) {
9470 				tot_frs++;
9471 			}
9472 		} else {
9473 			/*
9474 			 * its from any other place, we don't allow retran
9475 			 * output (only control)
9476 			 */
9477 			ret = 1;
9478 		}
9479 		if (ret > 0) {
9480 			/* Can't send anymore */
9481 			/*-
9482 			 * now lets push out control by calling med-level
9483 			 * output once. this assures that we WILL send HB's
9484 			 * if queued too.
9485 			 */
9486 			(void)sctp_med_chunk_output(inp, stcb, asoc, &num_out, &reason_code, 1,
9487 			    from_where,
9488 			    &now, &now_filled, frag_point, so_locked);
9489 #ifdef SCTP_AUDITING_ENABLED
9490 			sctp_auditing(8, inp, stcb, NULL);
9491 #endif
9492 			(void)sctp_timer_validation(inp, stcb, asoc, ret);
9493 			return;
9494 		}
9495 		if (ret < 0) {
9496 			/*-
9497 			 * The count was off.. retran is not happening so do
9498 			 * the normal retransmission.
9499 			 */
9500 #ifdef SCTP_AUDITING_ENABLED
9501 			sctp_auditing(9, inp, stcb, NULL);
9502 #endif
9503 			if (ret == SCTP_RETRAN_EXIT) {
9504 				return;
9505 			}
9506 			break;
9507 		}
9508 		if (from_where == SCTP_OUTPUT_FROM_T3) {
9509 			/* Only one transmission allowed out of a timeout */
9510 #ifdef SCTP_AUDITING_ENABLED
9511 			sctp_auditing(10, inp, stcb, NULL);
9512 #endif
9513 			/* Push out any control */
9514 			(void)sctp_med_chunk_output(inp, stcb, asoc, &num_out, &reason_code, 1, from_where,
9515 			    &now, &now_filled, frag_point, so_locked);
9516 			return;
9517 		}
9518 		if (tot_frs > asoc->max_burst) {
9519 			/* Hit FR burst limit */
9520 			return;
9521 		}
9522 		if ((num_out == 0) && (ret == 0)) {
9523 
9524 			/* No more retrans to send */
9525 			break;
9526 		}
9527 	}
9528 #ifdef SCTP_AUDITING_ENABLED
9529 	sctp_auditing(12, inp, stcb, NULL);
9530 #endif
9531 	/* Check for bad destinations, if they exist move chunks around. */
9532 	burst_limit = asoc->max_burst;
9533 	TAILQ_FOREACH(net, &asoc->nets, sctp_next) {
9534 		if ((net->dest_state & SCTP_ADDR_NOT_REACHABLE) ==
9535 		    SCTP_ADDR_NOT_REACHABLE) {
9536 			/*-
9537 			 * if possible move things off of this address we
9538 			 * still may send below due to the dormant state but
9539 			 * we try to find an alternate address to send to
9540 			 * and if we have one we move all queued data on the
9541 			 * out wheel to this alternate address.
9542 			 */
9543 			if (net->ref_count > 1)
9544 				sctp_move_to_an_alt(stcb, asoc, net);
9545 		} else if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) &&
9546 			    SCTP_BASE_SYSCTL(sctp_cmt_pf) &&
9547 		    ((net->dest_state & SCTP_ADDR_PF) == SCTP_ADDR_PF)) {
9548 			/*
9549 			 * JRS 5/14/07 - If CMT PF is on and the current
9550 			 * destination is in PF state, move all queued data
9551 			 * to an alternate desination.
9552 			 */
9553 			if (net->ref_count > 1)
9554 				sctp_move_to_an_alt(stcb, asoc, net);
9555 		} else {
9556 			/*-
9557 			 * if ((asoc->sat_network) || (net->addr_is_local))
9558 			 * { burst_limit = asoc->max_burst *
9559 			 * SCTP_SAT_NETWORK_BURST_INCR; }
9560 			 */
9561 			if (SCTP_BASE_SYSCTL(sctp_use_cwnd_based_maxburst)) {
9562 				if ((net->flight_size + (burst_limit * net->mtu)) < net->cwnd) {
9563 					/*
9564 					 * JRS - Use the congestion control
9565 					 * given in the congestion control
9566 					 * module
9567 					 */
9568 					asoc->cc_functions.sctp_cwnd_update_after_output(stcb, net, burst_limit);
9569 					if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_MAXBURST_ENABLE) {
9570 						sctp_log_maxburst(stcb, net, 0, burst_limit, SCTP_MAX_BURST_APPLIED);
9571 					}
9572 					SCTP_STAT_INCR(sctps_maxburstqueued);
9573 				}
9574 				net->fast_retran_ip = 0;
9575 			} else {
9576 				if (net->flight_size == 0) {
9577 					/* Should be decaying the cwnd here */
9578 					;
9579 				}
9580 			}
9581 		}
9582 
9583 	}
9584 	burst_cnt = 0;
9585 	do {
9586 		error = sctp_med_chunk_output(inp, stcb, asoc, &num_out,
9587 		    &reason_code, 0, from_where,
9588 		    &now, &now_filled, frag_point, so_locked);
9589 		if (error) {
9590 			SCTPDBG(SCTP_DEBUG_OUTPUT1, "Error %d was returned from med-c-op\n", error);
9591 			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_MAXBURST_ENABLE) {
9592 				sctp_log_maxburst(stcb, asoc->primary_destination, error, burst_cnt, SCTP_MAX_BURST_ERROR_STOP);
9593 			}
9594 			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
9595 				sctp_log_cwnd(stcb, NULL, error, SCTP_SEND_NOW_COMPLETES);
9596 				sctp_log_cwnd(stcb, NULL, 0xdeadbeef, SCTP_SEND_NOW_COMPLETES);
9597 			}
9598 			break;
9599 		}
9600 		SCTPDBG(SCTP_DEBUG_OUTPUT3, "m-c-o put out %d\n", num_out);
9601 
9602 		tot_out += num_out;
9603 		burst_cnt++;
9604 		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
9605 			sctp_log_cwnd(stcb, NULL, num_out, SCTP_SEND_NOW_COMPLETES);
9606 			if (num_out == 0) {
9607 				sctp_log_cwnd(stcb, NULL, reason_code, SCTP_SEND_NOW_COMPLETES);
9608 			}
9609 		}
9610 		if (nagle_on) {
9611 			/*-
9612 			 * When nagle is on, we look at how much is un_sent, then
9613 			 * if its smaller than an MTU and we have data in
9614 			 * flight we stop.
9615 			 */
9616 			un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
9617 			    (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
9618 			if ((un_sent < (int)(stcb->asoc.smallest_mtu - SCTP_MIN_OVERHEAD)) &&
9619 			    (stcb->asoc.total_flight > 0)) {
9620 				break;
9621 			}
9622 		}
9623 		if (TAILQ_EMPTY(&asoc->control_send_queue) &&
9624 		    TAILQ_EMPTY(&asoc->send_queue) &&
9625 		    TAILQ_EMPTY(&asoc->out_wheel)) {
9626 			/* Nothing left to send */
9627 			break;
9628 		}
9629 		if ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) <= 0) {
9630 			/* Nothing left to send */
9631 			break;
9632 		}
9633 	} while (num_out && (SCTP_BASE_SYSCTL(sctp_use_cwnd_based_maxburst) ||
9634 	    (burst_cnt < burst_limit)));
9635 
9636 	if (SCTP_BASE_SYSCTL(sctp_use_cwnd_based_maxburst) == 0) {
9637 		if (burst_cnt >= burst_limit) {
9638 			SCTP_STAT_INCR(sctps_maxburstqueued);
9639 			asoc->burst_limit_applied = 1;
9640 			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_MAXBURST_ENABLE) {
9641 				sctp_log_maxburst(stcb, asoc->primary_destination, 0, burst_cnt, SCTP_MAX_BURST_APPLIED);
9642 			}
9643 		} else {
9644 			asoc->burst_limit_applied = 0;
9645 		}
9646 	}
9647 	if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_CWND_LOGGING_ENABLE) {
9648 		sctp_log_cwnd(stcb, NULL, tot_out, SCTP_SEND_NOW_COMPLETES);
9649 	}
9650 	SCTPDBG(SCTP_DEBUG_OUTPUT1, "Ok, we have put out %d chunks\n",
9651 	    tot_out);
9652 
9653 	/*-
9654 	 * Now we need to clean up the control chunk chain if a ECNE is on
9655 	 * it. It must be marked as UNSENT again so next call will continue
9656 	 * to send it until such time that we get a CWR, to remove it.
9657 	 */
9658 	if (stcb->asoc.ecn_echo_cnt_onq)
9659 		sctp_fix_ecn_echo(asoc);
9660 	return;
9661 }
9662 
9663 
9664 int
9665 sctp_output(inp, m, addr, control, p, flags)
9666 	struct sctp_inpcb *inp;
9667 	struct mbuf *m;
9668 	struct sockaddr *addr;
9669 	struct mbuf *control;
9670 	struct thread *p;
9671 	int flags;
9672 {
9673 	if (inp == NULL) {
9674 		SCTP_LTRACE_ERR_RET_PKT(m, inp, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, EINVAL);
9675 		return (EINVAL);
9676 	}
9677 	if (inp->sctp_socket == NULL) {
9678 		SCTP_LTRACE_ERR_RET_PKT(m, inp, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, EINVAL);
9679 		return (EINVAL);
9680 	}
9681 	return (sctp_sosend(inp->sctp_socket,
9682 	    addr,
9683 	    (struct uio *)NULL,
9684 	    m,
9685 	    control,
9686 	    flags, p
9687 	    ));
9688 }
9689 
9690 void
9691 send_forward_tsn(struct sctp_tcb *stcb,
9692     struct sctp_association *asoc)
9693 {
9694 	struct sctp_tmit_chunk *chk;
9695 	struct sctp_forward_tsn_chunk *fwdtsn;
9696 	uint32_t advance_peer_ack_point;
9697 
9698 	SCTP_TCB_LOCK_ASSERT(stcb);
9699 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
9700 		if (chk->rec.chunk_id.id == SCTP_FORWARD_CUM_TSN) {
9701 			/* mark it to unsent */
9702 			chk->sent = SCTP_DATAGRAM_UNSENT;
9703 			chk->snd_count = 0;
9704 			/* Do we correct its output location? */
9705 			if (chk->whoTo != asoc->primary_destination) {
9706 				sctp_free_remote_addr(chk->whoTo);
9707 				chk->whoTo = asoc->primary_destination;
9708 				atomic_add_int(&chk->whoTo->ref_count, 1);
9709 			}
9710 			goto sctp_fill_in_rest;
9711 		}
9712 	}
9713 	/* Ok if we reach here we must build one */
9714 	sctp_alloc_a_chunk(stcb, chk);
9715 	if (chk == NULL) {
9716 		return;
9717 	}
9718 	chk->copy_by_ref = 0;
9719 	chk->rec.chunk_id.id = SCTP_FORWARD_CUM_TSN;
9720 	chk->rec.chunk_id.can_take_data = 0;
9721 	chk->asoc = asoc;
9722 	chk->whoTo = NULL;
9723 
9724 	chk->data = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_DATA);
9725 	if (chk->data == NULL) {
9726 		sctp_free_a_chunk(stcb, chk);
9727 		return;
9728 	}
9729 	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
9730 	chk->sent = SCTP_DATAGRAM_UNSENT;
9731 	chk->snd_count = 0;
9732 	chk->whoTo = asoc->primary_destination;
9733 	atomic_add_int(&chk->whoTo->ref_count, 1);
9734 	TAILQ_INSERT_TAIL(&asoc->control_send_queue, chk, sctp_next);
9735 	asoc->ctrl_queue_cnt++;
9736 sctp_fill_in_rest:
9737 	/*-
9738 	 * Here we go through and fill out the part that deals with
9739 	 * stream/seq of the ones we skip.
9740 	 */
9741 	SCTP_BUF_LEN(chk->data) = 0;
9742 	{
9743 		struct sctp_tmit_chunk *at, *tp1, *last;
9744 		struct sctp_strseq *strseq;
9745 		unsigned int cnt_of_space, i, ovh;
9746 		unsigned int space_needed;
9747 		unsigned int cnt_of_skipped = 0;
9748 
9749 		TAILQ_FOREACH(at, &asoc->sent_queue, sctp_next) {
9750 			if (at->sent != SCTP_FORWARD_TSN_SKIP) {
9751 				/* no more to look at */
9752 				break;
9753 			}
9754 			if (at->rec.data.rcv_flags & SCTP_DATA_UNORDERED) {
9755 				/* We don't report these */
9756 				continue;
9757 			}
9758 			cnt_of_skipped++;
9759 		}
9760 		space_needed = (sizeof(struct sctp_forward_tsn_chunk) +
9761 		    (cnt_of_skipped * sizeof(struct sctp_strseq)));
9762 
9763 		cnt_of_space = M_TRAILINGSPACE(chk->data);
9764 
9765 		if (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) {
9766 			ovh = SCTP_MIN_OVERHEAD;
9767 		} else {
9768 			ovh = SCTP_MIN_V4_OVERHEAD;
9769 		}
9770 		if (cnt_of_space > (asoc->smallest_mtu - ovh)) {
9771 			/* trim to a mtu size */
9772 			cnt_of_space = asoc->smallest_mtu - ovh;
9773 		}
9774 		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_TRY_ADVANCE) {
9775 			sctp_misc_ints(SCTP_FWD_TSN_CHECK,
9776 			    0xff, 0, cnt_of_skipped,
9777 			    asoc->advanced_peer_ack_point);
9778 
9779 		}
9780 		advance_peer_ack_point = asoc->advanced_peer_ack_point;
9781 		if (cnt_of_space < space_needed) {
9782 			/*-
9783 			 * ok we must trim down the chunk by lowering the
9784 			 * advance peer ack point.
9785 			 */
9786 			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_TRY_ADVANCE) {
9787 				sctp_misc_ints(SCTP_FWD_TSN_CHECK,
9788 				    0xff, 0xff, cnt_of_space,
9789 				    space_needed);
9790 			}
9791 			cnt_of_skipped = (cnt_of_space -
9792 			    ((sizeof(struct sctp_forward_tsn_chunk)) /
9793 			    sizeof(struct sctp_strseq)));
9794 			/*-
9795 			 * Go through and find the TSN that will be the one
9796 			 * we report.
9797 			 */
9798 			at = TAILQ_FIRST(&asoc->sent_queue);
9799 			for (i = 0; i < cnt_of_skipped; i++) {
9800 				tp1 = TAILQ_NEXT(at, sctp_next);
9801 				at = tp1;
9802 			}
9803 			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_TRY_ADVANCE) {
9804 				sctp_misc_ints(SCTP_FWD_TSN_CHECK,
9805 				    0xff, cnt_of_skipped, at->rec.data.TSN_seq,
9806 				    asoc->advanced_peer_ack_point);
9807 			}
9808 			last = at;
9809 			/*-
9810 			 * last now points to last one I can report, update
9811 			 * peer ack point
9812 			 */
9813 			advance_peer_ack_point = last->rec.data.TSN_seq;
9814 			space_needed -= (cnt_of_skipped * sizeof(struct sctp_strseq));
9815 		}
9816 		chk->send_size = space_needed;
9817 		/* Setup the chunk */
9818 		fwdtsn = mtod(chk->data, struct sctp_forward_tsn_chunk *);
9819 		fwdtsn->ch.chunk_length = htons(chk->send_size);
9820 		fwdtsn->ch.chunk_flags = 0;
9821 		fwdtsn->ch.chunk_type = SCTP_FORWARD_CUM_TSN;
9822 		fwdtsn->new_cumulative_tsn = htonl(advance_peer_ack_point);
9823 		chk->send_size = (sizeof(struct sctp_forward_tsn_chunk) +
9824 		    (cnt_of_skipped * sizeof(struct sctp_strseq)));
9825 		SCTP_BUF_LEN(chk->data) = chk->send_size;
9826 		fwdtsn++;
9827 		/*-
9828 		 * Move pointer to after the fwdtsn and transfer to the
9829 		 * strseq pointer.
9830 		 */
9831 		strseq = (struct sctp_strseq *)fwdtsn;
9832 		/*-
9833 		 * Now populate the strseq list. This is done blindly
9834 		 * without pulling out duplicate stream info. This is
9835 		 * inefficent but won't harm the process since the peer will
9836 		 * look at these in sequence and will thus release anything.
9837 		 * It could mean we exceed the PMTU and chop off some that
9838 		 * we could have included.. but this is unlikely (aka 1432/4
9839 		 * would mean 300+ stream seq's would have to be reported in
9840 		 * one FWD-TSN. With a bit of work we can later FIX this to
9841 		 * optimize and pull out duplcates.. but it does add more
9842 		 * overhead. So for now... not!
9843 		 */
9844 		at = TAILQ_FIRST(&asoc->sent_queue);
9845 		for (i = 0; i < cnt_of_skipped; i++) {
9846 			tp1 = TAILQ_NEXT(at, sctp_next);
9847 			if (at->rec.data.rcv_flags & SCTP_DATA_UNORDERED) {
9848 				/* We don't report these */
9849 				i--;
9850 				at = tp1;
9851 				continue;
9852 			}
9853 			if (at->rec.data.TSN_seq == advance_peer_ack_point) {
9854 				at->rec.data.fwd_tsn_cnt = 0;
9855 			}
9856 			strseq->stream = ntohs(at->rec.data.stream_number);
9857 			strseq->sequence = ntohs(at->rec.data.stream_seq);
9858 			strseq++;
9859 			at = tp1;
9860 		}
9861 	}
9862 	return;
9863 
9864 }
9865 
9866 void
9867 sctp_send_sack(struct sctp_tcb *stcb)
9868 {
9869 	/*-
9870 	 * Queue up a SACK in the control queue. We must first check to see
9871 	 * if a SACK is somehow on the control queue. If so, we will take
9872 	 * and and remove the old one.
9873 	 */
9874 	struct sctp_association *asoc;
9875 	struct sctp_tmit_chunk *chk, *a_chk;
9876 	struct sctp_sack_chunk *sack;
9877 	struct sctp_gap_ack_block *gap_descriptor;
9878 	struct sack_track *selector;
9879 	int mergeable = 0;
9880 	int offset;
9881 	caddr_t limit;
9882 	uint32_t *dup;
9883 	int limit_reached = 0;
9884 	unsigned int i, jstart, siz, j;
9885 	unsigned int num_gap_blocks = 0, space;
9886 	int num_dups = 0;
9887 	int space_req;
9888 
9889 	a_chk = NULL;
9890 	asoc = &stcb->asoc;
9891 	SCTP_TCB_LOCK_ASSERT(stcb);
9892 	if (asoc->last_data_chunk_from == NULL) {
9893 		/* Hmm we never received anything */
9894 		return;
9895 	}
9896 	sctp_set_rwnd(stcb, asoc);
9897 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
9898 		if (chk->rec.chunk_id.id == SCTP_SELECTIVE_ACK) {
9899 			/* Hmm, found a sack already on queue, remove it */
9900 			TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
9901 			asoc->ctrl_queue_cnt++;
9902 			a_chk = chk;
9903 			if (a_chk->data) {
9904 				sctp_m_freem(a_chk->data);
9905 				a_chk->data = NULL;
9906 			}
9907 			sctp_free_remote_addr(a_chk->whoTo);
9908 			a_chk->whoTo = NULL;
9909 			break;
9910 		}
9911 	}
9912 	if (a_chk == NULL) {
9913 		sctp_alloc_a_chunk(stcb, a_chk);
9914 		if (a_chk == NULL) {
9915 			/* No memory so we drop the idea, and set a timer */
9916 			if (stcb->asoc.delayed_ack) {
9917 				sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
9918 				    stcb->sctp_ep, stcb, NULL, SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_5);
9919 				sctp_timer_start(SCTP_TIMER_TYPE_RECV,
9920 				    stcb->sctp_ep, stcb, NULL);
9921 			} else {
9922 				stcb->asoc.send_sack = 1;
9923 			}
9924 			return;
9925 		}
9926 		a_chk->copy_by_ref = 0;
9927 		/* a_chk->rec.chunk_id.id = SCTP_SELECTIVE_ACK; */
9928 		a_chk->rec.chunk_id.id = SCTP_SELECTIVE_ACK;
9929 		a_chk->rec.chunk_id.can_take_data = 1;
9930 	}
9931 	/* Clear our pkt counts */
9932 	asoc->data_pkts_seen = 0;
9933 
9934 	a_chk->asoc = asoc;
9935 	a_chk->snd_count = 0;
9936 	a_chk->send_size = 0;	/* fill in later */
9937 	a_chk->sent = SCTP_DATAGRAM_UNSENT;
9938 	a_chk->whoTo = NULL;
9939 
9940 	if ((asoc->numduptsns) ||
9941 	    (asoc->last_data_chunk_from->dest_state & SCTP_ADDR_NOT_REACHABLE)
9942 	    ) {
9943 		/*-
9944 		 * Ok, we have some duplicates or the destination for the
9945 		 * sack is unreachable, lets see if we can select an
9946 		 * alternate than asoc->last_data_chunk_from
9947 		 */
9948 		if ((!(asoc->last_data_chunk_from->dest_state &
9949 		    SCTP_ADDR_NOT_REACHABLE)) &&
9950 		    (asoc->used_alt_onsack > asoc->numnets)) {
9951 			/* We used an alt last time, don't this time */
9952 			a_chk->whoTo = NULL;
9953 		} else {
9954 			asoc->used_alt_onsack++;
9955 			a_chk->whoTo = sctp_find_alternate_net(stcb, asoc->last_data_chunk_from, 0);
9956 		}
9957 		if (a_chk->whoTo == NULL) {
9958 			/* Nope, no alternate */
9959 			a_chk->whoTo = asoc->last_data_chunk_from;
9960 			asoc->used_alt_onsack = 0;
9961 		}
9962 	} else {
9963 		/*
9964 		 * No duplicates so we use the last place we received data
9965 		 * from.
9966 		 */
9967 		asoc->used_alt_onsack = 0;
9968 		a_chk->whoTo = asoc->last_data_chunk_from;
9969 	}
9970 	if (a_chk->whoTo) {
9971 		atomic_add_int(&a_chk->whoTo->ref_count, 1);
9972 	}
9973 	if (asoc->highest_tsn_inside_map == asoc->cumulative_tsn) {
9974 		/* no gaps */
9975 		space_req = sizeof(struct sctp_sack_chunk);
9976 	} else {
9977 		/* gaps get a cluster */
9978 		space_req = MCLBYTES;
9979 	}
9980 	/* Ok now lets formulate a MBUF with our sack */
9981 	a_chk->data = sctp_get_mbuf_for_msg(space_req, 0, M_DONTWAIT, 1, MT_DATA);
9982 	if ((a_chk->data == NULL) ||
9983 	    (a_chk->whoTo == NULL)) {
9984 		/* rats, no mbuf memory */
9985 		if (a_chk->data) {
9986 			/* was a problem with the destination */
9987 			sctp_m_freem(a_chk->data);
9988 			a_chk->data = NULL;
9989 		}
9990 		sctp_free_a_chunk(stcb, a_chk);
9991 		/* sa_ignore NO_NULL_CHK */
9992 		if (stcb->asoc.delayed_ack) {
9993 			sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
9994 			    stcb->sctp_ep, stcb, NULL, SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_6);
9995 			sctp_timer_start(SCTP_TIMER_TYPE_RECV,
9996 			    stcb->sctp_ep, stcb, NULL);
9997 		} else {
9998 			stcb->asoc.send_sack = 1;
9999 		}
10000 		return;
10001 	}
10002 	/* ok, lets go through and fill it in */
10003 	SCTP_BUF_RESV_UF(a_chk->data, SCTP_MIN_OVERHEAD);
10004 	space = M_TRAILINGSPACE(a_chk->data);
10005 	if (space > (a_chk->whoTo->mtu - SCTP_MIN_OVERHEAD)) {
10006 		space = (a_chk->whoTo->mtu - SCTP_MIN_OVERHEAD);
10007 	}
10008 	limit = mtod(a_chk->data, caddr_t);
10009 	limit += space;
10010 
10011 	sack = mtod(a_chk->data, struct sctp_sack_chunk *);
10012 	sack->ch.chunk_type = SCTP_SELECTIVE_ACK;
10013 	/* 0x01 is used by nonce for ecn */
10014 	if ((SCTP_BASE_SYSCTL(sctp_ecn_enable)) &&
10015 	    (SCTP_BASE_SYSCTL(sctp_ecn_nonce)) &&
10016 	    (asoc->peer_supports_ecn_nonce))
10017 		sack->ch.chunk_flags = (asoc->receiver_nonce_sum & SCTP_SACK_NONCE_SUM);
10018 	else
10019 		sack->ch.chunk_flags = 0;
10020 
10021 	if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && SCTP_BASE_SYSCTL(sctp_cmt_use_dac)) {
10022 		/*-
10023 		 * CMT DAC algorithm: If 2 (i.e., 0x10) packets have been
10024 		 * received, then set high bit to 1, else 0. Reset
10025 		 * pkts_rcvd.
10026 		 */
10027 		sack->ch.chunk_flags |= (asoc->cmt_dac_pkts_rcvd << 6);
10028 		asoc->cmt_dac_pkts_rcvd = 0;
10029 	}
10030 #ifdef SCTP_ASOCLOG_OF_TSNS
10031 	stcb->asoc.cumack_logsnt[stcb->asoc.cumack_log_atsnt] = asoc->cumulative_tsn;
10032 	stcb->asoc.cumack_log_atsnt++;
10033 	if (stcb->asoc.cumack_log_atsnt >= SCTP_TSN_LOG_SIZE) {
10034 		stcb->asoc.cumack_log_atsnt = 0;
10035 	}
10036 #endif
10037 	sack->sack.cum_tsn_ack = htonl(asoc->cumulative_tsn);
10038 	sack->sack.a_rwnd = htonl(asoc->my_rwnd);
10039 	asoc->my_last_reported_rwnd = asoc->my_rwnd;
10040 
10041 	/* reset the readers interpretation */
10042 	stcb->freed_by_sorcv_sincelast = 0;
10043 
10044 	gap_descriptor = (struct sctp_gap_ack_block *)((caddr_t)sack + sizeof(struct sctp_sack_chunk));
10045 
10046 	if (asoc->highest_tsn_inside_map > asoc->mapping_array_base_tsn)
10047 		siz = (((asoc->highest_tsn_inside_map - asoc->mapping_array_base_tsn) + 1) + 7) / 8;
10048 	else
10049 		siz = (((MAX_TSN - asoc->mapping_array_base_tsn) + 1) + asoc->highest_tsn_inside_map + 7) / 8;
10050 
10051 	if (compare_with_wrap(asoc->mapping_array_base_tsn, asoc->cumulative_tsn, MAX_TSN)) {
10052 		offset = 1;
10053 		/*-
10054 		 * cum-ack behind the mapping array, so we start and use all
10055 		 * entries.
10056 		 */
10057 		jstart = 0;
10058 	} else {
10059 		offset = asoc->mapping_array_base_tsn - asoc->cumulative_tsn;
10060 		/*-
10061 		 * we skip the first one when the cum-ack is at or above the
10062 		 * mapping array base. Note this only works if
10063 		 */
10064 		jstart = 1;
10065 	}
10066 	if (compare_with_wrap(asoc->highest_tsn_inside_map, asoc->cumulative_tsn, MAX_TSN)) {
10067 		/* we have a gap .. maybe */
10068 		for (i = 0; i < siz; i++) {
10069 			selector = &sack_array[asoc->mapping_array[i]];
10070 			if (mergeable && selector->right_edge) {
10071 				/*
10072 				 * Backup, left and right edges were ok to
10073 				 * merge.
10074 				 */
10075 				num_gap_blocks--;
10076 				gap_descriptor--;
10077 			}
10078 			if (selector->num_entries == 0)
10079 				mergeable = 0;
10080 			else {
10081 				for (j = jstart; j < selector->num_entries; j++) {
10082 					if (mergeable && selector->right_edge) {
10083 						/*
10084 						 * do a merge by NOT setting
10085 						 * the left side
10086 						 */
10087 						mergeable = 0;
10088 					} else {
10089 						/*
10090 						 * no merge, set the left
10091 						 * side
10092 						 */
10093 						mergeable = 0;
10094 						gap_descriptor->start = htons((selector->gaps[j].start + offset));
10095 					}
10096 					gap_descriptor->end = htons((selector->gaps[j].end + offset));
10097 					num_gap_blocks++;
10098 					gap_descriptor++;
10099 					if (((caddr_t)gap_descriptor + sizeof(struct sctp_gap_ack_block)) > limit) {
10100 						/* no more room */
10101 						limit_reached = 1;
10102 						break;
10103 					}
10104 				}
10105 				if (selector->left_edge) {
10106 					mergeable = 1;
10107 				}
10108 			}
10109 			if (limit_reached) {
10110 				/* Reached the limit stop */
10111 				break;
10112 			}
10113 			jstart = 0;
10114 			offset += 8;
10115 		}
10116 		if (num_gap_blocks == 0) {
10117 			/*
10118 			 * slide not yet happened, and somehow we got called
10119 			 * to send a sack. Cumack needs to move up.
10120 			 */
10121 			int abort_flag = 0;
10122 
10123 			asoc->cumulative_tsn = asoc->highest_tsn_inside_map;
10124 			sack->sack.cum_tsn_ack = htonl(asoc->cumulative_tsn);
10125 			sctp_sack_check(stcb, 0, 0, &abort_flag);
10126 		}
10127 	}
10128 	/* now we must add any dups we are going to report. */
10129 	if ((limit_reached == 0) && (asoc->numduptsns)) {
10130 		dup = (uint32_t *) gap_descriptor;
10131 		for (i = 0; i < asoc->numduptsns; i++) {
10132 			*dup = htonl(asoc->dup_tsns[i]);
10133 			dup++;
10134 			num_dups++;
10135 			if (((caddr_t)dup + sizeof(uint32_t)) > limit) {
10136 				/* no more room */
10137 				break;
10138 			}
10139 		}
10140 		asoc->numduptsns = 0;
10141 	}
10142 	/*
10143 	 * now that the chunk is prepared queue it to the control chunk
10144 	 * queue.
10145 	 */
10146 	a_chk->send_size = (sizeof(struct sctp_sack_chunk) +
10147 	    (num_gap_blocks * sizeof(struct sctp_gap_ack_block)) +
10148 	    (num_dups * sizeof(int32_t)));
10149 	SCTP_BUF_LEN(a_chk->data) = a_chk->send_size;
10150 	sack->sack.num_gap_ack_blks = htons(num_gap_blocks);
10151 	sack->sack.num_dup_tsns = htons(num_dups);
10152 	sack->ch.chunk_length = htons(a_chk->send_size);
10153 	TAILQ_INSERT_TAIL(&asoc->control_send_queue, a_chk, sctp_next);
10154 	asoc->ctrl_queue_cnt++;
10155 	asoc->send_sack = 0;
10156 	SCTP_STAT_INCR(sctps_sendsacks);
10157 	return;
10158 }
10159 
10160 /* EY - This method will replace sctp_send_sack method if nr_sacks negotiated*/
10161 void
10162 sctp_send_nr_sack(struct sctp_tcb *stcb)
10163 {
10164 	/*-
10165 	 * Queue up an NR-SACK in the control queue. We must first check to see
10166 	 * if an NR-SACK is somehow on the control queue. If so, we will take
10167 	 * and and remove the old one.
10168 	 */
10169 	struct sctp_association *asoc;
10170 	struct sctp_tmit_chunk *chk, *a_chk;
10171 
10172 	struct sctp_nr_sack_chunk *nr_sack;
10173 
10174 	struct sctp_gap_ack_block *gap_descriptor;
10175 
10176 	struct sack_track *selector;
10177 	struct sack_track *nr_selector;
10178 
10179 	/* EY do we need nr_mergeable, NO */
10180 	int mergeable = 0;
10181 	int offset;
10182 	caddr_t limit;
10183 	uint32_t *dup;
10184 	int limit_reached = 0;
10185 	unsigned int i, jstart, siz, j;
10186 	unsigned int num_gap_blocks = 0, num_nr_gap_blocks = 0, space;
10187 	int num_dups = 0;
10188 	int space_req;
10189 	unsigned int reserved = 0;
10190 
10191 	a_chk = NULL;
10192 	asoc = &stcb->asoc;
10193 	SCTP_TCB_LOCK_ASSERT(stcb);
10194 	if (asoc->last_data_chunk_from == NULL) {
10195 		/* Hmm we never received anything */
10196 		return;
10197 	}
10198 	sctp_set_rwnd(stcb, asoc);
10199 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
10200 		if (chk->rec.chunk_id.id == SCTP_NR_SELECTIVE_ACK) {
10201 			/* Hmm, found a sack already on queue, remove it */
10202 			TAILQ_REMOVE(&asoc->control_send_queue, chk, sctp_next);
10203 			asoc->ctrl_queue_cnt++;
10204 			a_chk = chk;
10205 			if (a_chk->data) {
10206 				sctp_m_freem(a_chk->data);
10207 				a_chk->data = NULL;
10208 			}
10209 			sctp_free_remote_addr(a_chk->whoTo);
10210 			a_chk->whoTo = NULL;
10211 			break;
10212 		}
10213 	}
10214 	if (a_chk == NULL) {
10215 		sctp_alloc_a_chunk(stcb, a_chk);
10216 		if (a_chk == NULL) {
10217 			/* No memory so we drop the idea, and set a timer */
10218 			if (stcb->asoc.delayed_ack) {
10219 				sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
10220 				    stcb->sctp_ep, stcb, NULL, SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_5);
10221 				sctp_timer_start(SCTP_TIMER_TYPE_RECV,
10222 				    stcb->sctp_ep, stcb, NULL);
10223 			} else {
10224 				stcb->asoc.send_sack = 1;
10225 			}
10226 			return;
10227 		}
10228 		a_chk->copy_by_ref = 0;
10229 		/* a_chk->rec.chunk_id.id = SCTP_SELECTIVE_ACK; */
10230 		a_chk->rec.chunk_id.id = SCTP_NR_SELECTIVE_ACK;
10231 		a_chk->rec.chunk_id.can_take_data = 1;
10232 	}
10233 	/* Clear our pkt counts */
10234 	asoc->data_pkts_seen = 0;
10235 
10236 	a_chk->asoc = asoc;
10237 	a_chk->snd_count = 0;
10238 	a_chk->send_size = 0;	/* fill in later */
10239 	a_chk->sent = SCTP_DATAGRAM_UNSENT;
10240 	a_chk->whoTo = NULL;
10241 
10242 	if ((asoc->numduptsns) ||
10243 	    (asoc->last_data_chunk_from->dest_state & SCTP_ADDR_NOT_REACHABLE)
10244 	    ) {
10245 		/*-
10246 		 * Ok, we have some duplicates or the destination for the
10247 		 * sack is unreachable, lets see if we can select an
10248 		 * alternate than asoc->last_data_chunk_from
10249 		 */
10250 		if ((!(asoc->last_data_chunk_from->dest_state &
10251 		    SCTP_ADDR_NOT_REACHABLE)) &&
10252 		    (asoc->used_alt_onsack > asoc->numnets)) {
10253 			/* We used an alt last time, don't this time */
10254 			a_chk->whoTo = NULL;
10255 		} else {
10256 			asoc->used_alt_onsack++;
10257 			a_chk->whoTo = sctp_find_alternate_net(stcb, asoc->last_data_chunk_from, 0);
10258 		}
10259 		if (a_chk->whoTo == NULL) {
10260 			/* Nope, no alternate */
10261 			a_chk->whoTo = asoc->last_data_chunk_from;
10262 			asoc->used_alt_onsack = 0;
10263 		}
10264 	} else {
10265 		/*
10266 		 * No duplicates so we use the last place we received data
10267 		 * from.
10268 		 */
10269 		asoc->used_alt_onsack = 0;
10270 		a_chk->whoTo = asoc->last_data_chunk_from;
10271 	}
10272 	if (a_chk->whoTo) {
10273 		atomic_add_int(&a_chk->whoTo->ref_count, 1);
10274 	}
10275 	if (asoc->highest_tsn_inside_map == asoc->cumulative_tsn) {
10276 		/* no gaps */
10277 		space_req = sizeof(struct sctp_nr_sack_chunk);
10278 	} else {
10279 		/* EY - what is this about? */
10280 		/* gaps get a cluster */
10281 		space_req = MCLBYTES;
10282 	}
10283 	/* Ok now lets formulate a MBUF with our sack */
10284 	a_chk->data = sctp_get_mbuf_for_msg(space_req, 0, M_DONTWAIT, 1, MT_DATA);
10285 	if ((a_chk->data == NULL) ||
10286 	    (a_chk->whoTo == NULL)) {
10287 		/* rats, no mbuf memory */
10288 		if (a_chk->data) {
10289 			/* was a problem with the destination */
10290 			sctp_m_freem(a_chk->data);
10291 			a_chk->data = NULL;
10292 		}
10293 		sctp_free_a_chunk(stcb, a_chk);
10294 		/* sa_ignore NO_NULL_CHK */
10295 		if (stcb->asoc.delayed_ack) {
10296 			sctp_timer_stop(SCTP_TIMER_TYPE_RECV,
10297 			    stcb->sctp_ep, stcb, NULL, SCTP_FROM_SCTP_OUTPUT + SCTP_LOC_6);
10298 			sctp_timer_start(SCTP_TIMER_TYPE_RECV,
10299 			    stcb->sctp_ep, stcb, NULL);
10300 		} else {
10301 			stcb->asoc.send_sack = 1;
10302 		}
10303 		return;
10304 	}
10305 	/* ok, lets go through and fill it in */
10306 	SCTP_BUF_RESV_UF(a_chk->data, SCTP_MIN_OVERHEAD);
10307 	space = M_TRAILINGSPACE(a_chk->data);
10308 	if (space > (a_chk->whoTo->mtu - SCTP_MIN_OVERHEAD)) {
10309 		space = (a_chk->whoTo->mtu - SCTP_MIN_OVERHEAD);
10310 	}
10311 	limit = mtod(a_chk->data, caddr_t);
10312 	limit += space;
10313 
10314 	nr_sack = mtod(a_chk->data, struct sctp_nr_sack_chunk *);
10315 	nr_sack->ch.chunk_type = SCTP_NR_SELECTIVE_ACK;
10316 	/* EYJ */
10317 	/* 0x01 is used by nonce for ecn */
10318 	if ((SCTP_BASE_SYSCTL(sctp_ecn_enable)) &&
10319 	    (SCTP_BASE_SYSCTL(sctp_ecn_nonce)) &&
10320 	    (asoc->peer_supports_ecn_nonce))
10321 		nr_sack->ch.chunk_flags = (asoc->receiver_nonce_sum & SCTP_SACK_NONCE_SUM);
10322 	else
10323 		nr_sack->ch.chunk_flags = 0;
10324 
10325 	if (SCTP_BASE_SYSCTL(sctp_cmt_on_off) && SCTP_BASE_SYSCTL(sctp_cmt_use_dac)) {
10326 		/*-
10327 		 * CMT DAC algorithm: If 2 (i.e., 0x10) packets have been
10328 		 * received, then set high bit to 1, else 0. Reset
10329 		 * pkts_rcvd.
10330 		 */
10331 		/* EY - TODO: which chunk flag is used in here? -The LSB */
10332 		nr_sack->ch.chunk_flags |= (asoc->cmt_dac_pkts_rcvd << 6);
10333 		asoc->cmt_dac_pkts_rcvd = 0;
10334 	}
10335 #ifdef SCTP_ASOCLOG_OF_TSNS
10336 	stcb->asoc.cumack_logsnt[stcb->asoc.cumack_log_atsnt] = asoc->cumulative_tsn;
10337 	stcb->asoc.cumack_log_atsnt++;
10338 	if (stcb->asoc.cumack_log_atsnt >= SCTP_TSN_LOG_SIZE) {
10339 		stcb->asoc.cumack_log_atsnt = 0;
10340 	}
10341 #endif
10342 	nr_sack->nr_sack.cum_tsn_ack = htonl(asoc->cumulative_tsn);
10343 	nr_sack->nr_sack.a_rwnd = htonl(asoc->my_rwnd);
10344 	asoc->my_last_reported_rwnd = asoc->my_rwnd;
10345 
10346 	/* reset the readers interpretation */
10347 	stcb->freed_by_sorcv_sincelast = 0;
10348 
10349 	gap_descriptor = (struct sctp_gap_ack_block *)((caddr_t)nr_sack + sizeof(struct sctp_nr_sack_chunk));
10350 
10351 	if (asoc->highest_tsn_inside_map > asoc->mapping_array_base_tsn)
10352 		siz = (((asoc->highest_tsn_inside_map - asoc->mapping_array_base_tsn) + 1) + 7) / 8;
10353 	else
10354 		siz = (((MAX_TSN - asoc->mapping_array_base_tsn) + 1) + asoc->highest_tsn_inside_map + 7) / 8;
10355 
10356 	if (compare_with_wrap(asoc->mapping_array_base_tsn, asoc->cumulative_tsn, MAX_TSN)) {
10357 		offset = 1;
10358 		/*-
10359 		 * cum-ack behind the mapping array, so we start and use all
10360 		 * entries.
10361 		 */
10362 		jstart = 0;
10363 	} else {
10364 		offset = asoc->mapping_array_base_tsn - asoc->cumulative_tsn;
10365 		/*-
10366 		 * we skip the first one when the cum-ack is at or above the
10367 		 * mapping array base. Note this only works if
10368 		 */
10369 		jstart = 1;
10370 	}
10371 	if (compare_with_wrap(asoc->highest_tsn_inside_map, asoc->cumulative_tsn, MAX_TSN)) {
10372 		/* we have a gap .. maybe */
10373 		for (i = 0; i < siz; i++) {
10374 			selector = &sack_array[asoc->mapping_array[i]];
10375 			if (mergeable && selector->right_edge) {
10376 				/*
10377 				 * Backup, left and right edges were ok to
10378 				 * merge.
10379 				 */
10380 				num_gap_blocks--;
10381 				gap_descriptor--;
10382 			}
10383 			if (selector->num_entries == 0)
10384 				mergeable = 0;
10385 			else {
10386 				for (j = jstart; j < selector->num_entries; j++) {
10387 					if (mergeable && selector->right_edge) {
10388 						/*
10389 						 * do a merge by NOT setting
10390 						 * the left side
10391 						 */
10392 						mergeable = 0;
10393 					} else {
10394 						/*
10395 						 * no merge, set the left
10396 						 * side
10397 						 */
10398 						mergeable = 0;
10399 						gap_descriptor->start = htons((selector->gaps[j].start + offset));
10400 					}
10401 					gap_descriptor->end = htons((selector->gaps[j].end + offset));
10402 					num_gap_blocks++;
10403 					gap_descriptor++;
10404 					if (((caddr_t)gap_descriptor + sizeof(struct sctp_gap_ack_block)) > limit) {
10405 						/* no more room */
10406 						limit_reached = 1;
10407 						break;
10408 					}
10409 				}
10410 				if (selector->left_edge) {
10411 					mergeable = 1;
10412 				}
10413 			}
10414 			if (limit_reached) {
10415 				/* Reached the limit stop */
10416 				break;
10417 			}
10418 			jstart = 0;
10419 			offset += 8;
10420 		}
10421 		if (num_gap_blocks == 0) {
10422 			/*
10423 			 * slide not yet happened, and somehow we got called
10424 			 * to send a sack. Cumack needs to move up.
10425 			 */
10426 			int abort_flag = 0;
10427 
10428 			asoc->cumulative_tsn = asoc->highest_tsn_inside_map;
10429 			nr_sack->nr_sack.cum_tsn_ack = htonl(asoc->cumulative_tsn);
10430 			sctp_sack_check(stcb, 0, 0, &abort_flag);
10431 		}
10432 	}
10433 	/*---------------------------------------------------------filling the nr_gap_ack blocks----------------------------------------------------*/
10434 
10435 	/* EY - there will be gaps + nr_gaps if draining is possible */
10436 	if ((SCTP_BASE_SYSCTL(sctp_do_drain)) && (limit_reached == 0)) {
10437 
10438 		mergeable = 0;
10439 
10440 		if (asoc->highest_tsn_inside_nr_map > asoc->nr_mapping_array_base_tsn)
10441 			siz = (((asoc->highest_tsn_inside_nr_map - asoc->nr_mapping_array_base_tsn) + 1) + 7) / 8;
10442 		else
10443 			siz = (((MAX_TSN - asoc->nr_mapping_array_base_tsn) + 1) + asoc->highest_tsn_inside_nr_map + 7) / 8;
10444 
10445 		if (compare_with_wrap(asoc->nr_mapping_array_base_tsn, asoc->cumulative_tsn, MAX_TSN)) {
10446 			offset = 1;
10447 			/*-
10448 			* cum-ack behind the mapping array, so we start and use all
10449 			* entries.
10450 			*/
10451 			jstart = 0;
10452 		} else {
10453 			offset = asoc->nr_mapping_array_base_tsn - asoc->cumulative_tsn;
10454 			/*-
10455 			* we skip the first one when the cum-ack is at or above the
10456 			* mapping array base. Note this only works if
10457 			*/
10458 			jstart = 1;
10459 		}
10460 		if (compare_with_wrap(asoc->highest_tsn_inside_nr_map, asoc->cumulative_tsn, MAX_TSN)) {
10461 			/* we have a gap .. maybe */
10462 			for (i = 0; i < siz; i++) {
10463 				nr_selector = &sack_array[asoc->nr_mapping_array[i]];
10464 				if (mergeable && nr_selector->right_edge) {
10465 					/*
10466 					 * Backup, left and right edges were
10467 					 * ok to merge.
10468 					 */
10469 					num_nr_gap_blocks--;
10470 					gap_descriptor--;
10471 				}
10472 				if (nr_selector->num_entries == 0)
10473 					mergeable = 0;
10474 				else {
10475 					for (j = jstart; j < nr_selector->num_entries; j++) {
10476 						if (mergeable && nr_selector->right_edge) {
10477 							/*
10478 							 * do a merge by NOT
10479 							 * setting the left
10480 							 * side
10481 							 */
10482 							mergeable = 0;
10483 						} else {
10484 							/*
10485 							 * no merge, set the
10486 							 * left side
10487 							 */
10488 							mergeable = 0;
10489 							gap_descriptor->start = htons((nr_selector->gaps[j].start + offset));
10490 						}
10491 						gap_descriptor->end = htons((nr_selector->gaps[j].end + offset));
10492 						num_nr_gap_blocks++;
10493 						gap_descriptor++;
10494 						if (((caddr_t)gap_descriptor + sizeof(struct sctp_gap_ack_block)) > limit) {
10495 							/* no more room */
10496 							limit_reached = 1;
10497 							break;
10498 						}
10499 					}
10500 					if (nr_selector->left_edge) {
10501 						mergeable = 1;
10502 					}
10503 				}
10504 				if (limit_reached) {
10505 					/* Reached the limit stop */
10506 					break;
10507 				}
10508 				jstart = 0;
10509 				offset += 8;
10510 			}
10511 		}
10512 	}
10513 	/*---------------------------------------------End of---filling the nr_gap_ack blocks----------------------------------------------------*/
10514 
10515 	/* now we must add any dups we are going to report. */
10516 	if ((limit_reached == 0) && (asoc->numduptsns)) {
10517 		dup = (uint32_t *) gap_descriptor;
10518 		for (i = 0; i < asoc->numduptsns; i++) {
10519 			*dup = htonl(asoc->dup_tsns[i]);
10520 			dup++;
10521 			num_dups++;
10522 			if (((caddr_t)dup + sizeof(uint32_t)) > limit) {
10523 				/* no more room */
10524 				break;
10525 			}
10526 		}
10527 		asoc->numduptsns = 0;
10528 	}
10529 	/*
10530 	 * now that the chunk is prepared queue it to the control chunk
10531 	 * queue.
10532 	 */
10533 	if (SCTP_BASE_SYSCTL(sctp_do_drain) == 0) {
10534 		num_nr_gap_blocks = num_gap_blocks;
10535 		num_gap_blocks = 0;
10536 	}
10537 	a_chk->send_size = sizeof(struct sctp_nr_sack_chunk) +
10538 	    (num_gap_blocks + num_nr_gap_blocks) * sizeof(struct sctp_gap_ack_block) +
10539 	    num_dups * sizeof(int32_t);
10540 
10541 	SCTP_BUF_LEN(a_chk->data) = a_chk->send_size;
10542 	nr_sack->nr_sack.num_gap_ack_blks = htons(num_gap_blocks);
10543 	nr_sack->nr_sack.num_nr_gap_ack_blks = htons(num_nr_gap_blocks);
10544 	nr_sack->nr_sack.num_dup_tsns = htons(num_dups);
10545 	nr_sack->nr_sack.reserved = htons(reserved);
10546 	nr_sack->ch.chunk_length = htons(a_chk->send_size);
10547 	TAILQ_INSERT_TAIL(&asoc->control_send_queue, a_chk, sctp_next);
10548 	asoc->ctrl_queue_cnt++;
10549 	asoc->send_sack = 0;
10550 	SCTP_STAT_INCR(sctps_sendsacks);
10551 	return;
10552 }
10553 
10554 void
10555 sctp_send_abort_tcb(struct sctp_tcb *stcb, struct mbuf *operr, int so_locked
10556 #if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
10557     SCTP_UNUSED
10558 #endif
10559 )
10560 {
10561 	struct mbuf *m_abort;
10562 	struct mbuf *m_out = NULL, *m_end = NULL;
10563 	struct sctp_abort_chunk *abort = NULL;
10564 	int sz;
10565 	uint32_t auth_offset = 0;
10566 	struct sctp_auth_chunk *auth = NULL;
10567 
10568 	/*-
10569 	 * Add an AUTH chunk, if chunk requires it and save the offset into
10570 	 * the chain for AUTH
10571 	 */
10572 	if (sctp_auth_is_required_chunk(SCTP_ABORT_ASSOCIATION,
10573 	    stcb->asoc.peer_auth_chunks)) {
10574 		m_out = sctp_add_auth_chunk(m_out, &m_end, &auth, &auth_offset,
10575 		    stcb, SCTP_ABORT_ASSOCIATION);
10576 		SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
10577 	}
10578 	SCTP_TCB_LOCK_ASSERT(stcb);
10579 	m_abort = sctp_get_mbuf_for_msg(sizeof(struct sctp_abort_chunk), 0, M_DONTWAIT, 1, MT_HEADER);
10580 	if (m_abort == NULL) {
10581 		/* no mbuf's */
10582 		if (m_out)
10583 			sctp_m_freem(m_out);
10584 		return;
10585 	}
10586 	/* link in any error */
10587 	SCTP_BUF_NEXT(m_abort) = operr;
10588 	sz = 0;
10589 	if (operr) {
10590 		struct mbuf *n;
10591 
10592 		n = operr;
10593 		while (n) {
10594 			sz += SCTP_BUF_LEN(n);
10595 			n = SCTP_BUF_NEXT(n);
10596 		}
10597 	}
10598 	SCTP_BUF_LEN(m_abort) = sizeof(*abort);
10599 	if (m_out == NULL) {
10600 		/* NO Auth chunk prepended, so reserve space in front */
10601 		SCTP_BUF_RESV_UF(m_abort, SCTP_MIN_OVERHEAD);
10602 		m_out = m_abort;
10603 	} else {
10604 		/* Put AUTH chunk at the front of the chain */
10605 		SCTP_BUF_NEXT(m_end) = m_abort;
10606 	}
10607 
10608 	/* fill in the ABORT chunk */
10609 	abort = mtod(m_abort, struct sctp_abort_chunk *);
10610 	abort->ch.chunk_type = SCTP_ABORT_ASSOCIATION;
10611 	abort->ch.chunk_flags = 0;
10612 	abort->ch.chunk_length = htons(sizeof(*abort) + sz);
10613 
10614 	(void)sctp_lowlevel_chunk_output(stcb->sctp_ep, stcb,
10615 	    stcb->asoc.primary_destination,
10616 	    (struct sockaddr *)&stcb->asoc.primary_destination->ro._l_addr,
10617 	    m_out, auth_offset, auth, stcb->asoc.authinfo.active_keyid, 1, 0, NULL, 0,
10618 	    stcb->sctp_ep->sctp_lport, stcb->rport, htonl(stcb->asoc.peer_vtag),
10619 	    stcb->asoc.primary_destination->port, so_locked, NULL);
10620 	SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
10621 }
10622 
10623 void
10624 sctp_send_shutdown_complete(struct sctp_tcb *stcb,
10625     struct sctp_nets *net)
10626 {
10627 	/* formulate and SEND a SHUTDOWN-COMPLETE */
10628 	struct mbuf *m_shutdown_comp;
10629 	struct sctp_shutdown_complete_chunk *shutdown_complete;
10630 
10631 	m_shutdown_comp = sctp_get_mbuf_for_msg(sizeof(struct sctp_chunkhdr), 0, M_DONTWAIT, 1, MT_HEADER);
10632 	if (m_shutdown_comp == NULL) {
10633 		/* no mbuf's */
10634 		return;
10635 	}
10636 	shutdown_complete = mtod(m_shutdown_comp, struct sctp_shutdown_complete_chunk *);
10637 	shutdown_complete->ch.chunk_type = SCTP_SHUTDOWN_COMPLETE;
10638 	shutdown_complete->ch.chunk_flags = 0;
10639 	shutdown_complete->ch.chunk_length = htons(sizeof(struct sctp_shutdown_complete_chunk));
10640 	SCTP_BUF_LEN(m_shutdown_comp) = sizeof(struct sctp_shutdown_complete_chunk);
10641 	(void)sctp_lowlevel_chunk_output(stcb->sctp_ep, stcb, net,
10642 	    (struct sockaddr *)&net->ro._l_addr,
10643 	    m_shutdown_comp, 0, NULL, 0, 1, 0, NULL, 0,
10644 	    stcb->sctp_ep->sctp_lport, stcb->rport,
10645 	    htonl(stcb->asoc.peer_vtag),
10646 	    net->port, SCTP_SO_NOT_LOCKED, NULL);
10647 	SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
10648 	return;
10649 }
10650 
10651 void
10652 sctp_send_shutdown_complete2(struct mbuf *m, int iphlen, struct sctphdr *sh,
10653     uint32_t vrf_id, uint16_t port)
10654 {
10655 	/* formulate and SEND a SHUTDOWN-COMPLETE */
10656 	struct mbuf *o_pak;
10657 	struct mbuf *mout;
10658 	struct ip *iph, *iph_out;
10659 	struct udphdr *udp = NULL;
10660 
10661 #ifdef INET6
10662 	struct ip6_hdr *ip6, *ip6_out;
10663 
10664 #endif
10665 	int offset_out, len, mlen;
10666 	struct sctp_shutdown_complete_msg *comp_cp;
10667 
10668 	iph = mtod(m, struct ip *);
10669 	switch (iph->ip_v) {
10670 	case IPVERSION:
10671 		len = (sizeof(struct ip) + sizeof(struct sctp_shutdown_complete_msg));
10672 		break;
10673 #ifdef INET6
10674 	case IPV6_VERSION >> 4:
10675 		len = (sizeof(struct ip6_hdr) + sizeof(struct sctp_shutdown_complete_msg));
10676 		break;
10677 #endif
10678 	default:
10679 		return;
10680 	}
10681 	if (port) {
10682 		len += sizeof(struct udphdr);
10683 	}
10684 	mout = sctp_get_mbuf_for_msg(len + max_linkhdr, 1, M_DONTWAIT, 1, MT_DATA);
10685 	if (mout == NULL) {
10686 		return;
10687 	}
10688 	SCTP_BUF_RESV_UF(mout, max_linkhdr);
10689 	SCTP_BUF_LEN(mout) = len;
10690 	SCTP_BUF_NEXT(mout) = NULL;
10691 	iph_out = NULL;
10692 #ifdef INET6
10693 	ip6_out = NULL;
10694 #endif
10695 	offset_out = 0;
10696 
10697 	switch (iph->ip_v) {
10698 	case IPVERSION:
10699 		iph_out = mtod(mout, struct ip *);
10700 
10701 		/* Fill in the IP header for the ABORT */
10702 		iph_out->ip_v = IPVERSION;
10703 		iph_out->ip_hl = (sizeof(struct ip) / 4);
10704 		iph_out->ip_tos = (u_char)0;
10705 		iph_out->ip_id = 0;
10706 		iph_out->ip_off = 0;
10707 		iph_out->ip_ttl = MAXTTL;
10708 		if (port) {
10709 			iph_out->ip_p = IPPROTO_UDP;
10710 		} else {
10711 			iph_out->ip_p = IPPROTO_SCTP;
10712 		}
10713 		iph_out->ip_src.s_addr = iph->ip_dst.s_addr;
10714 		iph_out->ip_dst.s_addr = iph->ip_src.s_addr;
10715 
10716 		/* let IP layer calculate this */
10717 		iph_out->ip_sum = 0;
10718 		offset_out += sizeof(*iph_out);
10719 		comp_cp = (struct sctp_shutdown_complete_msg *)(
10720 		    (caddr_t)iph_out + offset_out);
10721 		break;
10722 #ifdef INET6
10723 	case IPV6_VERSION >> 4:
10724 		ip6 = (struct ip6_hdr *)iph;
10725 		ip6_out = mtod(mout, struct ip6_hdr *);
10726 
10727 		/* Fill in the IPv6 header for the ABORT */
10728 		ip6_out->ip6_flow = ip6->ip6_flow;
10729 		ip6_out->ip6_hlim = MODULE_GLOBAL(ip6_defhlim);
10730 		if (port) {
10731 			ip6_out->ip6_nxt = IPPROTO_UDP;
10732 		} else {
10733 			ip6_out->ip6_nxt = IPPROTO_SCTP;
10734 		}
10735 		ip6_out->ip6_src = ip6->ip6_dst;
10736 		ip6_out->ip6_dst = ip6->ip6_src;
10737 		/*
10738 		 * ?? The old code had both the iph len + payload, I think
10739 		 * this is wrong and would never have worked
10740 		 */
10741 		ip6_out->ip6_plen = sizeof(struct sctp_shutdown_complete_msg);
10742 		offset_out += sizeof(*ip6_out);
10743 		comp_cp = (struct sctp_shutdown_complete_msg *)(
10744 		    (caddr_t)ip6_out + offset_out);
10745 		break;
10746 #endif				/* INET6 */
10747 	default:
10748 		/* Currently not supported. */
10749 		sctp_m_freem(mout);
10750 		return;
10751 	}
10752 	if (port) {
10753 		udp = (struct udphdr *)comp_cp;
10754 		udp->uh_sport = htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port));
10755 		udp->uh_dport = port;
10756 		udp->uh_ulen = htons(sizeof(struct sctp_shutdown_complete_msg) + sizeof(struct udphdr));
10757 		udp->uh_sum = in_pseudo(iph_out->ip_src.s_addr, iph_out->ip_dst.s_addr, udp->uh_ulen + htons(IPPROTO_UDP));
10758 		offset_out += sizeof(struct udphdr);
10759 		comp_cp = (struct sctp_shutdown_complete_msg *)((caddr_t)comp_cp + sizeof(struct udphdr));
10760 	}
10761 	if (SCTP_GET_HEADER_FOR_OUTPUT(o_pak)) {
10762 		/* no mbuf's */
10763 		sctp_m_freem(mout);
10764 		return;
10765 	}
10766 	/* Now copy in and fill in the ABORT tags etc. */
10767 	comp_cp->sh.src_port = sh->dest_port;
10768 	comp_cp->sh.dest_port = sh->src_port;
10769 	comp_cp->sh.checksum = 0;
10770 	comp_cp->sh.v_tag = sh->v_tag;
10771 	comp_cp->shut_cmp.ch.chunk_flags = SCTP_HAD_NO_TCB;
10772 	comp_cp->shut_cmp.ch.chunk_type = SCTP_SHUTDOWN_COMPLETE;
10773 	comp_cp->shut_cmp.ch.chunk_length = htons(sizeof(struct sctp_shutdown_complete_chunk));
10774 
10775 	if (iph_out != NULL) {
10776 		sctp_route_t ro;
10777 		int ret;
10778 		struct sctp_tcb *stcb = NULL;
10779 
10780 		mlen = SCTP_BUF_LEN(mout);
10781 		bzero(&ro, sizeof ro);
10782 		/* set IPv4 length */
10783 		iph_out->ip_len = mlen;
10784 #ifdef  SCTP_PACKET_LOGGING
10785 		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LAST_PACKET_TRACING)
10786 			sctp_packet_log(mout, mlen);
10787 #endif
10788 		if (port) {
10789 			comp_cp->sh.checksum = sctp_calculate_cksum(mout, offset_out);
10790 			SCTP_STAT_INCR(sctps_sendswcrc);
10791 			SCTP_ENABLE_UDP_CSUM(mout);
10792 		} else {
10793 			mout->m_pkthdr.csum_flags = CSUM_SCTP;
10794 			mout->m_pkthdr.csum_data = 0;	/* FIXME MT */
10795 			SCTP_STAT_INCR(sctps_sendhwcrc);
10796 		}
10797 		SCTP_ATTACH_CHAIN(o_pak, mout, mlen);
10798 		/* out it goes */
10799 		SCTP_IP_OUTPUT(ret, o_pak, &ro, stcb, vrf_id);
10800 
10801 		/* Free the route if we got one back */
10802 		if (ro.ro_rt)
10803 			RTFREE(ro.ro_rt);
10804 	}
10805 #ifdef INET6
10806 	if (ip6_out != NULL) {
10807 		struct route_in6 ro;
10808 		int ret;
10809 		struct sctp_tcb *stcb = NULL;
10810 		struct ifnet *ifp = NULL;
10811 
10812 		bzero(&ro, sizeof(ro));
10813 		mlen = SCTP_BUF_LEN(mout);
10814 #ifdef  SCTP_PACKET_LOGGING
10815 		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LAST_PACKET_TRACING)
10816 			sctp_packet_log(mout, mlen);
10817 #endif
10818 		comp_cp->sh.checksum = sctp_calculate_cksum(mout, offset_out);
10819 		SCTP_STAT_INCR(sctps_sendswcrc);
10820 		SCTP_ATTACH_CHAIN(o_pak, mout, mlen);
10821 		if (port) {
10822 			if ((udp->uh_sum = in6_cksum(o_pak, IPPROTO_UDP, sizeof(struct ip6_hdr),
10823 			    sizeof(struct sctp_shutdown_complete_msg) + sizeof(struct udphdr))) == 0) {
10824 				udp->uh_sum = 0xffff;
10825 			}
10826 		}
10827 		SCTP_IP6_OUTPUT(ret, o_pak, &ro, &ifp, stcb, vrf_id);
10828 
10829 		/* Free the route if we got one back */
10830 		if (ro.ro_rt)
10831 			RTFREE(ro.ro_rt);
10832 	}
10833 #endif
10834 	SCTP_STAT_INCR(sctps_sendpackets);
10835 	SCTP_STAT_INCR_COUNTER64(sctps_outpackets);
10836 	SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
10837 	return;
10838 
10839 }
10840 
10841 static struct sctp_nets *
10842 sctp_select_hb_destination(struct sctp_tcb *stcb, struct timeval *now)
10843 {
10844 	struct sctp_nets *net, *hnet;
10845 	int ms_goneby, highest_ms, state_overide = 0;
10846 
10847 	(void)SCTP_GETTIME_TIMEVAL(now);
10848 	highest_ms = 0;
10849 	hnet = NULL;
10850 	SCTP_TCB_LOCK_ASSERT(stcb);
10851 	TAILQ_FOREACH(net, &stcb->asoc.nets, sctp_next) {
10852 		if (
10853 		    ((net->dest_state & SCTP_ADDR_NOHB) && ((net->dest_state & SCTP_ADDR_UNCONFIRMED) == 0)) ||
10854 		    (net->dest_state & SCTP_ADDR_OUT_OF_SCOPE)
10855 		    ) {
10856 			/*
10857 			 * Skip this guy from consideration if HB is off AND
10858 			 * its confirmed
10859 			 */
10860 			continue;
10861 		}
10862 		if (sctp_destination_is_reachable(stcb, (struct sockaddr *)&net->ro._l_addr) == 0) {
10863 			/* skip this dest net from consideration */
10864 			continue;
10865 		}
10866 		if (net->last_sent_time.tv_sec) {
10867 			/* Sent to so we subtract */
10868 			ms_goneby = (now->tv_sec - net->last_sent_time.tv_sec) * 1000;
10869 		} else
10870 			/* Never been sent to */
10871 			ms_goneby = 0x7fffffff;
10872 		/*-
10873 		 * When the address state is unconfirmed but still
10874 		 * considered reachable, we HB at a higher rate. Once it
10875 		 * goes confirmed OR reaches the "unreachable" state, thenw
10876 		 * we cut it back to HB at a more normal pace.
10877 		 */
10878 		if ((net->dest_state & (SCTP_ADDR_UNCONFIRMED | SCTP_ADDR_NOT_REACHABLE)) == SCTP_ADDR_UNCONFIRMED) {
10879 			state_overide = 1;
10880 		} else {
10881 			state_overide = 0;
10882 		}
10883 
10884 		if ((((unsigned int)ms_goneby >= net->RTO) || (state_overide)) &&
10885 		    (ms_goneby > highest_ms)) {
10886 			highest_ms = ms_goneby;
10887 			hnet = net;
10888 		}
10889 	}
10890 	if (hnet &&
10891 	    ((hnet->dest_state & (SCTP_ADDR_UNCONFIRMED | SCTP_ADDR_NOT_REACHABLE)) == SCTP_ADDR_UNCONFIRMED)) {
10892 		state_overide = 1;
10893 	} else {
10894 		state_overide = 0;
10895 	}
10896 
10897 	if (hnet && highest_ms && (((unsigned int)highest_ms >= hnet->RTO) || state_overide)) {
10898 		/*-
10899 		 * Found the one with longest delay bounds OR it is
10900 		 * unconfirmed and still not marked unreachable.
10901 		 */
10902 		SCTPDBG(SCTP_DEBUG_OUTPUT4, "net:%p is the hb winner -", hnet);
10903 #ifdef SCTP_DEBUG
10904 		if (hnet) {
10905 			SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT4,
10906 			    (struct sockaddr *)&hnet->ro._l_addr);
10907 		} else {
10908 			SCTPDBG(SCTP_DEBUG_OUTPUT4, " none\n");
10909 		}
10910 #endif
10911 		/* update the timer now */
10912 		hnet->last_sent_time = *now;
10913 		return (hnet);
10914 	}
10915 	/* Nothing to HB */
10916 	return (NULL);
10917 }
10918 
10919 int
10920 sctp_send_hb(struct sctp_tcb *stcb, int user_req, struct sctp_nets *u_net)
10921 {
10922 	struct sctp_tmit_chunk *chk;
10923 	struct sctp_nets *net;
10924 	struct sctp_heartbeat_chunk *hb;
10925 	struct timeval now;
10926 	struct sockaddr_in *sin;
10927 	struct sockaddr_in6 *sin6;
10928 
10929 	SCTP_TCB_LOCK_ASSERT(stcb);
10930 	if (user_req == 0) {
10931 		net = sctp_select_hb_destination(stcb, &now);
10932 		if (net == NULL) {
10933 			/*-
10934 			 * All our busy none to send to, just start the
10935 			 * timer again.
10936 			 */
10937 			if (stcb->asoc.state == 0) {
10938 				return (0);
10939 			}
10940 			sctp_timer_start(SCTP_TIMER_TYPE_HEARTBEAT,
10941 			    stcb->sctp_ep,
10942 			    stcb,
10943 			    net);
10944 			return (0);
10945 		}
10946 	} else {
10947 		net = u_net;
10948 		if (net == NULL) {
10949 			return (0);
10950 		}
10951 		(void)SCTP_GETTIME_TIMEVAL(&now);
10952 	}
10953 	sin = (struct sockaddr_in *)&net->ro._l_addr;
10954 	if (sin->sin_family != AF_INET) {
10955 		if (sin->sin_family != AF_INET6) {
10956 			/* huh */
10957 			return (0);
10958 		}
10959 	}
10960 	sctp_alloc_a_chunk(stcb, chk);
10961 	if (chk == NULL) {
10962 		SCTPDBG(SCTP_DEBUG_OUTPUT4, "Gak, can't get a chunk for hb\n");
10963 		return (0);
10964 	}
10965 	chk->copy_by_ref = 0;
10966 	chk->rec.chunk_id.id = SCTP_HEARTBEAT_REQUEST;
10967 	chk->rec.chunk_id.can_take_data = 1;
10968 	chk->asoc = &stcb->asoc;
10969 	chk->send_size = sizeof(struct sctp_heartbeat_chunk);
10970 
10971 	chk->data = sctp_get_mbuf_for_msg(chk->send_size, 0, M_DONTWAIT, 1, MT_HEADER);
10972 	if (chk->data == NULL) {
10973 		sctp_free_a_chunk(stcb, chk);
10974 		return (0);
10975 	}
10976 	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
10977 	SCTP_BUF_LEN(chk->data) = chk->send_size;
10978 	chk->sent = SCTP_DATAGRAM_UNSENT;
10979 	chk->snd_count = 0;
10980 	chk->whoTo = net;
10981 	atomic_add_int(&chk->whoTo->ref_count, 1);
10982 	/* Now we have a mbuf that we can fill in with the details */
10983 	hb = mtod(chk->data, struct sctp_heartbeat_chunk *);
10984 	memset(hb, 0, sizeof(struct sctp_heartbeat_chunk));
10985 	/* fill out chunk header */
10986 	hb->ch.chunk_type = SCTP_HEARTBEAT_REQUEST;
10987 	hb->ch.chunk_flags = 0;
10988 	hb->ch.chunk_length = htons(chk->send_size);
10989 	/* Fill out hb parameter */
10990 	hb->heartbeat.hb_info.ph.param_type = htons(SCTP_HEARTBEAT_INFO);
10991 	hb->heartbeat.hb_info.ph.param_length = htons(sizeof(struct sctp_heartbeat_info_param));
10992 	hb->heartbeat.hb_info.time_value_1 = now.tv_sec;
10993 	hb->heartbeat.hb_info.time_value_2 = now.tv_usec;
10994 	/* Did our user request this one, put it in */
10995 	hb->heartbeat.hb_info.user_req = user_req;
10996 	hb->heartbeat.hb_info.addr_family = sin->sin_family;
10997 	hb->heartbeat.hb_info.addr_len = sin->sin_len;
10998 	if (net->dest_state & SCTP_ADDR_UNCONFIRMED) {
10999 		/*
11000 		 * we only take from the entropy pool if the address is not
11001 		 * confirmed.
11002 		 */
11003 		net->heartbeat_random1 = hb->heartbeat.hb_info.random_value1 = sctp_select_initial_TSN(&stcb->sctp_ep->sctp_ep);
11004 		net->heartbeat_random2 = hb->heartbeat.hb_info.random_value2 = sctp_select_initial_TSN(&stcb->sctp_ep->sctp_ep);
11005 	} else {
11006 		net->heartbeat_random1 = hb->heartbeat.hb_info.random_value1 = 0;
11007 		net->heartbeat_random2 = hb->heartbeat.hb_info.random_value2 = 0;
11008 	}
11009 	if (sin->sin_family == AF_INET) {
11010 		memcpy(hb->heartbeat.hb_info.address, &sin->sin_addr, sizeof(sin->sin_addr));
11011 	} else if (sin->sin_family == AF_INET6) {
11012 		/* We leave the scope the way it is in our lookup table. */
11013 		sin6 = (struct sockaddr_in6 *)&net->ro._l_addr;
11014 		memcpy(hb->heartbeat.hb_info.address, &sin6->sin6_addr, sizeof(sin6->sin6_addr));
11015 	} else {
11016 		/* huh compiler bug */
11017 		return (0);
11018 	}
11019 
11020 	/*
11021 	 * JRS 5/14/07 - In CMT PF, the T3 timer is used to track
11022 	 * PF-heartbeats.  Because of this, threshold management is done by
11023 	 * the t3 timer handler, and does not need to be done upon the send
11024 	 * of a PF-heartbeat. If CMT PF is on and the destination to which a
11025 	 * heartbeat is being sent is in PF state, do NOT do threshold
11026 	 * management.
11027 	 */
11028 	if ((SCTP_BASE_SYSCTL(sctp_cmt_pf) == 0) || ((net->dest_state & SCTP_ADDR_PF) != SCTP_ADDR_PF)) {
11029 		/* ok we have a destination that needs a beat */
11030 		/* lets do the theshold management Qiaobing style */
11031 		if (sctp_threshold_management(stcb->sctp_ep, stcb, net,
11032 		    stcb->asoc.max_send_times)) {
11033 			/*-
11034 			 * we have lost the association, in a way this is
11035 			 * quite bad since we really are one less time since
11036 			 * we really did not send yet. This is the down side
11037 			 * to the Q's style as defined in the RFC and not my
11038 			 * alternate style defined in the RFC.
11039 			 */
11040 			if (chk->data != NULL) {
11041 				sctp_m_freem(chk->data);
11042 				chk->data = NULL;
11043 			}
11044 			/*
11045 			 * Here we do NOT use the macro since the
11046 			 * association is now gone.
11047 			 */
11048 			if (chk->whoTo) {
11049 				sctp_free_remote_addr(chk->whoTo);
11050 				chk->whoTo = NULL;
11051 			}
11052 			sctp_free_a_chunk((struct sctp_tcb *)NULL, chk);
11053 			return (-1);
11054 		}
11055 	}
11056 	net->hb_responded = 0;
11057 	TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
11058 	stcb->asoc.ctrl_queue_cnt++;
11059 	SCTP_STAT_INCR(sctps_sendheartbeat);
11060 	/*-
11061 	 * Call directly med level routine to put out the chunk. It will
11062 	 * always tumble out control chunks aka HB but it may even tumble
11063 	 * out data too.
11064 	 */
11065 	return (1);
11066 }
11067 
11068 void
11069 sctp_send_ecn_echo(struct sctp_tcb *stcb, struct sctp_nets *net,
11070     uint32_t high_tsn)
11071 {
11072 	struct sctp_association *asoc;
11073 	struct sctp_ecne_chunk *ecne;
11074 	struct sctp_tmit_chunk *chk;
11075 
11076 	asoc = &stcb->asoc;
11077 	SCTP_TCB_LOCK_ASSERT(stcb);
11078 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
11079 		if (chk->rec.chunk_id.id == SCTP_ECN_ECHO) {
11080 			/* found a previous ECN_ECHO update it if needed */
11081 			ecne = mtod(chk->data, struct sctp_ecne_chunk *);
11082 			ecne->tsn = htonl(high_tsn);
11083 			return;
11084 		}
11085 	}
11086 	/* nope could not find one to update so we must build one */
11087 	sctp_alloc_a_chunk(stcb, chk);
11088 	if (chk == NULL) {
11089 		return;
11090 	}
11091 	chk->copy_by_ref = 0;
11092 	SCTP_STAT_INCR(sctps_sendecne);
11093 	chk->rec.chunk_id.id = SCTP_ECN_ECHO;
11094 	chk->rec.chunk_id.can_take_data = 0;
11095 	chk->asoc = &stcb->asoc;
11096 	chk->send_size = sizeof(struct sctp_ecne_chunk);
11097 	chk->data = sctp_get_mbuf_for_msg(chk->send_size, 0, M_DONTWAIT, 1, MT_HEADER);
11098 	if (chk->data == NULL) {
11099 		sctp_free_a_chunk(stcb, chk);
11100 		return;
11101 	}
11102 	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
11103 	SCTP_BUF_LEN(chk->data) = chk->send_size;
11104 	chk->sent = SCTP_DATAGRAM_UNSENT;
11105 	chk->snd_count = 0;
11106 	chk->whoTo = net;
11107 	atomic_add_int(&chk->whoTo->ref_count, 1);
11108 	stcb->asoc.ecn_echo_cnt_onq++;
11109 	ecne = mtod(chk->data, struct sctp_ecne_chunk *);
11110 	ecne->ch.chunk_type = SCTP_ECN_ECHO;
11111 	ecne->ch.chunk_flags = 0;
11112 	ecne->ch.chunk_length = htons(sizeof(struct sctp_ecne_chunk));
11113 	ecne->tsn = htonl(high_tsn);
11114 	TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
11115 	asoc->ctrl_queue_cnt++;
11116 }
11117 
11118 void
11119 sctp_send_packet_dropped(struct sctp_tcb *stcb, struct sctp_nets *net,
11120     struct mbuf *m, int iphlen, int bad_crc)
11121 {
11122 	struct sctp_association *asoc;
11123 	struct sctp_pktdrop_chunk *drp;
11124 	struct sctp_tmit_chunk *chk;
11125 	uint8_t *datap;
11126 	int len;
11127 	int was_trunc = 0;
11128 	struct ip *iph;
11129 
11130 #ifdef INET6
11131 	struct ip6_hdr *ip6h;
11132 
11133 #endif
11134 	int fullsz = 0, extra = 0;
11135 	long spc;
11136 	int offset;
11137 	struct sctp_chunkhdr *ch, chunk_buf;
11138 	unsigned int chk_length;
11139 
11140 	if (!stcb) {
11141 		return;
11142 	}
11143 	asoc = &stcb->asoc;
11144 	SCTP_TCB_LOCK_ASSERT(stcb);
11145 	if (asoc->peer_supports_pktdrop == 0) {
11146 		/*-
11147 		 * peer must declare support before I send one.
11148 		 */
11149 		return;
11150 	}
11151 	if (stcb->sctp_socket == NULL) {
11152 		return;
11153 	}
11154 	sctp_alloc_a_chunk(stcb, chk);
11155 	if (chk == NULL) {
11156 		return;
11157 	}
11158 	chk->copy_by_ref = 0;
11159 	iph = mtod(m, struct ip *);
11160 	if (iph == NULL) {
11161 		sctp_free_a_chunk(stcb, chk);
11162 		return;
11163 	}
11164 	switch (iph->ip_v) {
11165 	case IPVERSION:
11166 		/* IPv4 */
11167 		len = chk->send_size = iph->ip_len;
11168 		break;
11169 #ifdef INET6
11170 	case IPV6_VERSION >> 4:
11171 		/* IPv6 */
11172 		ip6h = mtod(m, struct ip6_hdr *);
11173 		len = chk->send_size = htons(ip6h->ip6_plen);
11174 		break;
11175 #endif
11176 	default:
11177 		return;
11178 	}
11179 	/* Validate that we do not have an ABORT in here. */
11180 	offset = iphlen + sizeof(struct sctphdr);
11181 	ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, offset,
11182 	    sizeof(*ch), (uint8_t *) & chunk_buf);
11183 	while (ch != NULL) {
11184 		chk_length = ntohs(ch->chunk_length);
11185 		if (chk_length < sizeof(*ch)) {
11186 			/* break to abort land */
11187 			break;
11188 		}
11189 		switch (ch->chunk_type) {
11190 		case SCTP_PACKET_DROPPED:
11191 		case SCTP_ABORT_ASSOCIATION:
11192 			/*-
11193 			 * we don't respond with an PKT-DROP to an ABORT
11194 			 * or PKT-DROP
11195 			 */
11196 			sctp_free_a_chunk(stcb, chk);
11197 			return;
11198 		default:
11199 			break;
11200 		}
11201 		offset += SCTP_SIZE32(chk_length);
11202 		ch = (struct sctp_chunkhdr *)sctp_m_getptr(m, offset,
11203 		    sizeof(*ch), (uint8_t *) & chunk_buf);
11204 	}
11205 
11206 	if ((len + SCTP_MAX_OVERHEAD + sizeof(struct sctp_pktdrop_chunk)) >
11207 	    min(stcb->asoc.smallest_mtu, MCLBYTES)) {
11208 		/*
11209 		 * only send 1 mtu worth, trim off the excess on the end.
11210 		 */
11211 		fullsz = len - extra;
11212 		len = min(stcb->asoc.smallest_mtu, MCLBYTES) - SCTP_MAX_OVERHEAD;
11213 		was_trunc = 1;
11214 	}
11215 	chk->asoc = &stcb->asoc;
11216 	chk->data = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_DATA);
11217 	if (chk->data == NULL) {
11218 jump_out:
11219 		sctp_free_a_chunk(stcb, chk);
11220 		return;
11221 	}
11222 	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
11223 	drp = mtod(chk->data, struct sctp_pktdrop_chunk *);
11224 	if (drp == NULL) {
11225 		sctp_m_freem(chk->data);
11226 		chk->data = NULL;
11227 		goto jump_out;
11228 	}
11229 	chk->book_size = SCTP_SIZE32((chk->send_size + sizeof(struct sctp_pktdrop_chunk) +
11230 	    sizeof(struct sctphdr) + SCTP_MED_OVERHEAD));
11231 	chk->book_size_scale = 0;
11232 	if (was_trunc) {
11233 		drp->ch.chunk_flags = SCTP_PACKET_TRUNCATED;
11234 		drp->trunc_len = htons(fullsz);
11235 		/*
11236 		 * Len is already adjusted to size minus overhead above take
11237 		 * out the pkt_drop chunk itself from it.
11238 		 */
11239 		chk->send_size = len - sizeof(struct sctp_pktdrop_chunk);
11240 		len = chk->send_size;
11241 	} else {
11242 		/* no truncation needed */
11243 		drp->ch.chunk_flags = 0;
11244 		drp->trunc_len = htons(0);
11245 	}
11246 	if (bad_crc) {
11247 		drp->ch.chunk_flags |= SCTP_BADCRC;
11248 	}
11249 	chk->send_size += sizeof(struct sctp_pktdrop_chunk);
11250 	SCTP_BUF_LEN(chk->data) = chk->send_size;
11251 	chk->sent = SCTP_DATAGRAM_UNSENT;
11252 	chk->snd_count = 0;
11253 	if (net) {
11254 		/* we should hit here */
11255 		chk->whoTo = net;
11256 	} else {
11257 		chk->whoTo = asoc->primary_destination;
11258 	}
11259 	atomic_add_int(&chk->whoTo->ref_count, 1);
11260 	chk->rec.chunk_id.id = SCTP_PACKET_DROPPED;
11261 	chk->rec.chunk_id.can_take_data = 1;
11262 	drp->ch.chunk_type = SCTP_PACKET_DROPPED;
11263 	drp->ch.chunk_length = htons(chk->send_size);
11264 	spc = SCTP_SB_LIMIT_RCV(stcb->sctp_socket);
11265 	if (spc < 0) {
11266 		spc = 0;
11267 	}
11268 	drp->bottle_bw = htonl(spc);
11269 	if (asoc->my_rwnd) {
11270 		drp->current_onq = htonl(asoc->size_on_reasm_queue +
11271 		    asoc->size_on_all_streams +
11272 		    asoc->my_rwnd_control_len +
11273 		    stcb->sctp_socket->so_rcv.sb_cc);
11274 	} else {
11275 		/*-
11276 		 * If my rwnd is 0, possibly from mbuf depletion as well as
11277 		 * space used, tell the peer there is NO space aka onq == bw
11278 		 */
11279 		drp->current_onq = htonl(spc);
11280 	}
11281 	drp->reserved = 0;
11282 	datap = drp->data;
11283 	m_copydata(m, iphlen, len, (caddr_t)datap);
11284 	TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
11285 	asoc->ctrl_queue_cnt++;
11286 }
11287 
11288 void
11289 sctp_send_cwr(struct sctp_tcb *stcb, struct sctp_nets *net, uint32_t high_tsn)
11290 {
11291 	struct sctp_association *asoc;
11292 	struct sctp_cwr_chunk *cwr;
11293 	struct sctp_tmit_chunk *chk;
11294 
11295 	asoc = &stcb->asoc;
11296 	SCTP_TCB_LOCK_ASSERT(stcb);
11297 	TAILQ_FOREACH(chk, &asoc->control_send_queue, sctp_next) {
11298 		if (chk->rec.chunk_id.id == SCTP_ECN_CWR) {
11299 			/* found a previous ECN_CWR update it if needed */
11300 			cwr = mtod(chk->data, struct sctp_cwr_chunk *);
11301 			if (compare_with_wrap(high_tsn, ntohl(cwr->tsn),
11302 			    MAX_TSN)) {
11303 				cwr->tsn = htonl(high_tsn);
11304 			}
11305 			return;
11306 		}
11307 	}
11308 	/* nope could not find one to update so we must build one */
11309 	sctp_alloc_a_chunk(stcb, chk);
11310 	if (chk == NULL) {
11311 		return;
11312 	}
11313 	chk->copy_by_ref = 0;
11314 	chk->rec.chunk_id.id = SCTP_ECN_CWR;
11315 	chk->rec.chunk_id.can_take_data = 1;
11316 	chk->asoc = &stcb->asoc;
11317 	chk->send_size = sizeof(struct sctp_cwr_chunk);
11318 	chk->data = sctp_get_mbuf_for_msg(chk->send_size, 0, M_DONTWAIT, 1, MT_HEADER);
11319 	if (chk->data == NULL) {
11320 		sctp_free_a_chunk(stcb, chk);
11321 		return;
11322 	}
11323 	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
11324 	SCTP_BUF_LEN(chk->data) = chk->send_size;
11325 	chk->sent = SCTP_DATAGRAM_UNSENT;
11326 	chk->snd_count = 0;
11327 	chk->whoTo = net;
11328 	atomic_add_int(&chk->whoTo->ref_count, 1);
11329 	cwr = mtod(chk->data, struct sctp_cwr_chunk *);
11330 	cwr->ch.chunk_type = SCTP_ECN_CWR;
11331 	cwr->ch.chunk_flags = 0;
11332 	cwr->ch.chunk_length = htons(sizeof(struct sctp_cwr_chunk));
11333 	cwr->tsn = htonl(high_tsn);
11334 	TAILQ_INSERT_TAIL(&stcb->asoc.control_send_queue, chk, sctp_next);
11335 	asoc->ctrl_queue_cnt++;
11336 }
11337 
11338 void
11339 sctp_add_stream_reset_out(struct sctp_tmit_chunk *chk,
11340     int number_entries, uint16_t * list,
11341     uint32_t seq, uint32_t resp_seq, uint32_t last_sent)
11342 {
11343 	int len, old_len, i;
11344 	struct sctp_stream_reset_out_request *req_out;
11345 	struct sctp_chunkhdr *ch;
11346 
11347 	ch = mtod(chk->data, struct sctp_chunkhdr *);
11348 
11349 
11350 	old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11351 
11352 	/* get to new offset for the param. */
11353 	req_out = (struct sctp_stream_reset_out_request *)((caddr_t)ch + len);
11354 	/* now how long will this param be? */
11355 	len = (sizeof(struct sctp_stream_reset_out_request) + (sizeof(uint16_t) * number_entries));
11356 	req_out->ph.param_type = htons(SCTP_STR_RESET_OUT_REQUEST);
11357 	req_out->ph.param_length = htons(len);
11358 	req_out->request_seq = htonl(seq);
11359 	req_out->response_seq = htonl(resp_seq);
11360 	req_out->send_reset_at_tsn = htonl(last_sent);
11361 	if (number_entries) {
11362 		for (i = 0; i < number_entries; i++) {
11363 			req_out->list_of_streams[i] = htons(list[i]);
11364 		}
11365 	}
11366 	if (SCTP_SIZE32(len) > len) {
11367 		/*-
11368 		 * Need to worry about the pad we may end up adding to the
11369 		 * end. This is easy since the struct is either aligned to 4
11370 		 * bytes or 2 bytes off.
11371 		 */
11372 		req_out->list_of_streams[number_entries] = 0;
11373 	}
11374 	/* now fix the chunk length */
11375 	ch->chunk_length = htons(len + old_len);
11376 	chk->book_size = len + old_len;
11377 	chk->book_size_scale = 0;
11378 	chk->send_size = SCTP_SIZE32(chk->book_size);
11379 	SCTP_BUF_LEN(chk->data) = chk->send_size;
11380 	return;
11381 }
11382 
11383 
11384 void
11385 sctp_add_stream_reset_in(struct sctp_tmit_chunk *chk,
11386     int number_entries, uint16_t * list,
11387     uint32_t seq)
11388 {
11389 	int len, old_len, i;
11390 	struct sctp_stream_reset_in_request *req_in;
11391 	struct sctp_chunkhdr *ch;
11392 
11393 	ch = mtod(chk->data, struct sctp_chunkhdr *);
11394 
11395 
11396 	old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11397 
11398 	/* get to new offset for the param. */
11399 	req_in = (struct sctp_stream_reset_in_request *)((caddr_t)ch + len);
11400 	/* now how long will this param be? */
11401 	len = (sizeof(struct sctp_stream_reset_in_request) + (sizeof(uint16_t) * number_entries));
11402 	req_in->ph.param_type = htons(SCTP_STR_RESET_IN_REQUEST);
11403 	req_in->ph.param_length = htons(len);
11404 	req_in->request_seq = htonl(seq);
11405 	if (number_entries) {
11406 		for (i = 0; i < number_entries; i++) {
11407 			req_in->list_of_streams[i] = htons(list[i]);
11408 		}
11409 	}
11410 	if (SCTP_SIZE32(len) > len) {
11411 		/*-
11412 		 * Need to worry about the pad we may end up adding to the
11413 		 * end. This is easy since the struct is either aligned to 4
11414 		 * bytes or 2 bytes off.
11415 		 */
11416 		req_in->list_of_streams[number_entries] = 0;
11417 	}
11418 	/* now fix the chunk length */
11419 	ch->chunk_length = htons(len + old_len);
11420 	chk->book_size = len + old_len;
11421 	chk->book_size_scale = 0;
11422 	chk->send_size = SCTP_SIZE32(chk->book_size);
11423 	SCTP_BUF_LEN(chk->data) = chk->send_size;
11424 	return;
11425 }
11426 
11427 
11428 void
11429 sctp_add_stream_reset_tsn(struct sctp_tmit_chunk *chk,
11430     uint32_t seq)
11431 {
11432 	int len, old_len;
11433 	struct sctp_stream_reset_tsn_request *req_tsn;
11434 	struct sctp_chunkhdr *ch;
11435 
11436 	ch = mtod(chk->data, struct sctp_chunkhdr *);
11437 
11438 
11439 	old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11440 
11441 	/* get to new offset for the param. */
11442 	req_tsn = (struct sctp_stream_reset_tsn_request *)((caddr_t)ch + len);
11443 	/* now how long will this param be? */
11444 	len = sizeof(struct sctp_stream_reset_tsn_request);
11445 	req_tsn->ph.param_type = htons(SCTP_STR_RESET_TSN_REQUEST);
11446 	req_tsn->ph.param_length = htons(len);
11447 	req_tsn->request_seq = htonl(seq);
11448 
11449 	/* now fix the chunk length */
11450 	ch->chunk_length = htons(len + old_len);
11451 	chk->send_size = len + old_len;
11452 	chk->book_size = SCTP_SIZE32(chk->send_size);
11453 	chk->book_size_scale = 0;
11454 	SCTP_BUF_LEN(chk->data) = SCTP_SIZE32(chk->send_size);
11455 	return;
11456 }
11457 
11458 void
11459 sctp_add_stream_reset_result(struct sctp_tmit_chunk *chk,
11460     uint32_t resp_seq, uint32_t result)
11461 {
11462 	int len, old_len;
11463 	struct sctp_stream_reset_response *resp;
11464 	struct sctp_chunkhdr *ch;
11465 
11466 	ch = mtod(chk->data, struct sctp_chunkhdr *);
11467 
11468 
11469 	old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11470 
11471 	/* get to new offset for the param. */
11472 	resp = (struct sctp_stream_reset_response *)((caddr_t)ch + len);
11473 	/* now how long will this param be? */
11474 	len = sizeof(struct sctp_stream_reset_response);
11475 	resp->ph.param_type = htons(SCTP_STR_RESET_RESPONSE);
11476 	resp->ph.param_length = htons(len);
11477 	resp->response_seq = htonl(resp_seq);
11478 	resp->result = ntohl(result);
11479 
11480 	/* now fix the chunk length */
11481 	ch->chunk_length = htons(len + old_len);
11482 	chk->book_size = len + old_len;
11483 	chk->book_size_scale = 0;
11484 	chk->send_size = SCTP_SIZE32(chk->book_size);
11485 	SCTP_BUF_LEN(chk->data) = chk->send_size;
11486 	return;
11487 
11488 }
11489 
11490 
11491 void
11492 sctp_add_stream_reset_result_tsn(struct sctp_tmit_chunk *chk,
11493     uint32_t resp_seq, uint32_t result,
11494     uint32_t send_una, uint32_t recv_next)
11495 {
11496 	int len, old_len;
11497 	struct sctp_stream_reset_response_tsn *resp;
11498 	struct sctp_chunkhdr *ch;
11499 
11500 	ch = mtod(chk->data, struct sctp_chunkhdr *);
11501 
11502 
11503 	old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11504 
11505 	/* get to new offset for the param. */
11506 	resp = (struct sctp_stream_reset_response_tsn *)((caddr_t)ch + len);
11507 	/* now how long will this param be? */
11508 	len = sizeof(struct sctp_stream_reset_response_tsn);
11509 	resp->ph.param_type = htons(SCTP_STR_RESET_RESPONSE);
11510 	resp->ph.param_length = htons(len);
11511 	resp->response_seq = htonl(resp_seq);
11512 	resp->result = htonl(result);
11513 	resp->senders_next_tsn = htonl(send_una);
11514 	resp->receivers_next_tsn = htonl(recv_next);
11515 
11516 	/* now fix the chunk length */
11517 	ch->chunk_length = htons(len + old_len);
11518 	chk->book_size = len + old_len;
11519 	chk->send_size = SCTP_SIZE32(chk->book_size);
11520 	chk->book_size_scale = 0;
11521 	SCTP_BUF_LEN(chk->data) = chk->send_size;
11522 	return;
11523 }
11524 
11525 static void
11526 sctp_add_a_stream(struct sctp_tmit_chunk *chk,
11527     uint32_t seq,
11528     uint16_t adding)
11529 {
11530 	int len, old_len;
11531 	struct sctp_chunkhdr *ch;
11532 	struct sctp_stream_reset_add_strm *addstr;
11533 
11534 	ch = mtod(chk->data, struct sctp_chunkhdr *);
11535 	old_len = len = SCTP_SIZE32(ntohs(ch->chunk_length));
11536 
11537 	/* get to new offset for the param. */
11538 	addstr = (struct sctp_stream_reset_add_strm *)((caddr_t)ch + len);
11539 	/* now how long will this param be? */
11540 	len = sizeof(struct sctp_stream_reset_add_strm);
11541 
11542 	/* Fill it out. */
11543 	addstr->ph.param_type = htons(SCTP_STR_RESET_ADD_STREAMS);
11544 	addstr->ph.param_length = htons(len);
11545 	addstr->request_seq = htonl(seq);
11546 	addstr->number_of_streams = htons(adding);
11547 	addstr->reserved = 0;
11548 
11549 	/* now fix the chunk length */
11550 	ch->chunk_length = htons(len + old_len);
11551 	chk->send_size = len + old_len;
11552 	chk->book_size = SCTP_SIZE32(chk->send_size);
11553 	chk->book_size_scale = 0;
11554 	SCTP_BUF_LEN(chk->data) = SCTP_SIZE32(chk->send_size);
11555 	return;
11556 }
11557 
11558 int
11559 sctp_send_str_reset_req(struct sctp_tcb *stcb,
11560     int number_entries, uint16_t * list,
11561     uint8_t send_out_req,
11562     uint32_t resp_seq,
11563     uint8_t send_in_req,
11564     uint8_t send_tsn_req,
11565     uint8_t add_stream,
11566     uint16_t adding
11567 )
11568 {
11569 
11570 	struct sctp_association *asoc;
11571 	struct sctp_tmit_chunk *chk;
11572 	struct sctp_chunkhdr *ch;
11573 	uint32_t seq;
11574 
11575 	asoc = &stcb->asoc;
11576 	if (asoc->stream_reset_outstanding) {
11577 		/*-
11578 		 * Already one pending, must get ACK back to clear the flag.
11579 		 */
11580 		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EBUSY);
11581 		return (EBUSY);
11582 	}
11583 	if ((send_out_req == 0) && (send_in_req == 0) && (send_tsn_req == 0) &&
11584 	    (add_stream == 0)) {
11585 		/* nothing to do */
11586 		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EINVAL);
11587 		return (EINVAL);
11588 	}
11589 	if (send_tsn_req && (send_out_req || send_in_req)) {
11590 		/* error, can't do that */
11591 		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, EINVAL);
11592 		return (EINVAL);
11593 	}
11594 	sctp_alloc_a_chunk(stcb, chk);
11595 	if (chk == NULL) {
11596 		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
11597 		return (ENOMEM);
11598 	}
11599 	chk->copy_by_ref = 0;
11600 	chk->rec.chunk_id.id = SCTP_STREAM_RESET;
11601 	chk->rec.chunk_id.can_take_data = 0;
11602 	chk->asoc = &stcb->asoc;
11603 	chk->book_size = sizeof(struct sctp_chunkhdr);
11604 	chk->send_size = SCTP_SIZE32(chk->book_size);
11605 	chk->book_size_scale = 0;
11606 
11607 	chk->data = sctp_get_mbuf_for_msg(MCLBYTES, 0, M_DONTWAIT, 1, MT_DATA);
11608 	if (chk->data == NULL) {
11609 		sctp_free_a_chunk(stcb, chk);
11610 		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
11611 		return (ENOMEM);
11612 	}
11613 	SCTP_BUF_RESV_UF(chk->data, SCTP_MIN_OVERHEAD);
11614 
11615 	/* setup chunk parameters */
11616 	chk->sent = SCTP_DATAGRAM_UNSENT;
11617 	chk->snd_count = 0;
11618 	chk->whoTo = asoc->primary_destination;
11619 	atomic_add_int(&chk->whoTo->ref_count, 1);
11620 
11621 	ch = mtod(chk->data, struct sctp_chunkhdr *);
11622 	ch->chunk_type = SCTP_STREAM_RESET;
11623 	ch->chunk_flags = 0;
11624 	ch->chunk_length = htons(chk->book_size);
11625 	SCTP_BUF_LEN(chk->data) = chk->send_size;
11626 
11627 	seq = stcb->asoc.str_reset_seq_out;
11628 	if (send_out_req) {
11629 		sctp_add_stream_reset_out(chk, number_entries, list,
11630 		    seq, resp_seq, (stcb->asoc.sending_seq - 1));
11631 		asoc->stream_reset_out_is_outstanding = 1;
11632 		seq++;
11633 		asoc->stream_reset_outstanding++;
11634 	}
11635 	if (add_stream) {
11636 		sctp_add_a_stream(chk, seq, adding);
11637 		seq++;
11638 		asoc->stream_reset_outstanding++;
11639 	}
11640 	if (send_in_req) {
11641 		sctp_add_stream_reset_in(chk, number_entries, list, seq);
11642 		asoc->stream_reset_outstanding++;
11643 	}
11644 	if (send_tsn_req) {
11645 		sctp_add_stream_reset_tsn(chk, seq);
11646 		asoc->stream_reset_outstanding++;
11647 	}
11648 	asoc->str_reset = chk;
11649 
11650 	/* insert the chunk for sending */
11651 	TAILQ_INSERT_TAIL(&asoc->control_send_queue,
11652 	    chk,
11653 	    sctp_next);
11654 	asoc->ctrl_queue_cnt++;
11655 	sctp_timer_start(SCTP_TIMER_TYPE_STRRESET, stcb->sctp_ep, stcb, chk->whoTo);
11656 	return (0);
11657 }
11658 
11659 void
11660 sctp_send_abort(struct mbuf *m, int iphlen, struct sctphdr *sh, uint32_t vtag,
11661     struct mbuf *err_cause, uint32_t vrf_id, uint16_t port)
11662 {
11663 	/*-
11664 	 * Formulate the abort message, and send it back down.
11665 	 */
11666 	struct mbuf *o_pak;
11667 	struct mbuf *mout;
11668 	struct sctp_abort_msg *abm;
11669 	struct ip *iph, *iph_out;
11670 	struct udphdr *udp;
11671 
11672 #ifdef INET6
11673 	struct ip6_hdr *ip6, *ip6_out;
11674 
11675 #endif
11676 	int iphlen_out, len;
11677 
11678 	/* don't respond to ABORT with ABORT */
11679 	if (sctp_is_there_an_abort_here(m, iphlen, &vtag)) {
11680 		if (err_cause)
11681 			sctp_m_freem(err_cause);
11682 		return;
11683 	}
11684 	iph = mtod(m, struct ip *);
11685 	switch (iph->ip_v) {
11686 	case IPVERSION:
11687 		len = (sizeof(struct ip) + sizeof(struct sctp_abort_msg));
11688 		break;
11689 #ifdef INET6
11690 	case IPV6_VERSION >> 4:
11691 		len = (sizeof(struct ip6_hdr) + sizeof(struct sctp_abort_msg));
11692 		break;
11693 #endif
11694 	default:
11695 		if (err_cause) {
11696 			sctp_m_freem(err_cause);
11697 		}
11698 		return;
11699 	}
11700 	if (port) {
11701 		len += sizeof(struct udphdr);
11702 	}
11703 	mout = sctp_get_mbuf_for_msg(len + max_linkhdr, 1, M_DONTWAIT, 1, MT_DATA);
11704 	if (mout == NULL) {
11705 		if (err_cause) {
11706 			sctp_m_freem(err_cause);
11707 		}
11708 		return;
11709 	}
11710 	SCTP_BUF_RESV_UF(mout, max_linkhdr);
11711 	SCTP_BUF_LEN(mout) = len;
11712 	SCTP_BUF_NEXT(mout) = err_cause;
11713 	iph_out = NULL;
11714 #ifdef INET6
11715 	ip6_out = NULL;
11716 #endif
11717 	switch (iph->ip_v) {
11718 	case IPVERSION:
11719 		iph_out = mtod(mout, struct ip *);
11720 
11721 		/* Fill in the IP header for the ABORT */
11722 		iph_out->ip_v = IPVERSION;
11723 		iph_out->ip_hl = (sizeof(struct ip) / 4);
11724 		iph_out->ip_tos = (u_char)0;
11725 		iph_out->ip_id = 0;
11726 		iph_out->ip_off = 0;
11727 		iph_out->ip_ttl = MAXTTL;
11728 		if (port) {
11729 			iph_out->ip_p = IPPROTO_UDP;
11730 		} else {
11731 			iph_out->ip_p = IPPROTO_SCTP;
11732 		}
11733 		iph_out->ip_src.s_addr = iph->ip_dst.s_addr;
11734 		iph_out->ip_dst.s_addr = iph->ip_src.s_addr;
11735 		/* let IP layer calculate this */
11736 		iph_out->ip_sum = 0;
11737 
11738 		iphlen_out = sizeof(*iph_out);
11739 		abm = (struct sctp_abort_msg *)((caddr_t)iph_out + iphlen_out);
11740 		break;
11741 #ifdef INET6
11742 	case IPV6_VERSION >> 4:
11743 		ip6 = (struct ip6_hdr *)iph;
11744 		ip6_out = mtod(mout, struct ip6_hdr *);
11745 
11746 		/* Fill in the IP6 header for the ABORT */
11747 		ip6_out->ip6_flow = ip6->ip6_flow;
11748 		ip6_out->ip6_hlim = MODULE_GLOBAL(ip6_defhlim);
11749 		if (port) {
11750 			ip6_out->ip6_nxt = IPPROTO_UDP;
11751 		} else {
11752 			ip6_out->ip6_nxt = IPPROTO_SCTP;
11753 		}
11754 		ip6_out->ip6_src = ip6->ip6_dst;
11755 		ip6_out->ip6_dst = ip6->ip6_src;
11756 
11757 		iphlen_out = sizeof(*ip6_out);
11758 		abm = (struct sctp_abort_msg *)((caddr_t)ip6_out + iphlen_out);
11759 		break;
11760 #endif				/* INET6 */
11761 	default:
11762 		/* Currently not supported */
11763 		sctp_m_freem(mout);
11764 		return;
11765 	}
11766 
11767 	udp = (struct udphdr *)abm;
11768 	if (port) {
11769 		udp->uh_sport = htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port));
11770 		udp->uh_dport = port;
11771 		/* set udp->uh_ulen later */
11772 		udp->uh_sum = 0;
11773 		iphlen_out += sizeof(struct udphdr);
11774 		abm = (struct sctp_abort_msg *)((caddr_t)abm + sizeof(struct udphdr));
11775 	}
11776 	abm->sh.src_port = sh->dest_port;
11777 	abm->sh.dest_port = sh->src_port;
11778 	abm->sh.checksum = 0;
11779 	if (vtag == 0) {
11780 		abm->sh.v_tag = sh->v_tag;
11781 		abm->msg.ch.chunk_flags = SCTP_HAD_NO_TCB;
11782 	} else {
11783 		abm->sh.v_tag = htonl(vtag);
11784 		abm->msg.ch.chunk_flags = 0;
11785 	}
11786 	abm->msg.ch.chunk_type = SCTP_ABORT_ASSOCIATION;
11787 
11788 	if (err_cause) {
11789 		struct mbuf *m_tmp = err_cause;
11790 		int err_len = 0;
11791 
11792 		/* get length of the err_cause chain */
11793 		while (m_tmp != NULL) {
11794 			err_len += SCTP_BUF_LEN(m_tmp);
11795 			m_tmp = SCTP_BUF_NEXT(m_tmp);
11796 		}
11797 		len = SCTP_BUF_LEN(mout) + err_len;
11798 		if (err_len % 4) {
11799 			/* need pad at end of chunk */
11800 			uint32_t cpthis = 0;
11801 			int padlen;
11802 
11803 			padlen = 4 - (len % 4);
11804 			m_copyback(mout, len, padlen, (caddr_t)&cpthis);
11805 			len += padlen;
11806 		}
11807 		abm->msg.ch.chunk_length = htons(sizeof(abm->msg.ch) + err_len);
11808 	} else {
11809 		len = SCTP_BUF_LEN(mout);
11810 		abm->msg.ch.chunk_length = htons(sizeof(abm->msg.ch));
11811 	}
11812 
11813 	if (SCTP_GET_HEADER_FOR_OUTPUT(o_pak)) {
11814 		/* no mbuf's */
11815 		sctp_m_freem(mout);
11816 		return;
11817 	}
11818 	if (iph_out != NULL) {
11819 		sctp_route_t ro;
11820 		struct sctp_tcb *stcb = NULL;
11821 		int ret;
11822 
11823 		/* zap the stack pointer to the route */
11824 		bzero(&ro, sizeof ro);
11825 		if (port) {
11826 			udp->uh_ulen = htons(len - sizeof(struct ip));
11827 			udp->uh_sum = in_pseudo(iph_out->ip_src.s_addr, iph_out->ip_dst.s_addr, udp->uh_ulen + htons(IPPROTO_UDP));
11828 		}
11829 		SCTPDBG(SCTP_DEBUG_OUTPUT2, "sctp_send_abort calling ip_output:\n");
11830 		SCTPDBG_PKT(SCTP_DEBUG_OUTPUT2, iph_out, &abm->sh);
11831 		/* set IPv4 length */
11832 		iph_out->ip_len = len;
11833 		/* out it goes */
11834 #ifdef  SCTP_PACKET_LOGGING
11835 		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LAST_PACKET_TRACING)
11836 			sctp_packet_log(mout, len);
11837 #endif
11838 		SCTP_ATTACH_CHAIN(o_pak, mout, len);
11839 		if (port) {
11840 			abm->sh.checksum = sctp_calculate_cksum(mout, iphlen_out);
11841 			SCTP_STAT_INCR(sctps_sendswcrc);
11842 			SCTP_ENABLE_UDP_CSUM(o_pak);
11843 		} else {
11844 			mout->m_pkthdr.csum_flags = CSUM_SCTP;
11845 			mout->m_pkthdr.csum_data = 0;	/* FIXME MT */
11846 			SCTP_STAT_INCR(sctps_sendhwcrc);
11847 		}
11848 		SCTP_IP_OUTPUT(ret, o_pak, &ro, stcb, vrf_id);
11849 
11850 		/* Free the route if we got one back */
11851 		if (ro.ro_rt)
11852 			RTFREE(ro.ro_rt);
11853 	}
11854 #ifdef INET6
11855 	if (ip6_out != NULL) {
11856 		struct route_in6 ro;
11857 		int ret;
11858 		struct sctp_tcb *stcb = NULL;
11859 		struct ifnet *ifp = NULL;
11860 
11861 		/* zap the stack pointer to the route */
11862 		bzero(&ro, sizeof(ro));
11863 		if (port) {
11864 			udp->uh_ulen = htons(len - sizeof(struct ip6_hdr));
11865 		}
11866 		SCTPDBG(SCTP_DEBUG_OUTPUT2, "sctp_send_abort calling ip6_output:\n");
11867 		SCTPDBG_PKT(SCTP_DEBUG_OUTPUT2, (struct ip *)ip6_out, &abm->sh);
11868 		ip6_out->ip6_plen = len - sizeof(*ip6_out);
11869 #ifdef  SCTP_PACKET_LOGGING
11870 		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LAST_PACKET_TRACING)
11871 			sctp_packet_log(mout, len);
11872 #endif
11873 		abm->sh.checksum = sctp_calculate_cksum(mout, iphlen_out);
11874 		SCTP_STAT_INCR(sctps_sendswcrc);
11875 		SCTP_ATTACH_CHAIN(o_pak, mout, len);
11876 		if (port) {
11877 			if ((udp->uh_sum = in6_cksum(o_pak, IPPROTO_UDP, sizeof(struct ip6_hdr), len - sizeof(struct ip6_hdr))) == 0) {
11878 				udp->uh_sum = 0xffff;
11879 			}
11880 		}
11881 		SCTP_IP6_OUTPUT(ret, o_pak, &ro, &ifp, stcb, vrf_id);
11882 
11883 		/* Free the route if we got one back */
11884 		if (ro.ro_rt)
11885 			RTFREE(ro.ro_rt);
11886 	}
11887 #endif
11888 	SCTP_STAT_INCR(sctps_sendpackets);
11889 	SCTP_STAT_INCR_COUNTER64(sctps_outpackets);
11890 	SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
11891 }
11892 
11893 void
11894 sctp_send_operr_to(struct mbuf *m, int iphlen, struct mbuf *scm, uint32_t vtag,
11895     uint32_t vrf_id, uint16_t port)
11896 {
11897 	struct mbuf *o_pak;
11898 	struct sctphdr *sh, *sh_out;
11899 	struct sctp_chunkhdr *ch;
11900 	struct ip *iph, *iph_out;
11901 	struct udphdr *udp = NULL;
11902 	struct mbuf *mout;
11903 
11904 #ifdef INET6
11905 	struct ip6_hdr *ip6, *ip6_out;
11906 
11907 #endif
11908 	int iphlen_out, len;
11909 
11910 	iph = mtod(m, struct ip *);
11911 	sh = (struct sctphdr *)((caddr_t)iph + iphlen);
11912 	switch (iph->ip_v) {
11913 	case IPVERSION:
11914 		len = (sizeof(struct ip) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr));
11915 		break;
11916 #ifdef INET6
11917 	case IPV6_VERSION >> 4:
11918 		len = (sizeof(struct ip6_hdr) + sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr));
11919 		break;
11920 #endif
11921 	default:
11922 		if (scm) {
11923 			sctp_m_freem(scm);
11924 		}
11925 		return;
11926 	}
11927 	if (port) {
11928 		len += sizeof(struct udphdr);
11929 	}
11930 	mout = sctp_get_mbuf_for_msg(len + max_linkhdr, 1, M_DONTWAIT, 1, MT_DATA);
11931 	if (mout == NULL) {
11932 		if (scm) {
11933 			sctp_m_freem(scm);
11934 		}
11935 		return;
11936 	}
11937 	SCTP_BUF_RESV_UF(mout, max_linkhdr);
11938 	SCTP_BUF_LEN(mout) = len;
11939 	SCTP_BUF_NEXT(mout) = scm;
11940 	iph_out = NULL;
11941 #ifdef INET6
11942 	ip6_out = NULL;
11943 #endif
11944 	switch (iph->ip_v) {
11945 	case IPVERSION:
11946 		iph_out = mtod(mout, struct ip *);
11947 
11948 		/* Fill in the IP header for the ABORT */
11949 		iph_out->ip_v = IPVERSION;
11950 		iph_out->ip_hl = (sizeof(struct ip) / 4);
11951 		iph_out->ip_tos = (u_char)0;
11952 		iph_out->ip_id = 0;
11953 		iph_out->ip_off = 0;
11954 		iph_out->ip_ttl = MAXTTL;
11955 		if (port) {
11956 			iph_out->ip_p = IPPROTO_UDP;
11957 		} else {
11958 			iph_out->ip_p = IPPROTO_SCTP;
11959 		}
11960 		iph_out->ip_src.s_addr = iph->ip_dst.s_addr;
11961 		iph_out->ip_dst.s_addr = iph->ip_src.s_addr;
11962 		/* let IP layer calculate this */
11963 		iph_out->ip_sum = 0;
11964 
11965 		iphlen_out = sizeof(struct ip);
11966 		sh_out = (struct sctphdr *)((caddr_t)iph_out + iphlen_out);
11967 		break;
11968 #ifdef INET6
11969 	case IPV6_VERSION >> 4:
11970 		ip6 = (struct ip6_hdr *)iph;
11971 		ip6_out = mtod(mout, struct ip6_hdr *);
11972 
11973 		/* Fill in the IP6 header for the ABORT */
11974 		ip6_out->ip6_flow = ip6->ip6_flow;
11975 		ip6_out->ip6_hlim = MODULE_GLOBAL(ip6_defhlim);
11976 		if (port) {
11977 			ip6_out->ip6_nxt = IPPROTO_UDP;
11978 		} else {
11979 			ip6_out->ip6_nxt = IPPROTO_SCTP;
11980 		}
11981 		ip6_out->ip6_src = ip6->ip6_dst;
11982 		ip6_out->ip6_dst = ip6->ip6_src;
11983 
11984 		iphlen_out = sizeof(struct ip6_hdr);
11985 		sh_out = (struct sctphdr *)((caddr_t)ip6_out + iphlen_out);
11986 		break;
11987 #endif				/* INET6 */
11988 	default:
11989 		/* Currently not supported */
11990 		sctp_m_freem(mout);
11991 		return;
11992 	}
11993 
11994 	udp = (struct udphdr *)sh_out;
11995 	if (port) {
11996 		udp->uh_sport = htons(SCTP_BASE_SYSCTL(sctp_udp_tunneling_port));
11997 		udp->uh_dport = port;
11998 		/* set udp->uh_ulen later */
11999 		udp->uh_sum = 0;
12000 		iphlen_out += sizeof(struct udphdr);
12001 		sh_out = (struct sctphdr *)((caddr_t)udp + sizeof(struct udphdr));
12002 	}
12003 	sh_out->src_port = sh->dest_port;
12004 	sh_out->dest_port = sh->src_port;
12005 	sh_out->v_tag = vtag;
12006 	sh_out->checksum = 0;
12007 
12008 	ch = (struct sctp_chunkhdr *)((caddr_t)sh_out + sizeof(struct sctphdr));
12009 	ch->chunk_type = SCTP_OPERATION_ERROR;
12010 	ch->chunk_flags = 0;
12011 
12012 	if (scm) {
12013 		struct mbuf *m_tmp = scm;
12014 		int cause_len = 0;
12015 
12016 		/* get length of the err_cause chain */
12017 		while (m_tmp != NULL) {
12018 			cause_len += SCTP_BUF_LEN(m_tmp);
12019 			m_tmp = SCTP_BUF_NEXT(m_tmp);
12020 		}
12021 		len = SCTP_BUF_LEN(mout) + cause_len;
12022 		if (cause_len % 4) {
12023 			/* need pad at end of chunk */
12024 			uint32_t cpthis = 0;
12025 			int padlen;
12026 
12027 			padlen = 4 - (len % 4);
12028 			m_copyback(mout, len, padlen, (caddr_t)&cpthis);
12029 			len += padlen;
12030 		}
12031 		ch->chunk_length = htons(sizeof(struct sctp_chunkhdr) + cause_len);
12032 	} else {
12033 		len = SCTP_BUF_LEN(mout);
12034 		ch->chunk_length = htons(sizeof(struct sctp_chunkhdr));
12035 	}
12036 
12037 	if (SCTP_GET_HEADER_FOR_OUTPUT(o_pak)) {
12038 		/* no mbuf's */
12039 		sctp_m_freem(mout);
12040 		return;
12041 	}
12042 	if (iph_out != NULL) {
12043 		sctp_route_t ro;
12044 		struct sctp_tcb *stcb = NULL;
12045 		int ret;
12046 
12047 		/* zap the stack pointer to the route */
12048 		bzero(&ro, sizeof ro);
12049 		if (port) {
12050 			udp->uh_ulen = htons(len - sizeof(struct ip));
12051 			udp->uh_sum = in_pseudo(iph_out->ip_src.s_addr, iph_out->ip_dst.s_addr, udp->uh_ulen + htons(IPPROTO_UDP));
12052 		}
12053 		/* set IPv4 length */
12054 		iph_out->ip_len = len;
12055 		/* out it goes */
12056 #ifdef  SCTP_PACKET_LOGGING
12057 		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LAST_PACKET_TRACING)
12058 			sctp_packet_log(mout, len);
12059 #endif
12060 		SCTP_ATTACH_CHAIN(o_pak, mout, len);
12061 		if (port) {
12062 			sh_out->checksum = sctp_calculate_cksum(mout, iphlen_out);
12063 			SCTP_STAT_INCR(sctps_sendswcrc);
12064 			SCTP_ENABLE_UDP_CSUM(o_pak);
12065 		} else {
12066 			mout->m_pkthdr.csum_flags = CSUM_SCTP;
12067 			mout->m_pkthdr.csum_data = 0;	/* FIXME MT */
12068 			SCTP_STAT_INCR(sctps_sendhwcrc);
12069 		}
12070 		SCTP_IP_OUTPUT(ret, o_pak, &ro, stcb, vrf_id);
12071 
12072 		/* Free the route if we got one back */
12073 		if (ro.ro_rt)
12074 			RTFREE(ro.ro_rt);
12075 	}
12076 #ifdef INET6
12077 	if (ip6_out != NULL) {
12078 		struct route_in6 ro;
12079 		int ret;
12080 		struct sctp_tcb *stcb = NULL;
12081 		struct ifnet *ifp = NULL;
12082 
12083 		/* zap the stack pointer to the route */
12084 		bzero(&ro, sizeof(ro));
12085 		if (port) {
12086 			udp->uh_ulen = htons(len - sizeof(struct ip6_hdr));
12087 		}
12088 		ip6_out->ip6_plen = len - sizeof(*ip6_out);
12089 #ifdef  SCTP_PACKET_LOGGING
12090 		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LAST_PACKET_TRACING)
12091 			sctp_packet_log(mout, len);
12092 #endif
12093 		sh_out->checksum = sctp_calculate_cksum(mout, iphlen_out);
12094 		SCTP_STAT_INCR(sctps_sendswcrc);
12095 		SCTP_ATTACH_CHAIN(o_pak, mout, len);
12096 		if (port) {
12097 			if ((udp->uh_sum = in6_cksum(o_pak, IPPROTO_UDP, sizeof(struct ip6_hdr), len - sizeof(struct ip6_hdr))) == 0) {
12098 				udp->uh_sum = 0xffff;
12099 			}
12100 		}
12101 		SCTP_IP6_OUTPUT(ret, o_pak, &ro, &ifp, stcb, vrf_id);
12102 
12103 		/* Free the route if we got one back */
12104 		if (ro.ro_rt)
12105 			RTFREE(ro.ro_rt);
12106 	}
12107 #endif
12108 	SCTP_STAT_INCR(sctps_sendpackets);
12109 	SCTP_STAT_INCR_COUNTER64(sctps_outpackets);
12110 	SCTP_STAT_INCR_COUNTER64(sctps_outcontrolchunks);
12111 }
12112 
12113 static struct mbuf *
12114 sctp_copy_resume(struct sctp_stream_queue_pending *sp,
12115     struct uio *uio,
12116     struct sctp_sndrcvinfo *srcv,
12117     int max_send_len,
12118     int user_marks_eor,
12119     int *error,
12120     uint32_t * sndout,
12121     struct mbuf **new_tail)
12122 {
12123 	struct mbuf *m;
12124 
12125 	m = m_uiotombuf(uio, M_WAITOK, max_send_len, 0,
12126 	    (M_PKTHDR | (user_marks_eor ? M_EOR : 0)));
12127 	if (m == NULL) {
12128 		SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
12129 		*error = ENOMEM;
12130 	} else {
12131 		*sndout = m_length(m, NULL);
12132 		*new_tail = m_last(m);
12133 	}
12134 	return (m);
12135 }
12136 
12137 static int
12138 sctp_copy_one(struct sctp_stream_queue_pending *sp,
12139     struct uio *uio,
12140     int resv_upfront)
12141 {
12142 	int left;
12143 
12144 	left = sp->length;
12145 	sp->data = m_uiotombuf(uio, M_WAITOK, sp->length,
12146 	    resv_upfront, 0);
12147 	if (sp->data == NULL) {
12148 		SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
12149 		return (ENOMEM);
12150 	}
12151 	sp->tail_mbuf = m_last(sp->data);
12152 	return (0);
12153 }
12154 
12155 
12156 
12157 static struct sctp_stream_queue_pending *
12158 sctp_copy_it_in(struct sctp_tcb *stcb,
12159     struct sctp_association *asoc,
12160     struct sctp_sndrcvinfo *srcv,
12161     struct uio *uio,
12162     struct sctp_nets *net,
12163     int max_send_len,
12164     int user_marks_eor,
12165     int *error,
12166     int non_blocking)
12167 {
12168 	/*-
12169 	 * This routine must be very careful in its work. Protocol
12170 	 * processing is up and running so care must be taken to spl...()
12171 	 * when you need to do something that may effect the stcb/asoc. The
12172 	 * sb is locked however. When data is copied the protocol processing
12173 	 * should be enabled since this is a slower operation...
12174 	 */
12175 	struct sctp_stream_queue_pending *sp = NULL;
12176 	int resv_in_first;
12177 
12178 	*error = 0;
12179 	/* Now can we send this? */
12180 	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
12181 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
12182 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
12183 	    (asoc->state & SCTP_STATE_SHUTDOWN_PENDING)) {
12184 		/* got data while shutting down */
12185 		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ECONNRESET);
12186 		*error = ECONNRESET;
12187 		goto out_now;
12188 	}
12189 	sctp_alloc_a_strmoq(stcb, sp);
12190 	if (sp == NULL) {
12191 		SCTP_LTRACE_ERR_RET(NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
12192 		*error = ENOMEM;
12193 		goto out_now;
12194 	}
12195 	sp->act_flags = 0;
12196 	sp->sender_all_done = 0;
12197 	sp->sinfo_flags = srcv->sinfo_flags;
12198 	sp->timetolive = srcv->sinfo_timetolive;
12199 	sp->ppid = srcv->sinfo_ppid;
12200 	sp->context = srcv->sinfo_context;
12201 	sp->strseq = 0;
12202 	(void)SCTP_GETTIME_TIMEVAL(&sp->ts);
12203 
12204 	sp->stream = srcv->sinfo_stream;
12205 	sp->length = min(uio->uio_resid, max_send_len);
12206 	if ((sp->length == (uint32_t) uio->uio_resid) &&
12207 	    ((user_marks_eor == 0) ||
12208 	    (srcv->sinfo_flags & SCTP_EOF) ||
12209 	    (user_marks_eor && (srcv->sinfo_flags & SCTP_EOR)))) {
12210 		sp->msg_is_complete = 1;
12211 	} else {
12212 		sp->msg_is_complete = 0;
12213 	}
12214 	sp->sender_all_done = 0;
12215 	sp->some_taken = 0;
12216 	sp->put_last_out = 0;
12217 	resv_in_first = sizeof(struct sctp_data_chunk);
12218 	sp->data = sp->tail_mbuf = NULL;
12219 	if (sp->length == 0) {
12220 		*error = 0;
12221 		goto skip_copy;
12222 	}
12223 	sp->auth_keyid = stcb->asoc.authinfo.active_keyid;
12224 	if (sctp_auth_is_required_chunk(SCTP_DATA, stcb->asoc.peer_auth_chunks)) {
12225 		sctp_auth_key_acquire(stcb, stcb->asoc.authinfo.active_keyid);
12226 		sp->holds_key_ref = 1;
12227 	}
12228 	*error = sctp_copy_one(sp, uio, resv_in_first);
12229 skip_copy:
12230 	if (*error) {
12231 		sctp_free_a_strmoq(stcb, sp);
12232 		sp = NULL;
12233 	} else {
12234 		if (sp->sinfo_flags & SCTP_ADDR_OVER) {
12235 			sp->net = net;
12236 		} else {
12237 			sp->net = asoc->primary_destination;
12238 		}
12239 		atomic_add_int(&sp->net->ref_count, 1);
12240 		sctp_set_prsctp_policy(sp);
12241 	}
12242 out_now:
12243 	return (sp);
12244 }
12245 
12246 
12247 int
12248 sctp_sosend(struct socket *so,
12249     struct sockaddr *addr,
12250     struct uio *uio,
12251     struct mbuf *top,
12252     struct mbuf *control,
12253     int flags,
12254     struct thread *p
12255 )
12256 {
12257 	struct sctp_inpcb *inp;
12258 	int error, use_rcvinfo = 0;
12259 	struct sctp_sndrcvinfo srcv;
12260 	struct sockaddr *addr_to_use;
12261 
12262 #ifdef INET6
12263 	struct sockaddr_in sin;
12264 
12265 #endif
12266 
12267 	inp = (struct sctp_inpcb *)so->so_pcb;
12268 	if (control) {
12269 		/* process cmsg snd/rcv info (maybe a assoc-id) */
12270 		if (sctp_find_cmsg(SCTP_SNDRCV, (void *)&srcv, control,
12271 		    sizeof(srcv))) {
12272 			/* got one */
12273 			use_rcvinfo = 1;
12274 		}
12275 	}
12276 	addr_to_use = addr;
12277 #if defined(INET6)  && !defined(__Userspace__)	/* TODO port in6_sin6_2_sin */
12278 	if ((addr) && (addr->sa_family == AF_INET6)) {
12279 		struct sockaddr_in6 *sin6;
12280 
12281 		sin6 = (struct sockaddr_in6 *)addr;
12282 		if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
12283 			in6_sin6_2_sin(&sin, sin6);
12284 			addr_to_use = (struct sockaddr *)&sin;
12285 		}
12286 	}
12287 #endif
12288 	error = sctp_lower_sosend(so, addr_to_use, uio, top,
12289 	    control,
12290 	    flags,
12291 	    use_rcvinfo, &srcv
12292 	    ,p
12293 	    );
12294 	return (error);
12295 }
12296 
12297 
12298 int
12299 sctp_lower_sosend(struct socket *so,
12300     struct sockaddr *addr,
12301     struct uio *uio,
12302     struct mbuf *i_pak,
12303     struct mbuf *control,
12304     int flags,
12305     int use_rcvinfo,
12306     struct sctp_sndrcvinfo *srcv
12307     ,
12308     struct thread *p
12309 )
12310 {
12311 	unsigned int sndlen = 0, max_len;
12312 	int error, len;
12313 	struct mbuf *top = NULL;
12314 	int queue_only = 0, queue_only_for_init = 0;
12315 	int free_cnt_applied = 0;
12316 	int un_sent = 0;
12317 	int now_filled = 0;
12318 	unsigned int inqueue_bytes = 0;
12319 	struct sctp_block_entry be;
12320 	struct sctp_inpcb *inp;
12321 	struct sctp_tcb *stcb = NULL;
12322 	struct timeval now;
12323 	struct sctp_nets *net;
12324 	struct sctp_association *asoc;
12325 	struct sctp_inpcb *t_inp;
12326 	int user_marks_eor;
12327 	int create_lock_applied = 0;
12328 	int nagle_applies = 0;
12329 	int some_on_control = 0;
12330 	int got_all_of_the_send = 0;
12331 	int hold_tcblock = 0;
12332 	int non_blocking = 0;
12333 	int temp_flags = 0;
12334 	uint32_t local_add_more, local_soresv = 0;
12335 
12336 	error = 0;
12337 	net = NULL;
12338 	stcb = NULL;
12339 	asoc = NULL;
12340 
12341 	t_inp = inp = (struct sctp_inpcb *)so->so_pcb;
12342 	if (inp == NULL) {
12343 		SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12344 		error = EINVAL;
12345 		if (i_pak) {
12346 			SCTP_RELEASE_PKT(i_pak);
12347 		}
12348 		return (error);
12349 	}
12350 	if ((uio == NULL) && (i_pak == NULL)) {
12351 		SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12352 		return (EINVAL);
12353 	}
12354 	user_marks_eor = sctp_is_feature_on(inp, SCTP_PCB_FLAGS_EXPLICIT_EOR);
12355 	atomic_add_int(&inp->total_sends, 1);
12356 	if (uio) {
12357 		if (uio->uio_resid < 0) {
12358 			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12359 			return (EINVAL);
12360 		}
12361 		sndlen = uio->uio_resid;
12362 	} else {
12363 		top = SCTP_HEADER_TO_CHAIN(i_pak);
12364 		sndlen = SCTP_HEADER_LEN(i_pak);
12365 	}
12366 	SCTPDBG(SCTP_DEBUG_OUTPUT1, "Send called addr:%p send length %d\n",
12367 	    addr,
12368 	    sndlen);
12369 	/*-
12370 	 * Pre-screen address, if one is given the sin-len
12371 	 * must be set correctly!
12372 	 */
12373 	if (addr) {
12374 		if ((addr->sa_family == AF_INET) &&
12375 		    (addr->sa_len != sizeof(struct sockaddr_in))) {
12376 			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12377 			error = EINVAL;
12378 			goto out_unlocked;
12379 		} else if ((addr->sa_family == AF_INET6) &&
12380 		    (addr->sa_len != sizeof(struct sockaddr_in6))) {
12381 			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12382 			error = EINVAL;
12383 			goto out_unlocked;
12384 		}
12385 	}
12386 	hold_tcblock = 0;
12387 
12388 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) &&
12389 	    (inp->sctp_socket->so_qlimit)) {
12390 		/* The listener can NOT send */
12391 		SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, ENOTCONN);
12392 		error = ENOTCONN;
12393 		goto out_unlocked;
12394 	}
12395 	if ((use_rcvinfo) && srcv) {
12396 		if (INVALID_SINFO_FLAG(srcv->sinfo_flags) ||
12397 		    PR_SCTP_INVALID_POLICY(srcv->sinfo_flags)) {
12398 			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12399 			error = EINVAL;
12400 			goto out_unlocked;
12401 		}
12402 		if (srcv->sinfo_flags)
12403 			SCTP_STAT_INCR(sctps_sends_with_flags);
12404 
12405 		if (srcv->sinfo_flags & SCTP_SENDALL) {
12406 			/* its a sendall */
12407 			error = sctp_sendall(inp, uio, top, srcv);
12408 			top = NULL;
12409 			goto out_unlocked;
12410 		}
12411 	}
12412 	/* now we must find the assoc */
12413 	if ((inp->sctp_flags & SCTP_PCB_FLAGS_CONNECTED) ||
12414 	    (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
12415 		SCTP_INP_RLOCK(inp);
12416 		stcb = LIST_FIRST(&inp->sctp_asoc_list);
12417 		if (stcb == NULL) {
12418 			SCTP_INP_RUNLOCK(inp);
12419 			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, ENOTCONN);
12420 			error = ENOTCONN;
12421 			goto out_unlocked;
12422 		}
12423 		SCTP_TCB_LOCK(stcb);
12424 		hold_tcblock = 1;
12425 		SCTP_INP_RUNLOCK(inp);
12426 		if (addr) {
12427 			/* Must locate the net structure if addr given */
12428 			net = sctp_findnet(stcb, addr);
12429 			if (net) {
12430 				/* validate port was 0 or correct */
12431 				struct sockaddr_in *sin;
12432 
12433 				sin = (struct sockaddr_in *)addr;
12434 				if ((sin->sin_port != 0) &&
12435 				    (sin->sin_port != stcb->rport)) {
12436 					net = NULL;
12437 				}
12438 			}
12439 			temp_flags |= SCTP_ADDR_OVER;
12440 		} else
12441 			net = stcb->asoc.primary_destination;
12442 		if (addr && (net == NULL)) {
12443 			/* Could not find address, was it legal */
12444 			if (addr->sa_family == AF_INET) {
12445 				struct sockaddr_in *sin;
12446 
12447 				sin = (struct sockaddr_in *)addr;
12448 				if (sin->sin_addr.s_addr == 0) {
12449 					if ((sin->sin_port == 0) ||
12450 					    (sin->sin_port == stcb->rport)) {
12451 						net = stcb->asoc.primary_destination;
12452 					}
12453 				}
12454 			} else {
12455 				struct sockaddr_in6 *sin6;
12456 
12457 				sin6 = (struct sockaddr_in6 *)addr;
12458 				if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
12459 					if ((sin6->sin6_port == 0) ||
12460 					    (sin6->sin6_port == stcb->rport)) {
12461 						net = stcb->asoc.primary_destination;
12462 					}
12463 				}
12464 			}
12465 		}
12466 		if (net == NULL) {
12467 			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12468 			error = EINVAL;
12469 			goto out_unlocked;
12470 		}
12471 	} else if (use_rcvinfo && srcv && srcv->sinfo_assoc_id) {
12472 		stcb = sctp_findassociation_ep_asocid(inp, srcv->sinfo_assoc_id, 0);
12473 		if (stcb) {
12474 			if (addr)
12475 				/*
12476 				 * Must locate the net structure if addr
12477 				 * given
12478 				 */
12479 				net = sctp_findnet(stcb, addr);
12480 			else
12481 				net = stcb->asoc.primary_destination;
12482 			if ((srcv->sinfo_flags & SCTP_ADDR_OVER) &&
12483 			    ((net == NULL) || (addr == NULL))) {
12484 				struct sockaddr_in *sin;
12485 
12486 				if (addr == NULL) {
12487 					SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12488 					error = EINVAL;
12489 					goto out_unlocked;
12490 				}
12491 				sin = (struct sockaddr_in *)addr;
12492 				/* Validate port is 0 or correct */
12493 				if ((sin->sin_port != 0) &&
12494 				    (sin->sin_port != stcb->rport)) {
12495 					net = NULL;
12496 				}
12497 			}
12498 		}
12499 		hold_tcblock = 0;
12500 	} else if (addr) {
12501 		/*-
12502 		 * Since we did not use findep we must
12503 		 * increment it, and if we don't find a tcb
12504 		 * decrement it.
12505 		 */
12506 		SCTP_INP_WLOCK(inp);
12507 		SCTP_INP_INCR_REF(inp);
12508 		SCTP_INP_WUNLOCK(inp);
12509 		stcb = sctp_findassociation_ep_addr(&t_inp, addr, &net, NULL, NULL);
12510 		if (stcb == NULL) {
12511 			SCTP_INP_WLOCK(inp);
12512 			SCTP_INP_DECR_REF(inp);
12513 			SCTP_INP_WUNLOCK(inp);
12514 		} else {
12515 			hold_tcblock = 1;
12516 		}
12517 	}
12518 	if ((stcb == NULL) && (addr)) {
12519 		/* Possible implicit send? */
12520 		SCTP_ASOC_CREATE_LOCK(inp);
12521 		create_lock_applied = 1;
12522 		if ((inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
12523 		    (inp->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE)) {
12524 			/* Should I really unlock ? */
12525 			SCTP_LTRACE_ERR_RET(NULL, NULL, NULL, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12526 			error = EINVAL;
12527 			goto out_unlocked;
12528 
12529 		}
12530 		if (((inp->sctp_flags & SCTP_PCB_FLAGS_BOUND_V6) == 0) &&
12531 		    (addr->sa_family == AF_INET6)) {
12532 			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12533 			error = EINVAL;
12534 			goto out_unlocked;
12535 		}
12536 		SCTP_INP_WLOCK(inp);
12537 		SCTP_INP_INCR_REF(inp);
12538 		SCTP_INP_WUNLOCK(inp);
12539 		/* With the lock applied look again */
12540 		stcb = sctp_findassociation_ep_addr(&t_inp, addr, &net, NULL, NULL);
12541 		if (stcb == NULL) {
12542 			SCTP_INP_WLOCK(inp);
12543 			SCTP_INP_DECR_REF(inp);
12544 			SCTP_INP_WUNLOCK(inp);
12545 		} else {
12546 			hold_tcblock = 1;
12547 		}
12548 		if (t_inp != inp) {
12549 			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, ENOTCONN);
12550 			error = ENOTCONN;
12551 			goto out_unlocked;
12552 		}
12553 	}
12554 	if (stcb == NULL) {
12555 		if ((inp->sctp_flags & SCTP_PCB_FLAGS_TCPTYPE) ||
12556 		    (inp->sctp_flags & SCTP_PCB_FLAGS_IN_TCPPOOL)) {
12557 			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, ENOTCONN);
12558 			error = ENOTCONN;
12559 			goto out_unlocked;
12560 		}
12561 		if (addr == NULL) {
12562 			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, ENOENT);
12563 			error = ENOENT;
12564 			goto out_unlocked;
12565 		} else {
12566 			/*
12567 			 * UDP style, we must go ahead and start the INIT
12568 			 * process
12569 			 */
12570 			uint32_t vrf_id;
12571 
12572 			if ((use_rcvinfo) && (srcv) &&
12573 			    ((srcv->sinfo_flags & SCTP_ABORT) ||
12574 			    ((srcv->sinfo_flags & SCTP_EOF) &&
12575 			    (sndlen == 0)))) {
12576 				/*-
12577 				 * User asks to abort a non-existant assoc,
12578 				 * or EOF a non-existant assoc with no data
12579 				 */
12580 				SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, ENOENT);
12581 				error = ENOENT;
12582 				goto out_unlocked;
12583 			}
12584 			/* get an asoc/stcb struct */
12585 			vrf_id = inp->def_vrf_id;
12586 #ifdef INVARIANTS
12587 			if (create_lock_applied == 0) {
12588 				panic("Error, should hold create lock and I don't?");
12589 			}
12590 #endif
12591 			stcb = sctp_aloc_assoc(inp, addr, 1, &error, 0, vrf_id,
12592 			    p
12593 			    );
12594 			if (stcb == NULL) {
12595 				/* Error is setup for us in the call */
12596 				goto out_unlocked;
12597 			}
12598 			if (create_lock_applied) {
12599 				SCTP_ASOC_CREATE_UNLOCK(inp);
12600 				create_lock_applied = 0;
12601 			} else {
12602 				SCTP_PRINTF("Huh-3? create lock should have been on??\n");
12603 			}
12604 			/*
12605 			 * Turn on queue only flag to prevent data from
12606 			 * being sent
12607 			 */
12608 			queue_only = 1;
12609 			asoc = &stcb->asoc;
12610 			SCTP_SET_STATE(asoc, SCTP_STATE_COOKIE_WAIT);
12611 			(void)SCTP_GETTIME_TIMEVAL(&asoc->time_entered);
12612 
12613 			/* initialize authentication params for the assoc */
12614 			sctp_initialize_auth_params(inp, stcb);
12615 
12616 			if (control) {
12617 				/*
12618 				 * see if a init structure exists in cmsg
12619 				 * headers
12620 				 */
12621 				struct sctp_initmsg initm;
12622 				int i;
12623 
12624 				if (sctp_find_cmsg(SCTP_INIT, (void *)&initm, control,
12625 				    sizeof(initm))) {
12626 					/*
12627 					 * we have an INIT override of the
12628 					 * default
12629 					 */
12630 					if (initm.sinit_max_attempts)
12631 						asoc->max_init_times = initm.sinit_max_attempts;
12632 					if (initm.sinit_num_ostreams)
12633 						asoc->pre_open_streams = initm.sinit_num_ostreams;
12634 					if (initm.sinit_max_instreams)
12635 						asoc->max_inbound_streams = initm.sinit_max_instreams;
12636 					if (initm.sinit_max_init_timeo)
12637 						asoc->initial_init_rto_max = initm.sinit_max_init_timeo;
12638 					if (asoc->streamoutcnt < asoc->pre_open_streams) {
12639 						struct sctp_stream_out *tmp_str;
12640 						int had_lock = 0;
12641 
12642 						/* Default is NOT correct */
12643 						SCTPDBG(SCTP_DEBUG_OUTPUT1, "Ok, defout:%d pre_open:%d\n",
12644 						    asoc->streamoutcnt, asoc->pre_open_streams);
12645 						/*
12646 						 * What happens if this
12647 						 * fails? we panic ...
12648 						 */
12649 
12650 						if (hold_tcblock) {
12651 							had_lock = 1;
12652 							SCTP_TCB_UNLOCK(stcb);
12653 						}
12654 						SCTP_MALLOC(tmp_str,
12655 						    struct sctp_stream_out *,
12656 						    (asoc->pre_open_streams *
12657 						    sizeof(struct sctp_stream_out)),
12658 						    SCTP_M_STRMO);
12659 						if (had_lock) {
12660 							SCTP_TCB_LOCK(stcb);
12661 						}
12662 						if (tmp_str != NULL) {
12663 							SCTP_FREE(asoc->strmout, SCTP_M_STRMO);
12664 							asoc->strmout = tmp_str;
12665 							asoc->strm_realoutsize = asoc->streamoutcnt = asoc->pre_open_streams;
12666 						} else {
12667 							asoc->pre_open_streams = asoc->streamoutcnt;
12668 						}
12669 						for (i = 0; i < asoc->streamoutcnt; i++) {
12670 							/*-
12671 							 * inbound side must be set
12672 							 * to 0xffff, also NOTE when
12673 							 * we get the INIT-ACK back
12674 							 * (for INIT sender) we MUST
12675 							 * reduce the count
12676 							 * (streamoutcnt) but first
12677 							 * check if we sent to any
12678 							 * of the upper streams that
12679 							 * were dropped (if some
12680 							 * were). Those that were
12681 							 * dropped must be notified
12682 							 * to the upper layer as
12683 							 * failed to send.
12684 							 */
12685 							asoc->strmout[i].next_sequence_sent = 0x0;
12686 							TAILQ_INIT(&asoc->strmout[i].outqueue);
12687 							asoc->strmout[i].stream_no = i;
12688 							asoc->strmout[i].last_msg_incomplete = 0;
12689 							asoc->strmout[i].next_spoke.tqe_next = 0;
12690 							asoc->strmout[i].next_spoke.tqe_prev = 0;
12691 						}
12692 					}
12693 				}
12694 			}
12695 			hold_tcblock = 1;
12696 			/* out with the INIT */
12697 			queue_only_for_init = 1;
12698 			/*-
12699 			 * we may want to dig in after this call and adjust the MTU
12700 			 * value. It defaulted to 1500 (constant) but the ro
12701 			 * structure may now have an update and thus we may need to
12702 			 * change it BEFORE we append the message.
12703 			 */
12704 			net = stcb->asoc.primary_destination;
12705 			asoc = &stcb->asoc;
12706 		}
12707 	}
12708 	if ((SCTP_SO_IS_NBIO(so)
12709 	    || (flags & MSG_NBIO)
12710 	    )) {
12711 		non_blocking = 1;
12712 	}
12713 	asoc = &stcb->asoc;
12714 	atomic_add_int(&stcb->total_sends, 1);
12715 
12716 	if (sctp_is_feature_on(inp, SCTP_PCB_FLAGS_NO_FRAGMENT)) {
12717 		if (sndlen > asoc->smallest_mtu) {
12718 			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EMSGSIZE);
12719 			error = EMSGSIZE;
12720 			goto out_unlocked;
12721 		}
12722 	}
12723 	/* would we block? */
12724 	if (non_blocking) {
12725 		if (hold_tcblock == 0) {
12726 			SCTP_TCB_LOCK(stcb);
12727 			hold_tcblock = 1;
12728 		}
12729 		inqueue_bytes = stcb->asoc.total_output_queue_size - (stcb->asoc.chunks_on_out_queue * sizeof(struct sctp_data_chunk));
12730 		if ((SCTP_SB_LIMIT_SND(so) < (sndlen + inqueue_bytes + stcb->asoc.sb_send_resv)) ||
12731 		    (stcb->asoc.chunks_on_out_queue >= SCTP_BASE_SYSCTL(sctp_max_chunks_on_queue))) {
12732 			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EWOULDBLOCK);
12733 			if (sndlen > SCTP_SB_LIMIT_SND(so))
12734 				error = EMSGSIZE;
12735 			else
12736 				error = EWOULDBLOCK;
12737 			goto out_unlocked;
12738 		}
12739 		stcb->asoc.sb_send_resv += sndlen;
12740 		SCTP_TCB_UNLOCK(stcb);
12741 		hold_tcblock = 0;
12742 	} else {
12743 		atomic_add_int(&stcb->asoc.sb_send_resv, sndlen);
12744 	}
12745 	local_soresv = sndlen;
12746 	/* Keep the stcb from being freed under our feet */
12747 	if (free_cnt_applied) {
12748 #ifdef INVARIANTS
12749 		panic("refcnt already incremented");
12750 #else
12751 		printf("refcnt:1 already incremented?\n");
12752 #endif
12753 	} else {
12754 		atomic_add_int(&stcb->asoc.refcnt, 1);
12755 		free_cnt_applied = 1;
12756 	}
12757 	if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
12758 		SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ECONNRESET);
12759 		error = ECONNRESET;
12760 		goto out_unlocked;
12761 	}
12762 	if (create_lock_applied) {
12763 		SCTP_ASOC_CREATE_UNLOCK(inp);
12764 		create_lock_applied = 0;
12765 	}
12766 	if (asoc->stream_reset_outstanding) {
12767 		/*
12768 		 * Can't queue any data while stream reset is underway.
12769 		 */
12770 		SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EAGAIN);
12771 		error = EAGAIN;
12772 		goto out_unlocked;
12773 	}
12774 	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
12775 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)) {
12776 		queue_only = 1;
12777 	}
12778 	if ((use_rcvinfo == 0) || (srcv == NULL)) {
12779 		/* Grab the default stuff from the asoc */
12780 		srcv = (struct sctp_sndrcvinfo *)&stcb->asoc.def_send;
12781 	}
12782 	/* we are now done with all control */
12783 	if (control) {
12784 		sctp_m_freem(control);
12785 		control = NULL;
12786 	}
12787 	if ((SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_SENT) ||
12788 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_RECEIVED) ||
12789 	    (SCTP_GET_STATE(asoc) == SCTP_STATE_SHUTDOWN_ACK_SENT) ||
12790 	    (asoc->state & SCTP_STATE_SHUTDOWN_PENDING)) {
12791 		if ((use_rcvinfo) &&
12792 		    (srcv->sinfo_flags & SCTP_ABORT)) {
12793 			;
12794 		} else {
12795 			SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ECONNRESET);
12796 			error = ECONNRESET;
12797 			goto out_unlocked;
12798 		}
12799 	}
12800 	/* Ok, we will attempt a msgsnd :> */
12801 	if (p) {
12802 		p->td_ru.ru_msgsnd++;
12803 	}
12804 	if (stcb) {
12805 		if (((srcv->sinfo_flags | temp_flags) & SCTP_ADDR_OVER) == 0) {
12806 			net = stcb->asoc.primary_destination;
12807 		}
12808 	}
12809 	if (net == NULL) {
12810 		SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12811 		error = EINVAL;
12812 		goto out_unlocked;
12813 	}
12814 	if ((net->flight_size > net->cwnd) && (SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 0)) {
12815 		/*-
12816 		 * CMT: Added check for CMT above. net above is the primary
12817 		 * dest. If CMT is ON, sender should always attempt to send
12818 		 * with the output routine sctp_fill_outqueue() that loops
12819 		 * through all destination addresses. Therefore, if CMT is
12820 		 * ON, queue_only is NOT set to 1 here, so that
12821 		 * sctp_chunk_output() can be called below.
12822 		 */
12823 		queue_only = 1;
12824 	} else if (asoc->ifp_had_enobuf) {
12825 		SCTP_STAT_INCR(sctps_ifnomemqueued);
12826 		if (net->flight_size > (net->mtu * 2))
12827 			queue_only = 1;
12828 		asoc->ifp_had_enobuf = 0;
12829 	} else {
12830 		un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
12831 		    (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
12832 	}
12833 	/* Are we aborting? */
12834 	if (srcv->sinfo_flags & SCTP_ABORT) {
12835 		struct mbuf *mm;
12836 		int tot_demand, tot_out = 0, max_out;
12837 
12838 		SCTP_STAT_INCR(sctps_sends_with_abort);
12839 		if ((SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_WAIT) ||
12840 		    (SCTP_GET_STATE(asoc) == SCTP_STATE_COOKIE_ECHOED)) {
12841 			/* It has to be up before we abort */
12842 			/* how big is the user initiated abort? */
12843 			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12844 			error = EINVAL;
12845 			goto out;
12846 		}
12847 		if (hold_tcblock) {
12848 			SCTP_TCB_UNLOCK(stcb);
12849 			hold_tcblock = 0;
12850 		}
12851 		if (top) {
12852 			struct mbuf *cntm = NULL;
12853 
12854 			mm = sctp_get_mbuf_for_msg(1, 0, M_WAIT, 1, MT_DATA);
12855 			if (sndlen != 0) {
12856 				cntm = top;
12857 				while (cntm) {
12858 					tot_out += SCTP_BUF_LEN(cntm);
12859 					cntm = SCTP_BUF_NEXT(cntm);
12860 				}
12861 			}
12862 			tot_demand = (tot_out + sizeof(struct sctp_paramhdr));
12863 		} else {
12864 			/* Must fit in a MTU */
12865 			tot_out = sndlen;
12866 			tot_demand = (tot_out + sizeof(struct sctp_paramhdr));
12867 			if (tot_demand > SCTP_DEFAULT_ADD_MORE) {
12868 				/* To big */
12869 				SCTP_LTRACE_ERR_RET(NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, EMSGSIZE);
12870 				error = EMSGSIZE;
12871 				goto out;
12872 			}
12873 			mm = sctp_get_mbuf_for_msg(tot_demand, 0, M_WAIT, 1, MT_DATA);
12874 		}
12875 		if (mm == NULL) {
12876 			SCTP_LTRACE_ERR_RET(NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, ENOMEM);
12877 			error = ENOMEM;
12878 			goto out;
12879 		}
12880 		max_out = asoc->smallest_mtu - sizeof(struct sctp_paramhdr);
12881 		max_out -= sizeof(struct sctp_abort_msg);
12882 		if (tot_out > max_out) {
12883 			tot_out = max_out;
12884 		}
12885 		if (mm) {
12886 			struct sctp_paramhdr *ph;
12887 
12888 			/* now move forward the data pointer */
12889 			ph = mtod(mm, struct sctp_paramhdr *);
12890 			ph->param_type = htons(SCTP_CAUSE_USER_INITIATED_ABT);
12891 			ph->param_length = htons((sizeof(struct sctp_paramhdr) + tot_out));
12892 			ph++;
12893 			SCTP_BUF_LEN(mm) = tot_out + sizeof(struct sctp_paramhdr);
12894 			if (top == NULL) {
12895 				error = uiomove((caddr_t)ph, (int)tot_out, uio);
12896 				if (error) {
12897 					/*-
12898 					 * Here if we can't get his data we
12899 					 * still abort we just don't get to
12900 					 * send the users note :-0
12901 					 */
12902 					sctp_m_freem(mm);
12903 					mm = NULL;
12904 				}
12905 			} else {
12906 				if (sndlen != 0) {
12907 					SCTP_BUF_NEXT(mm) = top;
12908 				}
12909 			}
12910 		}
12911 		if (hold_tcblock == 0) {
12912 			SCTP_TCB_LOCK(stcb);
12913 			hold_tcblock = 1;
12914 		}
12915 		atomic_add_int(&stcb->asoc.refcnt, -1);
12916 		free_cnt_applied = 0;
12917 		/* release this lock, otherwise we hang on ourselves */
12918 		sctp_abort_an_association(stcb->sctp_ep, stcb,
12919 		    SCTP_RESPONSE_TO_USER_REQ,
12920 		    mm, SCTP_SO_LOCKED);
12921 		/* now relock the stcb so everything is sane */
12922 		hold_tcblock = 0;
12923 		stcb = NULL;
12924 		/*
12925 		 * In this case top is already chained to mm avoid double
12926 		 * free, since we free it below if top != NULL and driver
12927 		 * would free it after sending the packet out
12928 		 */
12929 		if (sndlen != 0) {
12930 			top = NULL;
12931 		}
12932 		goto out_unlocked;
12933 	}
12934 	/* Calculate the maximum we can send */
12935 	inqueue_bytes = stcb->asoc.total_output_queue_size - (stcb->asoc.chunks_on_out_queue * sizeof(struct sctp_data_chunk));
12936 	if (SCTP_SB_LIMIT_SND(so) > inqueue_bytes) {
12937 		if (non_blocking) {
12938 			/* we already checked for non-blocking above. */
12939 			max_len = sndlen;
12940 		} else {
12941 			max_len = SCTP_SB_LIMIT_SND(so) - inqueue_bytes;
12942 		}
12943 	} else {
12944 		max_len = 0;
12945 	}
12946 	if (hold_tcblock) {
12947 		SCTP_TCB_UNLOCK(stcb);
12948 		hold_tcblock = 0;
12949 	}
12950 	/* Is the stream no. valid? */
12951 	if (srcv->sinfo_stream >= asoc->streamoutcnt) {
12952 		/* Invalid stream number */
12953 		SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12954 		error = EINVAL;
12955 		goto out_unlocked;
12956 	}
12957 	if (asoc->strmout == NULL) {
12958 		/* huh? software error */
12959 		SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EFAULT);
12960 		error = EFAULT;
12961 		goto out_unlocked;
12962 	}
12963 	/* Unless E_EOR mode is on, we must make a send FIT in one call. */
12964 	if ((user_marks_eor == 0) &&
12965 	    (sndlen > SCTP_SB_LIMIT_SND(stcb->sctp_socket))) {
12966 		/* It will NEVER fit */
12967 		SCTP_LTRACE_ERR_RET(NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, EMSGSIZE);
12968 		error = EMSGSIZE;
12969 		goto out_unlocked;
12970 	}
12971 	if ((uio == NULL) && user_marks_eor) {
12972 		/*-
12973 		 * We do not support eeor mode for
12974 		 * sending with mbuf chains (like sendfile).
12975 		 */
12976 		SCTP_LTRACE_ERR_RET(NULL, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
12977 		error = EINVAL;
12978 		goto out_unlocked;
12979 	}
12980 	if (user_marks_eor) {
12981 		local_add_more = min(SCTP_SB_LIMIT_SND(so), SCTP_BASE_SYSCTL(sctp_add_more_threshold));
12982 	} else {
12983 		/*-
12984 		 * For non-eeor the whole message must fit in
12985 		 * the socket send buffer.
12986 		 */
12987 		local_add_more = sndlen;
12988 	}
12989 	len = 0;
12990 	if (non_blocking) {
12991 		goto skip_preblock;
12992 	}
12993 	if (((max_len <= local_add_more) &&
12994 	    (SCTP_SB_LIMIT_SND(so) >= local_add_more)) ||
12995 	    (max_len == 0) ||
12996 	    ((stcb->asoc.chunks_on_out_queue + stcb->asoc.stream_queue_cnt) >= SCTP_BASE_SYSCTL(sctp_max_chunks_on_queue))) {
12997 		/* No room right now ! */
12998 		SOCKBUF_LOCK(&so->so_snd);
12999 		inqueue_bytes = stcb->asoc.total_output_queue_size - (stcb->asoc.chunks_on_out_queue * sizeof(struct sctp_data_chunk));
13000 		while ((SCTP_SB_LIMIT_SND(so) < (inqueue_bytes + local_add_more)) ||
13001 		    ((stcb->asoc.stream_queue_cnt + stcb->asoc.chunks_on_out_queue) >= SCTP_BASE_SYSCTL(sctp_max_chunks_on_queue))) {
13002 			SCTPDBG(SCTP_DEBUG_OUTPUT1, "pre_block limit:%u <(inq:%d + %d) || (%d+%d > %d)\n",
13003 			    (unsigned int)SCTP_SB_LIMIT_SND(so),
13004 			    inqueue_bytes,
13005 			    local_add_more,
13006 			    stcb->asoc.stream_queue_cnt,
13007 			    stcb->asoc.chunks_on_out_queue,
13008 			    SCTP_BASE_SYSCTL(sctp_max_chunks_on_queue));
13009 			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
13010 				sctp_log_block(SCTP_BLOCK_LOG_INTO_BLKA, so, asoc, sndlen);
13011 			}
13012 			be.error = 0;
13013 			stcb->block_entry = &be;
13014 			error = sbwait(&so->so_snd);
13015 			stcb->block_entry = NULL;
13016 			if (error || so->so_error || be.error) {
13017 				if (error == 0) {
13018 					if (so->so_error)
13019 						error = so->so_error;
13020 					if (be.error) {
13021 						error = be.error;
13022 					}
13023 				}
13024 				SOCKBUF_UNLOCK(&so->so_snd);
13025 				goto out_unlocked;
13026 			}
13027 			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
13028 				sctp_log_block(SCTP_BLOCK_LOG_OUTOF_BLK,
13029 				    so, asoc, stcb->asoc.total_output_queue_size);
13030 			}
13031 			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
13032 				goto out_unlocked;
13033 			}
13034 			inqueue_bytes = stcb->asoc.total_output_queue_size - (stcb->asoc.chunks_on_out_queue * sizeof(struct sctp_data_chunk));
13035 		}
13036 		inqueue_bytes = stcb->asoc.total_output_queue_size - (stcb->asoc.chunks_on_out_queue * sizeof(struct sctp_data_chunk));
13037 		if (SCTP_SB_LIMIT_SND(so) > inqueue_bytes) {
13038 			max_len = SCTP_SB_LIMIT_SND(so) - inqueue_bytes;
13039 		} else {
13040 			max_len = 0;
13041 		}
13042 		SOCKBUF_UNLOCK(&so->so_snd);
13043 	}
13044 skip_preblock:
13045 	if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
13046 		goto out_unlocked;
13047 	}
13048 	/*
13049 	 * sndlen covers for mbuf case uio_resid covers for the non-mbuf
13050 	 * case NOTE: uio will be null when top/mbuf is passed
13051 	 */
13052 	if (sndlen == 0) {
13053 		if (srcv->sinfo_flags & SCTP_EOF) {
13054 			got_all_of_the_send = 1;
13055 			goto dataless_eof;
13056 		} else {
13057 			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
13058 			error = EINVAL;
13059 			goto out;
13060 		}
13061 	}
13062 	if (top == NULL) {
13063 		struct sctp_stream_queue_pending *sp;
13064 		struct sctp_stream_out *strm;
13065 		uint32_t sndout, initial_out;
13066 
13067 		initial_out = uio->uio_resid;
13068 
13069 		SCTP_TCB_SEND_LOCK(stcb);
13070 		if ((asoc->stream_locked) &&
13071 		    (asoc->stream_locked_on != srcv->sinfo_stream)) {
13072 			SCTP_TCB_SEND_UNLOCK(stcb);
13073 			SCTP_LTRACE_ERR_RET(inp, stcb, net, SCTP_FROM_SCTP_OUTPUT, EINVAL);
13074 			error = EINVAL;
13075 			goto out;
13076 		}
13077 		SCTP_TCB_SEND_UNLOCK(stcb);
13078 
13079 		strm = &stcb->asoc.strmout[srcv->sinfo_stream];
13080 		if (strm->last_msg_incomplete == 0) {
13081 	do_a_copy_in:
13082 			sp = sctp_copy_it_in(stcb, asoc, srcv, uio, net, max_len, user_marks_eor, &error, non_blocking);
13083 			if ((sp == NULL) || (error)) {
13084 				goto out;
13085 			}
13086 			SCTP_TCB_SEND_LOCK(stcb);
13087 			if (sp->msg_is_complete) {
13088 				strm->last_msg_incomplete = 0;
13089 				asoc->stream_locked = 0;
13090 			} else {
13091 				/*
13092 				 * Just got locked to this guy in case of an
13093 				 * interrupt.
13094 				 */
13095 				strm->last_msg_incomplete = 1;
13096 				asoc->stream_locked = 1;
13097 				asoc->stream_locked_on = srcv->sinfo_stream;
13098 				sp->sender_all_done = 0;
13099 			}
13100 			sctp_snd_sb_alloc(stcb, sp->length);
13101 			atomic_add_int(&asoc->stream_queue_cnt, 1);
13102 			if ((srcv->sinfo_flags & SCTP_UNORDERED) == 0) {
13103 				sp->strseq = strm->next_sequence_sent;
13104 				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_LOG_AT_SEND_2_SCTP) {
13105 					sctp_misc_ints(SCTP_STRMOUT_LOG_ASSIGN,
13106 					    (uintptr_t) stcb, sp->length,
13107 					    (uint32_t) ((srcv->sinfo_stream << 16) | sp->strseq), 0);
13108 				}
13109 				strm->next_sequence_sent++;
13110 			} else {
13111 				SCTP_STAT_INCR(sctps_sends_with_unord);
13112 			}
13113 			TAILQ_INSERT_TAIL(&strm->outqueue, sp, next);
13114 			if ((strm->next_spoke.tqe_next == NULL) &&
13115 			    (strm->next_spoke.tqe_prev == NULL)) {
13116 				/* Not on wheel, insert */
13117 				sctp_insert_on_wheel(stcb, asoc, strm, 1);
13118 			}
13119 			SCTP_TCB_SEND_UNLOCK(stcb);
13120 		} else {
13121 			SCTP_TCB_SEND_LOCK(stcb);
13122 			sp = TAILQ_LAST(&strm->outqueue, sctp_streamhead);
13123 			SCTP_TCB_SEND_UNLOCK(stcb);
13124 			if (sp == NULL) {
13125 				/* ???? Huh ??? last msg is gone */
13126 #ifdef INVARIANTS
13127 				panic("Warning: Last msg marked incomplete, yet nothing left?");
13128 #else
13129 				SCTP_PRINTF("Warning: Last msg marked incomplete, yet nothing left?\n");
13130 				strm->last_msg_incomplete = 0;
13131 #endif
13132 				goto do_a_copy_in;
13133 
13134 			}
13135 		}
13136 		while (uio->uio_resid > 0) {
13137 			/* How much room do we have? */
13138 			struct mbuf *new_tail, *mm;
13139 
13140 			if (SCTP_SB_LIMIT_SND(so) > stcb->asoc.total_output_queue_size)
13141 				max_len = SCTP_SB_LIMIT_SND(so) - stcb->asoc.total_output_queue_size;
13142 			else
13143 				max_len = 0;
13144 
13145 			if ((max_len > SCTP_BASE_SYSCTL(sctp_add_more_threshold)) ||
13146 			    (max_len && (SCTP_SB_LIMIT_SND(so) < SCTP_BASE_SYSCTL(sctp_add_more_threshold))) ||
13147 			    (uio->uio_resid && (uio->uio_resid <= (int)max_len))) {
13148 				sndout = 0;
13149 				new_tail = NULL;
13150 				if (hold_tcblock) {
13151 					SCTP_TCB_UNLOCK(stcb);
13152 					hold_tcblock = 0;
13153 				}
13154 				mm = sctp_copy_resume(sp, uio, srcv, max_len, user_marks_eor, &error, &sndout, &new_tail);
13155 				if ((mm == NULL) || error) {
13156 					if (mm) {
13157 						sctp_m_freem(mm);
13158 					}
13159 					goto out;
13160 				}
13161 				/* Update the mbuf and count */
13162 				SCTP_TCB_SEND_LOCK(stcb);
13163 				if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
13164 					/*
13165 					 * we need to get out. Peer probably
13166 					 * aborted.
13167 					 */
13168 					sctp_m_freem(mm);
13169 					if (stcb->asoc.state & SCTP_PCB_FLAGS_WAS_ABORTED) {
13170 						SCTP_LTRACE_ERR_RET(NULL, stcb, NULL, SCTP_FROM_SCTP_OUTPUT, ECONNRESET);
13171 						error = ECONNRESET;
13172 					}
13173 					SCTP_TCB_SEND_UNLOCK(stcb);
13174 					goto out;
13175 				}
13176 				if (sp->tail_mbuf) {
13177 					/* tack it to the end */
13178 					SCTP_BUF_NEXT(sp->tail_mbuf) = mm;
13179 					sp->tail_mbuf = new_tail;
13180 				} else {
13181 					/* A stolen mbuf */
13182 					sp->data = mm;
13183 					sp->tail_mbuf = new_tail;
13184 				}
13185 				sctp_snd_sb_alloc(stcb, sndout);
13186 				atomic_add_int(&sp->length, sndout);
13187 				len += sndout;
13188 
13189 				/* Did we reach EOR? */
13190 				if ((uio->uio_resid == 0) &&
13191 				    ((user_marks_eor == 0) ||
13192 				    (srcv->sinfo_flags & SCTP_EOF) ||
13193 				    (user_marks_eor && (srcv->sinfo_flags & SCTP_EOR)))) {
13194 					sp->msg_is_complete = 1;
13195 				} else {
13196 					sp->msg_is_complete = 0;
13197 				}
13198 				SCTP_TCB_SEND_UNLOCK(stcb);
13199 			}
13200 			if (uio->uio_resid == 0) {
13201 				/* got it all? */
13202 				continue;
13203 			}
13204 			/* PR-SCTP? */
13205 			if ((asoc->peer_supports_prsctp) && (asoc->sent_queue_cnt_removeable > 0)) {
13206 				/*
13207 				 * This is ugly but we must assure locking
13208 				 * order
13209 				 */
13210 				if (hold_tcblock == 0) {
13211 					SCTP_TCB_LOCK(stcb);
13212 					hold_tcblock = 1;
13213 				}
13214 				sctp_prune_prsctp(stcb, asoc, srcv, sndlen);
13215 				inqueue_bytes = stcb->asoc.total_output_queue_size - (stcb->asoc.chunks_on_out_queue * sizeof(struct sctp_data_chunk));
13216 				if (SCTP_SB_LIMIT_SND(so) > stcb->asoc.total_output_queue_size)
13217 					max_len = SCTP_SB_LIMIT_SND(so) - inqueue_bytes;
13218 				else
13219 					max_len = 0;
13220 				if (max_len > 0) {
13221 					continue;
13222 				}
13223 				SCTP_TCB_UNLOCK(stcb);
13224 				hold_tcblock = 0;
13225 			}
13226 			/* wait for space now */
13227 			if (non_blocking) {
13228 				/* Non-blocking io in place out */
13229 				goto skip_out_eof;
13230 			}
13231 			if ((net->flight_size > net->cwnd) &&
13232 			    (SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 0)) {
13233 				queue_only = 1;
13234 			} else if (asoc->ifp_had_enobuf) {
13235 				SCTP_STAT_INCR(sctps_ifnomemqueued);
13236 				if (net->flight_size > (net->mtu * 2)) {
13237 					queue_only = 1;
13238 				} else {
13239 					queue_only = 0;
13240 				}
13241 				asoc->ifp_had_enobuf = 0;
13242 				un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
13243 				    (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
13244 			} else {
13245 				un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
13246 				    (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
13247 				if (net->flight_size > net->cwnd) {
13248 					queue_only = 1;
13249 					SCTP_STAT_INCR(sctps_send_cwnd_avoid);
13250 				} else {
13251 					queue_only = 0;
13252 				}
13253 			}
13254 			if ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY)) &&
13255 			    (stcb->asoc.total_flight > 0) &&
13256 			    (stcb->asoc.stream_queue_cnt < SCTP_MAX_DATA_BUNDLING) &&
13257 			    (un_sent < (int)(stcb->asoc.smallest_mtu - SCTP_MIN_OVERHEAD))) {
13258 
13259 				/*-
13260 				 * Ok, Nagle is set on and we have data outstanding.
13261 				 * Don't send anything and let SACKs drive out the
13262 				 * data unless wen have a "full" segment to send.
13263 				 */
13264 				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_NAGLE_LOGGING_ENABLE) {
13265 					sctp_log_nagle_event(stcb, SCTP_NAGLE_APPLIED);
13266 				}
13267 				SCTP_STAT_INCR(sctps_naglequeued);
13268 				nagle_applies = 1;
13269 			} else {
13270 				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_NAGLE_LOGGING_ENABLE) {
13271 					if (sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY))
13272 						sctp_log_nagle_event(stcb, SCTP_NAGLE_SKIPPED);
13273 				}
13274 				SCTP_STAT_INCR(sctps_naglesent);
13275 				nagle_applies = 0;
13276 			}
13277 			/* What about the INIT, send it maybe */
13278 			if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
13279 
13280 				sctp_misc_ints(SCTP_CWNDLOG_PRESEND, queue_only_for_init, queue_only,
13281 				    nagle_applies, un_sent);
13282 				sctp_misc_ints(SCTP_CWNDLOG_PRESEND, stcb->asoc.total_output_queue_size,
13283 				    stcb->asoc.total_flight,
13284 				    stcb->asoc.chunks_on_out_queue, stcb->asoc.total_flight_count);
13285 			}
13286 			if (queue_only_for_init) {
13287 				if (hold_tcblock == 0) {
13288 					SCTP_TCB_LOCK(stcb);
13289 					hold_tcblock = 1;
13290 				}
13291 				if (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_OPEN) {
13292 					/* a collision took us forward? */
13293 					queue_only_for_init = 0;
13294 					queue_only = 0;
13295 				} else {
13296 					sctp_send_initiate(inp, stcb, SCTP_SO_LOCKED);
13297 					SCTP_SET_STATE(asoc, SCTP_STATE_COOKIE_WAIT);
13298 					queue_only_for_init = 0;
13299 					queue_only = 1;
13300 				}
13301 			}
13302 			if ((queue_only == 0) && (nagle_applies == 0)) {
13303 				/*-
13304 				 * need to start chunk output
13305 				 * before blocking.. note that if
13306 				 * a lock is already applied, then
13307 				 * the input via the net is happening
13308 				 * and I don't need to start output :-D
13309 				 */
13310 				if (hold_tcblock == 0) {
13311 					if (SCTP_TCB_TRYLOCK(stcb)) {
13312 						hold_tcblock = 1;
13313 						sctp_chunk_output(inp,
13314 						    stcb,
13315 						    SCTP_OUTPUT_FROM_USR_SEND, SCTP_SO_LOCKED);
13316 					}
13317 				} else {
13318 					sctp_chunk_output(inp,
13319 					    stcb,
13320 					    SCTP_OUTPUT_FROM_USR_SEND, SCTP_SO_LOCKED);
13321 				}
13322 				if (hold_tcblock == 1) {
13323 					SCTP_TCB_UNLOCK(stcb);
13324 					hold_tcblock = 0;
13325 				}
13326 			}
13327 			SOCKBUF_LOCK(&so->so_snd);
13328 			/*-
13329 			 * This is a bit strange, but I think it will
13330 			 * work. The total_output_queue_size is locked and
13331 			 * protected by the TCB_LOCK, which we just released.
13332 			 * There is a race that can occur between releasing it
13333 			 * above, and me getting the socket lock, where sacks
13334 			 * come in but we have not put the SB_WAIT on the
13335 			 * so_snd buffer to get the wakeup. After the LOCK
13336 			 * is applied the sack_processing will also need to
13337 			 * LOCK the so->so_snd to do the actual sowwakeup(). So
13338 			 * once we have the socket buffer lock if we recheck the
13339 			 * size we KNOW we will get to sleep safely with the
13340 			 * wakeup flag in place.
13341 			 */
13342 			if (SCTP_SB_LIMIT_SND(so) <= (stcb->asoc.total_output_queue_size +
13343 			    min(SCTP_BASE_SYSCTL(sctp_add_more_threshold), SCTP_SB_LIMIT_SND(so)))) {
13344 				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
13345 					sctp_log_block(SCTP_BLOCK_LOG_INTO_BLK,
13346 					    so, asoc, uio->uio_resid);
13347 				}
13348 				be.error = 0;
13349 				stcb->block_entry = &be;
13350 				error = sbwait(&so->so_snd);
13351 				stcb->block_entry = NULL;
13352 
13353 				if (error || so->so_error || be.error) {
13354 					if (error == 0) {
13355 						if (so->so_error)
13356 							error = so->so_error;
13357 						if (be.error) {
13358 							error = be.error;
13359 						}
13360 					}
13361 					SOCKBUF_UNLOCK(&so->so_snd);
13362 					goto out_unlocked;
13363 				}
13364 				if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_BLK_LOGGING_ENABLE) {
13365 					sctp_log_block(SCTP_BLOCK_LOG_OUTOF_BLK,
13366 					    so, asoc, stcb->asoc.total_output_queue_size);
13367 				}
13368 			}
13369 			SOCKBUF_UNLOCK(&so->so_snd);
13370 			if (stcb->asoc.state & SCTP_STATE_ABOUT_TO_BE_FREED) {
13371 				goto out_unlocked;
13372 			}
13373 		}
13374 		SCTP_TCB_SEND_LOCK(stcb);
13375 		if (sp) {
13376 			if (sp->msg_is_complete == 0) {
13377 				strm->last_msg_incomplete = 1;
13378 				asoc->stream_locked = 1;
13379 				asoc->stream_locked_on = srcv->sinfo_stream;
13380 			} else {
13381 				sp->sender_all_done = 1;
13382 				strm->last_msg_incomplete = 0;
13383 				asoc->stream_locked = 0;
13384 			}
13385 		} else {
13386 			SCTP_PRINTF("Huh no sp TSNH?\n");
13387 			strm->last_msg_incomplete = 0;
13388 			asoc->stream_locked = 0;
13389 		}
13390 		SCTP_TCB_SEND_UNLOCK(stcb);
13391 		if (uio->uio_resid == 0) {
13392 			got_all_of_the_send = 1;
13393 		}
13394 	} else if (top) {
13395 		/* We send in a 0, since we do NOT have any locks */
13396 		error = sctp_msg_append(stcb, net, top, srcv, 0);
13397 		top = NULL;
13398 		if (srcv->sinfo_flags & SCTP_EOF) {
13399 			/*
13400 			 * This should only happen for Panda for the mbuf
13401 			 * send case, which does NOT yet support EEOR mode.
13402 			 * Thus, we can just set this flag to do the proper
13403 			 * EOF handling.
13404 			 */
13405 			got_all_of_the_send = 1;
13406 		}
13407 	}
13408 	if (error) {
13409 		goto out;
13410 	}
13411 dataless_eof:
13412 	/* EOF thing ? */
13413 	if ((srcv->sinfo_flags & SCTP_EOF) &&
13414 	    (got_all_of_the_send == 1) &&
13415 	    (stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_UDPTYPE)) {
13416 		int cnt;
13417 
13418 		SCTP_STAT_INCR(sctps_sends_with_eof);
13419 		error = 0;
13420 		if (hold_tcblock == 0) {
13421 			SCTP_TCB_LOCK(stcb);
13422 			hold_tcblock = 1;
13423 		}
13424 		cnt = sctp_is_there_unsent_data(stcb);
13425 		if (TAILQ_EMPTY(&asoc->send_queue) &&
13426 		    TAILQ_EMPTY(&asoc->sent_queue) &&
13427 		    (cnt == 0)) {
13428 			if (asoc->locked_on_sending) {
13429 				goto abort_anyway;
13430 			}
13431 			/* there is nothing queued to send, so I'm done... */
13432 			if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
13433 			    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
13434 			    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
13435 				/* only send SHUTDOWN the first time through */
13436 				sctp_send_shutdown(stcb, stcb->asoc.primary_destination);
13437 				if (SCTP_GET_STATE(asoc) == SCTP_STATE_OPEN) {
13438 					SCTP_STAT_DECR_GAUGE32(sctps_currestab);
13439 				}
13440 				SCTP_SET_STATE(asoc, SCTP_STATE_SHUTDOWN_SENT);
13441 				SCTP_CLEAR_SUBSTATE(asoc, SCTP_STATE_SHUTDOWN_PENDING);
13442 				sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWN, stcb->sctp_ep, stcb,
13443 				    asoc->primary_destination);
13444 				sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
13445 				    asoc->primary_destination);
13446 			}
13447 		} else {
13448 			/*-
13449 			 * we still got (or just got) data to send, so set
13450 			 * SHUTDOWN_PENDING
13451 			 */
13452 			/*-
13453 			 * XXX sockets draft says that SCTP_EOF should be
13454 			 * sent with no data.  currently, we will allow user
13455 			 * data to be sent first and move to
13456 			 * SHUTDOWN-PENDING
13457 			 */
13458 			if ((SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_SENT) &&
13459 			    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_RECEIVED) &&
13460 			    (SCTP_GET_STATE(asoc) != SCTP_STATE_SHUTDOWN_ACK_SENT)) {
13461 				if (hold_tcblock == 0) {
13462 					SCTP_TCB_LOCK(stcb);
13463 					hold_tcblock = 1;
13464 				}
13465 				if (asoc->locked_on_sending) {
13466 					/* Locked to send out the data */
13467 					struct sctp_stream_queue_pending *sp;
13468 
13469 					sp = TAILQ_LAST(&asoc->locked_on_sending->outqueue, sctp_streamhead);
13470 					if (sp) {
13471 						if ((sp->length == 0) && (sp->msg_is_complete == 0))
13472 							asoc->state |= SCTP_STATE_PARTIAL_MSG_LEFT;
13473 					}
13474 				}
13475 				asoc->state |= SCTP_STATE_SHUTDOWN_PENDING;
13476 				if (TAILQ_EMPTY(&asoc->send_queue) &&
13477 				    TAILQ_EMPTY(&asoc->sent_queue) &&
13478 				    (asoc->state & SCTP_STATE_PARTIAL_MSG_LEFT)) {
13479 			abort_anyway:
13480 					if (free_cnt_applied) {
13481 						atomic_add_int(&stcb->asoc.refcnt, -1);
13482 						free_cnt_applied = 0;
13483 					}
13484 					sctp_abort_an_association(stcb->sctp_ep, stcb,
13485 					    SCTP_RESPONSE_TO_USER_REQ,
13486 					    NULL, SCTP_SO_LOCKED);
13487 					/*
13488 					 * now relock the stcb so everything
13489 					 * is sane
13490 					 */
13491 					hold_tcblock = 0;
13492 					stcb = NULL;
13493 					goto out;
13494 				}
13495 				sctp_timer_start(SCTP_TIMER_TYPE_SHUTDOWNGUARD, stcb->sctp_ep, stcb,
13496 				    asoc->primary_destination);
13497 				sctp_feature_off(inp, SCTP_PCB_FLAGS_NODELAY);
13498 			}
13499 		}
13500 	}
13501 skip_out_eof:
13502 	if (!TAILQ_EMPTY(&stcb->asoc.control_send_queue)) {
13503 		some_on_control = 1;
13504 	}
13505 	if ((net->flight_size > net->cwnd) &&
13506 	    (SCTP_BASE_SYSCTL(sctp_cmt_on_off) == 0)) {
13507 		queue_only = 1;
13508 	} else if (asoc->ifp_had_enobuf) {
13509 		SCTP_STAT_INCR(sctps_ifnomemqueued);
13510 		if (net->flight_size > (net->mtu * 2)) {
13511 			queue_only = 1;
13512 		} else {
13513 			queue_only = 0;
13514 		}
13515 		asoc->ifp_had_enobuf = 0;
13516 		un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
13517 		    (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
13518 	} else {
13519 		un_sent = ((stcb->asoc.total_output_queue_size - stcb->asoc.total_flight) +
13520 		    (stcb->asoc.stream_queue_cnt * sizeof(struct sctp_data_chunk)));
13521 		if (net->flight_size > net->cwnd) {
13522 			queue_only = 1;
13523 			SCTP_STAT_INCR(sctps_send_cwnd_avoid);
13524 		} else {
13525 			queue_only = 0;
13526 		}
13527 	}
13528 	if ((sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY)) &&
13529 	    (stcb->asoc.total_flight > 0) &&
13530 	    (stcb->asoc.stream_queue_cnt < SCTP_MAX_DATA_BUNDLING) &&
13531 	    (un_sent < (int)(stcb->asoc.smallest_mtu - SCTP_MIN_OVERHEAD))) {
13532 		/*-
13533 		 * Ok, Nagle is set on and we have data outstanding.
13534 		 * Don't send anything and let SACKs drive out the
13535 		 * data unless wen have a "full" segment to send.
13536 		 */
13537 		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_NAGLE_LOGGING_ENABLE) {
13538 			sctp_log_nagle_event(stcb, SCTP_NAGLE_APPLIED);
13539 		}
13540 		SCTP_STAT_INCR(sctps_naglequeued);
13541 		nagle_applies = 1;
13542 	} else {
13543 		if (SCTP_BASE_SYSCTL(sctp_logging_level) & SCTP_NAGLE_LOGGING_ENABLE) {
13544 			if (sctp_is_feature_off(inp, SCTP_PCB_FLAGS_NODELAY))
13545 				sctp_log_nagle_event(stcb, SCTP_NAGLE_SKIPPED);
13546 		}
13547 		SCTP_STAT_INCR(sctps_naglesent);
13548 		nagle_applies = 0;
13549 	}
13550 	if (queue_only_for_init) {
13551 		if (hold_tcblock == 0) {
13552 			SCTP_TCB_LOCK(stcb);
13553 			hold_tcblock = 1;
13554 		}
13555 		if (SCTP_GET_STATE(&stcb->asoc) == SCTP_STATE_OPEN) {
13556 			/* a collision took us forward? */
13557 			queue_only_for_init = 0;
13558 			queue_only = 0;
13559 		} else {
13560 			sctp_send_initiate(inp, stcb, SCTP_SO_LOCKED);
13561 			SCTP_SET_STATE(&stcb->asoc, SCTP_STATE_COOKIE_WAIT);
13562 			queue_only_for_init = 0;
13563 			queue_only = 1;
13564 		}
13565 	}
13566 	if ((queue_only == 0) && (nagle_applies == 0) && (stcb->asoc.peers_rwnd && un_sent)) {
13567 		/* we can attempt to send too. */
13568 		if (hold_tcblock == 0) {
13569 			/*
13570 			 * If there is activity recv'ing sacks no need to
13571 			 * send
13572 			 */
13573 			if (SCTP_TCB_TRYLOCK(stcb)) {
13574 				sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_USR_SEND, SCTP_SO_LOCKED);
13575 				hold_tcblock = 1;
13576 			}
13577 		} else {
13578 			sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_USR_SEND, SCTP_SO_LOCKED);
13579 		}
13580 	} else if ((queue_only == 0) &&
13581 		    (stcb->asoc.peers_rwnd == 0) &&
13582 	    (stcb->asoc.total_flight == 0)) {
13583 		/* We get to have a probe outstanding */
13584 		if (hold_tcblock == 0) {
13585 			hold_tcblock = 1;
13586 			SCTP_TCB_LOCK(stcb);
13587 		}
13588 		sctp_chunk_output(inp, stcb, SCTP_OUTPUT_FROM_USR_SEND, SCTP_SO_LOCKED);
13589 	} else if (some_on_control) {
13590 		int num_out, reason, frag_point;
13591 
13592 		/* Here we do control only */
13593 		if (hold_tcblock == 0) {
13594 			hold_tcblock = 1;
13595 			SCTP_TCB_LOCK(stcb);
13596 		}
13597 		frag_point = sctp_get_frag_point(stcb, &stcb->asoc);
13598 		(void)sctp_med_chunk_output(inp, stcb, &stcb->asoc, &num_out,
13599 		    &reason, 1, 1, &now, &now_filled, frag_point, SCTP_SO_LOCKED);
13600 	}
13601 	SCTPDBG(SCTP_DEBUG_OUTPUT1, "USR Send complete qo:%d prw:%d unsent:%d tf:%d cooq:%d toqs:%d err:%d\n",
13602 	    queue_only, stcb->asoc.peers_rwnd, un_sent,
13603 	    stcb->asoc.total_flight, stcb->asoc.chunks_on_out_queue,
13604 	    stcb->asoc.total_output_queue_size, error);
13605 
13606 out:
13607 out_unlocked:
13608 
13609 	if (local_soresv && stcb) {
13610 		atomic_subtract_int(&stcb->asoc.sb_send_resv, sndlen);
13611 		local_soresv = 0;
13612 	}
13613 	if (create_lock_applied) {
13614 		SCTP_ASOC_CREATE_UNLOCK(inp);
13615 		create_lock_applied = 0;
13616 	}
13617 	if ((stcb) && hold_tcblock) {
13618 		SCTP_TCB_UNLOCK(stcb);
13619 	}
13620 	if (stcb && free_cnt_applied) {
13621 		atomic_add_int(&stcb->asoc.refcnt, -1);
13622 	}
13623 #ifdef INVARIANTS
13624 	if (stcb) {
13625 		if (mtx_owned(&stcb->tcb_mtx)) {
13626 			panic("Leaving with tcb mtx owned?");
13627 		}
13628 		if (mtx_owned(&stcb->tcb_send_mtx)) {
13629 			panic("Leaving with tcb send mtx owned?");
13630 		}
13631 	}
13632 #endif
13633 	if (top) {
13634 		sctp_m_freem(top);
13635 	}
13636 	if (control) {
13637 		sctp_m_freem(control);
13638 	}
13639 	return (error);
13640 }
13641 
13642 
13643 /*
13644  * generate an AUTHentication chunk, if required
13645  */
13646 struct mbuf *
13647 sctp_add_auth_chunk(struct mbuf *m, struct mbuf **m_end,
13648     struct sctp_auth_chunk **auth_ret, uint32_t * offset,
13649     struct sctp_tcb *stcb, uint8_t chunk)
13650 {
13651 	struct mbuf *m_auth;
13652 	struct sctp_auth_chunk *auth;
13653 	int chunk_len;
13654 
13655 	if ((m_end == NULL) || (auth_ret == NULL) || (offset == NULL) ||
13656 	    (stcb == NULL))
13657 		return (m);
13658 
13659 	/* sysctl disabled auth? */
13660 	if (SCTP_BASE_SYSCTL(sctp_auth_disable))
13661 		return (m);
13662 
13663 	/* peer doesn't do auth... */
13664 	if (!stcb->asoc.peer_supports_auth) {
13665 		return (m);
13666 	}
13667 	/* does the requested chunk require auth? */
13668 	if (!sctp_auth_is_required_chunk(chunk, stcb->asoc.peer_auth_chunks)) {
13669 		return (m);
13670 	}
13671 	m_auth = sctp_get_mbuf_for_msg(sizeof(*auth), 0, M_DONTWAIT, 1, MT_HEADER);
13672 	if (m_auth == NULL) {
13673 		/* no mbuf's */
13674 		return (m);
13675 	}
13676 	/* reserve some space if this will be the first mbuf */
13677 	if (m == NULL)
13678 		SCTP_BUF_RESV_UF(m_auth, SCTP_MIN_OVERHEAD);
13679 	/* fill in the AUTH chunk details */
13680 	auth = mtod(m_auth, struct sctp_auth_chunk *);
13681 	bzero(auth, sizeof(*auth));
13682 	auth->ch.chunk_type = SCTP_AUTHENTICATION;
13683 	auth->ch.chunk_flags = 0;
13684 	chunk_len = sizeof(*auth) +
13685 	    sctp_get_hmac_digest_len(stcb->asoc.peer_hmac_id);
13686 	auth->ch.chunk_length = htons(chunk_len);
13687 	auth->hmac_id = htons(stcb->asoc.peer_hmac_id);
13688 	/* key id and hmac digest will be computed and filled in upon send */
13689 
13690 	/* save the offset where the auth was inserted into the chain */
13691 	if (m != NULL) {
13692 		struct mbuf *cn;
13693 
13694 		*offset = 0;
13695 		cn = m;
13696 		while (cn) {
13697 			*offset += SCTP_BUF_LEN(cn);
13698 			cn = SCTP_BUF_NEXT(cn);
13699 		}
13700 	} else
13701 		*offset = 0;
13702 
13703 	/* update length and return pointer to the auth chunk */
13704 	SCTP_BUF_LEN(m_auth) = chunk_len;
13705 	m = sctp_copy_mbufchain(m_auth, m, m_end, 1, chunk_len, 0);
13706 	if (auth_ret != NULL)
13707 		*auth_ret = auth;
13708 
13709 	return (m);
13710 }
13711 
13712 #ifdef INET6
13713 int
13714 sctp_v6src_match_nexthop(struct sockaddr_in6 *src6, sctp_route_t * ro)
13715 {
13716 	struct nd_prefix *pfx = NULL;
13717 	struct nd_pfxrouter *pfxrtr = NULL;
13718 	struct sockaddr_in6 gw6;
13719 
13720 	if (ro == NULL || ro->ro_rt == NULL || src6->sin6_family != AF_INET6)
13721 		return (0);
13722 
13723 	/* get prefix entry of address */
13724 	LIST_FOREACH(pfx, &MODULE_GLOBAL(nd_prefix), ndpr_entry) {
13725 		if (pfx->ndpr_stateflags & NDPRF_DETACHED)
13726 			continue;
13727 		if (IN6_ARE_MASKED_ADDR_EQUAL(&pfx->ndpr_prefix.sin6_addr,
13728 		    &src6->sin6_addr, &pfx->ndpr_mask))
13729 			break;
13730 	}
13731 	/* no prefix entry in the prefix list */
13732 	if (pfx == NULL) {
13733 		SCTPDBG(SCTP_DEBUG_OUTPUT2, "No prefix entry for ");
13734 		SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, (struct sockaddr *)src6);
13735 		return (0);
13736 	}
13737 	SCTPDBG(SCTP_DEBUG_OUTPUT2, "v6src_match_nexthop(), Prefix entry is ");
13738 	SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, (struct sockaddr *)src6);
13739 
13740 	/* search installed gateway from prefix entry */
13741 	for (pfxrtr = pfx->ndpr_advrtrs.lh_first; pfxrtr; pfxrtr =
13742 	    pfxrtr->pfr_next) {
13743 		memset(&gw6, 0, sizeof(struct sockaddr_in6));
13744 		gw6.sin6_family = AF_INET6;
13745 		gw6.sin6_len = sizeof(struct sockaddr_in6);
13746 		memcpy(&gw6.sin6_addr, &pfxrtr->router->rtaddr,
13747 		    sizeof(struct in6_addr));
13748 		SCTPDBG(SCTP_DEBUG_OUTPUT2, "prefix router is ");
13749 		SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, (struct sockaddr *)&gw6);
13750 		SCTPDBG(SCTP_DEBUG_OUTPUT2, "installed router is ");
13751 		SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, ro->ro_rt->rt_gateway);
13752 		if (sctp_cmpaddr((struct sockaddr *)&gw6,
13753 		    ro->ro_rt->rt_gateway)) {
13754 			SCTPDBG(SCTP_DEBUG_OUTPUT2, "pfxrouter is installed\n");
13755 			return (1);
13756 		}
13757 	}
13758 	SCTPDBG(SCTP_DEBUG_OUTPUT2, "pfxrouter is not installed\n");
13759 	return (0);
13760 }
13761 
13762 #endif
13763 
13764 int
13765 sctp_v4src_match_nexthop(struct sctp_ifa *sifa, sctp_route_t * ro)
13766 {
13767 	struct sockaddr_in *sin, *mask;
13768 	struct ifaddr *ifa;
13769 	struct in_addr srcnetaddr, gwnetaddr;
13770 
13771 	if (ro == NULL || ro->ro_rt == NULL ||
13772 	    sifa->address.sa.sa_family != AF_INET) {
13773 		return (0);
13774 	}
13775 	ifa = (struct ifaddr *)sifa->ifa;
13776 	mask = (struct sockaddr_in *)(ifa->ifa_netmask);
13777 	sin = (struct sockaddr_in *)&sifa->address.sin;
13778 	srcnetaddr.s_addr = (sin->sin_addr.s_addr & mask->sin_addr.s_addr);
13779 	SCTPDBG(SCTP_DEBUG_OUTPUT1, "match_nexthop4: src address is ");
13780 	SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, &sifa->address.sa);
13781 	SCTPDBG(SCTP_DEBUG_OUTPUT1, "network address is %x\n", srcnetaddr.s_addr);
13782 
13783 	sin = (struct sockaddr_in *)ro->ro_rt->rt_gateway;
13784 	gwnetaddr.s_addr = (sin->sin_addr.s_addr & mask->sin_addr.s_addr);
13785 	SCTPDBG(SCTP_DEBUG_OUTPUT1, "match_nexthop4: nexthop is ");
13786 	SCTPDBG_ADDR(SCTP_DEBUG_OUTPUT2, ro->ro_rt->rt_gateway);
13787 	SCTPDBG(SCTP_DEBUG_OUTPUT1, "network address is %x\n", gwnetaddr.s_addr);
13788 	if (srcnetaddr.s_addr == gwnetaddr.s_addr) {
13789 		return (1);
13790 	}
13791 	return (0);
13792 }
13793